"""Kaggle notebook body: train the director LoRA. The HF bundle holds only two files needed here, so fetch them by URL instead of snapshot_download: this avoids importing huggingface_hub before the transformers 5.x upgrade (a stale already-imported hub breaks transformers' `from huggingface_hub.utils import httpx`). Output lands in /kaggle/working/director_lora_out: adapter/, adapter.zip, model_fp16/, sample.txt, train_meta.json. The ONNX export is a separate step. """ import os import shutil import subprocess import sys import time import urllib.request from pathlib import Path ROOT = Path("/kaggle/working") REPO = os.environ.get("BUNDLE_REPO", "idefinity/webfm-eval") BASES = [f"https://huggingface.co/datasets/{REPO}/resolve/main", f"https://hf-mirror.com/datasets/{REPO}/resolve/main"] SFT = ROOT / "director_lora" / "sft.jsonl" # new protocol, not the old radio set TRAIN = ROOT / "kaggle" / "director_lora_train.py" OUT = ROOT / "director_lora_out" FILES = {"director_lora/sft.jsonl": SFT, "kaggle/director_lora_train.py": TRAIN} # Pinned: 5.22.2 is the version whose Qwen3_5 auto mapping and module names # were checked. hub 1.x is what transformers 5.22.2 requires. PIP = ("pip install -q --upgrade " "'transformers==5.22.2' 'huggingface_hub>=1.31,<2' " "'peft==0.21.2' 'accelerate>=1.1'") # The Kaggle image ships torchao 0.10.0. peft 0.21.2 raises ImportError when # it finds torchao < 0.16 instead of ignoring it, even for plain fp16 LoRA. # We never quantize here, so remove it; the training script also patches the # peft probe as a fallback. UNINSTALL = "pip uninstall -y -q torchao" CHECK = (sys.executable + " -c \"" "import importlib.util, torch, transformers, peft, huggingface_hub; " "print('torch', torch.__version__, 'cuda', torch.version.cuda, " "'gpus', torch.cuda.device_count()); " "print('transformers', transformers.__version__, " "'peft', peft.__version__, 'hub', huggingface_hub.__version__); " "print('torchao spec', importlib.util.find_spec('torchao')); " "assert importlib.util.find_spec('torchao') is None, " "'torchao still installed'\"") def log(msg: str) -> None: print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) def fetch(rel: str, dst: Path) -> None: dst.parent.mkdir(parents=True, exist_ok=True) for attempt in range(6): for base in BASES: url = f"{base}/{rel}" try: with urllib.request.urlopen(url, timeout=180) as r, open(dst, "wb") as f: shutil.copyfileobj(r, f) size = dst.stat().st_size if size < 1000: raise RuntimeError(f"only {size} bytes") log(f"fetched {url} -> {dst} ({size/1e6:.2f} MB)") return except Exception as exc: log(f"fetch attempt {attempt + 1} via {base} failed: {exc}") time.sleep(4) raise SystemExit(f"cannot fetch {rel}") def run(cmd: str, env=None) -> int: log(f"$ {cmd[:220]}") return subprocess.run(cmd, shell=True, env=env).returncode def main() -> None: log(f"python {sys.version.split()[0]}") for rel, dst in FILES.items(): fetch(rel, dst) if run(PIP) != 0: raise SystemExit("dependency install failed") if run(UNINSTALL) != 0: log("WARN: torchao uninstall returned non-zero; peft fallback will handle it") if run(CHECK) != 0: raise SystemExit("environment check failed (torch/hub/torchao mismatch?)") env = dict(os.environ, WORK_ROOT=str(ROOT), DATA=str(SFT), LORA_OUT=str(OUT), CUDA_VISIBLE_DEVICES="0", HF_HUB_DISABLE_XET="1", EPOCHS=os.environ.get("EPOCHS", "2"), LR=os.environ.get("LR", "1e-4"), R=os.environ.get("R", "16"), ALPHA=os.environ.get("ALPHA", "32"), MAX_LEN=os.environ.get("MAX_LEN", "2048"), ACCUM=os.environ.get("ACCUM", "4"), DTYPE=os.environ.get("DTYPE", "auto"), GRAD_CKPT=os.environ.get("GRAD_CKPT", "0"), MAX_TRAIN_SECONDS=os.environ.get("MAX_TRAIN_SECONDS", "4200")) log(f"training on {SFT}") rc = subprocess.run([sys.executable, str(TRAIN)], env=env).returncode log(f"train rc={rc}; outputs in {OUT}") if OUT.exists(): for p in sorted(OUT.rglob("*")): if p.is_file(): log(f"artifact {p.relative_to(OUT)} {p.stat().st_size/1e6:.2f} MB") if rc != 0: raise SystemExit("director LoRA training failed") log("DONE") if __name__ == "__main__": main()