Datasets:
Long-context agent benchmark: facts, tool calls and rules far back in the context (items, score.py, card)
7fa7e5a verified Download score.py from thinletter/longctx-agent-bench: direct link, hf CLI and curl.
- Browser
- Download file 29.5 kB
-
https://huggingface.co/datasets/thinletter/longctx-agent-bench/resolve/main/score.py
- Command line
-
hf download hf://datasets/thinletter/longctx-agent-bench/score.py
-
curl -L -o score.py https://huggingface.co/datasets/thinletter/longctx-agent-bench/resolve/main/score.py
29.5 kB
| #!/usr/bin/env python | |
| """Scorer for the long-context agent benchmark: does a model still use information that lies far back in a long | |
| conversation? Five sets (facts, tool_calls, rules_en, rules_cs, rules_de), each at 8k and 32k tokens. | |
| python score.py --model Qwen/Qwen3.5-2B --data ./longctx-agent-bench --out result.json | |
| python score.py --model my/model --data ./longctx-agent-bench --reference Qwen/Qwen3.5-2B --out result.json | |
| python score.py --model my/model --data ./longctx-agent-bench --reference_scores ref_scores.json.gz \ | |
| --save_scores my_scores.json.gz --out result.json [--sets facts,rules_en] [--lengths 8k] [--limit 2] | |
| Everything is teacher-forced: one forward pass over each item's text, the model's next-token distribution read at | |
| the target positions, nothing generated. Needs torch and transformers (pyarrow only for .parquet files). | |
| Metrics (per set and length): | |
| facts query_acc: a query counts as recalled iff every token of its answer (the number and the final ".") is | |
| the model's top-1 prediction; token_acc over the answer tokens. | |
| tool_calls acc_far: next-token top-1 accuracy at the target tokens (a tool's name, its parameter names, the token | |
| that closes them, the next parameter / closing tag, a documented command's name) whose definition lies | |
| far back in the context; acc_fresh: the far targets without an earlier call of the same tool in the | |
| last 512 tokens (the model cannot copy a recent call); acc_near: the rest. | |
| rules_<lg> each item holds one context twice, without and with a planted policy rule; at every target (a later | |
| action the rule governs) score = log p(the rule-implied first token); effect = score(with rule) - | |
| score(without rule). The REFERENCE model (default: the scored model itself) defines which targets | |
| qualify: |effect_ref| >= 1.0 nat. Over the qualifying targets: retained = sum effect / sum effect_ref, | |
| follow = share of targets with effect / effect_ref >= 0.5, per placement (rule in the system prompt / | |
| in a later user message) and family (substitution / redirect / required) and over all families. | |
| Headline rows (result["rows"]): | |
| "Facts recalled at 8k / 32k tokens" facts query_acc | |
| "Distant tool calls at 8k / 32k tokens" tool_calls acc_far | |
| "Rules followed at 8k / 32k tokens" rules_en follow, rule in the system prompt, all families | |
| "Rules kept far back, worst case (1.00 = as the original)" rules_en: the lowest retained of the 12 cells | |
| (3 families x 2 placements x 2 lengths) | |
| "Czech rules kept far back, worst case" rules_cs, the same | |
| "German rules kept far back, worst case" rules_de, the same | |
| "Rules in Czech / German followed at 32k tokens" rules_cs / rules_de follow at 32k (system prompt, all) | |
| Tokenization: every item stores the text and, for the Qwen3.5 tokenizer, its token ids. --mode ids feeds those ids | |
| (models with the same vocabulary: the exact evaluated sequences); --mode text tokenizes the text with the model's own | |
| tokenizer and maps the targets by character offsets (any tokenizer; a target whose characters do not start at a | |
| token boundary of that tokenizer is skipped and counted under "unaligned"); --mode auto (default): ids when the | |
| tokenizer's vocabulary matches the dataset's tokenizer_fingerprint, else text. | |
| Backends (--backend): "hf" (default) any transformers causal LM; "thinctx" a ThinCtx model through the thinctx | |
| runtime's public scoring call Engine.score (thinctx 1.1, upcoming; thinctx 1.0.x cannot score ThinCtx models | |
| teacher-forced, and the backend then stops with that message). Other models / runtimes: score_sets(backend, tokenizer, ...) with any object | |
| that has read(ids, positions, tokens) -> (top-1 id per position, log p of the given token ids per position), or | |
| hidden(ids) -> [n, D] (the final hidden states of the token ids) and logits(h) -> [m, V] (HFBackend). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gzip | |
| import hashlib | |
| import json | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| SETS = ("facts", "tool_calls", "rules_en", "rules_cs", "rules_de") | |
| SPLITS = ("8k", "32k") | |
| FAMILIES = ("substitution", "redirect", "required") | |
| PLACEMENTS = ("system", "user") | |
| KINDS = ("name", "param", "next", "command") | |
| MIN_EFFECT = 1.0 # nats: a rules target qualifies iff the reference reacts at least this much | |
| FOLLOW = 0.5 # follow: effect >= FOLLOW x the reference's effect | |
| CHUNK = 256 # positions per [positions, vocab] logits block (memory only) | |
| ROWS = { | |
| "Facts recalled at 8k / 32k tokens": ("facts", "query_acc"), | |
| "Distant tool calls at 8k / 32k tokens": ("tool_calls", "acc_far"), | |
| "Rules followed at 8k / 32k tokens": ("rules_en", "follow"), | |
| "Rules kept far back, worst case (1.00 = as the original)": ("rules_en", "worst"), | |
| "Czech rules kept far back, worst case": ("rules_cs", "worst"), | |
| "German rules kept far back, worst case": ("rules_de", "worst"), | |
| "Rules in Czech / German followed at 32k tokens": ("rules_csde", "follow"), | |
| } | |
| # ---------------------------------------------------------------- data | |
| def resolve_data(data: str) -> Path: | |
| """A local dataset folder, or a Hugging Face dataset repo id (downloaded with huggingface_hub).""" | |
| p = Path(data) | |
| if p.is_dir(): | |
| return p | |
| from huggingface_hub import snapshot_download | |
| return Path(snapshot_download(repo_id=data, repo_type="dataset")) | |
| def load_items(root: Path, name: str, split: str) -> list: | |
| """The items of one set and length: <root>[/data]/<set>/<split>.jsonl[.gz] or .parquet.""" | |
| for base in (root / "data" / name, root / name): | |
| for ext in (".jsonl.gz", ".jsonl", ".parquet"): | |
| f = base / f"{split}{ext}" | |
| if not f.is_file(): | |
| continue | |
| if ext == ".parquet": | |
| import pyarrow.parquet as pq | |
| return pq.read_table(f).to_pylist() | |
| op = gzip.open if ext == ".jsonl.gz" else open | |
| with op(f, "rt", encoding="utf-8") as fh: | |
| return [json.loads(line) for line in fh if line.strip()] | |
| raise FileNotFoundError(f"no {name}/{split}.jsonl[.gz] / .parquet under {root}") | |
| def load_meta(root: Path) -> dict: | |
| for f in (root / "meta.json", root / "data" / "meta.json"): | |
| if f.is_file(): | |
| return json.loads(f.read_text(encoding="utf-8")) | |
| return {} | |
| def fingerprint(tok) -> str: | |
| """sha256 of the vocabulary (token string <TAB> id per line, by id): the dataset's tokenizer_fingerprint.""" | |
| v = sorted(tok.get_vocab().items(), key=lambda kv: kv[1]) | |
| return hashlib.sha256("\n".join(f"{t}\t{i}" for t, i in v).encode("utf-8")).hexdigest() | |
| # ---------------------------------------------------------------- model backends | |
| class HFBackend: | |
| """A transformers causal LM: hidden(ids) = the decoder's final hidden states (one forward, no cache), | |
| logits(h) = the output head as the model's own forward applies it.""" | |
| def __init__(self, model): | |
| self.model = model.eval() | |
| self.dev = next(model.parameters()).device | |
| self.dec = model.get_decoder() if hasattr(model, "get_decoder") else None | |
| self.head = model.get_output_embeddings() | |
| cfg = model.config | |
| cfg = getattr(cfg, "text_config", None) or cfg | |
| self.scale = float(getattr(cfg, "logits_scaling", 1.0) or 1.0) # Granite: logits / logits_scaling | |
| self.mult = float(getattr(cfg, "logit_scale", 1.0) or 1.0) # Cohere: logits * logit_scale | |
| self.cap = getattr(cfg, "final_logit_softcapping", None) # Gemma 2 / 3 | |
| def hidden(self, ids: list) -> torch.Tensor: | |
| x = torch.tensor([ids], dtype=torch.long, device=self.dev) | |
| if self.dec is not None: | |
| return self.dec(input_ids=x, use_cache=False).last_hidden_state[0] | |
| out = self.model(input_ids=x, use_cache=False, output_hidden_states=True) | |
| return out.hidden_states[-1][0] | |
| def logits(self, h: torch.Tensor) -> torch.Tensor: | |
| z = self.head(h) | |
| if self.mult != 1.0: | |
| z = z * self.mult | |
| if self.scale != 1.0: | |
| z = z / self.scale | |
| if self.cap: | |
| z = torch.tanh(z / self.cap) * self.cap | |
| return z | |
| class ThinCtxBackend: | |
| """A ThinCtx model through the thinctx runtime, public API only: thinctx.load(name) and | |
| Engine.score(ids, positions, tokens) -> {"argmax": [int per position], "logprobs": [[float per requested token] | |
| per position]} (the next-token distribution after ids[:p + 1], the sequence processed as the runtime processes a | |
| prompt). Engine.score comes with thinctx 1.1; thinctx 1.0.x does not have it.""" | |
| def __init__(self, name: str): | |
| import thinctx | |
| self.eng = thinctx.load(name) | |
| if not callable(getattr(self.eng, "score", None)): | |
| raise SystemExit(f"thinctx {getattr(thinctx, '__version__', '?')} has no Engine.score (teacher-forced " | |
| "log-probabilities at given positions): scoring a ThinCtx model needs thinctx >= 1.1") | |
| def read(self, ids: list, positions: list, tokens: list) -> tuple[list, list]: | |
| r = self.eng.score(list(ids), list(positions), [list(t) for t in tokens]) | |
| return [int(v) for v in r["argmax"]], [[float(v) for v in row] for row in r["logprobs"]] | |
| def load_hf(name: str, dtype: str = "bfloat16", device: str = "auto", attn: str | None = "sdpa"): | |
| """(HFBackend, tokenizer) of a hub id or local folder (attn: the attention implementation, None: the model's | |
| default).""" | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| dev = ("cuda" if torch.cuda.is_available() else "cpu") if device == "auto" else device | |
| tok = AutoTokenizer.from_pretrained(name) | |
| kw = {"dtype": getattr(torch, dtype)} | ({"attn_implementation": attn} if attn else {}) | |
| model = AutoModelForCausalLM.from_pretrained(name, **kw).to(dev) | |
| return HFBackend(model), tok | |
| # ---------------------------------------------------------------- tokenization | |
| class TextTok: | |
| """The model tokenizer's view of a text: ids (with the tokenizer's BOS when it adds one), char spans.""" | |
| def __init__(self, tok, text: str): | |
| enc = tok(text, add_special_tokens=False, return_offsets_mapping=True) | |
| ids, off = list(enc["input_ids"]), [tuple(o) for o in enc["offset_mapping"]] | |
| bos = getattr(tok, "bos_token_id", None) | |
| if bos is not None and tok("a", add_special_tokens=True)["input_ids"][:1] == [bos]: | |
| ids, off = [bos] + ids, [(0, 0)] + off | |
| self.tok, self.text, self.ids = tok, text, ids | |
| self.s = np.array([o[0] for o in off], dtype=np.int64) | |
| self.e = np.array([o[1] for o in off], dtype=np.int64) | |
| def overlapping(self, c0: int, c1: int) -> list: | |
| """Indices of the (non-empty) tokens overlapping characters [c0, c1).""" | |
| return np.flatnonzero((self.s < c1) & (self.e > c0) & (self.e > self.s)).tolist() | |
| def starting(self, c: int) -> int | None: | |
| """The index of the token starting at character c, None without a token boundary there.""" | |
| j = np.flatnonzero((self.s == c) & (self.e > self.s)) | |
| if not len(j): | |
| return None | |
| j = int(j[0]) | |
| return j if j == 0 or self.e[:j].max(initial=0) <= c else None | |
| def first_token(self, c: int, cont: str, ctx: int = 48) -> int | None: | |
| """The model's first token of the continuation `cont` written at character c (re-tokenized with up to ctx | |
| preceding characters, which must keep their own tokenization).""" | |
| pre = self.text[max(0, c - ctx):c] | |
| a = self.tok(pre, add_special_tokens=False)["input_ids"] | |
| b = self.tok(pre + cont, add_special_tokens=False)["input_ids"] | |
| return int(b[len(a)]) if len(b) > len(a) and list(b[:len(a)]) == list(a) else None | |
| # ---------------------------------------------------------------- requests: positions to read per sequence | |
| class Reads: | |
| """Every sequence to run once (keyed by its ids), with the positions to read: argmax and log p of given ids.""" | |
| def __init__(self): | |
| self.seqs = {} # key -> {"ids": int64 array, "pos": {p: set(token ids for log p)}} | |
| self.out = {} # (key, p) -> (argmax, {token: log p}) | |
| def seq(self, ids) -> str: | |
| arr = np.asarray(ids, dtype=np.int64) | |
| key = hashlib.sha1(arr.tobytes()).hexdigest() | |
| self.seqs.setdefault(key, {"ids": arr, "pos": {}}) | |
| return key | |
| def read(self, key: str, p: int, want=()) -> tuple: | |
| s = self.seqs[key] | |
| if not 0 <= int(p) < len(s["ids"]): | |
| raise IndexError(f"position {p} outside a sequence of {len(s['ids'])} tokens") | |
| s["pos"].setdefault(int(p), set()).update(int(t) for t in want) | |
| return key, int(p) | |
| def run(self, backend, log=None): | |
| n = len(self.seqs) | |
| t0 = time.time() | |
| for i, (key, s) in enumerate(sorted(self.seqs.items(), key=lambda kv: len(kv[1]["ids"]))): | |
| ps = sorted(s["pos"]) | |
| if hasattr(backend, "read"): # a runtime that reads the positions itself | |
| need = [sorted(s["pos"][p]) for p in ps] | |
| am, lps = backend.read(s["ids"].tolist(), ps, need) | |
| for p, a_, ts, lp in zip(ps, am, need, lps): | |
| self.out[(key, p)] = (int(a_), dict(zip(ts, (float(v) for v in lp)))) | |
| if log is not None and ((i + 1) % 20 == 0 or i + 1 == n): | |
| log(f" {i + 1} / {n} sequences ({time.time() - t0:.0f} s)") | |
| continue | |
| h = backend.hidden(s["ids"].tolist()) | |
| for c0 in range(0, len(ps), CHUNK): | |
| pc = ps[c0:c0 + CHUNK] | |
| z = backend.logits(h[torch.tensor(pc, device=h.device)]).float() | |
| am = z.argmax(-1).tolist() | |
| need = [sorted(s["pos"][p]) for p in pc] | |
| lp = z.log_softmax(-1) if any(need) else None | |
| for k, p in enumerate(pc): | |
| self.out[(key, p)] = (int(am[k]), {t: float(lp[k, t]) for t in need[k]}) | |
| del h | |
| if log is not None and ((i + 1) % 20 == 0 or i + 1 == n): | |
| log(f" {i + 1} / {n} sequences ({time.time() - t0:.0f} s)") | |
| # ---------------------------------------------------------------- per-set requests and results | |
| def _plan_facts(items, mode, tok, R: Reads): | |
| plan = [] | |
| for it in items: | |
| qs = [] | |
| if mode == "ids": | |
| k = R.seq(it["qwen_ids"][:-1]) | |
| for q in it["targets"]: | |
| qs.append([R.read(k, p) + (int(t),) for p, t in zip(q["qwen_pos"], q["qwen_answer_ids"])]) | |
| else: | |
| tt = TextTok(tok, it["text"]) | |
| k = R.seq(tt.ids) | |
| for q in it["targets"]: | |
| js = [j for j in tt.overlapping(*q["answer_char"]) if j >= 1] | |
| qs.append([R.read(k, j - 1) + (tt.ids[j],) for j in js] or None) | |
| plan.append((it["id"], qs)) | |
| return plan | |
| def _plan_tools(items, mode, tok, R: Reads): | |
| plan = [] | |
| for it in items: | |
| tt = None if mode == "ids" else TextTok(tok, it["text"]) | |
| k = R.seq(it["qwen_ids"][:-1] if mode == "ids" else tt.ids) | |
| ts = [] | |
| for t in it["targets"]: | |
| if mode == "ids": | |
| y = int(t["qwen_target_id"]) | |
| rd = [R.read(k, t["qwen_pos"], [y]) + (y,)] | |
| else: | |
| js = [j for j in tt.overlapping(*t["char"]) if j >= 1] | |
| rd = [R.read(k, j - 1, [tt.ids[j]]) + (tt.ids[j],) for j in js] or None | |
| ts.append((t, rd)) | |
| plan.append((it["id"], ts)) | |
| return plan | |
| def _rule_read(R, mode, k, tt, t, which: str): | |
| """The read of a rules target in one of the item's two texts (k: its sequence; tt: its TextTok in text mode).""" | |
| if mode == "ids": | |
| y = int(t["expected_qwen_id"]) | |
| return R.read(k, t[f"qwen_pos_{which}"], [y]) + (y,) | |
| c = int(t[f"char_{which}"]) | |
| exp, orig = t["expected_text"], t["original_text"] | |
| ws = min(len(orig) - len(orig.lstrip()), len(exp) - len(exp.lstrip())) | |
| for d in range(ws, -1, -1): # the latest token boundary within the shared leading whitespace | |
| j = tt.starting(c + d) | |
| if j is None or j < 1: | |
| continue | |
| y = tt.first_token(c + d, exp[d:]) | |
| return None if y is None else R.read(k, j - 1, [y]) + (y,) | |
| return None | |
| def _plan_rules(items, mode, tok, R: Reads): | |
| plan = [] | |
| for it in items: | |
| if mode == "ids": | |
| a = b = None | |
| ka, kb = R.seq(it["qwen_ids_without_rule"][:-1]), R.seq(it["qwen_ids_with_rule"][:-1]) | |
| else: | |
| a, b = TextTok(tok, it["text_without_rule"]), TextTok(tok, it["text_with_rule"]) | |
| ka, kb = R.seq(a.ids), R.seq(b.ids) | |
| ts = [(t, _rule_read(R, mode, ka, a, t, "without_rule"), _rule_read(R, mode, kb, b, t, "with_rule")) | |
| for t in it["targets"]] | |
| plan.append((it, ts)) | |
| return plan | |
| def _val(R, rd): | |
| key, p, y = rd | |
| am, lp = R.out[(key, p)] | |
| return am == y, lp.get(y) | |
| def _facts_scores(plan, R) -> dict: | |
| out = {} | |
| for iid, qs in plan: | |
| out[iid] = [None if q is None else [bool(_val(R, rd)[0]) for rd in q] for q in qs] | |
| return out | |
| def _tools_scores(plan, R) -> dict: | |
| out = {} | |
| for iid, ts in plan: | |
| row = [] | |
| for t, rd in ts: | |
| if rd is None: | |
| row.append(None) | |
| continue | |
| v = [_val(R, x) for x in rd] | |
| row.append([bool(all(ok for ok, _ in v)), float(sum(lp for _, lp in v))]) | |
| out[iid] = row | |
| return out | |
| def _rules_scores(plan, R) -> dict: | |
| out = {} | |
| for it, ts in plan: | |
| out[it["id"]] = [None if a is None or b is None else [_val(R, a)[1], _val(R, b)[1]] for _, a, b in ts] | |
| return out | |
| def facts_metrics(items, sc) -> dict: | |
| q_ok = q_n = t_ok = t_n = skipped = 0 | |
| for it in items: | |
| for q in sc[it["id"]]: | |
| if q is None: | |
| skipped += 1 | |
| continue | |
| q_ok, q_n = q_ok + int(all(q)), q_n + 1 | |
| t_ok, t_n = t_ok + sum(q), t_n + len(q) | |
| return {"query_acc": q_ok / max(1, q_n), "token_acc": t_ok / max(1, t_n), "n_queries": q_n, | |
| "unaligned": skipped} | |
| def tools_metrics(items, sc) -> dict: | |
| acc, skipped = {}, 0 | |
| for it in items: | |
| for t, v in zip(it["targets"], sc[it["id"]]): | |
| if v is None: | |
| skipped += 1 | |
| continue | |
| groups = ["far" if t["far"] else "near"] + (["fresh"] if t["fresh"] else []) + ( | |
| [f"far_{t['kind']}"] if t["far"] else []) | |
| for g in groups: | |
| a = acc.setdefault(g, [0, 0, 0.0]) | |
| a[0], a[1], a[2] = a[0] + int(v[0]), a[1] + 1, a[2] + v[1] | |
| out = {"unaligned": skipped} | |
| for g, (ok, n, lp) in acc.items(): | |
| out[f"acc_{g}"] = ok / n | |
| out[f"n_{g}"] = n | |
| if not g.startswith("far_"): | |
| out[f"logp_{g}"] = lp / n | |
| return out | |
| def rules_summary(targets: list, eff_ref: np.ndarray, eff_sys: np.ndarray, min_effect: float = MIN_EFFECT) -> dict: | |
| """Per family (+ "all") metrics over the far targets [(family, ...)] given the reference's and the model's | |
| effects (module docstring).""" | |
| out = {} | |
| for fam in list(FAMILIES) + ["all"]: | |
| ids = [i for i, t in enumerate(targets) if fam == "all" or t["family"] == fam] | |
| if not ids: | |
| continue | |
| ef, es = eff_ref[ids], eff_sys[ids] | |
| q = np.abs(ef) >= float(min_effect) | |
| o = {"n": len(ids), "n_qual": int(q.sum())} | |
| if q.any(): | |
| efq, esq = ef[q], es[q] | |
| o |= {"eff_ref": float(efq.mean()), "eff": float(esq.mean()), "frac_pos_ref": float((efq > 0).mean()), | |
| "retained": float(esq.sum() / efq.sum()) if abs(efq.sum()) > 1e-9 else None, | |
| "follow": float((esq / efq >= FOLLOW).mean()), "sign": float((esq * efq > 0).mean())} | |
| out[fam] = o | |
| return out | |
| def rules_metrics(items, sc, ref) -> dict: | |
| tg, er, es, skipped = [], [], [], 0 | |
| for it in items: | |
| for k, t in enumerate(it["targets"]): | |
| v, r = sc[it["id"]][k], ref[it["id"]][k] | |
| if v is None or r is None or None in v or None in r: | |
| skipped += 1 | |
| continue | |
| tg.append({"family": it["family"], "placement": it["placement"]}) | |
| er.append(r[1] - r[0]) | |
| es.append(v[1] - v[0]) | |
| er, es = np.asarray(er), np.asarray(es) | |
| out = {"by_placement": {}, "unaligned": skipped} | |
| for pc in PLACEMENTS: | |
| m = [i for i, t in enumerate(tg) if t["placement"] == pc] | |
| if m: | |
| out["by_placement"][pc] = rules_summary([tg[i] for i in m], er[m], es[m]) | |
| return out | |
| # ---------------------------------------------------------------- driver | |
| def plan_sets(root: Path, sets, splits, mode: str, tok, limit: int | None = None): | |
| """(Reads, {(set, split): (kind, items, plan)}).""" | |
| R, plans = Reads(), {} | |
| for name in sets: | |
| for sp in splits: | |
| items = load_items(root, name, sp) | |
| items = items[:limit] if limit else items | |
| if name == "facts": | |
| plans[(name, sp)] = ("facts", items, _plan_facts(items, mode, tok, R)) | |
| elif name == "tool_calls": | |
| plans[(name, sp)] = ("tools", items, _plan_tools(items, mode, tok, R)) | |
| else: | |
| plans[(name, sp)] = ("rules", items, _plan_rules(items, mode, tok, R)) | |
| return R, plans | |
| def raw_scores(R: Reads, plans: dict) -> dict: | |
| out = {} | |
| for (name, sp), (kind, items, plan) in plans.items(): | |
| f = {"facts": _facts_scores, "tools": _tools_scores, "rules": _rules_scores}[kind] | |
| out.setdefault(name, {})[sp] = f(plan, R) | |
| return out | |
| def choose_mode(mode: str, tok, meta: dict) -> str: | |
| if mode != "auto": | |
| return mode | |
| fp = meta.get("tokenizer_fingerprint") | |
| return "ids" if fp is not None and fingerprint(tok) == fp else "text" | |
| def score_sets(backend, tok, root, sets=SETS, splits=SPLITS, mode: str = "auto", limit: int | None = None, | |
| log=print) -> tuple[str, dict]: | |
| """(mode, raw per-target scores {set: {split: {item id: [...]}}}) of a model backend.""" | |
| root = Path(root) | |
| mode = choose_mode(mode, tok, load_meta(root)) | |
| log(f"mode {mode}") | |
| R, plans = plan_sets(root, sets, splits, mode, tok, limit) | |
| log(f"{len(R.seqs)} sequences, {sum(len(s['pos']) for s in R.seqs.values())} positions") | |
| R.run(backend, log) | |
| return mode, raw_scores(R, plans) | |
| def metrics(root, scores: dict, ref: dict | None = None, limit: int | None = None) -> dict: | |
| """{set: {split: metrics}} from raw scores (ref: the reference model's raw rules scores; None: the model's own).""" | |
| root = Path(root) | |
| out = {} | |
| for name, by in scores.items(): | |
| for sp, sc in by.items(): | |
| items = load_items(root, name, sp) | |
| items = items[:limit] if limit else items | |
| if name == "facts": | |
| m = facts_metrics(items, sc) | |
| elif name == "tool_calls": | |
| m = tools_metrics(items, sc) | |
| else: | |
| r = sc if ref is None else ref[name][sp] | |
| m = rules_metrics(items, sc, r) | |
| out.setdefault(name, {})[sp] = m | |
| return out | |
| def worst(by_split: dict) -> tuple[float | None, str | None, int]: | |
| """The lowest retained over every (family, placement, length) cell, where it is, the number of cells.""" | |
| cells = [] | |
| for sp, m in by_split.items(): | |
| for pc, sm in m.get("by_placement", {}).items(): | |
| for fam in FAMILIES: | |
| v = sm.get(fam, {}).get("retained") | |
| if v is not None: | |
| cells.append((v, f"{fam} / {pc} / {sp}")) | |
| if not cells: | |
| return None, None, 0 | |
| lo = min(cells) | |
| return lo[0], lo[1], len(cells) | |
| def rows(m: dict) -> dict: | |
| """The headline rows (module docstring) as the results page prints them (2 decimals).""" | |
| def f(v): | |
| return "–" if v is None else f"{v:.2f}" | |
| def follow(name, sp): | |
| return m.get(name, {}).get(sp, {}).get("by_placement", {}).get("system", {}).get("all", {}).get("follow") | |
| out = {} | |
| for label, (name, key) in ROWS.items(): | |
| if key == "worst": | |
| if name in m: | |
| out[label] = f(worst(m[name])[0]) | |
| elif name == "rules_csde": | |
| if "rules_cs" in m or "rules_de" in m: | |
| out[label] = f"{f(follow('rules_cs', '32k'))} / {f(follow('rules_de', '32k'))}" | |
| elif name in m: | |
| vals = [follow(name, sp) if key == "follow" else m[name].get(sp, {}).get(key) for sp in SPLITS] | |
| out[label] = " / ".join(f(v) for v in vals) | |
| return out | |
| def _dump(p: str, obj): | |
| op = gzip.open if p.endswith(".gz") else open | |
| with op(p, "wt", encoding="utf-8") as f: | |
| json.dump(obj, f) | |
| def _load(p: str): | |
| op = gzip.open if p.endswith(".gz") else open | |
| with op(p, "rt", encoding="utf-8") as f: | |
| return json.load(f) | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--model", required=True, help="a Hugging Face causal LM (hub id or local folder)") | |
| ap.add_argument("--backend", default="hf", choices=("hf", "thinctx"), | |
| help="hf: transformers; thinctx: a ThinCtx model through thinctx >= 1.1 (Engine.score)") | |
| ap.add_argument("--data", required=True, help="the dataset folder (or its hub id)") | |
| ap.add_argument("--sets", default=",".join(SETS)) | |
| ap.add_argument("--lengths", default=",".join(SPLITS)) | |
| ap.add_argument("--reference", default=None, help="the reference model of the rules sets (default: --model)") | |
| ap.add_argument("--reference_scores", default=None, help="the reference's raw scores (--save_scores of a run)") | |
| ap.add_argument("--save_scores", default=None, help="write the raw per-target scores here (.json or .json.gz)") | |
| ap.add_argument("--out", default=None, help="the result JSON (default: stdout only)") | |
| ap.add_argument("--mode", default="auto", choices=("auto", "ids", "text")) | |
| ap.add_argument("--dtype", default="bfloat16") | |
| ap.add_argument("--device", default="auto") | |
| ap.add_argument("--attn", default="sdpa", help="attention implementation (\"\" = the model's default)") | |
| ap.add_argument("--limit", type=int, default=None, help="only the first N items per set and length (a smoke test)") | |
| a = ap.parse_args(argv) | |
| root = resolve_data(a.data) | |
| sets = [s for s in a.sets.split(",") if s] | |
| splits = [s for s in a.lengths.split(",") if s] | |
| bad = set(sets) - set(SETS) or set(splits) - set(SPLITS) | |
| if bad: | |
| raise SystemExit(f"unknown sets / lengths {sorted(bad)}") | |
| t0 = time.time() | |
| log = lambda s: print(s, flush=True) # noqa: E731 | |
| rsets = [s for s in sets if s.startswith("rules_")] | |
| ref, ref_name = None, None | |
| if a.reference_scores: | |
| rr = _load(a.reference_scores) | |
| ref, ref_name = rr["scores"], rr.get("model") | |
| elif a.reference and a.reference != a.model and rsets: | |
| log(f"reference {a.reference}") | |
| be, tok = load_hf(a.reference, a.dtype, a.device, a.attn or None) | |
| _, rs = score_sets(be, tok, root, rsets, splits, a.mode, a.limit, log) | |
| ref, ref_name = rs, a.reference | |
| del be | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| log(f"model {a.model}") | |
| if a.backend == "thinctx": | |
| be = ThinCtxBackend(a.model) | |
| from transformers import AutoTokenizer | |
| tok = AutoTokenizer.from_pretrained(a.model) | |
| else: | |
| be, tok = load_hf(a.model, a.dtype, a.device, a.attn or None) | |
| mode, sc = score_sets(be, tok, root, sets, splits, a.mode, a.limit, log) | |
| if a.save_scores: | |
| _dump(a.save_scores, {"model": a.model, "mode": mode, "scores": sc}) | |
| if ref is None: | |
| ref_name = a.model | |
| m = metrics(root, sc, ref, a.limit) | |
| res = {"model": a.model, "reference": ref_name, "mode": mode, "limit": a.limit, "rows": rows(m), "sets": m, | |
| "time_s": round(time.time() - t0, 1)} | |
| for label, v in res["rows"].items(): | |
| log(f"{label}: {v}") | |
| if a.out: | |
| Path(a.out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(a.out).write_text(json.dumps(res, indent=1, ensure_ascii=False), encoding="utf-8") | |
| if __name__ == "__main__": | |
| main() | |