{"slug": "run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-1", "title": "Run Any PyTorch LLM Natively on Google TPUs: A Zero-to-Hero Guide to TorchTPU (Part 1)", "summary": "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.", "body_md": "**Companion GitHub Repository:** [agemagician/torchtpu-zero-to-hero](https://github.com/agemagician/torchtpu-zero-to-hero)\n\n`xm.mark_step()` boilerplate?\nHere is what running a Hugging Face Large Language Model on a Google Cloud TPU looks like today with **TorchTPU** (`torch_tpu`):\n\n``` python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, CompileConfig\n\ndevice = torch.device(\"tpu\")\ntokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen3-0.6B\")\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen3-0.6B\", dtype=torch.bfloat16).to(device)\nmodel.tie_weights()  # Re-share input/output embeddings on TPU storage\n\ninputs = tokenizer(\"Why are systolic arrays fast for transformers?\", return_tensors=\"pt\").to(device)\noutputs = model.generate(\n    **inputs,\n    max_new_tokens=64,\n    cache_implementation=\"static\",\n    compile_config=CompileConfig(backend=\"tpu\", dynamic=False),\n)\n```\n\nNo `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.\n\nIn 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**.\n\nWelcome 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`).\n\n| Part | Focus Area | Colab Notebooks | \n|---|---|---|\n| **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) | \n| **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) | \n| **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) | \n| **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) | \n| **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) | \n\nIf 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**.\n\nInside each TPU TensorCore:\n\n`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.\n\n`torch_xla` and `torchax`\n| Dimension | `torch_xla` (Legacy) | `torchax` (JAX Bridge) | **`TorchTPU` (`torch_tpu`)** | \n|---|---|---|---|\n| **Integration Layer** | Lazy tensor graph + manual `xm.mark_step()` | Python `__torch_dispatch__` ->`jax.Array` | **Native C++ `PrivateUse1` (`torch.device(\"tpu\")`)** | \n| **Runtime JAX Dependency** | No | Yes ( `jax.jit` ,`optax` for training) | **No** (JAX only optional at trace-time for Pallas) | \n| **Stateful `loss.backward()` + `torch.optim`** | Fragile / lazy barriers | Requires functional PyTree extraction | **100% Native PyTorch Autograd & Optimizers** | \n| **Distributed Stack** | `xmp.spawn` / XLA collectives | JAX `Mesh` /`NamedSharding` | **`torchrun` + `tpu_dist` + `DTensor` / `SimpleFSDP`** | \n\n**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.\n\nGoogle 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:\n\n`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):\n\n``` python\nimport os\nimport subprocess\nimport sys\n\nsubprocess.run(\n    [sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", \"-q\", \"torchvision\", \"torchaudio\"],\n    check=False,\n)\nsubprocess.check_call([\n    sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n    \"torch\", \"--index-url\", \"https://download.pytorch.org/whl/cpu\",\n])\nsubprocess.check_call([\n    sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n    \"-U\", \"torch_tpu\", \"libtpu\", \"transformers>=5.0,<6.0\", \"accelerate\", \"sentencepiece\",\n])\n\n# Configure process-locked compilation caches BEFORE `import torch`!\nos.environ[\"TRANSFORMERS_NO_TORCHVISION\"] = \"1\"\nos.makedirs(\"/tmp/tpu_tier3_cache\", exist_ok=True)\nos.environ[\"TORCH_TPU_TIER2_COMPILATION_CACHE\"] = \"disabled\"\nos.environ[\"TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT\"] = \"/tmp/tpu_tier3_cache\"\n```\n\nNow let's inspect our Colab `TPU v5e-1` hardware via `torch.accelerator` and `torch.tpu.get_device_properties()`:\n\n``` php\nimport torch\n\nassert torch.accelerator.is_available(), \"Select Runtime -> Change runtime type -> TPU!\"\ndevice = torch.device(\"tpu\")\nprops = torch.tpu.get_device_properties()\n\nprint(f\"Active Accelerator : {torch.accelerator.current_accelerator()} (count={torch.accelerator.device_count()})\")\nprint(f\"TPU Hardware       : {props.name} (version={props.version})\")\nprint(f\"HBM per Device     : {props.hbm_bytes_per_device / (1024**3):.2f} GiB\")\nprint(f\"BF16 Peak TFLOPs   : {props.bf16_flops_per_device / 1e12:.1f} TFLOP/s\")\nprint(f\"SparseCores/Device : {props.sparse_cores_per_device}\")\n```\n\n**Measured Output (`TPU v5e-1`):**\n\n```\nActive Accelerator : tpu (count=1)\nTPU Hardware       : TPU v5e (version=TpuVersion.V5E)\nHBM per Device     : 16.00 GiB\nBF16 Peak TFLOPs   : 197.0 TFLOP/s\nSparseCores/Device : 0\n```\n\n**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.\n\n`torch.compile`\nEvery eager op dispatched to `torch.device(\"tpu\")` creates a lightweight C++ `DeferredOp`. TorchTPU gives you three eager policies alongside whole-graph compilation:\n\n`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)`:\nHere 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):\n\n| Execution Mode | First Call / Compile (ms) | Steady State (ms/step) | Peak HBM (MiB) | \n|---|---|---|---|\n| 1. Eager Debug ( `LAUNCH_BLOCKING` ) | `514.16` | `3.128` | `1309.5` | \n| 2. Eager Strict ( `DEFER_NEVER` ) | `1.48` | `0.840` | `1787.5` | \n| 3. Eager Fused ( `DEFER_AND_FUSE` , per-call context) | `218.83` | `141.085` | `1632.5` | \n| **4. Compiled (`torch.compile(backend=\"tpu\")`)** | `2906.61` | **`0.519`** | **` 1386.9`** | \n\nLook at two critical takeaways in those numbers:\n\n`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 (\nBecause `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:\n\n```\nCPU bfloat16 rel_L2 error (noise floor) : 2.8969e-03\nTPU bfloat16 rel_L2 error               : 3.3779e-03\nTPU / CPU noise-floor ratio             : 1.17x\n```\n\nA 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`!)\n\nOn CUDA, `.transpose(1, 2)` only changes 1D stride metadata. On TPUs, compiled `PjRt` executables require **contiguous, zero-offset tiled buffers**:\n\n`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\nWhy 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 ...`.\n\nLet's compare three ways to handle growing KV shapes on `TPU v5e-1` across 8 decode steps:\n\n```\ndynamic=False (guard fails)    | step ms:  80.92,  75.63,  75.90,  74.89,  77.00,  74.39,  75.88,  76.93\ndynamic=None  (3-step warmup)  | step ms:  46.34, 174.12,  65.15,   0.91,   0.70,   0.67,   0.68,   0.66\nmark_dynamic  (2-step warmup)  | step ms: 133.76,  62.59,   0.85,   0.66,   0.64,   0.92,   0.70,   0.67\n```\n\n`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)\nHowever, 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.\n\nHere is the end-to-end `Qwen/Qwen3-0.6B` generation benchmark on Google Colab `TPU v5e-1`:\n\n| Decoding Path ( `Qwen/Qwen3-0.6B` ,`bfloat16` ) | Generated Tokens | Wall Time (s) | Throughput (tok/s) | Peak HBM (GiB) | \n|---|---|---|---|---|\n| Eager `DynamicCache` (baseline) | `16` | `4.33` | `3.7` | `1.29` | \n| Compiled `StaticCache` (cold XLA compile) | `64` | `21.45` | `3.0` | `1.35` | \n| **Compiled `StaticCache` (warm steady state)** | **`64`** | **` 0.48`** | **` 133.9`** | **` 1.35`** | \n\n`0`` 133.9 tok/s` vs. `3.7 tok/s`)` 1.35 GiB`\n| Symptom | Root Cause | Fix | \n|---|---|---|\n| `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()` | \n| C++ symbol mismatch importing `transformers` | Pre-installed CUDA `torchvision` clashes with CPU`torch` | Uninstall `torchvision` &`torchaudio` and set`TRANSFORMERS_NO_TORCHVISION=\"1\"` | \n| `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` | \n| Slow `model.generate()` on every token | `DynamicCache` increments sequence length each token | Pass `cache_implementation=\"static\"` +`CompileConfig(backend=\"tpu\", dynamic=False)` | \n\n`CompileConfig` guide`agemagician/torchtpu-zero-to-hero`)\nHuge 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.\n\n**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!", "url": "https://wpnews.pro/news/run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-1", "canonical_source": "https://dev.to/gde/run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-part-1-3hj7", "published_at": "2026-12-04 13:39:33+00:00", "updated_at": "2026-12-04 13:44:23.383777+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-infrastructure", "ai-chips", "developer-tools"], "entities": ["Google", "Meta", "PyTorch", "TorchTPU", "OpenXLA", "Hugging Face", "Google Cloud TPU", "Qwen"], "also_reported_by": [], "takeaway": "TorchTPU's static cache implementation with compile_config=CompileConfig(backend=\"tpu\", dynamic=False) and cache_implementation=\"static\" delivered 36x faster inference than the baseline on TPU v5e-1.", "recommendation": {"advice": "On TPU, run Hugging Face LLMs through torch_tpu with a static cache and dynamic=False compilation to get the reported 36x inference speedup over the baseline.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-1", "markdown": "https://wpnews.pro/news/run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-1.md", "text": "https://wpnews.pro/news/run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-1.txt", "jsonld": "https://wpnews.pro/news/run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-1.jsonld"}}