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
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
#!/usr/bin/env python3
"""
Score Hugging Face causal LMs on Deep Arithmark (and, side by side, ArithMark 3.0).

The scoring protocol follows ArithMark 3.0's (AxiomicLabs) so the two numbers
are directly comparable. This file is an independent implementation, not copied
code; it shares only imports and boilerplate with `bencharithmark-3.py`:

  * zero-shot continuation log-likelihood -- the model never generates text;
  * context and continuation tokenized separately, so the continuation cannot
    be scored through the context's tokenization;
  * `acc` sums the token log-probabilities, `acc_norm` averages them;
  * bf16, batch 32, `--max-context 1024`, by default.

On top of that it reports the profile the depth tiers are for:

  * a per-depth curve (2, 3, 4, 5 dependent operations), so a sub-1B model has
    something to climb instead of a single number pinned at chance;
  * per-template and per-topic accuracy, so a regression is attributable;
  * the share of items where `acc` and `acc_norm` disagree (a near-tie signal).

Usage
-----
    python bench_deeparithmark.py --model HuggingFaceTB/SmolLM2-135M
    python bench_deeparithmark.py --model gpt2 --compare   # ArithMark 3.0 too
    python bench_deeparithmark.py --models-file models.txt --out benchmarks/
"""

from __future__ import annotations

import argparse
import functools
import gc
import hashlib
import inspect
import json
import math
import time
from collections import defaultdict
from pathlib import Path

import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from transformers import AutoModelForCausalLM, AutoTokenizer

# Some 2026 checkpoints ship remote modelling code written against transformers 4.x
# (e.g. LiquidAI/LFM3, which decorates its convolution with a hub-kernel helper).
# transformers 5 removed that helper, so the import fails before the model can load.
# The decorator only swaps in an optional fused CUDA kernel; stubbing it out leaves
# the pure-torch path, which is the same maths at the same dtype.
def _accepts_layer_idx(fn) -> bool:
    try:
        return "layer_idx" in inspect.signature(fn).parameters
    except (TypeError, ValueError):
        return True


def _install_kernel_decorator_shim() -> None:
    try:
        import transformers.integrations as ti

        if not hasattr(ti, "use_kernel_func_from_hub_with_fallback"):
            def _noop(*_args, **_kwargs):
                return lambda fn: fn

            ti.use_kernel_func_from_hub_with_fallback = _noop

        import transformers.integrations.accelerate as tia

        if not hasattr(tia, "force_accelerate_hooks"):
            def _noop_hooks(*_args, **_kwargs):
                return lambda fn: fn

            tia.force_accelerate_hooks = _noop_hooks

        import transformers.masking_utils as tmu

        if not hasattr(tmu, "create_recurrent_attention_mask"):
            # transformers 4.x used this to hand a conv/linear-attention layer the plain
            # 2-D padding mask (1 = real token). It was deleted in 5.x; the contiguity
            # logic LFM3 needs on top of it (`seq_idx`) is computed in the model itself.
            def _recurrent_mask(config=None, inputs_embeds=None, attention_mask=None,
                                past_key_values=None, position_ids=None, layer_idx=None,
                                **_kwargs):
                if attention_mask is None:
                    return None
                return attention_mask.to(torch.bool) if attention_mask.dtype != torch.bool else attention_mask

            tmu.create_recurrent_attention_mask = _recurrent_mask

        if not _accepts_layer_idx(tmu.create_causal_mask):
            # 5.5 picks the layer's mask from the hybrid cache itself, so the explicit
            # `layer_idx` LFM3 passes is redundant rather than meaningful: drop it.
            def _wrap_drop_layer_idx(fn):
                @functools.wraps(fn)
                def wrapper(*args, layer_idx=None, **kwargs):
                    del layer_idx
                    return fn(*args, **kwargs)

                return wrapper

            tmu.create_causal_mask = _wrap_drop_layer_idx(tmu.create_causal_mask)
            tmu.create_sliding_window_causal_mask = _wrap_drop_layer_idx(
                tmu.create_sliding_window_causal_mask
            )
    except Exception:  # an old transformers that has the real helper is fine too
        pass


_install_kernel_decorator_shim()

# Our own data is read from disk; this repo is not published under AxiomicLabs.
DATA_DEFAULT = "deeparithmark-dataset/data/deeparithmark-1.jsonl"
# The one AxiomicLabs reference that must stay: `--compare` downloads the upstream
# benchmark from its authors' org, which is where it actually lives. Changing this
# to another namespace would break the head-to-head.
ARITHMARK3_REPO = "AxiomicLabs/Arithmark-3.0"
ARITHMARK3_FILE = "arithmark-3.jsonl"
BATCH_SIZE = 32
MAX_CONTEXT = 1024
DEPTHS = (2, 3, 4, 5)

