Text Embeddings from Contrastive Training

Dive into Deep Learning · §19.3

Text Embeddings from Contrastive Training
pooling · anisotropy · InfoNCE · alignment and uniformity · hard negatives · decoder embedders · smaller vectors

Averaged Encoder Vectors Find the Answer for 6% of Book Questions

The problem

Search the book’s 5,324 passages with 220 questions. Is a relevant passage among the ten nearest?

ranking training for retrieval Recall@10
BM25: count the question’s words none 0.96
ModernBERT, mean of its token vectors none 0.06

“How does the book’s load_array helper decide whether to shuffle?” Averaged vectors land on the page of utility functions, one heading above the answer. The 220 questions share 73 different first passages; under BM25, 210.

An encoder gives one vector per token. Nothing trained it to give one vector per text.

By the End of This Deck You Can

Goals

  • pool token vectors into one unit vector per text;
  • measure how strongly a set of vectors shares one direction;
  • derive the gradient of the contrastive loss and its limit for large batches;
  • train an embedder on question-passage pairs and audit mined negatives;
  • choose a released embedder and a storage format by measurement.

Running example: this book as 5,324 passages; 220 questions about 32 of its documents, drafted from the passages by a language model; BM25 (word counting) as the floor; the load_array question.

One Vector per Text Is What Search Needs

Where this fits

movement section
vectors Word Embeddings
Pretrained Encoders
Text Embeddings from Contrastive Training
finding Sparse, Dense and Approximate Retrieval
using Retrieval-Augmented Generation
Failures and Fixes in RAG
  • Uses: ModernBERT (one vector per token), cross-entropy, mutual information.
  • Skips: indexes for large corpora, encoder pretraining.

Three Ways to Pool, and Always Normalize

Pooling

pooling reads natural for
CLS the first position encoders with a sentence-level task
mean the average over real tokens encoders
last token the final real token decoders: only it saw the whole text
  • The attention mask marks padding, so left and right padding both work.
  • Scale to unit length: the dot product becomes the cosine. Unnormalized, long vectors rank high for every query.
  • Raw ModernBERT with CLS pooling: Recall@10 = 0. Its masked-token loss never scores the first position.

Raw Vectors Share One Direction: Mean Cosine 0.94

Anisotropy

Anisotropy: the mean cosine \bar c of distinct pairs. For unit vectors \mathbf{z}_1, \ldots, \mathbf{z}_n with mean \bar{\mathbf{z}}, \|\sum_i \mathbf{z}_i\|^2 = n + n(n-1)\,\bar c, so

\bar c = \frac{n\|\bar{\mathbf{z}}\|^2 - 1}{n - 1} \approx \|\bar{\mathbf{z}}\|^2.

pooling, 2,000 book passages anisotropy Recall@10
CLS 0.95 0.00
mean 0.94 0.06
mean, centered 0.00 0.05

Centering, subtracting the mean vector, removes the shared direction and leaves Recall@10 at 0.05: the shared direction is not the cause.

Check: A Mean Cosine of 0.94. How Far Is a Passage from the Mean Direction?

Check

2,000 unit vectors of raw passages, mean cosine 0.94 between distinct pairs. What is the angle between a typical vector and the mean direction?

Answer. The mean of \mathbf{z}_i^\top \bar{\mathbf{z}}/\|\bar{\mathbf{z}}\| is \|\bar{\mathbf{z}}\| \approx \sqrt{0.94} \approx 0.97, the cosine of about 14 degrees: a typical angle. The passages fill a narrow cone.

The Other Passages of the Batch Are the Negatives

InfoNCE

B pairs, unit vectors \mathbf{q}_i (question) and \mathbf{d}_i (its passage), cosines c_{ij} = \mathbf{q}_i^\top \mathbf{d}_j, temperature \tau:

