rumblr Work in progressWIP

● The AI Primer · Lesson 26 · Part 4: embeddings and search

Training embedding models

Contrastive training: how an embedding model learns what "similar" means

This lesson covers How an embedding model is taught what similar means, from pairs of texts that belong together

Members · open during launch 27 min10 figures and diagrams7 interactive

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

  1. Contrastive training pulls matching pairs together and pushes non-matches apart. Its loss, InfoNCE, is softmax cross-entropy over a batch.
  2. Every other answer in a batch is a wrong answer for each question, at no extra cost: these are in-batch negatives.
  3. 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.
  4. Temperature sharpens the softmax so small cosine gaps count; typical τ is 0.01 to 0.1.
  5. 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.

Play the teacher. This student has learned nothing yet and picks the card that shares the most words with the question. Deal it easy wrong cards, then slip in the look-alike.

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.

  1. Score each card with the dot product: q·p₊ = 1, q·p₋ = 0.
  2. Divide by the temperature τ (tau), a sharpness dial explained below. With τ = 1 the scores stay (1, 0).
  3. Softmax (from Attention): exponentiate and share out. e¹ = 2.718 and e⁰ = 1, so the right card gets 2.718 / 3.718 = 0.731.
  4. 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

Reading it: follow the three texts from the left. All three go through the same encoder, the model that turns text into a vector. On the right, the question's vector and the right answer's are pulled together, while the question's and the look-alike's are pushed apart. Telling the look-alike from the right answer is what separates retrieval (finding the answer) from topic matching (finding the subject).

Drag the three arrows to change the vectors and watch the four steps follow. Then take a training step and see which way the question moves.

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

Reading it: each row is one question scored against every answer card in the batch. The ✔ on the diagonal is its own answer; every ✗ is a negative that costs nothing extra because those answers are already in the batch. Columns to the right of the bar (|) are hard negatives added on purpose; they answer no question in the batch. Softmax runs along each row, and the loss asks each row to put its share on the ✔.
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

A real batch of questions, scored by the tiny bi-encoder before and after training. Each row is one term of the sum in the formula.

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

1 0 − 2 1 0 − 1 1 0 0 temperature τ (log scale) 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 softmax share of the right card Right card at cos 0.8 vs. three wrong at 0.6

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

Reading it: the horizontal axis is τ (log scale), the vertical axis is the right card's softmax share when it beats three wrong cards by 0.2 in cosine. Read from the right. At τ = 1 the 0.2 lead earns under a third of the share, so the loss keeps complaining about pairs that are already ranked correctly. Around τ = 0.05 the same lead earns about 95%.

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.

Set the cards' cosines yourself, then slide τ and watch which wrong card takes most of the push.

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

Reading it: both models see the same questions and answers in the same order. The branch on the right adds one extra wrong card per question, a card that has the right topic but the wrong intent. Both models then take the same exam: for a question about an unseen topic, does the right card beat its look-alike?

Figure 5 · Chart

0 50 100 150 200 250 300 350 400 training steps 0.0 0.2 0.4 0.6 0.8 1.0 right card beats look-alike (unseen topics) Negatives only teach the distinctions they contain in-batch negatives only plus hard negatives coin flip

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

Reading it: the horizontal axis is training steps, the vertical axis is the share of held-out questions whose right card beats the same-topic look-alike (the dashed line is a coin flip). The in-batch-only model spends most of its training below the coin flip, often preferring the wrong card, and ends near 60%. Nothing in its training ever penalised "same topic, wrong intent", so whatever it does on that distinction is an accident of what it learned about topics. With hard negatives the model reaches 100% within ten steps, on topics it never trained on, because it learned what "fix" and "rules" mean.

Figure 6 · Chart

−0.6 −0.4 −0.2 0.0 0.2 0.4 0.6 principal component 1 −0.6 −0.4 −0.2 0.0 0.2 0.4 0.6 0.8 principal component 2 in-batch negatives only −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 principal component 1 −0.6 −0.4 −0.2 0.0 0.2 0.4 principal component 2 plus hard negatives how-to question policy question how-to card policy card

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

Reading it: each panel squashes the embeddings of the four unseen topics to 2-D with PCA (the two most spread-out directions; see Math notation, from zero). Circles are questions and squares are answer cards; blue means how-to and orange means policy. With in-batch negatives only (left), the points group by topic, and how-to and policy questions sit on top of each other. With hard negatives (right), they split by intent, and each question sits next to the kind of card that actually answers it.

Figure 7 · Chart

reset card policy card how do i fix my password my password is broken password not working help i am stuck with my password password keeps failing what are the password rules is there a limit on password who can get password password rules for my team am i permitted to have password in-batch negatives only reset card policy card plus hard negatives −0.2 0.0 0.2 0.4 0.6 0.8 1.0 cosine similarity

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

Reading it: rows are the ten "password" questions (five how-to, then five policy), columns are the two password cards, and brighter means a higher cosine. On the left the two columns are nearly the same colour: the model sees "password" and can't tell the cards apart. On the right, the how-to rows light up the reset card and the policy rows light up the policy card, so the bright blocks are the right answers.

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.