# every model here is under 1B parameters, which is the target of this benchmark
DEFAULT_MODELS = [
    "gpt2",
    "EleutherAI/pythia-70m",
    "HuggingFaceTB/SmolLM2-135M",
    "Qwen/Qwen2.5-0.5B",
]


def load_items(path: Path) -> list[dict]:
    items = []
    with path.open(encoding="utf-8-sig") as fh:
        for line_no, line in enumerate(fh, 1):
            if not line.strip():
                continue
            item = json.loads(line)
            label = item["label"]
            items.append(
                {
                    "id": str(item.get("ind", line_no)),
                    "ctx": item["ctx"],
                    "endings": item["endings"],
                    "label": int(label),
                    "depth": item.get("metadata", {}).get("depth"),
                    "topic": item.get("metadata", {}).get("topic"),
                    "template": item.get("metadata", {}).get("template_id"),
                }
            )
    if not items:
        raise SystemExit(f"no items in {path}")
    return items


def resolve_device(requested: str) -> str:
    if requested != "auto":
        return requested
    return "cuda" if torch.cuda.is_available() else "cpu"


def load_model(model_name: str, device: str, dtype_name: str):
    dtype = {"float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16}[
        dtype_name
    ]
    if device == "cpu":
        dtype = torch.float32
    model = AutoModelForCausalLM.from_pretrained(
        model_name, dtype=dtype, trust_remote_code=True
    ).to(device)
    model.eval()
    tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True, use_fast=False)
    if tokenizer.pad_token_id is None:
        tokenizer.pad_token = tokenizer.eos_token or 0
    return model, tokenizer, dtype


@torch.inference_mode()
def score_items(model, tokenizer, device, dtype, items, batch_size: int, max_context: int):
    """Return (items, labels, raw_scores, norm_scores) -- 4 scores per item.

    Results follow the length-sorted order used for batching, so the returned
    item list is what the labels and scores line up with.
    """
    prepared = []
    for item in items:
        requests = []
        for ending in item["endings"]:
            ctx_ids = tokenizer(item["ctx"], add_special_tokens=False).input_ids
            end_ids = tokenizer(ending, add_special_tokens=False).input_ids
            if not ctx_ids or not end_ids:
                raise SystemExit(f"empty tokenization in item {item['id']}")
            ctx_ids = ctx_ids[-(max_context - len(end_ids)) :]
            requests.append((ctx_ids + end_ids, len(end_ids)))
        prepared.append((item, requests))
    # similar lengths together: less padding, fewer wasted logits
    prepared.sort(key=lambda pair: max(len(t) for t, _ in pair[1]))

    labels, raw, norm = [], [], []
    for start in range(0, len(prepared), batch_size):
        batch = prepared[start : start + batch_size]
        flats, lengths, cont_lens = [], [], []
        for _, requests in batch:
            for tokens, cont_len in requests:
                flats.append(tokens)
                lengths.append(len(tokens))
                cont_lens.append(cont_len)
        width = max(lengths)
        ids = torch.tensor(
            [t + [tokenizer.pad_token_id] * (width - len(t)) for t in flats],
            dtype=torch.long,
            device=device,
        )
        mask = torch.arange(width, device=device)[None, :] < torch.tensor(
            lengths, device=device
        )[:, None]
        starts = torch.tensor(
            [len(t) - c for t, c in zip(flats, cont_lens)], dtype=torch.long, device=device
        )
        with (
            torch.autocast("cuda", dtype=dtype) if device == "cuda" and dtype != torch.float32 else torch.no_grad()
        ):
            logits = model(ids, attention_mask=mask, use_cache=False).logits
        positions = torch.arange(1, width, device=device)[None, :]
        score_mask = (positions >= starts[:, None]) & (
            positions < torch.tensor(lengths, device=device)[:, None]
        )
        row_idx, rel = score_mask.nonzero(as_tuple=True)
        tok_pos = rel + 1
        picked = logits[row_idx, tok_pos - 1, :]
        targets = ids[row_idx, tok_pos]
        tok_ll = -F.cross_entropy(picked.float(), targets, reduction="none")
        raw_t = torch.zeros(len(flats), device=device).scatter_add_(0, row_idx, tok_ll)
        cnt_t = torch.zeros(len(flats), device=device).scatter_add_(
            0, row_idx, torch.ones_like(tok_ll)
        )
        raw_f = raw_t.cpu().tolist()
        norm_f = (raw_t / cnt_t.clamp_min(1)).cpu().tolist()
        for i, (item, _) in enumerate(batch):
            base = 4 * i
            labels.append(item["label"])
            raw.append(raw_f[base : base + 4])
            norm.append(norm_f[base : base + 4])
        del logits, ids, mask
    return [item for item, _ in prepared], labels, raw, norm


