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:

  1. 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.
  2. 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.
  3. 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.
  4. 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 FSDP setup mechanics, including sharding granularity, optimizer initialization order, accumulation synchronization trade-offs, and distributed checkpointing.
  • Quantify when sparse gradient collectives beat dense all_reduce in 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 custom Triton or CUDA code.

Step-by-step walkthrough

  1. 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 probability 1 / 10 = 0.10. Cross-entropy loss computes -ln(p_true), which at p_true = 0.10 equals -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 CPU
    

    The 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.

  2. 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 (RGB vs BGR) and orientation.
      • Check the label histogram and range: CIFAR-10 has 50,000 training images (5,000 per class, integer labels 0..9).
      • Check post-transform pixel statistics (mean ≈ 0, std ≈ 1 per channel). torchvision.transforms.ToTensor() already divides 0..255 uint8 pixels by 255 into [0, 1]; Normalize then subtracts CIFAR-10 means (0.491, 0.482, 0.447) and divides by stds (0.247, 0.243, 0.262). Feeding raw 0..255 floats or dividing by 255 twice is a classic bug.
      • Ensure shuffle=True on the training DataLoader (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.
    • Model & autograd graph:
      • The final nn.Linear outputs 10 raw logits with no ReLU (which clips negative logits to 0) and no Softmax after it.
      • Call model.train() before training epochs and model.eval() + torch.no_grad() during validation.
      • Verify nothing severs autograd (PyTorch's automatic differentiation engine): no .detach(), .item(), .numpy(), or torch.no_grad() inside the forward pass, and param.requires_grad is True.
    • Loss wiring:
      • nn.CrossEntropyLoss() internally applies log_softmax + negative log-likelihood; it expects float logits of shape [batch, 10] and int64 class indices of shape [batch]. Passing softmax(logits) into CrossEntropyLoss double-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.1 for SGD + momentum on CIFAR ResNets, ~ 1e-3 for AdamW; AdamW at 0.1 typically diverges or collapses).

    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 labels
    

    Read 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
    
  3. Symptom 2: non-finite objective values (NaN or Inf)

    A NaN (Not a Number, produced by undefined math like 0 / 0, Inf - Inf, or log(-1)) or Inf (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:

    1. 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.
    2. Pinpoint the forward layer: attach lightweight forward hooks (module.register_forward_hook) asserting torch.isfinite(output).all() to identify the exact layer where Inf or NaN first appears.
    3. 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 became NaN (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 before NaN. 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) where probs underflows to 0.0 (replace with F.cross_entropy or F.log_softmax), a / b without b + 1e-8, or torch.sqrt(v) at v = 0 (the forward value sqrt(0) = 0 is fine, but its derivative 1 / (2 * sqrt(0)) is Inf!).
    • Half-precision (float16) range limits:
      • float16 has only 5 exponent bits, so its largest finite number is 65504 (an activation x = 300 squared gives x * x = 90,000 -> Inf!), and small gradients below ~ 6e-5 underflow toward zero.
      • Forward overflow is fixed by switching to bfloat16 (8 exponent bits, same ~ 3.4e38 range as float32) or wrapping the offending custom block in torch.autocast("cuda", enabled=False) with .float().
      • Gradient underflow in float16 is fixed by GradScaler, which multiplies the loss by a large scale factor (e.g. 65536) before backward() to lift tiny gradients into float16's representable range, divides them back before optimizer.step(), and skips the step while halving the scale if any gradient overflowed to Inf. Always call scaler.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 1 on BatchNorm1d crashes outright). Increase per-GPU batch size, switch to GroupNorm, or enable nn.SyncBatchNorm.
  4. 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) in time.perf_counter() without torch.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 and torch.compile compilation) and call torch.cuda.synchronize() before starting and stopping wall-clock timers.

    Second, split the step in two to isolate CPU vs GPU bottlenecks: 1. Loop over DataLoader alone for 50 batches without running the model. 2. Allocate one synthetic tensor x = torch.randn(128, 3, 32, 32, device="cuda") and run forward + backward + optimizer 50 times without the DataLoader. 3. Capture a 5-step trace with torch.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,000 images, batch size 128 -> ceil(50,000 / 128) = 391 steps/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=True paired with .to(device, non_blocking=True) (enables direct DMA transfers from page-locked RAM), and persistent_workers=True (avoids respawning worker processes each epoch). Better yet, for CIFAR-10 specifically, all 60,000 * 32 * 32 * 3 uint8 pixels occupy only 184.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: verify next(model.parameters()).is_cuda is True; stop calling loss.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; use memory_format=torch.channels_last for 2D convolutions; set torch.backends.cudnn.benchmark = True (since inputs are fixed at 32 x 32); and wrap the model in torch.compile(model).

  5. 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 (4 bytes fp32 master weight + 4 bytes gradient + 4 bytes Adam first moment m + 4 bytes Adam second moment v): - CIFAR-10 ResNet-18 (~ 11.2M parameters): 11.2M * 16 bytes ≈ 180 MB. Replicating 180 MB on 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 across N = 8 GPUs with FSDP (FULL_SHARD, equivalent to ZeRO-3) cuts persistent model state to 112 GB / 8 = 14 GB per GPU!

    Here is how FSDP executes each wrapped layer block across N GPUs:

    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 state
    

    Notice the communication cost: for parameter size S, DDP's ring all-reduce (summing a tensor across all GPUs so every GPU gets the sum) equals 1 reduce-scatter + 1 all-gather (~ 2S bytes per GPU), whereas FULL_SHARD FSDP runs 2 all-gathers (forward + backward) + 1 reduce-scatter (~ 3S bytes per GPU, or 1.5x DDP's traffic), overlapped by prefetching Block L + 1 while computing Block L. (SHARD_GRAD_OP keeps parameters gathered until backward to match 2S, and HYBRID_SHARD shards 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, call torch.cuda.set_device(local_rank) before dist.init_process_group("nccl") so ranks do not pile contexts onto GPU 0, shard data with DistributedSampler calling sampler.set_epoch(epoch) each epoch, and scale learning rate appropriately for global_batch = per_gpu_batch * world_size. 2. Wrap per block: pass ModuleWrapPolicy({ResidualBlock}) (or in newer FSDP2, call fully_shard(block) on each block then fully_shard(model)) so peak gathered memory is just one block at a time rather than the entire model at once. 3. Optimizer & clipping: construct AdamW(model.parameters(), ...) after FSDP wrapping so each rank's optimizer manages only its local shard, and clip gradients with model.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, sampler
    
  6. FSDP gradient accumulation and checkpointing

    Gradient accumulation simulates a larger global batch by running K micro-batches before stepping the optimizer once. Under FSDP, intermediate micro-batches 1 .. K-1 present an important memory-vs-communication trade-off: - With model.no_sync() (or set_requires_gradient_sync(False) in FSDP2): skips reduce-scatter on micro-batches 1 .. K-1 (less network traffic), but forces each GPU to buffer full unsharded gradients until micro-batch K. - Without no_sync(): runs reduce-scatter on every micro-batch so accumulated gradients stay 1/N sharded 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 by accum_steps (for example 391 steps with accum_steps = 4 leaves 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)
    
  7. Sparse gradient all-reduce: patterns, math, and break-even

    Gradients are sparse either naturally (e.g., an embedding table with 10M rows where a batch touches only 2,000 token/item IDs) or by compression (top-k sparsification, transmitting only the k largest gradient entries by magnitude). Because NCCL's all_reduce operates 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_reduce and sparse (int32 index, float32 value) (8 bytes/entry) ring all_gather across N GPUs for M float32 parameters (S = 4M bytes): - Dense ring all-reduce: 1 reduce-scatter ((N - 1)/N * 4M bytes) + 1 all-gather ((N - 1)/N * 4M bytes) = 8M * (N - 1) / N bytes sent per GPU (and the same received). - Sparse ring all-gather of k pairs per GPU: 8k * (N - 1) bytes sent per GPU (and the same received). - Break-even: 8k * (N - 1) < 8M * (N - 1) / N simplifies directly to k / 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-k over M elements, exchanging variable message lengths, and running irregular index_add_ scatter writes can take longer than streaming a dense buffer over fast links; moreover, summing sparse vectors across N ranks increases density up to N * 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 buffer e_t: add e_{t-1} to the current gradient g_t, transmit top_k(g_t + e_{t-1}), and save the unsent remainder e_t = (g_t + e_{t-1}) - sent for step t + 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 below 1 / N (or embeddings are naturally sparse). For CIFAR-10 ResNet-18 (~ 45 MB dense gradients -> ~ 90 MB ring all-reduce, < 1 ms on NVLink and overlapped with backward), dense all-reduce wins decisively.

  8. 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 fraction p of runtime by factor s as 1 / ((1 - p) + p / s)): if an op takes 20% of step time and a kernel speeds it up 3x, total step speedup is 1 / (0.80 + 0.20 / 3) = 1.15x; if it takes 3%, even an infinitely fast kernel yields at most 1.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 check torch.testing.assert_close in fp32/bf16/fp16 (the custom kernel's error vs fp64 should be no worse than eager bf16/fp16 vs fp64). - Tricky shapes, strides, and values: non-multiples of block size (e.g., length 1, 127, 1025), empty tensors (0 elements), huge tensors (> 2^31 elements testing 64-bit pointer indexing!), non-contiguous transposed views, zeros, extreme magnitudes, and Inf/NaN propagation. - Autograd & memory safety: wrap forward + backward in torch.autograd.Function, verify gradients against eager autograd (and torch.autograd.gradcheck in fp64), check run-to-run determinism (atomic adds can reorder floats), run NVIDIA compute-sanitizer for 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 against torch.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), so 2.303 for 10 classes) 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 under torch.autograd.detect_anomaly(). Distinguish bfloat16 (prevents forward overflow via float32's exponent range) from GradScaler (prevents float16 gradient underflow, unscaling before clip_grad_norm_).
  • Synchronize before timing and split CPU vs GPU. Call torch.cuda.synchronize() (or use CUDA events) after warmup, time the DataLoader loop separately from synthetic-tensor GPU steps, eliminate per-step loss.item() host syncs, and enable mixed precision + torch.compile.
  • FSDP shards parameters, gradients, and optimizer state (1/N per rank). Initialize torch.cuda.set_device(local_rank) before dist.init_process_group("nccl"), wrap per residual/transformer block, create the optimizer after wrapping, clip via model.clip_grad_norm_, handle partial tail windows in gradient accumulation (noting no_sync() trades reduce-scatter calls for full unsharded gradient memory), and save parallel sharded checkpoints with torch.distributed.checkpoint (DCP).
  • Sparse all-reduce wins only well below density 1 / N on slow links. Against dense ring all_reduce (~ 2S bytes per GPU), all-gathering (int32, fp32) pairs costs 8k * (N - 1) bytes per GPU (break-even k / M = 1 / N), adds top-k selection 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 exhausting torch.compile and library kernels, then validate against a float64 reference, edge shapes (0, non-divisible, > 2^31 elements, 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) into nn.CrossEntropyLoss, or passing raw unconstrained logits into nn.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() without torch.cuda.synchronize(), or calling loss.item() / print() every step and stalling GPU execution on CPU round-trips.
  • Clipping scaled float16 gradients before scaler.unscale_(optimizer), which clips against an arbitrary dynamic scale factor (e.g. 65536) instead of max_norm.
  • Creating the optimizer before FSDP wrapping, forgetting sampler.set_epoch(epoch), or leaking partial tail micro-batches at the end of an epoch when len(loader) % accum_steps != 0.
  • Using top-k sparse 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.compile and 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 (~ 2S bytes) communicates 33% less data than FULL_SHARD FSDP's two all-gathers plus one reduce-scatter (~ 3S bytes). 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? float16 allocates 5 bits to the exponent (max value 65504, smallest normal ~ 6.1e-5) and 10 bits to the mantissa, so small backpropagated gradients easily underflow to 0.0 unless GradScaler temporarily scales the loss up into float16's narrow exponent window. bfloat16 allocates 8 bits to the exponent — identical to float32'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 in float32 compensates for bfloat16'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, and torch.cuda.manual_seed_all, pass a seeded torch.Generator plus worker_init_fn to DataLoader, set torch.backends.cudnn.benchmark = False, and call torch.use_deterministic_algorithms(True) (with CUBLAS_WORKSPACE_CONFIG=:4096:8 set 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 instant not torch.isfinite(loss) triggers so you can replay just that single step under detect_anomaly().

Follow-up questions

Similar questions

More Startups.Com interview questions

All 3 Startups.Com questions →