Files
rag-retrieval-core/ragretrieval/rerank.py
T

68 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Cross-encoder 精排 —— 排序逻辑抽出,模型可注入。
生产对照:`kb_index_lib.py:1234-1258`(rerank_candidates)。生产版直接
`from sentence_transformers import CrossEncoder` 懒加载真实模型。本文件把
**排序逻辑**与**打分器**解耦:排序逻辑在这里,`scorer` 由调用方注入。
这样做的两个理由:
1. 排序逻辑能离线跑单测(真实模型要 1GB 权重 + CPU 前向,不适合当测试夹具);
2. 更重要的——降级路径值得被测试。生产版"加载失败/打分失败就返回原始
顺序"是个静默降级:线上表现为"检索结果没变差,但排序质量悄悄退化",
没有告警。这种路径不写测试就等于不存在。生产库那次2364 个幽灵向量
事件本质就是这个教训:静默降级导致无人知晓。
"""
from __future__ import annotations
from typing import Callable
# 打分器签名:(query, text) -> float,越大越相关
Scorer = Callable[[str, str], float]
def rerank_candidates(
query: str,
candidates: list[dict],
scorer: Scorer | None = None,
top_n: int | None = None,
) -> list[dict]:
"""按 (query, text) 相关性打分后降序重排,每项附加 `rerank_score`。
- `scorer=None` → **原样返回**(对应生产版"模型加载失败"这一支)
- `scorer` 抛异常 → **原样返回**(对应生产版"打分失败"这一支)
两条降级分支都刻意不抛异常:精排是加分项,不是可用性前提,
检索链路不能因为它挂掉。代价是降级静默——所以生产侧额外有门禁兜底
(Golden Set 周期评测),本文件在测试里把这两支钉住。
"""
if not candidates:
return candidates
if scorer is None:
return candidates
try:
scored = [(c, float(scorer(query, c.get("text") or ""))) for c in candidates]
except Exception:
# 与生产版一致:打分失败返回原始顺序,不阻塞检索
return candidates
scored.sort(key=lambda x: x[1], reverse=True)
out = []
for c, s in scored:
item = dict(c)
item["rerank_score"] = round(s, 4)
out.append(item)
return out[:top_n] if top_n else out
def keyword_scorer(query: str, text: str) -> float:
"""零依赖的假打分器:纯字符重叠率。
只用于让流程能跑通/演示,**不是真的语义相关度**,别拿它评估检索质量。
真实检索链路里这一格是BGE-reranker-base(cross-encoder,1061MB权重)。
"""
q = set(query)
t = set(text)
if not q or not t:
return 0.0
return len(q & t) / len(q)