File size: 5,646 Bytes
9b6961f 14cb80d 9b6961f 14cb80d d489474 9b6961f 14cb80d 9b6961f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | """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()
from diffusion_eval_and_vis.config import SLICE_TRAINING_EXECUTION
execution = dict(SLICE_TRAINING_EXECUTION)
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, "execution": execution,
"effective_dataset_order": cfg.finetune.datasets_for_model(args.repo)}, 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, execution=execution)
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()
|