File size: 4,738 Bytes
b16b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Set up one Kaggle session, then run the job runner. Downloaded fresh from the Hub every session.



1. Large files (models, checkpoints) go to the scratch disk with the most free space.

2. Trainer packages install into Kaggle's own Python, pinned so Kaggle's torch stays as it is.

3. vLLM installs into its own venv, because it pins a different torch.

4. The exact environment (pip freeze of both, nvidia-smi) is saved and committed with the job.

5. Logs are copied to /kaggle/working/logs, the notebook's (public) output. They hold no secrets.

"""

from __future__ import annotations

import argparse
import importlib.metadata as md
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

CODE = Path(__file__).resolve().parent.parent


def sh(cmd: list[str], **kw) -> None:
    print("$", " ".join(str(c) for c in cmd[:8]), flush=True)
    subprocess.run([str(c) for c in cmd], check=True, **kw)


def heavy_dir() -> Path:
    free = {}
    for p in ("/tmp", "/kaggle/tmp", "/root"):
        if os.path.isdir(p):
            free[p] = shutil.disk_usage(p).free
    best = max(free, key=free.get) if free else "/tmp"
    print("free disk (GB):", {k: round(v / 2 ** 30) for k, v in free.items()}, "->", best, flush=True)
    return Path(best)


def main() -> int:
    p = argparse.ArgumentParser()
    p.add_argument("--job", default="auto")
    p.add_argument("--ops-repo", required=True)
    p.add_argument("--budget-hours", type=float, default=11.25)
    p.add_argument("--hub", default="hf", help="'local:<dir>' runs without the Hub (first smoke test)")
    a = p.parse_args()
    start = os.environ.setdefault("PM_SESSION_START", str(time.time()))
    heavy = heavy_dir()
    work, env_dir, venv = heavy / "pm-work", heavy / "pm-work" / "env", heavy / "vllm-env"
    env_dir.mkdir(parents=True, exist_ok=True)
    os.environ["HF_HOME"] = str(heavy / "hf-cache")
    os.environ["TOKENIZERS_PARALLELISM"] = "false"
    os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"

    sh([sys.executable, "-m", "pip", "install", "-q", "uv"])
    constraints = work / "constraints.txt"
    constraints.write_text(f"torch=={md.version('torch')}\n")
    sh(["uv", "pip", "install", "-q", "--python", sys.executable, "-c", constraints, "-r",
        CODE / "kaggle" / "requirements-train.txt"])
    # Kaggle ships torchao 0.10, which PEFT 0.21+ rejects at LoRA creation even though we never use it.
    subprocess.run(["uv", "pip", "uninstall", "-q", "--python", sys.executable, "torchao"])
    gen_python = venv / "bin" / "python"
    if not gen_python.exists():
        sh(["uv", "venv", "-q", venv, "--python", sys.executable])
    vllm_spec = os.environ.get("PM_VLLM_SPEC")
    reqs = ["-r", CODE / "kaggle" / "requirements-gen.txt"] + ([vllm_spec] if vllm_spec else [])
    sh(["uv", "pip", "install", "-q", "--python", gen_python, *reqs])

    for name, py in (("train", sys.executable), ("gen", str(gen_python))):
        with open(env_dir / f"pip-freeze-{name}.txt", "w") as f:
            subprocess.run([py, "-m", "pip", "freeze"] if name == "train" else
                           ["uv", "pip", "freeze", "--python", py], stdout=f, text=True)
    with open(env_dir / "nvidia-smi.txt", "w") as f:
        subprocess.run(["nvidia-smi"], stdout=f, stderr=subprocess.STDOUT, text=True)
    print(f"setup took {(time.time() - float(start)) / 60:.1f} min", flush=True)

    env = {**os.environ, "PYTHONPATH": str(CODE), "PM_SESSION_START": start}
    runner = subprocess.Popen([sys.executable, "-m", "pocket_math.runner", "--job", a.job, "--ops-repo",
                               a.ops_repo, "--work", str(work), "--gen-python", str(gen_python), "--env-dir",
                               str(env_dir), "--budget-hours", str(a.budget_hours), "--hub", a.hub], env=env,
                              start_new_session=True)
    # The runner stops on its own before the budget ends; this only catches a hang, so the logs
    # below are still copied before Kaggle's 12-hour kill.
    limit = float(start) + a.budget_hours * 3600 + 20 * 60 - time.time()
    try:
        rc = runner.wait(timeout=max(limit, 60))
    except subprocess.TimeoutExpired:
        print("runner passed its deadline; stopping it", flush=True)
        os.killpg(runner.pid, 9)
        rc = runner.wait()
    out = Path("/kaggle/working/logs")
    if out.parent.exists():
        for log in work.glob("*/logs/*.log"):
            dst = out / log.parent.parent.name / log.name
            dst.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(log, dst)
    return rc


if __name__ == "__main__":
    sys.exit(main())