Companion GitHub Repository: agemagician/torchtpu-zero-to-hero
Standard loss.backward() and optimizer.step() — plus whole-step XLA fusion when you want maximum speed
If you read my earlier TorchAX LoRA fine-tuning guide, you might remember the functional gymnastics required to train on TPUs via JAX: extracting model parameters into PyTrees, replacing torch.optim.AdamW with optax, writing manual jax.value_and_grad wrappers, and passing safe_serialization=False when saving checkpoints.
With TorchTPU, standard stateful PyTorch training works out of the box:
@torch.compile(backend="tpu", dynamic=False) def compiled_lora_fwd_loss(input_ids, attention_mask, labels): return lora_model(input_ids=input_ids, attention_mask=attention_mask, labels=labels, use_cache=False).loss optimizer.zero_grad(set_to_none=True) loss = compiled_lora_fwd_loss(batch_ids, batch_mask, batch_labels) loss.backward() torch.nn.utils.clip_grad_norm_(trainable_params, 1.0) optimizer.step() And when you pre-train from scratch and want zero Python boundary between forward, backward, and the optimizer update, TorchTPU also ships torch.tpu.optimizers.SingleTraceTrainer — fusing all three stages into one single XLA executable (2.06x faster step time in our Colab TPU benchmark below!).
Series Roadmap
| Part | Focus Area | Colab Notebooks |
|---|---|---|
| Part 1 | TPU Hardware Mental Model, Execution Modes & 36x Faster StaticCache Inference | Full Tutorial · 5-Min Quickstart |
| Part 2 (You are here) | Pre-Training Causal Transformers (SingleTraceTrainer, AdamW & Muon) & Native PEFT LoRA SFT | Full Tutorial · 5-Min Quickstart |
| Part 3 | Post-Training Alignment (Compiled DPO), Live Online GRPO RL & Disaggregated Pod RL (VeRL) | Full Tutorial · 5-Min Quickstart |
| Part 4 | FlashAttention on TPUs (splash_sdpa), Verified Custom Pallas Kernels, MXU Precision & XProf | Full Tutorial · 5-Min Quickstart |
| Part 5 | Cloud TPU Slices & Pods: tpu_dist, SimpleFSDP + DTensor TP, Pallas RDMA & vllm-torchtpu | Full Tutorial · 5-Min Quickstart |
1. Stage 1A: Pre-Training a Modern Causal Transformer (RoPE + RMSNorm + SwiGLU + GQA)
When pre-training a 6-layer Decoder Transformer (d_model=512, 8 query heads, 2 KV heads via Grouped-Query Attention enable_gqa=True, d_ff=1536, vocab_size=32768) on a 16 GiB TPU v5e-1, three TPU engineering patterns make a dramatic difference:
- Put
checkpoint(..., use_reentrant=False)INSIDEDecoderBlock.forwardandtorch.compile(layer, backend="tpu", dynamic=False)OUTSIDE per layer:- Wrapping each identical
DecoderBlockintorch.compilemeans XLA compiles the block once and reuses the cached binary across all 6 layers! - Placing
use_reentrant=Falseactivation checkpointing inside the block letsAOTAutogrademit a clean joint rematerialized backward graph without Python reentrant hooks.
- Wrapping each identical
- Never call
.item()orprint(loss)on every step: Callingloss.item()inside the training loop forces the CPU to block until the TPU finishes the entire step, starving the PjRt async dispatch queue. Instead, appendloss.detach()tensors on device and materialize.item()only when logging or aftertorch.accelerator.synchronize().
class ScratchDecoderBlock(nn.Module): # ... RoPE + GQA (F.scaled_dot_product_attention(..., enable_gqa=True)) + SwiGLU ... def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: if self.use_ckpt and self.training: return checkpoint(self._forward_impl, x, cos, sin, use_reentrant=False) return self._forward_impl(x, cos, sin) On [B=8, S=512, V=32768] (bfloat16), per-layer compiled stateful AdamW converged cleanly from 495.4230 -> 41.4849 in 20 steps at 21.09 ms/step.
2. Stage 1B: Slashing Vocabulary Logit HBM by 10.2x with Checkpointed Chunked Cross-Entropy
Here is the silent HBM killer in modern LLM training: projecting [B=8, S=512, D=512] hidden states to a large vocabulary (V=32,768 here, or V=151,936 in Qwen3 and V=262,144 in Gemma-3!) and casting logits to float32 for F.cross_entropy allocates gigabytes of transient HBM simultaneously during forward and backward.
By slicing flattened [B*S, D] hidden states into chunks of 512 tokens and wrapping each chunk's F.linear + F.cross_entropy in checkpoint(..., use_reentrant=False), XLA never keeps more than one [512, V] logit slice live in HBM:
def chunked_lm_head_ce_loss(hidden: torch.Tensor, lm_weight: torch.Tensor, labels: torch.Tensor, chunk_tokens: int = 512) -> torch.Tensor: flat_h = hidden.reshape(-1, hidden.shape[-1]) flat_y = labels.reshape(-1) total_tokens = flat_h.shape[0] def _chunk_loss(h_c: torch.Tensor, y_c: torch.Tensor, w: torch.Tensor) -> torch.Tensor: return F.cross_entropy(F.linear(h_c, w).float(), y_c, reduction="sum") total_loss = torch.zeros((), device=hidden.device, dtype=torch.float32) for start in range(0, total_tokens, chunk_tokens): end = min(start + chunk_tokens, total_tokens) total_loss = total_loss + checkpoint(_chunk_loss, flat_h[start:end], flat_y[start:end], lm_weight, use_reentrant=False) return total_loss / total_tokens Measured on Google Colab TPU v5e-1 ([B=8, S=512, V=32768]):
| Loss Implementation | Peak HBM Overhead (MiB) | Loss Abs Diff | Hidden Grad rel_L2 Diff |
|---|---|---|---|
Materialized [B, S, V] float32 Cross-Entropy | 1280.5 MiB | (reference) | (reference) |
Checkpointed Chunked Cross-Entropy (chunk=512) | 125.2 MiB (10.2x lower!) | 7.629e-06 | 1.671e-04 |
3. Stage 1C: 2.06x Faster Pre-Training Steps with SingleTraceTrainer (AdamW & Muon)
In standard PyTorch, loss.backward() and optimizer.step() launch separate compiled graphs. TorchTPU's Experimental torch.tpu.optimizers.SingleTraceTrainer uses make_fx and torch.func.grad_and_value to trace forward + loss + backward + functional optimizer state updates into one unified XLA program:
def transformer_loss_fn(mdl: nn.Module, args, kwargs) -> torch.Tensor: # Pass RoPE cos/sin via `args` so `make_fx` converts all tensors to FakeTensors! ids, lbls, c_rope, s_rope = args logits = mdl(ids, c_rope, s_rope) return F.cross_entropy(logits.view(-1, V).float(), lbls.view(-1)) stt_adamw = torch.tpu.optimizers.SingleTraceTrainer( model=model_1c, optimizer=torch.tpu.optimizers.AdamW(lr=5e-4, weight_decay=0.01), compile_fn=lambda gm: torch.compile(gm, backend="tpu", dynamic=False), compute_loss_fn=transformer_loss_fn, ) compiled_step = stt_adamw.make_compiled_train_step(example_inputs=(train_ids, train_lbls, cos_buf, sin_buf)) Two Crucial
SingleTraceTrainerRules:
- Pass all input tensors via
example_inputs(orregister_buffer): Becausemake_fxtraces inside a freshFakeTensorMode, any raw tensor captured via Python closure (like precomputed RoPEcos/sin) will raise aFakeTensormixing error unless passed throughargs!AdamWvs.MuonParameter Dimensionality:torch.tpu.optimizers.AdamWhandles arbitrary 1D/2D/ND Transformer parameters, whereastorch.tpu.optimizers.Muon(Newton-Schulz orthogonalized momentum — naturally suited to TPU MXU matmuls!) requires strictly 2D weight matrices (grad.ndim == 2, such asbias=Falsehiddennn.Linearstacks). After training, sync functional weights back viamodel.load_state_dict(stt_adamw.params, strict=False)+model.tie_weights().
Measured on TPU v5e-1:
| Training Strategy | Step 0 -> Final Loss | Steady-State Latency | Speedup |
|---|---|---|---|
Stateful Per-Layer torch.compile + torch.optim.AdamW | 495.4230 -> 41.4849 | 21.09 ms/step | 1.00x |
SingleTraceTrainer + torch.tpu.optimizers.AdamW | 495.4338 -> 41.5027 | 10.26 ms/step | 2.06x |
SingleTraceTrainer + torch.tpu.optimizers.Muon (2D stack) | 1.0053 -> 0.9650 (MSE) | Single-graph XLA | Verified |
4. Stage 2: Native Stateful PyTorch PEFT LoRA SFT on Qwen/Qwen3-0.6B (20,511 tok/s)
After clearing Stage 1 buffers (del ...; torch._dynamo.reset(); gc.collect(); torch.accelerator.empty_cache()), we instruction-tune Qwen/Qwen3-0.6B (with a 1-line swap to google/gemma-3-1b-it) on databricks/databricks-dolly-15k.
Clean ML Data Hygiene & Model-Agnostic Assistant Loss Masking
- Inspect & Filter First: Verify non-null/non-empty
instructionandresponserows (15,011 -> 15,011valid). - Split Before Tokenizing: Split into disjoint
trainandevalsets before applying chat templates and fixed-shape[BATCH_SIZE=4, MAX_SEQ_LEN=256]padding (drop_last=Trueso every batch has identical shape(4, 256)-> 0 shape recompilations). - Prefix-Length Assistant Masking: Tokenize
prompt_msgs(add_generation_prompt=True) to find exactprompt_cutoff, setlabels[:prompt_cutoff] = -100andlabels[seq_len:] = -100, while keeping the assistant's answer and turn-ending EOS token (<|im_end|>on Qwen3,<end_of_turn>on Gemma-3) unmasked — even whenpad_token_id == eos_token_id! - Set
lora_dropout=0.0: Keeps train and eval graph topology identical undertorch.compile(backend="tpu", dynamic=False).
Saving & Reloading safetensors Adapters on TorchTPU
Unlike torchax, lora_model.save_pretrained(save_dir) writes standard adapter_model.safetensors files directly! One subtle tip we uncovered on live TPU v5e-1: when reloading via peft.PeftModel.from_pretrained(reload_base, save_dir, torch_device="cpu"), pass torch_device="cpu" before calling reloaded_peft.to(device) — otherwise peft auto-detects "tpu" and passes device="tpu" into Rust safetensors.safe_open, which only recognizes CPU/CUDA device strings.
Measured LoRA SFT Results on Google Colab TPU v5e-1
Metric (Qwen/Qwen3-0.6B, LoRA r=16, alpha=32) | Measured Value |
|---|---|
| Trainable Parameters | 10,092,544 / 606,142,464 (1.6650%) |
| Held-Out Eval Loss (Before -> After 100 Steps) | 2.5007 -> 2.0353 |
| Held-Out Eval Perplexity (Before -> After) | 12.19 -> 7.65 |
Steady-State Training Throughput ([4, 256]) | 49.9 ms/step (20,511 tokens/sec) |
| Peak TPU HBM Allocated | 6.31 GiB (out of 16.00 GiB) |
Reloaded PeftModel Logit rel_L2 Difference | 0.000e+00 (bit-exact!) |
5. Quick Troubleshooting Reference
| Symptom | Root Cause | Fix |
|---|---|---|
SafetensorError: device tpu is invalid on PeftModel.from_pretrained | peft passes torch_device="tpu" to Rust safetensors | Pass torch_device="cpu" in PeftModel.from_pretrained(...), then .to("tpu") |
FakeTensor mixing error in SingleTraceTrainer | Closure-captured tensor not converted by make_fx | Pass auxiliary tensors (like RoPE cos/sin) via example_inputs or register_buffer |
AssertionError using Muon on a full Transformer | Muon Newton-Schulz orthogonalization requires ndim == 2 | Use AdamW for 1D norms/embeddings, and Muon strictly on 2D Linear(..., bias=False) matrices |
Slow step time despite torch.compile | Calling loss.item() inside the inner training loop | Collect loss.detach() on device and call .item() only on log intervals after synchronize() |
Further Reading & Credits
- Part 1: TPU Hardware Mental Model & 36x Faster Inference
- Hugging Face PEFT Documentation
- Databricks Dolly 15k Dataset (CC-BY-SA-3.0)
- Companion Repository (
agemagician/torchtpu-zero-to-hero)
Credits
Thanks to the TorchTPU teams at Google and Meta, the Hugging Face transformers & peft maintainers, and Databricks for the open Dolly-15k dataset.
Up Next in Part 3: How do you align your model with human preferences (DPO) and train chain-of-thought reasoning with live online Group Relative Policy Optimization (GRPO) RL on a single 16 GiB Colab TPU — jumping from 0.0% to 96.9% held-out math accuracy with zero XLA recompilations? See you in Part 3!