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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
OOLONG-synth runner: cheap model wrapped in an RLM vs. an expensive model read
|
| 4 |
+
straight through.
|
| 5 |
+
|
| 6 |
+
# cheap model, recursive
|
| 7 |
+
python run.py --mode rlm --model haiku --context-len 131072 -n 32
|
| 8 |
+
# expensive baselines
|
| 9 |
+
python run.py --mode baseline --model sonnet --context-len 131072 -n 32
|
| 10 |
+
python run.py --mode baseline --model 'opus[1m]' --context-len 262144 -n 32
|
| 11 |
+
|
| 12 |
+
Results append to results/<tag>.jsonl and are resumable: rerunning skips ids
|
| 13 |
+
already recorded, provided the run identity (mode/model/context_len) matches.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
import time
|
| 23 |
+
import traceback
|
| 24 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent / "bench"))
|
| 28 |
+
|
| 29 |
+
import oolong # noqa: E402
|
| 30 |
+
from rlm_haiku.rlm_repl import RLM_REPL # noqa: E402
|
| 31 |
+
from rlm_haiku.utils.llm import ClaudeCodeClient, QuotaExhausted, Usage # noqa: E402
|
| 32 |
+
|
| 33 |
+
RESULTS = Path(__file__).resolve().parent / "results"
|
| 34 |
+
|
| 35 |
+
MODELS = {
|
| 36 |
+
"haiku": "claude-haiku-4-5-20251001",
|
| 37 |
+
"sonnet": "claude-sonnet-4-6",
|
| 38 |
+
"sonnet[1m]": "claude-sonnet-4-6[1m]",
|
| 39 |
+
"opus": "claude-opus-4-8",
|
| 40 |
+
"opus[1m]": "claude-opus-4-8[1m]",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def run_baseline(row: dict, model: str, sub_model: str, max_iters: int, require_repl: bool = False) -> tuple[str, dict]:
|
| 45 |
+
"""Official OOLONG protocol: context + question in one shot, no tools."""
|
| 46 |
+
usage = Usage()
|
| 47 |
+
client = ClaudeCodeClient(model=model, usage=usage)
|
| 48 |
+
answer = client.completion([
|
| 49 |
+
{"role": "system", "content": oolong.SYSTEM_PREFIX},
|
| 50 |
+
{"role": "user", "content": row["context_window_text"] + "\n" + row["question"]},
|
| 51 |
+
])
|
| 52 |
+
return answer, usage.as_dict()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def run_rlm(row: dict, model: str, sub_model: str, max_iters: int, terse: bool = False,
|
| 56 |
+
require_repl: bool = False) -> tuple[str, dict]:
|
| 57 |
+
usage = Usage()
|
| 58 |
+
rlm = RLM_REPL(
|
| 59 |
+
model=model,
|
| 60 |
+
recursive_model=sub_model,
|
| 61 |
+
max_iterations=max_iters,
|
| 62 |
+
usage=usage,
|
| 63 |
+
terse=terse,
|
| 64 |
+
require_repl=require_repl,
|
| 65 |
+
)
|
| 66 |
+
answer = rlm.completion(context=row["context_window_text"], query=row["question"])
|
| 67 |
+
return answer, usage.as_dict()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def run_rlm_terse(row: dict, model: str, sub_model: str, max_iters: int, require_repl: bool = False) -> tuple[str, dict]:
|
| 71 |
+
return run_rlm(row, model, sub_model, max_iters, terse=True, require_repl=require_repl)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
RUNNERS = {"baseline": run_baseline, "rlm": run_rlm, "rlm-terse": run_rlm_terse}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def work(args) -> dict:
|
| 78 |
+
"""One example, in its own process (the REPL redirects the global stdout)."""
|
| 79 |
+
row, mode, model, sub_model, max_iters, require_repl = args
|
| 80 |
+
started = time.time()
|
| 81 |
+
try:
|
| 82 |
+
answer, usage = RUNNERS[mode](row, model, sub_model, max_iters, require_repl)
|
| 83 |
+
error, quota = None, False
|
| 84 |
+
except QuotaExhausted as e:
|
| 85 |
+
answer, usage, error, quota = "", {}, f"QuotaExhausted: {e}", True
|
| 86 |
+
except Exception:
|
| 87 |
+
answer, usage, error, quota = "", {}, traceback.format_exc(limit=4), False
|
| 88 |
+
|
| 89 |
+
scored = oolong.score_response(row, oolong.clean_final(answer)) if answer else {
|
| 90 |
+
"score": 0.0, "attempted_parse": "ERROR", "parse_confidence": "ERROR",
|
| 91 |
+
"gold": row["answer"],
|
| 92 |
+
}
|
| 93 |
+
return {
|
| 94 |
+
"id": int(row["id"]),
|
| 95 |
+
"dataset": row["dataset"],
|
| 96 |
+
"task": row["task"],
|
| 97 |
+
"answer_type": row["answer_type"],
|
| 98 |
+
"question": row["question"],
|
| 99 |
+
**scored,
|
| 100 |
+
"full_answer": answer,
|
| 101 |
+
"error": error,
|
| 102 |
+
"quota": quota,
|
| 103 |
+
"usage": usage,
|
| 104 |
+
"seconds": round(time.time() - started, 1),
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def main() -> None:
|
| 109 |
+
p = argparse.ArgumentParser()
|
| 110 |
+
p.add_argument("--mode", choices=RUNNERS, required=True)
|
| 111 |
+
p.add_argument("--model", default="haiku", help="root model (alias or full id)")
|
| 112 |
+
p.add_argument("--sub-model", default=None, help="recursive model; defaults to --model")
|
| 113 |
+
p.add_argument("--context-len", type=int, default=131072)
|
| 114 |
+
p.add_argument("-n", type=int, default=32, help="examples (stratified across the 8 sources)")
|
| 115 |
+
p.add_argument("--seed", type=int, default=0)
|
| 116 |
+
p.add_argument("--workers", type=int, default=4, help="examples in flight")
|
| 117 |
+
p.add_argument("--max-iters", type=int, default=12, help="root LM turns per RLM query")
|
| 118 |
+
p.add_argument("--require-repl", action="store_true", help="reject final answers before any REPL execution")
|
| 119 |
+
p.add_argument("--tag", default=None)
|
| 120 |
+
args = p.parse_args()
|
| 121 |
+
|
| 122 |
+
model = MODELS.get(args.model, args.model)
|
| 123 |
+
sub_model = MODELS.get(args.sub_model or args.model, args.sub_model or args.model)
|
| 124 |
+
tag = args.tag or f"{args.mode}_{args.model.replace('[1m]', '1m')}_{args.context_len}"
|
| 125 |
+
|
| 126 |
+
df = oolong.load(args.context_len, n=args.n, seed=args.seed)
|
| 127 |
+
rows = df.to_dict("records")
|
| 128 |
+
|
| 129 |
+
RESULTS.mkdir(exist_ok=True)
|
| 130 |
+
out = RESULTS / f"{tag}.jsonl"
|
| 131 |
+
meta = {"mode": args.mode, "model": model, "sub_model": sub_model,
|
| 132 |
+
"context_len": args.context_len, "seed": args.seed,
|
| 133 |
+
"require_repl": args.require_repl}
|
| 134 |
+
meta_path = RESULTS / f"{tag}.meta.json"
|
| 135 |
+
|
| 136 |
+
# Resume only if this is genuinely the same run; mixing configs fabricates a
|
| 137 |
+
# number no single run ever produced.
|
| 138 |
+
done, total_score, spent = {}, 0.0, 0.0
|
| 139 |
+
if out.exists() and meta_path.exists() and json.loads(meta_path.read_text()) == meta:
|
| 140 |
+
for line in out.read_text().splitlines():
|
| 141 |
+
if line.strip():
|
| 142 |
+
r = json.loads(line)
|
| 143 |
+
done[r["id"]] = r
|
| 144 |
+
total_score += r["score"]
|
| 145 |
+
spent += r.get("usage", {}).get("cost_usd", 0.0)
|
| 146 |
+
elif out.exists():
|
| 147 |
+
sys.exit(f"{out} exists with different settings; delete it or pass --tag")
|
| 148 |
+
meta_path.write_text(json.dumps(meta, indent=2))
|
| 149 |
+
|
| 150 |
+
todo = [r for r in rows if int(r["id"]) not in done]
|
| 151 |
+
n_total = len(rows)
|
| 152 |
+
print(f"[{tag}] {model} | {len(todo)} to run, {len(done)} cached, {n_total} total", flush=True)
|
| 153 |
+
if not todo:
|
| 154 |
+
print(f"[{tag}] already complete", flush=True)
|
| 155 |
+
|
| 156 |
+
errors, started, n_done, quota_hit = 0, time.time(), len(done), False
|
| 157 |
+
payloads = [(r, args.mode, model, sub_model, args.max_iters, args.require_repl) for r in todo]
|
| 158 |
+
|
| 159 |
+
with ProcessPoolExecutor(max_workers=args.workers) as pool, out.open("a") as fh:
|
| 160 |
+
futures = [pool.submit(work, pl) for pl in payloads]
|
| 161 |
+
for fut in as_completed(futures):
|
| 162 |
+
res = fut.result()
|
| 163 |
+
if res["quota"]:
|
| 164 |
+
# Quota is not a wrong answer. Bank nothing, stop everything, and
|
| 165 |
+
# let the operator resume once the window resets.
|
| 166 |
+
quota_hit = True
|
| 167 |
+
for f in futures:
|
| 168 |
+
f.cancel()
|
| 169 |
+
break
|
| 170 |
+
if res["error"]:
|
| 171 |
+
# Leave failed rows out of the journal so a resume retries them
|
| 172 |
+
# instead of banking a zero that no model actually produced.
|
| 173 |
+
errors += 1
|
| 174 |
+
print(f"[{tag}] ERROR (not journalled): {res['error'].splitlines()[-1][:160]}", flush=True)
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
fh.write(json.dumps(res) + "\n")
|
| 178 |
+
fh.flush()
|
| 179 |
+
os.fsync(fh.fileno())
|
| 180 |
+
|
| 181 |
+
n_done += 1
|
| 182 |
+
total_score += res["score"]
|
| 183 |
+
spent += res.get("usage", {}).get("cost_usd", 0.0)
|
| 184 |
+
rate = (time.time() - started) / max(1, n_done - len(done))
|
| 185 |
+
eta = rate * (n_total - n_done) / 60
|
| 186 |
+
print(
|
| 187 |
+
f"[{tag}] errors={errors} {n_done}/{n_total} "
|
| 188 |
+
f"score={total_score / n_done:.3f} ${spent:.2f} eta={eta:.1f}m",
|
| 189 |
+
flush=True,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
if quota_hit:
|
| 193 |
+
print(f"[{tag}] ABORTED: subscription quota exhausted. "
|
| 194 |
+
f"{n_done}/{n_total} banked; rerun the same command after the reset "
|
| 195 |
+
f"to resume.", flush=True)
|
| 196 |
+
if errors:
|
| 197 |
+
print(f"[{tag}] WARNING: {errors} example(s) failed and were NOT scored", flush=True)
|
| 198 |
+
print(
|
| 199 |
+
f"[{tag}] FINAL score={total_score / max(1, n_done):.4f} over {n_done} "
|
| 200 |
+
f"| cost=${spent:.2f} | {(time.time() - started) / 60:.1f}m",
|
| 201 |
+
flush=True,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
main()
|