模型与多模态实用指南2026年11月23日Flatkey

RAG 重排:固定候选的质量与延迟对照实例

一个可重复的7查询示例,展示重排何时改善片段顺序、何时没有相关性收益,以及为什么无法找回缺失候选。

RAG 重排:固定候选的质量与延迟对照实例

RAG 中的重排会为查询与每个检索片段的关系打分,再调整这些片段的顺序,然后才将它们交给语言模型。当第一阶段检索已经找到了正确证据,却把它排得太靠后时,重排可能有帮助。如果相关片段根本没有进入候选集,重排就无法把它找回来。

本教程运行了一组规模很小、可重复的对照:14 份合成文档、7 个查询,前后使用相同的 5 个检索候选,最终上下文只保留 3 个片段。其中 2 个查询的首个相关结果从第 2 位升到了第 1 位。另有几个查询没有获得可测得的相关性收益,却仍然增加了处理时间。一个刻意构造的检索遗漏也没有被修复。

文档与相关性等级都是作者定义的合成教学材料,在模型评分前已经冻结。它们不是客户记录、独立人工标注的判断,也不是生产基准测试。下方代码包含完整测试材料,方便你检查假设并重复实验。

重排在 RAG 流程中的位置

两个阶段承担不同的任务:

  1. 检索候选。 BM25 等词法方法或嵌入检索,从文档集中选出一个规模可控的子集。
  2. 重排这些候选。 交叉编码器(cross-encoder)同时接收查询和每个片段,输出相关性分数。在上下文预算内保留排名最高的片段。
  3. 生成并评估回答。 语言模型使用选定的上下文。回答是否正确、引用是否支持相应内容,都需要单独评估。

Sentence Transformers 的检索与重排文档介绍了这种结构。交叉编码器对查询与片段组成的配对执行推理;先检索候选,可以避免在大型文档集中对每个片段都执行这个成本较高的步骤。

本例的第一阶段使用 BM25,而不是嵌入相似度,这样词法检索规则可以直接检查。如果需要基于向量的第一阶段,可参阅嵌入与语义搜索教程。核对候选集是否相同的要求仍然适用。

我们固定了哪些条件

这个虚构知识库涉及文件删除、恢复、订阅、发票、项目归档、角色和记录存放位置。其中的规则只用于本例,并不描述 Flatkey 或其他真实产品的政策。

每个查询都对完整文档集给出了明确的相关性等级:

  • 2: 按测试材料中的规则,直接回答了问题。
  • 1: 提供有用的辅助信息,但不完整。
  • 0: 不相关,或对象、条件不符。

这些等级在推理前就已固定。它们是为演示指标而公开设定的假设,不是经过独立验证的标准答案。

BM25 使用 k1=1.2、b=0.75,按小写字母和数字切分词元,不做词干提取或同义词扩展。分数相同时按稳定的文档 ID 排序。每个查询检索 5 份文档。对照的两组都从同一个包含 5 个候选的集合中选出 3 个片段;重排改变候选的顺序,不改变候选集的成员。

第二阶段使用公开的英文 cross-encoder/ms-marco-MiniLM-L6-v2 模型,固定到 revision 233902d25c440f23af6f7d6e94d2946bac0bee0a。我们按其文档中的 Transformers 查询与片段分类方式运行,在 CPU 上使用 FP32,批次大小为 5,最大输入长度为 512。实际配对长度为 37–51 个 token,因此没有发生截断。

实验没有生成语言模型回答。这样可以单独观察片段排序,但不能证明最终回答有所改善。

RAG 重排:实际测得的质量变化

以下 3 个指标分别描述最终 3 个片段的不同方面:

  • Precision@3: 相关性等级大于 0 的片段所占比例。
  • MRR@3: 第一个相关性等级大于 0 的片段,其排名的倒数;如果前 3 个中没有这样的片段,则为 0。
  • nDCG@3: 考虑位置的分级相关性指标,使用增益 2^grade - 1 和对数折扣。理想排序来自完整的 14 份文档,而不只是检索到的 5 个候选。
