Resources / Blog
Fine-Tuning and Serving Gemma 4 31B on Google Cloud TPU
A production-ready recipe for LoRA fine-tuning and serving Gemma 4 31B on Google Cloud TPU — 1.61× faster training, 2.12× cheaper than 2×H100, and at long context 66% higher inference throughput with 23.6× faster time-to-first-token. Plus the deep TPU fixes we hit porting from PyTorch to JAX.
Fine-Tuning and Serving Gemma 4 31B on Google Cloud TPU
Large language model fine-tuning is increasingly bottlenecked not by data availability but by compute cost and iteration speed. Google Cloud TPUs, while natively supported for training, require non-trivial porting effort compared to the mature GPU ecosystem (PyTorch, HuggingFace, FSDP). We set out to build a ready recipe for fine-tuning Gemma 4 31B on Google Cloud TPU — and prove it could beat GPUs on both speed and cost. The result required porting a GPU-native training recipe built on PyTorch, HuggingFace TRL, and FSDP to the JAX + Tunix/Qwix stack, solving numerous code-level challenges along the way.
After our implementation, we observed training completed 1.61× faster at 2.12× lower cost. For inference, TPU matches GPU at short context and decisively outperforms at long context: 66% higher throughput and 23.6× faster time-to-first-token at 4096-token inputs.
What We Built
Our pipeline covers the complete workflow for fine-tuning and deploying large language models on TPU:
Training runs on TPU v5p-8, a configuration with 4 TPU chips providing 411 GB of combined High Bandwidth Memory. We use the JAX ecosystem: Tunix for the Gemma 4 model implementation, Qwix for LoRA adapter injection, Optax for optimization, and Orbax for distributed checkpointing. The entire stack runs in bfloat16 precision with gradient checkpointing enabled.
Inference runs on TPU v6e-8 (Trillium), Google's latest TPU generation, with 8 chips providing 250 GB of HBM. We serve the merged model through vLLM's TPU backend with tensor parallelism across all 8 chips.
Evaluation uses the NVlabs/verilog-eval benchmark (spec-to-RTL task): 156 problems where the model must generate syntactically correct Verilog RTL code from natural language specifications. Each generated module is compiled with iverilog and simulated against a reference testbench.
For our experiments, we fine-tuned on CodeV-R1, a dataset of 10,000 Verilog coding examples with chain-of-thought reasoning traces.
Results at a Glance

