rumblr Work in progressWIP

● The AI Primer · Lesson 3 · Part 1: how a language model works

Loss functions

turning "how wrong were we?" into one number

This lesson covers The one number training pushes down, and why choosing it is choosing the behaviour

Members · open during launch 30 min8 figures and diagrams7 interactive

What this is

What is a loss function?

A loss function turns a machine learning model's mistakes into one number, and training adjusts the AI model to make that number smaller. The AI model learns whatever the number rewards, so the choice of loss decides what it learns. Square each miss, and one wild example can dominate: when four predictions miss by 1 and one misses by 10, the big miss is 96% of the total. Charge each miss by its size instead, and the same miss is 71%. Predicting the next word, predicting a quantity and ranking search results each call for a different loss.

Why it matters: Every training job runs on a loss, and every training curve plots one. The tell that you chose the wrong loss is a number that goes down while the thing you care about does not.

At a glance

Key takeaways

  1. Cross-entropy is −ln(probability on the right answer): small when confident and right, huge when confident and wrong.
  2. Compute it from logits with log-sum-exp; its gradient is softmax − onehot.
  3. Perplexity = e^(average cross-entropy): the effective number of choices per token.
  4. MSE punishes big misses (its best constant guess is the mean); MAE is robust to outliers (its best guess is the median).
  5. Contrastive (InfoNCE) loss is cross-entropy over "which passage in this batch is mine?"; hard negatives carry most of the learning signal.
  6. Label smoothing trains against a target that is never 100% sure, so extreme confidence stops paying.

How it works, from scratch

Training repeats one step. The model makes a prediction, a loss function compares it with the right answer and returns one number, and the weights move a little to make that number smaller (Neural networks walks through the loop). What counts as wrong depends on what is being predicted. A language model picks the next word from its vocabulary, so its loss looks at how much probability it gave the word that actually came next. A price predictor outputs a number, so its loss looks at how far off the number was. A search model matches queries with passages, so its loss looks at whether the right passage scored above the wrong ones.

Figure 1 · Diagram

Reading it: a prediction and the right answer go in on the left, and one number comes out on the right. The branch in between depends on what is predicted: a choice among classes (such as the next token) uses cross-entropy, a number uses squared or absolute error, and a matching pair uses a contrastive loss.

Choose a kind of prediction, then drag it towards the right answer and watch the one number fall.

Chapter 1

Cross-entropy

Start with the first branch, a choice among options. Picture a weather forecaster who gets a bill every evening, charged on the probability they gave to what actually happened. Say "90% chance of rain" and it rains, and the bill is small. Say "1% chance of rain" and it pours, and the bill is large. Cross-entropy is that bill. It looks only at the probability the model gave the right answer, and the less it gave, the more it pays.

The bill is −ln p, where p is that probability. Here it is for four probabilities a model might give the correct next token:

Probability on the correct token Loss (−ln p)
0.9 0.11
0.5 0.69
0.1 2.30
0.01 4.61

Being confidently wrong (1%) costs about 44× as much as being mostly right (90%): 4.61 / 0.105 ≈ 44.

Figure 2 · Chart

0.0 0.2 0.4 0.6 0.8 1.0 probability the model gave the correct answer 0 1 2 3 4 5 loss = −ln p Cross-entropy punishes confident mistakes p=0.9 loss=0.11 p=0.5 loss=0.69 p=0.1 loss=2.30 p=0.01 loss=4.61

The loss −ln p is near zero and flat above 90% but climbs steeply to 4.61 at p = 0.01

Reading it: probability on the right answer runs along the bottom, and the loss it pays runs up the side. Start at the right edge: at p = 1 the loss is 0 and the curve is nearly flat, so going from 90% to 99% saves little. Move left and the curve turns sharply upward, reaching 4.61 at p = 0.01 and growing without limit as p approaches 0. The four marked dots are the rows of the table.

