Dive into Deep Learning · §19.3
Text Embeddings from Contrastive Training
pooling · anisotropy · InfoNCE · alignment and uniformity · hard negatives · decoder embedders · smaller vectors
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.
Goals
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.
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 |
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 |
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
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.
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}}
The number of candidates, B, caps what the loss can certify: \log B.
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]
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.
Derivation
I. \ell_i - \log B = -c_{ii}/\tau + \log \frac{1}{B}\sum_j e^{c_{ij}/\tau}
B \to \infty: the average becomes \mathbb{E}_{\mathbf{d}}\, e^{\mathbf{q}_i^\top \mathbf{d}/\tau}
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).
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.
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.
Training
query: / passage: prefixes, mean pooling, B = 64, \tau = 0.05.Loss: 3.2 nats (first ten steps) to 0.05 (last ten).
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.
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.
Qwen3-Embedding-0.6B
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
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.
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.
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.
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.
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.
Binary vectors
| 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.
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.
Choosing
A library loads a model’s pooling and prompts. Check them against the card.
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
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.