#!/usr/bin/env python3 """Coding eval against any OpenAI-compatible server: vLLM (base / looped / flat-control adapter) or llama.cpp `llama-server` (GGUF). Outputs are verified, not judged. Benches lcb LiveCodeBench v6 (code_generation_lite test6.jsonl: AtCoder + LeetCode, Jan-Apr 2025). The program is run against all public + private tests in a bubblewrap sandbox. kodcode KodCode-V1 medium/hard problems never used in training, sandboxed pytest. visual data/visual_prompts.jsonl (three.js / canvas / SVG pages such as a pagoda tower). Each page is rendered in headless Chromium: pass = loads, no uncaught JS error, not blank. That is only a floor; judge the screenshots with `visual_gallery.py` (blind A/B). export OPENAI_BASE_URL=http://localhost:8000/v1 OPENAI_API_KEY=none python scripts/eval_code_api.py --model looped-phai --tag looped_t3 --bench lcb kodcode visual python scripts/eval_code_api.py --compare base looped_t3 # paired comparison + 95% CI Sampling follows the model card (temperature 1.0, top_p 0.95, top_k 20, thinking on) unless --greedy / --no-thinking. Use --samples 2-4 on lcb to reduce noise. Resumable: finished (bench, task, sample) records in //results.jsonl are skipped. """ from __future__ import annotations import argparse import base64 import io import json import os import pickle import random import statistics import sys import threading import time import zlib from argparse import Namespace from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from verifiers import extract_code, extract_last_code, run_cp_tests, run_pytest_sandboxed # noqa: E402 LCB_STDIN = ("You will be given a question (problem specification) and will generate a correct Python program " "that matches the specification and passes all tests.\n\nQuestion: {q}\n\nRead the inputs from stdin " "solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose " "your code within delimiters as follows. Ensure that when the python program runs, it reads the " "inputs, runs the algorithm and writes output to STDOUT.\n```python\n# YOUR CODE HERE\n```\n") LCB_FUNC = ("You will be given a question (problem specification) and will generate a correct Python program " "that matches the specification and passes all tests.\n\nQuestion: {q}\n\nYou will use the following " "starter code to write the solution to the problem and enclose your code within delimiters.\n" "```python\n{starter}\n```\n") # ----------------------------------------------------------------------------- task loading class _StrOnlyUnpickler(pickle.Unpickler): """LiveCodeBench stores private tests as base64(zlib(pickle(json string))). Only plain strings are allowed: any class/function reference in the pickle is refused.""" def find_class(self, module, name): raise pickle.UnpicklingError(f"refusing to unpickle {module}.{name}") def _lcb_tests(raw: str) -> list[dict]: try: return json.loads(raw) except ValueError: s = _StrOnlyUnpickler(io.BytesIO(zlib.decompress(base64.b64decode(raw)))).load() if not isinstance(s, str): raise ValueError("unexpected private-test payload") return json.loads(s) def load_lcb(n: int, seed: int, files: list[str]) -> list[dict]: from huggingface_hub import hf_hub_download rows = [] for fn in files: p = hf_hub_download("livecodebench/code_generation_lite", fn, repo_type="dataset") rows += [json.loads(x) for x in open(p, encoding="utf-8") if x.strip()] rows.sort(key=lambda r: r["question_id"]) random.Random(seed).shuffle(rows) tasks = [] for r in rows[:n] if n else rows: cases = json.loads(r["public_test_cases"]) + _lcb_tests(r["private_test_cases"]) kind = cases[0]["testtype"] meta = json.loads(r["metadata"] or "{}") prompt = (LCB_FUNC.format(q=r["question_content"], starter=r["starter_code"]) if kind == "functional" else LCB_STDIN.format(q=r["question_content"])) tasks.append({"bench": "lcb", "id": r["question_id"], "prompt": prompt, "kind": kind, "cases": cases, "func_name": meta.get("func_name"), "difficulty": r["difficulty"]}) return tasks def load_kodcode(n: int, seed: int) -> list[dict]: from eval_local import load_tasks, training_prompts a = Namespace(humaneval=0, kodcode=n, ifeval=0, seed=seed) seen = training_prompts(["data/train_mix_v1.jsonl", "data/rs_mix_inkling.jsonl", "data/rs_mix_inkling_eval.jsonl"]) return [{"bench": "kodcode", "id": t["id"], "prompt": t["prompt"], "test": t["test"]} for t in load_tasks(a, seen)] def load_visual(path: str) -> list[dict]: rows = [json.loads(x) for x in open(path, encoding="utf-8") if x.strip()] return [{"bench": "visual", "id": r["id"], "prompt": r["prompt"]} for r in rows] # ----------------------------------------------------------------------------- scoring def score_code(t: dict, answer: str) -> tuple[bool, str]: if t["bench"] == "lcb": code = extract_last_code(answer) if code is None: return False, "no code block" return run_cp_tests(code, t["kind"], t["cases"], t.get("func_name")) code = extract_code(answer) if code is None: return False, "no code block" return run_pytest_sandboxed(code, t["test"]) # ----------------------------------------------------------------------------- generation def make_caller(args): from openai import OpenAI client = OpenAI(base_url=args.base_url, api_key=os.environ.get("OPENAI_API_KEY") or "none", timeout=7200, max_retries=3) def call(messages: list[dict], seed: int) -> dict: kw = dict(model=args.model, messages=messages, max_tokens=args.max_tokens, seed=seed) extra = {"chat_template_kwargs": {"enable_thinking": not args.no_thinking}} if args.greedy: kw["temperature"] = 0.0 else: kw.update(temperature=args.temperature, top_p=0.95) extra["top_k"] = 20 t0 = time.time() resp = client.chat.completions.create(extra_body=extra, **kw) ch = resp.choices[0] m = ch.message ex = m.model_extra or {} reasoning = (getattr(m, "reasoning_content", None) or getattr(m, "reasoning", None) or ex.get("reasoning_content") or ex.get("reasoning") or "") content = m.content or "" if not reasoning and "" in content: # server without a reasoning parser reasoning, content = content.split("", 1) return {"answer": content.strip(), "reasoning_chars": len(reasoning), "finish": ch.finish_reason, "completion_tokens": resp.usage.completion_tokens if resp.usage else None, "sec": round(time.time() - t0, 1), "served_model": resp.model} return call def run(args) -> None: if not args.base_url: raise SystemExit("set OPENAI_BASE_URL or --base-url") out = Path(args.out) / args.tag out.mkdir(parents=True, exist_ok=True) tasks = [] if "lcb" in args.bench: tasks += load_lcb(args.lcb_n, args.seed, args.lcb_files) if "kodcode" in args.bench: tasks += load_kodcode(args.kodcode_n, args.seed) if "visual" in args.bench: tasks += load_visual(args.visual_file) res_path = out / "results.jsonl" done = set() if res_path.exists(): done = {(r["bench"], r["id"], r["sample"]) for r in map(json.loads, open(res_path, encoding="utf-8"))} jobs = [(t, s) for t in tasks for s in range(args.samples) if (t["bench"], t["id"], s) not in done] print(f"[eval] {args.tag}: {len(jobs)} generations to do ({len(done)} done), model={args.model}", flush=True) renderer = None if any(t["bench"] == "visual" for t, _ in jobs): from render_html import Renderer renderer = Renderer() (out / "visual").mkdir(exist_ok=True) call = make_caller(args) def work(t: dict, s: int) -> dict: g = call([{"role": "user", "content": t["prompt"]}], seed=args.seed * 1000 + s) rec = {"bench": t["bench"], "id": t["id"], "sample": s, **g} if t["bench"] != "visual": rec["pass"], rec["detail"] = score_code(t, g["answer"]) return rec lock = threading.Lock() n_done, t0 = 0, time.time() with open(res_path, "a", encoding="utf-8") as f, ThreadPoolExecutor(args.concurrency) as pool: futs = {pool.submit(work, t, s): (t, s) for t, s in jobs} for fut in as_completed(futs): t, s = futs[fut] try: rec = fut.result() except Exception as e: # noqa: BLE001 print(f"[eval] {t['bench']}/{t['id']} failed: {type(e).__name__}: {str(e)[:200]}", flush=True) continue if t["bench"] == "visual": # Playwright is not thread-safe: render here, in the main thread from render_html import extract_html html = extract_html(rec["answer"]) stem = out / "visual" / f"{t['id']}_s{s}" if html is None: rec["pass"], rec["detail"] = False, "no html block" else: stem.with_suffix(".html").write_text(html, encoding="utf-8") r = renderer.render(html, stem.with_suffix(".png")) rec["pass"], rec["detail"], rec["render"] = r["ok"], "" if r["ok"] else "render failed", r with lock: f.write(json.dumps(rec, ensure_ascii=False) + "\n") f.flush() n_done += 1 print(f"[eval] {n_done}/{len(jobs)} {t['bench']:8s} {t['id']:<28s} s{s} pass={int(rec['pass'])} " f"{rec['finish']} {rec['completion_tokens']} tok {rec['sec']}s {rec.get('detail', '')[:60]}", flush=True) if renderer: renderer.close() summary = summarize(res_path) (out / "summary.json").write_text(json.dumps(summary, indent=2)) print(f"[eval] done in {(time.time() - t0) / 60:.1f} min -> {out}", flush=True) # ----------------------------------------------------------------------------- reporting def load_results(path: Path) -> dict: """{bench: {task id: [pass per sample]}}""" by: dict = {} for r in map(json.loads, open(path, encoding="utf-8")): by.setdefault(r["bench"], {}).setdefault(r["id"], []).append(r) return by def summarize(path: Path) -> dict: summary = {} for bench, d in sorted(load_results(path).items()): recs = [r for v in d.values() for r in v] rate = statistics.mean(statistics.mean(r["pass"] for r in v) for v in d.values()) toks = [r["completion_tokens"] for r in recs if r.get("completion_tokens")] summary[bench] = {"problems": len(d), "samples": len(recs), "pass_rate": round(rate, 4), "capped": sum(r["finish"] == "length" for r in recs), "mean_tokens": round(statistics.mean(toks)) if toks else None} print(f"[eval] {bench:8s} pass={rate:.3f} over {len(d)} problems ({len(recs)} samples), " f"capped={summary[bench]['capped']} mean_tok={summary[bench]['mean_tokens']}", flush=True) return summary def compare(out_dir: Path, a: str, b: str, n_boot: int = 10000) -> None: """Paired comparison on the problems both runs finished, with a bootstrap 95% CI of B - A.""" ra, rb = load_results(out_dir / a / "results.jsonl"), load_results(out_dir / b / "results.jsonl") rng = random.Random(0) print(f"{'bench':8s} {'n':>4s} {a:>12s} {b:>12s} {'B-A':>7s} 95% CI only-A only-B") for bench in sorted(set(ra) & set(rb)): ids = sorted(set(ra[bench]) & set(rb[bench])) if not ids: continue pa = [statistics.mean(r["pass"] for r in ra[bench][i]) for i in ids] pb = [statistics.mean(r["pass"] for r in rb[bench][i]) for i in ids] diffs = [y - x for x, y in zip(pa, pb)] boots = sorted(statistics.mean(rng.choices(diffs, k=len(diffs))) for _ in range(n_boot)) lo, hi = boots[int(0.025 * n_boot)], boots[int(0.975 * n_boot)] only_a = sum(x > y for x, y in zip(pa, pb)) only_b = sum(y > x for x, y in zip(pa, pb)) verdict = "B better" if lo > 0 else "A better" if hi < 0 else "no significant difference" print(f"{bench:8s} {len(ids):4d} {statistics.mean(pa):12.3f} {statistics.mean(pb):12.3f} " f"{statistics.mean(diffs):+7.3f} [{lo:+.3f},{hi:+.3f}] {only_a:6d} {only_b:6d} {verdict}") def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--compare", nargs=2, metavar=("TAG_A", "TAG_B")) ap.add_argument("--model", default=None, help="served model name") ap.add_argument("--tag", default=None) ap.add_argument("--base-url", default=os.environ.get("OPENAI_BASE_URL")) ap.add_argument("--bench", nargs="+", default=["lcb", "kodcode", "visual"], choices=["lcb", "kodcode", "visual"]) ap.add_argument("--lcb-n", type=int, default=100, help="0 = all 175 v6 problems") ap.add_argument("--lcb-files", nargs="+", default=["test6.jsonl"]) ap.add_argument("--kodcode-n", type=int, default=50) ap.add_argument("--visual-file", default=str(HERE.parent / "data" / "visual_prompts.jsonl")) ap.add_argument("--samples", type=int, default=1) ap.add_argument("--concurrency", type=int, default=8) ap.add_argument("--max-tokens", type=int, default=32768) ap.add_argument("--temperature", type=float, default=1.0) ap.add_argument("--greedy", action="store_true") ap.add_argument("--no-thinking", action="store_true") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default="runs/code_eval") args = ap.parse_args() if args.compare: compare(Path(args.out), *args.compare) return if not (args.model and args.tag): raise SystemExit("--model and --tag are required (or use --compare)") run(args) if __name__ == "__main__": main()