Diagnosing and Scaling PyTorch Model Training
Medium · Software Engineering Fundamentals · Machine Learning Engineer · Onsite
Prompt
Suppose you inherit a PyTorch script that trains a 10-class CIFAR-10 vision model, and runs fail in one of three ways:
- Accuracy plateaus around chance (~10%) with no meaningful learning,
- Numerical blowups drive the objective to NaN or Inf, or
- Step-by-step throughput lags far behind what the GPU should deliver.
Walk through how you would diagnose, scale, and optimize this workload across four areas:
- Root-cause triage: Outline a structured diagnostic workflow covering input preprocessing, network architecture, loss formulation, optimizer wiring, device placement, and floating-point precision, paired with fast sanity-check experiments to isolate the defect.
- Multi-GPU scaling via Fully Sharded Data Parallel (
FSDP): Explain how to bring up distributed process groups, choose module-wrapping boundaries, manage sharded parameters, gradients, and optimizer states, and handle both micro-batch gradient accumulation and state/activation checkpointing. - Sparse gradient / sparse tensor synchronization: Describe how to build or approximate sparse cross-worker gradient reductions — covering collective communication primitives, bandwidth and convergence trade-offs compared with standard dense reductions, and workload regimes where sparsity pays off.
- Custom GPU kernels (
Triton/CUDA): Specify the profiling criteria that justify authoring a custom kernel for training speed, along with how you verify numerical accuracy (forward and backward passes) and end-to-end throughput gains.
Scope & Expectations
- Present a hypothesis-driven debugging order backed by concrete, rapid experiments that separate data, model, numerical, and input-pipeline bottlenecks.
- Detail production
FSDPsetup mechanics, including sharding granularity, optimizer initialization order, accumulation synchronization trade-offs, and distributed checkpointing. - Quantify when sparse gradient collectives beat dense
all_reducein bytes and wall-clock time, including how to preserve optimizer convergence. - Establish clear profiling gates (
Amdahl's law, compiler baselines, roofline limits) and rigorous correctness/benchmarking checks before shipping customTritonorCUDAcode.
Step-by-step walkthrough
Triage first: make the bug reproducible and read the baseline
Before changing a single hyperparameter, make the failure fast, deterministic, and observable. Fix the random seeds (
random,numpy,torch), work on a small fixed slice of data so each trial finishes in seconds or a couple of minutes, and log six numbers every step: loss, accuracy, learning rate, global gradient norm (the square root of the sum of squared gradients across all model weights), throughput (images per second), and GPU memory.Compare the very first step against what an untrained 10-class CIFAR-10 classifier must produce mathematically. At initialization, the model's logits (raw, unnormalized scores for each of the 10 classes) sit near
0, so every class gets roughly equal probability1 / 10 = 0.10. Cross-entropy loss computes-ln(p_true), which atp_true = 0.10equals-ln(0.10) = ln(10) ≈ 2.303:Metric at step 0 Healthy 10-class start What a big deviation tells you immediately ------------------------ --------------------------- -------------------------------------------------------------- Initial loss ~ ln(10) = 2.303 >> 2.3 (e.g. 15 or 80): huge logits from bad init or 0..255 raw pixels <= 0: wrong loss function (e.g. NLLLoss fed raw positive logits) drops to ~0.001 in 3 steps: target label leaked into the input Initial accuracy ~ 10% (random guessing) 0% on balanced classes: labels off-by-one or argmax on wrong axis Global gradient norm finite, moderate (0.1..10) 0.0: computation graph cut or weights frozen 1e4 -> 1e9 -> Inf: learning rate too large or fp16 overflow Throughput (images/sec) near hardware capability 10x below expected: CPU DataLoader bottleneck, per-step GPU sync, or tensors accidentally left on CPUThe three failure modes in the prompt map to three distinct checklists. Follow one golden rule throughout: change one variable at a time, and write down what you expect to happen before running the experiment so every 2-minute run rules a hypothesis in or out.
Symptom 1: accuracy stays near 10% (no learning)
Walk through the training step in exact data-flow order — Data -> Model -> Loss -> Optimizer -> Evaluation — because a silent bug at any link leaves accuracy stuck at random chance (
10%):- Data pipeline:
- Plot 8–16 images after all transforms alongside their human-readable class names (
airplane,automobile, ...). Check channel order (RGBvsBGR) and orientation. - Check the label histogram and range: CIFAR-10 has
50,000training images (5,000per class, integer labels0..9). - Check post-transform pixel statistics (
mean ≈ 0,std ≈ 1per channel).torchvision.transforms.ToTensor()already divides0..255uint8 pixels by255into[0, 1];Normalizethen subtracts CIFAR-10 means(0.491, 0.482, 0.447)and divides by stds(0.247, 0.243, 0.262). Feeding raw0..255floats or dividing by255twice is a classic bug. - Ensure
shuffle=Trueon the trainingDataLoader(if the dataset on disk is sorted by class, unshuffled batches show one class at a time!) and ensure images and labels are never shuffled with separate random calls.
- Plot 8–16 images after all transforms alongside their human-readable class names (
- Model & autograd graph:
- The final
nn.Linearoutputs10raw logits with noReLU(which clips negative logits to0) and noSoftmaxafter it. - Call
model.train()before training epochs andmodel.eval()+torch.no_grad()during validation. - Verify nothing severs autograd (PyTorch's automatic differentiation engine): no
.detach(),.item(),.numpy(), ortorch.no_grad()inside the forward pass, andparam.requires_gradisTrue.
- The final
- Loss wiring:
nn.CrossEntropyLoss()internally applieslog_softmax+ negative log-likelihood; it expects float logits of shape[batch, 10]andint64class indices of shape[batch]. Passingsoftmax(logits)intoCrossEntropyLossdouble-exponentiates probabilities and flattens gradients.
- Optimizer loop:
- Enforce the five-step order:
optimizer.zero_grad()->logits = model(x)->loss = loss_fn(logits, y)->loss.backward()->optimizer.step(). - Construct the optimizer after
model.to(device)so it holds references to the GPU parameters, and match the learning rate to the optimizer (~ 0.1for SGD + momentum on CIFAR ResNets,~ 1e-3for AdamW; AdamW at0.1typically diverges or collapses).
- Enforce the five-step order:
Run these quick experiments in order:
Quick experiment Healthy outcome If it fails, inspect... ------------------------------------------------- ----------------------------------- -------------------------------------------- 1. Evaluate loss on 1 batch before any step ~ 2.303 Weight init, pixel scaling, or loss function 2. Overfit 1 fixed batch of 32-64 images Training loss -> < 0.01 in <= 300 Model architecture, broken graph, loss, or (augmentation and dropout turned off) steps; batch accuracy -> 100% optimizer / learning rate 3. Inspect param.grad and weight diff after 1 step Every .grad is non-None & non-zero; Frozen layers, detached tensor, or optimizer weights visibly change pointing at the wrong parameter list 4. Sweep 4 learning rates (1e-4, 1e-3, 1e-2, 1e-1) At least one LR drops loss steadily LR off by 10x-100x for 200 steps 5. Compare train-batch accuracy vs validation acc Both climb above 10% together Train climbs, val stuck at 10% -> bug in val transforms, model.eval(), or val labelsRead the single-batch overfit test carefully in one direction: if the network cannot memorize 64 fixed images, the model, loss, or optimizer is definitely broken. If it can, those mechanics work — but your dataset labels could still be scrambled, because a neural network can memorize 64 random labels too!
def overfit_one_batch(model, loader, loss_fn, optimizer, device, steps=300): """Sanity check: train on a single fixed batch and verify loss approaches 0.""" model.train() # Grab one batch once and keep reusing the exact same images and labels inputs, targets = next(iter(loader)) inputs, targets = inputs.to(device), targets.to(device) losses = [] for _ in range(steps): optimizer.zero_grad(set_to_none=True) logits = model(inputs) loss = loss_fn(logits, targets) loss.backward() optimizer.step() losses.append(loss.item()) return losses- Data pipeline:
Symptom 2: non-finite objective values (NaN or Inf)
A
NaN(Not a Number, produced by undefined math like0 / 0,Inf - Inf, orlog(-1)) orInf(Infinity, produced when a number exceeds the floating-point format's maximum value) spreads immediately to every weight on the next optimizer step. So step one is finding the very first tensor that goes non-finite:- Validate inputs first: assert
torch.isfinite(inputs).all()and(targets >= 0).all() and (targets < 10).all()on every batch — one corrupted image or divide-by-zero custom augmentation is enough. - Pinpoint the forward layer: attach lightweight forward hooks (
module.register_forward_hook) assertingtorch.isfinite(output).all()to identify the exact layer whereInforNaNfirst appears. - Pinpoint the backward op: enable
with torch.autograd.detect_anomaly():on the saved failing batch. It records forward stack traces and raises an error at the exact backward operation whose gradient first becameNaN(slow, so enable only while debugging).
Once located, match the failure to the four common root causes:
- Learning rate too high / exploding gradients: loss oscillates upward and gradient norm spikes (
10 -> 1000 -> Inf) a few steps beforeNaN. Lower the learning rate, add linear LR warmup over the first few hundred steps, and clip the global gradient norm (clip_grad_norm_(model.parameters(), max_norm=1.0)). - Numerically unsafe custom math: hand-written
torch.log(probs)whereprobsunderflows to0.0(replace withF.cross_entropyorF.log_softmax),a / bwithoutb + 1e-8, ortorch.sqrt(v)atv = 0(the forward valuesqrt(0) = 0is fine, but its derivative1 / (2 * sqrt(0))isInf!). - Half-precision (
float16) range limits:float16has only 5 exponent bits, so its largest finite number is65504(an activationx = 300squared givesx * x = 90,000 -> Inf!), and small gradients below~ 6e-5underflow toward zero.- Forward overflow is fixed by switching to
bfloat16(8 exponent bits, same~ 3.4e38range asfloat32) or wrapping the offending custom block intorch.autocast("cuda", enabled=False)with.float(). - Gradient underflow in
float16is fixed byGradScaler, which multiplies the loss by a large scale factor (e.g.65536) beforebackward()to lift tiny gradients intofloat16's representable range, divides them back beforeoptimizer.step(), and skips the step while halving the scale if any gradient overflowed toInf. Always callscaler.unscale_(optimizer)before gradient clipping so you clip true unscaled gradients:
scaler = torch.amp.GradScaler("cuda") for inputs, targets in loader: inputs = inputs.to(device, non_blocking=True) targets = targets.to(device, non_blocking=True) optimizer.zero_grad(set_to_none=True) # autocast runs convolutions/matmuls in fp16 and risky reductions/losses in fp32 with torch.autocast(device_type="cuda", dtype=torch.float16): loss = loss_fn(model(inputs), targets) scaler.scale(loss).backward() # Unscale in-place BEFORE clipping so max_norm=1.0 applies to true gradients scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # Automatically skips optimizer.step() if unscaled gradients contain Inf/NaN scaler.step(optimizer) scaler.update()- Tiny per-GPU batches with BatchNorm: with 2–4 images per GPU, batch variance estimates become noisy and cause loss spikes (and batch size
1onBatchNorm1dcrashes outright). Increase per-GPU batch size, switch toGroupNorm, or enablenn.SyncBatchNorm.
- Validate inputs first: assert
Symptom 3: sluggish step throughput and hardware underutilization
First, time GPU work properly. PyTorch launches CUDA kernels asynchronously: the CPU queues an operation onto the GPU stream and immediately moves to the next Python line without waiting for the GPU to finish. Wrapping
model(x)intime.perf_counter()withouttorch.cuda.synchronize()only measures microseconds of CPU launch overhead and blames the next blocking call for the entire step! Always warm up 10–20 steps (for cuDNN autotuning andtorch.compilecompilation) and calltorch.cuda.synchronize()before starting and stopping wall-clock timers.Second, split the step in two to isolate CPU vs GPU bottlenecks: 1. Loop over
DataLoaderalone for 50 batches without running the model. 2. Allocate one synthetic tensorx = torch.randn(128, 3, 32, 32, device="cuda")and run forward + backward + optimizer 50 times without theDataLoader. 3. Capture a 5-step trace withtorch.profiler: empty white gaps on the GPU stream timeline show the GPU sitting idle waiting for data or CPU-GPU synchronization.Concrete back-of-the-envelope check on CIFAR-10 (
50,000images, batch size128->ceil(50,000 / 128) = 391steps/epoch):Measured full step: 120 ms/step -> 391 * 0.120 s = 46.9 s per epoch (~ 1,067 images/s) DataLoader-only loop: 110 ms/batch -> CPU data loading is starving the GPU! Synthetic-GPU loop: 25 ms/step -> Fixing the loader drops an epoch toward 391 * 0.025 s = 9.8 s (~ 5,120 images/s)Apply targeted fixes based on which half is slow: - Input-bound fixes: set
num_workers=4..8,pin_memory=Truepaired with.to(device, non_blocking=True)(enables direct DMA transfers from page-locked RAM), andpersistent_workers=True(avoids respawning worker processes each epoch). Better yet, for CIFAR-10 specifically, all60,000 * 32 * 32 * 3uint8 pixels occupy only184.3 MB— preload the entire dataset into GPU memory once and run random crop/flip augmentations as batched tensor ops on GPU! - GPU / sync-bound fixes: verifynext(model.parameters()).is_cudaisTrue; stop callingloss.item(),print(),.cpu(), or.numpy()every step (each forces a host-device synchronization that drains the GPU queue — accumulate on GPU and log every 50 steps instead); enable mixed precision (bfloat16/float16) to use Tensor Cores; usememory_format=torch.channels_lastfor 2D convolutions; settorch.backends.cudnn.benchmark = True(since inputs are fixed at32 x 32); and wrap the model intorch.compile(model).Scaling to multi-GPU with FSDP: sharding and setup
First check whether DDP (Distributed Data Parallel) or FSDP (Fully Sharded Data Parallel) fits the model size. In mixed-precision training with AdamW, storing parameters, gradients, and optimizer moments takes roughly 16 bytes per parameter (
4bytes fp32 master weight +4bytes gradient +4bytes Adam first momentm+4bytes Adam second momentv): - CIFAR-10 ResNet-18 (~ 11.2Mparameters):11.2M * 16 bytes ≈ 180 MB. Replicating180 MBon every GPU with DDP is tiny and faster. - 7B-parameter model:7B * 16 bytes = 112 GB, which overflows an 80 GB GPU under DDP. Sharding acrossN = 8GPUs with FSDP (FULL_SHARD, equivalent to ZeRO-3) cuts persistent model state to112 GB / 8 = 14 GBper GPU!Here is how FSDP executes each wrapped layer block across
NGPUs:Persistent on each of N GPUs: [ 1/N params | 1/N grads | 1/N Adam m, v ] (only its local shard) Forward through Block L: all-gather shards -> full Block L params -> compute activations -> free non-owned shards Backward through Block L: all-gather shards -> full Block L params -> compute full grads -> reduce-scatter grads (sum & keep 1/N shard) -> free non-owned shards Optimizer step: each GPU updates ONLY its 1/N parameter shard using its 1/N Adam stateNotice the communication cost: for parameter size
S, DDP's ring all-reduce (summing a tensor across all GPUs so every GPU gets the sum) equals1reduce-scatter +1all-gather (~ 2Sbytes per GPU), whereasFULL_SHARDFSDP runs2all-gathers (forward + backward) +1reduce-scatter (~ 3Sbytes per GPU, or1.5xDDP's traffic), overlapped by prefetching BlockL + 1while computing BlockL. (SHARD_GRAD_OPkeeps parameters gathered until backward to match2S, andHYBRID_SHARDshards within a node over fast NVLink while replicating across nodes.)To configure FSDP cleanly: 1. Initialize: launch via
torchrun --nproc_per_node=8 train.py, calltorch.cuda.set_device(local_rank)beforedist.init_process_group("nccl")so ranks do not pile contexts onto GPU 0, shard data withDistributedSamplercallingsampler.set_epoch(epoch)each epoch, and scale learning rate appropriately forglobal_batch = per_gpu_batch * world_size. 2. Wrap per block: passModuleWrapPolicy({ResidualBlock})(or in newer FSDP2, callfully_shard(block)on each block thenfully_shard(model)) so peak gathered memory is just one block at a time rather than the entire model at once. 3. Optimizer & clipping: constructAdamW(model.parameters(), ...)after FSDP wrapping so each rank's optimizer manages only its local shard, and clip gradients withmodel.clip_grad_norm_(max_norm)so gradient norms are aggregated across all shards.import os import torch import torch.distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import MixedPrecision, ShardingStrategy from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.utils.data import DataLoader, DistributedSampler def setup_fsdp(build_model, block_class, train_set, per_gpu_batch): # Bind each process to its dedicated GPU BEFORE initializing NCCL local_rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) dist.init_process_group(backend="nccl") sampler = DistributedSampler(train_set, shuffle=True) loader = DataLoader( train_set, batch_size=per_gpu_batch, sampler=sampler, num_workers=4, pin_memory=True, persistent_workers=True, ) # Compute in bf16, keep gradient reductions and BatchNorm buffers in fp32 mp_policy = MixedPrecision( param_dtype=torch.bfloat16, reduce_dtype=torch.float32, buffer_dtype=torch.float32, ) model = FSDP( build_model(), auto_wrap_policy=ModuleWrapPolicy({block_class}), sharding_strategy=ShardingStrategy.FULL_SHARD, mixed_precision=mp_policy, device_id=local_rank, ) # Build optimizer AFTER FSDP wrapping so Adam moments are sharded too optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05) return model, optimizer, loader, samplerFSDP gradient accumulation and checkpointing
Gradient accumulation simulates a larger global batch by running
Kmicro-batches before stepping the optimizer once. Under FSDP, intermediate micro-batches1 .. K-1present an important memory-vs-communication trade-off: - Withmodel.no_sync()(orset_requires_gradient_sync(False)in FSDP2): skipsreduce-scatteron micro-batches1 .. K-1(less network traffic), but forces each GPU to buffer full unsharded gradients until micro-batchK. - Withoutno_sync(): runsreduce-scatteron every micro-batch so accumulated gradients stay1/Nsharded the whole time — usually the safer choice when you chose FSDP because GPU memory was already tight!In either mode, handle the final partial window when
len(loader)is not divisible byaccum_steps(for example391steps withaccum_steps = 4leaves a 3-batch tail) so leftover gradients never leak into the next epoch:import contextlib def train_epoch(model, optimizer, loader, sampler, loss_fn, epoch, accum_steps, use_no_sync=False): sampler.set_epoch(epoch) model.train() optimizer.zero_grad(set_to_none=True) total_batches = len(loader) for step_idx, (inputs, targets) in enumerate(loader): inputs = inputs.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) # True on every K-th micro-batch AND on the final batch of the epoch window_start = step_idx - (step_idx % accum_steps) window_size = min(accum_steps, total_batches - window_start) is_sync_step = ((step_idx + 1) % accum_steps == 0) or ((step_idx + 1) == total_batches) sync_ctx = model.no_sync() if (use_no_sync and not is_sync_step) else contextlib.nullcontext() with sync_ctx: # Divide by actual micro-batches in this window for an exact mean gradient loss = loss_fn(model(inputs), targets) / window_size loss.backward() if is_sync_step: model.clip_grad_norm_(1.0) optimizer.step() optimizer.zero_grad(set_to_none=True)For checkpointing, keep two distinct concepts clear: 1. Model & optimizer state checkpointing (saving to disk): - Sharded checkpoints (preferred at scale) via
torch.distributed.checkpoint(DCP): every rank writes its own local model and optimizer shard in parallel with zero rank-0 memory bottleneck, and DCP can automatically reshard if you later resume on a different GPU count! - Full rank-0 checkpoints (StateDictOptions(full_state_dict=True, cpu_offload=True)): gathers shards into rank-0 CPU RAM to export a single standalone file for inference, but is slow for large models. Always save model, optimizer, LR scheduler,GradScaler,epoch/step, and RNG states together. 2. Activation checkpointing (apply_activation_checkpointing): discards intermediate forward activations inside wrapped blocks and recomputes them during backward — trading ~33% extra forward FLOPs for a steep drop in activation memory so larger batches or sequences fit alongside FSDP.import torch.distributed.checkpoint as dcp from torch.distributed.checkpoint.state_dict import get_state_dict def save_sharded_checkpoint(model, optimizer, epoch, step, checkpoint_dir): # Collects each rank's local model and optimizer shards cleanly model_state, optim_state = get_state_dict(model, optimizer) state = { "model": model_state, "optimizer": optim_state, "epoch": epoch, "step": step, } dcp.save(state, checkpoint_id=checkpoint_dir)Sparse gradient all-reduce: patterns, math, and break-even
Gradients are sparse either naturally (e.g., an embedding table with
10Mrows where a batch touches only2,000token/item IDs) or by compression (top-k sparsification, transmitting only theklargest gradient entries by magnitude). Because NCCL'sall_reduceoperates on contiguous dense arrays, sparse synchronization uses three alternative patterns:Pattern 1: All-gather (index, value) pairs Pattern 2: Owner-partitioned all-to-all + all-gather ------------------------------------------- ---------------------------------------------------- Each of N ranks picks k pairs (8 bytes each) Split M indices into N ranges; Rank r owns range r: -> all_gather sizes, then all_gather pairs 1. all_to_all sends pairs only to their owner (~8k B) -> each rank receives (N - 1) * k pairs 2. Owner sums duplicate indices locally in its slice -> local index_add_ into dense grad buffer 3. all_gather reduced unique pairs across ranks- Pattern 3 (Model-parallel sharded embeddings) shards huge sparse tables by rows across GPUs and exchanges forward activations + backward gradients via
all_to_all, avoiding replicated sparse gradients altogether. For dense layers, low-rank dense compression (such as PowerSGD, built into PyTorch DDP communication hooks) keeps hardware-friendly dense collectives while shrinking bandwidth.
Let's check the byte break-even between dense ring
all_reduceand sparse(int32 index, float32 value)(8bytes/entry) ringall_gatheracrossNGPUs forMfloat32 parameters (S = 4Mbytes): - Dense ring all-reduce:1reduce-scatter ((N - 1)/N * 4Mbytes) +1all-gather ((N - 1)/N * 4Mbytes) =8M * (N - 1) / Nbytes sent per GPU (and the same received). - Sparse ring all-gather ofkpairs per GPU:8k * (N - 1)bytes sent per GPU (and the same received). - Break-even:8k * (N - 1) < 8M * (N - 1) / Nsimplifies directly tok / M < 1 / N!Worked example: M = 25M fp32 parameters (S = 100 MB), N = 16 GPUs -> break-even density 1/16 = 6.25% Dense ring all-reduce: 2 * (15/16) * 100 MB = 187.5 MB per GPU Sparse all-gather at 1.0%: k = 250k -> 15 * 250k * 8B = 30.0 MB per GPU (~6.25x less traffic) Sparse all-gather at 0.1%: k = 25k -> 15 * 25k * 8B = 3.0 MB per GPU (~62.5x less traffic)Even below
1 / N, sparse communication carries real systems and optimization trade-offs: - Compute & latency overhead: finding top-koverMelements, exchanging variable message lengths, and running irregularindex_add_scatter writes can take longer than streaming a dense buffer over fast links; moreover, summing sparse vectors acrossNranks increases density up toN * k(fill-in). - Convergence bias -> Error feedback: throwing away small gradients every step biases SGD and hurts accuracy. You must maintain a local error-feedback residual buffere_t: adde_{t-1}to the current gradientg_t, transmittop_k(g_t + e_{t-1}), and save the unsent remaindere_t = (g_t + e_{t-1}) - sentfor stept + 1(usually after a few dense warmup epochs). - When is it worth doing? Only when profiling proves multi-node gradient communication over slow links (e.g., Ethernet rather than intra-node NVLink) dominates step time and density is well below1 / N(or embeddings are naturally sparse). For CIFAR-10 ResNet-18 (~ 45 MBdense gradients ->~ 90 MBring all-reduce,< 1 mson NVLink and overlapped with backward), dense all-reduce wins decisively.- Pattern 3 (Model-parallel sharded embeddings) shards huge sparse tables by rows across GPUs and exchanges forward activations + backward gradients via
Custom CUDA or Triton kernels: when to write and how to validate
Custom GPU kernels require maintaining forward + backward passes across dtypes (
fp32,bf16,fp16), tensor shapes, and GPU architectures, so propose one only when four conditions all hold: 1. Amdahl's law justifies the ceiling (Amdahl's law bounds total speedup when optimizing a fractionpof runtime by factorsas1 / ((1 - p) + p / s)): if an op takes20%of step time and a kernel speeds it up3x, total step speedup is1 / (0.80 + 0.20 / 3) = 1.15x; if it takes3%, even an infinitely fast kernel yields at most1.03x! 2. Cheaper baselines are exhausted:torch.compile(which automatically fuses ops into Triton kernels), cuBLAS/cuDNN,F.scaled_dot_product_attention(FlashAttention),AdamW(..., fused=True), and tensor-core-friendly shapes (dimensions divisible by 8 or 16) still leave a major gap. 3. A clear hardware bottleneck exists: e.g., a memory-bound chain of 6 elementwise/reduction ops reading and writing HBM (high-bandwidth GPU memory) 6 times instead of once in SRAM, or a custom sparse/quantized/attention pattern missing from libraries — confirmed by a roofline check showing achieved GB/s or TFLOP/s far below GPU peak. 4. Long-term maintainability: start in Triton (Python-based block-tiled GPU programming) for fused elementwise, reduction, normalization, or custom attention kernels; drop to CUDA C++ only when warp-level primitives or fine-grained shared-memory scheduling are required.Validate correctness systematically before measuring speed: - Numerical reference: compute ground truth using eager PyTorch in
float64, and checktorch.testing.assert_closeinfp32/bf16/fp16(the custom kernel's error vsfp64should be no worse than eagerbf16/fp16vsfp64). - Tricky shapes, strides, and values: non-multiples of block size (e.g., length1,127,1025), empty tensors (0elements), huge tensors (> 2^31elements testing 64-bit pointer indexing!), non-contiguous transposed views, zeros, extreme magnitudes, andInf/NaNpropagation. - Autograd & memory safety: wrap forward + backward intorch.autograd.Function, verify gradients against eager autograd (andtorch.autograd.gradcheckinfp64), check run-to-run determinism (atomic adds can reorder floats), run NVIDIAcompute-sanitizerfor out-of-bounds/race bugs on CUDA C++, and confirm identical seeded training loss curves end to end.Validate speedup with hardware timers and end-to-end checks: - Warm up JIT compilation/autotuning, measure median kernel runtime with CUDA events (or
triton.testing.do_bench) across real production shapes, compare againsttorch.compile(not just uncompiled eager PyTorch!), compute achieved HBM bandwidth (bytes_read_and_written / seconds), and verify that full training throughput (images/sec) improves as Amdahl's law predicted:def benchmark_cuda_ms(fn, *args, warmup=20, rep=100): """Return median GPU execution time in milliseconds using CUDA events.""" for _ in range(warmup): fn(*args) torch.cuda.synchronize() elapsed_ms = [] for _ in range(rep): start_event = torch.cuda.Event(enable_timing=True) end_event = torch.cuda.Event(enable_timing=True) start_event.record() fn(*args) end_event.record() # Wait for end_event before reading elapsed hardware time torch.cuda.synchronize() elapsed_ms.append(start_event.elapsed_time(end_event)) elapsed_ms.sort() return elapsed_ms[len(elapsed_ms) // 2]
Intuition & how it works
Think of debugging and scaling a deep learning training script like diagnosing and expanding a factory assembly line. Before buying eight times as many machines or custom-machining a new gear, you inspect a single line station by station: are raw materials arriving labeled right side up (data pipeline), are gauges pegged past their upper limit (NaN / Inf instability), and is the main machine actually working or sitting idle waiting on a slow conveyor belt (DataLoader and CPU-GPU stalls)? Once a single GPU trains cleanly and saturates hardware, scaling becomes a sequence of targeted engineering trade-offs: FSDP (Fully Sharded Data Parallel) splits heavy model state across GPUs when a single card's memory cannot hold it, sparse all-reduce compresses gradient traffic when slow inter-node links become the bottleneck, and custom Triton/CUDA kernels fuse memory-heavy operations when off-the-shelf compilers still leave a large chunk of step time on the table.
Why does the naive approach fail? Beginners often tweak three hyperparameters at once on the full dataset, time GPU lines with Python's time.time() without synchronizing, or jump straight to FSDP, gradient sparsification, or custom CUDA kernels before profiling. Changing multiple variables hides which change helped; unsynchronized timers misread asynchronous kernel launches and blame the wrong line; FSDP adds 1.5x network communication when a small model already fits in DDP; top-k sparsification silently degrades accuracy without error feedback; and speeding up a 3% operation with custom CUDA yields at most a 1.03x overall gain.
Walk through a concrete trace on CIFAR-10 (50,000 RGB images of size 32 x 32 across 10 classes, ResNet-18 with ~ 11.2M parameters):
1. Step-0 sanity check:
Untrained 10-class logits ~ 0 -> p_c = 1/10 -> loss = -ln(0.1) = 2.303, accuracy ~ 10%.
Seeing loss = 45 immediately flags unnormalized 0..255 pixels or bad weight init.
2. Single-batch overfit check:
Train on 1 fixed batch of 64 images -> loss drops from 2.30 -> 0.004 in 200 steps.
Model, loss, and optimizer mechanics work; if full-run val accuracy stays 10%, check val transforms/labels!
3. Bottleneck split (batch size 128 -> ceil(50,000 / 128) = 391 steps/epoch):
Synchronized step = 120 ms (46.9 s/epoch). Loader alone = 110 ms; GPU on synthetic tensor = 25 ms.
Fixing DataLoader workers/pinning (or caching all 184.3 MB of CIFAR-10 on GPU) cuts epochs toward 9.8 s.
4. Multi-GPU sizing (mixed-precision AdamW ~ 16 bytes/param):
11.2M * 16 B = 180 MB -> fits easily on 1 GPU (use DDP; dense 45 MB grads all-reduce in < 1 ms on NVLink).
7B * 16 B = 112 GB -> overflows 80 GB GPU (use FSDP across 8 GPUs -> 14 GB persistent state per GPU).
Key points
- Triage with invariants and single-variable experiments. Fix seeds on a small subset, verify step-0 cross-entropy (
ln(C), so2.303for10classes) and gradient norms, use the single-batch overfit test to separate model/optimizer bugs from dataset/evaluation bugs, and change one thing per run. - Hunt the first non-finite tensor for
NaN/Inf. Check input batches, attach per-module forward hooks, and replay the failing step undertorch.autograd.detect_anomaly(). Distinguishbfloat16(prevents forward overflow viafloat32's exponent range) fromGradScaler(preventsfloat16gradient underflow, unscaling beforeclip_grad_norm_). - Synchronize before timing and split CPU vs GPU. Call
torch.cuda.synchronize()(or use CUDA events) after warmup, time theDataLoaderloop separately from synthetic-tensor GPU steps, eliminate per-steploss.item()host syncs, and enable mixed precision +torch.compile. - FSDP shards parameters, gradients, and optimizer state (
1/Nper rank). Initializetorch.cuda.set_device(local_rank)beforedist.init_process_group("nccl"), wrap per residual/transformer block, create the optimizer after wrapping, clip viamodel.clip_grad_norm_, handle partial tail windows in gradient accumulation (notingno_sync()tradesreduce-scattercalls for full unsharded gradient memory), and save parallel sharded checkpoints withtorch.distributed.checkpoint(DCP). - Sparse all-reduce wins only well below density
1 / Non slow links. Against dense ringall_reduce(~ 2Sbytes per GPU), all-gathering(int32, fp32)pairs costs8k * (N - 1)bytes per GPU (break-evenk / M = 1 / N), adds top-kselection and irregular scatter overhead, and requires an error-feedback residual buffer to preserve convergence. - Custom Triton/CUDA kernels come last. Justify them via
torch.profiler+ Amdahl's law (1 / ((1 - p) + p / s)) after exhaustingtorch.compileand library kernels, then validate against afloat64reference, edge shapes (0, non-divisible,> 2^31elements, non-contiguous),gradcheck, CUDA-event benchmarks, roofline bandwidth, and end-to-end training curves.
Common mistakes
- Tweaking learning rate, augmentations, and precision simultaneously, making it impossible to tell which change fixed or broke training.
- Passing
softmax(logits)intonn.CrossEntropyLoss, or passing raw unconstrained logits intonn.NLLLoss(which expects log-probabilities and drives loss toward-Inf). - Misreading a passing 1-batch overfit test as proof that the dataset is clean: neural networks happily memorize 64 mislabeled images; you still must visually check transformed samples and validation preprocessing.
- Timing CUDA steps with
time.time()withouttorch.cuda.synchronize(), or callingloss.item()/print()every step and stalling GPU execution on CPU round-trips. - Clipping scaled
float16gradients beforescaler.unscale_(optimizer), which clips against an arbitrary dynamic scale factor (e.g.65536) instead ofmax_norm. - Creating the optimizer before FSDP wrapping, forgetting
sampler.set_epoch(epoch), or leaking partial tail micro-batches at the end of an epoch whenlen(loader) % accum_steps != 0. - Using top-
ksparse gradients without error feedback (causing biased updates and accuracy loss) or deploying sparse collectives on dense intra-node models where dense ring all-reduce is faster. - Writing a custom CUDA kernel before checking
torch.compileand Amdahl's law, spending weeks accelerating an operation that accounts for 3% of step time.
Follow-up questions
- For a standard CIFAR-10 backbone, would you deploy FSDP or DDP across multiple GPUs? Choose DDP. An 11.2M-parameter ResNet-18 uses only ~180 MB for weights, gradients, and AdamW moments, so duplicating it per GPU is negligible, and DDP's single bucketed ring all-reduce (
~ 2Sbytes) communicates 33% less data thanFULL_SHARDFSDP's two all-gathers plus one reduce-scatter (~ 3Sbytes). Reach for FSDP when model state + activations exceed single-GPU VRAM (e.g., multi-billion-parameter backbones or huge batch/resolution regimes). - Why does mixed-precision training in float16 require GradScaler while bfloat16 typically omits it?
float16allocates 5 bits to the exponent (max value65504, smallest normal~ 6.1e-5) and 10 bits to the mantissa, so small backpropagated gradients easily underflow to0.0unlessGradScalertemporarily scales the loss up intofloat16's narrow exponent window.bfloat16allocates 8 bits to the exponent — identical tofloat32's dynamic range up to~ 3.4e38— so underflow and overflow rarely happen and loss scaling is unnecessary, while keeping master weights and gradient reductions infloat32compensates forbfloat16's 7-bit mantissa. - How would you make a multi-worker PyTorch job reproducible enough to isolate a rare NaN at step 4,000? Seed
random,numpy,torch.manual_seed, andtorch.cuda.manual_seed_all, pass a seededtorch.Generatorplusworker_init_fntoDataLoader, settorch.backends.cudnn.benchmark = False, and calltorch.use_deterministic_algorithms(True)(withCUBLAS_WORKSPACE_CONFIG=:4096:8set in the environment). Periodically checkpoint model, optimizer, scheduler, scaler, and RNG states, and add a lightweight guard that dumps the exact offending micro-batch and previous checkpoint to disk the instantnot torch.isfinite(loss)triggers so you can replay just that single step underdetect_anomaly().
Follow-up questions
- For a standard CIFAR-10 backbone, would you deploy FSDP or DDP across multiple GPUs?
- Why does mixed-precision training in float16 require GradScaler while bfloat16 typically omits it?
- How would you make a multi-worker PyTorch job reproducible enough to isolate a rare NaN at step 4,000?
Similar questions
- Autoregressive Transformer Serving with KV Caching
- Building Core Activation and Normalization Layers from Scratch
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging