DEV Community

Cover image for TorchTPU Performance: Execution Modes, XProf and Pallas Kernels
Omotayo Aina for Google Developer Experts

Posted on Edited on

TorchTPU Performance: Execution Modes, XProf and Pallas Kernels

Build the TPU mental model first (tiles, functional graphs, the deferred pipeline, cache tiers, MXU precision), then use it to delete copies, syncs and recompiles from a real FLUX block.

Series: A five-part, hands-on series for PyTorch engineers moving real workloads onto Cloud TPU v6e (Trillium) and v7x (Ironwood) with TorchTPU. Part 1 builds the mental model (execution modes, memory, profiling, kernels). Part 2 runs Hugging Face Transformers v5 and Diffusers natively. Part 3 serves models in production with vLLM-TorchTPU, SGLang-TorchTPU and llm-d. Part 4 trains and post-trains at pod scale with TorchTitan, Ray and GRPO. Part 5 hands the whole workflow to the TPU Agent Suite.

This is Part 1. Next: Part 2: Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers, Part 3: vLLM and SGLang on TPU: Production Serving with llm-d 1.0, Part 4: TorchTitan on Cloud TPU: SimpleFSDP, Graph Trainer, Ray and GRPO, Part 5: TPU Agent Suite: Onboard, Profile and Tune PyTorch on Cloud TPU.

The problem: it runs, but it is not fast

You changed .to("cuda") to .to("tpu"), and your model ran on the first try. That part of the TorchTPU promise holds. Then you looked closer. The training step is slower than the chip's spec sheet suggests. The decode loop takes 40 ms per token when the math should take well under one. XProf shows copy ops you never wrote, and the TPU timeline has gaps where nothing runs at all.

None of these are bugs in your model. They come from three facts about TPUs that CUDA never made you think about: TPU memory is laid out in 2D tiles, the compiler is functional, and every new tensor shape is a new program. Once you can see those three facts, the fixes are short and mechanical.

This post builds that picture first, then applies it. Everything here is backed by a runnable script, code/sample_01_torchtpu_execution_xprof_and_pallas.py, with CPU tests in tests/test_sample_01.py. Every API name was checked against the TorchTPU 0.2.0 source tree.

What you'll be able to do

By the end you should be able to:

  • Explain how a PyTorch op becomes a StableHLO program, why data_ptr() on TPU points at CPU metadata, and why views are not free.
  • Compare Strict Eager, Debug Eager, DeferAndFuse and torch.compile(backend="tpu"), and configure each one plus the three compilation cache tiers.
  • Configure MXU precision with torch.tpu.Precision and verify CPU vs TPU parity with tolerances that mean something.
  • Diagnose host syncs, backward view copies and per-token recompiles in a torch.profiler trace opened in XProf.
  • Decide when to reach for a Tokamax kernel, a hand-written Pallas kernel, or nothing at all.
  • Build and verify a fused Pallas op registered through torch.tpu.pallas.jax_op.

Setup

You need a Cloud TPU VM (v6e or v7x) with TorchTPU installed, and PyTorch 2.12 or newer if you want the native torch.profiler TPU integration. TorchTPU 0.2.0 actively supports v5e, v5p, v6e and v7x. Most of the APIs below are marked Experimental in the source (@annotations.experimental), so expect names to move between releases.

git clone https://github.com/ainaomotayo/torchtpu-sprint-26h4
cd torchtpu-sprint-26h4

# On a laptop: every pure-PyTorch path, no TPU needed.
python code/sample_01_torchtpu_execution_xprof_and_pallas.py --cpu-smoke

# On the TPU VM. tcmalloc avoids glibc arena lock contention between the
# Python dispatch thread and TorchTPU's background workers.
LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4 \
  python code/sample_01_torchtpu_execution_xprof_and_pallas.py --all
Enter fullscreen mode Exit fullscreen mode

The tcmalloc line is not folklore: torch_tpu/__init__.py runs _tcmalloc_check.check_tcmalloc() at import and emits a //TorchTpu/Performance/TcMalloc// warning when it is missing. The sample's inspect_tpu_environment() repeats that check on Linux by reading /proc/self/maps.

Part A: The hardware you are actually programming

TensorCores, MXUs and SparseCores

A TPU chip is built around one or more TensorCores. Each TensorCore is a single-threaded processor with matrix multiply units (MXUs), a vector unit (VPU) and a scalar unit. The MXU is a systolic array: it takes wide 2D operands and does a lot of multiply-accumulate work per cycle, but it cannot be split into independent threads, and it is bad at random-access reads and writes. Recent generations add SparseCores for gathers, scatters and embedding lookups, which can run at the same time as the TensorCore.

TorchTPU exposes the static facts per PyTorch device through torch.tpu.get_device_properties(). These numbers come straight from TpuSpec in csrc/common/tpu_hardware.cc:

Generation PyTorch devices per chip HBM per device Peak bf16 per device SparseCores per device
TPU v5e 1 16 GiB 197 TFLOP/s 0
TPU v5p 1 95 GiB 459 TFLOP/s 4
TPU v6e (Trillium) 1 32 GiB 918 TFLOP/s 2
TPU v7x (Ironwood) 2 96 GiB 1,153.5 TFLOP/s 2

The v7x row deserves a second look. An Ironwood chip has 192 GiB of HBM and 2,307 bf16 TFLOP/s, but it has no megacore fusion, so TorchTPU exposes each chip as two PyTorch devices (devices_per_chip = 2). A 4-chip tpu7x-standard-4t host shows up as 8 devices. Size your batch and your sharding against the per-device numbers, not the chip datasheet.

Query it with the Stable API first

The sample's inspect_tpu_environment() uses the device-agnostic torch.accelerator API wherever one exists and falls back to torch.tpu only for TPU-specific properties. The core of it:

device = torch.accelerator.current_accelerator()          # device(type='tpu')
free_b, total_b = torch.accelerator.get_memory_info()     # live HBM, bytes
props = torch.tpu.get_device_properties()                 # Experimental
print(props.name, props.devices_per_chip, props.hbm_bytes_per_device,
      props.bf16_flops_per_device, props.sparse_cores_per_device, props.topology)
Enter fullscreen mode Exit fullscreen mode