\ell = -\frac{1}{B} \sum_{i=1}^{B} \log \frac{e^{c_{ii}/\tau}}{\sum_{j=1}^{B} e^{c_{ij}/\tau}}

  • A B-way cross-entropy: B - 1 negatives per question, already encoded.
  • Mutual information I of question and passage: I \geq \log B - \ell, a bound never above \log B. At B = 64, 4.16 nats.

The number of candidates, B, caps what the loss can certify: \log B.

A Negative 0.3 Closer Gets 403 Times the Push

Gradient

\frac{\partial \ell}{\partial c_{ij}} = \frac{p_{ij} - \delta_{ij}}{\tau B}, \qquad p_{ij} = \mathrm{softmax}_j(c_{ij}/\tau), \qquad \delta_{ij} = [i = j]

  • Pull on the positive: 1 - p_{ii}. Total push on the negatives: the same.
  • Two negatives \Delta apart in cosine: weight ratio e^{\Delta/\tau}.
  • p_{ii} \to 1: every weight vanishes, and easy batches stop teaching.
largest gradient error 1.1e-16; largest |pull - push| per query 2.2e-16
   score gap  weight ratio at tau=0.05
0        0.1                       7.4
1        0.3                     403.4

A low temperature puts its gradient on the hardest negatives, true or false.

As the Batch Grows, InfoNCE Becomes Alignment Plus Uniformity

Derivation

I. \ell_i - \log B = -c_{ii}/\tau + \log \frac{1}{B}\sum_j e^{c_{ij}/\tau}

  1. B \to \infty: the average becomes \mathbb{E}_{\mathbf{d}}\, e^{\mathbf{q}_i^\top \mathbf{d}/\tau}

  2. Unit vectors: \mathbf{q}^\top \mathbf{d} = 1 - \tfrac12 \|\mathbf{q} - \mathbf{d}\|^2; the 1/\tau cancel:

\ell - \log B \to \underbrace{\frac{1}{2\tau}\mathbb{E}\|\mathbf{q} - \mathbf{d}^+\|^2}_{\text{alignment}} + \underbrace{\mathbb{E}_{\mathbf{q}} \log \mathbb{E}_{\mathbf{d}}\, e^{-\|\mathbf{q} - \mathbf{d}\|^2/(2\tau)}}_{\text{uniformity}}

Only two terms remain: one pulls pairs together, one pushes all vectors apart.

Source: Wang and Isola (2020).

Four Points: Two Coincident Pairs on Opposite Sides Win

The smallest case

Pairs (1, 2) and (3, 4) on the unit circle; each point is a question whose passage is its partner, so it also meets itself among the passages.

arrangement alignment \mathcal{U}_2 InfoNCE - \log 4, \tau = 0.05 \tau = 0.5
square: 0°, 90°, 180°, 270° 2.0 -4.4 18.6 0.87
pairs coincide: 0°, 0°, 180°, 180° 0.0 -1.1 -0.69 -0.68
all at 0° 0.0 0.0 0.0 0.0

Square: itself at cosine 1, partner at 0, a logit gap of 20. Coincident pairs: partner and itself tie, a loss of \log 2.

Uniformity Cannot Improve While the Vectors Share a Direction

Proposition

Measured on passages alone (Wang and Isola), for independent passages \mathbf{z}, \mathbf{z}': \mathcal{U}_t = \log \mathbb{E}\, e^{-t\|\mathbf{z} - \mathbf{z}'\|^2}. The loss’s own term has t = 1/(2\tau); we measure at t = 2.

Jensen, \log \mathbb{E} e^X \geq \mathbb{E} X, with anisotropy a:

\mathcal{U}_t \;\geq\; -2t\,(1 - a)

Raw mean pooling: a = 0.94, so \mathcal{U}_2 \geq -0.24; measured -0.23.

To spread the vectors, training must shorten the mean vector.

20,000 Wikipedia Pairs, One Epoch, One Minute

Training

  • Natural Questions: search questions with Wikipedia passages; the book measures transfer.
  • query: / passage: prefixes, mean pooling, B = 64, \tau = 0.05.
  • Learning rate 10^{-4}, chosen on 300 held-out pairs.
  • No batch holds a text twice: it would be a negative of its own question.
  • 313 steps, about 60 s on one RTX 4090; seeds 0, 1, 2.

