If you have spent any time running PyTorch workloads on Google Cloud TPUs using torch_tpu, you have probably noticed an awkward gap in the developer experience. Most official examples either stop at a toy matrix multiplication or assume you already have a dedicated multi-host TPU Cloud VM wired up to a standalone TensorBoard server.
Meanwhile, what a working PyTorch developer actually wants is simple: spin up an LLM on a free Google Colab TPU (v5e-1 with 16 GiB HBM), see why torch.compile(backend="tpu") suddenly freezes for twenty seconds mid-generation, try a real custom Pallas kernel from PyTorch without fighting obscure binding errors, and inspect what the TPU spent its cycles on without installing TensorFlow into a PyTorch environment.
For the TorchTPU Sprint, I built TorchTPU-Lens—a small, self-contained, Apache-2.0 developer toolkit and 4-tab Gradio visual playground that brings all of those pieces together in one place. Even better, using Google’s official googlecolab/google-colab-cli, you can provision the free Colab TPU runtime, run the verification suite, pull down real .xplane.pb hardware traces, and launch the live public dashboard directly from your terminal.
Everything executes inside a single free-tier Google Colab v5e-1 TPU runtime (torch==2.14.1+cpu + preinstalled torch_tpu + jax==0.11.2).
1. Why TorchTPU Changes the Equation (and Where Developers Get Stuck)
Modern TorchTPU bridges PyTorch directly onto Google TPUs via the PrivateUse1 / torch.accelerator subsystem and a dedicated torch.compile(backend="tpu") path, alongside torch.tpu.pallas.jax_op for dropping down to custom Pallas kernels without leaving PyTorch. On a free Colab TPU v5e runtime, torch_tpu is even preinstalled right alongside jax==0.11.2 and transformers==5.22.1.
Yet developers moving from CUDA GPUs to TorchTPU consistently hit four surprises:
- Dynamic shapes trigger silent XLA recompiles: Appending one token per autoregressive step changes tensor shapes every iteration, stalling generation while XLA re-traces and re-lowers HLO graphs.
torch.tpu.is_available()traps: In recenttorch_tpubuilds, severaltorch.tpu.*inspection methods are marked@internal_onlyor experimental; public user code is meant to usetorch.accelerator.is_available(),device_count(), andsynchronize().jax_opannotation & scalar pitfalls:torch.tpu.pallas.jax_opinspects function signatures witheval_str=True, and passing Python floats (like sampling temperature) into a compiled kernel forces graph recompilation unless passed inside a fixed-shape tensor.- Profiling dependency conflicts: Installing TensorFlow/TensorBoard just to read an XProf
.xplane.pbfile frequently collides with PyTorch/JAX pins in Colab.
torchtpu-lens targets google/gemma-4-E2B-it in bfloat16 when an HF_TOKEN is present (fitting comfortably inside a free v5e-1’s 16 GiB HBM), and automatically switches to ungated Qwen/Qwen3-1.7B when no token is configured so anyone can clone and run every tab immediately.
2. Walking Through All Four Functionalities Live on Colab TPU v5e
Every screencast and measurement below was captured directly against a live free-tier Colab TPU v5e session (16.0 GiB HBM, torch==2.14.1+cpu, torch_tpu, Qwen/Qwen3-1.7B fallback).
Tab 1: Serving & XLA Recompile Visualizer
Tab 1 lets you run the exact same prompt across four execution modes: eager, compile_dynamic, compile_static, and compile_static_pallas. In compile_dynamic, inputs stay unpadded and grow by one token per step; on our live v5e-1 run, the cold dynamic pass triggered 8 graph compilations, stalling Time to First Token at 19,305.21 ms (0.07 tok/s). Switching to compile_static_pallas pads sequences to 128-aligned static buckets ([128, 256, 512, 1024]) and keeps sampling on-device inside our Pallas kernel—jumping to 6.3–7.83 tok/s with 0 new XLA compiles across varying prompt lengths.
compile_dynamic against compile_static_pallas (128-token static bucket, 0 new compiles) on live Colab TPU v5e.
Tab 2: 2-Minute BF16 LoRA Fine-Tuner (Compile Once, Train at 45 ms/Step)
Fine-tuning on a single 16 GiB TPU doesn’t require complex distributed setups if you freeze base weights in bfloat16 and attach rank-8 PEFT LoRA adapters (q_proj, v_proj). By pre-tokenizing and statically padding every training batch to max_length=128, XLA compiles the forward+backward LoRA graph exactly once. On live TPU v5e, Step 1 took 52,049.21 ms to compile; Steps 2 through 12 then ran at 41–52 ms/step (over 1,000× faster), driving loss down from 5.69 to 3.57, and persistent disk caching brought Step 1 down to 63.96 ms on subsequent runs. You can also click Compare Base vs. LoRA to toggle adapter layers on and off in place.
bfloat16 LoRA fine-tuning curve and per-step latency on Colab TPU v5e (45.0 ms/step, Compile Delta: 0).
Tab 3: Zero-TensorFlow XProf Visual Inspector
Tab 3 wraps a single generation pass with torch.profiler.profile configured via torch.tpu.profiler.TpuProfilerConfig(run_dir=...) and ProfilerActivity.TPU, writes the native OpenXLA .xplane.pb trace, and decodes the protobuf wire format directly in pure Python (xprof_lite.py)—zero TensorFlow dependency required. On our captured v5e-1 trace (total_device_ms: 206.38 ms across 7 planes), it immediately surfaced 74.34 ms in MXU matmul fusions, 7.26 ms inside our custom Pallas jax_op kernel, 23.97 ms in pad/layout conversions, 3.56 ms in attention, and 72 host-device synchronizations.
.xplane.pb trace on TPU v5e and decoding TPU op breakdown + host sync counts in pure Python.
Tab 4: Pallas jax_op Sandbox
Finally, Tab 4 gives developers an interactive testbed for writing custom Pallas kernels inside PyTorch. Our ~150-line pallas_sampler.py implements a VMEM-tiled (128 × 1024) fused temperature scaling + Gumbel-max sampler via torch.tpu.pallas.jax_op, keeping full [B, V] probability tensors out of HBM. Adjusting batch size, vocabulary size, or temperature runs live parity checks against eager PyTorch—achieving Exact Parity vs PyTorch Eager: True in 0.793 ms on (128, 4096) tiles with 0 XLA recompiles across varying temperatures.
0.793 ms, Exact Parity: True) for torch.tpu.pallas.jax_op on TPU v5e.
3. Under the Hood: Five Practical TorchTPU & Colab CLI Lessons
Building this end-to-end surfaced several subtle runtime details that are worth documenting for anyone building on TorchTPU or automating Colab TPUs:
-
Module-scope
jaximport underfrom __future__ import annotations:torch.tpu.pallas.jax_opcallsinspect.signature(inspect.unwrap(fn), eval_str=True). If you use postponed annotations and only importjaxinside a helper function, binding throws aNameErroronjax.Array. Importingjaxat module scope fixes it cleanly. -
Pass runtime scalars in a fixed tensor, not Python floats: Passing
temperatureas a Pythonfloatforces XLA to recompile every time a slider moves. Packing[temperature, valid_vocab_size, ...]into an[8] float32device tensor keeps all shapes and static arguments constant across steps. -
Persistent compilation caches &
/dev/shm: ExportingTORCH_TPU_TIER3_COMPILATION_CACHE_ROOT,XLA_CACHE_DIR, andJAX_COMPILATION_CACHE_DIR—and symlinking/dev/shm/torch_tpu_cachewhen container shared memory is tight—cuts repeat startup time from ~52 seconds down to ~64 milliseconds. -
Colab’s persistent Jupyter kernel holds
/dev/vfio/0: Everycolab execinvocation shares the same persistent IPython kernel process. Spawning a child subprocess (e.g.,subprocess.run(["pytest", ...])or launching Gradio in a subprocess) fails withThe TPU is already in use by process with pid .... Runningpytest.main(...)anddemo.launch(..., server_port=None, prevent_thread_lock=True)in-process cleanly shares the kernel’s initialized TPU context. -
google-colab-clifield notes: Two quick local gotchas when automating Colab from the terminal: (a)google-colab-clidepends onfilelock.ReadWriteLock, which silently evaluates toNoneon Python builds lacking_sqlite3—installing viauv tool install --python /usr/bin/python3.12 google-colab-clisolves it; and (b)colab status -s <name>exits0even when a session is not found, so provisioning scripts should check the status output text rather than just the exit code.
| Workload / Check | Environment | Observed Live Result |
|---|---|---|
Pallas jax_op Sampler Gate |
Colab TPU v5e (16 GiB) |
PASSED · 0.793 ms · 0 recompiles across 8 temps |
| Dynamic vs. Static Serving | Qwen/Qwen3-1.7B (BF16) |
Cold dynamic 0.07 tok/s vs. static Pallas 6.3–7.83 tok/s (0 compiles) |
BF16 PEFT LoRA (len=128) |
Rank 8 (q_proj, v_proj) |
Step 1 cold 52,049 ms → steady 45–52 ms/step (warm Step 1: 63.96 ms) |
Pure-Python .xplane.pb Parser |
No TensorFlow installed | 206.38 ms device time: 74.34 ms MXU, 7.26 ms Pallas, 72 host syncs |
4. Run It Yourself in 60 Seconds
You can either click the Open in Colab badge in the repository README or provision a free Colab v5e-1 TPU straight from your terminal:
# 1. Install Google's official Colab CLI (using a Python build with sqlite3)
uv tool install --python /usr/bin/python3.12 google-colab-cli
colab whoami
# 2. Clone TorchTPU-Lens and run end-to-end on a free Colab TPU
git clone https://github.com/rabimba/torchtpu-lens.git
cd torchtpu-lens
# Optional: export HF_TOKEN=<your_token> to load google/gemma-4-E2B-it
# Without HF_TOKEN, it automatically uses ungated Qwen/Qwen3-1.7B
bash scripts/run_on_colab_tpu.sh --launch-ui
# 3. Tear down the runtime when finished
colab stop -s torchtpu-lens
If you don’t have a TPU session open and just want to inspect the dashboard layout or decode a downloaded .xplane.pb trace locally, torchtpu-lens also ships with an explicit offline UI preview (torchtpu-lens ui --demo-offline) and a standalone CLI trace decoder (torchtpu-lens profile --file colab_artifacts/<trace>.xplane.pb).
Source code, Colab notebook, and all captured screencasts are available under Apache-2.0 at github.com/rabimba/torchtpu-lens.
Comments
Post a Comment