Skip to content

How to read this book

15 min read

You have a PyTorch model and a reason to run it on Cloud TPU. The upstream documentation for TorchTPU is spread across several repositories, blog posts and talks, each written for a slightly different reader. This chapter tells you what TorchTPU is, why it was built, which reading order fits the job you have, and the conventions every later chapter assumes. It is short on purpose: read it once, then come back to the notation table when a later chapter uses a unit or a name you are unsure of.

What this chapter covers

  • What TorchTPU is, why it was built, and the four foundational repositories it was released as.
  • The two code changes that move a typical GPU training script onto TPU, and what those changes do not give you.
  • Reading orders for porting, serving and training, and the core chapters they share.
  • Notation and units: FLOPs and FLOP/s, decimal and binary bytes, data types, and the difference between a chip and a device.
  • Running the companion code on a laptop with --cpu-smoke and on a TPU VM.

What TorchTPU is

TorchTPU is an open-source, native PyTorch backend for Google Cloud TPUs, built by Google together with the PyTorch team at Meta. With it, existing PyTorch models run on TPU with small code changes, and training and inference scale from a single chip to multi-slice TPU pods.

The word "native" carries most of the weight. TorchTPU is a C++ backend registered with the PyTorch dispatcher (as the PrivateUse1 device), and it implements TPU collectives at the torch.distributed ProcessGroup level. Because it plugs in at those two points (and, for torch.compile, as a TorchDynamo backend), the rest of the PyTorch ecosystem comes along: Hugging Face models, TorchTitan for training, vLLM and SGLang for serving, Ray for orchestration across hosts, and llm-d for serving a fleet on Kubernetes. Under the hood, each PyTorch operation is lowered to StableHLO and compiled by the XLA compiler.

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 in the middle tier. TorchTPU does not replace PyTorch; it sits behind the dispatcher (single-device work) and the ProcessGroup API (collectives), which is why frameworks in the top tier run without being rewritten. A third entry point, the TorchDynamo backend behind torch.compile, is not drawn. Chapter 3 expands the bottom two tiers into the full stack.

Why it exists

TPUs have mostly been programmed from JAX and TensorFlow. The first compiled PyTorch path to TPU, PyTorch/XLA (2020), was built on Lazy Tensors. Its authors list four problems with it: it needed intrusive source changes to mark compilable regions, compile times were long, it had no real eager mode, and it lagged behind new PyTorch distributed primitives. TorchTPU started at Google in mid 2025 to fix those by treating TPU as one more PyTorch device rather than fitting PyTorch into JAX's execution model.

The project states three guiding principles:

Principle What it means in practice
PyTorch Citizenship No JAX dependency in the runtime, a solid eager mode, and torch.compile built on Dynamo rather than Lazy Tensor. Wide support for PyTorch distributed idioms (DDP, FSDP, DTensor) through TPU collectives at the ProcessGroup level.
Focus on the User Porting should be as simple as changing model.to("cuda") to model.to("tpu"), even though peak performance needs more than that. Runtime and compiler errors are meant to be actionable, and the project integrates with tools the community already uses, such as torch.profiler, DTensor and Ray.
Improve the State of the Art Compete with PyTorch on GPUs for large-scale workloads, with a JIT approach to eager execution (the DeferAndFuse mode) that narrows the gap to compiled code, and bounded dynamism to avoid recompiling on shape changes.

The two-line port, and what it does not give you

For a typical distributed script, the move from GPU to TPU is two strings:

import torch
import torch.distributed as dist

device = torch.device("tpu")                # was "cuda"
dist.init_process_group(backend="tpu_dist")  # was "nccl"
model = model.to(device)

A device-agnostic form also works, letting PyTorch pick the current accelerator and the process group pick its backend:

device = torch.accelerator.current_accelerator()
dist.init_process_group()

The TorchTPU authors are explicit about the limit of this: the model runs out of the box, but it will not reach peak TPU performance from that change alone, because its shapes, sharding and operators may be tuned for a GPU. Closing that gap is what Parts I to V of this book are for. Knowing whether you closed it, and whether the numbers stayed correct on the way, is what Part VI is for.

The ecosystem in one table