The natural logarithm ln(p) answers "e to what power gives p?" For a probability between 0 and 1 the answer is negative (ln 0.5 = −0.69, because e^−0.69 = 0.5), so we flip the sign to get a positive cost. (Every symbol used in these lessons is built from zero in Math notation, from zero.)

The formula and its symbols

Symbols

Symbol Meaning here In the example
the loss for one prediction 0.69
probability the model gave to the right answer, between 0 and 1 0.5
natural logarithm: the power you'd raise to, to get the input
flips the sign so the loss is positive

In words: "the loss is minus the natural log of the probability the model gave the right answer."

With the numbers: ; .

In Python
import math
p_correct = 0.5
# −ln p_correct
round(-math.log(p_correct), 2)  # → 0.69
# confidently wrong costs far more
round(-math.log(0.01), 2)  # → 4.61

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

In code: cross_entropy_from_prob is this one line. View source

A language model chooses its next token from its whole vocabulary, so cross-entropy on the next token is the loss it is pretrained with. The steep bill for confident mistakes pushes the model towards calibrated probabilities, where its stated confidence matches how often it is right.

Make the forecast yourself, choose the weather, and read the bill.

Chapter 2

Computing cross-entropy from logits

Cross-entropy needs the probability the model gave the right answer, but a model does not output probabilities. It outputs raw scores called logits, one per class, and softmax turns them into probabilities: raise e to each score and divide by the total (see Attention). Done literally, that breaks on large scores. A 64-bit floating-point number cannot hold e^1000, so a logit of 1000 overflows before the division happens. The fix, log-sum-exp, subtracts the largest logit from every logit first. The largest exponent is then e^0 = 1, nothing overflows, and the loss comes out the same.

Take logits (2, 1, 0.1) with the first class (class 0) correct. e² + e¹ + e^0.1 = 7.389 + 2.718 + 1.105 = 11.212, ln 11.212 = 2.417, so the loss is 2.417 − 2 = 0.417. With logits (1000, 0) and the second class (class 1) correct, log-sum-exp gives 1000 − 0 = 1000 without ever computing e^1000.

Figure 3 · Diagram

Reading it: solid arrows are the forward pass, which computes the loss; dotted arrows are the backward pass, which works out how each logit should move. Going forward, the logits never pass through a separate softmax: the largest logit is subtracted first, and the loss is the log of the total minus the right class's score. Coming back, each class's gradient is its predicted probability, minus 1 for the correct class. So the right logit is pushed up by 1 − p, and each wrong logit is pushed down by the probability it took.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the logits, one raw score per class (2, 1, 0.1)
the score of class
the index of the correct class 0
the probability softmax gives the correct class 7.389 / 11.212 = 0.659
"add up over every class " three terms
e ≈ 2.718 raised to the score
the largest logit, subtracted for safety 2
"the biggest value over all " 2

In words: "the loss is the log of the sum of e-to-every-score, minus the correct class's score; to compute that log safely, pull the biggest score out front first."

With the numbers: ; ; ; so log-sum-exp and the loss is (and too).

In Python
import math
def log_sum_exp(z):
    # m = max_j z_j
    m = max(z)
    # m + ln Σ_j e^(z_j − m)
    return m + math.log(sum(math.exp(z_j - m) for z_j in z))
z, y = [2.0, 1.0, 0.1], 0
round(log_sum_exp(z), 3)  # → 2.417
# ln Σ_j e^(z_j) − z_y
round(log_sum_exp(z) - z[y], 3)  # → 0.417
z, y = [1000.0, 0.0], 1
# e^1000 is never computed: no overflow
log_sum_exp(z) - z[y]  # → 1000.0

The gradient says how each logit should move:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the gradient: one slope per logit (0.25, −0.25)
the predicted probabilities (0.25, 0.75) for logits (0, ln 3)
1 at the correct class, 0 elsewhere (0, 1)

In words: "each logit's slope is its predicted probability, minus one if it's the right answer."

