FSDP on TorchTPU¶
Use this guide when your own training loop (not a TorchTitan recipe) needs Fully Sharded Data Parallel on TPU: the model's parameters, gradients and optimizer state do not fit one device, or you want to scale data parallelism without replicating them. TorchTPU's FSDP guide recommends SimpleFSDP, which puts the all-gather and reduce-scatter inside the compiled program so XLA can overlap them with compute; this page applies it, migrates from PyTorch FSDP2 (fully_shard) if you have it, and checks the result. Chapter 14 explains why FSDP2's hooks hurt on TPU and how to size the shard group. To train inside TorchTitan, use Run TorchTitan on TPU, where SimpleFSDP is one flag.
Prerequisites¶
- A TPU host that passes Install TorchTPU on a TPU VM; the examples assume 8 TPU devices (for example
v6e-8, or a four-chip v7x host). simple_fsdp.py, shipped asexamples/fsdp/simple_fsdp.pyin the TorchTPU repository, is self-contained and depends only on PyTorch.- A model whose sharded dimensions divide by the number of devices, or are small enough to be replicated.
Steps¶
1. Check that sharding is what you need¶
python code/ch14_fsdp/fsdp_memory.py --params <your parameter count> (this book's companion) prints the persistent state per shard for three byte budgets and the smallest group that fits v6e and v7x. It counts parameters, gradients and optimizer moments only; activations and the gathered layers come on top.
Check: the smallest fitting group is no larger than your device count. If it is, you need more devices, a smaller per-device batch, or tensor parallelism as well.
2. Initialize the process group and the mesh¶
import torch
from torch import distributed as dist
import torch.distributed.tensor as dt
dist.init_process_group(backend="tpu_dist")
world_size = dist.get_world_size()
mesh = dt.init_device_mesh("tpu", (world_size,), mesh_dim_names=("fsdp",))
On a real slice, build the mesh with torch.tpu.distributed.topology_aware_mesh (chapter 13).
Check: every rank reaches the line after init_device_mesh.
3. Checkpoint each layer, then shard with one call¶
import functools
from torch.utils import checkpoint as checkpoint_utils
import simple_fsdp
mp_policy = simple_fsdp.MixedPrecisionPolicy(
param_dtype=torch.bfloat16,
reduce_dtype=torch.float32,
)
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", # "replicate", "fully_shard", or "hybrid_shard"
mp_policy=mp_policy,
)
Activation checkpointing on each sharded layer frees the gathered weights after the layer's forward pass instead of keeping them until backward. The mixed-precision policy here is TorchTitan's: gather in bf16, reduce in fp32. TorchTPU's README example uses param_dtype=torch.float32, reduce_dtype=torch.bfloat16 for its toy model; TorchTitan's optimization guide calls dropping reduce_dtype to bf16 "a model-quality regression, not a perf lever". Parameters smaller than the mesh along the sharding dimension are replicated; pass shard_dim (an int or a dict from parameter name to dimension) to shard along another dimension, and ignored_params for frozen or tied weights. For HSDP use mode="hybrid_shard" on a 2D mesh (replicate on the first dimension, shard on the second).
If each rank initializes its own shard, seed ranks differently, torch.manual_seed(base_seed + dist.get_rank()), or every shard is the same random block.
Check: inside with simple_fsdp.disable_active_parametrization():, reading a weight returns its sharded DTensor, so you can confirm each rank holds a 1 / world_size slice.
4. Compile the step and scale the loss¶
compiled_model = torch.compile(model, backend="tpu")
def train_step(model, x, y, world_size):
y_pred = model(x)
loss = loss_fn(y_pred, y)
(loss / world_size).backward()
return loss.detach()
SimpleFSDP reduces gradients with a sum (FSDP2 averages), so divide the loss (or the learning rate) by the world size. Compile as much of the step as you can: TorchTPU's guide asks for the whole step, or at least forward, loss and backward together. Keep every rank on the same program: no .item() inside an if rank == 0 branch.
Check: step 0 is slow (it compiles: 8.2 s for SimpleFSDP in TorchTPU's tutorial) and later steps settle to a steady time.
5. Launch one process per device¶
eval "$(python3 -m torch.tpu.distributed)"
export TORCH_TPU_TOPOLOGY TORCH_TPU_SLICEBUILDER_ADDRESSES WORLD_SIZE
torchrun --nproc_per_node=${WORLD_SIZE:-8} your_fsdp_worker.py
This is the launcher pattern of TorchTPU's run_fsdp_to_simple_fsdp.sh. TorchTPU's reference run, from examples/fsdp in its repository, is bash ./fsdp_to_simple_fsdp/run_fsdp_to_simple_fsdp.sh. On GKE, put that command in the container of examples/tensor_parallel/torchtpu_singlehost_slice_job.yaml (Run TorchTPU on GKE).
Check: all ranks finish. In the reference run, compiled FSDPv2 and compiled SimpleFSDP print matching losses (identical to six decimals) and their step times.
6. Prove parity and memory before scaling up¶
Compare the sharded job with an unsharded (or FSDP2) run from the same initial weights and the same global batches: loss at every step for the first handful of steps, then the gradient norm, with assert_close. TorchTPU's manual FSDP example also measures that unsharded weights are freed after the forward pass (python3 manual_fsdp_memory_test.py in examples/fsdp/manual/).
This book's companion runs the same checks on CPU processes:
python code/ch14_fsdp/simple_fsdp_demo.py --cpu-smoke # any machine; ends "cpu-smoke: OK"
eval $(python3 -m torch.tpu.distributed | sed 's/^/export /')
torchrun --nproc_per_node=$WORLD_SIZE code/ch14_fsdp/simple_fsdp_demo.py --tpu # TPU VM
Check: step-1 loss matches the reference within the dtype's tolerance (about \(10^{-7}\) in fp32 on CPU; bf16 tolerances on TPU with bf16 gathers). A factor of world_size in the gradient norm is the loss-scaling bug; a step-1 match followed by slow drift is a precision or reduction-order change (Parity-check a port).
7. Migrating from FSDP2¶
Replace the per-layer fsdp.fully_shard(layer, ...) calls, the final fully_shard(model, ...) and every set_modules_to_forward_prefetch / set_modules_to_backward_prefetch list with step 3's single data_parallel call, keep the per-layer checkpointing, and add the loss / world_size scaling of step 4. TorchTPU's FSDPv2 to SimpleFSDP tutorial (examples/fsdp/fsdp_to_simple_fsdp/fsdp_to_simple_fsdp.md) shows both side by side.
Check: the losses of the two implementations agree step for step from identical initial weights, and the steady step time drops (about 3 times on the tutorial's toy model; carry the mechanism, not the factor).
Troubleshooting¶
| Symptom | Cause | Fix |
|---|---|---|
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 |
| Out of memory at step 1, peak at the all-gathers | No per-layer activation checkpointing, so every gathered layer lives until backward | checkpoint(..., use_reentrant=False) on each sharded layer |
| Training converges worse after sharded initialization | Every rank seeded its shard with the same seed | torch.manual_seed(base_seed + dist.get_rank()) |
| Loss drifts from the reference over many steps | reduce_dtype=torch.bfloat16 |
reduce_dtype=torch.float32 |
copy ops around every all-gather in the trace |
FSDP2's flat staging buffer | SimpleFSDP |
| Collectives in the trace with the TensorCore idle beside them | Collectives outside the compiled program (FSDP2 hooks), or the step compiled in pieces | SimpleFSDP; compile the whole step |
ValueError that a dimension must divide by the world size (manual FSDP) |
Sharded dimension not divisible by the mesh size | Make it divisible, or use SimpleFSDP with shard_dim |
| Job hangs at a collective | .item() or another materializing op inside a rank-specific branch |
Keep every rank on the same program |
| Step time never settles | Recompiles from changing shapes | Fixed batch and sequence length; torch.compile(..., backend="tpu", dynamic=False) |
| Device fails to initialize after a crash | Stale libtpu lock | rm -f /tmp/libtpu_lockfile |
References¶
- TorchTPU docs: FSDP best practices
- torch_tpu repository: SimpleFSDP on TorchTPU
- torch_tpu repository: examples/fsdp/fsdp_to_simple_fsdp
- torch_tpu repository: examples/fsdp/manual
- TorchTitan TPU experiments: Guide to optimizing LLMs on TorchTPU
- torch_tpu 0.2.0: examples/fsdp
- Companion code: code/ch14_fsdp/
- Chapter 14: FSDP and TorchTitan on TPU