Distributed PyTorch: c10d, DDP, FSDP2, DTensor, TP, PP, DCP

What each of PyTorch's distributed APIs makes every process hold and which collectives it calls, measured on the topic's running example: launch and process groups, collectives, DDP, FSDP2, DTensor, tensor and sequence parallel, context parallel, pipelining, distributed checkpoints, composing them, debugging. CPU processes on gloo, torch 2.14.1, Apple M1 Pro; GPU figures quoted and labelled. Data as of October 2026. Reading: 35 min, plus 20 in closed details.

The idea in one screen

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

  1. One model, one process. The topic's running example: embeddings, 4 blocks and the output layer, 3,186,944 parameters, 12,747,776 bytes of float32 weights. Each slab is one of those parts.
  2. DDP, 4 ranks. The whole model on each, different data; 2 all-reduces per step (1,051,648 and 11,696,128 bytes) average the gradients, drawn as dots running round all four ranks; 12,747,776 B of weights per rank.
  3. FSDP2, 4 ranks. 1/4 of every parameter, gradient and optimizer state; gathered whole just before use (here block 1, its pieces flowing from every rank) and freed after; 14 collectives: 9 all-gathers, 5 gradient reductions; 3,187,200 B of weights per rank.
  4. Tensor parallel, 2 ranks. Half of each attention and MLP matrix, the same data; the embeddings and output layer stay whole. 16 all-reduces of 524,288 B per step, one pair of dots per block.
  5. Pipeline, 2 stages. Half the blocks each; activations forward and their gradients back by send/recv, once per micro-batch; idle 10 to 21% of the step (measured bubble, from the 8-block variant of section 8).

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.

Rank, world size
a process's index, and how many there are.
Process group, backend
a set of ranks that run collectives together, and the library that moves the bytes (NCCL on NVIDIA GPUs, gloo on CPUs).
DeviceMesh
the ranks laid out as an n-dimensional grid, one process group per row of each dimension.
DTensor, placement
one logical tensor spread over a mesh; per mesh dimension it is Shard(d), Replicate() or Partial() (a pending sum).
Bucket, unit
DDP's group of gradients all-reduced together; FSDP2's group of parameters gathered together (one per fully_shard call).
Stage, schedule
a pipeline's run of layers on one rank, and the order in which ranks run micro-batches' forwards and backwards.
Every layout run here in one table (1 min)
APIWhat each process holdsCollectives in one step of the running example (measured)Per processSection
DDPthe whole model, different data2 all-reduces from step 1 on, 1 in step 012,747,776 B of weights, 25.5 MB of AdamW state3
FSDP2, 4 processes1/4 of every parameter, its gradient and its optimizer state14: 9 all-gathers, 5 gradient reductions3,187,200 B of weights4
HSDP, 2 × 21/2 of every parameter, copied in two replicas19: 9 all-gathers and 5 reductions in the shard group, 5 all-reduces in the replica group6,374,400 B4, Mesh explorer
TP, 2 processeshalf of each attention and MLP matrix, the same data16 all-reduces of 524,288 B (24 with a careless plan)saved activations 22.17 MB (one process: 47.41 MB)6
TP + sequence parallelas TP, plus half the sequence between the matrices18 all-gathers of 262,144 B, 16 reduce-scatterssaved activations 20.06 MB6
Context parallelhalf the sequence inside attention1 all-gather of K and V, or 1 pass per other processK and V of its own tokens7
Pipelining, 2 stageshalf the layerssend/recv of activations and their gradientsidle 10 to 21% of the step8
PP × FSDP × TP, 8 processes1/8 of the weightsTP all-reduces, FSDP all-gathers and reductions, one pp all-reduce for the tied embeddingabout 1.6 MB of 12.75 MB of weights10

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.

1. Launch, process groups and the store (c10d)

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.

torchrun starts the workers and names them; the store introduces them; a mesh cuts them into groups

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.

Elastic restarts

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.

A restart reruns every worker from the top; the checkpoint makes it continue where it stopped

Events from both ranks of one run (2 processes, --max-restarts 2, the script checkpoints after every step). Measured, 2 CPU processes.

Depth: what torchrun sets, the store's prefixes, the backend trap on a Mac, flaky restarts (3 min)

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 .

Found on this Mac: name the backend
Name the backend ("gloo", "nccl") or a device map such as "cpu:gloo,cuda:nccl".

