Skip to content

Sharding, meshes and collectives

35 min read

Prerequisites: TPU hardware for PyTorch engineers, Rooflines and arithmetic intensity, Profiling with XProf

A model that no longer fits on one TPU device, or that trains too slowly on one, has to be split. PyTorch describes the split with two objects you may already know from GPUs: a DeviceMesh, which arranges the processes on named axes such as dp and tp, and a DTensor placement (Shard, Replicate or Partial), which says how a tensor sits on each axis. Every time a tensor changes placement, the devices exchange data with one of four collectives: all-gather, reduce-scatter, all-reduce or all-to-all. This chapter covers what those collectives do, what each one costs on a TPU's interconnect, how TorchTPU compiles them into the TPU program instead of handing them to a library such as NCCL, and how to lay out a mesh so that the heavy traffic runs on ICI and only the light traffic crosses DCN. You will finish with a cost model you can check against an XProf trace, and a launch recipe for one host or many.

What this chapter covers

  • DeviceMesh, the DTensor placements Shard, Replicate and Partial, and the collective that moves a tensor from one placement to another.
  • How TorchTPU's tpu_dist backend turns a torch.distributed call into a StableHLO collective compiled into the TPU program, and why ranks that run different programs hang.
  • Ring cost of all-gather, reduce-scatter, all-reduce and all-to-all from the buffer size, the number of ranks and the ICI or DCN bandwidth, and the point below which hop latency dominates.
  • Mesh layout with torch.tpu.distributed.topology_aware_mesh, so that the most communication-heavy dimension stays on ICI, and multi-process launches on one host or several.
  • Checking a collective's duration in an XProf trace, and a job's scaling efficiency, against the cost model.

Why shard

There are two reasons, and they lead to different layouts.

Memory. Training with Adam keeps bf16 parameters and fp32 Adam moments; with gradients not counted, the scaling book's rule of thumb is about 10 bytes per parameter before any activations (How to Scale Your Model, "Training"). With chapter 1's capacities, that caps a fully replicated model at about \(32 \text{ GiB} / 10 \approx 3.4\) billion parameters on a v6e device and \(96 \text{ GiB} / 10 \approx 10\) billion on a v7x device (half of a 192 GiB chip). Anything larger must shard its parameters and optimizer state, which is what FSDP does.

Compute. Even a model that fits trains faster on more devices, as long as each device still has enough work to hide the communication. The scaling book calls the goal strong scaling: throughput that grows in proportion to the number of chips. It gets harder as you add chips, because the communication per device stays the same or grows while the computation per device shrinks. Most of this chapter is about measuring that trade.

TorchTPU runs one process per TPU device, as PyTorch does on GPUs. On v7x a chip is two devices, so the world size is twice the chip count (chapter 1).

Meshes and placements

The scaling book writes shardings with named-axis subscripts: \(A[I_X, J]\) is an array whose first dimension is split across mesh axis \(X\) and whose second is whole on every device; \(\{U_X\}\) marks an array whose values are partial sums still to be added across \(X\) (How to Scale Your Model, "Sharded Matrices"). PyTorch expresses the same ideas with a DeviceMesh and one placement per mesh dimension:

Scaling book DTensor placement on mesh axis X What each rank on X holds
\(A[I_X, J]\) Shard(0) rows \(I/\lvert X \rvert\) of the array
\(A[I, J_X]\) Shard(1) columns \(J/\lvert X \rvert\)
\(A[I, J]\) Replicate() the whole array
\(A[I, J]\{U_X\}\) Partial() a full-size array whose sum over X is the true value

A two-dimensional mesh takes one placement per dimension. On a mesh ("dp", "tp"), placements [Shard(0), Replicate()] split the rows across dp and repeat them on every rank of tp.

Changing placement is a collective. Each redistribution between two placements costs one specific collective. The companion demo runs every case on a CPU mesh and records what PyTorch issued with CommDebugMode:

Redistribution Collective Scaling book
Shard(0) to Replicate() all-gather removes a subscript: \([I_X] \to [I]\)
Replicate() to Shard(0) none, each rank keeps its slice adds a subscript for free
Partial() to Shard(0) reduce-scatter \([I]\{U_X\} \to [I_X]\)
Partial() to Replicate() all-reduce \([I]\{U_X\} \to [I]\)
Shard(0) to Shard(1) all-to-all moves a subscript: \([I_X, J] \to [I, J_X]\)

Where the partial sums come from. The scaling book reduces sharded matrix multiplication to four cases, and they tell you when each collective appears. If neither input is sharded on the contracted dimension, the local products are already the answer and nothing moves. If one input is sharded on it, you usually all-gather that input first. If both are sharded on it along the same axis, each rank's product is a partial sum: Partial(), finished by an all-reduce or, more cheaply, a reduce-scatter that leaves the result sharded. And two inputs sharded on non-contracted dimensions along the same axis must have one of them all-gathered first. In backward, the roles swap: the gradient of an all-gather is a reduce-scatter and the other way round, which is why FSDP's forward all-gathers become backward reduce-scatters.

Building the mesh. A DeviceMesh is built from a tensor of global ranks whose shape is the mesh shape. The ranks along the last dimension form the innermost groups:

import torch
from torch.distributed.device_mesh import DeviceMesh

# 4 ranks; on a TPU, take the rank tensor from topology_aware_mesh (below) instead
mesh = DeviceMesh("cpu", mesh=torch.arange(4).reshape(2, 2), mesh_dim_names=("dp", "tp"))
tp_mesh, dp_mesh = mesh["tp"], mesh["dp"]     # one process group per dimension

The CPU demo prints the groups this creates: rank 0's tp group is ranks [0, 1] and its dp group is ranks [0, 2]. Which physical devices those ranks are is the question of the section on mesh layout below.

Uneven shards

TorchTPU replaces DTensor.from_local with a wrapper that warns when you omit the global shape and stride: "Unevenly sharded tensors across ranks may cause collectives to hang or error out." Pass both whenever local shapes can differ. The FSDP guide's matching advice is to make sharded dimensions divisible by the mesh size.

