DEV Community

Cover image for Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers
Omotayo Aina for Google Developer Experts

Posted on Edited on

Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers

device_map="tpu" gets you running. StaticCache, a Kernels Hub MoE kernel and TensorParallelConfig get you fast, and this post shows why each one changes the numbers.

Series: A five-part, hands-on series for PyTorch engineers moving real workloads onto Cloud TPU v6e (Trillium) and v7x (Ironwood) with TorchTPU. Part 1 builds the mental model (execution modes, memory, profiling, kernels). Part 2 runs Hugging Face Transformers v5 and Diffusers natively. Part 3 serves models in production with vLLM-TorchTPU, SGLang-TorchTPU and llm-d. Part 4 trains and post-trains at pod scale with TorchTitan, Ray and GRPO. Part 5 hands the whole workflow to the TPU Agent Suite.

This is Part 2. Previous: Part 1: TorchTPU Performance: Execution Modes, XProf and Pallas Kernels. Next: Part 3: vLLM and SGLang on TPU: Production Serving with llm-d 1.0, Part 4: TorchTitan on Cloud TPU: SimpleFSDP, Graph Trainer, Ray and GRPO, Part 5: TPU Agent Suite: Onboard, Profile and Tune PyTorch on Cloud TPU.

The problem: it loads, it generates, and then it crawls

You have a working Hugging Face script. On a TPU VM you change one argument, device_map="tpu", and it runs on the first try. Then three things happen that the GPU version never showed you.

The first generate() call sits for tens of seconds per step before it settles. Your Mixture-of-Experts model decodes at batch 1 about as fast as you expected, but at batch 64 it barely beats batch 1. And the diffusion transformer you wanted to try does not fit in one chip's HBM at all.

None of these are bugs, and none of them need a fork of the model. Each one has a specific cause you can read in the Transformers and Diffusers source, and a specific fix that is one or two lines long: a preallocated StaticCache, a Tokamax ragged-dot kernel from the Hugging Face Kernels Hub, and a TensorParallelConfig that shards the transformer as it loads.

Part 1 built the mental model this post depends on: every new tensor shape is a new XLA program, views can cost copies, and a 0-D device tensor is the way to keep a changing value out of Dynamo's guards. Here we apply that model to real Hugging Face workloads and then analyze the published TPU numbers to see exactly where the speed comes from.