TorchTPU was open-sourced as four foundational repositories at the October 2026 PyTorch Conference. The book also covers projects that integrate with them.

Project What it does Where the book covers it
TorchTPU (google-pytorch/torch_tpu) The PyTorch backend: eager modes, torch.compile backend "tpu", tpu_dist collectives, Pallas kernel interop Parts I to III
vLLM-TorchTPU vLLM serving on TorchTPU Chapter 18
SGLang-TorchTPU SGLang serving on TorchTPU Chapter 19
TorchTitan PyTorch's reference platform for large-scale training, with TPU recipes and an optimization playbook Chapter 14
Hugging Face Transformers, Diffusers Model libraries that run on TorchTPU with to("tpu") Chapter 9
Ray Orchestration of training and serving across hosts Chapter 15
llm-d Distributed inference serving across a fleet on Kubernetes Chapters 20 and 21
TPU Agent Suite Agent-driven workflows for TPU work Chapter 26

How the book is organized

The book has seven Parts after this one, and each builds on one or more of the Parts before it.

Seven cards in two rows, read left to right and top to bottom and joined by arrows, each with a Part name in its header and its topics below. 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, with the topics each covers; the Book overview lists their chapters. Trust your results comes after training and serving because you can only judge a result you know how to produce.

The Book overview has the full table of contents and a map of which Part depends on which, and each Part overview maps its chapters' prerequisites. You can follow those maps instead of the page order: a chapter is safe to read once every chapter it lists as a prerequisite is done (a solid arrow into it on its Part map). Each chapter names the chapters it assumes at the top and shows how to check its results: a parity test, a compile count, an MFU computed by hand, an SLO measured under load.

Reading orders

Pick a reading order by the job in front of you. All three share a core.

A flow read from top to bottom. A dark pill, Chapter 0, has an arrow down into a band labelled Core that holds the chapter numbers 1, 2, 3, 4, 5, 6, 7, 8 in order. From the left side of Core, one line runs down the left margin and branches, with a dot and an arrow, into three bands below it, each a reading order with its chapters in order from left to right: Port a model: 9, 10, 11, 23. Serve a model: 10, 13, 17, 18, 19, 20, 21, 23, 24, 22. Train a model: 9, 10, 11, 13, 14, 15, 16, 23, 24, with a note inside the band below 15: 15 only if you post-train with RL. From the right end of each band a line joins one line down the right margin, which ends in an arrow into the right end of a white question box: Is the compiler's code for one op the limit? Yes leads left to a grey card: Chapter 12, then Part VII; Chapters 11 and 24 first, if not yet read. No leads down to a green card: Done.

All three orders start from the same core, Part I and chapter 8, and each is read left to right; Serve ends with chapter 22, after 24. Any of them continues to chapter 12 and Part VII only when a profile shows that the compiler's code for one op is the limit.

Goal After the core, read You are done when
Porting a model 9, 10, 11, 23 The port passes a parity check against a GPU or CPU baseline, and you can name the largest item in its profile.
Serving a model 10, 13, 17, 18, 19, 20, 21, 23, 24, then the case study in 22 You can state latency and throughput from a benchmark method you can defend, against an SLO.
Training a model 9, 10, 11, 13, 14, 15 if you post-train with RL, 16, 23, 24 You can compute your run's MFU by hand and show its loss matches a reference.

Any of the three orders continues to chapter 12's custom Pallas kernels and to Part VII when a profile shows that the compiler's code for one op is the limit. Read chapter 11 first if your order skipped it (the serving order does), since chapter 12 builds on it; the porting order also needs chapter 24 at that point, to show that a speedup is real.

Some adjustments for readers with a head start:

  • You already program TPUs from JAX. Skim chapters 1 and 2 for notation, then read chapters 3 to 7 closely: the execution model, view semantics and one-process-per-device are where TorchTPU differs from JAX.
  • You used PyTorch/XLA before. Read chapter 4 first. Eager mode is the default in TorchTPU and torch.compile goes through Dynamo, not Lazy Tensors, so habits from PyTorch/XLA do not transfer directly.
  • You need one answer, not a chapter. Use the Reference tab or the Guides tab. Each guide links back to the chapter that explains why.