def summarize(items, labels, raw, norm) -> dict:
    def pick(scores, i):
        return max(range(4), key=lambda k: scores[i][k])

    hit_raw = [int(pick(raw, i) == labels[i]) for i in range(len(items))]
    hit_norm = [int(pick(norm, i) == labels[i]) for i in range(len(items))]

    # Soft score: the probability a proper scoring rule assigns to the correct
    # option after a softmax over the four continuations. Hard accuracy is
    # all-or-nothing (a model either lands the exact number or not), so it sits
    # at 25 % for sub-1B models; this keeps the graded signal visible.
    def soft(row, label):
        top = max(row)
        exps = [math.exp(s - top) for s in row]
        return exps[label] / sum(exps)

    soft_norm = [soft(norm[i], labels[i]) for i in range(len(items))]
    soft_by_depth = defaultdict(lambda: [0.0, 0])
    for i, item in enumerate(items):
        if item.get("depth"):
            soft_by_depth[item["depth"]][0] += soft_norm[i]
            soft_by_depth[item["depth"]][1] += 1

    def pct(correct: int, n: int) -> float:
        return 100.0 * correct / n if n else 0.0

    by_depth = defaultdict(lambda: [0, 0])
    by_topic = defaultdict(lambda: [0, 0])
    by_template = defaultdict(lambda: [0, 0])
    for i, item in enumerate(items):
        if item.get("depth"):
            by_depth[item["depth"]][0] += hit_norm[i]
            by_depth[item["depth"]][1] += 1
        by_topic[item.get("topic") or "n/a"][0] += hit_norm[i]
        by_topic[item.get("topic") or "n/a"][1] += 1
        by_template[item.get("template") or "n/a"][0] += hit_norm[i]
        by_template[item.get("template") or "n/a"][1] += 1

    n = len(items)
    return {
        "n": n,
        "acc": pct(sum(hit_raw), n),
        "acc_norm": pct(sum(hit_norm), n),
        "soft": 100.0 * sum(soft_norm) / n,
        "disagreements": sum(1 for a, b in zip(hit_raw, hit_norm) if a != b),
        "by_depth": {
            d: {
                "acc_norm": pct(v[0], v[1]),
                "soft": 100.0 * soft_by_depth[d][0] / soft_by_depth[d][1],
                "n": v[1],
            }
            for d, v in sorted(by_depth.items())
        },
        "by_topic": {
            t: {"acc_norm": pct(v[0], v[1]), "n": v[1]} for t, v in sorted(by_topic.items())
        },
        "by_template": {
            t: {"acc_norm": pct(v[0], v[1]), "n": v[1]} for t, v in sorted(by_template.items())
        },
    }


def print_report(name, params, res) -> None:
    print(f"\n{name}  ({params:,} parameters)")
    print(f"  Deep Arithmark score (acc_norm)  {res['acc_norm']:6.2f}%")
    print(f"  soft score (P[correct])          {res['soft']:6.2f}%")
    print(f"  raw token-sum accuracy (acc)     {res['acc']:6.2f}%")
    if res["by_depth"]:
        print("  depth curve (acc_norm / soft):")
        for depth, vals in res["by_depth"].items():
            print(
                f"    depth {depth}: {vals['acc_norm']:6.2f}% / {vals['soft']:6.2f}%"
                f"  (n={vals['n']})"
            )
    print("  by template:")
    for template, vals in sorted(res["by_template"].items(), key=lambda kv: -kv[1]["acc_norm"]):
        print(f"    {template:34s} {vals['acc_norm']:6.2f}%  (n={vals['n']})")


def arithmark3_path() -> Path:
    return Path(hf_hub_download(ARITHMARK3_REPO, ARITHMARK3_FILE, repo_type="dataset"))


