Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/model.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ jobs:
uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12
python model/ci.py evaluate --directory "$RUN_DIR"
- name: Require strict improvement
run: python3 model/ci.py report --directory "$RUN_DIR" $BOOTSTRAP
run: >-
uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12
python model/ci.py report --directory "$RUN_DIR" $BOOTSTRAP
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
with:
Expand Down
18 changes: 2 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,22 +43,8 @@ https://github.com/user-attachments/assets/3b46a5d7-b39b-40f7-8575-fd3f6f0c1d7a
Accepted adapter: [LongLink/pyshell-worker](https://huggingface.co/LongLink/pyshell-worker/tree/4064ca4a5ebab1c97dd166133a74be4231771973).
Base model: `Qwen/Qwen3.5-0.8B`.

**Execution success: 15.00% (9/60 tasks).**

| Category | Passed | Success |
| --- | ---: | ---: |
| Filtered means | 0/5 | 0.00% |
| Grouped revenue | 0/5 | 0.00% |
| Inspect callable | 1/5 | 20.00% |
| Joined totals | 0/5 | 0.00% |
| Left join | 0/5 | 0.00% |
| Linear system | 2/5 | 40.00% |
| Missing input | 2/5 | 40.00% |
| Missing values | 0/5 | 0.00% |
| Monthly totals | 0/5 | 0.00% |
| Recover execution | 0/5 | 0.00% |
| Stateful followup | 2/5 | 40.00% |
| Statistics | 2/5 | 40.00% |
**Task success: 15.00% (9/60 tasks).**
**Valid Python: 99.08% (215/217 responses).**

<!-- model-stats:end -->

Expand Down
6 changes: 3 additions & 3 deletions model/benchmark/src/evaluate.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
from pathlib import Path
from contextlib import ExitStack, closing
from model.benchmark.src import scoring
from model.benchmark.src.trial import trial
from model.benchmark.src.settings import Settings
from model.benchmark.src.execution import Worker
Expand All @@ -18,7 +19,6 @@ def run(config: Settings) -> None:

generate = HFCompletion(config)
config.output.parent.mkdir(parents=True, exist_ok=True)
passed = 0
with config.output.open("x") as file, ExitStack() as stack:
workers = []
for _ in range(min(config.batch_size, len(records))):
Expand All @@ -40,7 +40,6 @@ def run(config: Settings) -> None:
row = result.value
file.write(json.dumps(row) + "\n")
file.flush()
passed += row["status"] == "passed"
completed += 1
print(f"{completed}/{len(records)}: {row['id']} {row['status']}", flush=True)
record = next(remaining, None)
Expand All @@ -50,4 +49,5 @@ def run(config: Settings) -> None:
prompt = next(task)
pending.append((worker, task, prompt))
active = pending
print(f"Passed {passed}/{len(records)} ({passed / len(records):.1%})", flush=True)
rows = [json.loads(line) for line in config.output.read_text().splitlines()]
print(scoring.summary(scoring.score(rows)), flush=True)
42 changes: 42 additions & 0 deletions model/benchmark/src/scoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import ast
from collections.abc import Sequence


def score(rows: Sequence[dict]) -> dict:
"""Score task outcomes and Python syntax across all generated responses."""
if not rows or len({row["id"] for row in rows}) != len(rows):
raise ValueError("Evaluation must contain unique, nonempty tasks")
statuses = {"passed", "incorrect", "call_limit", "boundary_error"}
if any(row["status"] not in statuses for row in rows):
raise ValueError("Unknown evaluation status")
generations = 0
valid_python = 0
for row in rows:
for step in row.get("steps", []):
source = step["source"]
if not isinstance(source, str):
raise ValueError("Generated source must be text")
generations += 1
try:
tree = ast.parse(source)
compile(tree, "<benchmark>", "exec")
except (SyntaxError, ValueError):
continue
valid_python += bool(tree.body)
passed = sum(row["status"] == "passed" for row in rows)
return {
"passed": passed,
"total": len(rows),
"generations": generations,
"success_rate": passed / len(rows),
"valid_python": valid_python,
"valid_python_rate": valid_python / generations if generations else None,
}


def summary(result: dict) -> str:
"""Format both aggregate scores with their distinct denominators."""
python = "not measured (0 responses)"
if result["valid_python_rate"] is not None:
python = f"{result['valid_python_rate']:.2%} ({result['valid_python']}/{result['generations']} responses)"
return f"Task success: {result['success_rate']:.2%} ({result['passed']}/{result['total']} tasks)\nValid Python: {python}"
16 changes: 11 additions & 5 deletions model/benchmark/src/worker.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import io
import os
import sys
import json
Expand All @@ -21,6 +22,7 @@ def main() -> None:
from api.shell import PythonShell

protocol = sys.stdout
incoming = sys.stdin
shell = None
handler = signal.signal(signal.SIGALRM, deadline)

Expand All @@ -36,11 +38,15 @@ def publish(result: dict[str, Any]) -> None:
if request["action"] not in ("reset", "execute"):
raise ValueError("Unsupported worker action")
signal.alarm(10)
with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
if request["action"] == "reset":
shell = PythonShell()
shell.namespace.update(np=np, pd=pd, statistics=statistics, json=json)
result = shell.execute(request["source"])
with io.StringIO() as stdin, contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
sys.stdin = stdin
try:
if request["action"] == "reset":
shell = PythonShell()
shell.namespace.update(np=np, pd=pd, statistics=statistics, json=json)
result = shell.execute(request["source"])
finally:
sys.stdin = incoming
signal.alarm(0)
publish(result)
except BaseException as error:
Expand Down
7 changes: 5 additions & 2 deletions model/benchmark/tests/test_evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ def benchmark(tmp_path, monkeypatch):
worker = Mock()
monkeypatch.setattr(evaluate, "Worker", worker)
rows = [
{**record, "status": status, "steps": []} for record, status in zip(records, ("passed", "incorrect", "call_limit"), strict=True)
{**record, "status": status, "steps": [{"source": "result = 1"}]}
for record, status in zip(records, ("passed", "incorrect", "call_limit"), strict=True)
]

def task(worker, record, calls):
Expand All @@ -37,7 +38,9 @@ def test_run_evaluates_one_adapter_and_saves_results(benchmark, capsys):
assert [json.loads(line) for line in config.output.read_text().splitlines()] == rows
model.assert_called_once_with(config)
worker.return_value.close.assert_called_once_with()
assert "Passed 1/3 (33.3%)" in capsys.readouterr().out
output = capsys.readouterr().out
assert "Task success: 33.33% (1/3 tasks)" in output
assert "Valid Python: 100.00% (3/3 responses)" in output


def test_existing_results_are_not_overwritten(benchmark):
Expand Down
50 changes: 50 additions & 0 deletions model/benchmark/tests/test_scoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import pytest
from model.benchmark.src import scoring


@pytest.mark.parametrize(
("source", "valid"),
[
("result = sum(values)", True),
("print(missing_variable)", True),
("raise AssertionError('must not execute')", True),
("def answer():\n return 42", True),
("", False),
(" \n# only a comment\n", False),
("```python\nresult = 42\n```", False),
("Here is the Python code:\nresult = 42", False),
("result = 42\nThe answer is forty two.", False),
("result =", False),
("return 42", False),
("break", False),
("result = 42\x00", False),
("<|end_code|>", False),
],
)
def test_python_validity_checks_unmodified_source_without_executing_it(source, valid):
result = scoring.score([{"id": "task", "status": "incorrect", "steps": [{"source": source}]}])
assert result["valid_python"] == int(valid)
assert result["valid_python_rate"] == float(valid)
assert result["success_rate"] == 0


def test_syntax_scores_all_responses_and_task_success_scores_tasks():
rows = [
{"id": "a", "status": "passed", "steps": [{"source": "result ="}, {"source": "result = 1"}]},
{"id": "b", "status": "call_limit", "steps": [{"source": "# empty"}, {"source": "print(missing)"}]},
{"id": "c", "status": "boundary_error", "steps": [{"source": "result = 1"}]},
]
result = scoring.score(rows)
assert result == {"passed": 1, "total": 3, "generations": 5, "success_rate": 1 / 3, "valid_python": 3, "valid_python_rate": 0.6}
assert scoring.summary(result) == "Task success: 33.33% (1/3 tasks)\nValid Python: 60.00% (3/5 responses)"


def test_older_results_without_generations_are_not_reported_as_zero_percent():
result = scoring.score([{"id": "a", "status": "passed"}])
assert result["valid_python_rate"] is None
assert "Valid Python: not measured (0 responses)" in scoring.summary(result)


def test_nontext_source_is_rejected():
with pytest.raises(ValueError, match="must be text"):
scoring.score([{"id": "a", "status": "passed", "steps": [{"source": 42}]}])
20 changes: 20 additions & 0 deletions model/benchmark/tests/test_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,32 @@ def run_worker(self, requests, protocol=None):
worker.main()
assert sys.stdout is protocol
assert sys.stderr is errors
assert sys.stdin is incoming

assert errors.getvalue() == ""
lines = protocol.getvalue().splitlines()
assert len(lines) == len(requests)
return [json.loads(line) for line in lines]

@pytest.mark.parametrize("source", ["exit(1)", "quit(1)", "import sys; sys.stdin.close()", "input()"])
def test_generated_code_cannot_close_or_consume_protocol_input(self, source):
results = self.run_worker(
[
{"action": "reset", "source": "value = 42"},
{"action": "execute", "source": source},
{"action": "execute", "source": "print(value)"},
{"action": "reset", "source": "print('new task')"},
]
)
if source in ("exit(1)", "quit(1)"):
assert "SystemExit" in results[1]["exception"]
assert results[1]["done"] is None
elif source == "input()":
assert "EOFError" in results[1]["exception"]
assert results[2]["stdout"] == "42\n"
assert results[2]["exception"] is None
assert results[3]["stdout"] == "new task\n"

@pytest.mark.parametrize("requests", [[], [{"action": "reset", "source": "pass"}]])
def test_previous_signal_handler_is_restored_on_eof(self, requests):
def previous_handler(_signal, _frame):
Expand Down
42 changes: 14 additions & 28 deletions model/ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import shutil
import subprocess
import sys
from collections import Counter
from pathlib import Path


Expand All @@ -24,23 +23,10 @@ def changes(paths: list[str]) -> bool:


def score(path: Path) -> dict:
from model.benchmark.src import scoring

rows = [json.loads(line) for line in path.read_text().splitlines()]
if not rows or len({row["id"] for row in rows}) != len(rows):
raise ValueError("Evaluation must contain unique, nonempty tasks")
statuses = {"passed", "incorrect", "call_limit", "boundary_error"}
if any(row["status"] not in statuses for row in rows):
raise ValueError("Unknown evaluation status")
families = Counter(row["family"] for row in rows)
passed = Counter(row["family"] for row in rows if row["status"] == "passed")
return {
"passed": sum(passed.values()),
"total": len(rows),
"success_rate": sum(passed.values()) / len(rows),
"families": {
family: {"passed": passed[family], "total": total}
for family, total in sorted(families.items())
},
}
return scoring.score(rows)


def compare(candidate: Path, baseline: Path) -> dict:
Expand Down Expand Up @@ -94,7 +80,6 @@ def train(directory: Path) -> None:


def evaluate(directory: Path, adapter: str, output: str) -> None:
sys.path.insert(0, str(Path.cwd()))
from model.benchmark.src import evaluate, settings

config = settings.Settings.model_validate(
Expand All @@ -119,6 +104,8 @@ def evaluate(directory: Path, adapter: str, output: str) -> None:


def report(directory: Path, bootstrap: bool) -> None:
from model.benchmark.src import scoring

result = {"candidate": score(directory / "candidate.jsonl"), "improved": True}
if not bootstrap:
result = compare(directory / "candidate.jsonl", directory / "baseline.jsonl")
Expand All @@ -135,9 +122,9 @@ def report(directory: Path, bootstrap: bool) -> None:
f"{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}"
)
(directory / "metrics.json").write_text(json.dumps(result, indent=2) + "\n")
summary = f"Candidate: {result['candidate']['success_rate']:.2%}\n"
summary = f"Candidate:\n{scoring.summary(result['candidate'])}\n"
if not bootstrap:
summary += f"Accepted: {result['baseline']['success_rate']:.2%}\n"
summary += f"Accepted:\n{scoring.summary(result['baseline'])}\n"
summary += (
"Bootstrap baseline\n" if bootstrap else f"Improved: {result['improved']}\n"
)
Expand Down Expand Up @@ -205,15 +192,14 @@ def readme(content: str, directory: Path, repo: str, revision: str) -> str:
f"Accepted adapter: [{repo}](https://huggingface.co/{repo}/tree/{revision}).",
f"Base model: `{adapter['base_model_name_or_path']}`.",
"",
f"**Execution success: {score['success_rate']:.2%} ({score['passed']}/{score['total']} tasks).**",
"",
"| Category | Passed | Success |",
"| --- | ---: | ---: |",
f"**Task success: {score['success_rate']:.2%} ({score['passed']}/{score['total']} tasks).**",
]
for family, result in sorted(score["families"].items()):
if score.get("valid_python_rate") is None:
lines.append("**Valid Python: not measured.**")
else:
lines.append(
f"| {family.replace('_', ' ').capitalize()} | {result['passed']}/{result['total']} | "
f"{result['passed'] / result['total']:.2%} |"
f"**Valid Python: {score['valid_python_rate']:.2%} "
f"({score['valid_python']}/{score['generations']} responses).**"
)
if metrics.get("evaluated_at") or metrics.get("workflow"):
lines.append("")
Expand Down Expand Up @@ -302,7 +288,6 @@ def main() -> None:
if args.command == "baseline":
baseline(directory, args.repo, args.bootstrap)
elif args.command == "train":
sys.path.insert(0, str(Path.cwd()))
train(directory)
elif args.command == "evaluate":
evaluate(directory, args.adapter, args.output)
Expand All @@ -315,4 +300,5 @@ def main() -> None:


if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
main()
Loading
Loading