With the numbers: logits (0, ln 3) give softmax (1/4, 3/4); with class 1 correct, the gradient is (0.25 − 0, 0.75 − 1) = (0.25, −0.25).

In Python
import math
z, y = [0.0, math.log(3)], 1
exps = [math.exp(z_j) for z_j in z]
# (1/4, 3/4)
softmax = [e / sum(exps) for e in exps]
# (0, 1)
onehot = [1 if j == y else 0 for j in range(len(z))]
# softmax(z) − onehot(y)
[round(s_j - o_j, 2) for s_j, o_j in zip(softmax, onehot)]  # → [0.25, -0.25]

In code: softmax_cross_entropy returns a batch's mean loss and this gradient, computed with log_sum_exp and log_softmax. View source

Deep learning frameworks therefore fuse softmax and cross-entropy into one operation that takes logits (torch.nn.functional.cross_entropy). Taking the softmax first and the log afterwards is a common cause of a loss that turns into NaN.

Set the logits, then scale them up until the direct computation overflows, and watch each logit's push.

Chapter 3

Perplexity

Training a language model averages this loss over every token of text, and an average of −ln p is hard to picture. Perplexity turns it back into a count. Picture a row of doors with a prize behind one. A model as unsure as someone choosing between two doors at random has perplexity 2; between ten doors, 10. Perplexity is e raised to the average loss.

A model that gives the right token 50% every time has loss 0.69 per token and perplexity e^0.69 = 2. One that gives 10% every time has perplexity 10. Three confident tokens (0.9) and one disaster (0.001) give perplexity about 6: one bad token outweighs three good ones.

Figure 4 · Diagram

Reading it: follow the boxes left to right. Each token's probability becomes a loss with −ln, the losses are averaged, and e^x undoes the log. What comes out is a number of equally likely options.
The formula and its symbols

Symbols

Symbol Meaning here In the example
perplexity 2
number of tokens 3
a counter over the tokens 1, 2, 3
probability given to the correct token at position 0.5 each
"the average over all tokens"
another way to write

In words: "perplexity is e raised to the average cross-entropy per token."

With the numbers: .

In Python
import math
p = [0.5, 0.5, 0.5]
N = len(p)
# (1/N) Σ −ln p_i
average = sum(-math.log(p_i) for p_i in p) / N
round(average, 2)  # → 0.69
# exp(...)
round(math.exp(average), 1)  # → 2.0

In code: perplexity averages cross_entropy_from_prob over the tokens and raises e to the result. View source

Perplexity is the usual way to report a language model's loss during training. Two perplexities can be compared only when the models use the same tokenizer on the same text, and neither says directly whether the model's answers are helpful or correct.

Set the probability on each of four tokens and count the doors.

Chapter 4

Regression losses: MSE and MAE

Cross-entropy scores a choice among options. When the prediction is a number, such as a price or a temperature, the loss scores how far off it was, and there are two common ways to charge for the distance. Think of fines for arriving late. MAE (mean absolute error) is a flat rate: every minute late costs the same. MSE (mean squared error) squares the minutes, so 10 minutes late costs 100, not 10, and one very late arrival outweighs many slightly late ones.

Say four predictions miss by 1 and one misses by 10. MSE = (1 + 1 + 1 + 1 + 100) / 5 = 20.8, and the outlier is 100/104 = 96% of it. MAE = (1 + 1 + 1 + 1 + 10) / 5 = 2.8, and the outlier is 10/14 = 71%.

Figure 5 · Chart

−4 −2 0 2 4 error y − ŷ 0.0 2.5 5.0 7.5 10.0 12.5 15.0 penalty Penalty per error squared (MSE) absolute (MAE) 0 2 4 6 8 10 12 constant prediction c 0.4 0.5 0.6 0.7 0.8 0.9 1.0 loss (scaled to max 1) Data 1,2,2,3,3,4 and outlier 20 MSE (min at mean 5.0) MAE (min at median 3)

