File size: 8,243 Bytes
bf2a341
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/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()