Part IV ยท Ch. 19 โ€” RAG and Vector Search

Part IV ยท Chapter 19 of 20

RAG and Vector Search

Embeddings at work: giving the model a library card


A question the model can't answer

Ask the smartest model on Earth "What's our refund policy?" and it cannot know. Your store's policy was never in its training text โ€” the mountain of data from Chapter 15 stopped before your policy existed, and your private wiki was never in it at all. Worse, Chapter 9 taught us exactly what the machine does when it can't know: it produces something plausible anyway. Confident, fluent, and made up.

Run through the tools we already own and watch each one miss. We could retrain from scratch on text that includes your wiki โ€” years of GPUs for a returns policy, absurd. We could fine-tune or add a LoRA adapter (Chapters 16โ€“17) โ€” but we drew an honest boundary there: adapters teach style and skills, and weights make an expensive, unreliable filing cabinet for facts that change every Tuesday. Or we could paste your whole document pile into the prompt โ€” but Chapter 18 priced that: the context window is a desk, not a library, with quadratic teeth.

The actual fix is one homely sentence: don't memorize the library โ€” get a library card. Fetch the few passages that matter for this question, put only those on the desk, and let the model read them. The fetching machine is vector search, and the whole pattern is RAG โ€” retrieval-augmented generation. Both are the meaning-map of Chapter 8, industrialized; you already own every part.

Whole passages become arrows

This chapter needs exactly one upgrade. Chapter 8 gave an arrow to every token. An embedding model โ€” a smaller sibling of the transformer you built in Chapter 11 โ€” reads a whole sentence or paragraph and outputs one vector for the entire thing. One passage, one arrow. It is trained (the same downhill story as everything else on this site) so that texts people use interchangeably land in the same direction.

Here is the property that makes it magic, told with this chapter's two star texts: "How do I get my money back?" and "Items may be returned within 30 days for a full refund." They share zero important words โ€” no "money," no "back" in the second; no "return," no "refund" in the first. A keyword search scores them as strangers. A good embedding model gives them nearly the same direction, because the two texts mean the same kind of thing.

Two text chips on the left โ€” 'How do I get my money back?' and 'Items may be returned within 30 days for a full refund.' โ€” with the annotation 'zero important words in common' beneath them. Both feed thin arrows into a single violet-bordered box labeled 'embedding model, a smaller sibling transformer'. On the right, a small pair of axes shows a mint arrow toward direction (3,4) labeled 'question' and an amber arrow toward (4,3) labeled 'refund passage', with an arc between them labeled cos theta = 0.96.
One passage, one arrow. An embedding model reads a whole text and hands back a single vector โ€” and texts that mean the same thing land in nearly the same direction, even with no words in common. A keyword search calls this pair strangers; the geometry calls them 96% aligned. (Toy 2-D vectors, hand-placed for teaching; real ones have hundreds of dimensions.)

Now the chapter's toy library, built with Chapter 8's honesty ritual: every vector below is hand-placed by me, invented for teaching โ€” real embedding vectors have hundreds of dimensions, same recipes, longer lists. The question is $\mathbf{q} = [3, 4]$ for "How do I get my money back?" โ€” written $\mathbf{q}$ on purpose (search people and attention people chose the same letter for the same reason: it is the thing that asks). The library is five passages from a small store's help pages, all length-5 arrows so every cosine will divide by 25: refund policy $\mathbf{v}_{\text{refund}} = [4, 3]$, warranty claims $[4.8, 1.4]$, holiday hours $[-3, 4]$, shipping times $[4, -3]$, careers page $[-3, -4]$. Here are the first two as columns:

$$\mathbf{q} = \begin{bmatrix} 3 \\ 4 \end{bmatrix} \qquad \mathbf{v}_{\text{refund}} = \begin{bmatrix} 4 \\ 3 \end{bmatrix}$$

In words: the question points to the spot (3, 4) on the plane; the refund passage points to (4, 3) โ€” almost the same direction, with the across- and up-parts merely swapped.

And here is a wink you have earned. The dot product $\mathbf{q} \cdot \mathbf{v}_{\text{refund}} = 3 \times 4 + 4 \times 3 = 24$, over lengths $5 \times 5$, is the exact arithmetic of $\text{cat} \cdot \text{dog}$ from Chapter 8 โ€” I chose these numbers on purpose, so you can check this whole chapter by eye. Directions carry meaning whether the arrow stands for a word or a paragraph.

A library of arrows: nearest-neighbor search