All code is in code/sample_01_torchtpu_execution_xprof_and_pallas.py, in a clearly marked section named "Part 2: Hugging Face on TorchTPU", with CPU tests in tests/test_sample_01_hf.py. Every Transformers, Diffusers and Kernels API below was checked against transformers 5.16.1 (the version TorchTPU's own requirements pin), diffusers 0.43.0 and kernels 0.19.1.

What you'll be able to do

By the end you should be able to:

  • Explain why Transformers, Diffusers and Kernels need no TPU wrapper library, and what generate() does differently when the model lives on a "tpu" device.
  • Compare DynamicCache and StaticCache under torch.compile, and predict how many compilations each one costs before you run it.
  • Configure a Kernels Hub MoE kernel through ALL_EXPERTS_FUNCTIONS and experts_implementation, and analyze why its speedup is 1.1x at batch 1 and 21.5x at batch 64.
  • Diagnose the three things that quietly break a static cache: sliding-window layers, models that rebuild masks from the cache length, and views passed into compiled code.
  • Deploy a Diffusers pipeline eagerly, then compiled, then sharded across chips with TensorParallelConfig.
  • Decide which of these tools a given model and batch size actually needs.

Setup

TorchTPU installs from PyPI. The extra index matters: it gives you the CPU build of torch, so pip does not pull the multi-gigabyte CUDA build onto a TPU VM, which has no use for it.

pip install torch-tpu --extra-index-url https://download.pytorch.org/whl/cpu
# Hugging Face libraries. accelerate is needed for device_map in transformers 5.16.1.
pip install "transformers>=5.16.1" accelerate diffusers kernels \
  --extra-index-url https://download.pytorch.org/whl/cpu
Enter fullscreen mode Exit fullscreen mode

Once installed, import torch loads TorchTPU automatically and registers the "tpu" device. You only need an explicit import torch_tpu if you turned backend autoloading off with TORCH_DEVICE_BACKEND_AUTOLOAD=0. The accelerate line is not decoration: in transformers 5.16.1, from_pretrained(..., device_map=...) raises a ValueError asking for it, which is how I found out while writing the tests. Diffusers added TensorParallelConfig after 0.37 (TorchTPU's pinned version), so install a current release if you want the multi-chip section.

To follow along on a laptop:

git clone https://github.com/ainaomotayo/torchtpu-sprint-26h4
cd torchtpu-sprint-26h4
python code/sample_01_torchtpu_execution_xprof_and_pallas.py --hf-cpu-smoke   # CPU, no download
python -m pytest tests/test_sample_01_hf.py -q

# On a TPU VM
python code/sample_01_torchtpu_execution_xprof_and_pallas.py --hf-generate Qwen/Qwen3.5-9B
Enter fullscreen mode Exit fullscreen mode

The CPU paths build tiny randomly initialised models from a config, so nothing is downloaded. Tests that need transformers skip cleanly when it is not installed.

Part A: Why there is no wrapper anymore

Until TorchTPU, PyTorch on TPU meant PyTorch/XLA, lazy tensors, and for Hugging Face users the Optimum TPU library on top. Hugging Face's own announcement is blunt about what changed: now that TorchTPU brings native support, Optimum TPU is not required anymore to run Hugging Face models with Transformers and Diffusers.

The reason is architectural. TorchTPU extends the PyTorch dispatcher with a new C++ backend registered as PrivateUse1, the slot PyTorch reserves for out-of-tree devices, and gives it the device string "tpu". Transformers, Diffusers and Kernels only ever call ordinary PyTorch ops. When those ops receive "tpu" tensors, the dispatcher routes them to TorchTPU. There is nothing in between to keep in sync with library releases.

Layered stack diagram: Transformers v5, Diffusers and Kernels call the PyTorch dispatcher, which routes the tpu device through PrivateUse1 to the TorchTPU backend and the TPU chip

Notice there is no box between the libraries and the dispatcher. That missing layer is why a new Transformers release does not need a new TPU release.

The libraries do know about TPUs, in small, specific places. Reading transformers 5.16.1, I found four:

Where What it does on "tpu"
utils/import_utils.py, is_torch_tpu_available() finds the torch_tpu package and checks torch.tpu.is_available()
generation/utils.py, _valid_auto_compile_criteria() "tpu" is one of the device types where generate() may compile decode
modeling_utils.py, _default_compile_config() on "tpu", returns CompileConfig(backend="tpu", dynamic=False, mode="default") instead of Inductor
distributed/utils.py maps the "tpu" device type to the "tpu_dist" process group backend

Diffusers has the same kind of small touch points: "tpu" is in its list of tensor-parallel devices, and the Stable Diffusion 3 pipeline clones the timestep on TPU because, in the source's words, a view into timesteps makes torch.compile recompile every step. That is Part 1's "views as compiled-function arguments" rule, fixed upstream. We will meet it again in Part E.

How much of the Hub actually runs

Google's TorchTPU launch post describes a continuous test pipeline over a stratified corpus of Hugging Face models, in eager and compiled modes. Phase 1 checks that a model instantiates, runs eagerly and compiles to StableHLO without crashing. Phase 2 checks numerics against a baseline: perplexity within 0.10 relative for causal LLMs, and a relative MSE threshold for vision, audio and encoder models.

Horizontal bar chart: Transformers test suite on TPU 96.5 percent, Tier 1 popular models 98.0 percent (4,821 of 4,917), Tier 2 architectures numerical parity 97.1 percent (638 of 657), causal LLMs with bounded dynamism 99.4 percent (834 of 839)

Read the bars as different questions: "does it run" (Tier 1), "does it match a GPU" (Tier 2), and "does the library's own test suite pass" (the amber bar, still a work in progress).

Metric (source) Result
Validated corpus (Google) 4,917 models, 500+ architecture families
Tier 1, popular models, run without crash (Google) 98%, 4,821 of 4,917
Tier 2, one model per family, numerical parity vs GPU (Google) 97%, 638 of 657
Causal LLMs with bounded dynamism, correct numerics (Google) 99%, 834 of 839
Transformers test suite on TPU, tests passing (Hugging Face) 96.5%

Hugging Face is candid that their side is not all green yet. They turn each failure into a small repro and a TorchTPU issue: 34 reported, 19 fixed at the time of their post. Running on TPU also caught bugs in Transformers itself, in StaticCache and in the Qwen3 tensor-parallel plans, both fixed upstream. That is one more reason to pin transformers>=5.16.1 rather than an older v5 release.

Part B: Transformers v5 with device_map="tpu"

Here is the whole port, from Hugging Face's post:

from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "Qwen/Qwen3.5-9B"
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="tpu",  # loads the model directly on the 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))
Enter fullscreen mode Exit fullscreen mode

The sample wraps the loading half as load_hf_causal_lm_on_tpu(). It defaults to device_map="tpu" on a TPU and "cpu" elsewhere, and passes experts_implementation through for the MoE section:

model, tokenizer = load_hf_causal_lm_on_tpu(
    "Qwen/Qwen3.5-9B", dtype=torch.bfloat16, experts_implementation=None)
Enter fullscreen mode Exit fullscreen mode

Before you run the plain generate() above, predict: is it compiled? Read _valid_auto_compile_criteria() and the answer is no. generate() compiles the decode step 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 above runs in eager mode, which is exactly what Hugging Face's post says ("The model runs in eager mode by default").

Change one argument and the picture flips:

# code/sample_01_torchtpu_execution_xprof_and_pallas.py, generate_with_static_cache()
out = model.generate(input_ids, max_new_tokens=64, do_sample=False,
                     cache_implementation="static")
Enter fullscreen mode Exit fullscreen mode

With cache_implementation="static", generate() allocates a StaticCache sized to the final length. Because the model sits on "tpu", the compile criteria now pass, and get_compiled_call() builds torch.compile(self.__call__, backend="tpu", dynamic=False, mode="default") from _default_compile_config(). Prefill still runs through the uncompiled call. Only the decode loop uses the compiled one.

Flow diagram: input_ids on the host feed an eager prefill on the TPU that fills a StaticCache; a compiled decode step loops on itself with next token and writes into the same cache with index_copy_

Prefill sees a new prompt length on almost every request, so compiling it would mean a compile per length. Decode always sees one token, so it is the part worth compiling.

--hf-generate MODEL_ID in the sample runs that call twice and times both, so you can see the first call pay for compilation and the second reuse the graph. I am not printing TPU numbers for it, because I would only be inventing them.

A note on one model in the original plan for this post. The Muse Glimmer 30B case study in the TorchTPU docs uses pretrained Hugging Face weights (meta-models/Muse-Glimmer-30B), but it does not load them through AutoModelForCausalLM. It defines the decoder in plain PyTorch and copies the safetensors tensors into it, which is why it makes such a clean experiment for the next section: the same model with two cache classes and nothing else changed.

Part C: StaticCache vs DynamicCache under torch.compile

Two update() methods, side by side

Every attention layer calls past_key_values.update(k, v, layer_idx) and attends over what it returns. In transformers 5.16.1 the two layer classes do this:

# transformers/cache_utils.py, DynamicLayer.update (abridged)
self.keys = torch.cat([self.keys, key_states], dim=-2)
self.values = torch.cat([self.values, value_states], dim=-2)
return self.keys, self.values
Enter fullscreen mode Exit fullscreen mode
# transformers/cache_utils.py, StaticLayer (abridged)
def __init__(self, max_cache_len: int, **kwargs):
    self.max_cache_len = max_cache_len
    # Very important that it's a tensor here, to avoid recompiling when we
    # update it and use it to create positions
    self.cumulative_length = torch.tensor(0, dtype=int)

def update(self, key_states, value_states, *args, **kwargs):
    if not self.is_initialized:
        self.lazy_initialization(key_states, value_states)  # zeros [B, H_kv, max_cache_len, D]
    kv_length = key_states.shape[-2]
    cache_position = torch.arange(kv_length, device=self.device) + self.cumulative_length
    self.cumulative_length.add_(kv_length)
    self.keys.index_copy_(2, cache_position, key_states)
    self.values.index_copy_(2, cache_position, value_states)
    return self.keys, self.values

def get_mask_sizes(self, query_length: int):
    return self.max_cache_len, 0   # the mask always spans the whole buffer
Enter fullscreen mode Exit fullscreen mode

The comment on cumulative_length is the whole story, and it is the same three rules as Part 1's StaticCacheAutoregressiveDecoder:

Rule Part 1 sample Transformers StaticLayer
Preallocate k_cache, v_cache buffers (L, B, H, max_cache_len, D) keys, values zeros [B, H_kv, max_cache_len, D] per layer, allocated on first update
Keep the length on the device cache_len, 0-D int64 buffer cumulative_length, 0-D tensor moved to the cache device
Write in place index_copy_(2, positions, k) index_copy_(2, cache_position, key_states)
Hide unwritten slots mask compares slot_ids to positions get_mask_sizes() returns max_cache_len; the model's mask hides future slots

StaticLayer adds one thing the toy decoder does not: torch._dynamo.mark_static_address() on the buffers and the counter, so the compiled graph treats them as fixed addresses that are mutated in place.

Why one recompiles and the other does not

Under torch.compile(dynamic=False), Dynamo installs guards on the sizes of every tensor the graph reads. DynamicLayer replaces self.keys with a tensor one slot longer each step, so the size guard fails on every decode step and Dynamo traces and compiles again. StaticLayer returns the same [B, H_kv, max_cache_len, D] tensor every step. What changes is the value of cumulative_length, and a tensor's value is not guarded. Only its shape, dtype and device are.

Animation: a DynamicLayer cache grows by one slot per decode step and its shape guard fails every step while its compile counter climbs; a StaticLayer buffer of 20 slots fills one slot per step under a moving cumulative_length index, its guard passes and its compile counter stays at 1

Watch the two guard lines. The top one asks about a size that just changed. The bottom one asks about a size that never will, while the green index slides underneath it.

Predict, then check

Take a 2-layer Llama, a prompt of 8 tokens, and 12 generated tokens: one eager prefill plus 11 compiled single-token decode calls, exactly the split generate() uses. How many compilations for each of these three setups?

  1. StaticCache, dynamic=False
  2. DynamicCache, dynamic=False
  3. DynamicCache, dynamic=None (automatic dynamic shapes)

Write your answers down, then run count_hf_decode_compilations(). It counts frames with the same CompileCounter backend Part 1 used, wrapping "tpu" on a TPU and "eager" elsewhere, since Dynamo's guards behave identically either way. The core of it:

kv = StaticCache(config=model.config, max_cache_len=prompt_len + decode_steps)
model(input_ids=input_ids, past_key_values=kv, use_cache=True)          # eager prefill

def decode_step(tok, cache_position, attention_mask):
  return model(input_ids=tok, past_key_values=kv, cache_position=cache_position,
               position_ids=cache_position[None].expand(tok.shape[0], -1),
               attention_mask=attention_mask, use_cache=True).logits

step = torch.compile(decode_step, backend=counter, dynamic=False)
# One contiguous position tensor per step, preallocated: not arange(...)[i],
# because a view passed into a compiled function costs an eager copy on TPU.
positions = [torch.tensor([p], device=device) for p in range(prompt_len, total)]
full_mask = torch.ones(batch, total, dtype=torch.long, device=device)
Enter fullscreen mode Exit fullscreen mode

The real output from --hf-cpu-smoke:

generate(): StaticCache tokens == DynamicCache tokens: True
static  cache, dynamic=False: 11 decode calls -> 1 compilation(s)
dynamic cache, dynamic=False: 11 decode calls -> 11 compilation(s)
dynamic cache, dynamic=None : 11 decode calls -> 2 compilation(s)
Enter fullscreen mode Exit fullscreen mode

One compile for the static cache, because the prefill was never compiled. One compile per call for the growing cache. Two for automatic dynamic shapes: the first call compiles static shapes, the second sees a different length and recompiles with the cache length marked dynamic. tests/test_sample_01_hf.py asserts these counts and also checks that all three paths produce exactly the same greedy tokens as model.generate().

What the same choice costs on a real TPU

The CPU counts tell you how many compilations happen. The Muse Glimmer 30B case study in the TorchTPU docs tells you what they cost: the full 52-layer model on a single TPU v7x chip, 20 decode steps, empty compilation cache, StaticCache compiled with dynamic=False against DynamicCache compiled with dynamic=None.

Line chart on a log scale: StaticCache prefill 21.0 s and decode step 1 19.8 s, then about 23.5 ms from step 2; DynamicCache prefill 18.3 s, step 1 20.0 s, step 2 22.0 s, step 3 4.9 s, then about 24 ms from step 4

Both lines end in the same place. The difference is how long they take to get there, and the log scale is the only way to see both the 20-second compiles and the 23-millisecond steps on one chart.

Metric StaticCache (dynamic=False) DynamicCache (dynamic=None)
Prefill (ms) 21,024.81 18,256.18
Decode step 1 (ms) 19,756.86 19,969.41
Decode step 2 (ms) 24.66 21,985.62
Decode step 3 (ms) 24.29 4,908.23
Average decode, warmed up (ms) 23.58 (steps 2 to 20) 24.17 (steps 4 to 20)

Now analyze it. Prefill and step 1 cost about 20 s each on both sides: those are the two static compilations (prompt length, then length 1) that any setup pays once. The dynamic side then pays roughly 27 s more, on steps 2 and 3, while Dynamo marks the cache length dynamic and TorchTPU compiles a bounded program. After that the dynamic program is 0.59 ms slower per token, 2.5%, because it is sized for the bucket's upper bound rather than the exact shapes. Over 20 tokens that is noise. Over a million tokens in a serving loop it is a real 2.5%, and the 27 s of extra warmup happens again in every new process, because the docs note that bounded-dynamic executables are not yet serialized to the persistent AOTAutogradCache.

So the static cache wins twice: less warmup and a slightly faster steady state. It costs one thing, memory, and that is the trade-off worth computing before you set max_cache_len.

The price of preallocation

A StaticCache holds 2 (K and V) x layers x B x H_kv x max_cache_len x D x bytes from the first step. For a Qwen3-30B-A3B-shaped model (the config in TorchTPU's perflab: 48 layers, 4 KV heads, head dim 128) in bf16, one token costs 2 x 4 x 128 x 2 B = 2 KiB per layer, 96 KiB across 48 layers. At batch 64 and max_cache_len=4096 that is 262,144 slots, or exactly 24 GiB, reserved whether you generate 10 tokens or 4,000. On a v6e chip with 32 GiB of HBM, that leaves nothing for the weights. Size max_cache_len to your real prompt plus generation budget, not to the model's context window.

Three ways a "static" cache still recompiles

TorchTPU's perflab decode benchmark (perflab/steps/decode.py) has to run thousands of Hub models through a static cache, and its comments document the traps better than any guide I have read:

  1. Sliding-window layers keep a Python int. StaticSlidingWindowLayer tracks cumulative_length_int, a Python int, to avoid data-dependent control flow. Dynamo guards on Python ints, so every decode step recompiles. Perflab's _drop_unreachable_sliding_windows() swaps such a layer for a plain StaticLayer whenever the window covers the whole cache (window >= max_cache_len), because then it never rolls. If your model mixes sliding and full attention (Gemma 4 does, with a 1,024-token window in perflab's config), check which layer classes your cache actually built.
  2. Some models rebuild masks from the cache length. Without an explicit attention_mask and position_ids, models such as OPT derive them from past_key_values.get_seq_length(), which a StaticLayer returns as a tensor. Using it as a slice bound graph-breaks and the mask grows every step. Pass a fixed (B, max_cache_len) mask and position_ids == cache_position, exactly as count_hf_decode_compilations() does.
  3. Some architectures cannot use it at all. Perflab falls back to DynamicCache for ALiBi models such as Bloom (fixed-length bias shapes) and for pure recurrent or SSM models (Mamba, RWKV, xLSTM), where there is no attention KV cache to preallocate.

If you still see recompiles, Part 1's tools apply unchanged: count frames with a counting backend, then look for the guard that failed with TORCH_LOGS=recompiles.

Part D: 21.5x faster MoE decode with a Kernels Hub kernel

Why MoE decode is hard on any accelerator

In an MoE layer a router picks the top-k experts for every token. Qwen3-30B-A3B (in the perflab config of its Coder sibling, which shares the MoE shapes) has 128 experts and activates 8 per token. Gemma 4 26B-A4B also has 128 experts with 8 active. Which experts get work, and how much, is decided by the data at run time. An accelerator wants the opposite: large, regular matrix multiplies with shapes known at compile time.

Transformers 5.16.1 ships three ways to run the experts, selected by experts_implementation:

Implementation What it does Cost at decode on TPU
"eager" Python loop over experts that received tokens, found with .nonzero() data-dependent shapes and a device-to-host sync per layer (Part 1, Part F)
"grouped_mm" (the default when it can dispatch) sort (token, expert) pairs by expert, one grouped matmul via torch.nn.functional.grouped_mm reads each active expert's weights once
"batched_mm" index gate_up_proj[expert_ids] per pair, then a batched matmul materializes one weight slab per (token, expert) pair, duplicates included

There is a twist in generate(). _optimize_model_for_decode() swaps every "grouped_mm" for "batched_mm" during decode on any non-CPU device, on the grounds that it is faster for small inputs. So depending on whether you call generate() or your own loop, your MoE baseline on TPU is one of these two. The Hub kernel's README measures against "transformers' default grouped_mm".

What the Hub kernel actually is

The kernel is tengomucho/ragged-dot-tpu on the Hugging Face Kernels Hub. Its v1 source is short enough to read in full, and it answers the questions the benchmark leaves open:

  • It is built on Tokamax's Pallas grouped matmul, tokamax.ragged_dot_general(..., implementation="mosaic_tpu_v2"). The comment explains the choice: v2 has a VMEM-aware tiling heuristic, while v1 only has tuned tiles for TPU7x.
  • It is wrapped with TorchTPU's jax_op, the same bridge Part 1 used for the fused RMSNorm kernel. JAX runs only at trace time.
  • The whole experts forward (sort by expert, both grouped matmuls, the gate activation, routing weights, un-sort and sum) is one JAX function, so "torch_tpu runs a single compiled op per layer instead of dispatching ~20 small ones".
  • It contracts against HF's stored [num_experts, out_features, in_features] layout directly, so no transposed weight copy is ever made.
  • Under expert parallelism, pairs routed to another rank carry a sentinel expert id, sort to the end, and fall outside every group, so their rows are never computed.
  • It un-sorts with a gather by the inverse permutation rather than a scatter-add, because, per the source, XLA's scatter-add on TPU returns wrong rows for some shapes (512 x 2816 fp32, Gemma 4's hidden size).

Left-to-right flow: get_kernel, register into ALL_EXPERTS_FUNCTIONS, from_pretrained on the host, then the Experts layer on the TPU calls ragged_dot through jax_op

Everything left of the TPU box happens once at load time. At run time each MoE layer is one call into one compiled op.

Plugging it in

The recipe from Hugging Face's post and the kernel README, wrapped in the sample as register_tokamax_ragged_dot_experts():

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",
)
Enter fullscreen mode Exit fullscreen mode