The squared penalty pulls away past an error of 1, and one outlier drags MSE's best constant to the mean 5.0 while MAE's stays at the median 3

Reading it: the left panel is the fine for a single error. Near zero the two curves are close, and past an error of 1 the squared fine climbs away from the absolute one. The right panel asks which one constant a model should predict for the data 1, 2, 2, 3, 3, 4 plus an outlier of 20, if it may predict only one. MSE's valley sits at the mean (5.0), dragged right by the outlier; MAE's valley sits at the median (3), where most of the data is.
The formula and its symbols

Symbols

Symbol Meaning here In the example
number of predictions 5
the true value for example 0 for all five
"y-hat", the predicted value 1, −1, 1, −1, 10
the error (residual) −1, 1, −1, 1, −10
square: multiply by itself (always positive)
absolute value: drop the sign

In words: "MSE is the average of the squared errors; MAE is the average of the errors ignoring their sign."

With the numbers: MSE ; MAE .

In Python
y = [0, 0, 0, 0, 0]
y_hat = [1, -1, 1, -1, 10]
N = len(y)
# MSE
sum((y_i - y_hat_i) ** 2 for y_i, y_hat_i in zip(y, y_hat)) / N  # → 20.8
# MAE
sum(abs(y_i - y_hat_i) for y_i, y_hat_i in zip(y, y_hat)) / N  # → 2.8

In code: mse and mae compute the two averages, and outlier_share the 96% and 71%. View source

So choose the loss whose valley sits where you want the predictions. MSE follows outliers, because its best constant is the mean. MAE resists them, because its best constant is the median. For noisy data with occasional wild values, MAE or a blend of the two (Huber loss) is the safer choice.

Drag the outlier and the constant guess, and watch which valley moves.

Chapter 5

Contrastive loss (InfoNCE)

The third branch is a match: which passage answers this query? A contrastive loss turns the match into a choice among options, so that cross-entropy can score it. Picture a party game. Guests arrive in pairs and are separated, and each must pick their partner out of the whole room, where everyone else is a decoy. The loss scores how confidently each guest picks their own partner over every decoy.

Embedding models, such as those behind search and CLIP, learn this way. A query and the passage that answers it are partners, and the other passages in the same batch serve as decoys at no extra cost (in-batch negatives). A decoy that closely resembles the right partner, such as a passage on the same topic that does not answer the question, is a hard negative.

Take two queries and two passages as vectors, scored with the dot product (multiply matching entries, add them up). Query 1 = (1, 0), query 2 = (0, 1), passage 1 = (1, 0), passage 2 = (0, 1). Every score is divided by a temperature before the softmax; here it is 1, and a smaller one makes the choice sharper. Query 1 scores 1 against its partner and 0 against the decoy, so its loss is −ln(e¹ / (e¹ + e⁰)) = ln(1 + e^−1) = 0.3133. Swap the passages and each query prefers the decoy: the loss rises to ln(1 + e¹) = 1.3133.

Figure 6 · Diagram

Reading it: every query in a batch is scored against every passage, which gives a square grid. Each row becomes a classification ("which of these passages is mine?") whose right answer is on the diagonal. Cross-entropy on each row pulls the query towards its own passage and away from all the others at once.

Figure 7 · Chart

0 1 2 3 4 document j −0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 query i InfoNCE: softmax over each row (τ = 0.1) 0.92 0.05 0.03 0.00 0.00 0.01 0.95 0.00 0.03 0.00 0.00 0.02 0.07 0.00 0.91 0.00 0.00 0.00 1.00 0.00 0.0 0.2 0.4 0.6 0.8 1.0

Rows 0, 1 and 3 put over 0.9 on their own passage; row 2 puts 0.91 on the hard negative and only 0.07 on its own

Reading it: rows are queries and columns are passages, both numbered from 0, and each cell is the probability that query i picks passage j. A well-trained model shows a bright diagonal, as rows 0, 1 and 3 do. Row 2 does not: it puts most of its probability on column 4, an extra hard negative built to resemble query 2, and only a few percent on its own passage in column 2. That row is where the loss, and therefore the gradient, is concentrated. Rows 0, 1 and 3 are already confident and add almost nothing to learning.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the loss for query 0.3133
query 's vector
query 's own passage (its positive)
passage : every passage in the batch, the positive included
dot product: how aligned query and passage are ,
"tau", the temperature: divides scores; small sharpens, large softens 1
number of passages scored (batch plus any extra negatives) 2
raised to the power

In words: "for each query, take e-to-the-score of its own passage, divide by the sum of e-to-the-score over every passage in the batch, and charge minus the log of that share."

With the numbers: . At temperature 0.1 the same vectors give : sharper.

In Python
import math
# the queries
q = [[1, 0], [0, 1]]
# their passages: d[i] is q[i]'s partner
d = [[1, 0], [0, 1]]
def dot(a, b):
    return sum(a_k * b_k for a_k, b_k in zip(a, b))
def info_nce(i, tau):
    # exp(q_i · d_j / τ) for every j
    scores = [math.exp(dot(q[i], d_j) / tau) for d_j in d]
    # −ln (own passage's share)
    return -math.log(scores[i] / sum(scores))
round(info_nce(0, tau=1.0), 4)  # → 0.3133
print(f"{info_nce(0, tau=0.1):.6f}")  # → 0.000045

Each row is a cross-entropy, so the gradient is the same softmax − onehot, passed back through the dot products into the query and passage vectors.

In code: info_nce scores the grid with softmax_cross_entropy and returns the gradients for both sets of vectors; info_nce_gradient_check checks them against small nudges. View source

Search and RAG embedding models are trained this way (see Training embedding models). A bigger batch brings more negatives for free. Easy negatives are already far from the query and contribute almost no gradient, while hard negatives produce most of the learning signal, which is why retrieval training goes looking for them (mining hard negatives).

Two queries and their passages on a circle: drag the passages and watch which one each query picks.

Chapter 6

Label smoothing

Back to cross-entropy, and to the forecaster. Cross-entropy's bill keeps falling as the probability on the right answer approaches 100%, so a model trained on it gains by pushing the right logit towards infinity. A careful forecaster never says "100% chance of rain". Label smoothing asks the same of a model, by changing the target instead of the loss. The target no longer says "the answer is this class, with total certainty" but "this class, with 92.5% certainty, and a little doubt spread over every class".

With 4 classes, the third one correct, and smoothing ε = 0.1: take 0.9 of the one-hot target, (0, 0, 0.9, 0), and add 0.1/4 = 0.025 to every class, giving (0.025, 0.025, 0.925, 0.025). A model that puts logit 50 on the right class and 0 on the others has plain cross-entropy ≈ 0, but smoothed cross-entropy 3 × 0.025 × 50 = 3.75.

Figure 8 · Diagram

Reading it: the one-hot label and an even spread over all K classes are blended with weight ε, giving a target that is 92.5% sure and never 100%. Against that target the loss can never reach zero, so pushing the logits towards infinity no longer pays.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the smoothed target distribution (0.025, 0.025, 0.925, 0.025)
"epsilon", how much certainty to give away 0.1
number of classes 4
a counter over the classes 1 to 4
target weight on class 0.925 on the right class
predicted probability of class ≈1 on the right class

In words: "the target keeps (1 − ε) on the right answer and spreads ε evenly over all classes; the loss is cross-entropy against that softer target."

With the numbers: on the right class and elsewhere; with logits (0, 0, 50, 0) the three wrong classes each have , so .