The work splits into two halves. The offline half is done once, before any question arrives: split your documents into chunks of a few hundred tokens each (Chapter 7's unit doing logistics work), run every chunk through the embedding model once, and file each (vector, original text) pair in a vector database. Your library is now a cloud of arrows, each dragging its passage behind it.

The online half happens at question time. Embed the question with the same model โ€” $\mathbf{q} = [3, 4]$ โ€” then find the stored arrows with the highest cosine similarity to it. That search has a name: nearest-neighbor search. Let's work the winner fully, using Chapter 2's cosine recipe, one display:

$$\cos\theta = \frac{\mathbf{q} \cdot \mathbf{v}_{\text{refund}}}{\|\mathbf{q}\| \, \|\mathbf{v}_{\text{refund}}\|} = \frac{3 \times 4 + 4 \times 3}{5 \times 5} = \frac{24}{25} = 0.96$$

In words: multiply matching slots and add to get 24, divide by both lengths โ€” the question and the refund passage agree 96 percent of the way.

Do the same for every shelf and the library summarizes into one ranking table. The careers page earns a special note: its arrow points exactly opposite the question, so its cosine bottoms out at $-1.00$ โ€” the perfect anti-match. Permission to enjoy that.

Worked example

Five passages, five dot products over the same $5 \times 5 = 25$, then sort:

Passage (its arrow)q ยท passagecos ฮธreading
refund policy [4, 3]3ร—4 + 4ร—3 = 240.96the winner
warranty claims [4.8, 1.4]3ร—4.8 + 4ร—1.4 = 200.80related
holiday hours [โˆ’3, 4]3ร—(โˆ’3) + 4ร—4 = 70.28a little
shipping times [4, โˆ’3]3ร—4 + 4ร—(โˆ’3) = 00.00exactly perpendicular
careers page [โˆ’3, โˆ’4]3ร—(โˆ’3) + 4ร—(โˆ’4) = โˆ’25โˆ’1.00the anti-match

The shipping row is worth a pause: $12 - 12 = 0$ means the shipping passage sits at a true right angle to the money-back question โ€” unrelated, in the precise Chapter 2 sense, neither agreeing nor opposing.

A full-plane plot with equal aspect. Five blue dots mark the library passages: refund at (4,3), warranty at (4.8,1.4), holiday hours at (โˆ’3,4), shipping times at (4,โˆ’3), careers at (โˆ’3,โˆ’4). A mint arrow runs from the origin to (3,4) for the question, labeled 'money back? q = [3,4]'. A solid mint connector to the refund dot is labeled 0.96 and a dashed one to warranty is labeled 0.80. Annotations note that shipping times sits exactly perpendicular at cos 0.00 and careers points perfectly away at cos โˆ’1.00.
Relevance as geometry. The question $\mathbf{q} = [3, 4]$ scores every passage with one cosine each: refund 96%, warranty 80%, holiday hours 28% โ€” while shipping times sits exactly perpendicular (0.00, unrelated) and careers points perfectly away (โˆ’1.00). Nearest-neighbor search is nothing more than computing these and sorting. (Toy vectors, hand-placed so you can check every number.)

Read that table as the chapter's thesis: the machine never understood the word "refund." It computed five dot products and sorted them. Meaning did the matching โ€” because meaning was already baked into where the arrows point (that was Chapter 8's whole story). Relevance has become geometry.

One honest word on scale. A real library holds a million chunks, and โ€” surprisingly โ€” a million dot products per question is fine. Chapter 2 told us this operation is exactly what modern hardware was built to do; a million of them is milliseconds. At billions of chunks, engineers switch to approximate nearest-neighbor search: pre-sort the arrows into neighborhoods and search only the promising ones, accepting a tiny chance of missing the true winner in exchange for enormous speed. The idea is no more than "shelve the library by topic first"; the rest is names.

RAG: the full loop

Now assemble the pattern end to end โ€” four steps, each one already yours. (1) Embed the question (this chapter). (2) Retrieve the top few chunks by cosine (this chapter). (3) Paste the winners into the prompt, above the question (Chapter 18's desk, used deliberately). (4) Generate โ€” the frozen model reads its context and answers from it (Chapter 9's game, unchanged).

Two horizontal lanes. The top lane, 'before any question โ€” index once', flows left to right: a stack of documents, sliced into chunks, into a violet 'embedding model' box, into a database cylinder labeled 'vector database' holding rows of vector-plus-text. The bottom lane, 'at question time', flows: a 'money back?' question chip, into a second identical violet 'embedding model (same one)' box, producing a mint arrow q = [3,4], into the database, out as two ranked chips tagged 0.96 and 0.80, into a prompt-assembly box showing context lines above a question line, into a violet 'LLM โ€” frozen' box with a padlock, out to an answer chip with a citation tag [1].
The whole loop. Once, offline: split documents into chunks, embed each, file (vector, text) pairs in a vector database. Per question: embed the question with the same model, fetch the top passages by cosine, paste them into the prompt above the question, and let the frozen model read its context and answer โ€” sources attached. No weights move at any step.

Step 3 is the one that makes the whole chapter click, so let's make it concrete. Using our toy library's top hits, the pipeline assembles a prompt that looks exactly like this:

The assembled prompt (step 3, made visible)

Context from company documents:
โ€” Items may be returned within 30 days for a full refund.
โ€” Warranty claims: defects covered for one year.
Question: How do I get my money back?
Answer using only the context above.

And here is the beat worth sitting with: nothing about the model changed. No training, no weight updates, no new machinery. The retrieved text walks in through the front door as ordinary tokens in the context, and attention (Chapter 10) does the rest.

