Highlights

Contents

Part V
05

Keeping learning inside numerical limits

Training needs sensible starting values and usable arithmetic. Different tensor roles have different precision requirements. Explain symmetry breaking, numerical range, and memory categories before choosing a training configuration.

THE TRAINING CHAPTER: TEN PARTS, ONE COMPLETE MODEL1. features2. output3. examples + loss4. optimizer5. precision6. resume + loop7. evaluation8. experiments9. decoding10. whole pipelineforward computation → learn parameters → measure results → generate

#Section 15Initialization

Give every neuron the same starting weights and the same inputs, and their derivatives can remain the same. Make random weights too large and activations or attention scores may begin at an unhelpful scale. Initialization must both distinguish the learned features and keep the first forward and backward passes usable.

Initialization is the rule for assigning parameters before training begins. Random initialization samples selected weights from a declared distribution. It breaks the symmetry between otherwise identical channels; a fixed random seed chooses a repeatable sample. Other parameters can have deterministic initial values: RMSNorm gains often start at one, and biases, when present, may start at zero. “Initialize everything randomly” is not the rule.

Variance measures the average squared deviation from a mean. Under an illustrative independence model, the variance of a sum is the sum of variances. For a projected coordinate y=∑i=1nwixiy=\sum_{i=1}^{n}w_i x_i, independent zero-mean weights and inputs give:

Var⁡(y)=n Var⁡(w)Var⁡(x).\operatorname{Var}(y)=n\,\operatorname{Var}(w)\operatorname{Var}(x).

Read this as: the projected coordinate's variance equals the number of input terms nn times a weight's variance times an input coordinate's variance. This equation assumes independent terms with the same variance; learned vectors need not satisfy that assumption. It explains why weight scale should account for the number of incoming coordinates.

Xavier and Kaiming intuition

Fan-in is the number of input coordinates feeding an output; fan-out is the number of outputs receiving an input. Xavier initialization balances forward and backward variance using both fan-in and fan-out. Kaiming initialization accounts for the effect of a rectifier such as ReLU, whose positive-half selection changes the variance calculation. Neither formula is a universal optimal Transformer recipe.

σXavier=2nin+nout,σKaiming,ReLU=2nin.\sigma_{\text{Xavier}}=\sqrt{\frac{2}{n_{\text{in}}+n_{\text{out}}}},\qquad \sigma_{\text{Kaiming,ReLU}}=\sqrt{\frac{2}{n_{\text{in}}}}.

Read this as: with gain one, Xavier-normal weights have standard deviation equal to the square root of two divided by the input-plus-output counts; a fan-in ReLU Kaiming-normal choice has standard deviation equal to the square root of two divided by the input count. These specify a normal-distribution example, not the bounds for the related uniform initializers.

For a Finch-24-shaped 512→1,536512\to1,536 projection, the illustrative Xavier standard deviation is 2/2,048=0.03125\sqrt{2/2,048}=0.03125. The ReLU Kaiming value is 2/512=0.0625\sqrt{2/512}=0.0625. SwiGLU also multiplies two branches and uses SiLU, so importing a ReLU argument unchanged would miss that product. A model's trained initialization recipe must be assessed with its activation, norm placement and depth. Glorot and Bengio's 2010 work, He and colleagues' rectifier analysis, PyTorch initializer conventions.

FAN-IN COUNTS HOW MANY RANDOM TERMS ARE ADDEDw₁x₁w₂x₂…w₅₁₂x₅₁₂Var(y) = 512 × Var(w) × Var(x)illustrative independent zero-mean terms
Figure 3.24An illustrative projection sums 512 weighted inputs. The fan-in term explains why the weight distribution's variance must depend on width; the figure does not assume trained coordinates stay independent.

Transformer-specific scaling and the residual path

The earlier residual discussion introduces depth scaling for projections that write into the stream. Finch-24 has two residual additions per block and eight blocks, giving 16 additions. In a toy model with starting stream variance one and 16 independent unit-variance branch contributions, final variance would be 17. Scaling each contribution's standard deviation by 1/16=0.251/\sqrt{16}=0.25 reduces its variance to 1/161/16, so the final variance becomes two.

