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
- Cross-entropy is −ln(probability on the right answer): small when confident and right, huge when confident and wrong.
- Compute it from logits with log-sum-exp; its gradient is softmax − onehot.
- Perplexity = e^(average cross-entropy): the effective number of choices per token.
- MSE punishes big misses (its best constant guess is the mean); MAE is robust to outliers (its best guess is the median).
- Contrastive (InfoNCE) loss is cross-entropy over "which passage in this batch is mine?"; hard negatives carry most of the learning signal.
- 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
flowchart LR
P[Prediction] --> LF{Loss function}
T[Right answer] --> LF
LF -->|classes or tokens| CE[Cross-entropy]
LF -->|numbers| REG[MSE or MAE]
LF -->|matching pairs| CON[Contrastive / InfoNCE]
CE & REG & CON --> N[One number to minimize]
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
The loss −ln p is near zero and flat above 90% but climbs steeply to 4.61 at p = 0.01
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.
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
flowchart LR Z[Logits z<br/>one score per class] --> M[Subtract max m] M --> LSE[log-sum-exp<br/>m + ln sum e^z-m] LSE --> L[Loss = LSE minus z_correct] Z --> L L -.backward.-> G[Gradient = softmax z<br/>minus one-hot target] G -.-> U[Raise the right logit,<br/>lower the others by their probability]
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.
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
flowchart LR P["Per-token probabilities<br/>0.5, 0.5, 0.5"] --> NL["−ln each<br/>0.69, 0.69, 0.69"] NL --> AV["Average<br/>0.69"] AV --> EX["e to that power<br/>e^0.69 = 2"] EX --> D["≈ choosing between<br/>2 equally likely doors"]
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.
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
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
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.
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
flowchart LR Q[Batch of queries] --> S[Score matrix<br/>every query vs every passage] D[Their matching passages] --> S S --> CE[Cross-entropy per row<br/>right answer = the diagonal] CE --> L[Pull pairs together<br/>push the rest apart]
Figure 7 · Chart
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
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).
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
flowchart LR O[One-hot target<br/>0, 0, 1, 0] --> MIX[Mix: 1 minus eps times one-hot<br/>plus eps/K everywhere] U[Uniform over K classes] --> MIX MIX --> T[Soft target<br/>0.025, 0.025, 0.925, 0.025] T --> CE[Cross-entropy against<br/>the soft target]
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.
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 paperChen 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 paperRadford 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 paperSzegedy et al., Rethinking the Inception Architecture for Computer Vision (2015): Introduced label smoothing as a regularizer against over-confident predictions.
The paperResearcher'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.