Skip to content
Skip to lesson
Back to Topics
LearnCore LLM FoundationsSentence Embeddings & Contrastive Loss
MediumEmbeddings & Vector Search21 min read

Sentence Embeddings & Contrastive Loss

Train vectors so the right passage outranks a lookalike, then check that ranking against hard negatives, reranking cost, and a smaller index.

On this page

Search your transformer notes for "How does RoPE encode token position?" and two passages immediately compete for rank 1. One explains how Rotary Position Embeddings rotate query and key pairs in 2D subspaces by angle mθm\theta so dot products depend on relative offset. The other describes adding a learned absolute position table before layer 0. Both share almost the same technical vocabulary (position, token, vector, attention), yet only the first answers the question.

A compresses an entire string into one fixed-width so a search engine can score millions of passages in milliseconds. is the training objective that bends that vector space until the true answer lands closer to the query than every topic-adjacent lookalike.

QueryPassage that should rank near itTopic-adjacent non-match
"How does RoPE encode token position?""Rotate query and key pairs by angle mθ so dot products encode relative offset.""Add learned absolute position tables before the first attention layer."

From static word tables to contextual representations

Before encoding whole passages, NLP built representations for individual words through a trainable lookup matrix E∈RV×dE \in \mathbb{R}^{V \times d}, where token ID ii selects row E[i]E[i]. Those coordinates come from the distributional hypothesis: words appearing in similar neighborhoods (apple and pear near sweet; river and lake near water) land near one another in vector space.

Static word vectors: PPMI-SVD, Word2Vec, GloVe, and FastText

Early dense vectors compressed global co-occurrence counts using Positive Pointwise Mutual Information (PPMI) and truncated :[1]

PMI(w,c)=log⁡#(w,c)⋅N#(w) #(c),PPMI(w,c)=max⁡(PMI(w,c),0)\text{PMI}(w, c) = \log \frac{\#(w, c) \cdot N}{\#(w)\, \#(c)}, \qquad \text{PPMI}(w, c) = \max(\text{PMI}(w, c), 0)

Three landmark methods then made static word vectors scalable without factoring a dense V×VV \times V matrix upfront:

LSGNS=−log⁡σ(u⋅v+)−∑n∈Nlog⁡σ(−u⋅vn)\mathcal{L}_{\text{SGNS}} = -\log \sigma(u \cdot v_+) - \sum_{n \in \mathcal{N}} \log \sigma(-u \cdot v_n)

Levy and Goldberg proved that Skip-gram negative sampling implicitly factorizes the shifted PMI matrix PMI(w,c)−log⁡k\text{PMI}(w, c) - \log k, unifying predictive embeddings with matrix factorization.[4]

Watch one distributional quirk: high static cosine does not imply synonymy. Antonyms like hot and cold appear in nearly identical contexts (hot/cold water) and routinely sit right next to each other.

Breaking the polysemy ceiling with context

Static tables hit a hard ceiling on polysemy: "She saw the bank by the river" and "He paid the loan at the bank" assign the exact same token ID to bank, returning one compromise vector for both senses. pass lookup rows through sequence layers that mix each token with its neighbors:

  1. ELMo: Runs forward and backward 2-layer LSTMs over character-CNN inputs and blends layers with task-learned softmax weights (ELMok=γ∑j=02sjhk,j\text{ELMo}_k = \gamma \sum_{j=0}^{2} s_j h_{k, j}).[7]
  2. BERT: Uses bidirectional Transformer self-attention so every token (bank) attends freely to both left and right context (river or loan).[8]
  3. GPT: Applies a lower-triangular so position 0 (bank) sees only itself while trailing positions integrate the full prefix.[9]

Why pooling static words or raw BERT fails

Word embeddings give every a vector. The quickest way to build a sentence vector is : average the token vectors. Why isn't that enough on its own?

First, averaging static word vectors is commutative (A+B=B+AA + B = B + A), so "compiler calls linker" and "linker calls compiler" collapse to the exact same vector! Second, taking a raw [CLS] vector straight out of pretrained BERT fails even worse: BERT was trained for joint pair classification, not independent cosine search. In the original SBERT benchmarks across seven semantic textual similarity (STS) tasks, raw BERT [CLS] scored just 29.19 (Spearman ×100\times 100) and mean-pooled BERT scored 54.81, both trailing simple averaged GloVe vectors at 61.32.[10]

mean_pool_order_collapse.py
import numpy as np

table = {
    "compiler": np.array([0.9, 0.1, 0.0]),
    "calls": np.array([0.8, 0.2, 0.1]),
    "linker": np.array([0.7, 0.1, 0.2]),
}
mean_pool = lambda s: np.mean([table[w] for w in s.split()], axis=0)

a = mean_pool("compiler calls linker")
b = mean_pool("linker calls compiler")
print("A:", np.round(a, 3).tolist(), "B:", np.round(b, 3).tolist(), "identical:", np.allclose(a, b))
Output
A: [0.8, 0.133, 0.1] B: [0.8, 0.133, 0.1] identical: True

