okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
8.0 KiB153 linesraw
1"""Complete missing quality cases within the original measurement clock."""
2import argparse
3import json
4import socket
5import subprocess
6import sys
7import time
8
9from evalplus.sanitize import sanitize
10from strata_bench_continue import Continuation, b
11
12
13def finish_small(runner, scope, context):
14    cases = json.loads((b.OUT / "japanese-cases.json").read_text(encoding="utf-8"))
15    tool_cases = json.loads((b.OUT / "tool-cases.json").read_text(encoding="utf-8"))
16    tools, pairs = tool_cases["schema"], tool_cases["pairs"]
17    def grade(model, group, index, passed):
18        with (b.OUT / "grades.jsonl").open("a", encoding="utf-8") as file:
19            file.write(json.dumps({"model": model, "group": group, "index": index, "pass": passed,
20                "context": runner.ctx, "stage": "supplement"})+"\n")
21    for model, needed in scope.items():
22        if not any(needed.values()) or runner.left() < 30:
23            continue
24        def run():
25            runner.start(model, context)
26            for i in needed["japanese"]:
27                prompt, expected = cases[i]
28                row = runner.perform(f"supplement-japanese-{i}-ctx{context}", prompt, group="japanese", max_tokens=128)
29                text = row["text"].strip().strip("`").strip()
30                try:
31                    actual = json.loads(text) if isinstance(expected, (list, dict)) else text
32                except ValueError:
33                    actual = None
34                grade(model, "japanese", i, actual == expected)
35                runner.event("japanese_grade", index=i, passed=actual == expected)
36            for i in needed["tool"]:
37                a, value_b = pairs[i]
38                body = runner.body(f"Use the add tool to add {a} and {value_b}. Do not compute it yourself.", 128)
39                body["tools"] = tools
40                row = runner.perform(f"supplement-tool-{i}-ctx{context}", body=body, group="tool")
41                calls = row["tool_calls"]
42                call = calls[0] if len(calls) == 1 else None
43                try:
44                    valid = bool(call and call["function"]["name"] == "add" and json.loads(call["function"]["arguments"]) == {"a": a, "b": value_b})
45                except ValueError:
46                    valid = False
47                if valid:
48                    follow = runner.body("", 128)
49                    follow["tools"] = tools
50                    follow["messages"] = body["messages"] + [{"role": "assistant", "content": row["text"], "tool_calls": calls},
51                        {"role": "tool", "tool_call_id": call["id"], "content": str(a+value_b)},
52                        {"role": "user", "content": "Reply with only the integer result returned by the tool."}]
53                    reply = runner.perform(f"supplement-tool-followup-{i}-ctx{context}", body=follow, group="tool_followup")
54                    valid = reply["text"].strip() == str(a+value_b)
55                grade(model, "tool", i, valid)
56        runner.safe_block(run)
57        runner.stop()
58
59
60def finish_mtp(runner, scope):
61    for model, states in scope.items():
62        for state, reps in states.items():
63            if not reps or runner.left() < 30:
64                continue
65            def run():
66                runner.start(model, mtp=state == "on")
67                for rep in reps:
68                    runner.perform(f"supplement-mtp-{state}-{rep}", runner.make(4096, rep=50+rep), 4096,
69                        group="mtp", max_tokens=1024)
70            runner.safe_block(run)
71            runner.stop()
72
73
74def main():
75    parser = argparse.ArgumentParser()
76    parser.add_argument("--max-minutes", type=float, default=20)
77    parser.add_argument("--small", action="store_true", help="Also finish ungraded Japanese/tool cases")
78    parser.add_argument("--small-context", type=int, choices=(8192, 131072), default=131072,
79        help="Explicit context for the supplemental small tasks; preserved in grades and configurations")
80    parser.add_argument("--mtp", action="store_true", help="Also finish missing MTP comparison repetitions")
81    args = parser.parse_args()
82    dataset = json.loads((b.OUT / "humaneval-subset.json").read_text(encoding="utf-8"))
83    missing = {}
84    for model in b.MODELS:
85        path = b.OUT / "code" / f"{model}-samples.jsonl"
86        saved = {json.loads(s)["task_id"] for s in path.read_text(encoding="utf-8").splitlines() if s.strip()} if path.exists() else set()
87        missing[model] = [tid for tid in dataset["ids"] if tid not in saved]
88    grades_path = b.OUT / "grades.jsonl"
89    grades = [json.loads(s) for s in grades_path.read_text(encoding="utf-8").splitlines() if s.strip()] if grades_path.exists() else []
90    marked = {(r["model"], r["group"], r["index"]) for r in grades}
91    small_missing = {model: {group: [i for i in range(n) if (model, group, i) not in marked]
92        for group, n in (("japanese", 12), ("tool", 8))} for model in b.MODELS}
93    requests = [json.loads(s) for s in (b.OUT / "requests.jsonl").read_text(encoding="utf-8").splitlines() if s.strip()]
94    mtp_missing = {model: {state: [rep for rep in (1, 2, 3) if not any(
95        r["model"] == model and r["group"] == "mtp" and r["label"].removeprefix("supplement-") == f"mtp-{state}-{rep}"
96        and r.get("ok") and r.get("token_count_matches") and r.get("engine", {}).get("reused") == 0 for r in requests)]
97        for state in ("on", "off")} for model in ("iq2_xs", "iq3_s")}
98    if not any(missing.values()) and not (args.small and any(any(v.values()) for v in small_missing.values())) and not (
99        args.mtp and any(any(v.values()) for v in mtp_missing.values())):
100        print(json.dumps({"already_complete": True}), flush=True)
101        return
102    with socket.socket() as sock:
103        if sock.connect_ex(("127.0.0.1", b.PORT)) == 0:
104            raise RuntimeError("Benchmark service is occupied; it was preserved")
105    runner = Continuation(["iq3_xxs", "iq3_s"])
106    (b.OUT / "code-completion.pid").write_text(str(b.os.getpid()))
107    supervisor = subprocess.Popen([sys.executable, str(b.SCRIPT), "--watchdog", str(b.os.getpid()),
108        str(runner.clock["measurement_stop_epoch"]+300)], stdout=subprocess.DEVNULL,
109        stderr=subprocess.DEVNULL, creationflags=b.FLAGS)
110    try:
111        runner.budget("code_completion", min(args.max_minutes*60, max(0, runner.hard-time.monotonic())))
112        runner.event("code_completion_scope", missing=missing, small_missing=small_missing if args.small else {},
113            mtp_missing=mtp_missing if args.mtp else {})
114        runner.init_tokenizer()
115        runner.inventory()
116        for model, ids in missing.items():
117            if not ids or runner.left() < 30:
118                continue
119            def generate():
120                runner.start(model)
121                path = b.OUT / "code" / f"{model}-samples.jsonl"
122                with path.open("a", encoding="utf-8") as file:
123                    for tid in ids:
124                        if runner.left() < 5:
125                            break
126                        problem = dataset["problems"][tid]
127                        row = runner.perform("supplement-code-" + tid.replace("/", "-"),
128                            "Complete this Python function. Output valid Python code only, no explanations.\n\n" + problem["prompt"],
129                            group="code", max_tokens=1024)
130                        solution = sanitize(row["text"], problem["entry_point"])
131                        file.write(json.dumps({"task_id": tid, "solution": solution})+"\n")
132                        file.flush()
133            runner.safe_block(generate)
134            runner.stop()
135        if args.small:
136            finish_small(runner, small_missing, args.small_context)
137        if args.mtp:
138            finish_mtp(runner, mtp_missing)
139        runner.evaluate(min(720, runner.left()))
140        runner.event("code_completion_finished")
141    finally:
142        if runner.active_worker and runner.active_worker.poll() is None:
143            b.kill_tree(runner.active_worker)
144        for job in runner.child_jobs:
145            b.kill_tree(job)
146        runner.stop()
147        runner.monitor.done.set()
148        if supervisor.poll() is None:
149            supervisor.terminate()
150
151
152if __name__ == "__main__":
153    main()