---
layout: post
title: "Cross-Entropy Loss Explained: From Logits to LLM Training"
date: 2026-06-14
tags: ["Training & Optimization", "From Scratch"]
category: "ai"
description: "What is cross-entropy loss? Derive softmax and negative log-likelihood, work a 3-class example, and see why MSE fails for language model classification."
keywords: "cross entropy loss explained, softmax cross entropy, negative log likelihood, classification loss, language model loss, cross entropy from scratch, why not MSE for classification"
image: /assets/images/og-cross-entropy-loss.png
---

I used to think cross-entropy was "the loss PyTorch picks for classification". `nn.CrossEntropyLoss()` is the default for a reason, but when I wired up pretraining for [AL-1](/blog/build-autograd-from-scratch/), I had to implement the backward pass myself. That showed me the choice is not arbitrary: cross-entropy is the negative log-likelihood of the correct class, so minimizing it is maximum likelihood. For next-token prediction, it penalizes wrong probability mass in the way that likelihood requires.

This post assumes you have working autograd and have run [numerical gradient checking](/blog/numerical-gradient-checking-explained/). It turns model outputs into a scalar you can minimize, derives the gradient, and shows the cancellation that makes softmax plus cross-entropy simple to implement.

---

## Why doesn't MSE work for classification?

Mean squared error (MSE) on one-hot targets sounds reasonable until you try it.

Take three classes with logits $z = [2.0,\, 1.0,\, 0.1]$ and true label $y = 0$. The one-hot target is $t = [1, 0, 0]$. The softmax probabilities are:

$$
p = \mathrm{softmax}(z) \approx [0.659,\, 0.242,\, 0.099]
$$

MSE loss:

$$
L_{\mathrm{MSE}} = \frac{1}{3}\sum_i (p_i - t_i)^2
$$

$$
L_{\mathrm{MSE}} \approx \frac{(0.659-1)^2 + (0.242)^2 + (0.099)^2}{3} \approx 0.062
$$

The model already assigns 66% to the correct class, and MSE is small. In the L2 sense, $0.66$ and $0.99$ are both close to $1.0$, so MSE barely separates them. For classification I care about **confidence on the right class** and **suppressing wrong classes**. Cross-entropy punishes low probability on the true label much harder:

$$
L_{\mathrm{CE}} = -\log p_y = -\log(0.659) \approx 0.417
$$

This loss is still moderate, but the gradient structure matters more than the value. MSE with softmax gives messy, vanishing gradients when the model is confidently wrong. Cross-entropy with softmax gives a clean $p - t$ residual. That is why language models use it.

I plotted both losses against the true-class logit. The other two logits stay at 1.0 and 0.1. The dashed line at $z_0 = 2$ is the example I just worked.

{% include fig.html src="cross-entropy-loss-explained/mse-vs-ce.svg" alt="Line chart of MSE and cross-entropy against the true-class logit. MSE flattens near 0.5 as the logit falls. Cross-entropy keeps rising." caption="As $z_0$ falls, MSE flattens out, so its gradient shrinks. Cross-entropy keeps rising." %}

```mermaid
flowchart LR
  LOG["Logits z"] --> SM["softmax"]
  SM --> P["probs p"]
  P --> CE["−log p_y"]
  TGT["target y"] --> CE
  CE --> L["scalar loss L"]
```

---

## What is cross-entropy, intuitively?

Cross-entropy measures how surprised the model's distribution should be by the true label.

If the model says $p(\text{cat}) = 0.9$ and the label is cat, the surprise is low: $-\log 0.9 \approx 0.105$. If the model says $p(\text{cat}) = 0.01$ and the label is cat, the surprise is large: $-\log 0.01 \approx 4.605$.

For a single example with true class $y$ and predicted probabilities $p$:

$$
L = -\log p_y
$$

The log does two jobs. It turns multiplication of probabilities into addition, which matters for long sequences. It also grows without bound as $p_y \to 0$, which is the penalty I want.

---

## How do you derive softmax?

The model outputs raw scores $z \in \mathbb{R}^C$, one logit per class. I need a probability vector $p$ that sums to 1.

First exponentiate, which makes every entry positive:

$$
\tilde{p}_i = e^{z_i}
$$

Then normalize:

$$
p_i = \frac{e^{z_i}}{\sum_j e^{z_j}}
$$

I always subtract the max before exponentiating so that nothing overflows. The result is unchanged, because the factor $e^{-m}$ cancels between numerator and denominator.

$$
m = \max_j z_j
$$

$$
p_i = \frac{e^{z_i - m}}{\sum_j e^{z_j - m}}
$$

For $C = 3$ logits $z = [2.0,\, 1.0,\, 0.1]$:

$$
m = 2.0
$$

