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.
#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 , independent zero-mean weights and inputs give:
Read this as: the projected coordinate's variance equals the number of input terms 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.
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 projection, the illustrative Xavier standard deviation is . The ReLU Kaiming value is . 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.
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 reduces its variance to , 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.
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 | 65,504 | ||
| Smallest positive normal | |||
| Spacing from 1 toward 2 | 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.
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 . An illustrative gradient of 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.
#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.
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.
Loss scaling and dynamic loss scaling
Loss scaling multiplies the loss by a factor before backward, producing gradients scaled by 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.
Read this as: differentiating a loss multiplied by constant scale multiplies every parameter derivative by ; divide the resulting gradient by to recover the intended correction. In exact arithmetic this is algebraically neutral. Rounding makes the intermediate range change useful.
An illustrative gradient 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 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.
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 and . 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.
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.
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.