Download finetune_runner.py from vanshnawander/structured-diffusion-eval: direct link, hf CLI and curl.
- Browser
- Download file 5.39 kB
-
https://huggingface.co/datasets/vanshnawander/structured-diffusion-eval/resolve/main/finetune_runner.py
- Command line
-
hf download hf://datasets/vanshnawander/structured-diffusion-eval/finetune_runner.py
-
curl -L -o finetune_runner.py https://huggingface.co/datasets/vanshnawander/structured-diffusion-eval/resolve/main/finetune_runner.py
5.39 kB
| """Sequential SliceGPT diffusion LoRA on a free/local GPU; optional public HF upload.""" | |
| import argparse | |
| from dataclasses import asdict | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import time | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from diffusion_eval_and_vis.config import StructuredPruningConfig | |
| from runner import write_json | |
| import training_core | |
| DATASET_REVISIONS = { | |
| "wikitext2": "b08601e04326c79dfdd32d625aee71d232d685c3", | |
| "c4": "1588ec454efa1a09f29cd18ddd04fe05fc8653a2", | |
| "alpaca": "dce01c9b08f87459cf36a430d809084718273017", | |
| } | |
| def relocate_resume(root): | |
| path = root / "resume.json" | |
| if path.exists(): | |
| state = json.loads(path.read_text()) | |
| for key in ["adapter", "runtime"]: | |
| parts = Path(state[key]).parts | |
| position = next(i for i, part in enumerate(parts) if part.startswith("resume_")) | |
| state[key] = str(root.joinpath(*parts[position:])) | |
| write_json(path, state) | |
| saved_path = root / "saved.json" | |
| if saved_path.exists(): | |
| saved = json.loads(saved_path.read_text()) | |
| saved["checkpoint_path"] = str(root / "merged") | |
| write_json(saved_path, saved) | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--repo", required=True) | |
| p.add_argument("--revision") | |
| p.add_argument("--output", default="training_results") | |
| p.add_argument("--cache-dir", default=".training_hf_cache") | |
| p.add_argument("--offload-dir", default=".training_offload") | |
| p.add_argument("--dtype", choices=["bfloat16", "float16"], default="bfloat16") | |
| p.add_argument("--device", default="cuda") | |
| p.add_argument("--device-map", choices=["auto", "single"], default="auto") | |
| p.add_argument("--time-budget-seconds", type=float, default=8*3600) | |
| p.add_argument("--show-config", action="store_true") | |
| p.add_argument("--restore-training-dir", help="Original training/<job> or prior notebook recovery folder") | |
| p.add_argument("--upload", action="store_true", help="Save/reload/verify, then upload publicly with HF_TOKEN") | |
| p.add_argument("--namespace", default="vanshnawander") | |
| args = p.parse_args() | |
| cfg = StructuredPruningConfig() | |
| cfg.eval.dtype, cfg.eval.device = args.dtype, args.device | |
| if args.show_config: | |
| print(json.dumps({"finetune_config": asdict(cfg.finetune), "eval_config": asdict(cfg.eval), | |
| "dataset_revisions": DATASET_REVISIONS}, indent=2)) | |
| return | |
| import torch | |
| from huggingface_hub import HfApi, hf_hub_download | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("Enable GPU(s). CPU/disk inference offload cannot be used for LoRA training.") | |
| if args.dtype == "bfloat16" and not torch.cuda.is_bf16_supported(): | |
| raise RuntimeError("Select float16 explicitly on T4; the precision override is recorded.") | |
| token = os.environ.get("HF_TOKEN", False) | |
| revision = args.revision or HfApi(token=token).model_info(args.repo).sha | |
| manifest = json.loads(Path(hf_hub_download(args.repo, "checkpoint_manifest.json", revision=revision, | |
| token=token)).read_text()) | |
| job = manifest.get("job", manifest.get("provenance", {}).get("job")) | |
| if not job or job["method"] != "slicegpt" or "provenance" in manifest: | |
| raise ValueError("Choose an original SliceGPT checkpoint for sequential LoRA training.") | |
| upload = {"repo_id": args.repo, "commit_sha": revision, "url": "https://huggingface.co/" + args.repo} | |
| # Different training precisions must never overwrite each other's merged models. | |
| profile = hashlib.sha256(json.dumps({"dtype": args.dtype, "finetune": asdict(cfg.finetune)}, sort_keys=True).encode()).hexdigest()[:8] | |
| identifier = "run-9fc515e82f313fab-kaggle-" + profile | |
| training_core.RUNS = Path(args.output).resolve() | |
| os.environ["TRAIN_HF_CACHE"] = args.cache_dir | |
| os.environ["TRAIN_OFFLOAD_DIR"] = args.offload_dir | |
| os.environ["TRAIN_DEVICE_MAP"] = args.device_map | |
| from training_support import Job | |
| root = training_core.RUNS / identifier / "pipeline/training" / Job(**job).name | |
| if args.restore_training_dir and not (root / "resume.json").exists(): | |
| import shutil | |
| shutil.copytree(args.restore_training_dir, root, dirs_exist_ok=True) | |
| relocate_resume(root) | |
| if (root / "uploaded.json").exists(): | |
| uploaded = json.loads((root / "uploaded.json").read_text()) | |
| saved = json.loads((root / "saved.json").read_text()) | |
| from training_support import verify_remote_files | |
| verify_remote_files(HfApi(token=token), uploaded["repo_id"], uploaded["commit_sha"], saved["files"]) | |
| print(json.dumps(uploaded, indent=2)) | |
| return | |
| result = training_core.train_one(asdict(cfg), identifier, job, upload, DATASET_REVISIONS, | |
| lambda: None, deadline=time.monotonic()+args.time_budget_seconds) | |
| print(json.dumps(result, indent=2), flush=True) | |
| if args.upload and not result.get("continued"): | |
| if not os.environ.get("HF_TOKEN"): | |
| raise RuntimeError("Set HF_TOKEN in Kaggle Secrets for the requested public upload.") | |
| uploaded = training_core.upload_finetuned(identifier, job, args.namespace, lambda: None) | |
| print(json.dumps(uploaded, indent=2), flush=True) | |
| if __name__ == "__main__": | |
| main() | |