def run_model(model_name, args, device, deep_items, am3_items):
    model, tokenizer, dtype = load_model(model_name, device, args.dtype)
    params = sum(p.numel() for p in model.parameters())
    out = {"model": model_name, "params": params, "protocol": {
        "dtype": str(dtype), "batch_size": args.batch_size,
        "max_context": args.max_context, "shots": 0,
    }}
    t0 = time.perf_counter()
    ordered, labels, raw, norm = score_items(
        model, tokenizer, device, dtype, deep_items, args.batch_size, args.max_context
    )
    res = summarize(ordered, labels, raw, norm)
    out["deeparithmark"] = res
    print_report(model_name, params, res)
    if args.dump_predictions:
        target = Path(args.dump_predictions)
        target.parent.mkdir(parents=True, exist_ok=True)
        with target.open("a", encoding="utf-8") as fh:
            for i, item in enumerate(ordered):
                fh.write(
                    json.dumps(
                        {
                            "model": model_name,
                            "id": item["id"],
                            "depth": item.get("depth"),
                            "template": item.get("template"),
                            "label": labels[i],
                            "raw_pick": max(range(4), key=lambda k: raw[i][k]),
                            "norm_pick": max(range(4), key=lambda k: norm[i][k]),
                            "raw": raw[i],
                            "norm": norm[i],
                        }
                    )
                    + "\n"
                )
    if am3_items is not None:
        ordered, labels, raw, norm = score_items(
            model, tokenizer, device, dtype, am3_items, args.batch_size, args.max_context
        )
        am3 = summarize(ordered, labels, raw, norm)
        out["arithmark3"] = am3
        print(f"  ArithMark 3.0 (acc_norm)         {am3['acc_norm']:6.2f}%   [same weights, same protocol]")
        print(f"  drop                             {am3['acc_norm'] - res['acc_norm']:+6.2f} points")
    out["seconds"] = round(time.perf_counter() - t0, 2)
    del model, tokenizer
    gc.collect()
    if device == "cuda":
        torch.cuda.empty_cache()
    return out


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--model", action="append", help="HF model id; repeatable")
    ap.add_argument("--data", default=DATA_DEFAULT)
    ap.add_argument("--compare", action="store_true", help="also score ArithMark 3.0")
    ap.add_argument("--arithmark3", help="local path to arithmark-3.jsonl")
    ap.add_argument("--batch-size", type=int, default=BATCH_SIZE)
    ap.add_argument("--max-context", type=int, default=MAX_CONTEXT)
    ap.add_argument("--dtype", choices=("float32", "float16", "bfloat16"), default="bfloat16")
    ap.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
    ap.add_argument("--out", default="benchmarks")
    ap.add_argument("--no-save", action="store_true")
    ap.add_argument(
        "--dump-predictions",
        help="write per-item scores to this JSONL path for error analysis",
    )
    args = ap.parse_args()

    torch.set_float32_matmul_precision("high")
    if torch.cuda.is_available():
        torch.backends.cuda.matmul.allow_tf32 = True

    data_path = Path(args.data)
    if not data_path.exists():
        raise SystemExit(f"missing {data_path}; run `python deeparithmark.py build`")
    deep_items = load_items(data_path)
    sha = hashlib.sha256(data_path.read_bytes()).hexdigest()
    device = resolve_device(args.device)
    print(f"device: {device} | items: {len(deep_items)} | sha256: {sha[:16]}...")

    am3_items = None
    if args.compare or args.arithmark3:
        am3_file = Path(args.arithmark3) if args.arithmark3 else arithmark3_path()
        am3_items = load_items(am3_file)
        print(f"comparing against ArithMark 3.0 ({len(am3_items)} items): {am3_file}")

    models = args.model or DEFAULT_MODELS
    results = []
    for name in models:
        try:
            results.append(run_model(name, args, device, deep_items, am3_items))
        except Exception as exc:  # a broken hub repo should not kill the sweep
            print(f"\n{name}: FAILED -- {str(exc).splitlines()[0]}")

    if results:
        print("\n" + "=" * 84)
        print(f"{'model':40s} {'deep':>8s} {'soft':>8s} {'arith3':>8s}")
        for r in results:
            am3 = r.get("arithmark3", {}).get("acc_norm")
            print(
                f"{r['model']:40s} {r['deeparithmark']['acc_norm']:7.2f}%"
                f" {r['deeparithmark']['soft']:7.2f}%"
                + (f" {am3:7.2f}%" if am3 is not None else "       -")
            )
        print("=" * 84)

    if not args.no_save and results:
        out_dir = Path(args.out)
        out_dir.mkdir(parents=True, exist_ok=True)
        payload = {
            "dataset": {"name": "deeparithmark-1", "path": str(data_path), "sha256": sha,
                        "items": len(deep_items)},
            "protocol": {
                "shots": 0, "dtype": args.dtype, "batch_size": args.batch_size,
                "max_context": args.max_context, "metric": "acc_norm",
            },
            "results": results,
        }
        target = out_dir / f"deeparithmark_{len(results)}models.json"
        target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
        print(f"\nresults -> {target}")


if __name__ == "__main__":
    main()