torchrun's own log of the restart, host and process ids removed:

Restarts on this machine were flaky
The 20-second timeout is the script's own (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).

2. Collectives: what each one leaves on every rank, and what it costs

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.

Cost per call: a fixed latency, then bytes over bandwidth

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.

Predict: at 64 MiB on 2 processes, which is fastest: all-reduce, all-gather, or broadcast?

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

Up to about 256 KiB every collective costs only its latency; past a few hundred KiB, time grows with the bytes

Depth: reading these against a GPU cluster (1 min)

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.

3. DDP: buckets that all-reduce while backward runs

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

  1. Backward starts at the loss. From step 1 on there are two buckets, rebuilt in the order the gradients arrived in step 0: 1,051,648 bytes (ln_f and block 3's mlp.proj: 4 tensors) and 11,696,128 bytes (the other 48).
  2. Bucket 0 is full: its all-reduce leaves at once. At 1.00 ms its 1,051,648 bytes go between the ranks while backward continues into block 3.
  3. Block 3 done, 4.65 ms. Bucket 1 is 18% full; bucket 0's all-reduce is already under way.
  4. Block 2 done, 8.80 ms. Each block adds 3,159,040 bytes of gradients; bucket 1 is 45% full.
  5. Block 1 done, 12.97 ms. Block 0 and the embeddings remain; 72% full.
  6. The last gradient arrives: bucket 1 leaves. tok.weight is ready at 17.23 ms; its bucket's all-reduce of 11,696,128 bytes is issued at 17.25 ms. Only this bucket waits for the end of backward.
  7. backward() returns, 30.94 ms. On NCCL the 1 MB all-reduce would run on its own CUDA stream under block 3 to 0's backward; on gloo with one thread per process the overlap is limited, so read the order, not the gaps.

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)
Predict: after buckets are rebuilt, how many collectives do 4 micro-batches issue with and without no_sync?

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.

Depth: the comm-hook lab, 30 steps per hook, PowerSGD's byte formula, and three hooks that broke (6 min)

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

Bytes sent per step per rank

Relative gradient error per step

Loss per step

Relative error = |hook's averaged gradient − exact average| / |exact average|.

Predict PowerSGD's bytes

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:

Three hooks that broke, and why they matter beyond this laptop
  • 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).
  • PowerSGD on 4 gloo processes crashed the job (gloo 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.

Depth: unused parameters and Join measured, gradient views, DDP under torch.compile (3 min)

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.

4. FSDP2: fully_shard, one unit gathered at a time

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:

  • every parameter becomes a DTensor (section 5) with placement Shard(0): on 4 ranks block 0's mlp.fc.weight [1024, 256] is [256, 256] per rank;
  • the module's class is swapped for a subclass that also inherits FSDPModule (checked: GPT becomes FSDPGPT, bases FSDPModule then GPT; each Block becomes FSDPBlock), so model.unshard(), reshard() and set_requires_gradient_sync() exist;
  • forward pre/post hooks and autograd hooks schedule the gathers and reductions (how they sit on the tensor-subclass machinery: Extending PyTorch).

Fig. 3, step by step: one training step on 4 ranks, rank 0's recording

  1. At rest, every rank holds a quarter. Each of the 5 units (the root: embeddings, final LayerNorm and the tied head; then blocks 0 to 3) is cut into 4 row shards, one per rank: 3,187,200 B of weights and 6,374,608 B of AdamW state per rank, against DDP's 12,747,776 and 25,495,760.
  2. The root unit is gathered, and kept. Its all-gather brings 28,160 bytes in per rank. It is not freed after forward, because backward needs it first.
  3. Block 0: gathered just before its forward, freed after. Each rank sends its quarter to the others (789,760 bytes in per rank), runs the block on the whole weights, then drops the three borrowed quarters.
  4. Blocks 1 to 3, one at a time. The same gather, compute and free per block, so at most one block (plus the root) is ever whole. Forward issued 1 + 4 = 5 all-gathers.
  5. Backward: gather again, then reduce-scatter the gradients. Block 3 is gathered a second time to compute its gradients; the full-size gradient is summed across ranks and each keeps the quarter it owns (3,159,040 bytes per block; on gloo an all-reduce of the full gradient, section 2).
  6. Down to block 0, then the root. Four backward all-gathers and five reductions (the root's last, 112,640 bytes): 1 + 4 + 4 = 9 all-gathers and 4 + 1 = 5 reductions, 14 collectives per step. Each rank ends with the gradient quarter its optimizer updates.

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.

Prefetching: issue the next gather early

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.

Explicit prefetch issues gathers earlier, and holds more gathered weights at once

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.

MixedPrecisionPolicy: what travels in which dtype

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.

HSDP: shard inside a group, replicate across groups

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.

Depth: reshard_after_forward as an integer, accumulation, offload, state dicts, an unsharded root, FSDP1 against FSDP2 (4 min)

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.
  • Sharded state dicts cost nothing. 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.
  • After a forward without backward, the root's parameters are plain tensors. The root unit is not resharded after forward, so its parameters are swapped for the unsharded full tensors until backward or 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).

5. DTensor and DeviceMesh: placements, and how an operation picks its output's

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

  1. One logical tensor, two ranks. A is 4 × 6; the mesh is one dimension of 2 ranks. A placement says what each rank stores of it.
  2. 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.
  3. Replicate(): all of it, everywhere. Both ranks hold the full 4 × 6.
  4. 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.
  5. A product of shards is a pending sum, free. 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.
  6. relu needs the sum: 1 all-reduce first. relu of a sum is not the sum of relus, so DTensor all-reduces the Partial to 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:

  • Linear operations commute with the sum, so a Partial passes through them free: S(1) x S(0) → P; Partial + Partial and 2 × Partial stay Partial.
  • Nonlinear ones do not. relu(Partial) forced an all-reduce first. This is why Megatron's MLP puts the GeLU between a column split and a row split.
  • Operations that need a whole row need it gathered. Softmax and LayerNorm along a sharded dimension all-gathered it (output Replicate); along an unsharded dimension they ran locally. Sequence parallelism (section 6) uses exactly this: LayerNorm is per token, so splitting the sequence is free.
  • A row-sharded embedding table gives a new kind of placement, 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.

Depth: all 28 propagation cases, from_local's traps, a custom operator's strategy (4 min)

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.

6. Tensor and sequence parallelism: parallelize_module and its plan

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.

Sequence parallelism turns each all-reduce into a reduce-scatter and an all-gather, and halves the tokens between them

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.

Sequence parallelism: stop duplicating the cheap parts

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

  1. Block input. Both ranks hold the whole activation, 8 sequences × 64 tokens × 256 (recorded ln1 input, local shape (8, 64, 256), a plain tensor). The same numbers sit in two memories.
  2. LayerNorm, duplicated. Both ranks normalise all 64 tokens: the same work done twice, and the same activation saved twice for backward.
  3. Attention, split by heads. Each rank computes its 2 of the 4 heads for all 64 tokens (q, k, v weights local [128, 256] of [256, 256]).
  4. Output projection: a Partial sum. Each rank multiplies its heads by its rows of proj: a full-shape (8, 64, 256) result that is only part of the sum.
  5. All-reduce. One all-reduce of 524,288 bytes adds the two partial sums; both ranks again hold the whole activation.
  6. Residual and LayerNorm, duplicated again. Add to the residual stream and normalise, on both ranks, for all tokens.
  7. MLP up-projection, split by hidden units. Each rank computes 512 of the 1,024 hidden units for every token; GELU works on its half alone.
  8. MLP down-projection: a Partial sum. Again a full-shape partial result on each rank.
  9. All-reduce. The second all-reduce of the block. Per training step of the whole model: 16 all-reduces (8 in forward, 8 in backward), recorded.

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

Predict: in TP + SP, what does a LayerNorm's weight gradient need at the end of backward?

7. Context parallelism: the API, run on a CPU

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:

  • The public API fails on a CPU: Its handlers cover the CUDA flash, memory-efficient and cuDNN attention kernels only (_context_parallel/_attention.py L907-955); on a CPU, SDPA dispatches to a different kernel.
  • The ring itself works. PyTorch's ring template (_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 ().
  • A model must be written for CP. The running example numbers its positions 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.

8. Pipelining: stages and schedules

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.

Every schedule's recorded order on two ranks: zero-bubble schedules fill the idle gaps with weight gradients

F forwardB backwardI input gradientW weight gradientidle (bubble)

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

A V schedule silently scales a tied weight twice
In the V layouts the token embedding (stage 0) and the output layer (stage 3) share one rank, and here one Parameter. But every stage divides its parameters' gradients by the number of micro-batches at the end of its backward (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.
Depth: all runs with their spread, the ideal clock against the formula (2 min)

9. Distributed checkpoints (DCP): every rank writes its own shards

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

  1. Four ranks, four quarters. After training under FSDP2, each rank holds its shard of every parameter and of AdamW's state, as DTensors.
  2. 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.
  3. 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).
  4. One file for tools that want one. 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:

Depth: the failed run, the files, Hugging Face safetensors (2 min)
  • The async save on the default group, from the run's log: .
  • Reshard check: largest parameter difference after loading the 4-rank FSDP checkpoint into HSDP.
  • One file for everyone else. dcp_to_torch_save(dcp_dir, "single.pt") wrote ; torch_save_to_dcp goes back.
  • Hugging Face safetensors. 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.

10. Composing PP, FSDP and TP the torchtitan way

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:

  1. Mesh, with tensor parallel innermost: dimensions ["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.
  2. Pipeline split first: the model (built on the meta device, no memory) is cut into stage modules, and everything below is applied to each stage (distributed/pipeline_parallel.py pipeline_llm, L65-125).
  3. Per stage: context parallel, then TP, then activation checkpointing, then 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.
  4. Then weights are materialised and initialised on each rank (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.

Each layer of the recipe cuts the same weight again: TP's half, then FSDP's half of that

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.

Depth: the 8-process run per rank; torchtitan's own trainer (2 min)

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.

11. Debugging: hangs, mismatches and the flight recorder

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 first sequence number at which ranks disagree is the bug

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 itWhat it catchesCostWhere measured
Flight recorder dump + torchfrtracewhich rank is at which collective; type and size mismatchesa ring buffer per grouphere, and the parent lab section 11
TORCH_DISTRIBUTED_DEBUG=DETAILshape and type mismatches before they hang, with both shapes in the error2 extra all-gathers per collectiveparent lab section 11
monitored_barrier() (gloo)which rank did not arriveone barrierparent lab section 11
py-spy dump --pid on the odd rankwhat its Python is doing insteadnonenot run here
NCCL_DEBUG=INFO, NCCL_DEBUG_SUBSYSNCCL's choice of rings, trees, transports and network cardslog volumenot 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.

Depth: the analyser on a gloo dump (1 min)

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.

As of PyTorch 2.15 (released 28 October 2026, read 2 November 2026): the rewritten NCCL backend and one-sided transports (1 min)

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.

12. Depth: what carries over to GPUs, and mistakes seen here

What carries over to NVIDIA GPUs, and what does not (1 min)
On this pageOn NCCL and GPUs
Carries overwhich collectives, in which order, with which sizes; bucket layouts; placements and shard shapes; propagation rules; schedules' action orders; losses and gradientsthe same: all of it is Python and C++ above the backend
Carries over in kindmemory per rank (float32, CPU allocator)halved by bf16, plus the caching allocator and NCCL buffers (Memory allocators)
Changesreduce-scatter runs as an all-reduce (gloo has none)a real reduce-scatter: half the bytes, no full-size temporary
Changesbf16 compression hook refused; context parallel's public API refusedboth supported
Changescollectives and compute share one CPU threadcollectives run on their own CUDA streams and overlap with compute
Does not carryevery time: collective latency (0.09 to 1.1 ms for small messages), bubbles, async saveNVLink and InfiniBand are orders of magnitude faster; GPU compute is too, so bubbles and overlap must be measured there
May not carrygloo aborts from out-of-order collectives (PowerSGD, async_save)the ordering rule is the same; whether timing exposes it differs. Not checked
Mistakes seen on this page, one line each (1 min)
  • 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).
  • Expecting an elastic restart to keep the job's state: workers restart from the top of the script (section 1).
  • Leaving find_unused_parameters=True on "to be safe": a graph walk and a bitmap all-reduce every step (section 3).
  • Three 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).
  • A V pipeline schedule with tied embeddings: the gradient comes out 0.37 of the right one, silently (section 8).
  • from_local with uneven pieces and no shape: a wrong global shape, then an abort at full_tensor() (section 5).
  • Reading FSDP2 parameters after an evaluation forward: the root's are full plain tensors until reshard() (section 4).
  • Expecting gradient accumulation to remove FSDP2's all-gathers: it removes reductions only (section 4).