FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Embeddings

How learned vectors encode useful similarity and support representation and retrieval.

Freshness: current•13 min read•Foundation Models and Multimodal AI

Key Learning Outcomes

  • ✓Interpret embedding geometry
  • ✓Select similarity measures
  • ✓Recognize representation limits
Full Technical Reference Document

Mental model

An embedding maps variable-length text into a fixed-dimensional vector space trained so semantically related queries and passages cluster along nearby directions. Bi-encoder transformers pool token hidden states into a single representation via contrastive objectives, allowing offline passage indexing and sub-millisecond inner-product scoring—provided normalization, prompt prefixes, and model versions stay aligned.

Token sequence
Transformer encoder
Mean or CLS pooling
L2 unit normalization
Cosine or MRL prefix slice
Conceptual teaching model synthesized from:Attention Is All You NeedSentence-BERT Sentence Embeddings using Siamese BERT-NetworksHow Transformers Solve Tasks

Theory

Raw transformer layers output a contextualized tensor H∈RT×dH \in \mathbb{R}^{T \times d} across TT subword tokens, not a single document vector. Vanilla BERT token spaces also exhibit severe anisotropy: un-tuned embeddings collapse into a narrow geometric cone where random unrelated sentences show artificially inflated cosine similarities (≥0.65\ge 0.65), compressing ranking resolution. Sentence-BERT (SBERT) and modern dense retrievers eliminate this distortion by training bi-encoder pooling heads—either attention-masked mean pooling over non-padding tokens or final [CLS]/[EOS] projections—under Siamese contrastive objectives.

Given a query embedding qq, a positive passage d+d^+, and N−1N-1 in-batch plus mined hard negatives {dj−}\{d_j^-\}, contrastive training minimizes the temperature-scaled InfoNCE loss:

LInfoNCE=−log⁡exp⁡(sim(q,d+)/τ)exp⁡(sim(q,d+)/τ)+∑j=1N−1exp⁡(sim(q,dj−)/τ)\mathcal{L}_{\text{InfoNCE}} = -\log \frac{\exp(\text{sim}(q, d^+) / \tau)}{\exp(\text{sim}(q, d^+) / \tau) + \sum_{j=1}^{N-1} \exp(\text{sim}(q, d_j^-) / \tau)}

Temperature τ\tau (typically 0.02–0.07) sharpens gradient penalties on hard negatives—documents sharing vocabulary with the query while answering a different question. Once vectors are projected onto the unit hypersphere (u^=u/∥u∥2\hat{u} = u / \|u\|_2), cosine similarity reduces directly to an inner product:

cos⁡(θ)=u⋅v∥u∥2∥v∥2=u^⋅v^\cos(\theta) = \frac{u \cdot v}{\|u\|_2 \|v\|_2} = \hat{u} \cdot \hat{v}

Maintaining strict L2 normalization unlocks hardware-accelerated inner-product (IP) kernels in FAISS and pgvector without computing vector norms at query time, while guaranteeing unit-bounded scores in [−1,1][-1, 1].

Embedding Norm Drift & Normalization Layer (RMSNorm vs LayerNorm)

Representation Drift & Anisotropy FactorDrift = 0.50 (Cosine Bias: 0.525)
0.0 (Zero Drift, Isotropic)1.0 (Moderate Mean Shift)2.0 (Severe Anisotropy Collapse)
Pre-Norm Raw Vector xμ = 1.225 · σ² = 3.859
Dim 0RMS(x) = 2.315Dim 15
Post-Norm Normalized Vector x / RMS(x)μ = 0.529 · σ² = 0.72
Dim 0Post-RMS = 1Dim 15
Pre-Norm Mean μ1.225
Post-Norm Mean0.529 (Shifted)
RMS Scale Factor2.315
Kernel Speedup+12% Faster

Asymmetric Query/Passage Prefixes and Matryoshka Slicing

Information retrieval is inherently asymmetric: user queries average 5–12 tokens ("pgvector iterative scan latency"), whereas indexed passages run 150–400 tokens of dense technical prose. Symmetric embedding models place questions closer to other questions than to their factual answers. Training with asymmetric task prefixes (prepending "search_query: " to queries and "search_document: " to corpus chunks) steers the encoder into distinct query-to-answer projections inside the same shared vector space. Omitting or swapping prefixes silently degrades top-5 recall by 5–15%.

Because storage and ANN traversal cost scale linearly with dimension dd, Matryoshka Representation Learning (MRL) trains nested prefix dimensions (d∈{64,128,256,512,1536}d \in \{64, 128, 256, 512, 1536\}) simultaneously by applying InfoNCE losses to truncated slices v[:k]v_{[:k]} before re-normalizing. Engineers can truncate an MRL vector to its leading dimensions, re-normalize (v[:k] / norm(v[:k])), and trade minimal recall for steep RAM reductions.

Quantitative Dimension & Storage Sizing

