Port a custom model¶
Use this guide when you have your own PyTorch model and training or inference script, written for CUDA or the CPU, and want it running on TorchTPU with evidence that the port is right and fast. It applies chapter 9's six-item checklist (device, dtype, eager mode first, host syncs, shapes, collectives) in order and ends 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. Chapter 9 explains why the order matters; chapters 4, 6 and 7 explain each item. For Hugging Face models, use Port a Hugging Face model.
Prerequisites¶
- A TPU host that passes Install TorchTPU on a TPU VM.
- This book's
code/ch09_porting/(source). The scanner needs only Python;port_model.pyneeds PyTorch.
Steps¶
1. Scan the source for porting hazards¶
python code/ch09_porting/port_checklist.py path/to/your_model/
The scanner reads the code with Python's ast module, never imports it, and reports each line a port usually has to touch, with the fix: .cuda() and "cuda" devices, torch.cuda.* calls, "nccl", CUDA_VISIBLE_DEVICES, torch.compile without backend="tpu" or with dynamic=True, host syncs in loops, if on a tensor, data-dependent shapes, tensors grown with torch.cat in a loop, num_workers > 0, and "high" / "highest" matmul precision.
Check: no error findings remain. A reviewed line can be silenced with a trailing # port: ok. The exit code is 1 when there is an error finding, 2 when a file does not parse. python code/ch09_porting/port_checklist.py --cpu-smoke shows the rules on a fixture and ends cpu-smoke: OK.
2. Apply the checklist¶
| # | Item | Change | How you know it is right |
|---|---|---|---|
| 1 | Device | torch.device("tpu") or torch.accelerator.current_accelerator(); torch.cuda.* calls become torch.accelerator.* (for example torch.accelerator.synchronize()) |
Every parameter and input reports device.type == "tpu" |
| 2 | dtype and precision | bf16 where the model allows; keep set_float32_matmul_precision at the TorchTPU default "medium" unless you need more |
Parity against a CPU run of the same dtype (step 4) |
| 3 | Eager mode first | Run in the default eager mode until outputs match; then torch.compile(..., backend="tpu") |
Same outputs eager and compiled |
| 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 |
| 5 | Shapes | Preallocated caches, padded buckets, masks instead of nonzero or boolean indexing; never dynamic=True |
The compile count stops growing after warm-up (step 5) |
| 6 | Collectives and processes | init_process_group(backend="tpu_dist"); launch with python3 -m torch.tpu.distributed then torchrun; DataLoader num_workers=0 |
All ranks finish and match an unsharded reference |
For a CUDA training loop, the result looks like chapter 9's worked problem 1:
device = torch.device("tpu")
model = Net().to(device)
step = torch.compile(model, backend="tpu")
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)
loss = F.cross_entropy(step(x), y)
loss.backward(); opt.step(); opt.zero_grad()
if i % 50 == 0:
print(loss.item())
torch.accelerator.synchronize()
drop_last=True keeps the smaller last batch from compiling a second program.
Check: rerun step 1; it reports no errors.
3. Run eagerly and make errors point at their cause¶
Run the model on the TPU without torch.compile first. If an error is raised far from the line that caused it, rerun with Debug mode and C++ stack traces:
TORCH_TPU_LAUNCH_BLOCKING=1 TORCH_SHOW_CPP_STACKTRACES=1 python your_script.py
If values are wrong with no error after indexing, TORCH_TPU_ENABLE_DEBUG_CHECKS=1 turns out-of-bounds indices into an error such as take(): expected indices to be in range.
Check: the eager run completes and its loss or output is finite.
4. Prove parity against a CPU reference¶
Run the same weights and inputs on the CPU in float32 and on the TPU in float32 under Precision.HIGHEST, and compare the output and every gradient. Comparing bf16 with float32 measures quantization, not the port. parity() in port_model.py does this for any module:
import sys
import torch
sys.path.insert(0, "code/ch09_porting")
from port_model import parity
rep = parity(model, (x,), torch.device("tpu")) # float32 assert_close tolerances by default
print(rep)
On the TPU side it runs under torch.tpu.precision(torch.tpu.Precision.HIGHEST). For a bf16 port, compare against a bf16 CPU run with bf16 tolerances instead.
Then prove the gate can fail: pass candidate= a copy of your model with one weight scaled by 1.01 (as broken_copy() does for the example block) and require the report to fail.
Check: the clean comparison passes and the broken copy fails. Many small differences point to precision; a few large ones point to a logic bug at the reported index (Parity-check a port).
5. Compile and confirm the compile count stops growing¶
Compile with a backend that counts the graphs Dynamo hands it, run a few warm-up steps, then run the rest under fail_on_recompile:
from port_model import CompileCounter
counter = CompileCounter("tpu")
forward = torch.compile(model, backend=counter, dynamic=False)
# ... run the warm-up steps with forward, then record counter.count ...
with torch.compiler.set_stance("fail_on_recompile"):
... # the remaining steps; any recompile raises RuntimeError
Check: counter.count does not move after warm-up and nothing raises. If it does, find the failing guard with TORCH_LOGS="recompiles" and fix the shape (static cache, buckets, masks). The counter sees Dynamo captures only, so on a TPU also compare per-step times: extra slow steps mean compiles inside the backend.
6. Measure the step time against a baseline¶
Synchronize before reading the clock, take the median of the steps after warm-up, and compare with a baseline: the same step in eager mode on the same TPU, or the GPU step time you are replacing. port_model.py runs all three checks on its example block and writes them as JSON:
python code/ch09_porting/port_model.py --cpu-smoke # any machine: ends "PORT CHECK: PASS"
python code/ch09_porting/port_model.py --json port_report.json # TPU VM
python code/ch09_porting/port_model.py --baseline-ms "$GPU_STEP_MS" --json port_report.json # against a GPU step time
Check: the warm median beats the baseline, and the JSON records the baseline's source. Never judge speed from the first steps of a new process: they compile. If the port is correct, compiles once and is still slower, profile it (Capture and read an XProf trace).
7. Keep the port from regressing¶
Run the scanner in CI with --strict (warnings fail too) so CUDA-only calls do not creep back in, and keep the parity, compile-count and step-time checks in a test that runs on every change.
Troubleshooting¶
| Symptom | Likely cause | Fix |
|---|---|---|
RuntimeError calling torch.tpu.device_count() |
On PyTorch 2.11 and later those torch.tpu device APIs are internal |
torch.accelerator.* |
Tensors stay on cpu; no tpu device |
TorchTPU not installed in this Python, or TORCH_DEVICE_BACKEND_AUTOLOAD=0 |
Activate the right environment; unset the variable |
NotImplementedError from torch.compile |
dynamic=True |
dynamic=False, or dynamic=None for bounded dynamism |
| Error raised far from its cause | Deferred execution reports errors at the next materialization point | TORCH_TPU_LAUNCH_BLOCKING=1 and TORCH_SHOW_CPP_STACKTRACES=1 |
| Wrong values with no error, after indexing | Out-of-bounds indices are not checked by default | TORCH_TPU_ENABLE_DEBUG_CHECKS=1 |
| Parity fails with many small differences | bf16 or one-pass MXU precision compared against float32 | Same dtype on both sides, or Precision.HIGHEST for the check |
| Parity fails with a few large differences | A logic bug (a cast, a scale, a transposed weight) | Fix it; the gate is working |
| Every step slow, compiles keep happening | A shape changes each step: a growing torch.cat, a growing mask |
Static buffers or buckets; TORCH_LOGS="recompiles" |
| Compiled code uses Inductor | torch.compile without backend="tpu" |
Pass backend="tpu" |
| DataLoader workers fail to open the TPU | Forked workers try to reacquire the libtpu lockfile |
num_workers=0 |
| Correct, compile count flat, still slower than the baseline | Host syncs, or one op dominates the step | Remove syncs; profile with XProf |
References¶
- TorchTPU docs: Manage numerical precision in TorchTPU
- TorchTPU docs: Execution model
- TorchTPU docs: Dynamic shapes
- TorchTPU docs: Get started with TorchTPU on GKE
- TorchTPU execution modes, XProf and Pallas sample code
- TorchTPU 0.2.0 docs: API Reference
- Companion code: code/ch09_porting/
- Chapter 9: Porting a model, including Hugging Face Transformers and Diffusers