Three details are worth knowing. trust_remote_code=[repo_id] allow-lists exactly this repository instead of trusting all remote code, which is the setting you want in production. version=1 pins the kernel's v1 branch, so a later push to the repo cannot change your numbers silently. And register() writes to a class-wide mapping, so the name works in every model you load afterwards, while from_pretrained validates it against that mapping and raises if it is missing.

The kernel imports torch_tpu, jax and tokamax at import time, 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. The sample's helper refuses to run off TPU with a clear message, which tests/test_sample_01_hf.py checks.

Testing the registration path on a laptop

You cannot run a Mosaic TPU kernel on a laptop, but you can run its algorithm. ragged_dot_experts_reference() is a pure-PyTorch twin of the kernel's experts_forward: same signature, same sort, same group sizes, same float32 activation and float32 sum, same inverse-permutation gather. register_reference_ragged_dot_experts() registers it through the exact path the Hub kernel uses:

name = register_reference_ragged_dot_experts()     # "sprint_ragged_dot_reference"
model, _ = load_hf_causal_lm_on_tpu(path, dtype=torch.float32, device_map="cpu",
                                    experts_implementation=name, load_tokenizer=False)
Enter fullscreen mode Exit fullscreen mode

The tests build a tiny Qwen3-MoE (8 experts, top-2), check the reference against "eager" and "grouped_mm" to 1e-5, and load it back through from_pretrained(experts_implementation=...). Another test compiles ragged_dot_reference() with fullgraph=True, dynamic=False and feeds it two completely different routings: one graph serves both, because group sizes are tensor values, not shapes. That is the property that lets one compiled decode step handle every routing decision.