The experiment again, running in your browser. Rewind the training, ask either model a question, or start both models from new random numbers.

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

Reading it: follow the arrows from your logs on the left to a deployed model on the right. The arrow back from evaluation is the case where the fine-tuned model loses to the base model: it goes back for better pairs instead of into production.

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.

The middle of that recipe, on the experiment's four unseen topics. Pick a question and a search system, see which wrong card you would mine, and compare recall@k.

Chapter 6

CLIP: two encoders, one shared space

Nothing in InfoNCE needs the question and the answer to be the same kind of thing. CLIP trains two encoders, one for images and one for text, so that a photo of a dog and the words "a photo of a dog" land at the same spot in one shared space. Its batches are pairs of an image and its caption, and its loss is InfoNCE run both ways.

Take two images and two captions, each a unit vector. Correctly paired, image 1 scores (1, 0) against the captions and caption 1 scores (1, 0) against the images: each direction's loss is ln(1 + 1/e) = 0.313. Swap the captions and every right pair scores 0 against a wrong pair's 1: the loss rises to ln(1 + e) = 1.313.

The formula and its symbols

Symbols

Symbol Meaning here
L_image→text InfoNCE where each image (a row of the table) must pick its own caption from all captions in the batch
L_text→image the same loss with the roles swapped: each caption (a column) must pick its own image
½( … + … ) the average of the two directions
L_CLIP the loss both encoders are trained on together

In words: each image must find its caption and each caption must find its image.

On the example: ½(0.313 + 0.313) = 0.313 correctly paired; ½(1.313 + 1.313) = 1.313 with the captions swapped.

In Python:

import math
# InfoNCE with τ = 1: row i must pick column i
def rows_pick_diagonal(S):
    return -sum(math.log(math.exp(row[i]) / sum(math.exp(s) for s in row))
                for i, row in enumerate(S)) / len(S)
def clip_loss(S):
    # captions picking images
    columns = [list(col) for col in zip(*S)]
    # ½(L_image→text + L_text→image)
    return (rows_pick_diagonal(S) + rows_pick_diagonal(columns)) / 2
# correctly paired
round(clip_loss([[1, 0], [0, 1]]), 3)  # → 0.313
# captions swapped
round(clip_loss([[0, 1], [1, 0]]), 3)  # → 1.313

In code: clip_loss computes L_CLIP by averaging info_nce_loss over the rows (images pick captions) and the columns (captions pick images). View source

Once trained, the shared space labels images with no classifier. Write a caption for each label ("a photo of a cat", "a photo of a dog"), embed the captions, and give an image the label whose caption is closest. This is zero-shot classification.

Figure 9 · Diagram

Reading it: each modality has its own encoder, and both end in vectors of the same length. The similarity table compares every image with every caption in the batch, and the loss runs along its rows and down its columns. The extra input at the bottom left is a label caption on its way through the text encoder, for zero-shot classification.

A toy version shows it working. Two small linear encoders are trained on made-up "images" and "captions" that describe the same hidden meaning through different, unrelated features. Before training, zero-shot labelling is near chance (20% for five classes); after training it is above 90%.

Figure 10 · Chart

'a photo of class 0' 'a photo of class 1' 'a photo of class 2' 'a photo of class 3' 'a photo of class 4' 0 5 10 15 20 25 30 35 test images, sorted by true class Zero-shot accuracy 92% −0.6 −0.4 −0.2 0.0 0.2 0.4 0.6 0.8 cosine similarity

After training, 36 of the 40 test images are most similar to their own label's caption, forming a diagonal staircase; the 4 misses are mostly classes 0 and 4 mistaken for each other

Reading it: rows are 40 test images sorted by their true class, columns are the five label captions, and brighter means more similar. Each block of rows lights up brightest in its own label's column, a diagonal staircase: the two encoders agree on where each meaning lives. Then look for the rows whose brightest cell sits in the wrong column: 4 of these 40 images are closest to another class's caption, three of them classes 0 and 4 mistaken for each other. Over all 500 held-out test images the accuracy is 92%, the number in the figure's title.

The same shared space lets text search images and images search text, and lets scanned document images and typed text share one retrieval index.

CLIP's training at a size that can be drawn: two numbers per image and per caption.

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

van den Oord, Li and Vinyals, Representation Learning with Contrastive Predictive Coding (2018)

Named and popularised the InfoNCE loss: pick the true sample out of a set of negatives.

The paper
Reimers and Gurevych, Sentence-BERT (2019)

Turned BERT into a bi-encoder that produces one comparable vector per sentence, making semantic search with transformers fast.

Read on rumblr →The paper
Karpukhin et al., Dense Passage Retrieval for Open-Domain Question Answering (2020)

Showed 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 paper
Radford et al., Learning Transferable Visual Models From Natural Language Supervision (CLIP, 2021)

Trained image and text encoders with a symmetric contrastive loss on 400 million pairs, giving zero-shot image classification.

Read on rumblr →The paper
Gao, Yao and Chen, SimCSE (2021)

Showed contrastive learning of sentence embeddings works even with dropout noise as the only "augmentation", and with NLI pairs as hard negatives.

The paper

Researcher'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.