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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
OOLONG-synth loader + official scorer.
|
| 3 |
+
|
| 4 |
+
The RLM blog's "132k / 263k token" OOLONG numbers correspond to `context_len`
|
| 5 |
+
131072 / 262144 in `oolongbench/oolong-synth`. The full repo is 12 GB; rows are
|
| 6 |
+
grouped by context_len within each shard, so a parquet predicate prunes whole
|
| 7 |
+
row groups and we download only the slice we need.
|
| 8 |
+
|
| 9 |
+
Scoring is ported verbatim from the official harness
|
| 10 |
+
(abertsch72/oolong: src/eval/eval_helpers.py) so numbers are comparable to the
|
| 11 |
+
leaderboard. Note it is NOT plain exact match: numeric answers get partial
|
| 12 |
+
credit 0.75**|gold-pred|.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import ast
|
| 18 |
+
import hashlib
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
import shutil
|
| 22 |
+
import tempfile
|
| 23 |
+
from datetime import datetime
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from urllib.request import urlopen
|
| 26 |
+
|
| 27 |
+
import pandas as pd
|
| 28 |
+
import pyarrow.parquet as pq
|
| 29 |
+
|
| 30 |
+
REPO = "oolongbench/oolong-synth"
|
| 31 |
+
CACHE = Path(__file__).resolve().parent.parent / "data"
|
| 32 |
+
PAPER_MIRROR_REPO = "lsteno/RLM-Evals"
|
| 33 |
+
PAPER_MIRROR_REVISION = "a6aea6d06da9f08d701038b64195049cf71e1997"
|
| 34 |
+
PAPER_PARQUET_SHA256 = (
|
| 35 |
+
"8cdd8ef5a01320d924271d7c9e0b1bb73b8198a53273f3f568e1e2c8750b8ee3"
|
| 36 |
+
)
|
| 37 |
+
PAPER_PARQUET_URL = (
|
| 38 |
+
"https://huggingface.co/datasets/lsteno/RLM-Evals/resolve/"
|
| 39 |
+
"refs%2Fconvert%2Fparquet/oolong_trec_coarse/eval/0000.parquet"
|
| 40 |
+
)
|
| 41 |
+
COLUMNS = [
|
| 42 |
+
"id",
|
| 43 |
+
"context_window_id",
|
| 44 |
+
"context_len",
|
| 45 |
+
"dataset",
|
| 46 |
+
"context_window_text",
|
| 47 |
+
"question",
|
| 48 |
+
"task_group",
|
| 49 |
+
"task",
|
| 50 |
+
"answer",
|
| 51 |
+
"answer_type",
|
| 52 |
+
"num_labels",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
# Baseline protocol from the official eval script: context in the system prompt,
|
| 56 |
+
# question as the user turn.
|
| 57 |
+
SYSTEM_PREFIX = "You are a helpful assistant."
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _sha256(path: Path) -> str:
|
| 61 |
+
with path.open("rb") as handle:
|
| 62 |
+
return hashlib.file_digest(handle, "sha256").hexdigest()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _paper_parquet() -> Path:
|
| 66 |
+
"""Fetch the 5.9 MB no-label mirror and enforce its audited content hash."""
|
| 67 |
+
cache = CACHE / "rlm_evals_oolong_trec_coarse.parquet"
|
| 68 |
+
if cache.exists():
|
| 69 |
+
digest = _sha256(cache)
|
| 70 |
+
if digest != PAPER_PARQUET_SHA256:
|
| 71 |
+
raise RuntimeError(
|
| 72 |
+
f"paper dataset cache hash mismatch at {cache}: {digest}; "
|
| 73 |
+
"move the file aside and retry"
|
| 74 |
+
)
|
| 75 |
+
return cache
|
| 76 |
+
|
| 77 |
+
CACHE.mkdir(exist_ok=True)
|
| 78 |
+
file_descriptor, temporary_name = tempfile.mkstemp(
|
| 79 |
+
prefix="oolong_trec_", suffix=".parquet.tmp", dir=CACHE
|
| 80 |
+
)
|
| 81 |
+
temporary = Path(temporary_name)
|
| 82 |
+
try:
|
| 83 |
+
with os.fdopen(file_descriptor, "wb") as destination:
|
| 84 |
+
with urlopen(PAPER_PARQUET_URL, timeout=300) as source:
|
| 85 |
+
shutil.copyfileobj(source, destination)
|
| 86 |
+
digest = _sha256(temporary)
|
| 87 |
+
if digest != PAPER_PARQUET_SHA256:
|
| 88 |
+
raise RuntimeError(
|
| 89 |
+
f"downloaded paper dataset hash mismatch: expected "
|
| 90 |
+
f"{PAPER_PARQUET_SHA256}, got {digest}"
|
| 91 |
+
)
|
| 92 |
+
os.replace(temporary, cache)
|
| 93 |
+
finally:
|
| 94 |
+
if temporary.exists():
|
| 95 |
+
temporary.unlink()
|
| 96 |
+
return cache
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def load_paper(context_len: int = 131_072) -> pd.DataFrame:
|
| 100 |
+
"""Load the audited no-label ``trec_coarse`` validation subset.
|
| 101 |
+
|
| 102 |
+
The mirror is a lossless filtered copy of ``oolongbench/oolong-synth``'s
|
| 103 |
+
validation split. Its compact Parquet representation avoids scanning the
|
| 104 |
+
original multi-gigabyte validation shards. The artifact hash and expected
|
| 105 |
+
row count are independently checked by this loader and ``run_paper.py``.
|
| 106 |
+
"""
|
| 107 |
+
table = pq.read_table(
|
| 108 |
+
_paper_parquet(),
|
| 109 |
+
filters=[("context_len", "==", context_len)],
|
| 110 |
+
)
|
| 111 |
+
df = table.to_pandas().rename(columns={"source_id": "id"})
|
| 112 |
+
return df.reset_index(drop=True)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def load(
|
| 116 |
+
context_len: int,
|
| 117 |
+
n: int | None = None,
|
| 118 |
+
seed: int = 0,
|
| 119 |
+
*,
|
| 120 |
+
split: str = "test",
|
| 121 |
+
dataset: str | None = None,
|
| 122 |
+
) -> pd.DataFrame:
|
| 123 |
+
"""Load an OOLONG slice without downloading the complete 12 GB dataset.
|
| 124 |
+
|
| 125 |
+
The original local experiment used the public ``test`` split across eight
|
| 126 |
+
source datasets. The RLM paper instead evaluates ``trec_coarse`` from the
|
| 127 |
+
``validation`` split, so both selectors are explicit and form part of the
|
| 128 |
+
cache identity.
|
| 129 |
+
"""
|
| 130 |
+
if split not in {"test", "validation"}:
|
| 131 |
+
raise ValueError(f"unsupported OOLONG split: {split!r}")
|
| 132 |
+
|
| 133 |
+
dataset_suffix = f"_{dataset}" if dataset else ""
|
| 134 |
+
split_suffix = "" if split == "test" and dataset is None else f"_{split}"
|
| 135 |
+
cache = CACHE / f"oolong_synth{split_suffix}{dataset_suffix}_{context_len}.parquet"
|
| 136 |
+
if not cache.exists():
|
| 137 |
+
from huggingface_hub import HfFileSystem
|
| 138 |
+
|
| 139 |
+
if "HF_TOKEN" not in os.environ:
|
| 140 |
+
tok = Path.home() / ".secrets" / "hf_token.txt"
|
| 141 |
+
if tok.exists():
|
| 142 |
+
os.environ["HF_TOKEN"] = tok.read_text().strip()
|
| 143 |
+
|
| 144 |
+
fs = HfFileSystem()
|
| 145 |
+
frames = []
|
| 146 |
+
filters = [("context_len", "==", context_len)]
|
| 147 |
+
if dataset is not None:
|
| 148 |
+
filters.append(("dataset", "==", dataset))
|
| 149 |
+
|
| 150 |
+
for f in sorted(fs.glob(f"datasets/{REPO}/data/{split}-*.parquet")):
|
| 151 |
+
with fs.open(f, "rb") as fh:
|
| 152 |
+
t = pq.read_table(
|
| 153 |
+
fh,
|
| 154 |
+
columns=COLUMNS,
|
| 155 |
+
filters=filters,
|
| 156 |
+
)
|
| 157 |
+
if t.num_rows:
|
| 158 |
+
frames.append(t.to_pandas())
|
| 159 |
+
print(f" {Path(f).name}: +{t.num_rows}", flush=True)
|
| 160 |
+
df = pd.concat(frames, ignore_index=True)
|
| 161 |
+
CACHE.mkdir(exist_ok=True)
|
| 162 |
+
df.to_parquet(cache)
|
| 163 |
+
|
| 164 |
+
df = pd.read_parquet(cache)
|
| 165 |
+
# Re-check predicates after reading. Besides guarding against malformed
|
| 166 |
+
# remote row-group metadata, this makes manually supplied caches safe.
|
| 167 |
+
df = df[df.context_len == context_len]
|
| 168 |
+
if dataset is not None:
|
| 169 |
+
df = df[df.dataset == dataset]
|
| 170 |
+
|
| 171 |
+
if n is None or n >= len(df):
|
| 172 |
+
return df.reset_index(drop=True)
|
| 173 |
+
|
| 174 |
+
if dataset is not None:
|
| 175 |
+
return df.sample(n=n, random_state=seed).reset_index(drop=True)
|
| 176 |
+
|
| 177 |
+
# Stratify by source dataset so one domain can't dominate a small sample.
|
| 178 |
+
per_ds = -(-n // df.dataset.nunique())
|
| 179 |
+
return (
|
| 180 |
+
df.groupby("dataset", group_keys=False)
|
| 181 |
+
.apply(lambda g: g.sample(min(len(g), per_ds), random_state=seed))
|
| 182 |
+
.sample(frac=1.0, random_state=seed)
|
| 183 |
+
.head(n)
|
| 184 |
+
.reset_index(drop=True)
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# --- official scorer (ported from abertsch72/oolong src/eval/eval_helpers.py) ---
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def attempt_answer_parse(answer: str) -> tuple[str, str]:
|
| 192 |
+
parse_confidence = "low"
|
| 193 |
+
if ":" not in answer: # bad start
|
| 194 |
+
if len(answer) < 20: # it's short, return the whole thing
|
| 195 |
+
return answer, parse_confidence
|
| 196 |
+
return answer.split()[-1], parse_confidence
|
| 197 |
+
|
| 198 |
+
candidate_answer = answer.split(":")[-1].strip()
|
| 199 |
+
candidate_answer = candidate_answer.replace("*", "") # OpenAI likes bolding
|
| 200 |
+
candidate_answer = candidate_answer.replace("[", "").replace(
|
| 201 |
+
"]", ""
|
| 202 |
+
) # Anthropic likes []
|
| 203 |
+
parse_confidence = "med"
|
| 204 |
+
if (
|
| 205 |
+
"User:" in answer
|
| 206 |
+
or "Answer:" in answer
|
| 207 |
+
or "Date:" in answer
|
| 208 |
+
or "Label" in answer
|
| 209 |
+
):
|
| 210 |
+
parse_confidence = "high"
|
| 211 |
+
if len(candidate_answer) < 20:
|
| 212 |
+
parse_confidence = "vhigh"
|
| 213 |
+
elif "more common" in candidate_answer:
|
| 214 |
+
candidate_answer = "more common"
|
| 215 |
+
elif "less common" in candidate_answer:
|
| 216 |
+
candidate_answer = "less common"
|
| 217 |
+
elif "same frequency" in candidate_answer:
|
| 218 |
+
candidate_answer = "same frequency"
|
| 219 |
+
|
| 220 |
+
return candidate_answer, parse_confidence
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def score_response(row, output: str) -> dict:
|
| 224 |
+
"""Official synth_process_response, minus the model-name bookkeeping."""
|
| 225 |
+
score = 0
|
| 226 |
+
gold = (
|
| 227 |
+
ast.literal_eval(row["answer"])[0]
|
| 228 |
+
if "datetime" not in row["answer"]
|
| 229 |
+
else datetime.strptime(row["answer"], "[datetime.date(%Y, %m, %d)]")
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
trimmed_output, parse_confidence = attempt_answer_parse(output)
|
| 233 |
+
if str(trimmed_output) == str(gold):
|
| 234 |
+
score = 1
|
| 235 |
+
elif str(trimmed_output) in ["more common", "less common", "same frequency"]:
|
| 236 |
+
if str(trimmed_output) in str(gold):
|
| 237 |
+
score = 1
|
| 238 |
+
elif row["answer_type"] == "ANSWER_TYPE.NUMERIC": # partial credit for numbers
|
| 239 |
+
try:
|
| 240 |
+
score = 0.75 ** (abs(int(gold) - int(trimmed_output)))
|
| 241 |
+
except Exception:
|
| 242 |
+
parse_confidence = "low"
|
| 243 |
+
elif row["answer_type"] == "ANSWER_TYPE.DATE":
|
| 244 |
+
try:
|
| 245 |
+
import dateutil.parser
|
| 246 |
+
|
| 247 |
+
score = float(dateutil.parser.parse(trimmed_output) == gold)
|
| 248 |
+
except Exception:
|
| 249 |
+
parse_confidence = "low"
|
| 250 |
+
|
| 251 |
+
return {
|
| 252 |
+
"score": float(score),
|
| 253 |
+
"attempted_parse": str(trimmed_output),
|
| 254 |
+
"parse_confidence": parse_confidence,
|
| 255 |
+
"gold": str(gold),
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# The RLM root model writes prose around FINAL(...); the official parser splits on
|
| 260 |
+
# the LAST colon in the whole response, which a stray colon anywhere would break.
|
| 261 |
+
# Keep only the final answer-bearing line before handing it to the parser.
|
| 262 |
+
_ANSWER_LINE = re.compile(
|
| 263 |
+
r"\b(label|answer|user|count|number|date|month|response)\s*[:=]", re.IGNORECASE
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def clean_final(text: str) -> str:
|
| 268 |
+
"""Reduce a verbose model answer to the line the official parser expects."""
|
| 269 |
+
if not text:
|
| 270 |
+
return ""
|
| 271 |
+
lines = [ln.strip().strip("#*- ") for ln in text.strip().splitlines() if ln.strip()]
|
| 272 |
+
for ln in reversed(lines):
|
| 273 |
+
if _ANSWER_LINE.search(ln):
|
| 274 |
+
return ln
|
| 275 |
+
return lines[-1] if lines else ""
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
|
| 280 |
+
def chk(out, answer, answer_type="ANSWER_TYPE.LABEL"):
|
| 281 |
+
return score_response(
|
| 282 |
+
{"answer": answer, "answer_type": answer_type}, clean_final(out)
|
| 283 |
+
)["score"]
|
| 284 |
+
|
| 285 |
+
assert chk("Label: correct", "['correct']") == 1
|
| 286 |
+
assert chk("Some reasoning here.\n\n**Label: incorrect**", "['incorrect']") == 1
|
| 287 |
+
assert chk("Label: correct", "['incorrect']") == 0
|
| 288 |
+
assert (
|
| 289 |
+
chk("Here is my analysis: blah.\nCount: 12", "['12']", "ANSWER_TYPE.NUMERIC")
|
| 290 |
+
== 1
|
| 291 |
+
)
|
| 292 |
+
assert abs(chk("Count: 13", "['12']", "ANSWER_TYPE.NUMERIC") - 0.75) < 1e-9
|
| 293 |
+
assert (
|
| 294 |
+
chk("The two are of the same frequency: same frequency", "['same frequency']")
|
| 295 |
+
== 1
|
| 296 |
+
)
|
| 297 |
+
assert chk("User: 81824", "['81824']") == 1
|
| 298 |
+
# A trailing prose sentence must not poison the parse of the answer line.
|
| 299 |
+
assert chk("Label: sports\n\nI computed this by counting.", "['sports']") == 1
|
| 300 |
+
print("scorer ok")
|