File size: 6,793 Bytes
d53b365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""k2_code_bench.py — smallish executable coding benchmark (MBPP) with a one-step feedback retry.

Per item: 3-shot MBPP prompt -> generate the function -> run the item's asserts in a
subprocess. If it fails, feed the failing assert back and let the model produce a corrected
version (pass@2 with feedback; the "slightly agentic" part, bounded to one retry).

Emits the same task JSON shape as k2_task_bench.py (task name "code") so k2_task_compare.py
works unchanged. Items are sorted by task_id, identical across runs.

Usage:
  python k2_code_bench.py --port 8399 --tag f16                       # all 424 eval items
  python k2_code_bench.py --port 8399 --tag clean --ids code_ids_f16.json
  python k2_code_bench.py --port 8399 --tag f16 --n 20 --out /tmp/x.json   # smoke
"""
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import urllib.request

DATA = "/mnt/Data/qat_k2/code_eval/sanitized-mbpp.json"
PY = sys.executable

SYS = ("You are an expert Python programmer, and here is your task: {prompt} "
       "Your code should pass these tests:\n\n{tests}\n\n[BEGIN]\n{code}[DONE]\n\n")


def load_items(path=DATA):
    d = json.load(open(path))
    return sorted(d, key=lambda x: x["task_id"])


def build_fewshot(items):
    """First 3 sanitized items as few-shot; they are excluded from the eval set."""
    shots, ids = [], []
    for it in items[:3]:
        tests = "\n".join(it["test_list"])
        code = it["code"].rstrip("\n") + "\n"
        shots.append(SYS.format(prompt=it["prompt"], tests=tests, code=code))
        ids.append(it["task_id"])
    return "".join(shots), ids


def target_prompt(it):
    return SYS.format(prompt=it["prompt"], tests="\n".join(it["test_list"]),
                      code="")[:-len("[DONE]\n\n")]


def gen(port, prompt, max_tokens=320, stop=("[DONE]", "\n\n\n")):
    body = json.dumps({"prompt": prompt, "max_tokens": max_tokens, "temperature": 0,
                       "stop": list(stop), "top_k": 1}).encode()
    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/completions", data=body,
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=600) as r:
        d = json.loads(r.read())
    return d["choices"][0]["text"]


def extract_code(text):
    """Slice out the first plausible top-level def block (drops trailing prose)."""
    text = text.split("[DONE]")[0]
    lines = text.splitlines()
    start = next((i for i, l in enumerate(lines)
                  if l.startswith(("def ", "import ", "from ", "class "))), None)
    if start is None:
        return ""
    out = []
    for l in lines[start:]:
        if l and not l[0].isspace() and not l.startswith(("#", "def ", "import ", "from ",
                                                          "class ", "@")):
            break
        out.append(l)
    return "\n".join(out).strip("\n")


def run_tests(it, code, timeout=10):
    imports = "\n".join(it.get("test_imports") or [])
    src = "\n".join(x for x in (imports, code, "\n".join(it["test_list"])) if x)
    with tempfile.TemporaryDirectory() as td:
        env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": td,
               "PYTHONHASHSEED": "0", "PYTHONDONTWRITEBYTECODE": "1"}
        try:
            p = subprocess.run([PY, "-c", src], capture_output=True, text=True,
                               timeout=timeout, cwd=td, env=env)
        except subprocess.TimeoutExpired:
            return False, "timeout"
        if p.returncode == 0:
            return True, ""
        err = (p.stderr or "").strip().splitlines()
        return False, (err[-1] if err else f"exit {p.returncode}")[:300]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=8399)
    ap.add_argument("--tag", required=True)
    ap.add_argument("--ids", help="JSON list of task_ids to run (e.g. the F16-solvable set)")
    ap.add_argument("--n", type=int, default=0, help="first N eval items (0 = all)")
    ap.add_argument("--attempts", type=int, default=2)
    ap.add_argument("--data", default=DATA)
    ap.add_argument("--out", default=None)
    ap.add_argument("--ids-out", default=None, help="write the task_ids this run solved")
    args = ap.parse_args()

    items = load_items(args.data)
    fewshot, shot_ids = build_fewshot(items)
    eval_items = [it for it in items if it["task_id"] not in shot_ids]
    if args.ids:
        want = set(json.load(open(args.ids)))
        eval_items = [it for it in eval_items if it["task_id"] in want]
    if args.n:
        eval_items = eval_items[:args.n]

    t0 = time.time()
    recs, solved = [], []
    for k, it in enumerate(eval_items):
        prompt = fewshot + target_prompt(it)
        ok, code, err, used = False, "", "", 0
        for a in range(args.attempts):
            used = a + 1
            try:
                raw = gen(args.port, prompt)
            except Exception as e:  # noqa: BLE001
                err = f"gen error: {e}"
                break
            code = extract_code(raw)
            ok, err = run_tests(it, code)
            if ok:
                break
            # one-step feedback retry: show the failing assert and ask for a corrected version
            prompt = (prompt + code + "\n\n# The tests failed with:\n# " + err.replace("\n", "\n# ")
                      + "\n# Corrected version:\n[BEGIN]\n")
        recs.append({"q": it["prompt"][:100], "gold": it["code"][:200], "pred": code,
                     "ok": ok, "task_id": it["task_id"], "attempts": used, "error": err})
        if ok:
            solved.append(it["task_id"])
        if (k + 1) % 10 == 0 or k + 1 == len(eval_items):
            acc = sum(r["ok"] for r in recs) / len(recs)
            print(f"  code {k+1}/{len(eval_items)} pass {acc*100:.1f}% "
                  f"({time.time()-t0:.0f}s)", flush=True)

    out = {"tag": args.tag,
           "tasks": {"code": {"acc": sum(r["ok"] for r in recs) / max(1, len(recs)),
                              "n": len(recs), "items": recs}},
           "elapsed_s": round(time.time() - t0, 1)}
    path = args.out or f"/mnt/Data/qat_k2/tasks_{args.tag}.json"
    if os.path.exists(path) and not args.out:
        old = json.load(open(path))
        old.setdefault("tasks", {}).update(out["tasks"])
        old["elapsed_s"] = old.get("elapsed_s", 0) + out["elapsed_s"]
        out = old
    json.dump(out, open(path, "w"), indent=1)
    if args.ids_out:
        json.dump(sorted(solved), open(args.ids_out, "w"), indent=0)
    print(f"== code: acc {out['tasks']['code']['acc']*100:.1f}% ({len(recs)}) "
          f"pass@1+feedback; solved {len(solved)} -> {path}")


if __name__ == "__main__":
    main()