查询 问题 MRR@3 重排前 → 重排后 nDCG@3 重排前 → 重排后
Q1 删除已上传的文档 0.5000 → 1.0000 0.5213 → 0.8262
Q2 避免下个月的续订扣款 0.5000 → 1.0000 0.5213 → 0.8262
Q3 归档会永久删除文件吗? 1.0000 → 1.0000 1.0000 → 1.0000
Q4 已删除上传文件的恢复期限 1.0000 → 1.0000 1.0000 → 1.0000
Q5 下载发票 1.0000 → 1.0000 0.9639 → 1.0000
Q6 查看者可以邀请成员吗? 1.0000 → 1.0000 1.0000 → 1.0000
Q7 记录存放在哪里? 0.0000 → 0.0000 0.0000 → 0.0000
7 个查询的均值 0.7143 → 0.8571 0.7152 → 0.8075

平均 Precision@3 在重排前后均为 0.4762。这里的重排主要改善了位置,没有增加这 3 个上下文片段中相关片段的数量。这些只是针对 7 个专门构造的查询得到的描述性结果,不是有统计依据的生产收益估计。

细看“删除已上传文档”这个查询

Q1 的原始问题是:“How do I remove an uploaded document?” BM25 把解释文件搜索的 D13 排在了真正说明删除步骤的 D01 前面。

文档 片段内容 等级 BM25 排名 重排后排名
D13 通过搜索查找已上传的文件 0 1 2
D01 选择文件、删除文件以及移入回收站的步骤 2 2 1
D11 PDF 发票下载失败后的重试 0 3 5
D05 永久删除项目与归档的区别 0 4 3
D10 活动日志条目 0 5 4

有用的删除步骤升到了前面,但最终上下文中仍然包含不相关的片段。另一段与文件恢复有关的相关材料 D08 不在这 5 个候选中。因此,即使 D01 升至首位,按完整文档集计算的 nDCG@3 仍然小于 1。

模型的原始 logits 是排序分数,而不是经过校准的概率。对于 Q2,每个候选的分数都是负数,但取消订阅的片段仍然排在第一位。如果没有用合适的数据验证,不能把“分数最高”当成置信度或能够回答问题的保证。

额外延迟,以及没有受益的查询

实验运行于 2026-11-23 UTC,硬件为具有 10 个物理核心的 Apple M5,实际使用 4 个 CPU 线程,软件为 Python 3.12.13、PyTorch 2.7.1 和 Transformers 4.52.4。交叉编码器对每个查询先预热 3 次,随后两个阶段分别在固定输入下计时 30 次。

BM25 计时包含查询评分和排序。交叉编码器的增量计时包含词元化、对 5 个候选执行 CPU 前向计算,以及排序。不包含模型下载、分词器与模型加载、索引构建。本次分词器和模型加载耗时约 1.03 秒,单独记录,不计入下表。

查询 BM25 中位数,ms 重排额外耗时中位数,ms 重排额外耗时 p95,ms
Q1 0.050 9.20 12.81
Q2 0.060 10.44 14.80
Q3 0.054 9.86 14.76
Q4 0.056 8.60 9.93
Q5 0.044 10.88 16.74
Q6 0.045 10.52 23.01
Q7 0.043 10.16 12.21

Q3、Q4 和 Q6 的 3 个质量指标都没有变化,但重排仍然增加了处理时间。Q5 只在分级相关性的排序方面略有改善。这种取舍是否有价值,取决于应用的质量要求和延迟预算。

p95 是根据 30 次重复、按最近秩法得到的粗略估计。这些测量针对短片段,记录的是本地 CPU 预热后的处理时间,并不代表网络延迟、托管 API、GPU 推理、并发生产负载或完整 RAG 响应时间。

重排无法修复的检索遗漏

Q7 的原始问题是:“What region keeps our information?” D12 的原文是:“Customer records reside exclusively in Dublin, Ireland. Geographic replication is disabled.”

