rumblr Work in progressWIP

● The AI Primer · Lesson 29 · Part 4: embeddings and search

Retrieval

keyword search, meaning search, and combining them

This lesson covers The whole search pipeline: keywords, embeddings, hybrid ranking, rerankers and chunking

Members · open during launch 35 min14 figures and diagrams8 interactive

What this is

What is retrieval?

Retrieval is how an AI system finds the few passages that answer a question, so that a language model can answer from material it was never trained on. Two kinds of search do the finding. Keyword search matches exact words: it finds the one page that says ERR-4012 and misses a paraphrase. Meaning search compares embeddings, the lists of numbers that stand for what a text says: it finds the paraphrase and lets the error code blur. On twenty test questions, each search alone misses some answers, and the two together put every answer in the top three. A slower AI model then reads the question beside each passage on the shortlist and puts them in final order.

Why it matters: Whenever a language model must answer from material too big to paste into the prompt (about 200,000 tokens, roughly 500 pages, is the line), retrieval quality caps answer quality, because the language model can only use what retrieval hands it.

At a glance

Key takeaways

  1. BM25 scores keyword matches: rare words weigh more (IDF), repeated mentions saturate (k₁), long documents are discounted (b). It finds exact IDs and misses synonyms.
  2. Dense retrieval (bi-encoder) finds meaning and paraphrases but blurs exact tokens. Documents are embedded once, ahead of time.
  3. Hybrid search fuses both rankings with RRF, Σ 1/(60 + rank), using ranks, not scores, and usually beats either search alone.
  4. Retrieve, then rerank: a bi-encoder or hybrid search shortlists 50 to 100 cheaply; a cross-encoder reads each (question, candidate) pair together and reorders the shortlist.
  5. ColBERT keeps a vector per word and scores with MaxSim: close to cross-encoder precision, still precomputable, much more storage.
  6. Chunk on structure, keep headings with their content and attach metadata. Measure recall@k on questions with known answers: a forgotten prefix raises no error, and only that measurement catches it.

How it works, from scratch

The examples search a small company knowledge base: twenty help articles from IT, finance and HR, such as "Password policy", "Car mileage expense" and "Error ERR-4012: VPN tunnel failed". Twenty test questions come with their known answers, so every method can be scored the same way. Two terms are used throughout:

  • Token. Here, one word after lowercasing and dropping filler words ("the", "is").
  • Recall@k. The share of questions whose answer appears in the top k results. MRR (mean reciprocal rank) also rewards putting the answer first: an answer at rank 1 scores 1, at rank 2 scores 1/2, missing scores 0, averaged over questions.

The full pipeline, one box per section below:

Figure 1 · Diagram

Reading it: two cheap, wide searches run side by side over the whole collection, and their rankings are merged into one shortlist. Only the shortlist reaches the reranker on the right, which is slow but precise. Everything left of the shortlist must be fast, because it faces millions of documents; everything right of it can be slow, because it faces a hundred at most.

Chapter 1

Keyword search: BM25

Keyword search scores a document by the words it shares with the question. BM25, the standard scoring rule, refines plain counting in three ways: a rare word counts for more than a common one, each extra mention of a word adds less than the one before, and a mention in a long document counts for a little less than the same mention in a short one.

Take three one-line documents:

Doc Words Length
d₁ cat cat dog 3
d₂ dog bird 2
d₃ fish 1

The average length is (3 + 2 + 1)/3 = 2. Search for cat. It appears in one of the three documents, so it is rare and gets a high weight (0.981, computed below); "dog" is in two, so it would get less (0.470). Only d₁ contains "cat", twice, and d₁ is a bit longer than average. Plugging in, d₁ scores 1.207 and the others score 0.

Figure 2 · Diagram

Reading it: each query word contributes one product: how rare the word is times how much this document talks about it. The length box feeds into the count box because a mention in a short document is stronger evidence than the same mention in a long one. A word the document doesn't contain contributes zero, so a document that shares no words with the query scores 0, however close its meaning.
The formula and its symbols

Symbols

Symbol Meaning here Range / typical
q the query, as a list of words
d one document, as a list of words
t ∈ q "each word t in the query"
Σ add up the following over every query word
f(t, d) how many times word t appears in document d (term frequency) 0, 1, 2, …
|d| the document's length in words
avgdl the average document length in the collection
k₁ saturation: how quickly extra mentions stop helping 1.2 to 2.0; 1.5 here
b length normalization: 0 ignores length, 1 fully normalizes 0.75
N number of documents in the collection
n(t) number of documents containing t (document frequency) 1 … N
ln natural logarithm: grows slowly, so ten times rarer is not ten times heavier
IDF(t) inverse document frequency: the word's rarity weight ≥ 0

In words: for each word of the query, multiply how rare the word is by a count of its mentions that saturates and is adjusted for document length, then add those products up.

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

On the example (query "cat", document d₁): N = 3, n(cat) = 1, so IDF = ln(1 + 2.5/1.5) = ln(2.667) = 0.981. f = 2, |d| = 3, avgdl = 2: the denominator is 2 + 1.5 · (1 − 0.75 + 0.75 · 3/2) = 2 + 1.5 · 1.375 = 4.0625. The count part is 2 · 2.5 / 4.0625 = 1.231. Score = 0.981 · 1.231 = 1.207.

In Python:

import math
# 3 documents; 1 of them contains "cat"
N, n_t = 3, 1
# ln(1 + (N - n(t) + 0.5) / (n(t) + 0.5))
IDF = math.log(1 + (N - n_t + 0.5) / (n_t + 0.5))
round(IDF, 3)  # → 0.981
# f(cat, d1), |d1|, average document length
f, d_len, avgdl = 2, 3, 2
k_1, b = 1.5, 0.75
count_part = f * (k_1 + 1) / (f + k_1 * (1 - b + b * d_len / avgdl))
round(count_part, 3)  # → 1.231
# Σ over the query's only word
round(IDF * count_part, 3)  # → 1.207

Figure 3 · Chart

0.0 2.5 5.0 7.5 10.0 12.5 15.0 17.5 20.0 mentions of the word in the document, f(t, d) 0 1 2 3 4 5 6 credit (before the rarity weight) Saturation: the 10th mention adds little raw count k₁ = 0.5 (ceiling 1.5) k₁ = 1.2 (ceiling 2.2) k₁ = 1.5 (ceiling 2.5) k₁ = 3.0 (ceiling 4.0) 0.5 1.0 1.5 2.0 2.5 3.0 document length ÷ average length, |d| / avgdl 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 credit for one mention Length: long documents are discounted average length b = 0.0 b = 0.5 b = 0.75 b = 1.0

BM25 credit flattens toward k1 + 1 however often a word repeats, and one mention counts less in a longer document once b is above 0

Reading it: on the left, the x-axis is how often a word appears in a document and the y-axis is the credit BM25 gives it (before the rarity weight). The dashed line is raw counting, where 20 mentions count 20 times as much as one. The BM25 curves bend over and flatten toward k₁ + 1: the tenth mention adds almost nothing, which stops keyword-stuffed pages from winning. Smaller k₁ flattens sooner. On the right, one mention in documents of different lengths: with b = 0 length is ignored; with b = 0.75 a mention in a document twice the average length counts noticeably less.

In code: BM25.scores applies the formula to every document. View source

BM25 needs no training and runs in any search engine (Elasticsearch, OpenSearch, Lucene). It is hard to beat on exact identifiers such as product codes, error numbers, names and ticket IDs, and company data is full of them. Its blind spot is the paraphrase. Ask the help articles about "automobile reimbursement" and keyword search finds nothing, because the article that answers it says "car" and "reimbursed".

The three documents from the worked example, scored as you change them. Change the query, the documents and the two dials, and watch each document's score.

Chapter 2

Meaning search: dense retrieval with a bi-encoder

Meaning search finds that article. An embedding model turns every document into a card of numbers, its embedding, before any question arrives. When a question comes in, the same model makes a card for it, and the search returns the documents whose cards are closest. Searching this way is called dense retrieval.

With a small toy embedding model, the question "automobile reimbursement" and the car-mileage article share no words, yet their cards have a cosine similarity of about 0.8, the highest in the collection. Exact codes go the other way. For "What does ERR-4012 mean" the right article comes only 4th: "what" and "does" are dropped as filler, the code is one of the two words left, and "mean" pulls the card elsewhere.

Figure 4 · Diagram

Reading it: the encoder runs twice, but never on the question and a document together, which is why this design is called a bi-encoder. Documents are encoded once, when they are added. A question costs one encoding plus a nearest-neighbor lookup (see Vector indexes), which takes milliseconds over millions of documents. Because the model never sees the question and the document side by side, it cannot check whether a passage answers this question or only shares its topic.

In code: SearchEngine.dense embeds the question and returns the nearest documents. View source

Dense retrieval handles paraphrases, synonyms and other languages, and blurs exact tokens; keyword search does the reverse. Measure both kinds of question on your own data before trusting either search alone.

Every text's card, drawn as a strip of numbers. Take words out of a question, or add some, and watch which documents come closest.

Chapter 3

Hybrid search: reciprocal rank fusion (RRF)

Each search finds answers the other misses, so hybrid search runs both and merges their two ranked lists. The usual merge is reciprocal rank fusion (RRF). Each list votes for the documents on it, a higher place earning a bigger vote, and a document's votes are added up. Only positions are compared, never the two searches' scores, which are not on the same scale.

With the standard constant k = 60:

Document Dense rank BM25 rank RRF score
X 1 3 1/61 + 1/63 = 0.0164 + 0.0159 = 0.0323
Y 1 (absent) 1/61 = 0.0164

X, high on both lists, beats Y, first on only one.

Figure 5 · Diagram

Reading it: the two rankings are the only inputs; their raw scores are thrown away on purpose. BM25 scores run from 0 to about 20, cosine similarities from −1 to 1, so adding them would let one search drown the other, and fixing that would need tuning for each collection. Ranks are on the same scale for every search, so RRF needs no tuning.
The formula and its symbols

Symbols

Symbol Meaning here Range / typical
d a document
m number of rankings being fused 2 here (BM25 and dense)
i which ranking 1 … m
rank_i(d) d's position in ranking i (1 = top); lists d isn't on contribute nothing 1, 2, 3, …
k a damping constant: keeps rank 1 from dwarfing rank 2 60 (from the original paper)
RRF(d) the fused score small positive numbers

In words: a document's fused score is the sum, over each ranking it appears in, of one over sixty-plus-its-rank.

On the example: X: 1/(60+1) + 1/(60+3) = 0.01639 + 0.01587 = 0.0323. Y: 1/(60+1) = 0.0164.

In Python:

k = 60
# d's position in each ranking that contains it
def RRF(ranks):
    # Σ_i 1/(k + rank_i(d))
    return sum(1 / (k + rank_i) for rank_i in ranks)
# X: 1st in one ranking, 3rd in the other
round(RRF([1, 3]), 4)  # → 0.0323
# Y: on one ranking only
round(RRF([1]), 4)  # → 0.0164

Figure 6 · Chart

it-004 it-002 fin-006 fin-001 fin-005 hr-002 0.000 0.005 0.010 0.015 0.020 0.025 0.030 0.035 fused RRF score RRF for "what does ERR-4012 mean" (B = BM25 rank, D = dense rank) B1 D4 D1 D2 D3 D5 D6 from BM25: 1/(60 + rank) from dense: 1/(60 + rank)

For the query what does ERR-4012 mean, the error-code article collects credit from both BM25 and dense search and fuses to a clear first place

Reading it: each bar is one document's fused score, split into the part contributed by BM25 (orange) and by dense search (blue). The error-code article it-004 is BM25's only hit and dense search's 4th, and the two contributions stack up to put it clearly first. The password-policy article that dense search wrongly ranked first gets only its blue half.

Figure 7 · Chart

BM25 dense hybrid hybrid + rerank I forgot my password and I'm locked out how long must a password be what does ERR-4012 mean ERR-4013 on my laptop automobile reimbursement for business driving how many vacation days do I get connect to internal systems from home suspicious email with a link per-diem for meals when traveling enroll in MFA first day checklist for a new hire match vendor bills to payments automobile reimbursement notebook computer replacement holiday allowance scam message in my inbox refund for the hotel ERR-4012 fix ERR-4013 ERR-4013 Rank of the right answer (1 = top, ✗ = not in top 10) 1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ✗ 1 1 1 ✗ 1 1 1 ✗ 1 1 1 ✗ 1 1 1 ✗ 1 1 2 1 1 1 1 1 8 1 1 1 2 1 1 paraphrases exact codes

BM25 misses the paraphrase questions and dense search misses the error codes, but their misses never overlap, so the hybrid ranks every answer first

Reading it: one row per question, one column per method; the number is the rank at which the right answer appeared (✗ = not in the top 10). Look at where the colors differ. BM25's failures (the paraphrase block) are where dense search succeeds, and dense search's failures (the error-code block) are where BM25 succeeds. Their mistakes don't overlap, so the hybrid column is all 1s.
Method recall@3 (20 questions) MRR
BM25 alone 0.75 0.75
Dense alone 0.90 0.85
Hybrid (RRF) 1.00 1.00

In code: reciprocal_rank_fusion fuses any number of rankings, and evaluate measures recall@k and MRR for any search method. View source

Company data is full of both paraphrases and exact identifiers, so there too hybrid search usually beats either method alone. Elasticsearch and most vector databases offer it built in.

Both searches side by side on the twenty test questions from the table above, with their votes counted into one list. Switch either search off to see what the other one misses.

Chapter 4

Reranking: bi-encoder vs. cross-encoder

Hybrid search ranks every test question's answer first, but a document on the right topic can still fool it. Ask "What are the password rules?" Two articles are about passwords. The password reset how-to (it-001) mentions "password" three times; the password policy (it-002) is the real answer. BM25 and the fused hybrid ranking both put the how-to first. A document like this, which looks relevant but doesn't answer the question, is called a hard negative.

Meaning search cannot settle it, because each document's card was made without seeing the question. A cross-encoder reads the question and a document together, as one input, and scores the pair. That is more accurate, and more expensive: every pair needs its own pass through the model, so a cross-encoder only reorders a shortlist that a cheaper search has already found. This step is reranking.

A toy cross-encoder shows the idea. It checks which of the question's ideas the document covers:

question ideas: {password, rules} coverage phrase exact score
it-002 policy password ✓, policy/rules ✓ 2/2 = 1.0 1.0 0.5 ≈ 1.78
it-001 reset how-to password ✓, rules ✗ 1/2 = 0.5 0.0 0.5 ≈ 0.69

The score weighs the features: coverage + 0.5 × phrase + 0.25 × exact + 0.25 × cosine, where the cosine is the ordinary bi-encoder similarity (0.63 for the policy, 0.27 for the how-to). For the policy that's 1.0 + 0.5 + 0.125 + 0.16 ≈ 1.78; for the how-to, 0.5 + 0 + 0.125 + 0.07 ≈ 0.69. After reranking, the policy is first.

Figure 8 · Diagram

Reading it: in the top box, the question and the document never meet until their vectors are compared, so document vectors can be computed ahead of time. In the bottom box they're one input, so attention (see Attention) can connect every question word to every document word: "rules" can notice that the document says "policy" and "must". Nothing can be precomputed, because the score depends on the pair.

The cost decides how the two kinds of model are combined. Say a cross-encoder pass takes 10 ms on a GPU. Over a collection of a million documents that is 10,000 seconds per question; over a shortlist of 50 it is 0.5 s, or much less when the pairs are batched. So the cheap searches retrieve wide, the cross-encoder reranks narrow, and the shortlist is capped to keep latency predictable.

In code: retrieve_then_rerank shortlists with hybrid search, then reorders the shortlist with CrossEncoder.score. View source

A reranker is a model, and it can be wrong too. On the twenty test questions, where hybrid search already ranks every answer first, it demotes one: for "refund for the hotel" it prefers the car-mileage article, which talks about reimbursing trips. Measure recall@k and MRR with and without the reranker before shipping it.

Run the reranker on the password question, then on "refund for the hotel", where it gets the order wrong. Change the length of the shortlist and watch what the reranker can reach.

Chapter 5

Late interaction: ColBERT

A bi-encoder is fast because every document's card is made in advance, and coarse because a whole document is squeezed into one card. A cross-encoder is precise and can prepare nothing in advance. Late interaction, introduced with the ColBERT model, sits between them. It keeps a card for every word of a document, made in advance. When a question arrives, each of its words looks for its single best-matching word in the document, and the document's score adds up how well the question's words found partners.

Take two-number word vectors. The query has words (1, 0) and (0, 1); the document has words (1, 0) and (0.6, 0.8).

Query word vs. doc word 1 vs. doc word 2 best
(1, 0) 1.0 0.6 1.0
(0, 1) 0.0 0.8 0.8

Score = 1.0 + 0.8 = 1.8.

Figure 9 · Diagram

Reading it: the grid in the middle is the question-by-document table from the worked example; "max" picks the best cell in each row; "sum" adds the row winners. The document side is precomputed, as with a bi-encoder, but nothing is squeezed into one vector, so each question word gets matched on its own.
The formula and its symbols

Symbols

Symbol Meaning here
|q|, |d| number of word vectors in the query and the document
q_i the vector of query word i
d_j the vector of document word j
q_i · d_j dot product: how similar those two words are
max over j the best-matching document word for query word i
Σ over i add those best matches up

In words: for each query word, find its most similar word in the document, and add up those best similarities.

On the example: max(1.0, 0.6) + max(0.0, 0.8) = 1.0 + 0.8 = 1.8.

In Python:

# one vector per query word
q = [(1, 0), (0, 1)]
# one vector per document word
d = [(1, 0), (0.6, 0.8)]
def dot(a, b):
    return sum(a_k * b_k for a_k, b_k in zip(a, b))
# each query word's best match
[max(dot(q_i, d_j) for d_j in d) for q_i in q]  # → [1, 0.8]
# Σ_i max_j q_i · d_j
sum(max(dot(q_i, d_j) for d_j in d) for q_i in q)  # → 1.8

Figure 10 · Chart

password policy passwords must least 14 characters include number symbol passwords expire every 180 password rules MaxSim: each query word keeps its best match (score = 1.85) 1.00 0.85 −0.2 0.0 0.2 0.4 0.6 0.8 1.0 similarity

In ColBERT's MaxSim grid for password rules, password best matches itself at 1.00 and rules best matches policy at 0.85, for a score of 1.85

Reading it: rows are the query's words, columns the document's words, and color is the similarity of each pair. The outlined cell in each row is that row's maximum, the only number that counts. "password" finds itself (1.00), ignoring the near-identical "passwords"; "rules" finds "policy" (0.85), a synonym it could never match by spelling. The score is the sum of the outlined cells: 1.00 + 0.85 = 1.85.

In code: LateInteraction.search ranks documents by maxsim. View source

Late interaction gets much of a cross-encoder's precision while keeping documents precomputed. The cost is storage: one vector per word instead of one per document, often 50 to 200 times more. ColBERTv2 compresses those vectors to make that affordable.

The worked example's two-number word vectors, drawn as arrows you can turn. Turn them and watch which document word each question word picks.