How TorchTPU runs a collective

TorchTPU implements distributed communication as a PyTorch process-group backend (a c10d::Backend, ProcessGroupTpu in the C++ source) registered under the name "tpu_dist". On a GPU you write backend="nccl"; here you write backend="tpu_dist", and DTensor, DDP, FSDPv2 and SimpleFSDP work directly on top of it. The backend implements all-reduce, broadcast, all-gather, gather, scatter, reduce-scatter, both all-to-all variants, barrier and point-to-point send and receive.

What happens underneath is different from NCCL. There is no separate communication library. The backend lowers each collective into a StableHLO collective operation (stablehlo.all_reduce, stablehlo.all_gather, stablehlo.reduce_scatter, stablehlo.all_to_all), and XLA compiles it into the TPU executable, which drives the ICI links itself.

Flow diagram in two dashed regions. The left region, Rank process, holds three amber blocks stacked top to bottom: DTensor, FSDP, DDP; torch.distributed; tpu_dist backend, joined by downward arrows. An arrow labelled replica_groups leaves tpu_dist backend to the right into the right region, TPU device, where a grey StableHLO collective block points down to a blue XLA executable block, which points down to a purple ICI links block.

Follow the one arrow that crosses between the regions: what reaches the TPU is a StableHLO op carrying every subgroup's membership, not a call into a communication library.

TorchTPU's distributed guide lists three consequences of compiling collectives:

  1. The topology must be known before initialization. A GPU process can inspect all GPUs on its host, pick cuda:{local_rank} and only then call init_process_group(). A TPU worker is bound to one device and cannot see the rest, so the environment must describe the slice before the runtime starts: its physical mesh (TORCH_TPU_TOPOLOGY), one host:port per device used to build the ICI mesh (TORCH_TPU_SLICEBUILDER_ADDRESSES), and the number of devices (WORLD_SIZE). The launch section below shows how these are filled in.
  2. Subgroups become global replica groups. dist.all_reduce(x, group=g) hands the backend only the subgroup this rank belongs to, but stablehlo.all_reduce needs every subgroup in the job, as replica_groups. The tpu_dist backend exchanges subgroup membership across all ranks of the default group when it sets up the collective and builds the replica_groups and device assignment XLA needs.
  3. The compiler expects SPMD; PyTorch allows MPMD. XLA's collectives assume every rank compiles and runs the same program with matching collectives. A PyTorch program can diverge by rank, through if dist.get_rank() == 0: or a dimension that does not divide evenly. If two ranks run different StableHLO modules that contain collectives, their synchronization flags or buffer offsets can mismatch, and the guide's words for the result are "runtime deadlocks or memory corruption".

Skinny collectives, and the two ways to fuse them. To make divergent ranks safe by default, TorchTPU runs every collective as a skinny collective: graph breaks around it, so it compiles into a small StableHLO module of its own. That is safe, and it prevents XLA from overlapping the collective with the computation around it. Two opt-ins remove the breaks:

Mode How to turn it on What it does Use it for
Skinny collectives default each collective in its own module correctness first; rank-dependent code
@torch.tpu.distributed.spmd_safe decorate a function collectives inside it are fused with the surrounding compute into one module a training step you know runs identically on every rank
Compilation handshake TORCH_TPU_SPMD_HANDSHAKE_STAGE=COMPILE_STAGE or DISPATCH_STAGE (default OFF) under torch.compile, ranks compare their graphs and fuse collectives only if they match fusion in torch.compile with a guard against divergence
import torch
import torch.distributed as dist

