Model Training Infrastructure and Distributed Training Questions
Scaling model training across hardware and time. Covers GPU/accelerator considerations, data and model parallelism, distributed and large-scale training, experiment tracking and training infrastructure, and the training-versus-inference compute tradeoff. Focuses on the systems and resource decisions that make large-model training feasible.
Explain synchronous versus asynchronous stochastic gradient descent in a distributed data-parallel setup. Discuss convergence guarantees, staleness, and scenarios where asynchronous updates are attractive despite potential instability.
Sample Answer
Direct answer
Synchronous SGD has every worker compute a gradient against the same, current parameter values and waits for all workers before applying a single combined update, giving convergence behavior equivalent to (or very close to) single-machine SGD at a larger effective batch size; asynchronous SGD lets each worker push its gradient and pull fresh parameters independently, without waiting for others, trading some workers computing gradients against slightly outdated ("stale") parameters for higher hardware utilization.
Structured elaboration
- Synchronous: every worker's gradient this step is computed against identical parameter values (the state after the previous step's update); once all gradients arrive, they're averaged and applied as one update, after which every worker again has identical, up-to-date parameters. Convergence guarantees closely mirror standard SGD's, since the process is mathematically equivalent to computing a gradient over a larger effective batch (the concatenation of every worker's mini-batch).
- Asynchronous: a worker pulls current parameters, computes a gradient, and pushes it back independently of other workers' progress; by the time its push arrives, the server's parameters may have already been updated by other workers' pushes in the meantime, meaning the pushed gradient was computed against parameters that are now "stale" (out of date) relative to the current server state.
- Staleness and its effect: the degree of staleness (how many other updates happened between a worker's pull and its push) tends to grow with more workers and with heterogeneous worker speeds (a slow worker's gradient becomes more stale the longer it takes to compute); staleness biases the effective update direction, since it's technically a gradient of an earlier point on the loss surface being applied to a later point, which can slow or, in extreme cases, destabilize convergence if unbounded.
- When each is chosen: synchronous is the default for most modern large-scale training (predictable convergence behavior, well-supported by AllReduce-based collectives) provided stragglers are managed; asynchronous is chosen specifically when worker heterogeneity or unreliability is severe enough that waiting for the slowest worker every step would be prohibitively wasteful, accepting some convergence-quality cost in exchange for higher aggregate hardware utilization.
Worked example
With 8 workers, one of which is consistently 3x slower than the others (a straggler): synchronous training's every-step wall-clock time is bounded by that slowest worker, wasting the other 7 workers' idle time waiting each step; asynchronous training lets the 7 faster workers keep contributing updates continuously without waiting, at the cost of the slow worker's occasional contributions being noticeably stale (computed against parameters several updates out of date) by the time they arrive.
Trade-offs & pitfalls
Bounded-staleness schemes (allowing async updates but capping how stale any single contribution is allowed to be before it's rejected or down-weighted) are a common middle ground, retaining most of asynchronous training's utilization benefit while limiting the worst-case convergence-bias risk that fully unbounded asynchrony carries.
You are asked to reduce the cloud training cost of a distributed training pipeline by 50% while keeping final model quality. Propose a prioritized plan of engineering and algorithmic changes (instance types, spot instances, mixed-precision, larger batch sizes with LARS/LAMB, checkpointing, more efficient kernels), estimate expected savings per item, and discuss risks.
Sample Answer
Direct answer
Cutting a distributed training pipeline's cloud cost by 50% while preserving model quality is best approached as a prioritized menu of levers ordered by expected cost-savings-to-quality-risk ratio: start with the cheapest, lowest-risk wins (spot/preemptible instances, mixed precision, right-sizing instance types) before touching anything that could meaningfully change model quality (reducing dataset size, more aggressive compression).
Structured elaboration
- Spot/preemptible instances: often 60-90% cheaper than on-demand for the same GPU type, with the cost of needing robust checkpointing and fault tolerance to handle preemption; for a training job that already checkpoints reasonably often, this is usually the single largest, lowest-quality-risk lever available.
- Mixed precision and larger effective batch via gradient accumulation: reduces wall-clock training time (fewer GPU-hours billed) with negligible to no quality impact if implemented correctly (loss scaling, appropriate LR scaling), a near-free win if not already in place.
- Right-sizing instance/GPU type: matching the GPU generation and count to the model's actual compute/memory profile rather than defaulting to the largest available instance; over-provisioned memory or compute that the workload never uses is pure waste.
- Reducing redundant/wasted compute: eliminating quota-padding in the training pipeline itself (unnecessary re-runs, overly frequent validation passes, excessive checkpoint overhead) before touching the model or data.
- Higher-risk-to-quality levers, use last and validate carefully: reducing dataset size or training steps (risks under-training), more aggressive quantization/compression during training (risks numerical instability), and reducing model size (directly risks quality) should be considered only after the lower-risk levers are exhausted, and always validated against the actual quality metric, not assumed safe.
Worked example
A training pipeline costing $100k/month on on-demand GPU instances: moving to spot instances at a typical 70% discount for the bulk of training (assuming acceptable preemption handling) alone could reduce cost to roughly $30k for that portion; combined with mixed precision cutting wall-clock time by, say, 30-40% (fewer billed GPU-hours for the same work), the compounded reduction plausibly reaches the 50% target without touching dataset size or model architecture at all, which is exactly the order of operations that keeps quality risk lowest.
LARS/LAMB for larger batch sizes, and more efficient kernels
- Larger batch sizes with LARS/LAMB: a bigger batch reduces the number of optimizer steps (and thus wall-clock time and GPU-hours) for the same total data seen, but plain SGD/Adam destabilizes at very large batch sizes unless the learning rate is scaled up proportionally, which itself causes divergence beyond a point; layer-wise adaptive rate scaling optimizers (LARS for SGD-style training, LAMB for Adam-style, both commonly used for large-batch BERT/ResNet-scale training) normalize the update per layer by that layer's weight norm, which lets the effective learning rate scale further with batch size before training destabilizes, making a bigger batch (and the throughput win it buys) actually usable rather than just theoretically available. This is a moderate-risk lever: it changes optimizer dynamics, so it needs the same before/after validation-metric check as any other quality-sensitive change.
- More efficient kernels: replacing generic framework ops with fused, hardware-tuned kernels (e.g. FlashAttention for the attention block, fused LayerNorm/optimizer kernels, or a framework's
torch.compile/XLA graph compilation) cuts wall-clock time per step with no change to the actual numerical computation being performed (same math, fewer memory round-trips and kernel-launch overheads), making it one of the lowest-quality-risk levers on the list, similar in risk profile to mixed precision.
Trade-offs & pitfalls
The critical discipline here is validating that "quality is preserved" empirically (tracking the actual validation metric before and after each change) rather than assuming a change is safe because it is theoretically lossless; mixed precision done carelessly (no loss scaling, no LR adjustment) or aggressive spot-instance usage without adequate checkpointing (losing significant progress on preemption) can each silently degrade either quality or effective cost savings if not implemented and monitored carefully.
Explain gradient accumulation and why it is used. Provide a brief algorithmic description of how to implement gradient accumulation to emulate a larger batch size on limited-memory GPUs, and mention how it interacts with learning rate schedules and batch-norm statistics.
Sample Answer
Direct answer
Gradient accumulation simulates training with a larger batch size than fits in memory by running several forward/backward passes on smaller micro-batches, summing (or averaging) their gradients without updating the weights, and only applying the optimizer update once after the desired number of micro-batches has accumulated.
Structured elaboration
- Why it's needed: GPU memory limits the largest batch that fits for a given model; gradient accumulation decouples the "effective batch size" the optimizer sees from the "micro-batch size" that actually fits in memory, letting you train with a large effective batch on hardware that can't hold that batch's activations all at once.
- Algorithm: for each of K micro-batches, run forward and backward (accumulating
.gradon each parameter, since PyTorch's default is to add to existing gradients rather than overwrite), without callingoptimizer.step()orzero_grad()in between; after the Kth micro-batch, calloptimizer.step()once, thenzero_grad()to reset for the next cycle. - Loss scaling convention: divide each micro-batch's loss by K before calling
.backward(), so the summed gradient across K micro-batches equals the average gradient a true large-batch step would have produced, keeping the effective learning rate consistent with what was tuned for that effective batch size.
Worked example
To simulate an effective batch size of 128 on hardware that only fits 32 samples at a time: run 4 micro-batches of 32 samples each, dividing each micro-batch's loss by 4 before backward, accumulating gradients across all 4, then calling optimizer.step() once; the resulting parameter update is (approximately, modulo any batch-size-sensitive layers like BatchNorm) equivalent to what a single true batch-128 step would have produced.
Interaction with learning-rate schedules
A learning-rate scheduler's .step() must be called once per completed accumulation cycle (once per true optimizer step), not once per micro-batch; calling it every micro-batch effectively runs the schedule K times faster than intended relative to the actual number of samples/effective-batches seen, so a warmup or decay schedule tuned for, say, 1000 optimizer steps would finish in 1000 micro-batches instead of 1000*K micro-batches, a large, easy-to-miss bug. The scheduler's total step count (and any warmup-step count) should be computed as total_micro_batches / accumulation_steps, matching the optimizer_step counter, not the raw micro-batch or sample index.
Trade-offs & pitfalls
Gradient accumulation increases wall-clock time per effective step (K sequential forward/backward passes instead of one) since it doesn't add compute parallelism, only memory savings; it also doesn't fix batch-size-sensitive layers like BatchNorm, whose statistics are still computed per micro-batch rather than over the full effective batch, unless specifically handled (e.g. via sync-BN-style aggregation or accepting the approximation).
Describe how GPU memory capacity and memory bandwidth constrain choices of batch size, model size, and training throughput. Explain the trade-offs between increasing batch size, using gradient accumulation, reducing precision, and applying activation checkpointing to fit larger models or larger effective batches into GPU memory while balancing convergence and throughput.
Sample Answer
Direct answer
GPU memory capacity limits how large a batch and model you can fit at all, while memory bandwidth (how fast data moves between GPU memory and compute units) limits how fast you can actually process that data once it fits, so a training configuration can be capacity-bound, bandwidth-bound, or compute-bound depending on which resource is the tightest constraint for a given model and batch size.
Structured elaboration
- Capacity constraint: parameters, gradients, optimizer state, and activations must all fit within the GPU's total memory (e.g. 80GB on an H100); exceeding this causes an out-of-memory error regardless of how fast the GPU could otherwise compute, forcing a smaller batch size, model, or the memory-saving techniques (mixed precision, checkpointing, sharding) discussed elsewhere in this topic.
- Bandwidth constraint: even when everything fits, operations that move a lot of data relative to the compute they perform (elementwise operations, some normalization layers, small matrix multiplies) can be bottlenecked by how fast data streams between HBM and the GPU's compute units rather than by the compute units' raw throughput; this shows up as low GPU utilization percentage even though the workload is running continuously.
- Batch size trade-off: larger batch sizes generally improve compute efficiency (better utilization of the GPU's parallel compute, amortizing fixed per-kernel-launch overhead) up to the point where capacity is exhausted; very small batch sizes tend to be more bandwidth-bound (relatively more data movement per unit of useful compute) since fixed overheads and memory-bound elementwise operations don't scale down favorably.
- Model size trade-off: a larger model directly increases capacity pressure (more parameters, more activation memory per sample) which forces either a smaller batch size or additional memory-saving techniques, in turn affecting how compute-efficient a given step actually is.
Worked example
Training a model where activation memory dominates: at batch size 8, activations plus weights plus optimizer state fit within an 80GB GPU with headroom, and the GPU runs near its compute-bound peak throughput; increasing batch size to 32 might exceed the 80GB budget entirely (capacity-bound failure), while decreasing to batch size 1 for debugging purposes leaves so much of each kernel launch as fixed overhead relative to the tiny amount of actual compute that the GPU spends much of its time bandwidth- or launch-overhead-bound rather than compute-bound.
Trade-offs & pitfalls
A common mistake is assuming more GPU memory alone fixes a slow training run; if the workload is bandwidth-bound rather than capacity-bound, adding memory (a bigger GPU) doesn't address the actual bottleneck, only profiling (checking whether the GPU is near its compute-throughput ceiling or spending time waiting on memory transfers) reveals which constraint is actually binding.
Explain the architectural differences between CPUs and GPUs and why GPUs are generally preferred for deep learning training. Cover parallelism models (SIMD/SIMT), number of ALUs/cores, memory hierarchy (registers, shared/local memory, device DRAM), memory bandwidth vs latency, and give examples of workloads or phases (data preprocessing, small-batch inference, control-heavy tasks) where CPUs or other accelerators might be a better choice in production ML systems.
Sample Answer
Direct answer
CPUs are built for fast, flexible execution of a wide variety of sequential tasks with a handful of powerful cores, while GPUs are built for massive parallelism: thousands of simpler cores executing the same operation across huge amounts of data simultaneously, which matches deep learning's core workload (matrix multiplications and other operations applied identically across millions of numbers) far better than a CPU's design does.
Structured elaboration
- Core count and design philosophy: a modern CPU has a handful to a few dozen powerful, complex cores, each optimized to execute a single instruction stream very fast, handle branching logic efficiently, and minimize latency for any one task. A GPU has thousands of much simpler cores, each individually slower and less flexible, but designed to all execute the same instruction on different pieces of data at the same time (the SIMT, single-instruction-multiple-thread, execution model).
- Why this matches deep learning: a neural network's core computation, matrix multiplication, is fundamentally "do the same multiply-and-add operation, over and over, on huge numbers of different values"; this maps almost perfectly onto a GPU's thousands-of-simple-cores-doing-the-same-thing design, while a CPU, however fast its individual cores are, simply doesn't have enough parallel execution units to keep up with the sheer volume of identical, independent arithmetic operations a large matrix multiplication requires.
- Memory bandwidth: GPUs are also built with much higher memory bandwidth than CPUs, needed to keep those thousands of parallel cores fed with data fast enough to avoid becoming memory-bound (as discussed in the memory-hierarchy topic), another design choice specifically suited to deep learning's data-hungry, highly parallel workload.
- Memory hierarchy: a GPU's memory system is tiered specifically to feed its massive core count: each thread has a small set of private registers (fastest, lowest latency, smallest capacity); threads within a block share a small, fast on-chip shared/local memory (an explicitly-managed scratchpad, still far lower latency than main memory, used to stage data reused across many threads); and device DRAM (HBM on modern data-center GPUs) is the large-capacity main memory all cores draw from, with far higher bandwidth than a CPU's DRAM but also meaningfully higher latency per individual access than registers or shared memory. GPUs tolerate that higher per-access latency by having enough concurrently-scheduled threads (far more than there are cores) to hide it: while one warp waits on a memory access, the scheduler switches to another warp with work ready, so high bandwidth (not low latency) is the property the GPU's design actually optimizes for, and SIMT's massive thread-level parallelism is precisely what makes hiding that latency possible.
- An analogy for a non-expert audience: a CPU is like a few dozen expert chefs, each capable of cooking any dish quickly and skillfully, one at a time; a GPU is like thousands of cooks who can only do one simple task (like chopping a specific vegetable) but can all do it simultaneously across thousands of ingredients at once, a design that wins decisively for a task that's fundamentally "do this same simple thing many, many times," which is exactly what training a neural network involves.
Worked example
A matrix multiplication of two 4096x4096 matrices involves roughly 40963×2≈1.37×1011 floating-point operations, every one of them structurally identical (a multiply and an add); a GPU's thousands of parallel execution units can process huge numbers of these identical operations concurrently, while a CPU with only a few dozen cores, however individually fast, must process far fewer of these operations at any given instant, resulting in dramatically lower achievable throughput for this specific, highly-parallel kind of workload despite a CPU often being faster for many other kinds of general-purpose tasks.
Trade-offs & pitfalls
CPUs remain better suited (often much better) for tasks with lots of branching, sequential dependencies, or a wide variety of different operations that don't parallelize the same way (general application logic, for instance); the GPU's advantage for deep learning is specifically because that workload happens to be an unusually good match for massive, simple parallelism, not because GPUs are universally "faster" than CPUs at everything. Concretely, in a production ML system: data preprocessing (tokenization, image decode/resize, variable-length string handling) is often better suited to CPUs, since it's branchy, per-example work with irregular control flow that doesn't map cleanly onto SIMT's identical-operation-across-many-threads model; small-batch, latency-sensitive inference (a single request at a time) frequently runs faster or more cost-effectively on a CPU too, since a GPU's parallelism advantage only pays off once there's enough simultaneous work to fill its thousands of cores, and the fixed overhead of a kernel launch and host-device data transfer can exceed the actual compute time for a tiny batch; and control-heavy tasks (business rule evaluation, tree-based decision logic, orchestration code around the model) are naturally CPU work, with other accelerators (TPUs, or inference-specialized ASICs) sometimes preferred over general-purpose GPUs specifically for very-large-batch, latency-tolerant inference at scale, where their different power/throughput trade-off can beat a GPU's.
Unlock Full Question Bank
Get access to all 17 Model Training Infrastructure and Distributed Training interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.