{"slug": "pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-2", "title": "Pre-Train Transformers & Fine-Tune HuggingFace LLMs with LoRA on Native PyTorch TPUs (Part 2)", "summary": "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.", "body_md": "**Companion GitHub Repository:** [agemagician/torchtpu-zero-to-hero](https://github.com/agemagician/torchtpu-zero-to-hero)\n\n`loss.backward()` and `optimizer.step()` — plus whole-step XLA fusion when you want maximum speed\nIf 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.\n\nWith **TorchTPU**, standard stateful PyTorch training works **out of the box**:\n\n``` python\n@torch.compile(backend=\"tpu\", dynamic=False)\ndef compiled_lora_fwd_loss(input_ids, attention_mask, labels):\n    return lora_model(input_ids=input_ids, attention_mask=attention_mask, labels=labels, use_cache=False).loss\n\noptimizer.zero_grad(set_to_none=True)\nloss = compiled_lora_fwd_loss(batch_ids, batch_mask, batch_labels)\nloss.backward()\ntorch.nn.utils.clip_grad_norm_(trainable_params, 1.0)\noptimizer.step()\n```\n\nAnd 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!).\n\n| Part | Focus Area | Colab Notebooks | \n|---|---|---|\n| **[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) | \n| **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) | \n| **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) | \n| **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) | \n| **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) | \n\n`RoPE` + `RMSNorm` + `SwiGLU` + `GQA`)\nWhen 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:\n\n`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()`.\n\n```\nclass ScratchDecoderBlock(nn.Module):\n    # ... RoPE + GQA (F.scaled_dot_product_attention(..., enable_gqa=True)) + SwiGLU ...\n    def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:\n        if self.use_ckpt and self.training:\n            return checkpoint(self._forward_impl, x, cos, sin, use_reentrant=False)\n        return self._forward_impl(x, cos, sin)\n```\n\nOn `[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`**.\n\n`10.2x` with Checkpointed Chunked Cross-Entropy\nHere 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.\n\nBy 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:\n\n``` python\ndef chunked_lm_head_ce_loss(hidden: torch.Tensor, lm_weight: torch.Tensor, labels: torch.Tensor, chunk_tokens: int = 512) -> torch.Tensor:\n    flat_h = hidden.reshape(-1, hidden.shape[-1])\n    flat_y = labels.reshape(-1)\n    total_tokens = flat_h.shape[0]\n\n    def _chunk_loss(h_c: torch.Tensor, y_c: torch.Tensor, w: torch.Tensor) -> torch.Tensor:\n        return F.cross_entropy(F.linear(h_c, w).float(), y_c, reduction=\"sum\")\n\n    total_loss = torch.zeros((), device=hidden.device, dtype=torch.float32)\n    for start in range(0, total_tokens, chunk_tokens):\n        end = min(start + chunk_tokens, total_tokens)\n        total_loss = total_loss + checkpoint(_chunk_loss, flat_h[start:end], flat_y[start:end], lm_weight, use_reentrant=False)\n    return total_loss / total_tokens\n```\n\n**Measured on Google Colab `TPU v5e-1` (`[B=8, S=512, V=32768]`):**\n\n| Loss Implementation | Peak HBM Overhead (MiB) | Loss Abs Diff | Hidden Grad `rel_L2` Diff | \n|---|---|---|---|\n| Materialized `[B, S, V]`` float32` Cross-Entropy | `1280.5 MiB` | *(reference)* | *(reference)* | \n| **Checkpointed Chunked Cross-Entropy (`chunk=512`)** | **` 125.2 MiB` (`10.2x` lower!)** | **`7.629e-06`** | **` 1.671e-04`** | \n\n`2.06x` Faster Pre-Training Steps with `SingleTraceTrainer` (`AdamW` & `Muon`)\nIn 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**:\n\n``` php\ndef transformer_loss_fn(mdl: nn.Module, args, kwargs) -> torch.Tensor:\n    # Pass RoPE cos/sin via `args` so `make_fx` converts all tensors to FakeTensors!\n    ids, lbls, c_rope, s_rope = args\n    logits = mdl(ids, c_rope, s_rope)\n    return F.cross_entropy(logits.view(-1, V).float(), lbls.view(-1))\n\nstt_adamw = torch.tpu.optimizers.SingleTraceTrainer(\n    model=model_1c,\n    optimizer=torch.tpu.optimizers.AdamW(lr=5e-4, weight_decay=0.01),\n    compile_fn=lambda gm: torch.compile(gm, backend=\"tpu\", dynamic=False),\n    compute_loss_fn=transformer_loss_fn,\n)\ncompiled_step = stt_adamw.make_compiled_train_step(example_inputs=(train_ids, train_lbls, cos_buf, sin_buf))\n```\n\n**Two Crucial `SingleTraceTrainer` Rules:**\n\n**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`!\n**`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()`.\n\n**Measured on `TPU v5e-1`:**\n\n| Training Strategy | Step 0 -> Final Loss | Steady-State Latency | Speedup | \n|---|---|---|---|\n| Stateful Per-Layer `torch.compile` +`torch.optim.AdamW` | `495.4230 -> 41.4849` | `21.09 ms/step` | `1.00x` | \n| **`SingleTraceTrainer` + `torch.tpu.optimizers.AdamW`** | **` 495.4338 -> 41.5027`** | **` 10.26 ms/step`** | **` 2.06x`** | \n| **`SingleTraceTrainer` + `torch.tpu.optimizers.Muon` (2D stack)** | **`1.0053 -> 0.9650` (MSE)** | Single-graph XLA | Verified | \n\n`Qwen/Qwen3-0.6B` (`20,511 tok/s`)\nAfter 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)**.\n\n`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\nUnlike `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.\n\n`TPU v5e-1`\n| Metric ( `Qwen/Qwen3-0.6B` , LoRA`r=16, alpha=32` ) | Measured Value | \n|---|---|\n| **Trainable Parameters** | `10,092,544` /`606,142,464` (`1.6650%` ) | \n| **Held-Out Eval Loss (Before -> After 100 Steps)** | **`2.5007` -> `2.0353`** | \n| **Held-Out Eval Perplexity (Before -> After)** | **`12.19` -> `7.65`** | \n| **Steady-State Training Throughput (`[4, 256]`)** | **` 49.9 ms/step` (`20,511 tokens/sec`)** | \n| **Peak TPU HBM Allocated** | **`6.31 GiB`** (out of` 16.00 GiB` ) | \n| **Reloaded `PeftModel` Logit `rel_L2` Difference** | **`0.000e+00` (bit-exact!)** | \n\n| Symptom | Root Cause | Fix | \n|---|---|---|\n| `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\")` | \n| `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` | \n| `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 | \n| 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()` | \n\n`agemagician/torchtpu-zero-to-hero`)\nThanks to the **TorchTPU teams at Google and Meta**, the **Hugging Face `transformers` & `peft` maintainers**, and **Databricks** for the open Dolly-15k dataset.\n\n**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!", "url": "https://wpnews.pro/news/pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-2", "canonical_source": "https://dev.to/gde/pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-tpus-part-2-16fj", "published_at": "2026-12-04 13:40:57+00:00", "updated_at": "2026-12-04 13:44:08.621735+00:00", "lang": "en", "topics": ["machine-learning", "large-language-models", "ai-infrastructure", "ai-tools", "developer-tools"], "entities": ["TorchTPU", "PyTorch", "HuggingFace", "Google TPUs", "TorchAX", "JAX", "SingleTraceTrainer", "agemagician/torchtpu-zero-to-hero"], "also_reported_by": [], "takeaway": "TorchTPU's SingleTraceTrainer fuses forward, backward and optimizer step into one XLA executable, cutting step time 2.06x versus separate stages in the author's Colab TPU benchmark.", "recommendation": {"advice": "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.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-2", "markdown": "https://wpnews.pro/news/pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-2.md", "text": "https://wpnews.pro/news/pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-2.txt", "jsonld": "https://wpnews.pro/news/pre-train-transformers-fine-tune-huggingface-llms-with-lora-on-native-pytorch-2.jsonld"}}