File size: 29,481 Bytes
7fa7e5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
#!/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

    @torch.no_grad()
    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]

    @torch.no_grad()
    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()