DEV Community

Cover image for The TorchTPU Book: A Free Guide to PyTorch on Cloud TPU, With Numbers You Can Check
Omotayo Aina for Google Developer Experts

Posted on Edited on

The TorchTPU Book: A Free Guide to PyTorch on Cloud TPU, With Numbers You Can Check

The TorchTPU Book is a free online book for PyTorch engineers who move real models from CUDA to Cloud TPU and need to know when the numbers they get are correct and real.

TorchTPU is an open-source, native PyTorch backend for Google Cloud TPUs, built by Google together with the PyTorch team at Meta.

The problem: it runs, and that is all you know

You change torch.device("cuda") to torch.device("tpu") and backend="nccl" to backend="tpu_dist". The model runs. The TorchTPU authors are explicit about what that does not give you: peak TPU performance, because your shapes, sharding and operators may be tuned for a GPU.

Three tiers. Top: a dashed container labelled PyTorch ecosystem holding Hugging Face, TorchTitan, Ray, vLLM-TorchTPU, SGLang-TorchTPU and llm-d. Middle: PyTorch dispatcher and ProcessGroup API both point into TorchTPU. Bottom: TorchTPU points to StableHLO, then XLA compiler, then Cloud TPU.

Notice the two arrows into TorchTPU, one for each string you changed: operations on the "tpu" device reach it through the dispatcher, and "tpu_dist" collectives through the ProcessGroup API. It sits behind PyTorch rather than replacing it, which is why the frameworks on top run without being rewritten.

The book's Part I overview lists what readers who skip the foundations tend to meet later: a model that is slower than expected, a loss curve that drifts from the GPU baseline, a serving step that recompiles on every request. And when TorchTPU's announcement post quotes 38% MFU (model FLOPs utilization), you cannot yet say what your own run should get.

The upstream documentation for TorchTPU is spread across several repositories, blog posts and talks, each written for a slightly different reader. This book covers the whole path in one order, from a first tensor on a TPU to a model that trains or serves at scale, with numbers someone else can check.

Three samples from the book

1. One example, three MFUs (chapters 16 and 24)

Muse Glimmer 30B is a 52-layer decoder from TorchTPU's case studies. TorchTPU ships a pure-PyTorch training loop for it on one host with four Ironwood (v7x) chips; Google reports 2,400 to 2,800 tokens per second per rank and 38% MFU.

MFU is the model's FLOP/s over the hardware's peak FLOP/s. Like the announcement post, chapter 16 counts the model's work as 6N: 6 FLOPs per matmul parameter per token. N is 26.51 billion, not 27.85 billion, because the embedding table is a lookup and does no matmul. A v7x chip appears to PyTorch as two devices, one rank each, so the peak per rank is half the chip's: 1,153.5 TFLOP/s. Chapter 16 estimates the run from its shapes before reading any measurement, then reproduces the published figure:

MFU = 2,800 x 6 x 26.51e9 / 1,153.5e12 = 38.6%
Enter fullscreen mode Exit fullscreen mode

That is the top of the reported range. The example README's own log takes 51.387 s for step 0, while torch.compile compiles, then about 17.1 s a step: 2,395 tokens per second per rank over steps 1 to 4, or 33.0% MFU. A stopwatch over all five steps reports 1,709 tokens per second, 29% low: 23.6% MFU.

Two panels titled "A stopwatch that includes compiling steps reports a different workload". Left, training, Muse Glimmer 30B on 4 v7x chips: per-step rates of 797 then about 2,400 tokens per second per rank, a green steady-state line at 2,395, and an orange stopwatch line rising from 797 to only 1,709 after 5 steps, labelled minus 29%. Right, decode on one v7x chip at batch 1, log scale: a green steady-state line at 42.4 tokens per second (23.58 ms), with stopwatch lines reaching only 0.99 and 0.49 tokens per second after 20 tokens.

Compare the orange lines with the green ones. In decode (right), two compiles of about 21 s and 20 s precede steady 23.6 ms tokens, and 20 tokens are not nearly enough to dilute them: the stopwatch is wrong by a factor of 87.

Chapter 24's verdict on the 38% claim: "the claim is honest about the best case of a range. Plan on about 33% for this code until you measure your own, and report your version."

2. A new shape is a new compile (chapter 7)

On TorchTPU a new tensor shape is a new compile. In the documentation's decode loop, whose KV cache grows by torch.cat, every step under dynamic=False takes 37.75 to 49.54 ms; the same step takes about 0.4 ms when it is not compiling. TorchTPU defaults torch.compile to dynamic=False when you do not pass dynamic, and dynamic=True raises NotImplementedError.

Chapter 7 gives three ways out (bounded dynamism with dynamic=None, a static KV cache, padding to buckets) and counts the compiles. Real output from its companion script on a laptop:

$ python code/ch07_dynamic_shapes/bucketing.py --cpu-smoke   (excerpt)
== 3. Dynamo compilations on the CPU (counting backend wrapping 'eager')
   growing cat, dynamic=False, 10 steps        -> 10 compiles (torch._dynamo counters unique_graphs: 10)
   growing cat, dynamic=None, 10 steps         -> 2 compiles
   growing cat, mark_dynamic(min=16, max=128)  -> 1 compile(s)
   static cache, 1 prefill + 20 decode steps   -> 2 compiles
   10 requests at their own lengths            -> 10 compiles
   10 requests padded to [128, 256, 512, 1024] -> 4 compiles (4 buckets used)
Enter fullscreen mode Exit fullscreen mode

These are Dynamo's counts on a CPU; on a TPU, dynamic=None compiles a third time, for the padded layout. For serving and variable-length training, the chapter shows how to choose buckets from your own length histogram, trading compile count against padding waste.

3. A 10% bug that a cross-dtype end-to-end check misses (chapter 23)

The companion bisect_demo.py injects a fault into a 12-block residual MLP: block 7's fc1 weight multiplied by 1.10. A bf16 candidate is compared with a float32 reference by peak-relative error (the largest absolute difference divided by the reference tensor's own peak magnitude) against a 5% bound. Block 7's output reads 3.89% and the model's head 3.70%, both under the bound, because the residual connection adds the faulty branch to a much larger stream. Only per-module rows catch it:

$ python code/ch23_correctness/bisect_demo.py --cpu-smoke   (excerpt)
4. Module rows of block 7 (bf16 vs fp32, first breach in execution order)
   blocks.7.norm    clean   1.31%   bug   1.31%
   blocks.7.fc1     clean   0.74%   bug  10.23%   <- breach
   blocks.7.act     clean   0.82%   bug  11.11%   <- breach
   blocks.7.fc2     clean   0.84%   bug  13.72%   <- breach
   blocks.7         clean   0.93%   bug   3.89%
   first_divergent_layer over 63 module rows: clean None, bug 37 (blocks.7.fc1)
Enter fullscreen mode Exit fullscreen mode

The chapter builds the rules from it: choose the level of agreement before you check, derive tolerances from the dtype and the operation, and put a negative control in every gate, because a gate that cannot fail proves nothing.

Who it is for

The book assumes modules, autograd, torch.compile at the user level, torch.distributed basics (DDP or FSDP), and a working picture of a Transformer. It does not assume TPU hardware, XLA, StableHLO, or any of the TorchTPU projects, from torch_tpu to llm-d.

If you already know JAX or PyTorch/XLA, chapter 0 tells you what to skim and what to read first.

What the book is

  • 26 chapters in seven Parts, plus chapter 0 and an appendix, about 16 hours end to end, not counting the worked problems or the code.
  • A dependency order: every chapter names its prerequisites at the top, and none uses a concept introduced later.
  • A way to check every chapter's result: a parity test against a baseline, an expected compile count, an MFU you compute by hand, an SLO you measure.
  • A source for every technical claim, and the concepts in Parts I, IV and V follow Google DeepMind's How to Scale Your Model, translated from JAX to PyTorch and TorchTPU.

Besides the book, the site has Guides (task pages with exact commands), Reference (API matrix, environment variables, a CUDA translation table, a 90-term glossary), Cheatsheets and Code. The prose and images are CC BY 4.0 and the code is Apache 2.0.

