Simple Algorithm
Artificial Intelligence · Deep Layer · 26 min

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

DerivationWhich passages get reinforced
  1. ∇ηlog⁡p(y∣x)=∑zpθ(y∣x,z) ∇ηpη(z∣x)p(y∣x)=∑zp(z∣x,y) ∇ηlog⁡pη(z∣x)\nabla_\eta\log p(y\mid x)=\sum_z\frac{p_\theta(y\mid x,z)\,\nabla_\eta p_\eta(z\mid x)}{p(y\mid x)}=\sum_zp(z\mid x,y)\,\nabla_\eta\log p_\eta(z\mid x)

    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 p(z∣x,y)=pη(z∣x)pθ(y∣x,z)/p(y∣x)p(z\mid x,y)=p_\eta(z\mid x)p_\theta(y\mid x,z)/p(y\mid x):

  2. ∇ηlog⁡p(y∣x)=∑z(p(z∣x,y)−pη(z∣x)) ∇ηs(x,z)\nabla_\eta\log p(y\mid x)=\sum_z\big(p(z\mid x,y)-p_\eta(z\mid x)\big)\,\nabla_\eta s(x,z)

    For the softmax retriever, ∇ηlog⁡pη(z∣x)=∇ηs(x,z)−∑z′pη(z′∣x)∇ηs(x,z′)\nabla_\eta\log p_\eta(z\mid x)=\nabla_\eta s(x,z)-\sum_{z'}p_\eta(z'\mid x)\nabla_\eta s(x,z'), and the posterior sums to one:

  3. 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 kk.

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 dd for a query qq by the log-odds that it is relevant, assuming that terms occur independently given relevance.

DerivationFrom relevance odds to BM25
  1. score(q,d)=∑t∈q∩dlog⁡pt (1−pˉt)pˉt (1−pt)\text{score}(q,d)=\sum_{t\in q\cap d}\log\frac{p_t\,(1-\bar p_t)}{\bar p_t\,(1-p_t)}

    Let ptp_t and pˉt\bar p_t be the probabilities that term tt occurs in relevant and in non-relevant documents. Under term independence, ranking by log⁡P(rel∣d)P(rel‾∣d)\log\frac{P(\text{rel}\mid d)}{P(\overline{\text{rel}}\mid d)} is, up to a document-independent constant, a sum over the query terms present in dd:

  2. IDF(t)=log⁡N−nt+0.5nt+0.5\mathrm{IDF}(t)=\log\frac{N-n_t+0.5}{n_t+0.5}

    Without relevance judgments, set pt=12p_t=\tfrac12 and estimate pˉt≈nt/N\bar p_t\approx n_t/N from the ntn_t of NN documents that contain tt, with 12\tfrac12 smoothing. The weight becomes an inverse document frequency:

  3. BM25(q,d)=∑t∈qIDF(t) ft,d (k1+1)ft,d+k1(1−b+b ∣d∣/avgdl)\mathrm{BM25}(q,d)=\sum_{t\in q}\mathrm{IDF}(t)\,\frac{f_{t,d}\,(k_1+1)}{f_{t,d}+k_1\big(1-b+b\,|d|/\mathrm{avgdl}\big)}

    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 ft,df_{t,d} is saturated and length-normalized:

  4. Typical settings are k1∈[1.2,2]k_1\in[1.2,2] and b=0.75b=0.75. As ft,d→∞f_{t,d}\to\infty a term's contribution saturates at (k1+1) IDF(t)(k_1+1)\,\mathrm{IDF}(t), and bb interpolates between no length normalization (b=0b=0) and full normalization (b=1b=1).

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:

python
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 free

One matrix product yields B2B^2 scores for the cost of BB encodings on each side. DPR used raw inner products; many later retrievers normalize the embeddings and tune the temperature τ\tau.

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 ∑imax⁡jqi⊤dj\sum_i\max_j\mathbf q_i^\top\mathbf d_j. Hybrid systems fuse sparse and dense rankings, for example by reciprocal rank fusion, ∑m1/(60+rankm(d))\sum_m1/\big(60+\mathrm{rank}_m(d)\big) (Cormack, Clarke & Büttcher, 2009).

Nearest neighbors in high dimensions

Exact kk-nearest-neighbor search by brute force costs O(nd)O(nd) per query, about 8×10118\times10^{11} multiply–adds for a billion 768-dimensional vectors. Space-partitioning trees help in a few dimensions but degrade toward a linear scan as dd 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 d→∞d\to\infty (Beyer et al., 1999), so pruning by distance bounds stops working. Two facts rescue practical search: distances survive projection to far fewer dimensions than dd, and approximate answers usually suffice.

DerivationProof sketch (Dasgupta & Gupta, 2003)
  1. k ∥f(w)∥2=∑i=1kZi2∼χk2,E∥f(w)∥2=1k\,\norm{f(\mathbf w)}^2=\sum_{i=1}^kZ_i^2\sim\chi^2_k,\qquad\E\norm{f(\mathbf w)}^2=1

    Fix a pair and the unit vector w=(u−v)/∥u−v∥\mathbf w=(\mathbf u-\mathbf v)/\norm{\mathbf u-\mathbf v}. By rotation invariance each (Gw)i(G\mathbf w)_i is an independent N(0,1)\mathcal N(0,1), so k∥f(w)∥2k\norm{f(\mathbf w)}^2 is chi-square with kk degrees of freedom:

  2. Pr⁡[∣∥f(w)∥2−1∣>ε]≤2exp⁡(−k2(ε22−ε33))≤2n2\Pr\Big[\big|\norm{f(\mathbf w)}^2-1\big|>\varepsilon\Big]\le2\exp\Big(-\frac k2\Big(\frac{\varepsilon^2}2-\frac{\varepsilon^3}3\Big)\Big)\le\frac2{n^2}

    A Chernoff bound with the moment generating function EeλZ2=(1−2λ)−1/2\E e^{\lambda Z^2}=(1-2\lambda)^{-1/2}, optimized over λ\lambda, bounds each tail, using ln⁡(1±ε)≤±ε−ε2/2+ε3/3\ln(1\pm\varepsilon)\le\pm\varepsilon-\varepsilon^2/2+\varepsilon^3/3:

  3. A union bound over the (n2)\binom n2 pairs fails with probability at most (n2)⋅2n2=1−1n\binom n2\cdot\frac2{n^2}=1-\frac1n, and linearity, f(u)−f(v)=∥u−v∥ f(w)f(\mathbf u)-f(\mathbf v)=\norm{\mathbf u-\mathbf v}\,f(\mathbf w), turns the bound on f(w)f(\mathbf w) into one on every pair. Repeating the draw boosts the success probability.

Predict before you look

Use the theorem's bound: what target dimension kk guarantees that all pairwise distances among n=106n=10^6 passages are preserved within ε=0.1\varepsilon=0.1? Answer in thousands.

Show the answer

11.8 thousand

4ln⁡106/(0.005−0.000333)=55.3/0.004667≈11,8404\ln10^6/(0.005-0.000333)=55.3/0.004667\approx11{,}840, 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 q⊤x\mathbf q^\top\mathbf x, not by distance. How can a Euclidean nearest-neighbor index answer maximum-inner-product queries?

Let M≥max⁡i∥xi∥M\ge\max_i\norm{\mathbf x_i} and append one coordinate: x~=(x,M2−∥x∥2)\tilde{\mathbf x}=\big(\mathbf x,\sqrt{M^2-\norm{\mathbf x}^2}\big) and q~=(q,0)\tilde{\mathbf q}=(\mathbf q,0). Then ∥q~−x~∥2=∥q∥2+M2−2 q⊤x\norm{\tilde{\mathbf q}-\tilde{\mathbf x}}^2=\norm{\mathbf q}^2+M^2-2\,\mathbf q^\top\mathbf x, 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 kk returned, for speed and memory. Locality-sensitive hashing has the cleanest theory: for the cc-approximate near-neighbor problem it answers queries in time about nρn^\rho, with ρ=1/c\rho=1/c for Hamming distance (Indyk & Motwani, 1998) and ρ≈1/c2\rho\approx1/c^2 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 ℓ=⌊−ln⁡U⋅mL⌋\ell=\lfloor-\ln U\cdot m_L\rfloor with UU uniform, so layers thin out geometrically, and on every layer up to ℓ\ell it links to about MM 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 nn in practice, echoing Kleinberg's navigable small worlds, where suitable long-range links let greedy routing on a grid finish in O(log⁡2n)O(\log^2n) steps (Kleinberg, 2000); HNSW itself has no worst-case guarantee.

text
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 exactly

Larger efef 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 CC lists and scan only the nproben_{\text{probe}} lists whose centroids are closest to the query. Product quantization (Jégou, Douze & Schmid, 2011) compresses each vector: split it into mm 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 m=96m=96, 32 times smaller. Libraries such as FAISS (Johnson, Douze & Jégou, 2019) combine inverted files, quantization and GPUs to search billions of vectors.

Check your understanding

With product quantization (mm 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?

  1. dd multiply–adds, as for an uncompressed vector
  2. mm table lookups and additions
  3. 256⋅m256\cdot m multiply–adds
  4. Decoding the vector back to dd floats, then dd multiply–adds
Show the answer

B. mm table lookups and additions

Before scanning, compute an m×256m\times256 table of squared distances from each query sub-vector to every centroid of its codebook, 256 d256\,d multiply–adds once per query. The squared distance to a stored vector is then the sum of the mm 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 p(y∣x)=λ pkNN(y∣x)+(1−λ) pLM(y∣x)p(y\mid x)=\lambda\,p_{k\text{NN}}(y\mid x)+(1-\lambda)\,p_{\text{LM}}(y\mid x), where pkNNp_{k\text{NN}} puts mass proportional to e−d(ki,q)e^{-d(\mathbf k_i,\mathbf q)} 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 p(y∣x)p(y\mid x) 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 ∑z(p(z∣x,y)−pη(z∣x))∇s(x,z)\sum_z\big(p(z\mid x,y)-p_\eta(z\mid x)\big)\nabla s(x,z), 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: O(ε−2log⁡n)O(\varepsilon^{-2}\log n) 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.

Question 1

During end-to-end RAG training, the gradient raises the retrieval score of a passage zz exactly when...

  1. zz is ranked first by the retriever
  2. its posterior p(z∣x,y)p(z\mid x,y) exceeds its prior pη(z∣x)p_\eta(z\mid x): conditioning on the correct output makes it more probable
  3. zz shares many words with the query
  4. the generator's loss given zz is above average
Show the answer

B. its posterior p(z∣x,y)p(z\mid x,y) exceeds its prior pη(z∣x)p_\eta(z\mid x): conditioning on the correct output makes it more probable

∇ηlog⁡p(y∣x)=∑z(p(z∣x,y)−pη(z∣x))∇ηs(x,z)\nabla_\eta\log p(y\mid x)=\sum_z\big(p(z\mid x,y)-p_\eta(z\mid x)\big)\nabla_\eta s(x,z): passages that help explain the answer gain score and the others lose it, with no relevance labels at all.

Question 2

In BM25, a query term appears in almost every document of the collection. What weight does it get?

  1. The largest weight, because it matches every document
  2. Exactly 1
  3. A weight set only by how often it appears in the query
  4. Close to zero, or even negative: log⁡N−nt+0.5nt+0.5\log\frac{N-n_t+0.5}{n_t+0.5} is small when nt≈Nn_t\approx N
Show the answer

D. Close to zero, or even negative: log⁡N−nt+0.5nt+0.5\log\frac{N-n_t+0.5}{n_t+0.5} is small when nt≈Nn_t\approx N

A term found everywhere is no evidence of relevance. With nt>N/2n_t>N/2 the raw IDF is negative, which is why many implementations use log⁡(1+N−nt+0.5nt+0.5)\log\big(1+\frac{N-n_t+0.5}{n_t+0.5}\big) to keep weights positive.

Question 3

The Johnson–Lindenstrauss target dimension kk depends on...

  1. the ambient dimension dd and the number of points nn
  2. the ambient dimension dd and the distortion ε\varepsilon
  3. only the number of points nn and the distortion ε\varepsilon
  4. the intrinsic dimension of the data
Show the answer

C. only the number of points nn and the distortion ε\varepsilon

k=O(ε−2log⁡n)k=O(\varepsilon^{-2}\log n), independent of dd: a random projection preserves the pairwise distances of any nn points, however high-dimensional.

Question 4

Why does HNSW give each inserted point a random top layer, with geometrically decreasing probability for higher layers?

  1. So that upper layers are sparse "express lanes" and a greedy descent crosses the dataset in few hops
  2. To guarantee that the exact nearest neighbor is always found
  3. To balance the sizes of k-means clusters
  4. 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).