LLM Systems

Retrieval-Augmented Generation: External Memory for Generation

How embedding retrieval selects a small weighted evidence set for generation, and why retrieval coverage, answer correctness, citations, and freshness are different quantities.

status: reviewimportance: importantdifficulty 4/5math: undergraduateread: 24mlive demo

Concept Structure

Retrieval-Augmented Generation: External Memory for Generation

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

4prerequisites
0next concepts
3related links

Learning map

Retrieval-Augmented Generation: External Memory for Generation
BeforeRepresentation Learning & Embedding GeometryNow4/4 sections readyTryManipulate one control and predict the visible change.NextSpeculative Decoding: Lossless Multi-Token Generation

Object flow

4/4 sections readyAsk about thisResearch room
ConceptRetrieval-Augmented Generation: External Memory for GenerationLLM Systems
Local snapshot ready
concept:llm-systems/retrieval-augmented-generation

Conceptual Bridge

What should feel connected as you move through this page.

Carry inRepresentation Learning & Embedding Geometry

Bring the mental model from Representation Learning & Embedding Geometry; this page will reuse it instead of restarting from zero.

Work hereRetrieval-Augmented Generation: External Memory for Generation

How embedding retrieval selects a small weighted evidence set for generation, and why retrieval coverage, answer correctness, citations, and freshness are different quantities.

Carry outSpeculative Decoding: Lossless Multi-Token Generation

The next edge should feel earned: use the demo prediction here before following Speculative Decoding: Lossless Multi-Token Generation.

Test the linkManipulate one control and predict the visible change.Then continue to Speculative Decoding: Lossless Multi-Token Generation
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

Canonical sources: Lewis et al., "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks", Guu et al., "REALM", Karpukhin et al., "Dense Passage Retrieval for Open-Domain Question Answering", Izacard and Grave, "Leveraging Passage Retrieval with Generative Models for Open Domain Question Answering", Borgeaud et al., "RETRO", Gao et al., "Enabling Large Language Models to Generate Text with Citations", Liu et al., "Evaluating Verifiability in Generative Search Engines", Vu et al., "FreshLLMs", and Asai et al., "Self-RAG".

Long context is what the model can read. Retrieval is the decision about what gets placed into that context.

Retrieval-Augmented Generation turns a finite external corpus into inference-time memory. A retriever embeds the query and chunks, ranks chunks by similarity plus optional reranking features, chooses a small top-kk set, and the generator answers while conditioned on that evidence set.

The important mistake is to treat "RAG" as "paste docs into a prompt, therefore grounded." That skips the hard part. The right chunk can be absent, present but low weight, present but ignored, or present next to a stronger stale distractor. A cited source can support the selected answer while the selected answer is still stale relative to the hidden current truth.

This page teaches only the finite evidence-selection object. It is not a vector database survey, agent architecture page, web-search tutorial, retriever-training page, or a claim that RAG solves hallucinations.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let a finite corpus contain chunks

C={d1,,dm}.\mathcal C=\{d_1,\ldots,d_m\}.

Each query and chunk has a normalized embedding:

q=e(x)Rr,vi=e(di)Rr,q=vi=1.q=e(x)\in\mathbb R^r, \qquad v_i=e(d_i)\in\mathbb R^r, \qquad \lVert q\rVert=\lVert v_i\rVert=1.

The retriever assigns a score

si=qvi+λρi+ϵi.s_i=q^\top v_i+\lambda\rho_i+\epsilon_i.

Here qviq^\top v_i is embedding similarity, ρi\rho_i is a rerank or freshness feature, λ\lambda controls its strength, and ϵi\epsilon_i is retrieval noise.

Choose the top-kk set

Rk(x)=TopKi(si).R_k(x)=\operatorname{TopK}_i(s_i).

Within that set, turn scores into retrieval weights:

p~(dix)=exp(si/τ)1[iRk(x)]jRk(x)exp(sj/τ).\tilde p(d_i\mid x)= \frac{\exp(s_i/\tau)\mathbf 1[i\in R_k(x)]} {\sum_{j\in R_k(x)}\exp(s_j/\tau)}.

For each retrieved chunk, let the generator define a finite answer distribution

gi(y)=pθ(yx,di).g_i(y)=p_\theta(y\mid x,d_i).

The RAG answer distribution is the mixture

