Text Embeddings, L2 Normalization & Cosine Similarity Top-K Retrieval
How Bi-Encoder embedding models map sentences onto the unit hypersphere, why L2 normalization turns Cosine Similarity into a blazing-fast GPU dot product, and how Matryoshka embeddings slash vector DB RAM by 6×.
Dense Text Embeddings map sentences into fixed-length semantic vectors where L2-normalized Cosine Similarity measures meaning closeness via a single dot product.
Keyword search misses synonyms ('car' vs. 'automobile'); dense vector search retrieves conceptually matching passages in milliseconds for RAG.
Every RAG pipeline, semantic search engine, and recommendation system starts by turning unstructured text into L2-normalized vectors on a unit hypersphere!
Normalizing vectors once at indexing time lets you run Top-K cosine search over millions of chunks with a single BLAS matrix multiply (Q @ D.T) or FAISS IndexFlatIP!
Knowing the difference between Asymmetric Retrieval (query: vs. passage: prefixes), Matryoshka truncation, and raw dot-product length bias prevents silent retrieval degradation.
Classic RAG coding interview: 'Implement L2-normalized Cosine Similarity Top-K retrieval in NumPy, handle zero-norm edge cases, and explain when Cosine ≠ Dot Product!'
If two vectors q and d are both L2-normalized (‖q‖₂ = 1, ‖d‖₂ = 1), what does their Cosine Similarity cos(q, d) = (q · d) / (‖q‖₂ ‖d‖₂) simplify to?
- Compute L2-normalized embeddings v̂ = v / max(‖v‖₂, ε) safely without dividing by zero
- Prove why Cosine Similarity equals Dot Product (and monotonic negative L2 distance) on unit-normalized vectors
- Contrast Bi-Encoder embeddings (fast offline indexing) with Cross-Encoders (deep online reranking)
- Explain Matryoshka Representation Learning (MRL) for truncating 1536-d vectors down to 256-d with ~98% recall
Imagine placing every paragraph in your company's wiki onto the surface of a giant semantic globe (the unit hypersphere): paragraphs about billing cluster near the north pole, Python tutorials cluster near Europe, and HR policies cluster near Asia. When a user asks a question, the Bi-Encoder drops a pin q̂ onto the globe — and Top-K retrieval simply scoops up the K closest pins via a single dot product!
1. Unit-Hypersphere Geometry: Cosine vs. Dot Product
Drag the Doc1 Norm Scale slider in the mini-lab below to see how raw Dot Product is fooled by vector magnitude, while Cosine Similarity stays 100% scale-invariant!
Exact Batched Cosine Top-K in 3 Lines of NumPy
- Normalize corpus once (offline):
D_hat = D / np.maximum(np.linalg.norm(D, axis=1, keepdims=True), 1e-12) - Normalize query & score:
scores = D_hat @ q_hat(shape(N,)) - Top-K indices:
np.argsort(scores)[::-1][:k](ornp.argpartitionfor selection on large !).
cos(q, d) = (q · d) / (max(‖q‖₂, ε) · max(‖d‖₂, ε))
Geometric length of the embedding vector.
'query: ...' on queries and 'passage: ...' on documents — omitting these prefixes can drop NDCG by 3–5 points!Cosine Similarity vs. Raw Dot Product Length Bias
2. Bi-Encoders vs. Cross-Encoders
Why can Bi-Encoders search 10 million documents in 5 milliseconds while Cross-Encoders can only score 50?
Pre-Computation Is the Secret
- Bi-Encoder: Encodes and separately → you embed all 10M documents once offline and only run 1 forward pass for at query time!
- Cross-Encoder: Feeds
[CLS] Q [SEP] Djointly into a Transformer → every word in attends to every word in , giving superior accuracy at the cost of running 1 forward pass per pair!
3. Matryoshka Embeddings (MRL) for 6× Vector DB Savings
Storing 100M 1536-dim FP32 vectors costs 614 GB of RAM. Matryoshka training lets you truncate dimensions on the fly!
How Matryoshka Truncation Works
During contrastive training (InfoNCE loss), the model computes loss not just on the full 1536-d vector, but simultaneously on prefixes [:256], [:512], and [:1024]. At serving time, simply slice v[:256] and re-normalize (v / ‖v‖₂) for 6× smaller RAM and 6× faster search at ~98% recall!
Worked Example: L2-Normalizing and Scoring 2 Documents
Query q = [3, 4], Doc1 d1 = [6, 8], Doc2 d2 = [-4, 3].
q̂ = [0.6, 0.8], d̂1 = [0.6, 0.8], d̂2 = [-0.8, 0.6].
On L2-normalized unit vectors, which similarity metric gives the EXACT same Top-K ranking as Cosine Similarity?
After slicing a Matryoshka embedding from 1536 dimensions down to 256 (v_small = v[:256]), what step MUST you perform before storing it for Dot-Product search?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
argsort sorts all items in , whereas argpartition finds the Top- in linear time — often 5–10× faster when and !
Unit-Hypersphere Query-to-Doc Cosine Retrieval Stage
Watch the normalized query vector q̂ sweep around the unit circle and highlight its Top-1 nearest document via pure dot product.
Q @ Dᵀ), while Matryoshka truncation + re-normalization cuts vector DB RAM by 6×.OpenAI text-embedding-3 & Nomic / BGE Matryoshka Models
Support configurable output dimensions (256–3072) to trade tiny recall differences for massive vector DB memory savings.
import torch
import torch.nn.functional as F
# L2-Normalized Dense Embeddings + Vectorized Top-K Cosine Similarity Retrieval
corpus = [
"PyTorch autograd computes reverse-mode gradients.",
"FAISS accelerates billion-scale vector search.",
"LoRA adapts LLM weights with low-rank matrices.",
]
torch.manual_seed(42)
doc_embs = F.normalize(torch.randn(len(corpus), 64), dim=-1) # [N, D]
query_emb = F.normalize(doc_embs[2] + 0.1 * torch.randn(64), dim=-1)
# For unit vectors, cosine similarity == single dot product
scores = doc_embs @ query_emb
top_scores, top_idx = torch.topk(scores, k=2)
for score, idx in zip(top_scores.tolist(), top_idx.tolist()):
print(f"score={score:.3f} | {corpus[idx]}")
v / max(‖v‖₂, 1e-12) as the final step before indexing!v / np.linalg.norm(v)?