@torch.compile
@torch.tpu.distributed.spmd_safe
def spmd_train_step(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
    out = x @ weight
    dist.all_reduce(out, op=dist.ReduceOp.AVG)   # fused with the matmul: XLA can overlap them
    return torch.nn.functional.silu(out)

The decorator's docstring is strict about its contract: only decorate functions that issue the same TPU operations, collectives included, in the same order and with the same shapes on every rank. It also synchronizes the function's input and output tensors without waiting, so that no operation from outside the function is fused into its graphs.

The two handshake stages differ in when they check. COMPILE_STAGE compares a fingerprint of each rank's FX graph before compiling and fuses only if all ranks agree; the guide recommends it for ordinary torch.compile jobs where all ranks compile together. It times out if only one rank recompiles, for example after a rank-specific shape change. DISPATCH_STAGE compiles fused, checks agreement every time the executable is dispatched, and if the ranks disagree recompiles with split (skinny) collectives; it costs more per call and survives rank-specific recompiles.

The four collectives and what they cost

All four collectives run as rings on a TPU axis: each rank talks only to its two neighbours, and data travels hop by hop. The scaling book derives their costs for TPUs; the companion code/ch13_collectives/cost_model.py restates them in PyTorch's terms. Its one function is

collective_time(kind, bytes_, n, link_bw, *, bidirectional=True, hop_latency=0.0) -> float

with kind one of "all_gather", "reduce_scatter", "all_reduce", "all_to_all" (anything else, or n < 1, raises ValueError). The arguments are chosen to be read off your code and chapter 1's table:

  • bytes_ (\(V\)) is the largest buffer one rank passes to the call: the gathered output of all_gather_into_tensor, the unreduced input of reduce_scatter_tensor, the tensor of all_reduce, the input of all_to_all_single.
  • n is the number of ranks on the ring.
  • link_bw (\(W\)) is one link in one direction: 45 GB/s on v4 and v5e, 90 GB/s on v5p, v6e and v7x (chapter 1).
  • bidirectional=True means a ring with a wraparound link, so every rank sends both ways at once and has \(2W\) of bandwidth, the scaling book's \(W_\text{ici}\). A line of chips without a wraparound link achieves about one direction's worth, bidirectional=False.

The bandwidth terms:

Collective Ring with wraparound One direction
all-gather \(\dfrac{V (n-1)}{2 n W}\) \(\dfrac{V (n-1)}{n W}\)
reduce-scatter \(\dfrac{V (n-1)}{2 n W}\) \(\dfrac{V (n-1)}{n W}\)
all-reduce \(\dfrac{2 V (n-1)}{2 n W}\) \(\dfrac{2 V (n-1)}{n W}\)
all-to-all \(\dfrac{V \lfloor n^2/4 \rfloor}{2 n W}\) \(\dfrac{V (n-1)}{2 W}\)

All-gather

Each rank starts with one shard of \(V/n\) bytes and must end with all \(n\). On a ring, every rank forwards the shard it received in the previous step to its neighbour, so after \(n - 1\) steps every shard has visited every rank, and every link has carried \(n - 1\) shards: \(V(n-1)/n\) bytes. With a wraparound link, half of each shard goes each way round and the load per direction halves.

An animation in eight frames of four ranks on a square ring, rank 0 top left, rank 1 top right, rank 2 bottom right, rank 3 bottom left, joined by purple clockwise arrows. Each rank has four slots. At the start rank r holds one shard in slot r: A, B, C or D, each in its rank's colour. In each of three steps every rank sends one shard to its clockwise neighbour, drawn on the link, and the receiver stores it; a counter reads per link so far 1, 2, then 3 shards. The last frame shows every rank holding A, B, C, D and the text: each link carried 3 shards, (n - 1) / n of V; sending both ways round halves that: T = V (n-1) / (2 n W).

All four links work in every step; no rank waits for a single sender. That is why the time depends on the bytes per link, not on the number of ranks.

Take the limit of large \(n\) and the all-gather costs \(V / W_\text{ici}\): the scaling book's striking result that the time barely depends on how many devices share the array. For small rings the \((n-1)/n\) factor matters. The scaling book's own example gathers bf16[2048, 8192] (34 MB) over a v5e axis of 4 chips, which has no wraparound link, and estimates 3 hops of 8.4 MB at 45 GB/s, about 560 µs; collective_time("all_gather", 2048 * 8192 * 2, 4, 45e9, bidirectional=False) gives 559 µs, and the companion tests check it. The scaling book's profile of that case measured 680 µs, about 82% of the model's speed.

Reduce-scatter

The mirror image. Every rank holds a full-size array of partial sums, and chunk \(j\) must be summed over all ranks and end on rank \(j\). Each step, every rank sends its running sum of one chunk to its neighbour, which adds its own piece. The bytes on each link are the same as an all-gather's, and so is the time; the additions are vector work that overlaps the transfers.

An animation in eight frames of four ranks on a clockwise ring, each holding four chunks labelled with its letter and the chunk index, such as A0 to A3 on rank 0. In each of three steps every rank sends the running sum of one chunk to its neighbour, drawn on the link with a label such as B0+C0, and the receiver adds its own piece, so labels grow to C1+D1+A1. The last frame shows rank j holding only a green chunk labelled Σj, and the text: same traffic as an all-gather, run in reverse: T = V (n-1) / (2 n W). A counter reads per link: 3 pieces = 3V/4.

Watch one chunk's label grow by one letter per hop: after three hops it has passed through every rank and arrives, complete, at its owner.

All-reduce

An all-reduce leaves the full sum on every rank. The ring algorithm is a reduce-scatter followed by an all-gather of the reduced chunks, so it costs exactly twice either one. This is the scaling book's reason for preferring a reduce-scatter whenever the next operation can consume a sharded result: it pays half, and defers the all-gather until (or unless) the full array is needed.

An animation in fourteen frames of four ranks on a clockwise ring. Steps 1 to 3 repeat the reduce-scatter: running sums such as B0+C0 travel the links until each rank holds one green Σ chunk. Steps 4 to 6 forward the green chunks Σ0 to Σ3 around the ring, overwriting the stale partial sums, until every rank holds Σ0, Σ1, Σ2, Σ3. A counter reaches 6 pieces per link, and the last frame reads: 6 pieces per link, twice an all-gather of V, T = 2 V (n-1) / (2 n W).

The counter reaches 3 when the reduce-scatter half ends and 6 when the all-gather half ends: an all-reduce is two collectives, and costs two.

All-to-all

An all-to-all reshards: rank \(r\) splits its buffer into \(n\) pieces and piece \(j\) goes to rank \(j\), so Shard(0) becomes Shard(1). Nothing is replicated, so no piece has to visit every rank. On a one-way ring each rank forwards what is not its own: 3 pieces in the first step, 2 in the second, 1 in the third.

An animation in eight frames of four ranks on a clockwise ring. Each rank holds b bytes in four pieces of b / 4; piece j, labelled with the rank's letter and digit j, belongs on rank j. In step 1 each link carries three pieces, in step 2 two, in step 3 one; pieces stop when they reach the rank their digit names. The last frame shows rank j holding A_j, B_j, C_j, D_j, and the text: 3 + 2 + 1 = 6 pieces of b/4 per link, one way: half an all-gather of the same 4b-byte array. A counter reads per link: 6 pieces = 1.5 b.

The links carry less in each step, because pieces leave the ring as soon as they reach their owner. An all-gather never gets that discount.

The scaling book's exercise on this ring sums the distances: \(1 + 2 + \dots + (n-1)\) in one direction, half an all-gather of the same array. Both directions together take the shorter way round, which wins another factor of two, so for the same logical array an all-to-all costs about a quarter of an all-gather on a bidirectional ring. The table's per-rank form hides this: the per-rank buffer of an all-to-all is only \(1/n\) of the logical array, so for equal per-rank buffers the all-to-all is the most expensive line on the chart below.

Latency, many axes, and what the model leaves out

Latency. Every hop has a fixed cost of about 1 µs (scaling book), whatever the size. With hop_latency set, the model returns \(\max(\text{hops} \times \text{latency}, \text{bandwidth term})\), the scaling book's form, where hops is the longest path a byte takes. On a 16-rank ring with wraparound, an all-gather is latency-bound when the buffer passed to the call (bytes_, the gathered output, not the per-rank shard) is below about 1.5 MB: an all-reduce of a few scalars for logging costs 16 µs, not the 0.3 µs its bytes suggest.

Two charts titled Ring cost model, code/ch13_collectives/cost_model.py. Left, Ring of 16 ranks, 90 GB/s per ICI link each way, 1 µs per hop: time in ms on a log scale against buffer per rank, labelled bytes passed to the torch.distributed call, from 4 KiB to 1 GiB on a log scale. Three lines: all-gather = reduce-scatter (blue), all-reduce (orange) and all-to-all (dashed teal). All three are flat at 8 to 16 microseconds for small buffers, then rise linearly; a dotted vertical line near 1.5 MiB is annotated below about 1.5 MiB the 1 µs hops dominate. At 1 GiB the all-gather reaches about 5.6 ms, the all-reduce about 11 ms and the all-to-all about 24 ms. Right, All-reduce of 1 GiB of bf16 gradients per rank, ICI 90 GB/s per link and DCN 12.5 GB/s egress per chip (v7x), horizontal bars on a log scale: ICI ring of 16 with wraparound 11.2 ms; ICI ring of 4 with wraparound 8.9 ms; ICI line of 4 without wraparound 17.9 ms; DCN across 2 slices with the full gradient 85.9 ms (orange); DCN across 2 slices with a 1/64 shard after an in-slice reduce-scatter 1.3 ms (green).

On the left, the x-axis is the buffer each rank passes to the torch.distributed call, not the size of the model or tensor; find where each line leaves its floor: below that size, batch small collectives together. On the right, compare the orange and green bars: the same gradients cross DCN 64 times faster once they have been reduce-scattered inside the slice.

Several axes. A collective over two or three physical axes at once (a gather over all of a 4x4x4 cube, say) has that many rings working in parallel, and the scaling book divides the time by the number of axes. The 1D model covers one axis; divide by hand when a mesh dimension spans several.

What it leaves out. The model is a lower bound for one axis of a healthy torus. On v7x, the two devices of a chip share the chip's external links, so a ring of devices that both drive the same link gets about half of it (chapter 2). Measured collectives also fall short of peak; the scaling book's v5e measurements reach about 95% of the link's bandwidth for gathers of 10 MB and more. And the model knows nothing about what the collective overlaps with, which is the next section's subject.

Which parallelism uses which collective

Each parallelism strategy is a choice of which arrays to shard on which mesh axis, and the collectives follow from the matmul rules above. The scaling book models a transformer layer as two matmuls, In[B, D] @ W_in[D, F] and @ W_out[F, D], where \(B\) counts tokens; TorchTPU's distributed guide gives the placement for each strategy.

Strategy Collectives When, per step Bytes per layer (scaling book, forward + backward) Physical placement (TorchTPU guide)
Data parallel (DP, DDP) all-reduce of gradients once, in backward, off the critical path \(8DF\) outer ICI axis or DCN, across slices
FSDP all-gather of weights, reduce-scatter of gradients every layer, forward and backward; the gather can run one layer ahead \(4DF + 8DF\) ICI axes within a slice
Tensor parallel (TP) all-gather of activations before W_in, reduce-scatter after W_out every layer, on the critical path \(4BD + 4BD\) the fastest local ICI ring
Context or sequence parallel (CP, SP) all-to-all, or a ring of point-to-point transfers for ring attention every attention layer local ICI axes
Expert parallel (EP) all-to-all, ragged_all_to_all every MoE router layer local ICI axes

The scaling book turns the first three rows into thresholds. For DP and FSDP, compute time grows with the tokens per device while the bytes do not, so they stay compute-bound while the tokens per device exceed \(C / W_\text{ici}\), the chip's FLOP/s over its ICI bandwidth on that axis. For a v6e chip on one axis that is \(918 \times 10^{12} / (2 \times 90 \times 10^9) = 5{,}100\) tokens (the scaling book's v5p figure is 2,550). For TP the batch cancels and the limit is on the degree: TP stays compute-bound while the number of TP ranks is below \(F\) divided by that same ratio, which the scaling book finds is 8 to 16 ways for most models. Combining FSDP and TP lowers the minimum batch further. Across slices, pure data parallelism over DCN needs a batch per slice above \(C / W_\text{dcn}\): for v7x, \(2{,}307 \times 10^{12} / 12.5 \times 10^9 \approx 185{,}000\) tokens.