Pretrained contextual representations also bring two geometric traps when plugged directly into vector search:

Contrastive training fixes sentence geometry directly by balancing two forces on the unit hypersphere Sd−1\mathcal{S}^{d-1}:[13]

  1. Alignment: Pull positive pairs (x,x+)(x, x^+) together by minimizing Lalign=E[∥f(x)−f(x+)∥22]=2−2 E[f(x)⊤f(x+)]\mathcal{L}_{\text{align}} = \mathbb{E}[\|f(x) - f(x^+)\|_2^2] = 2 - 2\,\mathbb{E}[f(x)^\top f(x^+)].
  2. Uniformity: Spread unrelated representations across the sphere by minimizing Luniform(t)=log⁡E[exp⁡(−t∥f(x)−f(y)∥22)]\mathcal{L}_{\text{uniform}}(t) = \log \mathbb{E}[\exp(-t\|f(x) - f(y)\|_2^2)].
Equal-scale unit circle showing contrastive separation for a RoPE query at 0 degrees. The positive RoPE guide stays near the query at 6 degrees (cosine 0.995). A hard negative starts crowded at -6 degrees (cosine 0.995) and rotates along a sweeping arc to 120 degrees (cosine -0.500). Companion cosine bars on the right contrast before and after separation.
Contrastive training holds the matching RoPE guide near the query (6°) while pushing a crowded hard negative apart from −6° to 120°.

Contrastive learning and InfoNCE

Rather than scoring one pair in isolation, modern retrieval encoders like SBERT,[10] SimCSE,[14] and E5[15] train with .[16] Given a batch of NN positive pairs (zi,zi+)(z_i, z_i^+) normalized to unit length, compute the N×NN \times N matrix S=QP⊤S = Q P^\top, divide by a τ\tau, and treat each row as an NN-way classification problem where the diagonal entry ii is the right answer:

LInfoNCE=−1N∑i=1Nlog⁡exp⁡(sim(zi,zi+)/τ)∑j=1Nexp⁡(sim(zi,zj+)/τ)\mathcal{L}_{\text{InfoNCE}} = -\frac{1}{N} \sum_{i=1}^{N} \log \frac{\exp(\text{sim}(z_i, z_i^+) / \tau)}{\sum_{j=1}^{N} \exp(\text{sim}(z_i, z_j^+) / \tau)}
Aligned cosine similarity and InfoNCE negative gradient-share bars for query "How does RoPE encode token position?". Left bars plot cosine scores on [0, 1]: RoPE guide positive 0.91, absolute-position hard negative 0.42 (gap 0.49), and NF4 easy negative 0.11 (gap 0.80). Right aligned bars show each negative's share of softmax gradient pressure at temperature tau = 0.10: the hard negative absorbs 95.7% (22x stronger) while the easy negative draws 4.3%.
Higher-scoring hard negatives draw far more softmax mass than easy distractors, concentrating gradient pressure right where the encoder is confused.

Trace one row by hand with τ=0.05\tau = 0.05, positive similarity 0.900.90, and in-batch negative similarity 0.200.20:

  1. Scale into : 0.90/0.05=18.00.90 / 0.05 = 18.0 and 0.20/0.05=4.00.20 / 0.05 = 4.0.
  2. Subtract the max for stability (00 and −14-14) and apply : P+=1/(1+e−14)≈0.99999917P^+ = 1 / (1 + e^{-14}) \approx 0.99999917.
  3. Take negative log: −log⁡(P+)≈8.3×10−7-\log(P^+) \approx 8.3 \times 10^{-7} (almost zero loss because the positive already wins decisively). Swap the two scores and the loss rockets to ≈14\approx 14 nats!
Side-by-side InfoNCE batch matrix and temperature-scaled softmax probabilities. Left: a 4-by-4 cosine similarity heatmap with bright positive pairs along the diagonal (q1-p1 0.90, q2-p2 0.85, q3-p3 0.88, q4-p4 0.82) and cooler off-diagonal in-batch negatives (row q1: 0.90, 0.20, 0.12, 0.08). Right: paired softmax probability bar charts for row q1 showing that low temperature tau=0.05 concentrates probability on p1 (1.00, 0.00, 0.00, 0.00), while high temperature tau=0.50 flattens mass across negatives (0.61, 0.15, 0.13, 0.12).
InfoNCE turns an N×NN \times N cosine similarity matrix into NN row-wise classifications whose targets sit on the diagonal; low temperature τ=0.05\tau=0.05 sharpens softmax probability onto the diagonal match while τ=0.50\tau=0.50 spreads mass across negatives.

In real transformer training, token hidden states have shape [batch, tokens, hidden]. Always mask out padding tokens before mean pooling and L2 normalization so padding never leaks into the pooled vector or receives nonzero gradients:

masked_pool_and_infonce.py
import torch
import torch.nn.functional as F

