Retrieval-Augmented Generation

A language model asked "who won the 2024 Nobel Prize in Physics?" will confidently answer using only what it memorized during training. If that event happened after training ended, the model will guess. It also guesses if the event was rare in the training corpus. Often it guesses fluently and wrongly. This is the central limitation of purely parametric language models. Their knowledge is frozen at training time. It is compressed lossily into billions of weights. It is impossible to audit or update without retraining. Retrieval-Augmented Generation (RAG) addresses this by splitting the problem in two. A retrieval system searches an external corpus for text relevant to the query. This corpus might be a document store, a knowledge base, or internal company documents. A generation system then conditions its output on both the query and the retrieved text. It uses the retrieved passages as evidence, rather than relying solely on memorized parameters. The knowledge lives in an updatable, inspectable corpus instead of being baked into weights. This matters enormously in deployed systems. Enterprises want chatbots that answer from their own private documents. They do not want answers from whatever the model saw on the public internet. Search engines want up-to-date answers without retraining a trillion-parameter model every day. Legal, medical, and financial applications need citations. They need a retrieved passage a human can check. An ungrounded hallucination in those domains is a liability, not a curiosity. RAG turns "the model said so" into "the model said so, and here is the document it read." This article builds RAG from first principles. It covers how the retriever and generator are trained and combined. It gives the precise algorithm end to end with pseudocode. It explains why marginalizing over retrieved documents is mathematically sound. It covers the complexity and failure modes of the retrieval step. It also shows where the architecture fits among neighboring ideas. These include Prompting & Prompt Engineering, Dense retrieval and embeddings, and eventual extensions into Tool Use & Function Calling.

Key takeaways
  • RAG couples a retriever (finds relevant documents) with a generator (an LLM) that conditions its output on those documents.
  • It replaces or supplements a model's frozen parametric memory with a queryable, updatable, inspectable external corpus.
  • The canonical formulation marginalizes generation probability over top-k retrieved documents, giving a principled probabilistic model.
  • Dense retrieval (embedding similarity, e.g., via Dense retrieval and embeddings) plus approximate nearest-neighbor search makes retrieval fast at web scale.
  • RAG reduces hallucination and enables citations, but is only as good as the retriever — irrelevant or missing documents still produce wrong answers.
  • It is a stepping stone toward broader grounding strategies covered in Hallucination & Factuality and Tool Use & Function Calling.
The core insight

RAG grounds language generation by retrieving relevant external documents and conditioning the model's output on them, turning frozen parametric memory into an updatable, evidence-backed lookup.

The idea

A standard autoregressive language model defines a probability distribution pθ(y∣x)p_\theta(y \mid x) over an output sequence yy given an input xx, with all world knowledge implicitly encoded in the parameters θ\theta. Retrieval-Augmented Generation instead defines generation as a two-stage process. First, a retriever pη(z∣x)p_\eta(z \mid x) scores candidate documents zz from a corpus Z\mathcal{Z} for relevance to xx. Second, a generator pθ(y∣x,z)p_\theta(y \mid x, z) produces the output conditioned on both the query and the retrieved document(s). The retriever is typically a dense retrieval model: a bi-encoder that maps queries and documents into a shared embedding space, where relevance is approximated by inner product or cosine similarity, exactly the machinery covered under Dense retrieval and embeddings. The key modeling move is to treat the retrieved document zz as a latent variable and marginalize over it: ``` p(y | x) = Σ_z p_η(z | x) · p_θ(y | x, z) ``` Because summing over an entire corpus (millions to billions of documents) is intractable, this sum is approximated by restricting it to the top-kk documents returned by nearest-neighbor search — a controlled, tractable approximation whose quality depends on retrieval recall. Two architectural variants matter here. In RAG-Sequence, one document is used to generate the entire output sequence, and the final probability marginalizes complete sequences over the top-k documents. In RAG-Token, a different (weighted) mixture over documents can be used at every generated token, letting the model blend evidence from several documents within a single answer. Fusion-in-Decoder (FiD) is a related and now more common pattern: instead of marginalizing at the probability level, the decoder attends jointly over the encoded representations of all retrieved passages simultaneously, letting cross-attention do the evidence-combination implicitly. RAG is best understood as a retrieve-then-read generalization of open-domain question answering, promoted from a task-specific pipeline into a general-purpose generation mechanism that can be trained end to end or used entirely at inference time with a frozen retriever and frozen or fine-tuned generator.

How it works

The system has two components trained (or configured) somewhat independently, and one inference-time procedure that ties them together.

Indexing (offline, done once per corpus update). Every document in the corpus is encoded into a dense vector using a document encoder EDE_D, and these vectors are stored in an approximate nearest-neighbor (ANN) index (e.g., HNSW, IVF-PQ, or a similar structure). This is the expensive, embarrassingly parallel, one-time (or periodically refreshed) cost.

Retrieval (online, per query). The query is encoded with a query encoder EQE_Q (often sharing weights or architecture with EDE_D, but not always identical), and the ANN index returns the top-kk nearest document vectors by similarity score.

Generation (online, per query). The generator — a sequence-to-sequence or decoder-only LLM — receives the query concatenated with (or cross-attending to) the retrieved passages, and produces the answer. If citations are required, retrieved passage identifiers are threaded through so the final answer can point back to its evidence. ``` function RAG_ANSWER(query x, corpus index I, k): q_vec = ENCODE_QUERY(x) # dense embedding, O(d) docs = ANN_SEARCH(I, q_vec, k) # top-k passages, see complexity below scores = SOFTMAX([SIM(q_vec, ENCODE_DOC(d)) for d in docs])

# --- Fusion-in-Decoder style: encode each (query, doc) pair independently --- encoded_reps = [] for d in docs: rep = ENCODER(CONCAT(x, d)) # each passage encoded separately encoded_reps.append(rep) all_reps = CONCAT(encoded_reps) # decoder attends over all of them jointly y = DECODER_GENERATE(all_reps) # single joint decode, cross-attends to all docs return y, docs # return answer AND supporting evidence function RAG_SEQUENCE_MARGINAL(query x, docs, generator):

# Alternative scoring: marginalize whole-sequence probability over documents total_prob = 0 for (d, p_retrieve) in docs_with_scores: p_gen = PROBABILITY(generator, y | x, d) # probability of a candidate y given this doc total_prob += p_retrieve p_gen return total_prob ``` Training has two common regimes: 1. <strong>Frozen retriever, fine-tuned or frozen generator (retrieval-augmented inference).</strong> The retriever and its index are built once (often reusing an existing dense retriever); the generator, which may be a large pretrained LLM, is used with in-context retrieved passages via prompting, requiring no additional training. This is the dominant pattern in production systems today because it needs no gradient updates to the retriever. 2. <strong>End-to-end trained RAG.</strong> The generator's loss is backpropagated through the retrieval scores pη(z∣x)p_\eta(z\mid x) as well, nudging the query encoder to retrieve documents that make the correct answer more likely. Because the ANN search itself (the discrete top-k selection) is non-differentiable, the standard trick is to keep the retrieved set fixed within a training step (or refresh the index periodically) and only backpropagate through the continuous* relevance scores of that fixed set, treating the reranking as differentiable and the retrieval-and-index-lookup as an occasionally-refreshed subroutine.

Figure
RAG inference pipeline: query, retrieval index, and fused generation
Query x Query Encoder E_Q(x) → vector ANN Index (dense vectors) doc 194 doc 812 doc 003 doc 456 doc 271 doc 999 similarity search → top-k top-k retrieved passages z1..zk Generator LLM encodes (x, zi) each Decoder joint cross-attn over all zi Answer y + citations

Complexity & correctness

Time complexity of retrieval. With an exact brute-force search over NN documents each of embedding dimension dd, retrieval costs O(N⋅d)O(N \cdot d) per query — linear in corpus size, which is prohibitive for NN in the billions. Approximate nearest-neighbor structures (HNSW, IVF, product quantization) reduce this to roughly O(log⁡N⋅d)O(\log N \cdot d) or O(N⋅d)O(\sqrt{N}\cdot d) depending on the structure, at the cost of recall: the true nearest neighbor is found with high probability but not certainty. This is the standard sublinear-search tradeoff also central to Dense retrieval and embeddings: you trade a small, tunable probability of missing the best document for orders-of-magnitude speedup.

