Naive RAG
Composed from severalalso called Vanilla RAG · single-pass RAG · standard RAG
- Ingest
- Index
- Retrieve
- Fuse
- Rerank
- Select
- Generate
- Evaluate
ingest → index → retrieve → generate — Retrieval fires once; stages run in order.
- Mechanism
- Retrieval is a fixed preprocessing step that fires exactly once: the context is the top-k of a single similarity functional, chosen before any generation begins.
- Wins when
- The answer lives in one passage the query names more or less directly — a question phrased in the corpus’s own vocabulary, with a single local answer.
- Fails when
- Two failures, and they are different. A query phrased unlike its source documents lands off the document manifold, so the nearest neighbors are the wrong ones. And an answer that requires composing evidence no single passage carries is unreachable at any k, because more context does not manufacture a relation the corpus never stated.
The mathematics it rests on
The Retrieval Problem: Relevance, Similarity, and the Geometry of Scores
Retrieval as ranking by a relevance functional — and the three similarity scores that agree on the sphere and diverge off it
Retrieval is ranking: given a query, score every document by a relevance functional rel(q, d) and return the top k, a set-valued operator on the resulting order. Because only the order matters, relevance is ordinal even though scores are cardinal — the ranking is invariant under any strictly monotone transform of the score, a fact we will lean on repeatedly. We then study the three similarity functions retrieval actually uses — Euclidean distance, the dot product, and cosine similarity — through the single identity ||a-b||^2 = ||a||^2 + ||b||^2 - 2<a,b>. On the unit sphere this identity collapses the three into one: ranking by Euclidean distance, by dot product, and by cosine all induce the same order. Off the sphere they diverge, because magnitude matters for the dot product but is quotiented away by cosine — the divergence that motivates normalization throughout the rest of the curriculum. We separate which of these are true metrics (Euclidean is; cosine distance violates the triangle inequality; the dot product is not a metric at all) because the triangle inequality is exactly the structure that tree- and graph-based approximate-nearest-neighbor indexes later exploit. The level sets make the picture geometric: equal-score loci are hyperplanes for the dot product, spheres for Euclidean distance, and cones for cosine. An interactive similarity playground and a tested, deterministic implementation accompany the derivation, with a finance example showing the same query ranking documents differently under dot product and cosine when document norms vary.
Chunking as a Segmentation and Optimization Problem
Where to cut a document, posed as a coherence-maximizing segmentation with an exact dynamic-programming optimum — and the proxy it secretly optimizes
Chunking is the first thing a retrieval pipeline does to a document and the least mathematized — the default is to split every few hundred tokens and move on. Posed properly it is a one-dimensional segmentation problem: choose boundaries that maximize within-chunk coherence. We show that coherence has a clean closed form — for L2-normalized sentence embeddings the within-segment cost is the segment length minus the norm of the sum of its embeddings, which is the length times one minus the mean resultant length, the von Mises-Fisher concentration statistic from the prerequisite topic — so minimizing total cost carves the document into tight clusters on the sphere. Because the cost is additive across segments, the globally optimal segmentation is computed exactly by an O(n squared) dynamic program, which we prove optimal and verify against brute force; TextTiling's greedy depth scores and fixed-size chunking are heuristics that cannot beat it. We then confront the honest catch that makes this more than an algorithms exercise: coherence is a proxy for downstream retrieval quality, and the harness shows boundary-recovery F1 peaking at the true section count while the coherence cost keeps falling under over-segmentation. An interactive Chunking Laboratory and a tested implementation accompany the derivation, with a synthetic 10-K filing on which the optimal segmentation recovers the section structure that fixed-size chunking misses.
Dense Retrieval and Dual Encoders: Architecture, Expressivity, and the Cost of Negatives
Why a query tower and a document tower trained to a separable score let you precompute every document, collapse retrieval to a single maximum-inner-product lookup, and represent exactly the relevance patterns of rank at most d by Eckart–Young — and why one batch of 2B encodings secretly buys B² training comparisons
InfoNCE told us how a dual encoder is trained; this topic asks what that architecture can represent and what it costs. A dual encoder is two towers, a query encoder and a document encoder, whose relevance score is the separable inner product of their outputs. We show that separability is the whole game: because the score factorizes, every document vector can be precomputed and stored once, and a query at serving time reduces to a single argmax over inner products — maximum-inner-product search, the problem the MIPS-hardness topic analyzes. We then ask the expressivity question. Stacking the scores into a query-by-document relevance matrix, a d-dimensional dual encoder can realize exactly the matrices of rank at most d; the Eckart-Young-Mirsky theorem makes the truncated SVD the optimal rank-d approximation to any target, so d is a clean upper bound on what the architecture can express, and retrieval accuracy collapses when d falls below the relevance pattern's intrinsic rank. We flag honestly that rank is an upper bound, not the tight sign-rank measure of how many dimensions relevance needs. Finally we account for training cost: a batch of B query-document pairs costs 2B encoder forward passes but produces a B-by-B Gram matrix of similarities, yielding B-squared-minus-B in-batch negatives at no extra encoding cost — the quadratic-utility-from-linear-cost law that makes in-batch-negative training the default. A laboratory reuses the InfoNCE finance encoder to show the precompute-then-MIPS path, the rank-d reconstruction of a relevance matrix, and the in-batch Gram trick; a tested notebook owns every number.
Retrieval versus Long Context: Attention Complexity and Positional Bias
If the context window is large enough to hold everything, why retrieve at all? Because attention costs (kL)² — quadratic in the tokens read — and because more context is not better: once the answer is in hand, extra passages are redundant at best and same-sector distractors at worst, so answer quality peaks at the smallest covering context and declines as you stuff the window, while a relevant passage buried in the middle is read at attenuated attention — a soft erasure. The right move is not a bigger window but a better-chosen one.
Modern context windows are large enough to hold a whole filing, which invites a tempting shortcut: skip retrieval and stuff everything in. This topic gives the mathematics of why that loses. The first reason is the rate: full self-attention over a context of k passages of L tokens forms a (kL)×(kL) score matrix, so the arithmetic cost is Θ((kL)²) — doubling the context quadruples the compute, and FlashAttention lowers the memory to O(n) but leaves the FLOPs untouched. The second reason is the distortion. We read the top-k retrieved passages under a finite attention budget — softmax weights w_j that sum to one — and combine their evidence additively, generalizing the von Mises–Fisher answer model the PMI and noisy-channel topics built: p(a|q,C_k) = softmax((⟨q,μ_a⟩ + Σ_j w_j⟨d_j,μ_a⟩)/τ). On a finance corpus of sectors of confusable companies, each answer carries several relevant passages plus a shell of same-sector distractors. Even with the answer reliably retrieved (recall@1 ≈ 1), answer quality Q(k) = E[p(a*|q,C_k)] is highest at the smallest covering context and declines monotonically: while the top-k is all-relevant the extra passages are redundant — a second filing of the same company moves belief almost not at all, the diminishing-returns result imported from the PMI topic — and once same-sector distractors enter, they steal attention budget and inject wrong-company evidence, so precision falls and the answer entropy H(A|context) rises toward the prior. Recall climbs while precision falls, and answer quality tracks precision, not recall: chasing recall@k by enlarging the window degrades the answer. Read against cost, the focused-retrieval point Pareto-dominates stuffing — quadratically more compute for strictly worse answers. The third pillar is positional: a relevant passage buried in the middle of a long context is read at attenuated attention (lost-in-the-middle), a soft erasure that drops quality even though the passage was retrieved. The answer model is the same synthetic softmax stand-in the previous topics used, so every quality number is exact for the model and illustrative of a real generator; a tested notebook owns every number, and the quadratic cost, the diminishing returns, and the monotone decline are asserted, not asserted-about.