torch.set_default_dtype(torch.float64)
states = torch.tensor([
    [[1., 0.], [0., 1.], [99., 99.]],
    [[0., 2.], [0., 0.], [99., 99.]],
], requires_grad=True)
mask = torch.tensor([[1., 1., 0.], [1., 0., 0.]])

pooled = (states * mask.unsqueeze(-1)).sum(dim=1) / mask.sum(dim=1, keepdim=True)
queries = F.normalize(pooled, dim=-1)
passages = F.normalize(torch.tensor([[1., 0.], [0., 1.]]), dim=-1)

logits = (queries @ passages.T) / 0.2
loss = F.cross_entropy(logits, torch.arange(len(queries)))
loss.backward()

print("Masked means:", pooled.detach().tolist())
print(f"InfoNCE loss: {loss.item():.6f}")
print("Padding grads (must be zero):", states.grad[:, 2, :].tolist())
print("First real token grad:", [round(v, 6) for v in states.grad[0, 0].tolist()])
Output
Masked means: [[0.5, 0.5], [0.0, 2.0]]
InfoNCE loss: 0.349931
Padding grads (must be zero): [[-0.0, 0.0], [0.0, 0.0]]
First real token grad: [-0.883883, 0.883883]

Many multimodal and dual-encoder recipes (such as CLIP[17]) also average the transpose direction into symmetric InfoNCE, Ldual=12(Lq→d+Ld→q)\mathcal{L}_{\text{dual}} = \tfrac{1}{2}(\mathcal{L}_{q \to d} + \mathcal{L}_{d \to q}). By contrast, L=max⁡(0,d(a,p)−d(a,n)+m)\mathcal{L} = \max(0, d(a, p) - d(a, n) + m) enforces an explicit distance margin mm on a single negative at a time: when d(a,p)=0.2d(a, p) = 0.2, d(a,n)=0.5d(a, n) = 0.5, and m=0.1m = 0.1, the margin is already met (max⁡(0,−0.2)=0\max(0, -0.2) = 0), whereas flipping d(a,p)=0.5,d(a,n)=0.3d(a, p) = 0.5, d(a, n) = 0.3 gives loss 0.30.3. Both InfoNCE and triplet losses remain standard in Sentence Transformers.[18]

How temperature τ\tau shapes gradients

Differentiating one InfoNCE row with respect to cosine scores sj=sim(q,cj)s_j = \text{sim}(q, c_j) yields:

∂L∂s+=−1τ(1−P+),∂L∂sj−=1τPj\frac{\partial \mathcal{L}}{\partial s^+} = -\frac{1}{\tau}(1 - P^+), \qquad \frac{\partial \mathcal{L}}{\partial s_j^-} = \frac{1}{\tau} P_j

The ratio of gradient pressure between a hard negative (s1−=0.72s_1^- = 0.72) and an easy negative (s2−=0.20s_2^- = 0.20) is exponential in 1/τ1/\tau:

∂L/∂s1−∂L/∂s2−=P1P2=exp⁡(s1−−s2−τ)\frac{\partial \mathcal{L} / \partial s_1^-}{\partial \mathcal{L} / \partial s_2^-} = \frac{P_1}{P_2} = \exp\left(\frac{s_1^- - s_2^-}{\tau}\right)