| Metric | TPU | GPU (2×H100) | Delta |
|---|---|---|---|
| Training time | 3.34 hr | 5.39 hr | 1.61× faster |
| Training cost | $56.11 | 19.23 | 2.12× cheaper |
| Throughput (tokens/sec) | 763 | 486 | 1.57× faster |
| Inference TTFT (4096 tokens) | 61 ms | 1,443 ms | 23.6× faster |
| Long-context throughput | 1,206 tok/s | 728 tok/s | +66% |
| End-to-end cost | $77.63 | 41.35 | 1.82× cheaper |
Hardware Configurations
Training Hardware
| Spec | TPU v5p-8 | GPU a3-highgpu-2g |
|---|---|---|
| Accelerator | 4× TPU v5p chips | 2× NVIDIA H100 80GB HBM3 |
| HBM per chip | 102.8 GB | 80 GB |
| Total HBM | 411.2 GB | 160 GB |
| Host RAM | ~355 GB | ~468 GB |
| Interconnect | ICI (inter-chip) | NVLink |
| GCP on-demand rate | 6.80/hr | 2.12/hr |
Inference Hardware
| Spec | TPU v6e-8 (Trillium) | GPU a3-highgpu-2g |
|---|---|---|
| Accelerator | 8× TPU v6e chips | 2× NVIDIA H100 80GB HBM3 |
| HBM per chip | 31.25 GB | 80 GB |
| Total HBM | 250 GB | 160 GB |
| Tensor parallelism | tp=8 | tp=2 |
| GCP on-demand rate | 1.52/hr | 2.12/hr |
Training Performance
Loss Convergence
Both TPU and GPU training show smooth convergence with no instabilities. The large absolute loss difference (0.072 vs 2.258 final) reflects different loss computation methods: the TPU recipe uses assistant-only loss on approximately 15% of tokens (the Verilog output), while the GPU recipe computes loss over the full sequence including prompt tokens. When normalized to the same range, convergence speed is comparable.
Gradient Stability
Gradient norms remain stable throughout training on both platforms. The GPU run shows sharper spikes (up to 106× at step 100) attributable to the larger effective batch aggregating more diverse gradients. The TPU gradient norms remain in the 1–10 range throughout. No gradient clipping was required on either platform.
Why is TPU Faster?
The TPU v5p-8 achieves 1.61× faster wall-clock time despite having only 4 chips vs 2 H100 GPUs. Several factors contribute:
HBM bandwidth: Each TPU v5p chip has 2.765 TB/s HBM bandwidth vs the H100's 3.35 TB/s, but TPU has 4 chips vs 2 GPUs. Total aggregate bandwidth: 11.06 TB/s (TPU) vs 6.7 TB/s (GPU).
ICI interconnect: TPU chips communicate via the ICI mesh at 900 GB/s bidirectional bandwidth, significantly faster than NVLink for the collective operations used in tensor parallelism.
XLA fusion: XLA compiles the forward+backward pass into a single fused kernel per layer, eliminating the kernel launch overhead present in PyTorch's eager mode, even with FSDP.
No torch.compile overhead: The GPU run disables torch.compile to avoid compatibility issues with Gemma 4's heterogeneous attention layers (different head dimensions for sliding-window vs full-attention), leaving PyTorch in eager mode throughout.
Modifications for TPU Compatibility
Getting Gemma 4 31B running on TPU required solving problems that don't appear in documentation or tutorials. Here's what we learned at the hardware and framework level.
1. Device Mesh Configuration and Head Divisibility Constraints
JAX requires an explicit 2D device mesh specifying how chips are arranged across FSDP and tensor-parallel dimensions. On v5p, the slice naming convention is v5p-N where N is the number of TensorCores; since each v5p chip contains two TensorCores operating in megacore mode, the number of JAX devices equals N/2. A v5p-8 slice therefore exposes 4 devices.
The mesh product must equal the device count, so a (1, 8) mesh is invalid on v5p-8 regardless of model architecture.
More critically, tp=8 is independently ruled out by Gemma 4 31B's attention configuration. The model uses two distinct attention types across its 60 layers in a fixed 5:1 pattern (50 sliding-window layers, 10 full-attention layers), with separate KV head counts:
-
Query heads: 32 (shared across both layer types)
-
Local KV heads (sliding): 16
-
Global KV heads (full-attention): 4 — the binding constraint
With tp=8, global KV heads would need to split 4 heads across 8 devices = 0.5 heads per device, which is invalid. The maximum tensor parallelism degree this model supports is tp=4, regardless of how many devices are available. This constraint is slice-size-independent — even a v5p-32 with 16 devices must use (fsdp=4, tp=4), not (fsdp=2, tp=8).
2. LoRA Module Naming: Tunix vs HuggingFace
The HuggingFace model has separate q_proj, k_proj, v_proj, and o_proj Linear layers. Tunix's JAX port uses different module names and, critically, fuses the K and V projections into a single tensor:
| HF PyTorch (GPU) | Tunix JAX (TPU) | Notes |
|---|---|---|
| q_proj | q_einsum | Renamed; same weights |
| k_proj + v_proj | kv_einsum | Fused into single tensor with dim-1 = {K,V} |
| o_proj | attn_vec_einsum | Renamed |
| gate_proj | gate_proj | Same |
| up_proj | up_proj | Same |
| down_proj | down_proj | Same |
The kv_einsum fusion is the most significant difference: Tunix stores both K and V projections in a single weight tensor of shape (in, 2, n_kv_heads, head_dim), while HuggingFace stores them as separate (n_kv_heads×head_dim, in) matrices. This requires special handling during checkpoint merging.
There is also no vision tower in the JAX port, so the exclusion regex required on GPU (to skip similarly-named projections in the multimodal vision tower) is unnecessary.
3. LoRA Sharding Annotation Corruption
When Qwix injects LoRA adapters into a model, it wraps existing weight matrices with low-rank decompositions. The problem is that it copies sharding metadata (PartitionSpec) from the original weights onto the new LoRA parameters — but these have completely different shapes.
Consider a fused key-value projection weight with shape (input_dim, 2, n_kv_heads, head_dim) and a 4-dimensional sharding specification. Qwix creates LoRA matrices with shape (input_dim, rank) and (rank, output_dim) — 2-dimensional tensors — but applies the same 4-dimensional sharding spec. When JAX later tries to shard these tensors across the TPU mesh, it crashes.
We solved this by traversing the model graph after LoRA injection, detecting every parameter where the sharding specification rank doesn't match the tensor rank, and resetting those parameters to replicated (unsharded) placement. A second pass checks divisibility: if a tensor dimension is not divisible by the mesh size for the assigned axis, we replicate that axis to avoid uneven sharding. This fix resolved failures on 60+ parameters per model load.
4. Optimizer State Sharding Propagation
Fixing the LoRA parameters wasn't enough. AdamW (via Optax) maintains momentum and variance buffers for every trainable parameter — and these buffers inherit the same broken sharding specifications. When the trainer calls its internal optimizer sharding routine, it fails on the same rank mismatch we already fixed for the parameters themselves.
The solution required monkey-patching the trainer's optimizer sharding method to apply the same rank-checking and divisibility-checking logic we used for parameters. This interception filters the partition specs through the same divisibility check before applying the sharding constraint.
5. Gemma 4 Sliding Window Attention Path Selection
Qwix needs to trace through the model with dummy inputs to determine where to inject LoRA adapters. The standard approach is using a minimal 1-token input to minimize tracing overhead. But Gemma 4's attention implementation uses sequence length to select between prefill and decode paths: if sequence_length == 1, it assumes decode mode and expects a pre-allocated KV cache.
During LoRA injection, no KV cache exists — we're tracing the model structure, not running inference. The result is an error about missing cache for sliding window attention, with no indication that the fix is simply using a longer dummy sequence.
Using a 2-token dummy input forces the prefill path, which doesn't require a cache. This same bug existed in both our training script and checkpoint merge tool.
6. Gradient Checkpointing via Method Patching
On TPU, gradient checkpointing (called rematerialization in JAX) must be applied at the decoder layer granularity. Tunix doesn't expose this as a configuration flag. We patch the unbound DecoderLayer method directly with nnx.remat, so all decoder layer instances use the rematerialized forward pass. Without this, the 31B model's activation memory during backward would exceed the v5p-8's 411 GB HBM.
7. Cross-Framework Checkpoint Conversion
After training, inference requires merging the LoRA adapters back into the base weights and saving a merged safetensors model. The GPU recipe uses HuggingFace PEFT's built-in merge_and_unload(). The TPU recipe requires a custom merge tool because:
-
Orbax checkpoints store the full model tree including LoRA wrappers in a JAX-specific format (not safetensors)
-
The Tunix JAX model uses different weight names and tensor layouts than HuggingFace safetensors
-
The kv_einsum fusion means one LoRA module maps to two safetensors keys
The delta computation must account for different tensor layouts. HuggingFace stores weight matrices as (out, in) while JAX einsum convention is often the transpose. The fused KV projection requires splitting the LoRA B matrix on dimension-1 to recover separate K and V deltas. All deltas are transposed to match HuggingFace layout before adding to the base weight.
8. XLA Compilation Overhead Reduction
The first training step on TPU triggers XLA compilation, converting the JAX program into optimized TPU machine code. For a model this size, compilation takes 8+ minutes. Disabling expensive LLVM optimization passes via XLA flags reduces first-step compilation time to approximately 3 minutes with negligible impact on training throughput (roughly 2-5% trade-off).
9. TPU VM Environment Constraints
Both TPU generations (v5p and v6e) ship with Python 3.10, but Tunix requires Python 3.11+. The first setup step is installing Python 3.11 via the deadsnakes PPA.
The TPU VM's boot disk (97 GB) cannot hold the 62.5 GB Gemma 4 31B model download alongside the OS. Tunix stages the model in /tmp/models before loading into HBM. The host has 355 GB of RAM-backed /dev/shm (tmpfs), which we redirect staging to at launch time. Without this, the model download fills the boot disk and crashes mid-load.
For inference on v6e-8 (Trillium), only the v2-alpha-tpuv6e runtime works correctly — the generic tpu-ubuntu2204-base runtime fails at TPU topology enumeration.
Inference Performance
The Long-Context Advantage
The most significant finding is TPU's dominance at long context lengths:
| Workload | TPU v6e-8 | GPU 2×H100 | Winner |
|---|---|---|---|
| Short context (512 in / 256 out) | |||
| Peak output throughput | 1,403 tok/s | 1,490 tok/s | H100 (+6%) |
| Median TTFT | 45 ms | 51 ms | TPU (1.1×) |
| Long context (4096 in / 512 out) | |||
| Peak output throughput | 1,206 tok/s | 728 tok/s | TPU (+66%) |
| Median TTFT @ QPS=4 | 61 ms | 1,443 ms | TPU (23.6×) |
| Median TPOT | 23.9 ms | 31.2 ms | TPU (1.3×) |
| Very long context (8192 in / 512 out) | |||
| Peak output throughput | 482 tok/s | 449 tok/s | TPU (+7%) |
| Median TTFT @ QPS=4 | 1,013 ms | 7,202 ms | TPU (7.1×) |
| Max context (~16k in / 512 out) | |||
| Peak output throughput | 474 tok/s | 326 tok/s | TPU (+45%) |
Why TPU Dominates at Long Context
At 4096+ token inputs, TPU v6e-8 comprehensively outperforms the GPU. Two factors drive this:
Prefill compute: Time-to-first-token is dominated by the prefill phase (processing all input tokens), which is compute-bound — proportional to O(n²) for full-attention layers and O(wn) for sliding-window layers. The v6e-8's 8 chips deliver substantially more raw compute than 2 H100s for this workload. At 4096 input tokens, the GPU's TTFT of 1,443 ms indicates it is saturated on compute during prefill; the TPU handles the same load in 61 ms.
Higher aggregate compute: With 8 TPU v6e chips vs 2 H100 GPUs, the TPU configuration has more total compute available for the memory-bound prefill phase. XLA also fuses QKV projection with the sliding-window and full-attention kernels in Gemma 4's heterogeneous attention, reducing HBM roundtrips.
Why GPU Edges Ahead at Short Context
At short input lengths (≤2048 tokens), GPU edges ahead by approximately 6% on peak output throughput. This is the memory-bandwidth-bound decode regime where the H100's higher per-GPU HBM bandwidth (3.35 TB/s vs ~1.6 TB/s per v6e chip) is most relevant. With short KV caches, each decode step reads relatively little KV state per token, so the bottleneck is weight loading — where H100 wins per chip.