Chapter 6

Chunking: how documents are cut before indexing

Every search so far ranked whole help articles a few sentences long. A longer document is cut into pieces called chunks before it is indexed, and each chunk is embedded and searched on its own. Where the cuts fall decides whether a fact stays next to the heading that explains it.

The simplest cut is a fixed-size window. Cut a 130-word text into 50-word chunks with 10 words of overlap, and a window starts every 50 − 10 = 40 words, at 0, 40 and 80, giving 3 chunks (words 1–50, 41–90, 81–130). Each shares 10 words with the next, so a sentence no longer than the overlap that is cut at one boundary survives whole in the next chunk.

Fixed windows ignore the document's structure. Take a short remote-work handbook and the question "home internet stipend". With 40-word fixed chunks, the best-matching chunk holds the heading "Home internet stipend", but the amount, "50 dollars per month", fell into the next window. With structure-aware chunks, cut at headings, the best chunk holds both.

Figure 11 · Diagram

Reading it: chunking takes several steps. Parsing decides what the structure is (and is where most quality is lost on messy PDFs). Splitting respects that structure. Prefixing the heading means a chunk that says "The stipend is 50 dollars" still says which stipend: the idea behind contextual retrieval. Metadata rides along so later stages can filter by date or by who's allowed to see it (see Retrieval-augmented generation).

Figure 12 · Chart

0 50 100 150 200 word position in the handbook Where the chunkers cut: the stipend heading and its amount Eligibility Home internet stipend Equipment Security at home Working hours heading 50 dollars fixed 40-word windows structure- aware chunks

Fixed 40-word windows split the stipend heading from its amount and cut through sections, while one structure-aware chunk holds both

Reading it: the colored strip in the middle is the handbook, one color per section, read left to right by word position. The brackets above it are the fixed 40-word windows; those below are the structure-aware chunks. The red marker is the "Home internet stipend" heading and the green marker the "50 dollars" amount. Above the strip they sit in different windows; below it, one chunk spans both. Notice also that the fixed windows cut straight through section boundaries.

Figure 13 · Interactive · computed from the lesson's code

Chunking

Try it: the handbook below is cut into fixed windows, searched with hybrid search and reranked by the toy cross-encoder described above. With the stipend question and 40-word chunks, retrieval ranks chunk 2 (the heading) first, and reranking lifts chunk 3, which holds the amount. Now pick the VPN question at 30 words with no overlap: the answer sentence is cut across chunks 6 and 7; raise the overlap to 10 words and one chunk holds it whole again. Drag top k down to 1 and watch the reranker lose its chance to help.

Parent-child retrieval. Small chunks match precisely; big chunks give the model enough context. Parent-child retrieval gets both. It indexes small children (single sentences), and when one matches, it hands the model the child's parent (the whole section).

Figure 14 · Diagram

Reading it: the search happens on the left, at sentence level, where matches are sharp. The hand-over happens on the right, at section level, where context is complete. The lookup in the middle maps each child to its parent.
The formula and its symbols

Symbols

Symbol Meaning here
n words in the document
s chunk size in words
o overlap in words (smaller than s)
s − o the step: how far each window moves
⌈ ⌉ "ceiling": round up to a whole number

In words: the number of chunks is the words left after the first overlap, divided by the step, rounded up.

On the example: ⌈(130 − 10)/(50 − 10)⌉ = ⌈120/40⌉ = 3.

In Python:

import math
# words, chunk size, overlap
n, s, o = 130, 50, 10
# ⌈(n - o) / (s - o)⌉: the step is s - o
math.ceil((n - o) / (s - o))  # → 3

In code: fixed_size_chunks and structure_aware_chunks cut the two ways, and parent_child_search matches a sentence and returns its section. View source

Good chunking comes down to four rules: split on structure, keep headings with their content, add modest overlap, and attach metadata for filtering.

