Distributed PyTorch runs the same script in several processes, one per device, which cooperate only through collectives (calls every process of a group makes together, such as summing a tensor across all of them). Every API on this page is a rule for what each process holds and which collectives it calls: copy the model and split the data (DDP), shard the model's state too (FSDP2), split the matrices (tensor parallel), split the sequence (sequence and context parallel), split the layers (pipelining), and save it all without gathering it in one place (DCP).
Fig. 1, step by step: the same model on several processes
Filled = held by that rank, faint = held only while in use or not at all. Counts and bytes measured on the running example, CPU processes, gloo, torch 2.14.1, 2026-10-13; slab sizes are not to scale.
You need: the parallelism forms themselves (why sharding saves memory, the split maths, which split at what scale), which Distributed Training owns; this page shows only PyTorch's API for each and what it does. The parent's Distributed lab tab follows one step of the same model through DDP, FSDP2, TP, a 2-stage pipeline, DCP and three hangs. The running example is the topic's 3,186,944-parameter character GPT (4 blocks, dmodel 256, batch 8 × 64 tokens, AdamW), imported unchanged by every script in src/exp/. The JAX counterpart of this page (meshes, shardings and collectives in JAX) is Sharding and scale.
Shard(d), Replicate() or Partial() (a pending sum).fully_shard call).| API | What each process holds | Collectives in one step of the running example (measured) | Per process | Section |
|---|---|---|---|---|
| DDP | the whole model, different data | 2 all-reduces from step 1 on, 1 in step 0 | 12,747,776 B of weights, 25.5 MB of AdamW state | 3 |
| FSDP2, 4 processes | 1/4 of every parameter, its gradient and its optimizer state | 14: 9 all-gathers, 5 gradient reductions | 3,187,200 B of weights | 4 |
| HSDP, 2 × 2 | 1/2 of every parameter, copied in two replicas | 19: 9 all-gathers and 5 reductions in the shard group, 5 all-reduces in the replica group | 6,374,400 B | 4, Mesh explorer |
| TP, 2 processes | half of each attention and MLP matrix, the same data | 16 all-reduces of 524,288 B (24 with a careless plan) | saved activations 22.17 MB (one process: 47.41 MB) | 6 |
| TP + sequence parallel | as TP, plus half the sequence between the matrices | 18 all-gathers of 262,144 B, 16 reduce-scatters | saved activations 20.06 MB | 6 |
| Context parallel | half the sequence inside attention | 1 all-gather of K and V, or 1 pass per other process | K and V of its own tokens | 7 |
| Pipelining, 2 stages | half the layers | send/recv of activations and their gradients | idle 10 to 21% of the step | 8 |
| PP × FSDP × TP, 8 processes | 1/8 of the weights | TP all-reduces, FSDP all-gathers and reductions, one pp all-reduce for the tied embedding | about 1.6 MB of 12.75 MB of weights | 10 |
Measured on Apple M1 Pro, CPU, gloo, torch 2.14.1, one thread per process, 2026-10-13; 50 recordings on 2, 4 and 8 processes. Counts, sizes, placements, memory and losses carry over to GPUs in kind; times do not (section 12). NCCL itself is on Streams, CUDA graphs and multi-GPU.
Eight Python processes start on eight GPUs. Before any tensor moves, each must learn who it is, find the others and agree on a channel. c10d (PyTorch's distributed core) does this in three layers: a store (a small key-value server everyone can reach), a process group (a set of ranks plus a backend) and the backend itself.
torchrun --nproc_per_node 4 train.py starts 4 copies with RANK, LOCAL_RANK, WORLD_SIZE, MASTER_ADDR and MASTER_PORT set. init_process_group("gloo") connects each to a TCPStore at that address; every rank writes its address under a key and reads the others' (the rendezvous). init_device_mesh("cpu", (2, 2), mesh_dim_names=("dp", "tp")) lays ranks 0 to 3 out as [[0, 1], [2, 3]] and creates one group per row ("tp": {0, 1}, {2, 3}) and per column ("dp": {0, 2}, {1, 3}); recorded on rank 1: coordinate (0, 1), tp group [0, 1], dp group [1, 3].
Neighbouring ranks share a row, which is why torchtitan puts tensor parallelism on the innermost (last) mesh dimension: neighbouring ranks share a server and its fast links (section 10). A collective can also run on any subset you name, dist.new_group([0, 1]). The Mesh explorer shows every group of every layout run here. How torchrun's agent, rendezvous and the launchers above it work on a cluster is Launching distributed training's subject; this page takes the processes as given.
Left: the launch and the rendezvous. Right: the 2 × 2 mesh, rows the tp groups, columns the dp groups; rank 1 highlighted. Measured, 4 CPU processes.
When one process dies, the others block in their next collective. torchrun --max-restarts N turns that into a restart: its agent kills the survivors, runs the rendezvous again and starts every worker from the top of the script, with TORCHELASTIC_RESTART_COUNT incremented. Nothing is kept in memory, so the script must resume from its own checkpoint. Run here with rank 1 crashing at step 3: losses after the restart equal an uninterrupted run exactly, because the checkpoint holds weights, AdamW state and the step number.
Events from both ranks of one run (2 processes, --max-restarts 2, the script checkpoints after every step). Measured, 2 CPU processes.
Every variable torchrun handed rank 1 of 4:
The store rank 0 hosts (or torchrun's agent, TORCHELASTIC_USE_AGENT_STORE=True) is wrapped in a chain : prefixes keep different groups' and restart attempts' keys apart. You can use it yourself; four ranks each wrote hello/<rank> and all read back .
"gloo", "nccl") or a device map such as "cpu:gloo,cuda:nccl".torchrun's own log of the restart, host and process ids removed:
init_process_group(timeout=...)); the cause was not isolated (gloo over the loopback interface on macOS). torchrun's restart budget absorbed it, which is the general lesson: give --max-restarts some slack and make resuming cheap. For failures that should not restart the whole job, torchft keeps healthy replicas training (the parent's Ecosystem map tab has its status; Fault tolerance at scale owns recovery).Every collective c10d offers, called once with 1 MiB (262,144 float32 values) per rank on 4 ranks, as PyTorch's flight recorder (a per-process log of every collective: name, sizes, dtypes, sequence number) saw it. The five verbs on toy values are in the parent lab's collectives primer (Distributed lab tab, section 2).
Measured, 4 CPU processes, gloo. "Bytes a ring sends per rank" is the textbook cost for S bytes on n ranks; backends pick their own algorithms (Interconnects and scaling owns them).
Two things the recording adds. reduce_scatter_tensor appears as an all_reduce of the whole tensor, because gloo has no reduce-scatter (it all-reduces and keeps a chunk; ProcessGroupGloo.cpp L1557): every gradient reduction on this page reads as an all-reduce. And all_to_all, the one the lab does not draw, sends rank r's j-th piece to rank j (recorded on 4 ranks, rank 1 sent ; every rank's piece number 1 landed on rank 1): it is what expert parallelism and Ulysses-style sequence parallelism are built on.
A collective's time is roughly α + S/B: a fixed latency α per call plus the bytes over an effective bandwidth. Small messages are all latency and big ones all bandwidth, which is why DDP groups gradients into buckets of megabytes and FSDP gathers a whole block at once. Predict first, then read the chart.
How the chart was measured: Apple M1 Pro, CPU, gloo over loopback, one thread per process, under the shared bench lock; median of 15 timed calls after 3 warm-ups, time of the slowest rank, barrier before each call. Load average at the end . The fit is least squares on the medians; where its two terms are equal (α × B) lies between about 160 KiB and 1.3 MiB for these collectives (derived from the fit). On 4 processes the largest size stops at 16 MiB: a 64 MiB all_gather_into_tensor on 4 gloo ranks aborted every process (SIGABRT, no message).
The shape transfers: a latency floor for small messages, then time growing with bytes, and all-reduce costing about two of its halves. The numbers do not. Loopback gloo here moves a 64 MiB all-reduce in 25.7 ms, about 2.6 GB/s; NVIDIA quotes 900 GB/s of NVLink bandwidth per H100 SXM GPU (NVIDIA, vendor). NCCL's benchmarks report a "bus bandwidth" that multiplies the measured rate by 2(n − 1)/n for all-reduce so that numbers on different n compare (nccl-tests PERFORMANCE.md); measuring that on real hardware belongs to Interconnects and scaling.
DDP (DistributedDataParallel) keeps a full model on every rank and averages gradients during backward. The C++ reducer (torch/csrc/distributed/c10d/reducer.cpp) puts one autograd hook on each parameter. Gradients are grouped into buckets; when every gradient of a bucket is ready, the bucket goes to a communication hook (by default an all-reduce) and backward carries on. In the first step all gradients share one bucket; after it, DDP rebuilds the buckets in the order the gradients actually arrived, the first one closing at about 1 MiB and the rest at 25 MiB (bucket_cap_mb), so the first bucket fills early in backward.
Fig. 2, step by step: one recorded backward on rank 0 of 2
mlp.proj are ready 12.53 ms into backward, but their bucket is the whole model: nothing can be sent yet (the bucket is 8% full).ln_f and block 3's mlp.proj: 4 tensors) and 11,696,128 bytes (the other 48).Both ranks are drawn with rank 0's recorded times; a layer fills with its bucket's colour as its gradients become ready, and bucket heights are to scale by bytes. Step 0: one bucket of 12,747,776 bytes, all-reduced 30.7 ms into backward, when the last gradient arrived. Step 1: buckets all-reduced at 1.0 and 17.25 ms. Measured: the parent lab's DDP run (2 CPU processes, gloo), reshaped by src/ddp_timeline.py. The same overlap at scale, 8 of 64 GPUs with seven buckets on NCCL, is Fig. 3 of Streams, CUDA graphs and multi-GPU.
Three switches change that machinery, each measured here on 2 processes.
Unused parameters. The reducer waits for every parameter of a bucket; one that forward did not use never gets a gradient, so its bucket never completes and DDP raises at the next step. find_unused_parameters=True walks the autograd graph from the outputs every step and all-reduces a used-parameter bitmap (216 bytes here: 54 parameters × 4 bytes); static_graph=True promises the same set every step, learns it once and rebuilds buckets after step 1.
Gradient accumulation. With 4 micro-batches per optimizer step, only the sum matters, so all-reducing after each wastes three. with ddp.no_sync(): lets backward accumulate locally:
for i, (x, y) in enumerate(micro_batches): # 4 per optimizer step
ctx = ddp.no_sync() if i < 3 else contextlib.nullcontext()
with ctx:
_, loss = ddp(x, y)
(loss / 4).backward() # the last backward all-reduces the sum
opt.step(); opt.zero_grad(set_to_none=True)
Communication hooks. ddp.register_comm_hook(state, hook) replaces each bucket's all-reduce with any function returning a future of the reduced bucket. PyTorch ships plain all-reduce, compression to 16 bits (fp16_compress_hook: 6,373,888 bytes per step instead of 12,747,776, gradient error 2.8e-4) and PowerSGD (Vogels et al. 2019, arXiv 1905.13727), which replaces each gradient matrix by a rank-r product P QT and all-reduces only P and Q (327,344 bytes at rank 4, 39 times fewer), keeping what it dropped as error feedback for the next step. Fewer bytes is not a faster step on NVLink, where 12.75 MB is cheap and PowerSGD's extra matrix work may cost more than it saves; the paper reports its gains on slower networks.
The running example trained for 30 steps under DDP with each hook, from the same weights on the same batches: src/exp/ddp_more.py hooks, one clean torchrun launch per hook (run_hooks.sh). Bytes are the flight recorder's input bytes of every collective of the step's backward. The "exact" gradient is each step's local gradients (computed under no_sync) all-reduced on a separate process group, so the error isolates the hook. PowerSGD uses start_powerSGD_iter=2 (its default is 1,000 plain all-reduce steps first, powerSGD_hook.py L184), so steps 0 and 1 are plain all-reduces. allreduce_hook divides by the world size then all-reduces (default_hooks.py L18). Measured, deterministic (no timing).
Relative error = |hook's averaged gradient − exact average| / |exact average|.
PowerSGD views each gradient as a matrix n × m and sends P (n × r) and Q (m × r) instead, but only when that saves at least a factor min_compression_rate (default 2): (n + m) r × 2 < n m. One-dimensional gradients (biases, LayerNorm) and matrices that fail the test go uncompressed (powerSGD_hook.py L79-104). For the running example's 52 parameter tensors:
bf16_compress_hook refuses gloo: Use fp16 compression on CPU, bf16 on NCCL.batched_powerSGD_hook is broken at 2.14.1 on any backend. It ran the two plain warm-up steps, then failed at its first compressed step with a bare AssertionError: it passes a 2-D matrix to _orthogonalize, which asserts a 3-D batch (L24-26, called from L808).EnforceNotMet ... op.nread == op.preamble.nbytes: a message of the wrong size arrived), for ranks 1 and 4, while rank 16 and rank 4 without error feedback finished. Logging every all-reduce the hook issues showed why: two thirds are issued from future callbacks on another thread, not the main thread, and at step 16 the ranks issued them in different orders: Collectives must be issued in the same order on every rank (the rule of section 11); a hook that issues them from callbacks can break it whenever timing differs. On 2 processes it did not happen in 180 steps. Not checked on NCCL.What transfers to GPUs: the bytes and the errors, exactly (they depend on shapes and arithmetic, not the backend), except that NCCL also accepts the bf16 hook. What does not: whether fewer bytes means a faster step.
The running example wrapped with one extra Linear that forward skips:
Measured, 2 CPU processes, gloo. The 216-byte all-reduce is the used-parameter bitmap, so every rank learns which parameters some rank used. find_unused_parameters=True also turns off the single-bucket first step (the size caps apply from step 0); its extra cost is the graph traversal plus the bitmap, so leaving it on "to be safe" costs every step. static_graph=True's two broadcasts in step 2 are the bucket rebuild: 3 collectives per step with find_unused_parameters; 2, 1, then 4 in the first three steps with static_graph. When a parameter is used on one rank only, every rank still ends with the same averaged gradient for it (checked on both ranks: neither left it empty).
Uneven inputs: Join. If rank 0 has 5 batches and rank 1 has 3, rank 0's fourth backward waits for a partner that has left the loop. Recorded: without help, both ranks failed with gloo's receive timeout after seconds (the script's 10 s timeout). The Join context manager (torch.distributed.algorithms.join) fixes it: each iteration starts with a 4-byte all-reduce counting the ranks still training, and a rank that has run out "shadows" the others' all-reduces with zeros until all are done. Recorded:
Two neighbours. gradient_as_bucket_view=True makes each .grad a view into its bucket instead of a copy (the parent lab measured it on this model: no change in peak, because the peak comes at the start of backward). Under torch.compile, DDP splits the compiled graph at bucket boundaries so the all-reduces still overlap (DDPOptimizer: 2, 4 and 13 graphs for 25, 4 and 1 MB buckets on the running example), measured on the torch.compile child.
FSDP2 (torch.distributed.fsdp.fully_shard) is PyTorch's ZeRO stage 3 (the form is on Distributed Training, section 4): each rank keeps 1/n of every parameter, gradient and optimizer state, gathers a unit's full weights just before using them and reduce-scatters its gradients. You call fully_shard on each block, then on the whole model; each call makes one unit. What it does to a module is concrete:
Shard(0): on 4 ranks block 0's mlp.fc.weight [1024, 256] is [256, 256] per rank;FSDPModule (checked: GPT becomes FSDPGPT, bases FSDPModule then GPT; each Block becomes FSDPBlock), so model.unshard(), reshard() and set_requires_gradient_sync() exist;Fig. 3, step by step: one training step on 4 ranks, rank 0's recording
Rank 0's step in issue order: 9 all-gathers (28,160 bytes in for the root, 789,760 per block) and 5 reductions (3,159,040 bytes per block, 112,640 for the root). The parent's Distributed lab tab animates this step against DDP's. Measured, 4 CPU processes, step 1. Sizes on the stage are not to scale.
By default FSDP2 prefetches implicitly: while block i runs forward it has already issued block i + 1's all-gather; in backward, the next block's. block.set_modules_to_forward_prefetch([...]) and set_modules_to_backward_prefetch([...]) name the modules explicitly, here two ahead.
Measured, 2 CPU processes, step 2: bars are each block's forward and backward on rank 0, diamonds the all-gathers and gradient reductions as issued. Gloo on one thread does not overlap communication with compute the way NCCL streams do, so read the order, not the gaps.
Measured, 2 CPU processes, step 1. param_dtype=bfloat16 casts each gathered weight, so the all-gathers carry half the bytes and forward and backward compute in bfloat16; the sharded master weights and AdamW stay float32 (persistent state is the same in all three rows). reduce_dtype sets the gradient reduction. torchtitan's default is exactly the middle row: bfloat16 parameters, float32 reductions (torchtitan 0.3.0 config/configs.py L85 and L93). On this M1 Pro CPU, bfloat16 matrix multiplication has no hardware support (FACTS fst: 2.1 GFLOP/s), so these rows are for bytes and dtypes, not speed.
Pass a 2-D mesh, fully_shard(m, mesh=init_device_mesh("cpu", (2, 2), mesh_dim_names=("replicate", "shard"))), and every parameter is placed (Replicate(), Shard(0)): sharded over the 2 ranks of its row, copied in the other row. Per step on 4 processes: all-gathers and gradient reductions within the shard group, plus one all-reduce per unit across the replicate group, 19 collectives in all against FSDP's 14, for half the sharding (6,374,400 bytes of weights per rank against 3,187,200). Losses were identical to FSDP2 and DDP on 4 processes (3.801371, 3.171438, 3.121909). Pick it when one node's worth of shards holds the model: the per-layer all-gathers stay on the node's fast links and only one gradient all-reduce per unit crosses the network. The Mesh explorer shows every rank's groups, shards and collectives.
Gradient accumulation. model.set_requires_gradient_sync(False) is FSDP2's no_sync: over 4 micro-batches it removed reductions only (20 to 5); each micro-batch still gathered the weights (36 all-gathers either way), because its forward and backward need them.
reshard_after_forward as an integer. After a block's forward, FSDP2 can free the gathered weights (True, gather again in backward), keep them (False, no second gather, more memory), or, given an integer k, keep them sharded over k ranks only. On 4 processes with reshard_after_forward=2, FSDP2 built a second mesh : forward all-gathers run over all 4 ranks (789,760 bytes in per block), backward all-gathers only within the pair (1,579,520 bytes in, from the pair's half). The step's peak above persistent state rose from 43.9 MB to 48.6 MB. On GPUs, make the pair the 8 GPUs of one server, so the backward gather never crosses the slower network.
Accumulation, measured (4 micro-batches, 2 processes): set_reshard_after_backward(False) keeps weights gathered between micro-batches at the cost of memory (not run here).
offload_policy=CPUOffloadPolicy() ran here (losses , the same as plain FSDP2), but means nothing on a CPU: on a GPU it keeps the sharded parameters, gradients and optimizer state in host memory and runs the optimizer step on the CPU. Not measured on a GPU.model.state_dict() issued ; get_model_state_dict(model, options=StateDictOptions(full_state_dict=True, cpu_offload=True)) issued all-gathers to build full tensors. Save with DCP (section 9) and you never pay the second.reshard(). Recorded in the DCP run: were not DTensors after an evaluation forward. Call model.reshard() after evaluation if code downstream expects shards.Measured, 2 CPU processes. FSDP1 still runs at 2.14.1 and printed no deprecation warning; the parent page's correction stands (no formal deprecation notice at 2.14, Ecosystem map tab).
A DTensor (torch.distributed.tensor) is one logical tensor spread over a DeviceMesh, with one placement per mesh dimension: Shard(d) (split along tensor dimension d), Replicate() (every rank has all of it) or Partial() (every rank has a full-shape tensor and the true value is their sum). FSDP2, tensor parallel and DCP are all built on it.
Fig. 4, step by step: one matrix on a mesh of 2 ranks, as run here
A is 4 × 6; the mesh is one dimension of 2 ranks. A placement says what each rank stores of it.Shard(0): rows split. Rank 0 keeps rows 0 and 1, rank 1 rows 2 and 3: local shape (2, 6), half the memory each.Replicate(): all of it, everywhere. Both ranks hold the full 4 × 6.Partial(): full shape, values sum. Each rank holds a full-shape 4 × 6 whose values are only part of A; the true tensor is the sum of the two, not yet taken.A split by columns (4 × 3 per rank) times B (6 × 8) split by rows (3 × 8 per rank) leaves each rank a full-shape (4, 8) partial product: S(1) x S(0) → P, no communication.Replicate and only then applies relu on each rank.2 ranks, A 4 × 6 and B 6 × 8 as run here; collectives as CommDebugMode counted them, every result checked against plain tensors. The relu rule was recorded on a Partial A (one all-reduce, output R); step 6 applies the same rule to the product. Measured, 2 CPU processes.
How it decides. DTensor is a tensor subclass (built as the Extending PyTorch child describes, with a C++ fast path). For every ATen operation it asks the sharding propagator: given the inputs' placements, which output placement can be computed locally, and if none, which inputs must be redistributed first? Each operation registers a strategy, a list of (output placements, required input placements) pairs; DTensor picks the cheapest, runs any redistribution (a collective), then runs the plain operation on the local pieces. Four rules fall out of 28 recorded cases, and they are most of tensor parallelism:
S(1) x S(0) → P; Partial + Partial and 2 × Partial stay Partial.relu(Partial) forced an all-reduce first. This is why Megatron's MLP puts the GeLU between a column split and a row split.MaskPartial: each rank looks up the ids it owns, writes zeros elsewhere, and the sum is pending. That is vocabulary-parallel embedding.Moving between placements is redistribute, one collective per change (Shard to Replicate is an all-gather, Partial to Replicate an all-reduce, Partial to Shard a reduce-scatter); the parent lab's redistribution explorer (Distributed lab tab, section 7) has every pair. Wrapping existing tensors is DTensor.from_local(t, mesh, [Shard(0)]), which declares that the ranks' local tensors together form one DTensor and moves no data; to_local() returns the local piece without copying.
Measured, 2 CPU processes. S(d) = Shard(d), R = Replicate, P = Partial(sum).
from_local, recorded: Two traps: with uneven pieces, the global shape must be given (shape= and stride=), and the pieces must follow torch.chunk's split (3 rows over 2 ranks is 2 and 1, recorded ). A first attempt here declared pieces of 3 and 1 rows with shape=(4, 2); full_tensor() then all-gathered pieces of the wrong size and gloo aborted both processes.
A custom operator needs a strategy. An operator DTensor does not know raises at once. Recorded for a small torch.library op dpt::rowscale(x, s) = x * s[:, None]: Registering a strategy fixes it:
from torch.distributed.tensor.experimental import register_sharding
@register_sharding(torch.ops.dpt.rowscale.default)
def rowscale_strategy(x, s):
# (output placements, input placements) pairs DTensor may choose from
return [([Shard(0)], [Shard(0), Shard(0)]), # rows split: each rank scales its own rows
([Replicate()], [Replicate(), Replicate()]),
([Shard(1)], [Shard(1), Replicate()])] # columns split: needs all of s
The fourth line asked for x by columns and s by rows; no strategy matches, so DTensor redistributed s to Replicate with one all-gather and picked the third strategy. Measured, 2 CPU processes.
Tensor parallelism (TP) splits the weight matrices inside a layer across ranks that all see the same batch (the Megatron split and its maths: Distributed Training, section 5, and the Megatron-LM paper page). PyTorch's API is parallelize_module(module, mesh, plan), where the plan maps submodule names to styles: ColwiseParallel (shard the weight's output dimension: each rank computes some output features), RowwiseParallel (shard the input dimension: each rank produces a Partial sum, then an all-reduce), SequenceParallel and PrepareModuleInput (convert a module's inputs between placements). Each style turns the module's parameters into DTensors and installs hooks that convert inputs and outputs.
Making attention splittable. The running example fuses q, k and v into one qkv projection, which cannot be column-split blindly (the parent lab found rank 0 got all of q and half of k); torchtitan's models use separate wq, wk, wv. Here each block's attention was swapped at run time for an equivalent module with separate q, k, v built from the same weights, whose forward uses as many heads as its local shard holds (src/exp/dpt_parts.py; the model file is unchanged). With 2 ranks each holds 2 of the 4 heads; losses equal one process at every step (3.801371, 3.187931, 3.167831) and gradients agree to 2.1e-6.
The plan decides the communication: 24 all-reduces or 16. Colwise on q, k and v separately means each wraps the same input in its own DTensor, and in backward each sends its own input-gradient all-reduce: 3 per attention instead of 1. Wrapping the attention input once ("attn": PrepareModuleInput(input_layouts=Replicate(), desired_input_layouts=Replicate(), use_local_output=False)) makes q, k and v share one DTensor input, whose gradients add up locally before a single all-reduce. Recorded per step: 24 all-reduces of 524,288 bytes with the first plan, 16 with the second (8 in forward: one after each attention and MLP of 4 blocks; 8 in backward). Same losses, same gradients, one third less communication.
Each lane is one rank's activation for one block's forward, the 64 tokens drawn as 8 tiles of 8; dark = rows it holds, gold = a Partial sum not yet reduced, light = just gathered. Placements and local shapes at each module boundary are the recorded ones (ln1 input local shape (8, 64, 256) under TP, (8, 32, 256) under TP + SP); counters are per training step of the whole model (4 blocks, forward and backward), from the flight recorder. Measured, 2 CPU processes, gloo.
Under TP, everything between the matrix multiplies (LayerNorms, the residual stream, dropout) runs on the full activation on every rank. Sequence parallelism (Korthikanti et al. 2022, arXiv 2205.05198) splits those along the sequence instead, which is free because they work token by token: each all-reduce becomes a reduce-scatter (each rank keeps its half of the tokens, summed) followed later by an all-gather (rebuild the full sequence before the next matrix multiply). In the plan, the LayerNorms get SequenceParallel(), the row-wise projections output Shard(1) (the sequence dimension), and PrepareModuleInput gathers the attention's and the MLP's inputs back to Replicate() (src/exp/tp_sp.py). The same block, before and after, recorded on 2 processes:
The animation, step by step: one block's forward on 2 ranks
ln1 input, local shape (8, 64, 256), a plain tensor). The same numbers sit in two memories.proj: a full-shape (8, 64, 256) result that is only part of the sum.ln1 input: S(1), local shape (8, 32, 256)). Half the memory.What the recording says: the all-reduces become pairs of all-gathers (262,144 bytes in per rank: half the activation) and reduce-scatters (gloo runs them as all-reduces of the full 524,288 bytes; NCCL would move half). In ring terms the bytes per step are about the same as TP's (34 halves of 262,144 bytes, 8.9 MB, against 16 all-reduces costing 524,288 bytes each on 2 ranks, 8.4 MB), because an all-reduce is a reduce-scatter plus an all-gather; the gain is memory and work. Saved activations per rank fell from 22.17 MB to 20.06 MB here (one process: 47.41 MB): small, because on this model the LayerNorm and residual activations are a small part of what is saved. On long sequences and many layers it is the saving that makes TP + SP + selective recomputation fit (Korthikanti et al., Table 2; on Distributed Training, section 5).
SequenceParallel makes the weight a Replicate DTensor, and DTensor reduces its Partial gradient for you: the gradients matched one process to 1.7e-6. Under plain TP the LayerNorm saw all tokens on every rank and no reduction was needed.At long context the activations of attention grow with the sequence and can outgrow one GPU on their own, so context parallelism (CP) splits the sequence inside attention too: each rank keeps the queries of its own tokens and the keys and values travel, by ring passes or one all-gather, with partial outputs merged by their log-sum-exp (the form, its three traffic patterns and the causal load balancing: Distributed Training, section 8; the online softmax it reuses: FlashAttention paper page). PyTorch's API is a context manager that shards the named buffers along their sequence dimension and swaps the attention kernel for a ring version (with a causal mask it also reorders the tokens so that rank 0 gets the first and last chunk, balancing the work): with context_parallel(mesh, buffers=[q, k, v], buffer_seq_dims=[2, 2, 2]): F.scaled_dot_product_attention(...). Run here on the real q, k and v of the running example's block 0 (8 × 4 heads × 64 tokens × 64), split over 2 and 4 processes:
_templated_ring_attention) called with the CPU flash kernel, load balancing off, matched full attention on every rank's tokens to . With the default rotation the "ring" is one all-gather of each rank's K and V (); with set_rotate_method("alltoall") it is n − 1 exchanges ().arange(T) of the local length, so each rank would count its tokens from 0; torchtitan passes positions in. torchtitan applies CP to every attention module before TP and FSDP (models/llama3/parallelize.py L46-51, 0.3.0) and folds the cp axis into the FSDP mesh, because ranks that split one sequence still need their weight gradients summed (distributed/parallel_dims.py, docstring of build_mesh). Not run on the whole model here.torch.distributed.pipelining gives each rank a contiguous run of layers (a stage, PipelineStage(module, stage_index, num_stages, device)), cuts the batch into micro-batches and streams them through: forward activations go to the next stage by send/recv, their gradients come back. A schedule object (Schedule1F1B(stage, n_microbatches, loss_fn), then schedule.step(x, target=y)) decides each rank's order of forward (F) and backward (B) work. The idle fill and drain, the bubble, is (p − 1)/(m + p − 1) of the step for p equal stages and m micro-batches (derived on Distributed Training, section 6). At 2.14.1 the library has seven schedules, and all seven ran here:
What the schedules change. 1F1B runs a backward as soon as one is possible, so a stage holds at most p micro-batches of activations instead of m (memory, not bubble). Interleaved 1F1B gives each rank v stages spread along the model (rank 0 holds stages 0 and 2), which divides the fill and drain by v at the price of v times more send/recv. Zero-bubble schedules (Qi et al. 2023, arXiv 2401.10241) split each backward into the input gradient (I, needed by the previous stage now) and the weight gradient (W, needed only by the optimizer), and slot the Ws into what would have been idle time. The V layouts (ZBVZeroBubble, DualPipeV from DeepSeek-V3) give rank 0 the first and the last stage, so the pipeline turns round on the same rank. Measured: ZBVZeroBubble idled 0.08 and 0.07 of the step at m = 4 against 1F1B's 0.19 and 0.10.
The explorer on the right is a replay you drive: pick a schedule, compare it with another, and press play or drag the time line; it opens on the whole step and never plays by itself.
The 8-block, dmodel 512 variant of the running example (25.3M parameters, so that compute outweighs Python overhead), cut into 2 stages (GPipe, 1F1B) or 4 (two per rank), batch 8 × 64 in 4 or 8 micro-batches, 2 CPU processes (4 for GPipe and 1F1B at 8 micro-batches). Every F, B, I and W action was timed by wrapping the stage's methods; the median of 5 timed steps is drawn. The ideal clock replays each rank's recorded order with F = 1, B = 2, I = 1, W = 1 units and no communication, respecting what each action waits for: the schedule's own bubble, apart from this machine's noise. Measured on Apple M1 Pro, CPU, gloo, under the bench lock.
Bubble = 1 − (time in compute actions) / (step time), per rank; formula column with p = 2 ranks. Every schedule's gradients matched one process (largest difference 1.3e-7 on the untied parameters).
scale_grads, stage.py L857-869), and a parameter in two stages is divided twice, once after part of its gradient has arrived. Recorded: the tied gradient came out 0.37 of the right one, with no error. Loop-style schedules put the two copies on different ranks, where a manual all-reduce of the two copies fixes them (largest difference 1.6e-7 over these runs; 1.5e-7 in the parent lab). Untie the weights, or pass scale_grads=False and divide once yourself.DCP (torch.distributed.checkpoint) has every rank write its own shards plus one .metadata file mapping every piece of every tensor to its offsets, so a checkpoint loads into any other layout and nothing is ever gathered on one rank. dcp.save(state, checkpoint_id=dir) and dcp.load(state, checkpoint_id=dir) take the state dict of DTensors that FSDP2 and TP already hold; the parent lab saved from 4 FSDP2 ranks and loaded into 2 and into 1.
Fig. 5, step by step: saved from 4 FSDP2 ranks, read back two ways
dcp.save: every rank writes its own file. Four .distcp files of about 9.8 MB each (model and AdamW state), written in parallel, nothing gathered; one .metadata of 144,171 bytes maps every piece of every tensor to its file and offsets.dcp.load into another layout. A 2 × 2 HSDP model (placements (Replicate(), Shard(0)), local block weight 512 × 256 instead of 256 × 256) asks for its pieces; the map says which files hold them, and each rank reads only those. Largest parameter difference 0.0; the next step's loss was identical on both layouts (3.0912256).dcp_to_torch_save turned the directory into one 38,343,430-byte .pt with no process group.File heights are to scale by bytes; the .pt has four times a shard file's footprint, so its volume is to scale. Which file each HSDP rank reads is drawn from the layout (rows 0 to 511 of a block weight are FSDP ranks 0 and 1's quarters); DCP's planner reads them through the map. Measured, 4 CPU processes.
Async save needs its own process group. dcp.async_save(state, checkpoint_id=...) copies the state to CPU memory, returns a future and writes in a background thread, so training continues; its planning uses collectives. On the default group, while the next forward and backward issued FSDP2's collectives, gloo aborted two of the four processes: two threads issuing collectives on one group in different orders (section 11's rule). With process_group=dist.new_group(backend="gloo"), as torchtitan does (components/checkpointer/dcp.py L189, 0.3.0), it worked:
dcp_to_torch_save(dcp_dir, "single.pt") wrote ; torch_save_to_dcp goes back.dcp.save(state, storage_writer=HuggingFaceStorageWriter(path, save_distributed=True, enable_consolidation=True)) refused the running example: safetensors will not store two names for one tensor, and the tied tok.weight/head.weight are one. Dropping head.weight (how Hugging Face stores tied embeddings) worked: File formats themselves are on Local and on-device inference, section 3.Real jobs combine several of these on one mesh. torchtitan (PyTorch's reference trainer; release 0.3.0 read here) does it in a fixed order, and the order is the lesson:
["pp", "dp_replicate", "fsdp", "tp"] unflattened from one world mesh (distributed/parallel_dims.py, build_mesh). Ranks next to each other share a server, so the chattiest axis (TP: collectives in every layer) gets the fastest links and the quietest (PP: point-to-point once per micro-batch) spans servers.distributed/pipeline_parallel.py pipeline_llm, L65-125).torch.compile per block, then FSDP2 last (models/llama3/parallelize.py L42-94). FSDP2 goes last because it shards whatever DTensors TP produced along one more mesh dimension; compile goes before it so each block compiles once.to_empty, init_weights), and the schedule (1F1B by default, config/configs.py L210) drives training.Run here on 8 processes with the running example in that order: two stages of 2 blocks, TP on each block (the 16-all-reduce plan of section 6), fully_shard over the dp axis, Schedule1F1B with 4 micro-batches, and one all-reduce over the pp axis for the tied embedding and head, which now live on different stages. Each rank held about 1.6 MB of the 12.75 MB of weights, and every rank's gradients matched one process on the same 16 sequences to 1.8e-7. The dp reductions happen once per step, not per micro-batch: the pipeline asks FSDP2 to reduce only after the last micro-batch. The Mesh explorer has this layout rank by rank.
Block 0's mlp.fc.weight on rank 0 of the 8-process run (pp 2 × dp 2 × tp 2), drawn to scale: [1024, 256] in the model, [512, 256] after ColwiseParallel, [256, 256] after fully_shard. Its placements on the (dp, tp) mesh were : sharded on dimension 0 by TP and again, "strided", by FSDP (_StridedShard), so that each rank's rows are the right ones of TP's shard. Measured, 8 CPU processes, gloo.
Measured, 8 CPU processes, gloo, one step. The reference is one process on the same 16 sequences (dp rank d trains on batch d; the two tp ranks of a replica share it). Each rank's collectives by mesh axis:
torchtitan's own trainer, run on this CPU with four patches (it imports Triton unconditionally, picks a CUDA-like device, uses FlexAttention, and sets FSDP2's gradient divide factor to 1 which needs a reduce op gloo lacks), and its defaults that change results, are on the Libraries on top of PyTorch child; so is DeepSpeed ZeRO against FSDP2, run there on CPU. Launching such a job on a cluster: Launching distributed training.
The rule behind every hang: all ranks of a group must call the same collectives, in the same order, with matching sizes. A collective completes only when every member calls it, so one rank that skips one, calls a different one, or dies leaves the rest waiting until the timeout (10 minutes for NCCL, 30 for other backends by default at 2.14.1). The parent lab caused three hangs on purpose; this page met the rule three more times without trying: PowerSGD's callbacks (section 3), async_save on the default group (section 9) and a from_local with wrongly sized pieces (section 5).
Every process group keeps a ring buffer of its recent collectives (TORCH_FR_BUFFER_SIZE entries: name, sizes, dtypes, sequence number, stack). On NCCL, TORCH_NCCL_DUMP_ON_TIMEOUT=1 makes the watchdog write one file per rank when a collective times out, and torchfrtrace <dir> (shipped with PyTorch as torch.distributed.flight_recorder.fr_trace) lines the ranks up and names the first mismatch. From PyTorch 2.15 the recorder is backend-agnostic and each watchdog publishes its health to the debug server, so a timeout on any rank triggers dumps from every rank, the ranks that were waiting included, not only from the one that timed out. So for a 512-GPU job that hangs: find the first sequence number where ranks disagree on the operation or its sizes, or where a rank is missing, then read that rank's stack. torchrun sets TORCH_NCCL_ASYNC_ERROR_HANDLING=1 for its workers, which makes the NCCL watchdog abort the process on a timeout instead of leaving it hung.
The parent lab's "skipped all-reduce", dumped from both ranks and lined up by torchfrtrace: collectives 1 to 3 (all-reduces) agree; at sequence number 4 rank 0 called an all_reduce that only rank 0 runs (a logging all-reduce under if rank == 0) while rank 1 went on to barrier: COLLECTIVE_TYPE_MISMATCH, culprit rank 0, with the stack naming the line. Measured, 2 CPU processes, gloo, torch 2.14.1.
| Tool, in the order to reach for it | What it catches | Cost | Where measured |
|---|---|---|---|
Flight recorder dump + torchfrtrace | which rank is at which collective; type and size mismatches | a ring buffer per group | here, and the parent lab section 11 |
TORCH_DISTRIBUTED_DEBUG=DETAIL | shape and type mismatches before they hang, with both shapes in the error | 2 extra all-gathers per collective | parent lab section 11 |
monitored_barrier() (gloo) | which rank did not arrive | one barrier | parent lab section 11 |
py-spy dump --pid on the odd rank | what its Python is doing instead | none | not run here |
NCCL_DEBUG=INFO, NCCL_DEBUG_SUBSYS | NCCL's choice of rings, trees, transports and network cards | log volume | not run here (no NCCL); see Streams, CUDA graphs and multi-GPU and NCCL environment variables |
Hangs on a real cluster (rendezvous, NCCL environment, network), and a TORCH_DISTRIBUTED_DEBUG=DETAIL run that segfaulted inside DDP's constructor on torch 2.14.1, are on Launching distributed training, section 8.
The dump was taken by hand on gloo (torch._C._distributed_c10d._dump_fr_trace). As dumped, the analyser crashed (): gloo leaves the dump's process-group table empty; NCCL fills it when it creates a communicator, and the analyser looks every entry's group up there. With the default group written into the table, as NCCL would have, it found the bug at once:
Paths in the stack are shortened.
The nccl backend name selects a rewritten backend. Ported from torchcomms and offered in 2.14 as the opt-in nccl2, it backs every nccl process group by default in 2.15; TORCH_DIST_USE_NCCL2=0 or the backend name nccl-legacy restores the old ProcessGroupNCCL. Communicators are created eagerly with the process group, and reconfiguring a group can opt into a shrink and grow fast path (NCCL 2.29 or newer) so surviving ranks skip a full bootstrap. The all-rank flight-recorder dumps above arrived with it.
One-sided transports. torch.distributed gained a Python transport API for one-sided reads and writes, with NIXL as the first backend: a transport connects to a peer through a store, with no process group or collective, and Transport.read_stream and write_stream enqueue transfers on a CUDA stream, so they can be captured in a CUDA graph.
All three are marked API Unstable in the PyTorch 2.15 release blog. Every measurement on this page was taken on torch 2.14.1 with gloo, so none of this was run here.
| On this page | On NCCL and GPUs | |
|---|---|---|
| Carries over | which collectives, in which order, with which sizes; bucket layouts; placements and shard shapes; propagation rules; schedules' action orders; losses and gradients | the same: all of it is Python and C++ above the backend |
| Carries over in kind | memory per rank (float32, CPU allocator) | halved by bf16, plus the caching allocator and NCCL buffers (Memory allocators) |
| Changes | reduce-scatter runs as an all-reduce (gloo has none) | a real reduce-scatter: half the bytes, no full-size temporary |
| Changes | bf16 compression hook refused; context parallel's public API refused | both supported |
| Changes | collectives and compute share one CPU thread | collectives run on their own CUDA streams and overlap with compute |
| Does not carry | every time: collective latency (0.09 to 1.1 ms for small messages), bubbles, async save | NVLink and InfiniBand are orders of magnitude faster; GPU compute is too, so bubbles and overlap must be measured there |
| May not carry | gloo aborts from out-of-order collectives (PowerSGD, async_save) | the ordering rule is the same; whether timing exposes it differs. Not checked |
init_process_group() with no backend on a machine with an accelerator: c10d picked "mps:gloo" here and every CPU collective failed (section 1, depth).find_unused_parameters=True on "to be safe": a graph walk and a bitmap all-reduce every step (section 3).ColwiseParallel styles on q, k, v and nothing else: 24 all-reduces instead of 16 (section 6).dcp.async_save on the default process group, or any collectives issued from callbacks and threads: ranks issue them in different orders and the job aborts (sections 3 and 9).from_local with uneven pieces and no shape: a wrong global shape, then an abort at full_tensor() (section 5).reshard() (section 4).Six ways of laying the running example over 4 or 8 processes, each run for real: pick a layout, click a rank, and see the groups it belongs to, the piece of each parameter it holds, every collective it issued in one training step, and its memory.
Recorded with src/exp/fsdp_more.py (DDP, FSDP2, HSDP, reshard_after_forward=2), fsdp_tp.py and compose3d.py; CPU processes, gloo, torch 2.14.1, Apple M1 Pro. Collectives are step 1's (step 0 for the 8-process run, which records one step), as the flight recorder saw them, grouped by the mesh dimension of their process group. On gloo a gradient reduce-scatter appears as an all-reduce of the whole tensor (Reading tab, section 2). Measured, deterministic. Theory of each layout: Distributed Training.