shard_map), what each parallelism strategy compiles to, collective costs checked against the compiler, choosing a mesh for a TPU slice, and multi-host runs. Measured on an Apple M1 Pro CPU with 8 simulated devices (jax 0.11.2); TPU numbers are published ones, kept apart. Data as of October 2026. Reading: 45 min, plus 26 in closed details.In JAX you write the step for one device and give a few arrays a layout over a named grid of devices; someone then lays out every other array (the compiler's propagation, the type system, or you inside shard_map), and the communication is whatever those layouts force. Communication is a consequence of layout, so you read it off the compiled program, never off the Python.
Fig. 1, step by step: three annotations in, one program per device out
jax.make_mesh((2, 4), ('data', 'model')) arranges 8 devices as a grid with named axes: 2 along data, 4 along model. Nothing in the model code mentions devices.P('data', 'model'): rows split by data, columns by model; each device holds one (64, 128) block, 32,768 bytes, as jax.debug.visualize_array_sharding printed here.P('data', None) is split by rows only, so the 4 devices of a data row hold the same 16 rows: an axis a spec does not name holds copies.data, between the two devices of each column. The compiled FSDP x tensor step of section 6 does exactly this: 28 of its 29 forward all-gathers run in groups of 2, the pairs along data.P('data', 'model') with no further traffic. The SPMD partitioner wrote that per-device program and its collectives; you read them in jit(f).lower(...).compile().as_text().mesh = jax.make_mesh((2, 4), ('data', 'model'))
w = jax.device_put(w, NamedSharding(mesh, P('data', 'model')))
x = jax.device_put(x, NamedSharding(mesh, P('data', None)))
loss, grads = jax.jit(step)(w, x)
Who is "someone" is set per mesh axis, by its axis type:
shard_mapPer-device code; you call psum, all_gather, ppermute (section 5).You know how PyTorch spreads a model over GPUs: you pick a wrapper (DDP, FSDP2, a tensor-parallel plan) or a DTensor placement, and it owns the communication. JAX works the other way round: change one PartitionSpec and a different set of collectives appears in the compiled program, while the Python code does not change.
You need JAX core (jit, tracing, vmap), the parallelism forms from Distributed Training (this page shows only JAX's API and behaviour for each), and HLO dumps from XLA and compilation.
measured means run here on an Apple M1 Pro CPU with 8 simulated devices (XLA_FLAGS=--xla_force_host_platform_device_count=8, jax 0.11.2): the compiled programs, the collectives and their sizes, the memory figures and the losses are real and deterministic; speeds are not (a "collective" between simulated devices is a memory copy). TPU numbers are published by Google; arithmetic on them is derived. Fig. 1 draws this run's shapes and specs; sizes on the stage are not to scale.
PNone means not split.device_put and jit take.shard_mapWhat each device keeps and what crosses the wires, per strategy. Bytes are the compiler's own (logical bytes summed over one train step: an all-gather's output, a reduce-scatter's input, an all-reduce's operand), on the running example scaled up to 25.4M parameters (d_model 512, 8 layers, 4,096 tokens per step, float32), 8 devices.
| Strategy | What is split | The JAX way | Collectives per step | Params + Adam per device | PyTorch |
|---|
Collectives and bytes: measured, compile().as_text() of the full train step (forward, backward, clipping, AdamW), src/runs/ss_scale.py. CPU caveat: XLA's CPU pipeline has no pass that turns an all-reduce followed by a slice into a reduce-scatter, so FSDP's gradient reduce-scatter shows up as an all-reduce here; on TPU and GPU it would be a reduce-scatter of the same size. For data parallel, FSDP, HSDP and tensor parallel, a two-line formula predicts these byte counts (section 10), which is what makes a mesh designable on paper before you rent a slice.
The objects. jax.make_mesh((2, 4), ('data', 'model')) () arranges the 8 devices as a 2 × 4 grid with named axes. A PartitionSpec says, for each dimension of an array, which mesh axes split it; a mesh axis the spec does not name holds copies. A NamedSharding(mesh, spec) joins the two. Take the running example's first MLP weight, fc1, [128, 512] in float32 (262,144 bytes), and change only its spec (the widget on the right):
The rule (derived from the definition, and matching what visualize_array_sharding printed for P('data', 'model'): (64, 128) per device): the size each device holds along dimension i is sizei divided by the product of the sizes of the mesh axes named for i; every element is held by as many devices as the product of the axes named nowhere. A tuple such as ('data', 'model') splits one dimension over both axes, data major. An axis may appear only once per spec: P('data', 'data') is refused because the spec "has duplicate entries" ().
Where shardings enter a program. jax.device_put(x, NamedSharding(mesh, spec)) places an array. jax.jit(f, in_shardings=..., out_shardings=...) fixes the layout of a function's inputs and outputs (the multi-host run in section 12 uses in_shardings=(rep, rep, xs, xs)); without them, jit takes the layouts its arguments already have. Inside, jax.lax.with_sharding_constraint(y, spec) () pins one intermediate. Every other array is left to whoever decides layouts along each mesh axis (section 2). JAX turns a NamedSharding into GSPMD's or Shardy's own notation (, ) when it hands the program to XLA.
Predict before you click P(None, 'model'): how many devices hold each block of the weight?
The problem. A train step creates hundreds of intermediate arrays (activations, gradients, optimizer updates). You annotate a handful: the parameters, the batch. Every other array needs a sharding too (which device holds which piece), and every place where an operation needs its inputs laid out differently from how they are is a collective. Something has to fill in the rest.
How JAX answers. Each named axis of a Mesh has an axis type (jax.sharding.AxisType), and the type says who decides along that axis (the hero's third panel):
| Axis type | Who decides intermediate shardings | What you see while tracing | When something is ambiguous | Closest PyTorch |
|---|---|---|---|---|
| Auto | The compiler: sharding propagation (Shardy, formerly GSPMD), after tracing, inside XLA | Nothing: jax.typeof(x) shows no sharding | The compiler picks something, possibly an expensive collective, silently | None for whole programs: DTensor decides operator by operator at run time |
| Explicit | JAX's sharding rules, operation by operation, while tracing; the sharding is part of the type | float32[32@data,512@model] | A ShardingTypeError at trace time, asking for out_sharding= | DTensor's per-operator placement rules, but checked at trace time |
| Manual | You: inside jax.shard_map each device runs your code on its own shard and you call the collectives | Per-device shapes | Nothing is ambiguous: you wrote every byte that moves | Rank-view code with torch.distributed collectives |
Run here (measured, src/runs/ss_debug.py): on an Explicit (2, 4) mesh, jax.typeof of the fc1 weight split by columns, a batch split by rows, and their product:
The same matmul on Auto axes prints float32[32,512]: the layout exists only in the compiler. Two defaults matter and changed recently. jax.make_mesh creates Explicit axes unless told otherwise (), so code from older tutorials fails at its first ambiguous op; pass axis_types=(AxisType.Auto,) * n to keep Auto behaviour. The jax.sharding.Mesh constructor still defaults to Auto, and the propagator behind Auto axes is Shardy, chosen by the flag jax_use_shardy_partitioner, default True (). The modes mix: jax.sharding.auto_axes and explicit_axes switch some axes inside one function (), and shard_map makes the axes it maps Manual inside its body while the rest of the program stays as it was.
shard_mode: "auto" # can be either auto or explicit, ). Explicit when you want every layout decision visible and checked, and accept writing out_sharding= in the places JAX asks. Manual for patterns no propagator invents: ring attention, pipelines, custom MoE dispatch, overlapping a collective with compute.The problem. Assigning a layout to every array so that total communication is smallest is a search over an exponential space; production compilers do not solve it. Both of XLA's propagators are heuristics that spread your annotations through the program and never invent a new split you did not ask for. Knowing their rules is how you predict where they will go wrong. Fig. 3 follows one through the MLP of a transformer block of the running example under Megatron's layout, every sharding read from the HLO that XLA dumped right after its propagation pass (Shardy, the default):
P('data', None, None), and Megatron's weights carry their own: fc1 [128, 512] P(None, 'model') (column-parallel), fc2 [512, 128] P('model', None) (row-parallel). Every other array has no sharding yet (dashed).(i, k), (k, j) -> (i, j): the row factor i brings data from x, the column factor j brings model from fc1. h [32, 128, 512] gets P(data, -, model), as the dump shows at model_jax.py:51: each device computes its (16, 128, 128) block with no communication.model_jax.py:68 come out P(data, -, model).model in both operands, so each device multiplies its 128 columns by its 128 rows of fc2 and holds a full-size [16, 128, 128] partial sum: the four devices of a data row each hold a quarter of the answer.model is an all-reduce among the 4 devices of each data row: 1,048,576 bytes per device ([16, 128, 128] in float32). Attention's output projection is row-parallel too, so the block's forward pass has exactly 2 all-reduces, 2,097,152 bytes, both at model_jax.py:51, and no other collective.Both propagators hand their result to the same SPMD partitioner, which rewrites the program per device and inserts the collectives: XLA's CPU pipeline adds either sdy::ShardyXLA () or ShardingPropagation (), then StatefulRngSpmdPartitioner.
| GSPMD (Xu et al. 2021) | Shardy (JAX's default since 0.7.0) | |
|---|---|---|
| A sharding is | a tile assignment over a device list (HloSharding) | mesh axes per dimension, like a PartitionSpec; each dimension open (more axes may be added) or closed |
| Through one op | preserved dimensions pass through; a matmul merges its operands' splits when they use different axes | one einsum-like sharding rule per op, a matmul being (i, k), (k, j) -> (i, j); axes move along factors |
| Order and conflicts | forward and backward passes to a fixed point, only ever refining; elementwise ops first, dot later | nested strategies: user priorities, op priorities, aggressive (resolves conflicts), basic |
| Never | invents a split you did not ask for. The remedy both leave you: annotate the output (with_sharding_constraint, or Explicit mode) | |
The design is in Xu et al., GSPMD, arXiv 2105.04663, section 3.5 (v2, December 2021). Its rules, in order of importance:
AyB times BCx gives AyCx).The paper is explicit about the limit: "We decided to keep the sharding propagation simple, so it does not try to create new sharding patterns on dimensions. The propagation result may not always be optimal", and the remedy it gives is the one you will use: "the user can explicitly annotate the output to precisely control the sharding decision."
Shardy is the MLIR-based successor that JAX switched to by default in 0.7.0 ("JAX is migrating from GSPMD to Shardy by default"). The Shardy propagation doc and sharding representation doc (both read 2026-10-15) describe three differences:
PartitionSpec; GSPMD's HloSharding is a tile assignment over a device list. A dimension can be open (?: "open for propagation to further shard it along additional axes") or closed.(i, k), (k, j) -> (i, j); reshapes use compound factors such as ((ij), k). "Shardy propagates sharding axes along factors instead of dimensions": project the operands' shardings onto factors, merge, project back.{"x"}p1), then operation priorities ("pass-through" ops such as elementwise and reshape first, dot and reduce later, the same idea as GSPMD's), then aggressive propagation (resolves conflicts), then basic propagation ("propagates axes that are compatible between all operands and results", no conflict resolution). Loops, conditionals and shard_map regions are crossed through "data flow edges".src/runs/ss_prop.py compiles loss = mean(block(x)2) and its gradient with XLA_FLAGS=--xla_dump_hlo_pass_re=shardy-xla|sharding-propagation, once with Shardy (the default) and once with jax_use_shardy_partitioner=False (GSPMD); src/runs/ss_hlo.py reads each instruction's sharding (converting both notations to P(...) over the mesh) and the Python line it came from. Operations are grouped by source line and kind; the largest instance stands for the group. jax 0.11.2, 8 simulated CPU devices, Auto axes.
Dump the program right after propagation with XLA_FLAGS="--xla_dump_to=DIR --xla_dump_hlo_pass_re=shardy-xla|sharding-propagation". The same tensor (the running example's q = x @ wq under Megatron tensor parallelism on a (data 2, model 4) mesh) in the two notations, pasted from the dumps:
# Shardy: per dimension, the mesh axes that split it dot(...), sharding={mesh['data'=2,'model'=4], [{'data'}, {}, {'model'}]} # GSPMD: a tile grid [2,1,4] over devices 0..7 in order (iota) dot(...), sharding={devices=[2,1,4]<=[8]}
Both say P('data', None, 'model'). A GSPMD sharding with last_tile_dim_replicate adds a final grid dimension of copies (devices=[2,1,1,4]<=[8] last_tile_dim_replicate is P('data', None, None) replicated over the 4 model devices). Turning Shardy off in jax 0.11.2 still works and prints a warning, pasted from the run: GSPMD sharding propagation is going to be deprecated and not supported in the future. Please consider migrating to Shardy (https://openxla.org/shardy). For reference, Shardy is already the default partitioner in JAX.
measured On one transformer block (forward and backward), five annotation cases, both propagators agree on every one of the 94 operation groups except a few small ones (the causal mask, a bias gradient) that Shardy leaves unannotated and GSPMD marks replicated, which means the same thing; and they insert identical collectives. On the whole train step they do not:
In counts: the same tensor-parallel train step compiled to 18 collectives under Shardy and 167 under GSPMD, and the unconstrained FSDP step to 210 under Shardy and 148 under GSPMD. Where they come from, line by line:
On the block alone the two propagators agree; on the whole step they diverge where the program has freedom: small replicated tensors and elementwise optimizer math that could be split over an idle axis, or activations whose layout nothing pins down. The lesson is not that one propagator is better: on the unconstrained FSDP layout GSPMD was the better one. It is that a layout that depends on propagation for the activations is fragile. The root lab's FSDP layout with one with_sharding_constraint on the residual stream per block compiles to the same collectives under both (78 all-gathers and 70 all-reduces each). Constrain activations at block boundaries, as MaxText does through its logical axis rules.
The root lab's layouts, full train step (forward, backward, clipping, AdamW), collectives grouped by the Python line they came from. Bars: bytes (summed result sizes) per line, Shardy above GSPMD.
The widget on the right replays every operation group of the same block, forward and backward, for five annotation cases and both propagators: Megatron's layout of Fig. 3, FSDP with only the weights annotated, FSDP plus one constraint on the residual stream, a sequence split, and a conflict (x arrives with its features split on the weights' axis). It opens with everything assigned; step back to step 0, where only your annotations (green) have a sharding, and forward in program order. The dump records the result, not the propagator's visiting order.
measured post-propagation HLO dumps, jax 0.11.2, 8 simulated CPU devices, Auto axes; how they were made is in the closed block above.
Highlighted rows: the two propagators chose differently. "none" means the propagator left the operation unannotated (the partitioner then replicates it). Per-device shape follows from the sharding and the mesh. The case is the one chosen in the stepper above.
| Line | Op | Phase | Shape | Shardy | GSPMD | Per device (Shardy) | Source (model_jax.py) |
|---|
The problem it solves. In Auto mode a bad layout costs you nothing at trace time and a lot at run time: the compiler quietly inserts whatever collective makes the program correct. Explicit mode moves the decision to trace time. Each operation has a rule mapping input shardings to an output sharding; when the rule cannot decide, or would need communication you did not ask for, tracing stops with a ShardingTypeError. The JAX guide states the intent: the rules "prefer to error and require annotation rather than falling back to arbitrarily chosen defaults", to "get important parallelism decisions in your face, rather than hide them" (JAX docs, Distributed arrays and automatic parallelization, read 2026-10-15).
What it costs, measured. The running example's loss and gradient, traced on an Explicit mesh exactly as written for Auto mode, then with the smallest change each error asks for. Step through the attempts for each layout; every message is pasted from the run (src/runs/ss_explicit.py, the forward is model_jax.apply written out with hooks).
Three lessons from the ladder. First, even plain data parallelism needs one annotation: the embedding lookup tok_emb[idx] is a gather whose output layout JAX will not guess, so you write tok_emb.at[idx].get(out_sharding=P('data', None, None)) (). Second, FSDP in Explicit mode is literally written out: jax.reshard(w, P()) before each use is the all-gather, and the gradient comes back with the weight's own sharding (float32[128@data,512]), because the transpose of a reshard is a reshard. Adding arrays split on the same axis along different dimensions is refused for the same reason, with the same fix. Third, Megatron's row-parallel matmul is the textbook ambiguous case: both operands are split along the summed dimension, so the result is a partial sum on every device, and you must say whether you want it summed and where (jnp.einsum(..., out_sharding=P('data', None, None)), ). After the fixes, data parallel compiles to the same single all-reduce of 3,305,476 bytes as the root lab's Auto-mode layout, tensor parallel to 17 all-reduces (loss and gradient only, no optimizer here), and every loss is within 4.8e-7 of one device.
JAX also has unreduced types, where "the logical value equals the distributed sum of the physical shards' values along that axis", for delaying a reduction (shown as f32[8,16]{U:X} in the guide). Not run here: the guide marks the details as still to come.
When no layout rule gives the communication you want, you write it. jax.shard_map(f, mesh=mesh, in_specs=..., out_specs=...) () cuts each input by its spec, runs f once per device on the local block, and assembles the outputs by out_specs. Inside f shapes are per device and the mapped axes are Manual: nothing crosses a wire unless you call a collective, by axis name.
Fig. 5, step by step: the shape of every shard_map
data. in_specs=P('data') names how to cut it: by rows, over data.in_specs=P('data') each call of f sees [4, 128], rows 4d to 4d + 3 (the shard shape the multi-host run in section 12 recorded). Nothing else is copied.f runs once per device on its local block. Shapes inside are per device, and jax.lax.axis_index('data') is this device's coordinate (3 for the device in view). The body computes a partial result g of its own.jax.lax.psum(g, 'data') is an all-reduce over the 8 devices of the data axis: the only bytes that move are the ones the psum names.jax.lax.psum(g, 'data') leaves the same sum on every device, so out_specs=P() (replicated) is correct; a per-device result would use out_specs=P('data') and be stacked back into one array.illustrative body; the shapes are the measured ones.
The collectives you call, and what they compile to (the names the rest of this page counts in compiled programs):
JAX call, inside shard_map | HLO op | What happens | Used on this page |
|---|---|---|---|
jax.lax.psum(x, 'ax') | all-reduce | every device ends with the sum over the axis | the pipeline hands its output to every stage (section 8) |
jax.lax.all_gather(x, 'ax', tiled=True) () | all-gather | every device ends with all the blocks, concatenated | all-gather context parallelism (section 7) |
jax.lax.psum_scatter(x, 'ax') () | reduce-scatter | sum over the axis, each device keeps 1/n of it | appears as the transpose of all_gather in the backward pass |
jax.lax.all_to_all(x, 'ax', split_axis, concat_axis, tiled=True) () | all-to-all | slice e of every device goes to device e | MoE dispatch and combine (section 9) |
jax.lax.ppermute(x, 'ax', perm) () | collective-permute | each device sends to the one perm names: a ring step | ring attention, pipeline stages (sections 7, 8) |
jax.lax.axis_index('ax') | none | this device's coordinate on the axis | one program serves every pipeline stage |
Two compiler facts measured on this page: jax.grad transposes all_gather into psum_scatter, so the backward of hand-written all-gather attention holds a true reduce-scatter even on CPU (section 7), and it transposes each all_to_all into another all-to-all (section 9). What each collective costs on the wire (ring, torus, tree) is Interconnects and scaling's subject; section 10 checks the byte counts JAX produces.
The framework-free theory of each strategy (why it exists, its memory and traffic in the abstract) is taught on Distributed Training (data parallelism in section 3, ZeRO and FSDP in section 4, tensor parallelism in section 5); the PyTorch implementations on Distributed PyTorch; the ZeRO stages step by step on the ZeRO paper page; Megatron's split on the Megatron-LM paper page. Here: what XLA produced for each, on the running example (826,368 parameters, the root lab's setup) and on the same model scaled up (25,417,728 parameters: d_model 512, 8 layers, 8 heads, MLP 2,048, context 256, batch 16; seeded initialisation), the full train step on 8 devices. Every layout's loss stays within 4.8e-7 of one device over 3 steps.
AllReduceCombiner merged every gradient into one collective. Each device still holds all parameters and Adam state: 305 MB of 305 MB.AllReduceReassociate pass, which merges the q, k and v input-gradient all-reduces into one, runs in the GPU pipeline and not the CPU one (). Bytes grow with batch and sequence, not with parameters: 227 MB at 25.4M parameters against 102 MB for data parallel.. The partitioner could not move an activation from one layout to the other directly, so it replicated it and re-split it. A warning like this is a performance bug report; the fix is a with_sharding_constraint that names the layout you want at that point.PyTorch FSDP2 makes the same choice explicit: fully_shard(reshard_after_forward=None), the default in torch 2.14.1, re-gathers in backward for every module except the root ("set to True for non-root modules and False for root modules", torch/distributed/fsdp/_fully_shard/_fully_shard.py:189).
The problem. At long context the activations of one sequence no longer fit on one device, and splitting the batch does not help when the batch is one sequence. Context parallelism splits the sequence itself: device d holds tokens dT/N to (d+1)T/N − 1 of every sequence. Everything except attention is per-token and needs no communication. Attention needs every query to meet every earlier key. The three traffic patterns and the causal load balancing are Distributed Training's section 8; here, what JAX compiles for each.
Three ways, run here. The running example's block-0 attention (q, k and v [32, 4 heads, 128 tokens, 32], real weights, causal) with the 128 tokens split 16 per device over 8 devices (src/runs/ss_cp.py):
shard_map: gather K and V, attend your own queries with the causal mask shifted by your offset. This is the variant Llama 3 used (Llama 3 paper, arXiv 2407.21783, section 3.3.2) and MaxText's default (context_parallel_strategy: "all_gather", ).ppermute, N steps, accumulating an online softmax (running max, denominator and numerator), so no device ever holds all keys or a full score matrix.The schedule, step by step
ppermute: one K and one V block, 262,144 bytes each.jax.shard_map over the seq axis)What the numbers say. All three give the one-device result (largest difference 7.5e-8 for the ring; gradients within 2.9e-6 for all three). Per device the ring sends exactly what a ring all-gather of K and V would (7 blocks of each: 3,670,016 bytes, against the all-gather's 4,194,304-byte output of which 7/8 arrives from other devices). The gain is memory: at 8,192 tokens the compiled temp memory is 123 MB per device for the ring against 273 MB for the all-gather version, because nobody holds all keys and values. The cost is N sequential steps, each needing its transfer to overlap with compute. The schedule also shows the known flaw of a plain causal ring: device 0 has work in 1 of 8 steps and device 7 in all 8. Load-balanced orderings (each device holds a chunk from the start and one from the end of the sequence) fix that; MaxText's context_parallel_load_balance: true is the default (). Not run here: the load-balanced ordering, and DeepSpeed-Ulysses, which uses all-to-all to swap the sequence split for a head split (arXiv 2309.14509; MaxText's "ulysses" option).
Megatron's sequence parallelism (Korthikanti et al. 2022, arXiv 2205.05198) is a different thing despite the name: inside a tensor-parallel group it splits the LayerNorm and dropout activations along the sequence, turning each all-reduce into a reduce-scatter plus an all-gather of the same total size. On CPU the reduce-scatter cannot be formed (no ReduceScatterCreator in the pipeline), so it is not shown separately here.
Each column is one loop iteration of stage_fn; a cell is what that stage computes (microbatch m, repeat r for circular runs); grey cells are bubble ticks, which compute on zeros and are discarded. Arrows are the ppermute at the end of the tick. Backward: the same grid right to left. measured src/runs/ss_pipe.py, the running example's 4 blocks over 4 or 2 stages: loss within 4.8e-7 and every gradient within 1.2e-7 of one device; the bubble is exactly (S−1)/(MR+S−1), 3/7 for 4 stages and 4 microbatches, 1/9 for MaxText's circular schedule with 2 stages, 2 repeats and 4 microbatches.
A pipeline gives each group of devices a run of consecutive layers (a stage) and streams microbatches through them; stages idle at the start and the end, the bubble. The theory and the GPU schedules (1F1B, interleaved, zero bubble, DualPipe) are Distributed Training's section 6 and the Distributed PyTorch page's section 8 (pipelining: stages and schedules); this section is how JAX does it.
No propagator invents a pipeline: it is a loop over time. The GSPMD paper reduced it to sharding (section 3.3): keep a buffer with one slot per stage, run every stage's layer at once with vmap, and shift the buffer by one each iteration; shard the stage dimension and "GSPMD will turn the buffer shifting into cross-device communication via CollectivePermute". MaxText's pipeline is this design: a jax.vmap over stages () and shard_map rotations with ppermute over the stage axis (). The version run here writes the per-device loop directly in shard_map, which is easier to read, and lets jax.grad differentiate the whole loop: the backward pass is the forward schedule run in reverse (GPipe's order: all forwards, then all backwards).
Three details carry the design. The stage index comes from jax.lax.axis_index("stage"), so one program serves every stage: whether a device reads a new microbatch or the buffer is a jnp.where, not Python control flow. rot sends stage j's output to j+1 and the last stage's back to stage 0: for circular schedules that is the path to the next repeat (stage 0 keeps it in circ until its turn). And the result is handed to every stage with a psum over stage of the last stage's outputs, an all-reduce you could avoid by computing the loss on the last stage only.
Circular schedules: why repeats shrink the bubble. With R repeats each stage holds R non-consecutive blocks of layers (stage 0 of 2: layers 0 and 2; stage 1: layers 1 and 3) and every microbatch goes round the ring R times. A tick now costs 1/R of a GPipe tick, and the S−1 bubble ticks are 1/R as long: on the running example, 2 stages with 4 microbatches, the bubble falls from 1/5 (GPipe, ticks of 2 layers) to 1/9 (circular, ticks of 1 layer). The price is R times as many transfers (16 collective-permutes against 8) and a ring back from the last stage to the first.
The schedule, tick by tick (the run chosen above the chart)
| Schedule | Stages S | Micro-batches M | Repeats R | Layers per stage | Ticks | Bubble | Collectives (forward + backward) | Loss / gradient vs one device | Temp per device |
|---|
measured batch 0 of the running example (32 sequences, so a microbatch is 32/M sequences), mesh (stage S, data 8/S), Auto axes, jax 0.11.2. Bubble = idle stage-ticks / all stage-ticks in the forward schedule, which equals the formula (S−1)/(MR+S−1) exactly in every run, the same formula MaxText's config states: (). Collective-permutes: one forward per tick except the last, and the same number backward.
Per device (inside jax.shard_map over the mesh axes stage and data); layers holds only this stage's blocks, stacked, and x all microbatches of this device's data shard:
MaxText's config notes the trade-off: more layers per stage "the easier it is to hide the pipeline communication behind the compute", more repeats a smaller bubble. With M = S (the 2-microbatch run) the circular schedule needs no storage at stage 0: the last stage's output arrives exactly when stage 0 needs it.
Not run here: 1F1B or zero-bubble orderings, which need the backward of each microbatch scheduled by hand (for example with jax.vjp per stage) instead of differentiating the whole loop; and timing, which on simulated CPU devices would mean nothing.
Cell (device g, expert e): tokens on device g that chose expert e (the real router output); filled part: tokens that fit in the capacity C and are sent; hatched: dropped.
In a mixture-of-experts layer each token goes to a few of many expert MLPs (the form is Distributed Training's section 7). Put one expert per device and tokens must travel to their experts and back: two all-to-alls per layer. Routing is data-dependent, so propagation finds that pattern only sometimes; here it is written with shard_map.
The setup (src/runs/ss_moe.py): the 4,096 tokens of the running example's batch 0, taken after block 0 and the next LayerNorm ([4,096, 128]), 512 on each of 8 devices; a router [128, 8] and 8 expert MLPs (128 → 256 → 128, exact GELU), one per device. The router and experts are new seeded weights, illustrative, not trained: the routing is lopsided (expert 6 is wanted by 120 to 150 of each device's 512 tokens, expert 1 by 21 to 35), which makes capacity visible. Each device routes its own tokens (Switch Transformer's groups); capacity C = ⌈capacity factor × 512 × k / 8⌉ tokens per expert per device; tokens over capacity are dropped (the layer outputs 0 for them, the residual stream carries them). Top-1 is Switch's routing (Switch Transformers paper page), top-2 GShard's and Mixtral's (Mixtral paper page).
One MoE layer, step by step (the routing and capacity chosen above the chart)
all_to_all(x, axis, split_axis=0, concat_axis=0, tiled=True) cuts this device's [8, C, 128] block along the expert dimension, sends slice e to device e, and stacks what arrives along the same dimension: afterwards dimension 0 means "which device it came from". The second all-to-all is the exact inverse. The backward pass transposes each all-to-all into another all-to-all (3 in the compiled gradient program, plus a small all-reduce for the router's replicated weights).
Hand-written against propagation. Written with two all_to_all calls the layer compiles to exactly 2 all-to-alls forward and 3 in the backward, in all six configurations. Written as GShard-style einsums for one device, with the groups and the experts annotated P('expert') and a with_sharding_constraint on the dispatched tensor and the expert outputs, and left to propagation, it used all-to-all in only 1 of 6 configurations; in the other 5 the compiler chose all-gathers and an all-reduce instead. Same numbers, different traffic.
Production code drops the fixed capacity. Padding every expert to C wastes compute and drops tokens. MaxText's default is capacity_factor: -1.0 # ... no dropping by default () and it sends exactly the tokens each expert needs with jax.lax.ragged_all_to_all (; the primitive at ), then runs the experts as one grouped matmul (megablox).
| Routing | Capacity factor | C | Dropped | shard_map: forward / backward | Propagation: forward / backward | Error vs one device |
|---|
measured jax 0.11.2, 8 simulated CPU devices. Error: output / gradients against a one-device reference with the same routing and drops.
Memory and traffic of MoE training at scale are on the MoE memory bottlenecks paper page.
The useful test of a cost model is whether it predicts the compiled program. Two-line predictions for each layout (src/runs/ss_formulas.py; P is the parameter bytes, L the layers, A one [batch per data group, sequence, d_model] activation), against the bytes XLA actually emitted at both model sizes:
| Model | Layout | Formula (CPU form) | Predicted | Compiled | Ratio |
|---|
Bytes are logical bytes per train step (see the first table). On TPU or GPU two terms change: FSDP's gradient all-reduce becomes a reduce-scatter of the same logical size, and tensor parallelism's backward has 2LA instead of 4LA. The one miss, tensor parallel over 8 devices on the 4-head running example, is the heads problem from the previous section; with 8 heads the prediction is exact.
Bytes become time through the link: for large messages a ring all-gather over a TPU axis takes about V / W whatever the number of devices, and an all-reduce about twice that; for small ones a per-hop latency dominates. The algorithms behind those two sentences are Interconnects and scaling's section 7: the latency and bandwidth model (about 1 µs per ICI hop), ring against 2-D torus against double binary tree in the scaling book's TPU forms, and an all-reduce time calculator, flat while latency dominates and then rising with the bytes.
The question. Given a model, a global batch and a slice (say 256 v5e chips or 512 v5p chips), how many ways to split for each strategy, and which physical torus axes should carry which? Three constraints decide it.
create_device_mesh on mock slices: on a v5p 4x4x4 cube, a (16, 4) mesh puts the 4 on one physical axis (1 hop) and the 16 on the other two (2 hops between logical neighbours), while (8, 8) is refused outright with unless you allow splitting physical axes.Across slices the network is the data-centre network (DCN), about 6.25 GB/s per chip in the book's v5p numbers, so the batch per slice must exceed C/Wdcn ≈ 73,440 tokens; the standard answer is FSDP and tensor parallelism inside the slice and pure data parallelism (or HSDP) across slices. MaxText encodes exactly this: 12 mesh axes (), each with an ici_*_parallelism and a dcn_*_parallelism degree, defaults ici_fsdp_parallelism: -1 # recommended ICI axis to be auto-sharded and dcn_data_parallelism: -1, and comments marking dcn_tensor_parallelism "never recommended" (). Model code never names a mesh axis: it names logical axes ('embed', 'heads', 'activation_batch_attn'), and logical_axis_rules () map them to mesh axes, so one config change re-lays out the whole model.
The model. A TPU slice larger than one host (one VM with a few chips attached) runs one Python process per host, all executing the same script: JAX is multi-controller. The JAX guide: "All processes (usually) run the same Python script", and "it's crucial that all processes with participating devices run the same computation in the same order", a rule that is "mostly unchecked", so a mismatch hangs (JAX docs, multi-controller JAX, read 2026-10-15). The PyTorch picture is close: torchrun starts one process per GPU and you call init_process_group; JAX starts one process per host and you call jax.distributed.initialize() (), which on Cloud TPU, Slurm or Kubernetes needs no arguments. After it, jax.devices() lists every chip of every host (the global devices) and jax.local_devices() this host's (also called addressable). A jitted function over a global array is still one SPMD program; the difference from one host is only that a process can touch the shards on its own devices and nothing else.
Run here. JAX runs the same thing on CPU with several processes on one machine, so this page does it for real: 2 processes, each owning 4 simulated devices, connected by jax.distributed over localhost (collectives between processes use gloo, the default CPU implementation, ). Each process loads only its 16 of the batch's 32 rows and builds the global batch with jax.make_array_from_process_local_data (), then both run the running example's data-parallel train step for 20 steps. measured
jax.distributed.initialize(coordinator_address=..., num_processes=2, process_id=i). Now jax.devices() lists all 8 in both processes (0, 1, 2, 3, 2048, 2049, 2050, 2051: process 1's devices got ids from 2048, as observed here), jax.local_devices() only its own 4. Both build the same mesh over all 8.make_array_from_process_local_data with the P('data', None) sharding and its own rows. The result is one global [32, 128] array; each process can touch only its own 4 shards of [4, 128].jax.devices() is local; every shard is addressable.device_puts them with P('data', None): 4 rows per device.Both pasted from the run: reading a global array in one process fails on purpose, and hosts passing different values for a replicated array both stop at device_put.
make_array_from_process_local_data assembles the global array without communication. Deterministic, checkpointable per-host loading with grain is on the training stack page. So is resuming a sharded checkpoint: restore is exact on any layout, but training continues bit for bit only from the shardings the state had when saved, because after one compiled step the compiler had re-sharded 81 of the 210 parameter and optimiser leaves (its section 5).jax.process_index() == 0 is fine; putting a device_put or a jitted call under that condition is not: the guide warns it "would lead to a deadlock as only process 0 initiates the collective communication".dcn_*_parallelism settings put data parallelism there (section 11).then, per step, the process builds the global batch from its own rows:
and calls the same jitted step as on one host (jax.jit(step, in_shardings=(rep, rep, xs, xs), out_shardings=(rep, rep, rep), donate_argnums=(0, 1)), data parallel over a mesh of all 8 global devices).
| Process 0 | Process 1 |
|---|
Single controller. Google's own Gemini runs used the other model, a single controller: "the 'single controller' programming model of Jax and Pathways allows a single Python process to orchestrate the entire training run" (Gemini 1 report, arXiv 2312.11805, section 3); Pathways is not open source.
Launching. The same script is started on every host of the slice (on Cloud TPU, one command over all workers; under GKE or Slurm, one pod or task per host). jax.distributed.initialize() then needs no arguments: the JAX guide lists Slurm, Kubernetes and Cloud TPU as environments where they "are automatically populated". Not run here.
| Question | Tool | What it printed here |
|---|
Finding a surprise collective. The compiled HLO names every collective, and its metadata records the Python line that produced it. Grouping collectives by line is the fastest way to find the one you did not plan. This page's parser does it in a few lines (src/runs/ss_hlo.py: newer HLO dumps store the line in a StackFrames table that each instruction points into with stack_frame_id). Applied to the root lab's unconstrained FSDP layout under Shardy, it points straight at the MLP: . Those are whole-batch activations, the signature of a propagator that followed the weights' split into the activations.
comp = jax.jit(step).lower(*args).compile()
for ins in ss_hlo.instructions(comp.as_text()): # name, op, type, sharding, file, line
if ins["op"].replace("-start", "") in ("all-gather", "all-reduce", "reduce-scatter", "all-to-all", "collective-permute"):
print(ins["op"], ins["type"], ins["file"], ins["line"])
Optional: design questions that combine several sections, and what changed from the old Notion page.
State first: 70.55B parameters at 16 bytes each is 1.13 TB of weights, gradients and Adam state (derived), so no form of pure data parallelism fits in 95 GiB chips; the state must be sharded. The scaling book takes 8,960 chips (16x20x28) and a 4M-token batch (1,024 sequences of 4,096), that is 468 tokens per chip: below the 2,550 that pure FSDP needs on v5p and above the about 113 that mixed FSDP plus tensor parallelism needs (α²/(MXMYF) with F = 28,672, MXMY = 2). The best FSDP degree is √(B/F · MX/MY · N) ≈ 1,619 with MX/MY = 2, and tensor parallelism must stay below F/2,550 ≈ 11. The book's answer: "roughly 2048-way FSDP and 4-way tensor parallelism", with tensor parallelism on the axis with the fewest hops; its takeaway box phrases the same budget as "data parallelism (1024-way), sequence parallelism (2-way), and tensor parallelism (4-way)". At 40% MFU it estimates "about 44 days" (scaling book, part 6). In JAX: a mesh ('fsdp', 'tensor') made with jax.make_mesh over the slice, parameters sharded by logical rules, activations constrained at block boundaries, jax.checkpoint per layer, and orbax for sharded checkpoints. Mention what you would check first: the compiled HLO for unplanned all-gathers, and memory_analysis() against HBM.
All-gathers of activations rather than weights: attribute the collectives in compile().as_text() to source lines and look for [batch, sequence, hidden]-shaped gathers (in the root lab's unconstrained FSDP case, 33.5 MB of MLP-hidden all-gathers in the forward and the same again in the backward). Fix with with_sharding_constraint on the residual stream (or Explicit mode). Then check the per-chip batch against C/Wici, whether weights are re-gathered in the backward pass, and whether the gradient reduction is a reduce-scatter (on TPU it should be).
Inside a slice, ICI connects every chip on a torus at high bandwidth, so FSDP and tensor parallelism reach thousands of chips; the bubble ((S−1)/(MR+S−1)) and the memory for microbatches in flight are costs you only pay when the network forces you to. GPU clusters hit slow inter-node links at 8 GPUs, which is where pipelining pays. The scaling book says the same in its pipelining section.
The old Notion page "Sharding and scale: GSPMD, Mesh, shard_map" (fetched 2026-09-22, saved in the root's src/read/old/sharding.md) was treated as unverified notes. Each claim was checked; the corrections (full list in src/coverage.md):
Built 2026-10-15 from src/runs/ (jax 0.11.2, 8 simulated CPU devices on an Apple M1 Pro, shared machine at load 25 to 60). Sources quoted at jax-v0.11.2, MaxText main 1a95d1e5, optax v0.2.8 and openxla/xla 91888df6; file and line located by pattern in src/runs/ss_source.py.
Pick a model, a TPU slice and a split; see what each chip holds and how long a step's compute and communication take, from published chip specs and the scaling book's formulas.
Everything on this tab is a derived calculation, not a measurement: chip numbers are Google's (Cloud TPU docs, last updated 2026-10-13, as collected by the root's TPU and Pallas lab) and the per-link ICI bandwidth is the scaling book's table. What was measured is the structure of the byte formulas: on 8 simulated devices they reproduce the compiled programs within 0.4% (Reading, section 10, which tabulates them against the compiler). The arithmetic is mirrored in src/runs/ss_mesh.py and checked against it.
This page's tabs, the knowledge base pages it leans on, and the best outside resources, each with an approximate time. Outside sources are marked Google (written by the makers of JAX, XLA or the TPU: authoritative on how things work, not neutral on whether to use them) or third-party. Links checked on 2026-10-15.
Mesh and PartitionSpec; Auto, Explicit and Manual sharding; how GSPMD and Shardy propagate and where they differ (stepper over the real dumps); Explicit mode on the running example; shard_map and its collectives; every strategy measured at two sizes; context, pipeline and expert parallelism written by hand; byte formulas checked against the compiler; choosing a mesh; many hosts; debugging. about 38 min, plus 28 in closed details
Model, slice, batch, FSDP and tensor degrees: memory per device, compute and communication per step, the scaling book's conditions and the topology check, with byte formulas checked against compiled programs (Reading, section 10). about 3 min, longer to explore
The root: its "Sharding lab" tab has a PartitionSpec playground, ring collectives and six layouts of the running example that this page builds on, and its "TPU and Pallas lab" shows how mesh axes land on the torus. Reading: 32 min, plus 13 in closed details; Sharding lab 18 min, plus 2
Tracing, jaxprs, vmap and its spmd_axis_name: the machinery shard_map and the pipeline's vmap sit on.
The pass pipeline the SPMD partitioner sits in, HLO dumps, fusion and buffer assignment.
Sharding annotations on Flax NNX parameters, orbax sharded checkpoints and restore onto a different mesh, grain's per-host loading.
Slices, pods, multislice and topology-aware meshes from the chip's side; rooflines per generation.
MaxText's logical axis rules, mesh axes and pipeline in context.
Every parallelism strategy framework-free, with a layout calculator for GPU clusters and the pipeline bubble table. 32 min, plus 5 in closed details
The PyTorch counterparts: DDP, FSDP2, DTensor, tensor and pipeline parallelism, pipelining stages and schedules in section 8. 35 min, plus 20 in closed details
Why the network decides the parallelism; ICI against NVLink and InfiniBand; a collective simulator.
The TPU hardware itself: systolic arrays, pods, optical switches.
ZeRO (the FSDP stages, step by step), Megatron-LM (the tensor-parallel split), Switch Transformers and Mixtral (routing), MoE memory bottlenecks.
Google (DeepMind authors), 2025-02-04. Sharded matmuls and collectives, parallelizing a transformer for training, and the LLaMA 3-70B worked example; the formulas this page checks. about 2 h for the three parts
Google, the current guide to Auto, Explicit and Manual axes, sharding in types and reshard. about 45 min
Google. Per-device programming with collectives, check_vma, and worked examples. about 35 min
Google. Processes, global and local devices, building global arrays, the same-order rule. about 25 min
Google (OpenXLA). Factor-based rules, priorities, open and closed dimensions. about 30 min
Google. Sharding representation, propagation with priorities (section 3.5), pipelining as sharding (3.3), the partitioner. about 1 h
Google. Mixture-of-experts with annotations and all-to-all dispatch: the einsum formulation section 9's propagation variant follows. about 1 h
third-party (UC Berkeley). Blockwise attention with K/V passed round a ring. about 40 min
Google. Read configs/base.yml (mesh axes, ICI and DCN degrees, logical axis rules) and layers/pipeline.py, layers/moe.py; quoted here at main 1a95d1e5. about 1 h
Google. Where the 2-D torus all-reduce on TPU pods comes from. about 30 min