The remote-work handbook, cut by your settings. Drag the chunk size and the overlap, then switch to cutting at headings, and watch where the heading "Home internet stipend" and its amount land.

Chapter 7

Asymmetric retrieval and the forgotten prefix

A badly placed cut loses an answer without raising an error. So can an embedding model that is called the wrong way. Retrieval is asymmetric: questions are short and phrased as asks, while passages are long statements. Some embedding models (the E5 family, for example) are trained to expect a "query: " prefix on questions and a "passage: " prefix on documents: a stamp that tells the model which side a text is on. Forget a prefix and every vector still looks normal (right length, plausible scores) but sits in a slightly wrong part of the space.

A simulated model shows the size of the effect. With both prefixes, 11 of 12 everyday questions find their answer in the top 3. Index the documents without "passage: " and the same questions fall to 9 of 12, and MRR drops from 0.875 to about 0.57. No error is raised anywhere.

Figure 15 · Diagram

Reading it: the top box is how the model was trained: both sides stamped, vectors aligned. In the bottom box the documents were indexed unstamped. The model still returns vectors, and the pipeline runs, but the two sides no longer line up well. The only way to catch it is to measure recall on a set of questions with known answers.

In code: PrefixedEmbedder simulates the model: it partly rotates the vector of any text that lacks a prefix. View source

Read the embedding model's documentation for required prefixes or instructions, use the same model and settings at indexing and query time, and keep a small set of questions with known answers, so that a drop in recall shows up.

The simulated model on its twelve everyday questions. Index the documents with their "passage: " stamp or without it, and see what changes and what does not.

Test yourself

13 questions

Answer each one out loud or on paper before you open it.

Question 1Documents "cat cat dog", "dog bird", "fish"; query "cat". What does BM25 give the first document?Think it through, then reveal

IDF(cat) = ln(1 + 2.5/1.5) = 0.981. With f = 2, |d| = 3, avgdl = 2, k₁ = 1.5 and b = 0.75 the denominator is 2 + 1.5 · 1.375 = 4.0625, so the score is 0.981 · 2 · 2.5 / 4.0625 = 1.207.

Question 2A document is 1st in dense search and 3rd in BM25. What's its RRF score?Think it through, then reveal

1/61 + 1/63 ≈ 0.0323, versus 0.0164 for a document that is 1st in only one list.

Question 3Query words (1, 0) and (0, 1); document words (1, 0) and (0.6, 0.8). What's the MaxSim score?Think it through, then reveal

max(1.0, 0.6) + max(0.0, 0.8) = 1.8.

Question 4How many 50-word chunks with 10 words of overlap does a 130-word text make?Think it through, then reveal

⌈(130 − 10)/(50 − 10)⌉ = 3, starting at words 0, 40 and 80.

Question 5What goes wrong if you forget an embedding model's "passage: " prefix when indexing?Think it through, then reveal