Suppose an engineering knowledge base indexes N=5,000,000N = 5{,}000{,}000 passages using a 1536-dimensional Matryoshka embedder:

  • Full 1536d FP32: Sfp32=5×106×1,536×4 bytes=30.72 GBS_{\text{fp32}} = 5 \times 10^6 \times 1{,}536 \times 4\text{ bytes} = 30.72\text{ GB} raw vectors, achieving baseline 94.2% Recall@10.
  • MRL 512d Slice FP32: Truncating to leading 512 dims and L2 re-normalizing reduces footprint by 66.7% to 10.24 GB while retaining 92.8% Recall@10.
  • MRL 256d Slice + Int8 Quantization: Truncating to 256 dims at 1 byte per dimension shrinks RAM 24x down to 1.28 GB (~89.5% Recall@10). Fetching the top-50 candidates from the fast 1.28 GB index and rescoring against full 1536d vectors on NVMe restores 94.0% Recall@10 at < 10ms rescore cost.

Trade-offs

Selecting an embedding design balances representational nuance, sequence truncation limits, asymmetric prefix discipline, and serving cost.

Representation StrategyExact Symbol FidelityStorage per 1M DocsLatency ProfileIdeal Production Role
Full Bi-Encoder (1536d FP32)Weak on rare IDs6.14 GB3–10ms ANNHigh-precision rescoring & semantic clustering
MRL Sliced (256d–512d)Weak on rare IDs1.02–2.05 GB1–4ms ANNMemory-bound first-stage ANN retrieval
Late-Interaction Multi-VectorStrong (token-level)25–60 GB (compressed)15–45ms MaxSimFine-grained passage reranking
Learned Sparse (SPLADE / BM25)Exact lexical match0.3–1.2 GB inverted2–8msSKU, error code, and entity identifier matching

Token limits inside bi-encoders (512 to 8,192 tokens) also create a truncation cliff: pooling across an entire 4,000-token PDF dilutes local entity signals into an unfocused average vector. Chunking into coherent 200–400 token passages with contextual headers consistently beats embedding giant monolithic documents.

Failure modes and misconceptions

Treating cosine similarity as factual truth or calibrated probability. Two mutually contradictory statements—"Restart requires root privileges" and "Restart never requires root privileges"—share nearly identical context tokens and frequently score 0.91+ cosine similarity. Embeddings measure distributional relatedness, not logical entailment.

Mixing embeddings across model versions or un-normalized MRL slices. Even minor tokenizer or checkpoint updates rotate coordinate axes arbitrarily; querying an index populated by v2 embeddings with v3 query vectors produces near-random results, and truncating MRL vectors without re-normalizing distorts inner-product rankings.

Omitting anisotropy diagnostics on domain-adapted models. Fine-tuning an encoder exclusively on narrow internal logs without sufficient random negatives can collapse representations into a narrow cone (average random pairwise cosine > 0.60), making similarity thresholds meaningless.

Ignoring prefix asymmetry or silently truncating tail clauses. Dropping required "query:" / "passage:" prompts or allowing long inputs to clip silently past max_seq_len hides systematic recall drops in tail sections like disclaimers and appendices.

Decision scenario

A developer documentation search portal indexes 2.5 million technical chunks and reports good semantic matching on conceptual questions ("how to handle retries"), but poor ranking on short keyword lookups and escalating vector database RAM bills (28 GB for 1536d FP32 vectors). Migrate to an MRL-capable embedder configured with explicit "search_query: " and "search_document: " prefixes, index 384-dimensional L2-normalized MRL vectors in RAM (3.84 GB, saving 86% memory), pair with BM25 for exact API symbol recall, and run an automated weekly anisotropy and version-lock check against a 300-query golden benchmark before promoting new index builds.

Learning outcomes

  • Explain how Siamese contrastive InfoNCE training and attention-masked pooling eliminate transformer cone anisotropy.
  • Apply L2 normalization, asymmetric query/passage prefixes, and Matryoshka dimension slicing with explicit re-normalization.
  • Diagnose embedding drift, anisotropy collapse, and model version mismatches before they corrupt downstream retrieval.

Implementation example

This Python embedder utility applies asymmetric role prefixes, slices vectors to a Matryoshka prefix length, enforces L2 normalization, and audits batch anisotropy before indexing.

python
import numpy as np
​
def encode_normalized_mrl(
texts: list[str],
model_encode_fn,
role: str,
target_dim: int = 384,
) -> np.ndarray:
if role not in {"query", "passage"}:
raise ValueError("role must be 'query' or 'passage'")
prefix = "search_query: " if role == "query" else "search_document: "
prefixed = [f"{prefix}{t.strip()}" for t in texts]
raw = np.asarray(model_encode_fn(prefixed), dtype=np.float32)
if raw.shape[1] < target_dim:
raise ValueError(f"Model dim {raw.shape[1]} < target MRL dim {target_dim}")
sliced = raw[:, :target_dim]
norms = np.linalg.norm(sliced, axis=1, keepdims=True)
return sliced / np.clip(norms, a_min=1e-12, a_max=None)
​
def mean_pairwise_anisotropy(unit_vectors: np.ndarray, sample_size: int = 256) -> float:
sample = unit_vectors[:sample_size]
sim_matrix = sample @ sample.T
mask = ~np.eye(len(sample), dtype=bool)
mean_cos = float(sim_matrix[mask].mean())
if mean_cos > 0.55:
raise RuntimeWarning(f"High embedding anisotropy detected: mean_cos={mean_cos:.3f}")
return mean_cos
Reflect before revealing the guide

Why must a Matryoshka embedding slice be L2 re-normalized after truncation before executing inner-product vector search?

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next