What this is
What is contrastive training?
Contrastive training is how an embedding model, the AI model behind search by meaning, learns what "similar" means. It is shown pairs that belong together (a question and its answer, a photo and its caption) and pairs that do not. Training pulls the first kind close and pushes the second apart. It is the usual way to train an embedding model. The wrong partners decide what it can tell apart: in a small experiment, an embedding model trained against random wrong answers picks the right answer over a look-alike 60% of the time; one trained against look-alikes picks it every time. The same training on images and captions gives CLIP, which puts a picture and a line of text in one shared space.
Why it matters: An embedding model trained on question and answer pairs ranks answers, and one trained on paraphrases ranks restatements, so its training pairs tell you what it will find. You train your own when a general embedding model keeps confusing things your users never confuse, such as the password reset steps and the password policy.
At a glance
Key takeaways
- Contrastive training pulls matching pairs together and pushes non-matches apart. Its loss, InfoNCE, is softmax cross-entropy over a batch.
- Every other answer in a batch is a wrong answer for each question, at no extra cost: these are in-batch negatives.
- A model learns only the distinctions its negatives contain. Hard negatives (same topic, wrong answer) teach it to find the answer, not just the topic.
- Temperature sharpens the softmax so small cosine gaps count; typical τ is 0.01 to 0.1.
- CLIP applies the same loss in both directions between an image encoder and a text encoder, which gives one shared space and zero-shot classification.
How it works, from scratch
A teacher has a stack of question cards and a stack of answer cards. She lays out a few questions, deals all the answers face up, and asks a student to pair each question with its answer, correcting every wrong pairing. Over many rounds the student learns what makes an answer fit a question.
What the student learns depends on the wrong cards. If they are about printers or holidays, the right answer is always the one on the question's subject, and the student can get by on the subject alone. So the teacher slips in a look-alike wrong card: same subject, wrong answer. "How do I reset my password?" now faces both the reset steps and the password policy, and a student who matches on the word "password" can only guess.
This game is contrastive training, and it is the usual way to train an embedding model. The student is the model. Pairing a question with its answer means making the question's vector point the same way as the answer's vector (see Similarity). The wrong cards are negatives, and the look-alikes are hard negatives.
Chapter 1
A tiny worked example: one question, two answer cards
To learn, the model needs a number that says how badly it paired a question: the loss. Here it is for one question and two cards. The question's vector is q = (1, 0). The right answer is p₊ = (1, 0) and a wrong one is p₋ = (0, 1). All three have length 1, so a dot product is a cosine.
- Score each card with the dot product: q·p₊ = 1, q·p₋ = 0.
- Divide by the temperature τ (tau), a sharpness dial explained below. With τ = 1 the scores stay (1, 0).
- Softmax (from Attention): exponentiate and share out. e¹ = 2.718 and e⁰ = 1, so the right card gets 2.718 / 3.718 = 0.731.
- Loss = −ln 0.731 = 0.313. It would be 0 if the right card got 100%.
At τ = 0.1 the scores become (10, 0), the right card gets 99.995%, and the loss is 0.0000454. No vector moved; the smaller τ alone made the model far more confident.
Training lowers the loss by moving vectors: the question's vector turns toward the right card and away from the wrong one.
Figure 1 · Diagram
flowchart LR Q["Question: reset my password"] --> E1[Encoder] P["Right answer: reset steps"] --> E2[Encoder] N["Look-alike: password policy"] --> E3[Encoder] E1 --> PULL[Pull these two<br/>vectors together] E2 --> PULL E1 --> PUSH[Push these two<br/>vectors apart] E3 --> PUSH
Chapter 2
The math: InfoNCE, the loss behind it
Training does not score one question at a time. Like the teacher, it deals a whole batch. B questions sit in rows and all the answer cards in the batch sit in columns. Every card that is not a question's own answer is a negative for it, at no extra cost: these are in-batch negatives.
Figure 2 · Diagram
flowchart LR
subgraph Batch["Similarity table for a batch of 3"]
direction TB
r1["q₁: ✔ ✗ ✗ | ✗"]
r2["q₂: ✗ ✔ ✗ | ✗"]
r3["q₃: ✗ ✗ ✔ | ✗"]
end
Batch --> SM["softmax along<br/>each row"] --> L["loss: −log of the<br/>✔ cell's share"]
The formula and its symbols
Symbols
| Symbol | Meaning here | Shape / range |
|---|---|---|
| B | number of questions in the batch | 8 in this lesson |
| M | number of answer cards in the batch (B, plus any hard negatives) | 8 or 16 here |
| i | which question (row) | 1 to B |
| j | which answer card (column) | 1 to M |
| qᵢ | the i-th question's vector, unit length | d numbers (d = 16) |
| pᵢ | question i's own answer vector (the ✔) | d numbers |
| pⱼ | the j-th answer card in the batch | d numbers |
| · | dot product; equals cosine because the vectors are unit length | −1 to 1 |
| τ (tau) | temperature: divides every score; small τ sharpens the softmax | 0.01 to 1; 0.1 here |
| exp | e raised to the power | > 0 |
| Σⱼ | add up over all M answer cards | |
| the fraction | softmax share of the right card | 0 to 1 |
| log, −(1/B) Σᵢ | take −log of each row's share, then average over the rows | L ≥ 0 |
In words: for every question, measure what share of its softmax goes to its own answer, take the negative log (big when the share is small), and average over the batch.
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
On the example: B = 1, M = 2, τ = 1: L = −log(e¹ / (e¹ + e⁰)) = −log 0.731 = 0.313.
In Python:
import math
def dot(a, b):
return sum(a_i * b_i for a_i, b_i in zip(a, b))
def info_nce(q, p, tau):
B = len(q)
total = 0
for i in range(B):
# exp(q_i · p_j / τ) for every card j
exps = [math.exp(dot(q[i], p_j) / tau) for p_j in p]
# log of the ✔ card's share
total += math.log(exps[i] / sum(exps))
# -(1/B) Σ_i
return -total / B
# B = 1 question
q = [(1, 0)]
# M = 2 cards; card 0 is the question's own answer
p = [(1, 0), (0, 1)]
round(info_nce(q, p, tau=1), 3) # → 0.313
print(f"{info_nce(q, p, tau=0.1):.7f}") # → 0.0000454
The name InfoNCE comes from "noise-contrastive estimation": telling the true pair apart from noise. It is the softmax cross-entropy loss from Loss functions, where the "classes" are the answer cards in the batch. Real retrieval models are trained with it: Dense Passage Retrieval (DPR) and E5 both use this loss with in-batch negatives, E5 at τ = 0.01.
The experiments below train a deliberately tiny bi-encoder, one encoder applied separately to questions and to answers. It counts the words in a text (a bag of words), multiplies the counts by one learned matrix W, and scales the result to length 1. Each training step moves W a little along the gradient, the direction in which each number in W should change to lower the loss.
In code: info_nce_loss computes L for a batch, treating any rows of P
beyond B as extra hard negatives; BiEncoder.encode maps texts to unit
vectors, and encoder_gradient_check checks the hand-derived gradient
against a numerical estimate. View source
Chapter 3
Temperature: the sharpness dial
In the worked example, dividing by τ = 0.1 instead of 1 took the right card's share from 0.731 to 99.995% without moving a vector. Embedding models need that sharpening. Cosines only run from −1 to 1, so a right answer often leads its wrong ones by a small margin, and at τ = 1 a small lead earns only a small share. Embedding models commonly train at τ between 0.01 and 0.1.
Take a right card with cosine 0.8 and three wrong cards at 0.6 each.
The formula and its symbols
Symbols
| Symbol | Meaning here | Range |
|---|---|---|
| share₊ | the softmax share that goes to the right card | 0 to 1 |
| 0.8, 0.6 | cosine of the right card and of each wrong card | −1 to 1 |
| 3 | the number of (identical) wrong cards | |
| τ (tau) | temperature: every cosine is divided by it | 0.01 to 1 in practice |
| e^x | e ≈ 2.718 raised to the power x | > 0 |
In words: the right card's share is its exponentiated, temperature-scaled score divided by the total over all cards.
On the example: at τ = 1, 2.2255 / (2.2255 + 3 × 1.8221) = 0.289; at τ = 0.05 the scores become 16 and 12, and 1 / (1 + 3e⁻⁴) = 0.948.
In Python:
import math
def share_plus(tau):
# e^(0.8/τ)
right = math.exp(0.8 / tau)
# three wrong cards, e^(0.6/τ) each
wrong = 3 * math.exp(0.6 / tau)
return right / (right + wrong)
round(share_plus(1), 3), round(share_plus(0.05), 3) # → (0.289, 0.948)
Figure 3 · Chart
With the right card 0.2 ahead in cosine it gets under a third of the softmax share at temperature 1 and about 95% at temperature 0.05
In code: positive_probability computes share₊ for given cosines and τ;
this curve is that function swept across τ. View source
The dial cuts both ways. Set τ too high and the model never becomes confident. Set it too low and the few hardest pairs take nearly all of the training signal, and training becomes unstable. When you fine-tune an embedding model, τ is one of the settings to tune.
Chapter 4
Hard negatives: the experiment
The teacher's look-alike cards rest on a claim: a model learns only the distinctions its negatives contain. A small experiment tests it.
Questions come in two intents for each topic: "how do I fix it?" (answered by a how-to card: "restart, reinstall and follow the setup guide") and "what are the rules?" (answered by a policy card: "approval, compliance and usage limits"). The question and answer cards share almost no words, so matching intent must be learned ("fix" goes with "restart"), not read off the overlap. Each batch holds one intent across different topics, so its in-batch negatives differ from the right card only by topic. We train two identical models; the only difference is that one also gets each question's same-topic, other-intent card as a hard negative. Then we test on four topics neither model has seen, including "password".
Figure 4 · Diagram
flowchart TD D[Training pairs] --> A[Batches: one intent,<br/>8 different topics] A --> M1[Model 1: in-batch negatives only<br/>wrong cards differ by topic] A --> H[Add each question's<br/>look-alike card] H --> M2[Model 2: plus hard negatives<br/>wrong cards also differ by intent] M1 --> T[Test on unseen topics:<br/>right card vs. look-alike] M2 --> T
Figure 5 · Chart
Without hard negatives the model stays mostly below a coin flip on look-alike cards and ends near 60%, while with hard negatives it reaches 100% within ten steps
Figure 6 · Chart
With in-batch negatives only, held-out questions and cards group by topic; with hard negatives they split by intent, each question beside the card that answers it
Figure 7 · Chart
On the unseen password topic, the in-batch-only model scores both cards almost alike, while the hard-negative model lights up the reset card for how-to questions and the policy card for policy questions
In code: make_pairs builds the (question, right card, look-alike)
triples; look_alike_accuracy runs the exam on unseen topics, and
training_curve records that score at checkpoints during training. View source
Real data does not come with look-alikes labelled, so you mine them: search your corpus with keyword search (BM25) or the current model, and take high-ranking results that are not the right answer. DPR trained this way, with one BM25-mined hard negative per question.
Chapter 5
Fine-tuning on your own domain
Mining is one step in adapting a general embedding model to your own documents. Start from pairs you already have: search logs, support tickets and the article that closed each one, questions and their FAQ entries. Mine hard negatives from your current search results and fine-tune. Then measure recall@k, the share of held-out questions whose right document is in the top k, and ship only if the new model beats the base model. Shipping means re-embedding the whole corpus, because a fine-tuned model has a new vector space (Embeddings in production).
Figure 8 · Diagram
flowchart LR L[Logs: real questions +<br/>the document that resolved each] --> P[Positive pairs] P --> MINE[Mine hard negatives:<br/>top results that are wrong] MINE --> T[Fine-tune with InfoNCE,<br/>in-batch + hard negatives] T --> E["Evaluate recall@k<br/>on a held-out set"] E -->|better than base model| D[Re-embed corpus, deploy] E -->|not better| P
A few thousand good pairs is usually enough to adapt a general model to
legal, medical or internal jargon. The sentence-transformers library
implements this loss as MultipleNegativesRankingLoss.
Test yourself
5 questions
Answer each one out loud or on paper before you open it.
Question 1Q: How are embedding models trained?Think it through, then reveal
Contrastively, on (query, relevant passage) pairs: an encoder embeds both, and InfoNCE rewards the pair's similarity over the similarity to other passages in the batch (in-batch negatives) and to deliberately chosen hard negatives.
Question 2Q: Why do hard negatives matter so much?Think it through, then reveal
Random negatives are usually about something else, so a model can beat them by topic matching alone. Hard negatives share the topic but don't answer the question, forcing the model to learn the fine distinction that retrieval actually needs.
Question 3Q: What does the temperature do in InfoNCE?Think it through, then reveal
It divides the similarities before softmax. A small temperature makes the softmax sharp, so small cosine differences produce large differences in probability and gradient. Too small makes training unstable; too large makes the model unable to become confident.
Question 4Q: How does CLIP put images and text in the same space?Think it through, then reveal
It trains an image encoder and a text encoder together on image-caption pairs with a symmetric contrastive loss: each image must pick its caption from the batch and each caption must pick its image. Matching pairs end up close in one shared space.
Question 5Q: How would you adapt an embedding model to a company's jargon?Think it through, then reveal
Collect real (query, correct document) pairs from logs, mine hard negatives from current search results, fine-tune with in-batch plus hard negatives, evaluate recall@k on a held-out set against the base model, then re-embed the corpus with the new model.
Primary sources
The papers behind this lesson
Named and popularised the InfoNCE loss: pick the true sample out of a set of negatives.
The paperTurned BERT into a bi-encoder that produces one comparable vector per sentence, making semantic search with transformers fast.
Read on rumblr →The paperShowed a question/passage bi-encoder trained with in-batch negatives plus BM25-mined hard negatives beats keyword search for open-domain QA.
Read on rumblr →The paperTrained image and text encoders with a symmetric contrastive loss on 400 million pairs, giving zero-shot image classification.
Read on rumblr →The paperShowed contrastive learning of sentence embeddings works even with dropout noise as the only "augmentation", and with NLI pairs as hard negatives.
The paperResearcher's shelf
Further reading
- sentence-transformers, training overview: https://www.sbert.net/docs/sentence_transformer/training_overview.html
- Wang et al., Text Embeddings by Weakly-Supervised Contrastive Pre-training (E5, 2022): https://arxiv.org/abs/2212.03533
- Muennighoff et al., MTEB: Massive Text Embedding Benchmark (2022): https://arxiv.org/abs/2210.07316
- MTEB leaderboard: https://huggingface.co/spaces/mteb/leaderboard
- Lilian Weng, Contrastive Representation Learning: https://lilianweng.github.io/posts/2021-05-31-contrastive/
About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.