Google DeepMind's How to Scale Your Model is organized the same way: preliminaries (rooflines, TPUs, sharding) that later parts depend on, which readers who know the material can skip. That book is written for JAX and does not cover TorchTPU. Where a chapter here builds on one of its ideas, the chapter links the original section.

Notation and conventions

Topic Convention in this book
Counting work FLOPs is a count of floating-point operations (adds plus multiplies). FLOP/s is a rate. TFLOP/s is \(10^{12}\) FLOP/s. A matmul of an \([M, K]\) by \([K, N]\) matrix costs \(2MKN\) FLOPs.
Bytes and bandwidth GB and TB are decimal (\(10^9\), \(10^{12}\) bytes). GiB is binary (\(2^{30}\) bytes); sources mix the two, and the book keeps whichever unit the source used. Bandwidth is GB/s or TB/s.
Arithmetic intensity FLOPs per byte moved, as in chapter 2. A kernel is compute-bound when its intensity exceeds the hardware's peak FLOP/s divided by its memory bandwidth.
Data types bf16 is bfloat16 (torch.bfloat16): 1 sign, 8 exponent and 7 mantissa bits. fp32 is IEEE single precision. fp8 and fp4 name the 8-bit and 4-bit floating-point formats. The MXU multiplies bf16 inputs and accumulates in fp32.
Chip, TensorCore, device A chip is the physical TPU package. A TensorCore is a compute unit on it, holding the MXUs, the vector unit (VPU) and a scalar unit. A device is what PyTorch sees as one "tpu" device and what one process owns. A chip can expose more than one device: a v7x chip exposes two, one per TensorCore. Per-chip and per-device numbers therefore differ by that factor; every number in the book says which it is.
Host, slice, pod A host is the VM attached to a set of chips. A slice is a user-configured group of chips joined by ICI. A pod is the full preconfigured set of chips that slices are carved from.
Interconnects ICI (inter-chip interconnect) links chips inside a slice. DCN (data-center network) links slices. ICI is much faster than DCN, which is why mesh layout matters (chapter 13).
Hardware generations The book writes generations as the Google Cloud version names: v5e, v5p, v6e (Trillium), v7x (Ironwood). Sources also write "TPU v7" or "TPUv7" for v7x; the book normalizes to v7x. Slice shapes are written as in the sources, for example v6e-8 for an 8-chip v6e slice.
Names in code TorchTPU is the project. torch_tpu is its repository. torch.tpu is the namespace of its Python APIs, for example torch.tpu.precision. "tpu" is the device string and the torch.compile backend name; "tpu_dist" is the distributed backend.
Boxes on the page Answer (green, collapsed) hides a worked problem's answer. Warnings mark a failure mode you will hit.

Companion code: CPU and TPU

Chapters that include code have a folder code/chNN_<topic>/ in the repository. Each script has two paths:

  • CPU path. python code/chNN_<topic>/<script>.py --cpu-smoke runs on a laptop with no TPU. It checks logic, arithmetic and tensor shapes, and exits with status 0. Tests in tests/chNN/ run this path with pytest, and CI runs them on every push.
  • TPU path. The same script without --cpu-smoke. It needs a Cloud TPU VM with TorchTPU installed; chapter 8 shows how to get one on a VM or on GKE. If you want to try TorchTPU before provisioning anything, the upstream introduction notebook runs on Colab with the TPU runtime enabled.

When a CPU path 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. The first script you will run is the roofline calculator in chapter 2.

The smallest program that touches a TPU is the upstream quickstart. It runs only on a TPU host:

import torch

device = torch.device("tpu")
x = torch.randn((4, 4), device=device)
y = torch.ones((4, 4), device=device)

result = torch.matmul(x, y).cpu()
print(f"Executed on device: {x.device}")
print(f"Result shape on CPU: {result.shape}, sum: {result.sum():.4f}")

The .cpu() call matters more than it looks: it is the point where the host waits for the TPU and copies the result back. Chapter 4 explains why that point controls when work runs.

Verifying the result

