Upload 6 files
Browse filesFiles changed (6)
- deep/__init__.pyAdded
- deep/make_candidates.pyAdded+70
- deep/merge_review.pyAdded+67
- deep/review.yamlAdded+110
- deep/select.pyAdded+139
- deep/server.pyAdded+165
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Deep mode, rule C, step 1: write the distinct patches of the tasks where the attempts disagree.
python deep/make_candidates.py --attempts /data/train/mini/results/deep --n 8 \ --out-patches /data/train/mini/pool_patches/cands-deep-n8 --out-subset /data/train/mini/results/review/deep-n8/subset.json
A task is left out when one patch has a majority of the attempts (rule A already decided it) or when no attempt made apatch. For the others: up to six distinct patches, the most shared first, as <out-patches>/<instance>/c<k>.diff with aREADME.txt. Nothing here reads the benchmark's tests or any score."""import argparseimport collectionsimport jsonimport osimport shutil
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 main(): ap = argparse.ArgumentParser() ap.add_argument("--attempts", required=True) ap.add_argument("--n", type=int, required=True) ap.add_argument("--subset", default="/data/train/mini/src/eval/subset.json") ap.add_argument("--out-patches", required=True) ap.add_argument("--out-subset", required=True) a = ap.parse_args() ids = json.load(open(a.subset))["instance_ids"] preds = [json.load(open(f"{a.attempts}/att-{k}/preds.json")) for k in range(1, a.n + 1)] shutil.rmtree(a.out_patches, ignore_errors=True) os.makedirs(os.path.dirname(a.out_subset), exist_ok=True) chosen, record = [], {} for iid in ids: groups = collections.defaultdict(list) for k, p in enumerate(preds): patch = (p.get(iid) or {}).get("model_patch") or "" if patch.strip(): groups[normal(patch)].append((k + 1, patch)) made = sum(len(v) for v in groups.values()) if not groups: continue ranked = sorted(groups.values(), key=lambda g: (-len(g), len(g[0][1]))) if len(ranked[0]) * 2 > made or len(ranked) == 1: continue d = f"{a.out_patches}/{iid}" os.makedirs(d) lines = [f"{len(ranked)} distinct patches came out of {made} attempts that produced one ({a.n} attempts in all)."] for i, g in enumerate(ranked[:6], 1): text = g[0][1] if g[0][1].endswith("\n") else g[0][1] + "\n" open(f"{d}/c{i}.diff", "w").write(text) lines.append(f"c{i}.diff: produced by {len(g)} of the attempts") if len(ranked) > 6: lines.append(f"({len(ranked) - 6} more patches, each from one attempt, are not shown)") open(f"{d}/README.txt", "w").write("\n".join(lines) + "\n") chosen.append(iid) record[iid] = {"attempts_with_patch": made, "distinct": len(ranked), "shown": [[k for k, _ in g] for g in ranked[:6]]} json.dump({"instance_ids": chosen, "n": a.n, "candidates": record}, open(a.out_subset, "w"), indent=1) print(json.dumps({"n": a.n, "tasks_to_review": len(chosen), "of": len(ids)}))
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Deep mode, rule C, step 3: the final predictions.
python deep/merge_review.py --base <rule A>/preds.json --review <review run>/preds.json --subset <review subset.json> \ --cands /data/train/mini/pool_patches/cands-deep-n8 --out /data/train/mini/results/agent/deepC-n8 --name rightnow-mini-deep-reviewed-n8
For a task the reviewing session handled and returned a patch for, that patch; for every other task, rule A's patch.select.json records, per reviewed task, whether the session returned one of the candidates unchanged or a new patch."""import argparseimport globimport jsonimport os
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 main(): ap = argparse.ArgumentParser() ap.add_argument("--base", required=True) ap.add_argument("--review", required=True) ap.add_argument("--subset", required=True) ap.add_argument("--cands", required=True) ap.add_argument("--out", required=True) ap.add_argument("--name", required=True) a = ap.parse_args() os.makedirs(a.out, exist_ok=True) base = json.load(open(a.base)) rev = json.load(open(a.review)) if os.path.exists(a.review) else {} sub = json.load(open(a.subset)) out, log = {}, [] for iid, v in base.items(): out[iid] = {"instance_id": iid, "model_name_or_path": a.name, "model_patch": v.get("model_patch") or ""} kinds = {"candidate": 0, "new patch": 0, "no patch, rule A kept": 0} for iid in sub["instance_ids"]: patch = (rev.get(iid) or {}).get("model_patch") or "" info = {"instance_id": iid, "distinct": sub["candidates"][iid]["distinct"]} if not patch.strip(): info["how"] = "no patch, rule A kept" else: which = None for f in sorted(glob.glob(f"{a.cands}/{iid}/c*.diff")): if normal(open(f).read()) == normal(patch): which = os.path.basename(f) info["how"] = "candidate" if which else "new patch" info["candidate"] = which info["same_as_rule_a"] = normal(patch) == normal(out.get(iid, {}).get("model_patch", "")) out[iid] = {"instance_id": iid, "model_name_or_path": a.name, "model_patch": patch} kinds[info["how"]] += 1 log.append(info) json.dump(out, open(a.out + "/preds.json", "w")) summary = {"n": sub["n"], "mode": "reviewing session with tools", "reviewed": len(sub["instance_ids"]), "returned": kinds, "changed_from_rule_a": sum(1 for x in log if x.get("same_as_rule_a") is False)} json.dump(dict(summary, tasks=log), open(a.out + "/select.json", "w"), indent=1) print(json.dumps(summary))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# Deep mode, rule C: the reviewing session. Used on top of mini-swe-agent's own swebench.yaml# (-c swebench.yaml -c deep/review.yaml): only the task text changes. The candidate patches of the earlier# attempts are put in /tmp/candidates/ before the session starts (deep/make_candidates.py, tools/review_run.sh).agent: instance_template: | <pr_description> Consider the following PR description: {{task}} </pr_description>
<instructions> # Task Instructions
## Overview
You're a software engineer interacting continuously with a computer by submitting commands. You'll be helping implement necessary changes to meet requirements in the PR description. Your task is specifically to make changes to non-test files in the current directory in order to fix the issue described in the PR description in a way that is general and consistent with the codebase. <IMPORTANT>This is an interactive process where you will think and issue AT LEAST ONE command, see the result, then think and issue your next command(s).</important>
## Candidate patches (read this first)
Several earlier attempts at this task each produced a patch. The distinct ones are in /tmp/candidates/ (c1.diff, c2.diff, ...). /tmp/candidates/README.txt says how many attempts produced each one. They disagree, and some of them are wrong. In this session you decide what the final patch is, by testing the candidates instead of trusting them.
For each response:
1. Include a THOUGHT section explaining your reasoning and what you're trying to accomplish 2. Provide one or more bash tool calls to execute
## Important Boundaries
- MODIFY: Regular source code files in /testbed (this is the working directory for all your subsequent commands) - DO NOT MODIFY: Tests, configuration files (pyproject.toml, setup.cfg, etc.)
## Recommended Workflow
1. Read the PR description and the code it concerns, then read every candidate patch 2. Create a script in /tmp that reproduces the issue, and run it on the unchanged code to see it fail 3. Try each candidate in turn: `git apply /tmp/candidates/cK.diff`, run your script and the existing tests next to the changed code, note the result, then undo it with `git apply -R /tmp/candidates/cK.diff` 4. Apply the candidate that is correct and most general. If none is fully right, apply the closest one and correct it 5. Test edge cases, then submit the final state of the source files as described below
## Command Execution Rules
You are operating in an environment where
1. You issue at least one command 2. The system executes the command(s) in a subshell 3. You see the result(s) 4. You write your next command(s)
Each response should include:
1. **Reasoning text** where you explain your analysis and plan 2. At least one tool call with your command
**CRITICAL REQUIREMENTS:**
- Your response SHOULD include reasoning text explaining what you're doing - Your response MUST include AT LEAST ONE bash tool call. You can make MULTIPLE tool calls in a single response when the commands are independent (e.g., searching multiple files, reading different parts of the codebase). - Directory or environment variable changes are not persistent. Every action is executed in a new subshell. - However, you can prefix any action with `MY_ENV_VAR=MY_VALUE cd /path/to/working/dir && ...` or write/load environment variables from files
## Environment Details
- You have a full Linux shell environment - Always use non-interactive flags (-y, -f) for commands - Avoid interactive tools like vi, nano, or any that require user input - You can use bash commands or invoke any tool that is available in the environment - You can also create new tools or scripts to help you with the task
## Submission
When you've completed your work, you MUST submit your changes as a git patch. Follow these steps IN ORDER, with SEPARATE commands:
Step 1: Create the patch file Run `git diff -- path/to/file1 path/to/file2 > patch.txt` listing only the source files that the final patch changes. Do NOT commit your changes.
<IMPORTANT> The patch must only contain changes to the specific source files that fix the issue. Do not submit file creations or changes to any of the following files:
- test and reproduction files - helper scripts, tests, or tools that you created - installation, build, packaging, configuration, or setup scripts unless they are directly part of the issue you were fixing (you can assume that the environment is already set up for your client) - binary or compiled files </IMPORTANT>
Step 2: Verify your patch Inspect patch.txt to confirm it only contains your intended changes and headers show `--- a/` and `+++ b/` paths.
Step 3: Submit (EXACT command required) You MUST use this EXACT command to submit:
```bash echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT && cat patch.txt ```
If the command fails (nonzero exit status), it will not submit.
<CRITICAL> - Creating/viewing the patch and submitting it MUST be separate commands (not combined with &&). - If you modify patch.txt after verifying, you SHOULD verify again before submitting. - You CANNOT continue working (reading, editing, testing) in any way on this task after submitting. </CRITICAL> </instructions>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""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 argparseimport collectionsimport concurrent.futuresimport jsonimport osimport reimport timeimport 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.
<report>{task}</report>
{cands}
Think it through, then end your answer with a line of the form: BEST: <number>"""
def review(url, model, task, cands, rot): order = cands[rot % len(cands):] + cands[:rot % len(cands)] text = "\n\n".join(f"<patch number=\"{i + 1}\">\n{p[:12000]}\n</patch>" 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-<k>/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<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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""Deep mode as one model id: `rightnow-mini-deep`.
An OpenAI-compatible server in front of a RightNow Mini endpoint. A request for `rightnow-mini-deep` is fanned out toN sampled attempts in parallel (default 16), a verifier picks one, and that one answer is returned. Any other modelid is passed through unchanged.
python deep/server.py --upstream http://127.0.0.1:9000 --model inkling-2-mini --port 9100
The verifier uses only what the caller sent: 1. agreement: if more than half of the attempts give the same answer (white space ignored), that answer wins; 2. review: otherwise the model reads the request and the distinct answers and votes three times with the answers in a different order each time; the most voted answer wins, then the one more attempts agreed on.Per-request fields (optional): "n_attempts" (1 to 64), "attempt_temperature" (default 0.8).The reply carries a "deep" object: attempts, distinct answers, how it was decided, seconds, tokens used."""import argparseimport asyncioimport collectionsimport jsonimport reimport time
import aiohttpfrom aiohttp import web
DEEP_ID = "rightnow-mini-deep"REVIEW = """Several answers were written for the same request. Pick the one that is most correct and complete.
<request>{req}</request>
{cands}
Think it through, then end with a line of the form: BEST: <number>"""
def norm(text): return re.sub(r"\s+", " ", text or "").strip()
def last_user(messages): for m in reversed(messages): if m.get("role") == "user": c = m.get("content") return c if isinstance(c, str) else json.dumps(c) return ""
async def call(session, url, body): async with session.post(url + "/v1/chat/completions", json=body) as r: d = await r.json() if r.status != 200: raise web.HTTPBadGateway(text=json.dumps(d)[:500]) return d
async def deep(app, body): a, s = app["args"], app["session"] n = max(1, min(64, int(body.pop("n_attempts", a.attempts)))) temp = float(body.pop("attempt_temperature", 0.8)) base = {k: v for k, v in body.items() if k not in ("stream", "n", "stream_options")} base.update(model=a.model, temperature=temp) t0 = time.perf_counter() done = await asyncio.gather(*[call(s, a.upstream, dict(base)) for _ in range(n)], return_exceptions=True) ok = [d for d in done if isinstance(d, dict) and d.get("choices")] if not ok: raise web.HTTPBadGateway(text="no attempt returned an answer") tokens = sum((d.get("usage") or {}).get("completion_tokens", 0) for d in ok) groups = collections.defaultdict(list) for d in ok: groups[norm(d["choices"][0]["message"].get("content"))].append(d) ranked = sorted(groups.values(), key=len, reverse=True) how, votes = "agreement", {} best = 0 if len(ranked) > 1 and len(ranked[0]) * 2 <= len(ok): how = "review" cands = list(range(min(len(ranked), 8))) tally = collections.Counter()
async def vote(rot): order = cands[rot % len(cands):] + cands[:rot % len(cands)] text = "\n\n".join(f"<answer number=\"{i + 1}\">\n{(ranked[g][0]['choices'][0]['message'].get('content') or '')[:12000]}\n</answer>" for i, g in enumerate(order)) # reasoning effort 0.3 and a large budget: at the model's default effort (0.9) and 4,096 tokens most reviews # ended while still reasoning, with no answer (results/deep.md) d = await call(s, a.upstream, {"model": a.model, "temperature": 0, "max_tokens": 16384, "chat_template_kwargs": {"reasoning_effort": 0.3}, "messages": [ {"role": "user", "content": REVIEW.format(req=last_user(body.get("messages", []))[:16000], cands=text)}]}) msg = d["choices"][0]["message"] said = msg.get("content") or "" if "BEST:" not in said: said += "\n" + (msg.get("reasoning") or msg.get("reasoning_content") or "") m = re.findall(r"BEST:\s*(\d+)", said) return (order[int(m[-1]) - 1] if m and 1 <= int(m[-1]) <= len(order) else None), (d.get("usage") or {}).get("completion_tokens", 0) for r in await asyncio.gather(*[vote(i) for i in range(3)], return_exceptions=True): if isinstance(r, tuple): tokens += r[1] if r[0] is not None: tally[r[0]] += 1 votes = dict(tally) best = max(cands, key=lambda g: (tally.get(g, 0), len(ranked[g]))) out = dict(ranked[best][0]) out["model"] = DEEP_ID out["deep"] = {"attempts": n, "answered": len(ok), "distinct_answers": len(ranked), "decided_by": how, "votes": votes, "agreeing_attempts": len(ranked[best]), "seconds": round(time.perf_counter() - t0, 3), "completion_tokens_all": tokens} return out
async def chat(request): app = request.app body = await request.json() stream = bool(body.get("stream")) if body.get("model") != DEEP_ID: async with app["session"].post(app["args"].upstream + "/v1/chat/completions", json=body) as r: if not stream: return web.Response(status=r.status, body=await r.read(), content_type="application/json") resp = web.StreamResponse(status=r.status, headers={"Content-Type": "text/event-stream"}) await resp.prepare(request) async for chunk in r.content.iter_any(): await resp.write(chunk) return resp out = await deep(app, body) if not stream: return web.json_response(out) resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"}) await resp.prepare(request) msg = out["choices"][0]["message"] chunk = {"id": out.get("id"), "object": "chat.completion.chunk", "model": DEEP_ID, "deep": out["deep"], "choices": [{"index": 0, "delta": {"role": "assistant", "content": msg.get("content") or ""}, "finish_reason": out["choices"][0].get("finish_reason")}]} await resp.write(f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n".encode()) return resp
async def models(request): a = request.app["args"] return web.json_response({"object": "list", "data": [{"id": a.model, "object": "model"}, {"id": DEEP_ID, "object": "model"}]})
async def make_app(args): app = web.Application(client_max_size=64 * 2**20) app["args"] = args app["session"] = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3600), connector=aiohttp.TCPConnector(limit=0)) app.router.add_post("/v1/chat/completions", chat) app.router.add_get("/v1/models", models)
async def close(app): await app["session"].close() app.on_cleanup.append(close) return app
def main(): ap = argparse.ArgumentParser() ap.add_argument("--upstream", default="http://127.0.0.1:9000") ap.add_argument("--model", default="rightnow-mini") ap.add_argument("--attempts", type=int, default=16) ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=9100) args = ap.parse_args() web.run_app(make_app(args), host=args.host, port=args.port, print=None)
if __name__ == "__main__": main()deep/__init__.pyAdded
deep/make_candidates.pyAdded+70
deep/merge_review.pyAdded+67
deep/review.yamlAdded+110
deep/select.pyAdded+139
deep/server.pyAdded+165