Seven cards in two rows joined by arrows, each with a Part name and its topics. First row: Foundations (TPU hardware, rooflines, execution, memory, precision, shapes), Run (capacity, install, porting models), Profile and optimize (XProf, tuning, Pallas kernels), Train at scale (sharding, FSDP, RL with Ray, 30B training). Second row: Serve at scale (inference math, vLLM, SGLang, llm-d), Trust your results (parity, benchmarks, MFU, SLOs), Extending the stack (lowerings, patches, plugins, agents).

The seven Parts in reading order. Trust your results comes after training and serving: you can judge a result only once you can produce it.

The companion code, and what it does not prove

Every script listed on the Code tab (under code/ in the book's repository) has a --cpu-smoke path, and most also have a TPU path:

  • --cpu-smoke runs on a laptop with the CPU build of PyTorch. It checks logic, arithmetic and tensor shapes, and exits with status 0. Tests under tests/chNN/ run this path with pytest, and CI runs them on every push.
  • The TPU path, the same script without the flag, needs a Cloud TPU VM with TorchTPU installed (chapter 8 sets one up).

The CPU path is not a TPU benchmark. When it cannot show anything useful about a TPU-only behavior, it says so and stops; it never prints a number that looks like a TPU measurement. No TPU numbers from these scripts appear in the book unless a chapter says it measured them. And a CPU-versus-TPU helper run on a laptop compares the CPU with itself, which, as chapter 23 puts it, tests the plumbing and nothing else.

Chapter 16's code is pure arithmetic, so its CPU path does reproduce the chapter's estimates and the published Muse Glimmer MFU figures. In a Python 3.12 virtual environment set up as the Code tab describes, I ran these at commit e9e56f5; each exits 0:

git clone https://github.com/ainaomotayo/torchtpu-book && cd torchtpu-book
# set up and activate .venv as the Code tab's "Set up" section shows, then:
python code/ch16_case_study/estimate.py --cpu-smoke    # the worksheet, including the 38.6% MFU
python code/ch16_case_study/mfu.py --cpu-smoke         # the six MFU figures in the announcement post
python code/ch07_dynamic_shapes/bucketing.py --cpu-smoke
python code/ch23_correctness/bisect_demo.py --cpu-smoke
python -m pytest -q tests/ch07 tests/ch16 tests/ch23 tests/ch24   # 148 passed
Enter fullscreen mode Exit fullscreen mode

Where to go next

Every reading order starts with chapter 0, Part I and chapter 8 (getting a TPU and installing TorchTPU), then branches, each with a "done when" test:

  • Porting: Porting a model, profiling, the optimization playbook, correctness. Done when the port passes a parity check against a GPU or CPU baseline and you can name the largest item in its profile.
  • Serving: profiling and sharding, then Inference math, vLLM-TorchTPU, SGLang-TorchTPU, llm-d, the Trust chapters and the inference case study. Done when you can state latency and throughput from a benchmark method you can defend, against an SLO.
  • Training: porting, profiling and the playbook, then sharding, FSDP and TorchTitan, RL with Ray if you need it, the 30B training case study and the Trust chapters. Done when you can compute your run's MFU by hand and show its loss matches a reference.

Chapter 0 lists the reading orders chapter by chapter. To judge the book before you commit, read chapter 16, then chapter 24. To run something now, start at the Code tab. Or begin at the book's front page.

The book and the series

My five-part DEV series, TorchTPU in Production: From First Tensor to Pod Scale, covers related ground, one running example per post; the book's code/samples folder includes its sample scripts.

The book was written for the TorchTPU Sprint. If you build something with it, post it with #TorchTPUSprint. If a number in it does not reproduce for you, tell me in the comments or open an issue on the book's repository.

Top comments (1)

Collapse
 
beararmd profile image
Bear Mac •

Dude! 😢
Awesome work. Thank you sincerely for access to these learning tools. I use PyTorch often enough that this will be a genuine asset to me... Again Thank you for the work! πŸ‘