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?

It's the search box's default question below: embeddings put the confidence-interval section first, while keyword search latches onto "average" and returns entropy's "average surprise". The flip side: exact codes and rare names, which keyword search finds trivially, can get lost (section 3).

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
  1. 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.
  2. 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.)
  3. 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.
  4. Every other pair in the batch is a free negative example, so bigger batches teach finer distinctions; this loss is often called InfoNCE.
  5. 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.

Methodrecall@1recall@3recall@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?

Measure retrieval at the k you actually use. At 86%, about 1 question in 7 reaches the model without its answer, and then the model either says it doesn't know (good) or makes something up (the evaluating LLMs lesson catches that).

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:

Search first.

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

5. What to carry forward

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