Practical Training Tricks
After this lesson, you will be able to:
- Use the learning rate finder (LR sweep) to pick a near-optimal LR in 5 minutes instead of guessing, and understand why the steepest-descent point of the loss-vs-LR curve is the right pick
- Choose the right LR schedule for your task: step decay, cosine annealing, OneCycle, or warmup + cosine for transformers, and know why warmup is mandatory above ~50M parameters
- Apply gradient clipping (by norm) to prevent the divergence-in-50-steps failure mode that kills RNN and transformer training, and tune max_norm so clipping fires on the tail not the bulk
- Train 2x faster with mixed precision (autocast + GradScaler), and pick fp16 vs bf16 based on whether you need range (transformers → bf16) or precision (vision → fp16)
- Combine gradient accumulation, gradient checkpointing, and EMA/SWA to fit larger effective batch sizes and squeeze a free 0.5-1% accuracy out of any training run
Before you start
Don't worry if this list looks long — these are the tricks every senior ML engineer pulls from muscle memory, and you only need a few of them at any one time. Pick LR finder + OneCycle + gradient clipping + mixed precision as your starter pack and you are 80% of the way to the same training results researchers publish.
#The Difference Between Research and Production Training
#The Learning Rate Finder
The single most expensive hyperparameter mistake is a wrong learning rate. Too high → divergence. Too low → wastes weeks of compute. The LR finder solves this in 5 minutes.
- Start at a tiny LR (like 1e-7).
- Run training for ~100 mini-batches, exponentially increasing the LR each step (e.g. multiply by 1.05).
- Plot loss vs. log(LR).
- The loss decreases as LR rises, then bottoms out, then explodes upward.
- Pick an LR slightly below where the loss starts increasing — typically the steepest descent point, often 1/10 of the divergence point.
The formula is a one-line consequence of "multiply by the same factor each step". Open the derivation to see the factor gamma appear.
Try it! In any PyTorch project, installtorch_lr_finder(or use Lightning's built-intuner.lr_find()) — it does this whole sweep with one call. Look at the plot and pick the steepest-descent point. You will rarely guess that LR by hand.
#Run an LR sweep yourself
lr_find does, just on a problem small enough to fit in a browser tab: a 2-D quadratic loss $f(\mathbf) = \tfrac\mathbf^\top H \mathbf$ with optimum at the origin. Crucially, $H$ has an intentionally wide condition number (eigenvalues 1 and 50) — the same kind of ill-conditioning that makes LR selection delicate on real deep networks, where the Hessian's biggest eigenvalue determines the largest stable LR.- Too small (flat-left zone) — the parameter barely moves, the loss is essentially unchanged from initialization. No learning.
- Steepest descent (the "good zone") — loss drops fastest per step. The minimum of this curve is the largest LR that is still stable on this batch.
- Diverges (loss explodes) — the step overshoots the basin and the quadratic loss grows without bound.
The LR range test on your model bottoms out at LR = 3e-2 (steepest descent / minimum loss). You want to train as fast as possible. What happens if you set your training LR directly to 3e-2?
- Warmup. Over the first 1k–5k steps, linearly ramp from $\eta_\text/25$ up to $\eta_\text$. This gives Adam-style optimizers a chance to fill their first- and second-moment buffers with real gradient statistics before the LR hits full strength. Without warmup, the moment estimates are dominated by the noisy first few batches and the effective per-parameter LR is unbounded.
- Cosine annealing. After warmup, smoothly decay from $\eta_\text$ to $\sim 0.01,\eta_\text$ over the rest of training, using a half-cosine curve. The decay is fastest in the middle of training and gentlest near the end, which lets the optimizer fine-tune near a minimum without oscillating.
- OneCycle (Smith 2018, "A disciplined approach to neural network hyper-parameters"). Asymmetric variant: a short warmup (~30% of training), a longer cosine decay phase, and a very short final cooldown to $\eta_\text/10000$. The high middle-phase LR exploits the steep-descent region the range test found; the long tail settles into a wide-flat minimum. This is the schedule that delivered the original super-convergence results in Smith's "Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates" (2018, arXiv:1708.07120).
#Learning Rate Schedules
A constant LR is almost never optimal. The loss landscape has different curvature at different points in training, and the LR should reflect that.
#Step Decay
The classic schedule from the SGD-on-ImageNet era. Start at LR 0.1, drop to 0.01 at epoch 30, drop to 0.001 at epoch 60. Simple, sometimes still works. Replaced in modern practice by smoother schedules.
#Cosine Annealing
The cosine formula looks arbitrary until you build it from the shape you want. Open the derivation to build it.
Cosine annealing is the modern default for most vision and NLP work. Smoother than step decay, and the long tail at the end stabilizes the final weights.
#Warmup
warmup_steps (typically 500-2000), then hands off to a decay schedule (cosine is most common).LR
^
| ___________
| / \____
| / \____
| / \____
| / \___
| /
| / <- linear warmup
| /
|/______________________________________
step
0.5%-2% of total training steps. BERT uses 10,000 warmup steps for 1M total; GPT-3 uses 375M tokens of warmup; Llama uses 2,000 steps.#OneCycle (Smith 2018)
The schedule that gave Smith his "super-convergence" results. Combines warmup + cosine into one explicit policy:
- Phase 1 (first ~30%): linearly ramp LR from
max_lr/25up tomax_lr. Simultaneously, momentum decreases from 0.95 to 0.85. - Phase 2 (next ~70%): cosine-anneal LR from
max_lrdown tomax_lr/10000. Momentum rises back from 0.85 to 0.95.
The high LR in the middle "explores" the loss landscape; the low LR at the end "settles" into a minimum. With OneCycle + the right max_lr (from LR finder), Smith showed CIFAR-10 converging in 70 epochs to baselines that took 350+ with constant LR.
scheduler = torch.optim.lr_scheduler.OneCycleLR(
optimizer,
max_lr=0.1, # peak LR (from LR finder)
total_steps=total_steps,
pct_start=0.3, # 30% warmup, 70% anneal
div_factor=25, # initial_lr = max_lr / 25
final_div_factor=1e4, # final_lr = initial_lr / 1e4
anneal_strategy='cos',
)You remove warmup from a 110M-parameter transformer training script (Adam, peak LR 1e-4, no warmup). What is the most likely failure mode in the first 1000 steps?
The fix is a 500-2000 step linear warmup; that single change is the difference between training succeeding and training producing NaN losses indistinguishable from a code bug.
#Gradient Clipping
Even with a correct LR and warmup, individual mini-batches can produce gradients with abnormally large norms. One bad step at LR 0.001 with a gradient norm of 100 effectively takes a step of size 0.1 — enough to fly the parameters out of the convergence basin.
The panic box says clipping caps the size and keeps the direction. Open the derivation to see why both claims hold.
Drag the gradient arrow, change the max norm, switch between norm and value mode, and press the exploding preset: norm clipping keeps the direction and caps the length, value clipping bends the arrow, and the exploding step overshoots the minimum while the clipped one stays close.
- Clip-by-norm (preferred): scales the whole gradient vector together. Preserves direction, just shrinks magnitude. This is what you want.
- Clip-by-value: clips each parameter's gradient independently to ±k. Distorts direction. Mostly historical; avoid unless you have a specific reason.
#Mixed Precision Training
The single highest-leverage performance change since the original 2017 NVIDIA paper. Modern training loops run forward + backward in 16-bit precision (fp16 or bf16) while keeping a master copy of the weights in fp32 for the optimizer step. On A100/H100 GPUs, this is roughly 2x faster than full fp32 training and uses ~50% less memory.
#The Two 16-bit Formats
| Format | Range | Precision | Use case |
|---|---|---|---|
| fp16 (half) | ~6e-5 to 6e4 | ~3-4 decimal digits | Vision models, smaller transformers, V100 GPUs |
| bf16 (bfloat16) | Same as fp32 (~1e-38 to 3e38) | ~2-3 decimal digits | Modern transformers, A100/H100/TPU |
#Loss Scaling for fp16
Open the derivation for the exact reason scaling by S helps and why unscaling afterwards loses nothing.
For bf16, you don't need GradScaler at all — the range is wide enough that gradients don't underflow:
with autocast(device_type='cuda', dtype=torch.bfloat16):
loss = loss_fn(model(x), y)
loss.backward()
optimizer.step()#Gradient Accumulation
.grad buffers, then step the optimizer once. Effective batch size is the same; it just takes 8x as many forward passes.accum_steps = 8
optimizer.zero_grad()
for i, (x, y) in enumerate(dataloader):
with autocast(...):
loss = loss_fn(model(x), y) / accum_steps # scale loss by accum factor
scaler.scale(loss).backward()
if (i + 1) % accum_steps == 0:
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad()accum_steps so the accumulated gradients have the correct magnitude (otherwise you're effectively training at 8x the LR).Why does dividing by the number of accumulation steps give exactly the large-batch gradient? Open the derivation.
#Why the learning rate scales with the batch size
The history note above mentions the linear scaling rule. It follows from the same bookkeeping, plus one approximation that is worth stating out loud.
#Gradient Checkpointing
Memory-vs-compute trade. Instead of storing all intermediate activations during the forward pass (so backward can use them), recompute the activations during backward. Roughly 30% slower but uses dramatically less memory — enough to fit larger models or longer sequences on the same hardware.
import torch.utils.checkpoint as checkpoint
# Wrap memory-heavy blocks
def forward(self, x):
x = checkpoint.checkpoint(self.transformer_block_1, x, use_reentrant=False)
x = checkpoint.checkpoint(self.transformer_block_2, x, use_reentrant=False)
return xThe standard idiom for fitting big transformer training on consumer GPUs.
#EMA / Stochastic Weight Averaging (SWA)
Free 0.5-1% accuracy boost. Average the parameters across the last N epochs of training; use the averaged parameters as the final model. Costs almost nothing extra.
ema = torch.optim.swa_utils.AveragedModel(model)
for epoch in range(epochs):
train_one_epoch(...)
if epoch >= start_swa_epoch:
ema.update_parameters(model)
torch.optim.swa_utils.update_bn(dataloader, ema) # recompute BN stats
# Use 'ema' for inference, not 'model'#A Worked Example: Layering the Tricks on CIFAR-10
Tests: Verify warmup ramps LR from 0 to peak; cosine anneals down; clipping fires occasionally not constantly.
#Reproducibility
Set seeds across every source of randomness:
import random, numpy as np, torch
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = FalseTrade-off: deterministic CUDA kernels are typically 5-15% slower. Worth it for paper reproductions; not worth it for production training where wall-clock matters.
#Dataloader bottlenecks: where 30% of training time hides
DataLoader is normal and invisible — the run completes, just at 70 percent the speed it should. Five knobs cover most of it.num_workers spawns worker processes that prefetch and decode batches in parallel with GPU compute. Rule of thumb: 4 * num_GPUs, then sweep. Too few and your GPU waits on CPU; too many and you saturate the host's RAM bus and lose to context-switching. On an 8-GPU node, num_workers=32 is a sane starting point.pin_memory=True allocates batches in pinned (page-locked) host memory, which is a hard requirement for non-blocking host-to-device transfer via tensor.to(device, non_blocking=True). Without it, every batch transfer is a synchronous copy through pageable memory. Cost: a small slice of RAM. Benefit: 5-15 percent throughput at no risk.persistent_workers=True keeps worker processes alive across epochs. By default, PyTorch tears down and re-spawns the workers at the end of each epoch, which costs hundreds of milliseconds and rewarms every dataset cache. With persistence on, those costs vanish — particularly noticeable on small datasets where epochs are short.prefetch_factor sets how many batches each worker prepares ahead of time (default 2). Crank to 4-8 if your CPU is fast enough and your batches are small; leave at 2 if your batches are huge and prefetching would blow up RAM.num_workers + pin_memory -> persistent workers + prefetch -> DALI/FFCV -> webdataset.torch.profiler. If GPU utilization is under 80 percent but nvidia-smi shows the GPU is not idle, you are compute-bound and these tricks will not help. If GPU utilization swings between 100 percent and 0 percent in a sawtooth pattern, the GPU is idle waiting for the next batch — exactly the dataloader bottleneck. The torch.profiler Chrome-trace view shows this directly: long horizontal "DataLoader" bars between short "Forward" bars are the smoking gun.You are training on a single 8-GPU node. Each GPU has its own model replica (data-parallel). You set `num_workers=8` in the DataLoader and find GPU utilization is at 55 percent with a clear sawtooth pattern in nvidia-smi. What is the most likely first fix?
#Key Takeaways
- The LR finder is the highest-ROI 5 minutes you will spend on a training run. It converts the worst guessing-game in deep learning (what should the LR be?) into a deterministic procedure with a clear plot to read.
- Warmup is non-negotiable for transformers. Without 500-2000 steps of linear ramp-up, LayerNorm + Adam on random initialization produces gradient explosions and NaN losses; this is so reliable that every transformer framework defaults warmup on.
- Gradient clipping (by norm) is a no-op 95% of the time and saves the run the other 5%. Set
max_norm=1.0for transformers,max_norm=0.5for seq2seq, log pre-clip norms to confirm the clip is firing on the tail not the bulk. - Mixed precision is free 2x speedup if you pick the right format. Bf16 on A100/H100 (no GradScaler needed); fp16 with GradScaler on V100/T4; never raw fp16 without scaling unless you want silent updates-zero bugs.
- EMA / SWA buys 0.5-1% accuracy for almost no cost — average the last 25% of training's weight snapshots and use the averaged model for inference; costs only a few MB of extra memory and one BN-recomputation pass.
#Quick Check
You are training a 110M-parameter BERT-like model on a TPUv4 pod and want to use mixed precision. Which combination is correct?