Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college lesson →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

Training TricksUnderstand the moving parts.

The optimizations that turn theoretical training into practical training.

Suggested preparation: None

WORKBENCH / CHANGE ONE THING

Watch an optimizer overshoot

Change the step size on a quadratic loss and inspect every update.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Walk downhill with small and large steps and predict when you cross the valley.

Where this deserves more time

Adam bias correction; decoupled decay; accumulation; FP16 versus BF16.

Open the complete high-school reading

Moment 01 / 10

Course Introduction and Objectives

Welcome. This module turns training from a black box into an engineering discipline: the objective is to make large models fit memory, time, and energy budgets without sacrificing optimization stability.

We will study mixed precision, where most matrix multiplications run in half precision or bfloat sixteen while sensitive reductions stay in single precision, paired with loss scaling to protect small gradients.

The naive view is that lower precision only speeds hardware; in practice it changes noise, gradient norms, and layer normalization statistics, so throughput and stability must be co-designed.

These methods are the substrate for recent systems: trillion-token pretraining, long-context transformers, mixture-of-experts, and preference tuning all depend on disciplined numerics.

By the end, you should read a training curve like a diagnostician: connect loss spikes, gradient norm explosions, and memory pressure to precision, clipping, and optimizer state.

Equations, code and original cards

Training Optimizations: Course Objectives

• Mixed precision: tensor cores, loss scaling, stable reductions

• Gradient optimization: clipping, AdamW, ZeRO, curriculum and batching

• Systems relevance: long context, MoE, RLHF and DPO, 2024–2026 constraints

Moment 02 / 10

Fundamentals of Gradient Descent and Optimizers

Gradient descent is the workhorse of deep learning: choose a loss, differentiate it, and move parameters downhill; optimizers determine how intelligently that step is taken.

A loss such as cross entropy measures discrepancy between predicted logits and targets; its negative log likelihood objective turns prediction into minimization. The gradient is the Jacobian transpose of that scalar with respect to parameters, pointing along steepest ascent, so we step against it.

Matrix calculus makes this scalable: Jacobians propagate derivatives through linear maps, Hessians encode curvature, and vectorized contractions let backpropagation evaluate billion parameter gradients without symbolic explosion.

The update is steepest descent under a Euclidean trust region: at iteration k plus one, set the parameter vector equal to its previous value minus the step size times the gradient, with gradient norm controlling displacement.

In words, parameters move opposite the local slope by a learning rate scaled gradient; too large diverges, too small wastes compute, and curvature makes a single global rate crude.

AdamW, the decoupled weight decay variant of Adam from Kingma and Ba, remains the default for transformers: exponential moving averages estimate first and second gradient moments, bias correct them, then normalize each coordinate while weight decay acts outside the adaptive step.

The first moment is an exponential moving average of gradients, governed by beta one; it behaves like momentum, damping oscillations and accelerating along persistent descent directions.

The second moment accumulates squared gradients under beta two, approximating per coordinate variance; its square root rescales steps, a diagonal preconditioner rather than full curvature.

The parameter step divides bias corrected momentum by that root mean square scale, adds decoupled weight decay, and multiplies by the learning rate, balancing signal, noise, and regularization.

The picture is coherent: losses define geometry, gradients supply local descent directions, matrix calculus makes them computable, and AdamW preconditioners stabilize training at transformer scale. Master these mechanics before chasing exotic schedules or architectures.

Clarification: AdamW includes bias correction and decoupled weight decay.

Equations, code and original cards

Gradient Descent and Adaptive Optimizers

From empirical risk to AdamW preconditioning

• Cross-entropy: negative log likelihood
• Gradient: Jacobian transpose of scalar loss
• Descent direction: steepest local slope

• Matrix calculus: Jacobians, Hessians, contractions
• Backpropagation: vectorized chain rule
• Scales to billion-parameter models

\theta^{(k+1)} = \theta^{(k)} - \eta \nabla L(\theta^{(k)})

Steepest descent update
(θ: parameters, η: learning rate, ∥g∥: gradient norm)

AdamW: moments, bias correction, decoupled weight decay

m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t
v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2
\hat m_t=m_t/(1-\beta_1^t),\quad\hat v_t=v_t/(1-\beta_2^t);\quad\theta_t=(1-\eta\lambda)\theta_{t-1}-\eta\hat m_t/(\sqrt{\hat v_t}+\epsilon)

Moment 03 / 10

Interactive: Tune AdamW Optimizer Parameters

This simulation visualizes AdamW, which combines adaptive per-parameter learning rates with decoupled weight decay, as a ball descending a one-dimensional loss surface.

Raising the learning rate scales each update step, but beyond a critical threshold the iterates oscillate and diverge rather than converge to the minimum.

Now vary beta one, the exponential decay of the first moment estimate; higher momentum accelerates traversal of flat regions and escapes shallow local minima.

Finally, increase the decoupled weight decay; it shrinks parameters toward zero each step, biasing the solution toward smaller norms and better generalization.

Equations, code and original cards

Moment 04 / 10

Mixed Precision Training Fundamentals

Mixed precision training is controlled numerical error: choose formats that cut bandwidth and arithmetic cost while keeping optimization statistically unbiased.

FP32 carries one sign, eight exponent, and twenty three mantissa bits; bfloat16 keeps the eight bit exponent but only seven mantissa bits, so range survives while resolution drops, which is why gradients usually remain representable.

Halving parameter and activation bytes reduces memory traffic, raises effective batch size, and lets tensor cores execute matrix multiplies at much higher throughput on modern accelerators.

The update remains theta next equals theta minus learning rate times gradient, but with bfloat16 forward and backward passes, FP32 master weights, and loss scaling to stop tiny gradients underflowing during accumulation.

The payoff is not magic accuracy; it is arithmetic intensity. Fewer bytes per element increase cache residency and utilization, so the same GPU trains larger models or finishes sooner.

In practice: keep sensitive reductions and master states in FP32, run the bulk in bfloat16, verify gradient norms, and measure stability before scaling.

Equations, code and original cards

Mixed Precision Training Fundamentals

Precision Formats Comparison

• FP32: 1 sign, 8 exponent, 23 mantissa bits; default for master weights
• BF16: 1/8/7 layout; FP32 range, coarse resolution
• Tensor cores favor BF16 matmuls; bandwidth and FLOPs improve

Storage and Computation Trade-offs

• BF16 halves bytes for weights, activations, and optimizer traffic
• Larger batches or deeper layers fit the same memory envelope
• FP32 master weights absorb update rounding error
• Bottleneck shifts from HBM bandwidth toward compute

Precision Scaling, Update Rule, and Stability

• SGD step: theta sub t plus one equals theta sub t minus eta times g sub t
• BF16 keeps exponent range; mantissa rounding is the error source
• Compute in BF16, accumulate and store master weights in FP32
• Scale loss by S, then unscale gradients to prevent underflow

Moment 05 / 10

ZeRO: Memory Optimization for Large Models

ZeRO, introduced by Rajbhandari and colleagues in 2020, eliminated the redundancy of data-parallel training, where every GPU replicates the full model state. By sharding parameters, gradients, and optimizer states across devices, it made trillion-parameter regimes feasible on finite clusters.

The bottleneck is arithmetic, not compute. Under mixed-precision Adam, each parameter costs sixteen bytes: two for the half-precision weight, two for its gradient, and twelve for the optimizer's master copy plus first and second moments.

ZeRO's three stages partition progressively more state: stage one shards optimizer moments, stage two adds gradients, and stage three shards the parameters themselves, cutting per-device memory from sixteen bytes per parameter to sixteen over the device count.

The cost is communication. Stage three replaces one all-reduce with an all-gather of parameters in both passes plus a reduce-scatter of gradients, raising volume from two to three times the parameter count.

The payoff is multiplicative: memory falls roughly linearly with device count while throughput stays near the bandwidth-optimal ring baseline, so a fixed cluster trains models an order of magnitude larger without pipeline bubbles.

The lesson generalizes: treat aggregate GPU memory as one logical pool, shard the state, and pay for it with collective communication. That principle underlies fully sharded data parallelism and every modern large-scale training stack.

Equations, code and original cards