At τ=0.05\tau = 0.05 (Sentence Transformers' default scale=20[18]; E5 uses τ=0.01\tau = 0.01[12]), that 0.520.52 cosine gap gives the hard negative 32,860×32{,}860\times more score gradient than the easy negative, compared to just 1.68×1.68\times at τ=1.0\tau = 1.0. Watch out for the flip side: on an already-easy row (s+=0.90,s−=0.20s^+ = 0.90, s^- = 0.20), lowering τ\tau saturates P+→1P^+ \to 1 so tightly that the absolute gradient shrinks by 27 orders of magnitude!

Dual smooth curves over temperature tau from 0.02 to 1.20 for a fixed similarity gap of 0.70. Left plot shows positive softmax probability P(pos) = 1/(1 + exp(-0.70/tau)) on a full 0 to 1 axis, marking exact values 0.999999 at tau=0.05, 0.999089 at tau=0.10, 0.802184 at tau=0.50, and 0.668188 at tau=1.00. Right plot shows the companion score gradient magnitude (1 - P(pos))/tau, which collapses to near zero at low tau where P(pos) saturates.
For a fixed 0.70 similarity gap, low τ\tau saturates P(positive)≈1P(\text{positive}) \approx 1 and shuts off gradient on easy pairs while focusing all learning on close competitors.
temperature_saturation.py
taus = np.array([0.01, 0.05, 0.10, 1.00])
sigmoid = lambda x: 1.0 / (1.0 + np.exp(-np.clip(x, -700.0, 700.0)))
p_pos = sigmoid((0.90 - 0.20) / taus)
p_neg = sigmoid((0.20 - 0.90) / taus)  # avoids 1 - P cancellation
grads = p_neg / taus

for tau, p, g in zip(taus, p_pos, grads):
    print(f"tau={tau:.2f}: P(pos)={p:.6f}, |grad|={g:.3e}")
Output
tau=0.01: P(pos)=1.000000, |grad|=3.975e-29
tau=0.05: P(pos)=0.999999, |grad|=1.663e-05
tau=0.10: P(pos)=0.999089, |grad|=9.111e-03
tau=1.00: P(pos)=0.668188, |grad|=3.318e-01

Building training pairs and mining hard negatives

Where do positive pairs and informative negatives come from?

Once the encoder easily rejects off-topic passages ("NF4 quantization" vs. "How does RoPE work?"), easy negatives stop teaching it anything. share vocabulary while describing a different mechanism ("Sinusoidal absolute position tables"), injecting fresh denominator mass into InfoNCE.

2D unit-circle cosine similarity plot for query "How does RoPE encode token position?" at 0 degrees (cosine 1.00). At exact cosine positions on the circle: true positive RoPE rotation sits at +23 degrees (cosine 0.92, protect); an unlabeled false negative RoPE paraphrase sits at -27 degrees (cosine 0.89, audit and mask); hard negative 1 Sinusoidal abs bias sits at +41 degrees (cosine 0.76, mine); hard negative 2 Learned pos embed sits at -47 degrees (cosine 0.68, mine); and easy negative NF4 quant sits at +87 degrees (cosine 0.05, drop).
On the unit circle, hard negatives sit in the high-cosine mining ring (0.680.68 to 0.760.76), unlabeled false negatives lurk even closer to the query (0.890.89) and must be audited out, and orthogonal distractors (0.050.05) are dropped.

Teams combine four mining strategies:

  1. In-batch negatives: Free comparisons that scale with batch size (not plain gradient accumulation unless embeddings are shared across microbatches).
  2. BM25 lexical hard negatives: High keyword overlap with wrong semantics.
  3. Cross-encoder mining and MarginMSE distillation: Score top-100 candidates with a joint cross-encoder teacher and either mine high-scoring non-matches or distill the teacher's score gap directly via MarginMSE:[20]
LMarginMSE=((scorestudent(q,p+)−scorestudent(q,n−))−(scoreteacher(q,p+)−scoreteacher(q,n−)))2\mathcal{L}_{\text{MarginMSE}} = \left( (\text{score}_{\text{student}}(q, p^+) - \text{score}_{\text{student}}(q, n^-)) - (\text{score}_{\text{teacher}}(q, p^+) - \text{score}_{\text{teacher}}(q, n^-)) \right)^2
  1. Iterative (self-adversarial) mining: Re-index the corpus with the updated bi-encoder to surface the model's newest mistakes, while filtering out unlabeled positives using teacher score ceilings or multi-positive objectives like SupCon (Lmean-log=−1∣P∣∑p∈Plog⁡Pp\mathcal{L}_{\text{mean-log}} = -\frac{1}{|\mathcal{P}|}\sum_{p\in\mathcal{P}}\log P_p,[21] which penalizes neglecting any valid positive far more strongly than summing positive mass inside a single log).
false_negatives_and_hard_negatives.py
# 1. Duplicate positive in the same batch creates a harmful repulsive gradient unless masked.
for mask_dup in (False, True):
    scores = torch.tensor([0.8, 0.8, 0.1], dtype=torch.float64, requires_grad=True)
    logits = scores / 0.2
    if mask_dup:
        logits = logits.masked_fill(torch.tensor([False, True, False]), -torch.inf)
    loss = F.cross_entropy(logits.unsqueeze(0), torch.tensor([0]))
    loss.backward()
    print(f"mask_dup={str(mask_dup):<5}: loss={loss.item():.4f}, grads={[round(g, 3) for g in scores.grad.tolist()]}")

# 2. Adding one mined hard negative (0.72) wakes up a saturated easy row (0.90 vs 0.20, tau=0.05).
easy_loss = F.cross_entropy(torch.tensor([[0.90, 0.20]]) / 0.05, torch.tensor([0])).item()
hard_loss = F.cross_entropy(torch.tensor([[0.90, 0.20, 0.72]]) / 0.05, torch.tensor([0])).item()
print(f"Easy-only loss: {easy_loss:.6f} -> With mined hard neg: {hard_loss:.6f}")
Output
mask_dup=False: loss=0.7081, grads=[-2.537, 2.463, 0.074]
mask_dup=True : loss=0.0298, grads=[-0.147, 0.0, 0.147]
Easy-only loss: 0.000001 -> With mined hard neg: 0.026958

Bi-encoder, cross-encoder, and ColBERT late interaction

Once you know how to train vectors, serving raises a second architectural question: when do the query and document tokens get to see each other?

Two-panel comparison of retrieval encoder architectures. The left panel shows token interaction geometry: Bi-Encoder pools query and passage tokens independently into single vectors for one dot product q dot d; ColBERT Late Interaction keeps per-token vectors and sums query-row maxima over a token-to-token similarity grid; Cross-Encoder concatenates query and passage tokens for dense all-to-all self-attention. The right panel plots representative query latency (log milliseconds) against retrieval precision, showing Bi-Encoder fastest at lower precision, ColBERT in the middle, and Cross-Encoder slowest with highest precision.
Three interaction points (pooled dot product, token-level MaxSim, and full joint self-attention) trade faster query latency for finer retrieval precision.
ArchitectureStored per documentQuery-time workInteractionTypical role
1 vector1 query encode + q⋅dq \cdot d or cosineFirst-stage recall over millions of docs
Raw textJoint forward over KK [q; d] pairsFull self-attentionHigh-precision top-KK
ColBERT (late interaction)LdL_d token vectors (d=128d=128)1 query encode + token MaxSim∑imax⁡jqi⋅dj\sum_i \max_j q_i \cdot d_jFine-grained token matching with larger index

ColBERT[22] sits cleanly between the two extremes. Both sides encode independently (keeping offline indexing intact), but instead of collapsing a passage to one vector, ColBERT stores normalized contextual token vectors (typically projected to d=128d = 128) and scores with MaxSim:

Score(q,d)=∑i=1∣q∣max⁡j=1∣d∣Eq,i⋅Ed,j⊤\text{Score}(q, d) = \sum_{i=1}^{|q|} \max_{j=1}^{|d|} E_{q,i} \cdot E_{d,j}^\top

Each query token picks its strongest matching document token (multiple query tokens may match the same document token). Storing 100 token vectors of width 128 takes 16.7×16.7\times the raw float bytes of a single width-768 vector, which ColBERTv2 compresses sharply by storing a nearest-centroid ID plus 1- or 2-bit quantized residuals.[23]

ColBERT MaxSim similarities compare query positions rope and angle with stored document positions shift, rope, and angle. Matrix rows are 0.12, 0.93, 0.08 and 0.19, 0.07, 0.91 across six dot products. Row maxima 0.93 and 0.91 sum to 1.84.
ColBERT's MaxSim takes each query token's peak similarity across stored document tokens and sums those row maxima (0.93+0.91=1.840.93 + 0.91 = 1.84).

In production, teams routinely pair a bi-encoder with a cross-encoder in a two-stage retrieval pipeline: the bi-encoder fetches a fast top-KK shortlist, and the cross-encoder reranks only those KK candidates. Notice the recall trap below: if candidate_k is too tight, the cross-encoder never sees the right passage and cannot save you!

Paired score bars and rank-swap slopegraph for query "How does RoPE encode token position?". Stage 1 bi-encoder shortlist at K=3 ranks abs-pos-bias #1 (0.84), rope-rotation #2 (0.81), and rope-theta-base #3 (0.78), excluding nf4-quant #4 (0.10, cross score 0.05 unused). Stage 2 cross-encoder reranking swaps the order to rope-rotation #1 (0.96) and rope-theta-base #2 (0.91) inside top_k=2, dropping abs-pos-bias to #3 (0.21).
Stage 1 bi-encoder recall caps what Stage 2 can rescue: with K=3K=3, the cross-encoder promotes rope-rotation (0.96) over abs-pos-bias (0.21).
maxsim_and_rerank.py
# 1. ColBERT MaxSim over query ["rope", "angle"] x doc ["shift", "rope", "angle"]
sim = np.array([[0.12, 0.93, 0.08], [0.19, 0.07, 0.91]])
print("MaxSim row maxima:", sim.max(axis=1).tolist(), "-> score:", round(float(sim.max(axis=1).sum()), 2))

# 2. Two-stage bi-encoder + cross-encoder reranking
docs = [
    {"id": "abs-pos-bias", "bi": 0.84, "cross": 0.21},
    {"id": "rope-rotation", "bi": 0.81, "cross": 0.96},
    {"id": "rope-theta-base", "bi": 0.78, "cross": 0.91},
    {"id": "nf4-quantization", "bi": 0.10, "cross": 0.05},
]
def search(candidate_k: int, top_k: int = 2):
    shortlist = sorted(docs, key=lambda d: d["bi"], reverse=True)[:candidate_k]
    return [d["id"] for d in sorted(shortlist, key=lambda d: d["cross"], reverse=True)[:top_k]]

print("K=3 reranked top-2:", search(candidate_k=3))
print("K=1 trapped top-2: ", search(candidate_k=1))
Output
MaxSim row maxima: [0.93, 0.91] -> score: 1.84
K=3 reranked top-2: ['rope-rotation', 'rope-theta-base']
K=1 trapped top-2:  ['abs-pos-bias']

Task prefixes and Matryoshka embeddings

Retrieval is asymmetric: queries are short questions while documents are long explanations. Many checkpoints therefore expect task formatting documented on their model cards: intfloat/e5-base-v2 requires "query: " and "passage: " prefixes,[12] BAAI/bge-base-en-v1.5 recommends a retrieval query instruction with plain passages,[24] and INSTRUCTOR takes [instruction, text] pairs.[25] Always store formatting settings alongside the index so query and corpus prefixes never drift out of sync.

What if your vector index is running out of RAM? Arbitrarily slicing a standard 768-d vector to v[:128] can collapse distinct vectors together: truncating unit vectors [0.6, 0.8] and [0.6, -0.8] to their first coordinate turns a −0.28-0.28 cosine into a 1.01.0 collision after re-normalization.

[26] solves this by summing the contrastive loss across nested prefix widths D={32,64,128,256,512,768}\mathcal{D} = \{32, 64, 128, 256, 512, 768\} during training:

LMRL=∑d∈Dwd LInfoNCE(z1:d∥z1:d∥2,z1:d+∥z1:d+∥2;τ)\mathcal{L}_{\text{MRL}} = \sum_{d \in \mathcal{D}} w_d \, \mathcal{L}_{\text{InfoNCE}}\left( \frac{z_{1:d}}{\|z_{1:d}\|_2}, \frac{z^+_{1:d}}{\|z^+_{1:d}\|_2}; \tau \right)

That packs the coarsest, highest-signal information into the front coordinates, enabling adaptive two-stage vector search: index 64-d prefixes in RAM (2.56 GB2.56\text{ GB} raw float32 for 10M docs vs. 30.72 GB30.72\text{ GB} at 768-d) to retrieve a shortlist, then fetch full vectors from disk to rescore. Always re-normalize truncated prefixes before dot-product search so dot product still equals cosine!

Matryoshka representation learning showing nested prefix slices [0..32] subset of [0..128] subset of [0..768] inside one 768-dimensional embedding, taking 4.17%, 16.67%, and 100% of full float storage. Below, a calibrated joint multi-width InfoNCE loss plot shows prefix losses 0.0088 at d=2, 0.0147 at d=4, and 0.0225 at d=6 averaged to mean loss 0.0153.
Matryoshka training supervises nested prefixes simultaneously so a single checkpoint supports 32-d, 128-d, or full 768-d deployment budgets.
matryoshka_and_truncation.py
def norm_rows(x: np.ndarray) -> np.ndarray:
    return x / np.linalg.norm(x, axis=-1, keepdims=True)

def info_nce(q: np.ndarray, p: np.ndarray, tau: float = 0.2) -> float:
    logits = (norm_rows(q) @ norm_rows(p).T) / tau
    shifted = logits - logits.max(axis=1, keepdims=True)
    log_probs = shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True))
    return float(-np.mean(np.diag(log_probs)))

# 1. Arbitrary truncation collapses [0.6, 0.8] and [0.6, -0.8] from cosine -0.28 to 1.00.
q_vec, d_vec = np.array([[0.6, 0.8]]), np.array([[0.6, -0.8]])
print("Full cosine:", round(float((q_vec @ d_vec.T)[0, 0]), 2),
      "Truncated 1D cosine:", round(float((norm_rows(q_vec[:, :1]) @ norm_rows(d_vec[:, :1]).T)[0, 0]), 2))

# 2. Multi-width Matryoshka loss across nested prefix sizes (2, 4, 6).
Q = np.array([[1.0, 0.0, 0.9, 0.1, 0.5, 0.2], [0.0, 1.0, 0.1, 0.9, 0.2, 0.5]])
P = np.array([[0.95, 0.05, 0.85, 0.15, 0.45, 0.25], [0.05, 0.95, 0.15, 0.85, 0.25, 0.45]])
losses = {d: info_nce(Q[:, :d], P[:, :d]) for d in (2, 4, 6)}
print({d: round(v, 4) for d, v in losses.items()}, "mean:", round(float(np.mean(list(losses.values()))), 4))
Output
Full cosine: -0.28 Truncated 1D cosine: 1.0
{2: 0.0088, 4: 0.0147, 6: 0.0225} mean: 0.0153