我们在推理前刻意设计了这种措辞不匹配,以展示词法检索的局限。在这个分词器下,所有文档的 BM25 分数都是 0。稳定的 ID 排序选出了 D01–D05,把 D12 留在候选集之外。对这 5 个候选重新排序无法引入 D12:候选 Recall@5 和前 3 个结果的所有相关性指标仍然为 0。

这是特意构造的教学案例,不能用来证明一般的 BM25 查询通常会这样失败。如果应用中出现类似遗漏,应先检查查询措辞、分块、同义词处理、混合检索和候选数量,再考虑让重排器改善结果。

这个小型测试材料中没有观察到质量退化,但这并不能排除其他查询、领域、语言或文档长度下出现退化的可能。

复现这个受控示例

使用 Python 3.12、torch==2.7.1 和 transformers==4.52.4。新环境需要下载公开模型;前文已链接固定的 revision 和 Apache-2.0 模型卡。脚本使用 safetensors,禁用远程仓库代码,并在 CPU 上推理。

通过 python -m pip install torch==2.7.1 transformers==4.52.4 安装这两个包。将以下内容保存为 rerank_example.py,然后运行 python rerank_example.py。代码包含完整合成语料、查询和明确的相关性等级。耗时会随硬件和系统负载变化,不同软硬件之间也可能有细微的浮点差异;在把分数差异视为有意义之前,先对照文档顺序与指标定义。

"""Synthetic lesson, not product policy or a production benchmark.
Python 3.12; pip install torch==2.7.1 transformers==4.52.4 numpy==2.5.5 safetensors==0.8.0
Run: python rerank_example.py --output results.json
Optional: --model-dir ./model uses an already downloaded pinned safetensors snapshot.
"""
import argparse, hashlib, json, math, platform, re, time
from collections import Counter
from pathlib import Path
from statistics import median
import torch, transformers
from transformers import AutoTokenizer, AutoModelForSequenceClassification


MODEL_ID = "cross-encoder/ms-marco-MiniLM-L6-v2"

REVISION = "233902d25c440f23af6f7d6e94d2946bac0bee0a"

DOCS = {
    "D01": "To delete an uploaded file, open Files, select the file, choose Delete, and confirm. The file moves to Trash, where an owner can restore it for 30 days.",
    "D02": "Deleting your account permanently closes the workspace and removes access. To stop future subscription renewals, use the Cancel subscription action in Billing instead; account deletion is not needed.",
    "D03": "Cancel a subscription from Billing > Subscription > Cancel renewal. Cancellation stops the next renewal charge; access continues until the paid period ends. Deleting files has no effect on renewal.",
    "D04": "Archiving a project hides it from the active project list. The owner can unarchive it at any time. Archive does not permanently delete project files.",
    "D05": "Permanent project deletion is different from archiving. Choose Settings > Delete project to remove a project permanently; archived projects remain restorable.",
    "D06": "To download invoices, open Billing > Invoices, select a billing month and choose Download PDF. Only workspace owners and billing administrators can access invoices.",
    "D07": "Only owners and workspace administrators may invite new members from Settings > Members > Invite. Members with viewer or editor roles cannot send invitations.",
    "D08": "When you delete a file, Trash retains a recoverable copy for 30 days. After 30 days it is permanently removed. The owner can restore a file from Trash before that deadline.",
    "D09": "Project exports contain file names, timestamps, and comments. Exporting a project does not delete files or cancel a subscription.",
    "D10": "The activity log records file uploads, file deletions, project archives and member invitations. Log entries do not change a member's role or a subscription's renewal settings.",
    "D11": "If a PDF invoice download fails, retry from Billing after checking that you are signed into an owner or billing administrator account. Failed PDF downloads do not change subscription charges.",
    "D12": "Customer records reside exclusively in Dublin, Ireland. Geographic replication is disabled.",
    "D13": "File search uses the document title and body. To find an uploaded file, search by its name. Search cannot restore items from Trash or change retention deadlines.",
    "D14": "Viewers can read projects and editors can update project files. Neither role is allowed to invite people; contact an owner or workspace administrator for invitation changes.",
}