ZeRO: Zero Redundancy Optimizer for Trillion-Scale Training

Memory Wall: 16 Bytes per Parameter under Mixed-Precision Adam

Three Stages: Shard Optimizer State, Gradients, then Parameters

Collectives: All-Gather Parameters, Reduce-Scatter Gradients (1.5x DDP Volume)

Payoff: Near-Linear Memory Reduction at Ring-All-Reduce Throughput

Moment 06 / 10

Code Illustrations: Implementing Mixed Precision and Optimizers

We will inspect PyTorch implementations of mixed precision and optimizer configuration, emphasizing numerical stability rather than convenience flags.

Autocast casts eligible matmuls and convolutions to half precision or bfloat sixteen, while master weights, reductions, softmax, and layer normalization remain single precision; the speedup comes from tensor cores, not from changing the objective.

The imports are minimal: torch, its neural network and optimizer modules, and the automatic mixed precision interface for autocast plus gradient scaling.

AdamW, following Loshchilov and Hutter, applies weight decay outside the adaptive moment update, so regularization is not scaled by the second moment estimate.

The scaler multiplies the loss by a dynamic factor, checks gradients for infinities, then unscales before clipping the global norm, preventing underflow without hiding instability.

In the loop, zero gradients, run forward under autocast, scale the loss, step only after unscaling and clipping, then update the scale each iteration.

The principle is simple: exploit half precision throughput where it is safe, keep optimization state exact, and make gradient pathology explicit.

Equations, code and original cards

Code Illustrations: Mixed Precision and Optimizer Mechanics

Mechanisms to Inspect

• Autocast with torch.cuda.amp; single-precision master state

• AdamW: decoupled weight decay, bias-corrected moments

• Dynamic loss scaling, unscale, global-norm clipping

• Loop order: zero, autocast, scale, step, update

import torch
from torch import nn, optim
from torch.cuda import amp
optimizer = optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
scaler = amp.GradScaler()
scaler.unscale_(optimizer); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

Moment 07 / 10

Advanced Variations and Research Trends (2024-2026)

Let's survey the frontier of training optimization research from 2024 through 2026. This slide collects the directions currently driving gains in compute efficiency, convergence stability, and alignment.

First, scaling laws remain the compass for training efficiency. Following Kaplan et al. and the Chinchilla correction, optimal compute allocation scales parameters roughly linearly with tokens at about twenty tokens per parameter, and recent work refines these exponents under mixed precision.

Second, novel gradient manipulations and adaptive techniques target convergence and stability. Think gradient clipping with adaptive norms, per-layer learning rate schemes, and loss scaling strategies that preserve signal under bfloat16 arithmetic.

Third, open questions in optimizer alignment ask whether our update rules actually match model objectives. Shampoo, Muon, and second-order methods expose gaps between what we optimize and what generalizes.

Finally, the 2026 literature on these topics offers rigorous ablations and scaling studies. These papers supply the experimental evidence grounding each technique we discuss.

In summary, tracking these trends lets you anticipate where training efficiency is heading, an essential skill for anyone building state-of-the-art systems.

Equations, code and original cards

Advanced Variations and Research Trends (2024-2026)

Frontier research in mixed precision and gradient-based optimization:

Scaling laws, efficiency gains, and alignment challenges, 2024 to 2026

Key Points

• Refined scaling laws for compute-optimal training

• Adaptive gradient manipulation and clipping schemes

• Open problems in optimizer-objective alignment

• Key references from the 2026 literature

Moment 08 / 10

Whiteboard: Deriving Key Formulae

Today we derive the core formulae underlying modern training: the gradient descent update, matrix calculus for backpropagation, and the error analysis that governs mixed precision arithmetic.

We begin with the gradient descent update, where each parameter moves opposite the loss gradient, scaled by the learning rate, to decrease the objective.

The update reads theta at step t plus one equals theta at step t minus eta times the gradient of the loss J. This first order rule anchors nearly all deep learning optimizers.

For backpropagation, matrix calculus gives gradients with respect to each weight matrix by composing Jacobians through the chain rule, propagating the loss signal backward layer by layer.

