Back to Blogs
#machinelearning#pytorch#python#tutorial

FlashAttention on TPUs (splash_sdpa), Custom Verified Pallas Kernels & XProf in TorchTPU (Part 4)

Eliminate O(S^2) attention HBM bottlenecks on Google TPUs with torch.tpu.ops.splash_sdpa (6.39x faster at 4K, 1.2 GiB vs OOM at 8K), author custom differentiable Pallas kernels verified with pallas.verifier.verify, control 6-pass MXU float32 precision, and capture XProf hardware traces.

Updated 8 min read
Cover for FlashAttention on TPUs (splash_sdpa), Custom Verified Pallas Kernels & XProf in TorchTPU (Part 4)

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

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:

  1. torch.tpu.ops.splash_sdpa (Splash Attention): Google's hardware-tuned Pallas Sparse Flash Attention kernel exposed as a native differentiable PyTorch operator (6.39x faster and 19.8x less HBM at S = 4,096 on our live TPU v5e-1 benchmark!).
  2. 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 on torch.Tensor buffers — backed by static contract, lowering, and autograd verification!
  3. Multi-Pass MXU float32 Precision, MoE ragged_dot, and XProf Hardware 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:

  1. Upgrade libtpu (pip install -U torch_tpu libtpu): Google Colab's base TPU VM image ships an older libtpu==0.0.50, whereas JAX 0.9+ Pallas TPU lowering requires libtpu >= 0.0.53 (0.0.54 on PyPI). Without -U libtpu, splash_sdpa fails with Pallas TPU requires a recent libtpu version (at least 0.0.53).
  2. Lock os.environ["JAX_PLATFORMS"] = "cpu" before importing jax: Because libtpu allows only one PJRT client per TPU chip, keeping JAX strictly on CPU lets torch_tpu own 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:

  1. Reading the 13th Mantissa Bit Directly via out_dtype=torch.float32: Multiplying (1 + 2^-6) * (1 + 2^-7) = 1 + 2^-6 + 2^-7 + 2^-13 places a 1 in the 13th mantissa bit. Standard torch.mm(a, b) on bfloat16 inputs rounds away bit 2^-13 upon bfloat16 output downcast (1.0234375000), whereas torch.mm(a, b, out_dtype=torch.float32) reads directly from the MXU's internal float32 accumulator and retains the exact 1.0235595703 value!
  2. torch.tpu.allow_excess_precision (Process-Locked XLA Fusion Flag): Controls XLA's --xla_allow_excess_precision compiler flag and locks permanently after the first XLA compilation in a process (subsequent mutation raises RuntimeError, verified in our isolated child probe).
  3. with torch.tpu.precision(mode): (float32 Multi-Pass Decomposition): Decomposes float32 matmuls into 1 pass (Precision.DEFAULT, 8-bit bf16 significand), 3 passes (Precision.HIGH, 16-bit significand), or 6 passes (Precision.HIGHEST, full 24-bit IEEE-754 float32 significand):

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

Splash Attention VMEM Tiling vs Materialized O(S^2) HBM Attention

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 to j in [i - W, i] (W + 1 tokens), so a 256-token window passes local_window_size = 255 -> fwd_noise_ratio = 1.09x | dQ_noise_ratio = 1.14x
  • 4. Packed Sequences (segment_ids of int32 [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!

  1. 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.verify immediately rejects it on CPU before touching TPU hardware:
   Buggy Kernel Verifier Passed? -> False
   Buggy Kernel Categories Caught -> ['FindingCategory.LOWERING_FAILURE']
Enter fullscreen mode Exit fullscreen mode
  1. Verified (128, 128)-Tiled Differentiable SwiGLU Kernel (0 Runtime 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
Enter fullscreen mode Exit fullscreen mode

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]) in 0.8s cold / sub-ms warm with rel_L2 = 1.665e-03 against per-expert matmuls — zero token-padding waste! (For autotuned MoE / MLA / PagedAttention kernels, also explore Tokamax and portable @helion.kernel DSL.)
  • Hardware Profiling (torch.profiler + TpuProfilerConfig): Always warm up compilation outside the profiler context, then capture hardware .xplane.pb timelines via TpuProfilerConfig(host_tracer_level=2, device_tracer_level=1, run_dir=prof_dir) (on TPU v5e-1, 8 compiled splash_sdpa training steps emitted a 583.1 KiB .xplane.pb hardware trace with Self 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

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!