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 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 sentence embedding compresses an entire string into one fixed-width vector so a search engine can score millions of passages in milliseconds. Contrastive learning is the training objective that bends that vector space until the true answer lands closer to the query than every topic-adjacent lookalike.
| Query | Passage that should rank near it | Topic-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 , where token ID selects row . 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 SVD:[1]
Three landmark methods then made static word vectors scalable without factoring a dense matrix upfront:
- Word2Vec (CBOW and Skip-gram with Negative Sampling):[2][3] Slides a local context window over raw text (CBOW predicts the center word from neighbors; Skip-gram predicts neighbors from the center word) and replaces a full-vocabulary softmax with binary classification against noise draws:
Levy and Goldberg proved that Skip-gram negative sampling implicitly factorizes the shifted PMI matrix , unifying predictive embeddings with matrix factorization.[4]
- GloVe (Global Vectors):[5] Aggregates global co-occurrence counts once and fits weighted least squares on nonzero entries (), using so neither rare noise nor ubiquitous stop words dominate.
- FastText (Subword Composition):[6] Learns vectors for boundary-marked character -grams (
<pl,pla,lay,ay>) alongside whole words, letting unseen inflections likeplayedcompose from shared stem subwords instead of falling back to an<UNK>row.
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. Contextual representations pass lookup rows through sequence layers that mix each token with its neighbors:
- ELMo: Runs forward and backward 2-layer LSTMs over character-CNN inputs and blends layers with task-learned softmax weights ().[7]
- BERT: Uses bidirectional Transformer self-attention so every token (
bank) attends freely to both left and right context (riverorloan).[8] - GPT: Applies a lower-triangular causal mask 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 token a vector. The quickest way to build a sentence vector is mean pooling: average the token vectors. Why isn't that enough on its own?
First, averaging static word vectors is commutative (), 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 ) and mean-pooled BERT scored 54.81, both trailing simple averaged GloVe vectors at 61.32.[10]
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))A: [0.8, 0.133, 0.1] B: [0.8, 0.133, 0.1] identical: TruePretrained contextual representations also bring two geometric traps when plugged directly into vector search:
- Anisotropy: Unfinetuned hidden states in BERT, ELMo, and GPT-2 crowd into a narrow cone sharing a large mean direction .[11] Two opposing residuals around a shared mean
[10, 0], namely[10, 1]and[10, -1], produce a raw cosine of0.980, flipping to-1.000only after subtracting . (Anisotropy alone is not fatal if relative ordering stays sharp;intfloat/e5-base-v2, for example, places most cosines between and while ranking accurately.[12]) - Unaligned coordinate spaces: Matching vector width never guarantees matching geometry across checkpoints. Even a clean orthogonal rotation preserves every internal distance inside Model B while scrambling search if a query from Model A hits an index built with Model B. Pin checkpoint revision, preprocessing, and similarity metric together, and re-index whenever you change encoders.
Contrastive training fixes sentence geometry directly by balancing two forces on the unit hypersphere :[13]
- Alignment: Pull positive pairs together by minimizing .
- Uniformity: Spread unrelated representations across the sphere by minimizing .