This chapter has no code to check. Its result is a reading plan, and the plan is sound when:

  • the reading order you wrote down as a list of chapter numbers puts every chapter after its prerequisites (check it against the map of Parts and the map on each Part overview);
  • the "done" condition for your goal is one sentence that names a measurable check: a parity threshold, an MFU, an SLO;
  • "bf16 TFLOP/s per chip" is unambiguous to you, including why the per-device number on v7x is half the per-chip number;
  • the three TorchTPU eager modes are familiar names, or you know that chapter 4 explains them.

Worked problems

Problem 1. Name the four repositories TorchTPU was open-sourced as.

Answer

TorchTPU (torch_tpu), vLLM-TorchTPU, SGLang-TorchTPU and TorchTitan. Hugging Face libraries, Ray, TorchRec and llm-d integrate with them but are separate projects.

Problem 2. A CUDA training script calls torch.device("cuda") and dist.init_process_group(backend="nccl"). What two changes make it run on TPU, and what does the TorchTPU team say those changes do not deliver?

Answer

Change the device to "tpu" and the backend to "tpu_dist" (or use torch.accelerator.current_accelerator() with dist.init_process_group() and let PyTorch choose). The model then runs, but not at peak TPU performance: its shapes, sharding and operators may be tuned for GPU. Getting closer to peak is the work of profiling and optimization (Part III).

Problem 3. At which two points does TorchTPU plug into PyTorch's runtime, what does each handle, and what third extension point does torch.compile use?

Answer

The dispatcher, where TorchTPU is registered as a C++ backend (PrivateUse1) and receives each ATen operation; and the torch.distributed ProcessGroup API, where it implements TPU collectives as the tpu_dist backend. The second is why DDP, FSDP2 and DTensor work without TPU-specific rewrites. The third extension point is the TorchDynamo custom backend "tpu", which torch.compile(model, backend="tpu") uses (chapter 3).

Problem 4. A source reports a result "on a single TPUv7 chip" with FSDP and a world size of 2. Using the book's conventions, how do you write the hardware, and why is the world size 2?

Answer

The book writes v7x. A v7x chip exposes two devices to PyTorch, one per TensorCore, and TorchTPU runs one process per device, so a single chip gives a world size of 2.

Problem 5. Your goal is to serve an LLM behind an endpoint with a latency SLO. A colleague suggests skipping chapter 6 because precision is "a training topic". Using the reading orders and prerequisites, explain why that does not work.

Answer

The serving order reads chapters 23 and 24 before its case study; they judge whether the served model is correct and fast. Chapter 23 lists chapter 6 (numerical precision) as a prerequisite, and chapter 24 builds on 23. Skipping chapter 6 leaves you unable to tell a precision-related accuracy change from a bug when you check the served model's outputs.

Problem 6. Why does the book put the Trust Part after Train and Serve, rather than before them?

Answer

Judging a result requires being able to produce it and to diagnose it. Parity gates, MFU arithmetic and SLO measurement only make sense once you have a training run or a serving deployment to apply them to. The trust checks still appear earlier, in each chapter's "Verifying the result" section; Part VI turns them into a method.

Quick questions

  1. What did PyTorch/XLA require of user code that TorchTPU set out to remove?
  2. What is the difference between FLOPs and FLOP/s, and which one describes a chip's peak bf16 rating?
  3. Which chapters does every reading order share?
  4. What does the --cpu-smoke path of a companion script check, and what does it not claim?
  5. In the quickstart program, what does the .cpu() call make the host do?

Key takeaways

  • TorchTPU is a native PyTorch backend for Cloud TPU, built by Google and Meta, that plugs in at the dispatcher and the ProcessGroup API (plus the TorchDynamo backend for torch.compile) and lowers work to StableHLO for the XLA compiler.
  • Changing "cuda" to "tpu" and "nccl" to "tpu_dist" makes a model run; it does not make it fast. The rest of the book is about the gap.
  • All reading orders share Part I and chapter 8; after that, porting, serving and training each have their own path, and all pass through Part VI.
  • A chip is not a device: a v7x chip exposes two devices. FLOPs count work, FLOP/s is a rate, and bf16 is the MXU's native input type with fp32 accumulation.
  • Companion code runs its --cpu-smoke path on a laptop and says plainly when something needs a TPU.

References