Diagnosing Periodic GPU Utilization Drops in Distributed Training

Hard · ML System Design · Data Scientist · Technical Screen

Prompt

You are training a large sequence Transformer across a distributed multi-node cluster—for instance, 128 GPUs across 16 eight-GPU hosts running PyTorch DDP or FSDP. Live cluster telemetry reveals a sharp, repeating utilization wave: aggregate GPU compute stays near ~85% for roughly 40 seconds, plunges to ~15% for 10 seconds, and repeats on an unbroken 50-second cycle.

This recurring stall wastes substantial accelerator budget and slows experiment velocity, while any pipeline or model layout changes you make during training directly affect how the model is deployed for online inference. Propose a systematic diagnosis and remediation architecture for the training cluster and trace how your choices carry over to production serving.

Scope & Expectations

  • Failure-mode hypotheses: Detail at least four distinct mechanisms capable of producing the 85%-to-15% periodic trough, covering CPU data ingestion and prefetch starvation, distributed collective synchronization barriers (NCCL), variable-length sequence padding and straggler ranks, and periodic synchronous checkpointing or inline validation.
  • Telemetry & profiling workflow: Specify the hardware/fabric metrics and step-targeted profiling tools (such as PyTorch Profiler, NVIDIA Nsight Systems, and NCCL flight-recorder traces) needed to inspect host-to-device DMA copies, GPU compute kernels, and inter-node links to isolate the bottleneck.
  • Pipeline & runtime fixes: Design concrete architectural interventions—such as background multi-process prefetching into pinned host memory, sequence packing, overlapped collective communication, and asynchronous sharded checkpointing—weighing VRAM/RAM footprint, throughput, and convergence stability.
  • Inference & serving parity: Explain how training-side choices (sequence packing vs. dynamic bucketing, parallelism topology, and bfloat16/float16 activation precision) impact low-latency online serving, and define how to verify numerical and latency parity before deployment.