Laying out the mesh: ICI and DCN

A mesh dimension is a set of process groups, and its collectives run over whatever physical links join the ranks in each group. Two rules from TorchTPU's guide decide the layout.

Order mesh dimensions from least to most communication-intensive. The outermost dimension should be the one that talks least (DP), the innermost the one that talks most (TP). topology_aware_mesh then puts the innermost dimensions on the shortest ICI paths.

Use topology_aware_mesh instead of torch.arange. On a TPU, consecutive ranks are not guaranteed to be physical neighbours in the order a reshape assumes. torch.tpu.distributed.topology_aware_mesh(mesh_shape, *, dcn_mesh_shape=None, allow_split_physical_axes=False, contiguous_submeshes=False) returns an int64 tensor of global ranks with shape mesh_shape, arranged so that logically adjacent positions are physically adjacent on ICI. It is marked experimental, needs an initialized process group, and every rank computes the same tensor from the same all-gathered device information:

import torch
import torch.distributed as dist
from torch.distributed.device_mesh import DeviceMesh

dist.init_process_group(backend="tpu_dist")
# 8 devices: dp=4 is the outer, lighter dimension; tp=2 the inner, heavier one
rank_tensor = torch.tpu.distributed.topology_aware_mesh(mesh_shape=(4, 2))
mesh = DeviceMesh("tpu", mesh=rank_tensor, mesh_dim_names=("dp", "tp"),
                  preserve_rank_order=True)
dp_mesh, tp_mesh = mesh["dp"], mesh["tp"]