The partial derivative of the loss L with respect to W is the local sensitivity; multiplying the upstream gradient by the local Jacobian yields exactly the descent direction for that layer.

Finally we bound the rounding error delta introduced by mixed precision, where half precision storage accelerates computation but perturbs gradients enough to threaten stability if left uncontrolled.

The bound shows rounding noise epsilon round compounding across steps, which motivates loss scaling, stochastic rounding, and decoupled weight decay as in AdamW to keep updates unbiased.

In summary, we derived the gradient update, expressed backpropagation as Jacobian composition, and bounded mixed precision error; together these justify momentum, weight decay, and loss scaling as principled, stable choices.

Equations, code and original cards

Whiteboard: Deriving Key Formulae

• Gradient update: first-order descent on \(J(\theta)\)

• Backpropagation as Jacobian composition

• Rounding-error bounds in mixed precision

• Why momentum and decoupled weight decay work

\theta_{t+1} = \theta_t - \eta \nabla_\theta J(\theta_t)

Gradient update: \(\theta_{t+1}=\theta_t-\eta\nabla_\theta J\)

• \(\theta_t\): parameters at step \(t\)

• \(\eta\): learning rate (step size)

• \(\nabla_\theta J\): steepest-ascent direction of loss

\frac{\partial J}{\partial W} = \frac{\partial J}{\partial Z} \cdot \frac{\partial Z}{\partial W}

Backpropagation via matrix calculus:

• \(\partial L/\partial W\): layer sensitivity

• Chain rule = product of local Jacobians

• Upstream gradient times local Jacobian

\delta_{\text{mixed}} \approx \delta_{\text{float32}} + \epsilon_{\text{round}}

Error bounds in mixed precision:

• \(\delta\): accumulated numerical error

• \(\epsilon_{\text{round}}\): per-op rounding noise

• Loss scaling keeps FP16 gradients representable

Moment 09 / 10

Challenging Quiz: Conceptual and Computational Questions

Time to stress-test your understanding of the training optimizations we just covered, from mixed precision and gradient checkpointing to FlashAttention's memory footprint. Work each problem independently; several have deliberately wrong naive answers.

Submit your answers when ready. I'll walk through each solution, flagging the failure modes that matter most when you're scaling runs past ten to the twenty-third FLOPs.

Equations, code and original cards

Moment 10 / 10

Summary and Further Reading

We close by recasting mixed precision as a numerical contract: keep master weights and reductions in single precision, run matmuls in half precision, and recover stability with dynamic loss scaling rather than guesswork.

The optimizer lesson is equally concrete: Adam W decouples weight decay from adaptive moments, LAMB rescales layerwise updates for large batches, and clipping plus warmup or restarts controls gradient norm spikes.

The reading list anchors these ideas: Micikevicius and colleagues on mixed precision, Kingma and Ba on Adam, Loshchilov and Hutter on Adam W and warm restarts, You on LAMB, and ZeRO plus Megatron for memory and parallelism.

For next steps, reproduce a small transformer twice, with and without half precision, log loss scale, gradient norm, throughput, and final validation perplexity, then ablate clipping, warmup, and batch size.

The takeaway is that speed is won by controlling numerics, not by hoping they behave: measure utilization, watch the residual stream and logits for overflow, and treat every optimization as a falsifiable ablation.

Equations, code and original cards

Summary and Further Reading

• Recap: half-precision compute, single-precision master weights and reductions; dynamic loss scaling prevents gradient underflow

• Optimizers: AdamW decouples weight decay; LAMB layerwise trust ratio; clipping, warmup, restarts stabilize gradient norms

• Practice: tune loss scale, beta and epsilon, clip threshold, batch size; checkpoint and log overflow, throughput, perplexity

• Key papers: Micikevicius et al. 2018; Kingma and Ba 2015; Loshchilov and Hutter 2019, 2017; You et al. 2020

• Systems reading: Rajbhandari et al. 2020 ZeRO; Shoeybi et al. 2019 Megatron; Narayanan et al. 2021 pipeline and tensor parallelism

• Next: replicate a small transformer ablation; vary precision, clipping, warmup, batch size; report tokens/sec and validation loss

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

1 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.