cd /news/machine-learning/pre-train-transformers-fine-tune-hug… · home › topics › machine-learning › article
[ARTICLE · art-181798] src=dev.to ↗ pub= topic=machine-learning verified=true sentiment=↑ positive

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.

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 playbook: Inference and self-hosting
by read7 min views10 publishedDec 4, 2026

Companion GitHub Repository: 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, 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!).

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

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):
    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:

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:

def transformer_loss_fn(mdl: nn.Module, args, kwargs) -> torch.Tensor:
    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.

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 re 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 , LoRAr=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 onPeftModel.from_pretrained peft passestorch_device="tpu" to Rustsafetensors Pass torch_device="cpu" inPeftModel.from_pretrained(...) , then.to("tpu")
FakeTensor mixing error inSingleTraceTrainer Closure-captured tensor not converted by make_fx Pass auxiliary tensors (like RoPE cos /sin ) viaexample_inputs orregister_buffer
AssertionError usingMuon on a full Transformer Muon Newton-Schulz orthogonalization requiresndim == 2 Use AdamW for 1D norms/embeddings, andMuon strictly on 2DLinear(..., 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 aftersynchronize()

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!

── more in #machine-learning 4 stories · sorted by recency
── more on @torchtpu 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/pre-train-transforme…] indexed:0 read:7min 2026-12-04 · —