preserve_rank_order=True keeps the rank order the tensor encodes, as TorchTPU's own example does. The product of mesh_shape must equal the world size, on multi-slice jobs too.

Across slices, the outermost dimension crosses DCN. On a multi-slice job, topology_aware_mesh reads the slice of each device and, unless you pass dcn_mesh_shape, splits the outermost dimension whose extent is above 1 across the slices; the rest of the mesh stays inside each slice on ICI. If that dimension's extent is not divisible by the number of slices it raises ValueError rather than splitting an inner dimension, because, in the source's words, that "would split shard groups across the slower inter-slice network". The figure shows what goes wrong when the order is reversed.

Two layouts of 8 ranks with dp = 2 and tp = 4 on two slices of 2 by 2 chips; within each slice purple ICI links join neighbouring chips, and each slice's amber host is joined to the other's by a dashed purple DCN line. Left, mesh_shape=(2, 4) with names dp, tp: slice A holds ranks 0 to 3, all tp group 0; slice B holds ranks 4 to 7, all tp group 1; the DCN line is labelled DCN: dp all-reduce. Right, mesh_shape=(4, 2) with names tp, dp: slice A holds ranks 0 and 2 of tp group 0 and ranks 1 and 3 of tp group 1; slice B holds ranks 4 and 6 of tp group 0 and 5 and 7 of tp group 1; the DCN line is labelled DCN: tp every layer.

Count the colours in each slice. On the left each slice holds one whole tp group, so only the once-per-step gradient all-reduce touches DCN; on the right every tp group straddles the slices, and every layer's collectives wait on the slow link.

The FSDP guide gives the multi-slice rule in one line: replicate (data parallel) across DCN and shard within each slice, which is hybrid sharding (HSDP). The chart's right panel shows why the order of operations matters too. A full 1 GiB gradient all-reduced across two v7x slices at 12.5 GB/s of egress per chip takes about 86 ms; reduce-scattered inside a 64-chip slice first, each chip sends only its 1/64 shard across DCN and that part takes 1.3 ms.

Ranks are not device IDs. On many TPU generations the device IDs of neighbouring ranks are not consecutive; TorchTPU's example is v7x, where ranks 0, 1 and 2 are neighbours but their device IDs are 0, 1 and 4. PyTorch code sees only ranks. A Pallas kernel that addresses other devices directly (a distributed variant of chapter 12's kernels) must build its mesh with torch.tpu.pallas.get_pallas_mesh, which matches the ranks the rest of the program uses.

Overlapping communication with compute

