File size: 2,483 Bytes
0cc835c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.11"
# dependencies = ["torch", "transformers<5", "sentencepiece", "huggingface_hub<1", "numpy", "onnx", "onnxruntime", "onnxscript", "bitsandbytes; sys_platform == 'linux'"]
# ///
"""Teacher -> soft labels -> distilled student -> 8-bit ONNX -> scores, all inside one job.

hf jobs uv run ... pipeline.py <student_args...>   (data mounted at /gesture, with scripts/ and pools/)
"""
import os, sys, shlex, shutil, subprocess

ROOT, WORK = "/gesture", "/tmp/work"
SRC = f"{ROOT}/{os.environ['DATA_DIR']}" if os.environ.get("DATA_DIR") else ROOT  # labelled splits, e.g. splits/merged
shutil.copytree(f"{ROOT}/scripts", WORK, dirs_exist_ok=True)
os.chdir(WORK)
env = os.environ | {"DATA": f"{SRC}"}


def run(*cmd: str, environ: dict | None = None) -> None:
    print("$", " ".join(cmd), flush=True)
    subprocess.run([sys.executable, *cmd], check=True, env=environ or env)


if os.environ.get("TEACHER_REPO"):  # reuse an already trained teacher
    from huggingface_hub import snapshot_download
    snapshot_download(os.environ["TEACHER_REPO"], local_dir="runs/teacher")
else:
    teacher = os.environ.get("TEACHER", "sentence-transformers/paraphrase-multilingual-mpnet-base-v2")
    run("train.py", "--base", teacher, "--data", SRC, "--out", "runs/teacher", *shlex.split(os.environ.get("TEACHER_ARGS", "")))
pools = os.environ.get("POOLS", "gen_train3.jsonl real_big.jsonl").split()
run("distill_data.py", "runs/teacher", "data_distill", *[f"{ROOT}/pools/{p}" for p in pools])
run("train.py", "--data", "data_distill", "--out", "runs/student", *sys.argv[1:])


def push(folder: str, repo: str | None) -> None:
    if repo:
        from huggingface_hub import HfApi

        api = HfApi()
        api.create_repo(repo, private=True, exist_ok=True)
        api.upload_folder(folder_path=folder, repo_id=repo, commit_message="distillation pipeline run", ignore_patterns=["*.onnx.data"])
        print("pushed", folder, "to", repo, flush=True)


push("runs/student", os.environ.get("PUSH_TO"))  # weights first, so a failed export loses nothing
try:
    run("export.py", "runs/student")
    for build in ("model.onnx", "model_qint8.onnx"):
        run("evaluate.py", "onnx:runs/student", build)
    push("runs/student", os.environ.get("PUSH_TO"))
except subprocess.CalledProcessError as error:
    print("export/evaluate failed:", error, flush=True)
if not os.environ.get("TEACHER_REPO"):
    push("runs/teacher", os.environ.get("PUSH_TEACHER_TO"))