fusion.py
3.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""跨变体 RRF 融合 + 业务维度软提升。
纯函数,无 IO——好测,也便于单独调权重。
**为什么用 RRF 而不是取各路最大分**:多变体下 max(hybrid_score) 有系统性偏差。
某一路排第 1 和另一路排第 40 的原始 RRF 分可能很接近,max 分不出来。
RRF 用排名而非分数,天然抗跨路分数尺度不可比。副作用正是我们想要的:
被多个变体同时召回的片段自动获得加成——这就是子查询拆分的价值所在。
**为什么软提升而不是硬过滤**:业务维度不进 Qdrant filter。LLM 把"问界"抽成别的时,
正确文档仍在召回集里,只是没拿到加成;换成硬过滤就直接被排除,且无从察觉。
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from src.rag.core.config import RAG_RRF_K
from src.rag.ingestion.taxonomy import Taxonomy, load_taxonomy
if TYPE_CHECKING:
from src.rag.retrieval.retriever import Candidate
def fuse_candidates(
per_variant: list[list["Candidate"]],
query_labels: dict[str, Any] | None = None,
taxonomy: Taxonomy | None = None,
) -> tuple[list["Candidate"], dict[str, Any]]:
"""把各变体的召回结果融合成一个排序列表。
:param per_variant: 每个检索变体的候选列表,各自已按 hybrid_score 降序
:param query_labels: 意图抽出的业务维度(如 {"brand": "问界"}),空则不加权
:return: (按 fusion_score 降序的候选, 实际生效的加权明细)
"""
grouped: dict[str, "Candidate"] = {}
for candidates in per_variant:
for rank, candidate in enumerate(candidates, start=1):
key = candidate.parent_chunk_id or candidate.child_chunk_id
contribution = 1.0 / (RAG_RRF_K + rank)
existing = grouped.get(key)
if existing is None:
candidate.fusion_score = contribution
grouped[key] = candidate
continue
existing.fusion_score += contribution
existing.hybrid_score = max(existing.hybrid_score, candidate.hybrid_score)
# payload 取信息更全的那份(不同变体命中的可能是同一父块的不同子块)
if len(candidate.payload) > len(existing.payload):
existing.payload = candidate.payload
if candidate.retrieval_type not in existing.retrieval_type:
existing.retrieval_type = f"{existing.retrieval_type},{candidate.retrieval_type}"
fused = list(grouped.values())
applied = _apply_soft_boost(fused, query_labels, taxonomy)
fused.sort(key=lambda c: c.fusion_score, reverse=True)
return fused, applied
def _apply_soft_boost(
candidates: list["Candidate"],
query_labels: dict[str, Any] | None,
taxonomy: Taxonomy | None,
) -> dict[str, Any]:
"""按 query_labels 与候选 payload 的匹配情况加权。
**只奖励命中,不惩罚缺失**:payload 里没有 brand 的候选(比如通用政策页)
不该因为问题提到"问界"就被压下去。
"""
if not query_labels:
return {}
taxonomy = taxonomy or load_taxonomy()
weights = {d.name: d.boost for d in taxonomy.boostable()}
applied: dict[str, Any] = {}
for name, wanted in query_labels.items():
weight = weights.get(name)
if not weight or not wanted:
continue
hits = 0
for candidate in candidates:
actual = (candidate.payload or {}).get(name)
if actual is None:
continue # 缺失不惩罚
values = actual if isinstance(actual, list) else [actual]
if wanted in values:
candidate.fusion_score *= 1.0 + weight
hits += 1
if hits:
applied[name] = {"value": wanted, "weight": weight, "hits": hits}
return applied