Download code/pocket_math/smoke.py from Palaestra/pocket-math-ops: direct link, hf CLI and curl.
- Browser
- Download file 7.3 kB
-
https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/smoke.py
- Command line
-
hf download hf://datasets/Palaestra/pocket-math-ops/code/pocket_math/smoke.py
-
curl -L -o smoke.py https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/smoke.py
7.3 kB
| """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" | |