# Pre-Train Transformers & Fine-Tune HuggingFace LLMs with LoRA on Native PyTorch TPUs (Part 2)

> Source: <https://dev.to/gde/pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-tpus-part-2-16fj>
> Published: 2026-12-04 13:40:57+00:00

**Recommendation:** When training on TPUs with TorchTPU, wrap the forward/loss in torch.compile(backend="tpu") and use SingleTraceTrainer to fuse forward, backward and optimizer into one XLA executable for faster steps.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

**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, `<end_of_turn>` on Gemma-3) unmasked — even when `pad_token_id == eos_token_id`!` lora_dropout=0.0`:` torch.compile(backend="tpu", dynamic=False)`.` 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.

`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!)** | 

| 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()` | 

`agemagician/torchtpu-zero-to-hero`)
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!