QUERIES = {
    "Q1": "How do I remove an uploaded document?",
    "Q2": "How can I avoid being charged again next month?",
    "Q3": "Does archiving a project permanently erase its files?",
    "Q4": "How many days can I recover a deleted upload?",
    "Q5": "Where can I download invoices?",
    "Q6": "Can a viewer invite new members?",
    "Q7": "What region keeps our information?",
}

POSITIVES = {
    "Q1": {"D01": 2, "D08": 1},
    "Q2": {"D03": 2, "D02": 1},
    "Q3": {"D04": 2, "D05": 2},
    "Q4": {"D08": 2, "D01": 2},
    "Q5": {"D06": 2, "D11": 1},
    "Q6": {"D07": 2, "D14": 2},
    "Q7": {"D12": 2},
}

def tokens(text):
    return re.findall(r"[a-z0-9]+", text.lower())

class BM25:
    def __init__(self, docs, k1=1.2, b=0.75):
        self.ids = sorted(docs)
        self.counts = {d: Counter(tokens(docs[d])) for d in self.ids}
        self.lengths = {d: sum(c.values()) for d, c in self.counts.items()}
        self.avg = sum(self.lengths.values()) / len(self.ids)
        self.df = Counter(t for c in self.counts.values() for t in c)
        self.k1, self.b = k1, b

    def search(self, query):
        scores = {}
        for d in self.ids:
            score = 0.0
            for t in set(tokens(query)):
                f, df = self.counts[d][t], self.df[t]
                idf = math.log(1 + (len(self.ids) - df + 0.5) / (df + 0.5))
                denominator = f + self.k1 * (1 - self.b + self.b * self.lengths[d] / self.avg)
                score += idf * f * (self.k1 + 1) / denominator
            scores[d] = score
        return sorted(self.ids, key=lambda d: (-scores[d], d)), scores

def metrics(order, grades, k=3):
    top = order[:k]
    gains = [grades[d] for d in top]
    positive = lambda g: g > 0
    dcg = lambda gs: sum((2 ** g - 1) / math.log2(i + 2) for i, g in enumerate(gs))
    ideal = dcg(sorted(grades.values(), reverse=True)[:k])
    return {"precisionAt3": sum(map(positive, gains)) / k,
            "mrrAt3": next((1 / (i + 1) for i, g in enumerate(gains) if positive(g)), 0.0),
            "ndcgAt3": dcg(gains) / ideal if ideal else 0.0}

def timing(values):
    ordered = sorted(values)
    return {"samplesMs": values, "medianMs": median(values), "p95Ms": ordered[math.ceil(0.95 * len(ordered)) - 1], "minMs": min(values), "maxMs": max(values)}

parser = argparse.ArgumentParser()
parser.add_argument("--model-dir")
parser.add_argument("--runs", type=int, default=30)
parser.add_argument("--output", default="results.json")
args = parser.parse_args()
# Author-defined illustrative grades, fixed before scoring; no independent human validation.
# 2=full answer, 1=useful but incomplete, 0=other.
fixture = {"documents": DOCS, "queries": QUERIES, "labels": POSITIVES}
fixture_hash = hashlib.sha256(json.dumps(fixture, sort_keys=True).encode()).hexdigest()
Path(args.output + ".fixture.json").write_text(json.dumps(fixture, indent=2))
torch.set_num_threads(4)
torch.manual_seed(0)
torch.use_deterministic_algorithms(True)
source = args.model_dir or MODEL_ID
opts = dict(revision=REVISION, trust_remote_code=False, token=False,
            local_files_only=bool(args.model_dir))
tokenizer = AutoTokenizer.from_pretrained(source, **opts)
model = AutoModelForSequenceClassification.from_pretrained(
    source, use_safetensors=True, **opts).to("cpu").eval()
