Download code/pocket_math/evaluate.py from Palaestra/pocket-math-ops: direct link, hf CLI and curl.
- Browser
- Download file 6.66 kB
-
https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/evaluate.py
- Command line
-
hf download hf://datasets/Palaestra/pocket-math-ops/code/pocket_math/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/evaluate.py
6.66 kB
| """Evaluation jobs: k samples per problem at the model's own token cap, graded with Math-Verify. | |
| Scores at smaller caps come from the same run: an answer counts at cap c only if it finished | |
| (not truncated) within c tokens, which is exactly what a run capped at c would have produced. | |
| Work is committed every chunk of problems, so a session can stop anywhere and the next one | |
| continues with the problems not yet done. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import time | |
| from collections import defaultdict | |
| from typing import Any | |
| from .config import profile | |
| from .context import JobContext, PhaseTimeout | |
| from .io import append_jsonl, read_jsonl, write_jsonl | |
| from .phases import gen_spec, load_problems, materialize, prompt_ids, run_generation | |
| TOOL_NOTE = ("You may run Python to help: put code between <tool_call> and </tool_call>, and its output " | |
| "will appear in an ```output block. Give the final answer in \\boxed{}.") | |
| COMMIT_MARGIN = 10 * 60 | |
| DEFAULT_CHUNK_SECONDS = 30 * 60 | |
| def correct_at(row: dict[str, Any], cap: int) -> bool: | |
| return bool(row["correct"]) and row["finish"] == "stop" and row["tokens"] <= cap | |
| def summarize(rows: list[dict[str, Any]], cap: int, caps: list[int] | None = None) -> dict[str, Any]: | |
| caps = sorted({c for c in (caps or [8192, 16384, 32768, 65536]) if c < cap} | {cap}) | |
| by_uid: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| for r in rows: | |
| by_uid[r["uid"]].append(r) | |
| def pass1(c: int, uids: list[str]) -> float: | |
| per = [sum(correct_at(r, c) for r in by_uid[u]) / len(by_uid[u]) for u in uids] | |
| return 100 * sum(per) / max(len(per), 1) | |
| uids = sorted(by_uid) | |
| by_source: dict[str, list[str]] = defaultdict(list) | |
| for u in uids: | |
| by_source[by_uid[u][0]["source"]].append(u) | |
| return { | |
| "problems": len(uids), "samples": len(rows), "cap": cap, | |
| "pass1": {str(c): round(pass1(c, uids), 2) for c in caps}, | |
| "pass1_by_source": {s: round(pass1(cap, us), 2) for s, us in sorted(by_source.items())}, | |
| "truncation_rate": round(sum(r["finish"] == "length" for r in rows) / max(len(rows), 1), 4), | |
| "mean_tokens": round(sum(r["tokens"] for r in rows) / max(len(rows), 1), 1), | |
| } | |
| def tail_conf(logprobs: list[float | None], window: int = 2048) -> float | None: | |
| vals = [x for x in logprobs[-window:] if x is not None and not math.isnan(x)] | |
| return sum(vals) / len(vals) if vals else None | |
| def run(ctx: JobContext) -> str: | |
| from .grading import extract_boxed, grade_many | |
| from .modeling import load_tokenizer | |
| cfg = ctx.config | |
| prof = profile(cfg["profile"]) | |
| cap = int(cfg.get("max_new_tokens") or prof["max_new_tokens"]) | |
| problems = load_problems(ctx, cfg["problems"]) | |
| shard, n_shards = cfg.get("shard", [0, 1]) | |
| problems = problems[shard::n_shards] | |
| # metrics.jsonl too: ctx.metric appends to the local copy, so without it a resumed job | |
| # would overwrite the earlier sessions' chunk timings. | |
| ctx.fetch(["results/results.jsonl", "metrics.jsonl"]) | |
| results_path = ctx.repo_dir / "results" / "results.jsonl" | |
| rows = list(read_jsonl(results_path)) if results_path.exists() else [] | |
| done = {r["uid"] for r in rows} | |
| remaining = [p for p in problems if p.uid not in done] | |
| ctx.log(f"{len(problems)} problems in this shard, {len(remaining)} left, k={cfg.get('k', 4)}, cap={cap}") | |
| if not remaining: | |
| return "done" | |
| trust = bool(prof.get("trust_remote_code")) | |
| model_dir = materialize(ctx, cfg["model"], trust) | |
| tok = load_tokenizer(model_dir, trust) | |
| note = cfg.get("tool_note", TOOL_NOTE) if cfg.get("tool") else None | |
| chunk = int(cfg.get("chunk_problems", 40)) | |
| gen_cfg = {"n": int(cfg.get("k", 4)), "max_new_tokens": cap, "sampling": cfg.get("sampling"), | |
| "backend": cfg.get("backend", "vllm"), "vllm": cfg.get("vllm"), "tool": cfg.get("tool", False)} | |
| gold = {p.uid: p for p in problems} | |
| n_chunk = int(ctx.state.get("chunks", 0)) | |
| while remaining: | |
| batch, remaining = remaining[:chunk], remaining[chunk:] | |
| est = ctx.state.get("phase_secs", {}).get("chunk", DEFAULT_CHUNK_SECONDS) | |
| ctx.require_time(est * 1.25 + COMMIT_MARGIN, f"eval chunk {n_chunk}") | |
| t0 = time.time() | |
| items = [(p.uid, prompt_ids(tok, prof, p.problem, note)) for p in batch] | |
| spec = gen_spec(model_dir, cfg["profile"], gen_cfg, int(cfg.get("seed", 0)) * 1_000_003 + n_chunk, | |
| eval_mode=True) | |
| try: | |
| samples = run_generation(ctx, spec, items, f"eval-{n_chunk}", timeout=max(3 * est, 3600)) | |
| except PhaseTimeout as e: | |
| ctx.commit({}, f"eval chunk {n_chunk} timed out; estimate raised", | |
| state={"phase_secs": {"chunk": 2 * max(est, e.elapsed)}}) | |
| raise | |
| graded = grade_many([(s.text, gold[s.uid].answer) for s in samples]) | |
| seen: dict[str, int] = defaultdict(int) | |
| new_rows = [] | |
| for s, ok in zip(samples, graded, strict=True): | |
| row = {"uid": s.uid, "source": gold[s.uid].source, "sample": seen[s.uid], "tokens": len(s.response_ids), | |
| "finish": s.finish, "answer": extract_boxed(s.text), "correct": bool(ok) and not s.truncated, | |
| "tail_conf": tail_conf(s.sampler_logprobs)} | |
| seen[s.uid] += 1 | |
| new_rows.append(row) | |
| append_jsonl(results_path, row) | |
| rows += new_rows | |
| resp = ctx.repo_dir / "results" / "responses" / f"chunk-{n_chunk:04d}.jsonl.gz" | |
| write_jsonl(resp, ({"uid": s.uid, "finish": s.finish, "text": s.text} for s in samples)) | |
| summary = summarize(rows, cap, cfg.get("caps")) | |
| secs = time.time() - t0 | |
| phase_secs = {"chunk": secs if "chunk" not in ctx.state.get("phase_secs", {}) else 0.5 * est + 0.5 * secs} | |
| ctx.metric({"chunk": n_chunk, "problems": len(batch), "seconds": secs, | |
| "tokens": sum(len(s.response_ids) for s in samples)}) | |
| n_chunk += 1 | |
| ctx.commit({"results/results.jsonl": results_path, f"results/responses/{resp.name}": resp, | |
| "results/summary.json": summary, "metrics.jsonl": ctx.repo_dir / "metrics.jsonl"}, | |
| f"eval chunk {n_chunk - 1}", state={"chunks": n_chunk, "phase_secs": phase_secs, | |
| "summary": summary["pass1"]}) | |
| ctx.log(f"chunk {n_chunk - 1}: {len(batch)} problems in {secs / 60:.1f} min; pass@1 so far {summary['pass1']}") | |
| return "done" | |