diff --git a/harbor_parity/.gitignore b/harbor_parity/.gitignore new file mode 100644 index 000000000..5e8994d66 --- /dev/null +++ b/harbor_parity/.gitignore @@ -0,0 +1,2 @@ +outputs/ +__pycache__/ diff --git a/harbor_parity/Dockerfile.eval b/harbor_parity/Dockerfile.eval new file mode 100644 index 000000000..fe0bc9c6a --- /dev/null +++ b/harbor_parity/Dockerfile.eval @@ -0,0 +1,42 @@ +# Scoring image for the original side: every HumanEvalPack toolchain in one +# image plus this repository (bigcode-evaluation-harness) installed, so that +# scoring goes through the harness' own HumanEvalFixTests.process_results and +# the Muennighoff/code_eval_octopack executor. +# +# Build from the repository root: +# docker build -f harbor_parity/Dockerfile.eval -t humanevalpack-original-eval . +FROM golang:1.22.12-bookworm AS go +FROM node:20.18.1-bookworm AS node +FROM eclipse-temurin:17-jdk-jammy AS jdk + +FROM rust:1.83-bookworm +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + g++ libboost-dev libssl-dev python3 python3-venv python3-pip git \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=go /usr/local/go /usr/local/go +COPY --from=node /usr/local/bin/node /usr/local/bin/node +COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules +COPY --from=jdk /opt/java/openjdk /opt/java/openjdk +ENV JAVA_HOME=/opt/java/openjdk \ + GOPATH=/root/go \ + NODE_PATH=/usr/local/lib/node_modules \ + PATH=/opt/java/openjdk/bin:/usr/local/go/bin:/root/go/bin:/venv/bin:$PATH +RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \ + && npm i -g js-md5@0.8.3 + +# The executor runs `go test main_test.go` in a bare temp dir (no go.mod), i.e. +# GOPATH mode. Put testify and its dependencies on the GOPATH. +RUN mkdir /tmp/gomod && cd /tmp/gomod \ + && GO111MODULE=on go mod init gomod \ + && GO111MODULE=on go get github.com/stretchr/testify/assert@v1.9.0 \ + && GO111MODULE=on go list -m -f '{{.Path}} {{.Dir}}' all | while read p d; do \ + if [ -n "$d" ] && [ "$p" != gomod ]; then mkdir -p "$GOPATH/src/$p" && cp -r "$d/." "$GOPATH/src/$p/"; fi; \ + done \ + && rm -rf /tmp/gomod +ENV GO111MODULE=off + +COPY . /harness +RUN python3 -m venv /venv && /venv/bin/pip install --no-cache-dir -e /harness +WORKDIR /work diff --git a/harbor_parity/README.md b/harbor_parity/README.md new file mode 100644 index 000000000..eeb80bfa1 --- /dev/null +++ b/harbor_parity/README.md @@ -0,0 +1,32 @@ +# HumanEvalFix parity for the Harbor `humanevalpack` adapter + +Original-side code for the parity experiment of the Harbor `humanevalpack` +adapter (https://github.com/harbor-framework/adapters/pull/142). + +This harness only does single-shot generation, so parity uses Harbor's +Scenario 2: the same agent (mini-swe-agent 2.4.6) runs on both sides, and this +side is scored with this repository's own evaluator +(`HumanEvalFixTests.process_results` -> `Muennighoff/code_eval_octopack`). + +- `parity_sample.json` - the 80 sampled tasks (16 per language). +- `agent_images/` - per-language images (same Dockerfiles as the adapter) plus + mini-swe-agent, installed the way Harbor installs it. +- `run_agent.py` - builds each task's runnable file and instruction with the + same rules as the adapter, runs the agent in a container, and saves + everything before the upstream test block as the generation. +- `Dockerfile.eval` - every HumanEvalPack toolchain plus this repository. +- `score.py` - grades each generation through `process_results` (one problem + at a time) and writes `scores.json`. +- `make_oracle_generations.py` - canonical-solution generations, used to check + the scorer (80/80 pass). + +```bash +docker build -f harbor_parity/Dockerfile.eval -t humanevalpack-original-eval . +export OPENAI_API_KEY=... OPENAI_BASE_URL=... +uv run --python 3.11 --with datasets --with evaluate python harbor_parity/run_agent.py \ + --output-dir harbor_parity/outputs/run1 --model openai/deepseek-v4.1-flash -n 2 +docker run --rm -v "$PWD/harbor_parity:/hp" humanevalpack-original-eval \ + python /hp/score.py --output-dir /hp/outputs/run1 +``` + +Results (pass@1 %, 3 runs): 98.75 / 97.50 / 100.00 (mean 98.75 +/- 0.72 SEM). diff --git a/harbor_parity/agent_images/cpp.Dockerfile b/harbor_parity/agent_images/cpp.Dockerfile new file mode 100644 index 000000000..d27794e01 --- /dev/null +++ b/harbor_parity/agent_images/cpp.Dockerfile @@ -0,0 +1,9 @@ +FROM debian:bookworm-slim +ENV DEBIAN_FRONTEND=noninteractive +# boost/any.hpp is in the upstream include helper; -lcrypto/-lssl are used by CPP/162 +RUN apt-get update && apt-get install -y --no-install-recommends \ + g++ libboost-dev libssl-dev python3 \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /workspace +COPY workspace/ /workspace/ +RUN mkdir -p /logs/verifier diff --git a/harbor_parity/agent_images/go.Dockerfile b/harbor_parity/agent_images/go.Dockerfile new file mode 100644 index 000000000..3a86d36ae --- /dev/null +++ b/harbor_parity/agent_images/go.Dockerfile @@ -0,0 +1,15 @@ +FROM golang:1.22.12-bookworm +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends python3 \ + && rm -rf /var/lib/apt/lists/* +# Pre-fetch testify (used by every upstream Go test) and warm the build cache so +# tests also run offline. +RUN mkdir -p /opt/humanevalpack/go && cd /opt/humanevalpack/go \ + && go mod init humanevalpack \ + && go get github.com/stretchr/testify/assert@v1.9.0 \ + && printf 'package main\n\nimport (\n "testing"\n "github.com/stretchr/testify/assert"\n)\n\nfunc TestWarm(t *testing.T) { assert.Equal(t, 1, 1) }\n' > warm_test.go \ + && go test warm_test.go && rm warm_test.go +WORKDIR /workspace +RUN cp /opt/humanevalpack/go/go.mod /opt/humanevalpack/go/go.sum /workspace/ +COPY workspace/ /workspace/ +RUN mkdir -p /logs/verifier diff --git a/harbor_parity/agent_images/java.Dockerfile b/harbor_parity/agent_images/java.Dockerfile new file mode 100644 index 000000000..54794d439 --- /dev/null +++ b/harbor_parity/agent_images/java.Dockerfile @@ -0,0 +1,7 @@ +FROM eclipse-temurin:17-jdk-jammy +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends python3 \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /workspace +COPY workspace/ /workspace/ +RUN mkdir -p /logs/verifier diff --git a/harbor_parity/agent_images/js.Dockerfile b/harbor_parity/agent_images/js.Dockerfile new file mode 100644 index 000000000..a3df80d27 --- /dev/null +++ b/harbor_parity/agent_images/js.Dockerfile @@ -0,0 +1,8 @@ +FROM node:20.18.1-bookworm +ENV DEBIAN_FRONTEND=noninteractive +# js-md5 is required by JavaScript/162; python3 (preinstalled) runs the verifier +RUN npm install -g js-md5@0.8.3 +ENV NODE_PATH=/usr/local/lib/node_modules +WORKDIR /workspace +COPY workspace/ /workspace/ +RUN mkdir -p /logs/verifier diff --git a/harbor_parity/agent_images/mswea.Dockerfile b/harbor_parity/agent_images/mswea.Dockerfile new file mode 100644 index 000000000..8a8889cd0 --- /dev/null +++ b/harbor_parity/agent_images/mswea.Dockerfile @@ -0,0 +1,19 @@ +# Adds mini-swe-agent on top of a per-language agent image, installed the same +# way Harbor's built-in `mini-swe-agent` agent installs it at trial start. +ARG BASE=scratch +FROM ${BASE} +ARG MSWEA_VERSION=2.4.6 +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl ca-certificates bash git build-essential \ + && rm -rf /var/lib/apt/lists/* +ENV PATH=/root/.local/bin:$PATH +# Retried as a whole: downloads from astral.sh / GitHub can be flaky. +RUN for i in 1 2 3 4 5; do \ + ( command -v uv >/dev/null 2>&1 || curl -LsSf https://astral.sh/uv/install.sh | sh ) \ + && uv python install 3.12 \ + && uv tool install --python 3.12 "mini-swe-agent==${MSWEA_VERSION}" \ + --with 'litellm[mcp]' --with orjson --with fastapi \ + && mini-swe-agent --help > /dev/null && exit 0; \ + echo "attempt $i failed, retrying"; sleep 15; \ + done; exit 1 +RUN mkdir -p /logs/agent diff --git a/harbor_parity/agent_images/rust.Dockerfile b/harbor_parity/agent_images/rust.Dockerfile new file mode 100644 index 000000000..5159160c1 --- /dev/null +++ b/harbor_parity/agent_images/rust.Dockerfile @@ -0,0 +1,14 @@ +FROM rust:1.83-bookworm +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends python3 \ + && rm -rf /var/lib/apt/lists/* +# Same dependencies as the upstream evaluator's Cargo.toml; prebuilt so that +# agent and verifier builds are fast and work offline. +ENV CARGO_TARGET_DIR=/opt/humanevalpack/rust-target +COPY workspace/Cargo.toml /opt/humanevalpack/rust/Cargo.toml +RUN cd /opt/humanevalpack/rust && mkdir src && echo 'fn main(){}' > src/main.rs \ + && cargo generate-lockfile && cargo build && cargo test --no-run \ + && rm -rf src +WORKDIR /workspace +COPY workspace/ /workspace/ +RUN cp /opt/humanevalpack/rust/Cargo.lock /workspace/Cargo.lock && mkdir -p /logs/verifier diff --git a/harbor_parity/make_oracle_generations.py b/harbor_parity/make_oracle_generations.py new file mode 100644 index 000000000..c5a27e166 --- /dev/null +++ b/harbor_parity/make_oracle_generations.py @@ -0,0 +1,29 @@ +"""Write canonical solutions as generations (sanity check of the scoring setup). + +Each generation has exactly the shape run_agent.py saves: the runnable file +(language prefix + declaration + body) up to the test block, with the body +replaced by `canonical_solution`. +""" +import argparse +import json +from pathlib import Path + +from datasets import load_dataset + +import run_agent as ra + +ap = argparse.ArgumentParser() +ap.add_argument("--output-dir", type=Path, required=True) +args = ap.parse_args() +args.output_dir.mkdir(parents=True, exist_ok=True) +tasks = json.loads((ra.HERE / "parity_sample.json").read_text())["tasks"] +for lang in ["js", "java", "go", "cpp", "rust"]: + task = ra.create_task(lang, "fixtests")() + ds = load_dataset("bigcode/humanevalpack", lang, split="test", revision=ra.DATASET_REVISION) + for tid in [t for t in tasks if t.startswith(lang + "-")]: + doc = dict(ds[int(tid.split("-")[1])]) + doc["buggy_solution"] = doc["canonical_solution"] + program = ra.runnable_context(lang, task, doc) + gen = program[: program.rfind(doc["test"].rstrip())] + (args.output_dir / f"{tid}.generation.txt").write_text(gen, encoding="utf-8", newline="\n") +print("done") diff --git a/harbor_parity/parity_sample.json b/harbor_parity/parity_sample.json new file mode 100644 index 000000000..ea046efb7 --- /dev/null +++ b/harbor_parity/parity_sample.json @@ -0,0 +1,86 @@ +{ + "seed": 20261201, + "per_language": 16, + "tasks": [ + "js-9", + "js-17", + "js-21", + "js-24", + "js-35", + "js-36", + "js-38", + "js-42", + "js-44", + "js-49", + "js-58", + "js-59", + "js-63", + "js-82", + "js-116", + "js-159", + "java-27", + "java-42", + "java-64", + "java-77", + "java-84", + "java-101", + "java-119", + "java-130", + "java-137", + "java-141", + "java-142", + "java-148", + "java-150", + "java-153", + "java-155", + "java-156", + "go-7", + "go-8", + "go-31", + "go-42", + "go-48", + "go-49", + "go-72", + "go-82", + "go-83", + "go-91", + "go-98", + "go-107", + "go-113", + "go-117", + "go-130", + "go-145", + "cpp-32", + "cpp-45", + "cpp-47", + "cpp-54", + "cpp-60", + "cpp-70", + "cpp-83", + "cpp-97", + "cpp-102", + "cpp-104", + "cpp-106", + "cpp-130", + "cpp-131", + "cpp-140", + "cpp-149", + "cpp-162", + "rust-11", + "rust-20", + "rust-26", + "rust-29", + "rust-50", + "rust-58", + "rust-73", + "rust-81", + "rust-83", + "rust-84", + "rust-86", + "rust-119", + "rust-136", + "rust-138", + "rust-145", + "rust-159" + ] +} \ No newline at end of file diff --git a/harbor_parity/run_agent.py b/harbor_parity/run_agent.py new file mode 100644 index 000000000..f46af6781 --- /dev/null +++ b/harbor_parity/run_agent.py @@ -0,0 +1,304 @@ +"""Original-side parity runner for HumanEvalFixTests (Harbor parity, Scenario 2). + +OctoPack evaluates single-shot generations and has no agent harness. For +parity with the Harbor adapter, the same agent (mini-swe-agent, same version, +model and settings as Harbor's built-in `mini-swe-agent` agent) is run here on +problems loaded through this harness' own `humanevalfixtests-` task: + +* the instruction is the HumanEvalFix instruction from + `HumanEvalFixBase.get_prompt` ("Fix bugs in ."), followed by + the same agent instructions the Harbor tasks use; +* the agent edits one file holding the HumanEvalFixTests context + (`get_prompt_base(doc) + buggy_solution + "\\n" + test`) with the language + prefix the evaluator adds before execution, so that it can be run; +* the edited code before the (unchanged) test block is saved as the + generation, which `score.py` grades with this harness' `process_results`. + +Usage (from the repository root, with OPENAI_API_KEY and OPENAI_BASE_URL set): + python harbor_parity/run_agent.py --output-dir harbor_parity/outputs/run1 +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shlex +import subprocess +import sys +import tempfile +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +from datasets import load_dataset + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) + + +def _load_humanevalpack(): + """Import bigcode_eval/tasks/humanevalpack.py by path. + + Importing it through the `bigcode_eval.tasks` package would import every + task module, some of which need Linux-only modules (e.g. fcntl); this + runner also has to work on the Docker host. + """ + import importlib.util + + path = HERE.parent / "bigcode_eval" / "tasks" / "humanevalpack.py" + spec = importlib.util.spec_from_file_location("humanevalpack_task", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +_hep = _load_humanevalpack() +IMPORT_HELPER, create_task = _hep.IMPORT_HELPER, _hep.create_task + +DATASET_REVISION = "9a41762f73a8cb23bb5811b73d5aab164efcf378" +LANG_FILE = { + "js": "/workspace/solution.js", + "java": "/workspace/Main.java", + "go": "/workspace/main_test.go", + "cpp": "/workspace/solution.cpp", + "rust": "/workspace/src/main.rs", +} +LANG_RUN = { + "js": "node /workspace/solution.js", + "java": "cd /workspace && javac Main.java && java -cp . Main", + "go": "cd /workspace && go test main_test.go", + "cpp": "cd /workspace && g++ -std=c++11 solution.cpp -lcrypto -lssl && ./a.out", + "rust": "cd /workspace && cargo test", +} +RUST_CARGO_TOML = """[package] +name = "rust" +version = "0.1.0" +edition = "2021" + +[dependencies] +rand = "0.4" +regex = "1" +md5 = "0.7.0" +""" +EXTRA_NOTES = { + "js": "\nThe program must not print anything when it is run: any output on stdout or stderr (including failed `console.assert` calls) counts as a failure.\n", +} +AGENT_TEMPLATE = """{instruction} + +Please fix the function in {file_path} such that all test cases pass. +Environment has been set up for you to start working. You may assume all necessary tools are installed. +You can run the tests with: + +``` +{run_command} +``` +{extra_notes} +# Problem Statement +{problem_statement} + +IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP. +You should NOT modify the existing test code at the end of {file_path}; it is re-run unchanged by the grader. If needed, you can add new test cases in a NEW file to reproduce the issue. +You SHOULD INCLUDE PROPER INDENTATION in your edit commands.""" + + +def runnable_context(lang: str, task, doc: dict) -> str: + """HumanEvalFixTests context with the evaluator's language prefix.""" + context = task.get_prompt_base(doc) + doc["buggy_solution"] # rust: has fn main(){} + test = doc["test"] + if lang == "cpp": + helpers = [h for h in IMPORT_HELPER["cpp"] if h.startswith("#include")] + return "\n".join(helpers) + "\nusing namespace std;\n" + context + "\n" + test + if lang == "go": + imports = re.findall(r'"([^"]+)"', doc["test_setup"]) + code_lines = [ + ln for ln in (context + "\n" + test).split("\n") if not ln.strip().startswith("//") + ] + for pkg in IMPORT_HELPER["go"]: + ident = pkg.split("/")[-1] + pat = re.compile(r"(? str: + # HumanEvalFixBase.get_prompt uses exactly this instruction + instruction = f'Fix bugs in {doc["entry_point"]}.' + fence = "```" + return AGENT_TEMPLATE.format( + instruction=instruction, + file_path=LANG_FILE[lang], + run_command=LANG_RUN[lang], + extra_notes=EXTRA_NOTES.get(lang, ""), + problem_statement=f"{fence}{lang}\n{program.rstrip()}\n{fence}", + ) + + +def locate_test_block(content: str, block: str) -> int: + """Index in ``content`` where the upstream test block starts, or -1. + + Identical to ``locate_test_block`` in the adapter's tests/verify.py: exact + match first, then a whitespace-insensitive match, since agents often run a + formatter (e.g. ``gofmt``) over the whole file. Only the candidate boundary + is taken from the edited file; scoring always uses the pristine tests. + """ + idx = content.rfind(block.rstrip()) + if idx != -1: + return idx + target = "".join(block.split()) + if not target: + return -1 + positions = [i for i, c in enumerate(content) if not c.isspace()] + squashed = "".join(content[i] for i in positions) + j = squashed.rfind(target) + return positions[j] if j != -1 else -1 + + +def sh(cmd: list[str], **kw) -> subprocess.CompletedProcess: + return subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", **kw) + + +def build_images(langs: list[str], version: str) -> None: + for lang in langs: + with tempfile.TemporaryDirectory() as ctx: + ws = Path(ctx) / "workspace" + ws.mkdir() + if lang == "rust": + (ws / "Cargo.toml").write_text(RUST_CARGO_TOML, newline="\n") + r = sh(["docker", "build", "-q", "-t", f"hep-agent-base-{lang}", + "-f", str(HERE / "agent_images" / f"{lang}.Dockerfile"), ctx]) + if r.returncode: + raise SystemExit(f"build base {lang} failed:\n{r.stderr[-3000:]}") + r = sh(["docker", "build", "-q", "-t", f"hep-agent-{lang}", + "--build-arg", f"BASE=hep-agent-base-{lang}", + "--build-arg", f"MSWEA_VERSION={version}", + "-f", str(HERE / "agent_images" / "mswea.Dockerfile"), str(HERE / "agent_images")]) + if r.returncode: + raise SystemExit(f"build agent {lang} failed:\n{r.stderr[-3000:]}") + print(f"built hep-agent-{lang}", flush=True) + + +def run_one(item: dict, args, out_dir: Path) -> dict: + tid, lang = item["task"], item["lang"] + gen_path = out_dir / f"{tid}.generation.txt" + if gen_path.exists() and not args.overwrite: + return {"task": tid, "skipped": True} + name = f"hep-parity-{tid}-{os.getpid()}-{int(time.time())}" + t0 = time.time() + rec = {"task": tid, "source_task_id": item["source_task_id"]} + try: + r = sh(["docker", "run", "-d", "--name", name, f"hep-agent-{lang}", "sleep", "infinity"]) + if r.returncode: + raise RuntimeError(r.stderr) + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / "file").write_text(item["program"], encoding="utf-8", newline="\n") + (tmp / "instruction.md").write_text(item["instruction"], encoding="utf-8", newline="\n") + target = LANG_FILE[lang] + sh(["docker", "exec", name, "mkdir", "-p", str(Path(target).parent).replace("\\", "/")]) + sh(["docker", "cp", str(tmp / "file"), f"{name}:{target}"]) + sh(["docker", "cp", str(tmp / "instruction.md"), f"{name}:/tmp/instruction.md"]) + if lang == "rust": + (tmp / "Cargo.toml").write_text(RUST_CARGO_TOML, newline="\n") + sh(["docker", "cp", str(tmp / "Cargo.toml"), f"{name}:/workspace/Cargo.toml"]) + + agent_cmd = ( + "mini-swe-agent --yolo " + f"--model={shlex.quote(args.model)} " + '--task="$(cat /tmp/instruction.md)" ' + "--output=/logs/agent/mini-swe-agent.trajectory.json " + "-c mini " + "-c model.model_kwargs.timeout=3600 " + "-c model.model_kwargs.drop_params=true " + f"-c model.model_kwargs.api_base={shlex.quote(os.environ['OPENAI_BASE_URL'])} " + "--exit-immediately 2>&1 None: + ap = argparse.ArgumentParser() + ap.add_argument("--output-dir", type=Path, required=True) + ap.add_argument("--sample", type=Path, default=HERE / "parity_sample.json") + ap.add_argument("--tasks", nargs="*", help="subset of sample task ids (e.g. js-9)") + ap.add_argument("--model", default="openai/deepseek-v4.1-flash") + ap.add_argument("--mswea-version", default="2.4.6") + ap.add_argument("--agent-timeout", type=int, default=600) + ap.add_argument("-n", "--concurrency", type=int, default=8) + ap.add_argument("--skip-build", action="store_true") + ap.add_argument("--overwrite", action="store_true") + args = ap.parse_args() + for var in ("OPENAI_API_KEY", "OPENAI_BASE_URL"): + if not os.environ.get(var): + raise SystemExit(f"{var} is not set") + + tasks = json.loads(args.sample.read_text())["tasks"] + if args.tasks: + tasks = [t for t in tasks if t in set(args.tasks)] + langs = sorted({t.split("-")[0] for t in tasks}) + if not args.skip_build: + build_images(langs, args.mswea_version) + + items = [] + for lang in langs: + task = create_task(lang, "fixtests")() + ds = load_dataset("bigcode/humanevalpack", lang, split="test", revision=DATASET_REVISION) + for tid in tasks: + if not tid.startswith(lang + "-"): + continue + n = int(tid.split("-")[1]) + doc = ds[n] + assert doc["task_id"].split("/")[1] == str(n), doc["task_id"] + program = runnable_context(lang, task, doc) + items.append({ + "task": tid, "lang": lang, "source_task_id": doc["task_id"], + "program": program, "test": doc["test"], + "instruction": build_instruction(lang, task, doc, program), + }) + + args.output_dir.mkdir(parents=True, exist_ok=True) + with ThreadPoolExecutor(args.concurrency) as pool: + list(pool.map(lambda it: run_one(it, args, args.output_dir), items)) + + +if __name__ == "__main__": + main() diff --git a/harbor_parity/score.py b/harbor_parity/score.py new file mode 100644 index 000000000..fa07f8f7b --- /dev/null +++ b/harbor_parity/score.py @@ -0,0 +1,103 @@ +"""Score original-side parity generations with this harness' evaluator. + +Each generation saved by run_agent.py is graded on its own through +`humanevalfixtests-`'s `process_results` (which applies the upstream +language pre-processing and calls the Muennighoff/code_eval_octopack +executor), so per-task pass/fail is available for the parity comparison. + +Run inside the scoring image (see Dockerfile.eval): + docker run --rm -v "$PWD/harbor_parity:/hp" humanevalpack-original-eval \ + python /hp/score.py --output-dir /hp/outputs/run1 +""" + +from __future__ import annotations + +import argparse +import contextlib +import io +import json +import os +import time +from pathlib import Path + +from datasets import DatasetDict, load_dataset + +import bigcode_eval.tasks.humanevalpack as hep +from bigcode_eval.tasks.humanevalpack import create_task + +# process_results calls evaluate.load("Muennighoff/code_eval_octopack") on every +# call; load the metric once since each problem is graded separately here. +_load, _metrics = hep.load, {} + + +def _cached_load(name, *args, **kwargs): + if name not in _metrics: + for attempt in range(5): # the Hub download can be flaky + try: + _metrics[name] = _load(name, *args, **kwargs) + break + except FileNotFoundError: + if attempt == 4: + raise + time.sleep(10) + return _metrics[name] + + +hep.load = _cached_load + +DATASET_REVISION = "9a41762f73a8cb23bb5811b73d5aab164efcf378" +HERE = Path(__file__).resolve().parent + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--output-dir", type=Path, required=True) + ap.add_argument("--sample", type=Path, default=HERE / "parity_sample.json") + ap.add_argument("--tasks", nargs="*", help="subset of sample task ids (e.g. js-9)") + args = ap.parse_args() + os.environ["HF_ALLOW_CODE_EVAL"] = "1" + os.chdir(args.output_dir) # the Rust executor builds in ./rust + + tasks = json.loads(args.sample.read_text())["tasks"] + if args.tasks: + tasks = [t for t in tasks if t in set(args.tasks)] + results = {} + for lang in ["js", "java", "go", "cpp", "rust"]: + lang_tasks = [t for t in tasks if t.startswith(lang + "-")] + if not lang_tasks: + continue + task = create_task(lang, "fixtests")() + for attempt in range(5): # the Hub can be flaky + try: + full = load_dataset("bigcode/humanevalpack", lang, split="test", revision=DATASET_REVISION) + break + except Exception: + if attempt == 4: + raise + time.sleep(15) + for tid in lang_tasks: + n = int(tid.split("-")[1]) + gen_file = args.output_dir / f"{tid}.generation.txt" + generation = gen_file.read_text(encoding="utf-8") if gen_file.exists() else "" + # Grade this one problem: process_results walks get_dataset() in order + task.dataset = DatasetDict({"test": full.select([n])}) + ref = task.get_reference(task.get_dataset()[0]) + log = io.StringIO() + with contextlib.redirect_stdout(log): + metrics = task.process_results([[generation]], [ref]) + passed = float(metrics["pass@1"]) == 1.0 + results[tid] = int(passed) + print(f"{tid}: {'pass' if passed else 'fail'}", flush=True) + + summary = { + "n_tasks": len(results), + "n_passed": sum(results.values()), + "accuracy": sum(results.values()) / len(results) if results else 0.0, + "per_task": results, + } + (args.output_dir / "scores.json").write_text(json.dumps(summary, indent=1)) + print(json.dumps({k: v for k, v in summary.items() if k != "per_task"})) + + +if __name__ == "__main__": + main()