retriever, rows = BM25(DOCS), []
for qid, query in QUERIES.items():
    full_order, bm_scores = retriever.search(query)
    candidates = full_order[:5]  # Freeze these same five for both rankings.
    grades = {d: POSITIVES[qid].get(d, 0) for d in DOCS}
    def rerank():
        features = tokenizer([query] * 5, [DOCS[d] for d in candidates],
            padding=True, truncation=True, max_length=512, return_tensors="pt")
        with torch.inference_mode():
            scores = dict(zip(candidates, model(**features).logits.flatten().tolist()))
        return sorted(candidates, key=lambda d: (-scores[d], d)), scores
    for _ in range(3):
        rerank()  # Warm-up; loading and download are outside measured time.
    after, logits = rerank()
    bm_ms, ce_ms = [], []
    for _ in range(args.runs):
        start = time.perf_counter_ns(); check, _ = retriever.search(query)
        bm_ms.append((time.perf_counter_ns() - start) / 1e6)
        assert check[:5] == candidates
        start = time.perf_counter_ns(); check, _ = rerank()
        ce_ms.append((time.perf_counter_ns() - start) / 1e6)
        assert check == after
    positive = {d for d, g in grades.items() if g > 0}
    recall5 = len(positive.intersection(candidates)) / len(positive)
    rows.append(dict(queryId=qid, query=query, candidates=candidates,
        bm25Top3=candidates[:3], rerankedTop3=after[:3], logits=logits,
        before=metrics(candidates, grades), after=metrics(after, grades),
        candidateRecallAt5=recall5, missing=sorted(positive.difference(candidates)),
        bm25Timing=timing(bm_ms), crossEncoderTiming=timing(ce_ms)))
means = {stage: {m: sum(r[stage][m] for r in rows) / len(rows)
         for m in rows[0][stage]} for stage in ["before", "after"]}
result = dict(model=MODEL_ID, revision=REVISION, fixtureSha256=fixture_hash,
    gradeSource="author-defined illustrative relevance grades fixed before scoring; no independent human annotation or validation",
    device="cpu", threads=4, python=platform.python_version(),
    torch=torch.__version__, transformers=transformers.__version__,
    runs=args.runs, means=means, rows=rows)
Path(args.output).write_text(json.dumps(result, indent=2))
print(json.dumps(means, indent=2))
# Raw logits are uncalibrated scores. Same-candidate recall cannot increase.
# Q7 intentionally exposes lexical retrieval failure; all documents are fictional.

输出中保留了第一阶段候选集,方便核对两组对照是否使用相同片段。如果修改文档、查询、标签、模型 revision 或候选预算,应将其保留为另一组实验;看过分数后再改这些条件,会改变对照所衡量的内容。

判断是否保留重排器

评估发现 下一步
相关证据已经被检索到,但排在上下文截断位置之后 固定候选集和上下文预算测试重排,逐查询检查改善与损失。
第一阶段的顺序已经满足任务要求 将额外质量收益与新增处理成本对比;收益不足时保留更简单的基线。
候选集中缺少相关证据 改善第一阶段召回,再重复受控对照。
片段相互冲突、已经过时,或属于另一权限范围 应用来源、时效和访问规则;仅按相关性排序不能判断真伪或授权。
延迟接近应用上限 在实际服务链路上测量有代表性的片段长度、候选数量、并发和冷启动。

真实部署需要有代表性的查询集和适当的相关性判断,保留不用于调优的评估集,同时评估生成回答、引用和检索。RAG 评估指南说明了这些测量如何配合使用。

当正确证据已经存在、只是排序不佳时,RAG 重排值得测试。是否保留它,应依据自身工作负载下逐查询的质量变化和新增延迟。

如果正在选择生成层,可以浏览 Flatkey 模型目录。披露: Flatkey 发布本教程,并运营链接指向的服务。上述实验使用公开的交叉编码器模型在本地运行。