The numbers, and why they look like this

Grouped bar chart: Qwen3-30B-A3B-Instruct-2507 decodes 1.13x faster at batch 1 and 21.5x faster at batch 64 (53 to 1131 tokens per second); gemma-4-26B-A4B-it decodes 1.07x faster at batch 1 and 12.8x at batch 64 (13 to 169 tokens per second)

The grey bars barely clear the dashed 1x line. Whatever the kernel fixes, it is something that scales with batch size.

Model (TPU v6e-8, EP over 8 cores, decode) Batch 1 Batch 64 Batch 64 throughput
Qwen3-30B-A3B-Instruct-2507 1.13x 21.5x 53 to 1,131 tok/s
gemma-4-26B-A4B-it 1.07x 12.8x 13 to 169 tok/s

These are the kernel README's numbers, also quoted in Hugging Face's post. Now the analysis. 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. The only thing left for the kernel to win is overhead: one fused op instead of about twenty. That is the 7 to 13%.

At batch 64 there are 512 pairs. A gather-based path like batched_mm materializes 512 weight slabs per layer per step. A grouped path reads each active expert once, and with 128 experts almost all of them are active at batch 64. moe_decode_weight_bytes() in the sample turns that into bytes, using the real model shapes and an expected-active-experts formula for uniform routing:

Qwen3-30B-A3B-shaped MoE layer, batch  1: batched_mm gathers  0.08 GB, grouped reads 0.08 GB (1.0x)
Qwen3-30B-A3B-shaped MoE layer, batch  8: batched_mm gathers  0.60 GB, grouped reads 0.49 GB (1.2x)
Qwen3-30B-A3B-shaped MoE layer, batch 64: batched_mm gathers  4.83 GB, grouped reads 1.19 GB (4.1x)
Enter fullscreen mode Exit fullscreen mode

Line chart of expert weight bytes per layer per decode step against batch size, log2 axis: batched_mm gather grows linearly to 4.83 GB for Qwen3-30B-A3B and 6.09 GB for Gemma 4, while grouped reads flatten near 1.19 GB and 1.50 GB, a 4.1x gap at batch 64

Solid lines keep climbing because every extra token adds 8 more gathered slabs. Dashed lines flatten because there are only 128 experts to read.

Decode is HBM-bound (Part 1's roofline put a decode GEMV at about 1 FLOP per byte), so 4x less weight traffic per layer is close to 4x less time per layer, before counting the gathered copy's write and reread, or the twenty dispatches per layer. That explains the shape of the curve: flat at batch 1, a gap that opens with batch. It does not explain all of 21.5x on its own, and I would not claim it does. Against a well-implemented grouped_mm, traffic is the same and the rest of the win is kernel quality: one fused op, tiles tuned for the MXU, no relayout of the weights. Treat the model as a way to predict where the kernel matters for your own model, not as a reproduction of the benchmark.

The routing itself is easiest to see with toy sizes:

Animation with 8 tokens and top-2 of 6 experts: first, batched_mm copies a weight slab per token-expert pair until 16 slabs have moved; then the ragged dot sorts the 16 pairs by expert, computes group sizes 4, 3, 2, 5, 0, 2, and reads the 5 active experts once each

Count the slabs in the orange counter, then in the green one. Expert E4 receives no tokens, so its group size is 0 and its weights are never read.

Part E: Diffusers, eager then compiled

TPU is a first-class device in Diffusers. For prototyping, the change is one line:

import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-medium", dtype=torch.bfloat16)
pipe.to("tpu")                     # eager mode: that's the whole change
# Deployment: compile the denoiser once.
pipe.transformer.compile(backend="tpu", fullgraph=True, dynamic=False)

pipe(prompt="warmup", height=1024, width=1024, num_inference_steps=40, guidance_scale=4.5)
image = pipe("a corgi astronaut planting a flag on a pizza moon",
             height=1024, width=1024, num_inference_steps=40, guidance_scale=4.5).images[0]
Enter fullscreen mode Exit fullscreen mode

The Diffusers TPU guide states the shape rules plainly: TorchTPU needs static shapes, so pass dynamic=False. A new height or width compiles once for that shape and is reused after that. Changing num_inference_steps does not recompile, because the step count changes how many times the compiled transformer is called, not what it is called with. SD3.5 Medium is about 15 GB in bf16, which fits on one v6e chip.

Why compile only the transformer? It is the module that runs 40 or 49 times per image, and the text encoders and VAE run once. Compiling the loop body is where the time is.

When a pipeline does not fit on one chip and you have only one, the guide's option is enable_model_cpu_offload(), which detects the "tpu" device and moves each model onto the TPU only while it runs. Its offload hooks cannot be traced, so with offload you compile the transformer's repeated blocks instead: pipe.transformer.compile_repeated_blocks(backend="tpu", fullgraph=True, dynamic=False).

What compiling buys

Hugging Face ran two large pipelines on a Cloud TPU v6e-4 with TP=4, bf16, batch 1:

Two bar charts: Qwen-Image-2.1 at 1024x1024 with 40 steps takes 8 s eager and 3.5 s compiled, 2.29x; MiniMax-H3 video plus audio at 1344x768, 5.2 s clip, 49 steps, takes 262 s eager and 188 s compiled, 1.39x

Same backend, same flag, very different payoffs. The left model is dominated by per-op overhead. The right one by work that was already big.

Pipeline (v6e-4, TP=4, bf16) Output Eager Compiled Speedup
Qwen/Qwen-Image-2.1 1024x1024 image, 40 steps 8.0 s 3.5 s 2.29x
MiniMaxAI/MiniMax-H3 1344x768, 5.2 s video + audio, 49 steps 262 s 188 s 1.39x

Why is the image model's gain larger? The sources give the numbers, not the cause, so here is the analysis Part 1 sets up. Compilation removes per-op dispatch and fuses elementwise chains so they stop round-tripping through HBM. When each op is small relative to dispatch cost, that is most of the step. A 5-second 1344x768 video plus audio produces a far longer token sequence than one 1024x1024 image, so attention and large matmuls dominate, and those were already efficient in eager mode. The FLUX case study in Part 1 measured exactly this pattern: compiling a FLUX block gained 1.12x at sequence length 32K but about 3x at 640. Expect your compile gain to shrink as your sequence grows, and look to attention kernels (Part 1's splash_sdpa) once it does.