Loss: 3.2 nats (first ten steps) to 0.05 (last ten).

Check: What Does a Final Loss of 0.05 Nats at B = 64 Certify?

Check

The bound: I \geq \log B - \ell.

Answer. \log 64 - 0.05 \approx 4.11 nats, of at most 4.16. The model picks its passage among 64 nearly every time, so p_{ii} \approx 1 and the gradient weights vanish. Harder negatives or larger batches give it more to learn from; whether that helps must be measured.

A Third of the Top-5 Mined Negatives Answer the Question

Hard negatives

Hard negatives: passages the model ranks high that are not the labeled answer. Mined by the seed-0 model; 500 questions, one passage per bucket, judged by Qwen3-Reranker-0.6B, which reads question and passage together (a model, not people):

mined ranks probably relevant
1 to 5 30%
6 to 10 10%
11 to 30 2%
31 to 50 under 1%

Adding one negative from ranks 11 to 50: +0.03 Recall@10 in one run, interval reaching 0, and 128 candidates instead of 64. Not yet shown to help.

Mine below the top ranks, audit with a model that reads question and passage together, and compare gains with the seed range.

A Decoder Embedder Reads Its Vector at the Last Token

Qwen3-Embedding-0.6B

  • A Qwen3 decoder with causal attention, trained on far more pairs: weak pairs written by a larger Qwen3 model, then labeled pairs with hard negatives, then a merge of checkpoints.
  • Last-token pooling, left padding: every row ends in a real token.
  • Query instruction: Instruct: {task}\nQuery:{query}; passages bare. The task is free text.

A wrong convention raises no error. Pooling and padding errors read the wrong token; the instruction’s effect must be measured.

Check: Right Padding, Last Position. What Does the Vector Read?

Check

A batch of three questions, padded on the right; the code takes the hidden state at position T - 1 of every row.

Answer. For every question shorter than the longest, the state of a padding token. Index the last real token through the attention mask, or pad on the left.

Contrastive Training Adds 70 Points; a Released Embedder About 20 More

Results on the book

model Recall@1 Recall@10 nDCG@10 anisotropy
BM25 0.76 0.96 0.82
raw mean pooling 0.04 0.06 0.04 0.94
contrastive, 3 seeds 0.36 to 0.41 0.73 to 0.78 0.50 to 0.53 0.52 (seed 0)
contrastive + 1 hard negative 0.42 0.80 0.56
Qwen3-Embedding, card’s task 0.70 0.99 0.81 0.28

Paired: raw \to contrastive +0.70 Recall@10, 15 times the seed spread; contrastive \to Qwen3-Embedding +0.23.

The questions borrow their passages’ rare words: no embedder here beats BM25 at rank 1. Qwen3-Embedding may also have read this book on the web.

Our Instruction Lowers the First Ranks; the Card’s Costs Nothing

Instructions

Qwen3-Embedding, 220 book questions. Change against no instruction, paired, intervals over documents. Our task: questions about the book; the card’s: web search queries.

task in the instruction Recall@1 MRR@10 Recall@10
our task -0.032 [-0.068, 0.000] -0.026 [-0.048, -0.004] -0.014 [-0.028, 0.000]
the card’s task +0.005 [-0.025, +0.034] +0.007 [-0.012, +0.027] -0.005 [-0.015, 0.000]

The card reports +1 to 5% from instructions. Here neither wording gains: ours lowers the first ranks, and the card’s task leads it by 0.033 MRR@10 [0.012, 0.053]. The chapter uses the card’s task from here on (d2l.BOOK_TASK).

Start from the card’s wording and test any other against no instruction. A wording is a parameter: choose it on training questions, never on the questions you report.

Training Spreads Random Passages Apart Faster Than Pairs

Geometry

For unit vectors with anisotropy a, two random passages lie at mean squared distance 2 - 2a. Alignment: the mean squared distance from a question to its passage.