Step-by-step walkthrough

  1. Clarify the symptom, assumptions, and success criteria

    Think of synchronous multi-GPU training as a 128-runner relay team where all 128 runners must reach a checkpoint line and exchange batons at the end of every 2.0-second lap before anyone is allowed to start the next lap. If every 20 laps the supply table runs out of water bottles for 10 seconds, or if a referee pauses the entire track for 10 seconds to record scores, the whole team sprints at 85% effort for 40 seconds and stands nearly idle at 15% for 10 seconds in a repeating 50-second cycle.

    Before jumping to fixes, define the key distributed-training terms and pin down the cluster setup:

    • DDP (Distributed Data Parallel): Every GPU holds a complete copy of the model weights, computes gradients on its own mini-batch slice, and averages gradients across all GPUs at the end of every step.
    • FSDP (Fully Sharded Data Parallel): Model weights, gradients, and optimizer states are sliced across all 128 GPUs so large models fit in GPU memory; GPUs fetch each layer's missing slices right before using that layer and discard them right after.

    Clarifying questions to ask the interviewer

    • Which metric is oscillating? Is the graph showing legacy kernel-occupancy utilization (nvidia-smi), or true compute core utilization (Tensor Core / Streaming Multiprocessor activity)?
    • Is the dip global or partial? Do all 128 GPUs plunge to ~15% in unison, or do ~108 GPUs drop to 0% while ~20 stay pegged?
    • Does training throughput (tokens/sec in the trainer log) dip on the exact same 50-second beat?
    • What periodic hooks exist? What are save_steps, eval_steps, logging_steps, and dataset shard or shuffle-buffer sizes?

    Concrete baseline assumptions for our design

    • Model & parallelism: 8-billion-parameter (8B) Transformer sequence model trained in bfloat16 mixed precision with FSDP across 128 NVIDIA H100 80 GB GPUs (16 nodes × 8 GPUs/node).
    • Hardware interconnects: Inside each node, GPUs connect via NVLink/NVSwitch (ultra-fast GPU-to-GPU wires at 900 GB/s bidirectional per GPU); across nodes, each GPU has a dedicated 400 Gb/s InfiniBand network card (~50 GB/s line rate, ~40 GB/s practical).
    • Batching & storage: Up to 4,096 tokens per sequence, 4 sequences per GPU per step (16,384 token slots/GPU, 2,097,152 token slots globally per step), reading compressed shards from cloud object storage (such as S3 or GCS).
    • Definition of "fixed": Real (non-padding) tokens/second stays flat within ±5% over multi-hour runs with zero 50-second dips, convergence parity holds (validation loss at equal token count matches baseline noise), and training optimizations remain compatible with low-latency online serving.
  2. Back-of-the-envelope cluster math

    Calculate the exact cost, memory footprint, step duration, network time, and checkpoint duration so hypotheses can be checked against physics:

    1. Cost of the 40 s @ 85% / 10 s @ 15% oscillation (50 s period)
       Average utilization       = (0.85 x 40 s + 0.15 x 10 s) / 50 s = 35.5 / 50 = 71.0%
       Throughput left on table  = 1 - (71.0% / 85.0%) = 16.5% wasted  (85 / 71 = 1.20x potential speedup)
       Wasted compute per day    = 128 GPUs x 24 h x 16.5% = ~507 GPU-hours/day (~$1,520/day or ~$45.6k/mo at $3/GPU-h)
    
    2. Model memory (why FSDP is required instead of DDP)
       Mixed-precision state     = 2 B (bf16 weights) + 2 B (bf16 grads) + 12 B (fp32 master + Adam m, v) = 16 B/param
       Unsharded 8B state        = 8e9 x 16 B = 128 GB  --> exceeds 80 GB H100 VRAM! DDP cannot fit.
       FSDP sharded across 128   = 128 GB / 128 = 1.0 GB static state per GPU (leaving ~79 GB for activations & buffers)
    
    3. Compute step time & steps per 40-second busy window
       FLOPs per GPU per step    ~ 6 x 8e9 params x 16,384 tokens = 7.86e14 FLOPs (786 TFLOPs)
       H100 bf16 dense peak      = 989 TFLOP/s; at a typical 40% MFU (~396 TFLOP/s achieved):
       Step duration             = 786 TFLOPs / 396 TFLOP/s = ~1.98 seconds (~2.0 s per step)
       Steps in 40 s active phase = 40 s / 2.0 s/step = ~20 steps!  (Cluster rate ~ 1,050,000 tokens/s)
    
    4. FSDP collective communication per step (healthy fabric)
       16 GB bf16 weights gathered in forward + 16 GB gathered in backward + 16 GB grads scattered ~ 47.6 GB/GPU
       7/8 stays intra-node on NVLink; 1/8 crosses the 8 NICs -> ~6.0 GB per NIC per step
       At ~40 GB/s effective InfiniBand -> 6.0 GB / 40 GB/s = ~0.15 s/step (~7.5% of step, mostly overlapped)
    
    5. Synchronous checkpoint vs. input data volume
       Checkpoint size           = 8e9 x 12 B (fp32 weights + Adam m, v) = 96 GB
       Sync write at ~9.6 GB/s   = 96 GB / 9.6 GB/s = ~10.0 seconds!  <-- matches the 10-second dip!
       Pre-tokenized text rate   = 1.05M tokens/s x 2 B (uint16 IDs) = ~2.1 MB/s cluster-wide (~131 KB/s per node)
    

    (Here MFU, or Model FLOPs Utilization, is the ratio of useful model math achieved per second to the GPU's theoretical datasheet peak.)

    Look at what this 2-minute calculation reveals immediately: - 20 steps take ~40 seconds, and a 96 GB synchronous checkpoint takes ~10 seconds—a leftover save_steps=20, eval_steps=20, or 20-batch data buffer reproduces a 40 s / 10 s cycle down to the second! - Raw text bandwidth is tiny (~2.1 MB/s), so if data loading causes the dip, it is a blocking stall (synchronous buffer refill, object-storage shard boundary, or CPU tokenization), not network pipe saturation.

  3. Read the utilization metric correctly before guessing

    The fastest way to waste days debugging GPUs is to misinterpret what "GPU utilization" actually measures on cluster dashboards:

    1. Legacy GPU_UTIL (nvidia-smi / DCGM_FI_DEV_GPU_UTIL) measures the fraction of time at least one GPU kernel was resident on the chip—even if that kernel uses 1% of the chip's cores! NCCL (NVIDIA Collective Communications Library, which executes multi-GPU operations like all-reduce, all-gather, and reduce-scatter) launches GPU kernels that spin-wait in a loop while waiting for a slow peer. Under GPU_UTIL, 127 GPUs stuck waiting at an NCCL barrier report 100% utilization while doing zero math—meaning a drop to 15% GPU_UTIL implies the CPU stopped launching kernels altogether!
    2. True compute utilization (DCGM_FI_PROF_SM_ACTIVE / DCGM_FI_PROF_PIPE_TENSOR_ACTIVE) measures the fraction of SMs (Streaming Multiprocessors, the parallel compute blocks inside a GPU) or Tensor Cores (specialized matrix-multiply units) actively doing work. On dashboards that plot SM or Tensor Core activity as "aggregate GPU compute utilization," both CPU starvation and NCCL barrier stalls plunge utilization down toward ~15%!

    Compare the two timelines side by side:

    Case A: Lockstep CPU Stall (sync checkpoint, inline eval, or synchronized shard refill)
      Rank 0..127 GPU: [=== 20 steps of fwd/bwd math (40 s) ===][     NO KERNELS AT ALL (10 s)     ]
      Tensor Active:    ~~~~~~~~~~~~~~~ ~85% ~~~~~~~~~~~~~~~~~~  ~~~~~~~~~~~~~ ~0-15% ~~~~~~~~~~~~~
      Legacy GPU_UTIL:  ~~~~~~~~~~~~~~~ ~85% ~~~~~~~~~~~~~~~~~~  ~~~~~~~~~~~~~ ~0-15% ~~~~~~~~~~~~~
    
    Case B: Straggler or Periodic Network Contention at NCCL Collective Barrier
      Slow Rank 17:    [=== normal (40 s) ===][=== slow data / throttled GPU / bad link (10 s) ===]
      Fast Ranks:      [=== normal (40 s) ===][mat][.... NCCL spin-wait ....][mat][.. spin-wait ..]
      Tensor Active:    ~~~~~~~~ ~85% ~~~~~~~  ~~~~~~~~~~~~~~~~~~~~~ ~15% ~~~~~~~~~~~~~~~~~~~~~~~~~
      Legacy GPU_UTIL:  ~~~~~~~~ ~85% ~~~~~~~  ~~~~~~~~~~~~~~~~~~~~ ~95-100% ~~~~~~~~~~~~~~~~~~~~~~
    

    Five 2-minute triage checks (before running heavy profilers)

    1. Verify tokens/sec in trainer logs: Confirm step wall-clock time actually spikes during the 10 s window (ruling out Prometheus/Grafana scrape-interval aliasing).
    2. Un-average the 128 GPUs: Plot a heatmap of all 128 GPUs individually instead of a cluster mean.
    3. Test step-based vs. wall-clock period: Temporarily cut micro-batch size from 4 to 2 so steps run ~2× faster (~1.0 s/step). If the dip now happens every ~30 seconds (still every 20 steps), the trigger is step-counted (save_steps, eval_steps, shuffle buffer, shard size). If it stays at 50.0 wall-clock seconds, it is a timer or host cron daemon!
    4. Perturb one suspect interval: Double save_steps or disable inline validation for 10 minutes; if the period doubles or vanishes, you have proven causality.
    5. Grab a zero-overhead live stack trace: Run py-spy dump --pid <rank_pid> during the 10-second trough on rank 0 and one worker rank to catch torch.save, DataLoader.__next__, or evaluate() red-handed.
  4. Four root-cause hypotheses across the stack

    Every candidate root cause must explain why utilization stays healthy for ~40 seconds and then drops to ~15% for ~10 seconds:

    1. Data ingestion & CPU prefetch starvation:
      • Mechanism: A naive streaming dataset fills an in-memory buffer of ~80 sequences (20 steps × 4 seqs/GPU), drains it at full GPU speed over 40 seconds, and then blocks synchronously for 10 seconds downloading and decompressing the next compressed object-storage shard or tokenizing raw text on CPU. Similarly, because all 128 synchronous ranks consume samples in lockstep, equal-sized shards cause all 128 ranks to hit End-Of-Shard on the exact same step (persistent_workers=False makes this worse by killing and respawning Python worker processes at epoch/shard boundaries). Unpinned pageable H2D (host-to-device, i.e., CPU RAM to GPU VRAM) copies without non_blocking=True add per-step host stalls on top.
      • Signature: data_wait_ms jumps from <1 ms to 10,000 ms every 20 steps; PCIe H2D traffic goes flat during the stall and bursts right at the end; S3 GET requests and worker CPU spike during the dip.
    2. Periodic synchronous checkpointing or in-line validation:
      • Mechanism: Every N = 20 steps (~40 s), the trainer either calls synchronous torch.save (stalling all 128 GPUs for ~10 s while writing 96 GB to shared storage, or gathering all shards onto rank 0) or runs an unoptimized validation loop (small batch size, fresh DataLoader worker startup, autoregressive decoding, or Python metric syncs via .item()).
      • Signature: Storage write bandwidth (~9–10 GB/s) or validation log lines align 1-to-1 with every 10 s trough.
    3. Distributed NCCL collective barriers & periodic stragglers:
      • Mechanism: FSDP executes two all-gather collectives and one reduce-scatter collective per Transformer layer, acting as hard synchronization barriers. If one node hits periodic thermal/power clock throttling, runs a 50-second host monitoring/log-rotation daemon that steals CPU cores from NCCL proxy threads, or shares network switches with a bursty neighbor job (or experiences InfiniBand link retransmits / PCIe downgrade), 127 fast GPUs sit idle inside NCCL barriers waiting for that 1 slow rank.
      • Signature: DCGM_FI_PROF_PIPE_TENSOR_ACTIVE drops to ~15% while NCCL kernel durations explode; one rank enters collectives late (straggler) or all ranks enter together and transfer slowly (network).
    4. Variable-length sequence padding & length-ordered shards:
      • Mechanism: Under dynamic padding, each GPU pads its 4 sequences up to the longest sequence in its local micro-batch, and synchronous FSDP forces all 128 GPUs to wait for whichever GPU drew the longest sequence globally. For lengths uniform on [100, 4096] (mean 2,098), the expected max of 4 sequences is 100 + (4/5) × 3996 ≈ 3,297 (36% wasted locally), and across all 128 × 4 = 512 sequences globally it is 100 + (512/513) × 3996 ≈ 4,088—wasting 49% of cluster compute! Worse, if upstream shards were packed by source or sorted by length (e.g., short conversational shards followed by 4,096-token code shards), or if sudden max-length spikes trigger PyTorch's CUDA caching allocator to run blocking cudaFree/cudaMalloc defragmentation, periodic throughput cliffs appear.
      • Signature: tokens_real / tokens_padded fluctuates sharply, or mem_reserved_gb resets alongside allocator sync spikes.
  5. Diagnostic observability stack and profiling workflow

    Instrument the cluster in two tiers—cheap always-on counters plus surgical, dip-aligned profiler captures:

    Tier 1: Zero-sync per-step trainer telemetry + 1-second hardware counters

    Log one JSON record per rank per step asynchronously (reading CUDA events—lightweight GPU timestamps—from step t - 1 during step t so timing never forces torch.cuda.synchronize()):

    Per-step trainer log (step_metrics):
      step, rank, node, step_ms, data_wait_ms, h2d_ms, fwd_ms, bwd_ms, opt_ms,
      probe_ms (collective-free matmul every 50 steps), tokens_real, tokens_padded,
      max_seq_len, cuda_malloc_retries, events (["checkpoint", "eval"])
    
    1-second hardware & fabric telemetry (Prometheus / DCGM / InfiniBand):
      - Compute:   DCGM_FI_PROF_SM_ACTIVE, DCGM_FI_PROF_PIPE_TENSOR_ACTIVE, DCGM_FI_DEV_SM_CLOCK, throttle_reasons
      - H2D/Mem:   DCGM_FI_PROF_PCIE_RX_BYTES / TX_BYTES (host-to-device / device-to-host), DRAM_ACTIVE
      - Fabric:    DCGM_FI_PROF_NVLINK_TX_BYTES, IB port_xmit_data / port_rcv_data, port_xmit_wait, symbol_errors
    

    Tier 2: Targeted profiling aligned to the dip step

    Never profile all 128 GPUs continuously (trace files are gigabytes and add 10–30% overhead). Instead, capture rank 0 + one rank per node across a 10-step window straddling the dip using NVTX (NVIDIA Tools Extension named timeline markers), PyTorch Profiler, NVIDIA Nsight Systems (nsys profile --trace=cuda,nvtx,osrt for an 80-second window capturing CPU OS file/socket syscalls alongside GPU streams), and NCCL Flight Recorder (TORCH_NCCL_TRACE_BUFFER_SIZE=2000, TORCH_NCCL_ENABLE_TIMING=1):

    import torch
    from torch.profiler import ProfilerActivity, profile, schedule, tensorboard_trace_handler
    
    
    def run_profiled_window(loader, train_step_fn, dip_step: int, trace_dir: str) -> None:
        """Capture 2 healthy steps right before dip_step, the dip itself, and 5 recovery steps."""
        # skip_first fast-forwards with zero overhead until right before the known oscillation trough
        dip_schedule = schedule(
            skip_first=max(0, dip_step - 3),
            wait=0,
            warmup=1,
            active=8,
            repeat=1,
        )
        with profile(
            activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
            schedule=dip_schedule,
            record_shapes=True,
            on_trace_ready=tensorboard_trace_handler(trace_dir),
        ) as prof:
            for step_idx, batch in enumerate(loader):
                # NVTX labels make CPU/GPU phases readable in Nsight Systems and Chrome/Perfetto traces
                torch.cuda.nvtx.range_push(f"step_{step_idx}")
                train_step_fn(batch)
                torch.cuda.nvtx.range_pop()
                prof.step()
                if step_idx > dip_step + 6:
                    break
    

    Follow a strict diagnostic decision tree to isolate the exact bottleneck:

    Does real tokens/s drop every 50 s?
      |-- No  --> Dashboard scrape artifact; switch dashboard to DCGM_FI_PROF_PIPE_TENSOR_ACTIVE + step tokens/s.
      |-- Yes --> Inspect Nsight / PyTorch trace during the 10 s trough:
            |-- GPU streams completely empty on all ranks (CPU stalled):
            |     |-- Blocked in DataLoader.__next__ / S3 read  --> Input pipeline / shard boundary refill
            |     |-- Blocked in torch.save / filesystem write  --> Synchronous checkpointing
            |     |-- Running eval forward / Python metrics     --> In-line validation or logging syncs
            |-- GPU streams filled with long NCCL kernels (Tensor Pipe ~0%):
                  |-- Flight recorder shows 1 rank entering late --> Straggler (check data_wait_ms vs GPU clocks)
                  |-- All ranks enter on time, transfer is slow  --> Fabric saturation / IB or PCIe link degradation
    
  6. Target end-to-end training pipeline architecture

    To eliminate the 15% troughs permanently, move every non-compute operation off the GPU's critical path so the main compute stream only ever sees dense matrix math and un-overlapped edge collectives:

      Cloud Object Storage (pre-tokenized, Zstd-compressed 512 MB shards + byte-offset index)
                           |
                           | async background range-GETs (next 2 shards prefetched per worker)
                           v
      +------------------------------- Per Training Node (8x H100) -------------------------------+
      |  Local NVMe Ring Cache                                                                    |
      |         |                                                                                 |
      |  Multi-Process CPU Workers (persistent_workers=True, staggered shard offsets)             |
      |    -> decompress + continuous reservoir shuffle + pack into exact 4,096-token chunks      |
      |         |                                                                                 |
      |  Pinned (Page-Locked) Host Queue  --(Side CUDA Stream: async DMA H2D copy)--> GPU VRAM    |
      |                                                                                  |        |
      |  GPU Compute Stream:   [ Fwd L0 ][ Fwd L1 ][ Fwd L2 ] ... [ Bwd L2 ][ Bwd L1 ][ Opt ]     |
      |  GPU NCCL Stream:    [AG L0][AG L1][AG L2]             [RS L2][RS L1] (overlapped!)       |
      |                                                                                           |
      |  Async Checkpoint: GPU --(<0.2 s D2H snapshot)--> Pinned RAM --> Background NVMe -> S3    |
      +-------------------------------------------------------------------------------------------+
                                                                               |
                                                        Separate 2-GPU Eval Job watches S3 bucket
    
  7. Deep dive 1: Zero-starvation data pipeline and H2D overlap

    To keep GPU Tensor Cores busy without waiting on host CPUs or remote storage, understand how CPU-to-GPU memory transfers actually work under the hood:

    • Why pin_memory=True is mandatory for async H2D: Normal OS memory is pageable (the OS can swap it to disk at any moment). A GPU's DMA (Direct Memory Access) copy engine can only read physical RAM addresses that are locked in place (pinned / page-locked memory). Calling tensor.to("cuda", non_blocking=True) on pageable memory silently forces the CPU driver to allocate a temporary pinned buffer and copy bytes on the CPU first—blocking the Python thread!
    • Why a dedicated side CUDA stream is required: A CUDA stream is a FIFO queue of GPU operations. If you launch an H2D copy on the default compute stream, it waits behind the current step's backward pass instead of overlapping with it. Copying batch t + 1 on copy_stream while batch t runs on compute_stream hides H2D transfer latency completely.
    • Eliminating periodic buffer stalls: Pre-tokenize raw text offline into uint16/uint32 token arrays, stagger initial shard offsets across workers so ranks never cross shard boundaries simultaneously, keep persistent_workers=True, and use a continuous replacement shuffle buffer (pop 1 random item, push 1 new item) instead of fill-drain-refill.
    import torch
    from torch.utils.data import DataLoader
    
    
    def build_fast_dataloader(dataset) -> DataLoader:
        return DataLoader(
            dataset,
            batch_size=4,
            num_workers=8,            # 8 background OS processes per GPU bypassing Python's GIL
            pin_memory=True,          # page-locked host RAM required for true DMA async H2D copies
            prefetch_factor=4,        # 8 x 4 = 32 micro-batches queued ahead (~4 MB total for token IDs)
            persistent_workers=True,  # keep worker processes and open shard handles alive across epochs
            drop_last=True,           # keep batch shapes uniform across all 128 synchronous ranks
        )
    
    
    class AsyncCudaPrefetcher:
        """Overlaps batch N+1 Host-to-Device DMA transfer on a side CUDA stream while batch N computes."""
    
        def __init__(self, loader: DataLoader, device: torch.device):
            self.loader_iter = iter(loader)
            self.device = device
            self.copy_stream = torch.cuda.Stream(device=device)
            self.next_batch = None
            self._preload_next()
    
        def _preload_next(self) -> None:
            try:
                cpu_batch = next(self.loader_iter)
            except StopIteration:
                self.next_batch = None
                return
            # Enqueue non-blocking H2D DMA transfers onto the dedicated copy stream
            with torch.cuda.stream(self.copy_stream):
                gpu_batch = {}
                for key, tensor in cpu_batch.items():
                    gpu_batch[key] = tensor.to(self.device, non_blocking=True)
                self.next_batch = gpu_batch
    
        def __iter__(self):
            return self
    
        def __next__(self) -> dict:
            compute_stream = torch.cuda.current_stream(self.device)
            # Ensure copy_stream finished transferring batch N before compute_stream reads it
            compute_stream.wait_stream(self.copy_stream)
            batch = self.next_batch
            if batch is None:
                raise StopIteration
            for tensor in batch.values():
                # Tell PyTorch's caching allocator that compute_stream owns this tensor until step end
                tensor.record_stream(compute_stream)
            self._preload_next()
            return batch
    
  8. Deep dive 2: Sequence packing, collective overlap, and straggler isolation

    1. Sequence packing with block-diagonal document masks: Instead of padding short sequences with [PAD] zeros and letting one 4,096-token outlier stall 127 ranks, concatenate tokenized documents separated by <EOS> and slice exact 4,096-token chunks. Every GPU now processes 100% real tokens (16,384 per GPU) with identical matrix shapes (eliminating both the 49% padding waste and CUDA allocator fragmentation spikes!). To prevent tokens in Document B from attending to unrelated Document A inside the same chunk, reset position_ids to 0 at every document boundary and pass cumulative document offsets (cu_seqlens, e.g., [0, 4, 7, 11]) to variable-length FlashAttention (flash_attn_varlen_func), which enforces a block-diagonal causal mask:

    Dynamic Padding (49% cluster compute wasted on [PAD] + barrier wait):
      Seq 1: [ d0 d1 d2 <EOS> PAD PAD PAD PAD ]
      Seq 2: [ e0 e1 <EOS> PAD PAD PAD PAD PAD ]
    
    Sequence Packing (100% real tokens + reset positions + block-diagonal causal mask):
      Chunk:       [ d0  d1  d2 <EOS> |  e0  e1 <EOS> |  f0 ]
      position_id: [  0   1   2    3  |   0   1    2  |   0 ]
      doc_starts:  [0, 4, 7]  --> Doc e cannot see Doc d; Doc f cannot see Doc d or e!
    
    def pack_documents_into_chunks(documents: list, chunk_len: int, eos_id: int) -> list:
        """Pack variable-length token lists into exact chunk_len sequences with per-doc position resets."""
        chunks = []
        tokens = []
        position_ids = []
        doc_starts = []
    
        for doc in documents:
            pos_in_doc = 0
            for token_id in doc + [eos_id]:
                if len(tokens) == chunk_len:
                    chunks.append((tokens, position_ids, doc_starts))
                    tokens = []
                    position_ids = []
                    doc_starts = []
                    pos_in_doc = 0
                # Mark the start of a new document (or continuation of a split document at offset 0)
                if pos_in_doc == 0:
                    doc_starts.append(len(tokens))
                tokens.append(token_id)
                position_ids.append(pos_in_doc)
                pos_in_doc += 1
        return chunks
    

    2. Overlapping communication with compute (FSDP / HSDP / Tensor Parallelism): - Enable FSDP backward_prefetch=BackwardPrefetch.BACKWARD_PRE and forward_prefetch=True with limit_all_gathers=True (rate-limiting concurrent all-gathers so prefetched buffers cannot spike VRAM into out-of-memory crashes). Layer L + 1's all-gather then runs on the NCCL stream while Layer L's matrix multiplies run on the compute stream. - If shared inter-node InfiniBand bandwidth is noisy, switch to HSDP (Hybrid Sharded Data Parallel): shard weights 8-ways within each NVLink node (128 GB / 8 = 16 GB state/GPU, easily fitting in 80 GB) and replicate DDP-style across the 16 nodes. Layer-by-layer all-gathers stay 100% inside ultra-fast NVLink, cutting inter-node NIC traffic from ~6.0 GB to ~3.75 GB per step (one end-of-backward gradient all-reduce). (For 70B+ models using intra-node Tensor Parallelism—splitting individual weight matrices across 8 NVLink GPUs—use async decomposed TP to overlap all-gather / reduce-scatter tiles with tiled GEMM sub-blocks.)

    3. Automated straggler isolation: Because synchronous barriers equalize step_ms across all 128 ranks, run a 30 ms collective-free local matmul probe every 50 steps and all_gather (data_wait_ms, probe_ms) across ranks. Any GPU whose probe_ms exceeds 1.2 × cluster_median twice in a row has thermal throttling or bad silicon and is automatically cordoned and swapped for a warm spare node via elastic torchrun.

  9. Deep dive 3: Async checkpointing, decoupled eval, and convergence trade-offs

    Two-phase asynchronous checkpointing: Replace the 10-second synchronous torch.save with PyTorch Distributed Checkpoint (torch.distributed.checkpoint.async_save):

    1. Fast GPU-to-Pinned-RAM snapshot (<0.2 s blocking): Each of the 128 ranks copies only its own 96 GB / 128 = 0.75 GB state shard over PCIe Gen5 (~50 GB/s) into pre-allocated pinned host RAM (8 × 0.75 GB = 6.0 GB host RAM per node). Training resumes Step t + 1 immediately!
    2. Background persistence (0 s GPU stall): A background thread/process writes the shard to local NVMe and streams it to S3 over the management Ethernet NIC (or rate-limited on InfiniBand so S3 uploads never starve NCCL RDMA traffic!), writing a _COMMITTED manifest marker last for crash atomicity.

    By Young's checkpoint formula optimal_interval ≈ sqrt(2 × blocking_save_time × MTBF), assuming one cluster fault every 24 hours (86,400 s), cutting blocking save cost from 10 s to 0.2 s lowers the optimal interval from ~22 minutes to ~3 minutes while reducing checkpoint overhead below 0.1%!

    import concurrent.futures
    import torch
    
    _checkpoint_executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
    _in_flight_save = None
    
    
    def save_shard_async(shard_state: dict, target_path: str):
        """Pause the GPU <0.2 s for a D2H copy to CPU RAM; serialize to disk in the background."""
        global _in_flight_save
        # Cap in-flight snapshots to 1 so slow storage can never exhaust host RAM
        if _in_flight_save is not None:
            _in_flight_save.result()
    
        cpu_snapshot = {}
        for key, value in shard_state.items():
            if torch.is_tensor(value):
                # Synchronous D2H copy finishes before returning so step t+1 can safely mutate GPU weights
                cpu_snapshot[key] = value.detach().cpu()
            else:
                cpu_snapshot[key] = value
    
        _in_flight_save = _checkpoint_executor.submit(torch.save, cpu_snapshot, target_path)
        return _in_flight_save
    

    Decoupled evaluation & logging: Move validation off the 128-GPU training job onto a separate 2-GPU evaluation worker watching the S3 checkpoint prefix; accumulate scalar training loss on GPU and call .item() only every 20 steps.

    Explicit trade-offs across Memory, Throughput, and Convergence:

    Intervention Throughput Gain Memory Cost Convergence Impact & Mitigation
    Async prefetch + pinned RAM + async checkpoint Eliminates 10 s troughs (+20% steps/h) ~6.5 GB host RAM/node Bitwise math-preserving (zero convergence risk—ship first!)
    FSDP prefetch (limit_all_gathers=True) Hides ~7–10% comm time +1–2 layers unsharded VRAM (~1.0 GB) Math-preserving
    HSDP (intra-node shard, inter-node DDP) Cuts NIC traffic 1.6×; isolates slow IB +15.0 GB VRAM/GPU (1.0 -> 16.0 GB) Math-preserving
    Sequence packing + varlen document masks ~1.9× real tokens/s on variable lengths Flat peak VRAM (no max-length spikes) Per-token loss gives equal weight per token instead of per document; splits >4,096-token docs. Validate via 2,000-step fixed-seed A/B run!
    Length bucketing (without packing) Lowers local padding Variable VRAM per bucket High risk if unshuffled: length-homogeneous batches correlate gradients; shuffle bucket order every step
    Selective activation checkpointing Allows larger micro-batch Saves 40–60% activation VRAM Adds ~15–33% recompute FLOPs; zero math change
  10. Downstream impact on low-latency inference and serving parity

    Training optimizations directly shape online serving latency, throughput, and numerical accuracy:

    1. Sequence packing & static vs. dynamic bucketing -> Online batching:
      • If you pack sequences during training without document masks and reset position IDs, the model learns to condition on preceding unrelated text—degrading quality at serving time, where every user prompt starts cleanly at position_id = 0. Also verify long-context quality near position 4,096, since splitting >4,096-token documents changes how often late positions are trained.
      • Online LLM servers (such as vLLM or TensorRT-LLM) do not use sequence packing or dynamic padding across requests; they use continuous batching (inserting newly arrived requests and evicting finished ones at every generated token step) backed by a paged KV cache (storing past attention Key/Value vectors in fixed-size 16-token blocks so zero VRAM is wasted on padding). Where CUDA Graphs or static ahead-of-time compiled shapes are used for decode steps, choose bucket sizes ([1, 2, 4, 8, 16, 32, ...]) from the production concurrency and prompt-length histogram, not training chunk sizes.
    2. Parallelism layout (FSDP / Pipeline Parallelism vs. Tensor Parallelism):
      • Pipeline Parallelism (PP)—placing Layers 0–15 on GPU 0 and Layers 16–31 on GPU 1—is great for high-throughput training with dozens of micro-batches, but hurts low-latency serving because generating one token for one user must hop sequentially through every stage (time-per-output-token increases with pipeline depth). Online serving therefore reshards FSDP checkpoints into single-node Tensor Parallelism (e.g., TP=2 or TP=4 over NVLink so all GPUs collaborate simultaneously on every layer).
      • Resharding safety: Ensure num_attention_heads and num_kv_heads divide cleanly by the serving TP degree at architecture design time, and de-interleave fused QKV and SwiGLU gate_up weight matrices carefully when converting FSDP checkpoints.
    3. Activation precision (bf16 vs. fp16 / fp8):
      • bfloat16 has 8 exponent bits (max value ~3.4 × 10^38), whereas float16 has only 5 exponent bits (max value 65,504). Models trained in bf16 routinely develop hidden-state outlier activations above 65,504 in deeper layers—exporting them to an fp16 serving engine overflows straight to Inf/NaN! Serve in native bf16, or calibrate fp8/int8 quantization scales on real production prompt traffic.
    4. Automated Train-Serve Parity Gate (run before every model promotion):
      • Evaluate 1,000 golden production prompts (spanning 64 to 4,096 tokens) in both the PyTorch training graph and the production serving engine on identical weights: assert 0 NaNs, per-token KL divergence (a measure of probability-distribution drift between two logit vectors) < 0.001, greedy top-1 token agreement > 98%, offline benchmark parity within ±0.2%, and p99 time-to-first-token (TTFT) and time-per-output-token (TPOT) within SLA.

Intuition & how it works

Picture a 128-worker assembly line spread across 16 rooms where all 128 workers must compare notes at the end of every 2.0-second cycle before anyone can begin the next cycle. If a supply cart runs empty every 20 cycles and takes 10 seconds to reload from a warehouse, or if a manager freezes the whole floor every 20 cycles to copy 96 GB of progress ledgers onto shared storage, the factory hums at 85% capacity for 40 seconds and drops to 15% for 10 seconds on a repeating 50-second clock.

The naive response is to stare at the single cluster-average "GPU utilization" curve and tweak five knobs at once—changing batch size, worker counts, NCCL flags, and learning rate in a single restart. That approach fails because legacy nvidia-smi utilization counts NCCL (NVIDIA Collective Communications Library) spin-waiting kernels as "100% busy," averaging across 128 GPUs hides single-node stragglers (one slow worker holding up 127 fast peers at a barrier), and changing training math alongside infrastructure hides which change fixed throughput or broke model convergence.

Instead, we verify physics first, isolate the exact trigger in minutes with cheap experiments, and move all I/O and host work off the GPU critical path. Walk through a concrete 50-second cycle on our 128 × H100 FSDP (Fully Sharded Data Parallel, which slices model weights and optimizer states across GPUs) run:

  1. Quantify the cycle: At ~2.0 s per step, 20 training steps take ~40 s at ~85% Tensor Core utilization, followed by a 10 s drop to ~15% (71.0% average vs. 85% steady—wasting 16.5% of cluster GPU-hours, or ~507 GPU-hours/day).
  2. Bisect in 2 minutes: Halving micro-batch size from 4 to 2 cuts step time to ~1.0 s, and the dip immediately shifts from every 50 seconds to every ~30 seconds (still every 20 steps)—proving a step-counted trigger rather than a 50-second host cron timer.
  3. Catch the culprit: Inspecting per-step step_metrics and a live py-spy dump stack trace during Step 20 shows every rank blocked inside a synchronous 96 GB checkpoint write (~9.6 GB/s -> ~10.0 s) or lockstep shard download.
  4. Remediate cleanly: Switching to a two-phase asynchronous checkpoint (<0.2 s GPU-to-pinned-CPU copy of 0.75 GB/rank, persisted in the background) plus pinned-memory asynchronous prefetching and sequence packing eliminates the 10-second trough completely without altering model convergence.

Key trade-offs

  • Systematic isolation vs. changing everything at once. Turning on async checkpoints, sequence packing, HSDP (Hybrid Sharded Data Parallel), and a new DataLoader simultaneously may flatten utilization, but makes any loss regression impossible to debug. Shipping bitwise math-preserving fixes first (async checkpointing, decoupled evaluation, pinned-memory H2D prefetching, FSDP collective prefetch) removes idle troughs with zero convergence risk before testing throughput-altering changes like sequence packing in fixed-seed 2,000-step A/B runs.
  • Asynchronous vs. synchronous checkpointing. Asynchronous sharded checkpointing shrinks GPU pause time from ~10 s to <0.2 s (and lowers Young's optimal save interval from ~22 minutes to ~3 minutes, cutting lost work on node crashes), at the cost of ~6.0 GB of pinned host RAM per 8-GPU node, atomic commit manifests, and rate-limiting S3 uploads so they do not contend with NCCL network traffic.
  • Sequence packing vs. dynamic padding vs. length bucketing. Dynamic padding keeps one document per row cleanly isolated, but wastes ~49% of synchronous 128-GPU compute on [PAD] tokens and barrier waits when sequence lengths vary widely (100..4096). Sequence packing (concatenating documents into exact 4,096-token chunks with block-diagonal causal masks and reset position_ids) lifts real-token utilization near 100% and eliminates variable-shape CUDA allocator stalls, at the trade-off of splitting >4,096-token documents and shifting from per-sequence to per-token loss weighting. Length bucketing avoids splitting documents, but induces gradient correlation unless bucket order is randomized every step.
  • Full FSDP vs. Hybrid Sharding (HSDP). Full 128-way FSDP minimizes static state memory (1.0 GB/GPU), moving ~6.0 GB per GPU per step over InfiniBand (~0.15 s at 40 GB/s, mostly overlapped). HSDP shards 8-ways inside each node over fast NVLink and replicates across the 16 nodes, keeping all per-layer all-gather barriers off InfiniBand and cutting inter-node traffic 1.6× (~3.75 GB/GPU gradient all-reduce), at a 16× static-state memory cost (16.0 GB/GPU).
  • Prefetch queue depth vs. pinned host RAM. Increasing num_workers × prefetch_factor absorbs multi-second object-storage hiccups, but pinned (page-locked) memory cannot be swapped out by the OS; it costs only megabytes for integer token IDs, whereas video or audio tensors require strict host-RAM budgeting so workers do not trigger OS out-of-memory kills.
  • Inline validation vs. decoupled evaluation cluster. Running validation inside the training loop gives instant step-exact metrics but stalls 128 expensive training GPUs on small eval batches; dedicating 2 separate GPUs to watch new S3 checkpoints introduces a 2–5 minute metric delay in exchange for 100% uninterrupted training throughput.
  • Training parallelism vs. low-latency serving layout. Pipeline Parallelism (splitting layers sequentially across GPUs) scales high-batch training cheaply over slower links, but adds sequential stage-to-stage hops to every generated token at inference; online serving trades checkpoint resharding effort for Tensor Parallelism inside a single NVLink node to hit sub-50 ms per-token latency.

Common mistakes

  • Confusing nvidia-smi GPU-Util (DCGM_FI_DEV_GPU_UTIL) with useful math. Because NCCL kernels spin-wait on the GPU while blocked on a slow peer, legacy GPU_UTIL can read 100% during severe straggler stalls and counts [PAD] matrix multiplies as full utilization. Always pair DCGM_FI_PROF_PIPE_TENSOR_ACTIVE (Tensor Core activity) with real non-padding tokens/sec.
  • Looking only at the 128-GPU cluster average. Averaging hides whether all 128 GPUs go idle together (lockstep CPU stall) or 1 straggler node slows down 127 waiting peers.
  • Skipping the step-vs-wall-clock period test. Failing to test whether halving batch size shifts the 50-second period wastes hours guessing between step-triggered hooks (save_steps=20, shard size) and 50-second wall-clock host daemons.
  • Profiling blind during the 40-second busy window. Capturing steps 0..8 misses a stall that happens at step 20; always align PyTorch Profiler's schedule(skip_first=...) or an 80-second Nsight Systems window directly across a known trough.
  • Passing non_blocking=True without pin_memory=True and a side CUDA stream. Without page-locked host RAM, host-to-device copies silently block the CPU thread, and without a separate stream (plus tensor.record_stream), copies serialize behind compute or risk premature buffer reuse.
  • Forcing CPU-GPU synchronization every step in logging code. Calling loss.item(), print(tensor), or torch.cuda.empty_cache() on every step drains the asynchronous CUDA launch queue so the CPU cannot stay ahead of the GPU.
  • Packing sequences without document attention masks and reset position_ids. Allowing cross-document attention leaks unrelated context during training and breaks parity with online serving, where every user prompt begins fresh at position 0.
  • Exporting bfloat16-trained weights directly into float16 serving without range checks. Because fp16 overflows above 65,504 while bf16 reaches ~3.4 × 10^38, uncalibrated conversion causes silent Inf/NaN logit corruption on outlier activations.

Follow-up questions

  • When you replace per-batch dynamic padding with concatenated sequence packing, what changes in per-example loss weighting, causal attention masking, and online serving batch execution? On loss weighting, dynamic padding with sequence-averaged loss gives a 100-token short message the same gradient weight as a 4,000-token essay, whereas packed sequences with token-averaged loss weight every token equally (up-weighting long documents) and split documents longer than 4,096 tokens across chunk boundaries; always pack randomly shuffled documents rather than sorting by length so gradient batches stay i.i.d. On causal attention masking, you must pass cumulative document start offsets (cu_seqlens) into a variable-length FlashAttention kernel to enforce a block-diagonal causal mask and reset position_ids to 0 at each document start—preventing cross-document contamination and cutting attention FLOPs from O(chunk_len^2) down to O(sum(doc_len_i^2)). On online serving, inference engines process independent live requests starting at position 0 (matching masked packing cleanly) and use continuous batching with a paged KV cache rather than sequence concatenation, so online requests neither wait to be packed together nor waste memory on padding.
  • Suppose profiling shows ranks spending most of the trough inside NCCL collectives—how do you tell apart degraded physical interconnects (PCIe lanes or InfiniBand links) from software or data-loading stragglers? Inspect per-rank collective entry timestamps in PyTorch's NCCL Flight Recorder (TORCH_NCCL_ENABLE_TIMING=1): if Rank 17 consistently enters all-gather 500 ms after Ranks 0–16, the collective itself is healthy and Rank 17 is a straggler—then separate a software/data straggler (high data_wait_ms or unbucketed sequence length that moves across ranks when shards shuffle and disappears on synthetic in-memory batches) from a GPU compute straggler (elevated probe_ms on our collective-free matmul check alongside thermal/power clock throttling in DCGM). Conversely, if all 128 ranks enter the collective within milliseconds of each other yet the collective duration is slow, the network or PCIe fabric is degraded. Confirm hardware degradation by checking InfiniBand port counters (symbol_error_counter, link_downed, port_xmit_wait, and negotiated link rate via ibstat), verifying full PCIe Gen5 x16 width in nvidia-smi -q plus kernel XID/AER logs, and running pairwise 2-node nccl-tests (all_gather_perf) across all 16 × 15 / 2 = 120 node pairs—any degraded NIC or switch cable immediately stands out in every pair involving that node.
  • How would you redesign the ingestion pipeline to keep all GPUs fed at peak speed when raw training records live in compressed shards on remote cloud object storage? First, offline-repack tiny individual blobs into 256 MB–1 GB Zstd-compressed shard files paired with lightweight byte-offset index files, eliminating per-sample HTTP request overhead and S3 per-prefix request-rate throttling (5,500 GET/s per prefix). Second, assign each (rank, worker_id) a deterministic, disjoint, token-balanced shard schedule with staggered starting byte offsets so all 128 ranks never hit shard boundaries on the same step. Third, run an asynchronous background downloader per node that prefetches the next 2 shards per worker into a local NVMe ring cache using parallel byte-range GETs (~1 concurrent stream per 85 MB/s needed) with hedged retries at p95 latency and exponential backoff. Fourth, keep persistent_workers=True in multi-process CPU workers that stream-decompress shards into a continuous replacement reservoir shuffle buffer (never fill-drain-refill), pack fixed-length chunks into pin_memory=True host buffers for side-stream DMA transfer, and checkpoint each worker's exact (shard_id, sample_offset) alongside model weights for deterministic zero-duplication restarts.

Follow-up questions

Similar questions

More Tower interview questions

All 3 Tower questions →