Part F: Diffusion transformers across chips with TensorParallelConfig

The problem in numbers

The Diffusers TPU guide's example is FLUX.2-dev: its text encoder is about 48 GB and its transformer about 64 GB. A v6e chip has 32 GiB of HBM. No amount of compilation fits 64 GB into 32 GiB, and CPU offload would move tens of gigabytes per image. The answer is tensor parallelism: split each large weight across chips, and have each chip compute its share.

Colwise, rowwise, one all-reduce

Each Diffusers transformer that supports TP declares a _tp_plan that names its linear layers and how to split them. FLUX.1's, from diffusers 0.43.0 (abridged):

_tp_plan = {
    "transformer_blocks.*.attn.to_q": "colwise",
    "transformer_blocks.*.attn.to_k": "colwise",
    "transformer_blocks.*.attn.to_v": "colwise",
    "transformer_blocks.*.attn.to_out.0": "rowwise",
    "transformer_blocks.*.ff.net.0.proj": "colwise",
    "transformer_blocks.*.ff.net.2": "rowwise",
    ...
}
Enter fullscreen mode Exit fullscreen mode

QwenImage21Transformer2DModel, MiniMaxH3Transformer3DModel and Flux2Transformer2DModel ship plans in the same form. The pattern is always colwise, then rowwise. A colwise layer splits the weight's 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 splits its input features to match, so each chip produces a partial sum of the full output, and one all-reduce over ICI adds them up.