Time complexity of generation. Given kk retrieved passages each of length LL tokens, a Fusion-in-Decoder style encoder processes each passage independently in O(k⋅L2)O(k \cdot L^2) time (quadratic self-attention per passage, but not quadratic across passages, since they're encoded separately before the decoder fuses them) — this is why FiD scales better with kk than naively concatenating all kk passages into one long context, which would cost O((kL)2)O((kL)^2) under standard full self-attention. The decoder's cross-attention over the concatenated encoder outputs costs O(T⋅kL)O(T \cdot kL) for an output of length TT. Total generation cost is therefore roughly

O(kL2+T⋅kL)O(k L^2 + T \cdot kL)

compared to O((kL)2+T⋅kL)O((kL)^2 + T\cdot kL) for naive concatenation — a substantial saving when kk is large, since encoding cost grows linearly rather than quadratically in kk.

Space complexity. The index stores NN vectors of dimension dd, i.e., O(Nd)O(N d) floats (often compressed via product quantization to a fraction of a byte per dimension), plus graph or inverted-list overhead for the ANN structure, typically O(N)O(N) additional pointers.

Correctness argument. The probabilistic justification for RAG rests on the law of total probability. If zz is genuinely the (unknown) supporting document and the corpus Z\mathcal{Z} is exhaustive, then

p(y∣x)=∑z∈Zp(z∣x) p(y∣x,z)p(y \mid x) = \sum_{z \in \mathcal{Z}} p(z \mid x)\, p(y \mid x, z)

is exact by definition of marginalization — no approximation is needed if the sum runs over the whole corpus and the retriever's distribution pη(z∣x)p_\eta(z\mid x) is the true posterior over which document is relevant. The approximation error introduced by RAG comes from two truncations: (1) restricting the sum to the top-kk retrieved documents (valid as an approximation because pη(z∣x)p_\eta(z\mid x) is typically sharply peaked — a well-trained dense retriever assigns near-zero mass to irrelevant documents, so the truncated sum captures nearly all the probability mass); and (2) the retriever itself being an imperfect estimate of true relevance (an empirical error, bounded by retrieval recall@k, not a mathematical one). Thus RAG is exact under an idealized retriever and approximately correct in proportion to how close the real retriever's top-k recall is to 1. This gives a precise, falsifiable criterion for diagnosing failures: if the answer is wrong, either the retriever failed to place the needed document in the top-k (a recall failure, addressable by better retrieval or larger kk), or the generator ignored/misused a correctly retrieved document (a grounding failure, addressable by better fine-tuning or prompting).

Honest tradeoffs. RAG adds a hard dependency on retrieval quality: a system with a superb generator and a weak retriever will still hallucinate, just now while sounding like it's citing evidence — arguably worse, since the citation lends false credibility. RAG also adds latency (an ANN lookup plus longer, evidence-laden context) and cannot handle queries whose answer requires reasoning not present verbatim in any single document (e.g., multi-hop arithmetic over scattered facts) without additional retrieval iterations or Tool Use & Function Calling.

Worked example

Consider a customer-support RAG system over a small internal corpus, queried with: > "What is our refund policy for items damaged in shipping?" Suppose the indexed corpus contains four passages:

Doc IDContent (excerpt)Cosine similarity to query
D1"Refunds for damaged items require photo evidence within 14 days."0.81
D2"Standard returns must be initiated within 30 days of purchase."0.52
D3"Shipping delays are handled by our logistics partner."0.38
D4"Employees may not discuss refund exceptions with customers."0.29

With k=2k = 2, the retriever returns D1 and D2 (highest similarity). D1 is directly on-topic; D2 is tangentially related (returns policy generally, not damage-specific). The retrieval scores are converted to a normalized distribution via softmax over the top-k similarities: ``` softmax([0.81, 0.52]) ≈ [0.57, 0.43] (temperature-scaled example) ``` The generator, using Fusion-in-Decoder, encodes `(query, D1)` and `(query, D2)` independently, then the decoder cross-attends over both encoded representations while generating. Because D1's content directly answers the question and D2's does not, a well-trained generator learns (via its cross-attention weights, shaped by training signal) to lean heavily on D1's evidence despite D2 receiving nontrivial retrieval mass. The output: > "Damaged items are eligible for a refund if you submit photo evidence within 14 days of delivery. [Source: D1]" Trace of what would go wrong at each failure point, useful for debugging:

StageIf it failsSymptom
Query encodingEncoder doesn't capture "damaged in shipping" semanticsRetrieves generic return-policy docs only
ANN search / indexkk too small, or index stale (D1 added after last reindex)Correct document never appears in candidate set
Retrieval scoringD4 (irrelevant, policy about discussing exceptions) ranks highly due to keyword overlap on "refund exceptions"Noisy or off-topic passage crowds out D1
Generation / groundingGenerator ignores retrieved D1, answers from parametric memoryFluent but wrong or generic policy stated, no real citation

A second, contrasting case: query "What is our refund policy for lost luggage on international flights?" — no passage in the corpus addresses this. A well-behaved RAG system should recognize low maximum similarity (e.g., top score 0.31, well below the 0.81 seen above) and abstain or say "the available documents do not cover this," rather than force an answer from a low-relevance passage. This retrieval-confidence-aware abstention is precisely the mechanism connecting RAG to broader work on Hallucination & Factuality.

Common pitfalls & traps

PitfallWhy it happensConsequence
Treating retrieval as infallibleAssuming top-k always contains the needed factConfident wrong answers with a plausible-looking (wrong) citation
Chunking documents too coarsely or too finelyFixed-size chunking ignores semantic boundariesRelevant sentence split across chunks, or chunk too broad to embed precisely
No relevance/confidence thresholdSystem always returns top-k regardless of actual similarityAnswers manufactured from irrelevant documents when nothing relevant exists
Stale indexCorpus updated but ANN index not rebuilt/refreshedRetrieves outdated facts even though source documents were corrected
Ignoring retrieved context (parametric override)Generator's pretrained prior is stronger than the in-context evidenceModel contradicts its own retrieved passage
Context window overflow with large kkConcatenating too many/too-long passagesTruncated evidence, lost relevant passage, higher latency and cost

Pioneers & history

RAG synthesizes decades of information retrieval research with the sequence-to-sequence generation paradigm that matured through neural machine translation and pretrained transformers. Its immediate lineage runs through open-domain question answering (retrieve-then-read pipelines using classical sparse retrieval like TF-IDF/BM25), through the shift to learned dense retrieval, and finally into a single differentiable architecture combining both.

Origins · 1 minKaren Spärck Jones and how this was discovered
KS
Karen Spärck Jones
1935–2007 · Pioneered TF-IDF term-weighting, foundational to all information retrieval, including the retrievers inside modern RAG systems

History
1972
— Karen Spärck Jones formalizes inverse document frequency, the statistical backbone of classical text retrieval.
2004
— BM25 ranking function becomes the standard strong sparse-retrieval baseline used for decades.
2018
— BERT and pretrained transformer encoders enable learned dense embeddings for semantic retrieval.
2020
— Dense Passage Retrieval and the RAG paper formalize retrieval as a differentiable, marginalized latent variable inside a generation model.
2021
— Fusion-in-Decoder demonstrates scalable joint attention over many retrieved passages, becoming a dominant production pattern.

Where this matters

RAG underlies enterprise "chat with your documents" products, where a company's internal wikis, contracts, or support tickets are indexed and queried by an LLM interface without any model retraining. Search engines that generate synthesized answers with citations (rather than only a ranked link list) use retrieval-augmented pipelines to ground responses in live web content. Legal and medical assistant tools rely on RAG to point to source statutes or clinical guidelines, since an unsupported claim in these domains carries real liability. Coding assistants use retrieval over a codebase or documentation set so suggestions reflect the actual project rather than generic patterns memorized from public code. RAG is also a natural precursor to agentic systems that interleave retrieval with other actions, connecting directly to Tool Use & Function Calling, where retrieval becomes just one callable tool among many (calculators, APIs, code execution) that a model can invoke mid-generation. Because retrieval quality directly bounds output faithfulness, RAG is also the primary architectural lever discussed in work on Hallucination & Factuality, and its prompt-construction step (how retrieved text is formatted and inserted into context) draws directly on techniques from Prompting & Prompt Engineering.

Ask the tutor: How would you redesign a RAG pipeline to handle a question that requires combining facts from three separate documents through multi-step reasoning?

Is RAG a replacement for fine-tuning an LLM on domain data?

Not entirely — the two address different problems. Fine-tuning changes the model's parametric behavior: its style, task-following ability, or deeply internalized patterns. RAG changes what facts the model has access to at inference time, without touching parameters. A model fine-tuned on legal writing style still needs RAG to cite the correct, current statute, since fine-tuning data goes stale just like pretraining data. Many production systems use both: a fine-tuned model for tone and task format, combined with RAG for up-to-date, sourced factual content. Choosing between them is really a question of whether the gap is in behavior (fine-tune) or knowledge (retrieve).

Why not just make the context window huge and put the whole corpus in the prompt?

Even with very large context windows, this doesn't scale: corpora can contain millions of documents, far exceeding any practical context length, and attention cost grows at least linearly (often worse) with context size, making inference slow and expensive. Long-context models also empirically show a "lost in the middle" effect, attending less reliably to information buried deep in a long, mostly irrelevant context. Retrieval narrows the input to a small, high-relevance subset, which is both cheaper and more reliably attended to than a sea of mostly-irrelevant tokens. Long context and RAG are complementary — a longer context lets you usefully include more retrieved passages, not skip retrieval altogether.

How is the retriever trained if we don't have labeled "correct document" pairs?

Several strategies exist. Supervised approaches use QA datasets where the supporting passage is known (e.g., from crowd-sourced annotations), training the query and document encoders so that correct pairs have high similarity via a contrastive loss. Weakly supervised approaches treat documents that lead the generator to produce the correct known answer as positive signal, backpropagating end-to-end. Some systems bootstrap from BM25-retrieved hard negatives to teach the encoder to distinguish topically similar but wrong documents from truly relevant ones. In production, many systems reuse an already-trained general-purpose dense retriever (see Dense retrieval and embeddings) and skip retriever-specific fine-tuning entirely.

Does RAG eliminate hallucination completely?

No — it reduces one major source of hallucination (missing or outdated knowledge) but introduces or leaves open others. The generator can still ignore retrieved evidence and answer from its parametric prior, misread or misattribute a retrieved passage, or over-generalize beyond what the passage actually supports. If retrieval itself returns irrelevant documents, the generator may hallucinate while appearing to cite real sources, which can be more misleading than an unsupported claim. RAG is a mitigation, formally analyzed and extended in Hallucination & Factuality, not a guarantee of factual correctness.

What's the difference between RAG-Sequence and RAG-Token?

RAG-Sequence picks (or marginalizes over) documents once per query and uses the same document(s) to generate the entire output sequence, which is simpler and works well when one passage fully answers the question. RAG-Token allows the effective mixture over documents to vary at each generated token, letting different parts of a longer answer draw on different passages — useful when an answer must synthesize facts scattered across multiple sources. RAG-Token is more expressive but more complex to implement and marginally more expensive at generation time, since document weighting must be recomputed or tracked per token rather than fixed for the whole sequence.

How does chunking strategy affect RAG quality?

Documents must be split into retrievable chunks, and this choice has an outsized effect on quality. Chunks too large dilute the embedding (a chunk about five topics embeds as an average, matching none precisely) and waste context budget on irrelevant text. Chunks too small lose necessary context (a sentence fragment referring back to "the policy above" is meaningless in isolation) and can be embedded ambiguously. Common mitigations include semantic chunking (splitting at topic or section boundaries rather than fixed token counts), overlapping windows so boundary information isn't lost, and attaching metadata (document title, section headers) to each chunk's embedding input to preserve context that's otherwise lost when a chunk is isolated.

Can RAG handle multi-hop questions that need information from several documents combined via reasoning?

Basic single-pass RAG struggles here, because a single retrieval step conditioned on the original query may fail to retrieve a document needed for an intermediate reasoning step never mentioned in the original phrasing. Iterative or multi-hop RAG variants address this by retrieving, generating a partial reasoning step or sub-query, then retrieving again based on that intermediate output, repeating until enough evidence is assembled. This blurs into agentic patterns where retrieval is one of several actions a model can invoke adaptively — the same generalization that leads toward Tool Use & Function Calling, where retrieval, calculation, and API calls are all callable tools orchestrated by the model's own reasoning trace.

Before this

Where this leads