File size: 8,795 Bytes
b5d98ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbfa56
b5d98ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbfa56
 
b5d98ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""The inference system: confidence-weighted voting with early stop, the Python tool, and answer repair.



Reported as a system score (with samples and tokens per problem), never as pass@1.



    python -m pocket_math.system --spec spec.json --inp problems.jsonl --out results.jsonl   (vLLM venv)



The job handler (`run`) shards problems across GPUs, resumes by problem, and commits chunks.

"""

from __future__ import annotations

import argparse
import json
import math
import sys
import time
from pathlib import Path
from typing import Any

from .context import JobContext, PhaseTimeout
from .io import append_jsonl, read_jsonl, write_json, write_jsonl

REPAIR_SUFFIX = "\n\n**Final Answer**\n\\[\n\\boxed{"


def _conf(lps: list[float], window: int) -> float:
    vals = [x for x in lps[-window:] if x is not None and not math.isnan(x)]
    return sum(vals) / len(vals) if vals else -1e9


def solve_all(spec_d: dict[str, Any], problems: list[dict[str, Any]], out_path: Path) -> None:
    from transformers import AutoTokenizer

    from .generate import GenSpec, generate_samples, make_backend, occurrence_keys, request_seeds
    from .grading import extract_boxed, grade, same_answer
    from .voting import Vote, decide, should_stop

    spec = GenSpec.from_json(spec_d)
    tok = AutoTokenizer.from_pretrained(spec.model_dir, trust_remote_code=spec.trust_remote_code)
    backend = make_backend(spec)
    wave, max_samples = int(spec_d.get("wave", 8)), int(spec_d.get("max_samples", 64))
    vote_kw = {"keep_top": float(spec_d.get("keep_top", 1.0)), "weighting": spec_d.get("weighting", "count")}
    stop_kw = {"min_votes": int(spec_d.get("min_votes", 8)), "threshold": float(spec_d.get("threshold", 0.75))}
    window = int(spec_d.get("conf_window", 2048))
    votes: dict[str, list[Vote]] = {p["uid"]: [] for p in problems}
    tokens: dict[str, int] = {p["uid"]: 0 for p in problems}
    repaired: dict[str, int] = {p["uid"]: 0 for p in problems}
    by_uid = {p["uid"]: p for p in problems}
    active = [p["uid"] for p in problems]
    step = 0
    while active:
        wave_spec = GenSpec.from_json({**spec_d, "n": wave, "seed": spec.seed + 1009 * step})
        samples = generate_samples(backend, [(u, by_uid[u]["prompt_ids"]) for u in active], wave_spec, tok)
        need_repair = []
        for s in samples:
            tokens[s.uid] += len(s.response_ids)
            ans = None if s.truncated else extract_boxed(s.text)
            if ans is None and spec_d.get("repair", True):
                need_repair.append(s)
            else:
                votes[s.uid].append(Vote(ans, _conf(s.sampler_logprobs, window)))
        if need_repair:
            suffix = tok(REPAIR_SUFFIX, add_special_tokens=False).input_ids
            keep = spec.max_new_tokens - len(suffix) - 48
            prompts = [s.prompt_ids + s.response_ids[:keep] + suffix for s in need_repair]
            greedy = GenSpec.from_json({**spec_d, "temperature": 0.0, "top_p": 1.0, "n": 1})
            outs = backend.complete(prompts, 1, [40] * len(prompts), greedy, list(spec.stop_token_ids),
                                    request_seeds(spec.seed, occurrence_keys([s.uid for s in need_repair])))
            for s, comps in zip(need_repair, outs, strict=True):
                text = "\\boxed{" + tok.decode(comps[0].token_ids, skip_special_tokens=True)
                ans = extract_boxed(text if "}" in text else text + "}")
                repaired[s.uid] += 1
                votes[s.uid].append(Vote(ans, _conf(s.sampler_logprobs, window) - 1.0))
        still = []
        for u in active:
            n = len(votes[u])
            if n >= max_samples or should_stop(votes[u], same_answer, **stop_kw, **vote_kw):
                d = decide(votes[u], same_answer, **vote_kw)
                ok = bool(d.answer) and grade("\\boxed{" + d.answer + "}", by_uid[u]["answer"])
                append_jsonl(out_path, {"uid": u, "source": by_uid[u]["source"], "answer": d.answer, "correct": ok,
                                        "share": round(d.share, 4), "n_samples": n, "tokens": tokens[u],
                                        "repaired": repaired[u]})
            else:
                still.append(u)
        active = still
        step += 1


def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
    n = max(len(rows), 1)
    return {"problems": len(rows), "accuracy": round(100 * sum(r["correct"] for r in rows) / n, 2),
            "mean_samples": round(sum(r["n_samples"] for r in rows) / n, 2),
            "mean_tokens": round(sum(r["tokens"] for r in rows) / n, 1)}


def run(ctx: JobContext) -> str:
    from .config import profile
    from .evaluate import TOOL_NOTE
    from .modeling import load_tokenizer
    from .phases import gen_spec, load_problems, materialize, prompt_ids

    cfg = ctx.config
    prof = profile(cfg["profile"])
    problems = load_problems(ctx, cfg["problems"])
    shard, n_shards = cfg.get("shard", [0, 1])
    problems = problems[shard::n_shards]
    ctx.fetch(["results/results.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]
    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", 24))
    n_chunk = int(ctx.state.get("chunks", 0))
    while remaining:
        batch, remaining = remaining[:chunk], remaining[chunk:]
        est = ctx.state.get("phase_secs", {}).get("chunk", 3600)
        ctx.require_time(est * 1.25 + 600, f"system chunk {n_chunk}")
        t0 = time.time()
        spec = gen_spec(model_dir, cfg["profile"], {"n": 1, "max_new_tokens": cfg.get("max_new_tokens"),
                                                     "sampling": cfg.get("sampling"), "vllm": cfg.get("vllm"),
                                                     "backend": cfg.get("backend", "vllm"), "tool": cfg.get("tool", False)},
                        int(cfg.get("seed", 0)) * 1_000_003 + n_chunk, eval_mode=True)
        spec_d = {**spec.__dict__, **(cfg.get("voting") or {})}
        root = ctx.work / "system" / f"chunk-{n_chunk}"
        n = max(1, ctx.session.n_gpus) if spec.backend == "vllm" else 1
        procs = []
        for i in range(n):
            part = batch[i::n]
            if not part:
                continue
            d = root / str(i)
            write_jsonl(d / "problems.jsonl", ({"uid": p.uid, "source": p.source, "answer": p.answer,
                                                "prompt_ids": prompt_ids(tok, prof, p.problem, note)} for p in part))
            write_json(d / "spec.json", {**spec_d, "seed": spec_d["seed"] + 7919 * i})
            python = ctx.session.gen_python if spec.backend == "vllm" else sys.executable
            procs.append(([python, "-m", "pocket_math.system", "--spec", str(d / "spec.json"), "--inp",
                           str(d / "problems.jsonl"), "--out", str(d / "out.jsonl")],
                          {"CUDA_VISIBLE_DEVICES": str(i)} if ctx.session.n_gpus else {}))
        try:
            ctx.run_many(procs, f"system-{n_chunk}", timeout=max(3 * est, 3600), secret_free=True)
        except PhaseTimeout as e:
            ctx.commit({}, f"system chunk {n_chunk} timed out; estimate raised",
                       state={"phase_secs": {"chunk": 2 * max(est, e.elapsed)}})
            raise
        for i in range(len(procs)):
            for r in read_jsonl(root / str(i) / "out.jsonl"):
                rows.append(r)
                append_jsonl(results_path, r)
        summary = summarize(rows)
        secs = time.time() - t0
        n_chunk += 1
        ctx.commit({"results/results.jsonl": results_path, "results/summary.json": summary},
                   f"system chunk {n_chunk - 1}",
                   state={"chunks": n_chunk, "phase_secs": {"chunk": secs}, "summary": summary})
    return "done"


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser()
    p.add_argument("--spec", required=True)
    p.add_argument("--inp", required=True)
    p.add_argument("--out", required=True)
    a = p.parse_args(argv)
    out = Path(a.out)
    out.unlink(missing_ok=True)
    solve_all(json.loads(Path(a.spec).read_text()), list(read_jsonl(a.inp)), out)
    return 0


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