Companion GitHub Repository: agemagician/torchtpu-zero-to-hero
Standard 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 .β¦