pRAG(yx)=iRk(x)p~(dix)gi(y).p_{\mathrm{RAG}}(y\mid x)= \sum_{i\in R_k(x)} \tilde p(d_i\mid x)g_i(y).

Now separate the quantities people often blur. Let yy^\star be the hidden correct current answer, and let

G(x)={i:di supports y and is admissible or fresh}.G(x)=\{i:d_i\text{ supports }y^\star\text{ and is admissible or fresh}\}.

Retrieval coverage is

coveragek(x)=1[G(x)Rk(x)].\mathrm{coverage}_k(x)= \mathbf 1[G(x)\cap R_k(x)\ne\varnothing].

Good-evidence mass is

evidenceMassk(x)=iG(x)Rk(x)p~(dix).\mathrm{evidenceMass}_k(x)= \sum_{i\in G(x)\cap R_k(x)} \tilde p(d_i\mid x).

Generation correctness probability is

correctProbk(x)=pRAG(yx).\mathrm{correctProb}_k(x)= p_{\mathrm{RAG}}(y^\star\mid x).

The selected answer is

y^=argmaxypRAG(yx).\hat y=\arg\max_y p_{\mathrm{RAG}}(y\mid x).

If the output cites a source d^\hat d, source support is only

sourceSupports(y^,d^)=1[d^ supports y^].\mathrm{sourceSupports}(\hat y,\hat d)= \mathbf 1[\hat d\text{ supports }\hat y].

That is not the same as correctness. A stale policy chunk can support "14 days" while the hidden current answer is "30 days."

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt

This witness uses the same finite corpus as the demo. The middle assertion is the core lesson: with k=2k=2, the correct current chunk is retrieved, so coverage is true, but the selected answer remains wrong because the stale chunk has more retrieval weight.

import numpy as np

ANSWERS = ["30", "14", "45", "unknown"]
TRUE_ANSWER = "30"

def norm(v):
    v = np.asarray(v, dtype=float)
    return v / np.linalg.norm(v)

query = norm([1.0, 0.0])

docs = [
    {
        "id": "old_policy",
        "text": "2024 handbook: standard returns are accepted within 14 days.",
        "embedding": norm([0.98, 0.20]),
        "fresh": 0,
        "supports_answer": "14",
        "gen": {"30": 0.05, "14": 0.86, "45": 0.02, "unknown": 0.07},
    },
    {
        "id": "current_policy",
        "text": "April 2026 policy: standard returns are accepted within 30 days.",
        "embedding": norm([0.92, 0.39]),
        "fresh": 1,
        "supports_answer": "30",
        "gen": {"30": 0.82, "14": 0.05, "45": 0.03, "unknown": 0.10},
    },
    {
        "id": "forum_exception",
        "text": "A customer once returned a jacket after 45 days during a promotion.",
        "embedding": norm([0.86, -0.51]),
        "fresh": 0,
        "supports_answer": "45",
        "gen": {"30": 0.10, "14": 0.05, "45": 0.75, "unknown": 0.10},
    },
    {
        "id": "shipping",
        "text": "Express shipping arrives in 2 business days.",
        "embedding": norm([0.30, 0.95]),
        "fresh": 1,
        "supports_answer": "unknown",
        "gen": {"30": 0.15, "14": 0.10, "45": 0.05, "unknown": 0.70},
    },
    {
        "id": "warranty",
        "text": "Electronics warranty coverage lasts one year.",
        "embedding": norm([0.10, -0.99]),
        "fresh": 1,
        "supports_answer": "unknown",
        "gen": {"30": 0.12, "14": 0.08, "45": 0.05, "unknown": 0.75},
    },
]

def softmax(xs, tau=1.0):
    xs = np.asarray(xs, dtype=float) / tau
    xs = xs - xs.max()
    ps = np.exp(xs)
    return ps / ps.sum()

def rag(k=2, tau=0.25, fresh_bonus=0.0, noise_sigma=0.0, seed=0):
    rng = np.random.default_rng(seed)
    rows = []
    for d in docs:
        cosine = float(query @ d["embedding"])
        noise = float(rng.normal(0.0, noise_sigma)) if noise_sigma else 0.0
        score = cosine + fresh_bonus * d["fresh"] + noise
        rows.append({**d, "cosine": cosine, "noise": noise, "score": score})

    rows.sort(key=lambda r: (-r["score"], r["id"]))
    top = rows[:k]
    weights = softmax([r["score"] for r in top], tau=tau)

    rag_probs = {a: 0.0 for a in ANSWERS}
    for w, r in zip(weights, top):
        for a in ANSWERS:
            rag_probs[a] += float(w) * r["gen"][a]

    answer = max(ANSWERS, key=lambda a: (rag_probs[a], -ANSWERS.index(a)))
    cited = max(top, key=lambda r: r["gen"][answer] * float(weights[top.index(r)]))

    return {
        "retrieved_ids": [r["id"] for r in top],
        "weights": {r["id"]: float(w) for r, w in zip(top, weights)},
        "coverage": any(r["supports_answer"] == TRUE_ANSWER for r in top),
        "evidence_mass": sum(float(w) for r, w in zip(top, weights) if r["supports_answer"] == TRUE_ANSWER),
        "rag_probs": rag_probs,
        "answer": answer,
        "p_correct": rag_probs[TRUE_ANSWER],
        "correct": answer == TRUE_ANSWER,
        "cited_source": cited["id"],
        "citation_supports_answer": cited["supports_answer"] == answer,
    }

baseline = rag(k=1, tau=0.25)
covered_but_wrong = rag(k=2, tau=0.25)
fresh_rerank = rag(k=2, tau=0.25, fresh_bonus=0.12)

assert baseline["retrieved_ids"] == ["old_policy"]
assert baseline["coverage"] is False
assert baseline["answer"] == "14"
assert baseline["citation_supports_answer"] is True
assert baseline["correct"] is False

assert covered_but_wrong["retrieved_ids"] == ["old_policy", "current_policy"]
assert covered_but_wrong["coverage"] is True
assert covered_but_wrong["answer"] == "14"
assert covered_but_wrong["p_correct"] < 0.50
assert 0.0 < covered_but_wrong["evidence_mass"] < 1.0

assert fresh_rerank["retrieved_ids"][0] == "current_policy"
assert fresh_rerank["coverage"] is True
assert fresh_rerank["answer"] == "30"
assert fresh_rerank["p_correct"] > covered_but_wrong["p_correct"]
assert fresh_rerank["cited_source"] == "current_policy"
04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the External Memory Mixer to test one distinction: retrieving the right chunk is not the same as assigning it enough weight to make the answer correct. Predict the regime first, then reveal the top-kk evidence set, evidence mass, answer mixture, selected citation, and correctness.

Live Concept Demo

Explore Retrieval-Augmented Generation: External Memory for Generation

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Retrieval-Augmented Generation: External Memory for Generation should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

How embedding retrieval selects a small weighted evidence set for generation, and why retrieval coverage, answer correctness, citations, and freshness are different quantities.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Retrieval-Augmented Generation: External Memory for Generation should make visible.

Visual Inquiry

Make the image answer a mathematical question

How embedding retrieval selects a small weighted evidence set for generation, and why retrieval coverage, answer correctness, citations, and freshness are different quantities.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Retrieval-Augmented Generation: External Memory for Generation easier to reason about before the page gives the answer.

Claim Review

How embedding retrieval selects a small weighted evidence set for generation, and why retrieval coverage, answer correctness, citations, and freshness are different quantities.

StatusSubstantive claim review pending

Source IDs and witness objects are attached for review; they are not proof by themselves.

SourcesNo references

Add source metadata before claiming support.

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Practice Loop

Try the idea before it explains itself

How embedding retrieval selects a small weighted evidence set for generation, and why retrieval coverage, answer correctness, citations, and freshness are different quantities.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Retrieval-Augmented Generation: External Memory for Generation.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptRetrieval-Augmented Generation: External Memory for GenerationLLM Systems

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptLLM Systems

Retrieval-Augmented Generation: External Memory for Generation

Anchored question

What is the smallest example that makes Retrieval-Augmented Generation: External Memory for Generation click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:llm-systems/retrieval-augmented-generation.

No local draft saved.
Evidence to inspect
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Retrieval-Augmented Generation: External Memory for Generation Object key: concept:llm-systems/retrieval-augmented-generation Context: LLM Systems Anchor id: concept/concept-notebook/llm-systems/retrieval-augmented-generation Open question: What is the smallest example that makes Retrieval-Augmented Generation: External Memory for Generation click without losing the math? Evidence to inspect: - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/llm-systems/retrieval-augmented-generation concept:llm-systems/retrieval-augmented-generation