Diagram: the input enters a 4-chip group where to_q is split column-wise into four vertical slices and to_out row-wise into four horizontal slices; the partial outputs go over ICI into one all-reduce and then to the output

The only arrow that crosses chips is the one labeled ICI. Everything inside the dashed box is local work on a quarter of the weights.

Predict before you run it: if you split an MLP colwise then rowwise four ways, put an elementwise GELU between the halves, and sum the four partial outputs, does the result match the unsplit MLP exactly? tensor_parallel_linear_parity() checks it in float64:

colwise + rowwise over 4 shards, one all-reduce: max|diff| vs full matmul = 2.27e-13
Enter fullscreen mode Exit fullscreen mode

It matches, because GELU acts on each element independently, so it does not care which chip holds that element. That is also why the rule has a constraint: the TP degree must divide the number of attention heads (Diffusers checks this before loading), since heads are the unit a colwise Q/K/V split hands out. QwenImage21Transformer2DModel defaults to 32 heads in diffusers, so TP of 2, 4 or 8 divides it and 3 does not. Check the num_attention_heads in your checkpoint's transformer/config.json before you pick a degree.

Sharding while loading

TensorParallelConfig is passed to the model's from_pretrained through the parallel_config argument. The key property, in the Diffusers source comments: a tensor-parallel parallel_config makes from_pretrained shard while it reads, so each rank only ever materializes its own slice. The full model never has to fit anywhere.

Animation: eight safetensors shards stream into memory; a single chip's HBM bar overflows past 32 GiB on the way to 64 GB and turns orange, while four TP ranks each fill to 16 GB and stay well under the 32 GiB line

An illustrative 4-way split of FLUX.2-dev's roughly 64 GB transformer on v6e. The guide's own example uses all 8 chips of a host, which halves each bar again.