Why does this beat the alternatives for facts? Three reasons. Your knowledge updates by re-embedding the changed page โ€” minutes and pennies, instead of the retraining Chapter 17 priced. The model can quote its sources, so answers become checkable โ€” the honest antidote to Chapter 9's plausible-but-false failure mode. And access control stays outside the model: retrieve only what this user is allowed to see.

Now the honest failure modes, no doom. Retrieval is now the weakest link: if the right chunk isn't fetched โ€” bad chunking, or a question phrased off the map โ€” the model answers from vibes again, wearing the same confident tone. And retrieval is not obedience: a model can still ignore or garble the passages on its desk. Grounding reduces hallucination; it does not abolish it. The engineering craft โ€” chunk sizes, overlap, how many chunks to fetch, blending keyword and vector search โ€” is exactly the craft of making the right passage land on the desk.

See it move

The toy library, live: eleven passages drawn as arrows on the map, a draggable question arrow, a cosine ranking that updates as you move, and a panel showing the exact prompt RAG would assemble from the winners. This widget is a vector database with eleven rows โ€” production systems swap in a million chunks and hundreds of dimensions, and change nothing else.

Why the LLM cares

"Chat with your PDF." Enterprise copilots that know the internal wiki. Support bots quoting the returns policy. Coding assistants that pull your codebase's own files. Search engines' AI answers with little citation numbers. Every one is this chapter's loop wearing a different shirt. When an answer arrives with sources attached, you are looking at RAG.

Keep this division of labor โ€” it is the takeaway rule of thumb, and it echoes Chapters 16โ€“18 exactly. Weights hold skills: language, reasoning patterns, tone โ€” that is pretraining and fine-tuning's job. The context holds the working facts of the moment โ€” that is the window's job. Retrieval is the bridge that keeps refilling the context from outside. Want the model to sound like your lab group? A LoRA adapter (Chapter 17). Want it to know this week's protocols? RAG. The two compose โ€” tune the voice, retrieve the facts.

Three panels in a row. Left, violet-bordered, 'weights': a locked lattice icon; 'skills: language, tone, reasoning' and 'changed by training (slow)'. Middle, mint-bordered, 'context window': a desk with token chips; 'the working facts of the moment' and 'changed by typing (instant)'. Right, blue-bordered, 'the library': a database drum; 'all your documents, as vectors' and 'changed by re-embedding a page (minutes)'. An arrow labeled 'retrieval refills the desk' runs from the library to the context window; a short arrow from weights points at the context labeled 'reads it'.
Three homes for knowledge, three speeds of change. Skills live in frozen weights (retrain or adapt to change โ€” slow). The moment's facts live on the context-window desk (instant, but small and temporary). Everything else lives in the library, as vectors โ€” and retrieval is the librarian who keeps the desk stocked. Tune the voice with LoRA; supply the facts with RAG.

Embeddings have a second life, too. The same embed-and-compare move powers semantic search with no generation at all, duplicate detection, clustering feedback into themes, and recommendations ("this song's vector is near that one's"). Chapter 8 promised that embeddings escaped the LLM โ€” this chapter is where you see the escape route.

And so we cash the site's oldest check one last time. Chapter 2 called the dot product the most important operation on this site. Today it ran your library. Attention asks it inside the model; retrieval asks it outside; and both are the same question โ€” how much do these two directions agree?

What you now know

  • A frozen model cannot know your private or post-training facts, and weights make a poor filing cabinet for them โ€” so RAG fetches the right passages at question time and puts them on the model's desk instead.
  • An embedding model turns a whole passage into one vector, placed so that same-meaning texts point the same way โ€” "money back?" and the refund policy share no important words yet score $\cos\theta = 24/25 = 0.96$.
  • A vector database is a library of (vector, text) pairs built once offline; answering a question is nearest-neighbor search โ€” cosine against the library, then sort: 0.96, 0.80, 0.28, 0.00, โˆ’1.00 in our toy.
  • RAG is retrieve-then-paste: the winning chunks enter the prompt as ordinary tokens in the context window, the frozen model reads them, and nothing about the model changes โ€” no training, no memory, no weight updates.
  • Grounding makes answers checkable (the model can quote sources) but retrieval is now the weakest link: fetch the wrong chunk and the model answers plausibly from nothing, same as ever.
  • The division of labor to keep: weights hold skills (tune with LoRA), the context holds the moment's facts (refilled by retrieval) โ€” and both attention inside the model and search outside it are the same dot-product question from Chapter 2.

Where we're headed. That was the last machine this site builds โ€” and look at what's on your bench now: vectors that carry meaning, dot products that measure agreement, matrices that transform, softmax that spreads belief, a loss that grades, gradients that teach, a transformer that predicts, adapters that specialize, caches that economize, and a librarian that retrieves. One short chapter remains, and it builds nothing at all. It zooms out: everything you learned here was one member โ€” the famous one โ€” of a much bigger family called machine learning. The final chapter hands you the family map, shows you which parts of your toolkit work everywhere (nearly all of it), and points you at the sister site that rebuilds the whole field from the ground up.