Courses / GenAI & LLM / Module 5
Module 5: Embeddings and semantic search basics
8 h · theory 2 · hands-on 3 · project 2 · revision 1
You will be able to
- Explain what embedding similarity does and does not capture
- Embed and search a small corpus with cosine similarity
- Pick an embedding model for a language and budget
- Know when keyword search beats embeddings
Capstone increment: Similar-document lookup for extracted records (find duplicates and near-duplicates).
Job-description skills: Embeddings, Semantic search · Lab tools: sentence-transformers, numpy
1. What an embedding is
An embedding model turns text into a fixed-length vector (typically 384 to 3,072 numbers) so that texts with similar meaning land close together. “vacation policy” and “annual leave rules” share no words but end up near each other; that is the whole point.
Closeness is measured with cosine similarity: the angle between two vectors, from -1 to 1. Normalise vectors to length 1 once and cosine becomes a plain dot product, which is what vector databases compute at scale.
Embedding models are trained on pairs of related texts (questions and answers, titles and articles) so that related pairs score high. They capture topic and paraphrase well. They capture negation, numbers, exact identifiers and fine logic poorly.
Deep dive
Deep dive: cosine similarity and how embedding models are trained
Cosine similarity measures the angle between two vectors: cos θ = (a·b) / (|a| |b|). It is 1 for the same direction, about 0 for unrelated and −1 for opposite. Most embedding models return normalised vectors (length 1), and then cosine is just the dot product. That is why a vector database gives the same ranking whether you choose “dot” or “cosine” for normalised vectors.
Embedding models are trained with a contrastive loss on pairs of (question, passage that answers it). For each question in a batch, the model scores its own passage and every other passage in the batch (the in-batch negatives), and the loss, called InfoNCE, is the cross-entropy of picking the right one. A temperature τ divides the similarities before the softmax; a small τ makes small differences matter.
- Encode a batch of B questions and their B passages into vectors.
- Compute the B × B grid of similarities. The diagonal holds the right pairs.
- Divide by τ and apply a softmax along each row.
- Loss = −log(weight on the diagonal). Gradient descent pulls the right pairs together and pushes the others apart.
- Add hard negatives: passages that look right but aren’t (same topic, different product). Without them the model learns topics, not distinctions.
Worked example: cosine for three normalised 3-d vectors
a = [0.6, 0.8, 0.0] |a| = 1 b = [0.8, 0.6, 0.0] |b| = 1 c = [0.0, 0.6, 0.8] |c| = 1 cos(a, b) = 0.6·0.8 + 0.8·0.6 + 0 = 0.96 nearly the same meaning cos(a, c) = 0 + 0.8·0.6 + 0 = 0.48 cos(b, c) = 0 + 0.6·0.6 + 0 = 0.36
Loss on training batches 0.001 · loss over all passages 0.549 · questions answered with the right passage 3 / 5
| Question | Top passage | Margin over its look-alike |
|---|---|---|
| refund for my laptop | Laptops can be refunded within 14 days ✓ | 0.05 vs “Clothing refunds: 30 d…” |
| refund for a shirt | Laptops can be refunded within 14 days ✗ | -0.03 vs “Laptops can be refunde…” |
| laptop delivery is late | Clothing orders delayed: what to do ✗ | -0.00 vs “Clothing orders delaye…” |
| shirt hasn’t arrived yet | Clothing orders delayed: what to do ✓ | 0.01 vs “Late laptop deliveries…” |
| reset my password | Reset your account password ✓ | no look-alike |
Similarity grid (rows are questions, columns are passages; darker is more similar):
Guided experiments
- Random negatives, 100 steps. The training loss is almost zero, so training “worked”. How many questions get the right passage, and what are the margins? Why can a model ace its training batches and still confuse laptops with shirts?
- Switch to random + hard negatives and replay from 0 to 100 steps. Which column of the grid separates? This is why embedding fine-tuning recipes mine hard negatives (look-alike passages that are wrong).
- With hard negatives, try τ = 1. The loss stays high: the softmax is too soft to push the look-alikes apart. Compare τ = 0.05 and 0.1. Most models train with τ around 0.01–0.1.
- Your own domain will have look-alikes too (two product variants, two policy versions). How would you find hard negatives for them automatically? (Hint: retrieve with the current model and keep the high-ranked wrong passages.)
2. Keyword search versus embeddings
Keyword search (BM25) scores documents by shared words, weighting rare words more. It is unbeatable for exact tokens: form numbers like HR-17, product codes, names and error messages. It fails on synonyms and paraphrases.
Embeddings handle synonyms and paraphrase but blur exact tokens and can return confident nonsense when nothing relevant exists. Production systems combine both (hybrid search). Move the blend slider below and watch which questions each method gets right.
| Rank (faded = not retrieved) | Relevant? | Document | BM25 → dense → blended score |
|---|---|---|---|
| 1 | Travel reimbursement Claim travel expenses with form HR-17 within 30 days. Attach receipts for flights, trains and hotels. | BM25 1.00 · dense 0.00 · 0.50 | |
| 2 | Salary and payslips Salary is credited on the last working day. Download payslips and Form 16 from the payroll portal. | BM25 0.44 · dense 0.00 · 0.22 | |
| 3 | Annual leave policy Employees get 24 days of annual leave. Apply for leave in the HR portal at least two weeks ahead. | BM25 0.00 · dense 0.00 · 0.00 | |
| 4 | Holiday calendar Public holidays for 2027 by office location. Optional holidays need manager approval. | BM25 0.00 · dense 0.00 · 0.00 | |
| 5 | Laptop and equipment Each employee receives a laptop. Report a lost or stolen device to IT security within 24 hours. | BM25 0.00 · dense 0.00 · 0.00 | |
| 6 | Password and MFA rules Use a password manager and turn on MFA. Never share one-time codes, even with IT. | BM25 0.00 · dense 0.00 · 0.00 | |
| 7 | Work from home Hybrid staff may work remotely up to three days a week. Home internet is reimbursed up to Rs 1,000 a month. | BM25 0.00 · dense 0.00 · 0.00 | |
| 8 | Parental leave Birth parents get 26 weeks of paid leave; other parents get 4 weeks. Tell HR 8 weeks before the leave starts. | BM25 0.00 · dense 0.00 · 0.00 |
Guided experiments
- “where is form HR-17”: slide to dense only. The travel document drops out and recall falls to 0. Why does BM25 find it instantly?
- “vacation days per year”: slide to BM25 only. It can only match the word “days”, so the holiday calendar is missed. Which word in the question does no document contain?
- “time off when we have a baby”: BM25 only retrieves nothing at all. Slide to dense only: both leave policies come back. What did the dense side “know” that BM25 didn’t?
- “my computer was stolen” at the middle setting: try k = 1, then k = 2. Recall@k and nDCG change while MRR stays at 1. What does each metric reward?
- Find one blend where every question gets recall@3 = 1. That’s why production systems use hybrid search.
- Type your own question and tick the relevant documents yourself. That is how a golden set is built.
3. Choosing an embedding model
Start from the MTEB leaderboard, filtered to retrieval tasks and your languages, then test the top few on your own data: leaderboard scores rarely transfer exactly. For Indian-language content, check that the model was trained on those languages; many English-first models degrade sharply on Hindi or Tamil.
Trade-offs to weigh: vector size (storage and speed), maximum input length (longer chunks get truncated silently), cost per million tokens for hosted models, and whether data may leave your network. Small open models from sentence-transformers run well on a CPU for tens of thousands of documents.
Embeddings from different models are not compatible. Changing the model means re-embedding the whole corpus, so record the model name and version next to every vector.
4. Search at scale and other uses
Up to a few hundred thousand vectors, exact search with NumPy or FAISS is fast enough. Beyond that, approximate nearest-neighbour indexes (HNSW is the common choice) trade a little recall for large speed-ups. Vector databases like Qdrant add filtering, persistence and replication.
Embeddings are useful beyond RAG: duplicate and near-duplicate detection, clustering support tickets by topic, routing requests to the right prompt, and finding few-shot examples similar to the current input. The capstone uses them to flag duplicate vendors and invoices.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 5.1: Compare two embedding models
Embed 200 FAQ entries with two sentence-transformers models (one small English model, one multilingual). For 30 test questions in English and Hindi, record recall@5 for each model.
Expected: A table of recall@5 by model and language, plus vectors per second on your machine.
Lab 5.2: Duplicate detection (capstone increment)
Add a duplicates check to the capstone: when a new invoice is extracted, embed vendor name plus invoice number and flag records above a similarity threshold, confirmed by an exact GSTIN or amount match.
Expected: GET /duplicates lists suspected pairs with scores; a test shows an OCR-garbled duplicate being caught and a different vendor with a similar name not being merged.
Lab 5.3: Find the failure cases
Write 10 query pairs where embeddings should fail: negation, numbers, exact codes, very short queries. Measure similarity for each and note which BM25 handles better.
Expected: A list of failure patterns you can cite when someone proposes “just use embeddings”.
Go deeper
Videos
- Transformers, the tech behind LLMs | Deep Learning Chapter 5 · 3Blue1Brown · ~27 min. The word-embedding section gives the best visual intuition for directions in embedding space.
- Sentence Embeddings Explained | Hugging Face Transformers (Hands-On) · Tech With Mala · ~11 min. A short code walkthrough of producing sentence embeddings and comparing them.
- SimCSE: Simple Contrastive Learning of Sentence Embeddings - EMNLP 2021 · Princeton NLP · ~12 min. The authors explain contrastive training with in-batch and hard negatives in 12 minutes.
Further reading
- Article The Illustrated Word2vec · Jay Alammar. Builds the intuition for embeddings as directions in space, starting from word vectors.
- Paper Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks · Reimers and Gurevych, 2019. Why plain BERT is a poor sentence embedder and how siamese training fixed it; the root of modern embedding models.
- Paper SimCSE: Simple Contrastive Learning of Sentence Embeddings · Gao, Yao and Chen, 2021. Contrastive training with in-batch negatives, explained cleanly, with the effect of hard negatives measured.
- Paper MTEB: Massive Text Embedding Benchmark · Muennighoff et al., 2022. What the leaderboard actually measures, task by task, so you can read it critically.
- Docs Sentence Transformers documentation · SBERT. The library most teams use to run, evaluate and fine-tune embedding models and cross-encoders.
GitHub repositories
- huggingface/sentence-transformers: examples/sentence_transformer/applications: semantic search, clustering and paraphrase mining scripts.
- embeddings-benchmark/mteb: How retrieval tasks are scored, so you can read the leaderboard critically and run it on your own data.
- facebookresearch/faiss: The wiki’s ‘Getting started’ and index selection guide: flat versus HNSW versus IVF.
Checkpoint quiz
Interview questions
- Explain to a product manager why semantic search sometimes returns confident but irrelevant results.
- How would you choose an embedding model for a Hindi and English support knowledge base?
- When would you choose keyword search over embeddings, and when both?
- What happens to an existing index when you change embedding models, and how do you roll that out?
- Design near-duplicate detection for a million invoices.
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).