6.4 Losses with a fused backward
The op library and gradcheck_all provides log_softmax and gather, so cross-entropy could be written as three ops: -gather(log_softmax(z), t).mean(). It would be correct, slow, and fragile. Backward through that chain keeps a [N, V] array alive at each step, and for the bigram (V = 256) or a real vocabulary (V = 49,152 for SmolLM2) that is most of the memory a training step uses. Padding makes it worse: batches of token windows have rows that must not count, and a mean that divides by the padded length silently shrinks the loss.
Concepts from other sections (10)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- training step: one zero-grad, loss, finiteness check, backward, clip, and optimizer update on one batch. Read more: 6.6 Training loop and the autograd bigram
- token window: consecutive ids, split into inputs and targets shifted by one. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Fused cross-entropy: the gradient computed directly from logits. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
- Expected value: the average outcome across many repetitions of a situation under the model. Read more: Chapter 4: Uncertainty and evidence in Mathematics
- vector-Jacobian product (VJP): the function mapping an output gradient to input gradients without forming the Jacobian. Read more: 6.2 Tensor, broadcasting backward, and no_grad
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all
- Jacobian-vector product (JVP): , the directional derivative of a vector function, computed by one forward-mode pass. Read more: 14.1 Dual numbers and forward-mode autodiff in Mathematics
Every training loop from here on, starting with Training loop and the autograd bigram and running through Bengio’s neural probabilistic language model, GPT decoder-only, and the capstone, calls this file once per step. So the loss must be one graph node with a closed-form gradient, correct about padding, and finite for any logits. This section builds three such losses (softmax cross-entropy with ignore_index, label smoothing, and three reductions; mean squared error; and binary cross-entropy on logits with pos_weight), and then shows a small test suite that pins them down.
The section builds on from_op from Tensor, broadcasting backward, and no_grad and, from Mathematics, on the stable log_softmax of Stable numerics, the independent cross_entropy_vjp derivation of Matrix differentials, the trace trick, and closed-form VJPs, and the definition of cross-entropy in Entropy, cross-entropy, KL, JS, and the k3 estimator. For the test suite, it helps to have read TDD, unit tests, and mutation testing in Software Engineering, on writing tests that catch faults. The solution is losses.py with its test suite test_losses.py; the contract is losses.pyi.
Learning objectives
- Derive the fused cross-entropy gradient for one-hot and smoothed targets.
- Implement
ignore_indexso padding adds no loss, gets no gradient, and does not count in the mean, with an all-padding batch giving 0 rather thannan.- Apply label smoothing over all classes and compute a smoothed loss by hand.
- Write binary cross-entropy in a softplus form that stays finite at logits of .
- Design tests whose expected values come from hand computation and each catch one plausible mistake.
Deriving the losses
Section titled “Deriving the losses”The notation for this section:
| Symbol | Meaning | Type / shape |
|---|---|---|
| logits of row ( rows, classes) | float[N, V] (or [..., V]) | |
target class of row , or ignore_index | int[N] | |
| predicted distribution | float[V] | |
1 when row is kept ( ignore_index) | ||
| number of kept rows | int | |
| label smoothing, in | float | |
| smoothed target, the one-hot vector | float[V] | |
| row loss, | float | |
| logit and target of binary cross-entropy, | float | |
pos_weight, the weight on positive examples | float, default 1 | |
| , | functions |
The fused gradient
Section titled “The fused gradient”For one row with a one-hot target, . Differentiating, . With a smoothed target, (because ), so . That is the whole backward: one subtraction on the probabilities, which the forward already computed as . A correct fused VJP equals the cross_entropy_vjp derived in Mathematics on the same inputs.
The forward has to be stable. . Computing instead underflows: at softmax returns exactly in float64, and .
Reductions and padding
Section titled “Reductions and padding”The kept mask zeroes ignored rows in both directions: their loss is 0 and their gradient row is 0. "none" returns the per-row losses (); "sum" is ; "mean" is that sum divided by , the number of kept rows. Dividing by would make a batch of 3 real rows and 5 padding rows report 3/8 of its true loss and train at 3/8 of the learning rate.
When the mean is . This book defines it as loss 0 with a zero gradient. Torch returns nan, and one nan step poisons every weight. The upstream gradient scales the rows: by for the mean, by for the sum, and row by row for "none".
Label smoothing
Section titled “Label smoothing”A target of exactly one class asks the model to push to 1, which needs . Smoothing moves of the target mass onto a uniform distribution over all classes, so and every other class gets . The contract writes the same loss as . Spreading over classes (excluding the target) is a different, also published, variant; torch and this book use .
Mean squared error and binary cross-entropy
Section titled “Mean squared error and binary cross-entropy”Mean squared error is over all elements, and its gradient is .
Binary cross-entropy on logits takes one logit and target : . Using and , this is
and never exponentiates a positive number. The gradient is , divided by the element count for the mean.
Working it by hand
Section titled “Working it by hand”Two rows are enough to see every rule at work. Take logits for two rows over classes: row 0 is with target 2, and row 1 has target ignore_index (-100), whatever its logits.
- , sum 6, so .
- .
- Row 1 is ignored: , , so the mean loss is .
- The gradient of row 0 is , divided by . Row 1 gets zeros.
Now add label smoothing to the same row 0, with . Each class gets and the target keeps more, so .
- .
- The gradient is .
Both gradients sum to zero, as every softmax gradient must. The walkthrough below traces both examples through the code.
Designing the API
Section titled “Designing the API”def cross_entropy(logits: Tensor, targets: ArrayLike, ignore_index: int = -100, label_smoothing: float = 0.0, reduction: Literal["mean", "sum", "none"] = "mean") -> Tensordef mse(pred: Tensor, target: ArrayLike) -> Tensordef bce_with_logits(logits: Tensor, targets: ArrayLike, pos_weight: Optional[ArrayLike] = None) -> TensorEach returns one from_op node whose VJP is the closed form above. Targets are validated before anything else: integers, shape logits.shape[:-1], each in or equal to ignore_index.
A correct solution reproduces both hand examples: loss with gradient and zeros on the ignored row, and the smoothed with its loss and . Its loss and gradient equal torch.nn.functional on every option, so training loops ported from torch behave the same. The fused VJPs pass central differences (a closed form off by a factor fails), the fused gradient equals the independently derived cross_entropy_vjp matrix, and each smoothed row loss equals computed the slow way from the definition.
The padding rules are checked as properties. Appending ignored rows changes neither the loss nor the kept gradients, which padded batches (the token windows of Safetensors for every dtype, atomic checkpoints, and the token stream, the packing of Supervised fine-tuning) rely on. A batch of only padding gives loss 0 and a zero gradient, because one nan step ruins a run. Logits of and bce logits of 1000 stay finite, because trained logits are large. The none, sum, and mean reductions agree with each other, which matters because evaluation sums none in The evaluation harness and the model zoo. Float32 logits give a float32 loss and gradient. And out-of-range or float targets, an unknown reduction, a bad , and shape mismatches are all rejected, so data and config bugs fail here.
Building it step by step
Section titled “Building it step by step”The reasoning chain
Section titled “The reasoning chain”- One node per loss. The loss is the last op of every training step and its input is the largest array in the graph (
[N, V]logits). Composinglog_softmax,gather, andmeanwould keep an[N, V]intermediate per op alive until backward. A singlefrom_opnode keeps onlylog_softmax(z)and recomputes in backward. - The gradient is , scaled. The derivation gave for any target distribution that sums to 1. So backward is: exponentiate the stored log-probabilities, subtract everywhere, subtract more at the target, then apply the keep mask and the reduction’s scale.
- Validate, then neutralize ignored targets. A target of
-100cannot be used as an index (NumPy would read class , or fail). So the target array is validated over kept rows only, ignored entries are replaced by 0 for indexing, and the keep mask zeroes their loss and gradient afterwards. This way the indexing code never branches per row. - The mean divides by kept rows, and is defined. The mean’s denominator is , and the case returns 0 in both directions instead of .
- Stable forms everywhere. Cross-entropy reads from a stable
log_softmax. Binary cross-entropy is rewritten with softplus so that no exponent is ever positive, and its gradient uses a stable . - Keep the input’s dtype. Every output and gradient is cast back to the logits’ dtype, so float32 training stays float32.
Validating targets
Section titled “Validating targets”def _targets(targets, shape, v: int, ignore_index: int): """(targets as int64 with ignored rows set to 0, the keep mask), validated.""" t = np.asarray(targets) if t.size and not np.issubdtype(t.dtype, np.integer): # 2.0 is not a class raise ValueError(f"targets must be integers, got dtype {t.dtype}") t = t.astype(np.int64) if t.shape != shape: # one target per row of logits raise ValueError(f"targets have shape {t.shape}, logits need {shape}") keep = t != ignore_index kept = t[keep] # range-check only the rows that count if kept.size and (kept.min() < 0 or kept.max() >= v): # -1 would wrap to class V-1 raise ValueError(f"targets must lie in [0, {v}) or equal ignore_index {ignore_index}") return np.where(keep, t, 0), keep # 0 is a safe index; keep masks it out laterThe cross-entropy forward
Section titled “The cross-entropy forward”def cross_entropy(logits, targets, ignore_index=-100, label_smoothing=0.0, reduction="mean"): if reduction not in _REDUCTIONS: raise ValueError(f"reduction must be one of {_REDUCTIONS}, got {reduction!r}") eps = float(label_smoothing) if not 0.0 <= eps <= 1.0: raise ValueError(f"label_smoothing must be in [0, 1], got {eps}") z = logits if isinstance(logits, Tensor) else Tensor(logits) a = z.data # ... logits need a class axis v = a.shape[-1] t, keep = _targets(targets, a.shape[:-1], v, ignore_index) lp = np.asarray(stable.log_softmax(a, axis=-1), dtype=a.dtype) # M09.2: never log(softmax) nll = -np.take_along_axis(lp, t[..., None], axis=-1)[..., 0] # -log p_t per row # smoothed: (1 - eps)(-log p_t) + eps * mean_j(-log p_j), the contract's form of H(q, p) rows = nll if eps == 0.0 else (1.0 - eps) * nll - eps * lp.mean(axis=-1) rows = np.where(keep, rows, 0.0).astype(a.dtype) # padding adds no loss n = int(keep.sum()) # K, the kept rows if reduction == "mean": # Divide by the rows that count: padding must not dilute the loss. out = rows.sum() / n if n else np.zeros((), dtype=a.dtype) elif reduction == "sum": out = rows.sum() else: out = rows # "none": per-row, ignored rows are 0 out = np.asarray(out, dtype=a.dtype)lp.mean(axis=-1) is the average of over all classes, which is what makes the smoothing spread over every class, the target included. On the hand-worked row with : , the hand value.
The cross-entropy backward
Section titled “The cross-entropy backward” def vjp(g): # d loss_i / d z_i = softmax(z_i) - q_i, q_i the (smoothed) target. d = np.exp(lp) # p, from the stored stable log-probabilities if eps: d = d - eps / v # the uniform part of q, on every class # the one-hot part of q: subtract (1 - eps) at each row's target np.put_along_axis(d, t[..., None], np.take_along_axis(d, t[..., None], axis=-1) - (1.0 - eps), axis=-1) d = d * keep[..., None] # ignored rows get exactly zero if reduction == "mean": d = d * (g / n if n else 0.0) # K = 0: a zero gradient, not nan elif reduction == "sum": d = d * g else: d = d * g[..., None] # "none": one upstream value per row return (d.astype(a.dtype, copy=False),)
return from_op(out, (z,), vjp, "cross_entropy")On the hand-worked row, exp(lp) = [1/6, 1/3, 1/2]; without smoothing the target entry becomes , giving . With , subtract everywhere, then more at class 2, giving . The ignored row in the first example was indexed at class 0 (by _targets), and the keep mask erases whatever that produced.
Mean squared error
Section titled “Mean squared error”def mse(pred, target): p = pred if isinstance(pred, Tensor) else Tensor(pred) y = np.asarray(target, dtype=p.dtype) # the target takes pred's dtype if y.shape != p.shape: # no silent broadcasting of a target raise ValueError(f"target has shape {y.shape}, pred has {p.shape}") d = p.data - y n = d.size out = np.asarray((d * d).sum() / n, dtype=p.dtype) return from_op(out, (p,), lambda g: (g * (2.0 / n) * d,), "mse") # (2/n)(pred - y)The shape check matters more than it looks: pred of shape [N, 1] against a target of shape [N] would broadcast to [N, N] and compute a meaningless loss without any error.
Binary cross-entropy on logits
Section titled “Binary cross-entropy on logits”def bce_with_logits(logits, targets, pos_weight=None): z = logits if isinstance(logits, Tensor) else Tensor(logits) x = z.data y = np.asarray(targets, dtype=x.dtype) # ... shape check, as in mse w = np.ones((), dtype=x.dtype) if pos_weight is None else np.asarray(pos_weight, dtype=x.dtype) c = 1.0 + (w - 1.0) * y # the weight on softplus(-x) = -log sigmoid(x) # softplus(-x) = max(-x, 0) + log1p(exp(-|x|)): the exponent is never positive. sp = np.maximum(-x, 0.0) + np.log1p(np.exp(-np.abs(x))) n = x.size out = np.asarray(((1.0 - y) * x + c * sp).sum() / n, dtype=x.dtype) sig_neg = np.exp(-np.logaddexp(0.0, x)) # sigmoid(-x) = 1 / (1 + e^x), stable for either sign
def vjp(g): # d/dx [(1 - y) x + c softplus(-x)] = (1 - y) - c sigmoid(-x), averaged over n return ((g / n * ((1.0 - y) - c * sig_neg)).astype(x.dtype, copy=False),)
return from_op(out, (z,), vjp, "bce_with_logits")np.logaddexp(0, x) is computed without overflow, so is finite for . You can check the pos_weight hand value: at , , , and , so the loss is .
The full solution is losses.py.
A test suite that catches faults
Section titled “A test suite that catches faults”The solution ships a small test suite of its own, written against the contract only (it imports tinyllm.autograd.losses and tinyllm.autograd.tensor, plus NumPy and pytest). Each test’s expected value is computed by hand from the worked examples, never by running the code, which is what lets it catch a wrong implementation. Each test targets one plausible mistake:
| Test | What it shows | The mistake it catches |
|---|---|---|
test_hand_example_matches_section_3 | logits , target 2: loss , gradient | a wrong sign or a missing subtraction at the target |
test_ignored_rows_get_no_loss_and_no_gradient | a row whose target is ignore_index adds no loss and gets a zero gradient, also with a custom ignore_index | padding that trains toward a fake target |
test_mean_divides_by_kept_rows | two kept rows and one ignored row: the mean is , the sum is | a mean that divides by |
test_all_ignored_batch_is_zero | only padding gives loss exactly 0 and a zero gradient | $0/0 = $ nan |
test_label_smoothing_hand_value | on : loss , gradient | smoothing over classes, or summing instead of averaging |
test_large_logits_are_finite | logits with target 2 give exactly ; bce at gives 1000 | and overflow |
test_out_of_range_target_raises | targets 3 and on are a ValueError | trusting targets |
test_mse_and_bce_gradients_by_finite_differences | both gradients match central differences; bce with pos_weight 2 at , is | a closed form off by a factor, a misplaced pos_weight |
Two of them are worth reading in full:
def test_mean_divides_by_kept_rows(): """Two kept rows and one ignored row: the mean is the kept sum over 2.""" z = leaf([ROW, ROW, ROW]) # ROW = [0, ln 2, ln 3] loss = cross_entropy(z, np.array([2, 0, -100])) # target 2: -ln(1/2) = ln 2; target 0: -ln(1/6) = ln 6; padding: nothing np.testing.assert_allclose(loss.data, (LN2 + LN6) / 2, rtol=1e-12) total = cross_entropy(leaf([ROW, ROW, ROW]), np.array([2, 0, -100]), reduction="sum") np.testing.assert_allclose(total.data, LN2 + LN6, rtol=1e-12)
def test_large_logits_are_finite(): """Logits of 1e4 and bce logits of 1000 give finite losses and gradients.""" z = leaf([[1e4, 0.0, -1e4]]) loss = cross_entropy(z, np.array([2])) assert np.isfinite(loss.data) # log p_2 = -1e4 - 1e4 - log(1 + e^-1e4 + e^-2e4) = -2e4 to double precision np.testing.assert_allclose(loss.data, 2e4, rtol=1e-12) b = leaf([-1000.0, 1000.0]) lb = bce_with_logits(b, np.array([1.0, 0.0])) # both maximally wrong: 1000 each np.testing.assert_allclose(lb.data, 1000.0, rtol=1e-12)The second test asserts the exact value, not just finiteness: a loss that is finite but clipped (for example by adding a tiny constant inside the log) would pass isfinite and fail here. The full suite is test_losses.py.
Why this design
Section titled “Why this design”Forward and backward are each with a constant number of passes over the logits. Memory between forward and backward is one [N, V] array (lp) plus the small target and mask arrays; the three-op composition would hold three. Composition is correct, but it pays for generality the loss does not need: three VJPs, three saved arrays, and a backward that multiplies a softmax Jacobian-vector product by a scatter. The fused form is one subtraction on probabilities the forward already computed.
Returning loss 0 for an all-padding batch, instead of torch’s nan, is a deliberate departure. Matching torch here would mean one empty batch (which data loaders do produce at the end of an epoch or with aggressive filtering) poisons every weight. Defining as 0 with zero gradient makes such a step a no-op. Smoothing over rather than is torch’s choice too, and it keeps a simple mixture of the one-hot and the uniform distribution, so the gradient is with no special case.
Two tradeoffs are accepted. The [N, V] logits themselves are still materialized; fusing the output projection into the loss (Liger Kernel) is the next step and is left out for clarity. And mse and bce_with_logits support only the mean reduction, which is all the book’s training loops use.
What can go wrong
Section titled “What can go wrong”| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| counting ignored rows in the mean, or giving them gradient | padded batches report a smaller loss; padding logits train toward a fake target | rows and gradients are multiplied by the keep mask, and the mean divides by keep.sum() |
| trusting targets | -1 silently trains the last class (NumPy indexes from the end) | _targets range-checks every kept target |
| dividing by | an all-padding batch gives nan, then every weight is nan | rows.sum() / n if n else 0, and the VJP scale is 0 when n == 0 |
| and | inf loss at logits of | stable.log_softmax and the softplus form with log1p(exp(-abs(x))) |
| smoothing over classes, or summing instead of averaging | disagrees with torch; the loss grows with the vocabulary size | eps * lp.mean(axis=-1) in the forward, eps / v on every class in the backward |
Warning: A mean that divides by instead of does not crash or produce
nan. It quietly scales the learning rate by the fraction of real rows, which varies from batch to batch.
Where this leads
Section titled “Where this leads”This section built on one from_op node per loss, the stable log_softmax, the independently derived cross_entropy_vjp that the fused gradient must equal, and the definition of a smoothed row’s loss.
Next, the bigram and the MLPs of Training loop and the autograd bigram minimize cross_entropy, mse, and bce_with_logits. Packed batches in Supervised fine-tuning mark their padding with ignore_index. And every language-model training step in the book ends in cross_entropy: mixed-precision training, Bengio’s neural probabilistic language model, RNN language model with stateful TBPTT, Encoder-decoder with teacher forcing, Encoder-decoder Transformer, GPT decoder-only, BERT: the bidirectional encoder and masked language modeling, ELECTRA: replaced-token detection, and Fine-tuning heads and the linear-head export.
Further reading
Section titled “Further reading”- Goodfellow, Bengio, Courville, Deep Learning (free online), sections 6.2.2 and 7.5.
- Szegedy et al., “Rethinking the Inception Architecture” (2016), section 7 (label smoothing).
- Liger Kernel
fused_linear_cross_entropy(liger_kernel/ops/fused_linear_cross_entropy.py): fuses the output projection too, so the[N, V]logits are never materialized, chunked over rows. - PyTorch
nll_loss(aten/src/ATen/native/LossNLL.cpp): the sameignore_indexsemantics, plus per-class weights. torch.nn.CrossEntropyLoss(label_smoothing=...)(aten/src/ATen/native/Loss.cpp): label smoothing combined with class weights and probability targets.torch.nn.functional.binary_cross_entropy_with_logits(aten/src/ATen/native/Loss.cpp): the same softplus form, vectorized on GPU.
Key terms
Section titled “Key terms”- fused loss: a loss implemented as one graph node with a closed-form gradient, instead of a chain of ops.
ignore_index: a target value marking a row (usually padding) that contributes no loss, no gradient, and no count to the mean.- label smoothing: mixing the one-hot target with a uniform distribution over all classes, weight .
- softplus: , used to write binary cross-entropy without positive exponents.
pos_weight: a multiplier on the positive-class term of binary cross-entropy.
Summary
Section titled “Summary”- Softmax cross-entropy is one graph node: its forward uses
log_softmax, and its gradient is the closed form . - Padding rows (
ignore_index) add no loss, get no gradient, and do not count in the mean; a batch of only padding is loss 0, notnan. - Label smoothing spreads over every class, the target included, so a row’s loss is the cross-entropy against the smoothed target.
- Stable forms keep logits of finite:
log_softmaxfor cross-entropy, softplus for binary cross-entropy. - A good test suite for a loss pins hand-computed values, the padding rules, and the stability limits.
Review questions
Section titled “Review questions”-
Why is the gradient of smoothed cross-entropy still , with no extra term from the smoothing?
Answer
With any target distribution that sums to 1, , because . Differentiating gives . Smoothing only changes , and still sums to 1, so the form is unchanged.
-
Why does
_targetsreplace ignored targets with 0 instead of leaving them as-100?Answer
Both the forward (
take_along_axis) and the backward (put_along_axis) index with the targets.-100would read class for and raise for smaller . Class 0 is always a valid index, and the keep mask then zeroes the loss and the gradient of those rows, so the value read there never matters. -
A batch has 3 real rows and 5 padding rows. What goes wrong if the mean divides by 8?
Answer
The reported loss is of the true mean, and the gradient is scaled by instead of , so the batch trains at of the intended learning rate. Worse, the factor changes with the amount of padding, so loss curves are not comparable across batches.
-
Why compute as
exp(-logaddexp(0, x))rather than1 / (1 + exp(x))?Answer
At ,
exp(x)overflows toinfwith a warning;1 / inf = 0is actually the right answer, but at the other common formexp(-x) / (1 + exp(-x))givesinf / inf = nan.logaddexp(0, x)is computed stably for either sign, and is then a number in without any intermediate overflow. -
Why does
test_large_logits_are_finiteassert the exact value rather than onlynp.isfinite?Answer
An implementation that hides overflow by clipping (for example adding a tiny constant inside the log) produces a finite but wrong loss. Asserting the exact value catches that, while
isfinitealone would pass it.