Companion GitHub Repository: agemagician/torchtpu-zero-to-hero
From 0.0% to 96.9% Verifiable Math Accuracy in 45 Online GRPO Steps — on a Single 16 GiB Colab TPU
Post-training is where base language models turn into helpful assistants (Direct Preference Optimization [DPO]) and verifiable step-by-step reasoners (Group Relative Policy Optimization [GRPO], the online RL algorithm popularized by DeepSeek-R1).
Running post-training and online RL on a single 16 GiB TPU TensorCore (TPU v5e-1) forces you to solve three classic systems bottlenecks:
-
Vocabulary Logit HBM Blowups: Upcasting
[B*G=8, S=192, V=151,936]Qwen3 logits tofloat32allocates ~0.93 GiBper tensor (>5 GiBacross forward + autograd), leaving no room for KV caches and weights. -
Mid-Step Dynamo Guard Breaks: Toggling
with model.disable_adapter():inside a DPO training step mutates module state and invalidatestorch.compileguards. -
Variable-Length Rollout Recompilations: Generating
G = 4online reasoning rollouts per prompt with variable prompt/completion lengths triggers XLA recompilation storms unless bucketed cleanly.
In Part 3, we solve all three cleanly in pure PyTorch on TorchTPU — achieving 0 post-warmup XLA recompilations in both DPO and live online GRPO, staying under 7.5 GiB peak HBM, and then examining how production TPU clusters scale GRPO across multi-slice Pods with VeRL + vllm-torchtpu + TorchTitan (SimpleFSDP).
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 | Pre-Training Causal Transformers (SingleTraceTrainer, AdamW & Muon) & Native PEFT LoRA SFT |
Full Tutorial · 5-Min Quickstart |
| Part 3 (You are here) | 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. Backbone-Chunked Selective Token Log-Probabilities (1.55 GiB Total HBM!)
Both DPO and GRPO require per-token log-probabilities log π_θ(y_t | x, y_<t) in float32 (never bfloat16, where exp(new_logp - old_logp) suffers catastrophic cancellation!). Instead of calling CausalLM.forward() — which materializes the entire [N, S, V] logits tensor — we:
- Unwrap the inner Transformer decoder (
get_base_model().get_decoder()) to compute compact[mb, S-1, D]hidden states — working identically on both plain Hugging FaceCausalLMs andPeftModelForCausalLMwrappers! - Slice the sequence axis into
64-token chunks wrapped incheckpoint(..., use_reentrant=False), gathering target logits inbfloat16and computingtorch.logsumexp(..., dim=-1)in exactfloat32:
def unwrap_causal_lm(mdl):
base_lm = mdl.get_base_model() if hasattr(mdl, "get_base_model") else mdl
backbone = base_lm.get_decoder() if hasattr(base_lm, "get_decoder") else base_lm.model
return backbone, base_lm.get_output_embeddings()
def _chunk_logp(h_slice: torch.Tensor, tgt_slice: torch.Tensor, head_w: torch.Tensor) -> torch.Tensor:
logits_bf16 = F.linear(h_slice, head_w)
picked_bf16 = logits_bf16.gather(-1, tgt_slice.unsqueeze(-1)).squeeze(-1)
lse_fp32 = torch.logsumexp(logits_bf16.float(), dim=-1)
return picked_bf16.float() - lse_fp32
On Qwen/Qwen3-0.6B (vocab_size = 151,936), computing exact float32 selective log-probabilities across (4, 192) sequences peaked at just 1.55 GiB total HBM (model weights + activations + vocabulary projection combined)!
2. Stage 1: Zero-Recompile Direct Preference Optimization (DPO)
Given preference pairs (x, y_chosen, y_rejected) from argilla/ultrafeedback-binarized-preferences-cleaned, DPO optimizes:
L_DPO = -mean( log_sigmoid( beta * [ (log pi_theta(y_w|x) - log pi_ref(y_w|x))
- (log pi_theta(y_l|x) - log pi_ref(y_l|x)) ] ) )
To achieve zero steady-state recompilations and minimal HBM on TPU:
-
Filter & Split First: Filter malformed/empty preference turns and split into disjoint
train(160) andeval(28) pairs before fixed-length (SEQ_LEN = 256) tokenization. -
Precompute Reference Log-Probs Once: Compute
log π_ref(y_w|x)andlog π_ref(y_l|x)in compiledtorch.no_grad()before attaching LoRA. That eliminates keeping a second frozen 0.6B model in HBM, halves per-step FLOPs, and avoidsdisable_adapter()Dynamo guard invalidation! -
Cleanly Unload Adapter After DPO: Call
model = dpo_model.unload()(without merging into base weights) +model.tie_weights()so Stage 2 GRPO starts on the exact clean base model without reloading weights.
Measured DPO Results on Colab TPU v5e-1 (50 steps, beta = 0.1):
-
Held-Out Implicit Reward Margin:
+0.0042(53.6%preference accuracy) ->+1.3503(64.3%preference accuracy) -
Steady-State Dynamo Recompilations:
0
3. Stage 2: Live Online GRPO RL with Verifiable Reasoning Rewards
Unlike offline DPO, GRPO generates fresh trajectories online on every single training step:
- Sample
B = 2multi-step arithmetic prompts (e.g.,(6 * 12) - 9) and replicate eachG = 4times (8parallel sequences). -
Left-Pad Prompts to Fixed
PROMPT_LEN = 64with explicitposition_ids = (mask.cumsum(-1) - 1).clamp(min=0)and decodeMAX_NEW_TOKENS = 96(TOTAL_LEN = 160) using a@torch.compile(backend="tpu", dynamic=False)prefill function and 1-tokenStaticCachedecode function (HybridCacheautomatically selected if swappingMODEL_IDtogoogle/gemma-3-1b-it). - Score each rollout with a verifiable reward function (
+0.2for<think>...</think>,+0.2for<answer>...</answer>,+1.0for exact integer match, plus smooth proximity shaping so group variance stays positive early in training) and compute group-normalized advantages:
A_hat[i, g] = (reward[i, g] - mean(reward[i, :])) / (std(reward[i, :]) + 1e-4)
- Update the LoRA policy using the compiled clipped surrogate objective (
clip(ratio, 0.8, 1.2), zero-KL verifiable RLbeta = 0.0).
Measured Live Online GRPO Results on Google Colab TPU v5e-1 (45 steps)
Metric (Qwen/Qwen3-0.6B, B=2, G=4, TOTAL_LEN=160) |
Pre-GRPO (Held-Out) | Post-GRPO (Held-Out) |
|---|---|---|
| Mean Verifiable Reward | 0.059 |
1.125 (19.1x gain!) |
| Exact Integer Match Accuracy | 0.0% |
96.9% |
| End-to-End Online RL Step Time (8 rollouts + backward + step) | — | 1.08 s/step |
| Peak TPU HBM (Base Model + KV Cache + LoRA Autograd) | — | 7.44 GiB |
| Post-Warmup Dynamo Recompilations | — | 0 |
Why did exact match jump from 0.0% to 96.9% so fast? Before GRPO, Qwen3-0.6B reasoned verbosely inside <think>...</think> past the 96-token budget without closing </think><answer>63</answer>. Within 45 online GRPO steps, group-relative rewards taught the policy to compress its <think> chain-of-thought concisely and emit exact <answer>N</answer> integers!
4. Stage 3: Scaling GRPO to Cloud TPU Pods — Disaggregated VeRL + vllm-torchtpu + TorchTitan
On a single Colab TPU, our single Python process alternated between StaticCache rollout generation and compiled backward passes. How do production teams scale GRPO to 70B+ models across 64 TPU chips?
On NVIDIA GPUs, RL frameworks often co-locate vLLM and FSDP processes on the same GPU via hybrid_engine: True. On Google Cloud TPUs, libtpu enforces strict one-OS-process-per-TPU-device ownership: two OS processes cannot open /dev/vfio/* simultaneously.
Production TPU RL with Volcano Engine Reinforcement Learning (VeRL) + Ray solves this cleanly via Disaggregated TPU Slice Pools (full configuration shipped in recipes/verl_rl/verl_grpo_qwen3_tpu.yaml):
-
hybrid_engine: False: Rollout workers and Actor trainer workers run on dedicated TPU slices orchestrated by Ray. -
Rollout Slice Pool (
vllm-torchtpu): Runs Pallas Ragged Paged Attention + Tensor Parallelism over fast intra-slice ICI torus links to generate thousands of group completions per second. -
Actor Trainer Slice Pool (
TorchTitan+SimpleFSDP): Compiles whole-step@spmd_safepolicy updates over ICI (tpu_dist) and broadcasts updatedbfloat16weights to the rollout slices over Data Center Network (DCN) between steps!
5. Quick Troubleshooting Reference
| Symptom | Root Cause | Fix |
|---|---|---|
AttributeError: 'CausalLMOutputWithPast' has no attribute 'last_hidden_state' on PeftModel
|
PeftModelForCausalLM exposes .model (LoraModel), not the inner decoder |
Use mdl.get_base_model().get_decoder() and .get_output_embeddings()
|
| NaN or noisy GRPO policy ratios | Computing logsumexp or new_lp - old_lp in bfloat16
|
Upcast chunk logits to float32 before torch.logsumexp
|
Device lock crash co-locating vLLM and trainer on TPU |
libtpu permits only 1 OS process per TPU device |
Set hybrid_engine: False in VeRL (or run single-process sequentially on 1-chip Colab) |
| Wrong reasoning answers on left-padded batches | Default position_ids count left-pad tokens from 0
|
Pass (attention_mask.cumsum(-1) - 1).clamp(min=0) as explicit position_ids
|
Further Reading & Credits
- Part 1: TPU Hardware Mental Model & 36x Faster Inference
- Part 2: Pre-Training Transformers & LoRA SFT on TorchTPU
- DeepSeekMath / GRPO Paper (arXiv:2402.03300) & Direct Preference Optimization (arXiv:2305.18290)
- UltraFeedback Binarized Preferences Dataset (MIT)
- Disaggregated VeRL TPU Recipe (
recipes/verl_rl/verl_grpo_qwen3_tpu.yaml)
Credits
Thanks to the TorchTPU, vllm-torchtpu, TorchTitan, and VeRL open-source communities, and Argilla for curating UltraFeedback.
Up Next in Part 4: What happens when context length grows to S = 8,192 and standard attention crashes out of 16 GiB HBM? We drop straight down to TPU VMEM SRAM with Splash Attention (splash_sdpa — 6.39x faster at 4K & 1.2 GiB vs OOM at 8K), write a custom differentiable Pallas kernel audited by pallas.verifier.verify, unlock 6-pass MXU float32 precision, and capture hardware XProf timelines!