For an illustrative base weight standard deviation of 0.02, that residual-write scaling gives 0.005. It is a depth-aware initialization example, not a verified universal choice for every Llama-like architecture. Independence and equal contribution variance are a model for intuition; normalization, correlations and learning alter the actual trajectory.

RESIDUAL CONTRIBUTIONS ADD VARIANCE IN AN INDEPENDENCE MODELunscaled branchesVar = 17start 1 + 16 contributions × 1standard deviation × 0.25Var = 2start 1 + 16 contributions × 0.0625
Figure 3.25A calculated independence model compares 16 unscaled residual contributions with contributions scaled by one-quarter in standard deviation. Variance totals are 17 and 2, not measurements from a trained Finch-24 run.

Initialization affects early logit variance, gradient size and optimizer transients. Warmup can help with those transients, but cannot undo a missing mask or an incorrectly loaded parameter. When using a pretrained checkpoint, its learned values replace the initialization; creating and then reinitializing a tied head can accidentally overwrite the embedding too.

#Section 16Precision in neural-network training

A weight of one needs a very small change, but the chosen numeric format may round that change away. Another activation may be representable until squaring it exceeds the format's range. These are different failures: too few nearby representable values and too small a permitted magnitude range.

Floating point stores a sign, an exponent that determines scale, and a fraction that gives detail within that scale. FP32 is a common 32-bit format. FP16 is the IEEE half format, and BF16, bfloat16, uses a wider exponent and shorter fraction than FP16 while keeping the same total storage size. Numeric range is the span of magnitudes a format can represent. Precision describes how finely it resolves nearby numbers at a given scale.

Property FP32 FP16 BF16
Bits per scalar 32 16 16
Bytes per scalar 4 2 2
Exponent bits 8 5 8
Stored fraction bits 23 10 7
Largest finite value 3.402823×10383.402823\times10^{38} 65,504 3.389531×10383.389531\times10^{38}
Smallest positive normal 1.175494×10−381.175494\times10^{-38} 6.103516×10−56.103516\times10^{-5} 1.175494×10−381.175494\times10^{-38}
Spacing from 1 toward 2 1.192093×10−71.192093\times10^{-7} 0.0009765625 0.0078125

The spacing is local, not a constant absolute error at every magnitude. BF16 has approximately FP32's exponent range but far less precision. FP16 has more fraction bits than BF16 but a much narrower range. Neither format is uniformly "more accurate" across all possible computations.

SAME STORAGE SIZE CAN BUY DIFFERENT RANGE AND PRECISIONFP32±8 exponent23 fraction32 bitsFP16±5 exponent10 fraction16 bitsBF16±8 exponent7 fraction16 bitsone sign bit; the hidden leading bit is not stored for normal values
Figure 3.26The bit allocations explain the tradeoff. BF16 spends more bits on exponent range, while FP16 spends more on the fraction; both store two bytes per scalar.

Overflow occurs when a computed magnitude exceeds the representable finite range. Underflow concerns magnitudes near or below the smallest representable positive values. Subnormal values fill a small range below the normal minimum with reduced relative precision; actual kernels may flush them to zero. FP16's smallest positive subnormal is 2−24=5.960464×10−82^{-24}=5.960464\times10^{-8}. An illustrative gradient of 10−810^{-8} rounds to zero when cast to FP16 under ordinary nearest rounding, even though FP32 represents it.

A stable softmax subtracts its row maximum to prevent an avoidable exponent overflow. A norm can compute squares and reductions in FP32. These targeted choices are more useful than casting the whole training program to FP16 and hoping the same algorithm survives. Precision errors can accumulate, and floating-point addition is not associative: reordering a reduction can change its rounded result.

ZOOM IN ABOVE ONE: BF16 STEPS ARE WIDER THAN FP16 STEPSFP1611.0078125spacing 0.0009765625BF1611.0078125spacing 0.0078125same interval and scale; FP32 spacing is 2⁻²³ near one
Figure 3.27Computed representable steps above one compare FP16 with BF16 on the same numeric interval. Wider BF16 spacing is the price of its larger exponent range at the same storage size.