In PyTorch 2.11 and later, the redundant torch.tpu device helpers (for example torch.tpu.device_count()) are internal and raise if you call them from user code. Use torch.accelerator.device_count() and friends. If you are migrating a big codebase, TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1 downgrades that error to a one-time warning while you clean up.

Ridge points: is this op paying for HBM or for the MXU?

get_device_properties() gives you peak FLOP/s but not HBM bandwidth, so the sample carries a small table for the roofline math (v6e: 1,638 GB/s per chip; v7x: 7,380 GB/s per chip, split across its two devices). The ridge point is peak compute divided by bandwidth. Any op with fewer FLOPs per HBM byte than that is bandwidth bound.

Log-log roofline chart for TPU v6e and v7x per device: v6e ridge at 560 FLOP per byte, v7x at 313, with a decode GEMV at 1 FLOP per byte and a 4096 cubed GEMM at 1365 FLOP per byte

Notice how far left the decode GEMV sits: at 1 FLOP per byte it uses well under 1% of either chip's MXU, which is why decode is a memory problem.

Running --cpu-smoke on a laptop prints the same table from the offline specs:

  TPU v6e    32.0 GiB    918.0 bf16 TFLOP/s    1638 GB/s  ridge  560 FLOP/B
  TPU v7     96.0 GiB   1153.5 bf16 TFLOP/s    3690 GB/s  ridge  313 FLOP/B (fp8 625)
Enter fullscreen mode Exit fullscreen mode

Two consequences matter for the rest of this post. First, an elementwise chain (add, GELU, RMSNorm) does well under one FLOP per byte, so on TPU its cost is the HBM round trip, and fusion is the only fix. Second, the v7x ridge is lower than v6e's because Ironwood's bandwidth grew faster than its compute, so more of your model becomes compute bound on v7x.

Memory is 2D tiles, not a 1D byte array

On CUDA, a buffer is a 1D byte array and a kernel thread can read any offset. TPU memory is organized as two-dimensional register-aligned tiles. The last two dimensions of every array are padded to the tile: 8 sublanes by 128 lanes of 32-bit words. Narrow types pack several values per word, so in VMEM a bf16 tile holds (16, 128) elements and an 8-bit tile (32, 128).

Predict before you look: a (20, 200) float32 tensor holds 4,000 numbers. How many slots does it occupy?

Animation laying a 20 by 200 float32 tensor into 8 by 128 tiles: six tiles, 4,000 real elements in blue, 2,144 padding slots in orange, 65.1 percent utilization

Watch the third tile row: only 4 of its 8 sublanes carry data, and the second tile column is 72 of 128 lanes wide, so one third of what the hardware moves is padding.

The answer is 6,144 slots, 65.1% utilization. The sample's tile_padding_report() does this arithmetic for any shape and dtype, and tests/test_sample_01.py pins the classic worst case: a (1024, 1, 1) tensor uses 1 of every 1,024 slots. XLA picks the real physical layout, and on a TPU torch.tpu.get_device_layout_if_materialized(t) shows you what it chose for a materialized tensor. The practical rule is simple: keep the two minor dimensions at multiples of 8 and 128, and squeeze trailing singleton dimensions before they reach a hot loop.

What data_ptr() points at

PyTorch's torch.UntypedStorage is little more than a pointer and a byte count, which maps cleanly onto CUDA. It does not carry enough information for a TPU, where a buffer is always typed and has a known multi-dimensional shape. TorchTPU's answer is the key to everything else: on TPU, UntypedStorage.data_ptr() does not point at device memory. It points at a CPU-side metadata object that describes the TPU buffer.

Side-by-side diagram: on CUDA, data_ptr points directly at a 1D byte buffer; on TorchTPU, data_ptr points at CPU metadata that references a 2D tiled HBM buffer

The extra hop on the right is what lets TorchTPU swap the underlying buffer on every in-place write without PyTorch noticing.

That indirection lets TorchTPU translate between PyTorch's mutable, stride-based world and XLA's immutable, shape-based one. The next section shows how.

Part B: Functional graphs, views and buffer donation

XLA consumes StableHLO, which is a static single assignment language: values are created, never modified. PyTorch is full of mutation (add_, out=, slicing assignment) and shared-storage views. TorchTPU bridges the two with four mechanisms, all described in the TorchTPU memory model docs.

View decomposition. A strided view is reinterpreted as a sequence of logical StableHLO ops. This example from the docs builds the same tensor two ways:

base = torch.arange(10, dtype=torch.float)
physical_view = base.as_strided(sizes=(2, 2, 2), strides=(2, 3, 0), storage_offset=1)
# StableHLO: slice, reshape, slice, transpose, reshape, broadcast_in_dim
logical_view = base[1:].view(3, 3)[:2, ::2].t().unsqueeze(-1).expand(2, 2, 2)
Enter fullscreen mode Exit fullscreen mode

Logical equivalence is guaranteed. Equal cost is not: a reshape or transpose can force a relayout from one tiled layout to another, which is a real HBM copy. On TorchTPU, views are not free.

View inversion. To write through a view, TorchTPU runs decomposition backwards. A partial write becomes stablehlo.dynamic_update_slice, which produces a new buffer containing old and new values, and TorchTPU swaps that buffer into the storage's metadata. Writing through a broadcast view is ambiguous (many logical slots share one physical slot), so TorchTPU always fails it explicitly, where CUDA would leave it undefined.

Buffer donation. An out-of-place update briefly needs both the old and new buffers. When TorchTPU can prove the old buffer is dead, it annotates the program to donate it, and XLA reuses the memory. When it cannot prove that, it falls back to an out-of-place update of the whole base storage, even if you only wrote one row.

Flow diagram: an in-place op goes through view inversion into dynamic_update_slice, which ends in buffer donation when safe, or a full copy when it is not

The orange branch is the one to fear: its memory cost scales with the size of the base storage, not the size of your write.

Copy-on-write. Because values are immutable, tensor.clone() can be a reference until one side is mutated. CUDA pays for the clone up front. TorchTPU pays lazily, only if a write happens.

Put together, the memory model docs boil this down to rules that invert some CUDA habits:

CUDA habit TorchTPU reality
Views are free, copies cost Copies are often free (copy-on-write); views can force a relayout
Slice a big buffer and write into it Prefer many small tensors; partial writes may copy the whole storage
Strides are dynamic, any layout works Contiguous tensors avoid relayouts and keep donation possible
Writes through broadcasts are "undefined" They raise, always

One escape hatch exists for code that cannot avoid the expensive cases: a custom kernel specifies TPU buffer behavior manually. We get there in Part I.

Part C: The deferred pipeline and four execution modes

What happens when you call x @ w

When an op runs on the TorchTPU backend, no TPU work happens immediately. The execution model docs describe the stages:

  1. Create a DeferredOp. A CPU-side object records inputs, the StableHLO builder for the op, and output shapes and dtypes. The returned tensor's storage points (through the metadata layer) at that DeferredOp.
  2. Enqueue it on the current stream. For the calling Python thread, the op is now done.
  3. Analyze the stream. A background thread decides how many executables to cut, their inputs and outputs, optimization level, and whether to place work on a TensorCore or SparseCore.
  4. Compile or fetch. The graph is fingerprinted and looked up in the compilation cache. On a miss, it is lowered to MLIR (StableHLO, or Mosaic for custom kernels) and handed to a compile thread pool.
  5. Execute. The executable is enqueued on XLA's PjRt runtime, which returns futures that are plugged into the outputs.
  6. Wait, optionally. torch.accelerator.synchronize(), torch.Event.synchronize() or any device-to-host copy blocks Python until the TPU catches up.

Left-to-right pipeline: aten op, DeferredOp, Stream queue, StableHLO and Compile cache on the host CPU, crossing via PjRt to the TensorCore on the TPU

Five of the six boxes run on the host. The TPU only sees finished executables, which is why host-side overhead and host syncs show up as idle TPU time.

In the C++ engine this lives under csrc/eager/: DeviceBufferRef, DeviceBufferList and DeferredOp form the DAG, and traversal.cc plus materialization_heuristics.h decide where to cut it.

The four modes

The execution modes differ only in when stage 3 is allowed to start and how much it sees. This is the single most important table in the post:

Mode How you select it Graph size XLA level Best for
Strict Eager (default) nothing, or EagerMode.DEFER_NEVER one op -O1 fastest time to first result
Debug Eager TORCH_TPU_LAUNCH_BLOCKING=1 or EagerMode.DEFER_NEVER_AND_LAUNCH_BLOCKING one op, host waits for each -O1 pinpointing the op that failed
DeferAndFuse (optimized eager) TORCH_TPU_DEFER_AND_FUSE=1 or EagerMode.DEFER_AND_FUSE many ops, cut at syncs and detected loops -O2 faster steady state when torch.compile is not an option
Compiled torch.compile(model, backend="tpu") whole FX graph -O2 maximum warmed-up throughput

A few details are easy to get wrong, so here is what the source says.

Strict Eager is the default. GetDefaultEagerMode() in csrc/eager/eager_mode.cc returns kDeferNever unless TORCH_TPU_LAUNCH_BLOCKING or TORCH_TPU_DEFER_AND_FUSE is set (launch blocking wins if both are). Some community cheatsheets get this wrong (DeferAndFuse as the default, or STRICT and DEBUG enum members). The real public enum in src/torch_tpu/_internal/execution_mode/__init__.py has exactly DEFER_AND_FUSE, DEFER_NEVER and DEFER_NEVER_AND_LAUNCH_BLOCKING.

Strict Eager is still asynchronous. Ops run one at a time, but Python does not wait for them. A runtime error can surface many lines after the op that caused it, which is exactly what Debug Eager is for. Debug Eager also turns on TORCH_TPU_ENABLE_DEBUG_CHECKS by default, so it is slow on purpose. Never ship it.

DeferAndFuse materializes on a sync or a loop. Ops stay queued across Python calls until you force a device-to-host transfer or synchronize, or until the runtime detects a repeating op sequence and compiles one iteration for reuse. Tensors you already dropped get fused away or eliminated. Dead code elimination is skipped for distributed collectives to avoid cross-TPU deadlocks. The docs report up to 50% improvement over default eager with no model changes.

Animation comparing two eager modes: Strict Eager launches six ops as six small TPU executables with dispatch gaps; DeferAndFuse queues the same six ops as DeferredOps and launches one fused StableHLO program

In the top lane, notice the orange gaps between launches. In the bottom lane nothing reaches the TPU until the whole step can be compiled once and reused.

Those gaps are real. Enqueueing an executable with PjRt costs up to about 50 microseconds. If your ops are big, that overhead hides under the previous op's runtime. If they are tiny (small tensors in Strict Eager), the TPU outruns the host and stalls in what the docs call microbubbles. DeferAndFuse or torch.compile removes them by launching fewer, larger programs.

Compiled mode skips the eager machinery at call time. TorchTPU registers a Dynamo backend named "tpu". It traces the FX graph once with placeholder tensors, builds a single StableHLO program, compiles it at -O2, and returns a callable. Later calls create no DeferredOps and need no cache lookup: the executable goes straight to PjRt. TorchTPU does not use TorchInductor at all. backend="inductor" with TPU inputs raises a RuntimeError (see src/torch_tpu/_loader.py) unless you pass options={"tpu_backend": "pallas"}.

Switching modes in code

Env vars are read once, when the backend initializes during import torch, and then locked. Setting os.environ["TORCH_TPU_DEFER_AND_FUSE"] halfway through a script does nothing. The sample handles this by applying its CLI flags before importing torch:

# Top of code/sample_01_torchtpu_execution_xprof_and_pallas.py
if __name__ == "__main__":
  _preconfigure_env(sys.argv[1:])   # sets TORCH_TPU_* from --defer-and-fuse etc.
import torch                          # backend initializes here and locks them
Enter fullscreen mode Exit fullscreen mode

Inside a process, use the context manager instead. It nests and restores the previous mode on exit:

with torch.tpu.set_eager_mode(torch.tpu.EagerMode.DEFER_AND_FUSE):
  y = block(x)
print(torch.tpu.eager_mode)   # back to EagerMode.DEFER_NEVER
Enter fullscreen mode Exit fullscreen mode

set_eager_mode is forbidden inside a compiled region (a compiled graph cannot choose how to dispatch eager ops), so call it around compiled functions, not in them.

Two pitfalls that cost real copies

Views as compiled-function arguments. PjRt requires executable inputs to be contiguous, zero-offset and of a fixed dtype. Pass a non-trivial view (or a bitcast) into a compiled function and TorchTPU makes a temporary eager copy to call it. If you chain compiled functions, make each one return contiguous tensors so the next call does not pay that copy. This is the .contiguous() rule from FLUX Milestone 3.

Retained intermediates in DeferAndFuse. At each materialization point, every live tensor gets materialized. A debug tensor you kept around for logging becomes a forced output and blocks fusion. Delete intermediates early or overwrite them in place.

Measure it yourself

benchmark_execution_and_precision_modes() runs a float32 pre-norm transformer block through every mode and precision you ask for and reports first-call latency (dominated by compilation), steady-state step latency, and max error against a CPU float32 reference:

results = benchmark_execution_and_precision_modes(
    batch=8, seq_len=512, hidden=1024, num_heads=8,
    modes=("strict_eager", "defer_and_fuse", "debug_eager", "compiled"),
    precisions=("DEFAULT", "HIGH", "HIGHEST"))
Enter fullscreen mode Exit fullscreen mode

Timing follows the FLUX case study's method: warm up, dispatch the timed steps back to back, then call torch.accelerator.synchronize() once so device time is included. Before you run it, write down two predictions: which mode has the slowest first call, and which has the fastest steady state? The docs' answer is that Strict Eager wins time to first result (many tiny -O1 compiles in parallel, high reuse) and torch.compile wins steady state, with DeferAndFuse between them. I am not printing TPU numbers here because I would only be inventing them. Run it on your slice and keep the table for your own model.

Part D: The three compilation cache tiers

Every executable TorchTPU builds is keyed by a fingerprint of the StableHLO graph structure, the input and output shapes, and the compiler options, including the TPU hardware, libtpu and PjRt versions. Lookups cascade through three tiers before XLA is allowed to compile:

Cascade diagram: a graph fingerprint is checked in Tier 1 in-process memory, then Tier 2 /dev/shm, then Tier 3 disk or GCS, and only on a miss at every tier goes to XLA compile

Only the orange box costs seconds. The job of the cache configuration is to make sure each graph reaches it once per fleet, not once per process.

Tier Scope Default Configure with
1 in-process memory always on nothing
2 host-local shared memory, across processes on for distributed jobs, off for single-device TORCH_TPU_TIER2_COMPILATION_CACHE=<name> (a directory name, placed under /dev/shm/torch_tpu_cache/), or disabled
3 persistent, across hosts, programs and restarts off TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT=gs://bucket/path or a shared filesystem path

Tier 2 is what stops eight ranks on one host from compiling the same graph eight times. Tier 3 is what makes a preempted job restart in seconds instead of minutes, and it is the cheapest win in this post for anyone running on Colab, spot capacity or a CI fleet. With the sample:

python code/sample_01_torchtpu_execution_xprof_and_pallas.py \
  --section modes --tier2-cache=sample01 --tier3-cache=gs://my-bucket/tpu-cache
Enter fullscreen mode Exit fullscreen mode

Run it twice. The second run's first-call column should collapse because the executables come from Tier 3. Two caveats from the dynamic shapes docs: bounded-dynamic executables are not serialized to the persistent AOTAutogradCache yet, so they recompile in each new process, and any change to libtpu or compiler flags changes the fingerprint by design.

Part E: MXU precision

The MXU multiplies bfloat16 inputs (8 bits of significand) and accumulates in float32. The VPU, which runs elementwise ops, norms and softmax, works in full float32. So "float32 matmul" on a TPU is a choice about how many bf16 passes to spend, and TorchTPU maps PyTorch's knob onto torch.tpu.Precision:

torch.set_float32_matmul_precision torch.tpu.Precision MXU passes Significand bits multiplied
"medium" (TPU default) DEFAULT 1 8
"high" HIGH 3 16
"highest" HIGHEST 6 24

Two bar charts: Precision DEFAULT, HIGH and HIGHEST use 1, 3 and 6 bf16 MXU passes and multiply 8, 16 and 24 significand bits

Cost grows linearly with passes, accuracy grows by 8 significand bits per step. Only float32 inputs are affected. Bf16 models already run one pass.

Note the default differs from CUDA, where PyTorch's default is "highest". HIGH splits each float32 into high and low bf16 parts and computes three cross terms. HIGHEST splits into three parts and computes six (the other three underflow in float32 anyway). The docs add a useful nuance: on memory-bound models the extra passes fill otherwise idle MXU cycles, so the end-to-end slowdown is often well under 3x or 6x.

Scope precision to the layers that need it:

with torch.tpu.precision(torch.tpu.Precision.HIGHEST):
  logits = model.lm_head(hidden)        # numerically sensitive layer only
Enter fullscreen mode Exit fullscreen mode

Three rules from the source and docs:

  • torch.tpu.precision calls torch._dynamo.graph_break(). With fullgraph=True that is an error, so wrap the call to the compiled function, which is what the benchmark does.
  • Selecting HIGH or HIGHEST emits a one-time performance warning. Keep DEFAULT unless you see convergence problems.
  • torch.tpu.allow_excess_precision (default False) controls whether fused ops may keep float32 intermediates instead of rounding to bf16 between steps. It sets an XLA flag that is locked at the first compile, so set it at the top of the script or not at all.

For bf16 inputs, torch.bmm(a, b, out_dtype=torch.float32) hands you the float32 accumulator directly instead of rounding it back down. On v7x, the MXU also accepts fp8 inputs, which is where the 625 FLOP/B fp8 ridge in the table above comes from.

Parity you can trust

When you port a model, compare like with like: bf16 on TPU against bf16 on CPU, or float32 under Precision.HIGHEST against CPU float32. Comparing bf16 against float32 measures quantization, not hardware drift. The sample's cpu_vs_tpu_parity() packages that check. Parts 2 and 5 reuse it:

report = cpu_vs_tpu_parity(block, x, atol=1e-2, rtol=1e-2, check_grads=True)
print(report.passed, report.max_abs_diff, report.max_rel_diff)
Enter fullscreen mode Exit fullscreen mode

It deep-copies a module to each device so weights match, compares any pytree of outputs, and with check_grads=True also compares input and parameter gradients after a backward pass.

Part F: Host syncs and recompilations

The silent device-to-host read

This line looks harmless:

if y.sum() > 0:
  y = y * 0.5
Enter fullscreen mode Exit fullscreen mode

y.sum() > 0 is a device tensor. Python's if needs a host bool, so PyTorch synchronizes the stream, copies one byte back over PCIe, and only then continues. In Strict Eager this drains the whole pipeline. In DeferAndFuse and torch.compile it is worse: it also splits the graph, so the compiler can no longer fuse across that line. .item(), .cpu(), print(tensor) and ops with data-dependent output shapes such as torch.masked_select and torch.nonzero do the same thing.

Animation of host and TPU timelines: with an if on a device value the host blocks while the TPU drains, then the TPU idles while Python catches up; with torch.where both stay busy and the step ends earlier

Look for two orange blocks in the top half: the host waiting on the TPU, then the TPU waiting on the host. The timing is illustrative. The shape is what XProf shows.

The fix keeps the decision on the device:

def step_sync_free(x: torch.Tensor) -> torch.Tensor:
  y = x @ x.transpose(-1, -2)
  y = torch.where(y.sum() > 0, y * 0.5, y)
  return F.gelu(y)
Enter fullscreen mode Exit fullscreen mode

tests/test_sample_01.py checks that step_with_host_sync and step_sync_free agree on both branches. Both functions also appear in the profiling section below, under named scopes, so you can see the gap in a trace.

Every new shape is a new program

XLA compiles for static shapes. With torch.compile(..., dynamic=False), Dynamo guards on exact sizes, so a KV cache that grows by one token per step fails the guard on every step and recompiles every step. The dynamic shapes docs measured exactly that on TPU:

Line chart of decode step latency: dynamic=False stays near 38 to 50 ms every step because it recompiles, dynamic=None spikes on steps 2 and 3 then drops to about 0.4 ms

The green line compiles three times (static on step 1, a bounded bucket on step 2, once more for its own output layout on step 3), then reuses one executable. The orange line never stops paying.

TorchTPU's built-in answer is bounded dynamism. With the default dynamic=None (or torch._dynamo.mark_dynamic(t, dim, min=..., max=...)), TorchTPU splits the dimension's range into buckets aligned to bucket_size (default 128, the lane width), up to num_dynamic_buckets (default 1, maximum 8), compiles one executable per bucket upper bound, and pads at runtime. Its limits matter for this series: no custom kernels (Pallas jax_op included), no data-dependent shapes, dynamic=True is not supported, and you pay compute and HBM for the bucket's upper bound.

The model-side fix: a static cache

The alternative is to never change shape in the first place. StaticCacheAutoregressiveDecoder in the sample is the pattern Hugging Face's StaticCache uses, reduced to three rules:

# Preallocate once: (layers, batch, heads, max_cache_len, head_dim)
self.register_buffer("k_cache", torch.zeros(cache_shape, dtype=dtype), persistent=False)
# The write position is a 0-D device tensor, never a Python int.
self.register_buffer("cache_len", torch.zeros((), dtype=torch.long), persistent=False)

def _forward_with_cache(self, input_ids):
  b, t = input_ids.shape
  positions = self.cache_len + torch.arange(t, device=input_ids.device)
  mask = self.slot_ids[None, :] <= positions[:, None]          # hides unfilled slots
  ...
  self.k_cache[i].index_copy_(2, positions, k)                 # in-place write
  ...
  self.cache_len.add_(t)
Enter fullscreen mode Exit fullscreen mode

A 0-D tensor is not a Dynamo guard and reading it never leaves the device, so its value can change every step without a recompile. index_copy_ at a tensor position lowers to a dynamic_update_slice on a contiguous buffer, the case where donation works. The mask compares positions rather than slicing the cache to its live length, because slicing would change the shape. Every prefill with the same prompt length has identical shapes, and so does every decode.

Predict: 1 prefill plus 20 decode steps, compiled with dynamic=False. How many compilations for the static cache, and how many for the growing torch.cat cache?

Animation: a 24-slot static cache fills 8 prompt slots then one slot per decode step while compiles stays at 2; below it a torch.cat cache grows by one slot per step and its compile count climbs with every step

Watch the two counters: the green one stops at 2 after the first decode step, the orange one never stops.

count_decode_recompilations() answers with a counting Dynamo backend that wraps "tpu" on a TPU and "eager" elsewhere. Dynamo's guards behave the same either way, so here is the real output from a laptop:

static cache : 1 prefill + 20 decode steps -> 2 compilation(s)
growing cat  : 20 decode steps -> 20 compilation(s)
Enter fullscreen mode Exit fullscreen mode

The tests also check that cached decoding produces exactly the same greedy tokens and logits as recomputing the full sequence without a cache. Part 2 picks this decoder up and connects it to Transformers v5's StaticCache.

For ragged batches, the same alignment idea applies along the sequence axis: torch.tpu.ops.align_jagged_to_multiple(nt, multiple=128) pads a jagged NestedTensor to a multiple of 128 and strip_jagged_padding undoes it.

Part G: Profiling with torch.profiler and XProf

TorchTPU plugs into the standard torch.profiler context manager and adds a TPU activity plus a TpuProfilerConfig for XProf. Install the viewer first. TensorBoard still needs setuptools<81 because newer versions dropped pkg_resources:

pip install "setuptools<81"
pip install xprof tensorboard tensorboard-plugin-profile
Enter fullscreen mode Exit fullscreen mode

The fields of TpuProfilerConfig, straight from src/torch_tpu/_internal/profiler/profiler_config.py:

Field Default Meaning
host_tracer_level 2 0 off, 1 user TraceMe events, 2 adds XLA events, 3 adds low-level XLA events
device_tracer_level 1 0 off, 1 TPU hardware activity
python_tracer_level 0 1 traces Python calls (adds overhead)
run_dir None where .xplane.pb files go; if unset, the Kineto trace directory (the API reference also lists TORCH_TPU_PROFILER_OUTPUT_DIR as a fallback)
worker_rank None string suffix for per-rank file names in multi-host runs
experimental_options None extra keys, such as v7x performance counter sampling

