Bring the mental model from Representation Learning & Embedding Geometry; this page will reuse it instead of restarting from zero.
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.
Concept Structure
Retrieval-Augmented Generation: External Memory for Generation
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Retrieval-Augmented Generation: External Memory for GenerationConceptual Bridge
What should feel connected as you move through this page.
How embedding retrieval selects a small weighted evidence set for generation, and why retrieval coverage, answer correctness, citations, and freshness are different quantities.
The next edge should feel earned: use the demo prediction here before following Speculative Decoding: Lossless Multi-Token Generation.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
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- 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
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let a finite corpus contain chunks
Each query and chunk has a normalized embedding:
The retriever assigns a score
Here is embedding similarity, is a rerank or freshness feature, controls its strength, and is retrieval noise.
Choose the top- set
Within that set, turn scores into retrieval weights:
For each retrieved chunk, let the generator define a finite answer distribution
The RAG answer distribution is the mixture
Now separate the quantities people often blur. Let be the hidden correct current answer, and let
Retrieval coverage is
Good-evidence mass is
Generation correctness probability is
The selected answer is
If the output cites a source , source support is only
That is not the same as correctness. A stale policy chunk can support "14 days" while the hidden current answer is "30 days."
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
This witness uses the same finite corpus as the demo. The middle assertion is the core lesson: with , 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
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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- 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.
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.
Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
Source IDs and witness objects are attached for review; they are not proof by themselves.
Add source metadata before claiming support.
Use equation, code, and demo objects to check whether the source support is operational.
Source support candidates
No structured source note is attached yet.
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.
Before touching the demo, predict one visible change that should happen in Retrieval-Augmented Generation: External Memory for Generation.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
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.Open the draft below to save one note and next action in this browser.
Retrieval-Augmented Generation: External Memory for Generation
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
This draft stays locally in this browser for concept:llm-systems/retrieval-augmented-generation.
- 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
- 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
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.
concept/concept-notebook/llm-systems/retrieval-augmented-generation
concept:llm-systems/retrieval-augmented-generation