Porting a model, including Hugging Face Transformers and Diffusers¶
Prerequisites: Execution model: eager modes, deferred ops, torch.compile, Dynamic shapes and recompilation, Getting capacity and installing: VM and GKE
A port to TorchTPU rarely fails on the first line. model.to("tpu") works, the forward pass runs, and the loss goes down. The trouble arrives later and quietly: a step that is slower than on the GPU you replaced because a .item() drains the pipeline every iteration, a decode loop that compiles a new program for every token, outputs that differ from the reference by more than you can explain, or a model that does not fit in one chip's HBM at all. This chapter turns the rules of Part I into a checklist you can apply to any model, runs it on a small custom block, and then applies it to the cases most people start with: Hugging Face Transformers with device_map="tpu" and a static cache, a Mixture-of-Experts kernel from the Kernels Hub, and Diffusers pipelines on one chip and sharded across several. It closes with the FLUX case study read as a worked analysis, and with the three checks that decide whether a port worked: parity against a CPU reference, no recompiles after warm-up, and a step time that beats a baseline.
What this chapter covers¶
- A six-item porting checklist (device, dtype, eager mode, host syncs, shapes, collectives) and a static scanner that finds the lines to change.
- Proving a port of a custom
nn.Modulewith three checks: parity against a CPU reference, a compile count that stops growing after warm-up, and step time against a baseline. - Hugging Face Transformers with
device_map="tpu"andcache_implementation="static", and whengenerate()compiles its decode step. - A Kernels Hub MoE kernel plugged in through
experts_implementation, and Diffusers pipelines run eagerly, compiled and sharded withTensorParallelConfig. - The FLUX case study's step times, split by optimization, and why the split depends on sequence length.
- A table of port failures by symptom, with the tool that confirms each and the chapter that fixes it.
The porting checklist¶
A port is six questions, asked in order. Each one is a chapter of Part I applied to your code, and each has an observable answer.
| # | Item | What to change | How you know it is right | Chapter |
|---|---|---|---|---|
| 1 | Device | torch.device("tpu") or torch.accelerator.current_accelerator(); no .cuda(), no "cuda" strings; torch.cuda.* calls become torch.accelerator.* or torch.tpu.* |
Every parameter and input reports device.type == "tpu" |
3 |
| 2 | dtype and precision | Weights and activations in bf16 where the model allows; keep set_float32_matmul_precision at the TorchTPU default "medium" unless you need more; scope higher precision to the ops that need it |
Parity against a CPU run of the same dtype, at the tolerance that dtype predicts | 6 |
| 3 | Eager mode first | Run in the default Strict eager mode until outputs match, use Debug mode (TORCH_TPU_LAUNCH_BLOCKING=1) when an error surfaces far from its cause, then compile with torch.compile(..., backend="tpu") |
Same outputs eager and compiled | 4 |
| 4 | Host syncs | No .item(), .cpu(), print(tensor) or if tensor: inside the step; read values every N steps |
fullgraph=True compiles the step without a graph break |
4 |
| 5 | Shapes | Static shapes: preallocated caches, padded buckets, masks instead of nonzero or boolean indexing; never dynamic=True |
The compile count stops growing after warm-up | 7 |
| 6 | Collectives and processes | init_process_group(backend="tpu_dist") (alias "tpu"); launch with python3 -m torch.tpu.distributed then torchrun; DataLoader num_workers=0 in the process that owns the TPU |
All ranks finish and match an unsharded reference | 8, 13 |
The order matters. Items 1 and 2 make the model run and make its numbers comparable. Item 3 separates "wrong answer" from "slow answer": a mismatch in eager mode is a correctness bug, a mismatch that appears only when compiled is a compile issue. Items 4 and 5 are where speed is lost, and a port can pass both parity checks while failing them. Item 6 only applies once the model is right on one device.
The decisions in between follow this flow. Every box ends in a check you can run. The scan covers items 1, 4 and 5 in the source; the three numbered gates are Checks 1, 2 and 3 of the minimal port below.
Each numbered gate is one of the three checks in the next sections, and each failure sends you back only as far as the step it invalidates; keep the three checks in CI once the port is done. The parity gate is useful only if it fails on a deliberately broken copy of the model, which port_model.py also checks. Item 6 (collectives, chapters 8 and 13) follows once the port passes on one device.
Scan before you run¶
Items 1, 4 and 5 leave fingerprints in the source code: .cuda(), torch.cuda.synchronize(), "nccl", .item() inside a loop, x[x > 0], kv = torch.cat([kv, new]) in a loop. The companion scanner port_checklist.py reads a script with Python's ast module and reports them with the fix. It never imports the code it scans or PyTorch, so it runs on a laptop or in CI against code whose dependencies you do not have.
Here is its output on the chapter's fixture, a CUDA-era training script with one of each hazard (paths shortened):
$ python code/ch09_porting/port_checklist.py code/ch09_porting/fixtures/before_port.py
before_port.py:16:12: warn cuda-env: CUDA_VISIBLE_DEVICES has no effect on TPU (fix: use TPU_VISIBLE_DEVICES)
before_port.py:20:15: info rearrange-qkv: an axis-moving rearrange before a split can cost an HBM copy in backward (fix: ...)
before_port.py:25:37: error nccl-backend: "nccl" backend on a TPU (fix: backend="tpu_dist" (alias "tpu"), or omit it: ...)
before_port.py:26:5: error torch-cuda-api: torch.cuda.set_device() is CUDA-only (fix: torch.accelerator.set_device_index(rank))
before_port.py:27:5: info matmul-precision: "high" is about 3x the MXU cost of the TorchTPU default "medium" (fix: ...)
before_port.py:28:13: error cuda-device: .cuda() moves the tensor or module to a GPU (fix: .to(device) with device = torch.device("tpu"))
before_port.py:29:15: warn compile-backend: compile without backend=: this is Inductor, not XLA (fix: pass backend="tpu")
before_port.py:29:44: error compile-dynamic-true: dynamic=True raises NotImplementedError on TorchTPU (fix: ...)
before_port.py:30:61: warn dataloader-workers: num_workers=4: forked workers try to reacquire the libtpu lockfile (fix: ...)
...
before_port.py:37:12: warn tensor-branch: `if` tests .any(); on a tensor this is a host sync and a graph break (fix: ...)
before_port.py:42:9: warn growing-tensor-in-loop: `history` grows by concatenation every iteration: a new shape each step (fix: ...)
before_port.py:43:35: warn host-sync-in-loop: .item() in a loop: the host waits for the TPU every iteration (fix: ...)
before_port.py:44:18: warn data-dependent-shape: boolean-mask indexing: the result's length depends on the values (fix: ...)
before_port.py:45:15: warn data-dependent-shape: nonzero: the output shape depends on the values (a host sync, then a new shape) (fix: ...)
before_port.py:46:5: error torch-cuda-api: torch.cuda.synchronize() is CUDA-only (fix: torch.accelerator.synchronize())
19 finding(s): 9 error, 8 warn, 2 info
Each rule is tied to a source: the torch.cuda replacements come from the TorchTPU API reference's CUDA tables (the same ones chapter 3 uses), the dynamic=True error from TorchTPU's loader (chapter 7), the DataLoader rule from the GKE guide's MNIST example (chapter 8), and the rearrange note from the FLUX case study below. On the ported fixture it reports one info: a .item() under if step % 50 == 0, which it recognizes as periodic logging rather than a per-step sync. Run on chapter 3's before_cuda.py it finds seven errors; on after_tpu.py, none.
A scanner is a review list, not a proof. It cannot see a host sync hidden in a helper function in another file, or tell a tensor .sum() from a NumPy one. Once the port runs, the three checks in the next section are what you trust. Keep the scanner in CI with --strict after the port, so CUDA-only calls do not creep back in; a reviewed line can be silenced with a trailing # port: ok.
A minimal custom model port¶
The model is a pre-norm transformer block of the kind most people port: RMSNorm, attention through F.scaled_dot_product_attention, a GELU MLP, trained with AdamW. It is already TPU-friendly: it splits Q, K and V with .view() and torch.unbind (the zero-copy split the FLUX case study recommends), and every shape is fixed. The port itself is three lines:
device = torch.device("tpu") # item 1
model = TinyBlock(hidden=128).to(device) # item 1
step_fn = torch.compile(model, backend="tpu", dynamic=False) # items 3 and 5
What makes it a port rather than a hope is the evidence. port_model.py produces three pieces of it.
Check 1: parity against a CPU reference. Run the same weights on the CPU in float32 and on the TPU, compare the outputs and every gradient. Compare like with like: the TorchTPU precision guide's rule is bf16 on TPU against bf16 on CPU, or float32 on TPU under Precision.HIGHEST against float32 on CPU, because comparing bf16 to float32 measures quantization, not the port. The script uses the second form, so float32 default tolerances apply:
with torch.tpu.precision(torch.tpu.Precision.HIGHEST): # on the TPU side only
out = model_tpu(x)
out.float().sum().backward()
# then torch.testing.assert_close(tpu_tensor.cpu(), cpu_tensor) for the output and all 11 gradients
A parity gate is only useful if it fails when the port is wrong. The script also runs the gate against a copy of the model with one weight scaled by 1.01, a stand-in for a dropped scale factor or a wrong cast, and requires that gate to fail.
Check 2: no recompiles after warm-up. The compiled forward uses a counting backend that increments a counter for each graph Dynamo hands it, then delegates to "tpu" ("eager" on a CPU). After the warm-up steps, the remaining steps run under torch.compiler.set_stance("fail_on_recompile"), which turns any recompile into a RuntimeError. The counter must not move, and nothing must raise.
Check 3: step time against a baseline. Synchronize before reading the clock, take the median of the steps after warm-up, and require it to be no more than 5% slower than a baseline: by default the same step in the default eager mode on the same TPU, or the GPU step time you are replacing via --baseline-ms.
On a laptop the script runs every check with the CPU standing in for the device:
$ python code/ch09_porting/port_model.py --cpu-smoke
device: cpu (CPU FALLBACK: checks logic and gates only, not TPU numerics or speed)
1. parity vs CPU float32 (12 tensors: output + gradients): PASS max|diff| 0.00e+00
same gate, port with a 1% weight bug: FAIL (caught) max|diff| 1.26e+00
2. compiles: 1 during warm-up, 1 after (no recompiles)
3. step time: eager first 6.2 ms, warm 1.69 ms; compiled first 89.6 ms, warm 1.73 ms; baseline 1.69 ms (eager on the same device)
step-time check: not enforced on the CPU
PORT CHECK: PASS
Read it honestly. Parity is exact because the CPU is compared with itself; the line that matters is the second one, which proves the gate rejects a 1% error. The compile count is real: Dynamo's guards behave the same on a CPU, and the tests feed the loop a new sequence length after warm-up to show that fail_on_recompile catches it. The times say nothing about a TPU, which is why the step-time check is not enforced there. On a TPU VM, python code/ch09_porting/port_model.py --json port_report.json produces the same report with TPU numerics and timings; keep the JSON as the record of the port.
Hugging Face Transformers on TPU¶
TorchTPU registers itself as a PyTorch backend under the PrivateUse1 slot with the device string "tpu", so Transformers, Diffusers and the Kernels library call ordinary PyTorch ops and the dispatcher routes them to TorchTPU. There is no wrapper library between them. Hugging Face's announcement says so directly: with TorchTPU's native support, Optimum TPU is no longer required to run Hugging Face models with Transformers and Diffusers.
Install the libraries next to TorchTPU, with the CPU index from chapter 8 so pip does not pull a CUDA torch:
pip install torch-tpu --extra-index-url https://download.pytorch.org/whl/cpu
pip install "transformers>=5.16.1" accelerate diffusers kernels \
--extra-index-url https://download.pytorch.org/whl/cpu
accelerate is required, not optional: in transformers 5.16.1, from_pretrained(..., device_map=...) raises a ValueError asking for it. Pin transformers>=5.16.1, the version TorchTPU's requirements pin; running on TPU found bugs in Transformers' own StaticCache and in the Qwen3 tensor-parallel plans, which were fixed upstream.
How much of the Hub runs? Google's launch post reports a validated corpus of 4,917 models: 98% (4,821) run without a crash, 97% (638 of 657 architecture representatives) match a GPU baseline numerically (perplexity within 0.10 relative for causal LLMs, a relative MSE threshold for other models), and 834 of 839 causal LLMs give correct numerics with bounded dynamism. Hugging Face's own Transformers test suite passes 96.5% of the tests that run on TPU; each failure becomes a small repro and a TorchTPU issue (34 reported, 19 fixed at the time of the post). Those are good odds, not a guarantee for your model, which is why the parity check stays.
Loading: device_map="tpu"¶
The whole port of a causal LM is one argument:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "Qwen/Qwen3.5-9B"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16, device_map="tpu")
tokenizer = AutoTokenizer.from_pretrained(model_id)
inputs = tokenizer("The future of AI is", return_tensors="pt").to("tpu")
out = model.generate(**inputs, max_new_tokens=64)
print(tokenizer.decode(out[0], skip_special_tokens=True))
device_map="tpu" loads the model directly onto the TPU: from_pretrained places each module's weights on the current device as it reads them. That is placement, not sharding. Every module lands whole on one device, and a model that does not fit one device's HBM needs tensor parallelism instead, covered under Diffusers below.
Watch where the arrows go. With device_map="tpu" every module goes to one device and three stay idle; with tensor parallelism every sharded block goes to all four, a quarter each. Fill heights are illustrative.
Generation: when does generate() compile?¶
The snippet above runs its decode loop eagerly. In transformers 5.16.1, generate() compiles the decode step on its own only when three things hold: the device type is one of cuda, xpu, neuron or tpu; the cache is compileable; and the cache is not a plain DynamicCache. The default cache is a DynamicCache, so the snippet runs eagerly, which matches Hugging Face's note that "the model runs in eager mode by default".
One argument changes that:
out = model.generate(**inputs, max_new_tokens=64, do_sample=False,
cache_implementation="static")
cache_implementation="static" allocates a StaticCache sized to the final length. The criteria now pass, and because the model is on "tpu", Transformers' _default_compile_config() returns CompileConfig(backend="tpu", dynamic=False, mode="default") instead of Inductor. Prefill still runs eagerly; only the one-token decode step is compiled.
Prefill sees a new prompt length on almost every request, so it stays eager; decode always sees one token, so it is the part worth compiling. The cache is one fixed buffer that both write into.
The StaticLayer behind it follows the same three rules as the static cache in chapter 7: preallocated [B, H_kv, max_cache_len, D] buffers, a 0-D cumulative_length tensor that holds the length on the device, and writes with index_copy_. Under dynamic=False Dynamo guards on tensor sizes, not values, so the buffer that never changes size passes its guard every step while the length moves.
hf_generate.py --cpu-smoke checks this on a tiny random Llama (two layers, no download): generate() with both caches gives identical greedy tokens, and an eager prefill followed by 11 compiled decode calls compiles this many times:
generate(): StaticCache tokens == DynamicCache tokens: True
static cache, dynamic=False: 11 decode calls -> 1 compilation(s) (expected 1)
dynamic cache, dynamic=False: 11 decode calls -> 11 compilation(s) (expected 11)
dynamic cache, dynamic=None : 11 decode calls -> 2 compilation(s) (expected 2)
Chapter 7 showed what the same choice costs on a real TPU, using the Muse Glimmer 30B case study: the static cache settles after its two unavoidable compiles at about 23.6 ms per token; the dynamic cache with dynamic=None pays roughly 27 seconds more of warm-up and then runs about 2.5% slower per token.
The static cache has one price: memory, reserved up front. It holds \(2 \times L \times B \times H_{kv} \times \text{max\_cache\_len} \times D \times \text{bytes}\) from the first step. For a Qwen3-30B-A3B-shaped model (48 layers, 4 KV heads, head dimension 128) in bf16, one token costs \(2 \times 4 \times 128 \times 2 = 2\) KiB per layer, 96 KiB across 48 layers. At batch 64 and max_cache_len=4096 that is 262,144 slots, exactly 24 GiB, on a v6e chip with 32 GiB of HBM. Size max_cache_len to the real prompt plus generation budget, not to the model's context window.
Three model features still recompile with a "static" cache. The comments of TorchTPU's perflab decode benchmark, which runs thousands of Hub models through a static cache, document them (see also Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers):
- Sliding-window layers.
StaticSlidingWindowLayertracks its length in a Pythonint, which Dynamo guards on, so every decode step recompiles. When the window covers the whole cache it never rolls, and perflab swaps the layer for a plainStaticLayer. Printtype(layer).__name__for each layer of the cache you built. - Masks rebuilt from the cache length. Without an explicit
attention_maskandposition_ids, some models (OPT, for example) derive them frompast_key_values.get_seq_length(); used as a slice bound, it graph-breaks and the mask grows every step. Pass a fixed(B, max_cache_len)mask andposition_idsequal tocache_position, ascount_decode_compilations()does. - Architectures without a KV cache to preallocate. Perflab falls back to
DynamicCachefor ALiBi models such as BLOOM and for recurrent or state-space models (Mamba, RWKV, xLSTM).
When a recompile remains, chapter 7's tools apply unchanged: a counting backend for the number, TORCH_LOGS="recompiles" for the guard that failed.
Mixture of experts: a kernel from the Kernels Hub¶
A Mixture-of-Experts (MoE) layer routes each token to its top-k experts, and which experts get work is decided by the data at run time. Qwen3-30B-A3B has 128 experts with 8 active per token. Transformers 5.16.1 offers three implementations, chosen by experts_implementation: "eager" (a Python loop over the experts that received tokens, found with .nonzero(), which is a data-dependent shape and a host sync per layer), "grouped_mm" (sort the token-expert pairs by expert, one grouped matmul that reads each active expert once), and "batched_mm" (index the weights by expert id for every pair and run a batched matmul, which materializes one weight slab per pair, duplicates included). One more detail matters for TPU: during decode on any non-CPU device, generate() switches every "grouped_mm" to "batched_mm".
The Kernels Hub has a TPU kernel for this layer, tengomucho/ragged-dot-tpu, built on Tokamax's Pallas grouped matmul (ragged_dot) and wrapped with TorchTPU's jax_op. The whole experts forward is one JAX function, so each MoE layer becomes one compiled op instead of about twenty small ones. Plugging it in, from Hugging Face's post:
from kernels import get_kernel
from transformers import AutoModelForCausalLM
from transformers.integrations.moe import ALL_EXPERTS_FUNCTIONS
repo_id = "tengomucho/ragged-dot-tpu"
kernel = get_kernel(repo_id, version=1, trust_remote_code=[repo_id])
ALL_EXPERTS_FUNCTIONS.register("tokamax_ragged_dot", kernel.experts_forward)
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen3-30B-A3B-Instruct-2507",
device_map="tpu",
experts_implementation="tokamax_ragged_dot",
)
trust_remote_code=[repo_id] allow-lists exactly this repository rather than all remote code. version=1 pins the kernel's v1 branch so a later push cannot change your numbers. register() writes to a class-wide mapping, and from_pretrained raises if experts_implementation names something that is not registered. The kernel imports torch_tpu, jax and tokamax when it loads, so it only loads on a TPU VM, and it accepts gated experts without bias with a SiLU (Qwen3-MoE) or GELU-tanh (Gemma 4) gate; anything else raises NotImplementedError.
Everything in the host region happens once at load time. At run time each MoE layer is one call into one compiled op.
The published numbers, from the kernel's README as quoted in Hugging Face's post (TPU v6e-8, decode):
The batch 1 bars barely clear the 1x line. Whatever the kernel fixes grows with batch size.
Why does the gain grow with batch? At batch 1 with top-8 routing there are 8 token-expert pairs and 8 distinct experts, so every implementation reads the same 8 weight slabs and the kernel can only win on overhead. At batch 64 there are 512 pairs. A gather path materializes 512 slabs per layer per step; a grouped path reads each active expert once, and with 128 experts and uniform routing about \(E\,(1 - (1 - k/E)^B)\) of them are active. moe_tp.py turns that into bytes for a Qwen3-30B-A3B-shaped layer:
Qwen3-30B-A3B-shaped MoE layer, batch 1: gather path 0.08 GB, grouped 0.08 GB (1.0x)
Qwen3-30B-A3B-shaped MoE layer, batch 8: gather path 0.60 GB, grouped 0.49 GB (1.2x)
Qwen3-30B-A3B-shaped MoE layer, batch 64: gather path 4.83 GB, grouped 1.19 GB (4.1x)
Decode is HBM-bound (chapter 2), so four times less weight traffic is close to four times less time for that layer. That explains the shape of the curve, flat at batch 1 and opening with batch; it does not explain all of 21.5x, and the rest is kernel quality (one fused op, tiles tuned for the MXU, no relayout of the weights). Use the model to predict where the kernel will matter for your MoE, not to reproduce the benchmark.
You can test the registration path on a laptop. hf_generate.py registers a pure-PyTorch twin of the kernel's experts_forward (same signature, same sort, group sizes, inverse-permutation gather and float32 sum) under its own name; on a tiny Qwen3-MoE it matches "eager" to about \(10^{-7}\). Its grouped matmul compiles once with fullgraph=True, dynamic=False and serves every routing, because group sizes are tensor values, not shapes. That property is what lets one compiled decode step serve every routing decision.
Diffusers¶
One chip: eager, then compiled¶
TPU is a first-class device in Diffusers. For prototyping the change is pipe.to("tpu"); for deployment, compile the denoiser once:
import torch
from diffusers import StableDiffusion3Pipeline
pipe = StableDiffusion3Pipeline.from_pretrained(
"stabilityai/stable-diffusion-3.5-medium", dtype=torch.bfloat16)
pipe.to("tpu") # eager
pipe.transformer.compile(backend="tpu", fullgraph=True, dynamic=False) # compiled
image = pipe("a corgi astronaut planting a flag on a pizza moon").images[0]
The first call compiles; every later call with the same image size reuses the graph. A new height or width compiles once for that shape. Changing num_inference_steps does not recompile, because it changes how many times the compiled transformer is called, not its inputs. Only the transformer is compiled because it runs once per denoising step (40 or 49 times in the examples below) while the text encoders and the VAE run once. Diffusers also applied one of chapter 5's view rules upstream: the Stable Diffusion 3 pipeline clones the timestep on TPU, because a view into timesteps made torch.compile recompile every step.
Hugging Face measured two large pipelines on a Cloud TPU v6e-4 (TP=4, bf16, batch 1):
Same backend, same flags, very different payoffs. The FLUX analysis below explains the difference.
Hugging Face's post gives the numbers, not the cause, and the FLUX case study supplies the pattern that fits them: compilation removes per-op dispatch and fuses elementwise chains, which is most of a step when ops are small, and little of it when attention over a long sequence dominates. A 5-second video plus audio is a much longer sequence than one 1024 by 1024 image.
If a pipeline does not fit one chip and you have only one, enable_model_cpu_offload() moves each model onto the TPU only while it runs. Its hooks cannot be traced, so compile the repeated blocks instead: pipe.transformer.compile_repeated_blocks(backend="tpu", fullgraph=True, dynamic=False). SD3.5 Medium, at about 15 GB in bf16, fits one v6e chip without either.
Too big for one chip: tensor parallelism¶
The Diffusers TPU guide's example, FLUX.2-dev, has a text encoder of about 48 GB and a transformer of about 64 GB; a v6e chip has 32 GiB of HBM. Compilation cannot help, and offloading would move tens of gigabytes per image. The answer is to split each large weight across chips.
Each Diffusers transformer that supports this declares a _tp_plan naming its linear layers and how to split them, always in pairs: a colwise layer (Q, K, V, the first MLP projection) splits its output features, so each chip computes a slice of the activations, for attention a subset of the heads, with no communication; the rowwise layer that follows (the attention output, the second MLP projection) splits its input features to match, so each chip holds a partial sum of the full output, and one all-reduce over ICI adds them.
The only arrow that leaves the dashed group is the one labelled ICI. Everything inside is local work on a quarter of the weights.
Does the split change the answer? moe_tp.py splits an MLP colwise then rowwise four ways with a GELU in between and sums the partial outputs: the difference from the unsplit MLP in float64 is \(2.27 \times 10^{-13}\), rounding only. The GELU acts on each element independently, so it does not care which chip holds that element. The same reasoning gives the one hard constraint: heads are the unit a colwise Q/K/V split hands out, so the TP degree must divide the number of attention heads. QwenImage21Transformer2DModel defaults to 32 heads, so TP of 2, 4 or 8 works and 3 does not.
TensorParallelConfig is passed to the transformer's from_pretrained through parallel_config, and Diffusers shards while it reads, so each rank only ever holds its own slice. The recipe, one process per chip:
import diffusers
import torch.distributed as dist
from torch.distributed.device_mesh import DeviceMesh
dist.init_process_group(backend="tpu_dist")
mesh = DeviceMesh("tpu", list(range(dist.get_world_size())))
transformer = diffusers.QwenImage21Transformer2DModel.from_pretrained(
"Qwen/Qwen-Image-2.1", subfolder="transformer", dtype=torch.bfloat16,
parallel_config=diffusers.TensorParallelConfig(mesh=mesh))
pipe = diffusers.DiffusionPipeline.from_pretrained(
"Qwen/Qwen-Image-2.1", transformer=transformer, dtype=torch.bfloat16)
for name, comp in pipe.components.items(): # text encoder, VAE: local copies
if name != "transformer" and isinstance(comp, torch.nn.Module):
comp.to("tpu")
pipe.transformer.compile(backend="tpu", fullgraph=True, dynamic=False)
image = pipe("...").images[0]
if dist.get_rank() == 0: # every rank runs the pipeline
image.save("out.png")
Launch it with TorchTPU's public launcher, which detects the slice and exports TORCH_TPU_TOPOLOGY, TORCH_TPU_SLICEBUILDER_ADDRESSES and WORLD_SIZE:
eval $(python3 -m torch.tpu.distributed | sed 's/^/export /')
torchrun --nproc_per_node=$WORLD_SIZE qwen_image_tp.py
The Diffusers guide instead uses torch_tpu._internal.distributed.launchers.singlehost_wrapper, an internal module it warns may change; prefer the public entry point. Before it fetches any file, Diffusers checks that torch.distributed is initialized, that device_map is not also given, that the weights are safetensors, that low_cpu_mem_usage is on, and that the TP degree divides the head count. TensorParallelConfig arrived after Diffusers 0.37, the version TorchTPU pins, so install a current release (0.43.0 has it). If the text encoder is also too big, Transformers has its own TP on the same mesh: from_pretrained(..., distributed_config=DistributedConfig(tp_plan="auto"), device_mesh=mesh).
diffusers_tp.py in the companion code packages both paths; its CPU mode checks the head-divisibility rule and that the TP path refuses to run without a TPU.
The FLUX port as a worked analysis¶
TorchTPU's FLUX case study ports a reference PyTorch DoubleStreamBlock (the FLUX diffusion transformer's two-stream block, from the TorchTitan and black-forest-labs implementations) and optimizes a training step in four milestones. It is the best published example of what happens after a port runs: which changes paid, by how much, and why.
The setup: one TPU v6e chip, batch 2, hidden size 1024, 8 heads of 128, an image sequence of 32,256 tokens plus 512 text tokens (32,768 total), bf16 parameters and inputs, a full training step (forward, loss, backward, optimizer), 3 warm-up steps and 10 timed steps with one torch.accelerator.synchronize() after the last.
| Milestone | Before | After | Where it shows |
|---|---|---|---|
| 1. Zero-copy views | einops.rearrange(qkv, "B L (K H D) -> K B L H D", ...) moves the Q/K/V axis to the front |
torch.unbind(qkv.view(B, L, 3, H, D), dim=2) |
A copy op in the backward pass, visible only in XProf (chapter 5) |
| 2. Fused RoPE | 2x2 rotation matrices per frequency pair, applied on 6D tensors | Compact [cos, sin] pairs, elementwise rotation |
Large copy blocks in XProf; the gain appears only when compiled |
| 3. Whole-block compile | One TPU program per op | torch.compile of the whole block |
Fewer HBM round trips, less dispatch |
| 4. Pallas SplashAttention | F.scaled_dot_product_attention materializes the \(O(S^2)\) scores in HBM |
splash_sdpa(q, k, v), attention in on-chip tiles, through torch.tpu.pallas.jax_op |
Memory-bound attention at long sequences |
The hatched blocks on the right are one large, one medium and two small. The attention kernel and the compiler do almost all of the work at this sequence length; the two layout fixes are nearly free and nearly invisible.
Where the saving comes from. The compiled path reads left to right; each step is a row of the case study's table. The total saving is \(178.61 - 122.51 = 56.10\) ms per step.
| Step added | Step time (ms) | Saved (ms) | Share of the saving |
|---|---|---|---|
| Baseline, eager | 178.61 | ||
torch.compile (M3) |
159.33 | 19.28 | 34.4% |
| Zero-copy views (M1) | 159.08 | 0.25 | 0.4% |
| Fused RoPE (M2) | 153.60 | 5.48 | 9.8% |
| SplashAttention (M4) | 122.51 | 31.09 | 55.4% |
Over half of the saving is the attention kernel and a third is the compiler. That matches the case study's own diagnosis: at 32,768 tokens attention dominates the step.
The levers are close to additive. The milestones were also measured alone. SplashAttention alone, in eager mode, saves \(178.61 - 149.81 = 28.80\) ms; added last on the compiled path it saves 31.09 ms. Compilation alone saves 19.28 ms. If the effects were independent, compile plus Splash plus the 5.73 ms of views and RoPE would land at about \(178.61 - 19.28 - 28.80 - 5.73 = 124.80\) ms; the measured all-four step is 122.51 ms. The levers are close to additive here, with the attention kernel worth slightly more inside a compiled block than in eager mode. Close to additive means you can estimate the value of a lever from the profile before you build it, which is the habit chapter 11 develops.
What was nearly free. Zero-copy views moved the step by 0.25 ms compiled and 0.31 ms eager. The case study keeps it anyway, because the copy it removes is real (an HBM-to-HBM copy in every attention block's backward) and the fix costs nothing. Fused RoPE gained 5.48 ms only when compiled, because its elementwise rotation fuses with the surrounding ops; in eager mode each of its extra ops is a separate program. A change that looks like a loss in eager mode can be a win compiled. Measure in the mode you will deploy.
The answer depends on the sequence length. The case study adds that at a sequence length of 640, compilation alone is about 3x faster, and the attention kernel matters less. Short sequences make each op small, so dispatch and HBM round trips between ops are most of the step, which is exactly what compilation removes. Long sequences make attention's \(O(S^2)\) traffic dominant, which is what a tiled kernel removes. The Diffusers pair above fits the same pattern: the image pipeline gained 2.29x from compiling, the much longer video sequence 1.39x.
Kernels need tuning. With the default 512-token blocks, SplashAttention was about 10% slower than standard SDPA under compilation at this sequence length, and float32 inputs were slower still; the measured win needed 2048-token blocks and bf16. Profile, try a few block sizes, and only then reach for a custom kernel (chapter 12).
The case study's introduction states 1.48x; its table gives 178.61 to 122.51 ms, 1.46x, which is the figure used here.
The lessons the case study draws generalize to most ports: avoid hidden layout copies, store less and compute more for positional embeddings, compile the whole block, and reach for a custom kernel only for the memory-bound op that dominates. In porting terms: get the model right first, compile it, then let the profile pick the next lever.
Failure modes and how to diagnose them¶
Most port failures announce themselves with a specific symptom. The table maps each to its cause, the tool that confirms it, and the fix.
| Symptom | Likely cause | Confirm with | Fix |
|---|---|---|---|
RuntimeError calling torch.tpu.device_count() or another torch.tpu device function |
On PyTorch 2.11 and later those are internal | The error message | torch.accelerator.* (chapter 3) |
Tensors stay on cpu; no tpu device |
TorchTPU not installed in this Python, or TORCH_DEVICE_BACKEND_AUTOLOAD=0 |
preflight.py (chapter 8) |
Activate the right environment; unset the variable |
ValueError from from_pretrained(..., device_map="tpu") asking for accelerate |
transformers 5.16.1 needs it for device_map |
The message | pip install accelerate |
NotImplementedError from torch.compile |
dynamic=True |
port_checklist.py (compile-dynamic-true) |
dynamic=False, or dynamic=None for bounded dynamism |
| Error raised far from the line that caused it | Deferred execution reports errors at the next materialization point | Rerun with TORCH_TPU_LAUNCH_BLOCKING=1 (Debug mode) and TORCH_SHOW_CPP_STACKTRACES=1 |
Fix the op the synchronous run points at |
| Wrong values with no error, after indexing | Out-of-bounds indices are not checked by default | TORCH_TPU_ENABLE_DEBUG_CHECKS=1 raises, for example take(): expected indices to be in range |
Fix the index computation |
| Parity fails with many small differences | bf16 or one-pass MXU precision compared against float32 | Compare like with like; read assert_close's mismatch count |
Same dtype on both sides, or Precision.HIGHEST for the check (chapter 6) |
| Parity fails with a few large differences | A logic bug in the port (a cast, a scale, a transposed weight) | The index assert_close reports |
Fix the bug; the gate is working |
| Every step slow, compiles keep happening | A shape changes each step: a growing torch.cat, a growing mask, a DynamicCache |
Counting backend; TORCH_LOGS="recompiles" |
Static cache with an explicit mask and cache_position, or buckets (chapter 7) |
| A static cache still recompiles every decode step | StaticSlidingWindowLayer's Python int length, or a mask rebuilt from the cache length |
type(layer).__name__ per cache layer; TORCH_LOGS="recompiles" |
Swap the layer when the window covers the cache; pass the mask and position_ids |
| A Diffusers pipeline recompiles every denoising step | A view passed into the compiled transformer | TORCH_LOGS="recompiles" |
Pass a contiguous tensor (clone it), as the SD3 pipeline does for the timestep |
| A compile on the first call at each new image size | Expected: one program per shape | Per-call times | Warm each size you serve |
from_pretrained raises on experts_implementation |
The name was not registered first | The message | ALL_EXPERTS_FUNCTIONS.register(name, fn) before loading |
The Hub MoE kernel raises NotImplementedError |
Experts with bias, or a gate other than SiLU or GELU-tanh | The message | Use the default experts for that model |
| MoE decode barely faster at batch 64 than at batch 1 | The gather path copies one weight slab per token-expert pair | moe_decode_weight_bytes() for your shapes |
The Kernels Hub ragged-dot kernel |
| HBM full before the weights finish loading | max_cache_len far above need, or the model is larger than one device |
HBM size times devices against weights plus cache | Smaller max_cache_len; TP, or offload with compile_repeated_blocks |
| TP load refused | TP degree does not divide the heads, device_map also set, weights not safetensors, or torch.distributed not initialized |
The message; check_tp_plan() in diffusers_tp.py |
Fix the stated requirement |
diffusers has no TensorParallelConfig |
Diffusers 0.37 or older | import diffusers; diffusers.__version__ |
Install a current release |
| DataLoader workers fail to open the TPU | Forked workers try to reacquire the libtpu lockfile |
port_checklist.py (dataloader-workers) |
num_workers=0 |
| Correct, compile count flat, still slower than the baseline | Host syncs, or the step's time sits in one op | port_checklist.py, then an XProf trace |
Remove syncs (chapter 4); profile (chapter 10) and apply the playbook (chapter 11) |
The last row is where this chapter hands off. A port that is correct, compiles once and is still slow is no longer a porting problem; it is a profiling problem, and Part III starts there.
Verifying the result¶
A port is done when the source scans clean and three pieces of evidence agree, recorded for your TorchTPU version and machine type:
# Anywhere (laptop, CI): the scanner, the gates and the Hugging Face logic.
python code/ch09_porting/port_checklist.py --cpu-smoke # ends "cpu-smoke: OK"
python code/ch09_porting/port_model.py --cpu-smoke # ends "PORT CHECK: PASS"
python code/ch09_porting/hf_generate.py --cpu-smoke # "cpu-smoke: OK" (SKIPPED without transformers)
pytest tests/ch09 -q
- The source is clean.
port_checklist.py --stricton your model directory reports no errors or warnings, or only lines you reviewed and marked# port: ok. - Parity against a CPU reference. Outputs and gradients match a CPU run of the same weights and inputs, compared like with like: float32 under
Precision.HIGHESTagainst float32 with float32 tolerances, or bf16 against bf16 with bf16 tolerances. For a Hugging Face model, compare one forward's logits in the same dtype on both sides; greedy top-1 agreement is the number that matters for generation, with rare flips only where the top two logits are within rounding. The gate must also fail on a deliberately broken copy, or it proves nothing. - No recompiles after warm-up. A counting backend stops growing after the first steps, and the remaining steps run under
torch.compiler.set_stance("fail_on_recompile")without raising. For generation, the compile count matches your prediction: one for a static-cache decode loop underdynamic=False. On a TPU, compare that count with the number of slow steps; extra slow steps mean compiles inside the backend, and per-step time is what to trust (chapter 7). - Step time against a baseline. The warm median step time, measured after warm-up with a synchronize before each clock read, beats the baseline you chose: the eager step on the same TPU, or the GPU step you are replacing. Record the baseline's source with the number. Never judge speed from the first steps of a new process: they compile.
port_model.py --json port_report.json on a TPU VM writes all three for the example block. For your own model, keep the same three numbers in a test that runs on every change.
Worked problems¶
Problem 1. Port this loop. List every line you change and why, in checklist order.
model = Net().cuda()
step = torch.compile(model)
for x, y in DataLoader(ds, batch_size=32, num_workers=8):
x, y = x.cuda(), y.cuda()
loss = F.cross_entropy(step(x), y)
loss.backward(); opt.step(); opt.zero_grad()
print(loss.item())
torch.cuda.synchronize()
Answer
device = torch.device("tpu")
model = Net().to(device) # 1 device
step = torch.compile(model, backend="tpu") # 3 compile with the TPU backend
for i, (x, y) in enumerate(DataLoader(ds, batch_size=32, num_workers=0, drop_last=True)):
x, y = x.to(device), y.to(device) # 1 device
loss = F.cross_entropy(step(x), y)
loss.backward(); opt.step(); opt.zero_grad()
if i % 50 == 0:
print(loss.item()) # 4 a periodic sync, not every step
torch.accelerator.synchronize() # 1 torch.cuda -> torch.accelerator
Device: .cuda() and torch.cuda.synchronize() become torch.device("tpu") and torch.accelerator.synchronize(). Compile: without backend="tpu", torch.compile uses Inductor. Host syncs: .item() every step makes the host wait for the TPU every iteration; read it every N steps. Shapes: drop_last=True keeps the last, smaller batch from compiling a second program. Processes: num_workers=8 forks workers that try to reacquire the libtpu lockfile; use 0. Then run the parity check before trusting the loss curve.
Problem 2. You load Qwen/Qwen3.5-9B with device_map="tpu" and call model.generate(**inputs, max_new_tokens=64). Generation is slow and the first and twentieth tokens take about the same time. Is decode compiled? Change one argument to compile it, and say what compiles and what does not.
Answer
It is not compiled. generate() compiles decode only when the device type is in its list (tpu is), the cache is compileable, and the cache is not a plain DynamicCache; the default cache is a DynamicCache, so it runs eagerly, as Hugging Face's post says. Pass cache_implementation="static": generate() then allocates a StaticCache sized to the final length and compiles the one-token decode step with CompileConfig(backend="tpu", dynamic=False, mode="default"). Prefill stays eager, because its prompt length changes per request. Expect one slow first call (the decode compile) and fast later calls with the same max_new_tokens.
Problem 3. You need to generate with batch 32 and max_cache_len=8192 on the Qwen3-30B-A3B-shaped model from the chapter, in bf16. How much HBM does the static cache reserve, and what would you change if it does not fit next to the weights?
Answer
Per token: \(2 \times 4 \times 128 \times 2 = 2048\) bytes per layer, times 48 layers = 96 KiB. Slots: \(32 \times 8192 = 262{,}144\), the same as the chapter's batch 64 at 4096, so 24 GiB, reserved at the first step whatever you generate. A v6e chip has 32 GiB of HBM, so that leaves nothing for the weights: 30B parameters in bf16 are about 61 GB, which already exceeds 32 GiB before any cache is added, so this model does not fit on one v6e chip at all. First set max_cache_len to the real prompt plus generation budget rather than the context window; if prompts really are that long, the model needs more than one device (tensor parallelism), and the cache is then split across devices too.
Problem 4. You want to shard QwenImage21Transformer2DModel (32 heads by default) on a host with 6 usable chips. Which TP degrees work, what launch commands do you use, and what must be true before from_pretrained reads a file?
Answer
The TP degree must divide the head count: 1, 2, 4 or 8 divide 32, and 6 does not, so use 4 of the 6 chips (or 2), and check num_attention_heads in the checkpoint's transformer/config.json first. Launch one process per chip: eval $(python3 -m torch.tpu.distributed | sed 's/^/export /'), then torchrun --nproc_per_node=4 qwen_image_tp.py (restrict visibility with TPU_VISIBLE_DEVICES if needed). Before loading, each rank must have called dist.init_process_group(backend="tpu_dist") and built the DeviceMesh, must not pass device_map, needs safetensors weights and low_cpu_mem_usage left on, and needs a Diffusers release newer than 0.37. Save the image on rank 0 only.
Problem 5. Using the FLUX case study, decide which single milestone you would implement first if you could do only one, for a training run at sequence length 32,768, and for one at 640. Justify both.
Answer
At 32,768: SplashAttention. Alone, in eager mode, it gives the largest single gain in the table (178.61 to 149.81 ms, 1.19x, 28.80 ms), more than compiling alone (19.28 ms, 1.12x), because attention dominates the step at that length. The caveat is cost: it is a Pallas kernel that needed tuning (2048-token blocks and bf16; the default blocks were about 10% slower than SDPA compiled), while compiling is one line. If engineering time is the constraint, compile first and measure. At 640: compilation. The case study states compilation is about 3x faster at that length and the attention kernel matters less, because small ops make dispatch and HBM round trips the dominant cost. The case study's text, not its table, gives the 640-token result (compilation about 3x faster).
Problem 6. After porting a Qwen3-MoE model, decode throughput at batch 64 is only 1.5 times that at batch 1. The compile count is flat after warm-up and parity passes. Diagnose the likely cause from the chapter, and say what evidence would confirm it before you change anything.
Answer
The port is correct and not recompiling, so this is a performance problem in the MoE layers. During decode on a non-CPU device, generate() switches "grouped_mm" to "batched_mm", which materializes one weight slab per token-expert pair: at batch 64 with top-8 routing that is 512 slabs per layer against about 126 distinct active experts, so expert weight traffic grows almost linearly with batch while a grouped read would flatten. moe_decode_weight_bytes() predicts 4.83 GB against 1.19 GB per layer per step for this shape. Confirm with an XProf trace (chapter 10): the MoE layers should dominate decode time with gather and copy ops, and their share should grow with batch. Then register the Kernels Hub ragged-dot kernel with experts_implementation="tokamax_ragged_dot", rerun the parity check, and measure batch 1 and batch 64 again; the published gain is small at batch 1 and large at batch 64.
Quick questions¶
- Name the six checklist items in order and, for each, the observable result that says it is done.
- Why does the chapter run in Strict eager mode before compiling, and what does a mismatch that appears only after compiling tell you?
- Which three conditions make
generate()compile its decode step, and which one does the default call fail? - What does a
StaticCachekeep on the device that a Python integer would turn into a guard, and what is the price of the static cache? - Give two reasons a "static" cache can still recompile every step.
- Why does the Kernels Hub MoE kernel gain little at batch 1 and much at batch 64?
- What is the difference between
device_map="tpu"andTensorParallelConfigin where the weights end up? - Why must the TP degree divide the number of attention heads?
- In the FLUX case study, which milestone saved the most time at 32,768 tokens, and why would the answer change at 640?
- What three checks decide whether a port worked, and why must the parity gate be shown to fail on a broken copy?
Key takeaways¶
- A port is six questions in order: device, dtype and precision, eager mode first, host syncs, shapes, collectives. The first three make it right; the last three keep it fast and scalable. A static scanner finds most of the lines to change before anything runs.
- Prove a port with three checks: parity of outputs and gradients against a CPU reference compared like with like (and a gate that fails on a broken copy), a compile count that stops growing after warm-up under
fail_on_recompile, and a warm step time against a recorded baseline. - Hugging Face Transformers needs no wrapper:
device_map="tpu"loads onto the TPU, andcache_implementation="static"makesgenerate()compile decode with the"tpu"backend. The defaultDynamicCacheruns eagerly. Sizemax_cache_lento the real need; the cache is reserved up front. - Sliding-window layers, masks rebuilt from the cache length, and views passed into compiled code are the usual reasons a "static" pipeline still recompiles.
- MoE decode at large batch is weight traffic: a gather path copies one slab per token-expert pair. The Kernels Hub ragged-dot kernel reads each active expert once in one fused op, 21.5x faster at batch 64 on Qwen3-30B-A3B and about 1.1x at batch 1.
- Diffusers:
pipe.to("tpu"), then compile the transformer withbackend="tpu", fullgraph=True, dynamic=False. A model too big for one chip is sharded withTensorParallelConfigwhile it loads, one process per chip, with a TP degree that divides the head count. - The FLUX case study's 1.46x came 55% from the attention kernel and 34% from compiling at 32,768 tokens; at short sequences compiling dominates. Measure in the mode you deploy, and let the profile choose the next lever.
References¶
- Hugging Face and TorchTPU: TPUs, Natively: install,
device_map="tpu", Diffusers on TPU, the Kernels Hub MoE recipe and its benchmark, CI status - Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers: Transformers 5.16.1 compile criteria, static-cache traps, the MoE weight-traffic model, Diffusers tensor parallelism
- Sample code: TorchTPU execution modes, XProf and Pallas (sample_01)
- FLUX optimization: the four milestones, results table and measurement setup; also in the TorchTPU repository
- FLUX Performance Optimization Tutorial on Google Cloud TPUs
- TorchTPU API Reference:
torch.acceleratorreplacements fortorch.cuda, precision context, debug environment variables,splash_sdpa,jax_op - Manage numerical precision in TorchTPU: comparing like with like, the
"medium"default - TorchTPU execution model: default eager mode and Debug mode
- Get started with TorchTPU on GKE: DataLoader
num_workersand thelibtpulockfile - Introducing TorchTPU: Hugging Face model coverage figures
- Hugging Face Transformers:
generation/utils.pyandmodeling_utils.pyin release 5.16.1 - Diffusers: TPU
- tengomucho/ragged-dot-tpu: the Kernels Hub MoE kernel
- Companion code for this chapter