run_xprof_trace() profiles the sync anti-pattern and its fix side by side:

from torch.tpu.profiler import TpuProfilerConfig

config = TpuProfilerConfig(host_tracer_level=2, device_tracer_level=1,
                           python_tracer_level=0, run_dir=log_dir)
with torch.profiler.profile(
    activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.TPU],
    experimental_config=config,
    on_trace_ready=torch.profiler.tensorboard_trace_handler(str(log_dir)),
) as prof:
  for _ in range(steps):
    with named_scope("with_host_sync"):
      step_with_host_sync(x)
    with named_scope("sync_free"):
      step_sync_free(x)
    torch.accelerator.synchronize()
    prof.step()
print(prof.key_averages().table(sort_by="self_device_time_total", row_limit=8))
Enter fullscreen mode Exit fullscreen mode

Then open the trace with xprof --logdir=<log_dir> --port=6006 (or tensorboard --logdir=... and the Profile tab). On GKE, write the trace dir to a Cloud Storage FUSE mount and point xprof --logdir=gs://... at it.

A note on named_scope: TorchTPU has a scope helper that tags the TPU ops themselves in eager, compiled and exported execution, but in 0.2.0 it lives at torch_tpu._internal.profiler.named_scope and is not part of the public torch.tpu namespace. The sample imports it defensively and always wraps it in torch.profiler.record_function, so the host-side range shows up even if the internal path moves.

On Ironwood you can go one level deeper. Passing enable_v7x_counters=True adds the TensorCore performance counter sampling from the profiling docs (tpu_enable_periodic_counter_sampling and tpu_tc_perf_counter_sampling_options at interval_us:1). It is the tool for seeing inside a Pallas kernel, and it only works on v7x and later.

What to look for, from the XProf guide:

Pattern in the trace Meaning Fix
Large gaps between TPU ops host-side bottleneck: Python, data loading, a sync remove .item() style reads, prefetch data, try DeferAndFuse
Many short TPU bursts too many graph breaks or recompiles find the break with TORCH_TRACE, use torch.compile
copy or relayout ops you did not write a view forced a layout change change the view, see FLUX Milestone 1
Low MXU utilization shapes not aligned to 128 pad dimensions to multiples of 128

The healthy profile is long, continuous TPU blocks with few host gaps and MXU utilization above 60%. Profile 100 to 1,000 representative steps, not a whole run: the profiler adds roughly 5 to 10% overhead per step.

Part H: Case study, the FLUX DoubleStreamBlock

Google's FLUX case study in the TorchTPU docs applies all of the above to one DoubleStreamBlock of the FLUX diffusion transformer: one TPU v6e chip, batch 2, hidden 1024, 8 heads of 128, total sequence length 32,768, bf16, timing forward + loss + backward + optimizer step.

Horizontal bar chart of FLUX DoubleStreamBlock training step times on TPU v6e: baseline 178.61 ms, best configuration with views, fused RoPE, SplashAttention and torch.compile 122.51 ms, 1.46x

No single change gets close to the green bar. The view and RoPE fixes look like noise alone, yet the biggest win only appears once all four milestones are stacked.

Configuration Mean step time Speedup
Baseline reference (eager) 178.61 ms 1.00x
Pallas SplashAttention only (eager) 149.81 ms 1.19x
Zero-copy views only (eager) 178.30 ms 1.00x
torch.compile only 159.33 ms 1.12x
Views + fused RoPE + SplashAttention (eager) 156.73 ms 1.14x
Views + torch.compile 159.08 ms 1.12x
Views + fused RoPE + torch.compile 153.60 ms 1.16x
Views + fused RoPE + SplashAttention + torch.compile 122.51 ms 1.46x

These are the numbers published in the TorchTPU 0.2.0 docs. The examples/FLUX_optimization/README.md in the repository reports a later run of the same matrix (176.05 ms to 119.35 ms, 1.48x). The conclusions are identical. The sample reproduces milestones 1 and 2 as two classes that share one state_dict, so you can check parity exactly: FluxDoubleStreamBlockReference and FluxDoubleStreamBlockOptimized.

Milestone 1: zero-copy QKV split

