Skip to content

FSDP and TorchTitan on TPU

40 min read

Prerequisites: Sharding, meshes and collectives

Fully sharded data parallelism is the layout most large training jobs on TPU use: every device keeps a slice of every weight, gradient and optimizer moment, gathers a layer's full weights just before it runs, and hands the gradients back with a reduce-scatter. Chapter 13 gave you the collectives and their cost; this chapter applies them. You will compute what FSDP saves in memory and what it costs in traffic, see why TorchTPU recommends SimpleFSDP over PyTorch's FSDP2, run TorchTitan's TPU recipes from the command line, capture the whole training step as one program, and learn the checks that tell you a sharded run is correct and fast: loss parity, a stable step time, MFU and scaling efficiency.

What this chapter covers

  • Per-device memory of parameters, gradients and optimizer state under FSDP, and the transient peak of the gathered layers, for a given model, precision policy and number of devices.
  • SimpleFSDP-style sharding of a PyTorch model, loss scaling for a summed gradient, and loss parity against a single-process reference.
  • TorchTitan on TPU: running a recipe, overriding its configuration from the command line, and choosing between the regular trainer and Graph Trainer.
  • Whether an FSDP step is bound by compute or by communication, from the model size, the tokens per device and chapter 13's cost model.
  • The common FSDP failures on TPU (out of memory at the all-gather peak, recompiles, exposed collectives, a wrong gradient scale) and their symptoms.
  • Judging a run by loss parity, steady-state step time, MFU and weak-scaling efficiency.

FSDP in the vocabulary of chapter 13

The scaling book writes FSDP for one transformer block as \(\text{In}[B_X, D] \cdot W_\text{in}[D_X, F] \cdot W_\text{out}[F, D_X]\): the batch is split over the mesh axis \(X\), as in plain data parallelism, and so is one dimension of every weight (How to Scale Your Model, "Training"). In DTensor terms, every parameter sits at rest as Shard(0) on the FSDP mesh dimension. Because the activations are not sharded along the contracted dimension, a layer cannot multiply by a sharded weight; it first redistributes it to Replicate(), which chapter 13 told you is an all-gather. The gradient each rank then computes for the full weight covers only its own rows of the batch, a Partial() sum, and turning Partial() into Shard(0) is a reduce-scatter.

TorchTPU's FSDP guide describes the same mechanism in one sentence: each TPU core stores a 1 / world_size slice of the model, a layer's full weights are reconstructed with an all-gather before it runs, and in backward the gradients are combined and re-sharded with a reduce-scatter. The optimizer then runs on the shard: AdamW is elementwise, so each rank updates exactly the rows it owns, from its gradient shard and its slice of the moments, with no communication at all.

An animation in twelve frames of four ranks side by side, each a dashed box with rows W1, W2, dW1, dW2 and Adam of four slots each. At rest each rank fills only its own slot in W1, W2 and Adam. In forward, an all-gather banner fills all four W1 slots on every rank with letters A to D coloured by origin rank; while layer 1 computes, W2 is gathered too and the counter at the bottom right reads full layers resident: 2 layers (peak); W1 then returns to its single shard. In backward W2 is gathered again, each rank's dW2 row fills with orange p slots for a partial gradient, a reduce-scatter banner leaves one green sigma slot per rank, and the same happens for layer 1. A counter at the bottom left counts the step's all-gathers and reduce-scatters. A final frame shows AdamW updating only the local shard with no communication, and the bottom-left counter reads: per layer and step, 2 all-gathers and 1 reduce-scatter.

Watch the counter in the bottom right: full weights exist for at most two layers at a time, and only while they are needed. The bottom-left counter ends at two all-gathers and one reduce-scatter per layer, the numbers the companion demo measures.

Three details of that lifecycle matter on TPU.

The forward gather can run one layer ahead. Nothing in layer 2's all-gather depends on layer 1's output, so it can overlap layer 1's matmul. The scaling book marks both forward gathers and both backward reduce-scatters as off the critical path. The price is memory: two layers are full at the peak instead of one.

Backward gathers again. TorchTPU's FSDP guide asks for activation checkpointing on each sharded layer (torch.utils.checkpoint.checkpoint(..., use_reentrant=False)) so that the gathered weights are freed right after each layer's forward pass instead of living until backward. That is the ZeRO-3 behaviour you expect from FSDP, and it means backward all-gathers each layer a second time when it recomputes it. Per layer and step: two all-gathers and one reduce-scatter.

The gradient reduction is a sum. SimpleFSDP declares its gradient placement as Partial(reduce_op="sum"), so the reduce-scatter adds the ranks' gradients. If each rank's loss is a mean over its own rows, divide it by the world size, or the gradient is world_size times the gradient of the global mean. FSDP2 averages by default, which is why TorchTPU's migration tutorial puts this at the top of its list of changes.

When FSDP is compute-bound

FSDP adds no bytes over data parallelism. Data parallelism all-reduces every gradient once; FSDP all-gathers the weights and reduce-scatters the gradients, and chapter 13 showed that an all-reduce is a reduce-scatter plus an all-gather. The scaling book's conclusion is that FSDP and plain data parallelism become communication-bound at the same point: when the tokens per device drop below the chip's FLOP/s divided by its ICI bandwidth on that axis. Chapter 13 worked that out as about 5,100 tokens per device for a v6e chip on one axis with wraparound. With checkpointing, backward's second gather adds one more weight-sized transfer per step, so keep a margin above that figure.

The scaling book also names the levels of ZeRO: ZeRO-1 shards optimizer state, ZeRO-2 adds gradients, ZeRO-3 adds parameters. All three have the same communication volume, so the book's advice is to use ZeRO-3. TorchTitan exposes the choice as fsdp_reshard_after_forward: "always" is ZeRO-3, "never" keeps the gathered weights after forward (ZeRO-2 for the parameters), and Graph Trainer then force-saves the all-gather outputs instead of recomputing them.

Memory per device

The persistent state of FSDP divides by the size of the sharding group. With \(P\) parameters, \(n\) devices and \(b_p\), \(b_g\), \(b_o\) bytes per parameter for the parameter, its gradient and its optimizer state:

\[ M_\text{state} = \frac{P \,(b_p + b_g + b_o)}{n} \]

The companion function is memory_per_chip(params, n_chips, bytes_param=2, bytes_grad=2, optimizer_bytes_per_param=8) in code/ch14_fsdp/fsdp_memory.py. Three byte budgets are in common use, and the difference between them is not a rounding error:

Budget \(b_p + b_g + b_o\) Where it comes from
bf16 parameters, fp32 Adam moments, gradients not counted 2 + 0 + 8 = 10 The scaling book's rule of thumb (also chapter 13's)
bf16 parameters and gradients, fp32 Adam moments 2 + 2 + 8 = 12 The function's defaults
fp32 master weights and gradients, fp32 AdamW moments 4 + 4 + 8 = 16 The TorchTitan TPU recipes: "Master weights are float32" (Llama 3 8B v6e-8 recipe); the gradient of a fp32 shard is fp32

In the 16-byte case the bf16 weights exist only while a layer is gathered: the mixed-precision policy (param_dtype=bfloat16) casts the shard on the way into the all-gather.

n_chips is the number of shards. On v7x, where TorchTPU makes each chip two devices with 96 GiB of HBM each (chapter 1), pass the device count and compare with 96 GiB.

