Part 5: Large language models Lesson 9 of 10 in this part
How embedding models are trained
What you will learn. Explain how an embedding model learns to place related texts close together, work out cosine similarity and the contrastive loss for a small batch by hand, and say why the choice of negatives and the temperature matter.
Before this lesson: Embeddings and vector search, How large language models work. Already know these? Carry on.
In plain words
An embedding model turns a piece of text into a short list of numbers so that texts with similar meaning get similar lists. The earlier lesson on embeddings used such a model. This lesson shows how one is made. A transformer reads the text and produces one vector per token. A pooling step, usually the average of the token vectors, turns them into one vector for the whole text. Training then needs examples of what should be close: a question and its answer, a title and its article, two paraphrases. In a batch of such pairs, every other answer is treated as a wrong answer, called a negative. The contrastive loss (often called InfoNCE) rewards the model when each question is closest to its own answer and far from the others. A setting called the temperature controls how sharply the loss punishes a wrong ranking.
- InputCollect pairs that should be closeQuestion and answer, title and article
- ModelEmbed both sides with the same networkPool the token vectors to one vector
- ProcessCompare every question with every answerA table of cosine similarities
- OutputUpdate the network to raise the diagonalOwn answers closer, others farther
The model only ever sees which pairs belong together. Everything else follows from that.
Easy negatives
- Answers to unrelated questions
- Quickly learned, teach little after that
Hard negatives
- Answers that look close but are wrong
- Teach fine differences
- May include unlabelled true matches
Hard negatives teach the model fine differences. Too hard, and they may be real matches.
Low temperature
- Sharp: a wrong ranking is punished hard
- Can make training unstable
High temperature
- Gentle: all answers share the probability
- Learns slowly and less sharply
A small temperature makes the loss look at the gap between the best and the rest.
Real-world example
A company wants search over its support articles. A general embedding model finds articles on the right topic but often ranks the wrong one first, because many articles are alike. The team collects pairs of real customer questions and the article that solved each, and fine-tunes the embedding model on them with a contrastive loss, using the other articles in each batch as negatives and a few look-alike articles as hard negatives. They measure how often the right article is first (top-1 accuracy) on questions the model did not see, and compare with the general model. They also check that the fine-tuned model still handles questions about topics that were not in the training pairs.
How it works
- Embed. Pass each text through the network and average the token vectors to get one vector. Scale each vector to length one.
- Compare. The cosine similarity of two unit vectors is their dot product. Compute it for every question against every answer in the batch.
- Loss. Divide the similarities by the temperature, turn each row into probabilities with a softmax, and take minus the logarithm of the probability given to the right answer. Average over the batch.
- Update. Gradient descent changes the network so that the right answers' similarities rise and the others fall.
- Use. At search time, embed the query once, compare with stored vectors, and return the nearest. Larger batches mean more negatives, which usually helps.
Live simulation
An embedding is a set of numbers learned so that related items sit close together. You can watch that learning happen.
The question. How does a model learn to place related words close together without anyone telling it what the words mean?
What to watch
- Each dot is a word on a 2-D map. Each word is pulled toward one partner from its topic and pushed away from words of other topics.
- The readout counts how many words have a nearest neighbour from their own topic. It starts near chance.
- Change the temperature. A low value makes the loss care mostly about the closest wrong word; a high value spreads its care over all wrong words.
This simulation needs JavaScript, which is switched off or not loaded. The lists above say what it shows, and the example programs below print the same kind of numbers.
Try this
- Train until every word's nearest neighbour is from its own topic.
What this leaves out. Twelve words and two numbers per word; the pairs come from the topics we wrote down. Real embedding models have hundreds of numbers per word, learn from pairs found in large amounts of text or from labelled examples, and use other words in the same batch as the wrong ones.
Python program that prints the same headline numbers: examples/sim-llm/llm.py.
Python example
Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.
Mean pooling of three token vectors, then the cosine similarity table and the contrastive loss for three question and answer pairs, before and after training. The vectors are fixed by hand, so this shows the loss, not a trained network. No neural framework was run.
"""How an embedding model is trained: mean pooling, cosine similarity and the contrastive (InfoNCE) loss.
Three question and answer pairs are turned into short vectors. The loss is low when each question is closest to its own
answer and far from the other answers in the batch. The vectors are fixed by hand so the numbers repeat.
Run: python embed_train.py (needs numpy)
"""
import numpy as np
print("mean pooling of three token vectors:", np.mean([[1, 2], [3, 4], [5, 0]], axis=0).tolist())
Q = np.array([[1.0, 0.2, 0.0], [0.1, 1.0, 0.3], [0.0, 0.3, 1.0]]) # question vectors
A_before = np.array([[0.4, 0.9, 0.1], [0.9, 0.3, 0.2], [0.2, 0.5, 0.8]]) # answer vectors from an untrained model
A_after = np.array([[1.0, 0.3, 0.1], [0.2, 1.0, 0.2], [0.1, 0.2, 1.0]]) # the same answers after training
def unit(M):
return M / np.linalg.norm(M, axis=1, keepdims=True)
def report(name, A, tau=0.1):
sim = unit(Q) @ unit(A).T # cosine similarity of every question with every answer
logits = sim / tau
probs = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True)
loss = float(-np.log(np.diag(probs)).mean()) # InfoNCE: each question should pick its own answer
hits = float(np.mean(sim.argmax(axis=1) == np.arange(3)))
print(name + ": similarity of question i with answer j")
for row in sim:
print(" " + " ".join("%.2f" % v for v in row))
print(" loss %.3f, top-1 accuracy %.2f" % (loss, hits))
report("before training", A_before)
report("after training ", A_after)mean pooling of three token vectors: [3.0, 2.0]
before training: similarity of question i with answer j
0.57 0.97 0.31
0.93 0.44 0.75
0.36 0.29 0.94
loss 3.020, top-1 accuracy 0.33
after training : similarity of question i with answer j
0.99 0.38 0.13
0.39 0.99 0.47
0.17 0.46 0.99
loss 0.005, top-1 accuracy 1.00Before training, the first question is most similar to the second answer (0.97), not its own (0.57), and only one question in three finds its own answer (accuracy 0.33). The loss is 3.020. After training, every question is closest to its own answer (accuracy 1.00) and the loss is 0.005.
.NET (C#) example
C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.
The same pooling, similarity and loss written from scratch in C#, with no packages, printing the same output. To use an embedding model from C#, call a hosted embedding service through Microsoft.Extensions.AI, or run an exported ONNX model with ONNX Runtime. Training an embedding model is done in Python.
// Mean pooling, cosine similarity and the contrastive (InfoNCE) loss, from scratch. Same output as embed_train.py. No packages.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
double[][] tokens = { new[] { 1.0, 2.0 }, new[] { 3.0, 4.0 }, new[] { 5.0, 0.0 } };
var pooled = Enumerable.Range(0, 2).Select(k => tokens.Average(t => t[k])).ToArray();
Console.WriteLine("mean pooling of three token vectors: [" + string.Join(", ", pooled.Select(v => v.ToString("0.0"))) + "]");
double[][] Q = { new[] { 1.0, 0.2, 0.0 }, new[] { 0.1, 1.0, 0.3 }, new[] { 0.0, 0.3, 1.0 } }; // question vectors
double[][] aBefore = { new[] { 0.4, 0.9, 0.1 }, new[] { 0.9, 0.3, 0.2 }, new[] { 0.2, 0.5, 0.8 } }; // untrained answers
double[][] aAfter = { new[] { 1.0, 0.3, 0.1 }, new[] { 0.2, 1.0, 0.2 }, new[] { 0.1, 0.2, 1.0 } }; // after training
double[] Unit(double[] v) { double n = Math.Sqrt(v.Sum(x => x * x)); return v.Select(x => x / n).ToArray(); }
void Report(string name, double[][] A, double tau = 0.1)
{
var q = Q.Select(Unit).ToArray(); var a = A.Select(Unit).ToArray();
var sim = q.Select(qi => a.Select(aj => qi.Zip(aj, (x, y) => x * y).Sum()).ToArray()).ToArray(); // cosine similarity of every question with every answer
double loss = 0; int hits = 0;
for (int i = 0; i < 3; i++)
{
var e = sim[i].Select(s => Math.Exp(s / tau)).ToArray();
loss += -Math.Log(e[i] / e.Sum()); // InfoNCE: each question should pick its own answer
if (Array.IndexOf(sim[i], sim[i].Max()) == i) hits++;
}
Console.WriteLine(name + ": similarity of question i with answer j");
foreach (var row in sim) Console.WriteLine(" " + string.Join(" ", row.Select(v => v.ToString("F2"))));
Console.WriteLine($" loss {loss / 3:F3}, top-1 accuracy {hits / 3.0:F2}");
}
Report("before training", aBefore);
Report("after training ", aAfter);Maths behind it
- Averages of vectors (mean pooling)
- Dot product, vector length and cosine similarity (linear algebra)
- Softmax and the negative logarithm of a probability (probability)
- Exponentials with a temperature scale (algebra)
Common mistakes
- Using negatives that are really true matches, which teaches the model the wrong thing.
- Training with very small batches, so there are too few negatives.
- Using different pooling or normalisation at search time than at training time.
- Judging the model on the training pairs. Use questions it has not seen.
- Forgetting to check that a fine-tuned model has not lost its general ability.
Quick check
What does pooling do in an embedding model?
Show answer
It turns the many token vectors of a text into one vector, most often by taking their average.
What are the "negatives" in a batch of question and answer pairs?
Show answer
Every answer that belongs to a different question. The loss pushes each question away from them.
Why divide similarities by a small temperature in the loss?
Show answer
It sharpens the softmax, so the model is punished hard when a wrong answer outranks the right one.
The loss fell from 3.020 to 0.005 in the example. What else changed?
Show answer
Top-1 accuracy rose from 0.33 to 1.00, because every question became closest to its own answer.
Completion
Evidence of completion. The cosine similarity table for a batch of three question and answer pairs before and after training, with the contrastive loss and top-1 accuracy for each, and a sentence on what changed.
Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.