Navigation
πŸ‹οΈ Training SystemsΒ· 10 min read

Training Diagnostics

Loss spikes, gradient anomalies, silent data corruption, thermal throttling β€” diagnosing infrastructure-level training failures.

diagnosticsloss-spikegradientcorruptiondebuggingtraining

Training a large model for weeks on thousands of GPUs exposes failure modes that don’t appear in small-scale experiments. This chapter covers the symptoms, causes, and solutions for the most common training pathologies.


1. Loss Spikes

Symptoms

Loss suddenly increases 2-100Γ— for one or more steps, then may or may not recover.

Common Causes

CausePatternFix
Bad data batchSingle spike, recoversFilter training data more aggressively
Learning rate too highRepeated spikes, may divergeReduce LR, use warmup
Gradient explosionLoss β†’ NaN/InfGradient clipping (max_norm=1.0)
Numerical instabilitySpikes after many stepsCheck LayerNorm, softmax in FP32
Bit flip (silent corruption)Random spike, no data correlationECC monitoring, redundant computation

Monitoring

# Log gradient norm every step
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
wandb.log({"grad_norm": grad_norm, "loss": loss.item()})

# Alert on anomalies
if loss.item() > 10 * running_avg_loss:
    alert(f"Loss spike at step {step}: {loss.item():.4f} (avg: {running_avg_loss:.4f})")

Recovery from Loss Spikes

Option 1: Skip the bad batch, continue training
Option 2: Rollback to checkpoint before spike, skip the data range
Option 3: Reduce learning rate and resume

Meta’s Llama-3 training encountered β€œa handful of loss spikes” during 405B pre-training and handled them by rolling back to a checkpoint and skipping the problematic data.


2. Gradient Anomalies

Vanishing Gradients

SymptomCauseFix
Gradient norm β†’ 0Too many layers without residual connectionsPre-norm architecture, residual scaling
Some params never updateDead neurons (ReLU at 0)Use SiLU/GELU, check initialization
Loss plateausLR too low for current loss landscapeLR warmup, cosine schedule

Exploding Gradients

SymptomCauseFix
Gradient norm β†’ ∞Unstable attention (large logits)QK-norm, attention scaling
NaN in specific layersNumerical overflow in FP16Use BF16, check loss scaling
Step time increasesInf/NaN handling is slowFix root cause, don’t just clip
# QK-norm: normalize Q and K before attention
# Prevents attention logits from growing unboundedly
q = F.normalize(q, dim=-1) * math.sqrt(head_dim)
k = F.normalize(k, dim=-1)
attn = q @ k.transpose(-2, -1)  # bounded by √(head_dim)

3. Silent Data Corruption

The most dangerous failure β€” incorrect computation without any error signal.

Causes

CauseDetectionFrequency
GPU SRAM bit flipUncorrectable ECC errorRare but real
HBM bit flipECC correctable (masked) or uncorrectableRare
Network bit flipCRC catches most, but not allVery rare
Software bug (CUDA, NCCL)Regression testsVaries

Detection Strategies

# Strategy 1: Periodic gradient checksum
# Every N steps, compute gradient on 2 different GPUs and compare
if step % 1000 == 0:
    grad_checksum = compute_gradient_checksum(model)
    all_checksums = dist.all_gather(grad_checksum)
    if not all_equal(all_checksums):
        alert("Gradient mismatch β€” possible silent corruption!")

# Strategy 2: Monitor per-layer gradient norms
for name, param in model.named_parameters():
    if param.grad is not None:
        grad_norm = param.grad.norm().item()
        if math.isnan(grad_norm) or grad_norm > 1000:
            alert(f"Anomalous gradient in {name}: {grad_norm}")

Meta’s Approach (from Llama-3 paper)

β€œWe developed tools for online detection of anomalies including: NaN checks in every microbatch, comparison of per-layer gradient norms across data-parallel replicas, and automated rollback when divergence is detected.”


4. Thermal Throttling

Symptoms

  • Step time gradually increases over minutes/hours
  • Some GPUs report lower clock speeds than others
  • nvidia-smi shows GPU temperature >80Β°C

Diagnosis

# Check GPU temperatures
nvidia-smi --query-gpu=temperature.gpu --format=csv -l 5

# Check power draw
nvidia-smi --query-gpu=power.draw --format=csv -l 5

# Check clock speed throttling
nvidia-smi --query-gpu=clocks_event_reasons.hw_thermal_slowdown --format=csv

Mitigation

ActionEffect
Improve data center coolingPrevents throttling entirely
Reduce power limitLower temps at cost of compute
Stagger workloadsAvoid thermal hotspots
Replace thermal pasteFix degraded cooling on specific GPUs

5. Learning Rate Scheduling Issues

LR scheduling directly affects training stability and efficiency:

Common Schedules

ScheduleFormulaUse case
Linear warmuplr=lrmaxΓ—t/twarmup\text{lr} = \text{lr}_{max} \times t / t_{warmup}First 1-5% of training
Cosine decaylr=lrmin+0.5(lrmaxβˆ’lrmin)(1+cos⁑(Ο€t/T))\text{lr} = \text{lr}_{min} + 0.5(\text{lr}_{max} - \text{lr}_{min})(1 + \cos(\pi t / T))Standard for pre-training
WSD (Warmup-Stable-Decay)Warmup β†’ constant β†’ linear decayUsed by MiniCPM, some prefer over cosine
SymptomLikely causeFix
Loss doesn’t decrease from startLR too low or warmup too longIncrease LR, shorten warmup
Loss diverges after warmupLR too highReduce max LR
Loss plateaus mid-trainingLR decayed too earlyExtend constant phase (WSD)
Loss spikes at specific stepsLR schedule discontinuitySmooth transitions
Different results at different scalesLR not adjusted for batch sizeScale LR with batch\sqrt{\text{batch}} or linearly

Batch Size and LR Coupling

When scaling to more GPUs (larger effective batch), the learning rate must be adjusted:

lrscaled=lrbaseΓ—BnewBbase\text{lr}_{\text{scaled}} = \text{lr}_{\text{base}} \times \sqrt{\frac{B_{\text{new}}}{B_{\text{base}}}}

Linear scaling (lr∝B\text{lr} \propto B) also works for smaller scale-ups but becomes unstable at very large batches. LAMB and LARS optimizers handle this automatically.


6. Network Congestion

Symptoms

  • AllReduce time increases without model/config changes
  • Some steps take 2-10Γ— longer than others
  • nccl-tests show lower bandwidth than expected

Diagnosis

# Run nccl-tests during off-hours (baseline) vs during training (contention)
mpirun -np 16 ./all_reduce_perf -b 1M -e 1G -f 2 -g 1

# Check for InfiniBand errors
perfquery -x  # port counters
ibdiagnet      # comprehensive network diagnostics

Common Causes

CauseFix
Oversubscribed fabricAdd spine switches or reduce DP degree
Faulty NIC/cableReplace hardware (check ibdiagnet errors)
PFC storms (RoCE)Tune ECN/DCQCN parameters
Competing trafficIsolate training network from storage/management

For communication performance analysis, see Communication Overhead Estimation.


Self-Check

  • Diagnose a loss spike: identify likely cause from the pattern
  • Implement gradient norm monitoring with anomaly detection
  • Explain silent data corruption and two detection strategies
  • Diagnose thermal throttling from nvidia-smi output
  • Identify network congestion from nccl-tests results

References