The TorchTPU stack and the CUDA translation table¶
Prerequisites: TPU hardware for PyTorch engineers, Rooflines and arithmetic intensity
When a PyTorch script misbehaves on a TPU, the first useful question is which layer the problem lives in. A RuntimeError from a torch.tpu call, a first step that takes minutes, a flag rejected at startup and a loss that drifts from the GPU run come from four different places, and each has its own fix. This chapter lays out the layers between torch.matmul and the MXU, follows one operation down through them, and places each project in the TorchTPU ecosystem on that map. It then gives you the CUDA-to-TorchTPU translation table, with the API stage of every row from TorchTPU's own API list, ports a small CUDA training script, and ends with a check that tells you the port really runs on the TPU.
What this chapter covers¶
- The six layers of the TorchTPU stack, from your PyTorch code down to libtpu and the TPU hardware, and what each layer does.
- How one PyTorch operation travels from the dispatcher through a deferred op, StableHLO, the compilation cache, XLA and PjRt to the TPU, and back to the host.
- The three points where TorchTPU plugs into PyTorch, and where torch_tpu, vLLM-TorchTPU, SGLang-TorchTPU, TorchTitan, llm-d and the TPU Agent Suite sit relative to the stack.
- The TorchTPU or
torch.acceleratorequivalent of common CUDA calls, environment variables and backends, with the API stage of each. - The CUDA habits that do not translate one to one, and the later chapter that deals with each.
Six layers from torch.matmul to the MXU¶
A TPU is programmed through the XLA compiler stack, which has two entry points: StableHLO, a higher-level IR for ML operations, and Mosaic, a lower-level IR for custom kernels. The TPU's instruction set is proprietary and not published. The TorchTPU documentation suggests treating StableHLO, and Mosaic even more so, as the TPU's counterpart of PTX. Everything TorchTPU does is a way of turning PyTorch calls into those two IRs and handing them to the compiler and runtime in libtpu.
The three arrows are the three places TorchTPU plugs into PyTorch: everything above them is unchanged PyTorch; below them, TorchTPU (layer 3) turns each call into StableHLO or Mosaic, which XLA in libtpu compiles and runs. Eager ops and compiled graphs share one compilation cache.
| # | Layer | What lives there | What you touch |
|---|---|---|---|
| 1 | Your PyTorch code | Models, training loops, and frameworks built on PyTorch: Hugging Face, TorchTitan, vLLM-TorchTPU, SGLang-TorchTPU | torch.device("tpu"), nn.Module, torch.distributed |
| 2 | PyTorch core | The dispatcher (eager ops), TorchDynamo (torch.compile), the ProcessGroup API (collectives), torch.accelerator |
Standard PyTorch APIs, torch.accelerator |
| 3 | TorchTPU (torch_tpu) |
A C++ backend registered as PrivateUse1 and renamed tpu; deferred ops and three eager modes; a three-tier compilation cache; the tpu_dist collective backend; Pallas interop |
torch.tpu.*, TORCH_TPU_* variables |
| 4 | Compiler IR | StableHLO for ordinary ops and collectives, Mosaic for custom kernels | Pallas kernels, HLO dumps |
| 5 | libtpu | The XLA compiler and the PjRt runtime: compile, launch, copy | LIBTPU_INIT_ARGS, XLA_FLAGS |
| 6 | TPU hardware | TensorCores, SparseCores, HBM, ICI and DCN (chapter 1) | Nothing directly |
These layers follow the execution path of one process from the top down. The ecosystem view, which slices the same software by role, comes in Where the ecosystem projects sit.
Layer 1: your PyTorch code¶
TorchTPU's design goal is that this layer barely changes. The documentation's own example of a port is two lines:
device = torch.device("cuda")
dist.init_process_group(backend="nccl")
model = model.to(device)
device = torch.device("tpu")
dist.init_process_group(backend="tpu_dist")
model = model.to(device)
device = torch.accelerator.current_accelerator()
dist.init_process_group() # tpu_dist is the default for tpu devices
model = model.to(device)
The portable form works because, once TorchTPU is loaded, the TPU becomes the current accelerator and tpu_dist becomes the default distributed backend. The TorchTPU authors are clear about the limit: the model should run with that change, but a model whose shapes, sharding and operators were tuned for a GPU will not reach peak TPU performance from it alone. Parts II and III close that gap.
Layer 2: PyTorch core and the three plug-in points¶
TorchTPU is an out-of-tree backend: it does not modify PyTorch, it registers itself through the extension points PyTorch provides for new hardware. There are three of them, and they are the three arrows in the figure.
| PyTorch extension point | What TorchTPU registers | How your code reaches it |
|---|---|---|
Dispatcher, PrivateUse1 key |
A C++ backend, with its own tensor storage (a c10::UniqueVoidPtr inside c10::StorageImpl); the device is renamed tpu |
torch.device("tpu"), then any op |
| TorchDynamo custom backend | The backend "tpu" |
torch.compile(model, backend="tpu") |
ProcessGroup API (c10d::Backend) |
The backend "tpu_dist", also aliased "tpu", the default for tpu devices |
dist.init_process_group() |
You do not need import torch_tpu. When the TorchTPU wheel is installed, import torch autoloads it, which sets up the backend and renames PrivateUse1 to tpu. Setting TORCH_DEVICE_BACKEND_AUTOLOAD=0 turns that off.
Because the integration sits at the dispatcher and the process group, everything built on those two keeps working: DDP, FSDP2 and DTensor run through the same ProcessGroup API as on other accelerators. Two things are absent on purpose. TorchTPU does not use TorchInductor; torch.compile hands the FX graph to XLA instead. And its design principles exclude any JAX dependency in the runtime.
Layer 3: TorchTPU¶
This is where a PyTorch call becomes a TPU program. Each time the dispatcher calls TorchTPU for an ATen op, the runtime does not run anything. It creates a deferred op holding a StableHLO builder for that op (and, for ops such as aten::native_batch_norm, the static parameters that belong in a cache key), and returns a new tensor whose storage points, through an indirection, at that deferred op.
Work runs when a synchronization point is reached. Which points count depends on the eager mode:
| Eager mode | How to select it | What it does | CUDA analogue |
|---|---|---|---|
| Strict (default) | Nothing to set; torch.tpu.EagerMode.DEFER_NEVER |
One ATen op at a time, executed asynchronously with the CPU | Ordinary eager PyTorch on a GPU |
| Debug | TORCH_TPU_LAUNCH_BLOCKING=1 (DEFER_NEVER_AND_LAUNCH_BLOCKING) |
One op at a time, synchronous, with bounds checks | CUDA_LAUNCH_BLOCKING=1 |
| DeferAndFuse | TORCH_TPU_DEFER_AND_FUSE=1 (DEFER_AND_FUSE) |
Defers ops until a materialization point and compiles them together | None |
The TorchTPU announcement reports DeferAndFuse as 50% or more faster than Strict on some workloads, with lower peak HBM use because fused ops need fewer temporary buffers. That is the fusion of elementwise chains from chapter 2, done for you in eager mode. Chapter 4 covers the modes in depth.
At a synchronization point, TorchTPU analyzes the region of deferred ops, decides which to materialize, and builds a compilation cache key for that graph. On a hit it dispatches the cached executable; on a miss it compiles asynchronously, stores the result and dispatches it. The cache has three tiers:
| Tier | Where | Default | Setting |
|---|---|---|---|
| 1 | Process memory | Always on | None |
| 2 | Host shared memory, shared by processes on one host | On for distributed programs, off for single-device | TORCH_TPU_TIER2_COMPILATION_CACHE (a directory name under /dev/shm/torch_tpu_cache/, or "disabled") |
| 3 | A persistent path, for example on Cloud Storage, shared across hosts and restarts | Off | TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT |
The key is three 64-bit fingerprints: a shapeless key for the graph's structure, a dimensions key for its tensor sizes, and a compile options key that covers the XLA options and the versions of TorchTPU, libtpu and the PjRt runtime. Two consequences follow directly. A new input shape is a new dimensions key and therefore a new compilation (chapter 7). And upgrading TorchTPU or libtpu changes every compile options key, so a persistent cache filled by the old version gives no hits.
Two more pieces live in this layer. tpu_dist implements collectives at the ProcessGroup level, but there is no separate communication library underneath it as NCCL is on GPU: collectives are lowered to StableHLO ops (stablehlo.all_gather, stablehlo.all_to_all and so on) and compiled like everything else (chapter 13). And torch.tpu.pallas.jax_op wraps a kernel written with JAX's Pallas API so that PyTorch can call it as an ordinary operator (chapter 12).
Layer 4: StableHLO and Mosaic¶
The StableHLO that TorchTPU's builder produces for a bf16 aten::mul of two [4, 16] tensors is, from the TorchTPU documentation:
func.func @main(%arg0: tensor<4x16xbfloat16>, %arg1: tensor<4x16xbfloat16>) -> tensor<4x16xbfloat16> {
%0 = stablehlo.multiply %arg0, %arg1 : tensor<4x16xbfloat16>
return %0 : tensor<4x16xbfloat16>
}
Two properties of StableHLO shape everything TorchTPU does above it:
- It follows the SSA form, so nothing is mutated in place. A write always produces a new value, at least conceptually. PyTorch's views and in-place ops are rebuilt on top of that by view decomposition and inversion; a write into a slice becomes a
dynamic_update_slice. Chapter 5 explains what that costs. - The compiler assumes shapes are known at compile time. TorchTPU relaxes this with bounded dynamism, where only the maximum size of a dimension is fixed in advance (chapter 7).
Mosaic is the second entry point, one level lower. Pallas kernels lower to Mosaic, which gives a kernel author control that StableHLO does not, such as how tiles move through VMEM.
Layer 5: libtpu, XLA and PjRt¶
A C++ program reaches a local TPU by creating a PjRt client. Its API compiles MLIR (StableHLO or Mosaic) into a TPU executable, launches that executable, and copies data to and from the TPU. Execution is asynchronous: the CPU waits for a result by waiting on the corresponding PjRt buffer. TorchTPU is such a program, and libtpu is the library that provides the client and the TPU compiler.
You configure this layer with two environment variables, and the TorchTPU repository documentation is precise about which flag goes where:
| Variable | Takes | Example | If a flag is in the wrong one |
|---|---|---|---|
XLA_FLAGS |
Generic XLA compiler and debug flags | --xla_dump_hlo_as_text --xla_dump_to=/tmp/hlo_dump |
Startup fails: Unknown flag in XLA_FLAGS: --xla_tpu_... |
LIBTPU_INIT_ARGS |
TPU compiler flags | --xla_tpu_enable_async_collective_fusion=true |
Startup fails: Unknown command line flag 'xla_dump_to' |
The current API reference in the TorchTPU repository documents this split; the 0.2.0 API reference does not have it. Both variables, like every TorchTPU variable, are read once when the backend initializes, usually during import torch. Set them before that import, not after.
Layer 6: the hardware¶
Chapter 1 covered this layer. Three facts from it matter for the layers above. A TensorCore is single-threaded, so it runs one computation at a time; the DMA engines and SparseCores beside it can run in parallel with it. Only one user-space process can access a TPU device, which is why TorchTPU runs one process per device. And on v7x, each chip is two devices.
One operation, all the way down¶
Follow z = x * y through the stack in DeferAndFuse mode, the example the TorchTPU announcement walks through.
Watch how long the path is on the first call and how short it is on frame 10. The compile in frame 7 is paid once per distinct graph and shape; every later call with the same key goes from TorchTPU straight to PjRt.
- Your code calls the op (frames 1 and 2).
xandylive on thetpudevice, so the dispatcher sendsaten::multo TorchTPU. - TorchTPU defers it (frame 3). It records a deferred op with a StableHLO builder and returns
zat once.zis a real PyTorch tensor with a shape and dtype, but no value yet. - A materialization point arrives (frame 4).
z.cpu(),z.item()or a similar call needs the value. TorchTPU looks at the deferred ops that lead toz, runs a liveness analysis to decide which others to materialize with it (ops with side effects, such as collectives, are always kept, in order), and computes the cache key. - Cache miss, compile (frames 5 to 7). The first time, the key is not in the cache. TorchTPU builds the StableHLO program and compiles it on a thread pool through the PjRt client, then stores the executable.
- Launch and copy back (frames 8 and 9). PjRt runs the executable on the TPU. TorchTPU waits for
zto be ready and copies it from HBM into the CPU tensor. - The next time, a hit (frame 10). Same graph, same shapes, same versions: the executable is fetched and launched without compiling.
In Strict mode the region is a single op and it is dispatched right away, but the cache, the compile on a miss and the launch through PjRt are the same. The announcement explains why deferring does not leave the TPU idle in a real training loop: once the first few steps have filled the cache, the CPU only traces and dispatches, and stays ahead of a TPU that is busy with long computations. For loops that never reach a host transfer, a repeated-ops heuristic detects the repetition (think of a stack of transformer blocks) and starts materialization early.
Where the ecosystem projects sit¶
Most of the projects in the TorchTPU ecosystem are PyTorch programs, so they sit in layer 1 and reach the TPU through the same three plug-in points as your own code. Two sit above the stack and coordinate many processes, and one sits beside it, in your coding assistant.
Most projects are PyTorch programs in layer 1 and reach the TPU through the same three plug-in points as your own code; TorchTPU itself is layer 3, with its registrations in layer 2. Ray and llm-d coordinate many such processes from above, and the TPU Agent Suite (Preview) works beside the stack, in your coding assistant.
| Project | Where it sits | What it adds | Chapter |
|---|---|---|---|
TorchTPU (google-pytorch/torch_tpu) |
Layer 3, with registrations in layer 2 | The backend itself: device, eager modes, torch.compile backend, compilation cache, tpu_dist, Pallas interop |
This Part |
| TorchTitan on TPU | Layer 1 (training framework) | TPU sharding and compilation passes co-developed with Meta, SimpleFSDP with parameter sharding inside the compiled graph, whole-step graph compilation, recipes for dense, MoE and diffusion models |
14 |
| vLLM-TorchTPU, SGLang-TorchTPU | Layer 1 (serving engines) | The standard vLLM and SGLang schedulers, KV cache managers and API servers, running on TorchTPU execution with Pallas kernels for compute-intensive blocks inside the compiled graph | 18, 19 |
| Hugging Face Transformers and Diffusers; TorchRec | Layer 1 (model libraries) | Models that run with to("tpu") or device_map="tpu"; TorchRec offloads sparse embedding lookups to SparseCores |
9 |
| Ray | Above layer 1, across processes and hosts | Reserves whole slices (SlicePlacementGroup), gives each worker one TPU device, and configures TorchTPU's slice-builder addresses and mesh topology |
15 |
| llm-d | Above the serving engines, across a Kubernetes fleet | Runs in front of vLLM and SGLang: routes requests by prefix-cache state and replica load, coordinates disaggregated prefill and decode pools, manages tiered KV cache offload | 20, 21 |
| TPU Agent Suite (Preview) | Beside the stack, in your coding assistant | A router agent (tpu-agent) that hands each request to tpu-model-onboarding, tpu-diagnostics, tpu-kernel-development or tpu-knowledge-base; every command it runs on your VM or cluster needs your approval |
26 |
The figure above and the ecosystem figure in chapter 0 draw the same picture, chapter 0's from the top: the frameworks in one row, the dispatcher and ProcessGroup API beneath them, and TorchTPU beneath those. Read by role, the projects stack in the same order: torch_tpu, then the engines, then RL frameworks, then orchestration such as llm-d and Ray, then the TPU Agent Suite. This chapter's stack is what each of them runs on.
The practical reading of the table: when vLLM-TorchTPU recompiles or TorchTitan reports a low MFU, the cause is almost always in layers 2 to 5 of the stack under it, and the tools for finding it (eager modes, the cache, HLO dumps, XProf) are the same ones you use on your own code.
Device and accelerator APIs¶
TorchTPU sorts every public API into stages, and the stage tells you how much to trust a call across releases. The list in torch_tpu/docs/public_apis.md is generated from the code and is the reference this book follows; TorchTPU states that using any API not on it is undefined behaviour.
| Stage | What it covers | Promise |
|---|---|---|
| Stable | torch.accelerator.* device, stream, memory and RNG calls; torch.tpu.ops.max_pool{1,2,3}d and their backward ops; variables such as TPU_VISIBLE_DEVICES, LIBTPU_INIT_ARGS, TORCH_DEVICE_BACKEND_AUTOLOAD |
Changes go through a deprecation process |
| Experimental | Most of torch.tpu: eager modes, Precision and precision, get_device_properties, Stream and Event, torch.tpu.distributed, torch.tpu.pallas, torch.tpu.ops, torch.tpu.optimizers, torch.tpu.profiler; variables such as TORCH_TPU_DEFER_AND_FUSE and XLA_FLAGS |
May change or disappear in any release; a one-time warning on first use |
| Deprecated | For example torch.tpu.get_device_name (since 0.2.1) and torch.tpu.topology_aware_mesh (since 0.2.0) |
Removed at least two minor releases later |
| Internal | torch.tpu duplicates of torch.accelerator calls: is_available, device_count, current_device, set_device, synchronize, current_stream, set_stream, device, get_rng_state, initial_seed |
Calling one from your code raises an error |
The rule that follows: use torch.accelerator for anything it covers, and torch.tpu only for what is TPU-specific. The internal torch.tpu device calls raise a RuntimeError from user code on PyTorch 2.11 or later (2.13 or later for the two RNG calls). TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1 turns the error into a one-time warning while you migrate; the API reference says it will likely be removed in a future release.
import torch
device = torch.accelerator.current_accelerator() # torch.device("tpu") when the TPU is the accelerator
print(torch.accelerator.is_available())
print(torch.accelerator.device_count()) # devices visible to this process
print(torch.accelerator.current_device_index())
props = torch.tpu.get_device_properties() # Experimental
print(props.name, props.devices_per_chip, props.hbm_bytes_per_device, props.bf16_flops_per_device)
Names that moved between releases
torch.tpu.get_device_name()is deprecated since TorchTPU 0.2.1; readtorch.tpu.get_device_properties().name. Thetotal_memoryandmulti_processor_countproperties are deprecated in the same release; usehbm_bytes_per_deviceand the other TPU-specific fields.torch.tpu.topology_aware_meshis deprecated since 0.2.0 in favour oftorch.tpu.distributed.topology_aware_mesh. The 0.2.0 API reference page and the TorchTPU announcement still show the old name;public_apis.mdis the one to follow.
The CUDA translation table¶
The table below maps common CUDA calls to their TorchTPU counterparts, as given in TorchTPU's public API list, its API reference and its architecture documentation. "PyTorch" in the stage column means a standard PyTorch call that takes a TPU device type or backend name.
| Area | On CUDA | On TorchTPU | Stage | What to know |
|---|---|---|---|---|
| Device | torch.device("cuda") |
torch.device("tpu") or torch.accelerator.current_accelerator() |
PyTorch | Available after import torch through autoload |
| Device | torch.cuda.is_available() |
torch.accelerator.is_available() |
Stable | |
| Device | torch.cuda.device_count() |
torch.accelerator.device_count() |
Stable | Counts devices visible to the current process |
| Device | torch.cuda.set_device(i) |
torch.accelerator.set_device_index(i) |
Stable | |
| Device | torch.cuda.current_device() |
torch.accelerator.current_device_index() |
Stable | |
| Device | torch.cuda.get_device_properties() |
torch.tpu.get_device_properties() |
Experimental | name, devices_per_chip, hbm_bytes_per_device, bf16_flops_per_device and more |
| Sync | torch.cuda.synchronize() |
torch.accelerator.synchronize() |
Stable | Waits for all pending TPU work, including deferred ops |
| Streams | torch.cuda.Stream, torch.cuda.Event |
torch.tpu.Stream, torch.tpu.Event |
Experimental | One computation at a time per TensorCore (see below); torch.tpu.Event(enable_timing=True) supports elapsed_time |
| Visibility | CUDA_VISIBLE_DEVICES |
TPU_VISIBLE_DEVICES |
Stable | Comma-separated TPU chip indices |
| Memory | torch.cuda.memory_allocated(), max_memory_allocated() |
torch.accelerator.memory.memory_allocated(), max_memory_allocated() |
Stable | |
| Memory | torch.cuda.empty_cache() |
torch.accelerator.memory.empty_cache() |
Stable | |
| RNG | torch.cuda.manual_seed_all(s) |
torch.tpu.manual_seed_all(s) |
Experimental | |
| Mixed precision | torch.amp.autocast("cuda", dtype=torch.bfloat16) |
torch.amp.autocast("tpu", dtype=torch.bfloat16) |
PyTorch | bf16 is the default autocast dtype on TPU |
| fp32 matmuls | torch.set_float32_matmul_precision(...) |
The same call, plus with torch.tpu.precision(torch.tpu.Precision.HIGH): for a scope |
PyTorch, Experimental | TorchTPU defaults to "medium": one bf16 MXU pass, fp32 accumulation. "high" is about 3 times the MXU cost, "highest" about 6 times |
| Compile | torch.compile(model) (Inductor) |
torch.compile(model, backend="tpu") |
PyTorch | XLA, not TorchInductor |
| Debug | CUDA_LAUNCH_BLOCKING=1 |
TORCH_TPU_LAUNCH_BLOCKING=1 |
Experimental | Synchronous Debug mode, adds bounds checks |
| Fusion in eager | None | TORCH_TPU_DEFER_AND_FUSE=1 |
Experimental | No CUDA counterpart |
| Distributed | dist.init_process_group(backend="nccl") |
backend="tpu_dist" (alias "tpu"), or no argument |
PyTorch | Collectives are StableHLO ops, not a separate library |
| Mesh | DeviceMesh("cuda", ...) |
DeviceMesh("tpu", mesh=torch.tpu.distributed.topology_aware_mesh(shape)) |
Experimental | Orders ranks to follow the physical ICI torus |
| Launch | torchrun alone |
torch.tpu.distributed.set_tpu_launch_env(), or the shell recipe under Porting, before torchrun |
Experimental | Sets TORCH_TPU_TOPOLOGY and TORCH_TPU_SLICEBUILDER_ADDRESSES |
| IR | PTX | StableHLO, Mosaic | The documentation's own analogy | |
| Kernels | Triton or CUDA C++ kernels | Pallas kernels wrapped with torch.tpu.pallas.jax_op; Helion (experimental) |
Experimental | A rewrite, not a port |
| Attention kernel | A FlashAttention-style kernel | torch.tpu.ops.splash_sdpa(q, k, v, ...) |
Experimental | Backed by the Pallas Splash Attention kernel |
| Profiling | torch.profiler with CUDA activity |
torch.profiler with ProfilerActivity.TPU and experimental_config=TpuProfilerConfig(...) |
Experimental | Traces open in XProf (chapter 10) |
| Monitoring | nvidia-smi |
tpu-info |
Installed with vllm-torchtpu; shows chip utilization and HBM use |
Look at the colour of the stage tags. The green rows are the ones to write without hesitation; the amber rows work today but may change between TorchTPU releases, so keep them in one place in your code; the blue rows are plain PyTorch with a different device or backend name.
Porting a small CUDA training script¶
The companion code has a single-device CUDA training loop (before_cuda.py) and its port (after_tpu.py). The model is a two-layer MLP learning a fixed linear map on synthetic data, trained with AdamW, bf16 autocast and torch.compile, logging the loss with .item() every 10 steps. The data is generated on the CPU from a seeded generator, so both versions see the same batches. This is the whole diff between them, without the docstrings:
+def pick_device(force_cpu: bool = False) -> torch.device:
+ """The current accelerator if it is a TPU, else the CPU."""
+ acc = torch.accelerator.current_accelerator() if torch.accelerator.is_available() else None
+ if acc is not None and acc.type == "tpu" and not force_cpu:
+ return acc
+ return torch.device("cpu")
+
+
def main(argv=None) -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--steps", type=int, default=50)
+ ap.add_argument("--cpu-smoke", action="store_true", help="use the CPU even if a TPU is present")
args = ap.parse_args(argv)
- if not torch.cuda.is_available():
- print("before_cuda.py needs an NVIDIA GPU with CUDA; none found. Run after_tpu.py instead.")
- return 0
- device = torch.device("cuda")
- print(f"device: {device} ({torch.cuda.get_device_name()})")
+ device = pick_device(args.cpu_smoke)
+ on_tpu = device.type == "tpu"
+ if on_tpu:
+ print(f"device: {device} ({torch.tpu.get_device_properties().name})")
+ else:
+ print("device: cpu (CPU FALLBACK: no TPU found; eager, no torch.compile; checks logic only)")
torch.manual_seed(0)
- torch.cuda.manual_seed_all(0)
- torch.set_float32_matmul_precision("high")
+ if on_tpu:
+ torch.tpu.manual_seed_all(0)
+ torch.set_float32_matmul_precision("medium")
model = build_model().to(device)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
- step_fn = torch.compile(model)
+ step_fn = torch.compile(model, backend="tpu") if on_tpu else model
...
- with torch.amp.autocast("cuda", dtype=torch.bfloat16):
+ with torch.amp.autocast(device.type, dtype=torch.bfloat16):
loss = F.mse_loss(step_fn(x).float(), y)
...
- torch.cuda.synchronize()
- print(f"peak memory: {torch.cuda.max_memory_allocated() / 2**20:.1f} MiB")
+ if on_tpu:
+ torch.accelerator.synchronize()
+ print(f"peak memory: {torch.accelerator.memory.max_memory_allocated() / 2**20:.1f} MiB")
Line by line:
- Device.
torch.accelerator.current_accelerator()returns thetpudevice on a TPU VM. A script that will only ever run on a TPU can writetorch.device("tpu").pick_deviceexists so the same file runs on a laptop: when the current accelerator is not a TPU (no accelerator, a GPU, or Apple's MPS), it falls back to the CPU and printsCPU FALLBACK. That run checks the logic and nothing else. - Seeding.
torch.cuda.manual_seed_allbecomes the Experimentaltorch.tpu.manual_seed_all. - Precision. This line changes meaning, not just spelling. On TorchTPU,
"high"selects a 3-pass algorithm at roughly 3 times the MXU cost, and"medium", the TorchTPU default, is one bf16 pass with fp32 accumulation. Translate by intent: if the CUDA script picked its setting for speed, the TPU setting is"medium". Chapter 6 covers when to choose otherwise. - Compile. The backend becomes
"tpu". The first step compiles the whole model into one TPU program; later steps reuse it. - Autocast, synchronize, memory. The device type string changes, and the two
torch.cudacalls become their Stabletorch.acceleratorforms.
Everything else stays: the model, the optimizer, the data, loss.backward(), opt.step(), and the .item() logging.
The .item() call is worth a second look. On a TPU it is a materialization point: the host waits for the step to finish and copies one number back. Every 10 steps that costs little; every step, it stops the host from running ahead of the TPU, and in DeferAndFuse mode it also cuts the fused region short. Chapter 4 shows how to find such points.
A multi-process version needs the two launch variables from the translation table. The TorchTPU announcement's single-host recipe sets them in the shell and then calls torchrun as usual:
eval $(python -m torch.tpu.distributed | sed 's/^/export /')
torchrun --nproc_per_node=8 train.py
Inside train.py, each process calls dist.init_process_group(backend="tpu_dist") and uses torch.device("tpu"). Chapter 8 covers launching on VMs and GKE.
What does not translate one to one¶
The table above maps names. The habits below need more than a new name, and each has its own chapter.
| CUDA habit | What is different on TorchTPU | Chapter |
|---|---|---|
| An eager op runs as soon as it is launched | Three eager modes; deferred ops run at materialization points such as .cpu(), .item() or if tensor.all():, which also end a fused region |
4 |
| Views and in-place writes are free metadata changes | StableHLO values are immutable; views are rebuilt by decomposition and inversion, and some cost a copy | 5 |
| fp32 matmuls run at fp32 or TF32 accuracy | The default is one bf16 MXU pass with fp32 accumulation; "high" and "highest" cost about 3 and 6 times as much |
6 |
| Input shapes may change every step | Each new shape is a new compilation; torch.compile currently sets dynamic=False on TPU, and bounded dynamism is the way out |
7 |
A process sees every GPU on the node and picks cuda:{local_rank} |
A process sees one device, and must know it is distributed, the world size and the TPU type before init_process_group |
8, 13 |
| Streams overlap independent kernels | A TensorCore runs one computation at a time; overlap comes from DMA engines, SparseCores and the XLA schedule. The API reference states that manual multi-stream management is not needed | 4, 10 |
| NCCL runs collectives as a separate library | Collectives are StableHLO ops; by default each is compiled in its own small module so ranks cannot diverge, which costs overlap until you mark code with torch.tpu.distributed.spmd_safe |
13 |
| FSDP2 with eager hooks | TorchTPU lists SimpleFSDP as validated and FSDPv2 as experimental with low performance |
14 |
| Triton or CUDA kernels | Rewritten in Pallas and called through torch.tpu.pallas.jax_op, or in Helion (experimental) |
12 |
| Two processes can share a GPU | Only one process can access a TPU device, so RL colocation does not work out of the box | 15 |
When something goes wrong, the symptom usually tells you the layer. This map is a first triage, not a full diagnosis:
Find the symptom and follow its arrow to the layer to look at first. No tpu device means TorchTPU is not installed, no TPU was found, or TORCH_DEVICE_BACKEND_AUTOLOAD=0 turned its autoload off; an unknown flag sits in the wrong one of the two variables. Only the green card needs no fix: the first step compiles, and a Tier-3 cache lets restarts skip it.
Verifying the result¶
A port has worked when four things are true: the TPU backend is loaded, your tensors and results live on the TPU, you know exactly which versions produced the result, and the numbers agree with a CPU reference to the accuracy the MXU should give. check_env.py checks all four.
- Rehearse on a laptop.
python code/ch03_stack/check_env.py --cpu-smokeprints the eight checks and the API each one uses, runs them on your CPU, and shows that the validator rejects that run for the right reasons (notpuaccelerator, tensors oncpu). It then validates a hand-written example of a passing TPU report fromfixtures/. - Run it on the TPU VM.
python code/ch03_stack/check_env.py --json report.json. A passing run showsaccelerator: tpu,tensor_deviceandresult_deviceon atpudevice, at least one visible device, a device name that matches the machine you asked for, and the installedtorchandtorch_tpuversions. Keep the JSON with your results: the versions are part of every cache key and of every performance claim. - Read the numerical check. The script multiplies two fp32
[512, 512]matrices on the TPU and compares with the CPU. At the default precision the relative error should be about 2e-3, the error of rounding the inputs to bf16 (the script simulates that on the CPU and prints it). It must be below 1e-2. Insidetorch.tpu.precision(torch.tpu.Precision.HIGHEST)it must be below 1e-4. A default-precision error near 1e-7 is a warning sign: the matmul did not go through a single bf16 pass, so either it ran on the CPU or a global precision override is set. - Run the port. On the TPU VM,
python code/ch03_stack/port_example/after_tpu.pyshould print the chip name on its device line, a first step that takes noticeably longer than the rest (the compile), andloss decreased. If it printsCPU FALLBACK, check 2 will tell you why. - Look at what the compiler saw, once. Set
XLA_FLAGS="--xla_dump_hlo_as_text --xla_dump_to=/tmp/hlo_dump"before starting Python, run a few steps, and open a*.after_optimizations.txtfile. You should find your model's matmuls in it. This is the layer 5 view of your program, and chapter 10 builds on it.
Worked problems¶
Problem 1. Name the layer of the stack where each of these lives: (a) --xla_tpu_enable_async_collective_fusion=true; (b) TORCH_TPU_DEFER_AND_FUSE=1; (c) stablehlo.all_gather; (d) torch.compile's graph capture; (e) a SparseCore.
Answer
(a) Layer 5, libtpu: it is a TPU compiler flag and goes in LIBTPU_INIT_ARGS. (b) Layer 3, TorchTPU: it selects the eager mode. (c) Layer 4, StableHLO: tpu_dist in layer 3 lowers a torch.distributed all-gather to this op. (d) Layer 2, PyTorch core: TorchDynamo captures the FX graph and hands it to TorchTPU's "tpu" backend in layer 3. (e) Layer 6, the hardware.
Problem 2. Translate each CUDA line to TorchTPU and give the stage of the API you used: torch.cuda.is_available(), torch.cuda.empty_cache(), torch.cuda.manual_seed_all(0), CUDA_LAUNCH_BLOCKING=1, dist.init_process_group(backend="nccl").
Answer
| CUDA | TorchTPU | Stage |
|---|---|---|
torch.cuda.is_available() |
torch.accelerator.is_available() |
Stable |
torch.cuda.empty_cache() |
torch.accelerator.memory.empty_cache() |
Stable |
torch.cuda.manual_seed_all(0) |
torch.tpu.manual_seed_all(0) |
Experimental |
CUDA_LAUNCH_BLOCKING=1 |
TORCH_TPU_LAUNCH_BLOCKING=1 |
Experimental |
dist.init_process_group(backend="nccl") |
dist.init_process_group(backend="tpu_dist"), or no backend argument |
PyTorch call, TorchTPU backend name |
Problem 3. Which project would you reach for? (a) Serve an open LLM behind an OpenAI-compatible API on a TPU host. (b) Route multi-turn chat requests across a fleet of serving replicas on GKE so each turn lands where its context is cached. (c) Pre-train a dense LLM with FSDP over a multi-host slice. (d) Have your coding assistant work out why a model has an unsupported operator.
Answer
(a) vLLM-TorchTPU or SGLang-TorchTPU. (b) llm-d, in front of those engines. (c) TorchTitan on TPU, with SimpleFSDP. (d) The TPU Agent Suite; its tpu-model-onboarding agent resolves unsupported operators.
Problem 4. On PyTorch 2.11, a script that ran on an older setup now fails at torch.tpu.synchronize() with a RuntimeError. Explain why, and give the fix and the stopgap.
Answer
torch.tpu.synchronize duplicates torch.accelerator.synchronize. On PyTorch 2.11 and later, TorchTPU classifies such duplicates as internal, and calling one from user code raises an error. The fix is torch.accelerator.synchronize(), a Stable API. The stopgap is TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1, which turns the error into a one-time warning; the API reference says it will likely be removed, so treat it as temporary.
Problem 5. A training job uses a Tier-3 compilation cache on Cloud Storage, and restarts usually skip compilation. After an image update that upgraded libtpu, the first step takes minutes again although the model and batch shapes did not change. Explain.
Answer
The cache key has three parts, and the compile options key includes the versions of TorchTPU, libtpu and the PjRt runtime. A new libtpu gives every graph a new key, so none of the cached executables match and each graph is compiled again (and then cached under the new key). The shapeless and dimensions keys did not change, which is why the second restart on the new image is fast again.
Problem 6. In DeferAndFuse mode, z = x * y returns immediately even when x and y are very large, and the time shows up later at print(z.sum().item()). Explain where the work went and what happens at the print.
Answer
The dispatcher called TorchTPU, which only recorded a deferred op (a StableHLO builder) and returned a tensor whose storage points at it; nothing ran on the TPU. .item() is a materialization point: TorchTPU takes the region of deferred ops leading to the result (the multiply and the sum), builds its cache key, compiles it on a miss, launches it through PjRt, waits, and copies the scalar back. Because z is still referenced from Python, it is materialized too. Had the code been print((x * y).sum().item()), the product would be a temporary that is already dropped at the materialization point, and TorchTPU could fuse it into the sum without writing it out.
Problem 7. A model that calls torch.nn.functional.scaled_dot_product_attention runs on TorchTPU after a device change, but a model with a custom Triton attention kernel does not. Explain the difference, and the two ways to bring the Triton model over.
Answer
scaled_dot_product_attention is a PyTorch operator, so it reaches TorchTPU through the dispatcher and TorchTPU supplies the TPU implementation (the TorchTPU announcement discusses it as a kernel provided by the PyTorch framework). A Triton kernel is GPU code that bypasses that path. The TPU's entry points are StableHLO and Mosaic, so the kernel has to be rewritten: in Pallas and registered with torch.tpu.pallas.jax_op (production-ready), or in Helion with backend="pallas" (experimental). Before writing one, check torch.tpu.ops.splash_sdpa and the Tokamax kernels, which may already cover it.
Problem 8. A colleague's check_env.py report shows accelerator: tpu, tensor_device: tpu:0, matmul_rel_err_default: 4e-07 and a warning. What most likely happened, and why does the check warn instead of failing?
Answer
The tensors are on the TPU, so this is not a CPU fallback. An fp32 matmul at TorchTPU's default precision rounds its inputs to bf16 and should be off by about 2e-3; 4e-7 is fp32-level agreement, so something made the matmul run at high precision. The usual cause is a global torch.set_float32_matmul_precision("highest") (or "high") set earlier in the process or by a library. The result is correct, so the check does not fail, but it costs about 3 to 6 times the MXU time, which is worth knowing before you benchmark.
Quick questions¶
- List the six layers from the top down and name one thing you can set or call in each of layers 1 to 5.
- What are the three PyTorch extension points TorchTPU registers with, and what name does it register at each?
- Why does a TorchTPU op return before the TPU has done any work, and name three calls that force the work to happen.
- What three fingerprints make up a compilation cache key, and which one changes when you upgrade libtpu?
- Which of
torch.accelerator.synchronize,torch.tpu.get_device_propertiesandtorch.tpu.synchronizeis Stable, which Experimental, and which internal? - A CUDA script sets
torch.set_float32_matmul_precision("high")for speed. What does the same line cost on TorchTPU, and what should the port set instead?
Key takeaways¶
- The stack has six layers: your PyTorch code, PyTorch core, TorchTPU, the compiler IR (StableHLO and Mosaic), libtpu (XLA compiler and PjRt runtime), and the TPU hardware. Most problems can be placed in one of them by their symptom.
- TorchTPU plugs into PyTorch at three points: the dispatcher (
PrivateUse1, renamedtpu), TorchDynamo (backend"tpu") and the ProcessGroup API ("tpu_dist"). Anything built on those, from DTensor to vLLM, comes along. - Every op becomes a deferred op with a StableHLO builder. It runs at a synchronization point that depends on the eager mode, through a three-tier compilation cache keyed by graph structure, tensor sizes and compiler options including the TorchTPU, libtpu and PjRt versions.
- Use
torch.acceleratorfor device, stream, memory and synchronization calls; usetorch.tpuonly for TPU-specific features, and treat those as Experimental. Thetorch.tpuduplicates oftorch.acceleratorcalls raise an error on PyTorch 2.11 and later. - Most CUDA names have a direct TorchTPU counterpart, but some that look identical change meaning:
"high"matmul precision costs about 3 times the MXU time on a TPU, and the fast default is"medium". - Eager timing, views, precision, dynamic shapes, process-to-device mapping, streams, collectives and custom kernels do not translate one to one; chapters 4 to 7, 12 and 13 deal with them.
- A port is verified when the backend is
tpu, tensors and results live on the TPU, the versions are recorded, and an fp32 matmul agrees with the CPU to about 2e-3 at default precision and far better atPrecision.HIGHEST.
References¶
- How TorchTPU works: TPU primer, StableHLO and Mosaic, PJRT, out-of-tree
PrivateUse1backend, deferred ops, compilation cache tiers,torch.compilewithout TorchInductor - TorchTPU Public APIs: API stages and the Stable, Experimental, deprecated and internal lists
- TorchTPU API Reference: CUDA-to-TorchTPU tables, device queries, streams and events, launch variables, the
LIBTPU_INIT_ARGSandXLA_FLAGSsplit, HLO dumps - TorchTPU API Reference, 0.2.0: the 0.2.0 release of the same page
- TorchTPU execution model: Strict as the default eager mode, synchronization calls
- TorchTPU supported feature set and future work: validated and experimental features, including
SimpleFSDPand FSDPv2 - Introducing TorchTPU: design principles, eager modalities, the deferred-op walk-through, compilation cache keys, kernels and distributed initialization
- Introducing TorchTPU: Native PyTorch on Google Cloud TPUs: talk on the dispatcher and ProcessGroup integration
- PyTorch on Cloud TPU: the ecosystem projects and what each adds
- Cloud TPU Setup for vLLM-TorchTPU:
tpu-infofor chip utilization and HBM use - TorchTPU source repository: Python and C++ layers,
set_tpu_launch_env - TorchTPU performance: execution modes, XProf and Pallas kernels:
torch.profilerwithProfilerActivity.TPUandTpuProfilerConfig - Companion code for this chapter




