Fixing and Scaling a Misbehaving CIFAR-10 Training Job
Machine LearningModel answerLast updated
Diagnose a CIFAR-10 PyTorch job that stalls, hits NaNs, or runs slowly, then scale it with FSDP, reason about sparse gradient communication, and decide when custom kernels pay off.
A teammate hands you a PyTorch script that trains an image classifier on CIFAR-10. It has one or more of these problems:
- Accuracy hovers around chance level (about 10%).
- The loss turns into NaN or Inf partway through training.
- Each epoch takes far longer than the hardware should require.
Answer the following as you would in a technical discussion.
- Debugging. Lay out a systematic checklist for finding the root cause of each symptom. Cover data, model, loss, optimizer, device placement, and numeric precision, and name the quick experiments you would run to narrow things down.
- Scaling out with FSDP. Describe how you would move this job to several GPUs with Fully Sharded Data Parallel. Address:
- how distributed training is initialized,
- how the model is wrapped,
- what happens to parameters, gradients, and optimizer state,
- how gradient accumulation and checkpointing work.
- Sparse gradient all-reduce. Explain how you would implement or approximate a sparse gradient (or sparse matrix) all-reduce. Which communication patterns would you use, how do they compare to a dense all-reduce, and when is the effort justified?
- Custom kernels. When would you propose writing a custom CUDA or Triton kernel for training, and how would you verify both the speedup and the correctness?
Be concrete: mention specific PyTorch APIs, rough numbers, and trade-offs. Point out where the standard advice does not fit this particular workload.
Hints
Hint 1
Start with experiments that remove whole categories of bugs: check the initial loss against ln(10), overfit a single small batch, and look at the post-transform images with their labels.
Hint 2
For FSDP, think about what is sharded (parameters, gradients, optimizer state), when all-gather and reduce-scatter occur, and why the optimizer must be created after wrapping. Also ask whether a model as small as a CIFAR ResNet even needs FSDP.
Hint 3
For sparse all-reduce and custom kernels, do the arithmetic: compare bytes on the wire for top-k plus indices versus dense, and compare a kernel's achieved bandwidth or FLOPs against the hardware roofline before deciding it is worth writing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The core skill is isolating variables rather than guessing, and reasoning about cost with numbers. One point to make early: a CIFAR-10 ResNet has roughly 10 to 25M parameters and fits easily on a single GPU, so plain DDP is normally the right tool. FSDP matters when parameters plus optimizer state do not fit in memory. I would still describe FSDP because the question asks for it, but I would say this up front.
1. Debugging checklist
Cheap sanity checks first
- Initial loss. With 10 balanced classes, cross-entropy at initialization should be near ln(10) ≈ 2.30. A much larger value points to badly scaled logits, bad init, or missing normalization.
- Overfit one batch. Take 32 images, disable augmentation, train 200 steps. Loss should approach zero. If it does not, the bug is in the model, loss, or optimizer, not in dataset scale.
- Look at the data. Plot a batch after transforms with its labels. Verify label/image alignment, CIFAR mean/std normalization, NCHW layout, and a [0,1] range before normalizing.
- Known-good baseline. Run a stock torchvision ResNet-18 through the same pipeline with SGD at lr around 0.1. If it learns, the fault is in the custom model.
Accuracy stuck near 10%
- Data: labels decoupled from images in a custom Dataset, evaluating on training data, augmentation touching labels,
shuffle=Falseon sorted data. - Model/loss: softmax applied before
CrossEntropyLoss(which expects raw logits), wrong output width, model left ineval()mode, frozen parameters, missing nonlinearities. - Optimizer: missing
zero_grad(), optimizer built from stale parameters after the model was replaced or moved, an LR that is far too small or large (run an LR range test), huge weight decay. - Gradients: log per-layer gradient norms. All zeros suggests a broken graph from
.detach(),no_grad, or.data.
NaN/Inf
- Enable
torch.autograd.set_detect_anomaly(True)briefly to locate the first offending op. - Check inputs with
torch.isfinite(x).all()for corrupt samples or divide-by-zero in normalization. - Precision: fp16 without
GradScaleroverflows. Switch to bf16, or turn AMP off to confirm it is the cause. - Replace hand-written
log(softmax(x))withlog_softmaxor the fused loss. - For LR-driven blowups: warmup, lower LR, and
clip_grad_norm_with max norm around 1.0.
Slowness
- Profile with
torch.profilerand check whether the GPU sits idle waiting for data. - Loader:
num_workers > 0,pin_memory=True,persistent_workers=True,non_blocking=Truetransfers. - Hidden syncs:
loss.item(),.cpu(), or printing tensors every step. Log every N steps. - Compute:
cudnn.benchmark=True, bf16 autocast,channels_last,torch.compile. - Confirm both model and tensors are actually on CUDA.
2. Scaling with FSDP
Initialization. Launch with torchrun --nproc_per_node=N train.py. Each process reads LOCAL_RANK, calls torch.cuda.set_device, then init_process_group("nccl"). Use DistributedSampler and call sampler.set_epoch(epoch) each epoch so shuffles differ.
Wrapping. Use an auto-wrap policy so each residual stage or block is its own FSDP unit, then wrap the root. The unit is the all-gather granularity: its full parameters exist only during its forward or backward. Configure MixedPrecision (bf16 params and reduction) and optionally CPU offload.
What is sharded. Parameters, gradients, and optimizer state are all split across ranks (ZeRO-3 style).
- Forward: all-gather a unit's parameters, compute, free them.
- Backward: all-gather again, compute gradients, then reduce-scatter so each rank keeps only its gradient shard.
- Build the optimizer after wrapping so it sees the sharded flat parameters. Adam moments are then 1/N the size.
- Use FSDP's own
clip_grad_norm_so the norm is global across shards.
Gradient accumulation. Divide the loss by the number of micro-steps. On non-final micro-steps, skip communication with no_sync() (FSDP1) or set_requires_gradient_sync(False) (FSDP2). Trade-off: skipping sync keeps unsharded gradients in memory. If memory is tight, sync every micro-step and pay for extra communication.
Checkpointing. Use torch.distributed.checkpoint with sharded state dicts: each rank writes its shard in parallel, and the result can be resharded to a different world size on load. Save optimizer state through the FSDP-aware APIs. For export, gather a full state dict on rank 0 with CPU offload. Activation checkpointing is a separate memory/compute trade applied per block.
3. Sparse gradient all-reduce
Patterns
- Top-k with all-gather: each rank selects its k largest-magnitude entries and sends (index, value) pairs. All-gather them, then scatter-add into a dense buffer. Cost per rank is about N·k·(4+4) bytes received.
- Sparse reduce-scatter / parameter-server style: partition the index space by rank, send each entry to its owner, reduce there, and gather back. Better when overlap between ranks is high.
- Error feedback: keep a local residual of the dropped gradient and add it back next step. Without it, top-k compression biases training and hurts accuracy.
Versus dense
- Ring all-reduce moves about 2·(N−1)/N · bytes per rank, independent of N, and is highly optimized in NCCL. Sparse all-gather grows linearly with N, and the union of indices densifies as ranks are added.
- Sparse needs index overhead (roughly doubling bytes per element), irregular kernels, and a top-k selection cost.
- Dense is deterministic and easy to reason about. Sparse adds convergence risk.
When it is worth it Break-even is roughly density below 1/(2N) or so, before accounting for selection cost. Example: 8 ranks, 1% density, fp32 values plus int32 indices gives about 8·0.01·8 = 0.64 bytes per parameter received versus about 7 bytes per parameter for dense ring, which is a large win. This only pays off if communication is the bottleneck: slow interconnects (Ethernet, cross-node), very large models, or naturally sparse gradients such as huge embedding tables. On NVLink or InfiniBand with a small CIFAR model, dense all-reduce overlapped with backward is almost always better.
4. Custom CUDA/Triton kernels
When
- The profiler shows a specific op dominating step time, not a vague slowness.
- The op is memory-bound with a chain of elementwise operations that could be fused (for example norm + activation + dropout), and
torch.compilefails to fuse it. - There is a non-standard operation with no efficient built-in, such as a custom sparse op.
- Never for ops already served by cuDNN or cuBLAS, which are hard to beat.
Validation
- Correctness: compare against a reference PyTorch implementation in fp32 across random shapes, including odd sizes and edge values. Use tolerances suited to the dtype (about 1e-5 fp32, 1e-2 bf16). Check gradients with
torch.autograd.gradcheckin float64 where feasible, and run a short training run to confirm the loss curve matches. - Speed: benchmark with warmup and
cuda.synchronize, ortriton.testing.do_bench, over realistic shapes. Report achieved memory bandwidth or FLOPs against the roofline. Confirm end-to-end step-time improvement, since a 3x faster op that is 2% of the step gains almost nothing. - Maintenance: weigh the cost of owning the kernel across GPU generations and PyTorch versions.
Common mistakes
- Jumping to FSDP for a model that fits on one GPU.
- Creating the optimizer before wrapping.
- Using plain
clip_grad_norm_on sharded gradients. - Top-k compression without error feedback.
- Benchmarking kernels without synchronization or warmup.