File size: 7,299 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""Phase 0 checks on a real Kaggle T4 x2. Each part is recorded as works or fails, and later parts still run.



Parts: environment, vLLM generation speed, fp16 against fp32 log-probs (student and teachers),

teacher scoring speed, training memory at 4k-32k tokens, and the Python sandbox in the vLLM venv.

Results go to results/smoke.json after every part.

"""

from __future__ import annotations

import json
import subprocess
import sys
import time
import traceback
from typing import Any

from .config import profile
from .context import JobContext
from .io import write_jsonl


def _versions(python: str) -> dict[str, str]:
    code = ("import importlib.metadata as m, json; out={}\n"
            "for p in ['torch','transformers','peft','vllm','math-verify','huggingface_hub','sympy','numpy']:\n"
            "    try: out[p]=m.version(p)\n    except Exception: out[p]=None\nprint(json.dumps(out))")
    r = subprocess.run([python, "-c", code], capture_output=True, text=True, timeout=120)
    return json.loads(r.stdout.strip().splitlines()[-1]) if r.returncode == 0 else {"error": r.stderr[-500:]}


def run(ctx: JobContext) -> str:
    from .modeling import load_tokenizer
    from .phases import gen_spec, materialize, prompt_ids, run_generation, run_scoring

    cfg = ctx.config
    report: dict[str, Any] = ctx.read_json("results/smoke.json", {}) or {}

    def part(name: str, fn) -> Any:
        if report.get(name, {}).get("ok"):
            return report[name].get("value")
        t0 = time.time()
        try:
            value = fn()
            report[name] = {"ok": True, "seconds": round(time.time() - t0, 1), "value": value}
        except Exception as e:  # noqa: BLE001 - a failing part is a result, not a crash
            report[name] = {"ok": False, "seconds": round(time.time() - t0, 1),
                            "error": f"{type(e).__name__}: {e}"[:3000], "trace": traceback.format_exc()[-3000:]}
            value = None
        ctx.commit({"results/smoke.json": report}, f"smoke: {name}")
        ctx.log(f"smoke {name}: {'works' if report[name]['ok'] else 'FAILS'}")
        return value

    part("env", lambda: {"main": _versions(sys.executable), "gen": _versions(ctx.session.gen_python),
                         "gpus": ctx.session.n_gpus,
                         "nvidia_smi": subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout[-3000:]})

    student_prof = cfg["profile"]
    student_dir = materialize(ctx, cfg["student"])
    problems = cfg["problems"]
    samples_path = ctx.work / "smoke_samples.jsonl.gz"

    def generate():
        tok = load_tokenizer(student_dir)
        items = [(f"smoke/{i}", prompt_ids(tok, profile(student_prof), p["problem"])) for i, p in enumerate(problems)]
        spec = gen_spec(student_dir, student_prof, {"n": int(cfg.get("n", 4)), "max_new_tokens": cfg.get("gen_tokens", 2048),
                                                    "vllm": cfg.get("vllm")}, 0, eval_mode=False)
        t0 = time.time()
        samples = run_generation(ctx, spec, items, "smoke-gen", timeout=3600)
        secs = time.time() - t0
        write_jsonl(samples_path, (s.to_json() for s in samples))
        toks = sum(len(s.response_ids) for s in samples)
        vllm_env = (ctx.session.work / "vllm_env.json")
        return {"samples": len(samples), "tokens": toks, "seconds_incl_startup": round(secs, 1),
                "tok_per_s_incl_startup": round(toks / secs, 1),
                "vllm_env": json.loads(vllm_env.read_text()) if vllm_env.exists() else None,
                "truncated": sum(s.truncated for s in samples),
                "example_tail": samples[0].text[-400:] if samples else ""}

    part("generate", generate)
    models = [("student", cfg["student"], student_prof)] + [(f"teacher:{t['profile']}", t["model"], t["profile"])
                                                            for t in cfg.get("teachers", [])]
    for label, ref, prof_name in models:
        trust = bool(profile(prof_name).get("trust_remote_code"))

        def precision(ref=ref, trust=trust, prof_name=prof_name):
            d = materialize(ctx, ref, trust)
            out = ctx.work / f"precision-{prof_name}.json"
            cmd = [sys.executable, "-m", "pocket_math.bench", "precision", "--model", str(d), "--samples",
                   str(samples_path), "--out", str(out)] + (["--trust-remote-code"] if trust else []) +                 (["--vs-generator"] if prof_name == student_prof else [])
            ctx.run(cmd, f"precision-{prof_name}", timeout=3600, env={"CUDA_VISIBLE_DEVICES": "0"}, secret_free=True)
            return json.loads(out.read_text())

        part(f"precision:{label}", precision)
        if label == "student":
            continue

        def score_speed(ref=ref, trust=trust, prof_name=prof_name):
            from .io import read_jsonl

            d = materialize(ctx, ref, trust)
            tok = load_tokenizer(d, trust)
            rows = []
            for i, r in enumerate(read_jsonl(samples_path)):
                p = problems[int(r["uid"].split("/")[1])]["problem"]
                rows.append({"idx": i, "prompt_ids": prompt_ids(tok, profile(prof_name), p),
                             "response_ids": r["response_ids"]})
            t0 = time.time()
            scores = run_scoring(ctx, d, rows, f"score-{prof_name}", timeout=3600, trust_remote_code=trust)
            secs = time.time() - t0
            toks = sum(len(r["response_ids"]) for r in rows)
            return {"rows": len(scores), "tokens": toks, "seconds_incl_load": round(secs, 1),
                    "tok_per_s_incl_load": round(toks / secs, 1)}

        part(f"score_speed:{label}", score_speed)

    def train_mem():
        out = ctx.work / "train_mem.json"
        cmd = [sys.executable, "-m", "pocket_math.bench", "train-mem", "--model", str(student_dir), "--lens",
               ",".join(str(x) for x in cfg.get("train_lens", [4096, 8192, 16384, 32768])),
               "--rank", str(cfg.get("lora_rank", 64)), "--out", str(out)]
        ctx.run(cmd, "train-mem", timeout=3600, env={"CUDA_VISIBLE_DEVICES": "0"}, secret_free=True)
        return json.loads(out.read_text())

    part("train_memory", train_mem)

    def sandbox():
        code = ("from pocket_math.sandbox import run_python, format_tool_output\n"
                "r = run_python('import sympy, os\\nprint(sympy.factorint(2**32+1), \"HF_TOKEN\" in os.environ)')\n"
                "print(format_tool_output(r))")
        r = subprocess.run([ctx.session.gen_python, "-c", code], capture_output=True, text=True, timeout=300,
                           env={"PYTHONPATH": str(__import__("pathlib").Path(__file__).resolve().parent.parent),
                                "PATH": __import__("os").environ.get("PATH", "")})
        if r.returncode != 0 or "641" not in r.stdout or "True" in r.stdout:
            raise RuntimeError(f"sandbox output: {r.stdout[-500:]} {r.stderr[-500:]}")
        return r.stdout.strip()

    part("sandbox", sandbox)
    ok = sum(1 for v in report.values() if v.get("ok"))
    ctx.log(f"smoke finished: {ok}/{len(report)} parts work")
    return "done"