Skip to content

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.

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.

The section uses a handful of symbols throughout; here they are in one place.

SymbolMeaningType / shape
rd16(x)\mathrm{rd}_{16}(x)xx rounded to nearest, ties to even, into bf16 or fp16elementwise
ppthe precision of a format, in significant bits: 24 (fp32), 11 (fp16), 8 (bf16)int
u=2−pu = 2^{-p}the unit roundoff: the largest relative error of one roundingfloat
wwa parameter (the float32 master copy)float32[...]
η\etathe learning ratefloat
LL, g=∂L/∂wg = \partial L/\partial wthe loss and a gradientfloat, like ww
SSthe loss scale (loss_scale)float, a power of 2
NN, nin_i, kkrows in the full batch, rows in micro-batch ii, number of micro-batchesint
LiL_ithe mean loss over micro-batch ii‘s rowsfloat
sjs_j, PPsegment sizes and peak memory of a checkpoint scheduleint

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 3.4×10383.4 \times 10^{38}) with p=8p = 8, so u=2−8≈0.4%u = 2^{-8} \approx 0.4\%. fp16 has 5 exponent bits and 10 mantissa bits: p=11p = 11, u≈0.05%u \approx 0.05\%, but its largest finite value is 65504, its smallest normal 2−14≈6.1×10−52^{-14} \approx 6.1 \times 10^{-5}, and its smallest subnormal 2−24≈6×10−82^{-24} \approx 6 \times 10^{-8}. 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 Y=ABY = AB becomes

Y=rd16(rd16(A) rd16(B)),the product computed in float32.Y = \mathrm{rd}_{16}\big(\mathrm{rd}_{16}(A)\, \mathrm{rd}_{16}(B)\big), \qquad \text{the product computed in float32}.

Each operand entry has relative error up to uu, and the output gets one more rounding. Errors of different entries look independent, so a dot product of length KK drifts by about K u\sqrt K\, u relative, not KuK u. For training this is noise of a few tenths of a percent, smaller than minibatch noise.

To put that rounding into the autograd graph, write the emulated storage as an op cast with forward y=rd16(x)y = \mathrm{rd}_{16}(x). 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: xˉ=rd16(yˉ)\bar x = \mathrm{rd}_{16}(\bar y).

Built from from_op, the autocast matmul is cast(cast(a) @ cast(b)), and its backward computes Aˉ=rd16(rd16(Yˉ) rd16(B)⊤)\bar A = \mathrm{rd}_{16}(\mathrm{rd}_{16}(\bar Y)\, \mathrm{rd}_{16}(B)^\top): 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.

The update w←w−ηgw \leftarrow w - \eta g is where precision matters most. The spacing of bf16 numbers near 1 is 2−7≈0.00782^{-7} \approx 0.0078, so a weight of 1 updated by ηg=10−3\eta g = 10^{-3} 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.

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 (softmax−onehot)/N(\mathrm{softmax} - \mathrm{onehot})/N, and backpropagated through a few layers many entries fall below 2−242^{-24} and flush to zero.

The fix comes from one observation: backprop is linear in the upstream gradient. Every VJP is linear in yˉ\bar y, so starting backward from S⋅LS \cdot L instead of LL multiplies every gradient by exactly SS. Choose SS so the small gradients land in fp16’s normal range, then divide the float32 master gradients by SS before the update. With SS a power of two, scaling and unscaling are exact, because they only change the exponent.

