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

Companion GitHub Repository: agemagician/torchtpu-zero-to-hero

What if your standard PyTorch code ran natively on Google Cloud TPUs — with zero JAX wrappers and zero xm.mark_step() boilerplate?

Here is what running a Hugging Face Large Language Model on a Google Cloud TPU looks like today with TorchTPU (torch_tpu):

import torch from transformers import AutoModelForCausalLM, AutoTokenizer, CompileConfig device = torch.device("tpu") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16).to(device) model.tie_weights() # Re-share input/output embeddings on TPU storage inputs = tokenizer("Why are systolic arrays fast for transformers?", return_tensors="pt").to(device) outputs = model.generate( **inputs, max_new_tokens=64, cache_implementation="static", compile_config=CompileConfig(backend="tpu", dynamic=False), ) 

No import jax. No torchax.enable_globally(). No deprecated torch_xla xm.mark_step() calls scattered through your loops. You create a torch.device("tpu"), move your standard nn.Module to the accelerator, and run PyTorch.

In my previous TorchAX + HuggingFace series, we saw how torchax bridged PyTorch models onto JAX via Python __torch_dispatch__ interception. TorchTPU (torch_tpu), co-developed by Google and Meta and announced on the PyTorch Blog, is the official C++ PrivateUse1 PyTorch backend for Google Cloud TPUs. It lowers standard ATen and TorchDynamo FX graphs directly to OpenXLA (StableHLO) and executes them on TPU hardware through PjRt and libtpu — with no JAX runtime dependency.

Welcome to TorchTPU: Zero to Hero, a 5-part hands-on engineering series where every single benchmark, training loop, Pallas kernel, and distributed recipe is verified end-to-end on Google Colab TPUs (TPU v5e-1, torch 2.14.1+cpu, torch_tpu 0.3.0, libtpu 0.0.54).

Series Roadmap

