Port a Hugging Face model¶
Use this guide when the model you want on TPU is a Hugging Face Transformers model (a causal LM, including Mixture-of-Experts models) or a Diffusers pipeline. TorchTPU registers itself as a native PyTorch backend with the device string "tpu", so Transformers and Diffusers run on it with no wrapper library: Hugging Face's announcement says Optimum TPU is no longer required. Chapter 9 explains why decode compiles only with a static cache, why MoE decode gains grow with batch, and how to read the FLUX case study; this page is the recipe.
Prerequisites¶
- A TPU host that passes Install TorchTPU on a TPU VM (or a GKE pod from Run TorchTPU on GKE).
- Enough HBM for the weights plus the cache you will reserve. A v6e chip has 32 GiB. A model larger than one device needs tensor parallelism (step 7), not
device_map. - For the checks: this book's
code/ch09_porting/(source).
Steps¶
1. Install the libraries¶
pip install torch_tpu==0.2.0 --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
Hugging Face's install line leaves torch-tpu unpinned; the command above pins torch_tpu==0.2.0, the version in the TorchTPU README and in Install TorchTPU on a TPU VM.
accelerate is required: in transformers 5.16.1, from_pretrained(..., device_map=...) raises a ValueError without it. transformers>=5.16.1 is the version TorchTPU's requirements pin.
Check: on a laptop, python code/ch09_porting/hf_generate.py --cpu-smoke runs the Transformers checks on tiny random models and prints cpu-smoke: OK (or cpu-smoke: SKIPPED if transformers is not installed).
2. Load onto the TPU and generate¶
import torch
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" places every module whole on the current device as it loads. It does not shard.
Check: text prints. This call runs eagerly: the default cache is a DynamicCache, and generate() does not compile with it, so the first and the twentieth token take about the same time.
3. Compile the decode step with a static cache¶
out = model.generate(**inputs, max_new_tokens=64, do_sample=False,
cache_implementation="static")
With a StaticCache on a "tpu" device, generate() compiles the one-token decode step itself with CompileConfig(backend="tpu", dynamic=False, mode="default"). Prefill stays eager.
Size the cache before you run: it reserves \(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, batch 64 at max_cache_len=4096 is 24 GiB. Set max_cache_len to the real prompt plus generation budget, not the context window.
Check: on a TPU VM, python code/ch09_porting/hf_generate.py --model Qwen/Qwen3.5-9B generates twice with the static cache and prints the time of each call: the first compiles the decode step, the second reuses it and is much faster. On a laptop the smoke run shows the compile counts this predicts:
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)
4. Check parity against a CPU reference¶
Compare one forward pass of the TPU model with a CPU copy of the same checkpoint, in the same dtype on both sides. greedy_logits_parity() in hf_generate.py returns the largest logit difference and the top-1 agreement:
import sys
sys.path.insert(0, "code/ch09_porting")
from hf_generate import greedy_logits_parity, load_causal_lm
ref, tok = load_causal_lm(model_id, device_map="cpu") # bf16 by default, like the port
port, _ = load_causal_lm(model_id, device_map="tpu")
ids = tok("The future of AI is", return_tensors="pt")["input_ids"]
with torch.no_grad():
print(greedy_logits_parity(ref, port, ids))
Check: top-1 agreement is the number that matters for greedy generation. Rare disagreements are expected only where the reference's top two logits are within rounding of each other. Parity-check a port gives the tie rule and the bounds.
5. MoE models: plug in the Kernels Hub kernel¶
For a Qwen3-MoE or Gemma 4 MoE model, register the TPU ragged_dot experts kernel before loading:
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",
)
version=1 pins the kernel's branch; trust_remote_code=[repo_id] allow-lists only this repository. The kernel loads only on a TPU VM, and it accepts gated experts without bias with a SiLU or GELU-tanh gate; anything else raises NotImplementedError. The same path is python code/ch09_porting/hf_generate.py --model Qwen/Qwen3-30B-A3B-Instruct-2507 --hub-moe-kernel.
Check: rerun step 4's parity, then measure decode at batch 1 and at a large batch. The published gain on v6e-8 is about 1.1x at batch 1 and 21.5x at batch 64 for Qwen3-30B-A3B; expect little at batch 1.
6. Diffusers on one chip¶
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]
Compile only the transformer: it runs once per denoising step. If the pipeline does not fit one chip and you have only one, use enable_model_cpu_offload() and compile the repeated blocks instead: pipe.transformer.compile_repeated_blocks(backend="tpu", fullgraph=True, dynamic=False). The companion runs the same recipe with python code/ch09_porting/diffusers_tp.py --model stabilityai/stable-diffusion-3.5-medium --one-chip.
Check: the first call compiles; later calls at the same image size are fast. A new height or width compiles once for that shape; a new num_inference_steps does not recompile.
7. Diffusers across chips: tensor parallelism¶
One process per chip. Each rank joins the process group, builds a mesh, and loads the transformer sharded with TensorParallelConfig:
import diffusers
import torch
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:
eval $(python3 -m torch.tpu.distributed | sed 's/^/export /')
torchrun --nproc_per_node=$WORLD_SIZE qwen_image_tp.py
Requirements Diffusers checks before it reads a file: torch.distributed initialized, no device_map, safetensors weights, low_cpu_mem_usage on, and a TP degree that divides the attention head count (32 for QwenImage21Transformer2DModel, so 2, 4 or 8). TensorParallelConfig needs a Diffusers release newer than 0.37. The companion packages this path: torchrun --nproc_per_node=$WORLD_SIZE code/ch09_porting/diffusers_tp.py --model Qwen/Qwen-Image-2.1 --transformer-class QwenImage21Transformer2DModel --heads 32.
Check: rank 0 writes out.png, and python code/ch09_porting/diffusers_tp.py --cpu-smoke confirms the head-divisibility rule on a laptop.
Troubleshooting¶
| Symptom | Cause | Fix |
|---|---|---|
ValueError from from_pretrained(..., device_map="tpu") asking for accelerate |
transformers 5.16.1 needs it for device_map |
pip install accelerate |
| Generation slow, every token the same speed | Default DynamicCache runs eagerly |
cache_implementation="static" |
| A static cache still recompiles every decode step | StaticSlidingWindowLayer tracks its length in a Python int, or the mask is rebuilt from the cache length |
Print type(layer).__name__ per cache layer; pass a fixed (B, max_cache_len) mask and position_ids; find the guard with TORCH_LOGS="recompiles" |
| HBM full before the weights finish loading | max_cache_len far above need, or the model is larger than one device |
Smaller max_cache_len; tensor parallelism |
from_pretrained raises on experts_implementation |
The name was not registered first | 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 | Use the default experts for that model |
| A Diffusers pipeline recompiles every denoising step | A view passed into the compiled transformer | Pass a contiguous tensor (clone it), as the SD3 pipeline does for the timestep |
| TP load refused | TP degree does not divide the heads, device_map also set, non-safetensors weights, or no process group |
Fix the stated requirement |
diffusers has no TensorParallelConfig |
Diffusers 0.37 or older | Install a current release |
| Parity fails with many small differences | bf16 compared with float32 | Same dtype on both sides |
References¶
- Hugging Face and TorchTPU: TPUs, Natively
- Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers
- TorchTPU docs: API Reference
- Diffusers: TPU
- Hugging Face Kernels Hub: tengomucho/ragged-dot-tpu
- Companion code: code/ch09_porting/
- Chapter 9: Porting a model, including Hugging Face Transformers and Diffusers