"""LoRA supervised fine-tuning with a plain PyTorch loop (transparent and easy to defend). Objective: next-token cross-entropy on the assistant answer only L = - (1/|A|) * sum_{t in A} log p_theta(y_t | y_ best[0]: best = (score, epoch + 1) model.save_pretrained(out_dir / "best_adapter"); tok.save_pretrained(out_dir / "best_adapter") log(f"saved best adapter (epoch {epoch + 1}, {cfg['select_metric']}={score:.4f})") model.save_pretrained(out_dir / "last_adapter") meta = {"config": cfg, "token_stats": stats, "trainable_params": trainable, "total_params": total, "best_epoch": best[1], "best_score": best[0], "train_minutes": (time.time() - t0) / 60, "gpu": torch.cuda.get_device_name(0) if device == "cuda" else "cpu", "peak_mem_gb": torch.cuda.max_memory_allocated() / 2**30 if device == "cuda" else None} json.dump(history, open(out_dir / "history.json", "w"), indent=1) json.dump(meta, open(out_dir / "train_meta.json", "w"), indent=1) return out_dir / "best_adapter", history, meta