Datasets:
Download run.py from Rickesh/rlm-oolong-reproduction: direct link, hf CLI and curl.
- Browser
- Download file 8.24 kB
-
https://huggingface.co/datasets/Rickesh/rlm-oolong-reproduction/resolve/b02fc870a7f9f7760c02207a1090dc71c9debbfe/run.py
- Command line
-
hf download hf://datasets/Rickesh/rlm-oolong-reproduction@b02fc870a7f9f7760c02207a1090dc71c9debbfe/run.py
-
curl -L -o run.py https://huggingface.co/datasets/Rickesh/rlm-oolong-reproduction/resolve/b02fc870a7f9f7760c02207a1090dc71c9debbfe/run.py
8.24 kB
| #!/usr/bin/env python3 | |
| """ | |
| OOLONG-synth runner: cheap model wrapped in an RLM vs. an expensive model read | |
| straight through. | |
| # cheap model, recursive | |
| python run.py --mode rlm --model haiku --context-len 131072 -n 32 | |
| # expensive baselines | |
| python run.py --mode baseline --model sonnet --context-len 131072 -n 32 | |
| python run.py --mode baseline --model 'opus[1m]' --context-len 262144 -n 32 | |
| Results append to results/<tag>.jsonl and are resumable: rerunning skips ids | |
| already recorded, provided the run identity (mode/model/context_len) matches. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import traceback | |
| from concurrent.futures import ProcessPoolExecutor, as_completed | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent / "bench")) | |
| import oolong # noqa: E402 | |
| from rlm_haiku.rlm_repl import RLM_REPL # noqa: E402 | |
| from rlm_haiku.utils.llm import ClaudeCodeClient, QuotaExhausted, Usage # noqa: E402 | |
| RESULTS = Path(__file__).resolve().parent / "results" | |
| MODELS = { | |
| "haiku": "claude-haiku-4-5-20251001", | |
| "sonnet": "claude-sonnet-4-6", | |
| "sonnet[1m]": "claude-sonnet-4-6[1m]", | |
| "opus": "claude-opus-4-8", | |
| "opus[1m]": "claude-opus-4-8[1m]", | |
| } | |
| def run_baseline(row: dict, model: str, sub_model: str, max_iters: int, require_repl: bool = False) -> tuple[str, dict]: | |
| """Official OOLONG protocol: context + question in one shot, no tools.""" | |
| usage = Usage() | |
| client = ClaudeCodeClient(model=model, usage=usage) | |
| answer = client.completion([ | |
| {"role": "system", "content": oolong.SYSTEM_PREFIX}, | |
| {"role": "user", "content": row["context_window_text"] + "\n" + row["question"]}, | |
| ]) | |
| return answer, usage.as_dict() | |
| def run_rlm(row: dict, model: str, sub_model: str, max_iters: int, terse: bool = False, | |
| require_repl: bool = False) -> tuple[str, dict]: | |
| usage = Usage() | |
| rlm = RLM_REPL( | |
| model=model, | |
| recursive_model=sub_model, | |
| max_iterations=max_iters, | |
| usage=usage, | |
| terse=terse, | |
| require_repl=require_repl, | |
| ) | |
| answer = rlm.completion(context=row["context_window_text"], query=row["question"]) | |
| return answer, usage.as_dict() | |
| def run_rlm_terse(row: dict, model: str, sub_model: str, max_iters: int, require_repl: bool = False) -> tuple[str, dict]: | |
| return run_rlm(row, model, sub_model, max_iters, terse=True, require_repl=require_repl) | |
| RUNNERS = {"baseline": run_baseline, "rlm": run_rlm, "rlm-terse": run_rlm_terse} | |
| def work(args) -> dict: | |
| """One example, in its own process (the REPL redirects the global stdout).""" | |
| row, mode, model, sub_model, max_iters, require_repl = args | |
| started = time.time() | |
| try: | |
| answer, usage = RUNNERS[mode](row, model, sub_model, max_iters, require_repl) | |
| error, quota = None, False | |
| except QuotaExhausted as e: | |
| answer, usage, error, quota = "", {}, f"QuotaExhausted: {e}", True | |
| except Exception: | |
| answer, usage, error, quota = "", {}, traceback.format_exc(limit=4), False | |
| scored = oolong.score_response(row, oolong.clean_final(answer)) if answer else { | |
| "score": 0.0, "attempted_parse": "ERROR", "parse_confidence": "ERROR", | |
| "gold": row["answer"], | |
| } | |
| return { | |
| "id": int(row["id"]), | |
| "dataset": row["dataset"], | |
| "task": row["task"], | |
| "answer_type": row["answer_type"], | |
| "question": row["question"], | |
| **scored, | |
| "full_answer": answer, | |
| "error": error, | |
| "quota": quota, | |
| "usage": usage, | |
| "seconds": round(time.time() - started, 1), | |
| } | |
| def main() -> None: | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--mode", choices=RUNNERS, required=True) | |
| p.add_argument("--model", default="haiku", help="root model (alias or full id)") | |
| p.add_argument("--sub-model", default=None, help="recursive model; defaults to --model") | |
| p.add_argument("--context-len", type=int, default=131072) | |
| p.add_argument("-n", type=int, default=32, help="examples (stratified across the 8 sources)") | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--workers", type=int, default=4, help="examples in flight") | |
| p.add_argument("--max-iters", type=int, default=12, help="root LM turns per RLM query") | |
| p.add_argument("--require-repl", action="store_true", help="reject final answers before any REPL execution") | |
| p.add_argument("--tag", default=None) | |
| args = p.parse_args() | |
| model = MODELS.get(args.model, args.model) | |
| sub_model = MODELS.get(args.sub_model or args.model, args.sub_model or args.model) | |
| tag = args.tag or f"{args.mode}_{args.model.replace('[1m]', '1m')}_{args.context_len}" | |
| df = oolong.load(args.context_len, n=args.n, seed=args.seed) | |
| rows = df.to_dict("records") | |
| RESULTS.mkdir(exist_ok=True) | |
| out = RESULTS / f"{tag}.jsonl" | |
| meta = {"mode": args.mode, "model": model, "sub_model": sub_model, | |
| "context_len": args.context_len, "seed": args.seed, | |
| "require_repl": args.require_repl} | |
| meta_path = RESULTS / f"{tag}.meta.json" | |
| # Resume only if this is genuinely the same run; mixing configs fabricates a | |
| # number no single run ever produced. | |
| done, total_score, spent = {}, 0.0, 0.0 | |
| if out.exists() and meta_path.exists() and json.loads(meta_path.read_text()) == meta: | |
| for line in out.read_text().splitlines(): | |
| if line.strip(): | |
| r = json.loads(line) | |
| done[r["id"]] = r | |
| total_score += r["score"] | |
| spent += r.get("usage", {}).get("cost_usd", 0.0) | |
| elif out.exists(): | |
| sys.exit(f"{out} exists with different settings; delete it or pass --tag") | |
| meta_path.write_text(json.dumps(meta, indent=2)) | |
| todo = [r for r in rows if int(r["id"]) not in done] | |
| n_total = len(rows) | |
| print(f"[{tag}] {model} | {len(todo)} to run, {len(done)} cached, {n_total} total", flush=True) | |
| if not todo: | |
| print(f"[{tag}] already complete", flush=True) | |
| errors, started, n_done, quota_hit = 0, time.time(), len(done), False | |
| payloads = [(r, args.mode, model, sub_model, args.max_iters, args.require_repl) for r in todo] | |
| with ProcessPoolExecutor(max_workers=args.workers) as pool, out.open("a") as fh: | |
| futures = [pool.submit(work, pl) for pl in payloads] | |
| for fut in as_completed(futures): | |
| res = fut.result() | |
| if res["quota"]: | |
| # Quota is not a wrong answer. Bank nothing, stop everything, and | |
| # let the operator resume once the window resets. | |
| quota_hit = True | |
| for f in futures: | |
| f.cancel() | |
| break | |
| if res["error"]: | |
| # Leave failed rows out of the journal so a resume retries them | |
| # instead of banking a zero that no model actually produced. | |
| errors += 1 | |
| print(f"[{tag}] ERROR (not journalled): {res['error'].splitlines()[-1][:160]}", flush=True) | |
| continue | |
| fh.write(json.dumps(res) + "\n") | |
| fh.flush() | |
| os.fsync(fh.fileno()) | |
| n_done += 1 | |
| total_score += res["score"] | |
| spent += res.get("usage", {}).get("cost_usd", 0.0) | |
| rate = (time.time() - started) / max(1, n_done - len(done)) | |
| eta = rate * (n_total - n_done) / 60 | |
| print( | |
| f"[{tag}] errors={errors} {n_done}/{n_total} " | |
| f"score={total_score / n_done:.3f} ${spent:.2f} eta={eta:.1f}m", | |
| flush=True, | |
| ) | |
| if quota_hit: | |
| print(f"[{tag}] ABORTED: subscription quota exhausted. " | |
| f"{n_done}/{n_total} banked; rerun the same command after the reset " | |
| f"to resume.", flush=True) | |
| if errors: | |
| print(f"[{tag}] WARNING: {errors} example(s) failed and were NOT scored", flush=True) | |
| print( | |
| f"[{tag}] FINAL score={total_score / max(1, n_done):.4f} over {n_done} " | |
| f"| cost=${spent:.2f} | {(time.time() - started) / 60:.1f}m", | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |