Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 21/ 160
02. RAG

Embeddings

Dense vector representations that place similar meaning nearby for retrieval and clustering.

BeginnerVectors · Similarity · Models3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The computer turns each piece of text into a long list of numbers so that texts with similar meanings get similar numbers.

Think of it like…

A map where every sentence gets coordinates, and sentences about the same thing are neighbours. Searching means dropping a pin for the question and looking at what's nearby, even if the street names (the words) are completely different.

Where you’ve seen it

A help centre has 40,000 articles. Keyword search fails on "my card was swallowed by the ATM" because no article uses those words. After embedding every article (1,024 dimensions) and the query with the same model, the nearest vectors are "ATM retained my card" and "What to do if your card is captured", and the right answer appears in the top 3. Storage: 40,000 × 1,024 × 4 bytes ≈ 164 MB.

Words you’ll hear

Dense vector
A fixed-length list of floats where every dimension carries some of the meaning.
Embedding model
A neural network trained so that related inputs get nearby vectors (for example with contrastive learning).
Dimensionality
Vector length; more dimensions can capture more nuance but cost more memory and compute.
Re-embedding
Recomputing all vectors when you change the model, because vectors from different models aren't comparable.

Visual diagram

Loading interactive diagram

Theory & deep dive

How embeddings are trained and used

Embedding models are usually transformer encoders trained with contrastive learning: pull the vectors of matching pairs (a question and its answer passage, a sentence and its paraphrase) together, and push non-matching pairs apart. After training, the model maps any text to a vector without needing the exact words to match. The output is typically normalised to unit length, so similarity depends on direction (see the cosine similarity lesson).

Use cases beyond search: clustering support tickets, de-duplicating near-identical records, classifying text with a nearest-neighbour or simple linear model on top of vectors, recommending related content, and detecting outliers. Multimodal models embed images and text into the same space, so you can search images with a text query. Embeddings capture topical and semantic similarity well, but they can blur precise facts ("Pune" vs "Pune district", "not eligible" vs "eligible"), which is why hybrid search and reranking are often added.

Embedding and comparing in a few lines

vecs = embed(["reset password", "forgot my login", "quarterly revenue"]) then compare with cosine similarity: the first two score around 0.8 while either against the third is around 0.1 (values vary by model).

Key takeaway: Contrastive training makes meaning geometric; use one model for both sides.

Choosing a model and keeping vectors healthy

Compare models on your own data, not only on public leaderboards such as MTEB: build 100 to 300 realistic queries with known relevant documents and measure recall@k for each candidate. Weigh quality against cost and latency (API price per million tokens or GPU for self-hosting), maximum input length, supported languages (multilingual models matter for Indian-language content), and dimensionality. Some models support Matryoshka truncation, letting you shorten vectors (for example 1,024 to 256 dimensions) with modest quality loss to cut storage and search time by 4×.

Plan for change. Store the model name and version beside each vector and the source text hash, so you can re-embed only changed documents and migrate models in a controlled way (build the new index in parallel, evaluate, then switch). Don't mix vectors from different models in one index. Respect the model's input limit by chunking, apply any recommended query or document prefixes, and normalise text consistently (the same preprocessing at index and query time). Treat embeddings of sensitive text as sensitive data: they can leak information about the source.

Storage maths

10 million chunks × 1,536 dimensions × 4 bytes (float32) ≈ 61 GB. At 256 dimensions it's about 10 GB, and with 8-bit quantisation about 2.5 GB, which changes the hosting choice entirely.

Key takeaway: Evaluate on your data, record the model version, and plan re-embedding.

How it works, step by step

Step 1 of 4
Selection

1. Pick candidate models

Shortlist by language support, input length, price and dimensions, using public benchmarks only as a start.

multilingual · 8K tokens · 1,024 dims
Key numbers at this step
Then
test on your data

When to use it & trade-offs

What it is

An embedding is a list of numbers (a dense vector, typically 384 to 3,072 dimensions) produced by a model so that texts, images or other items with similar meaning land near each other in vector space. "How do I reset my password?" and "I forgot my login credentials" share almost no words but end up close together. This turns search, clustering, recommendations and deduplication into geometry: find the nearest vectors.

Why it matters: Embeddings power the retrieval step of RAG, semantic search, recommendations and classification-by-similarity. The choice of embedding model, its dimensionality and how you keep vectors in sync with your data sets the ceiling on retrieval quality and drives storage and latency cost. Many RAG failures are embedding problems wrongly blamed on the LLM.

When to reach for it

  • Semantic search and RAG retrieval
  • Clustering and deduplicating text
  • Recommending related content

When to avoid or be careful

  • Mixing vectors from different models
  • Choosing a model only by leaderboard rank
  • Embedding documents longer than the model's input limit without chunking

Embedding model choices

Hosted embedding API
Best for: Fast start and variable volume

Strengths: No GPU to run; strong general quality.

Watch out: Per-token cost; data leaves your environment; model changes are the provider's call.

Open-weight model you host
Best for: Privacy, high volume, domain fine-tuning

Strengths: Control and fixed cost; can fine-tune.

Watch out: You run and scale inference.

Smaller or truncated vectors
Best for: Cost-sensitive or very large collections

Strengths: 4–16× less memory and faster search.

Watch out: Some recall loss; test before adopting.

Interview signals & numbers to know

When this topic comes up

  • “Keyword search misses synonyms and paraphrases-what would you change?”
  • “How would you choose and evaluate an embedding model for our data?”
  • “Vector storage costs are growing-how would you reduce them?”
  • “What must happen before switching to a new embedding model?”

Benchmarks & rules of thumb

384–3,072 dimensions -
a common range, but always model-specific
4 bytes/dimension -
raw float32 storage per vector
10M × 1,536-D vectors -
≈61.4 GB of raw storage, before index overhead

Common mistakes & follow-ups

Common interview mistakes

  • Upgrading the embedding model for new documents only, so old and new vectors in one index don't match.
  • Skipping a domain test set and discovering after launch that the model handles product codes poorly.
  • Embedding at query time with different text normalisation than at index time.

Likely interviewer follow-ups

  • How would you choose between two embedding models?
  • What happens when you switch embedding models?
  • How could you cut vector storage by 4×?
Interview tip: Mention testing models on your own queries and recording model versions beside vectors. Those two practices separate production RAG from demos.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Embeddings with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Open vs Closed Models
Next topic
Cosine Similarity