Too large an SS, however, overflows the large gradients to ∞\infty (and ∞−∞\infty - \infty 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 SS by the backoff 12\tfrac12. After interval consecutive good steps, multiply SS 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.

Memory is the other constraint, and accumulation addresses it by splitting a batch. The loss of a batch of NN rows is the mean of per-row losses ℓr\ell_r. Split the rows into micro-batches B1,…,BkB_1, \dots, B_k with nin_i rows each, and let LiL_i be micro-batch ii‘s own mean. Then

L=1N∑rℓr=∑i=1kniN⋅1ni∑r∈Biℓr=∑i=1kniNLi,L = \frac1N \sum_{r} \ell_r = \sum_{i=1}^k \frac{n_i}{N} \cdot \frac{1}{n_i}\sum_{r \in B_i} \ell_r = \sum_{i=1}^k \frac{n_i}{N} L_i,

and since the gradient is linear, ∇L=∑iniN∇Li\nabla L = \sum_i \tfrac{n_i}{N} \nabla L_i. Backpropagating niNLi\tfrac{n_i}{N} L_i for each micro-batch, without zeroing in between (the Tensor adds into .grad), accumulates exactly ∇L\nabla L, and only one micro-batch’s activations exist at a time. Weighting by 1k\tfrac1k 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.

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 xx 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.

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 A=[1,1]A = [1, 1] and B=[1,2−8]⊤B = [1, 2^{-8}]^\top. Both are bf16 values already. The float32 product is 1+2−8=1.003906251 + 2^{-8} = 1.00390625. Its bf16 neighbours are 1 and 1+2−71 + 2^{-7}, with 1+2−81 + 2^{-8} exactly halfway; ties go to the even mantissa, so autocast returns 1.01.0. An input of 1.011.01 is stored as 1.0078125=1+2−71.0078125 = 1 + 2^{-7}, the nearest bf16 value. For L=∑YL = \sum Y, Yˉ=1\bar Y = 1, so Aˉ=rd(Yˉ) rd(B)⊤=[1,2−8]\bar A = \mathrm{rd}(\bar Y)\,\mathrm{rd}(B)^\top = [1, 2^{-8}] and Bˉ=rd(A)⊤rd(Yˉ)=[1,1]⊤\bar B = \mathrm{rd}(A)^\top \mathrm{rd}(\bar Y) = [1, 1]^\top. The same product outside autocast is the float32 1.003906251.00390625.

Accumulation. Use one weight w=1w = 1, inputs x=[1,2,3,4]x = [1, 2, 3, 4], targets 2x2x, and the loss the mean of (wx−2x)2(wx - 2x)^2. With w=1w = 1 the residuals are −x-x. The table compares one batch with a split into micro-batches of 1 and 3 rows:

rowsLiL_i∂Li/∂w=mean(2(wx−2x)x)\partial L_i/\partial w = \mathrm{mean}(2(wx - 2x)x)weight
one batch1, 2, 3, 4(1+4+9+16)/4=7.5(1 + 4 + 9 + 16)/4 = 7.52(−1−4−9−16)/4=−152(-1 - 4 - 9 - 16)/4 = -151
micro-batch 111−2-21/41/4
micro-batch 22, 3, 429/329/32(−4−9−16)/3=−58/32(-4 - 9 - 16)/3 = -58/33/43/4

Weighted, the gradient is 14(−2)+34(−583)=−0.5−14.5=−15\tfrac14(-2) + \tfrac34(-\tfrac{58}{3}) = -0.5 - 14.5 = -15, and the loss is 14⋅1+34⋅293=7.5\tfrac14 \cdot 1 + \tfrac34 \cdot \tfrac{29}{3} = 7.5. Weighting each micro-batch by 12\tfrac12 gives −10.67-10.67; not weighting at all gives −21.3-21.3.

Loss scaling. Take S=8S = 8, growth 2, backoff 12\tfrac12, interval 2, and SGD with η=0.5\eta = 0.5 on one parameter starting at 0. The scaled gradients arrive as follows:

stepscaled ggfinite?unscaled g/Sg/Sww afterSS aftergood steps
18yes1−0.5-0.581
2∞\inftyno: skip−0.5-0.540
34yes1−1.0-1.041
48yes2−2.0-2.08 (grown)0
516yes2−3.0-3.081

If the count did not restart at the overflow, step 3 would already be the second good step and would grow SS 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 [2,2,2,1,1,1][2, 2, 2, 1, 1, 1]), and every gradient equals the plain run’s.

The interface is small: one op, one context manager, one scaler class, and two functions for the training step, plus the two checkpointing functions.

python/tinyllm/train/precision.py
def cast(x: Tensor, dtype: Literal["bf16", "fp16"]) -> Tensor # rounds forward and backward
@contextmanager
def 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) -> None
def grad_accumulate(model, micro_batches, loss_fn, scaler=None) -> float # weights n_i / N
def train_step_mixed(model, micro_batches, loss_fn, opt, precision="fp32", scaler=None, clip=None) -> dict
# python/tinyllm/train/recompute.py
def checkpoint(fn, *args, params=(), rngs=()) -> Tensor
def checkpoint_sequential(layers, x, mem_budget_layers, rngs=()) -> Tensor # uses checkpoint_schedule

