Pre-Train Transformers & Fine-Tune HuggingFace LLMs with LoRA on Native PyTorch TPUs (Part 2) A developer published a second-part tutorial and companion GitHub repository (agemagician/torchtpu-zero-to-hero) showing how to pre-train causal Transformers and LoRA fine-tune HuggingFace models natively on PyTorch TPUs using TorchTPU, without the JAX/PyTree and optax workarounds required by the earlier TorchAX approach. The guide demonstrates standard stateful training via torch.compile(backend="tpu") and introduces torch.tpu.optimizers.SingleTraceTrainer, which fuses forward, backward and optimizer update into one XLA executable and measured 2.06x faster step time in a Colab TPU benchmark. It also walks through pre-training a 6-layer decoder Transformer with RoPE, RMSNorm, SwiGLU and grouped-query attention. Companion GitHub Repository: agemagician/torchtpu-zero-to-hero https://github.com/agemagician/torchtpu-zero-to-hero 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 https://dev.to/gde/fine-tune-any-huggingface-model-like-gemma-on-tpus-with-torchax-5g21 , 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 : python @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 . | Part | Focus Area | Colab Notebooks | |---|---|---| | Part 1 https://dev.to/gde/run-any-pytorch-llm-natively-on-google-tpus-a-zero-to-hero-guide-to-torchtpu-part-1-3hj7 | TPU Hardware Mental Model, Execution Modes & 36x Faster StaticCache Inference | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part01 foundations inference tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part01 foundations inference quickstart.ipynb | | Part 2 You are here | Pre-Training Causal Transformers SingleTraceTrainer , AdamW & Muon & Native PEFT LoRA SFT | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part02 pretrain sft tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part02 pretrain sft quickstart.ipynb | | Part 3 | Post-Training Alignment Compiled DPO , Live Online GRPO RL & Disaggregated Pod RL VeRL | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part03 alignment rl grpo tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part03 alignment rl grpo quickstart.ipynb | | Part 4 | FlashAttention on TPUs splash sdpa , Verified Custom Pallas Kernels, MXU Precision & XProf | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part04 splash kernels xprof tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part04 splash kernels xprof quickstart.ipynb | | Part 5 | Cloud TPU Slices & Pods: tpu dist , SimpleFSDP + DTensor TP, Pallas RDMA & vllm-torchtpu | Full Tutorial https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part05 pods distributed serving tutorial.ipynb · 5-Min Quickstart https://colab.research.google.com/github/agemagician/torchtpu-zero-to-hero/blob/main/notebooks/part05 pods distributed serving quickstart.ipynb | 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: checkpoint ..., use reentrant=False INSIDE DecoderBlock.forward and torch.compile layer, backend="tpu", dynamic=False OUTSIDE per layer: DecoderBlock in torch.compile means XLA compiles the block use reentrant=False activation checkpointing inside the block lets AOTAutograd emit a clean joint rematerialized backward graph without Python reentrant hooks. .item or print loss on every step: loss.item inside the training loop forces the CPU to block until the TPU finishes the entire step, starving the PjRt async dispatch queue. Instead, append loss.detach tensors on device and materialize torch.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 . 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: python 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 | 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 : php 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 SingleTraceTrainer Rules: Pass all input tensors via example inputs or register buffer : Because make fx traces inside a fresh FakeTensorMode , any raw tensor captured via Python closure like precomputed RoPE cos / sin will raise a FakeTensor mixing error unless passed through args AdamW vs. Muon Parameter Dimensionality: torch.tpu.optimizers.AdamW handles arbitrary 1D/2D/ND Transformer parameters, whereas torch.tpu.optimizers.Muon Newton-Schulz orthogonalized momentum — naturally suited to TPU MXU matmuls requires strictly 2D weight matrices grad.ndim == 2 , such as bias=False hidden nn.Linear stacks . After training, sync functional weights back via model.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 | 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 https://huggingface.co/datasets/databricks/databricks-dolly-15k . instruction and response rows 15,011 - 15,011 valid . train and eval sets BATCH SIZE=4, MAX SEQ LEN=256 padding drop last=True so every batch has identical shape 4, 256 - prompt msgs add generation prompt=True to find exact prompt cutoff , set labels :prompt cutoff = -100 and labels seq len: = -100 , while keeping the assistant's answer and turn-ending EOS token <|im end| on Qwen3,