17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing
The capstone trains a 10.4M-parameter Llama with a 512-token context. The loop from Training loop and the autograd bigram runs one batch per step, all in float32, and keeps every layer’s activations until backward() returns. Three things break at that size. First, the batch the recipe calls for (32 sequences) does not fit: the memory_plan from Counting: parameters, FLOPs, KV bytes, and memory plans puts the float32 activations of one 512-token sequence through the 8 layers at 161 MiB, so a batch of 32 needs 5.0 GiB of activations next to 159 MiB of weights, gradients, and AdamW moments. Second, real hardware trains in bf16 or fp16 for speed and memory, and you need to know that the run you design here still converges when every matmul reads 8-bit mantissas before you trust a recipe that depends on it. Third, when a gradient underflows or overflows in fp16, a float32 loop never sees it.
Concepts from other sections (15)
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.
- Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay in Mathematics
- grad mode: a per-thread flag that controls whether ops record a graph;
no_gradturns it off and restores it. Read more: 6.2 Tensor, broadcasting backward, and no_grad - ties to even: rounding a value exactly halfway between two representable numbers to the one with an even last bit. Read more: 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32
- unit roundoff: for float32, the maximum relative error of one rounding. Read more: 22.4 Softmax in C: three-pass and online two-pass
- Master copy: an fp32 copy of 16-bit weights kept so small updates are not rounded away. Read more: 11.1 Counting: parameters, FLOPs, KV bytes, and memory plans in Mathematics
- Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent , filling the gap between zero and the smallest normal. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even in Mathematics
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- 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
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- 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
- VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- Context manager: an object with
__enter__and__exit__methods, used in awithstatement, so the setup and cleanup of a scoped resource happen on every exit path, including exceptions. Read more: Chapter 22: Python in Programming and Algorithms - 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
- Error budget: the per-output bound a quantized layer must stay within. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
This section adds the four tools every large training run uses, each behind one call: autocast (emulated low precision), DynamicLossScaler (fp16 range), grad_accumulate (a big batch from small ones), and checkpoint_sequential (activations kept on a recompute schedule). The emulation runs on numpy and is not faster. What it gives you is the exact numerics, so the claim that the capstone converges within 2% of float32 at a lower peak memory is measured, not assumed. The capstone trainer calls all four with --bf16 --micro-batch 8 --accum 4 --checkpoint-activations; without this section those flags have nothing to call.
You will build on a good deal of earlier material. From this book: the Tensor, from_op, and grad mode of Tensor, broadcasting backward, and no_grad; mse from Losses with a fused backward, which is the loss in the examples; and Module.parameters() from Module system and basic layers. From Mathematics: round_to_bf16 and round_to_fp16 from IEEE 754 anatomy, ulps, and round to nearest even; SGD from The Optimizer protocol and AdamW from Adam and AdamW; clip_grad_norm_ from Learning-rate schedules and gradient clipping; and checkpoint_schedule from Hessian-vector products and the recompute-versus-memory schedule.
The solution lives in precision.py (cast, autocast, autocast_bf16, autocast_dtype, DynamicLossScaler, grad_accumulate, train_step_mixed) and recompute.py (checkpoint, checkpoint_sequential), with the contracts in precision.pyi and recompute.pyi.
Learning objectives
- Emulate a bf16 or fp16 matmul, forward and backward, and explain why the master weights stay float32.
- Derive loss scaling from the linearity of backprop and trace a dynamic loss scaler through overflows and growth.
- Weight micro-batches so that accumulation reproduces one large batch’s gradient exactly, for unequal sizes.
- Build activation checkpointing as a single graph node whose gradients equal the plain run’s bit for bit.
Notation
Section titled “Notation”The section uses a handful of symbols throughout; here they are in one place.
| Symbol | Meaning | Type / shape |
|---|---|---|
| rounded to nearest, ties to even, into bf16 or fp16 | elementwise | |
| the precision of a format, in significant bits: 24 (fp32), 11 (fp16), 8 (bf16) | int | |
| the unit roundoff: the largest relative error of one rounding | float | |
| a parameter (the float32 master copy) | float32[...] | |
| the learning rate | float | |
| , | the loss and a gradient | float, like |
the loss scale (loss_scale) | float, a power of 2 | |
| , , | rows in the full batch, rows in micro-batch , number of micro-batches | int |
| the mean loss over micro-batch ‘s rows | float | |
| , | segment sizes and peak memory of a checkpoint schedule | int |
Two 16-bit formats and what a bf16 matmul does
Section titled “Two 16-bit formats and what a bf16 matmul does”Both 16-bit formats keep a sign, an exponent, and a mantissa in 16 bits, but they split the bits differently. bf16 keeps float32’s 8 exponent bits and 7 mantissa bits: the same range (up to about ) with , so . fp16 has 5 exponent bits and 10 mantissa bits: , , but its largest finite value is 65504, its smallest normal , and its smallest subnormal . bf16 trades precision for range; fp16 trades range for precision. numpy has neither, so round_to_bf16 and round_to_fp16 emulate them: each returns a float array whose entries are all values of the format.
A tensor core reads two bf16 matrices, multiplies, accumulates the sums in float32, and writes a bf16 result. So becomes
Each operand entry has relative error up to , and the output gets one more rounding. Errors of different entries look independent, so a dot product of length drifts by about relative, not . For training this is noise of a few tenths of a percent, smaller than minibatch noise.
The cast is an op with a gradient
Section titled “The cast is an op with a gradient”To put that rounding into the autograd graph, write the emulated storage as an op cast with forward . Its true derivative is zero almost everywhere (rounding is a step function), which would stop all learning. What hardware does instead is pass the gradient through the conversion, and a gradient that arrives in bf16 is a bf16 value. So the backward of a cast is the cast of the gradient: .
Built from from_op, the autocast matmul is cast(cast(a) @ cast(b)), and its backward computes : a bf16 backward matmul, exactly what a GPU runs. Because every matmul in your models goes through Tensor.__matmul__ (F.matmul, Linear, attention), autocast can swap in the rounding version for the length of a with block and put the original back on the way out, including when the block raises. That is what torch.autocast does with its dispatch keys.
Why the weights stay float32
Section titled “Why the weights stay float32”The update is where precision matters most. The spacing of bf16 numbers near 1 is , so a weight of 1 updated by rounds straight back to 1, and the update is lost. Training in pure bf16 stalls once updates become small. So the parameters, the optimizer state (AdamW’s moments), and the update stay float32; these are the “master weights”. Only the matmuls, which dominate the time and the activation memory, run on rounded operands. The memory plan counts this: bf16 AdamW is 2 (weights) + 2 (grads) + 4 (master) + 8 (moments) = 16 bytes per parameter, the same as float32, and the saving is all in activations.
Loss scaling and dynamic scaling
Section titled “Loss scaling and dynamic scaling”bf16 has float32’s range and needs nothing more. In fp16, though, the problem is range, not precision. Gradients of a mean loss over many tokens are small: a cross-entropy gradient on the logits is , and backpropagated through a few layers many entries fall below and flush to zero.
The fix comes from one observation: backprop is linear in the upstream gradient. Every VJP is linear in , so starting backward from instead of multiplies every gradient by exactly . Choose so the small gradients land in fp16’s normal range, then divide the float32 master gradients by before the update. With a power of two, scaling and unscaling are exact, because they only change the exponent.
Too large an , however, overflows the large gradients to (and to NaN). The robust approach is to detect, not to predict. After backward, if any gradient is non-finite, skip the whole step (one poisoned entry would corrupt every weight it touches through the optimizer), drop the gradients, and multiply by the backoff . After interval consecutive good steps, multiply by the growth factor 2 to probe upward again. The count of good steps restarts after every overflow and every growth. A skipped step costs one batch; a run without scaling silently loses its small gradients. Clipping comes after unscaling, because the clip bound is a norm in true gradient units.
Gradient accumulation
Section titled “Gradient accumulation”Memory is the other constraint, and accumulation addresses it by splitting a batch. The loss of a batch of rows is the mean of per-row losses . Split the rows into micro-batches with rows each, and let be micro-batch ‘s own mean. Then
and since the gradient is linear, . Backpropagating for each micro-batch, without zeroing in between (the Tensor adds into .grad), accumulates exactly , and only one micro-batch’s activations exist at a time. Weighting by gives the same answer only when all micro-batches have equal size, and the last one of an epoch usually does not. The results agree with one big batch to float32 rounding, not bit for bit, because the sums are added in a different order.
Activation checkpointing
Section titled “Activation checkpointing”Accumulation shrinks the batch; checkpointing shrinks what each layer keeps. The recompute-versus-memory schedule in Mathematics counted the trade: keep only some layers’ inputs and recompute the rest during backward. The mechanism here is one graph node. checkpoint(fn, x) runs fn under no_grad, so none of its intermediate values are recorded, and returns a node (from_op) whose parents are and the parameters fn reads. When backward reaches the node, its VJP reruns fn with grad mode on, from fresh leaf copies of its inputs, backpropagates the upstream gradient through that rerun (which adds the parameter gradients into their .grad directly), and returns the inputs’ gradients. checkpoint_sequential applies checkpoint_schedule: every segment but the last goes through checkpoint, and the last runs normally.
Three details make the gradients equal bit for bit. The rerun performs the same floating-point operations on the same values, so it produces the same activations. A dropout layer draws a new mask from its generator on every call, so the node records the generator’s state before the forward pass, sets it back for the rerun, and afterwards restores the state the stream had reached, as if nothing had been rerun. And the segment’s parameters must be parents of the node: the first segment’s input is data, which does not require grad, and from_op records a node only when some parent requires grad, so without the parameters the first layers would silently get no gradient. That is the classic bug of reentrant checkpointing in PyTorch.
There is one difference from the schedule’s memory model. This book’s backward() keeps the whole outer graph alive until it returns, whereas PyTorch frees each saved tensor as soon as backward has used it. So the activation memory held between forward and backward falls as the schedule predicts, while the peak during backward falls less, because the last segment stays alive while earlier segments are recomputed.
Working it by hand
Section titled “Working it by hand”Four small examples pin each tool to exact numbers. They are also the first four checks a correct solution must pass.
A bf16 matmul. Take and . Both are bf16 values already. The float32 product is . Its bf16 neighbours are 1 and , with exactly halfway; ties go to the even mantissa, so autocast returns . An input of is stored as , the nearest bf16 value. For , , so and . The same product outside autocast is the float32 .
Accumulation. Use one weight , inputs , targets , and the loss the mean of . With the residuals are . The table compares one batch with a split into micro-batches of 1 and 3 rows:
| rows | weight | |||
|---|---|---|---|---|
| one batch | 1, 2, 3, 4 | 1 | ||
| micro-batch 1 | 1 | 1 | ||
| micro-batch 2 | 2, 3, 4 |
Weighted, the gradient is , and the loss is . Weighting each micro-batch by gives ; not weighting at all gives .
Loss scaling. Take , growth 2, backoff , interval 2, and SGD with on one parameter starting at 0. The scaled gradients arrive as follows:
| step | scaled | finite? | unscaled | after | after | good steps |
|---|---|---|---|---|---|---|
| 1 | 8 | yes | 1 | 8 | 1 | |
| 2 | no: skip | 4 | 0 | |||
| 3 | 4 | yes | 1 | 4 | 1 | |
| 4 | 8 | yes | 2 | 8 (grown) | 0 | |
| 5 | 16 | yes | 2 | 8 | 1 |
If the count did not restart at the overflow, step 3 would already be the second good step and would grow one step early.
Checkpointing six layers. With a budget of 4 units, checkpoint_schedule(6, 4) == [0, 3]. The forward pass runs layers 0 to 2 under no_grad and keeps only their input, then layers 3 to 5 normally. Backward runs layers 5, 4, 3, reaches the checkpoint node, reruns layers 0 to 2 forward, and backpropagates through them. Each of layers 0 to 2 has run forward twice and layers 3 to 5 once (forward counts ), and every gradient equals the plain run’s.
Designing the API
Section titled “Designing the API”The interface is small: one op, one context manager, one scaler class, and two functions for the training step, plus the two checkpointing functions.
def cast(x: Tensor, dtype: Literal["bf16", "fp16"]) -> Tensor # rounds forward and backward@contextmanagerdef autocast(dtype) -> Iterator[None] # every Tensor matmul: cast(cast(a) @ cast(b))def autocast_bf16(); def autocast_dtype() -> Optional[str]class DynamicLossScaler: def __init__(self, init=2.0**16, growth=2.0, backoff=0.5, interval=2000) def scale(self, loss: Tensor) -> Tensor # loss * S def step(self, opt, params, clip=None) -> bool # check, unscale, clip, step, update S def state_dict(self) -> dict; def load_state_dict(self, sd) -> Nonedef grad_accumulate(model, micro_batches, loss_fn, scaler=None) -> float # weights n_i / Ndef train_step_mixed(model, micro_batches, loss_fn, opt, precision="fp32", scaler=None, clip=None) -> dict
# python/tinyllm/train/recompute.pydef checkpoint(fn, *args, params=(), rngs=()) -> Tensordef checkpoint_sequential(layers, x, mem_budget_layers, rngs=()) -> Tensor # uses checkpoint_scheduletrain_step_mixed is the foundations chapter’s train_step grown up for the capstone. It zeroes the gradients, accumulates the micro-batches under autocast(precision) (no block for "fp32"), then runs either the scaler’s step or a finite-loss check, clipping, and opt.step(). It returns {"loss", "skipped", "scale"}, plus "grad_norm" when it clipped. autocast patches Tensor.__matmul__ and __rmatmul__ process-wide while the outermost block is open; blocks nest, and the innermost dtype applies.
Building it step by step
Section titled “Building it step by step”Before reading the code, it helps to see how each design decision follows from the principles above.
- Rounding has to happen where hardware rounds, and only there. A tensor core reads 16-bit operands and writes a 16-bit result, so the emulation must round both operands and the output of every matmul. Rounding anything else (the weights, the update) would model a machine that does not exist and would lose the small updates discussed earlier.
- So rounding must be a graph op, not a numpy call. If the forward pass rounded
a.datain place, the backward pass would see float32 gradients. Makingcastafrom_opnode with VJP gives the backward matmuls the same rounding for free, because the autograd engine composes VJPs. - Every matmul goes through
Tensor.__matmul__, so patching that one method covers every model. The patch must be scoped (a context manager), must survive exceptions (finally), and must nest: only the outermost block installs and removes the patch, and a stack of dtypes says which format applies right now. - Loss scaling follows from linearity. Every VJP is linear in its upstream gradient, so backpropagating produces . Scaling the loss is one multiplication; unscaling is one multiplication of each master gradient by . Everything after unscaling (clipping, the optimizer) then works in true gradient units.
- Overflow is detected, not predicted. A single non-finite entry would poison every weight through AdamW’s moments, so the step is all or nothing: skip, drop the gradients, halve , restart the count. Growth is the mirror image: after
intervalgood steps, double and restart the count. - Accumulation is a reweighting of the loss. By the identity derived above, backpropagating for each micro-batch without zeroing sums to . The weight must use row counts, which means the solution must know each micro-batch’s size before it starts.
- Checkpointing is one graph node whose VJP reruns the forward. The forward runs under
no_grad, so nothing inside is saved. The node’s parents must include the parameters (otherwise a data input gives a node that is never recorded), and the rerun must start from fresh leaves (otherwise its backward would flow into the outer graph a second time) and replay the random generators.
The cast and the patched matmul
Section titled “The cast and the patched matmul”_round keeps the array’s own float dtype, so a float64 model stays float64.
def _round(a: np.ndarray, dtype: str) -> np.ndarray: """a rounded to dtype, in a's own float dtype.""" return np.asarray(_ROUND[dtype](a)).astype(a.dtype, copy=False)
def cast(x: Tensor, dtype: str) -> Tensor: _check(dtype) # forward: round the values; backward: round the gradient (straight-through, but in 16 bits) return from_op(_round(x.data, dtype), (x,), lambda g: (_round(np.asarray(g), dtype),), f"cast_{dtype}")
def _matmul(a: Tensor, b: Any) -> Tensor: """a @ b with rounded operands and output (the patched __matmul__).""" dt = _stack[-1] # the innermost open block decides the format b = _as_tensor(b, a) # both operands rounded, the float32 product rounded once more on the way out return cast(_orig["mm"](cast(a, dt), cast(b, dt)), dt)_rmatmul is the same with the operands swapped, for ndarray @ Tensor. The context manager installs the patch only when the stack is empty and removes it only when the stack empties again:
@contextmanagerdef autocast(dtype: str) -> Iterator[None]: _check(dtype) # an unknown dtype raises before anything is patched if not _stack: # outermost block: save the originals and patch _orig["mm"], _orig["rmm"] = Tensor.__matmul__, Tensor.__rmatmul__ Tensor.__matmul__, Tensor.__rmatmul__ = _matmul, _rmatmul _stack.append(dtype) try: yield finally: # runs on an exception too _stack.pop() if not _stack: # an inner block leaving does not unpatch the outer one Tensor.__matmul__, Tensor.__rmatmul__ = _orig.pop("mm"), _orig.pop("rmm")The loss scaler
Section titled “The loss scaler”The scaler’s step is the whole of dynamic scaling in order: check, skip or unscale, clip, step, grow.
def step(self, opt: Any, params: Iterable[Any], clip: Optional[float] = None) -> bool: ps = [p for p in params if p.grad is not None] if not all(np.isfinite(p.grad).all() for p in ps): for p in ps: p.grad = None # drop the poisoned gradients self.loss_scale *= self.backoff self.good_steps = 0 # restart the count return False inv = 1.0 / self.loss_scale for p in ps: p.grad *= inv # unscale first: the clip bound is in true units self.last_grad_norm = float(clip_grad_norm_(ps, clip)) if clip is not None else None opt.step() self.good_steps += 1 if self.good_steps == self.interval: self.loss_scale *= self.growth self.good_steps = 0 return Truestate_dict saves good_steps along with , so a resumed run grows on the same step the uninterrupted run would.
Accumulation and the mixed training step
Section titled “Accumulation and the mixed training step”Accumulation computes all sizes first, because each weight needs the total :
def grad_accumulate(model, micro_batches, loss_fn, scaler=None) -> float: mbs = list(micro_batches) # ... empty list or an empty micro-batch raises sizes = [_size(mb) for mb in mbs] total = sum(sizes) out = 0.0 for mb, n in zip(mbs, sizes): loss = _split(loss_fn(model, mb)) w = n / total # a mean over n rows times n / N is that rows' share of the big mean part = loss * w # no zero_grad here: .grad accumulates across micro-batches (scaler.scale(part) if scaler is not None else part).backward() out += w * float(np.asarray(loss.data).reshape(())) # the reported loss is weighted too return outtrain_step_mixed composes these: opt.zero_grad(), then grad_accumulate inside autocast(precision) (no block for "fp32"), then either scaler.step(...), which may skip, or a check that raises FloatingPointError on a non-finite loss before clipping and opt.step().
The checkpoint node
Section titled “The checkpoint node”def checkpoint(fn, *args, params=(), rngs=()) -> Tensor: # each distinct Tensor once: a tensor passed twice gets one summed gradient tensors = list({id(a): a for a in args if isinstance(a, Tensor)}.values()) parents = tensors + list(params) # parameters are parents, so a data input still records a node if not is_grad_enabled(): return fn(*args) before = [r.state() for r in rngs] # where each generator stood before the forward pass with no_grad(): out = fn(*args) # no graph: the activations inside fn are freed now
def vjp(g): after = [r.state() for r in rngs] for r, s in zip(rngs, before): r.set_state(s) # replay the same dropout masks # fresh leaves: the rerun's backward stops here instead of entering the outer graph leaves = {id(a): Tensor(a.data, requires_grad=a.requires_grad, dtype=a.data.dtype) for a in tensors} try: y = fn(*[leaves[id(a)] if isinstance(a, Tensor) else a for a in args]) if y.requires_grad: y.backward(g) # parameters inside fn get their .grad here, directly finally: for r, s in zip(rngs, after): r.set_state(s) # the stream continues where the forward pass left it grads = [leaves[id(a)].grad for a in tensors] return grads + [None] * len(params) # parameter grads were already added by y.backward
return from_op(out.data, parents, vjp, "checkpoint")The VJP returns None for the parameters because the rerun’s backward has already added their gradients into .grad; returning them again would double them. checkpoint_sequential applies checkpoint_schedule and runs the last segment plainly:
starts = checkpoint_schedule(len(layers), mem_budget_layers)ends = starts[1:] + [len(layers)]for i, (a, b) in enumerate(zip(starts, ends)): seg = layers[a:b] if i == len(starts) - 1: x = _segment(seg)(x) # the last segment keeps its activations: no rerun else: params = [p for m in seg for p in m.parameters()] x = checkpoint(_segment(seg), x, params=params, rngs=rngs)The full solution is in precision.py and recompute.py, and a model test suite is in test_l11_1_mine.py.
Why this design
Section titled “Why this design”The costs are modest. Autocast adds three elementwise roundings per matmul, next to the matmul’s . Accumulation costs nothing extra in compute and divides activation memory by . Checkpointing with segments runs every checkpointed layer forward twice (about one extra forward pass, a third more compute) and keeps the activations of one segment plus the segment inputs, as the schedule counted.
Patching __matmul__ beats giving every tensor a dtype. A real per-tensor dtype would mean touching every op in the library. Patching the one method every matmul goes through gives exact hardware numerics for matmuls, which are where the error lives, in ten lines and with no change to any model. The accepted tradeoff is process-wide state, hence the stack and the finally.
Dynamic scaling beats static scaling because a fixed must be tuned per model and fails when the gradient scale drifts during training; dynamic scaling costs a skipped step on each overflow and nothing else. Weighting by beats because the two agree only for equal sizes, while the row-count weight is exact for every split, at the cost of computing sizes up front. Finally, a reentrant node is chosen over saved-tensor hooks: PyTorch’s non-reentrant checkpoint frees memory more aggressively, but needs hooks this book’s engine does not have. One from_op node needs only the engine as it is, and the price is the explicit params argument.
What can go wrong
Section titled “What can go wrong”A correct solution has to pass a set of checks that go well beyond the hand examples. The table lists them along with why each matters later.
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| hand example: bf16 matmul | unit | , , bf16 gradients | the emulation is pinned to exact values |
| hand example: accumulation | unit | loss 7.5, gradient from micro-batches of 1 and 3 | the capstone’s --accum 4 |
| hand example: loss scaler | unit | the five-step trace of , the count, and | fp16 runs |
| hand example: checkpoint schedule | unit | forward counts , equal gradients | --checkpoint-activations |
| cast rounds both directions | unit | both formats, forward and gradient, dtype kept | the op every autocast matmul is built from |
| autocast matmul matches a rounded reference | property | random products, reflected operands, Linear | attention and MLP matmuls |
| gradients are bf16, masters stay float32 | property | weight gradients are bf16 values; a update survives in the master | why mixed precision converges |
| autocast restores the matmul | boundary | an exception, nesting, an unknown dtype | no bf16 leaking into the next eval |
| fp16 underflow rescued by loss scaling | differential | tiny gradients vanish in fp16 and match float32 once scaled | fp16 hardware |
| scaler skips inf steps | property | an overflow changes nothing, drops gradients, halves until steps succeed | a long run survives a spike |
| scaler unscales before clipping | differential | clip to 1 of a gradient of norm 5 scaled by 1024 | the clip bound means what it says |
| scaler state round trip | unit | resume keeps and the count; bad arguments raise | TrainRun resumes from checkpoints |
| accumulation equals one big batch | differential | micro-batches of 5, 11, 16 rows equal one of 32 to | the capstone’s loss within 2% |
| bf16 training tracks float32 | differential | 60 AdamW steps in bf16 end within 2% of float32 | the capstone in miniature |
| NaN loss rejected | boundary | a NaN loss raises before any update | the training loop’s guarantee kept |
| checkpoint gradients bitwise equal | differential | 7 layers, three budgets, float64 and float32, bit for bit | checkpointing never changes training |
| checkpoint replays the dropout generator | differential | same masks, and the stream ends where the plain run’s does | dropout in the capstone |
| parameters learn from a data input | unit | the first segment’s parameters learn from a data input | the embedding and first block |
checkpoint called directly | boundary | a tensor passed twice, a number argument, no_grad | checkpoint used directly |
| checkpointing lowers peak memory | property | tracemalloc: forward under half, overall peak lower | the reason to checkpoint |
The mistakes that make those checks fail fall into four families, and each one is answered by a specific line of the code above.
Precision emulation. If you forget to round the matmul output, bf16 runs look more accurate than hardware will be; _matmul wraps the product in a final cast. If you pass the gradient through the cast unrounded, a “bf16” backward produces float32 gradients; cast’s VJP rounds the gradient with _round. Rounding only one operand halves the error budget unnoticed, which is why _matmul casts both a and b. A cast that turns float64 into float32 causes dtype mixing downstream; _round converts back with .astype(a.dtype).
Warning: Without
try/finallyaround the patched matmul, an exception leaves every later matmul in bf16, and an inner block that unpatches on exit makes the rest of the outer block run in float32.autocastrestores the methods infinally, and only the block that empties_stackunpatches.
Accumulation. Weighting micro-batches by gives the wrong gradient whenever the sizes differ; grad_accumulate weights by n / total. Summing micro-batch losses makes gradients times too large; each part is loss * w with weights summing to 1. Zeroing gradients between micro-batches means only the last micro-batch trains; grad_accumulate never zeroes, and train_step_mixed zeroes once, before. Reporting the unweighted mean loss makes the logged loss disagree with the gradient’s; the returned loss is sum(w * loss_i).
Loss scaling. Never unscaling makes the update times too large; step multiplies every gradient by 1 / loss_scale before opt.step(). Stepping on non-finite gradients makes every weight NaN after one overflow; step checks np.isfinite on every gradient and returns False. Keeping the bad gradients after a skip lets a loop without zero_grad add onto ; a skipped step sets every p.grad = None. Not restarting the count after an overflow grows right back into overflow; good_steps = 0 on overflow and on growth. Clipping before unscaling makes the clip act on and produces tiny updates; unscaling comes before clip_grad_norm_. Losing the count on resume makes the resumed run grow late; state_dict saves good_steps. And without a scaler, stepping on a NaN loss poisons the run silently; train_step_mixed raises FloatingPointError before opt.step().
Checkpointing. Checkpointing the last segment too makes every layer run twice for nothing; checkpoint_sequential runs the last segment through _segment directly. If the parameters are not parents of the node, the first segment stops learning on data input; params are part of the node’s parents. A tensor passed twice would get its gradient twice; tensors deduplicates the arguments by id. Not replaying the generator makes the rerun’s dropout mask differ from the forward pass’s; the VJP sets each generator to its before state. Not restoring the generator after the rerun makes later draws repeat, so runs with and without checkpointing diverge; the VJP’s finally sets each generator to its after state. Running the forward pass with the graph on gives correct gradients but saves no memory; the forward pass runs under no_grad(). Rerunning on the original tensors sends the rerun’s backward into the outer graph; the rerun reads fresh leaf copies of the inputs.
Where this leads
Section titled “Where this leads”The capstone trainer is the direct consumer: it trains with bf16, accumulation of 4 micro-batches of 8, and checkpointed blocks, and compares the result with a float32 run. Accumulation also returns in Data parallelism and ZeRO stages 1 to 3, where production systems fuse it with gradient partitioning.
Every piece here has a production counterpart that adds more:
| Solution piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
autocast | torch.autocast | per-op cast policies (softmax and norms kept in float32), real bf16 kernels | torch/amp/autocast_mode.py, aten/src/ATen/autocast_mode.cpp |
DynamicLossScaler | torch.amp.GradScaler | per-device inf checks fused into one kernel, optimizer-step skipping | torch/amp/grad_scaler.py |
| bf16 and fp16 | NVIDIA Transformer Engine | fp8 matmuls with per-tensor delayed scaling, the same idea one format lower | transformer_engine/pytorch/fp8.py |
checkpoint_sequential | torch.utils.checkpoint | non-reentrant checkpointing with saved-tensor hooks, RNG state for every device | torch/utils/checkpoint.py |
| uniform segments | Megatron-LM selective recomputation | recompute only attention’s cheap, large softmax and dropout, keep the matmul outputs | megatron/core/tensor_parallel/random.py |
grad_accumulate | DeepSpeed gradient_accumulation_steps | accumulation fused with ZeRO’s gradient partitioning | deepspeed/runtime/engine.py |
Further reading
Section titled “Further reading”- Micikevicius et al., Mixed Precision Training (2018).
- Kalamkar et al., A Study of BFLOAT16 for Deep Learning Training (2019).
- Chen et al., Training Deep Nets with Sublinear Memory Cost (2016).
- Korthikanti et al., Reducing Activation Recomputation in Large Transformer Models (2022).
Key terms
Section titled “Key terms”- bf16: a 16-bit format with float32’s 8 exponent bits and 7 mantissa bits; float32’s range at unit roundoff .
- fp16: a 16-bit format with 5 exponent bits and 10 mantissa bits; finer precision but a maximum of 65504 and a smallest subnormal of .
- autocast: a scoped mode in which every matmul rounds its operands and output to a 16-bit format.
- master weights: the float32 copy of the parameters and optimizer state that receives every update.
- loss scale: a power of two that multiplies the loss so that small fp16 gradients stay representable; divided out before the update.
- dynamic loss scaling: halving and skipping the step on overflow, and doubling after a run of good steps.
- gradient accumulation: summing the gradients of micro-batches weighted by to reproduce one large batch’s gradient.
- activation checkpointing: discarding a segment’s activations in the forward pass and recomputing them during backward.
Summary
Section titled “Summary”- Mixed precision rounds what a matmul reads and writes, and nothing else: the weights stay float32 masters, so an update smaller than bf16’s spacing still lands.
- fp16 gradients below flush to zero. Multiplying the loss by multiplies every gradient by (backprop is linear), which lifts them into range; dividing by before the update undoes it, and a step whose gradients overflowed is skipped and halved.
- Weighting micro-batch ‘s mean loss by makes micro-batches give exactly the gradient of one batch of rows.
- A checkpointed segment reruns the same operations on the same values during backward, so its gradients are equal bit for bit, provided the rerun replays the random draws and its parameters are parents of the node.
Review questions
Section titled “Review questions”-
Why is the backward of
castthe cast of the gradient, and not the true derivative?Answer
The true derivative of rounding is zero almost everywhere, which would stop learning. Hardware passes the gradient through the conversion, and that gradient is itself stored in 16 bits, so the faithful emulation rounds it. This also makes the backward matmuls bf16 matmuls without any extra code.
-
Why is it safe to multiply the loss by and divide the gradients by , and why a power of two?
Answer
Backprop is linear in the upstream gradient, so every gradient is exactly times the true one, and dividing restores it. A power of two changes only the exponent, so neither the scaling nor the unscaling rounds.
-
Why does the scaler set every gradient to
Nonewhen it skips a step?Answer
A loop that forgets
zero_gradwould otherwise add the next step’s gradients onto or NaN and skip forever. Dropping them makes the skip leave no trace except the smaller . -
What goes wrong if
checkpointleaves the parameters out of the node’s parents?Answer
When the segment’s input is data (no
requires_grad),from_opsees no parent that requires grad and records no node, so backward never reaches the rerun and the segment’s parameters get no gradient. With the parameters as parents, the node is recorded and its VJP runs. -
Why does the VJP restore the generators to the after state when it is done?
Answer
Setting them to the before state replays the forward masks, but leaves the stream rewound. Later draws would then repeat earlier ones, and a run with checkpointing would diverge from one without it. Restoring the state the stream had reached makes the rerun invisible.
-
In the accumulation example, what gradient do you get by weighting each of the two micro-batches by , and why is it wrong?
Answer
instead of . Equal weights treat the 1-row micro-batch as if it held half the rows; only the row-count weights and reproduce the full batch’s mean.