Evaluating retrieval: STS, MTEB, and Recall@K vs. MRR

Pairwise STS measures between cosine scores and human relatedness ratings, but high STS alone never guarantees strong search. The [27] (incorporating BEIR[28] for retrieval and expanded to 500+ multilingual tasks in MMTEB[29]) exposed that no single encoder dominates all eight task families (retrieval, classification, clustering, STS, reranking, pair classification, summarization, and bitext mining).[30]

MTEB task-group distribution across 58 datasets alongside an STS Spearman rank-agreement schematic. Left horizontal bar chart ranks the eight MTEB categories: Retrieval 15, Classification 12, Clustering 11, STS 10, Reranking 4, Pair classification 3, Bitext mining 2, and Summarization 1. Right panel illustrates STS Spearman correlation aligning human similarity ratings (4.5/5 high, 1.2/5 low) with cosine similarity rank order.
STS tests pairwise relatedness via Spearman correlation; MTEB spans eight distinct task categories so you can screen models before benchmarking on your own corpus.

On your own held-out search queries, measure (coverage: did the relevant documents enter the top KK?) separately from MRR or (ordering: how high did the first relevant document land?). In practice, you train and pool embeddings with sentence-transformers[10] and index/search them with .[31]

recall_and_mrr.py
cases = [
    ({"rope-rotation", "theta-base"}, ["abs-bias", "rope-rotation", "theta-base"]),
    ({"alibi-slope"}, ["alibi-slope", "rope-rotation", "abs-bias"]),
    ({"yarn-scale"}, ["abs-bias", "alibi-slope", "rope-rotation"]),
]
def eval_at_k(relevant: set[str], ranked: list[str], k: int = 2):
    top = ranked[:k]
    recall = len(relevant & set(top)) / len(relevant)
    rr = next((1 / i for i, doc in enumerate(top, 1) if doc in relevant), 0.0)
    return recall, rr