Part Focus Area Colab Notebooks
Part 1 (You are here) TPU Hardware Mental Model, Execution Modes & 36x Faster StaticCache Inference Full Tutorial · 5-Min Quickstart
Part 2 Pre-Training Causal Transformers from Scratch (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 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. The TPU Hardware & TorchTPU Compiler Mental Model

If you come from NVIDIA GPUs, a GPU is an army of independent scalar/warp threads (SIMT) backed by hardware L1/L2 caches that forgive dynamic control flow and tiny kernel launches. A Google Cloud TPU is built around a fundamentally different philosophy: compiler-scheduled 2D systolic arrays.

TorchTPU Software Stack & TPU TensorCore Architecture

Inside each TPU TensorCore:

  • Matrix Multiply Unit (MXU): A 128 x 128 (v5e) or 256 x 256 (v6e Trillium / v7x Ironwood) systolic array that multiplies bfloat16 tiles while accumulating partial sums in IEEE-754 float32.
  • Vector Processing Unit (VPU): Executes elementwise activations (SiLU, GELU, Softmax, RMSNorm) and reductions in float32 across (8, 128) vector lanes.
  • Vector Memory (VMEM): Software-managed on-chip SRAM scratchpad (16–64+ MiB per core) directly feeding the MXU and VPU. Unlike a GPU L2 cache, the XLA compiler explicitly schedules asynchronous DMA transfers between off-chip High Bandwidth Memory (HBM) and VMEM to overlap memory movement with math.

When you run torch.compile(fn, backend="tpu", dynamic=False), TorchDynamo captures your PyTorch FX graph, AOTAutograd traces forward and backward ATen ops, and TorchTPU lowers them into StableHLO. OpenXLA then fuses whole chains of matmuls, norms, and activations so intermediate tensors stay inside VMEM registers without round-tripping to HBM.

Where TorchTPU Fits vs. torch_xla and torchax

Dimension torch_xla (Legacy) torchax (JAX Bridge) TorchTPU (torch_tpu)
Integration Layer Lazy tensor graph + manual xm.mark_step() Python __torch_dispatch__ -> jax.Array Native C++ PrivateUse1 (torch.device("tpu"))
Runtime JAX Dependency No Yes (jax.jit, optax for training) No (JAX only optional at trace-time for Pallas)
Stateful loss.backward() + torch.optim Fragile / lazy barriers Requires functional PyTree extraction 100% Native PyTorch Autograd & Optimizers
Distributed Stack xmp.spawn / XLA collectives JAX Mesh / NamedSharding torchrun + tpu_dist + DTensor / SimpleFSDP

API Stability Note: In PyTorch 2.11+, generic accelerator APIs (torch.accelerator.is_available(), torch.accelerator.synchronize(), torch.accelerator.max_memory_allocated()) are Stable and replace legacy torch.tpu.is_available() / torch.tpu.synchronize() calls (which are internal dispatcher hooks and raise RuntimeError if called directly). Hardware-specific torch.tpu.* APIs (get_device_properties, set_eager_mode, splash_sdpa) are currently marked Experimental while the 0.3.x API surface matures.

2. Step 1: Colab TPU Setup & Pre-Import Compilation Caching

Google Colab pre-installs CUDA builds of torch, torchvision, and torchaudio, plus an older system libtpu. Because TorchTPU pairs with the lightweight CPU build of PyTorch (routing accelerator ops through C++ libtpu and PjRt), our setup cell follows three strict rules:

  1. Uninstall conflicting CUDA torchvision/torchaudio packages and install CPU torch alongside -U torch_tpu libtpu and transformers>=5.0,<6.0 (Transformers v5 natively supports CompileConfig(backend="tpu") with StaticCache).
  2. Set process-locked environment variables BEFORE import torch: TorchTPU reads cache and runtime flags once during C++ library initialization.
  3. Disable Tier-2 (/dev/shm RAM cache) on single-process Colab and enable Tier-3 (/tmp disk cache): Persists compiled XLA binaries across graph resets without consuming host RAM.
import os import subprocess import sys subprocess.run( [sys.executable, "-m", "pip", "uninstall", "-y", "-q", "torchvision", "torchaudio"], check=False, ) subprocess.check_call([ sys.executable, "-m", "pip", "install", "-q", "torch", "--index-url", "https://download.pytorch.org/whl/cpu", ]) subprocess.check_call([ sys.executable, "-m", "pip", "install", "-q", "-U", "torch_tpu", "libtpu", "transformers>=5.0,<6.0", "accelerate", "sentencepiece", ]) # Configure process-locked compilation caches BEFORE `import torch`! os.environ["TRANSFORMERS_NO_TORCHVISION"] = "1" os.makedirs("/tmp/tpu_tier3_cache", exist_ok=True) os.environ["TORCH_TPU_TIER2_COMPILATION_CACHE"] = "disabled" os.environ["TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT"] = "/tmp/tpu_tier3_cache" 

Now let's inspect our Colab TPU v5e-1 hardware via torch.accelerator and torch.tpu.get_device_properties():

import torch assert torch.accelerator.is_available(), "Select Runtime -> Change runtime type -> TPU!" device = torch.device("tpu") props = torch.tpu.get_device_properties() print(f"Active Accelerator : {torch.accelerator.current_accelerator()} (count={torch.accelerator.device_count()})") print(f"TPU Hardware : {props.name} (version={props.version})") print(f"HBM per Device : {props.hbm_bytes_per_device / (1024**3):.2f} GiB") print(f"BF16 Peak TFLOPs : {props.bf16_flops_per_device / 1e12:.1f} TFLOP/s") print(f"SparseCores/Device : {props.sparse_cores_per_device}") 

Measured Output (TPU v5e-1):

Active Accelerator : tpu (count=1) TPU Hardware : TPU v5e (version=TpuVersion.V5E) HBM per Device : 16.00 GiB BF16 Peak TFLOPs : 197.0 TFLOP/s SparseCores/Device : 0 

Pro Tip (model.tie_weights()): When moving Hugging Face Causal LMs (Qwen/Qwen3-0.6B by default, or google/gemma-3-1b-it with HF_TOKEN) to "tpu" via model.to(device), functionalized UntypedStorage movement can allocate separate HBM buffers for tied weights (embed_tokens and lm_head). Calling model.tie_weights() right after .to(device) immediately re-shares the underlying TPU storage buffer.

3. Benchmarking TorchTPU's Three Eager Modes vs. torch.compile

Every eager op dispatched to torch.device("tpu") creates a lightweight C++ DeferredOp. TorchTPU gives you three eager policies alongside whole-graph compilation:

  1. EagerMode.DEFER_NEVER_AND_LAUNCH_BLOCKING (TORCH_TPU_LAUNCH_BLOCKING=1): Blocks the host CPU after every single op so Python stacktraces point to the exact line of any shape or indexing bug.
  2. EagerMode.DEFER_NEVER (Default Strict Eager): Compiles (-O1) and dispatches each individual op asynchronously. Fast first-call startup for interactive REPL work.
  3. EagerMode.DEFER_AND_FUSE (TORCH_TPU_DEFER_AND_FUSE=1): Queues chains of ops into a pending DAG and fuses them (-O2) only when a value is materialized (e.g., .item(), .cpu(), or exiting with torch.tpu.set_eager_mode(...)).
  4. torch.compile(fn, backend="tpu", dynamic=False): Captures the entire forward/backward graph once via TorchDynamo and lowers it into one fused -O2 XLA binary.

Here is what we measured on a [8, 512, 1024] SwiGLU + RMSNorm Transformer block (bfloat16) on TPU v5e-1 (synchronizing once outside the 20-step steady-state loop so we measure true accelerator throughput rather than host-sync stalls):

Execution Mode First Call / Compile (ms) Steady State (ms/step) Peak HBM (MiB)
1. Eager Debug (LAUNCH_BLOCKING) 514.16 3.128 1309.5
2. Eager Strict (DEFER_NEVER) 1.48 0.840 1787.5
3. Eager Fused (DEFER_AND_FUSE, per-call context) 218.83 141.085 1632.5
4. Compiled (torch.compile(backend="tpu")) 2906.61 0.519 1386.9

Look at two critical takeaways in those numbers:

  • torch.compile(backend="tpu") is both 1.62x faster (0.519 ms vs. 0.840 ms) AND uses 400.6 MiB less HBM (1386.9 MiB vs. 1787.5 MiB) than strict eager mode, because intermediate [8, 512, 2816] SwiGLU gate/up activations are fused inside on-chip VMEM instead of being written out to HBM between ops.
  • Notice why entering and exiting with torch.tpu.set_eager_mode(DEFER_AND_FUSE): inside every step cost 141 ms: exiting the context flushes and re-hashes the deferred op queue on CPU! If you use DEFER_AND_FUSE, enable it once globally (TORCH_TPU_DEFER_AND_FUSE=1) around an entire uncompiled script — and prefer torch.compile(backend="tpu") for all inner loops.

4. MXU bfloat16 Noise-Floor Parity & The Contiguous Memory Rule

How to Test Numerical Parity on TPUs Without False Alarms

Because bfloat16 has 7 mantissa bits (vs. 23 in float32), comparing a TPU bfloat16 layer against a CPU float32 reference with 1e-5 tolerances will fail due to normal quantization rounding. Instead, compare both CPU bfloat16 and TPU bfloat16 relative L2 error against a CPU float32 ground truth:

CPU bfloat16 rel_L2 error (noise floor) : 2.8969e-03 TPU bfloat16 rel_L2 error : 3.3779e-03 TPU / CPU noise-floor ratio : 1.17x 

A ratio near 1.0x–1.2x proves the MXU is matching IEEE bfloat16 precision cleanly. (In Part 4, we will show how torch.tpu.Precision.HIGH and Precision.HIGHEST unlock 3-pass and 6-pass MXU float32 accuracy down to 1e-6!)

Strided Views vs. Contiguous Buffers & Buffer Donation

On CUDA, .transpose(1, 2) only changes 1D stride metadata. On TPUs, compiled PjRt executables require contiguous, zero-offset tiled buffers:

  • Passing a transposed non-contiguous view (base.transpose(1, 2)) into a @torch.compile(backend="tpu") function measured 0.184 ms/call vs. 0.121 ms/call (1.52x faster) when passing .contiguous() inputs, because non-contiguous boundary inputs force an eager relayout copy before every launch.
  • Conversely, updating a preallocated fixed-shape KV slot via kv_buf.index_copy_(2, cache_pos, new_kv) keeps tensor shapes static (1, 4, 128, 64) across steps, allowing XLA buffer donation to reuse the same HBM buffer in-place without doubling memory.

5. Bounded Dynamism vs. StaticCache — Getting a 36.25x Decoding Speedup

Why is default model.generate() slow when naively compiled on TPUs? Because DynamicCache appends one token per step (torch.cat([kv_cache, new_tok], dim=2)), growing sequence length 16 -> 17 -> 18 ....

Let's compare three ways to handle growing KV shapes on TPU v5e-1 across 8 decode steps:

dynamic=False (guard fails) | step ms: 80.92, 75.63, 75.90, 74.89, 77.00, 74.39, 75.88, 76.93 dynamic=None (3-step warmup) | step ms: 46.34, 174.12, 65.15, 0.91, 0.70, 0.67, 0.68, 0.66 mark_dynamic (2-step warmup) | step ms: 133.76, 62.59, 0.85, 0.66, 0.64, 0.92, 0.70, 0.67 
  • With dynamic=False on a growing tensor, TorchDynamo's shape guard fails every single token (~76 ms/step of XLA recompilation).
  • With Bounded Dynamism (dynamic=None or torch._dynamo.mark_dynamic(kv, 2, min=16, max=128)), TorchTPU compiles a 128-aligned upper-bound bucket once (in 3 warmup steps for dynamic=None, or 2 warmup steps for mark_dynamic) and runs Steps 4–8 in 0.66 ms/step (>110x faster)!

However, for LLM autoregressive generation, preallocating a fixed-size KV buffer via Hugging Face's cache_implementation="static" (dynamic=False) is even better: shapes never change at all, Tier-3 / AOTAutogradCache caching works out of the box, and custom Pallas kernels remain compatible.

Here is the end-to-end Qwen/Qwen3-0.6B generation benchmark on Google Colab TPU v5e-1:

Decoding Path (Qwen/Qwen3-0.6B, bfloat16) Generated Tokens Wall Time (s) Throughput (tok/s) Peak HBM (GiB)
Eager DynamicCache (baseline) 16 4.33 3.7 1.29
Compiled StaticCache (cold XLA compile) 64 21.45 3.0 1.35
Compiled StaticCache (warm steady state) 64 0.48 133.9 1.35
  • Warm repeat Dynamo recompilations: 0
  • Steady-state throughput speedup over Eager: 36.25x (133.9 tok/s vs. 3.7 tok/s) in just 1.35 GiB of TPU HBM!

6. Quick Troubleshooting Reference

Symptom Root Cause Fix
RuntimeError calling torch.tpu.is_available() or torch.tpu.synchronize() Marked Internal in PyTorch 2.11+ Use torch.accelerator.is_available() and torch.accelerator.synchronize()
C++ symbol mismatch importing transformers Pre-installed CUDA torchvision clashes with CPU torch Uninstall torchvision & torchaudio and set TRANSFORMERS_NO_TORCHVISION="1"
TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT has no effect Environment variable set after import torch Set all TORCH_TPU_*, XLA_FLAGS, and LIBTPU_INIT_ARGS before importing torch
Slow model.generate() on every token DynamicCache increments sequence length each token Pass cache_implementation="static" + CompileConfig(backend="tpu", dynamic=False)

Further Reading & Credits

Credits

Huge thanks to the TorchTPU engineering teams at Google and Meta, the OpenXLA & PjRt teams, and the Hugging Face Transformers team for making native PyTorch execution on Cloud TPUs a reality.

Up Next in Part 2: Ready to train? We pre-train a RoPE + RMSNorm + SwiGLU + GQA Transformer from scratch (slashing vocabulary logit HBM by 10.2x and doubling step speed with SingleTraceTrainer + AdamW & Muon) and fine-tune Qwen3-0.6B with native stateful PyTorch PEFT LoRA at 20,511 tokens/sec! Drop a comment below with which open-weights LLM you're excited to benchmark on TorchTPU!