$$
e^{z - m} = [e^0,\, e^{-1},\, e^{-1.9}] = [1.0,\, 0.368,\, 0.150]
$$

$$
\sum = 1.518
$$

$$
p = [0.659,\, 0.242,\, 0.099]
$$

Now I add a large constant $c$ to every logit. The naive formula overflows once $z_i + c$ passes about 709. The shifted version gives the same $p$ at every $c$.

{% include fig.html src="cross-entropy-loss-explained/softmax-overflow.svg" alt="Two tables comparing naive softmax and shifted softmax. At c equals 0 they match. At c equals 800 the naive row overflows and the shifted row is unchanged." caption="At $c = 0$ the shifted row is the $p$ I computed above. At $c = 800$ the naive row fails and the shifted row does not change." %}

---

## How do you combine softmax and cross-entropy?

For one example with true index $y$:

$$
L = -\log p_y = -\log \frac{e^{z_y}}{\sum_j e^{z_j}}
$$

Expand:

$$
L = -z_y + \log\sum_j e^{z_j}
$$

The second term is the **log-sum-exp** (LSE). I implement this form in code. The forward pass does not need to materialize $p$ unless I want probabilities for inspection.

For a batch of $N$ examples, the mean loss is:

$$
L = \frac{1}{N}\sum_{n=1}^{N} \left( \log\sum_j e^{z_{nj}} - z_{n,y_n} \right)
$$

Language models use the same loss with more dimensions. Logits have shape $(B, T, V)$ and targets have shape $(B, T)$, so each position is an independent classification over a vocabulary of size $V$. GPT-2 small has $V = 50257$. The loss is averaged over all non-masked token positions.

---

## What is the gradient? (The cancellation)

This is the part that made the implementation make sense to me. Define $p = \mathrm{softmax}(z)$. For one example:

$$
\frac{\partial L}{\partial z_i} = p_i - \mathbb{1}[i = y]
$$

The gradient is the predicted probability minus the one-hot target. The correct class gets $p_y - 1$, which is negative when $p_y < 1$, so a gradient descent step raises that logit. Each wrong class gets $p_i$, which is positive, so a step lowers those logits.

As a check, take $p = [0.659, 0.242, 0.099]$ and $y = 0$:

$$
\frac{\partial L}{\partial z} = [0.659 - 1,\, 0.242,\, 0.099] = [-0.341,\, 0.242,\, 0.099]
$$

The true-class logit should increase and the others should decrease, which is what the signs say.

The result follows from the chain rule applied to $L = -z_y + \mathrm{LSE}(z)$:

$$
\frac{\partial L}{\partial z_i} = -\mathbb{1}[i=y] + \frac{e^{z_i}}{\sum_j e^{z_j}} = p_i - \mathbb{1}[i=y]
$$

There is no separate softmax Jacobian multiplied by a cross-entropy gradient: the two collapse into one expression. In autograd I can fuse the ops and implement a single backward kernel. I fused them in AL-1's `cross_entropy`, and [gradcheck](/blog/numerical-gradient-checking-explained/) passed on the first try.

```mermaid
flowchart TB
  subgraph "Backward at one logit z_i"
    PY["p_y"] --> GY["∂L/∂z_y = p_y − 1"]
    PI["p_i (i≠y)"] --> GI["∂L/∂z_i = p_i"]
  end
```

---

## A full numeric walk-through (3 classes)

Logits $z = [1.0,\, 3.0,\, 0.5]$, true label $y = 1$ (middle class).

**Step 1: stable softmax**

$$
m = 3.0
$$

$$
e^{z-m} = [e^{-2},\, e^{0},\, e^{-2.5}] = [0.135,\, 1.0,\, 0.082]
$$

$$
Z = 1.2174
$$

$$
p = [0.111,\, 0.821,\, 0.067]
$$

**Step 2: loss**

$$
L = -\log p_1 = -\log(0.8214) \approx 0.196
$$

**Step 3: gradient**

$$
\frac{\partial L}{\partial z} = [0.111,\, 0.8214 - 1,\, 0.067] = [0.111,\, -0.179,\, 0.067]
$$

The model already puts 82% on class 1, so the gradient on the true class is modest. If instead $p_1 = 0.05$:

$$
L = -\log(0.05) \approx 2.996
$$

$$
\frac{\partial L}{\partial z_1} = 0.05 - 1 = -0.95
$$

The pull is much steeper. The correction scales with how wrong the model is.

I put both cases side by side. The left one is the walk-through at $z_1 = 3.0$.

