# /// script # requires-python = ">=3.10" # dependencies = [ # "huggingface_hub>=0.26.0", # ] # /// """Run syllabus LoRA SFT on Hugging Face Jobs (GPU). Downloads finetune JSONL from the Hub, clones training-pipeline, runs readiness gates, trains with OOM-safe defaults, and pushes the adapter to a Hub model repo. Override via environment variables: HF_DATASET_REPO (default: Dev-the-dev91/syllabus-finetune) HF_OUTPUT_MODEL (default: Dev-the-dev91/syllabus-extractor-lora) HF_PIPELINE_REPO (default: https://github.com/madch3m/training-pipeline.git) HF_MAX_LENGTH (default: 2048) HF_TRAIN_EPOCHS (default: 3) HF_JOB_FLAVOR (informational only when run locally) """ from __future__ import annotations import os import subprocess from pathlib import Path from huggingface_hub import HfApi, hf_hub_download HF_USER = os.environ.get("HF_USER", "Dev-the-dev91") DATASET_REPO = os.environ.get("HF_DATASET_REPO", f"{HF_USER}/syllabus-finetune") OUTPUT_MODEL = os.environ.get("HF_OUTPUT_MODEL", f"{HF_USER}/syllabus-extractor-lora") PIPELINE_GIT = os.environ.get( "HF_PIPELINE_REPO", "https://github.com/madch3m/training-pipeline.git", ) MAX_LENGTH = os.environ.get("HF_MAX_LENGTH", "2048") NUM_EPOCHS = os.environ.get("HF_TRAIN_EPOCHS", "3") WORK = Path(os.environ.get("HF_WORK_DIR", "/tmp/training_pipeline")) def run(cmd: list[str], *, cwd: Path | None = None) -> None: print("+", " ".join(cmd), flush=True) subprocess.run(cmd, check=True, cwd=cwd) def uv_run(script_args: list[str], *, cwd: Path) -> None: """Run a repo script using the synced project venv (--extra train).""" run(["uv", "run", "--extra", "train", *script_args], cwd=cwd) def _require_hub_token() -> str: token = os.environ.get("HF_TOKEN", "").strip() if not token or token in ("$HF_TOKEN", "${HF_TOKEN}"): raise SystemExit( "HF_TOKEN is missing or still the literal '$HF_TOKEN' placeholder.\n" "Resubmit with: uv run python scripts/submit_hf_training_job.py\n" "Or CLI: hf jobs uv run --secrets HF_TOKEN \n" "(Do not pass secrets={'HF_TOKEN': '$HF_TOKEN'} from Python — use the real token.)" ) return token def main() -> None: token = _require_hub_token() api = HfApi(token=token) who = api.whoami()["name"] print(f"Hub user: {who}") print(f"Dataset: {DATASET_REPO}") print(f"Output model: {OUTPUT_MODEL}") if WORK.exists(): run(["rm", "-rf", str(WORK)]) run(["git", "clone", "--depth", "1", PIPELINE_GIT, str(WORK)]) # Create .venv with train extras so `uv run --extra train` sees datasets/trl/torch. run(["uv", "sync", "--extra", "train"], cwd=WORK) data_dir = WORK / "data" / "finetune" data_dir.mkdir(parents=True, exist_ok=True) for name in ("train.jsonl", "valid.jsonl"): cached = hf_hub_download( repo_id=DATASET_REPO, filename=name, repo_type="dataset", ) (data_dir / name).write_bytes(Path(cached).read_bytes()) print(f"Fetched {name} from {DATASET_REPO}") train_path = data_dir / "train.jsonl" valid_path = data_dir / "valid.jsonl" uv_run( [ "validate_training_readiness.py", "--train-jsonl", str(train_path), "--valid-jsonl", str(valid_path), "--strict", ], cwd=WORK, ) out_dir = WORK / "artifacts" / "hf_syllabus_extractor" uv_run( [ "train_hf_structured_extractor.py", "--train-jsonl", str(train_path), "--valid-jsonl", str(valid_path), "--model-name", "Qwen/Qwen2.5-0.5B-Instruct", "--output-dir", str(out_dir), "--max-length", MAX_LENGTH, "--per-device-train-batch-size", "1", "--gradient-accumulation-steps", "8", "--num-train-epochs", NUM_EPOCHS, "--bf16", "--disable-mlflow", ], cwd=WORK, ) api.create_repo(OUTPUT_MODEL, repo_type="model", exist_ok=True) api.upload_folder( folder_path=str(out_dir), repo_id=OUTPUT_MODEL, repo_type="model", commit_message="LoRA adapter from HF Jobs syllabus SFT", ) print(f"Uploaded adapter: https://huggingface.co/{OUTPUT_MODEL}") if __name__ == "__main__": main()