Distributed Training Without Topology Amnesia
Make every byte of training state, every process group, and every recovery boundary explicit before calling a run scalable.
- Authorship
- InterviewsVector
- Published / updated
- 2026-09-26 / 2026-09-26
- Review status
- Artifact tests passing · primary sources recorded
Original InterviewsVector teaching. Executable artifacts are deterministic illustrative audits with focused tests and recorded primary sources; they do not claim hardware benchmarks, distributed execution, production deployment, capacity certification, or universal model quality.
The decision in one pass
A distributed training design is a state-and-communication map, not a worker count. Freeze the model graph, precision, optimizer, dataset order, batch semantics, checkpoint format, cluster devices, links, and failure policy. Inventory parameters, master weights, gradients, optimizer slots, activations, temporary buffers, data-loader state, random state, and communication workspaces by lifetime and rank ownership. Decide which dimensions use data, tensor, or pipeline parallelism, then state exactly which training state is replicated or sharded and which collectives reconstruct it at each phase. Place chatty groups on the fastest links, preserve globally correct batch and update semantics, and budget activation memory separately from state sharding. Benchmark step time, per-rank memory, collective tails, skew, input stalls, numerical behavior, and recovery on the exact topology. A run is not operational until a version-bound checkpoint can restore on a declared topology without silently changing data position or optimizer semantics.
Why this matters
Adding workers can expose a network bottleneck, a slow rank, a data-loader stall, or a checkpoint storm instead of increasing useful training throughput. ZeRO and fully sharded data parallelism reduce replicated state but require all-gathers and reduce-scatters at precise moments. Tensor and pipeline groups change activation and communication behavior. Activation checkpointing exchanges memory for recomputation but does not shard optimizer state. A job can report healthy average utilization while one rank determines every step and a checkpoint that saves successfully still fails during real recovery.
You will be able to
- Create a rank-owned ledger for parameters, gradients, optimizer state, activations, temporary buffers, RNG, data position, and checkpoint metadata.
- Distinguish data, tensor, and pipeline parallel dimensions from parameter, gradient, and optimizer-state sharding.
- Map all-reduce, all-gather, reduce-scatter, broadcast, point-to-point, and synchronization onto physical link and process-group boundaries.
- Measure per-rank memory, critical-path collectives, skew, input time, useful samples or tokens per second, numerical behavior, and recovery.
- Define checkpoint and restart semantics that preserve model, optimizer, scheduler, scaler, RNG, and dataset progress across failures.
Prerequisite contract
Your Vector Loop for this lab
- 01
Model
Map model, optimizer, precision, gradients, activations, data order, batch semantics, devices, ranks, links, process groups, checkpoint state, and failure domains.
- 02
Derive
Derive state bytes and shard factors, effective global batch, collective payloads and ordering, activation trade-offs, critical-path time, and recovery requirements.
- 03
Build
Build a deterministic full-shard topology audit over invented rank placement and aggregate evidence; bind all state and decisions to immutable scope and content digests.
- 04
Stress
Inject missing ranks, incorrect state shards, reordered collectives, activation pressure, link tails, rank skew, input stalls, NaNs, checkpoint corruption, and restore-on-different-topology failures.
- 05
Operate
Observe per-rank step phases, memory, collectives, input, skew, numerical health, checkpoints, recovery point, wasted work, and infrastructure cost by exact run identity.
- 06
Defend
Defend the state placement, collective schedule, global-batch semantics, bottleneck evidence, checkpoint contract, and the rollback or resize boundary.
Begin with a complete training-state ledger
Parameters are only one part of the resident set. Training can also hold gradients, optimizer moments, master-precision weights, activations retained for backward, temporary kernel and collective buffers, distributed metadata, and data-loader queues. Some state persists across the run, some exists only within a layer or microbatch, and some can be recomputed. Record bytes, precision, lifetime, ownership, reconstruction operation, and checkpoint responsibility per rank instead of multiplying parameter count by one convenient factor.
| State | Placement decision | Failure if forgotten |
|---|---|---|
| parameters and master weights | replicate, tensor-shard, pipeline-shard, or full-shard | out-of-memory or unexpected all-gather |
| gradients | replicate, reduce, or reduce-scatter | wrong update semantics or critical-path communication |
| optimizer slots | replicate or shard across data ranks | memory estimate misses the largest persistent state |
| activations | retain, checkpoint and recompute, partition, or offload | peak memory and compute are both mispredicted |
| RNG and data progress | save per logical stream and sampler | restart silently changes examples, dropout, or reproducibility |
Separate the parallel mesh from the shard policy
Data-parallel ranks process different examples and combine update information. Tensor-parallel ranks cooperate inside operations. Pipeline stages own ordered model regions and exchange activations and gradients. A sharding policy then describes which state is partitioned within a group; it is not another synonym for data parallelism. Write named process groups and rank coordinates explicitly so the same rank is not accidentally assigned contradictory ownership.
global_batch = data_parallel_degree × microbatch_per_rank × accumulation_steps
This common form applies only when examples are partitioned across the declared data group and pipeline scheduling preserves the intended number of optimizer updates. Token-based batches, dropped batches, uneven data, or adaptive accumulation require a more explicit contract.
| Policy | State behavior | Communication consequence |
|---|---|---|
| replicated data parallel | parameters, gradients, and optimizer state are largely replicated | gradient all-reduce on the update path |
| optimizer/gradient sharding | selected update state is partitioned across data ranks | reduce-scatter, ownership-aware update, and reconstruction traffic |
| full parameter sharding | parameters, gradients, and optimizer state are partitioned | parameter all-gather around compute plus gradient reduce-scatter |
| activation checkpointing | selected activations are discarded and recomputed | additional compute; not a replacement for persistent-state sharding |
Place collectives on the physical cluster
- 01Name each process groupList rank membership, ordering, device and node placement, transport path, expected payload, and the training phase that invokes the group.
- 02Record collective orderAll ranks must participate consistently; mismatched calls, counts, or datatypes can hang, crash, or corrupt execution rather than returning a friendly validation error.
- 03Measure the critical pathSeparate overlapped from exposed communication, inspect tails rather than only averages, and correlate each collective with the layer, bucket, microbatch, and slow rank.
- 04Test contention and topology lossCo-located jobs, storage traffic, bad links, topology fallback, and one slow device can change collective behavior without changing world size.
A bandwidth formula is a hypothesis because collective algorithms, message sizes, topology, protocol, channels, contention, and overlap change the achieved result. Treat NCCL or another communication runtime as part of the versioned training system, and capture its topology and diagnostic output when debugging a hang or regression.
Audit a full-shard topology snapshot
1def audit_training_topology(contract: TrainingContract, evidence: TrainingEvidence) -> TrainingAudit:2 contract = validate_record(contract, TrainingContract)3 evidence = validate_record(evidence, TrainingEvidence)4 if evidence.scope != contract.scope or evidence.contract_content_id != contract.content_id:5 raise ValueError("evidence belongs to another training contract")6 # Reconstruct rank placement, state shards, and collective order before7 # applying readiness, memory, throughput, collective, and skew gates.Expected output
example=illustrative_only
decision=PASS_TOPOLOGY_AUDIT
topology=dp8-tp2-pp1;world_size=16
state_shards=parameters:8,gradients:8,optimizer:8
peak_memory_gib=58.000;step_throughput=120.000
collective_p95_ms=35.000;rank_step_skew=0.060
claim=LOCAL_TRAINING_AUDIT_NOT_DISTRIBUTED_RUNVerify: python3 -m unittest discover -s courses/ai-engineering/reference-impl/distributed_training -p 'test_*.py' -v
The invented fixture maps sixteen ranks evenly onto two eight-device nodes and audits a `dp8-tp2-pp1` full-shard topology. Parameters, gradients, and optimizer state are each sharded eight ways, the declared collective sequence is parameter all-gather followed by gradient reduce-scatter, and checkpoint restore, rank health, telemetry, activation checkpointing, memory, throughput, collective tail, and rank skew all meet local gates. The implementation rejects wrong world size, uneven placement, partial state sharding, reordered collectives, stale scope, tampered digests, exact-type violations, constructor bypass, and caller mutation.
No process group is initialized and no collective, training step, checkpoint, or recovery is executed. Aggregate invented measurements cannot establish convergence, numerical equivalence, reproducibility, or production throughput. The audit demonstrates reviewable topology evidence only.
Design recovery before scaling useful work
| Failure | Evidence to preserve | Recovery contract |
|---|---|---|
| rank or node loss | last complete step, topology, health, communicator state | abort or elastic policy, replacement placement, bounded restart |
| collective hang | rank-local stacks, collective sequence, counts, topology, link health | global timeout, coordinated termination, diagnostic retention |
| NaN or divergence | loss scale, gradients, inputs, precision, optimizer and model revision | stop update, isolate first bad step, restore known checkpoint |
| checkpoint corruption | manifest, shard digests, completeness marker, storage errors | reject partial generation and fall back to verified generation |
| data-position drift | sampler epoch, shard cursor, RNG, skipped records | restore declared repeat/skip semantics without silent duplication |
A checkpoint is a distributed commit, not a directory that happens to contain files. Publish a manifest only after every required shard and metadata record is durable and digest-verified. Test restoration on the same topology and, if supported, an explicitly different topology. Verify optimizer, scheduler, scaler, RNG, data sampler, global step, and model output behavior—not merely that files can be deserialized.
Operate on useful work, not aggregate utilization
Track step phases and useful samples or tokens processed, not only accelerator utilization. Record data wait, forward, backward, recomputation, optimizer, collective, checkpoint, and idle time per rank. Monitor reserved and peak memory, allocator retries, gradient norms, loss scale, NaNs, stragglers, network retransmits, storage throughput, restart count, recovery point, wasted compute, energy, and cost. The slowest synchronized rank and the least reliable state boundary define the system.
- Keep exact run manifests for code, model, data, tokenizer, optimizer, schedule, precision, kernels, communication runtime, topology, seeds, and environment.
- Alert on rank-level skew and exposed communication before cluster averages hide them.
- Bound checkpoint frequency from recovery-point objective, save duration, storage load, and expected wasted work; more frequent is not automatically safer.
- Requalify after model shape, sequence, batch, precision, optimizer, framework, compiler, driver, communication, cluster, or storage changes.
Operate at three altitudes
Production lens
- — Instrument per-rank data, forward, backward, recompute, optimizer, collective, checkpoint, and idle phases together with memory, numerical health, network, storage, and useful throughput.
- — Treat checkpoints as manifest-bound distributed commits and continuously prove restore semantics, fallback, data position, RNG, optimizer, scheduler, scaler, and next-step behavior.
- — Exercise rank loss, slow devices, bad links, collective mismatch, NaNs, storage throttling, partial checkpoints, topology changes, and repeated recovery before expensive runs depend on them.
Staff lens
- — Own training efficiency as a model, data, optimizer, framework, compiler, communication, scheduler, storage, capacity, reliability, and finance system with one versioned evidence ledger.
- — Choose a topology by time-to-qualified-model and recoverable useful work, not peak device utilization or a best-case scaling chart.
Interview defense
A model fits with full sharding across sixteen GPUs, but scaling from eight GPUs makes each step slower. How do you diagnose it?
I would verify that global batch, accumulation, data order, precision, kernels, and model graph stayed constant, then reconstruct the `dp/tp/pp` rank map and state-shard policy. I would break step time per rank into data, forward, recomputation, backward, optimizer, collectives, and idle time; inspect all-gather and reduce-scatter tails, message sizes, topology, contention, and the slowest rank; and reconcile per-rank peak memory and temporary buffers. I would check whether the larger data group adds communication without enough compute, whether activation memory or input stalls dominate, and whether overlap is real. I would compare smaller groups or different placement on the same workload, then test checkpoint restore and rank loss before accepting a topology. Fitting is only a capacity result, not a scaling result.
Expect the interviewer to press on
- — Which state does full sharding reduce, and which memory can remain dominant?
- — Why can one slow rank determine the complete step time?
- — What must a checkpoint contain beyond parameter tensors?
Misconceptions to remove
“FSDP or ZeRO makes the model memory problem disappear.”
They reduce selected replicated training state; activations, temporaries, communication buffers, uneven shards, allocator headroom, and reconstruction peaks still require explicit budgets.
“High average GPU utilization means distributed training is efficient.”
Utilization can include recomputation, stalls, or unproductive work and can hide rank tails. Useful tokens or samples per time, quality, recovery, and cost must be measured end to end.
“If a checkpoint directory exists, the run is recoverable.”
Every required shard and logical state must be complete, bound to a manifest, verified, loadable, and proven to resume the intended update and data semantics.
Check your model
1. Why are activation checkpointing and state sharding different controls?
Checkpointing discards selected activations and recomputes them, while state sharding partitions persistent parameters, gradients, or optimizer state across ranks.
2. What makes collective order a correctness concern?
Ranks must call compatible collectives with consistent counts and datatypes; mismatches can hang, crash, or corrupt execution rather than merely reduce performance.
3. What does a recovery test verify after deserialization?
That model, optimizer, scheduler, scaler, RNG, data progress, global step, topology policy, and the next training update follow the declared semantics.
Prove the mechanism
Extend the topology audit with a checkpoint manifest containing model, optimizer, scheduler, scaler, RNG, sampler, and shard digests. Add incomplete and cross-topology restore cases without weakening exact-type or mutation defenses.
Add a production constraint
Design a qualification plan comparing replicated data parallel, optimizer/gradient sharding, and full sharding across two cluster topologies. Include state ledgers, process groups, collectives, activation policy, global batch, numerical evidence, slow-rank injection, checkpoints, recovery, useful throughput, energy, and cost.
Artifact: Distributed training topology audit
courses/ai-engineering/reference-impl/distributed_training/training_topology_audit.py
Download reference implementationPrimary references and next links
References
- 1. FullyShardedDataParallel
PyTorch. Official framework reference for parameter sharding, process groups, state dictionaries, and full-shard operation.
- 2. ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
Rajbhandari et al.. Primary research on partitioning optimizer state, gradients, and parameters to reduce data-parallel memory redundancy.
- 3. Collective Operations
NVIDIA NCCL. Official collective definitions and requirements for consistent rank participation, counts, and datatypes.
- 4. Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM
Narayanan et al.. Primary research on composing tensor, pipeline, and data parallelism across GPU clusters.
Continue through the graph
- Backpropagation as Local Contracts →
Place forward values and reverse gradients into the distributed ownership and collective schedule.
- The Accelerator Memory Hierarchy →
Translate training state and collectives into per-tier capacity and traffic constraints.
Glossary: data parallelism · tensor parallelism · pipeline parallelism · FSDP · ZeRO · all-reduce · all-gather · reduce-scatter · activation checkpointing · recovery point objective