"""Deep mode, the selection step: from N sampled attempts at one task, return one patch. python deep/select.py --attempts /data/train/mini/results/deep --n 8 --url http://127.0.0.1:9006 \ --model inkling-2-mini --out /data/train/mini/results/agent/deep-n8 The verifier never sees the benchmark's tests. It uses only what a user of the model would have: 1. agreement: if more than half of the attempts that produced a patch produced the same patch, that patch wins; 2. review (the default): otherwise the model itself reads the task and the distinct candidate patches and votes (three votes, candidate order rotated); the most voted patch wins, ties go to the patch more attempts agreed on, then the shorter. With --mode agree there is no model call: the most shared patch wins, then the shorter. Writes preds.json in the benchmark's format, plus select.json with how every task was decided. """ import argparse import collections import concurrent.futures import json import os import re import time import urllib.request from datasets import load_dataset def normal(patch): keep = [] for line in (patch or "").splitlines(): if line.startswith(("index ", "diff --git", "new file mode", "old mode", "new mode", "similarity index")): continue if line.startswith("@@"): line = "@@" keep.append(line.rstrip()) return "\n".join(keep).strip() def ask(url, model, prompt): # Reasoning effort 0.3 (the model's default is 0.9) and a large budget: in the first run the model spent all of 4,096 tokens reasoning and gave # no answer in about nine reviews of ten, so no vote was cast. The answer is read from the reply, and from the # reasoning text when the reply holds none. body = {"model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": 16384, "temperature": 0, "chat_template_kwargs": {"reasoning_effort": 0.3}} req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=1800) as r: d = json.loads(r.read()) m = d["choices"][0]["message"] text = m.get("content") or "" if "BEST:" not in text: text += "\n" + (m.get("reasoning") or m.get("reasoning_content") or "") return text, d["usage"]["completion_tokens"] REVIEW = """You are reviewing candidate patches for a bug report. Exactly one answer is wanted: the number of the patch most likely to fix the report correctly without breaking other behaviour. {task} {cands} Think it through, then end your answer with a line of the form: BEST: """ def review(url, model, task, cands, rot): order = cands[rot % len(cands):] + cands[:rot % len(cands)] text = "\n\n".join(f"\n{p[:12000]}\n" for i, (_, p) in enumerate(order)) out, toks = ask(url, model, REVIEW.format(task=task[:16000], cands=text)) m = re.findall(r"BEST:\s*(\d+)", out) if not m or not 1 <= int(m[-1]) <= len(order): return None, toks return order[int(m[-1]) - 1][0], toks def main(): ap = argparse.ArgumentParser() ap.add_argument("--attempts", required=True, help="folder with att-/preds.json") ap.add_argument("--n", type=int, required=True, help="use attempts 1..n") ap.add_argument("--subset", default="/data/train/mini/src/eval/subset.json") ap.add_argument("--url", required=True) ap.add_argument("--model", required=True) ap.add_argument("--out", required=True) ap.add_argument("--workers", type=int, default=16) ap.add_argument("--mode", choices=("review", "agree"), default="review", help="review: the model votes when the attempts disagree. agree: no model call, the most shared patch wins") ap.add_argument("--name", default="", help="model name written into the predictions (default rightnow-mini-deep-n)") a = ap.parse_args() os.makedirs(a.out, exist_ok=True) ids = json.load(open(a.subset))["instance_ids"] ds = load_dataset("princeton-nlp/SWE-bench_Verified", split="test") task_of = {i: p for i, p in zip(ds["instance_id"], ds["problem_statement"]) if i in set(ids)} preds = [json.load(open(f"{a.attempts}/att-{k}/preds.json")) for k in range(1, a.n + 1)] def decide(iid): t0 = time.time() patches = [(k + 1, (p.get(iid) or {}).get("model_patch") or "") for k, p in enumerate(preds)] groups = collections.defaultdict(list) for k, p in patches: if p.strip(): groups[normal(p)].append((k, p)) made = sum(len(v) for v in groups.values()) info = {"instance_id": iid, "attempts": a.n, "attempts_with_patch": made, "distinct_patches": len(groups)} if not groups: return iid, "", dict(info, how="no attempt produced a patch", seconds=0.0) ranked = sorted(groups.values(), key=lambda g: (-len(g), len(g[0][1]))) if len(ranked[0]) * 2 > made or len(ranked) == 1: k, p = ranked[0][0] return iid, p, dict(info, how="agreement", agree=len(ranked[0]), attempt=k, seconds=round(time.time() - t0, 2)) if a.mode == "agree": # no model call: the patch most attempts share, then the shorter one k, p = ranked[0][0] return iid, p, dict(info, how="most shared, then shortest", agree=len(ranked[0]), attempt=k, seconds=round(time.time() - t0, 2)) cands = [(gi, g[0][1]) for gi, g in enumerate(ranked[:6])] votes, toks = collections.Counter(), 0 for rot in range(3): try: v, t = review(a.url, a.model, task_of[iid], cands, rot) except Exception: v, t = None, 0 toks += t if v is not None: votes[v] += 1 best = max(range(len(cands)), key=lambda gi: (votes.get(gi, 0), len(ranked[gi]), -len(ranked[gi][0][1]))) k, p = ranked[best][0] return iid, p, dict(info, how="review", votes=dict(votes), agree=len(ranked[best]), attempt=k, review_tokens=toks, seconds=round(time.time() - t0, 2)) out, log = {}, [] with concurrent.futures.ThreadPoolExecutor(a.workers) as ex: for iid, patch, info in ex.map(decide, ids): out[iid] = {"instance_id": iid, "model_name_or_path": a.name or f"rightnow-mini-deep-n{a.n}", "model_patch": patch} log.append(info) json.dump(out, open(a.out + "/preds.json", "w")) how = collections.Counter(x["how"] for x in log) novote = sum(1 for x in log if x["how"] == "review" and not x.get("votes")) json.dump({"n": a.n, "mode": a.mode, "decided": dict(how), "reviews_with_no_vote": novote, "tasks": log}, open(a.out + "/select.json", "w"), indent=1) print(json.dumps({"n": a.n, "mode": a.mode, "tasks": len(log), "decided": dict(how), "reviews_with_no_vote": novote, "with_patch": sum(1 for v in out.values() if v["model_patch"].strip())})) if __name__ == "__main__": main()