scores = [eval_at_k(rel, rank) for rel, rank in cases]
for idx, (r, rr) in enumerate(scores, 1):
    print(f"Query {idx}: Recall@2={r:.2f}, RR@2={rr:.2f}")
print(f"Mean Recall@2={sum(r for r, _ in scores)/len(scores):.2f}, MRR@2={sum(rr for _, rr in scores)/len(scores):.2f}")
Output
Query 1: Recall@2=0.50, RR@2=0.50
Query 2: Recall@2=1.00, RR@2=1.00
Query 3: Recall@2=0.00, RR@2=0.00
Mean Recall@2=0.50, MRR@2=0.50
Deep dive: Practice exercises and common debugging pitfalls
  1. Triplet loss check: With d(a,p)=0.3d(a,p) = 0.3 and d(a,n)=0.7d(a,n) = 0.7, margin m=0.1m = 0.1 gives max⁡(0,−0.3)=0\max(0, -0.3) = 0 (satisfied), while m=0.5m = 0.5 gives max⁡(0,0.1)=0.1\max(0, 0.1) = 0.1 (active gradient).
  2. Latency budget check: With 2M chunks, a 200 ms query budget, 10 ms query encode, and 15 ms/pair sequential cross-encoder scoring, scoring the full corpus takes 8.3 hours! A two-stage pipeline leaves 190 ms for ANN + reranking, fitting at most a top-10 shortlist (150 ms150\text{ ms}) if ANN + overhead stay under 40 ms.
  3. Common bugs: Using raw BERT [CLS] without contrastive training; forgetting padding masks before mean pooling; keeping easy batches where loss drops to 0 without lifting Recall@K; slicing embeddings without Matryoshka training or prefix re-normalization; omitting model-card query/passage prefixes.
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A fresh sequence has valid token states [2,0] and [0,4], followed by padding [100,100]. Pool only valid states, then use cosine with [1,0]. Which pooled mean and similarity follow?
2.A one-positive InfoNCE row has positive score 0.4, negative score 0.6 and temperature 0.2. Which positive probability, loss and raw-score gradient pair are approximately correct?
3.Use triplet loss max(0,d_positive−d_negative+margin), with distances 0.45 and 0.55. What losses follow for margins 0.05 and 0.20?
4.One microbatch contains two positive query-passage pairs and a second contains four. Training uses in-batch negatives and accumulates gradients without sharing embeddings between microbatches. How many text encodings and off-diagonal query-to-passage comparisons does training use in total?
5.One anchor has verified positive softmax probabilities 0.6 and 0.2, plus negative probability 0.2. What are negative-log positive mass and mean positive negative-log loss, respectively?
6.For one query, a teacher scores the relevant passage 3.25 points below a non-match. The student scores both passages with raw cosines in [−1, 1]. Using the relevant score minus the non-match score for both margins, which student margin comes closest to the teacher's, and what is its squared error?
7.A late-interaction similarity matrix has query rows [0.4,0.8,0.2], [0.7,0.1,0.5] and [0.3,0.9,0.2] over three document tokens. Which MaxSim score and matching rule follow?
8.A Matryoshka model indexes one million width-96 float32 vectors out of a 768-d full model. Held-out Recall@200 is 0.86 against a target floor of 0.90. What raw short-vector payload and deployment decision follow?
9.A search service has a 175 ms deadline. Query encoding takes 14 ms, lookup takes 19 ms and other overhead takes 12 ms. The cross-encoder takes 11 ms per candidate. All work runs sequentially. What is the largest shortlist that fits, and which stage should you tune if required passages rank below that cutoff?
10.A query has relevant judgments {A,B,C}. At cutoff 2, control ranks [X,B,A] and candidate ranks [B,X,A]. The target recall floor is 0.4. Which metric and comparison follow?

10 questions remaining.

References

Indexing by Latent Semantic Analysis

Deerwester, S., et al. · 1990 · JASIS

https://doi.org/10.1002/(SICI)1097-4571(199009)41:6%3C391::AID-ASI1%3E3.0.CO;2-9

