Skip to main content
← CONCEPTS / AI & ML SYSTEMS
An end-to-end domain learning journey

Backpropagation & Optimizers
(Momentum, AdamW).

Backpropagation applies the multivariable chain rule backward through computation graphs to compute parameter gradients, while adaptive optimizers (Momentum, RMSProp, AdamW) stabilize curvature and decouple L2 weight decay.
Start the journey7 sections· Last modified Nov 16, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If model quality drifts from offline training baselines, AdamW), use AdamW (decoupled weight decay) with cosine learning-rate warmup for Transformer training, and gradient clipping (norm <= 1.0) to prevent exploding updates.

TL;DR30-second simplified summary
▾

Core Mechanics: Backpropagation (reverse-mode automatic differentiation) computes the gradient ∇θL\nabla_\theta \mathcal{L} of a scalar loss L\mathcal{L} with respect to millions or billions of parameters in one backward pass by applying.

Visual & Structural Flow: Depicts Forward Pass -> Loss -> Reverse-Mode Autodiff -> AdamW Update (Forward Graph -> Activation Cache -> Backward JVP -> AdamW State); Mixed-Precision Gradient Health & Recovery State Machine (CONVERGING -> CLIPPED -> INF / NAN); BF16 Compute -> Reduce-Scatter Grads -> Sharded FP32 AdamW (BF16 Forward/Back -> Reduce-Scatter -> Norm Clip <= 1.0 -> Sharded FP32 AdamW).

Trade-Offs & Production: Compare convergence speed, memory footprint, and regularization behavior. Multi-GPU LLM training shards the bulky fp32 AdamW optimizer states (m_t, v_t, master weights) across data-parallel ranks using FSDP / ZeRO-2, performs forward/backward.

Failure Modes & Application: Connect backpropagation and optimizer stability to exploding/vanishing gradients and Transformer architectures.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Deep Learning Foundations: Backpropagation, Transformers & Optimizers
Modern deep learning combines reverse-mode automatic differentiation (backpropagation), parallelizable sequence modeling via scaled dot-product self-attention (Transformers), and adaptive momentum-based gradient updates (AdamW) to train multi-billion-parameter...
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What are Backpropagation and Adaptive Optimizers.

Why this matters: The mechanism: understand how Backpropagation and Adaptive Optimizers works from first principles.

Backpropagation (reverse-mode automatic differentiation) computes the gradient ∇θL\nabla_\theta \mathcal{L} of a scalar loss L\mathcal{L} with respect to millions or billions of parameters in one backward pass by applying the multivariable chain rule through the forward computation graph.

Once gradients gt=∇θL(θt)g_t = \nabla_\theta \mathcal{L}(\theta_t) are computed, an optimizer updates weights:

  • Momentum: Smooths noisy SGD steps via an exponential moving average mt=β1mt−1+(1−β1)gtm_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t.
  • RMSProp: Scales per-parameter steps inversely by vt+ϵ\sqrt{v_t + \epsilon} where vtv_t tracks squared gradients gt2g_t^2.
  • AdamW: Combines Momentum (mtm_t) + RMSProp (vtv_t) with bias correction and decoupled weight decay (θt+1=(1−ηλ)θt−ηm^tv^t+ϵ\theta_{t+1} = (1 - \eta \lambda)\theta_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}).
Training Step Loop

Forward Pass -> Loss -> Reverse-Mode Autodiff -> AdamW Update

Forward GraphActivation CacheBackward JVPAdamW State1. Save layer activations (bf16)2. Compute scalar loss L3. Chain rule dL/dW per layer4. Clip grad norm <= 1.05. Update m_t, v_t, fp32 weights

Reverse-mode autodiff reuses cached forward activations to compute all parameter gradients in O(1) backward passes.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need AdamW & Gradient Clipping (and why naive SGD/Adam fails).

Why this matters: The problem: see what breaks without AdamW & Gradient Clipping under real concurrency or scale.

Plain SGD struggles on Transformer loss landscapes with ill-conditioned curvature (steep in some directions, flat in others). Meanwhile, classic Adam mixes L2 regularization into the gradient gtg_t before dividing by vt\sqrt{v_t}, which weakens weight decay on parameters with large gradients.

Deep training runs also hit two classic numerical failures: exploding gradients (loss spikes to NaN in bf16/fp16) and activation memory OOM when caching every layer's intermediate tensors for backward.

Training Stability

Mixed-Precision Gradient Health & Recovery State Machine

||g||_2 > max_normScaled AdamW stepfp16 overflow -> skipCONVERGINGGrad norm <= 1.0CLIPPEDSpike scaled to 1.0INF / NANSkip step; drop scale

Global gradient norm clipping (<= 1.0) and fp32 master weights prevent single-batch spikes from corrupting training.

Engineering Decision Framework
Problem
How to implement Backpropagation & Optimizers (Momentum, AdamW) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If model quality drifts from offline training baselines, adamW), use AdamW (decoupled weight decay) with cosine learning-rate warmup for Transformer training, and gradient clipping (norm <= 1.0) to prevent exploding updates.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Backpropagation & Optimizers (Momentum, AdamW) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Adam vs. AdamW

AdamW decouples weight decay from the adaptive gradient variance v_t, giving consistent regularization across all layers.

Activation Checkpointing