The transient peak is the gathered layers. With per-layer checkpointing and one layer gathered ahead, two layers' weights are full at once, in the gather dtype: allgather_peak_bytes(layer_params, gather_bytes=2, layers_in_flight=2). This term does not shrink as you add devices. Without checkpointing every gathered layer stays alive until backward, and the peak becomes the whole model in bf16.

Two charts titled FSDP memory per device, code/ch14_fsdp/fsdp_memory.py. Left, Llama 3 70B (70.4B parameters), state per FSDP shard: persistent state per device in GiB on a log scale against FSDP group size from 8 to 1024 devices on a log scale. Three falling lines: fp32 master weights plus fp32 grads plus AdamW at 16 bytes per parameter (blue), bf16 params and grads plus AdamW at 12 (orange), and the scaling book's 10 bytes per parameter (dashed teal). Dotted horizontal lines mark v7x HBM per device, 96 GiB, and v6e HBM per device, 32 GiB; an annotation says 16 B/param fits v6e from 33 shards, state only, no activations. Right, Where it goes at 16 B/param, before activations: stacked bars for 32, 64 and 128 shards made of fp32 weights, fp32 gradients and AdamW m and v, each divided by n, plus a hatched block for 2 gathered bf16 layers that is not divided; totals 36.0, 19.6 and 11.4 GiB, against a dotted line at v6e 32 GiB.

On the left, find where each line crosses the HBM line for your chip: that is the smallest group that can even hold the state. On the right, watch the hatched block stay the same height while everything else halves: at large group sizes the gathered layers and the activations, not the shards, decide what fits.

Read the chart with Llama 3 70B, whose 70.4 billion parameters the scaling book counts from its configuration (56.3B in the feed-forward matrices, 12B in attention, 2.1B in the embeddings). At 16 bytes per parameter the state is 1,049 GiB. It fits in the 96 GiB of a v7x device from 11 shards and in the 32 GiB of a v6e chip from 33, but only with no room for anything else. At 64 v6e chips the state is 16.4 GiB per device, plus 3.2 GiB for two gathered layers (each layer is about 856 million parameters, 1.7 GB in bf16), which leaves about 12 GiB for activations and temporaries. That is the kind of number the next sections spend: on a larger batch, on saving activations instead of recomputing them, or on not offloading.

