""" OOLONG-synth loader + official scorer. The RLM blog's "132k / 263k token" OOLONG numbers correspond to `context_len` 131072 / 262144 in `oolongbench/oolong-synth`. The full repo is 12 GB; rows are grouped by context_len within each shard, so a parquet predicate prunes whole row groups and we download only the slice we need. Scoring is ported verbatim from the official harness (abertsch72/oolong: src/eval/eval_helpers.py) so numbers are comparable to the leaderboard. Note it is NOT plain exact match: numeric answers get partial credit 0.75**|gold-pred|. """ from __future__ import annotations import ast import hashlib import os import re import shutil import tempfile from datetime import datetime from pathlib import Path from urllib.request import urlopen import pandas as pd import pyarrow.parquet as pq REPO = "oolongbench/oolong-synth" CACHE = Path(__file__).resolve().parent.parent / "data" PAPER_MIRROR_REPO = "lsteno/RLM-Evals" PAPER_MIRROR_REVISION = "a6aea6d06da9f08d701038b64195049cf71e1997" PAPER_PARQUET_SHA256 = ( "8cdd8ef5a01320d924271d7c9e0b1bb73b8198a53273f3f568e1e2c8750b8ee3" ) PAPER_PARQUET_URL = ( "https://huggingface.co/datasets/lsteno/RLM-Evals/resolve/" "refs%2Fconvert%2Fparquet/oolong_trec_coarse/eval/0000.parquet" ) COLUMNS = [ "id", "context_window_id", "context_len", "dataset", "context_window_text", "question", "task_group", "task", "answer", "answer_type", "num_labels", ] # Baseline protocol from the official eval script: context in the system prompt, # question as the user turn. SYSTEM_PREFIX = "You are a helpful assistant." def _sha256(path: Path) -> str: with path.open("rb") as handle: return hashlib.file_digest(handle, "sha256").hexdigest() def _paper_parquet() -> Path: """Fetch the 5.9 MB no-label mirror and enforce its audited content hash.""" cache = CACHE / "rlm_evals_oolong_trec_coarse.parquet" if cache.exists(): digest = _sha256(cache) if digest != PAPER_PARQUET_SHA256: raise RuntimeError( f"paper dataset cache hash mismatch at {cache}: {digest}; " "move the file aside and retry" ) return cache CACHE.mkdir(exist_ok=True) file_descriptor, temporary_name = tempfile.mkstemp( prefix="oolong_trec_", suffix=".parquet.tmp", dir=CACHE ) temporary = Path(temporary_name) try: with os.fdopen(file_descriptor, "wb") as destination: with urlopen(PAPER_PARQUET_URL, timeout=300) as source: shutil.copyfileobj(source, destination) digest = _sha256(temporary) if digest != PAPER_PARQUET_SHA256: raise RuntimeError( f"downloaded paper dataset hash mismatch: expected " f"{PAPER_PARQUET_SHA256}, got {digest}" ) os.replace(temporary, cache) finally: if temporary.exists(): temporary.unlink() return cache def load_paper(context_len: int = 131_072) -> pd.DataFrame: """Load the audited no-label ``trec_coarse`` validation subset. The mirror is a lossless filtered copy of ``oolongbench/oolong-synth``'s validation split. Its compact Parquet representation avoids scanning the original multi-gigabyte validation shards. The artifact hash and expected row count are independently checked by this loader and ``run_paper.py``. """ table = pq.read_table( _paper_parquet(), filters=[("context_len", "==", context_len)], ) df = table.to_pandas().rename(columns={"source_id": "id"}) return df.reset_index(drop=True) def load( context_len: int, n: int | None = None, seed: int = 0, *, split: str = "test", dataset: str | None = None, ) -> pd.DataFrame: """Load an OOLONG slice without downloading the complete 12 GB dataset. The original local experiment used the public ``test`` split across eight source datasets. The RLM paper instead evaluates ``trec_coarse`` from the ``validation`` split, so both selectors are explicit and form part of the cache identity. """ if split not in {"test", "validation"}: raise ValueError(f"unsupported OOLONG split: {split!r}") dataset_suffix = f"_{dataset}" if dataset else "" split_suffix = "" if split == "test" and dataset is None else f"_{split}" cache = CACHE / f"oolong_synth{split_suffix}{dataset_suffix}_{context_len}.parquet" if not cache.exists(): from huggingface_hub import HfFileSystem if "HF_TOKEN" not in os.environ: tok = Path.home() / ".secrets" / "hf_token.txt" if tok.exists(): os.environ["HF_TOKEN"] = tok.read_text().strip() fs = HfFileSystem() frames = [] filters = [("context_len", "==", context_len)] if dataset is not None: filters.append(("dataset", "==", dataset)) for f in sorted(fs.glob(f"datasets/{REPO}/data/{split}-*.parquet")): with fs.open(f, "rb") as fh: t = pq.read_table( fh, columns=COLUMNS, filters=filters, ) if t.num_rows: frames.append(t.to_pandas()) print(f" {Path(f).name}: +{t.num_rows}", flush=True) df = pd.concat(frames, ignore_index=True) CACHE.mkdir(exist_ok=True) df.to_parquet(cache) df = pd.read_parquet(cache) # Re-check predicates after reading. Besides guarding against malformed # remote row-group metadata, this makes manually supplied caches safe. df = df[df.context_len == context_len] if dataset is not None: df = df[df.dataset == dataset] if n is None or n >= len(df): return df.reset_index(drop=True) if dataset is not None: return df.sample(n=n, random_state=seed).reset_index(drop=True) # Stratify by source dataset so one domain can't dominate a small sample. per_ds = -(-n // df.dataset.nunique()) return ( df.groupby("dataset", group_keys=False) .apply(lambda g: g.sample(min(len(g), per_ds), random_state=seed)) .sample(frac=1.0, random_state=seed) .head(n) .reset_index(drop=True) ) # --- official scorer (ported from abertsch72/oolong src/eval/eval_helpers.py) --- def attempt_answer_parse(answer: str) -> tuple[str, str]: parse_confidence = "low" if ":" not in answer: # bad start if len(answer) < 20: # it's short, return the whole thing return answer, parse_confidence return answer.split()[-1], parse_confidence candidate_answer = answer.split(":")[-1].strip() candidate_answer = candidate_answer.replace("*", "") # OpenAI likes bolding candidate_answer = candidate_answer.replace("[", "").replace( "]", "" ) # Anthropic likes [] parse_confidence = "med" if ( "User:" in answer or "Answer:" in answer or "Date:" in answer or "Label" in answer ): parse_confidence = "high" if len(candidate_answer) < 20: parse_confidence = "vhigh" elif "more common" in candidate_answer: candidate_answer = "more common" elif "less common" in candidate_answer: candidate_answer = "less common" elif "same frequency" in candidate_answer: candidate_answer = "same frequency" return candidate_answer, parse_confidence def score_response(row, output: str) -> dict: """Official synth_process_response, minus the model-name bookkeeping.""" score = 0 gold = ( ast.literal_eval(row["answer"])[0] if "datetime" not in row["answer"] else datetime.strptime(row["answer"], "[datetime.date(%Y, %m, %d)]") ) trimmed_output, parse_confidence = attempt_answer_parse(output) if str(trimmed_output) == str(gold): score = 1 elif str(trimmed_output) in ["more common", "less common", "same frequency"]: if str(trimmed_output) in str(gold): score = 1 elif row["answer_type"] == "ANSWER_TYPE.NUMERIC": # partial credit for numbers try: score = 0.75 ** (abs(int(gold) - int(trimmed_output))) except Exception: parse_confidence = "low" elif row["answer_type"] == "ANSWER_TYPE.DATE": try: import dateutil.parser score = float(dateutil.parser.parse(trimmed_output) == gold) except Exception: parse_confidence = "low" return { "score": float(score), "attempted_parse": str(trimmed_output), "parse_confidence": parse_confidence, "gold": str(gold), } # The RLM root model writes prose around FINAL(...); the official parser splits on # the LAST colon in the whole response, which a stray colon anywhere would break. # Keep only the final answer-bearing line before handing it to the parser. _ANSWER_LINE = re.compile( r"\b(label|answer|user|count|number|date|month|response)\s*[:=]", re.IGNORECASE ) def clean_final(text: str) -> str: """Reduce a verbose model answer to the line the official parser expects.""" if not text: return "" lines = [ln.strip().strip("#*- ") for ln in text.strip().splitlines() if ln.strip()] for ln in reversed(lines): if _ANSWER_LINE.search(ln): return ln return lines[-1] if lines else "" if __name__ == "__main__": def chk(out, answer, answer_type="ANSWER_TYPE.LABEL"): return score_response( {"answer": answer, "answer_type": answer_type}, clean_final(out) )["score"] assert chk("Label: correct", "['correct']") == 1 assert chk("Some reasoning here.\n\n**Label: incorrect**", "['incorrect']") == 1 assert chk("Label: correct", "['incorrect']") == 0 assert ( chk("Here is my analysis: blah.\nCount: 12", "['12']", "ANSWER_TYPE.NUMERIC") == 1 ) assert abs(chk("Count: 13", "['12']", "ANSWER_TYPE.NUMERIC") - 0.75) < 1e-9 assert ( chk("The two are of the same frequency: same frequency", "['same frequency']") == 1 ) assert chk("User: 81824", "['81824']") == 1 # A trailing prose sentence must not poison the parse of the answer line. assert chk("Label: sports\n\nI computed this by counting.", "['sports']") == 1 print("scorer ok")