A collective that overlaps with computation costs nothing on the step time, as long as it is shorter than the computation it hides behind (chapter 2's max instead of sum). The strategies differ in how much freedom they leave:

  • DP's all-reduce is off the critical path. Gradients for layer \(L\) are ready while backward is still computing layer \(L - 1\), so their all-reduce can run then.
  • FSDP's all-gather can run one layer ahead, and its reduce-scatter in backward is off the critical path, like DP's all-reduce.
  • TP's collectives are on the critical path: the next matmul needs the gathered activations. Hiding them needs a collective matmul, which splits the matmul into chunks and computes one while the next chunk travels (How to Scale Your Model, "Sharded Matrices", the section on overlapping matmul communication).

On TorchTPU there is a precondition: XLA can only overlap what is in the same compiled module. A skinny collective sits alone in its module, so the TPU waits for it. The FSDP guide's first best practice is to compile the whole training step with torch.compile(backend="tpu"), or at least forward, loss and backward together, so that XLA sees every collective and every matmul at once. Then remove the graph breaks around the collectives:

A decision tree read from top to bottom. A dark pill, Collectives in a compiled step, leads down to three white rounded questions on a spine. Rank-dependent code in the step? Yes leads right to a blue card, Skinny collectives (default), Move divergent code out of the step; No leads down. Guaranteed identical on every rank? Yes leads right to a blue card, Decorate the step, @torch.tpu.distributed.spmd_safe; No leads down. Can one rank recompile without the others? Both answers lead into a blue dashed container titled TORCH_TPU_SPMD_HANDSHAKE_STAGE that holds two cards: No leads right to COMPILE_STAGE, Ranks compare graphs before compiling; Yes leads down and right to DISPATCH_STAGE, Checked at every dispatch; skinny if ranks differ.

Only rank-dependent code keeps skinny collectives by choice. spmd_safe always fuses; the handshake fuses when the ranks' graphs match and falls back to skinny collectives when they do not. The two opt-ins combine: collectives inside an spmd_safe function always fuse, and the handshake decides for the rest.

Reductions and precision. A reduction over ranks adds the same numbers in a different order than one device would, so a sharded run matches its single-device reference to the tolerances of chapter 6, not bit for bit. A SimpleFSDP-style layer gathers weights in bf16 and reduce-scatters gradients in fp32 for that reason; and because SimpleFSDP's gradients are summed (a Partial with a sum), the loss is scaled by 1 / world_size to match FSDP2's average. Chapter 14 takes this up.

Launching on one host or many

The worker is ordinary PyTorch with two strings changed:

import torch
import torch.distributed as dist

dist.init_process_group(backend="tpu_dist")      # "nccl" on a GPU
device = torch.device("tpu")                     # this process's one TPU device
x = torch.ones(4, 4, device=device) * (dist.get_rank() + 1)
dist.all_reduce(x, op=dist.ReduceOp.SUM)
dist.destroy_process_group()

The launcher must set the topology variables before any worker starts. TorchTPU's CLI module computes them and prints shell assignments; eval exports them.

eval $(python3 -m torch.tpu.distributed | sed 's/^/export /')
torchrun --nproc_per_node=$WORLD_SIZE train.py

On one host the module picks a free local port per device for TORCH_TPU_SLICEBUILDER_ADDRESSES and reads the topology from the attached devices. On GKE, a single v7x host with slice topology 2x2x1 becomes TORCH_TPU_TOPOLOGY="2,2,1,2", because TorchTPU launches one process per TensorCore.

eval "$(python3 -m torch.tpu.distributed)"
export TORCH_TPU_TOPOLOGY TORCH_TPU_SLICEBUILDER_ADDRESSES TORCH_TPU_XPROF_SESSION_ID
export NNODES NODE_RANK MASTER_ADDR MASTER_PORT
python3 -m torch.distributed.run --nnodes=$NNODES --node_rank=$NODE_RANK \
    --master_addr=$MASTER_ADDR --master_port=$MASTER_PORT \
    --nproc_per_node=8 train.py

This is TorchTPU's own multi-host example (examples/tensor_parallel/manual/launch_multihost.sh, eight devices per v7x host). On several hosts the module builds one address per device from TPU_WORKER_HOSTNAMES (base port TORCH_TPU_BASE_PORT, default 8070), sets NNODES, takes MASTER_ADDR from the first worker hostname and MASTER_PORT 29500, and derives each host's NODE_RANK from its devices' physical coordinates, falling back to JOB_COMPLETION_INDEX. The printed WORLD_SIZE counts every device on every host, so --nproc_per_node=$WORLD_SIZE is only correct on one host.

import torch

torch.tpu.distributed.set_tpu_launch_env()   # in the parent, before spawning workers
# then start workers, e.g. with torch.distributed.launcher.elastic_launch

set_tpu_launch_env(*, nnodes=None, nproc_per_node=None) is the function behind the CLI. It is experimental, idempotent, and never overwrites a variable that is already set, so you can pin any value from outside. Given nnodes, it checks it against TPU_WORKER_HOSTNAMES so that a mismatched configuration fails at once instead of hanging at rendezvous.

The default process group spans every device in the slice. To rehearse the program logic without a TPU, swap in backend="gloo" and torch.device("cpu"), which is what the companion demo does:

$ python code/ch13_collectives/collectives_demo.py --cpu-smoke
== 1. four collectives, 4 CPU processes, gloo backend
   reduce_scatter
      rank 0: in [0, 1, 2, 3]           out [60]                   ok
      rank 3: in [30, 31, 32, 33]       out [72]                   ok
   all_to_all
      rank 0: in [0, 1, 2, 3]           out [0, 10, 20, 30]        ok
      rank 3: in [30, 31, 32, 33]       out [3, 13, 23, 33]        ok

== 2. DeviceMesh("cpu", [[0, 1], [2, 3]], mesh_dim_names=("dp", "tp")), DTensor redistributions along tp
   rank 0's dp group: ranks [0, 2]
   rank 0's tp group: ranks [0, 1]
   Shard(0) -> Replicate()    local (2, 4)   -> (4, 4)   collectives: all_gather_into_tensor x1    ok
   Replicate() -> Shard(0)    local (4, 4)   -> (2, 4)   collectives: none                         ok
   Partial() -> Shard(0)      local (4, 4)   -> (2, 4)   collectives: reduce_scatter_tensor x1     ok
   Partial() -> Replicate()   local (4, 4)   -> (4, 4)   collectives: all_reduce x1                ok
   Shard(0) -> Shard(1)       local (2, 4)   -> (4, 2)   collectives: all_gather_into_tensor x1    ok
   note: on CPU, PyTorch emulates the all-to-all redistribution with all-gather + chunk

== 3. ring cost model
   all_gather of bf16[2048, 8192] over 4 v5e chips, no wraparound: 559 us (scaling book: about 560 us)

cpu-smoke: OK

The values name their origin (rank \(r\)'s element \(j\) is \(10r + j\)), so the all-to-all visibly transposes the four buffers. The last DTensor line is a CPU artifact: for a CPU mesh, PyTorch logs that the process group "does not support alltoall yet" and gathers instead. On the TPU path the same script, run under torchrun, repeats the check with "tpu_dist", builds the mesh with topology_aware_mesh, and times each collective against the model.

Failure modes

Symptom Cause Fix
TP or FSDP collectives take 10 to 100 times their ICI estimate on a multi-slice job Mesh dimensions in the wrong order: the heavy dimension is outermost and was split across slices over DCN Order mesh_shape from least to most communication-intensive; pass dcn_mesh_shape to choose the split explicitly
ValueError from topology_aware_mesh about the outermost non-trivial axis Its extent is not divisible by the number of slices Reshape the mesh so the outer (DP) dimension absorbs the slice count
Gradient all-reduce over DCN dominates the step Plain DP or FSDP across all devices of several slices: the full gradient crosses DCN HSDP: shard within the slice, replicate across slices, so only a shard crosses DCN
Collectives about twice the model's time on a small slice No wraparound link on that axis (v5e and v6e below 16 chips, v7x below a full cube) Model it with bidirectional=False; prefer axes with wraparound for heavy dimensions
Job hangs at a collective, or times out Ranks run different programs: a collective inside if rank == 0:, rank-dependent shapes, or uneven shards, with fused collectives Keep collectives out of rank branches; pad to the same shapes; use DISPATCH_STAGE or skinny collectives for code that may diverge
Hang after one rank recompiles, with COMPILE_STAGE Only that rank entered the handshake DISPATCH_STAGE, which tolerates rank-specific recompiles
Deadlock with @spmd_safe The decorated function is not SPMD Remove the decorator or the divergence
Warning about unevenly sharded tensors from DTensor.from_local Global shape and stride not passed Pass both; make sharded dimensions divisible by the mesh size
RuntimeError from topology_aware_mesh saying the process group is not initialized Called before init_process_group Initialize with backend="tpu_dist" first
RuntimeError: Duplicate pjrt device ids across torch ranks Two processes resolved the same device, or a multi-slice job runs without the MegaScale PJRT client, so each slice numbers its devices from zero One process per device; check the multi-slice runtime setup
Workers fail at start-up, or each sees a one-device world TORCH_TPU_SLICEBUILDER_ADDRESSES and TORCH_TPU_TOPOLOGY not set before the workers started eval the CLI output before torchrun, or call set_tpu_launch_env() in the parent
Wrong process count on a multi-host job --nproc_per_node=$WORLD_SIZE, where WORLD_SIZE counts all hosts' devices Pass --nnodes, --node_rank and the devices per host
all_to_all_single with uneven split sizes fails The tpu_dist header marks uneven splits for the single-tensor form "Currently not supported" Use dist.all_to_all with a list of tensors, which supports different sizes along dimension 0
Collectives correct but never overlap; compute idle around each in the trace Skinny collectives (the default) in their own modules Compile the whole step; @spmd_safe or the handshake
A distributed Pallas kernel talks to the wrong device Device IDs assumed equal to ranks Build the kernel's mesh with torch.tpu.pallas.get_pallas_mesh

Verifying the result

Four checks, from cheapest to most telling.

  1. The values are right. python code/ch13_collectives/collectives_demo.py --cpu-smoke ends with cpu-smoke: OK, and pytest tests/ch13 -q passes. On the TPU, the demo's step 1 shows every rank's four outputs matching the closed-form answers under "tpu_dist". For your own model, compare a sharded run against an unsharded one at chapter 6's tolerances, and check y.full_tensor() for any DTensor you are unsure of.
  2. The mesh is what you meant. Print the rank tensor from topology_aware_mesh and the ranks of each dimension's group (dist.get_process_group_ranks(mesh["tp"].get_group())). On a multi-slice job, the INFO log line topology_aware_mesh: splitting mesh_shape=... across N slices on axis k names the dimension that crosses DCN; k must be your data-parallel axis.
  3. Each collective takes the time the model predicts. Capture a trace as in chapter 10 (with TpuProfilerConfig(worker_rank=...) to tell the ranks' files apart) and find the collectives in the XLA Ops row: all-gather, reduce-scatter, all-reduce, all-to-all, sometimes inside a fusion's calls=. Compute collective_time with the buffer size, the size of the group, the link bandwidth and whether the axis wraps around. Expect the measurement at or a little above the model for buffers of several MB (the scaling book measured about 95% of link bandwidth for large gathers, and 680 µs against a 560 µs estimate in its small-axis example). Twice the model points to a missing wraparound link or two devices sharing a link; ten times or more points to DCN. Also look at what runs beside each collective: idle compute next to it means it did not overlap.
  4. Scaling efficiency holds. Fix the per-device batch, double the number of devices, and measure throughput (tokens per second) in steady state, without warm-up compiles. Efficiency is \(\text{throughput}(2N) / (2 \times \text{throughput}(N))\). Before you run, predict it: per layer, compare the model's collective time with the matmul time from chapter 2's roofline. If communication is shorter and overlapped, efficiency should stay near 1; if it is longer, the step time grows by roughly the difference, and the efficiency you measure should match that prediction. A drop the model does not predict is a layout or overlap problem, and checks 2 and 3 tell you which.

Worked problems

Problem 1. A job builds DeviceMesh("tpu", mesh=torch.arange(8).reshape(2, 4), mesh_dim_names=("dp", "tp")) and a DTensor of global shape [8, 1024] with placements [Shard(0), Replicate()]. List the dp and tp groups, and say what rank 5 holds.

Answer

The innermost dimension's groups are the rows: tp groups [0, 1, 2, 3] and [4, 5, 6, 7]. The dp groups are the columns: [0, 4], [1, 5], [2, 6], [3, 7]. Shard(0) on dp splits the 8 rows in two; Replicate() on tp repeats each half on all four ranks of the row. Rank 5 has dp coordinate 1, so it holds rows 4 to 7, shape [4, 1024], the same as ranks 4, 6 and 7. (On a TPU, take the rank tensor from topology_aware_mesh instead of arange; the groups are then whatever ranks it places in each row and column.)

Problem 2. For each redistribution along one mesh axis, name the collective and its cost relative to an all-gather of the same array: (a) Partial() to Replicate(); (b) Replicate() to Shard(1); (c) Shard(0) to Shard(1); (d) Partial() to Shard(0). Why does backward of an FSDP layer issue the collective in (d)?

Answer

(a) All-reduce, twice an all-gather. (b) None: each rank keeps its slice. (c) All-to-all, about a quarter of an all-gather of the same array on a ring with wraparound (half on a one-way ring). (d) Reduce-scatter, the same as an all-gather. FSDP all-gathers the sharded weights in forward; the gradient of an all-gather is a reduce-scatter, so each rank's gradient with respect to the full weight, a partial sum over its share of the batch, is reduce-scattered back to its shard.

Problem 3. An FSDP layer's W_in is bf16[8192, 28672], sharded over a 16-device ring of v6e chips with wraparound. (a) How long does the all-gather take? (b) With 4,096 tokens per device, how long is the forward matmul at 918 TFLOP/s? (c) Can the gather hide behind the matmul, and what tokens per device would it need?

Answer

(a) \(V = 2 \times 8192 \times 28672 = 469{,}762{,}048\) bytes. \(T = V \times 15 / (2 \times 16 \times 90 \times 10^9) = 2.45\) ms; collective_time("all_gather", 469762048, 16, 90e9) agrees. (b) \(2 \times 4096 \times 8192 \times 28672 = 1.92 \times 10^{12}\) FLOPs, \(/ 918 \times 10^{12} = 2.10\) ms. (c) No: 2.45 ms of gathering against 2.10 ms of matmul, so the layer is communication-bound by about 0.35 ms even with perfect overlap. The ratio is independent of \(D\) and \(F\): it needs tokens per device above \(918 \times 10^{12} \times (15/16) / (2 \times 90 \times 10^9) \approx 4{,}780\), the scaling book's \(C / W_\text{ici}\) threshold with the ring's \((n-1)/n\) factor.

Problem 4. Two v7x slices train with data parallelism, each with a 1 GiB bf16 gradient per chip. Model one ICI axis of each slice as a 16-chip ring with wraparound at 90 GB/s per link, and DCN as 12.5 GB/s of egress per chip. Compare (a) one flat ring all-reduce over all 32 chips, whose ring includes the DCN hops, and (b) a hierarchical all-reduce: reduce-scatter inside each slice, all-reduce of the shard across the two slices, all-gather inside each slice.

Answer

(a) A ring is as fast as its slowest link, so treat it as one-way at 12.5 GB/s: \(2 \times (31/32) \times 2^{30} / 12.5 \times 10^9 \approx 166\) ms. (b) Reduce-scatter over 16 on ICI: 5.59 ms. Each chip now holds a \(2^{30}/16\) = 64 MiB shard; all-reduce it over 2 slices on DCN, one way: \(2 \times (1/2) \times 67{,}108{,}864 / 12.5 \times 10^9 = 5.37\) ms. All-gather over 16 on ICI: 5.59 ms. Total about 16.6 ms, ten times faster, because only a sixteenth of the gradient crosses the slow link. This is the shape of HSDP, and the reason the FSDP guide says to replicate across DCN and shard within each slice. It is a bound from a simple ring model, not a measured algorithm.

Problem 5. A training loop all-reduces a 32 KiB tensor of metrics every step on a 16-rank ring with wraparound. What does the bandwidth term predict, what does the latency term predict, and what would you change?

Answer

Bandwidth: \(2 \times 32{,}768 \times 15 / (2 \times 16 \times 90 \times 10^9) \approx 0.34\) µs. Latency: an all-reduce on a 16-ring with wraparound takes \(2 \times \lceil 15/2 \rceil = 16\) hops at about 1 µs, so about 16 µs, fifty times the bandwidth term. It is latency-bound, and splitting it into several small all-reduces multiplies the cost. Concatenate the metrics into one tensor, reduce them less often, or reduce them together with the gradients. And never read the result with .item() inside the step: that is a host sync (chapter 4).

Problem 6. This step hangs on 8 ranks. Explain why from TorchTPU's execution model, and fix it.

@torch.compile
@torch.tpu.distributed.spmd_safe
def step(x, w):
    y = x @ w
    dist.all_reduce(y)
    if dist.get_rank() == 0:
        stats = y.float().pow(2).mean()
        dist.all_reduce(stats)
    return y
Answer

@spmd_safe promises that every rank issues the same operations and collectives in the same order, so TorchTPU fuses the collectives into the compiled module. Rank 0's module has two all-reduces and the others' have one: the ranks run different StableHLO programs, and the second collective on rank 0 has no partners, the deadlock the guide warns about. Fix: compute and reduce stats on every rank (remove the branch; only print on rank 0, outside the step), or move the rank-dependent code out of the decorated function. Without @spmd_safe, the collective would be skinny but rank 0 would still wait for partners that never call it: a collective must be called by every rank of its group.

Problem 7. On a v6e slice, a trace shows an all-gather of a 256 MiB per-rank output over an 8-device group taking 3.1 ms. Compare it with the model and say whether anything is wrong.

Answer

With wraparound: \(2^{28} \times 7 / (2 \times 8 \times 90 \times 10^9) = 1.30\) ms; measured is 2.4 times slower. But an axis of 8 v6e chips has no wraparound link (v6e wraps only on a full 16-chip axis), so the right model is one way: 2.61 ms. 3.1 ms is 84% of that model's speed, in line with the scaling book's measured fraction. Nothing is wrong with the layout; to go faster, gather over more axes at once or put this dimension on a full 16-chip axis.

Quick questions

  1. What do Shard(0), Replicate() and Partial() mean on one mesh axis, and how does the scaling book write each?
  2. Which redistribution costs no communication, and which costs twice an all-gather?
  3. Name the three differences TorchTPU's guide lists between its tpu_dist backend and a GPU backend.
  4. What is a skinny collective, why is it the default, and what does it cost?
  5. When would you choose COMPILE_STAGE over DISPATCH_STAGE?
  6. Why does an all-gather's time barely depend on the number of ranks, and when does it start to?
  7. Why is an all-to-all cheaper than an all-gather of the same array on a ring?
  8. In what order should mesh dimensions be listed for topology_aware_mesh, and what happens to the outermost one on a multi-slice job?
  9. Which variables must be set before TorchTPU workers start, and what sets them?
  10. A collective takes twice the model's time; another takes thirty times. What do you suspect in each case?

Key takeaways

  • A DeviceMesh names process groups on logical axes; a DTensor placement says how a tensor sits on each. Moving from Shard to Replicate is an all-gather, Partial to Shard a reduce-scatter, Partial to Replicate an all-reduce, Shard to another Shard an all-to-all, and Replicate to Shard is free.
  • TorchTPU's "tpu_dist" backend compiles collectives into the TPU program as StableHLO ops with global replica groups; there is no NCCL. The topology must be in the environment before workers start, and every rank must run the same collectives, or the job hangs.
  • Collectives run as skinny modules by default, safe but not overlapped. Compile the whole step and use @torch.tpu.distributed.spmd_safe or TORCH_TPU_SPMD_HANDSHAKE_STAGE to let XLA overlap them with compute.
  • On a ring with wraparound, an all-gather or reduce-scatter of \(V\) bytes takes \(V(n-1)/(2nW)\), an all-reduce twice that, and an all-to-all about a quarter of an all-gather of the same array. Below about 1.5 MB the 1 µs hops dominate. Without wraparound, double it; over DCN, use the chip's egress.
  • Order mesh dimensions from least to most communication-intensive and take the rank layout from topology_aware_mesh; across slices its outermost dimension crosses DCN, so make that data parallelism and shard within each slice.
  • Launch with eval $(python3 -m torch.tpu.distributed | sed 's/^/export /') and torchrun on one host, or the --nnodes and --node_rank form on several; rehearse the logic on CPU with gloo.
  • Trust a distributed run when its collectives in XProf take about what the cost model predicts, and when its measured scaling efficiency matches the efficiency the model predicted. Chapter 14 applies all of this to FSDP and TorchTitan.

References