Two things push the figure up. HSDP replicates the state across replica groups, so per-device memory goes up by the replicate degree (TorchTitan's optimization guide); a 2-way replicated 64-way shard holds what a 64-way FSDP group holds, not what a 128-way one would. And the in-graph optimizer of Graph Trainer holds both the input and the updated copies of parameters and optimizer state, because step inputs are not donated today.

Three ways to write FSDP on TorchTPU

TorchTPU's FSDP guide starts from one principle: on TPU, performance comes from compiling the whole training step into one XLA program with torch.compile(backend="tpu"), because only then can the compiler schedule collectives against the computation and combine small collectives when it pays. It then ranks the three ways to write FSDP by how well they compose with that:

Approach What it is When to use it (TorchTPU's guide)
SimpleFSDP (simple_fsdp.data_parallel) Parameters stored as sharded DTensors; a parametrization all-gathers on access; autograd reduce-scatters The recommended default: FSDP or HSDP without changing the model definition
Manual FSDP Each layer stores its shard and calls torch.distributed._functional_collectives.all_gather_tensor in forward; the functional collective's autograd formula reduce-scatters in backward You own the model code and want communication next to computation for tuning
PyTorch FSDPv2 (fully_shard) Pre-forward and post-backward module hooks issue the collectives Existing code not yet migrated. It works, but its hooks cause graph breaks, and competitive performance needs upcoming support for stream offload to the SparseCore

Which of them to start from:

A decision tree read from top to bottom. A dark pill, Training with FSDP on TPU, leads down to the white rounded question Is the model in TorchTitan, or can it be? Yes leads right to a blue card, Start from a TPU recipe, SimpleFSDP and per-block compile already on. No leads down to the question Own the model code and tune communication? Yes leads right to a blue card, Manual FSDP, Functional collectives, @spmd_safe step. No leads down and right to a blue card, SimpleFSDP, the default, with the call simple_fsdp.data_parallel and the line Per-layer checkpoint, compiled step.

All three routes put the collectives inside compiled code so XLA can schedule them against the matmuls; TorchTitan's TPU recipes already use SimpleFSDP and per-block compile. FSDPv2's fully_shard is left out because its hooks break the graph, as the table says.

Why FSDP2's hooks hurt on TPU

The TorchTitan integration post explains the mismatch. FSDP2 was built for the GPU execution model: its all-gathers and reduce-scatters are issued from module hooks as explicit calls, and overlap comes from running them on dedicated CUDA streams synchronized with events. None of that is visible to a compiler. On TPU a torch.compile region breaks at every FSDP hook, and a whole-step graph cannot be captured at all. TorchTPU provides no-op stream and event objects only so that FSDP2 runs; XLA has no use for them, since it schedules from data dependencies.

There is a second cost. FSDP2 copies each parameter shard into a flat staging buffer before the all-gather and copies the result back out into per-parameter tensors afterwards. In the FLUX.1 case study on a v6e-8, the trace (of the eager FSDP2 run) "was dominated by FSDP2 copying parameter shards into a flat staging buffer before each all-gather and back out into per-parameter tensors afterwards"; replacing FSDP2 with SimpleFSDP, which gathers each parameter directly, took the step from 9.95 s to 6.52 s.

Animated timeline in two parts. Top, FSDP2 (hooks, flat staging buffer): one TensorCore lane runs orange copy blocks, a purple AG block, another copy, then a blue MM block, repeated for four layers, ending with the note done: same 4 layers, later. Bottom, SimpleFSDP (collectives in the graph): an ICI / SparseCore lane runs AG 0 to AG 3 while the TensorCore lane runs MM 0 to MM 3 back to back, ending earlier with the note done: 4 layers. A small label reads schematic, not to scale.

Schematic, not to scale: watch the orange staging copies disappear and the gathers move off the matmul lane once the collectives live inside the compiled program.

What SimpleFSDP does instead

SimpleFSDP stores each parameter as a sharded DTensor and registers a parametrization on its module. Reading the weight calls ReplicateComputation, which runs DTensor.redistribute from Shard to Replicate with forward_dtype=param_dtype and backward_dtype=reduce_dtype. The redistribute is the all-gather; its autograd backward is the reduce-scatter. There are no hooks and no explicit collective calls, so both collectives are ordinary nodes in whatever graph is being traced, a per-block torch.compile region or Graph Trainer's whole step.

Diagram inside a blue dashed container labelled One XLA program: a teal Sharded weight block feeds a purple All-gather (bf16) block, which feeds a blue Matmul block; from the Matmul an arrow runs down and back to a purple Reduce-scatter (fp32) block, which feeds a green Sharded gradient block.

Both collectives sit in the same program as the matmul that needs them. That is the only reason XLA can start the gather before the matmul and run the reduce-scatter alongside the rest of backward.

Two more behaviours come from simple_fsdp.py. mode is "replicate" (plain data parallelism), "fully_shard" or "hybrid_shard" (HSDP, which needs a 2D DeviceMesh: replicate on the first dimension, shard on the second). And a parameter whose size along the sharding dimension is smaller than the mesh dimension is replicated instead of sharded; shard_dim (an int, or a dict from parameter name to dimension) picks another dimension. Inside with simple_fsdp.disable_active_parametrization(): reading a weight returns the sharded DTensor itself, which is how you inspect a shard or its gradient.

The migration from FSDP2 is short. Before, per layer, with prefetch lists tuned by hand:

from torch.distributed import fsdp

layers = [layer for layer in model.children() if list(layer.parameters())]
for layer in layers:
    layer.forward = functools.partial(checkpoint_utils.checkpoint, layer.forward, use_reentrant=False)
    fsdp.fully_shard(layer, mesh=mesh, mp_policy=mp_policy)
fsdp.fully_shard(model, mesh=mesh, mp_policy=mp_policy)
for i, layer in enumerate(layers):
    if i < len(layers) - 2:
        layer.set_modules_to_forward_prefetch([layers[i + 1], layers[i + 2]])
    if i >= 2:
        layer.set_modules_to_backward_prefetch([layers[i - 1], layers[i - 2]])

After, one call and no prefetch lists, then a compiled step with the loss scaled for the sum reduction:

import simple_fsdp   # torch_tpu/examples/fsdp/simple_fsdp.py, or TorchTitan's graph_trainer/simple_fsdp.py

for layer in model.children():
    if list(layer.parameters()):
        layer.forward = functools.partial(checkpoint_utils.checkpoint, layer.forward, use_reentrant=False)
model = simple_fsdp.data_parallel(model, device_mesh=mesh, mode="fully_shard", mp_policy=mp_policy)
compiled_model = torch.compile(model, backend="tpu")

def train_step(model, x, y, world_size):
    loss = loss_fn(model(x), y)
    (loss / world_size).backward()      # SimpleFSDP sums gradients; FSDP2 averages
    return loss.detach()

The mesh in TorchTPU's example is dt.init_device_mesh("tpu", (world_size,), mesh_dim_names=("fsdp",)) after dist.init_process_group(backend="tpu_dist"); on a real slice, build it from torch.tpu.distributed.topology_aware_mesh as chapter 13 showed.

Which mixed-precision policy

TorchTPU's SimpleFSDP README and migration tutorial build MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.bfloat16) for their toy model. TorchTitan's optimization guide calls MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32) "the standard, correct setup" and warns not to drop reduce_dtype to bf16 to save bandwidth: "that is a model-quality regression, not a perf lever." Every TorchTitan TPU recipe gathers in bf16 and reduces in fp32. This chapter follows the TorchTitan guide; treat the example's policy as a property of that example, not a recommendation.

Manual FSDP

TorchTPU's manual FSDP example shows the same contract written by hand. ManualFSDPLinear keeps a (out_features // world_size, in_features) weight shard, raises if out_features does not divide by the world size, and builds the full weight with all_gather_tensor(self.weight, gather_dim=0, group=self.group) inside a checkpointed forward. Because functional collectives have autograd formulas, backward reduce-scatters with no custom autograd.Function. Two details from the worker are worth copying: the step is decorated with @torch.tpu.distributed.spmd_safe and compiled with torch.compile(fwd_and_bwd, backend="tpu", fullgraph=True), so the collectives fuse with the computation; and the replicated bias needs its own all_reduce of the gradient, because nothing shards it.

What the switch buys

TorchTPU's migration tutorial runs compiled FSDPv2 and compiled SimpleFSDP from identical initial weights on 8 TPU cores and prints each step:

Grouped bar chart on a log scale of step time in milliseconds for steps 0 to 4 of the TorchTPU FSDPv2 to SimpleFSDP tutorial on 8 TPU cores with a toy feed-forward model. Compiled FSDPv2 (orange): 10664, 194, 156, 155, 157 ms. Compiled SimpleFSDP (green): 8206, 139, 37, 52, 52 ms. Step 0 is shaded and labelled step 0: compilation; the later steps are labelled steady state from step 2. Under each step the losses are listed as FSDPv2 | SimpleFSDP, identical to six decimals except step 4, 0.952552 against 0.952553.

Read the chart twice. First the losses under the axis: the two implementations agree to the sixth decimal, which is what a correct migration looks like. Then the bars after step 1: about 3 times faster in steady state on a toy model. Step 0 is compilation and says nothing about either.

Do not carry the factor of 3 to your model; carry the mechanism. In TorchTitan the switch is one field, --parallelism.use_simple_fsdp, which the TPU recipes set.

The companion demo: SimpleFSDP on CPU processes

code/ch14_fsdp/simple_fsdp_demo.py follows SimpleFSDP's pattern with a ShardedLinear whose only parameter is a row shard of the weight. One autograd.Function does what SimpleFSDP's ReplicateComputation does: all-gather in param_dtype on the way in, reduce-scatter with a sum in reduce_dtype on the way back, both as functional collectives a tracer can record. Every layer is checkpointed, and the loss is divided by the world size. The smoke run trains a three-layer MLP for five AdamW steps in one process, then again sharded over 2 and 4 gloo processes, each feeding its own rows of the same global batch:

$ python code/ch14_fsdp/simple_fsdp_demo.py --cpu-smoke
== 1. single-process reference (world 1, collectives skipped)
   losses  1.056516 0.812816 1.142944 1.060535 0.931654
   ok: ShardedLinear at world 1 trains exactly like nn.Linear
   1792 parameters, 28672 bytes of params + grads + AdamW moments
== 2. SimpleFSDP-style sharding over 4 gloo processes, 2 rows per rank
   losses  1.056516 0.812816 1.142944 1.060535 0.931654   max |diff| vs reference 1.2e-07
   ok: every step's global loss matches the reference within 1e-05
   ok: gathered final weights match the reference (max |diff| 6.0e-08)
   one step issued 6 all-gathers and 3 reduce-scatters for 3 layers (checkpointed: gathered again in backward)
   ok: 2 all-gathers and 1 reduce-scatter per layer per step
   rank 0 holds 448 parameters and 7168 bytes of state; memory_per_chip(1792, 4, 4, 4, 8) = 7168
   ok: each rank holds 1/4 of the parameters, gradients and optimizer state
== 3. whole-step trace: forward + loss + backward + functional AdamW in one FX graph
   graph: 100 call_function nodes, 8 matmul-like, 4 aten.sqrt (3 parameter tensors + 1 bias correction)
   traced  1.056516 0.812816 1.142944
   eager   1.056516 0.812816 1.142944
   ok: three traced steps match eager torch.optim.AdamW
   ok: the optimizer update is inside the traced graph
cpu-smoke: OK

(The 2-process block is omitted here; it prints the same losses.) Three things to take from it. The losses agree with the single process to about \(10^{-7}\) in fp32, because the only difference is the order in which the reduce-scatter adds the ranks' gradients. The counts confirm the lifecycle animation: two gathers and one reduce-scatter per layer. And each rank's bytes of state are exactly memory_per_chip(P, n, 4, 4, 8): the formula is not an approximation for the persistent part. Remove the / world in train() and the gradients come out 2 or 4 times too large; the loss curve then differs from the reference, which is the migration bug the parity check exists to catch.

The demo builds each full weight from one seed and gives each rank its rows, so the sharded runs start where the reference starts. A real job that initializes each shard on its own rank must seed the ranks differently, torch.manual_seed(base_seed + dist.get_rank()), or every shard is the same random block repeated, which TorchTPU's guide says can hurt convergence.

TorchTitan on TPU

TorchTitan is the PyTorch ecosystem's reference platform for large-scale training. TorchTitan TPU is Google's fork of it, adapted to run on Cloud TPUs (https://github.com/google-pytorch/torchtitan/); the TPU work lives in torchtitan/experiments/tpu, which this chapter calls the TPU lane. It ships recipes for dense models (Llama 3 70B and 405B, Qwen 3 8B and 32B), mixture-of-experts models (Qwen 3 235B) and diffusion transformers (FLUX.1 12B), and it is the trainer inside post-training pipelines such as VeRL's GRPO, which chapter 15 takes up.

Layered diagram in three dashed bands stacked top to bottom. The top amber band, Configuration, holds CLI overrides on the left, Recipe config in the middle and libtpu flags on the right; an arrow labelled overrides runs from CLI overrides to Recipe config. The middle blue band, TorchTitan TPU, holds TPUTrainer and TpuGraphTrainer in its upper row, both fed by arrows from Recipe config, and SimpleFSDP and Pallas kernels in its lower row. The bottom purple band, TorchTPU runtime, holds tpu_dist backend on the left and XLA program on the right. SimpleFSDP points down to tpu_dist backend with the label collectives, tpu_dist backend points right to XLA program with the label StableHLO, Pallas kernels points down to XLA program with the label custom calls, and libtpu flags points down the right edge to XLA program.

Trace one config field to the band it lands in: --parallelism.use_simple_fsdp changes what reaches the tpu_dist backend, a kernel switch changes the custom calls, a libtpu flag changes only how XLA compiles the same program.

The pieces, from the top of the figure down:

Configuration is Python, not TOML. A recipe is a function in a config_registry.py, such as qwen3_1_7b() in torchtitan/experiments/tpu/qwen3/config_registry.py, that returns a config object. --module names the package and --config the function; TorchTitan's ConfigManager calls it and hands the result to tyro, so every nested field can be overridden on the command line as --section.field=value (precedence: command line over the recipe's defaults). You will find older TorchTitan material written against .toml job files; the TPU lane has none, and you should read a recipe's function to see what it sets. The top-level sections include training, parallelism, compile, checkpoint, profiler and, in the TPU lane, tpu_config.

Two trainers. A recipe that returns a TPUTrainer config gets the regular trainer: an eager training loop with per-block torch.compile. A recipe that returns a TpuGraphTrainer.Config gets Graph Trainer, which traces the whole step; experiments/tpu/train.py dispatches on the config type.

Parallelism is separate from the model. FSDP and tensor parallelism are layered onto a parallelism-agnostic model; only expert parallelism needs explicit communication in the MoE layer, through a pluggable token dispatcher. --parallelism.use_simple_fsdp selects SimpleFSDP, --parallelism.data_parallel_shard_degree and --parallelism.data_parallel_replicate_degree set the FSDP and HSDP degrees, and ParallelismConfig(enable_tpu_topo_mesh=True) builds the mesh with topology_aware_mesh and preserve_rank_order=True.

Kernels are config-tree rewrites. TorchTitan builds the model from a configuration tree that can be rewritten before construction, so a recipe swaps standard attention for Splash attention, the final projection and loss for a fused Pallas cross-entropy that never writes the logits to HBM, or MoE matmuls for grouped Pallas kernels, without touching the model or the trainer loop. Each kernel is a JAX function turned into a PyTorch custom op by torch.tpu.pallas.jax_op (chapter 12), each is a flag, and each is tested against the plain PyTorch path it replaces.

Flags live in the config. libtpu_init_flags and xla_flags are fields of the TPU trainer config, composed from named bundles in tpu_flags.py (tpu_flags.merge_flags(tpu_flags.SPARSECORE_LATENCY_HIDING_SCHEDULER, ...)). On the command line, --extra-libtpu-init-flags and --extra-xla-flags add or override single flags, '!flag' drops one, and --libtpu-init-flags='' drops the recipe's whole set; an exported LIBTPU_INIT_ARGS or XLA_FLAGS has the last word. --debug.print-config prints the merged configuration, flags included.

Running a job on one TPU VM

The TPU lane's README installs TorchTPU 0.2.0 with PyTorch 2.15.0 under Python 3.14:

python3.14 -m venv venv; source venv/bin/activate
git clone https://github.com/google-pytorch/torchtitan
cd torchtitan
pip install torch==2.15.0 torch_tpu==0.2.0 -r torchtitan/experiments/tpu/requirements.txt \
  --extra-index-url https://download.pytorch.org/whl/test/cpu
pip install -r requirements.txt -r .ci/docker/requirements-flux.txt

The two pip install commands are separate because tokamax and tyro declare conflicting typeguard versions; pip warns and completes. Then the README's first job, Qwen3 1.7B with FSDP on a v6e-4 VM, using the tokenizer and the c4_test sample data bundled with the repository so it needs no downloads:

torchrun --nproc_per_node=4 -m torchtitan.experiments.tpu.train \
    --module=torchtitan.experiments.tpu.qwen3 \
    --config=qwen3_1_7b \
    --training.steps=10

--nproc_per_node is the number of TPU devices on the host: one process per device, as always on TorchTPU.

Running a recipe on several hosts

Larger models run on GKE, submitted with Cluster Toolkit's gcluster job submit. The Llama 3 8B recipe for a v6e-8 slice (topology 2x4: two hosts of four chips) shows how much of a recipe is command-line flags:

gcluster job submit \
  --name "$WORKLOAD_NAME" --cluster "$CLUSTER_NAME" \
  --compute-type ct6e-standard-4t --topology 2x4 --num-slices 1 \
  --location "$ZONE" --project "$PROJECT_ID" --image "$WORKLOAD_IMAGE" \
  --env="WORKERS_0_HOSTNAME=${WORKLOAD_NAME}-main-job-0-0.${WORKLOAD_NAME}" \
  --env="WORKLOAD_NAME=$WORKLOAD_NAME" \
  --command "torchrun \
    --nnodes=2 --nproc_per_node=4 \
    --rdzv_backend=static --rdzv_endpoint=\$WORKERS_0_HOSTNAME:29501 --node_rank=\$TPU_WORKER_ID \
    -m torchtitan.experiments.tpu.train \
    --module=torchtitan.experiments.tpu.llama3 --config=llama3_8b \
    --hf_assets_path=tests/assets/tokenizer --dataloader.dataset_path=tests/assets/c4_test \
    --training.steps=20 \
    --training.num_tokens_per_microbatch_per_dp_rank=16384 \
    --training.max_context_length=8192 \
    --compile.enable \
    --parallelism.use_simple_fsdp \
    --splash_attention_kernel.use_splash_attention_kernel \
    --splash_attention_kernel.sa_block_kv_compute=2048 \
    --tpu_config.eager_mode=DEFER_AND_FUSE \
    --libtpu-init-flags='xla_tpu_scoped_vmem_limit_kib=131072 tpu_program_stack_shrink_after_unload=false'"

Per-block compile, SimpleFSDP, Splash attention, the fused loss (which the llama3_8b recipe enables) and deferred-and-fused eager mode for whatever runs outside the compiled blocks: that is the first rung of TorchTitan's optimization playbook, all as flags. The batch is in tokens: 16,384 per data-parallel rank is two sequences of 8,192. The recipe README lists what you should see: 5,383 tokens per second per chip and 33.96% MFU. The section on checking a run below reproduces that MFU from the model's shape.

To profile, add --profiler.enable_profiling with --profiler.profile_freq, --profiler.profiler_warmup and --profiler.profiler_active; traces go under the dump folder's profile_trace for each process and open in TensorBoard or XProf (chapter 10).

Several slices: HSDP over DCN

Across slices, the layout that pays is the one chapter 13 derived: shard inside each slice over ICI, replicate across slices over DCN, so the only DCN traffic is one gradient reduction per step, overlapped with backward.

Two blue dashed containers, Slice 0 and Slice 1, each holding a blue FSDP over ICI block above a 4 by 4 grid of chip icons. A two-way arrow from each slice's block runs down to one purple DCN all-reduce block spanning both slices.

All-gathers and reduce-scatters stay inside a slice; only the replicated gradient crosses DCN, once per step.

The TPU lane's multi-slice command adds --num-slices, the MegaScale variables and three settings, each of which prevents a silent slowdown:

    --env MEGASCALE_NUM_SLICES=2 \
    --env MEGASCALE_COORDINATOR_ADDRESS="$WORKLOAD_NAME-main-job-0-0.$WORKLOAD_NAME:8080" \
    --env LIBTPU_INIT_ARGS="--xla_tpu_scoped_vmem_limit_kib=65536 --megascale_grpc_premap_memory_bytes=4294967296 --megascale_use_numa_aware_block_allocator=false" \
    ...
        --module=torchtitan.experiments.tpu.muse_glimmer \
        --config=muse_glimmer_30b_full_logits \
        --parallelism.data_parallel_replicate_degree=$MEGASCALE_NUM_SLICES \
        --parallelism.enable_min_cost_redistribute \
        --training.steps=30
  • --parallelism.data_parallel_replicate_degree=$MEGASCALE_NUM_SLICES is required. The replicate axis is the one split across DCN. With the default of 1, FSDP shard groups would straddle the slices and the job would train correctly at a fraction of the throughput, so TorchTitan refuses to start.
  • --parallelism.enable_min_cost_redistribute makes DTensor's planner reduce-scatter before the replicate-axis reduction, so DCN carries a shard instead of the full gradient: chapter 13's 86 ms against 1.3 ms.
  • On v7x, MegaScale pins a host-memory pool per process, and TorchTPU runs one process per TensorCore, 8 per VM: 256 GiB per VM by default. The two megascale_* flags bring it to 32 GiB, which matters once activation offload also wants host memory.

TorchTitan's optimization guide adds a caution: HSDP is not a multi-host requirement. Full sharding spans hosts fine over ICI, and every shipped multi-host v7x recipe it lists is plain FSDP with data_parallel_replicate_degree=1. Choose HSDP when the FSDP group would be wider than the collectives need or when the replicate axis maps onto a slow link, and budget for its extra memory. The FLUX.1 case study is the example: at 12B, pure FSDP slowed down past one 64-chip cube, and HSDP (shard within each 4x4x4 cube, replicate across cubes, on a topology-aware mesh) held 93% weak-scaling efficiency to 1,024 chips.

Whole-step capture with Graph Trainer

Per-block torch.compile makes each transformer block one XLA program. What it leaves out is the rest of the step: the optimization guide lists the optimizer step, the loss, the embedding and layout ops as separate programs, and "the host-side gaps between whatever is not inside a compiled region set a structural MFU ceiling." Compiling the blocks harder does not help, because that idle time is not in the blocks.

TpuGraphTrainer removes the surface. It traces forward, loss and backward with make_fx into one FX graph ahead of time (skipping AOTAutograd's partitioning, so XLA sees the whole computation), runs graph passes over it, and compiles the result for TPU. With compile.optimizer_compile="in_graph" a functional AdamW update joins the same graph, so an iteration has no host-side work between the first forward op and the weight write-back. This is the JAX model of training, where the whole step is one jitted function.

An amber dashed Host CPU container holding a Python loop block sends a single arrow into a blue dashed One XLA program container holding Forward, Loss, Backward, AdamW and Updated weights in a row.

One arrow crosses the host boundary per step. Compare with per-block compile, where an arrow leaves the host for every block, the loss and the optimizer.

A recipe selects Graph Trainer by returning its config; the optimization guide's conversion of a regular recipe is:

config = TpuGraphTrainer.Config.from_tpu_trainer_config(
    base_config, graph_trainer_model_registry  # e.g. graph_trainer.qwen3.model_registry
)
config.compile = TpuGraphTrainerCompileConfig(
    enable=True,
    components=["model"],
    memory_policy="default",       # replaces the eager activation_checkpoint config
    optimizer_compile="in_graph",  # optional: fold AdamW into the step graph
)

qwen3_8b() in experiments/tpu/qwen3/config_registry.py is the reference recipe with the in-graph optimizer; the integration post reports 51 to 52% MFU for Qwen3-8B on this path. The companion demo's step 3 is the same idea at toy size: make_fx over torch.func.grad_and_value and an out-of-place AdamW gives one graph whose four aten.sqrt nodes (one per parameter tensor plus the bias correction) prove the optimizer is inside it, and three traced steps match eager torch.optim.AdamW. Out-of-place is the point: an in-place optimizer.step() cannot be traced into a functional graph.

What Graph Trainer costs, from the guide:

  • The whole step must trace. No graph breaks to fall back on, no data-dependent Python control flow.
  • Activation memory is a graph pass. Graph Trainer ignores the eager activation_checkpoint config. compile.memory_policy decides per tensor: default (selective recompute: saves aten.linear, SDPA, topk and the reduce-scatter and all-to-all outputs), full (full recompute; only layer boundaries saved), tpu_selective (full recompute plus named save regions such as attention.inner_attention or feed_forward.w2), and offload variants that move saved activations to host memory. Under ZeRO-3 the policy may recompute the FSDP all-gathers, as the lifecycle animation does.
  • optimizer_compile="in_graph" costs HBM: step inputs are not donated today, so the graph holds input and updated copies of parameters and optimizer state. Budget for it, or use optimizer_compile="separate_graph". compile_grad_norm cannot be combined with the in-graph optimizer.
  • Keep compile.mode="aot_fx_trace", the default; the TPU joint-graph options are rejected in other modes. On libtpu 0.0.48 and later set xla_enable_hlo_sharding_v3=False, as the recipes do, because Shardy HLO sharding v3 segfaults on Graph Trainer.

Past about 100B parameters, one unrolled graph stops working. Compile time and compile-time memory grow with depth; with ZeRO-3 on one unrolled graph XLA can merge the forward all-gathers with the recomputed ones and keep full parameters alive through backward, which the config rejects unless you pick a structure; and every layer's saved input stays live until its backward. Two structures fix the first two. Scan over layers (compile.use_scan_layers=True) stacks each kind of weight into one [n_layers, ...] tensor and runs the decoder as one loop body; FSDP gathers one layer's shard per iteration, so the full stack is never resident. The graph splitter (compile.graph_split.enabled=True) keeps the layers unrolled and cuts the step into separately compiled forward and backward programs, optionally one per layer group. Host offload fixes the third and works with either. Scan needs identical layers (it stacks sibling layers' weights) on a data-parallel mesh: FSDP and HSDP are tested; tensor, context, pipeline and expert parallelism are rejected. It also takes its own offload policy, compile.memory_policy="full_and_scan_offload" (full recompute, with the one stacked layer-input tensor offloaded to the host), which the Llama 3 scan recipes above 8B need to run at all, and it rejects the generic *_and_offload policies and tpu_selective. The graph splitter is not restricted by the config and uses the *_and_offload policies. No recipe combines the two. Qwen3 235B runs both ways, within a few percent of each other, at 29% and more MFU.

Inside TorchTitan, the choice runs:

A decision tree read from top to bottom. A dark pill, A TorchTitan TPU recipe, leads down to the white rounded question Whole step traces, and dispatch-bound or 100B+? No leads right to a blue card, Stay on TPUTrainer, Tune kernels, batch and flags. Yes leads down to Over about 100B parameters, or graph too big? No leads right to a blue card, Graph Trainer, one graph, with the setting optimizer_compile="in_graph" and the line If HBM allows. Yes leads down to Identical layers, FSDP or HSDP only? Yes leads right to a blue card, Scan over layers, with the setting compile.use_scan_layers and the line Policy: full_and_scan_offload. No leads down and right to a blue card, Graph splitter, with the setting compile.graph_split.enabled and the line Policy: any *_and_offload.

Graph Trainer pays off when per-block compile leaves the step dispatch-bound, or when the model is large enough to need scan or the splitter, and in both cases the whole step must trace. Scan needs identical layers on a data-parallel mesh; the splitter has no such limit in the config. Where both apply, either works.

Flag names in the integration post

The TorchTitan integration post writes the switches as --tpu_config.use_graph_trainer, --tpu_config.use_scan_layers and --tpu_config.use_graph_split. In the current TorchTitan source none of those fields exist on tpu_config (a test asserts that use_graph_split is absent): Graph Trainer is chosen by the recipe's config type, and scan and the splitter are compile.use_scan_layers and compile.graph_split.enabled, as the optimization guide says. Use the source's names. The post's other flags (--compile.enable, --parallelism.use_simple_fsdp, --tpu_config.eager_mode=DEFER_AND_FUSE, --splash_attention_kernel.use_splash_attention_kernel) do exist.

Overlapping communication with compute

SimpleFSDP puts the collectives in the program; something still has to schedule them early enough. Four things decide whether an FSDP collective shows up in the trace as exposed time.

Everything must be in one program. This is the reason for SimpleFSDP and for compiling the whole step, and in your own code for @torch.tpu.distributed.spmd_safe or TORCH_TPU_SPMD_HANDSHAKE_STAGE (chapter 13). XLA only overlaps what it can see together; each program boundary is also a host dispatch.

The scheduler has to want to. TorchTitan's recipes carry libtpu flag bundles for this, defined in tpu_flags.py. Four matter most for FSDP: SPARSECORE_LATENCY_HIDING_SCHEDULER (lets the layer scheduler overlap FSDP collectives with compute), SPARSECORE_COLLECTIVE_OFFLOAD (moves all-gathers and reduce-scatters off the TensorCore onto SparseCores), HIERARCHICAL_REDUCE_SCATTER (splits multi-dimensional reduce-scatters into stages), and ICI_AG_PIPELINING (starts each layer's all-gather one scan iteration early, at an HBM cost). On Qwen3 235B, the latency-hiding flags and SparseCore offload hid most of the collective time, leaving a small exposed reduce-scatter tail at the end of backward.

There has to be enough compute to hide behind. The scaling book's threshold from earlier in this chapter: tokens per device above the chip's FLOP/s over its ICI bandwidth, about 5,100 on one v6e axis. Below it, overlap cannot save you; raise the batch per device, shrink the FSDP group (HSDP), or add tensor parallelism.

Flags change how, not what. A pure scheduling flag leaves the loss bit-identical. A flag that changes fusion or reduction order, hierarchical reduce-scatter among them, shifts rounding. The integration post's rule: after every flag sweep, check the step-1 loss and gradient norm. Bit-identical means the flag is free; a small difference is a rounding-order change that is safe only once a loss-curve comparison with the baseline recipe says so.

For mid-size models that keep one unrolled graph, the guide offers a lighter control over FSDP scheduling: compile.fsdp_barrier_policy="prefetch" or "interleave" with compile.enable_remat_barriers=True, as in qwen3_8b_zero3(). With the graph splitter, backward_partition_mode="fsdp_pipeline" moves each layer's all-gather into the preceding program and its reduce-scatter into the following one so that communication overlaps the neighbouring layer.

Checkpointing

Checkpointing a sharded run on TPU, in brief:

  • SimpleFSDP composes with torch.distributed.checkpoint, which saves and loads weights directly in their sharded DTensor form; that is why simple_fsdp.py registers its parametrization with a custom helper rather than nn.utils.parametrize.
  • TorchTitan's checkpoint config has --checkpoint.enable (default off), --checkpoint.folder (default checkpoint, under the dump folder), --checkpoint.interval (default 500 steps) and --checkpoint.async_mode with values disabled, async and async_with_pinned_mem.
  • Under scan, named_parameters() reports the stacked tensors. Model checkpoints keep their per-layer keys and move between scan and non-scan runs; optimizer checkpoints do not, so a run cannot resume across a flip of compile.use_scan_layers. The MoE kernel-native weight layout has the same property: model checkpoints are translated by state-dict hooks, optimizer state needs a conversion.
  • On the roadmap: Multi-Tier Checkpointing on GKE, which keeps checkpoints in local memory and in-cluster replicas with Cloud Storage as the durable tier.

Failure modes

Symptom Cause Fix
Out of memory at step 1, with the peak at the all-gathers No per-layer activation checkpointing, so every gathered layer lives until backward; or ZeRO-3 on one unrolled Graph Trainer graph, where gathers merge and full parameters stay alive (the config rejects this unless you choose a structure) Checkpoint each sharded layer (use_reentrant=False); use a memory policy that recomputes; scan or the graph splitter for large models; compute the peak with allgather_peak_bytes
Out of memory after turning on a prefetch or pipelining flag ICI_AG_PIPELINING and early prefetch keep one more layer full Budget a third layer in allgather_peak_bytes, or drop the flag
Out of memory at the LM head with a large vocabulary The [tokens, vocab] logits The fused Pallas cross-entropy; its token count must be a multiple of loss_b_block_size (1024) or it silently falls back to XLA
HBM higher than the state formula predicts with Graph Trainer optimizer_compile="in_graph" holds input and output copies of parameters and optimizer state optimizer_compile="separate_graph", or budget for the copy
Loss and gradient norm world_size times off after moving from FSDP2 SimpleFSDP sums gradients; FSDP2 averages Divide the loss (or the learning rate) by the world size
Training converges worse after sharded initialization Every rank seeded its shard with the same seed: the full weight repeats one block torch.manual_seed(base_seed + dist.get_rank())
Loss drifts from the reference over many steps reduce_dtype=torch.bfloat16, or a flag that reorders reductions reduce_dtype=torch.float32; check step-1 loss and gradient norm after every flag change
Step time never settles; compile logs every few steps Recompiles: shapes that change, or dynamic left at None so Dynamo switches a region to dynamic shapes after a recompile Fixed batch and sequence length; torch.compile(..., backend="tpu", dynamic=False); chapter 7
copy ops around every all-gather in the trace FSDP2's flat staging buffer SimpleFSDP (--parallelism.use_simple_fsdp)
Collectives in the trace with idle TensorCore beside them FSDP2 hooks or skinny collectives keep them out of the compiled program; or the scheduling flags are missing SimpleFSDP, compile the whole step, the recipe's latency-hiding and SparseCore bundles
Exposed reduce-scatter at the end of backward The last layers' gradients have no compute left to hide behind The recipe's scheduler flags; a small tail is expected (the Qwen3 235B case study keeps one)
Multi-slice job refuses to start, or trains at a fraction of the speed data_parallel_replicate_degree left at 1, so shard groups would straddle DCN --parallelism.data_parallel_replicate_degree=$MEGASCALE_NUM_SLICES and --parallelism.enable_min_cost_redistribute
Host memory exhausted on a v7x multi-slice job with offload MegaScale's pinned pool: 16 GiB per NUMA node per process, 8 processes per VM --megascale_grpc_premap_memory_bytes=4294967296 --megascale_use_numa_aware_block_allocator=false
ValueError that a dimension must divide by the world size (manual FSDP) Sharded dimension not divisible by the mesh size; SimpleFSDP instead replicates parameters too small to shard Make sharded dimensions divisible; shard_dim
Job hangs at a collective .item() or another materializing op inside a rank-specific branch Keep every rank on the same program (chapter 13)
Segfault when Graph Trainer compiles, libtpu 0.0.48+ Shardy HLO sharding v3 xla_enable_hlo_sharding_v3=False
Optimizer checkpoint fails to load Scan flipped on or off, or the kernel-native MoE layout changed, since it was saved Resume with the same structure, or convert the optimizer state
Device fails to initialize after a crash Stale libtpu lock rm -f /tmp/libtpu_lockfile

Verifying the result

Four checks, in the order you can run them.

1. Loss parity with a reference. Run the sharded job and an unsharded (or FSDP2) reference from the same initial weights and the same global batches, and compare the loss at every step for at least the first handful of steps, then the gradient norm. TorchTPU's FSDP guide asks for assert_close against an unsharded or FSDPv2 reference before scaling up, and its examples do exactly that: the migration worker checks losses and predictions of compiled FSDPv2 and SimpleFSDP, the manual worker checks gradients against a single-device CPU reference. In fp32 on CPU the companion demo agrees to about \(10^{-7}\); on TPU, with bf16 gathers, expect the tolerances of chapter 6, not bit equality. A factor of world_size in the gradient norm is the loss-scaling bug; a step-1 match followed by a slow drift is a precision or reduction-order change. Also measure what memory survives the forward-backward boundary: TorchTPU's manual_fsdp_memory_test.py checks that unsharded weights are freed after the forward pass.

2. A stable step time after warm-up. Step 0 compiles: 10.7 s for FSDPv2 and 8.2 s for SimpleFSDP in the tutorial, against tens of milliseconds afterwards. Judge only steady-state steps, and confirm they stay steady: a step time that jumps every few steps is a recompile. TorchTitan's --profiler.profiler_warmup skips warm-up steps before a trace, and --tpu_config.enable_mfu_benchmark emits one aggregate MFU measurement from --tpu_config.mfu_benchmark_start_step (default 5) to the end of the run.

3. MFU computed by hand. MFU is model FLOPs per second over the chip's peak. TorchTitan's convention, in models/utils.py: training FLOPs per token are \(6 \times\) the active parameters (every parameter except embedding tables not shared with the output head) plus, per layer, \(6 \times n_\text{heads} \times (d_{qk} + d_v) \times\) the attended tokens, with no discount for the causal mask and no count for recomputation:

\[ \text{MFU} = \frac{\text{tokens/s per chip} \times \big(6 P_\text{active} + \sum_\text{layers} 6\, n_\text{heads}\, (d_{qk} + d_v)\, S\big)}{\text{peak FLOP/s per chip}} \]

For the Llama 3 8B v6e-8 recipe above (dim 4,096, 32 layers, 32 query and 8 KV heads of 128, FFN 14,336, vocabulary 128,256, sequence 8,192), fsdp_memory.py gives \(P_\text{active} = 7{,}504{,}924{,}672\) and 57.91 GFLOP per token; \(5{,}383 \times 57.91 \times 10^{9} / 918 \times 10^{12} = 33.96\%\), the README's figure to the second decimal. Keep both numbers per chip or both per device: TorchTitan's get_peak_flops returns 2,307 TFLOP/s divided by 2 for a v7x device, and Google's case studies report v7x throughput per chip. Mixing the two is off by a factor of 2.

4. Scaling efficiency. Fix the batch per device, multiply the devices, and compare per-chip throughput in steady state: weak-scaling efficiency is \(\text{tokens/s per chip}(N) / \text{tokens/s per chip}(N_0)\). The published reference points on v7x: FLUX.1 holds 93% from 8 to 1,024 chips with HSDP; Muse Glimmer 30B goes from 6,096 to 5,768 tokens per second per chip between 8 and 128 chips (95%); Qwen3 235B keeps 92% from 64 to 8,192 chips across eight slices. Before you run, predict it: per layer, compare chapter 13's collective time with the matmul time. If the collectives fit behind the compute, efficiency should stay in the 90s; a drop the model does not predict is a layout or overlap problem, and an XProf trace of the collectives tells you which. Weak scaling grows the global batch with the chip count, so it measures the framework and the interconnect, not a training recipe: Google's own caveat is that the 8,192-chip Qwen3 run used a batch larger than anyone would train that model with.

Worked problems

Problem 1. Llama 3 8B has 8,030,261,248 parameters (7,504,924,672 active plus a 525,336,576-parameter embedding table). You train it with FSDP over a v6e-8, TorchTitan style: fp32 master weights and gradients, AdamW. (a) What is the persistent state per chip? (b) What do two gathered decoder layers add (each layer has 218,112,000 parameters)? (c) Could plain data parallelism hold it?

Answer

(a) memory_per_chip(8_030_261_248, 8, 4, 4, 8) \(= 8.03 \times 10^{9} \times 16 / 8 = 16.06 \times 10^{9}\) bytes, 14.96 GiB. (b) allgather_peak_bytes(218_112_000, 2, 2) \(= 0.87 \times 10^{9}\) bytes, 0.81 GiB in bf16. Together about 15.8 GiB of a v6e chip's 32 GiB, which leaves roughly 16 GiB for activations and temporaries. (c) No: unsharded, the state alone is 128.5 GB, four times a chip's HBM. Even the scaling book's 10 bytes per parameter (80 GB) does not fit.

Problem 2. You migrate a training loop on 8 devices from fully_shard to simple_fsdp.data_parallel and keep loss.backward(). The model uses AdamW and TorchTitan's default gradient clipping (max_norm=1.0). What changes in the gradients, why might the loss curve still look almost right for a while, and how do you fix it?

Answer

FSDP2 averages gradients across the 8 ranks; SimpleFSDP's Partial(reduce_op="sum") adds them, so every gradient is 8 times larger and the logged gradient norm is 8 times higher. AdamW divides the first moment by the square root of the second, so a constant scale on the gradient mostly cancels in the update, apart from eps; that is why the curve can look plausible. Clipping does not cancel: a norm 8 times larger crosses max_norm far more often and clips steps the reference would not. Divide the loss by the world size before backward() (or scale the learning rate, as the tutorial allows), then confirm step-1 loss and gradient norm against the FSDP2 run.

Problem 3. A Llama 3 8B run on a v7x slice logs 2,700 tokens per second per device. Compute its MFU correctly, and say what you would get by dividing by the per-chip peak.

Answer

Per device: 57.91 GFLOP per token at sequence 8,192 (as in the recipe check), so \(2{,}700 \times 57.91 \times 10^{9} = 1.564 \times 10^{14}\) FLOP/s, over TorchTitan's per-device peak of \(2{,}307 \times 10^{12} / 2 = 1{,}153.5 \times 10^{12}\): 13.6%. Per chip is the same: two devices give 5,400 tokens per second per chip, over 2,307 TFLOP/s. Dividing the per-device rate by the per-chip peak gives 6.8%, half the true figure. mfu(tokens_per_s_per_chip, flops_per_token, peak_flops_per_chip) keeps both sides per chip.

Problem 4. In the Llama 3 8B v6e-8 recipe each chip processes 16,384 tokens per step at 5,383 tokens per second. Use fsdp_comm_bytes_per_step and chapter 13's ring model (90 GB/s per link; treat the 8 chips as one ring without wraparound, as chapter 13 does for 8 v6e chips) to estimate the FSDP traffic per step and its time. Is the step communication-bound?

Answer

Step time: \(16{,}384 / 5{,}383 = 3.04\) s. Traffic: two bf16 gathers and one fp32 reduce-scatter of 8.03B parameters, \(8 \times 8.03 \times 10^{9} \times 7/8 = 56.2\) GB sent per device. One way at 90 GB/s that is about 0.62 s; with a wraparound ring it would be half. So the collectives need about 20% of the step if nothing overlaps them, and almost nothing if the scheduler hides them behind the matmuls. The step is compute-bound: the recipe has 16,384 tokens per device, well above chapter 13's threshold of about 5,100 (twice that without wraparound). The 34% MFU is limited by what runs on the TensorCore, which is why the playbook's next levers are kernels, batch and Graph Trainer, not the mesh.

Problem 5. In the FLUX.1 case study on a v6e-8, replacing FSDP2 with SimpleFSDP took the step from 9.95 s to 6.52 s, before any torch.compile. Per-block compile later took 5.55 s to 3.02 s. Which cost did each change remove, and why does the first one help even though the model was not yet compiled?

Answer

SimpleFSDP removed data movement: FSDP2's copies of every shard into a flat staging buffer before each all-gather, and back out into per-parameter tensors afterwards, which the trace showed dominating the step. SimpleFSDP gathers each parameter directly, so the buffer and both copies disappear; that saves HBM round trips whether or not the step is compiled. Per-block compile removed dispatch: each block became one XLA program instead of many small ones, and the collectives of a block could be scheduled with its matmuls. The order matters because each fix changes what the next measurement means: with the copies gone, the trace showed the dispatch gaps that compilation then closed.

Problem 6. A 30B model trains on two v7x slices of 64 chips (128 devices each), with 16 bytes of state per parameter. (a) Compare per-device state for FSDP over all 256 devices and HSDP with 128-way sharding replicated twice. (b) Why does TorchTitan refuse to start the first layout across slices? (c) What does --parallelism.enable_min_cost_redistribute change about the DCN traffic, for 4 bytes of fp32 gradient per parameter?

Answer

(a) FSDP over 256: \(30 \times 10^{9} \times 16 / 256 = 1.875\) GB per device. HSDP: \(30 \times 10^{9} \times 16 / 128 = 3.75\) GB per device, twice as much, the replicate degree. Both are far below 96 GiB, so memory does not decide here. (b) With data_parallel_replicate_degree=1 the only axis left to split across DCN is the shard axis, so every FSDP group straddles the slices and every layer's all-gather and reduce-scatter crosses DCN. The job would be correct and slow, and TorchTitan refuses to start because a slow job is harder to notice than one that will not launch. (c) Without it, DTensor's greedy planner all-reduces the full 120 GB of fp32 gradient across the replicate axis before reduce-scattering; with it, the reduce-scatter inside each slice comes first and only each device's 1/128 shard crosses DCN, shrinking the payload by the shard degree, chapter 13's 86 ms against 1.3 ms argument.

Quick questions

  1. Which DTensor placements does an FSDP parameter pass through in one step, and which collective moves it between each?
  2. Why does per-layer activation checkpointing add a second all-gather per layer, and what does it buy?
  3. Why is FSDP's communication volume the same as plain data parallelism's, and when does each become communication-bound?
  4. Write the persistent memory per device for \(P\) parameters on \(n\) shards, and name the terms it leaves out.
  5. Why do FSDP2's hooks prevent a whole-step graph on TPU, and what else did they cost in the FLUX case study?
  6. What does ReplicateComputation do when a module reads its weight, and where do param_dtype and reduce_dtype apply?
  7. How do you select a recipe, override one field, and change one libtpu flag in a TorchTitan TPU launch?
  8. What does Graph Trainer capture that per-block compile does not, and what does optimizer_compile="in_graph" cost?
  9. When do you reach for scan over layers, and when for the graph splitter?
  10. Name the four checks that a sharded run is correct and fast, and the trap in computing MFU on v7x.

Key takeaways

  • FSDP is chapter 13 applied: each weight rests as Shard(0), is all-gathered to Replicate() before use, and its Partial() gradient is reduce-scattered back to a shard; AdamW then updates the shard with no communication. With per-layer checkpointing that is two all-gathers and one reduce-scatter per layer and step, the same volume as data parallelism's all-reduce plus one gather.
  • Persistent memory per device is \(P(b_p + b_g + b_o)/n\): 10, 12 or 16 bytes per parameter depending on the budget, 16 for TorchTitan's fp32 master weights. The gathered layers, activations and the in-graph optimizer's copy come on top and do not shrink with \(n\).
  • On TPU use SimpleFSDP or manual FSDP, not FSDP2: their collectives are nodes in the traced graph, so XLA can overlap them and there are no staging copies. Gather in bf16, reduce in fp32, divide the loss by the world size, seed shards per rank.
  • TorchTitan's TPU lane is configured in Python: --module and --config pick a recipe function, --section.field overrides it, and libtpu flags are config fields. Launch with torchrun ... -m torchtitan.experiments.tpu.train; across slices set data_parallel_replicate_degree to the slice count.
  • Graph Trainer traces forward, loss, backward and optionally AdamW into one program, removing the host gaps per-block compile leaves; past about 100B parameters, scan or the graph splitter plus host offload make the step compile and fit.
  • Trust a run when its loss matches a reference at the right tolerance, its steady-state step time is flat after compilation, its hand-computed MFU matches the logged one, and its weak-scaling efficiency matches what chapter 13's cost model predicts. Chapter 15 puts this trainer inside a reinforcement learning loop; chapter 16 takes a full 30B run apart.

References