Lab

How RAG finds the right passage

See how keyword search, embedding search and rank fusion pick passages from your documents, and why the right one is sometimes missed.

Before this: Meaning as a map shows how words become vectors, and Will it run on my machine? covers context length and memory.

You point a chatbot at your own notes and ask a question. A moment later it answers, quoting a paragraph you wrote months ago. How did it find that paragraph among thousands?

The usual answer is retrieval-augmented generation, or RAG. It sounds like the model has learned your documents. It has not. A search step finds a few passages that look relevant, pastes them into the prompt, and the model reads them like any other text. If the search picks the wrong passages, the best model in the world answers from the wrong page.

This page is about that search step. Below is a sample collection of 24 short notes, about 4,000 words, written for this explainer as “a local AI handbook”. Ask it something and watch three different searches rank its chunks.

Ask the collection

89 chunks · 4,028 words
Question

Keyword search wins: the format name is not in the word-vector vocabulary, so embedding search only sees "mean".

3
Chunks that would go into the prompt
1.2
How fast repeats stop counting
0.75
How much long chunks are penalised

word query word (keyword match)word closest to the query's vectorphrase labelled answer

BM25 (keywords)

recall@3 100%

Embedding (meaning)

Our expectation, not measured · sentence-embedding model: Likely still behind BM25: a sentence model splits q4_k_m into word pieces, so the name keeps some signal, but exact identifiers are where keyword search stays more reliable.

Loading word vectors…

Hybrid (rank fusion)

Waiting for embedding search…

tensors use about 4 bits, a few important ones get more, and it averages about 4.89 bits per weight on Llama 3.1 8B. Lower bits mean a smaller file and faster generation, at some cost in quality. Many people start with Q4_K_M as a balance and move up to q8_0 if they have room. Another common format is safetensors, which

Query wordCountIDFScore
mean14.093.70
q4_k_m13.002.71
BM25 total6.40

Cosine similarity with the question: ….

Hybrid score = 1/(60 + BM25 rank) + 1/(60 + embedding rank), shown ×1,000.

A sample collection of 24 short notes written for this explainer, split into chunks of 60 words with 10 words of overlap. Embedding search averages 50-dimensional GloVe word vectors, a classic baseline that is much weaker than the sentence-embedding models real systems use.

What RAG is, and what it isn’t

A RAG system has two halves. Indexing happens once, and again whenever documents change: split each document into chunks, compute a vector for each chunk and build a keyword index. Answering happens for every question: search the index, take the best few chunks, put them into a prompt with an instruction and the question, and let the model write.

RAG does not change the model’s weights, and it does not make the model “know” your documents. Remove a note from the index and the model can no longer use it. That is a strength. You can see exactly which passages were retrieved and ask whether a person could answer from them. When an answer is wrong, you can usually tell whether search failed or the model did.

This page stops at the prompt. It runs no language model, so nothing it shows depends on one model’s quirks.

Keyword search: BM25

The oldest working answer is to count words. BM25, from the probabilistic relevance framework of Robertson and Zaragoza, scores a chunk D for a question Q by adding up one term for each question word q:

score=∑q∈QIDF(q)·f·(k1+1)f+k1·(1−b+b·|D|/avgdl)

Here f is how often the word appears in the chunk. IDF is large for rare words and small for common ones: q4_k_m appears in 4 of the 89 chunks and gets an IDF of 3.00. The setting k1 makes repeats count less and less, and b penalises long chunks, which contain more words by chance. Click any result to see the per-word arithmetic. In the exact-name question, “mean” carries more of the top score (3.70) than q4_k_m (2.71): “mean” appears in one chunk and the format name in four, so the rarer word weighs more.

BM25 is fast and precise for exact names, error codes and model files, such as quantisation formats like Q4_K_M: things a word-vector model has never seen. Its weakness is vocabulary. If the question says “hot” and the note says “warm”, the score is zero.

Meaning search: embeddings

Embedding search turns the question and every chunk into vectors and ranks chunks by cosine similarity, so that “hot” can match “warm” (cosine 0.74 in GloVe) and “computer” can match “laptop” (0.77). “Similar” means “used in similar contexts”, not “means the same”: “hot” is even closer to “cold” (0.80). Here each chunk’s vector is the average of the GloVe vectors of its words, a classic baseline.

Averaging has visible costs. Words outside the vocabulary vanish: q4_k_m, reranker and hack have no vectors in our set of about 20,000 words. Everything also looks alike. For the synonyms question, every chunk’s cosine falls between 0.66 and 0.96, and the gaps between neighbours in the ranking are tiny. An average of 60 words is a blur of all of them.

Hybrid search: reciprocal rank fusion

Since the two searches fail differently, it is common to run both and merge the lists. Their scores are on different scales (BM25 has no upper limit; cosine sits between −1 and 1), so reciprocal rank fusion ignores scores and uses only ranks:

RRF(d)=160+rankBM25(d)+160+rankembedding(d)

The 60 comes from Cormack, Clarke and Büttcher, who found it worked well and that the exact value mattered little. In the “hybrid helps” question, the reranker chunk is 2nd and 3rd, so it scores 1/62 + 1/63 = 0.0320 (32.0 in the widget). BM25’s favourite is 1st in one list but far down the other, so it falls behind. In the synonyms question the right chunk is 1st in one list and absent from the other, worth only 1/61 = 0.0164, and chunks that are mediocre in both lists overtake it. Fusion is a vote, and a lone expert can lose.

Chunking

Before anything is indexed, each note is cut into chunks. The widget above uses chunks of 60 words that overlap by 10. Words stand in for tokens here; English averages about 1.3 tokens per word.

Chunking

4 chunks in this note · 89 in the collection
Note
60 words
10 words

Question: “What should I bring to a hack night?” Sizes are in words, standing in for tokens; English averages about 1.3 tokens per word.

word 1word 191
Answer part 1
…
hybrid rank of the best chunk holding it
Answer part 2
…
hybrid rank of the best chunk holding it
Recall@3 (hybrid)
…
share of answer parts retrieved
Text stored
1.16×
words in all chunks ÷ words in the notes

I bring to a hack night? Bring a laptop and its charger if you want to run models yourself, because power points near the tables are limited. A notebook is handy too. If you only want to watch and ask questions, bring nothing at all. There is always someone happy to show you what is running on their screen. If

Each bar is one chunk, placed by the words it covers. Green bars mark chunks holding part of the answer; the small marks underneath are where the answer parts sit in the note. Select a chunk to read it.

Small chunks are precise but cut explanations in half. Large chunks keep explanations together, but each one mixes several topics, blurs its vector and costs more of the prompt. Overlap repeats text across boundaries so a sentence near the edge survives whole somewhere; at 60 words with 10 of overlap, the index stores 1.16 times the original text. Splitting on paragraphs or headings, instead of a fixed count, often does better still.

Building the prompt

The retrieved chunks go into a prompt: an instruction (“answer using only these passages, cite them, say if the answer is missing”), the numbered passages, then the question. Every one of those words costs context. A longer context also costs memory, because the runtime keeps a KV cache entry for every token, and Will it run on my machine? shows how fast that grows.

Building the prompt

loading…
5 chunks
Chunk size (words)

Retrieving passages…

40506070805th10th15th20thposition of the answer documentaccuracy %no documents 56.1%

The curve is the paper's measurement: 75.8% with the answer first, 53.8% at 10th, 63.2% last, against 56.1% with no documents at all.

Position matters. Liu and colleagues gave models 20 retrieved documents, exactly one holding the answer, and moved it around. GPT-3.5-Turbo answered 75.8% correctly with the answer first, 53.8% with it 10th and 63.2% with it last, while with no documents at all it scored 56.1%. Material in the middle of a long prompt can be worth less than none. That is why some systems put the best chunks at the start and end. Reordering only helps when the ranking is right, though, and the cheapest fix is often fewer, better chunks.

Why retrieval fails

Most RAG failures are search failures. Three common ones, live on the same collection:

Why retrieval fails

Hybrid · top-k 3 · no answer exists
Failure

Question: “How do I fine-tune a model on my own photos?”

Loading word vectors…

Our expectation, not measured · sentence-embedding model: The same failure: any embedding model returns its nearest chunks whether or not one answers the question, so the prompt still has to tell the model to say it does not know.

Hybrid results

dashed line: top-k cut-off at 3
Loading word vectors…

Measuring retrieval: recall@k

You can test search without any model. Write questions whose answers you know, mark the passages that contain each answer, and count how often they appear in the top k results. That share is recall at k (a different top-k from the sampling setting of the same name). For the five labelled questions in the first widget at its default settings, recall@3 is 50% for BM25, 50% for embedding search and 50% for hybrid. The averages hide the story: each method fails on different questions. At k = 1, hybrid search reaches 50% against 20% for BM25 and 30% for embeddings; at k = 10, embedding and hybrid search reach 80% while BM25 stays at 50%. Five questions are far too few to choose a system, but the method is the same with fifty.

What this means for local AI

  • Retrieval runs well on modest hardware. Embedding models are small. all-MiniLM-L6-v2 produces 384-dimensional vectors, bge-small-en-v1.5 also 384, and nomic-embed-text-v1.5 768; all run on a laptop processor. Keyword search needs no model at all. If you change the embedding model, embed the whole collection again, since vectors from different models cannot be compared.
  • Your documents can stay home. Running the embedding model and the language model locally means neither your documents nor your questions leave the machine. If you hold personal information about other people for a business, club or organisation, the Privacy Act 2020 applies; purely personal or household use is largely exempt under section 27. Principle 12 covers disclosing personal information overseas, but a cloud service that only stores or processes it for you counts as you holding it (section 11), so it is not a disclosure, and you stay responsible for its security (principle 5). The index is a copy of your text: encrypt it like the documents, and rebuild it after deleting anything sensitive.
  • Chunk size is a trade-off, not a rule. The embedding model’s input limit sets a ceiling (all-MiniLM-L6-v2 truncates after 256 word pieces). Below that, choose by measuring recall@k on your own questions. On this collection, 120-word chunks beat 60-word chunks on both of the questions in the chunking figure.
  • Spend context carefully. An 8K context has room for about 25 full 240-word chunks (about 320 tokens each by our estimate), fewer once the answer and the conversation need space. Five good ones beat twelve loose ones, both for accuracy and for the KV cache.
  • Treat retrieved text as untrusted input. A document in the index can contain instructions, and the model reads them like any other text. This is prompt injection: keep passages clearly marked as material to quote, not commands, especially from files you did not write. No wording fully prevents it, which is why an agent’s harness limits what a model may do with what it reads.
  • Use both kinds of search. Model names, file formats and error codes are exactly the words that averaged or even trained embeddings handle less reliably. Hybrid search is cheap insurance.

What we simplified

  • No language model. The page stops at the prompt. Whether a model would use the passages well is the subject of the Liu et al. curve, which is their measurement, not ours. The amber marker maps your prompt onto their 20-document axis only as an illustration.
  • Averaged word vectors. We average 50-dimensional GloVe vectors from 2014. Real RAG uses trained sentence-embedding models with hundreds of dimensions, which handle word order, negation and unseen words much better. The “Our expectation, not measured” notes in the widgets say what such a model would likely do for each question; they are reasoned from published sources, not measured. This vector set spells most te reo words without macrons, so we strip macrons for lookup only (whānau is looked up as whanau); displayed text keeps them.
  • Words, not tokens. Chunk sizes are in words, and prompt sizes are estimated at 4/3 tokens per word. Use a real tokeniser for exact counts.
  • Simple text handling. No stemming, a short stopword list and fixed-size chunks. Production systems often stem, split on structure and add titles to chunks.
  • Brute-force search. We compare the question with all 89 chunks. Large collections use an approximate vector index and often a reranker.
  • A tiny, labelled sample. 24 notes and five labelled questions, written to show these effects. Real collections are larger and messier, and the traps here are deliberate.

Next: give a model tools and let it act on what it finds. See How an AI agent works. To try retrieval on your own notes first:

  1. Write 20 questions whose answers you know, and mark the passages that hold each answer.
  2. Measure recall@k for two or three chunk sizes before choosing one.
  3. Remove duplicate and outdated copies.
  4. Run keyword and embedding search together.
  5. Only then choose and tune the language model.

Or see how AI policy is changing in Aotearoa and elsewhere on the policy map.

Inspired by, and worth your time