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 22/ 160
02. RAG

Cosine Similarity

Angle-based similarity for normalized embeddings and why it dominates ANN search ranking.

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

In plain words

It checks whether two lists of numbers point the same way, which tells you whether the texts mean something similar.

Think of it like…

Two people pointing at things from the same spot: cosine similarity cares whether they point in the same direction, not how far their arms stretch. Two people pointing the same way score near 1, at right angles near 0, opposite ways near −1.

Where you’ve seen it

A search service ranks 5 million chunks by embedding <=> query (cosine distance) in pgvector. Because the team normalises all vectors at write time, they switch to inner product with <#>, which is slightly faster, and get identical rankings. A fixed threshold of "cosine ≥ 0.75 counts as relevant" worked on the old model but dropped half the relevant results on the new one, whose similarity scores run lower, so they tune thresholds per model with labelled data.

Words you’ll hear

Dot product
Sum of element-wise products; equals cosine similarity for unit-length vectors.
Normalisation
Scaling a vector to length 1 (divide by its L2 norm).
Cosine distance
1 − cosine similarity; the form many databases use, where smaller is closer.
Euclidean (L2) distance
Straight-line distance; for unit vectors it's a monotonic function of cosine.

Visual diagram

Loading interactive diagram

Theory & deep dive

The maths and why normalising helps

The dot product a · b = Σ aᵢbᵢ grows with both direction agreement and vector length. Dividing by the lengths removes the length effect, leaving cos(θ). If you L2-normalise every vector once (a / ‖a‖), cosine similarity is just a · b, a single multiply-and-add per dimension that hardware handles very fast, and for unit vectors ‖a − b‖² = 2 − 2·cos(θ), so ranking by smallest L2 distance, largest cosine or largest dot product gives exactly the same order.

That equivalence is why most embedding APIs return normalised vectors and why vector indexes let you choose between metrics: pick the one the model was trained with (check the model card), and normalise consistently. With unnormalised vectors the metrics disagree: dot product favours long vectors, L2 penalises differences in length, cosine ignores length.

A tiny worked example

a = (3, 4) and b = (6, 8): a·b = 18 + 32 = 50; ‖a‖ = 5, ‖b‖ = 10; cosine = 50 / 50 = 1.0, since they point the same way though b is twice as long. With c = (4, −3): a·c = 12 − 12 = 0, so cosine = 0 (perpendicular).

Key takeaway: Normalise once, then dot product = cosine = a monotonic function of L2.

Using scores correctly

Cosine scores are not probabilities and their scale differs across models: one model's unrelated texts may score 0.1 and another's 0.4, and typical text embeddings rarely go below 0, so "0.8 means relevant" is model-specific. For ranking, only the order matters; for thresholds ("don't answer if best score is below x") calibrate on labelled relevant and irrelevant pairs from your data and re-check after any model change. Scores also depend on text length and style: very short queries can have noisy similarity.

In SQL and vector databases, read the operator carefully. pgvector's <=> returns cosine distance (0 = identical), <-> is L2 distance and <#> is the negative inner product (negated so that ascending order works). Convert back with 1 - (a <=> b) to show cosine similarity. Use the index operator class that matches your query metric (vector_cosine_ops, vector_l2_ops, vector_ip_ops); a mismatch silently disables the index and forces a full scan.

pgvector query with matching operator class

CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops); then SELECT id, 1 - (embedding <=> $1) AS similarity FROM chunks ORDER BY embedding <=> $1 LIMIT 5; The ORDER BY expression must use the same operator as the index.

Key takeaway: Match the metric and operator class; calibrate thresholds per model.

How it works, step by step

Step 1 of 4
Model card

1. Check the model's metric

Find whether the model was trained for cosine, dot product or L2 and whether outputs are already normalised.

normalised: yes · metric: cosine
Key numbers at this step
Default
cosine

When to use it & trade-offs

What it is

Cosine similarity measures the angle between two vectors: cos(θ) = (a · b) / (‖a‖ ‖b‖), from −1 (opposite) through 0 (unrelated) to +1 (same direction). It ignores vector length and cares only about direction, which suits embeddings, where direction carries meaning. If vectors are normalised to length 1, cosine similarity equals the plain dot product, so vector databases store normalised vectors and rank by the cheaper dot product. Cosine distance is 1 − cosine similarity.

Why it matters: Every similarity search in RAG ranks candidates by a score like this, and mistakes are common: comparing normalised and unnormalised vectors, using Euclidean distance where the model was trained for cosine, setting a fixed similarity threshold that works on one model and fails on another, or confusing distance (smaller is better) with similarity (larger is better).

When to reach for it

  • Ranking retrieved chunks
  • Deduplicating near-identical documents
  • Setting an "I don't know" threshold in RAG

When to avoid or be careful

  • Hard-coding thresholds copied from another model
  • Using L2 and cosine interchangeably on unnormalised vectors
  • Indexing with one operator class and querying with another

Similarity and distance measures

Cosine similarity
Best for: Most text embeddings

Strengths: Length-invariant; intuitive −1 to 1 range.

Watch out: Slightly more work than a dot product on unnormalised data.

Dot product (inner product)
Best for: Normalised vectors; recommendation models trained for it

Strengths: Fastest; equals cosine on unit vectors.

Watch out: Length-sensitive on unnormalised vectors.

Euclidean (L2) distance
Best for: Models trained with L2; image features

Strengths: Geometric; common in older indexes.

Watch out: Different scale; smaller is better.

Interview signals & numbers to know

When this topic comes up

  • “What's the difference between cosine and dot product?”
  • “Why is my vector index not used?”
  • “Set a relevance cut-off”
  • Normalised embeddings
  • pgvector operators

Benchmarks & rules of thumb

−1 … +1 -
cosine similarity range
2 − 2·cos -
squared L2 distance between unit vectors
1 − cos -
cosine distance

Common mistakes & follow-ups

Common interview mistakes

  • Treating <=> as similarity and sorting descending, returning the least similar rows.
  • Using a 0.8 cut-off tuned on one model after switching to another with a lower score scale.
  • Mixing normalised and unnormalised vectors in one index.

Likely interviewer follow-ups

  • Why do vector databases often store normalised vectors?
  • How do cosine, dot product and L2 relate for unit vectors?
  • How would you pick a similarity threshold?
Interview tip: Work the (3, 4) and (6, 8) example on a whiteboard: same direction, different lengths, cosine 1. It shows you understand what cosine ignores.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

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

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Embeddings
Next topic
Chunking Strategies