Prompting, Retrieval & Tool Use
Giving models context, memory and actions.
A language model's weights are a frozen, lossy compression of its training data. Retrieval adds a memory that can be searched, updated and cited: each question becomes a nearest-neighbor query over millions of passages, answered in milliseconds by data structures that trade a little exactness for enormous speed. This lesson makes each piece precise, from the probabilistic model to the geometry of high-dimensional search.
What you’ll learn
- Formalize retrieval-augmented generation as a latent-variable model and derive the gradient that trains its retriever from answers alone.
- Derive BM25 from the probabilistic relevance framework, and train a dense retriever with in-batch negatives.
- Prove the Johnson–Lindenstrauss lemma, and explain how HNSW graphs, inverted files and product quantization approximate nearest-neighbor search.
- Describe retrieval inside the model (kNN-LM, RETRO), tool calls, and the documented failure modes of long contexts and retrieved text.
Retrieval as a latent variable
Nobody labels which passage is relevant; the retriever learns from the answer alone. Differentiate the log marginal likelihood of RAG-Sequence and recognize the posterior :
For the softmax retriever, , and the posterior sums to one:
Passages whose posterior exceeds their prior, the ones that made the correct output more likely, have their scores raised; the others are lowered. This is the E-step of EM in gradient form, restricted to the retrieved top .
Lewis et al. trained the query encoder and a BART generator on this marginal likelihood but kept the passage encoder, and hence the index of Wikipedia passages, fixed. REALM (Guu et al., 2020) also updated the passage encoder during pretraining and refreshed the index asynchronously. A stale index is the price of not re-embedding the corpus at every step.
Sparse and dense retrievers
The classic baseline scores documents by weighted term matches. The probabilistic relevance framework (Robertson & Spärck Jones, 1976; Robertson & Zaragoza, 2009) ranks a document for a query by the log-odds that it is relevant, assuming that terms occur independently given relevance.
Let and be the probabilities that term occurs in relevant and in non-relevant documents. Under term independence, ranking by is, up to a document-independent constant, a sum over the query terms present in :
Without relevance judgments, set and estimate from the of documents that contain , with smoothing. The weight becomes an inverse document frequency:
Repeated occurrences should count, with diminishing returns (Robertson and Walker's approximation to a two-Poisson model of "eliteness"), and long documents match terms by chance, so the term frequency is saturated and length-normalized:
Typical settings are and . As a term's contribution saturates at , and interpolates between no length normalization () and full normalization ().
BM25 needs no training, matches rare names and codes exactly, and is hard to beat out of domain: on the BEIR benchmark many dense retrievers trained on one dataset fell below BM25 on others (Thakur et al., 2021). Its blind spot is vocabulary mismatch: "car" never matches "automobile".
A dense retriever embeds queries and passages separately (a bi-encoder), so passages are indexed once. DPR (Karpukhin et al., 2020) trains it contrastively: for each question, the gold passages of the other questions in the batch serve as negatives, plus a "hard" negative retrieved by BM25 that does not contain the answer. That is the InfoNCE loss of Self-Supervised & Contrastive Learning:
import torch
import torch.nn.functional as F
def in_batch_loss(q_enc, p_enc, questions, passages, tau=1.0):
q = q_enc(questions) # (B, d): one row per question
p = p_enc(passages) # (B, d): passage i answers question i
scores = q @ p.T / tau # (B, B) inner products; diagonal = positives
labels = torch.arange(q.shape[0], device=q.device)
return F.cross_entropy(scores, labels) # B - 1 negatives per question, for freeOne matrix product yields scores for the cost of encodings on each side. DPR used raw inner products; many later retrievers normalize the embeddings and tune the temperature .
DPR beat a strong BM25 system by 9 to 19 points of top-20 passage accuracy on open-domain question answering, the result that made dense retrieval standard. Cross-encoders, which read query and passage together, are more accurate but need one network pass per pair, so they only rerank a shortlist. Late interaction sits between: ColBERT (Khattab & Zaharia, 2020) keeps one vector per token and scores . Hybrid systems fuse sparse and dense rankings, for example by reciprocal rank fusion, (Cormack, Clarke & Büttcher, 2009).
Nearest neighbors in high dimensions
Exact -nearest-neighbor search by brute force costs per query, about multiply–adds for a billion 768-dimensional vectors. Space-partitioning trees help in a few dimensions but degrade toward a linear scan as grows, a face of the curse of dimensionality: for many distributions the ratio of the farthest to the nearest neighbor's distance tends to 1 as (Beyer et al., 1999), so pruning by distance bounds stops working. Two facts rescue practical search: distances survive projection to far fewer dimensions than , and approximate answers usually suffice.
Fix a pair and the unit vector . By rotation invariance each is an independent , so is chi-square with degrees of freedom:
A Chernoff bound with the moment generating function , optimized over , bounds each tail, using :
A union bound over the pairs fails with probability at most , and linearity, , turns the bound on into one on every pair. Repeating the draw boosts the success probability.
Use the theorem's bound: what target dimension guarantees that all pairwise distances among passages are preserved within ? Answer in thousands.
Show the answer
11.8 thousand
, more than typical embedding dimensions of hundreds to a few thousand. JL is a worst-case guarantee for arbitrary points; real embeddings have low intrinsic dimension, and search only needs to preserve the order of the nearest few, which is why compressed indexes work far better than this bound suggests.
Think first Dense retrievers often score by inner product , not by distance. How can a Euclidean nearest-neighbor index answer maximum-inner-product queries?
Let and append one coordinate: and . Then , so the nearest augmented point maximizes the inner product (Bachrach et al., 2014). For unit vectors, inner product, cosine similarity and Euclidean distance give the same ranking.
Approximate indexes: graphs, inverted files and codes
Approximate nearest-neighbor (ANN) indexes trade recall, the fraction of the true top returned, for speed and memory. Locality-sensitive hashing has the cleanest theory: for the -approximate near-neighbor problem it answers queries in time about , with for Hamming distance (Indyk & Motwani, 1998) and for Euclidean distance (Andoni & Indyk, 2006). In practice, graph indexes and vector quantization dominate.
HNSW (Malkov & Yashunin, 2020) builds proximity graphs in layers. Each point draws a top level with uniform, so layers thin out geometrically, and on every layer up to it links to about neighbors that are close but not redundant with one another. A query descends greedily from the sparse top layer and finishes with a beam search on the bottom one. Query cost grows roughly logarithmically with in practice, echoing Kleinberg's navigable small worlds, where suitable long-range links let greedy routing on a grid finish in steps (Kleinberg, 2000); HNSW itself has no worst-case guarantee.
SEARCH(query q, entry point e, top layer L, beam width ef, k):
for layer l = L down to 1: # coarse-to-fine descent
repeat
e ← the neighbor of e on layer l that is closest to q
until no neighbor of e is closer to q than e
C ← beam search on layer 0 from e, keeping the ef closest points seen
return the k closest points of C # optionally re-ranked exactlyLarger raises recall and cost. Insertion runs the same search to find each new point's neighbors, layer by layer.
Inverted files (IVF) cluster the vectors with k-means into lists and scan only the lists whose centroids are closest to the query. Product quantization (Jégou, Douze & Schmid, 2011) compresses each vector: split it into sub-vectors, quantize each with its own 256-centroid codebook, and store one byte per sub-vector. A 768-dimensional float32 vector (3,072 bytes) becomes 96 bytes with , 32 times smaller. Libraries such as FAISS (Johnson, Douze & Jégou, 2019) combine inverted files, quantization and GPUs to search billions of vectors.
With product quantization ( sub-vectors, 256 centroids each), what does it cost to compute the approximate distance between a query and one stored vector, once the per-query preparation is done?
- multiply–adds, as for an uncompressed vector
- table lookups and additions
- multiply–adds
- Decoding the vector back to floats, then multiply–adds
Show the answer
B. table lookups and additions
Before scanning, compute an table of squared distances from each query sub-vector to every centroid of its codebook, multiply–adds once per query. The squared distance to a stored vector is then the sum of the table entries selected by its code bytes: asymmetric distance computation. PQ scans are fast as well as compact.
Retrieval inside the model, long contexts and tools
Retrieval can also act inside the model. The kNN-LM (Khandelwal et al., 2020) stores a key–value pair (context embedding, next token) for every token of a corpus and interpolates , where puts mass proportional to on the targets of the nearest stored contexts. It lowered perplexity without any additional training.
RETRO (Borgeaud et al., 2022) retrieves neighbors for every 64-token chunk from a database of 2 trillion tokens, using frozen BERT embeddings, and attends to them through chunked cross-attention. Its 7.5-billion-parameter model performed comparably to GPT-3 and Jurassic-1 on the Pile with 25 times fewer parameters. The authors also measured how much of the gain came from test documents overlapping the database: retrieval and contamination are hard to separate.
Prompting is conditioning: system instructions, retrieved passages, worked examples (in-context learning; see In-Context Learning & Emergence) and requested reasoning steps (Reasoning in Language Models) all change without changing weights. Long context windows invite pasting everything in, but position matters: in multi-document question answering, accuracy was highest when the relevant passage came first or last and dropped markedly when it sat in the middle (Liu et al., 2024, "Lost in the middle").
Tools generalize retrieval to any function. The model emits a structured call (a search query, a calculator expression, code), a harness executes it and appends the result to the context, and generation continues. Toolformer (Schick et al., 2023) learned where to insert API calls by keeping only those that lowered the loss on the tokens that followed. Loops that interleave reasoning, tool calls and observations (ReAct; Yao et al., 2023) turn models into agents, the subject of LLM Agents & Tool Use.
Key takeaways
- RAG treats the retrieved passage as a latent variable; the retriever's gradient is , so it learns from answers alone.
- BM25 is the relevance log-odds with an IDF weight, saturating term frequency and length normalization; dense bi-encoders trained with in-batch negatives (InfoNCE) capture paraphrases, and hybrids combine both.
- Johnson–Lindenstrauss: random dimensions preserve all pairwise distances; practical approximate search (HNSW graphs, inverted files, product quantization) trades recall for speed and memory, then re-ranks exactly.
- Retrieval also works inside models (kNN-LM, RETRO); tools generalize it to any function, and retrieved text must be treated as untrusted input.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
During end-to-end RAG training, the gradient raises the retrieval score of a passage exactly when...
- is ranked first by the retriever
- its posterior exceeds its prior : conditioning on the correct output makes it more probable
- shares many words with the query
- the generator's loss given is above average
Show the answer
B. its posterior exceeds its prior : conditioning on the correct output makes it more probable
: passages that help explain the answer gain score and the others lose it, with no relevance labels at all.
In BM25, a query term appears in almost every document of the collection. What weight does it get?
- The largest weight, because it matches every document
- Exactly 1
- A weight set only by how often it appears in the query
- Close to zero, or even negative: is small when
Show the answer
D. Close to zero, or even negative: is small when
A term found everywhere is no evidence of relevance. With the raw IDF is negative, which is why many implementations use to keep weights positive.
The Johnson–Lindenstrauss target dimension depends on...
- the ambient dimension and the number of points
- the ambient dimension and the distortion
- only the number of points and the distortion
- the intrinsic dimension of the data
Show the answer
C. only the number of points and the distortion
, independent of : a random projection preserves the pairwise distances of any points, however high-dimensional.
Why does HNSW give each inserted point a random top layer, with geometrically decreasing probability for higher layers?
- So that upper layers are sparse "express lanes" and a greedy descent crosses the dataset in few hops
- To guarantee that the exact nearest neighbor is always found
- To balance the sizes of k-means clusters
- To compress the stored vectors
Show the answer
A. So that upper layers are sparse "express lanes" and a greedy descent crosses the dataset in few hops
Each layer keeps a random fraction of the layer below, much as in a skip list. Long links on the sparse layers move the search quickly to the right region; the dense bottom layer refines it. Nothing makes the result exact.
Further reading
- P. Lewis et al., "Retrieval-augmented generation for knowledge-intensive NLP tasks," NeurIPS (2020).
- V. Karpukhin et al., "Dense passage retrieval for open-domain question answering," EMNLP (2020).
- S. Robertson & H. Zaragoza, "The probabilistic relevance framework: BM25 and beyond," Foundations and Trends in Information Retrieval (2009).
- Y. A. Malkov & D. A. Yashunin, "Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs," IEEE Transactions on Pattern Analysis and Machine Intelligence (2020).
- S. Borgeaud et al., "Improving language models by retrieving from trillions of tokens," ICML (2022).