In Python
import math
eps, K, y = 0.1, 4, 2
# t_k
t = [(1 - eps) * (1 if k == y else 0) + eps / K for k in range(K)]
[round(t_k, 3) for t_k in t]  # → [0.025, 0.025, 0.925, 0.025]
z = [0.0, 0.0, 50.0, 0.0]
m = max(z)
log_total = m + math.log(sum(math.exp(z_k - m) for z_k in z))
# ln softmax(z)_k
log_softmax = [z_k - log_total for z_k in z]
# −Σ_k t_k ln softmax(z)_k
round(-sum(t_k * ls_k for t_k, ls_k in zip(t, log_softmax)), 2)  # → 3.75

In code: smoothed_targets builds the soft target t, and smoothed_cross_entropy scores the logits against it. View source

Label smoothing curbs over-confidence and often improves calibration. It was used to train the original transformer.

Set ε and the number of classes, then push the right logit up and compare the two losses.

Test yourself

6 questions

Answer each one out loud or on paper before you open it.

Question 1The model puts 1% on the right token. What's the loss, and why so large?Think it through, then reveal

−ln(0.01) = 4.61, about 44× the loss at 90% (0.105). The log punishes confident mistakes steeply, which pushes the model toward calibrated probabilities.

Question 2Loss is 0.69 per token. What's the perplexity?Think it through, then reveal

e^0.69 = 2: as uncertain as a coin flip between two options.

Question 3Why compute cross-entropy from logits instead of from softmax outputs?Think it through, then reveal

Softmax of large logits overflows, and the log of a tiny probability underflows to −∞. Log-sum-exp subtracts the max first and never exponentiates a large number. The fused gradient is simply softmax − onehot.

Question 4When would you pick MAE over MSE?Think it through, then reveal

When outliers are noise you don't want to chase. MSE squares errors, so one huge miss dominates; MAE weighs errors linearly.

Question 5How does InfoNCE get negatives without labelling them?Think it through, then reveal

It uses the other items in the batch: for each query, every other query's positive passage is a negative. Bigger batches mean more (and harder) negatives for free.

Question 6Why do hard negatives matter?Think it through, then reveal

Easy negatives are already far away and contribute almost no gradient. Hard negatives score high and produce most of the learning signal, teaching the model to separate "on topic" from "actually answers the question".

Primary sources

The papers behind this lesson

van den Oord, Li & Vinyals, Representation Learning with Contrastive Predictive Coding (2018): Named and analysed InfoNCE, the "pick the positive out of N" contrastive loss.

The paper

Chen et al., A Simple Framework for Contrastive Learning of Visual Representations (SimCLR, 2020): Showed how much in-batch negatives, large batches and the temperature matter for contrastive training.

The paper

Radford et al., Learning Transferable Visual Models From Natural Language Supervision (CLIP, 2021): Trained image and text encoders with a symmetric InfoNCE loss on 400 million pairs, putting both in one vector space.

Read on rumblr →The paper

Szegedy et al., Rethinking the Inception Architecture for Computer Vision (2015): Introduced label smoothing as a regularizer against over-confident predictions.

The paper

Researcher's shelf

Further reading

  • Goodfellow, Bengio & Courville, Deep Learning, ch. 6 (cost functions): https://www.deeplearningbook.org/contents/mlp.html
  • CS231n notes, Linear classification (softmax and cross-entropy): https://cs231n.github.io/linear-classify/
  • PyTorch cross_entropy: https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html
  • van den Oord et al., Representation Learning with Contrastive Predictive Coding (InfoNCE, 2018): https://arxiv.org/abs/1807.03748
  • Chen et al., SimCLR (in-batch negatives and temperature, 2020): https://arxiv.org/abs/2002.05709
  • Radford et al., CLIP (2021): https://arxiv.org/abs/2103.00020
  • Szegedy et al., Rethinking the Inception Architecture (label smoothing, 2015): https://arxiv.org/abs/1512.00567
  • Müller et al., When Does Label Smoothing Help? (2019): https://arxiv.org/abs/1906.02629

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.