Run Any PyTorch LLM Natively on Google TPUs: A Zero-to-Hero Guide to TorchTPU (Part 1) A developer published a five-part hands-on guide to TorchTPU (torch_tpu), the official C++ PrivateUse1 PyTorch backend for Google Cloud TPUs co-developed by Google and Meta. The backend lowers standard ATen and TorchDynamo FX graphs to OpenXLA StableHLO and runs them on TPU hardware via PjRt and libtpu without a JAX runtime dependency, letting standard Hugging Face models run with a plain torch.device("tpu"). Part 1 covers the TPU hardware mental model, execution modes, and a reported 36x faster StaticCache inference, with all benchmarks verified on Colab TPU v5e-1 using torch_tpu 0.3.0. Companion GitHub Repository: agemagician/torchtpu-zero-to-hero https://github.com/agemagician/torchtpu-zero-to-hero 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 : python 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 https://dev.to/gde/run-any-huggingface-model-on-tpus-a-beginners-guide-to-torchax-4ln0 , 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 https://pytorch.org/blog/introducing-torchtpu/ , 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 . | Part | Focus Area | Colab Notebooks | |---|---|---| | Part 1 You are here | TPU Hardware Mental Model, Execution Modes & 36x Faster StaticCache Inference | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part01 foundations inference tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part01 foundations inference quickstart.ipynb | | Part 2 | Pre-Training Causal Transformers from Scratch SingleTraceTrainer , AdamW & Muon & Native PEFT LoRA SFT | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part02 pretrain sft tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part02 pretrain sft quickstart.ipynb | | Part 3 | Post-Training Alignment Compiled DPO , Live Online GRPO RL & Disaggregated Pod RL VeRL | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part03 alignment rl grpo tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part03 alignment rl grpo quickstart.ipynb | | Part 4 | FlashAttention on TPUs splash sdpa , Verified Custom Pallas Kernels, MXU Precision & XProf | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part04 splash kernels xprof tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part04 splash kernels xprof quickstart.ipynb | | Part 5 | Cloud TPU Slices & Pods: tpu dist , SimpleFSDP + DTensor TP, Pallas RDMA & vllm-torchtpu | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part05 pods distributed serving tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part05 pods distributed serving quickstart.ipynb | 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 . Inside each TPU TensorCore: 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 . SiLU , GELU , Softmax , RMSNorm and reductions in 8, 128 vector lanes. 16–64+ MiB per core directly feeding the MXU and VPU. Unlike a GPU L2 cache, the 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. 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. 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: 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 . import torch : /dev/shm RAM cache on single-process Colab and enable Tier-3 /tmp disk cache : python 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 : php 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. 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: EagerMode.DEFER NEVER AND LAUNCH BLOCKING TORCH TPU LAUNCH BLOCKING=1 : EagerMode.DEFER NEVER Default Strict Eager : -O1 and dispatches each individual op asynchronously. Fast first-call startup for interactive REPL work. EagerMode.DEFER AND FUSE TORCH TPU DEFER AND FUSE=1 : -O2 only when a value is materialized e.g., .item , .cpu , or exiting with torch.tpu.set eager mode ... . torch.compile fn, backend="tpu", dynamic=False : 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 8, 512, 2816 SwiGLU gate/up activations are fused inside on-chip VMEM instead of being written out to HBM between ops. with torch.tpu.set eager mode DEFER AND FUSE : 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 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 On CUDA, .transpose 1, 2 only changes 1D stride metadata. On TPUs, compiled PjRt executables require contiguous, zero-offset tiled buffers : base.transpose 1, 2 into a @torch.compile backend="tpu" function measured 0.184 ms/call 0.121 ms/call 1.52x faster when passing .contiguous inputs, because non-contiguous boundary inputs force an eager relayout copy before every launch. kv buf.index copy 2, cache pos, new kv keeps tensor shapes static 1, 4, 128, 64 across steps, allowing XLA 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 dynamic=False on a growing tensor, TorchDynamo's shape guard fails ~76 ms/step of XLA recompilation . 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 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 | 0 133.9 tok/s vs. 3.7 tok/s 1.35 GiB | 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 | CompileConfig guide agemagician/torchtpu-zero-to-hero 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