The reference unpacks the fused projection with einops.rearrange(qkv, "B L (K H D) -> K B L H D"), which is a reshape followed by a permute that moves the Q/K/V axis to the front. In the forward pass both versions return strided views. The difference is in backward: to route gradients through the K-first permute, autograd materializes a new buffer, and on TPU that is an HBM-to-HBM copy (tt_jit_copy__as_strided_inverse in the case study's XProf traces).

Before and after diagram: the reference path permutes the fused QKV tensor K-first and pays a backward copy; the optimized path uses view plus unbind and needs no copy

Both rows produce identical Q, K and V. Only the top row's gradient has to be rearranged back into the projection's layout.

 def split_qkv(self, qkv):
   b, l, _ = qkv.shape
-  return qkv.view(b, l, 3, self.num_heads, self.head_dim).permute(2, 0, 1, 3, 4).unbind(0)
+  return torch.unbind(qkv.view(b, l, 3, self.num_heads, self.head_dim), dim=2)
Enter fullscreen mode Exit fullscreen mode

Keeping the size-3 axis next to (H, D) makes Q, K and V slices of the projection buffer at offsets 0, H*D and 2*H*D, and their gradients land directly in the original layout. Alone, it moves the step from 178.61 ms to 178.30 ms, because the copy is a small slice of a 32K-token step. It is still free to take, and the benefit grows with the number of blocks.

Milestone 2: compact, fusible RoPE

The reference materializes a full 2x2 rotation matrix [[cos, -sin], [sin, cos]] per frequency pair and contracts against 6D reshaped queries and keys. The optimized version stores [cos, sin] and rotates with four multiply-adds:

def apply_rope(self, q, k, pe):
  cos, sin = pe[..., 0], pe[..., 1]
  b, s, h, d = q.shape
  q_ = q.float().view(b, s, h, d // 2, 2)
  q0, q1 = q_[..., 0], q_[..., 1]
  q_out = torch.stack([q0 * cos - q1 * sin, q0 * sin + q1 * cos], dim=-1).view(b, s, h, d)
  ...
Enter fullscreen mode Exit fullscreen mode

The multiplications and additions are the same, so the results match bit for bit. What changes is memory: check_flux_parity() prints the table size dropping from 163,840 B to 81,920 B at its test shape, and under torch.compile the elementwise rotation fuses into its neighbors. On top of views and compile, the case study measured 159.08 ms to 153.60 ms (3.4%).

Here is check_flux_parity() on a laptop, comparing outputs and every gradient (inputs and all parameters) of the two blocks:

forward max|diff| = 0.000e+00   backward max|diff| = 0.000e+00
RoPE table: 163,840 B (2x2 matrices) -> 81,920 B (cos, sin)
Enter fullscreen mode Exit fullscreen mode

Milestone 3: compile the whole block

Eager runs every op as its own program, so intermediate activations round-trip through HBM and the host keeps stalling on dispatch. torch.compile(block, backend="tpu", dynamic=False) lowers the whole block, forward and backward, into one XLA graph: 178.61 ms to 159.33 ms (1.12x). The gain is modest here because attention dominates at 32K tokens. The case study notes it is about 3x at sequence length 640, where the elementwise work dominates. Remember the contiguity rule from Part C when you compile several functions in a row.

Milestone 4: Pallas SplashAttention

At long sequence lengths, standard attention materializes an O(S^2) score matrix in HBM. SplashAttention is a Pallas kernel that computes attention in on-chip tiles. TorchTPU ships it as torch.tpu.ops.splash_sdpa, and FluxDoubleStreamBlockOptimized(..., use_splash_attention=True) swaps it in with the case study's 2048-token blocks:

torch.tpu.ops.splash_sdpa(q, k, v, is_causal=False, block_q=2048, block_kv=2048,
                          block_q_dkv=2048, block_kv_dkv=2048)
Enter fullscreen mode Exit fullscreen mode

Mind the default: splash_sdpa defaults to is_causal=True, which is wrong for FLUX's bidirectional joint attention. With views, fused RoPE and compile already in place, the kernel takes the step from 153.60 ms to 122.51 ms (1.25x). The case study is candid about tuning: with the default 512-token blocks the kernel was about 10% slower than standard SDPA under compilation, and float32 inputs were slower still. Benchmark a few block sizes in bf16 before you commit.

Part I: Your own Pallas kernel with jax_op and the verifier

Pick the right tool first

Approach Status (docs) Use it when
Built-in ops (torch.tpu.ops.*, SDPA) shipped an op already exists: splash_sdpa, ragged_dot, index-free max_pool2d
Tokamax production ready you need a standard LLM or MoE block (grouped matmul, paged attention, MLA, TopK)
Pallas via torch.tpu.pallas.jax_op production ready you need a bespoke fused kernel with explicit VMEM tiling
Helion experimental you want one kernel source for GPU and TPU and can live with preview status

Tokamax kernels are themselves Pallas kernels exposed through jax_op, so the mechanism below is the same one they use.

How jax_op works

You write the kernel in Pallas, which ships inside the jax package. torch.tpu.pallas.jax_op(name, fn) reads the jax.Array type annotations to infer a PyTorch op schema, traces your function once with abstract shape and dtype placeholders, exports it to MLIR, and registers a torch.library.custom_op with a fake kernel so Dynamo can trace through it. At runtime, in eager and under torch.compile, JAX does not run: the exported kernel executes directly on torch.Tensor TPU buffers.

Pipeline diagram: a Pallas kernel is wrapped by jax_op, traced once into Mosaic MLIR, registered as a torch custom op, and called from eager or compiled code, with verifier.verify checking the jax_op from below

The trace happens once per input signature. The verifier hangs off the jax_op, not the runtime path, so it costs nothing in production.

The kernel: fused residual RMSNorm + SwiGLU

The sample fuses a pattern every LLM has: add the residual, RMS-normalize, then compute silu(y @ Wg) * (y @ Wu). Unfused, the normalized activations y make a full trip to HBM and back. Fused, they never leave VMEM.

def kernel(x_ref, res_ref, w_ref, wg_ref, wu_ref, o_ref):
  h = x_ref[...].astype(jnp.float32) + res_ref[...].astype(jnp.float32)
  y = h * jax.lax.rsqrt(jnp.mean(h * h, axis=-1, keepdims=True) + eps)
  y = (y * w_ref[...].astype(jnp.float32)).astype(wg_ref.dtype)
  g = jnp.dot(y, wg_ref[...], preferred_element_type=jnp.float32)   # MXU, f32 accumulate
  u = jnp.dot(y, wu_ref[...], preferred_element_type=jnp.float32)
  o_ref[...] = (jax.nn.silu(g) * u).astype(o_ref.dtype)

def fused_rmsnorm_swiglu(x: jax.Array, residual: jax.Array, norm_weight: jax.Array,
                         w_gate: jax.Array, w_up: jax.Array) -> jax.Array:
  rows, hidden = x.shape
  inter = w_gate.shape[1]
  br = min(block_rows, rows)
  row_tile = pl.BlockSpec((br, hidden), lambda i: (i, 0))
  return pl.pallas_call(
      kernel,
      out_shape=jax.ShapeDtypeStruct((rows, inter), x.dtype),
      grid=(rows // br,),
      in_specs=[row_tile, row_tile,
                pl.BlockSpec((1, hidden), lambda i: (0, 0)),
                pl.BlockSpec((hidden, inter), lambda i: (0, 0)),
                pl.BlockSpec((hidden, inter), lambda i: (0, 0))],
      out_specs=pl.BlockSpec((br, inter), lambda i: (i, 0)),
      interpret=interpret,
  )(x, residual, norm_weight, w_gate, w_up)
Enter fullscreen mode Exit fullscreen mode

The grid walks the rows in block_rows tiles. Pallas double-buffers each BlockSpec, so while the kernel computes on tile i, the DMA engine is already fetching tile i + 1 from HBM. norm_weight is (1, hidden) rather than 1D so its block is a legal 2D tile.

Plan the tiles before you write the kernel

Two things break Pallas kernels before they ever run: misaligned block shapes and a VMEM footprint that does not fit. plan_pallas_tiles() checks both on any machine. For bf16, rows must be multiples of 16 (the packed sublane count) and both feature dims multiples of 128:

rows=1024 hidden=512 inter=1024 torch.bfloat16 block_rows=256: aligned=True, VMEM ~8.5 MiB (double-buffered)
Enter fullscreen mode Exit fullscreen mode

8.5 MiB is comfortable against 128 MiB of VMEM per TensorCore on v6e and 64 MiB per TensorCore on v7x. Note what dominates: the two full weight matrices, double-buffered. For a real 4096 by 14336 MLP you would tile the inter dimension too, which is exactly the kind of change the planner tells you to make before you debug a Mosaic error.

Register, verify, run

op = torch.tpu.pallas.jax_op("sprint01::fused_rmsnorm_swiglu",
                             build_pallas_fused_rmsnorm_swiglu(block_rows))
verifier = torch.tpu.pallas.verifier
report = verifier.verify(op, dev_args, mode=verifier.VerificationMode.STATIC)
print(report.summary())
report.raise_for_errors()

eager_out = op(*dev_args)
compiled = torch.compile(lambda *a: op(*a), backend="tpu", dynamic=False, fullgraph=True)
compiled_out = compiled(*dev_args)
Enter fullscreen mode Exit fullscreen mode

torch.tpu.pallas.verifier is experimental and runs on CPU. verify(target, args, kwargs=None, *, mode=..., options=None) detects what it was handed: a jax_op gets op-contract, TPU-lowering, model-checking, autograd-parity and CPU-interpret checks. A raw JAX function gets model-checking and interpret checks. Any other callable, such as an nn.Module, is traced to FX so its buffer donation and aliasing can be checked, and then every jax_op it calls is verified at the shapes it uses. Only Severity.ERROR findings fail a report.

The mode matters more than the docs make obvious. VerificationMode.FULL (the default) runs kernels in CPU interpret mode, and creating JAX's CPU devices initializes JAX's other backends too, including the TPU. In a process that already owns the TPU through TorchTPU, use STATIC, which never executes kernels and needs no JAX devices. Run FULL in its own process:

JAX_PLATFORMS=cpu python code/sample_01_torchtpu_execution_xprof_and_pallas.py --verify-pallas-full
Enter fullscreen mode Exit fullscreen mode

Read the phases a report actually covered from report.checked_phases rather than assuming a fixed list. The Phase enum in 0.2.0's public API defines no members, so any article that lists five named phases is describing something the release does not expose. verify is also forbidden inside a compiled region.

With jax installed and no TPU, register_and_verify_pallas_kernel() runs the same kernel body through the Pallas interpreter on CPU and checks it against the PyTorch reference fused_rmsnorm_swiglu_reference(). From my laptop:

Pallas interpret mode on CPU: grid=4, max|err| vs PyTorch reference 1.562e-02   (bf16)
Pallas interpret mode on CPU: grid=4, max|err| vs PyTorch reference 5.722e-06   (float32)
Enter fullscreen mode Exit fullscreen mode

The bf16 error is one bf16 rounding step at that output magnitude. The float32 error is accumulation order. That is the shape of a correct kernel.

Two limits to remember. This op has no backward. For training, register one with op.register_autograd(backward, setup_context=...) exactly as the SplashAttention example does, saving residuals in forward so the backward kernel does not recompute it. And custom kernels do not support bounded dynamic shapes, so keep their inputs static, which the static cache pattern above already does.

Decision table

If you see... Use... Because...
slow first iteration in a notebook or test Strict Eager (default) many tiny -O1 compiles in parallel, best time to first result
a crash reported far from its cause Debug Eager, TORCH_TPU_LAUNCH_BLOCKING=1 the host waits on every op, so the error lands on the right line
microbubbles and you cannot use torch.compile DeferAndFuse fuses op runs at -O2 without code changes, up to 50% faster
a stable training or inference step torch.compile(backend="tpu", dynamic=False) one -O2 program, no per-call eager overhead
recompiles on restart or on every rank Tier 3 cache (plus Tier 2 on multi-process hosts) the fingerprint is computed once per fleet
float32 convergence trouble in one layer scoped torch.tpu.precision(HIGHEST) 6 passes only where they are needed
per-token recompiles static cache with a 0-D length, or dynamic=None buckets shapes stop changing, or change within a compiled bucket
a copy op after a reshape or permute a different view (view + unbind) keeps the layout, removes the relayout
attention dominating at long sequence splash_sdpa with tuned blocks on-chip tiling avoids O(S^2) HBM traffic
an unfused chain that keeps hitting HBM a Pallas kernel via jax_op, Tokamax first explicit VMEM residency for intermediates

Try it yourself

  1. Find the bucket. Change count_decode_recompilations() to compile the growing-cat path with dynamic=None instead of dynamic=False, run it on a TPU, and explain the compile count you get using the bucket rules from Part F. Then call torch._dynamo.mark_dynamic(kv, 2, min=16, max=128) before the first step and predict how the count changes before you run it.
  2. Break the alignment on purpose. Call register_and_verify_pallas_kernel(hidden=500) and read the planner's message. Then try inter=14336 with block_rows=256 and see what the VMEM estimate says. Extend the kernel's grid to a second dimension that tiles inter, and keep the interpret-mode check passing.
  3. Profile the FLUX block. Wrap FluxDoubleStreamBlockReference and FluxDoubleStreamBlockOptimized in run_xprof_trace()-style named scopes with a backward pass, open both in XProf's Op Profile, and find the copy that Milestone 1 removes.

If you build something on top of this, post it with #TorchTPUSprint.

What's next

You now have the model Part 2 depends on: tiles, functional updates, the deferred pipeline, cache tiers, precision, and why shapes must hold still. Part 2 runs unmodified Hugging Face Transformers v5 and Diffusers on TorchTPU, takes StaticCacheAutoregressiveDecoder apart in depth against Transformers' own StaticCache, and plugs Tokamax MoE kernels in through the same jax_op bridge you just used.

Sources and further reading

Top comments (0)