RAG 的 pipeline 是什么?
hallucination、data poisoning、context length 怎么解决?
先弄清楚:每个概念是什么
- RAG
- 像开卷考试,先找相关段落(retrieve),再看着答题(generate)。更新知识只要换 index,不用重新训练。
- Dense、BM25 与 hybrid search
- BM25 数关键词重叠,擅长人名、型号这类精确匹配。dense 检索懂同义改写。两路分数合起来就是 hybrid。
- ANN index 与 rerank
- ANN(如 FAISS 的 HNSW)在百万向量里近似找 top-k,快但可能漏。cross-encoder 把 query 和每段放在一起读,慢但准。
- Data poisoning 与 prompt injection
- 有人往知识库塞假文档,或在网页里藏一句"忽略之前的指令"。
30 秒回答
Offline, I chunk and embed the documents and build an ANN index plus a BM25 index. Online, I rewrite the query, retrieve top-k with hybrid search, rerank with a cross-encoder, and generate from the best few chunks with citations. For hallucination: answer only from the context, cite each claim, check numbers against the source, and say "I don't know" without evidence. For poisoning: trusted sources only, cross-check them, and treat retrieved text as data, never instructions. For context length: keep only top reranked chunks, compress, or map-reduce. Evaluate retrieval with recall@k and MRR, generation with faithfulness and answer relevance.
Pipeline
- Offline:chunking(太小丢上下文,太大噪声多,size 和 overlap 在自己的 query 集上扫)→ embedding → ANN index + BM25 index,存 metadata(来源、日期)
- Retrieve:query rewriting → hybrid search 取 top-k(比如 50)
- Rerank:cross-encoder 精排,留 top-n(比如 5)
- Generate:chunk 带编号放进 prompt,要求只依据材料、逐句标出处
三个难点
| 难点 | 怎么解决 |
|---|---|
| hallucination (数字、时间) | rerank、按日期 filter;逐句 citation;数字回原文核对;没依据就说不知道;structured data 走 SQL / tool |
| data poisoning / prompt injection | source allowlist、可信度加权;多 source 交叉验证,冲突标出;retrieved content 用 delimiter 包住,system prompt 规定只当数据 |
| context length | 只留 rerank 最靠前的;compression / summarization;按 token budget 动态选;map-reduce;long-context model |
必答点
- pipeline:chunk → embed → index → hybrid retrieve → rerank → 带 citation 生成
- hallucination:检索错时模型照样编,所以 grounding + 逐句 citation + 数字核对 + 允许说不知道
- poisoning:控制 source、交叉验证;retrieved content 是数据不是指令
- context:先 rerank 再少放,compression / map-reduce
- 分开评估:retrieval 看 recall@k、MRR,generation 看 faithfulness、answer relevance(RAGAS,不需要参考答案)
追问
recall@k 和 MRR 怎么算?
3 个 query,第一个相关 chunk 分别排在第 1、第 3、没召回:recall@3 \(= 2/3\);MRR \(= (1 + 1/3 + 0)/3 = 0.44\)。
context 放得越多越好吗?
不是。Lost in the Middle 发现相关段落在开头或结尾时准确率最高,在中间时明显下降(U 形)。所以少放,最相关的放首尾。
多检索几段能把投毒稀释掉吗?
不够。PoisonedRAG 对每个目标问题只往几百万段的知识库注入 5 段文本,attack success rate 就约 90%。k = 50 时 HotpotQA 上仍有约 41%,paraphrasing、perplexity 检测、去重也挡不住。
原论文的 RAG 怎么训练?
retriever \(p_\eta\)(DPR)和 generator \(p_\theta\)(BART)end-to-end 微调,把检索到的文档 \(z\) 当 latent variable 求和:
\[ p(y\mid x) \approx \sum_{z\in\text{top-}k} p_\eta(z\mid x)\, p_\theta(y\mid x, z) \]来源Lewis et al. 2020 §2.1(p.3)、§3(p.4,100 词 chunk、FAISS HNSW)、§4.5(p.7,BM25、index hot-swapping)· Zou et al. 2024, PoisonedRAG abstract(p.1)、§7.1–7.4(pp.13–14)· Greshake et al. 2023 abstract(indirect prompt injection)· Liu et al. 2023, Lost in the Middle abstract、Fig. 1(p.1)· Es et al. 2023, RAGAS §3(p.3)