Companion GitHub Repository: agemagician/torchtpu-zero-to-hero
One Unbroken FX Graph Across SimpleFSDP + DTensor Tensor Parallelism — From 1-Chip Colab to Multi-Slice TPU Pods
Welcome to the finale of TorchTPU: Zero to Hero! Over Parts 1–4, we went from torch.device("tpu") inference (36.25x speedup) through scratch pre-training, LoRA SFT (20,511 tok/s), DPO, live online GRPO RL (0.0% -> 96.9%), and VMEM-tiled splash_sdpa (19.8x less HBM at 4K).
Now we scale out: across Cloud TPU Slices connected via optical/copper 2D/3D torus Inter-Chip Interconnect (ICI) and Multi-Slice TPU Pods connected across slices via Data Center Network (DCN) — plus high-throughput production serving with vllm-torchtpu.
Every worker script we build and execute in Part 5 (scripts/train_pod.py, scripts/pallas_rdma_demo.py, and scripts/serve_vllm_tpu.py) runs unmodified from WORLD_SIZE=1 Google Colab up to 32+ chip Trillium (v6e) and Ironwood (v7x) TPU Pods!
Series Roadmap
| Part | Focus Area | Colab Notebooks |
|---|---|---|
| Part 1 | TPU Hardware Mental Model, Execution Modes & 36x Faster StaticCache Inference |
Full Tutorial · 5-Min Quickstart |
| Part 2 | Pre-Training Causal Transformers (SingleTraceTrainer, AdamW & Muon) & Native PEFT LoRA SFT |
Full Tutorial · 5-Min Quickstart |
| Part 3 | Post-Training Alignment (Compiled DPO), Live Online GRPO RL & Disaggregated Pod RL (VeRL) |
Full Tutorial · 5-Min Quickstart |
| Part 4 | FlashAttention on TPUs (splash_sdpa), Verified Custom Pallas Kernels, MXU Precision & XProf |
Full Tutorial · 5-Min Quickstart |
| Part 5 (You are here) | Cloud TPU Slices & Pods: tpu_dist, SimpleFSDP + DTensor TP, Pallas RDMA & vllm-torchtpu |
Full Tutorial · 5-Min Quickstart |
1. TPU Slice vs. Multi-Slice Pod Topology & The CPU Coordinator Pattern
To place PyTorch parallelism dimensions onto physical TPU networks without bandwidth bottlenecks, map each communication pattern to its matching link tier:
| Parallelism Axis | Collective Traffic | Target Interconnect |
DeviceMesh Dimension |
|---|---|---|---|
| Tensor Parallelism (TP) | Per-layer activation all_reduce / reduce_scatter
|
Fastest inner ICI ring (tp=2..8) |
Innermost ("tp") |
FSDP Sharding (fully_shard) |
Per-layer parameter all_gather + grad reduce_scatter
|
Intra-slice ICI torus | Middle ("dp" or "dp_shard") |
HSDP Replication (hybrid_shard) |
Once-per-step gradient all_reduce across slices |
Cross-slice DCN Ethernet | Outermost ("dp_replicate") |
Subprocess Isolation Trick for 1-Chip Colab (
TORCH_DEVICE_BACKEND_AUTOLOAD="0"): Becauselibtpuallows only one OS process to hold/dev/vfio/0at a time, settingos.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"in the parent Jupyter notebook keeps the coordinator strictly on CPU while childtorchrunjobs, HLO collective probes, andvllm-torchtpuservers acquire and cleanly release the TPU!
2. tpu_dist, topology_aware_mesh, @spmd_safe & Why SimpleFSDP Beats FSDPv2
TorchTPU ships its own C++ ProcessGroup backend — dist.init_process_group(backend="tpu_dist") — which routes collectives directly over ICI (via XLA collective HLOs) and DCN (via host-coordinated transfers) with no external NCCL dependency.
Why SimpleFSDP instead of PyTorch FSDPv2 (fully_shard)?
PyTorch's imperative FSDPv2 (fully_shard) attaches Python pre-forward and post-backward runtime hooks that break torch.compile into fragmented subgraphs. SimpleFSDP (originating in Meta's TorchTitan and shipped in torch_tpu/examples/fsdp/simple_fsdp.py) wraps parameters as sharded DTensors via nn.utils.parametrize:
- Forward parameter access triggers
DTensor.redistribute(all_gather), and autograd automatically emitsreduce_scatterin backward — 100% inside one unbroken FX graph (0graph breaks) so XLA overlaps ICI collectives with MXU matmuls!
Four Essential Composition Rules in scripts/train_pod.py
-
Topology-Aware Rank Ordering: Call
rank_tensor = torch.tpu.distributed.topology_aware_mesh(mesh_shape=mesh_shape)and pass it intoDeviceMesh("tpu", mesh=rank_tensor, mesh_dim_names=dim_names)so adjacent ranks sit on physically adjacent ICI torus neighbors. -
Parallelize Order: Apply
DTensorTensor Parallelism (ColwiseParallel/RowwiseParallel, computing local attention head counts dynamically viaq.shape[-1] // self.head_dim) before inside-blockcheckpoint(..., use_reentrant=False)andsimple_fsdp.data_parallel(...). -
Decorator Order &
@spmd_safe: Place outer@torch.compile(backend="tpu", fullgraph=True, dynamic=False)on top of inner@torch.tpu.distributed.spmd_safe(skipping redundant cross-rank collective rendezvous handshakes when every rank runs identical SPMD code!), and keepoptimizer.step()outsidefullgraph=True. -
Scale
(raw_loss / dp_total_size).backward():SimpleFSDPreduces gradients withPartial(reduce_op="sum"), so dividing bydp_total_sizekeeps gradient magnitudes invariant across slice sizes.
Measured torchrun Execution on Google Colab TPU v5e-1:
Detected TPU Topology Env: {'TORCH_TPU_TOPOLOGY': '1,1,1', 'TORCH_TPU_SLICEBUILDER_ADDRESSES': 'localhost:43083', 'WORLD_SIZE': '1', 'NODE_RANK': '0'}
Parsed Pod Metrics: {'world_size': 1, 'mesh_dims': ['dp'], 'loss_first': 10.4027, 'loss_last': 0.3723, 'steady_ms_per_step': 5.55, 'peak_hbm_gb': 0.874, 'graph_breaks': 0}
-
Loss convergence:
10.4027 -> 0.3723in 10 steps at5.55 ms/step -
Peak child TPU HBM:
0.874 GiB(88.8%XLA compilation cache hit rate) -
Dynamo graph breaks:
0
3. Dual Compiler Proof: Real TPU StableHLO Dump + 8-Rank 2D (dp=4, tp=2) AOTAutograd Audit
On a single-chip Colab VM (WORLD_SIZE=1), XLA's post-optimization pass folds away single-replica collectives. How do we prove on 1-chip Colab what our code lowers to on an 8-chip v6e-8 slice? With two deterministic compiler audits:
Audit 5A: Real TPU StableHLO MLIR Collective Lowering
Setting XLA_FLAGS="--xla_dump_hlo_as_text --xla_dump_to=/tmp/hlo_collectives" alongside TORCHINDUCTOR_FX_GRAPH_CACHE="0" (so PyTorch's AOTAutogradCache does not short-circuit XLA compilation on repeat runs!) and compiling all_gather_dim, reduce_scatter_dim, and dist.all_reduce under @spmd_safe produced:
Dumped 4 MLIR files and 4 pre-opt HLO files | Matched collective IR ops:
['stablehlo.all_reduce', 'stablehlo.all_gather', 'stablehlo.reduce_scatter', 'all-reduce', 'all-gather', 'reduce-scatter']
Audit 5B: 8-Rank 2D (dp=4, tp=2) Virtual-Mesh SimpleFSDP + TP vs. FSDPv2
Using FakeStore (world_size=8) and aot_autograd graph capture across a 2-layer Transformer on CPU:
8-Rank 2D (dp=4, tp=2) SimpleFSDP + TP -> fw_graphs=1, bw_graphs=1, breaks=0, collectives=['all_gather', 'reduce_scatter', 'all_reduce']
8-Rank 1D FSDPv2 (`fully_shard`) -> fw_graphs=3, bw_graphs=3, breaks=1
SimpleFSDP + DTensor TP lowers the entire 2D-parallel model into 1 forward graph + 1 backward graph (0 graph breaks) with all three collectives inline, whereas FSDPv2 fragments into 3 forward + 3 backward subgraphs!
4. Direct Inter-Chip Pallas RDMA (pltpu.make_async_remote_copy) + 4-Device Verification
When building ring attention or custom MoE dispatchers, scripts/pallas_rdma_demo.py pairs torch.tpu.pallas.get_pallas_mesh with pltpu.make_async_remote_copy and hardware DMA semaphores (pltpu.SemaphoreType.DMA) for zero-CPU chip-to-chip memory transfers over ICI.
Even on a 1-chip machine, --verify spawns 4 virtual XLA devices (--xla_force_host_platform_device_count=4) and formally validates shard_map partition specs, semaphore descriptors, and Mosaic TPU lowering via torch.tpu.pallas.verifier.verify:
RDMA_VERIFY_PASSED: True
RDMA_CHECKED_PHASES: ['Phase.CONTRACTS', 'Phase.LOWERING']
5. Production Multi-Host Launch Recipes & vllm-torchtpu Serving
In the companion repository, you will find ready-to-run Cloud TPU deployment manifests:
-
Cloud TPU VM Slice & Multi-Slice Launcher (
recipes/tpu_vm/launch_slice_and_pod.sh): Exportspython3 -m torch.tpu.distributedtopology variables on every TPU VM host, computesNPROC_PER_NODE=$(( WORLD_SIZE / NNODES )), unsets hostWORLD_SIZEsotorchrunassigns per-worker ranks cleanly, and distinguishesLIBTPU_INIT_ARGS(--xla_tpu_*flags) fromXLA_FLAGS(--xla_dump_*flags). -
GKE Autopilot/Standard
JobSetManifest (recipes/gke/tpu_pod_jobset.yaml): Configures2slices oftpu-v6e-slice(4x4topology =16chips/slice,32chips total),google.com/tpu: 4per pod,hostNetwork: true, and a16GiRAM-backed/dev/shmvolume for multi-process Tier-2 compilation caching. -
High-Throughput Serving with
vllm-torchtpu(scripts/serve_vllm_tpu.py): Installsvllm-torchtpuinto an isolated Python 3.12uvvirtual environment (--extra-index-url https://download.pytorch.org/whl/cpu --index-strategy unsafe-best-match) withgpu_memory_utilization=0.60. Note on hardware support: upstreamvllm-torchtpuV1EngineCorevalidates Cloud TPU Trillium (v6e) and Ironwood (v7x) slices, whereas free Colabv5e-1instances should use the36.25xcompiled Hugging FaceStaticCachepath from Part 1 (and switch toserve_vllm_tpu.pywhen deploying onv6e/v7xCloud TPU VMs or GKE).
6. Quick Troubleshooting Reference
| Symptom | Root Cause | Fix |
|---|---|---|
Empty HLO collective dump on repeat runs despite XLA_FLAGS="--xla_dump_to=..."
|
PyTorch AOTAutogradCache short-circuited XLA compilation |
Set TORCHINDUCTOR_FX_GRAPH_CACHE="0" alongside disabling Tier-2/Tier-3 caches when dumping IR |
ModuleNotFoundError: No module named 'torch.tpu' in child CPU script |
Parent inherited TORCH_DEVICE_BACKEND_AUTOLOAD="0"
|
Pass TORCH_DEVICE_BACKEND_AUTOLOAD="1" (TorchTPU defers /dev/vfio lock until torch.device("tpu") is used!) |
--xla_tpu_* flag rejected as unknown flag |
Placed in XLA_FLAGS instead of LIBTPU_INIT_ARGS
|
Put --xla_tpu_* flags in LIBTPU_INIT_ARGS and --xla_dump_* flags in XLA_FLAGS before import torch
|
Multi-host torchrun rank collision |
python3 -m torch.tpu.distributed sets slice WORLD_SIZE in shell |
Compute NPROC_PER_NODE=$(( WORLD_SIZE / NNODES )), then unset WORLD_SIZE before torchrun
|
Series Wrap-Up & Credits
Across all 5 parts of TorchTPU: Zero to Hero, we went from a 5-line torch.device("tpu") inference snippet to pre-training Transformers with SingleTraceTrainer, fine-tuning LLMs at 20,511 tok/s with LoRA, training reasoning models to 96.9% math accuracy with live online GRPO RL, writing formally verified VMEM-tiled Pallas kernels (splash_sdpa + jax_op), and scaling SimpleFSDP + DTensor Tensor Parallelism across Cloud TPU Pods with zero graph breaks.
-
Part 1: TPU Hardware Mental Model & 36x Faster
StaticCacheInference -
Part 2: Pre-Training Transformers (
SingleTraceTrainer,AdamW&Muon) & LoRA SFT - Part 3: Post-Training Alignment (DPO), Live Online GRPO RL & Disaggregated Pod RL
-
Part 4: FlashAttention on TPUs (
splash_sdpa), Verified Custom Pallas Kernels & XProf - Star & Fork the Full Companion Repo: github.com/agemagician/torchtpu-zero-to-hero
- Official TorchTPU Repo: github.com/google-pytorch/torch_tpu
- vLLM TorchTPU Plugin: github.com/vllm-project/vllm-torchtpu
Credits
Deep appreciation to the Google and Meta TorchTPU teams (and authors of SimpleFSDP across TorchTitan and torch_tpu), the vLLM & VeRL communities, the JAX/Pallas & OpenXLA teams, and the Google Developer Experts (GDE) program.
Which part of the TorchTPU stack — StaticCache inference, SingleTraceTrainer, online GRPO RL, splash_sdpa Pallas kernels, or multi-slice SimpleFSDP pods — are you planning to deploy in your next project? Let me know in the comments!