train_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.

Before reading the code, it helps to see how each design decision follows from the principles above.

  1. 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.
  2. So rounding must be a graph op, not a numpy call. If the forward pass rounded a.data in place, the backward pass would see float32 gradients. Making cast a from_op node with VJP xˉ=rd16(yˉ)\bar x = \mathrm{rd}_{16}(\bar y) gives the backward matmuls the same rounding for free, because the autograd engine composes VJPs.
  3. 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.
  4. Loss scaling follows from linearity. Every VJP is linear in its upstream gradient, so backpropagating SLS L produces SgS g. Scaling the loss is one multiplication; unscaling is one multiplication of each master gradient by 1/S1/S. Everything after unscaling (clipping, the optimizer) then works in true gradient units.
  5. 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 SS, restart the count. Growth is the mirror image: after interval good steps, double SS and restart the count.
  6. Accumulation is a reweighting of the loss. By the identity derived above, backpropagating niNLi\tfrac{n_i}{N} L_i for each micro-batch without zeroing sums to ∇L\nabla L. The weight must use row counts, which means the solution must know each micro-batch’s size before it starts.
  7. 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.

_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:

@contextmanager
def 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 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 True

state_dict saves good_steps along with SS, so a resumed run grows SS on the same step the uninterrupted run would.

Accumulation computes all sizes first, because each weight needs the total NN:

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 out

train_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().

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.

The costs are modest. Autocast adds three elementwise roundings per matmul, O(size)O(\text{size}) next to the matmul’s O(MNK)O(MNK). Accumulation costs nothing extra in compute and divides activation memory by kk. Checkpointing with segments sjs_j 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 SS 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 ni/Nn_i/N beats 1/k1/k 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.

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.

CaseKind of checkChecksWhy it matters downstream
hand example: bf16 matmulunit1+2−8→11 + 2^{-8} \to 1, 1.01→1.00781251.01 \to 1.0078125, bf16 gradientsthe emulation is pinned to exact values
hand example: accumulationunitloss 7.5, gradient −15-15 from micro-batches of 1 and 3the capstone’s --accum 4
hand example: loss scalerunitthe five-step trace of SS, the count, and wwfp16 runs
hand example: checkpoint scheduleunitforward counts [2,2,2,1,1,1][2, 2, 2, 1, 1, 1], equal gradients--checkpoint-activations
cast rounds both directionsunitboth formats, forward and gradient, dtype keptthe op every autocast matmul is built from
autocast matmul matches a rounded referencepropertyrandom products, reflected operands, Linearattention and MLP matmuls
gradients are bf16, masters stay float32propertyweight gradients are bf16 values; a 10−310^{-3} update survives in the masterwhy mixed precision converges
autocast restores the matmulboundaryan exception, nesting, an unknown dtypeno bf16 leaking into the next eval
fp16 underflow rescued by loss scalingdifferentialtiny gradients vanish in fp16 and match float32 once scaledfp16 hardware
scaler skips inf stepspropertyan overflow changes nothing, drops gradients, halves SS until steps succeeda long run survives a spike
scaler unscales before clippingdifferentialclip to 1 of a gradient of norm 5 scaled by 1024the clip bound means what it says
scaler state round tripunitresume keeps SS and the count; bad arguments raiseTrainRun resumes from checkpoints
accumulation equals one big batchdifferentialmicro-batches of 5, 11, 16 rows equal one of 32 to 10−610^{-6}the capstone’s loss within 2%
bf16 training tracks float32differential60 AdamW steps in bf16 end within 2% of float32the capstone in miniature
NaN loss rejectedboundarya NaN loss raises before any updatethe training loop’s guarantee kept
checkpoint gradients bitwise equaldifferential7 layers, three budgets, float64 and float32, bit for bitcheckpointing never changes training
checkpoint replays the dropout generatordifferentialsame masks, and the stream ends where the plain run’s doesdropout in the capstone
parameters learn from a data inputunitthe first segment’s parameters learn from a data inputthe embedding and first block
checkpoint called directlyboundarya tensor passed twice, a number argument, no_gradcheckpoint used directly
checkpointing lowers peak memorypropertytracemalloc: forward under half, overall peak lowerthe 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/finally around 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. autocast restores the methods in finally, and only the block that empties _stack unpatches.