Diffusers enforces a few requirements before it fetches any file, and they are good to know before you debug them: torch.distributed must be initialized. device_map cannot be combined with TP (TP already places each rank's shard). Weights must be safetensors. low_cpu_mem_usage must stay on. And the TP degree must divide the head count.

Launching it on a TPU host

TP in Diffusers is one process per chip. Each rank initializes the tpu_dist process group, builds a mesh over the chips, and loads the transformer with parallel_config. The sample packages it as build_tp_diffusers_pipeline():

# code/sample_01_torchtpu_execution_xprof_and_pallas.py, build_tp_diffusers_pipeline() (core)
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)
Enter fullscreen mode Exit fullscreen mode

Compiling the sharded transformer works the same way as compiling the unsharded one. Every rank runs the pipeline call, so save the image on rank 0 only, as the Diffusers guide does with if dist.get_rank() == 0:.

Left-to-right flow: torchrun, then inside each rank tpu_dist, DeviceMesh, parallel_config and compile

Order matters: the mesh must exist before from_pretrained, because the loader needs it to decide which slice each rank reads.

Launch one process per chip. TorchTPU's distributed docs give a public command that detects the slice topology 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
Enter fullscreen mode Exit fullscreen mode

The Diffusers guide instead uses python -m torch_tpu._internal.distributed.launchers.singlehost_wrapper, and warns in the same breath that it is an internal module expected to change. Prefer the public torch.tpu.distributed entry point.

If the text encoder is also too big (FLUX.2-dev's 48 GB Mistral encoder is), shard it with Transformers' own TP on the same mesh: from_pretrained(..., distributed_config=DistributedConfig(tp_plan="auto"), device_mesh=mesh). Then only the VAE needs a plain .to("tpu").

Decision table

If you see... Use... Because...
plain generate() running eagerly on TPU cache_implementation="static" generate() only auto-compiles decode with a compileable, non-DynamicCache cache
one compile per generated token StaticCache with an explicit mask and cache_position a 0-D cumulative_length is not a guard; a growing torch.cat shape is
recompiles with a static cache on a sliding-window model check for StaticSlidingWindowLayer it tracks length in a Python int; swap it when the window covers the cache
a model with variable prompt lengths you cannot pad DynamicCache with dynamic=None two extra warmup steps, then a bounded program about 2.5% slower
HBM full before the weights load a smaller max_cache_len the cache is reserved up front: 96 KiB per token for a Qwen3-30B-A3B-shaped model
MoE decode that does not scale with batch tengomucho/ragged-dot-tpu, experts_implementation="tokamax_ragged_dot" one fused op, each active expert read once; 21.5x at batch 64 on Qwen3-30B-A3B
MoE at batch 1 default experts are fine 1.07x to 1.13x is the whole upside there
a diffusion pipeline that fits on one chip pipe.to("tpu"), then pipe.transformer.compile(backend="tpu", fullgraph=True, dynamic=False) 2.29x on Qwen-Image-2.1; new resolutions compile once each
a pipeline that does not fit, one chip only enable_model_cpu_offload() + compile_repeated_blocks() offload hooks cannot be traced; repeated blocks can
a pipeline that does not fit, several chips TensorParallelConfig(mesh=mesh) via parallel_config each rank loads only its slice; colwise + rowwise costs one all-reduce per pair

Try it yourself

  1. Break the static cache on purpose. In count_hf_decode_compilations(), pass full_mask[:, :prompt_len + i + 1] for the static cache too, so the mask grows. Predict the compile count, run it, and use TORCH_LOGS=recompiles to name the guard that failed. Then fix it again without looking at the original.
  2. Find the sliding-window trap. Build a tiny Gemma3-style config with sliding_window smaller than max_cache_len, create a StaticCache, and print type(layer).__name__ for each layer. Write a version of perflab's _drop_unreachable_sliding_windows() and show with CompileCounter that it only helps when the window covers the whole cache.
  3. Price your own MoE. Call moe_decode_weight_bytes() with the hidden_size, moe_intermediate_size, num_experts and num_experts_per_tok of an MoE you care about, and find the batch size where the gather path moves 2x the bytes of a grouped read. On a TPU VM, run --hf-generate <model> --hf-tokamax-moe at that batch and at batch 1 and check whether the kernel's gain moves where the model says it should.
  4. Shard something. Write a _tp_plan for Part 1's FluxDoubleStreamBlockOptimized (which projections are colwise, which rowwise?) and extend tensor_parallel_linear_parity() into an attention-shaped check that splits by heads.

If you build something on top of this, post it with #TorchTPUSprint.

What's next

You can now run Hugging Face models on TPU and explain every number that changed: why the static cache compiles once, why the MoE kernel's gain grows with batch, and why compiling helps an image model more than a video model. Part 3 takes the same ideas into production serving. vLLM-TorchTPU and SGLang-TorchTPU pad requests into static token buckets for the same reason StaticCache exists, run MoE kernels from the same Tokamax family at much larger scale, and add the paged KV cache, speculative decoding and disaggregated prefill that a single generate() call never needs.

Sources and further reading

Top comments (0)