Back to Blogs
#machinelearning#pytorch#python#tutorial

Scaling PyTorch Across Cloud TPU Slices & Pods: SimpleFSDP, DTensor TP, Pallas RDMA & vLLM (Part 5)

Scale native PyTorch across Cloud TPU slices (ICI) and multi-slice pods (DCN) with tpu_dist, topology_aware_mesh, @spmd_safe, SimpleFSDP + DTensor Tensor Parallelism (0 graph breaks!), 4-device verified Pallas RDMA, GKE JobSet recipes, and vllm-torchtpu serving.

8 min read
Cover for Scaling PyTorch Across Cloud TPU Slices & Pods: SimpleFSDP, DTensor TP, Pallas RDMA & vLLM (Part 5)

Open Full Tutorial In Colab
Open 5-Min Quickstart In Colab

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

Cloud TPU Slice ICI Torus vs Multi-Slice Pod DCN Topology

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"): Because libtpu allows only one OS process to hold /dev/vfio/0 at a time, setting os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" in the parent Jupyter notebook keeps the coordinator strictly on CPU while child torchrun jobs, HLO collective probes, and vllm-torchtpu servers 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 emits reduce_scatter in backward — 100% inside one unbroken FX graph (0 graph breaks) so XLA overlaps ICI collectives with MXU matmuls!

Four Essential Composition Rules in scripts/train_pod.py

  1. Topology-Aware Rank Ordering: Call rank_tensor = torch.tpu.distributed.topology_aware_mesh(mesh_shape=mesh_shape) and pass it into DeviceMesh("tpu", mesh=rank_tensor, mesh_dim_names=dim_names) so adjacent ranks sit on physically adjacent ICI torus neighbors.
  2. Parallelize Order: Apply DTensor Tensor Parallelism (ColwiseParallel / RowwiseParallel, computing local attention head counts dynamically via q.shape[-1] // self.head_dim) before inside-block checkpoint(..., use_reentrant=False) and simple_fsdp.data_parallel(...).
  3. 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 keep optimizer.step() outside fullgraph=True.
  4. Scale (raw_loss / dp_total_size).backward(): SimpleFSDP reduces gradients with Partial(reduce_op="sum"), so dividing by dp_total_size keeps 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}
Enter fullscreen mode Exit fullscreen mode
  • Loss convergence: 10.4027 -> 0.3723 in 10 steps at 5.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']
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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): Exports python3 -m torch.tpu.distributed topology variables on every TPU VM host, computes NPROC_PER_NODE=$(( WORLD_SIZE / NNODES )), unsets host WORLD_SIZE so torchrun assigns per-worker ranks cleanly, and distinguishes LIBTPU_INIT_ARGS (--xla_tpu_* flags) from XLA_FLAGS (--xla_dump_* flags).
  • GKE Autopilot/Standard JobSet Manifest (recipes/gke/tpu_pod_jobset.yaml): Configures 2 slices of tpu-v6e-slice (4x4 topology = 16 chips/slice, 32 chips total), google.com/tpu: 4 per pod, hostNetwork: true, and a 16Gi RAM-backed /dev/shm volume for multi-process Tier-2 compilation caching.
  • High-Throughput Serving with vllm-torchtpu (scripts/serve_vllm_tpu.py): Installs vllm-torchtpu into an isolated Python 3.12 uv virtual environment (--extra-index-url https://download.pytorch.org/whl/cpu --index-strategy unsafe-best-match) with gpu_memory_utilization=0.60. Note on hardware support: upstream vllm-torchtpu V1 EngineCore validates Cloud TPU Trillium (v6e) and Ironwood (v7x) slices, whereas free Colab v5e-1 instances should use the 36.25x compiled Hugging Face StaticCache path from Part 1 (and switch to serve_vllm_tpu.py when deploying on v6e / v7x Cloud 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.

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!