Accumulation. Weighting micro-batches by 1/k1/k gives the wrong gradient whenever the sizes differ; grad_accumulate weights by n / total. Summing micro-batch losses makes gradients kk 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 SS 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 ∞\infty; a skipped step sets every p.grad = None. Not restarting the count after an overflow grows SS right back into overflow; good_steps = 0 on overflow and on growth. Clipping before unscaling makes the clip act on S⋅gS \cdot g and produces tiny updates; unscaling comes before clip_grad_norm_. Losing the count on resume makes the resumed run grow SS 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.

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 pieceProduction equivalentWhat it addsWhere to look
autocasttorch.autocastper-op cast policies (softmax and norms kept in float32), real bf16 kernelstorch/amp/autocast_mode.py, aten/src/ATen/autocast_mode.cpp
DynamicLossScalertorch.amp.GradScalerper-device inf checks fused into one kernel, optimizer-step skippingtorch/amp/grad_scaler.py
bf16 and fp16NVIDIA Transformer Enginefp8 matmuls with per-tensor delayed scaling, the same idea one format lowertransformer_engine/pytorch/fp8.py
checkpoint_sequentialtorch.utils.checkpointnon-reentrant checkpointing with saved-tensor hooks, RNG state for every devicetorch/utils/checkpoint.py
uniform segmentsMegatron-LM selective recomputationrecompute only attention’s cheap, large softmax and dropout, keep the matmul outputsmegatron/core/tensor_parallel/random.py
grad_accumulateDeepSpeed gradient_accumulation_stepsaccumulation fused with ZeRO’s gradient partitioningdeepspeed/runtime/engine.py
  • bf16: a 16-bit format with float32’s 8 exponent bits and 7 mantissa bits; float32’s range at unit roundoff 2−82^{-8}.
  • 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 2−242^{-24}.
  • 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 SS that multiplies the loss so that small fp16 gradients stay representable; divided out before the update.
  • dynamic loss scaling: halving SS and skipping the step on overflow, and doubling SS after a run of good steps.
  • gradient accumulation: summing the gradients of micro-batches weighted by ni/Nn_i/N to reproduce one large batch’s gradient.
  • activation checkpointing: discarding a segment’s activations in the forward pass and recomputing them during backward.
  • 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 2−242^{-24} flush to zero. Multiplying the loss by SS multiplies every gradient by SS (backprop is linear), which lifts them into range; dividing by SS before the update undoes it, and a step whose gradients overflowed is skipped and SS halved.
  • Weighting micro-batch ii‘s mean loss by ni/Nn_i/N makes kk micro-batches give exactly the gradient of one batch of NN 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.
  1. Why is the backward of cast the 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.

  2. Why is it safe to multiply the loss by SS and divide the gradients by SS, and why a power of two?

    Answer

    Backprop is linear in the upstream gradient, so every gradient is exactly SS times the true one, and dividing restores it. A power of two changes only the exponent, so neither the scaling nor the unscaling rounds.

  3. Why does the scaler set every gradient to None when it skips a step?

    Answer

    A loop that forgets zero_grad would otherwise add the next step’s gradients onto ∞\infty or NaN and skip forever. Dropping them makes the skip leave no trace except the smaller SS.

  4. What goes wrong if checkpoint leaves the parameters out of the node’s parents?

    Answer

    When the segment’s input is data (no requires_grad), from_op sees 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.

  5. 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.

  6. In the accumulation example, what gradient do you get by weighting each of the two micro-batches by 12\tfrac12, and why is it wrong?

    Answer

    12(−2)+12(−583)≈−10.67\tfrac12(-2) + \tfrac12(-\tfrac{58}{3}) \approx -10.67 instead of −15-15. Equal weights treat the 1-row micro-batch as if it held half the rows; only the row-count weights 14\tfrac14 and 34\tfrac34 reproduce the full batch’s mean.