Why can mean pooling static word vectors make "compiler calls linker" and "linker calls compiler" identical?
Answer
Vector addition is commutative, so averaging the same set of static token vectors produces the exact same coordinates regardless of word order.
Contrastive learning and InfoNCE
Rather than scoring one pair in isolation, modern retrieval encoders like SBERT,[10] SimCSE,[14] and E5[15] train with InfoNCE.[16] Given a batch of positive pairs normalized to unit length, compute the cosine similarity matrix , divide by a temperature , and treat each row as an -way classification problem where the diagonal entry is the right answer:
![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%.](https://assets.leetllm.com/v1/fbbcbf3f93cf/fundamentals/sentence-embeddings-contrastive-learning/illustrations/_generated/contrastive_learning_dark.png)
Trace one row by hand with , positive similarity , and in-batch negative similarity :
- Scale into logits: and .
- Subtract the max for stability ( and ) and apply softmax: .
- Take negative log: (almost zero loss because the positive already wins decisively). Swap the two scores and the loss rockets to nats!

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:
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()])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, . By contrast, triplet loss enforces an explicit distance margin on a single negative at a time: when , , and , the margin is already met (), whereas flipping gives loss . Both InfoNCE and triplet losses remain standard in Sentence Transformers.[18]
How temperature shapes gradients
Differentiating one InfoNCE row with respect to cosine scores yields:
The ratio of gradient pressure between a hard negative () and an easy negative () is exponential in :
At (Sentence Transformers' default scale=20[18]; E5 uses [12]), that cosine gap gives the hard negative more score gradient than the easy negative, compared to just at . Watch out for the flip side: on an already-easy row (), lowering saturates so tightly that the absolute gradient shrinks by 27 orders of magnitude!

import numpy as np
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}")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-01For a fixed 0.70 similarity gap, does lowering temperature from 1.00 to 0.05 increase the absolute score gradient?
Answer
No. Saturation drives down far faster than grows, dropping the gradient from to . Low amplifies hard negatives while letting easy rows go quiet.
Building training pairs and mining hard negatives
Where do positive pairs and informative negatives come from?
- Supervised NLI and Siamese training: SBERT[10] trained shared-weight Siamese networks on entailment/contradiction pairs; supervised SimCSE uses entailment as the positive and contradiction as a hard negative.[14]
- Self-supervised SimCSE: No labels? Run the exact same sentence through the encoder twice with two independent dropout masks.[14] The two stochastic views become a positive pair, pushing BERT-base unsupervised STS from 54.81 to 76.3 (and 81.6 with NLI supervision).
- In-batch negatives (DPR):[19] A batch of query-passage pairs gives off-diagonal negatives at zero extra encoder cost. Beware false negatives: if two queries in the same batch map to the same passage, unmasked InfoNCE actively pushes the matching passage down with a positive score gradient and hits a loss floor!
Once the encoder easily rejects off-topic passages ("NF4 quantization" vs. "How does RoPE work?"), easy negatives stop teaching it anything. Hard negatives share vocabulary while describing a different mechanism ("Sinusoidal absolute position tables"), injecting fresh denominator mass into InfoNCE.

Teams combine four mining strategies:
- In-batch negatives: Free comparisons that scale with batch size (not plain gradient accumulation unless embeddings are shared across microbatches).
- BM25 lexical hard negatives: High keyword overlap with wrong semantics.
- 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]
- 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 (,[21] which penalizes neglecting any valid positive far more strongly than summing positive mass inside a single log).
import torch
import torch.nn.functional as F
# 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}")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.026958Bi-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?

| Architecture | Stored per document | Query-time work | Interaction | Typical role |
|---|---|---|---|---|
| Bi-encoder | 1 vector | 1 query encode + ANN search | or cosine | First-stage recall over millions of docs |
| Cross-encoder | Raw text | Joint forward over [q; d] pairs | Full self-attention | High-precision top- reranker |
| ColBERT (late interaction) | token vectors () | 1 query encode + token MaxSim | Fine-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 ) and scores with MaxSim:
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 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]

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- shortlist, and the cross-encoder reranks only those candidates. Notice the recall trap below: if candidate_k is too tight, the cross-encoder never sees the right passage and cannot save you!

rope-rotation (0.96) over abs-pos-bias (0.21).import numpy as np
# 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))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 cosine into a collision after re-normalization.
Matryoshka Representation Learning (MRL)[26] solves this by summing the contrastive loss across nested prefix widths during training:
That packs the coarsest, highest-signal information into the front coordinates, enabling adaptive two-stage vector search: index 64-d prefixes in RAM ( raw float32 for 10M docs vs. 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.](https://assets.leetllm.com/v1/671721d08003/fundamentals/sentence-embeddings-contrastive-learning/illustrations/_generated/matryoshka_dimensions_dark.png)
import numpy as np
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))Full cosine: -0.28 Truncated 1D cosine: 1.0
{2: 0.0088, 4: 0.0147, 6: 0.0225} mean: 0.0153Evaluating retrieval: STS, MTEB, and Recall@K vs. MRR
Pairwise STS measures Spearman rank correlation between cosine scores and human relatedness ratings, but high STS alone never guarantees strong search. The Massive Text Embedding Benchmark (MTEB)[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]

On your own held-out search queries, measure Recall@K (coverage: did the relevant documents enter the top ?) separately from MRR or NDCG (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 FAISS.[31]
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}")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.50Your cross-encoder scores the right passage highly whenever you pass it manually, yet production search still misses that passage. Which stage is broken?
Answer
Stage 1 (first-stage recall). A cross-encoder can only reorder candidates that enter its shortlist; improve first-stage retrieval or widen the shortlist within your latency budget.
Deep dive: Practice exercises and common debugging pitfalls
- Triplet loss check: With and , margin gives (satisfied), while gives (active gradient).
- 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 () if ANN + overhead stay under 40 ms.
- 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.