Skip to main content
← PROBLEMS / AI-SYSTEMS
An end-to-end domain learning journey

Diagnose & Fix Vanishing/Exploding
Gradients and Training Instability.

Deep 24-layer Transformers trained in FP16 with Post-LayerNorm and no warmup/clipping suffer residual variance growth and FP16 exponent overflow (65,504 max), spiking to NaN loss.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, use Pre-LayerNorm, linear LR warmup + cosine decay, global gradient norm clipping (`1.0`), and BF16 (or FP16 with dynamic `GradScaler`) to stabilize deep training.

TL;DR30-second simplified summary
▾

Core Mechanics: Mixed-precision training cuts activation memory in half, letting 24-layer Transformers fit on multi-GPU clusters.

Visual & Structural Flow: Depicts FP16 Post-LN Overflow vs. Pre-LN + GradScaler + Clipping (24-Layer Forward -> Backward Pass -> AdamW + Scaler); Pre-LN Residual + Mixed-Precision Guardrails (Pre-LN Block -> BF16 / GradScaler -> clip_grad_norm_(1.0) -> Warmup + Cosine LR).

Trade-Offs & Production: Switching back to full FP32 doubles activation/gradient memory and breaks the cluster's fixed memory budget. Stabilize the 24-layer Transformer within the same memory footprint: Pre-LayerNorm (x + Attn(LN(x))): Keeps an unscaled identity residual path from input to output, bounding gradient variance.

Failure Modes & Application: Every large-scale LLM and vision foundation-model training stack uses these exact primitives: LLM Pre-Training (LLaMA / GPT / Megatron-LM): Combines Pre-RMSNorm, BF16 mixed precision, 1.0.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
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.
CNN, RNN & Transformer Architectures
Neural architectures encode distinct inductive biases: CNNs exploit local spatial translation invariance, RNNs/LSTMs process sequential recurrence with O(1) inference state, and Transformers use parallel self-attention over global context.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why 24-layer Transformers diverge to NaN in FP16.

Why this matters: The mechanism: understand how Why 24-layer Transformers diverge to NaN in FP16 works from first principles.

Think of Why 24-layer Transformers diverge to NaN in FP16 as the intuition layer for Diagnose & Fix Vanishing/Exploding Gradients and Training Instability: The mechanism: understand how Why 24-layer Transformers diverge to NaN in FP16 works from first principles.

Mixed-precision training cuts activation memory in half, letting 24-layer Transformers fit on multi-GPU clusters. However, IEEE FP16 only has a 5-bit exponent (max representable value 65,504, min normal 6.1e-5)—so any unscaled attention logit or gradient spike overflows to Inf/NaN and corrupts all weights on the next optimizer step.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Post-LN gradient spikes and wasted GPU cluster hours.

Why this matters: The problem: see what breaks without Post-LN gradient spikes and wasted GPU cluster hours under real concurrency or scale.

At step 1,200, three numerical failures compound:

  1. Post-LN Residual Amplification: Applying LayerNorm after residual addition causes gradient norms near the output layer to blow up without warmup.
  2. FP16 Overflow & Underflow: Large gradients overflow 65,504 -> NaN, while small gradients underflow to 0 (vanishing updates).
  3. Wasted Compute: Multi-GPU runs crash mid-epoch, burning cluster budget.
Training Step Instability

FP16 Post-LN Overflow vs. Pre-LN + GradScaler + Clipping

24-Layer ForwardBackward PassAdamW + Scaler1. Naive FP16 Post-LN: grad >65504 -> NaN2. Pre-LN + BF16 (or GradScalerloss*S)3. unscale_() ->clip_grad_norm_(1.0)4. Skip Inf/NaN step, cosine LRwarmup

Pre-LN bounds residual variance while unscale + norm clipping + dynamic GradScaler prevents NaN weight updates.

Engineering Decision Framework
Problem
How to implement Diagnose & Fix Vanishing/Exploding Gradients and Training Instability 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
To keep the architecture evolvable without sacrificing reliability, use Pre-LayerNorm, linear LR warmup + cosine decay, global gradient norm clipping (1.0), and BF16 (or FP16 with dynamic GradScaler) to stabilize deep training.
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 Diagnose & Fix Vanishing/Exploding Gradients and Training Instability experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive fixes (dropping to FP32 or slashing learning rate).

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

Think of Naive fixes (dropping to FP32 or slashing learning rate) as the intuition layer for Diagnose & Fix Vanishing/Exploding Gradients and Training Instability: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Switching back to full FP32 doubles activation/gradient memory and breaks the cluster's fixed memory budget. Meanwhile, slashing the learning rate 10x without Pre-LN or clipping stalls convergence and underfits.

Design Trade-Off

Naive fixes (dropping to FP32 or slashing learning rate)

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
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Pre-LN + Warmup + Norm Clipping + BF16/GradScaler.

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

Stabilize the 24-layer Transformer within the same memory footprint:

  • Pre-LayerNorm (x + Attn(LN(x))): Keeps an unscaled identity residual path from input to output, bounding gradient variance.
  • BF16 or Dynamic GradScaler: Prefer BF16 (same 8-bit exponent as FP32, max 3.4e38, no loss scaling needed); if hardware requires FP16, wrap backward in torch.cuda.amp.GradScaler().
  • Unscale -> Clip (1.0) -> Step: Always call scaler.unscale_(optimizer) before clip_grad_norm_(params, 1.0) so clipping operates on true gradient magnitudes, plus linear LR warmup (1-5% of steps) into cosine decay.
Stabilized Training Loop

Pre-LN Residual + Mixed-Precision Guardrails

Pre-LN Blockx + Sublayer(LN(x))BF16 / GradScalerPrevents 65,504…clip_grad_norm_(1.…Caps spike after…Warmup + Cosine LRSmooth early AdamW…safe optimizer step

Pre-LN, dynamic loss scaling, gradient norm clipping, and LR warmup eliminate NaN spikes without losing speed.

scaler = torch.amp.GradScaler("cuda", enabled=use_fp16)
for step, batch in enumerate(loader):
    optimizer.zero_grad(set_to_none=True)
    with torch.amp.autocast("cuda", dtype=torch.bfloat16 if use_bf16 else torch.float16):
        loss = model(batch)
    scaler.scale(loss).backward()
    scaler.unscale_(optimizer)  # Must unscale BEFORE clipping!
    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    scaler.step(optimizer)      # Skips step automatically if Inf/NaN
    scaler.update()
    scheduler.step()
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where gradient stability safeguards are used.

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

Every large-scale LLM and vision foundation-model training stack uses these exact primitives:

  • LLM Pre-Training (LLaMA / GPT / Megatron-LM): Combines Pre-RMSNorm, BF16 mixed precision, 1.0 global norm clipping, and QK-Norm to train 70B+ models.
  • Distributed FSDP / DeepSpeed: Aggregates global L2 gradient norms across all GPUs before clipping and stepping.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

When using FP16 `GradScaler`, why must `scaler.unscale_(optimizer)` be called *before* `clip_grad_norm_(model.parameters(), 1.0)`?

Recommended Learning Flow