Fundamentals: vocabulary, hardware and the ecosystem map¶
Related chapters
Chapter 1 (hardware), chapter 2 (rooflines) and chapter 3 (the stack and the CUDA translation table). The verified lookup tables are in the Reference section: hardware, glossary, CUDA to TorchTPU and the torch.tpu API matrix.
Prerequisites: Basic familiarity with PyTorch (
torch.Tensor,nn.Module,torch.distributed) and standard GPU concepts (SMs, HBM, CUDA streams).Covers: Cloud TPU hardware constants (
v4throughv8i/v8t), the six-layer software stack, core C++ and Python symbols, feature status, and CUDA to TorchTPU API translations.
1.1 Cloud TPU hardware generations (v4, v5e, v5p, v6e, v7x, v8i/v8t)¶
In one sentence¶
Unlike GPUs, which use dozens of streaming multiprocessors (SMs) with hardware-managed L1/L2 caches and SIMT warp schedulers, a Google Cloud TPU is a compiler-scheduled, bulk-synchronous VLIW domain-specific processor built around large 2D Matrix Multiply Units (MXUs), wide Vector Processing Units (VPUs), explicit software-managed VMEM/SMEM SRAM scratchpads, dedicated SparseCores for irregular gather/scatter and collectives, and direct chip-to-chip optical Inter-Chip Interconnect (ICI) torus/Boardfly links.
Note
How it works: a single-threaded systolic array instead of a SIMT thread hierarchy
A GPU saturates compute by launching thousands of scalar threads grouped into warps across dozens of SMs; if one warp stalls on memory, the hardware warp scheduler swaps in another warp. A TPU TensorCore has no hardware warp scheduler and is fundamentally single-threaded: its compiler (OpenXLA / Mosaic / LLO) packs independent scalar, vector (8x128 VPU), matrix (256x256 MXU), and asynchronous DMA instructions into a single wide Very Long Instruction Word (VLIW) bundle every clock cycle. Peak utilization therefore requires wide, (8, 128)-aligned tensor shapes and compiler-scheduled async DMA double-buffering between HBM and VMEM.
Inside a TPU chip (v6e single core, v7x dual chiplet)¶
A v6e chip is one PyTorch device. A v7x chip is two devices, each a chiplet with its own TensorCore, SparseCores and HBM; the two are joined by a die-to-die link of 600 GB/s each way and share the chip's six ICI links.
VMEM capacity
VMEM capacity differs by generation, so read it at runtime with pltpu.get_tpu_info().vmem_capacity_bytes (chapter 12). On v7x it is 64 MiB of physical VMEM per core, with a 32 MiB default scoped limit (Chip constants and compiler hard limits).
Hardware reference table¶
Sources: tpu_hardware.cc, _device_module.py, TPU v7x (Ironwood) Specification and Chip constants and compiler hard limits.
| Hardware Dimension | TPU v4 | TPU v5e | TPU v5p | TPU v6e (Trillium) | TPU v7x (Ironwood) | TPU v8i / v8t (Next-Gen) |
|---|---|---|---|---|---|---|
PCI Device ID (0x1ae0) |
Legacy (libtpu probe) |
0x0063 |
0x0062 |
0x006f |
0x0076 (GhostFish) |
v8i: 0x0083 / v8t: 0x007c |
| Logical Devices / Chip | 1 (2 TCs in Megacore) | 1 (1 TensorCore) | 1 (2 TCs in Megacore) | 1 (1 TensorCore) | 2 (devices_per_chip=2, split dual-chiplet, no Megacore) |
v8i: 2 / v8t: 1 |
| TensorCores / Logical Device | 2 (fused as Megacore) | 1 | 2 (fused as Megacore) | 1 | 1 per chiplet (2 chiplets/package) | 1 per logical device |
| MXU Array Dimensions | \(4 \times (128 \times 128)\) / TC | \(4 \times (128 \times 128)\) / TC | \(4 \times (128 \times 128)\) / TC | \(2 \times (256 \times 256)\) / TC | \(2 \times (256 \times 256)\) / chiplet (\(4 \times 256^2\) / chip) | \(256 \times 256\) systolic arrays |
Minimum MXU Tile ((sublane, lane)) |
\((8, 128)\), mxu_dim=128 |
\((8, 128)\), mxu_dim=128 |
\((8, 128)\), mxu_dim=128 |
\((8, 128)\), mxu_dim=256 |
\((8, 128)\), mxu_dim=256 |
\((8, 128)\), mxu_dim=256 |
| VPU Architecture (Sublanes \(\times\) Lanes) | \(8 \times 128\) FP32 ALU | \(8 \times 128\) FP32 ALU | \(8 \times 128\) FP32 ALU | \(8 \times 128\) FP32 ALU (2× clock/width) | \(8 \times 128\) (1,024 ALUs); \(55.8\text{ TFLOPS}\) BF16 / \(13.95\text{ TFLOPS}\) FP32 per chiplet | \(8 \times 128\) VPU |
| Peak BF16 Compute | \(275\text{ TFLOPS}\) / chip | \(197\text{ TFLOPS}\) / chip | \(459\text{ TFLOPS}\) / chip | \(918\text{ TFLOPS}\) / chip | \(2,307\text{ TFLOPS}\) / chip (\(1,153.5\text{ TFLOPS}\) / chiplet; \(892.8\) P3 derated) | v8i: \(1,101\text{ TFLOPS}\) / chip; v8t: \(996.1\text{ TFLOPS}\) / chip |
| Peak FP8 / INT8 Compute | \(275\text{ TOPS}\) INT8 (No native FP8) | \(393\text{ TOPS}\) INT8 / FP8 | \(918\text{ TOPS}\) INT8 / \(459\text{ TFLOPS}\) FP8 | \(1,836\text{ TOPS}\) INT8 / \(918\text{ TFLOPS}\) FP8 (the bf16 rate) | \(4,614\text{ TFLOPS}\) / chip (\(2,307\text{ TFLOPS}\) / chiplet; \(1,785.6\) P3 derated) | \(2\times\) BF16 rate |
| Native FP4 / Microscaling Support | Emulated (dequant to BF16) | Emulated (dequant to BF16) | Emulated (dequant to BF16) | Emulated (dequant to BF16) | Native FP4 (e2m1), MXFP8/MXFP4 (32-element block) (\(4,614\text{ TFLOPS}\)/chip) |
Native FP8 / FP4 |
| HBM Capacity | \(32\text{ GiB}\) HBM2 / chip | \(16\text{ GiB}\) HBM2e / chip | \(95\text{ GiB}\) HBM2e / chip | \(32\text{ GiB}\) HBM / chip | \(192\text{ GiB}\) HBM3e / chip (\(96\text{ GiB}\) / \(103\text{ GB}\) per chiplet) | v8i: \(288\text{ GB}\) (\(309\text{ GB}\)) + \(384\text{ MB}\) SRAM; v8t: \(231\text{ GB}\) |
| HBM Peak Bandwidth | \(1,200\text{ GB/s}\) / chip | \(819\text{ GB/s}\) / chip | \(2,765\text{ GB/s}\) / chip | \(1,638\text{ GB/s}\) / chip | \(7,380\text{ GB/s}\) / chip (\(3,686\text{ GB/s}\) theoretical / \(3,365\text{ GB/s}\) P3 / \(3,207\text{ GB/s}\) practical per chiplet) | v8i: \(8.6\text{ TB/s}\) / chip; v8t: Multi-TB/s HBM3e/HBM4 |
| VMEM Scratchpad Capacity | Query vmem_capacity_bytes |
Query vmem_capacity_bytes |
Query vmem_capacity_bytes |
Query vmem_capacity_bytes |
\(64\text{ MiB}\) physical / chiplet (\(32\text{ MiB}\) default XLA scoped limit) | Multi-MiB VMEM + \(384\text{ MB}\) SRAM (v8i) |
| SMEM / CMEM Scratchpad | \(1\text{ MiB}\) SMEM + \(128\text{ MiB}\) CMEM | \(1\text{ MiB}\) SMEM, \(0\) CMEM | \(1\text{ MiB}\) SMEM, \(0\) CMEM | \(1\text{ MiB}\) SMEM, \(0\) CMEM | \(1\text{ MiB}\) SMEM / chiplet, \(0\) CMEM | \(1\text{ MiB}\) SMEM |
| SparseCores (SC) / Device | \(0\) (Emb Lookup Unit) | \(0\) | 4 / chip (SIMD width 8) | 2 / chip (SIMD width 8) | 2 / chiplet (4 / chip); 16 subcores/SC = 32 subcores/chiplet in lockstep, SIMD width 16, \(8\text{ MiB}\) VMEM/SC (\(512\text{ KiB}\)/subcore), \(1,700\text{ GB/s}\) uni DMA | v8i: 1 SC/dev (SIMD 16); v8t: 2 SC/dev (SIMD 16) |
| Inter-Chip Interconnect (ICI) | 3D Torus (6 links, \(45\text{ GB/s}\) uni/link) | 2D Torus (4 links, \(45\text{ GB/s}\) uni/link, \(400\text{ GB/s}\) bidi/chip) | 3D Torus (6 links, \(90\text{ GB/s}\) uni/link, \(1,200\text{ GB/s}\) bidi/chip) | 2D Torus (4 links, \(90\text{ GB/s}\) uni/link, \(800\text{ GB/s}\) bidi/chip) | D2D Intra-Chip (\(600\text{ GB/s}\) uni) + 3D Torus ICI (6 links/chip, \(80\text{ to }90\text{ GB/s}\) uni/link, \(1,200\text{ GB/s}\) bidi/chip) | \(19.2\text{ TBps}\) bidi ICI (v8i: Boardfly C,B,G + CAE; v8t: 3D Torus Virgo Superpod) + 400 GBps bidi DCN (v8t) |
| Host VM Layout (Chips / Devices) | 4 chips (4 devices) / host | 4 or 8 chips (4 or 8 devices) / host | 4 chips (4 devices) / host | 4 or 8 chips (4 or 8 devices) / host | 4 chips = 8 logical devices / host (224 vCPUs, \(960\text{ GB}\) DRAM, 2 NUMA nodes, \(100\text{ Gbps}\) DCN/chip) | 4 chips (8 devs on v8i, 4 devs on v8t) / host |
Single-Host Topologies (bounds) |
2,2,1 |
1,1,1, 2,2,1, 2,4,1 |
1,1,1 to 2,2,2 |
1,1,1, 2,2,1, 2,4,1 |
1,1,1,2, 1,2,1,2, 2,2,1,2 (4th dim = dual-chiplet axis) |
C,B,G Boardfly (v8i) / 3D Torus (v8t) |
| Max Pod Slice Scale | \(4,096\) chips | \(256\) chips (\(16 \times 16\)) | \(8,960\) chips (\(6,144\) single slice) | \(256\) chips (\(16 \times 16\)) | \(9,216\) chips (\(18,432\) logical devices) | \(9,600\) chips (v8t Superpod) |
| BF16 Operational Intensity Ridge (\(\beta_{\text{BF16}}\)) | \(\approx \mathbf{229}\text{ FLOPs/Byte}\) | \(\approx \mathbf{240}\text{ FLOPs/Byte}\) | \(\approx \mathbf{166}\text{ FLOPs/Byte}\) | \(\approx \mathbf{560}\text{ FLOPs/Byte}\) | \(\approx \mathbf{312}\text{ FLOPs/Byte}\) (peak) / \(\mathbf{265}\text{ FLOPs/Byte}\) (P3 derated) | \(\approx \mathbf{350\text{ to }450}\text{ FLOPs/Byte}\) |
| FP8 / FP4 Operational Intensity Ridge (\(\beta_{\text{FP8}}\)) | N/A | \(\approx \mathbf{480}\text{ FLOPs/Byte}\) | \(\approx \mathbf{332}\text{ FLOPs/Byte}\) | \(\approx \mathbf{560}\text{ FLOPs/Byte}\) (FP8 at the bf16 rate; \(\approx 1,120\) ops/byte for INT8) | \(\approx \mathbf{625}\text{ FLOPs/Byte}\) (peak) / \(\mathbf{531}\text{ FLOPs/Byte}\) (P3 derated) | \(\approx \mathbf{700\text{ to }900}\text{ FLOPs/Byte}\) |
TPU 8 interconnect units
The v8i / v8t column gives ICI and DCN bandwidth in the units of How TorchTPU works: 19.2 TBps bidirectional ICI and 400 GBps bidirectional DCN. Confirm the units against Google's TPU 8 documentation before you calculate with them (chapter 1).
Achievable v7x HBM bandwidth
The v7x P3 (3,365 GB/s) and practical (3,207 GB/s) per-chiplet HBM figures are estimates of achievable bandwidth from Chip constants and compiler hard limits, which recommends building rooflines on the practical figure. Say which figure you used (chapter 1).
v6e FP8 and INT8
v6e runs INT8 matmuls at twice its bf16 rate but FP8 at the bf16 rate: llm-d's Google Cloud TPU provider page lists 918 TFLOPS bf16 with FP8 at the same rate. Its FP8 ridge therefore equals its bf16 ridge, about 560 FLOPs per byte (chapter 1, hardware reference).
Warning
Common pitfalls: hardware and topology
- Pitfall: "1 TPU Chip always equals 1 PyTorch device (
tpu:i)." Fact: Onv4andv5p, two TensorCores on a silicon package were fused into a single logical device ("Megacore"). On TPU v7x (Ironwood) and TPU v8i,devices_per_chip = 2: the two TensorCore chiplets on each package are exposed as two independent logical PyTorch devices (tpu:2kandtpu:2k+1, connected via a dedicated \(600\text{ GB/s}\) unidirectional Die-to-Die (D2D) link). Because both chiplets share the package's external 3D Torus ICI router, when both chiplets simultaneously drive an external ICI axis (X, Y, or Z), effective per-chiplet external ICI bandwidth is derated by 50% (\(\sim 40\text{ to }45\text{ GB/s}\) uni/chiplet). Map the innermost tensor-parallel axis (tp=2) onto the intra-chip D2D link. - Pitfall: "Any number of OS processes can share a single TPU device like CUDA MPS."
Fact: A TPU VFIO device node (
/dev/vfio/*) can be opened by only one user-space OS process at a time (Introducing TorchTPU).TorchTPUenforces a strict 1-process-per-logical-device model (unlike JAX's 1-process-per-host model), which means co-located RL rollout and trainer workers must either partition devices across processes or execute within the same process.
Worked example: inspecting hardware and topology in Python¶
import torch
import torch_tpu # Autoloaded when TORCH_DEVICE_BACKEND_AUTOLOAD=1 (default)
# Queries C++ PCI & libtpu topology probe without initializing PJRT (torch_tpu/csrc/common/tpu_hardware.cc)
# props.total_memory and props.multi_processor_count are deprecated since TorchTPU 0.2.1; use the fields below.
props = torch.tpu.get_device_properties(0)
print(f"Device Name: {props.name}") # e.g. 'TPU v7' or 'TPU v6e'
print(f"Devices per Chip: {props.devices_per_chip}") # 2 on v7x/v8i, 1 on v5e/v5p/v6e
print(f"HBM per Device: {props.hbm_bytes_per_device / 2**30:.1f} GiB") # 96.0 GiB/v7x chiplet (192 GiB/chip)
print(f"BF16 Peak TFLOPS/Dev: {props.bf16_flops_per_device / 1e12:.1f}") # 1153.5 TFLOPS/v7x chiplet
print(f"SparseCores/Device: {props.sparse_cores_per_device} (SIMD={props.sparse_core_simd_width})")
print(f"Visible Devices/Host: {torch.accelerator.device_count()}") # 8 on v7x host (4 chips x 2 chiplets)
# Roofline arithmetic intensity of a BF16 matmul [M, K] x [K, N]
M, K, N = 4096, 4096, 4096
flops = 2 * M * K * N
bytes_accessed = 2 * (M * K + K * N + M * N) # 2 bytes per BF16 element
operational_intensity = flops / bytes_accessed # = 1365.3 FLOPs/Byte
# Since 1365.3 > 560 (v6e ridge) and > 312 (v7x ridge), the [4096, 4096] GEMM is compute-bound on the MXU.
1.2 The six-layer PyTorch-on-TPU software stack¶
In one sentence¶
The PyTorch-on-TPU stack decouples authoring ergonomics (standard PyTorch nn.Module, DTensor, and torch.compile) from silicon execution by lowering PyTorch FX graphs through StableHLO MLIR into Google's closed-source libtpu.so PJRT compiler/runtime, while wrapping the runtime in specialized distributed engines for 6D training (TorchTitan), bucketed serving (vLLM/SGLang), RL (Miles), Kubernetes disaggregation (llm-d), and autonomous kernel engineering (tpu-agent-suite).
The six layers¶
The same six layers as on the Overview page, here with each layer's main components. The table below gives each layer's repository, source files and responsibilities.
Layer reference¶
| Layer | Repository / Component | Key Source Files & Directories | Core Abstractions & Responsibilities |
|---|---|---|---|
| Layer 6: Agentic engineering | tpu-agent-suite |
package/skills/, package/scripts/, package/references/ |
Automated XProf trace diagnosis (analyze_profile.py), hardware Roofline modeling (TPU v7x (Ironwood / GhostFish) Specification), autonomous Pallas/Kiln/Helion kernel synthesis (tpu-kernel-development), tpu-model-onboarding, and tpu-diagnostics. |
| Layer 5: K8s orchestration | llm-d 1.0 & Ray |
Announcing llm-d 1.0: Open distributed inference for agents on Google Cloud TPUs and GPUs, Announcing Ray support for PyTorch on Google TPUs | Kubernetes Gateway API Inference Extension (InferencePool, InferenceObjective, InferenceModelRewrite), Envoy ext_proc Endpoint Picker (EPP), ZMQ KV Indexer, LeaderWorkerSet (LWS), DisaggregatedSet, KEDA + EPP autoscaling, FMA, and Ray SlicePlacementGroup. |
| Layer 4: Post-training and RL | Miles & VeRL |
radixark/miles, sglang-torchtpu/, vllm-torchtpu/ |
Decoupled actor rollout (SGLang/vLLM on TPU) + policy trainer (TorchTitan SimpleFSDP/FSDP2), asynchronous weight synchronization, and trajectory replay buffers. |
| Layer 3: Workload engines (training) | torchtitan & TorchRec |
torchtitan/experiments/tpu/, graph_trainer/ |
6D Parallelism (DDP, SimpleFSDP/FSDP2, TP/AsyncTP, PP, CP, EP), scan stacked-layer loop, SingleTraceTrainer (compile_step), activation offloading, and TorchRec SparseCore DLRM embedding offload. |
| Layer 3: Workload engines (serving) | vllm-torchtpu & sglang-torchtpu |
src/vllm_torchtpu/, python/sglang/srt/hardware_backend/tpu/ |
Bucketed torch.compile execution, Ragged Paged Attention v3 (RPA v3), sequence-on-lane FP8 KV cache, CPU-resident TpuPagedTokenToKVPoolAllocator + KVFreeFence, tpu-sync (Raiden) P/D KV transfer. |
| Layer 2: PyTorch TPU runtime | torch_tpu |
torch_tpu/csrc/, torch_tpu/src/torch_tpu/ |
Native PrivateUse1 (tpu) device, Strict/Debug/DeferAndFuse eager modes, fx_to_mlir (EagerLikeFxInterpreter) StableHLO lowering, 3-tier compilation cache, TpuAllocator, tpu_dist, WindowTPU, @jax_op. |
| Layer 1: Compiler and silicon | OpenXLA + libtpu.so |
pjrt_client.h, tpu_hardware.cc |
XLA HLO pass pipeline (fusion, remat, GSPMD/Shardy), Mosaic/LLO compiler (VMEM layout, \((8, 128)\) tiling, VLIW bundling), PJRT C API execution on Cloud TPU hardware. |
Feature status and roadmap¶
Sources: TorchTPU supported feature set and future work, Introducing TorchTPU.
| Domain / Dimension | Validated (Production CI/CD) | Experimental (Available for Early Feedback) | Near-Term & Future Roadmap |
|---|---|---|---|
| Operator & Model Corpus | ~450 Core ATen ops (fwd+bwd) + 135+ C++ StableHLO builder dirs (csrc/ops/); 4,917 HF models across 500+ families: 98% Tier-1 Pass Rate (4,821/4,917), 97% Tier-2 GPU Numerical Parity (638/657) (\(\Delta \text{PPL}_{\text{rel}} \le 0.10\); \(\text{RelMSE} \le 0.10\) or \(\text{MSE} < 0.05\)). |
Bounded Dynamism (SymInt): 99% pass rate (834/839 causal LLMs); Jagged tensors (align_jagged_to_multiple); TPU Agent for ATen migration. |
Day-1 model support; precompiled dynamic ATen kernels ("True Eager" zero warmup); TPU Agent for kernel migration. |
| Model Architectures | Transformers (Dense + MoE): Qwen, Llama, Muse Glimmer, Gemma; Diffusion: WAN, FLUX; CNNs (NHWC). |
GLM, Kimi, DeepSeek, GPT-OSS, Mamba (SSM), LSTM/GRU, DLRM (validated 18.3 ms step parity on 32-chip v7x via TorchRec SparseCore). |
Reasoning, multimodal, video diffusion (Wan 2.2, Flux Klein), next-gen MoE variants. |
| TPU Silicon Generations | v5e, v5p, v6e (Trillium), v7x (Ironwood). |
n/a | v8i, v8t (288 GB HBM @ 8.6 TB/s, 19.2 TBps ICI). |
| Kernel Authoring & Quantization | Pallas (@torch.tpu.pallas.jax_op), Tokamax, Kiln (C++); Full-tensor FP8/FP4 & Per-channel FP8. |
Helion (@helion.kernel(backend="pallas")). |
Block-wise FP8/FP4 via torchao (peak perf on v8t); dynamic Mosaic kernels. |
| Distributed & Ecosystem | topology_aware_mesh, SimpleFSDP, Activation Offloading, Checkpointing, Multi-slice up to 8,192 v7x chips (16,384 TensorCores); HuggingFace, Ray, vLLM, SGLang, TorchTitan, TorchRec. |
FSDPv2 (hook graph breaks), MPMD (skinny collectives), TorchComm. |
High-perf FSDPv2 & MPMD (SparseCore skinny collective offload), VeRL RL, training \(\gg 8\text{K}\) chips, multi-tier checkpointing, WebGPU Trace Viewer 2.0 & XProfz continuous flight-recorder. |
Note
TorchTPU vs. PyTorch/XLA vs. TorchAX vs. JAX (TorchTPU FAQ):
- Why
PyTorch/XLAis Deprecated: Introduced in 2020 around Lazy Tensors,PyTorch/XLArequired invasivexm.mark_step()annotations, suffered from long compile stalls, lacked true eager mode, and carried heavy JAX runtime dependencies.PyTorch/XLAis officially deprecated and replaced byTorchTPU. - How
TorchTPUDiffers fromTorchAX(torch_xla2):TorchAXintercepts PyTorch operations at the Python__torch_dispatch__level and lowers them into JAX/XLA (used primarily for rapid inference prototyping).TorchTPUis a C++20PrivateUse1("tpu") dispatcher andc10d::Backend("tpu_dist") with zero JAX runtime dependencies. - Does
TorchTPUReplaceJAX? No:TorchTPUcomplementsJAXby giving native PyTorch codebases (TorchTitan,vLLM,SGLang,HuggingFace,TorchRec) native TPU support without rewriting models in JAX.
1.3 Glossary of core abstractions¶
In one sentence¶
Working in the PyTorch-on-TPU ecosystem means using five intersecting vocabularies: OpenXLA/PJRT compiler primitives, torch_tpu C++ runtime & memory abstractions, 6D distributed & RDMA collectives, TPU kernel DSLs, and vLLM/SGLang/llm-d disaggregated serving primitives.
A. Compiler, runtime and memory (torch_tpu and OpenXLA)¶
| Term / Symbol | Definition | Source / Reference |
|---|---|---|
PJRT (Pretty much Just another RunTime) |
Uniform C API hardware abstraction layer (libtpu.so) that manages TPU device discovery, HBM buffer allocation (PjRtBuffer), XLA compilation, and asynchronous execution (PjRtLoadedExecutable). |
pjrt_client.h |
StableHLO |
Backward-compatible Static Single Assignment (SSA) MLIR dialect emitted by torch_tpu's fx_to_mlir (EagerLikeFxInterpreter) and C++ op builders as the portable IR between PyTorch and OpenXLA. |
export.py |
OpenXLA & HLO |
Domain-specific linear algebra compiler that transforms StableHLO into High-Level Optimizer (HLO) IR, performing algebraic simplification, operator fusion, GSPMD/Shardy sharding, and rematerialization. | How TorchTPU works |
LLO (Low-Level Optimizer) |
Final proprietary backend inside libtpu.so that lowers XLA HLO / Mosaic IR into VLIW instruction bundles, schedules \((8, 128)\) VMEM tile DMAs, and allocates hardware sync flags. |
How TorchTPU works |
PrivateUse1 (tpu) |
PyTorch C10 dispatcher extension slot claimed by torch_tpu (rename_privateuse1_backend("tpu")) via entry-point autoload (TORCH_DEVICE_BACKEND_AUTOLOAD=1) without modifying upstream PyTorch C++ core. |
_loader.py |
DeferredOp & DeviceBufferList |
C++ node in an unmaterialized Directed Acyclic Graph (DAG) created in DeferAndFuse eager mode (TORCH_TPU_DEFER_AND_FUSE=1) that clusters eager ops into a fused -O2 StableHLO program upon materialization. |
device_buffer.h |
DeviceBufferRef |
CPU-side metadata handle pointed to by UntypedStorage.data_ptr() tracking its lifecycle states (Deferred, Transferring, Executing/Materializing, Materialized PjRtBuffer*, and Placeholder, which stands for an argument of a compiled executable and never materializes; see How it works, section 2.2). |
device_buffer.cc |
TpuAllocator |
The c10::DeviceAllocator TorchTPU registers for the tpu device. It hands out DeviceBufferRef handles and leaves HBM management to PjRt; its emptyCache is a no-op. There is no separate caching allocator (chapter 5). |
tensor_to_buffer.cc |
| View Decomposition & Inversion | Bidirectional stride translator (csrc/ops/view_decomposition/) that decomposes strided PyTorch views into StableHLO (slice/reshape/transpose) and inverts in-place slice writes into stablehlo.dynamic_update_slice. |
TorchTPU and the TPU memory model |
| Buffer donation | When the last reference to an obsolete buffer is removed, TorchTPU annotates the StableHLO so the input is donated and XLA can update it in place without doubling peak memory; when donation is not provably safe it falls back to an out-of-place update. (chapter 5) | TorchTPU and the TPU memory model |
CacheKey (192-bit) |
Deterministic uint64_t[3] fingerprint (Shapeless Key + Dimensions Key [= Graph Key] + Compile Options Key) indexing the 3-tier (tier 1 in memory, then tier 2 in /dev/shm, then tier 3 on disk or GCS) compilation cache. |
compilation_cache.h |
@torch.tpu.pallas.jax_op |
Decorator that traces a JAX/Pallas kernel into StableHLO/Mosaic MLIR and registers it as a native torch.library.custom_op with automatic FakeTensor meta-kernels, BLAKE2b fingerprinting, and donate_argnums. |
pallas.py |
B. Distributed collectives, parallelism and RL (tpu_dist, TorchTitan, Miles)¶
| Term / Symbol | Definition | Source / Reference |
|---|---|---|
tpu_dist (ProcessGroupTpu) |
Native PyTorch c10d::Backend registered under "tpu_dist" that lowers collectives (all_reduce, reduce_scatter, all_gather, all_to_all, ragged_all_to_all) directly into StableHLO ops over ICI or DCN. |
process_group_tpu.h |
topology_aware_mesh() |
Mesh builder (torch.tpu.distributed.topology_aware_mesh) that queries physical 2D/3D/4D TPU coordinates and permutes ranks so high-intensity axes (tp, cp, ep, fsdp) map onto contiguous ICI torus rings. |
_distributed_module.py |
| Skinny Collectives | Default MPMD-safe tpu_dist mode that inserts graph breaks around collectives so each runs as a standalone 1-op executable (prevents deadlocks on rank divergence, or offloads to SparseCore via TORCH_TPU_INTERNAL_SKINNY_SC_OFFLOAD=1). |
TorchTPU distributed support |
@spmd_safe & Handshake Stages |
Opt-in decorator (@torch.tpu.distributed.spmd_safe) and consensus protocol (TORCH_TPU_SPMD_HANDSHAKE_STAGE=OFF|COMPILE_STAGE|DISPATCH_STAGE) that elide graph breaks around collectives for full XLA compute-ICI overlap. |
spmd_util.py, handshake.h |
WindowTPU |
Communication window (c10d::WindowTPU, window_num_stripes) behind PyTorch's one-sided c10d::Window interface (put, signal, wait_signal). Host-to-device transfers are true one-sided DMA; peer transfers over ICI are currently emulated with two-sided send and receive, so the receiving rank's CPU must call wait_signal. |
window_tpu.h |
TPUTrainer & TpuGraphTrainer |
TorchTitan TPU trainers supporting 2-graph split execution (materialize_forward_before_backward via torch.ops.tpu.synchronize(loss, wait=False)) or unified AoT/JIT graph training (optimizer_compile="in_graph"|"separate_graph"). |
train.py, tpu_graph_trainer.py |
LayerLoop (scan) & scan_backward_patch |
Compiles \(L\) homogeneous Transformer layers in \(O(1)\) compile time via torch.ops.higher_order.scan (LayerLoop) while patching scan backward to index forward buffers directly instead of torch.flip (saving \(4.2\text{ to }10\text{ GB}\) HBM). |
layer_loop.py, scan_backward_patch.py |
apply_bld_layout ([B, L, D]) |
Pre-sets physical layout [2, 1, 0] (torch.ops.tpu.MustUseCustomLayout) on [B, L, D] activations so sequence L is sublane-contiguous (8) and hidden D is lane-contiguous (128), eliminating relayout copies. |
bld_layout.py |
SimpleFSDP & SingleTraceTrainer |
Compiler-friendly FSDP (SimpleFSDP) and functional training harness (SingleTraceTrainer.compile_step) capturing forward + loss + backward + functional AdamW/Muon/Sgd in one donated XLA program. |
train.py, single_trace_trainer.py |
AsyncTP, DualPipeV & ZBVZeroBubble |
Compiler-pipelined Tensor Parallelism (AsyncTP) and bidirectional/zero-bubble Pipeline Parallelism schedules (DualPipeV, ZBVZeroBubble) that split backward passes into activation (\(B\)) and weight (\(W\)) grads. |
pipeline.py |
Ulysses, Ring, HeadTail, PTRR |
Context Parallelism (CP) algorithms in TorchTitan that partition long sequences (\(S \ge 32\text{K}\text{ to }1\text{M}\)) across ICI via all_to_all head sharding (Ulysses), ring KV passing (Ring), or causal load-balancing (HeadTail/PTRR). |
context_parallel/ |
Miles & VeRL (RLHF / GRPO) |
Distributed RL orchestration pairing SGLang-TorchTPU/vLLM-TorchTPU rollout actors with TorchTitan policy trainers on TPU v7x via shared memory or disk; a direct ICI weight transfer is planned, and measured about 50 times faster than shared memory in a test (chapter 15). |
SGLang‑TorchTPU: PyTorch‑Native Production Serving on TPUs |
C. Kernel DSLs and execution units (Pallas, Mosaic, Kiln, Helion, Tokamax)¶
| Term / Symbol | Definition | Source / Reference |
|---|---|---|
MXU (Matrix Multiply Unit) |
\(128 \times 128\) (v4/v5e/v5p) or \(256 \times 256\) (v6e/v7x/v8) systolic array that computes \(C_{FP32} \mathrel{+}= A_{BF16/FP8/FP4} \times B_{BF16/FP8/FP4}\) at up to \(1,153.5\text{ TFLOPS}\) BF16 (\(2,307\text{ TFLOPS}\) FP8/FP4) per v7x chiplet. |
Chip constants and compiler hard limits |
VPU (Vector Processing Unit) |
2D SIMD execution unit organized as 8 sublanes \(\times\) 128 lanes (1,024 FP32 ALUs) that executes elementwise ops, reductions, activations (exp2, tanh), and layouts directly out of VMEM vector registers (vregs). |
Chip constants and compiler hard limits |
VMEM & SMEM |
Explicitly managed on-chip SRAM scratchpads (VMEM: \(64\text{ MiB}\) per core on v7x, other generations reported by vmem_capacity_bytes, for 2D \((8, 128)\)-tiled vector/matrix blocks; SMEM: \(1\text{ MiB}\) for scalar loop counters, dynamic block indices, and metadata). |
TorchTPU and the TPU memory model |
SparseCore (SC) |
Dedicated gather/scatter/embedding/collective processor (v5p: 4/chip, v6e: 2/chip, v7x: 2/chiplet = 4/chip, SIMD 16, \(8\text{ MiB}\) VMEM/SC) that runs in parallel with TensorCore (sparse_dense_matmul, async All-Gather). |
TPU v7x (Ironwood / GhostFish) Specification, ops.py |
Pallas (jax.experimental.pallas) |
Tile-based JAX kernel DSL for TPUs exposing explicit PrefetchScalarGridSpec grids, VMEM/SMEM BlockSpec memory spaces, async local/remote DMA copies (pltpu.make_async_remote_copy), and static verification (torch.tpu.pallas.verifier). |
pallas.py, verifier.py |
Mosaic (mosaic_tpu) |
Low-level MLIR dialect and compiler backend beneath Pallas and Kiln that handles vector register allocation, \((8, 128)\) layout canonicalization, pipeline double-buffering, and LLO lowering. | write-tpu-kernels/SKILL.md |
Kiln (torch_tpu::mosaic::kiln) |
Native C++20 embedded Mosaic kernel DSL (CreateKernel, GridSpec, VmemRef, SmemRef, AsyncCopy, Pipeline) in torch_tpu for authoring zero-Python-overhead TPU kernels (flash_attention, rms_norm, rope, swiglu). |
kiln.h |
Helion (@helion.kernel) |
Experimental PyTorch-native tile-oriented kernel DSL (for tile in hl.tile(...)) that compiles portable Python tile programs into Pallas/Mosaic TPU kernels (backend="pallas"). |
Introducing TorchTPU |
Tokamax |
OpenXLA library of production-tuned, autotuned Pallas/Mosaic TPU kernels (splash_sdpa, ragged_paged_attention_v3, ragged_dot grouped GEMM, Gated DeltaNet, MLA, fused cross-entropy, TopK) exposed via @jax_op. |
Introducing TorchTPU |
D. Serving engines and KV cache (vLLM-TorchTPU, SGLang-TorchTPU)¶
| Term / Symbol | Definition | Source / Reference |
|---|---|---|
RPA v3 & Batched RPA |
Pallas/Tokamax kernels (ragged_paged_attention_v3, pallas_tpu_rpa_batched) fusing ragged prefill and paged decode attention with in-place KV cache updates (buffer donation) and SMEM page-table prefetching. |
attention.py, pallas_jax_op.py |
5D / 6D / SEQ_ALONG_LANE KV Pools |
TPU-tiled KV layouts: 5D token-major (TpuFusedMHATokenToKVPool), 6D block-major (TpuBlockMajorMHATokenToKVPool / BlockMajorPoolLayout with unified GDN v3 state), and 4D SEQ_ALONG_LANE (halving 1-head FP8 KV to \(256\text{ B/tok}\)). |
kv_pool.py, kv_cache_manager.py |
ExponentialBucketing / Bucketer |
Input-padding schedulers in vLLM (compile_sizes + num_reqs_paddings) and SGLang (PAD_TOKENS prefill / PAD_BATCH decode) + TPU_PRECOMPILE_PEER_REPLAY=1 that guarantee zero runtime XLA recompilation. |
tpu_runner.py, bucketer.py |
TpuPagedTokenToKVPoolAllocator |
SGLang-TorchTPU memory allocator that maintains the free-page list in CPU RAM rather than on TPU HBM, so no device tensor changes shape at page boundaries and triggers a recompile. (chapter 19) |
allocator_tpu.py |
KVFreeFence |
1-step delayed page reclamation queue in SGLang-TorchTPU (free_pages_pending) that prevents CPU page allocators from recycling a KV page while an asynchronous in-flight TPU decode step is still reading it. |
kv_free_fence.py |
Raiden (tpu-sync 3-Engine DMA) |
Multi-port DCN/ICI KV transfer engine (jax.experimental.transfer) streaming Full-Attention KV (Engine 1), SWA KV (Engine 2), and GDN/Mamba state (Engine 3) with chunked-prefill pull or heterogeneous TP strided push-resharding. |
conn.py, raiden/ |
fused_ep_moe & Pallas Megakernels |
SPMD MoE (fused_ep_moe v2 + SparseCore ragged_gather_reduce_v2) and Whole-Decoder Pallas Megakernels (Kimi-K3 \(>700\text{ tok/s}\), GLM-5.3-Flash, Muse Spark, Qwen3.5 \(\$0.0201/\text{1M tok}\)). |
moe.py, Introducing vLLM TorchTPU |
E. llm-d 1.0 gateway, routing, KV management and disaggregation¶
| Term / Symbol | Definition | Source / Reference |
|---|---|---|
InferencePool |
Gateway API Inference Extension CRD (inference.networking.k8s.io/v1) grouping model-serving pods (selector, targetPorts) behind an endpointPickerRef (failureMode: FailOpen|FailClose). |
llm-d InferencePool |
EndpointPicker (EPP) |
Envoy ext_proc (FULL_DUPLEX_STREAMED) router composed of Request Handler, Flow Control, Request Scheduler (Filter -> Score -> Pick + P/D ProfileHandler), and Data Layer. |
Endpoint Picker (EPP) |
InferenceObjective & InferenceModelRewrite |
CRDs (IPP / llm-d.ai/v1) defining workload priority bands (including < 0 sheddable batch tiers) and rewriting incoming HTTP model names to backend base/LoRA identifiers. |
llm-d Glossary |
DataLayer |
Pluggable EPP telemetry pipeline (Source -> Extract -> Attribute) ingesting Prometheus (PollingDataSource), Kubernetes watch (NotificationSource), and lifecycle events (EndpointSource). |
llm-d Data Layer |
FlowControl |
3-Tier admission dispatcher (Priority Band -> FairnessPolicy -> OrderingPolicy fcfs/edf/slo-deadline) with SaturationDetector gating and in-flight eviction (enableEviction: true) of sheddable requests. |
Flow Control |
LatencyPredictor |
Sidecar architecture (1 Training Server + \(N\) Prediction Servers) training online XGBoost quantile regression models for TTFT & TPOT (\(\sim 5\%\) MAPE) to drive SLO-aware filtering/scoring. | Latency Predictor |
KV-Cache Indexer (ZMQ :5557/:5556) |
Global block/radix index inside EPP consuming real-time ZMQ BlockStored, BlockRemoved, and AllBlocksCleared events (plus speculativeIndexing 2s TTL) for exact prefix-cache scoring. |
KV-Cache Indexer |
KV Offloader |
Multi-tier KV offload subsystem supporting Native vLLM OffloadingConnector (CPUOffloadingSpec + TieringOffloadingSpec fs/obj/p2p), SGLang HiCache (TpuDMAHiCacheController), and MooncakeStoreConnector. |
KV-Cache Offloading |
P2P KV-Cache Sharing |
Cross-replica CPU-to-CPU KV pull over NIXL/UCX RDMA (p2p-source-producer, minCachedTokenDelta) that fetches evicted prefix blocks from peer DRAM without interrupting the source pod's TPU/GPU. |
P2P KV-Cache Sharing |
LeaderWorkerSet (LWS) |
Kubernetes CRD (leaderworkerset.x-k8s.io/v1) managing multi-host TP/PP/EP TPU slices as atomic gang-scheduled units with exclusive-topology placement and RecreateGroupOnPodRestart. |
LeaderWorkerSet (LWS) |
DisaggregatedSet |
CRD (disaggregatedset.x-k8s.io/v1) orchestrating coupled Prefill/Decode child LWS pools (<ds>-<slice>-<rev>-<role>), placementPolicy (ExclusiveSlice|ExclusiveTopology), and DisaggregatedSetRoleScaler. |
DisaggregatedSet |
KEDA + EPP vs. WVA (Deprecated) |
KEDA + EPP Metrics (5 signals: inflight, queue, saturation, token backlog, latency + Kueue cohort quota) is the recommended autoscaler, superseding the deprecated Workload Variant Autoscaler (WVA). |
KEDA with EPP Metrics, Workload Variant Autoscaler (WVA): Deprecated |
Batch Gateway & Async Processor |
OpenAI Batch API gateway (/v1/batches, PostgreSQL/Redis/S3) and 6-stage llm-d-async worker pipeline (11 dispatch gates + RL Co-operative Time-Slicing raising TPU duty cycle from \(\sim 40\%\) to \(>70\%\)). |
Batch Gateway Architecture, Async Processor Architecture |
FMA (Fast Model Actuation) & ModelExpress |
Dual-controller (Launcher + Standby) rapid pod startup combining sleep-state DRAM weight offload with peer-to-peer (ModelExpress) RDMA weight streaming to cut cold-start times to \(<10\text{ s}\). |
Reuse Warm Model Servers (FMA) |
1.4 CUDA to TorchTPU translation¶
Prerequisites: Familiarity with
torch.cuda/NCCLidioms and the core primitives in section 1.3.Covers: translating single-device and distributed CUDA PyTorch code to
TorchTPU, the API lifecycle stages of TorchTPU Public APIs (Stable,Experimental,Internal), and the host allocator requirement (libtcmalloc).
In one sentence¶
Because torch_tpu implements both PyTorch's device-agnostic torch.accelerator (Stable) API and a torch.tpu (Experimental) module that mirrors torch.cuda, model code that is written against torch.accelerator or a device string ports by changing the device ("cuda" \(\to\) "tpu"), while low-level systems primitives (CUDA Graphs, NCCL, Triton, Nsight) map onto compiler-driven XLA/TPU equivalents; the pitfalls below list what does not carry over.
Note
How it works: the torch.accelerator (Stable) and torch.tpu (Experimental) API stages (TorchTPU Public APIs):
TorchTPU Public APIs puts every public API and environment variable in one of these stages:
Stable(deprecation takes at least 2 minor releases; preferred for portable code):- Device, stream and memory:
torch.accelerator.{current_accelerator, is_available, device_count, current_device_index, set_device_index, device_index, synchronize, current_stream, set_stream}andtorch.accelerator.memory.{empty_cache, get_memory_info, memory_allocated, memory_reserved, max_memory_allocated, max_memory_reserved, memory_stats, reset_peak_memory_stats}. - RNG:
torch.accelerator.random.{initial_seed, get_rng_state, get_rng_state_all}(PyTorch 2.13 or later). - Ops:
torch.tpu.ops.{max_pool1d, max_pool2d, max_pool3d}and their backward ops. - Environment variables:
LIBTPU_INIT_ARGS,TORCH_DEVICE_BACKEND_AUTOLOAD,TPU_PREMAPPED_BUFFER_SIZE,TPU_VISIBLE_DEVICES,TMPDIRand the launcher variablesLOCAL_RANK,RANK,WORLD_SIZE,MASTER_ADDR,MASTER_PORT,NNODES,NODE_RANK. Experimental(may change without a deprecation process; a one-time warning on use):- Python:
torch.tpu.{EagerMode, eager_mode, set_eager_mode, Precision, precision, allow_excess_precision, get_device_properties, manual_seed, manual_seed_all, Stream, Event, TpuLayout, get_device_layout_if_materialized},torch.tpu.distributed.{set_tpu_launch_env, spmd_safe, topology_aware_mesh, window_num_stripes, window_stripe_chunk_mb},torch.tpu.ops.*beyond max pooling,torch.tpu.optimizers.*,torch.tpu.pallas.{jax_op, get_pallas_mesh, verifier}andtorch.tpu.profiler.TpuProfilerConfig. - Environment variables:
TORCH_TPU_DEFER_AND_FUSE,TORCH_TPU_LAUNCH_BLOCKING,TORCH_TPU_ENABLE_DEBUG_CHECKS,TORCH_TPU_SPMD_HANDSHAKE_STAGE,TORCH_TPU_TIER2_COMPILATION_CACHE,TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT,TORCH_TPU_TOPOLOGY,TORCH_TPU_SLICEBUILDER_ADDRESSES,TORCH_TPU_PROFILER_OUTPUT_DIR,TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS,XLA_FLAGSand a few more. Deprecated:torch.tpu.get_device_nameand thetotal_memoryandmulti_processor_countproperties (0.2.1), andtorch.tpu.topology_aware_mesh(0.2.0).Internal(calling one raises an error): thetorch.tpudevice, stream and RNG calls thattorch.acceleratorreplaces, such astorch.tpu.is_available,torch.tpu.set_deviceandtorch.tpu.synchronize; everything undertorch_tpu._Candtorch_tpu._internal; and theTORCH_TPU_INTERNAL_*variables.
The book's torch.tpu API matrix lists every entry, following TorchTPU Public APIs.
Warning
Common migration pitfalls:
- Pitfall 1: "I should always use
torch.tpu.is_available(),torch.tpu.set_device(), andtorch.tpu.synchronize()just liketorch.cuda.*." Fact: On PyTorch \(\ge 2.11\), legacy device-management aliases (torch.tpu.{is_available, device_count, current_device, set_device, synchronize}) are internal and raise aRuntimeErrorwhen called from user code (PyTorch 2.13 or later for the RNG calls).export TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1turns the error into a one-time warning while you migrate. (chapter 3) Prefertorch.accelerator.*for device, stream and memory management. - Pitfall 2: "Standard
glibcptmallocis fine for CPU host memory on TPU VMs." Fact: OpenXLA compilation and PJRT buffer transfers allocate and free millions of transient C++ AST/IR objects on the host CPU. Withoutlibtcmalloc, host memory fragments and degrades compilation/dispatch speed by \(20\text{ to }40\%\)._tcmalloc_check.pyemits warning//TorchTpu/Performance/TcMalloc//iflibtcmallocis missing. Set:export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4(orlibtcmalloc.so.4). - Pitfall 3: "PyTorch's default
float32matmul precision string on TorchTPU is'default'." Fact: In PyTorch's standard APItorch.get_float32_matmul_precision(), the default string is"medium", whichtorch_tpumaps totorch.tpu.Precision.DEFAULT(1-passbfloat16MXU). Passing"high"maps toPrecision.HIGH(3-pass BF16), and"highest"maps toPrecision.HIGHEST(6-pass BF16).
Translation table¶
| # | Systems Dimension | NVIDIA GPU / CUDA Idiom | Cloud TPU / TorchTPU Equivalent (Stable Preferred) |
Critical Architectural Nuance & Gotcha |
|---|---|---|---|---|
| 1 | Device String & Autoload | torch.device("cuda:0") |
torch.device("tpu") or torch.accelerator.current_accelerator() |
import torch auto-loads torch_tpu when TORCH_DEVICE_BACKEND_AUTOLOAD=1 (default) via the torch.backends entry point. |
| 2 | Availability Check | torch.cuda.is_available() |
torch.accelerator.is_available() (legacy: torch.tpu.is_available()) |
Stable. TorchTPU detects TPUs by PCI vendor 0x1ae0 and device ID (0x0063 v5e, 0x0062 v5p, 0x006f v6e, 0x0076 v7x, 0x0083 v8i, 0x007c v8t in tpu_hardware.cc). |
| 3 | Device Count | torch.cuda.device_count() |
torch.accelerator.device_count() |
Counts the devices visible to the current process. A host has 4 devices on v4/v5p, 4 or 8 on v5e/v6e and 8 on v7x (4 chips \(\times\) 2 chiplets), but a process started by the TorchTPU launch recipe sees one. |
| 4 | Set Active Device | torch.cuda.set_device(local_rank) |
torch.accelerator.set_device_index(local_rank) |
Legacy torch.tpu.set_device() requires TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1 on PyTorch \(\ge 2.11\). |
| 5 | Host-Device Sync | torch.cuda.synchronize() |
torch.accelerator.synchronize() |
Blocks host thread until all queued PJRT executions and DeferredOp DAGs complete. |
| 6 | Execution Streams | torch.cuda.Stream() / with torch.cuda.stream(s): |
torch.tpu.Stream (Experimental) / torch.accelerator.set_stream(s) |
Each TPU core has a single VLIW instruction pipeline; overlap is scheduled inside XLA/Pallas via async DMA semaphores rather than multi-stream SM multiplexing. |
| 7 | Timing Events | torch.cuda.Event(enable_timing=True) |
torch.tpu.Event(enable_timing=True) (or XProf) |
Host-side events require synchronization; prefer XProf for zero-overhead nanosecond device timelines. |
| 8 | RNG State & Seeding | torch.cuda.manual_seed_all(42) |
torch.tpu.manual_seed_all(42) (Experimental) |
torch.tpu.default_generators holds the default torch.Generator for each local device (TorchTPU API Reference). |
| 9 | Autocast Mixed Precision | torch.amp.autocast("cuda", dtype=torch.bfloat16) |
torch.amp.autocast("tpu", dtype=torch.bfloat16) |
bfloat16 is the default autocast dtype on TPU; the MXU accumulates in float32. |
| 10 | FP32 MatMul Precision | torch.set_float32_matmul_precision("high") |
torch.set_float32_matmul_precision("medium" \| "high" \| "highest") or with torch.tpu.precision(...): |
"medium" (Precision.DEFAULT, default)=1-pass BF16; "high" (Precision.HIGH)=3-pass (about \(3\times\) the MXU cost); "highest" (Precision.HIGHEST)=6-pass (\(6\times\) slower). |
| 11 | Memory Telemetry | torch.cuda.memory_allocated() / max_memory_allocated() |
torch.accelerator.memory.memory_allocated() / max_memory_allocated() |
Stable. TorchTPU's TpuAllocator leaves HBM management to PjRt (chapter 5). |
| 12 | Cache Release | torch.cuda.empty_cache() |
torch.accelerator.memory.empty_cache() |
Stable. TpuAllocator.emptyCache is a no-op because PjRt manages memory. |
| 13 | Graph Compilation | torch.compile(model, backend="inductor") |
torch.compile(model, backend="tpu") |
Lowers FX \(\to\) StableHLO (fx_to_mlir in export.py) \(\to\) XLA HLO \(\to\) PjRtLoadedExecutable. |
| 14 | Overhead Elimination | torch.cuda.CUDAGraph() (mode="reduce-overhead") |
torch.compile(backend="tpu") + Shape Bucketing / SingleTraceTrainer |
TorchTPU has no CUDA Graphs API; a compiled step runs as one PJRT executable. |
| 15 | Synchronous Debug Mode | CUDA_LAUNCH_BLOCKING=1 |
TORCH_TPU_LAUNCH_BLOCKING=1 (Experimental) |
Debug eager mode: synchronous compilation and execution per op, with the TORCH_TPU_ENABLE_DEBUG_CHECKS checks on by default. |
| 16 | Eager Op Fusion | N/A (Eager launches individual CUDA kernels) | TORCH_TPU_DEFER_AND_FUSE=1 (Experimental) |
Defers eager ops until a materialization point or a detected loop repetition and compiles them together at -O2; the documentation reports up to 50% faster than Strict eager. (chapter 4) |
| 17 | Compilation Cache | TORCHINDUCTOR_CACHE_DIR=/tmp/inductor |
TORCH_TPU_TIER2_COMPILATION_CACHE="default" + TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT=gs://... |
3-tier cache: in-memory, then a host cache (on by default when the world size is above 1), then a root path you set. |
| 18 | Distributed Backend | dist.init_process_group(backend="nccl") |
dist.init_process_group(backend="tpu") (alias "tpu_dist") |
Uses ProcessGroupTpu (csrc/distributed/process_group_tpu.h) over optical 2D/3D ICI torus + DCN fallback. |
| 19 | Device Mesh Creation | init_device_mesh("cuda", (dp, tp)) |
DeviceMesh("tpu", mesh=torch.tpu.distributed.topology_aware_mesh((dp, tp))) |
Orders ranks to follow the physical ICI torus (chapter 13). |
| 20 | One-Sided RDMA | NVSHMEM / SymmetricMemory (ncclMemAlloc) |
WindowTPU (SharedMemoryPool) + Pallas make_async_remote_copy |
Closest counterpart: WindowTPU (csrc/distributed/window_tpu.h) has a one-sided put API, but peer transfers over ICI are currently emulated with two-sided send and receive. |
| 21 | FSDP Implementation | fully_shard (PyTorch FSDP2 eager hooks) |
SimpleFSDP (compiled DTensor graph) or FSDP2 (@spmd_safe) |
TorchTPU's feature list marks SimpleFSDP as validated and FSDPv2 as experimental with low performance; this does not translate one to one (chapter 14). |
| 22 | Custom Kernel DSL | Triton (@triton.jit) / CUTLASS C++ |
Pallas (@pl.pallas_call), Mosaic, Kiln, Helion |
Explicit BlockSpec VMEM pipelining + \((8, 128)\) tile alignment instead of SIMT thread-block pointer arithmetic. |
| 23 | Custom Op Registration | torch.library.custom_op + CUDA C++ / Triton |
torch.tpu.pallas.jax_op (Experimental) |
jax_op is the public way to call a Pallas kernel (chapter 12). |
| 24 | Flash / Paged Attention | FlashAttention-2/3 / FlashInfer |
torch.tpu.ops.splash_sdpa(q, k, v, ...) (Experimental); RPA v3 in the serving engines |
Uses scalar block prefetching in SMEM and in-place KV buffer donation. |
| 25 | FP8 Formats | torch.float8_e4m3fn / float8_e5m2 (TensorCore) |
torch.float8_e4m3fn / float8_e5m2 + MXFP8 (32-element block) |
Peak FP8 rates per generation are in the hardware table in section 1.1. |
| 26 | FP4 Formats | Blackwell NVFP4 (e2m1 + E4M3 group-16 scale) |
Native MXFP4 (32-element block, E8M0 scale) & NVFP4 (float4_e2m1fn_x2) on v7x/v8 |
Native FP4 is a v7x and later feature (see section 1.1). |
| 27 | System & Kernel Profiler | Nsight Systems (nsys) & Nsight Compute (ncu) |
torch.profiler with ProfilerActivity.TPU and experimental_config=TpuProfilerConfig(...) \(\to\) XProf (.xplane.pb) |
Traces open in XProf (chapter 10). XProfz and the WebGPU Trace Viewer are roadmap items. |
| 28 | Hardware Telemetry CLI | nvidia-smi / DCGM |
tpu-info |
Shows chip utilization and HBM use; installed with vllm-torchtpu (Cloud TPU Setup). |
| 29 | Multiprocessing & Visibility | CUDA_VISIBLE_DEVICES=0,1,2,3 (mp.spawn) |
TPU_VISIBLE_DEVICES=0,1,2,3 + torch.tpu.distributed.set_tpu_launch_env() |
Call set_tpu_launch_env() (or use the launch recipe with torchrun) before starting the processes; it sets TORCH_TPU_TOPOLOGY & TORCH_TPU_SLICEBUILDER_ADDRESSES. |
The CUDA to TorchTPU page in the Reference section has the same mapping as a compact table.
Worked example: migrating a CUDA script to TorchTPU¶
# Before: CUDA / NCCL / Inductor script
import os
import torch
import torch.distributed as dist
dist.init_process_group(backend="nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
device = torch.device(f"cuda:{local_rank}")
torch.set_float32_matmul_precision("high")
model = MyTransformer().to(device)
compiled_model = torch.compile(model, backend="inductor", mode="reduce-overhead")
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
loss = compiled_model(inputs.to(device))
loss.backward()
torch.cuda.synchronize()
# After: TorchTPU script (Stable torch.accelerator API)
# Pre-launch env: export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4
# export TORCH_TPU_SPMD_HANDSHAKE_STAGE=COMPILE_STAGE
import torch
import torch.distributed as dist
import torch_tpu # Auto-loaded by `import torch` when TORCH_DEVICE_BACKEND_AUTOLOAD=1
dist.init_process_group(backend="tpu")
device = torch.device("tpu") # each TorchTPU process sees exactly one device
# 'medium' (Precision.DEFAULT) uses 1-pass native BF16 MXU; use 'high' for 3-pass FP32 emulation
torch.set_float32_matmul_precision("medium")
model = MyTransformer().to(device)
compiled_model = torch.compile(model, backend="tpu", fullgraph=True)
with torch.amp.autocast("tpu", dtype=torch.bfloat16):
loss = compiled_model(inputs.to(device))
loss.backward()
torch.accelerator.synchronize()

