Upload 8 files
Browse filesFiles changed (8)
- eval/instance_report.pyAdded+49
- eval/make_subset.pyAdded+36
- eval/relay_model.pyAdded+35
- eval/rescore.shAdded+44
- eval/rescore_merge.pyAdded+56
- eval/run_agent.shAdded+50
- eval/score.shAdded+35
- eval/subset.jsonAdded+138
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Build a run report from the harness's per-instance reports, for a run whose own final report was not written.
python eval/instance_report.py <folder the harness ran in> <run id> <preds.json> <out.json> [--ids id1 id2 ...]
The SWE-bench harness scores each instance into logs/run_evaluation/<run id>/<model>/<instance>/report.json and then,as its last step, lists every container on the machine to write one summary file. On a machine where hundreds ofshort-lived containers of other runs come and go, that listing can fail (a container disappears between being listedand being read) and the summary is never written. The per-instance reports are complete by then; this adds them upthe same way. An instance with a patch and no report counts as an error, to be scored again (eval/rescore.sh)."""import globimport jsonimport sys
def main(): folder, run_id, preds_path, out = sys.argv[1:5] only = set(sys.argv[sys.argv.index("--ids") + 1:]) if "--ids" in sys.argv else None preds = json.load(open(preds_path)) resolved, completed, errors, empty = [], [], [], [] for iid, p in sorted(preds.items()): if only is not None and iid not in only: continue if not (p.get("model_patch") or "").strip(): empty.append(iid) continue found = glob.glob(f"{folder}/logs/run_evaluation/{run_id}/*/{iid}/report.json") if not found: errors.append(iid) continue completed.append(iid) try: if json.load(open(found[0])).get(iid, {}).get("resolved"): resolved.append(iid) except ValueError: completed.pop() errors.append(iid) n = len(resolved) + (len(completed) - len(resolved)) + len(errors) + len(empty) report = {"built_from": "the per-instance reports (the harness's own run report was not written)", "total_instances": n, "submitted_instances": n, "completed_instances": len(completed), "resolved_instances": len(resolved), "unresolved_instances": len(completed) - len(resolved), "empty_patch_instances": len(empty), "error_instances": len(errors), "completed_ids": completed, "resolved_ids": resolved, "unresolved_ids": sorted(set(completed) - set(resolved)), "empty_patch_ids": empty, "error_ids": errors} json.dump(report, open(out, "w"), indent=1) print(f"built {out}: resolved {len(resolved)}, completed {len(completed)}, errors {len(errors)}, empty {len(empty)}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536"""The evaluation subset: 100 instances of SWE-bench Verified, drawn once with a fixed seed.
python eval/make_subset.py # writes eval/subset.json
The file also lists every repository of SWE-bench Verified: training data must share none of them."""import jsonimport randomimport sysfrom pathlib import Path
from datasets import load_dataset
DATASET, SPLIT, SEED, N = "princeton-nlp/SWE-bench_Verified", "test", 20261201, 100
def main(): out = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).parent / "subset.json") ds = load_dataset(DATASET, split=SPLIT) repo_of = dict(zip(ds["instance_id"], ds["repo"])) ids = sorted(repo_of) pick = sorted(random.Random(SEED).sample(ids, N)) per_repo = {} for i in pick: per_repo[repo_of[i]] = per_repo.get(repo_of[i], 0) + 1 out.write_text(json.dumps({ "dataset": DATASET, "split": SPLIT, "dataset_fingerprint": ds._fingerprint, "total_instances": len(ids), "seed": SEED, "n": N, "method": "random.Random(seed).sample(sorted(instance_ids), n)", "instance_ids": pick, "instances_per_repo": dict(sorted(per_repo.items())), "all_repos_of_the_benchmark": sorted(set(repo_of.values())), }, indent=1) + "\n", encoding="utf-8") print(f"{out}: {len(pick)} of {len(ids)} instances, {len(per_repo)} repositories")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435"""The comparison model for the agent harness, reached through the laptop relay (tools/or_proxy.py).
Same request the harness's own OpenRouter class sends (one bash tool, cost reported per call); only the addressdiffers, and the key stays on the laptop."""import jsonimport os
import requestsfrom minisweagent.models.openrouter_model import (BASH_TOOL, OpenRouterAPIError, OpenRouterAuthenticationError, OpenRouterModel, OpenRouterRateLimitError)
class RelayOpenRouterModel(OpenRouterModel): def __init__(self, **kwargs): super().__init__(**kwargs) self._api_url = os.environ.get("RELAY_URL", "http://127.0.0.1:18811/v1/chat/completions") self._api_key = "relay"
def _query(self, messages, **kwargs): payload = {"model": self.config.model_name, "messages": messages, "tools": [BASH_TOOL], "usage": {"include": True}, **(self.config.model_kwargs | kwargs)} try: response = requests.post(self._api_url, headers={"Content-Type": "application/json"}, data=json.dumps(payload), timeout=600) response.raise_for_status() return response.json() except requests.exceptions.HTTPError as e: if response.status_code in (401, 402): # 402: the relay's spend cap raise OpenRouterAuthenticationError(f"relay refused: HTTP {response.status_code} {response.text[:200]}") from e if response.status_code == 429: raise OpenRouterRateLimitError("Rate limit exceeded") from e raise OpenRouterAPIError(f"HTTP {response.status_code}: {response.text[:300]}") from e except requests.exceptions.RequestException as e: raise OpenRouterAPIError(f"Request failed: {e}") from e1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env bash# Score again, alone, every instance whose scoring errored, and add what resolves to the run's summary.# Two things make an instance's scoring error on a busy machine: a docker call that times out while hundreds of other# containers start and stop, and one scikit-learn test of the subset that collapses when its cores are shared. Here# one instance runs at a time on 16 cores of its own, set before its tests start, with up to three tries.# Every run is treated the same way, the comparison model's run included.# LABEL=stock-1 [OUT=...] [LANE=0|1] bash eval/rescore.shset -uR=/data/train/miniP=$R/venv/bin/pythonLABEL=${LABEL:?give LABEL}; OUT=${OUT:-$R/results/agent/$LABEL}; LANE=${LANE:-0}CORES=$((LANE * 16))-$((LANE * 16 + 15))cd "$OUT" || exit 1IDS=$($P $R/src/eval/rescore_merge.py ids "$OUT" "$LABEL")[ -z "$IDS" ] && exit 0mkdir -p "$OUT/rescore"cd "$OUT/rescore" || exit 1 # the harness writes its report and logs into the folder it runs inif ! ls "$OUT"/rescore/*.json >/dev/null 2>&1; then for try in 1 2 3; do rm -f .pinned ( end=$((SECONDS + 1500)) while [ $SECONDS -lt $end ]; do for c in $(/usr/bin/docker ps --format '{{.Names}}' | grep -F ".$LABEL-rescore"); do grep -qxF "$c" .pinned 2>/dev/null && continue /usr/bin/docker update --cpus 0 --cpuset-cpus "$CORES" "$c" >/dev/null 2>&1 && echo "$c" >> .pinned done sleep 0.3 done ) & W=$! rm -f ./*."$LABEL-rescore".json # shellcheck disable=SC2086 sudo -n env PATH=$R/venv-smith/bin:/usr/bin:/bin HF_HOME=$R/hf $R/venv-smith/bin/python -m swebench.harness.run_evaluation \ --dataset_name princeton-nlp/SWE-bench_Verified --split test --predictions_path "$OUT/preds.json" --run_id "$LABEL-rescore" \ --max_workers 1 --timeout 900 --namespace swebench --instance_ids $IDS > score-$try.log 2>&1 kill $W 2>/dev/null sudo -n chown -R "$USER":"$USER" "$OUT" 2>/dev/null # shellcheck disable=SC2086 ls ./*."$LABEL-rescore".json >/dev/null 2>&1 || $P $R/src/eval/instance_report.py "$OUT/rescore" "$LABEL-rescore" "$OUT/preds.json" \ "instances.$LABEL-rescore.json" --ids $IDS >> score-$try.log 2>&1 [ -z "$($P $R/src/eval/rescore_merge.py errors "$OUT" "$LABEL")" ] && break done echo "tries: $try" > tries.txtfi$P $R/src/eval/rescore_merge.py merge "$OUT" "$LABEL"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""Helper of eval/rescore.sh.
python eval/rescore_merge.py ids <run folder> <label> the instance ids whose scoring errored (once per run) python eval/rescore_merge.py errors <run folder> <label> the ids that errored again in the last rescoring python eval/rescore_merge.py merge <run folder> <label> adds what resolved when scored alone to summary.json python eval/rescore_merge.py reset <run folder> <label> forgets a rescoring that added nothing, so it is done again"""import globimport jsonimport sys
def main(): cmd, out, label = sys.argv[1:4] s = json.load(open(out + "/summary.json")) if cmd == "ids": if s.get("rescored_alone") is not None: return r = json.load(open(out + "/" + s["report_file"])) print(" ".join(r.get("error_ids") or [])) return reports = glob.glob(out + "/rescore/*.json") new, err = set(), [] for f in reports: r = json.load(open(f)) new |= set(r.get("resolved_ids") or []) err += r.get("error_ids") or [] if cmd == "errors": print(" ".join(sorted(set(err))) if reports else "no report") return if cmd == "reset": ra = s.get("rescored_alone") if ra is not None and not ra.get("resolved"): s.pop("rescored_alone", None) s.pop("resolved_first_scoring", None) json.dump(s, open(out + "/summary.json", "w"), indent=1) print("reset", label) return if s.get("rescored_alone") is not None: return if not reports: print(json.dumps({"label": label, "rescore": "no report was written; not merged"})) return added = sorted(new - set(s["resolved_ids"])) s["resolved_first_scoring"] = s["resolved"] s["resolved_ids"] = sorted(set(s["resolved_ids"]) | new) s["resolved"] = len(s["resolved_ids"]) s["score_pct"] = round(100 * s["resolved"] / s["subset_n"], 1) s["rescored_alone"] = {"resolved": added, "still_error": sorted(set(err))} json.dump(s, open(out + "/summary.json", "w"), indent=1) print(json.dumps({"label": label, "resolved": s["resolved"], "resolved_first_scoring": s["resolved_first_scoring"], "rescored_alone": s["rescored_alone"]}))
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/usr/bin/env bash# One pass of the bash-only agent (mini-swe-agent, its own swebench.yaml) over the evaluation subset.# LABEL=stock-1 URL=http://127.0.0.1:9006/v1 MODEL=hosted_vllm/inkling-2-mini bash eval/run_agent.sh# LABEL=opus55-1 RELAY=1 WORKERS=8 bash eval/run_agent.sh # the comparison model, through the laptop relay# Output: /data/train/mini/results/agent/$LABEL/{preds.json, <instance>/<instance>.traj.json, run.log}set -uR=/data/train/miniLABEL=${LABEL:?give LABEL}; URL=${URL:-http://127.0.0.1:9006/v1}; MODEL=${MODEL:-hosted_vllm/inkling-2-mini}WORKERS=${WORKERS:-32}; TEMP=${TEMP:-0}; MAXTOK=${MAXTOK:-16384}; STEPS=${STEPS:-250}; RELAY=${RELAY:-0}SUBSET=${SUBSET:-$R/src/eval/subset.json}; DATA=${DATA:-verified}; SPLIT=${SPLIT:-test}export PATH=$R/bin:$R/venv/bin:$PATH MSWEA_DOCKER_EXECUTABLE=$R/bin/docker HF_HOME=$R/hf PYTHONPATH=$R/src/evalOUT=${OUT:-$R/results/agent/$LABEL}; mkdir -p "$OUT"FILTER=$(python - "$SUBSET" <<'EOF'import json, re, sysprint("^(" + "|".join(re.escape(i) for i in json.load(open(sys.argv[1]))["instance_ids"]) + ")$")EOF)if [ "$RELAY" = 1 ]; then MODEL_ARGS=(--model-class relay_model.RelayOpenRouterModel -m anthropic/claude-opus-5.5 -c model.set_cache_control=default_end -c model.model_kwargs.max_tokens="$MAXTOK" -c agent.cost_limit="${COST_LIMIT:-2.5}")else export MSWEA_COST_TRACKING=ignore_errors MODEL_ARGS=(-m "$MODEL" -c model.model_kwargs.api_base="$URL" -c model.model_kwargs.api_key=EMPTY -c model.model_kwargs.temperature="$TEMP" -c model.model_kwargs.max_tokens="$MAXTOK" -c agent.cost_limit=0)fiecho "== $LABEL start $(date -u +%FT%TZ) workers=$WORKERS temp=$TEMP steps=$STEPS maxtok=$MAXTOK relay=$RELAY" | tee -a "$OUT/meta.txt"# STARTUP: a command run in the task's container before the agent starts, with the instance's fields as {{ names }}.# SWE-smith needs one: a task is a branch of the repository inside the image, so it must be checked out first.STARTUP_ARGS=()[ -n "${STARTUP:-}" ] && STARTUP_ARGS=(-c "run.env_startup_command=$STARTUP")# shellcheck disable=SC2086mini-extra swebench --subset "$DATA" --split "$SPLIT" --filter "$FILTER" -o "$OUT" -w "$WORKERS" \ -c swebench.yaml -c agent.step_limit="$STEPS" "${MODEL_ARGS[@]}" "${STARTUP_ARGS[@]}" ${EXTRA_ARGS:-} > "$OUT/run.log" 2>&1echo "== $LABEL agent done $(date -u +%FT%TZ) exit=$?" | tee -a "$OUT/meta.txt"python - "$OUT" <<'EOF'import json, sys, glob, collectionsout = sys.argv[1]try: p = json.load(open(out + "/preds.json"))except Exception as e: print("no preds.json:", e); sys.exit()st = collections.Counter()for f in glob.glob(out + "/*/*.traj.json"): try: st[json.load(open(f)).get("info", {}).get("exit_status")] += 1 except Exception: st["unreadable"] += 1print("predictions:", len(p), "with a patch:", sum(1 for v in p.values() if (v.get("model_patch") or "").strip()), "exit statuses:", dict(st))EOF1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env bash# Score one agent pass with the official SWE-bench harness, version 4.0.4 (the benchmark's own tests, in its own images).# LABEL=stock-1 bash eval/score.sh# An instance of the subset with no prediction or an empty patch counts as not resolved: the score is always out of N.set -uR=/data/train/miniLABEL=${LABEL:?give LABEL}; OUT=${OUT:-$R/results/agent/$LABEL}; EW=${EW:-24}SUBSET=${SUBSET:-$R/src/eval/subset.json}cd "$OUT" || exit 1echo "== $LABEL scoring start $(date -u +%FT%TZ)" | tee -a meta.txtrm -f "instances.$LABEL.json"sudo -n env PATH=$R/venv-smith/bin:/usr/bin:/bin HF_HOME=$R/hf $R/venv-smith/bin/python -m swebench.harness.run_evaluation \ --dataset_name princeton-nlp/SWE-bench_Verified --split test --predictions_path "$OUT/preds.json" --run_id "$LABEL" \ --max_workers "$EW" --namespace swebench --report_dir "$OUT" > score.log 2>&1sudo -n chown -R "$USER":"$USER" "$OUT" $R/hf 2>/dev/null# The harness's last step can fail on a busy machine and leave no run report (see eval/instance_report.py); the# per-instance reports are complete by then and are added up instead.ls ./*."$LABEL".json >/dev/null 2>&1 || $R/venv/bin/python $R/src/eval/instance_report.py "$OUT" "$LABEL" "$OUT/preds.json" "instances.$LABEL.json" >> score.log 2>&1echo "== $LABEL scoring done $(date -u +%FT%TZ)" | tee -a meta.txt$R/venv/bin/python - "$OUT" "$SUBSET" "$LABEL" <<'EOF'import glob, json, sysout, subset, label = sys.argv[1:4]ids = json.load(open(subset))["instance_ids"]reports = [f for f in glob.glob(out + f"/*.{label}.json")]if not reports: print("NO REPORT FILE; see score.log"); sys.exit(1)r = json.load(open(reports[0]))resolved = sorted(set(r.get("resolved_ids", [])) & set(ids))summary = {"label": label, "subset_n": len(ids), "resolved": len(resolved), "score_pct": round(100 * len(resolved) / len(ids), 1), "submitted": r.get("submitted_instances"), "completed": r.get("completed_instances"), "empty_patch": r.get("empty_patch_instances"), "error": r.get("error_instances"), "unresolved": r.get("unresolved_instances"), "resolved_ids": resolved, "report_file": reports[0].split("/")[-1]}json.dump(summary, open(out + "/summary.json", "w"), indent=1)print(json.dumps({k: v for k, v in summary.items() if k != "resolved_ids"}))EOF123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138{ "dataset": "princeton-nlp/SWE-bench_Verified", "split": "test", "dataset_fingerprint": "1fdfd21ba2621130", "total_instances": 500, "seed": 20261201, "n": 100, "method": "random.Random(seed).sample(sorted(instance_ids), n)", "instance_ids": [ "astropy__astropy-14598", "astropy__astropy-7336", "astropy__astropy-7671", "django__django-10554", "django__django-11138", "django__django-11211", "django__django-11276", "django__django-11451", "django__django-11555", "django__django-11749", "django__django-11815", "django__django-11885", "django__django-12125", "django__django-12143", "django__django-12262", "django__django-12304", "django__django-12663", "django__django-12754", "django__django-12774", "django__django-12965", "django__django-13012", "django__django-13023", "django__django-13112", "django__django-13343", "django__django-13449", "django__django-13513", "django__django-13551", "django__django-13794", "django__django-13809", "django__django-13964", "django__django-14011", "django__django-14155", "django__django-14434", "django__django-14493", "django__django-14539", "django__django-14559", "django__django-14725", "django__django-14771", "django__django-15022", "django__django-15280", "django__django-15467", "django__django-15695", "django__django-15731", "django__django-15732", "django__django-15814", "django__django-15957", "django__django-16116", "django__django-16333", "django__django-16560", "django__django-16642", "django__django-16662", "django__django-17087", "matplotlib__matplotlib-20859", "matplotlib__matplotlib-22865", "matplotlib__matplotlib-24570", "matplotlib__matplotlib-25122", "matplotlib__matplotlib-25332", "matplotlib__matplotlib-25960", "matplotlib__matplotlib-26208", "matplotlib__matplotlib-26342", "mwaskom__seaborn-3187", "psf__requests-5414", "psf__requests-6028", "pydata__xarray-3151", "pydata__xarray-4356", "pydata__xarray-4966", "pydata__xarray-6721", "pydata__xarray-7229", "pydata__xarray-7233", "pydata__xarray-7393", "pylint-dev__pylint-4970", "pytest-dev__pytest-10081", "pytest-dev__pytest-5631", "pytest-dev__pytest-5809", "pytest-dev__pytest-6197", "pytest-dev__pytest-7571", "pytest-dev__pytest-8399", "scikit-learn__scikit-learn-13779", "scikit-learn__scikit-learn-14629", "scikit-learn__scikit-learn-14710", "scikit-learn__scikit-learn-25232", "sphinx-doc__sphinx-10673", "sphinx-doc__sphinx-8120", "sphinx-doc__sphinx-9698", "sympy__sympy-12481", "sympy__sympy-13031", "sympy__sympy-13091", "sympy__sympy-13877", "sympy__sympy-13974", "sympy__sympy-15976", "sympy__sympy-16450", "sympy__sympy-16766", "sympy__sympy-17655", "sympy__sympy-19637", "sympy__sympy-20428", "sympy__sympy-21379", "sympy__sympy-22080", "sympy__sympy-23824", "sympy__sympy-24066", "sympy__sympy-24213" ], "instances_per_repo": { "astropy/astropy": 3, "django/django": 49, "matplotlib/matplotlib": 8, "mwaskom/seaborn": 1, "psf/requests": 2, "pydata/xarray": 7, "pylint-dev/pylint": 1, "pytest-dev/pytest": 6, "scikit-learn/scikit-learn": 4, "sphinx-doc/sphinx": 3, "sympy/sympy": 16 }, "all_repos_of_the_benchmark": [ "astropy/astropy", "django/django", "matplotlib/matplotlib", "mwaskom/seaborn", "pallets/flask", "psf/requests", "pydata/xarray", "pylint-dev/pylint", "pytest-dev/pytest", "scikit-learn/scikit-learn", "sphinx-doc/sphinx", "sympy/sympy" ]}eval/instance_report.pyAdded+49
eval/make_subset.pyAdded+36
eval/relay_model.pyAdded+35
eval/rescore.shAdded+44
eval/rescore_merge.pyAdded+56
eval/run_agent.shAdded+50
eval/score.shAdded+35
eval/subset.jsonAdded+138