model question to its passage two random passages ratio
raw mean pooling 0.19 0.12 0.6
contrastive, seed 0 0.60 0.96 1.6
Qwen3-Embedding 0.61 1.43 2.4

Training moved pairs apart too, but unrelated passages much more. Retrieval depends on the ratio.

Int8 Loses Nothing Measurable; 1,024 Signs Beat 32 Floats

Smaller vectors

Qwen3-Embedding stored as bytes Recall@10 GB per 10^8
float32, 1,024 coordinates 4,096 0.99 410
int8, 1,024 1,024 0.99 102
float32, first 128 512 0.92 51
float32, first 32 128 0.68 12.8
binary + rescoring, 1,024 128 0.98 12.8

At equal bytes, many coarse coordinates rank far better than a few precise ones.

Signs Estimate Angles; Rescoring Restores the Query’s Magnitudes

Binary vectors

  • Random direction \mathbf{r}: P(\mathrm{sign}\,\mathbf{r}^\top\mathbf{a} \neq \mathrm{sign}\,\mathbf{r}^\top\mathbf{b}) = \theta/\pi.
  • Hamming distance: XOR and population count. It ignores magnitude.
  • Rescoring: top 100 by Hamming, reordered by float query \cdot passage signs. Passages stay at one bit.
model float binary + rescoring
contrastive, plain 0.76 0.72
contrastive, Matryoshka 0.74 0.72
Qwen3-Embedding 0.99 0.98

A loss of about 1 to 4 points at 1/32 of the bytes.

Matryoshka Training Helps Where It Was Trained, Not on the Book

Truncation

\ell_{\textrm{MRL}}: the mean of InfoNCE on the first k coordinates, renormalized, over k \in \{768, 512, 256, 128, 64\}.

first k of 768 NQ, plain NQ, Matryoshka book, plain book, Matryoshka
64 0.91 0.92 0.60 0.58
32 0.76 0.83 0.41 0.40
16 0.51 0.62 0.14 0.16

On held-out Natural Questions: +8 and +11 points at 32 and 16, intervals excluding 0. On the book: within noise, even with its passages cut to the 160 tokens of training. Length is not the cause.

A Leaderboard Average Does Not Choose Your Embedder

Choosing

  • MTEB averages many tasks and languages; one domain is a small part.
  • Build your own: a few hundred questions about your documents, ideally written by people who have not just read the answer, and a BM25 floor.
  • Compare with paired differences, intervals over documents, and the seed range.
  • On the book the embedder finds more within ten (+0.04 Recall@10 without an instruction, +0.03 with the card’s task; intervals exclude 0). At rank 1 the two are level, and BM25 leads once our first wording is added. Keep both, the embedder in int8 or binary + rescoring.

A library loads a model’s pooling and prompts. Check them against the card.

Check: A Hundred Million Passages as 1,024-Bit Vectors. How Many GB?

Check

Qwen3-Embedding, binary: one bit per coordinate, 10^8 passages.

Answer. 1,024 bits are 128 bytes, and 128 \times 10^8 bytes are 12.8 GB, against 410 GB in float32. With rescoring, Recall@10 stays at 0.98 of 0.99.

Recap

Recap

  • Raw mean pooling: Recall@10 0.06; BM25 0.96. Mean cosine 0.94 = squared length of the mean vector; removing it does not help.
  • InfoNCE: B - 1 free negatives, a \log B ceiling, gradient weights e^{\Delta/\tau}; large-batch limit = alignment + uniformity.
  • 20,000 pairs, one minute: +0.70 Recall@10. A reranker calls 30% of the top-5 mined passages answers: mine below them.
  • Qwen3-Embedding: 0.99, possibly having read the book; 0.98 at 128 bytes. Our first instruction wording cost MRR@10 0.03; the card’s cost nothing, and the chapter uses it.

Next: a flat scan is one matrix product for 5,324 passages. Millions of passages, and questions about exact identifiers, need an index and a word index beside it.