Nothing errors: vectors look normal and scores look plausible, but documents land where the model never aligned them with questions, and recall silently drops (11 of 12 to 9 of 12 in the lesson's simulation). Only an evaluation on labeled questions catches it.

Question 6What do BM25's k₁ and b control?Think it through, then reveal

k₁ sets saturation: how fast extra mentions of a word stop adding score (the credit per word can never exceed k₁ + 1). b sets length normalization: 0 ignores document length, 1 fully scales mentions by length relative to the average. Typical values are k₁ ≈ 1.2 to 2 and b = 0.75.

Question 7Bi-encoder vs. cross-encoder: how do you combine them in one pipeline?Think it through, then reveal

A bi-encoder embeds questions and documents separately, so documents are embedded once and searched in milliseconds with an ANN index; it's fast but never sees the pair together. A cross-encoder reads question and document as one input, so it's accurate but costs one model pass per pair and can't precompute anything. Combine them: retrieve the top 50 to 100 with the bi-encoder (or hybrid search), rerank that shortlist with the cross-encoder, and pass the top few to the model. Cap the shortlist to keep latency predictable.

Question 8Why does hybrid search beat pure vector search on company data?Think it through, then reveal

Company data is full of exact identifiers (error codes, product SKUs, ticket numbers, names) that embeddings blur, and full of paraphrases and jargon that keyword search misses. BM25 and dense search fail on different questions, so fusing their rankings with RRF recovers the answers each one misses.

Question 9Why does RRF use ranks instead of scores?Think it through, then reveal

BM25 scores and cosine similarities live on unrelated scales, and those scales vary by query and collection. Ranks are always comparable, so RRF needs no tuning or score normalization. The constant k = 60 keeps the very top rank from dominating.

Question 10What's a hard negative, and how do you fix one in retrieval?Think it through, then reveal

A document on the right topic that doesn't answer the question, like the password-reset how-to for "what are the password rules". Fix it with a reranker that reads the question and document together, and when you fine-tune an embedding model, train on hard negatives so it learns the distinction (see Training embedding models).

Question 11What does ColBERT trade to get better precision than a bi-encoder?Think it through, then reveal

Storage and some query cost. It keeps one vector per word instead of one per document, often 50 to 200 times more vectors, and scores with MaxSim over word pairs, in exchange for word-level matching with precomputed documents.

Question 12Fixed-size vs. structure-aware chunking?Think it through, then reveal

Fixed-size windows are simple but cut through headings, sentences and tables, separating facts from their context. Structure-aware chunking splits at headings and paragraphs, keeps each heading with its content, and attaches metadata. Parent-child retrieval searches small pieces but returns their larger parent for context.

Question 13Your RAG system gives confident wrong answers. How do you tell whether retrieval is the cause?Think it through, then reveal

Build a small labeled set of real questions with known answer passages and measure recall@k of retrieval alone. If the right passage isn't in the top k, no prompt change will fix the answer; fix retrieval (hybrid, reranking, chunking, prefixes, domain fine-tuning). If it is there, the problem is in generation.

Primary sources

The papers behind this lesson

Robertson & Zaragoza, The Probabilistic Relevance Framework: BM25 and Beyond (Foundations and Trends in Information Retrieval, 2009).

The authoritative account of where BM25 comes from: the probabilistic model behind IDF, and why term-frequency saturation and length normalization take the form they do.

The paper
Cormack, Clarke & Büttcher, Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (SIGIR 2009).

Introduced RRF, Σ 1/(k + rank) with k = 60, and showed that this simple, tuning-free fusion beats more elaborate methods.

The paper
Reimers & Gurevych, Sentence-BERT (2019).

Made bi-encoders practical: a siamese BERT that produces one comparable vector per sentence, turning hours of pairwise cross-encoding into milliseconds of vector search.

Read on rumblr →The paper
Karpukhin et al., Dense Passage Retrieval for Open-Domain Question Answering (2020).

Showed a dual encoder trained with in-batch and BM25-mined hard negatives can beat BM25 on open-domain question answering, the template for modern dense retrievers.

Read on rumblr →The paper
Khattab & Zaharia, ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT (2020).

Introduced late interaction: per-token vectors scored with MaxSim, getting near cross-encoder quality with precomputed documents.

Read on rumblr →The paper

Researcher's shelf

Further reading

  • Nogueira & Cho, Passage Re-ranking with BERT (2019), the cross-encoder reranker: https://arxiv.org/abs/1901.04085
  • Santhanam et al., ColBERTv2 (compressed late interaction): https://arxiv.org/abs/2112.01488
  • Wang et al., Text Embeddings by Weakly-Supervised Contrastive Pre-training (E5, the query/passage prefixes): https://arxiv.org/abs/2212.03533
  • Anthropic, Introducing Contextual Retrieval (contextual chunk prefixes + hybrid + reranking): https://www.anthropic.com/news/contextual-retrieval
  • sentence-transformers documentation (bi-encoders and cross-encoders): https://www.sbert.net/
  • Elasticsearch reciprocal rank fusion reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/rrf.html

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.