Companion GitHub Repository: agemagician/torchtpu-zero-to-hero
12,115.8 MiB -> 610.5 MiB at 4K Context, and 1,221.0 MiB at 8K Where Standard Attention OOMs
At long context lengths (S >= 4,096), materializing the quadratic [B, H, S, S] attention score matrix in off-chip High Bandwidth Memory (HBM) hits a memory-bandwidth wall and crashes single-chip 16 GiB TPUs with RESOURCE_EXHAUSTED.
On NVIDIA GPUs, you reach for FlashAttention and Triton. On Google Cloud TPUs with TorchTPU, you reach for:
-
torch.tpu.ops.splash_sdpa(Splash Attention): Google's hardware-tuned Pallas Sparse Flash Attention kernel exposed as a native differentiable PyTorch operator (6.39xfaster and19.8xless HBM atS = 4,096on our liveTPU v5e-1benchmark!). -
torch.tpu.pallas.jax_op+pallas.verifier.verify: Write custom VMEM-tiled Pallas kernels that trace Mosaic MLIR once on CPU (JAX_PLATFORMS="cpu") and execute at zero runtime JAX cost directly ontorch.Tensorbuffers — backed by static contract, lowering, and autograd verification! - Multi-Pass MXU
float32Precision, MoEragged_dot, andXProfHardware Profiling.
Series Roadmap
| Part | Focus Area | Colab Notebooks |
|---|---|---|
| Part 1 | TPU Hardware Mental Model, Execution Modes & 36x Faster StaticCache Inference |
Full Tutorial · 5-Min Quickstart |
| Part 2 | Pre-Training Causal Transformers (SingleTraceTrainer, AdamW & Muon) & Native PEFT LoRA SFT |
Full Tutorial · 5-Min Quickstart |
| Part 3 | Post-Training Alignment (Compiled DPO), Live Online GRPO RL & Disaggregated Pod RL (VeRL) |
Full Tutorial · 5-Min Quickstart |
| Part 4 (You are here) | FlashAttention on TPUs (splash_sdpa), Verified Custom Pallas Kernels, MXU Precision & XProf |
Full Tutorial · 5-Min Quickstart |
| Part 5 | Cloud TPU Slices & Pods: tpu_dist, SimpleFSDP + DTensor TP, Pallas RDMA & vllm-torchtpu
|
Full Tutorial · 5-Min Quickstart |
1. Two Mandatory Setup Rules for Pallas on TorchTPU (libtpu >= 0.0.54 & JAX_PLATFORMS="cpu")
Before importing jax or torch, lock two critical environment details:
-
Upgrade
libtpu(pip install -U torch_tpu libtpu): Google Colab's base TPU VM image ships an olderlibtpu==0.0.50, whereas JAX 0.9+ Pallas TPU lowering requireslibtpu >= 0.0.53(0.0.54on PyPI). Without-U libtpu,splash_sdpafails withPallas TPU requires a recent libtpu version (at least 0.0.53). -
Lock
os.environ["JAX_PLATFORMS"] = "cpu"before importingjax: Becauselibtpuallows only one PJRT client per TPU chip, keeping JAX strictly on CPU letstorch_tpuown the TPU exclusively while JAX is invoked only at compile/trace time on zero-memory abstract shape placeholders to emit Mosaic MLIR!
2. MXU float32 Accumulator Retention & 1/3/6-Pass torch.tpu.precision
Three distinct controls govern floating-point precision on the TPU's systolic MXU:
-
Reading the 13th Mantissa Bit Directly via
out_dtype=torch.float32: Multiplying(1 + 2^-6) * (1 + 2^-7) = 1 + 2^-6 + 2^-7 + 2^-13places a1in the 13th mantissa bit. Standardtorch.mm(a, b)onbfloat16inputs rounds away bit2^-13uponbfloat16output downcast (1.0234375000), whereastorch.mm(a, b, out_dtype=torch.float32)reads directly from the MXU's internalfloat32accumulator and retains the exact1.0235595703value! -
torch.tpu.allow_excess_precision(Process-Locked XLA Fusion Flag): Controls XLA's--xla_allow_excess_precisioncompiler flag and locks permanently after the first XLA compilation in a process (subsequent mutation raisesRuntimeError, verified in our isolated child probe). -
with torch.tpu.precision(mode):(float32Multi-Pass Decomposition): Decomposesfloat32matmuls into 1 pass (Precision.DEFAULT, 8-bitbf16significand), 3 passes (Precision.HIGH, 16-bit significand), or 6 passes (Precision.HIGHEST, full 24-bit IEEE-754float32significand):
Measured on TPU v5e-1 ((8, 2048, 2048) float32 matmul vs. float64 reference):
torch.tpu.Precision Mode |
MXU Passes | Latency (ms) | Max Abs Error | Mean Relative Error |
|---|---|---|---|---|
Precision.DEFAULT |
1 pass | 1.569 ms |
6.110e-01 |
2.998e-02 |
Precision.HIGH |
3 passes | 2.452 ms |
3.540e-03 |
1.282e-04 |
Precision.HIGHEST |
6 passes | 4.702 ms |
1.221e-04 |
1.442e-06 |
3. FlashAttention on TPUs: torch.tpu.ops.splash_sdpa
torch.tpu.ops.splash_sdpa tiles Q, K, and V into 128-aligned blocks streamed via async DMA into on-chip VMEM, computing online softmax rescaling (m_i, l_i) in VPU registers without ever writing [B, H, S, S] attention scores to HBM — and skipping masked-out causal, sliding-window, or cross-document tiles entirely!
Four Attention Contracts Verified Forward + Backward (S = 512, D = 128, bfloat16)
-
1. Causal MHA (
16Q / 16KV):fwd_noise_ratio = 1.09x|dQ_noise_ratio = 1.14x|dK_rel = 4.860e-03|dV_rel = 3.774e-03 -
2. Grouped-Query Attention (
16Q / 4KV,enable_gqa=True):fwd_noise_ratio = 1.09x|dQ_noise_ratio = 1.14x|dK_rel = 4.898e-03|dV_rel = 3.744e-03 -
3. Sliding-Window Attention (
local_window_size = 255): Note the off-by-one contract!LocalMask(window_size=(W, 0))attends toj in [i - W, i](W + 1tokens), so a 256-token window passeslocal_window_size = 255->fwd_noise_ratio = 1.09x|dQ_noise_ratio = 1.14x -
4. Packed Sequences (
segment_idsofint32[B, S]):fwd_noise_ratio = 1.09x|dQ_noise_ratio = 1.12x
Sequence-Length Scaling Benchmark on TPU v5e-1 (B=2, H=16, D=128, Forward + Backward)
Seq Len (S) |
Materialized O(S²) SDPA (ms) |
O(S²) Peak HBM (MiB) |
splash_sdpa (ms) |
splash_sdpa HBM (MiB) |
Speedup |
|---|---|---|---|---|---|
1024 |
3.25 |
1448.0 |
0.79 |
96.5 |
4.12x (15.0x less HBM) |
2048 |
12.92 |
5864.0 |
2.30 |
305.3 |
5.63x (19.2x less HBM) |
4096 |
49.56 |
12115.8 |
7.76 |
610.5 |
6.39x (19.8x less HBM) |
8192 |
OOM (>16 GiB) |
OOM |
31.27 |
1221.0 |
inf (runs in 1.2 GiB!) |
4. Writing Custom Differentiable Pallas Kernels + Auditing with pallas.verifier.verify
When you design a novel fused operator, torch.tpu.pallas.jax_op bridges a pl.pallas_call function (annotated with jax.Array parameter/return types) into a native torch.library operator compatible with register_autograd and torch.compile(backend="tpu").
Even better, torch.tpu.pallas.verifier.verify audits your custom operator statically across Phase.CONTRACTS, Phase.LOWERING, Phase.FX_GRAPH, and Phase.AUTOGRAD!
-
Catching a Classic Triton-to-Pallas Tile Alignment Bug: When we deliberately pass a Triton-style
(64, 64)BlockSpec(violating TPU Mosaic's requirement that the last two block dimensions be divisible by(8, 128)),pallas.verifier.verifyimmediately rejects it on CPU before touching TPU hardware:
Buggy Kernel Verifier Passed? -> False
Buggy Kernel Categories Caught -> ['FindingCategory.LOWERING_FAILURE']
-
Verified
(128, 128)-Tiled Differentiable SwiGLU Kernel (0Runtime JAX Calls!):
Fixed SwiGLU Verifier Passed? -> True
Checked Verification Phases -> ['Phase.CONTRACTS', 'Phase.LOWERING', 'Phase.AUTOGRAD']
JAX traces after warmup: {'fwd': 33, 'bwd': 2} -> after 10 TPU runs: {'fwd': 33, 'bwd': 2} (0 runtime JAX calls!)
Compiled Pallas SwiGLU Parity -> fwd rel_L2=1.659e-03 | dGate=1.655e-03 | dUp=1.652e-03
5. MoE ragged_dot + Capturing Hardware .xplane.pb Timelines with XProf
-
Grouped Mixture-of-Experts Matmuls (
torch.tpu.ops.ragged_dot): Computes[512, 256]routed tokens across[4, 256, 256]expert weight matrices (group_sizes = [128, 128, 128, 128]) in0.8scold / sub-ms warm withrel_L2 = 1.665e-03against per-expert matmuls — zero token-padding waste! (For autotuned MoE / MLA / PagedAttention kernels, also explore Tokamax and portable@helion.kernelDSL.) -
Hardware Profiling (
torch.profiler+TpuProfilerConfig): Always warm up compilation outside the profiler context, then capture hardware.xplane.pbtimelines viaTpuProfilerConfig(host_tracer_level=2, device_tracer_level=1, run_dir=prof_dir)(onTPU v5e-1, 8 compiledsplash_sdpatraining steps emitted a583.1 KiB.xplane.pbhardware trace withSelf TPU time total: 6.200 ms, ready for%tensorboard --logdir /tmp/profiler_output).
6. Quick Troubleshooting Reference
| Symptom | Root Cause | Fix |
|---|---|---|
RuntimeError: Pallas TPU requires a recent libtpu version (>= 0.0.53). Found: cpu |
Colab pre-installs libtpu==0.0.50
|
Upgrade explicitly via pip install -U torch_tpu libtpu before importing torch
|
FindingCategory.LOWERING_FAILURE on custom Pallas BlockSpec
|
Last 2 tile dims not divisible by (8, 128)
|
Use (128, 128) (or (8*k, 128*m)) VMEM block shapes |
ValueError: seq_len must be a positive multiple of 128 in splash_sdpa
|
Unaligned sequence length or dynamic=True
|
Pad Q/K/V sequence dims to multiples of 128 and compile with dynamic=False
|
Off-by-one causal window in splash_sdpa(local_window_size=W)
|
Attends to [i - W, i] (W + 1 tokens) |
Pass local_window_size = window_tokens - 1 (e.g., 255 for a 256-token window) |
Further Reading & Credits
- Part 1: TPU Hardware Mental Model & 36x Faster Inference
- Part 2: Pre-Training Transformers & LoRA SFT on TorchTPU
- Part 3: Post-Training DPO & Live Online GRPO RL on TorchTPU
- JAX Pallas TPU Documentation
- OpenXLA Tokamax Kernel Library & XProf Profiler
- Companion Repository (
agemagician/torchtpu-zero-to-hero)
Credits
Thanks to the Pallas & Mosaic compiler teams at Google, the TorchTPU kernel & verifier authors, and the OpenXLA XProf team.
Up Next in Part 5 (Series Finale): Ready to scale from 1 TPU chip to 64+ chip Cloud TPU Slices & Multi-Slice Pods? We wire up tpu_dist, topology_aware_mesh, @spmd_safe, SimpleFSDP + DTensor Tensor Parallelism (0 graph breaks!), inter-chip Pallas RDMA (pltpu.make_async_remote_copy), GKE JobSet YAML recipes, and vllm-torchtpu serving!