Evaluation Results
Benchmark Results
Both fine-tuned models were evaluated on NVlabs/verilog-eval (spec-to-RTL task): 156 problems, 5 samples per problem at temperature=0.8, top_p=0.95.
| Metric | TPU-trained | GPU-trained |
|---|---|---|
| pass@1 | 0.641 | 0.697 |
| pass@5 | 0.795 | 0.814 |
| Checkpoint step | 1,244 (final) | 1,250 (final) |
| Inference engine | Tunix Sampler (JAX) | vLLM (CUDA) |
Per-Problem Analysis
Most problems are solved at 100% by both models. Differences concentrate on harder FSM, K-map, and cellular automata problems (indices 100-156).
Score Distribution
GPU-trained model: 101 problems at 100%, 39 at 0%. TPU-trained model: 89 at 100%, 50 at 0%. The difference is primarily in the zero-score bucket (11 additional problems failing entirely for TPU).
The 5.6 percentage point gap on pass@1 is within normal run-to-run variance for stochastic sampling at n=5 and is attributable to training objective differences (assistant-only vs full-sequence loss) rather than hardware.
Training Configuration
Both runs used identical hyperparameters:
| Parameter | TPU | GPU |
|---|---|---|
| Base model | Gemma 4 31B-IT | Gemma 4 31B-IT |
| Optimizer steps | 1,244 | 1,250 |
| Effective batch size | 8 | 8 |
| Sequence length | 4,096 | 4,096 |
| LoRA rank | 64 | 64 |
| LoRA alpha | 64 | 64 |
| Learning rate | 1e-4 | 1e-4 |
| Warmup steps | 100 | 100 |
| LR schedule | Cosine → 0 | Cosine → 0 |
| Precision | bf16 | bf16 |
| Framework | JAX + Tunix/Qwix | PyTorch + HuggingFace TRL |
| Parallelism | Tensor Parallel (tp=4) | FSDP (full_shard) |
| Dataset | CodeV-R1 (10K samples) | CodeV-R1 (10K samples) |
Cost Analysis
Training Economics
| TPU v5p-8 | GPU 2×H100 | Winner | |
|---|---|---|---|
| On-demand hourly rate | 6.80/hr | 2.12/hr | TPU (24% cheaper/hr) |
| Training time | 3.34 hr | 5.39 hr | TPU (1.61× faster) |
| Total training cost | $56.11 | 19.23 | TPU (2.12× cheaper) |
| Cost per 1M tokens trained | $6.10 | 2.68 | TPU (2.08× cheaper) |
The 2.12× cost advantage compounds the lower hourly rate and faster execution time.
Inference Economics
| Workload | TPU tok/hr | GPU tok/hr | TPU $/1M tok | GPU $/1M tok |
|---|---|---|---|---|
| Short context (≤2048 tokens) | 5.05M | 5.36M | $4.27 | $4.13 |
| Long context (4096 tokens) | 4.34M | 2.62M | $4.95 | $8.44 |
For short-context workloads, GPU is 3% cheaper per token. For long-context workloads (≥4096 tokens), TPU is 41% cheaper per output token.
Total Cost of Ownership
| Cost Component | TPU | GPU |
|---|---|---|
| Training (v5p-8 / a3-highgpu-2g) | $56.11 | 19.23 |
| Inference — 1 hr serving | 1.52 | 2.12 |
| Total (train + 1hr serve) | $77.63 | 41.35 |
| Train + 8hr inference | 28.27 | 96.19 |
| Train + 24hr inference | $572.59 | $650.11 |
TPU is 1.82× cheaper end-to-end for a single training run plus a day of inference serving.
Key Takeaways
TPU Advantages
-
Training speed: 1.61× faster wall-clock time (3.34 hr vs 5.39 hr)
-
Training cost: 2.12× cheaper ($56.11 vs
19.23) — lower hourly rate compounded by faster executionInference TTFT at 4096 tokens: 23.6× faster (61 ms vs 1,443 ms at QPS=4)
Inference TTFT at 8192 tokens: 7.1× faster (1,013 ms vs 7,202 ms at QPS=4)
Inference throughput at long context: +66% output tok/s at 4096 tokens
Memory headroom: 411 GB total HBM for training enables larger batches or longer sequences
GPU Advantages
-
Ecosystem maturity: PyTorch + HuggingFace has broader library support, simpler LoRA injection, and faster prototyping with fewer workarounds
-
Short-context throughput: marginally higher peak burst at ≤2048 token inputs (+6%)
-
Short-context cost: 3% cheaper per token at short context
-
P99 tail latency: slightly better at short context (20.49 ms vs 22.29 ms) due to no XLA bucket padding overhead
Conclusion
Training: TPU is the clear winner — 1.61× faster and 2.12× cheaper. The engineering overhead of porting from PyTorch to JAX + Tunix is real (roughly a week for mesh configuration, sharding annotation fixes, custom data pipeline, and checkpoint conversion) but is a one-time cost amortized across many runs.
Inference: TPU is the clear winner at long-context workloads. At 4096-token inputs, TPU delivers 66% higher throughput and 23.6× faster TTFT. At short context (≤2048 tokens), performance is comparable with a marginal GPU throughput edge.
The observed 1.82× cost advantage across a representative train-and-serve pipeline suggests that TPUs are a compelling alternative for ML workloads, particularly given their high-bandwidth memory (HBM) capacity relative to comparably priced GPU configurations.
Open Source
The complete training and inference pipeline is available on GitHub:
Repository: github.com/h2loop/gemma-tpu
The release includes:
-
Production-ready training script with all TPU-specific fixes applied
-
Checkpoint merge tool that correctly handles Gemma 4's tensor layouts
-
Automatic checkpoint resume for spot instance preemption recovery
-
Configurable dataset loading supporting JSONL, HuggingFace datasets, and chat-format data
Technical Paper
For complete methodology details, ablation studies, and extended analysis, see our technical report:
arXiv: arxiv.org/abs/2605.25645
The paper includes hardware utilization analysis, scaling experiments across TPU configurations, detailed framework comparison between PyTorch and JAX, and comprehensive inference benchmarking across context lengths from 512 to 16k tokens.