AI from scratch · Embeddings and retrieval · Stage 6: LLM engineering
Embeddings and retrieval
A language model knows what was in its training data and nothing else: not your company's documents, not today's outages, not this course. The standard fix is to look the facts up and put them in the prompt, retrieval-augmented generation (RAG). Its heart is search by meaning: turn every passage and every question into a vector, and fetch the passages nearest the question. This lesson builds that search over this course's own 47 lessons, measures it honestly with a set of test questions, and assembles the grounded prompt.
1. A sentence as a vector
The word vectors lesson gave every word one point. A sentence embedding model gives a whole passage one point: a small transformer (chapter 7) reads the text, and the average of its output vectors is the embedding. It's trained on millions of pairs that mean the same thing (a question and its answer, a title and its article) to put each pair close together and unrelated text far apart. The model used here, all-MiniLM-L6-v2, has 6 layers and 22 million weights and outputs 384 numbers; similarity is chapter 7's cosine.
"How sure can I be about a measured average?" shares almost no words with the section titled "A confidence interval, and what 95% means". Can embedding search still match them?
- No: they share almost no words
- Yes: the model was trained so that texts about the same thing land close together, whatever words they use
- Only if the title is in the question
A sentence embedding model turns a whole passage into one vector, trained so that passages meaning the same thing land close together.
Why contrastive training makes meaning into distance
- Take a batch of \(B\) matching pairs (question \(q_i\), passage \(p_i\)), embed them all, and compute every cosine \(s_{ij} = q_i \cdot p_j\): a \(B \times B\) table.
- For question \(i\), treat the row \(s_{i1}, \dots, s_{iB}\) as scores for a \(B\)-way classification whose right answer is \(j = i\): softmax and cross-entropy, exactly chapter 5's loss. (Scores are divided by a small temperature first, chapter 10.)
- The gradient (chapter 5's \(p - y\)) pulls \(q_i\) toward \(p_i\) and pushes it away from the other passages in the batch, in proportion to how much it confused them.
- Every other pair in the batch is a free negative example, so bigger batches teach finer distinctions; this loss is often called InfoNCE.
- After millions of batches, "close" in the vector space means "would have been a matching pair": closeness has become relatedness of meaning, which is all the search needs.
2. Search this course
Every section of every lesson was cut into overlapping pieces of about 100 words, each embedded once (offline) and stored with the page: 640 pieces from 254 sections, 0.9 MB. Your question is embedded right here in the browser by the same model (23 MB, once), and compared with all 640 in a few milliseconds. The left column is keyword search (TF-IDF, which weighs words that are rare in the collection more), the middle is embedding search, the right adds the two.
Try: why is the GPU waiting on memory, numbers too big for half precision, leaky ReLU, Court Sq. Notice where each column shines: paraphrases favor embeddings; exact rare words like a station name favor keywords.
Embed every passage once, embed each question when it comes, and return the passages with the highest cosine: search by meaning in a few lines.
3. Measure it, don't eyeball it
A search that looks good on three questions you made up proves little (the experiments lesson). So the course comes with 35 test questions, each written in different words than the lessons use and paired with the section that answers it. Recall@k is the share of questions whose right section appears in the top \(k\) results.
| Method | recall@1 | recall@3 | recall@5 |
|---|
Measured offline with the full-precision model: embeddings 54% / 74% / 80%, keywords 54% / 77% / 77%, the hybrid 57% / 83% / 86%. Two lessons hide in that table. Embeddings alone don't beat keywords on this collection: a course is full of exact terms (Adam, IoU, LSTM) that keywords match perfectly. And adding the two up beats both, because they fail on different questions, which is why production search is usually hybrid. The pieces' size mattered too: whole sections of up to 1,600 characters, cut off at the model's 256-token window, got only 74% at k = 5; 600-character pieces got 80%.
Your RAG app passes the top 5 sections to the model. Which number matters most?
- recall@1
- The share of all 254 sections that are relevant
- recall@5: if the answer isn't among the five passages, the model can't use it
Judge retrieval with test questions and recall@k at the k you'll use; on this course keywords and embeddings tie, and adding them together wins.
4. Retrieval-augmented generation
The last step puts the top passages in the prompt, numbered, with instructions to answer only from them and to cite them. This is the prompt your search above would send:
- Grounded: facts come from the passages, which you control and can update without retraining anything.
- Citable: each claim points to a passage, so a user or a checker can verify it.
- Allowed to fail: "If the passages don't contain the answer, say so" turns some hallucinations into honest "I don't know"s.
At scale the 640-row comparison becomes millions: a vector index (FAISS, HNSW graphs in Postgres's pgvector or a vector database) finds the nearest vectors approximately, in milliseconds, by skipping most of them. Before the top results reach the model, a slower, more accurate reranker (a model that reads question and passage together) often reorders them.
RAG puts the retrieved passages in the prompt with instructions to answer only from them and cite them, so answers are grounded, checkable and updatable.
Where it breaks: retrieval's blind spots
- Exact identifiers. An elevator id like EL445X or a part number means little to an embedding model; keywords find it instantly. Hybrid search, or routing such queries to plain lookup, fixes it.
- Negation and numbers. "Stations that are not accessible" and "stations that are accessible" embed almost identically; so do "under 4 hours" and "over 4 hours". Filters on structured fields belong in code, not in vectors.
- Answers split across pieces. If a fact spans a chunk boundary, neither half matches well. Overlapping pieces (as here) and keeping titles with every piece reduce it.
- Stale or hostile passages. The model trusts what retrieval hands it: an outdated page gives an outdated answer, and a passage with hidden instructions is a prompt injection (chapter 8). Re-index when content changes, and treat retrieved text as data.
5. What to carry forward
- Sentence embeddings put whole passages in a vector space where cosine ≈ relatedness, learned contrastively.
- Index once (embed every piece), search per query (embed, compare, top k).
- Chunk into pieces the model can read whole, with titles and overlap.
- Measure with test questions and recall@k; combine keywords and embeddings.
- RAG: retrieved passages, numbered, "answer only from these, cite them, say if they don't say".
All lessons: AI from scratch. Embeddings: all-MiniLM-L6-v2 (Apache 2.0), in the browser via transformers.js. The index and the 35 questions: ai/data/course-chunks.json and retrieval-questions.json, built by ai/data/build_chunks.py.
Last updated