#Section 17Mixed-precision training

The model spends much of its work multiplying large matrices. Lower-precision inputs can use less memory bandwidth and, on suitable accelerators, faster matrix hardware. We still want enough range for sensitive operations and enough detail to accumulate small parameter changes. Using different precisions for different jobs is the basic solution.

Mixed-precision training evaluates selected operations in lower precision while keeping other operations or stored values at higher precision. Autocast chooses operation dtypes according to the framework's policy inside a region. It is not an instruction that every operation, gradient and optimizer buffer becomes 16-bit. Hardware support, tensor dimensions, kernel choice and the rest of the workload determine any speed benefit.

Lower-precision forward and FP32 values

A common PyTorch setup keeps the model parameters in FP32 and uses torch.amp.autocast for the forward and loss region. Selected linear operations use BF16 or FP16 representations; sensitive operations can remain or be explicitly performed in FP32. Backward follows the dtypes of the recorded operations; running backward outside the autocast region is the documented pattern. A matrix multiply may accumulate internally at higher precision on suitable hardware, but that is a kernel contract, not a property of every low-precision operation. Current autocast documentation.

python
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
    logits = model(x)                              # (B, T, V)
    loss = F.cross_entropy(logits.float().reshape(-1, V), y.reshape(-1))
loss.backward()

FP32 master values are high-precision parameter values retained for updates when a separate low-precision parameter copy is used for computation. In the FP32-parameter autocast setup, the persistent FP32 parameters already fill that role; another full FP32 copy is not inherently necessary. Directly storing BF16 parameters and using a custom optimizer can choose a different state layout. Check the implementation instead of inferring it from the word "mixed."

For an illustrative weight 1 and decrement 0.0001, the FP32 result is 0.9999, which rounds back to one in BF16. Repeating updates directly on the rounded BF16 value can keep losing such a change. A retained FP32 value can accumulate it before producing a BF16 computation copy. This illustrates rounding loss in updates, not a claim that every BF16-training implementation must use the same master-copy arrangement.

KEEP A SMALL UPDATE BEFORE ROUNDING THE COMPUTATION COPYFP32 retained value1 - 0.00010.9999direct BF16 value1 - 0.0001rounds back to 1the next update needs the retained value, not just its cast
Figure 3.28An illustrative small update survives in a stored FP32 value but can disappear in a directly rounded BF16 parameter. Master values retain changes that the computation copy cannot yet resolve.

Loss scaling and dynamic loss scaling

Loss scaling multiplies the loss by a factor SS before backward, producing gradients scaled by SS as well. The optimizer must see gradients divided by the same factor. This helps FP16 gradients avoid rounding to zero in the lower range; it does not create more information than the computation supplies.

∇θ(SL)=S∇θL,g=gscaledS.\nabla_\theta(S\mathcal L)=S\nabla_\theta\mathcal L,\qquad g=\frac{g_{\text{scaled}}}{S}.

Read this as: differentiating a loss multiplied by constant scale SS multiplies every parameter derivative by SS; divide the resulting gradient by SS to recover the intended correction. In exact arithmetic this is algebraically neutral. Rounding makes the intermediate range change useful.

An illustrative gradient 10−810^{-8} scaled by 65,536 becomes 0.00065536, within FP16's normal range. Unscaling must happen before clipping, or the threshold applies to the enlarged gradient. Dynamic loss scaling adjusts SS in response to finite and nonfinite gradients: a scaler can skip an overflowing update and reduce the scale, then grow it after a finite interval. It does not fix all causes of NaNs.

SCALE BEFORE BACKWARD, UNSCALE BEFORE CLIPPINGunscaled gradient0.00000001scale × 65,5360.00065536unscale ÷ 65,5360.00000001too small for FP16inside normal rangeoptimizer-sized gradientfinite check → clipping → optimizer step
Figure 3.29A calculated illustrative FP16 gradient is enlarged before the limited-range stage and reduced before the optimizer. Overflow detection can skip the update; clipping belongs after unscaling.
python
scaler = torch.amp.GradScaler("cuda")
with torch.amp.autocast("cuda", dtype=torch.float16):
    loss = compute_loss(model(x), y)
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optimizer)
scaler.update()

BF16 usually does not need FP16-style loss scaling because its exponent range is much wider. That does not make BF16 overflow, rounding or poor optimization impossible. Use the current torch.amp interface rather than the deprecated torch.cuda.amp forms. Micikevicius and colleagues' mixed-precision paper explains master copies and loss scaling; their arrangement is one specific memory design.

#Section 18GPU memory during training

Weights alone undercount training memory. Gradients, optimizer history, saved forward values, and temporary buffers also need space.

An optimizer state is persistent history used by the update rule, such as Adam's mm and vv. Activations are tensors computed from input data inside the forward pass. An activation checkpoint saves selected values and recomputes other forward operations during backward, trading extra computation for less saved activation memory. This differs from a disk training checkpoint, which Part VI will explain.

A named-tensor ledger

Optimizer history may be allocated only after an update. Measure representative forward, backward, and optimizer steps rather than inspecting memory immediately after loading.

Persistent state depends on parameter, gradient, and optimizer dtypes, master copies, and offloading. Autocast alone does not specify one universal memory layout.

FULL FP32 ADAMW: FOUR NAMED ARRAYS PER LEARNED SCALARparameters4 bytes / scalar154.533 MiBgradients4 bytes / scalar154.533 MiBmoment m4 bytes / scalar154.533 MiBmoment v4 bytes / scalar154.533 MiB648,159,232 bytes = 618.133 MiBactivations, cast copies, workspaces and allocator reserves are extra
Figure 3.30Finch-24’s full FP32 AdamW layout stores four equal-size named arrays. The 648,159,232-byte subtotal excludes saved activations, temporary tensors and allocator overhead.

Batch size and sequence length

Feature activations grow with batch size and sequence length. A materialized attention grid grows with position pairs, so long sequences can introduce a different memory bottleneck.

SEQUENCE LENGTH CHANGES ACTIVATION AND SCORE TENSORS DIFFERENTLYT = 8T = 4096residual: B × T × d16 KiB8 MiBone FFN branch: B × T × f48 KiB24 MiBscores: B × H × T²2 KiB512 MiBB = 2, H = 8, BF16; these are single named tensors
Figure 3.31Calculated named-tensor counts separate linear activation growth from quadratic materialized attention scores. Fused attention avoids saving the complete score grid; it does not remove the dense attention arithmetic.

The FlashAttention chapter explains how avoiding that score grid changes storage and memory traffic. Checkpointing can reduce saved activations, accumulation can reduce the active microbatch size at a fixed effective batch, and sharding can partition persistent state. These solve different parts of the ledger. Shorter contexts may change the modeling task, so they are not a neutral memory optimization.

Fixed-weight inference does not retain gradients or Adam history. Fitting its weights therefore does not establish that full training fits on the same device.

Activation recomputation

Activation checkpointing, also called rematerialization, saves selected boundary activations and recomputes omitted intermediates during backward. It trades additional forward work for reduced saved-activation memory. It is separate from a disk training checkpoint, which saves the experiment for later resume. The recomputed region must behave consistently with the original forward, including random draws and any mutable state; read the library’s RNG and reentrant behavior contract rather than assuming arbitrary code can be replayed.

The PyTorch checkpoint API documents these execution choices. This method can help when retained activations dominate, but it does not remove the model’s parameters, gradients or optimizer moments. Chunking the output loss or using an attention kernel that avoids materialized score matrices tackles different categories in the memory ledger. A memory intervention should identify the category it saves.

REMATERIALIZATION TRADES EXTRA FORWARD WORK FOR SAVED ACTIVATIONSretain intermediatesinputstage 1stage 2stage 3save boundary inputinputstage 1stage 2stage 3recompute inside the region when backward needs it
Figure 3.32An illustrative region either retains its intermediate activation grids or saves a boundary input and regenerates the interior during backward. The grids show the storage policy, not a measured peak-memory reduction.