Efficient Estimation of Word Representations in Vector Space.

Mikolov, T., Chen, K., Corrado, G., & Dean, J. · 2013 · arXiv preprint

https://arxiv.org/abs/1301.3781

Distributed Representations of Words and Phrases and their Compositionality

Mikolov, T., Sutskever, I., Chen, K., Corrado, G., & Dean, J. · 2013 · NeurIPS 2013

https://arxiv.org/abs/1310.4546

Neural Word Embedding as Implicit Matrix Factorization.

Levy, O. & Goldberg, Y. · 2014

https://proceedings.neurips.cc/paper_files/paper/2014/hash/b78666971ceae55a8e87efb7cbfd9ad4-Abstract.html

GloVe: Global Vectors for Word Representation.

Pennington, J., Socher, R., & Manning, C. D. · 2014

https://aclanthology.org/D14-1162.pdf

Enriching Word Vectors with Subword Information.

Bojanowski, P., et al. · 2017

https://arxiv.org/abs/1607.04606

Deep contextualized word representations.

Peters, M., et al. · 2018 · NAACL 2018

https://arxiv.org/abs/1802.05365

BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.

Devlin, J., et al. · 2019 · NAACL 2019

https://arxiv.org/abs/1810.04805

Improving Language Understanding by Generative Pre-Training.

Radford, A., et al. · 2018

https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf

Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks.

Reimers, N., & Gurevych, I. · 2019 · EMNLP 2019

https://arxiv.org/abs/1908.10084

How Contextual are Contextualized Word Representations? Comparing the Geometry of BERT, ELMo, and GPT-2 Embeddings.

Ethayarajh, K. · 2019

https://arxiv.org/abs/1909.00512

E5-base-v2 model card

intfloat / E5 authors · 2026

https://huggingface.co/intfloat/e5-base-v2

Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere

Wang, T., & Isola, P. · 2020 · ICML 2020

https://arxiv.org/abs/2005.10242

SimCSE: Simple Contrastive Learning of Sentence Embeddings.

Gao, T., Yao, X., & Chen, D. · 2021 · EMNLP 2021

https://arxiv.org/abs/2104.08821

Text Embeddings by Weakly-Supervised Contrastive Pre-training.

Wang, L., et al. · 2022

https://arxiv.org/abs/2212.03533

Representation Learning with Contrastive Predictive Coding.

Oord, A. van den, Li, Y., & Vinyals, O. · 2018

https://arxiv.org/abs/1807.03748

Learning Transferable Visual Models From Natural Language Supervision.

Radford, A., et al. · 2021 · ICML 2021

https://arxiv.org/abs/2103.00020

Sentence Transformers loss reference

Sentence Transformers Contributors · 2026

https://www.sbert.net/docs/package_reference/sentence_transformer/losses.html

Dense Passage Retrieval for Open-Domain Question Answering.

Karpukhin, V., et al. · 2020 · EMNLP 2020

https://arxiv.org/abs/2004.04906

Improving Efficient Neural Ranking Models with Cross-Architecture Knowledge Distillation

Hofstätter, S., Althammer, S., Schröder, M., Sertkan, M., & Hanbury, A. · 2020

https://arxiv.org/abs/2010.02666

Supervised Contrastive Learning

Khosla, P., et al. · 2020

https://arxiv.org/abs/2004.11362

ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT.

Khattab, O., & Zaharia, M. · 2020 · SIGIR 2020

https://arxiv.org/abs/2004.12832

ColBERTv2: Effective and Efficient Retrieval via Lightweight Late Interaction

Santhanam, K., Khattab, O., Saad-Falcon, J., Potts, C., & Zaharia, M. · 2022 · NAACL 2022

https://arxiv.org/abs/2112.01488

BGE-base-en-v1.5 model card

Beijing Academy of Artificial Intelligence · 2026

https://huggingface.co/BAAI/bge-base-en-v1.5

INSTRUCTOR embedding usage

INSTRUCTOR Contributors · 2026

https://github.com/xlang-ai/instructor-embedding

Matryoshka Representation Learning.

Kusupati, A., et al. · 2022 · NeurIPS 2022

https://arxiv.org/abs/2205.13147

MTEB: Massive Text Embedding Benchmark.

Muennighoff, N., et al. · 2023 · EACL 2023

https://arxiv.org/abs/2210.07316

BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models.

Thakur, N., et al. · 2021 · NeurIPS 2021 Datasets and Benchmarks

https://arxiv.org/abs/2104.08663

MMTEB: Massive Multilingual Text Embedding Benchmark

Enevoldsen, K., et al. · 2025 · ICLR 2025

https://arxiv.org/abs/2502.13595

MTEB Leaderboard

Hugging Face / MTEB contributors · 2026

https://leaderboard.mteb.org/

Billion-scale similarity search with GPUs.

Johnson, J., Douze, M., & Jégou, H. · 2017 · arXiv preprint

https://arxiv.org/abs/1702.08734

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.