{% include fig-pair.html src_a="cross-entropy-loss-explained/gradient-right.svg" alt_a="Bars at z1 equals 3. Class 1 has probability 0.821, its gradient is minus 0.179 and the loss is 0.197." caption_a="$z_1 = 3.0$: the model is mostly right, so the pull is small." src_b="cross-entropy-loss-explained/gradient-wrong.svg" alt_b="Bars when class 1 has probability 0.05. Its gradient is minus 0.95 and the loss is 2.996." caption_b="$p_1 = 0.05$: the model is badly wrong, so the pull is close to $-1$." caption="The three gradient entries sum to zero in both cases." %}

---

## What about perplexity?

Perplexity is the exponential of the average cross-entropy, reported for language models:

$$
\mathrm{PPL} = e^{L}
$$

If the average CE is $2.3$ nats per token, perplexity is $e^{2.3} \approx 9.97$, which reads as "as uncertain as a uniform guess among about 10 tokens". GPT-2 at convergence on web text lands around 20–30 depending on the dataset, and a uniform guess over a 50k vocabulary gives about 50,000. Perplexity increases monotonically with CE, so minimizing one minimizes the other.

I plotted perplexity against the average loss. The first point is the 2.3 nats from my example.

{% include fig.html src="cross-entropy-loss-explained/perplexity.svg" alt="Perplexity against average cross-entropy on a log axis. A loss of 2.3 gives perplexity about 9.97. A uniform guess over 50,257 tokens has a loss of about 10.82." caption="The vertical axis is logarithmic, so the curve is a straight line. The uniform guess over $V = 50257$ tokens has $L = \ln 50257 \approx 10.82$." %}

---

## From-scratch implementation sketch

Forward (mean over $N$ tokens):

```python
import numpy as np

def cross_entropy_forward(logits, targets):
    N, V = logits.shape
    m = logits.max(axis=1, keepdims=True)
    shifted = logits - m
    log_sum_exp = m[:, 0] + np.log(np.exp(shifted).sum(axis=1))
    rows = np.arange(N)
    nll = log_sum_exp - logits[rows, targets]
    loss = nll.mean()
    return loss, shifted
```

Backward (given stored shifted logits from forward):

```python
def cross_entropy_backward(shifted, targets, grad_out=1.0):
    N, V = shifted.shape
    exp = np.exp(shifted)
    probs = exp / exp.sum(axis=1, keepdims=True)
    grad = probs.copy()
    grad[np.arange(N), targets] -= 1.0
    grad *= grad_out / N
    return grad
```

PyTorch's `F.cross_entropy` expects raw logits and integer targets, and applies log-softmax and NLL internally. Do not apply softmax first: that applies softmax twice and the loss no longer matches the model's outputs.

---

## ignore_index and masked positions

Instruction fine-tuning masks the loss on padding or prompt tokens. The formula is the same, but positions where `target == ignore_index` are zeroed out, and the sum is divided by the number of kept positions, not the total length.

For AL-1 pretraining I use every token in the packed window. For instruction tuning I will mask the user prompt positions and backpropagate only on assistant completions. That uses the same `cross_entropy` with a different mask.

---

## Where does this sit in the training loop?

```mermaid
flowchart LR
  BATCH["batch x, y"] --> GPT["GPT forward"]
  GPT --> LOG["logits (B,T,V)"]
  LOG --> CE["cross_entropy"]
  CE --> L["loss"]
  L --> BW["backward"]
  BW --> OPT["AdamW step"]
```

Cross-entropy is the objective. [Autograd](/blog/build-autograd-from-scratch/) computes $\partial L / \partial \theta$, and [AdamW](/blog/adam-optimizer-explained/) uses those gradients to update the weights. Embeddings, attention and LayerNorm only learn because a scalar loss defines what "better" means.

For language models, "better" means assigning high probability to the true next token at every position. Cross-entropy expresses that requirement as a differentiable function.

---

## Common mistakes I hit

| Mistake | Symptom |
|---|---|
| Softmax before `cross_entropy` | Loss stuck, gradients near zero |
| `log(softmax)` manually without max trick | `inf` / `nan` on large logits |
| Mean vs sum mismatch in backward | Gradients off by factor of $N$ |
| Wrong target dtype (float one-hot vs int indices) | Silent wrong loss |
| Forgetting to divide masked CE by kept count | Loss scale drifts with sequence length |

Run [gradcheck](/blog/numerical-gradient-checking-explained/) on the fused op with random logits shape $(2, 3, 7)$ before trusting the training loop. The check takes about five seconds and catches errors that would otherwise cost hours of debugging a training run.

---

I used to treat cross-entropy as a black-box API call. Implementing it once, with forward, backward and a numeric check, changed that. The loss is "make $p_y$ big" written as $-\log p_y$, and its gradient $p - t$ is simple enough to make the training stack downstream easier to implement. Next in the series: moving the weights with [AdamW](/blog/adam-optimizer-explained/).