Trade ~33% extra compute to recompute activations on the fly during backward, cutting GPU VRAM usage dramatically.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Optimizers fit across Deep Learning workloads.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where Optimizers fit across Deep Learning workloads as the intuition layer for Backpropagation & Optimizers (Momentum, AdamW): Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Choose the optimizer based on model architecture, batch size, and GPU memory budget.

ChoiceWhat it buysWhat it costs
AdamW + Cosine Warmup (LLMs & Transformers)Fast convergence on sparse/heterogeneous gradients (embeddings, attention); decoupled weight decay.Stores 2 fp32 moment buffers (m_t, v_t) per param: 8 bytes/param extra VRAM.
SGD + Momentum (CNNs / Vision ResNets)Often generalizes slightly better on vision benchmarks; 50% less optimizer state memory than AdamW.Sensitive to learning-rate tuning; converges poorly on Transformers without careful warmup.
8-bit AdamW / ZeRO-Offload (Memory-Constrained)Quantizes m_t/v_t to 8-bit or shards across GPUs (FSDP/ZeRO), cutting optimizer RAM 4–8x.Slight communication or dequantization overhead per step.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How AdamW, Warmup, and Gradient Clipping are configured.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Standard production recipe for stable Transformer training:

  1. Exclude Norms & Biases from Weight Decay: Never apply weight decay to LayerNorm/RMSNorm gains or bias vectors.
  2. Warmup + Cosine Decay: Linearly ramp LR over 1–5% of steps to avoid early v_t instability, then decay via cosine schedule.
  3. Global Grad Clipping: Clip global L2 norm clip_grad_norm_(params, 1.0) before optimizer.step().
  4. BF16 + FP32 Master Weights: Train in bfloat16 (wide exponent range) while accumulating updates in float32.
Component Topology

How AdamW, Warmup, and Gradient Clipping are configured

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
# Production AdamW setup: separate weight decay groups + grad clipping (PyTorch)
import torch

def build_adamw(model: torch.nn.Module, lr: float = 3e-4, weight_decay: float = 0.1):
    decay_params, no_decay_params = [], []
    for name, param in model.named_parameters():
        if not param.requires_grad:
            continue
        # Never decay 1D norms/biases
        if param.ndim < 2 or "norm" in name or name.endswith(".bias"):
            no_decay_params.append(param)
        else:
            decay_params.append(param)
    return torch.optim.AdamW(
        [{"params": decay_params, "weight_decay": weight_decay},
         {"params": no_decay_params, "weight_decay": 0.0}],
        lr=lr, betas=(0.9, 0.95), eps=1e-8,
    )

# Training step: backward -> clip -> step -> zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
optimizer.zero_grad(set_to_none=True)
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: SGD+Momentum vs. RMSProp vs. Adam vs. AdamW.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: SGD+Momentum vs. RMSProp vs. Adam vs. AdamW as the intuition layer for Backpropagation & Optimizers (Momentum, AdamW): The trade-off: compare competing approaches across latency, consistency, and operational cost.

Compare convergence speed, memory footprint, and regularization behavior.

Design Trade-Off

Alternatives: SGD+Momentum vs. RMSProp vs. Adam vs. AdamW

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
ChoiceWhat it buysWhat it costs
SGD + MomentumMinimal memory (4 bytes/param state); strong generalization on well-conditioned CNNs.Single global learning rate struggles when gradient scales vary 100x across layers.
Adam (Coupled L2)Adaptive per-parameter learning rates via first and second moments.L2 penalty gets divided by sqrt(v_t), distorting regularization on large-gradient weights.
AdamW (Decoupled Weight Decay)Consistent weight decay independent of gradient magnitude; default for modern LLMs.Requires 8–12 bytes/param in fp32 for optimizer states unless sharded via ZeRO/FSDP.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production example: FSDP / ZeRO-2 Distributed Mixed-Precision Training.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production example: FSDP / ZeRO-2 Distributed Mixed-Precision Training as the intuition layer for Backpropagation & Optimizers (Momentum, AdamW): Production architecture: see how the components compose end to end under real load.

Multi-GPU LLM training shards the bulky fp32 AdamW optimizer states (m_t, v_t, master weights) across data-parallel ranks using FSDP / ZeRO-2, performs forward/backward in bfloat16, all-reduces gradients, clips global norm, and updates only each rank's owned parameter shard.

Distributed Optimizer Sharding

BF16 Compute -> Reduce-Scatter Grads -> Sharded FP32 AdamW

BF16 Forward/BackTensor Core matmulsReduce-ScatterSync grads across GPUsNorm Clip <= 1.0Global L2 guardSharded FP32 AdamW1/N m_t, v_t per GPU

1.Memory Savings: Sharding fp32 optimizer states across N GPUs reduces per-GPU optimizer memory by N-fold.

2.set_to_none=True: Frees gradient tensors between steps instead of zero-filling, lowering peak VRAM fragmentation.

3.Loss/Grad Telemetry: Track global_grad_norm and weight_norm per step to catch silent divergence early.

Sharded fp32 AdamW + bf16 Tensor Core compute maximizes GPU utilization without exploding VRAM.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by Training Optimization & System Design Deep Dives.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by Training Optimization & System Design Deep Dives as the intuition layer for Backpropagation & Optimizers (Momentum, AdamW): Applied problems: connect these internals to concrete system design and debugging scenarios.

Connect backpropagation and optimizer stability to exploding/vanishing gradients and Transformer architectures.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does AdamW outperform classic Adam when training deep Transformers with weight decay?

Recommended Learning Flow