Skip to main content

TorchTPU-Lens: Serving, LoRA Fine-Tuning, and Live Pallas/XProf Inspection on a Free Colab TPU

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.

TORCHTPU-LENS END-TO-END FLOW (FREE COLAB TPU v5e-1) Developer Terminal google-colab-cli colab new --tpu v5e1 colab exec / download Colab TPU v5e-1 (16 GiB HBM) Static 128-Bucket Serving & BF16 LoRA Pallas jax_op (128×1024 VMEM Sampler) TpuProfilerConfig → .xplane.pb 4-Tab Gradio UI 1. Serving & Recompiles 2. BF16 LoRA Fine-Tuner 3. Pure-Python XProf 4. Pallas jax_op Sandbox Public gradio.live Tunnel Persistent Disk Caches: TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT • XLA_CACHE_DIR • JAX_COMPILATION_CACHE_DIR

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 recent torch_tpu builds, several torch.tpu.* inspection methods are marked @internal_only or experimental; public user code is meant to use torch.accelerator.is_available(), device_count(), and synchronize().
  • jax_op annotation & scalar pitfalls: torch.tpu.pallas.jax_op inspects function signatures with eval_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.pb file frequently collides with PyTorch/JAX pins in Colab.
Gemma 4 Ready + Zero-Config Ungated Fallback

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.

Screencast of Tab 1 Serving and Recompile Visualizer running on Colab TPU v5e
Screencast 1: Comparing 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.

Screencast of Tab 2 BF16 LoRA Fine-Tuner running 12 steps on Colab TPU v5e
Screencast 2: Live 12-step 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.

Screencast of Tab 3 Visual XProf Inspector capturing and decoding a live .xplane.pb trace on Colab TPU v5e
Screencast 3: Capturing a live .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.

Screencast of Tab 4 Pallas jax_op Sandbox verifying exact parity on Colab TPU v5e
Screencast 4: Live parity and kernel latency test (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:

  1. Module-scope jax import under from __future__ import annotations: torch.tpu.pallas.jax_op calls inspect.signature(inspect.unwrap(fn), eval_str=True). If you use postponed annotations and only import jax inside a helper function, binding throws a NameError on jax.Array. Importing jax at module scope fixes it cleanly.
  2. Pass runtime scalars in a fixed tensor, not Python floats: Passing temperature as a Python float forces XLA to recompile every time a slider moves. Packing [temperature, valid_vocab_size, ...] into an [8] float32 device tensor keeps all shapes and static arguments constant across steps.
  3. Persistent compilation caches & /dev/shm: Exporting TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT, XLA_CACHE_DIR, and JAX_COMPILATION_CACHE_DIR—and symlinking /dev/shm/torch_tpu_cache when container shared memory is tight—cuts repeat startup time from ~52 seconds down to ~64 milliseconds.
  4. Colab’s persistent Jupyter kernel holds /dev/vfio/0: Every colab exec invocation shares the same persistent IPython kernel process. Spawning a child subprocess (e.g., subprocess.run(["pytest", ...]) or launching Gradio in a subprocess) fails with The TPU is already in use by process with pid .... Running pytest.main(...) and demo.launch(..., server_port=None, prevent_thread_lock=True) in-process cleanly shares the kernel’s initialized TPU context.
  5. google-colab-cli field notes: Two quick local gotchas when automating Colab from the terminal: (a) google-colab-cli depends on filelock.ReadWriteLock, which silently evaluates to None on Python builds lacking _sqlite3—installing via uv tool install --python /usr/bin/python3.12 google-colab-cli solves it; and (b) colab status -s <name> exits 0 even 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

Popular posts from this blog

Racecraft (Project Koru) · Prologue — The Origin Story

Racecraft · Prologue , The Origin Story It Started With a Wine List and a Question About Racing How a happy-hour conversation in the Bay Area turned into a trustable AI race coach , and then into a second version that runs entirely on a phone, on the NPU. This is the prologue to a five-part series. Two years ago(1st November, 2024) I was in the Bay Area for a GDE Summit. If you've never been: it's a couple of days of talks among Google Developer Experts, the kind of people who get unreasonably excited about a new on-device runtime, and then , mercifully , a happy hour where everyone stops performing and just eats. We ended up at a restaurant(Puesto Santa Clara), a long table of GDEs, and I was doing the most important engineering of the evening: trying to decide which wine to order. Across the table was Ajeet Mirwani . I don't even remember how the wine talk turned into racing talk , these things drift , but the moment the word "racing" ...

The Throughput Trap: Benchmarking vLLM on OpenXLA and the Reality of Production LLM Serving

vLLM Systems · DevLab 2026, Deep Dive I was recently invited by the Google TPU team to speak at the OpenXLA Summer DevLab 2026 . This post breaks down our deep-dive evaluation of the matured vLLM + OpenXLA stack, the fundamental engineering mismatches between CUDA and XLA serving paths, and why traditional capacity metrics are lying to you. If you are operating large language models at enterprise scale right now, your platform architecture team is likely staring at a massive infrastructure crossroads: Should we migrate our core serving workloads from GPUs to TPUs? Historically, NVIDIA's CUDA ecosystem was the only serious option for user-facing, low-latency LLM generation. But here in 2026, the economics and infrastructure options have transformed. Google TPUs are highly available, cheaper per chip, and the open-source serving stack built around vLLM and OpenXLA has officially achieved absolute production readiness. Yet, when our infrast...

A Split‑Brain Neuro‑Symbolic Training Method for High‑Velocity Autonomous Coaching from Telemetry

 Author: Rabimba Karanjai Scope: Problem statement + data methodology + model training (no deployment discussion) Abstract Real‑time coaching in motorsport is a safety‑critical learning problem : a system must map noisy, high‑frequency telemetry to short, actionable guidance that remains physically consistent and avoids hazardous recommendations . This paper proposes a “Split‑Brain” training formulation that separates (i) a semantic coaching target (what action/critique should be expressed) from (ii) a reflexive interface (how actions are represented as compact, verifiable tokens). The approach trains a Small Language Model (SLM) in the Gemma family [1] using QLoRA fine‑tuning [2] , and introduces a telemetry tokenizer plus teacher‑student synthesis pipeline to generate instruction‑action pairs at scale. Core contribution: a reproducible method to convert “ golden lap ” differential tel...