Skip to content

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.

Common misconception: “High similarity means the document answers the question.” It means the texts are about similar things. “Leave is not allowed during probation” and “leave is allowed during probation” are near-identical vectors.

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.

  1. Encode a batch of B questions and their B passages into vectors.
  2. Compute the B × B grid of similarities. The diagonal holds the right pairs.
  3. Divide by τ and apply a softmax along each row.
  4. Loss = −log(weight on the diagonal). Gradient descent pulls the right pairs together and pushes the others apart.
  5. 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
How an embedding model learnsFive support questions and their passages. Training pulls each question towards its own passage and pushes it away from the other passages in the same batch.
Negatives in each batch:

Loss on training batches 0.001 · loss over all passages 0.549 · questions answered with the right passage 3 / 5

QuestionTop passageMargin over its look-alike
refund for my laptopLaptops can be refunded within 14 days ✓0.05 vs “Clothing refunds: 30 d…”
refund for a shirtLaptops can be refunded within 14 days ✗-0.03 vs “Laptops can be refunde…”
laptop delivery is lateClothing orders delayed: what to do ✗-0.00 vs “Clothing orders delaye…”
shirt hasn’t arrived yetClothing orders delayed: what to do ✓0.01 vs “Late laptop deliveries…”
reset my passwordReset your account password ✓no look-alike

Similarity grid (rows are questions, columns are passages; darker is more similar):

Guided experiments
  1. 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?
  2. 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).
  3. 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.
  4. 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.)
Common misconception: A similarity of 0.8 does not mean “80% relevant”. Scores depend on the model: one model’s 0.8 is another’s 0.5. Choose thresholds per model, from labelled examples.

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.

Keyword vs meaning: retrieval playgroundPick a question or type your own, mark which documents are relevant, then slide between BM25 and dense retrieval.
recall@3 1.00MRR 1.00nDCG@3 1.001 relevant document marked
Rank (faded = not retrieved)Relevant?DocumentBM25 → dense → blended score
1Travel 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
2Salary 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
3Annual 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
4Holiday calendar
Public holidays for 2027 by office location. Optional holidays need manager approval.
BM25 0.00 · dense 0.00 · 0.00
5Laptop 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
6Password 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
7Work 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
8Parental 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
  1. “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?
  2. “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?
  3. “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?
  4. “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?
  5. Find one blend where every question gets recall@3 = 1. That’s why production systems use hybrid search.
  6. 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.

In production: Many embedding models expect a prefix such as “query: ” or “passage: ”. Leaving it out silently costs several points of recall. Read the model card.

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 code

Labs

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

Further reading

GitHub repositories

Checkpoint quiz

1. Two sentences differ only by “not”. Their embeddings will usually be…
2. A user searches for the exact error code E-4417. Which retrieval method is most reliable?
3. After normalising vectors to unit length, cosine similarity equals…
4. You switch to a better embedding model. What must you do?
5. When is exact (brute-force) vector search a sensible choice?
6. A fine-tuned embedding model has near-zero training loss but still confuses “refund for a laptop” with “refund for a shirt”. What is the most likely cause?

Interview questions

  1. Explain to a product manager why semantic search sometimes returns confident but irrelevant results.
  2. How would you choose an embedding model for a Hindi and English support knowledge base?
  3. When would you choose keyword search over embeddings, and when both?
  4. What happens to an existing index when you change embedding models, and how do you roll that out?
  5. 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).