Maps to: CMU 11-711 Spring 2026, Lecture 10 (02/12), guest lecture by Akari Asai, slides
anlp-s2026-10-rag.pdf(adapted from Graham Neubig’s Fall 2024 course). There is no course demo code for this lecture. Readings: A. Asai, S. Min, Z. Zhong, D. Chen, Retrieval-based Language Models and Applications (ACL 2023 tutorial); A. Asai et al., Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection (ICLR 2024). Additional: A. Asai et al., Task-aware Retrieval with Instructions (2023); A. Mallen, A. Asai et al., When Not to Trust Language Models (2023); A. Asai et al., Reliable, Adaptable, and Attributable Language Models with Retrieval (2024); R. Shao et al., Scaling Retrieval-Based Language Models with a Trillion-Token Datastore (2024); A. Asai et al., OpenScholar (2024). Sources: the public slides, the readings, and the papers cited in each section. Every number labelled “measured” comes fromcode/lecture10/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code:code/lecture10/— both demos run in under 40 seconds. Reading time: ~100 minutes for the prose; ~20 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain the limits of a monolithic LM: hallucination, finite parametric memory, the long tail, and the knowledge cutoff. Explain what retrieval offers: fewer hallucinations, parameter efficiency, updatable knowledge, verifiability.
- Describe the three parts of a retrieval-augmented system — datastore, retriever, LM — and the design choices in each.
- Compute TF-IDF and BM25 scores, explain dense dual-encoder retrievers and their contrastive training, approximate nearest-neighbor search, rerankers, and the metrics recall@k, MRR and nDCG.
- Contrast three ways of using retrieved text: input augmentation (RAG), intermediate fusion (RETRO), output interpolation (kNN-LM).
- Explain when retrieval helps (rare entities, fresh facts), when it hurts (unhelpful documents), and how adaptive retrieval and Self-RAG’s reflection tokens decide when to retrieve and what to trust.
0.2 Prerequisites and scope
- Prerequisites: Lecture 7 (Fact World, the long tail, scaling laws), Lecture 6 (pretraining data), Lecture 2 (embeddings, contrastive-style training), Lecture 9 (decoding).
- Scope: retrieval-based language models from the datastore to the reader.
- Not in scope: tool use and agents in general (Lecture 18); long-context models as an alternative to retrieval (Lecture 22); multimodal retrieval (Lectures 11–12).
0.3 Section → code map
| Section | Idea | Demo in code/lecture10/ |
|---|---|---|
| §3.1–3.2 | TF-IDF and BM25 by hand; sparse vs dense on Fact World by popularity; metrics | 01_retrievers.py Parts A–B (+ rag_world.py) |
| §3.3 | approximate nearest-neighbor search (inverted file) | 01_retrievers.py Part C |
| §1, §4.2 | closed-book accuracy and confidence by popularity; RAG with BM25, dense and oracle retrieval | 02_rag.py Parts A–B |
| §4.2–4.3 | knowledge updates; unhelpful documents; adaptive retrieval and a relevance check | 02_rag.py Parts C–E |
| §4.4 | kNN-LM: output interpolation, and a swapped datastore | 02_rag.py Part F |
0.4 Notation
| Symbol | Meaning |
|---|---|
| the input (query, question); the output | |
| the datastore of text chunks | |
| a retriever’s relevance score; top- the highest-scoring chunks | |
| , | term frequency of term in chunk ; inverse document frequency |
| dense embeddings of query and chunk | |
| , | retriever and generator distributions (RAG) |
| kNN-LM interpolation weight |
1. The limits of a monolithic LM
1.1 Hallucination and obsolete knowledge
The slides open with GPT-5.1, asked in January 2026 to list the speaker’s papers. It mixes real papers by her, real papers by other people attributed to her, and papers that do not exist. An analysis of ICLR 2026 submissions found the same kind of fabricated reference in submitted papers.
Asked “when did GPT-5.2 come out?”, a model whose training data ends earlier answers that there is no confirmed release date. The answer was true at its data cutoff and wrong by the time it was asked.
1.2 Why: what the parameters can hold
The monolithic recipe of Lectures 6–8 is: data → pretrain by → adapt. Two problems:
- can’t store infinite information. Allen-Zhu & Li (2024) estimate a knowledge capacity of about 2 bits per parameter. Long-tail facts appear too rarely to be memorized: Lecture 7’s scaling laws were made of exactly this tail. Mallen, Asai et al. (2023) showed that LM accuracy on factual questions collapses for unpopular entities, and that scaling the model helps popular entities far more than rare ones.
- only captures information as of the data cutoff. RealTime QA (Kasai et al., 2023) asks about this week’s news; no frozen model can answer.
Measured (demo 02 Part A). A Transformer trained on Fact World text — 2,500 people with Zipf popularity, three facts each (Lecture 7) — answers “where does X live ?” closed-book:
| popularity ranks | closed-book accuracy | mean confidence when right | mean confidence when wrong |
|---|---|---|---|
| 1–10 | 100.0% | 1.00 | — |
| 11–100 | 100.0% | 0.95 | — |
| 101–1000 | 68.2% | 0.61 | 0.33 |
| 1001–2500 | 37.5% | 0.48 | 0.36 |
Chance is 5% (20 cities). The model knows its popular facts and guesses on the tail. Its confidence barely separates right from wrong answers there (0.48 vs 0.36), so wrong answers come out fluent and unflagged: a hallucination.
1.3 Retrieval-augmented LMs: the intuitions
Ask a plain LM “Who is Akari Asai?” and it may answer “a Japanese voice actress”: a real person, but not the one meant. A retrieval-augmented LM first finds the speaker’s homepage, then answers “a Ph.D. student at UW” (as she then was). Four benefits:
- Reduces hallucinations: the answer is grounded in retrieved text.
- Parameter efficiency: facts live in the datastore, not in parameters, so a smaller model suffices.
- Updates knowledge without retraining: refresh the datastore; “GPT-5.2 Instant, Dec 11, 2025” is found even though the model’s training data ended in October.
- Improves verifiability: the answer can cite the retrieved source.
2. Overview: datastore, retriever, LM
x: "When did GPT 5.2 come out?"
│
├─► Retriever: Sim(· | x) over the Datastore, take the top-k chunks
│ 0.9 "Dec 11, 2025 – OpenAI: GPT-5.2 Instant is a fast, capable workhorse for …"
│ 0.7 "GPT-5 (Wikipedia): Preceded in the series by GPT-4, it was …"
│ 0.1 "Ruby on Rails 5.2 Release Notes …"
│
└─► LM(x, retrieved chunks) → y: "December 11, 2025"
The key design choices, by component:
| datastore | retriever | LM |
|---|---|---|
| sources of the datastore | types of retrievers | architectures |
| processing | training | training |
| scaling | evaluation | inference |
2.1 Part 1 — the datastore
What should be in it? It depends on the queries:
- for “When did GPT 5.2 come out?”: fresh web pages or news;
- for factual questions about the world: English Wikipedia, the classic choice (Chen et al., 2017; Guu et al., 2020; Lewis et al., 2020; …);
- for “How should I implement RAG using LlamaIndex?”: code snippets, documentation and community forums.
Scaling. English Wikipedia is about 5 billion tokens. MassiveDS (Shao et al., 2024) is a 1.4-trillion-token datastore across many domains. On knowledge-intensive tasks, a smaller LM with the large datastore can match or beat a larger LM without one, and performance keeps improving as the datastore grows. Gains come with costs in indexing, storage and search.
Processing:
- Curate and preprocess: e.g. HTML → plain text, as in Lecture 6’s pipeline.
- Chunk: by paragraph (split on newlines) or every words (e.g. 100–250).
- Post-process: e.g. remove very short or low-quality chunks.
Chunk size is a real trade-off. Small chunks are precise but may cut an answer from its context; large chunks are complete but dilute the match and consume the reader’s context window.
The demos’ datastore (rag_world.Datastore) has one chunk per person:
kemi dorasu lives in lima . kemi dorasu is a baker . kemi dorasu owns a cat .
3. Part 2 — the retriever
Three families:
- sparse retrievers: similarity from term-frequency vectors (TF-IDF, BM25);
- dense retrievers: similarity of dense embeddings from pretrained encoders (DPR, Contriever, ColBERT);
- rerankers: scores from jointly encoding query and document (cross-encoders).
3.1 Sparse retrieval: TF-IDF and BM25
Represent a document by which terms it contains, in increasingly refined steps:
- One-hot vector: does the term appear?
- Term-count vector: how many times?
- Weighted terms: down-weight terms that occur everywhere.
then compare the query vector with each document vector by cosine similarity. BM25 (Robertson & Zaragoza, 2009) refines this in two ways. It saturates the term frequency: the tenth occurrence adds less than the first. And it normalizes by document length:
typically with and ; a document’s score sums over the query’s terms.
Measured (demo 01 Part A, the slides’ example). Query “what is nlp”; documents:
- d1 = “what is life ? candy is life !”
- d2 = “nlp is an acronym for natural language processing”
- d3 = “i like to do good research on nlp”
| term | IDF | d1 weight | d2 weight | d3 weight |
|---|---|---|---|---|
| what | 1.10 | 0.34 | 0 | 0 |
| candy | 1.10 | 0.34 | 0 | 0 |
| nlp | 0.41 | 0 | 0.15 | 0.14 |
| is | 0.41 | 0.25 | 0.15 | 0 |
| life | 1.10 | 0.68 | 0 | 0 |
Cosine similarities: d1 0.39, d2 0.10, d3 0.05. BM25 gives the same order. The slides use another TF normalization (0.44 / 0.21 / 0.32), but d1 wins either way, although the query is about NLP. It shares “what” and “is”, while “nlp” is a common term in this tiny collection. Sparse retrieval can’t fully capture semantic similarity: it matches words, not meanings.
3.2 Dense retrieval
Encode each chunk once, offline: . At query time encode and retrieve
There are two common ways to get the embedding:
- the output vector of the [CLS] token of a masked LM (DPR, Karpukhin et al., 2020);
- mean or max pooling over output vectors, which also works for autoregressive LMs (SBERT, SGPT, Qwen embeddings).
Training: contrastive learning. Pull a query and its positive chunk together, push negatives apart:
With in-batch negatives, the other queries’ positives in the same batch serve as negatives for free (DPR). Hard negatives (BM25 hits that are wrong) help further. Contriever (Izacard et al., 2022) trains without any labelled pairs, using crops of the same document as positives.
Rerankers. A bi-encoder encodes query and chunk separately, which is fast: chunk vectors are precomputed. A cross-encoder reads them together through one encoder and outputs a relevance score. It is more accurate, because every query word can attend to every chunk word, but it must run once per (query, chunk) pair. The standard pipeline is to retrieve 100 candidates with BM25 or a bi-encoder, then rerank them with a cross-encoder.
Evaluation metrics:
- Unranked sets: precision and recall.
- Ranked lists: recall@k (is the gold chunk in the top ?), MRR (mean of ), and nDCG@10, which credits relevant results discounted by ; it is the standard metric of BEIR.
- BEIR (Thakur et al., 2021): 18 zero-shot retrieval datasets. BM25 is a strong baseline; dense retrievers trained on one dataset can struggle out of domain; unsupervised pretraining (Contriever) and cross-encoder reranking help.
- MTEB (Muennighoff et al., 2022): a leaderboard of text embeddings across retrieval and other tasks.
Measured (demo 01 Part B): 7,500 questions against 2,500 bios, recall@1 broken down by popularity.
- Sparse retrievers use no training.
- The dense retriever (mean-pooled embeddings + MLP, InfoNCE with in-batch negatives) is trained on 1,000 or 10,000 questions sampled in proportion to popularity, as real training data is.
| retriever | R@1 | R@5 | MRR | nDCG@10 | R@1, ranks 1–10 | 11–100 | 101–1000 | 1001–2500 |
|---|---|---|---|---|---|---|---|---|
| TF-IDF | 100.0% | 100.0% | 1.000 | 1.000 | 100.0% | 100.0% | 100.0% | 100.0% |
| BM25 | 100.0% | 100.0% | 1.000 | 1.000 | 100.0% | 100.0% | 100.0% | 100.0% |
| dense, 1,000 training questions | 80.3% | 93.8% | 0.863 | 0.887 | 100.0% | 95.6% | 81.7% | 78.5% |
| dense, 10,000 training questions | 95.9% | 99.6% | 0.976 | 0.982 | 100.0% | 99.3% | 96.9% | 95.2% |
A full name is a rare, exact clue, which is sparse retrieval’s best case. The dense retriever is as good as its training data. 1,000 popularity-skewed questions mention only 416 of the 2,500 people, and recall falls from 100% for the most popular to 78.5% for the rarest. This is Sciavolino et al.’s (2021) finding in miniature: dense retrievers fail on simple questions about rare entities, where BM25 does well. On queries that share meaning but not words, dense retrievers win. Fact World’s questions don’t test that.
3.3 Fast nearest-neighbor search
Scoring all chunk vectors exactly is fine at – chunks. Beyond that, approximate search trades a little accuracy for a lot of speed (FAISS; Johnson et al., 2019):
- inverted-file (IVF) indexes cluster the vectors and scan only the clusters nearest the query;
- graph indexes (HNSW) walk a neighbor graph;
- quantization (product quantization) compresses vectors to cut index size, at some cost in accuracy.
Measured (demo 01 Part C, an IVF index with 32 k-means cells over the 2,500 dense vectors):
| cells probed | vectors scanned | same top-1 as exact search |
|---|---|---|
| 1 | 3.2% | 69.5% |
| 2 | 6.3% | 87.2% |
| 4 | 12.6% | 95.7% |
| 8 | 25.1% | 99.0% |
| 32 (all) | 100.0% | 100.0% |
Scanning an eighth of the index finds the exact nearest neighbor 96% of the time. That is the speed–recall dial of every vector database.
Summary of Part 2: the different types of retrievers; training with a contrastive loss; common metrics (nDCG@10, …); and the performance vs cost trade-off at every step: sparse vs dense, exact vs approximate, bi- vs cross-encoder.
4. Part 3 — using retrieval in the LM
4.1 Three places to put retrieved text
| input augmentation | intermediate fusion | output interpolation | |
|---|---|---|---|
| how | put retrieved chunks into the LM’s input | incorporate chunks in intermediate layers | combine output token distributions |
| pros | easy to apply, no training needed, effective | scales to many passages | no training required* |
| cons | hard to use many chunks (context length) | requires retraining | limited effectiveness on many tasks |
| example | RAG | RETRO, InstructRETRO | kNN-LM |
4.2 RAG: input augmentation
RAG (Lewis et al., 2020) retrieves chunks and conditions generation on them. In its original, jointly trained form, the output marginalizes over the retrieved chunks:
Training a RAG system comes in three forms:
- independent: train the retriever and reader separately (DrQA, Chen et al., 2017; DPR);
- sequential: fix one and train the other with its signal (REPLUG, Shi et al., 2023, trains the retriever from the LM’s feedback);
- joint: train both end to end (RAG; REALM, Guu et al., 2020).
Today “RAG” usually means the simplest version: retrieve with an off-the-shelf retriever, paste the chunks into the prompt of an off-the-shelf LM (“Question: … References: …”), and generate. This is in-context RAG.
Effectiveness. Mallen et al. (2023) bucketed questions by the popularity of their subject. Retrieval gave GPT-3 the largest gains on rare entities. On the most popular entities it could even hurt, when the retrieved text was worse than what the model already knew.
Measured (demo 02 Part B). The same model now reads the top retrieved bio before the question:
| system | retrieval right | ranks 1–10 | 11–100 | 101–1000 | 1001–2500 | all |
|---|---|---|---|---|---|---|
| closed book | — | 100.0% | 100.0% | 68.2% | 37.5% | 51.1% |
| RAG, BM25 top-1 | 100.0% | 100.0% | 100.0% | 100.0% | 100.0% | 100.0% |
| RAG, dense top-1 (1,000 training questions) | 82.4% | 100.0% | 92.2% | 85.4% | 81.0% | 83.1% |
| RAG, gold bio (oracle) | 100.0% | 100.0% | 100.0% | 100.0% | 100.0% | 100.0% |
- Retrieval helps most where parametric memory is weakest: the rarest bin goes from 37.5% to 100%.
- The reader is only as good as what it is given. With the dense retriever, RAG is wrong wherever retrieval is wrong. For ranks 11–100 it is worse than closed book (92.2% vs 100%): Mallen et al.’s “retrieval can hurt popular entities”, reproduced.
Knowledge updates (Part C). After training, 500 people (20%) moved to another city. The closed-book model gives the old city for 51.4% of them and the new one for 1.6%. RAG over the updated datastore gives the new city for 100%. The knowledge was updated without retraining.
Limitations of in-context RAG (slides):
- Inflexibility: it retrieves even when the model already knows the answer, or when retrieval cannot help.
- No robustness to unhelpful documents. Asked “Who is Sam Altman?”, a system that retrieved a passage about Samuel Adams answers “He is a founding father of the US”.
Measured (Part D). Give the model the bio of a namesake — someone with the same first name — for the 100 most popular people, whose cities it knows closed-book (100%). Accuracy falls to 0.0%, and 100.0% of answers copy the namesake’s city. The context overrides what the model knew.
4.3 Deciding when to retrieve, and what to trust
Adaptive retrieval (Mallen et al., 2023): retrieve only when the model is unlikely to know, e.g. for entities below a popularity threshold, or when the closed-book answer has low confidence.
Self-RAG (Asai et al., 2024) trains the LM to emit reflection tokens that control retrieval and critique its own use of it:
- Retrieve? Is retrieval needed for the next segment? If no, the model generates directly.
- IsRel: is each retrieved passage relevant?
- IsSup: is the generation supported by the passage?
- IsUse: is the response useful?
At inference, the reflection tokens let the system call search adaptively, generate from several passages in parallel, and pick the segment whose critiques score best.
Measured (Part E, with the dense retriever, which errs on 18% of questions). Retrieval policies, alone and with a relevance check: fall back to the closed-book answer when the retrieved bio is about someone else, a hand-written stand-in for Self-RAG’s learned IsRel.
| policy | retrieval rate | accuracy | + relevance check |
|---|---|---|---|
| never retrieve (closed book) | 0.0% | 51.1% | 51.1% |
| always retrieve | 100.0% | 83.1% | 90.5% |
| retrieve if confidence < 0.5 | 63.3% | 81.4% | 84.6% |
| retrieve if confidence < 0.9 | 93.6% | 83.6% | 90.5% |
| retrieve if popularity rank > 100 | 96.0% | 83.4% | 90.5% |
- Confidence-based skipping helps a little. Skipping retrieval when confident (≥ 0.9) matches always-retrieve with 6% fewer retrievals, and slightly beats it (83.6% vs 83.1%), because it avoids a few retrieval errors on popular people.
- More skipping costs accuracy. The model’s confidence is poorly calibrated in the middle of the tail (§1.2), so skipping at a 0.5 threshold loses 1.7 points.
- The relevance check matters most, adding 7.4 points. It catches exactly the cases where the retriever handed over someone else’s bio, which is the job IsRel was designed for.
Tool-augmented LMs and deep research. Retrieval is one tool among many. Toolformer (Schick et al., 2023) trains LMs to call tools adaptively. Deep-research agents search, read and write iteratively, producing long cited reports. Examples:
- DR Tulu (Shao, Asai et al., 2025) trains with reinforcement learning on evolving rubrics, because long-form answers are hard to verify.
- Tongyi DeepResearch combines large-scale SFT with rejection sampling and RL with verifiable answer-matching rewards.
These are retrieval systems that decide for themselves when and what to retrieve (Lectures 17–18).
4.4 RETRO and kNN-LM
RETRO (Borgeaud et al., 2022) retrieves neighbors for every chunk of the input from a trillion-token database. It feeds them into the model through chunked cross-attention in intermediate layers. It scales to many passages, but the model must be trained (or retrofitted) for it. Borgeaud et al. report that a 7.5B RETRO model matched much larger models on language modeling.
kNN-LM (Khandelwal et al., 2020) interpolates at the output:
To build it:
- Store every (context, next token) pair of a text collection, keyed by the LM’s hidden state for the context.
- Look up the nearest keys at test time, and form by weighting their next tokens by .
No training is required, and the datastore can be swapped. Khandelwal et al. found it helps most for rare patterns, “generalization through memorization”, but it is less effective on many downstream tasks.
Measured (Part F). The datastore is keyed by the model’s last hidden state for ” lives in”; the prompt is the same statement:
| datastore | ranks 1–10 | 11–100 | 101–1000 | 1001–2500 | all | |
|---|---|---|---|---|---|---|
| training-time facts | 0.0 (LM alone) | 100.0% | 100.0% | 81.6% | 54.4% | 66.0% |
| training-time facts | 0.25 | 100.0% | 100.0% | 97.4% | 88.5% | 92.2% |
| training-time facts | 0.5 | 100.0% | 100.0% | 100.0% | 100.0% | 100.0% |
| UPDATED facts | 0.0 (LM alone) | 100.0% | 78.9% | 64.2% | 44.1% | 52.8% |
| UPDATED facts | 0.5 | 100.0% | 100.0% | 100.0% | 100.0% | 100.0% |
Interpolation fixes the tail, and swapping the datastore updates the answers without retraining. A caveat: each query’s context is stored here verbatim, so its nearest neighbor is an exact match, which is the best case. Real kNN-LMs match similar, not identical, contexts.
One more detail of this table: the LM alone answers the statement prompt correctly for 66.0% of people, but the question prompt (Part A) for only 51.1%. It was trained on statements (popularity-sampled) and on far fewer questions. The format through which knowledge is asked for still matters, as in Lecture 8.
Summary of Part 3:
- Architectures: RAG is widely used but has several limitations; RETRO (intermediate fusion) and kNN-LM (output interpolation) gain capacity while adding challenges.
- Training: independent, sequential or joint.
- Inference: recent progress overcomes RAG’s shortcomings, e.g. adaptive retrieval, self-critique, and deep-research agents.
5. Summary
- Monolithic LMs hallucinate and go stale: parameters hold finitely many facts (~2 bits/param), the long tail is not memorized, and data has a cutoff. Measured: closed-book accuracy 100% on the most popular people, 37.5% on the rarest; confidence barely separates right from wrong there (0.48 vs 0.36).
- A retrieval-augmented system = datastore (sources, chunking, scale up to 1.4T tokens) + retriever + LM.
- Sparse retrievers (TF-IDF, BM25) need no training and excel at rare exact terms: 100% R@1 on Fact World. Dense retrievers (contrastive dual encoders) match meaning, but are only as good as their training data: 78.5% on the rarest people with 1,000 popularity-skewed training questions. Rerankers add accuracy at a per-pair cost. ANN search trades recall for speed: 12.6% scanned → 95.7% exact.
- RAG fixes the tail (37.5% → 100% with BM25) and updates knowledge without retraining (moved people: 100% new city vs 51.4% old closed-book). But it is only as good as retrieval, and can hurt popular facts (92.2% vs 100%).
- Unhelpful documents override knowledge: a namesake’s bio took accuracy from 100% to 0%.
- Adaptive retrieval and Self-RAG-style critique decide when to retrieve and what to trust. A relevance check added 7.4 points; confidence-based skipping is limited by calibration.
- RETRO fuses retrieved text in intermediate layers; kNN-LM interpolates output distributions and supports swapping the datastore.
Common pitfalls
- Assuming a dense retriever beats BM25. On rare names and exact terms, BM25 is often better, and always cheaper to start with. Check BEIR-style out-of-domain behavior.
- Evaluating a retriever only on popular queries. The long tail is where it fails and where retrieval matters most.
- Trusting retrieved text unconditionally. A wrong passage overrides a right parametric answer (Part D); check relevance or support.
- Retrieving for everything. It costs latency and can hurt questions the model already answers well.
- Chunks too large or too small. One dilutes the match; the other separates an answer from its subject.
- Forgetting to update the datastore (or the index) when the world changes: RAG’s freshness is only as fresh as its index.
- Reading a model’s confidence as calibrated. Adaptive retrieval by confidence only works as well as the confidence does.
- Approximate search without measuring recall. An IVF index probing one cell missed the exact neighbor 30% of the time.
Exercises
-
TF-IDF by hand. A collection has 1,000 documents; “transformer” appears in 10 of them, “the” in all 1,000. A 100-word document contains “transformer” 3 times and “the” 8 times. Compute the TF-IDF weights of both terms (natural log). Which carries more signal, and why?
Answer
TF(transformer) = 0.03, IDF = ln(1000/10) = 4.61 → 0.138. TF(the) = 0.08, IDF = ln(1) = 0 → 0. "transformer" is rare in the collection, so its presence says a lot about the document; "the" is everywhere and says nothing. -
BM25 saturation. With , , how does the term-frequency factor grow from to to ? Why is that desirable?
Answer
f = 1: 2.5/2.5 = 1.0; f = 2: 5/3.5 = 1.43; f = 10: 25/11.5 = 2.17 (limit 2.5). Repeating a term ten times should not make a document ten times as relevant; saturation prevents keyword stuffing from dominating and rewards matching several different query terms. -
In-batch negatives. A batch has 64 (query, positive) pairs. How many negatives does each query get under the InfoNCE loss with in-batch negatives? What can go wrong when two queries in a batch are about the same chunk?
Answer
63 (the other queries' positives). If two queries share a positive chunk, that chunk appears as a "negative" for the other query — a false negative that pushes a correct match away; it is rare with many chunks and is sometimes masked out explicitly. -
Why do dense retrievers miss rare entities? In demo 01, the dense retriever trained on 1,000 popularity-sampled questions reaches 100% R@1 on the most popular people but 78.5% on the rarest. Give the mechanism, and two fixes.
Answer
Its embeddings and MLP were trained mostly on questions about popular people (only 416 of 2,500 people appear in the training questions); rare names are represented only through name tokens shared with others, so their query and bio vectors are less precisely aligned. Fixes: more and more balanced training data (10,000 questions → 95.2%), hybrid retrieval (combine BM25 and dense scores), or reranking BM25 candidates with a cross-encoder. -
RAG marginal. In the RAG formula, suppose top-2 retrieval gives , , and the generator gives answer token “lima” probability 0.9 given and 0.1 given . What is ? What would in-context RAG with both passages in the prompt do differently?
Answer
$0.7 \times 0.9 + 0.3 \times 0.1 = 0.66$: a mixture over passages, each read separately. In-context RAG reads both passages in one prompt and lets attention decide which to use — no explicit marginalization; a misleading second passage can then directly influence the answer (as in demo 02 Part D). -
Adaptive retrieval. A model is right closed-book on 95% of popular questions and 30% of rare ones; RAG is right on 85% of popular (retrieval errors) and 90% of rare ones. Half the questions are popular. Compare never, always, and “retrieve only for rare”.
Answer
Never: 0.5·0.95 + 0.5·0.30 = 62.5%. Always: 0.5·0.85 + 0.5·0.90 = 87.5%. Rare only: 0.5·0.95 + 0.5·0.90 = 92.5% — and half the retrievals. This is Mallen et al.'s argument; it requires knowing which questions are rare (popularity) or a calibrated confidence. -
kNN-LM. Write for neighbors with distances and stored next tokens . Why can kNN-LM incorporate new data without retraining, and what is its cost at inference?
Answer
$P_{\text{kNN}}(y \mid x) = \sum_{i: v_i = y} \exp(-d_i) / \sum_{i=1}^k \exp(-d_i)$. New (context, token) pairs are just added to the datastore; the LM's weights are untouched (demo 02 Part F: swapping the datastore updated all answers). The cost: a nearest-neighbor search over a datastore with one entry per training token, at every generated token — large memory and latency.
Related assignment (concepts only)
- Assignment 1 is due today (02/12), and Assignment 2 is released today. Retrieval pipelines — chunking, a sparse or dense retriever, and a reader that uses the retrieved text — are common building blocks of knowledge-intensive NLP projects.
rag_world.pyhere is a teaching implementation on a synthetic world. These notes do not provide assignment code.
Further reading
- A. Asai, S. Min, Z. Zhong, D. Chen, “Retrieval-based Language Models and Applications”, ACL 2023 tutorial (course reading).
- A. Asai, Z. Wu, Y. Wang, A. Sil, H. Hajishirzi, “Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection”, ICLR 2024 (course reading).
- A. Mallen, A. Asai, V. Zhong, R. Das, D. Khashabi, H. Hajishirzi, “When Not to Trust Language Models: Investigating Effectiveness of Parametric and Non-Parametric Memories”, ACL 2023.
- P. Lewis et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks”, NeurIPS 2020; K. Guu et al., “REALM”, ICML 2020; W. Shi et al., “REPLUG”, 2023.
- V. Karpukhin et al., “Dense Passage Retrieval for Open-Domain Question Answering”, EMNLP 2020; G. Izacard et al., “Unsupervised Dense Information Retrieval with Contrastive Learning” (Contriever), TMLR 2022; C. Sciavolino et al., “Simple Entity-Centric Questions Challenge Dense Retrievers”, EMNLP 2021.
- S. Robertson, H. Zaragoza, “The Probabilistic Relevance Framework: BM25 and Beyond”, 2009; N. Thakur et al., “BEIR”, NeurIPS Datasets 2021; N. Muennighoff et al., “MTEB”, 2022; J. Johnson, M. Douze, H. Jégou, “Billion-scale similarity search with GPUs” (FAISS), 2019.
- S. Borgeaud et al., “Improving Language Models by Retrieving from Trillions of Tokens” (RETRO), ICML 2022; U. Khandelwal et al., “Generalization through Memorization: Nearest Neighbor Language Models”, ICLR 2020.
- R. Shao et al., “Scaling Retrieval-Based Language Models with a Trillion-Token Datastore”, NeurIPS 2024; A. Asai et al., “OpenScholar”, 2024; Z. Allen-Zhu, Y. Li, “Physics of Language Models: Part 3.3, Knowledge Capacity Scaling Laws”, 2024.
Preview of Lecture 11 — Multimodal I
So far every input has been text. Lecture 11 asks how a Transformer can see:
- ViT: images as sequences of patches.
- CLIP: contrastive image–text pretraining, the same InfoNCE loss as today’s dense retriever, with images on one side. It enables zero-shot classification.
- Vision–language models (LLaVA, Molmo, PaliGemma): a vision encoder connected to an LM and tuned on visual instructions.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| retrieval-augmented generation (RAG) | 检索增强生成 |
| retrieval-based / retrieval-augmented LM | 基于检索的 / 检索增强的语言模型 |
| hallucination | 幻觉 |
| parametric / non-parametric memory | 参数化 / 非参数化记忆 |
| knowledge cutoff / obsolete knowledge | 知识截止 / 过时知识 |
| long tail / popularity | 长尾 / 流行度 |
| verifiability / attribution / citation | 可验证性 / 归因 / 引用 |
| datastore / chunk / chunking | 数据存储 / 文本块 / 分块 |
| retriever / reader (generator) | 检索器 / 阅读器(生成器) |
| sparse / dense retrieval | 稀疏 / 稠密检索 |
| term frequency / inverse document frequency (TF-IDF) | 词频 / 逆文档频率 |
| BM25 / term-frequency saturation / length normalization | BM25 / 词频饱和 / 长度归一化 |
| cosine similarity / dot product | 余弦相似度 / 点积 |
| dual encoder (bi-encoder) / cross-encoder / reranker | 双编码器 / 交叉编码器 / 重排序器 |
| contrastive learning / InfoNCE / in-batch negatives / hard negatives | 对比学习 / InfoNCE / 批内负例 / 难负例 |
| approximate nearest neighbor (ANN) / inverted file (IVF) / HNSW | 近似最近邻 / 倒排文件 / 分层可导航小世界图 |
| product quantization | 乘积量化 |
| recall@k / MRR / nDCG | 前 k 召回率 / 平均倒数排名 / 归一化折损累计增益 |
| input augmentation / intermediate fusion / output interpolation | 输入增强 / 中间层融合 / 输出插值 |
| marginalization | 边缘化 |
| adaptive retrieval | 自适应检索 |
| reflection token (Retrieve, IsRel, IsSup, IsUse) | 反思词元(是否检索、是否相关、是否被支持、是否有用) |
| tool-augmented LM / deep research agent | 工具增强语言模型 / 深度研究智能体 |
| kNN-LM / interpolation weight | k 近邻语言模型 / 插值权重 |