This LLM Systems concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.
LLM Systems
RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation
RAG retrieval is evidence triage: sparse and dense first-stage retrievers, chunking, reranking, and ranked metrics all fail in different ways.
Concept Structure
RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation
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.
Learner Contract
What this page should let you do.
3 prerequisites listed; refresh them before leaning on the math or code.
Explain the mechanism, trace the main notation, and test one prediction in the live demo.
Read the intuition before the notation; the math should name a mechanism you already felt.
Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.
Claim/source review status
Substantive review recorded
1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
Retrieval-augmented generation is often described as “chat with your documents.” That phrase is useful for a product demo, but it hides the part that determines whether the model sees good evidence.
Retrieval is an evidence-triage system.
For each query, the system must decide:
- What units are retrievable? Sentences, passages, overlapping chunks, tables, code cells, or whole documents?
- What first-stage scorer gives enough recall? Sparse keyword scoring, dense embeddings, or a hybrid?
- Should a slower reranker look at the query and each candidate together?
- Did the ranked list actually contain evidence, or did the generator merely sound confident afterward?
BM25 and dense retrieval fail differently. BM25 can love exact words and miss paraphrases. Dense retrieval can love semantic neighbors and pull in a persuasive distractor. Chunking can split the answer across boundaries, while an oversized chunk can bury the answer in unrelated context. A reranker can rescue a candidate set when the right evidence was retrieved somewhere, but it cannot rerank evidence that never arrived.
That is why retrieval evaluation should happen before answer generation. A learner should be able to look at a query, a small corpus, and a ranked list and ask: “Was the supporting evidence in the top ? At what rank? Is the cited span actually enough?”
The central habit is:
Treat RAG retrieval as a measurable ranked-evidence pipeline, not as a magic truth layer.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let a corpus be split into chunks
where each chunk is the unit the retriever can return. A query is . A first-stage retriever assigns a score and returns the top- candidate set
For a sparse lexical retriever, Okapi BM25 scores a document or chunk by summing term-level evidence. One common form is
Here is a query term, is the frequency of term in chunk , is the chunk length, is average chunk length, controls term-frequency saturation, and controls length normalization. The important shape is not just “keyword overlap.” BM25 rewards informative query terms, saturates repeated terms, and normalizes for chunk length.
For dense retrieval, an encoder maps the query and each chunk to vectors:
A bi-encoder retriever can rank chunks by dot product or cosine similarity:
This is nearest-neighbor search in representation space. It can catch paraphrases, but its errors are geometric: a chunk can be close because it is topically similar, not because it contains the exact needed evidence.
A reranker usually starts from first-stage candidates and assigns a slower interaction score
The final list is
The dependency on matters. If chunking or first-stage retrieval excludes the true support, the reranker cannot invent it.
For evaluation, let be the set of chunks judged relevant or citation-supporting. If is the top- retrieved list, then a single-query recall-at- indicator is
If the first relevant result appears at rank , then
For graded relevance labels at rank ,
These are retrieval metrics. They do not say the generator will quote faithfully, avoid unsupported synthesis, or notice stale evidence. Citation support and answer correctness must be evaluated separately.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
import math, numpy as np
chunks = [
("A", "the theorem assumes gaussian initialization and infinite width", [0.86, 0.55], 1),
("B", "a blog says the theorem works for many neural networks", [0.92, 0.88], 0),
("C", "assumption notes for optimizer step size and clipping", [0.30, 0.20], 0),
("D", "older note claims finite width is enough without caveats", [0.78, 0.62], 0),
]
query = "what assumptions make the theorem valid"
q_vec = np.array([0.90, 0.70])
relevant = {doc_id for doc_id, _, _, rel in chunks if rel}
def bm25_like(text):
q_terms, terms = set(query.split()), text.split()
return sum(1 + math.log(1 + terms.count(t)) for t in q_terms & set(terms))
def dense(vec):
v = np.array(vec)
return float(q_vec @ v / (np.linalg.norm(q_vec) * np.linalg.norm(v)))
def rerank(doc_id, lexical, semantic):
support_bonus = 0.55 if doc_id == "A" else 0.0
stale_penalty = 0.45 if doc_id == "D" else 0.0
return 0.35 * lexical + 0.65 * semantic + support_bonus - stale_penalty
rows = [(doc_id, bm25_like(text), dense(vec), rel) for doc_id, text, vec, rel in chunks]
scores = {
"bm25": [(doc_id, lex, rel) for doc_id, lex, _, rel in rows],
"dense": [(doc_id, sem, rel) for doc_id, _, sem, rel in rows],
"rerank": [(doc_id, rerank(doc_id, lex, sem), rel) for doc_id, lex, sem, rel in rows],
}
for name, ranked in scores.items():
ranked = sorted(ranked, key=lambda x: x[1], reverse=True)
order = [doc_id for doc_id, _, _ in ranked]
first_rel = next((i + 1 for i, x in enumerate(order) if x in relevant), None)
recall3 = any(x in relevant for x in order[:3])
mrr = 0 if first_rel is None else 1 / first_rel
print(name, order, "Recall@3", recall3, "MRR", round(mrr, 3))
The point is not that these hand-written scores are a production retriever. The point is that retrieval has a ledger: one ranking can be keyword-driven, another semantic, and a reranker can only repair candidates that survived the earlier stage.
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
The lab asks you to predict which retrieval stage will put the true supporting chunk at rank 1 before you inspect the ledger. Change the chunking profile and retrieval stage, commit to a hypothesis, then reveal the top-3 evidence, Recall@3, MRR, nDCG, and the failure note.
Use it as a small source-grounding ritual: before asking a generator to answer, decide whether the retriever has actually placed evidence where the generator can see it.
Live Concept Demo
Explore RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation
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 RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation 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
RAG retrieval is evidence triage: sparse and dense first-stage retrievers, chunking, reranking, and ranked metrics all fail in different ways.
Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation should make visible.
Visual Inquiry
Make the image answer a mathematical question
RAG retrieval is evidence triage: sparse and dense first-stage retrievers, chunking, reranking, and ranked metrics all fail in different ways.
Which visible object should carry the first intuition?
Pick the cue that should make RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Supports the BM25 term-frequency, inverse-document-frequency, and length-normalization retrieval score used as the sparse retrieval baseline.
Open sourceSupports ranked retrieval evaluation with precision-recall tradeoffs, mean average precision, and the need to evaluate ranking quality rather than only final answer quality.
Open sourceSupports bi-encoder dense retrieval, query/passage embeddings, inner-product ranking, and the contrast with sparse retrieval for open-domain QA.
Open sourceSupports cross-encoder reranking over first-stage candidates by scoring query-passage pairs jointly.
Open sourceSupports evaluating retrieval systems across heterogeneous tasks and warns against over-trusting one retrieval setting.
Open sourceSupports the practical framing that chunking chooses the retrievable units and balances semantic coherence, retrieval granularity, and context length.
Open sourceClaim Review
RAG retrieval is evidence triage: sparse and dense first-stage retrievers, chunking, reranking, and ranked metrics all fail in different ways.
Claims without a substantive review badge still need exact source-support review.
manning-2008-iir-bm25, manning-2008-iir-ranked-eval, karpukhin-2020-dpr, nogueira-2019-bert-reranking, thakur-2021-beir, langchain-2026-text-splitters
Use equations, runnable code, and demos to check whether the source support is operational.
The lesson uses the sources for the retrieval mechanisms and metric vocabulary, then uses a finite toy corpus to make their failure modes visible before generation.
Sources: Introduction to Information Retrieval: Okapi BM25, Introduction to Information Retrieval: Evaluation of Ranked Retrieval Results, Dense Passage Retrieval for Open-Domain Question Answering, Passage Re-ranking with BERT, BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models, LangChain Docs: Text SplittersThe lab is a deterministic teaching witness, not a production vector database, exact BM25 implementation, learned embedding model, or evidence that retrieved context will be faithfully used by a generator.A bounded review summary is present; still check caveats and exact reference scope.Checked Stanford IIR BM25/ranked-eval chapters, DPR, BERT reranking, BEIR, and LangChain text splitting. The central synthesis is supported: sparse and dense retrieval, chunking, reranking, and ranked metrics are separate evidence-quality levers; generated-answer truth remains a separate evaluation.
Reviewer: codex-local-source-review; reviewed 2026-07-02Source support candidates
book 2008Introduction to Information Retrieval: Okapi BM25Supports the BM25 term-frequency, inverse-document-frequency, and length-normalization retrieval score used as the sparse retrieval baseline.
book 2008Introduction to Information Retrieval: Evaluation of Ranked Retrieval ResultsSupports ranked retrieval evaluation with precision-recall tradeoffs, mean average precision, and the need to evaluate ranking quality rather than only final answer quality.
paper 2020Dense Passage Retrieval for Open-Domain Question AnsweringSupports bi-encoder dense retrieval, query/passage embeddings, inner-product ranking, and the contrast with sparse retrieval for open-domain QA.
paper 2019Passage Re-ranking with BERTSupports cross-encoder reranking over first-stage candidates by scoring query-passage pairs jointly.
Practice Loop
Try the idea before it explains itself
RAG retrieval is evidence triage: sparse and dense first-stage retrievers, chunking, reranking, and ranked metrics all fail in different ways.
Before touching the demo, predict one visible change that should happen in RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation.
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 a claim, equation, code, or demo
Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.Open the draft below to save one note and next action in this browser.
RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation
What is the smallest example that makes RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays in this browser, attached to the selected learning item.
- References to inspect: attached references on this page.
- Definition, prerequisite, and contrast concept links
- The equation or runnable code 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 - RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation Selected item key: recorded for copy. Context: LLM Systems Page anchor: recorded for copy. Open question: What is the smallest example that makes RAG Retrieval Fundamentals: BM25, Dense Retrieval, Reranking, Chunking, and Evaluation click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code 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/rag-retrieval-bm25-dense-reranking-chunking-eval
concept:llm-systems/rag-retrieval-bm25-dense-reranking-chunking-eval