{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d181fb23",
   "metadata": {},
   "source": [
    "# E1: the released checkpoints, re-measured\n",
    "\n",
    "The paper's large-scale claims rest on single checkpoints evaluated once. E1 re-measures them on\n",
    "the released weights, with paired statistics, and asks two questions the paper did not test on\n",
    "these models: do they gain from more loops than trained, and where does ARLoop's router look? The\n",
    "protocol (`experiments/e1_release/PROTOCOL.md`) was registered before any full run. Every number\n",
    "on this page is read from `runs/e1/` while the book is built."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78d2ff87",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib, re, json\n",
    "\n",
    "BOOK = next(p for p in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents] if (p / \"seminar_lib.py\").exists())\n",
    "sys.path.insert(0, str(BOOK))\n",
    "sys.dont_write_bytecode = True   # keep book/ free of __pycache__\n",
    "import seminar_lib as lib\n",
    "import matplotlib\n",
    "matplotlib.use(\"module://matplotlib_inline.backend_inline\")\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "PROT = lib.PROTOCOL[\"E1\"]\n",
    "E1 = lib.RUNS / \"e1\"\n",
    "summary = lib.read_json(E1 / \"summary.json\")\n",
    "acc = (summary or {}).get(\"gsm8k_acc\", {})\n",
    "acc_nobos = (summary or {}).get(\"gsm8k_acc_nobos\", {})\n",
    "pairs = (summary or {}).get(\"paired\", {})\n",
    "bpb = (summary or {}).get(\"wikitext_bpb\", {})\n",
    "RUN = re.compile(r\"^(ar06|pn06|ar12)-R(\\d+)(?:-(repeat|cycle))?$\")\n",
    "MODEL = {\"ar06\": \"ARLoop-0.6B\", \"pn06\": \"PreNormLoop-0.6B\", \"ar12\": \"ARLoop-1.2B\"}\n",
    "PAPER_GSM8K = {k: lib.scores(MODEL[k])[\"GSM8K\"] for k in MODEL}\n",
    "\n",
    "\n",
    "def parse(name):\n",
    "    m = RUN.match(name)\n",
    "    return (m.group(1), int(m.group(2)), m.group(3) or \"\") if m else None\n",
    "\n",
    "\n",
    "def pct(x):                                    # accuracy in %, two decimals as in the digest\n",
    "    return f\"{100 * x:.2f}\"\n",
    "\n",
    "\n",
    "def pts(x):                                    # a difference in points, signed\n",
    "    return lib.signed(100 * x)\n",
    "\n",
    "\n",
    "def ci(p):                                     # the 95% interval of a paired comparison, in points\n",
    "    return f\"[{pts(p['ci95'][0])}, {pts(p['ci95'][1])}]\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85c14a33",
   "metadata": {},
   "source": [
    "## The protocol in brief\n",
    "\n",
    "* **Models**, pinned: ARLoop-0.6B, PreNormLoop-0.6B and ARLoop-1.2B at the revisions in\n",
    "  {doc}`../mechanism/m2_parameters`; BF16, the authors' remote code, one RTX PRO 6000 (WMI).\n",
    "* **GSM8K {cite}`cobbe2021gsm8k` as in the paper** (App. B): `gsm8k_cot`, 5-shot, greedy, at most 1,024 new tokens, no\n",
    "  chat template, flexible-extract exact match, all 1,319 test items. Differences from the authors'\n",
    "  evaluation: the Hugging Face (HF) backend of lm-eval {cite}`lmeval2024` instead of vLLM (the default of their released\n",
    "  evaluation code), with batched generation. As the\n",
    "  authors' evaluation script does by default, `<|endoftext|>` is prepended as the\n",
    "  beginning-of-sequence token (BOS). A first attempt did not actually prepend it with the HF\n",
    "  backend. Its ARLoop-0.6B run became a **no-BOS control**, completed by a no-BOS run of\n",
    "  PreNormLoop-0.6B (`runs/e1/gsm8k-nobos/`) and a rerun of the ARLoop-0.6B one from a frozen code\n",
    "  snapshot (`runs/e1/gsm8k-nobos-rerun/`). The primary runs are in `runs/e1/gsm8k-bos/`. Since the\n",
    "  correction, every receipt records whether BOS was prepended, measured on an encoded probe\n",
    "  (amendments of 2026-11-15).\n",
    "* **Numbers of loops.** ARLoop uses its trained routing parameters (queries and norm weights) for\n",
    "  $R \\le 3$; for $R > 3$ two declared inference-only rules supply the missing ones (`repeat`,\n",
    "  `cycle`; see {doc}`../mechanism/m2_parameters`). PreNormLoop runs at any $R$. WikiText-2 bits per byte (rolling\n",
    "  log-likelihood, no BOS) serve as a held-out language-modelling signal.\n",
    "* **Decision rules**, fixed before the runs (paired over the same 1,319 items):\n",
    "  - E1.1 *supports* the pair gap if the paired bootstrap 95% interval of ARLoop − PreNormLoop at\n",
    "    $R = 3$ lies above 0, *contradicts* it if the interval lies below 0, and is *inconclusive*\n",
    "    otherwise (exact McNemar test reported);\n",
    "  - E1.2 *supports* the 1.2B number if it is within ±2 points of the paper's;\n",
    "  - E1.3, for $R > 3$: *supports \"no gain\"* if the interval of (R) − (R = 3) lies at or below 0, or\n",
    "    contains 0 with a point estimate ≤ 0; *contradicts* it if the interval lies above 0. For $R = 2$\n",
    "    against 3: *supports \"deeper is better\"* if the interval of (3) − (2) lies above 0;\n",
    "  - E1.4 is descriptive. **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "069dd926",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT, \"`gsm8k_cot`, 5-shot (first five Wei et al. exemplars), greedy, ≤1,024 new tokens, no chat template\",\n",
    "                       \"flexible-extract exact match, all 1,319 test items\",\n",
    "                       \"HF backend (theirs: vLLM)\", \"one RTX PRO 6000 (WMI `gpu_csi`)\",\n",
    "                       \"*Supports* if the paired bootstrap 95% interval is > 0; *contradicts* if < 0; else *inconclusive*\",\n",
    "                       \"*Supports* if within ±2 points of 63.1\",\n",
    "                       \"*supports \\\"no gain\\\"* if the paired interval of (R) − (R = 3) is ≤ 0 or contains 0 with point estimate ≤ 0; *contradicts* if the interval is > 0\",\n",
    "                       \"For R = 2 vs 3: *supports \\\"deeper is better\\\"* if (3) − (2) interval > 0\",\n",
    "                       \"Our runs set `add_bos_token=True`\", \"**BOS, corrected.**\",\n",
    "                       \"kept as a no-BOS control under `runs/e1/gsm8k-nobos/`\",\n",
    "                       \"Primary runs with BOS go to `runs/e1/gsm8k-bos/`\")\n",
    "# the no-BOS control as described above: the ARLoop-0.6B number comes from the snapshot rerun,\n",
    "# and both no-BOS receipts record that no BOS was prepended\n",
    "NOBOS_SRC = (summary or {}).get(\"nobos_ar06_R3_source\", \"gsm8k-nobos\").split()[0]\n",
    "NOBOS_DIRS = {\"ar06-R3\": E1 / NOBOS_SRC / \"ar06-R3\", \"pn06-R3\": E1 / \"gsm8k-nobos\" / \"pn06-R3\"}\n",
    "nobos_receipts = {k: lib.read_json(d / \"receipt.json\") for k, d in NOBOS_DIRS.items()}\n",
    "if acc_nobos:\n",
    "    assert NOBOS_SRC == \"gsm8k-nobos-rerun\" and set(acc_nobos) == set(NOBOS_DIRS)\n",
    "    assert all(r is not None and r[\"bos_prepended\"] is False for r in nobos_receipts.values())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab89076a",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "expected = [(\"summary of all runs\", E1 / \"summary.json\"),\n",
    "            (\"routing probe, ARLoop-0.6B\", E1 / \"routing\" / \"ar06-R3\" / \"routing.json\"),\n",
    "            (\"routing probe, PreNormLoop-0.6B\", E1 / \"routing\" / \"pn06-R3\" / \"routing.json\")]\n",
    "receipts = sorted(E1.rglob(\"receipt.json\")) if E1.exists() else []\n",
    "lib.md(\"**Files at build time.**\\n\\n\" +\n",
    "       lib.table([(what, f\"`{lib.rel(p)}`\", \"present\" if p.exists() else \"**pending**\") for what, p in expected] +\n",
    "                 [(\"run receipts\", f\"`{lib.rel(E1)}/**/receipt.json`\", f\"{len(receipts)} found\")],\n",
    "                 [\"what\", \"file\", \"status\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a28a78cc",
   "metadata": {},
   "source": [
    "## E1.1 — the pair gap on GSM8K\n",
    "\n",
    "The paper reports GSM8K 40.9 for ARLoop-0.6B and 35.7 for PreNormLoop-0.6B (Table 3), a gap of\n",
    "+5.2 points, one run each, no interval. **[paper]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d78110d",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert (PAPER_GSM8K[\"ar06\"], PAPER_GSM8K[\"pn06\"], PAPER_GSM8K[\"ar12\"]) == (40.9, 35.7, 63.1)\n",
    "assert f\"{PAPER_GSM8K['ar06'] - PAPER_GSM8K['pn06']:+.1f}\" == \"+5.2\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f242f0f",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "KEY = \"ARLoop-0.6B vs PreNormLoop-0.6B at R=3\"\n",
    "\n",
    "\n",
    "def verdict_pair(ci):\n",
    "    return \"supports\" if ci[0] > 0 else (\"contradicts\" if ci[1] < 0 else \"inconclusive\")\n",
    "\n",
    "\n",
    "pg = pairs.get(KEY)\n",
    "recomputed = None\n",
    "if pg is None:\n",
    "    lib.pending(\"E1.1\", \"`runs/e1/summary.json` has no paired comparison of the two 0.6B models at \"\n",
    "                \"R = 3 yet; nothing is shown.\")\n",
    "else:\n",
    "    sa = lib.samples_em(E1 / \"gsm8k-bos\" / pg[\"a\"] / \"samples.jsonl\")\n",
    "    sb = lib.samples_em(E1 / \"gsm8k-bos\" / pg[\"b\"] / \"samples.jsonl\")\n",
    "    if sa and sb:\n",
    "        recomputed = lib.paired(sa, sb)            # exact replication of analyze.py, bootstrap included\n",
    "    lib.md(lib.table([\n",
    "        (\"ARLoop-0.6B, R = 3\", pct(pg[\"acc_a\"]), PAPER_GSM8K[\"ar06\"]),\n",
    "        (\"PreNormLoop-0.6B, R = 3\", pct(pg[\"acc_b\"]), PAPER_GSM8K[\"pn06\"]),\n",
    "        (\"difference (points)\", f\"{pts(pg['diff'])}, 95% interval {ci(pg)}\",\n",
    "         lib.signed(PAPER_GSM8K[\"ar06\"] - PAPER_GSM8K[\"pn06\"], 1))],\n",
    "        [\"GSM8K (%), 5-shot CoT, flexible extract\", f\"ours (n = {pg['n']:,}) [exp]\", \"paper [paper]\"]) +\n",
    "        f\"\\n\\nItems solved only by ARLoop-0.6B: {pg['only_a']}; only by PreNormLoop-0.6B: {pg['only_b']}; \"\n",
    "        f\"exact McNemar p = {lib.pvalue(pg['mcnemar_p'])}. **Decision rule: {verdict_pair(pg['ci95'])}.** \" +\n",
    "        (\"Recomputed here from the per-item samples (accuracies, discordant items, McNemar and the \"\n",
    "         \"bootstrap interval): identical.\" if recomputed else\n",
    "         \"The per-item samples are not in `runs/e1/gsm8k-bos/`; the statistics are read from `summary.json`.\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "422b12bb",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if pg is not None:\n",
    "    assert pg[\"n\"] == 1319 and pg[\"a\"] == \"ar06-R3\" and pg[\"b\"] == \"pn06-R3\"\n",
    "    assert pg[\"only_a\"] - pg[\"only_b\"] == round(pg[\"diff\"] * pg[\"n\"])\n",
    "    assert abs(pg[\"mcnemar_p\"] - lib.mcnemar_exact(pg[\"only_a\"], pg[\"only_b\"])) < 1e-12\n",
    "    assert pg[\"ci95\"][0] <= pg[\"diff\"] <= pg[\"ci95\"][1]\n",
    "    assert abs(acc[\"ar06-R3\"] - pg[\"acc_a\"]) < 1e-12 and abs(acc[\"pn06-R3\"] - pg[\"acc_b\"]) < 1e-12\n",
    "    if recomputed:\n",
    "        for k in (\"n\", \"only_a\", \"only_b\"):\n",
    "            assert recomputed[k] == pg[k]\n",
    "        for k in (\"acc_a\", \"acc_b\", \"diff\", \"mcnemar_p\"):\n",
    "            assert abs(recomputed[k] - pg[k]) < 1e-12\n",
    "        assert all(abs(u - v) < 1e-12 for u, v in zip(recomputed[\"ci95\"], pg[\"ci95\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "031e7a7e",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if acc_nobos:\n",
    "    rows = []\n",
    "    for k, v in sorted(acc_nobos.items()):\n",
    "        bv = pairs.get(f\"{k}: BOS vs no BOS\")\n",
    "        r = nobos_receipts.get(k) or {}\n",
    "        rows.append((MODEL[parse(k)[0]], pct(acc[k]) if k in acc else \"–\", pct(v),\n",
    "                     f\"{pts(bv['diff'])} {ci(bv)}, p\\u00a0=\\u00a0{lib.pvalue(bv['mcnemar_p'])}\" if bv else \"–\",\n",
    "                     f\"`{lib.rel(NOBOS_DIRS[k])}`, job {r.get('job_id', '–')}\"))\n",
    "    same = summary.get(\"nobos_ar06_R3_rerun_identical_generations\")\n",
    "    text = (\"**Control: the same comparison without BOS.** Both no-BOS receipts record that no BOS was \"\n",
    "            \"prepended.\" + (f\" The ARLoop-0.6B run is the rerun from a frozen code snapshot; its generations are \"\n",
    "                            f\"identical to those of the first no-BOS run on {same[0]:,} of {same[1]:,} items.\" if same else \"\") +\n",
    "            \"\\n\\n\" + lib.table(rows, [\"model, R = 3\", \"GSM8K with BOS (%)\", \"without BOS (%)\",\n",
    "                                      \"BOS − no BOS (points, 95% interval, McNemar)\", \"no-BOS run\"]))\n",
    "    nb = pairs.get(\"no BOS: ARLoop-0.6B vs PreNormLoop-0.6B at R=3\")\n",
    "    if nb:\n",
    "        text += (f\"\\n\\nWithout BOS the pair gap is {pts(nb['diff'])} points, 95% interval {ci(nb)}, McNemar \"\n",
    "                 f\"p = {lib.pvalue(nb['mcnemar_p'])}; **decision rule: {verdict_pair(nb['ci95'])}.** BOS lowers \"\n",
    "                 \"PreNormLoop-0.6B's accuracy and does not detectably change ARLoop-0.6B's (its interval contains 0). \"\n",
    "                 \"The size of the paper's gap therefore depends on the BOS choice (finding F9 of the digest).\")\n",
    "    lib.md(text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b01daee8",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if acc_nobos:\n",
    "    nb = pairs[\"no BOS: ARLoop-0.6B vs PreNormLoop-0.6B at R=3\"]\n",
    "    bos_pn, bos_ar = pairs[\"pn06-R3: BOS vs no BOS\"], pairs[\"ar06-R3: BOS vs no BOS\"]\n",
    "    assert verdict_pair(nb[\"ci95\"]) == \"inconclusive\"\n",
    "    assert bos_pn[\"ci95\"][1] < 0 and bos_ar[\"ci95\"][0] < 0 < bos_ar[\"ci95\"][1]\n",
    "    for k, p in ((\"ar06-R3\", bos_ar), (\"pn06-R3\", bos_pn)):\n",
    "        assert p[\"n\"] == 1319 and abs(p[\"acc_a\"] - acc[k]) < 1e-12 and abs(p[\"acc_b\"] - acc_nobos[k]) < 1e-12\n",
    "        assert abs(p[\"mcnemar_p\"] - lib.mcnemar_exact(p[\"only_a\"], p[\"only_b\"])) < 1e-12\n",
    "    assert abs(nb[\"acc_a\"] - acc_nobos[\"ar06-R3\"]) < 1e-12 and abs(nb[\"acc_b\"] - acc_nobos[\"pn06-R3\"]) < 1e-12\n",
    "    assert summary[\"nobos_ar06_R3_rerun_identical_generations\"] == [1319, 1319]\n",
    "    assert lib.quote_check(lib.DIGEST, \"The size of the pair gap depends on the BOS choice (F9).\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e30dc73f",
   "metadata": {},
   "source": [
    "## E1.2 — ARLoop-1.2B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ec55609",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if \"ar12-R3\" not in acc:\n",
    "    lib.pending(\"E1.2\", \"no GSM8K run of ARLoop-1.2B at R = 3 in `runs/e1/summary.json` yet.\")\n",
    "else:\n",
    "    a12 = 100 * acc[\"ar12-R3\"]\n",
    "    v12 = \"supports\" if abs(a12 - PAPER_GSM8K[\"ar12\"]) <= 2 else \"contradicts\"\n",
    "    lib.md(f\"ARLoop-1.2B at R = 3: GSM8K **{a12:.2f}%** (paper: {PAPER_GSM8K['ar12']}%); difference \"\n",
    "           f\"{lib.signed(a12 - PAPER_GSM8K['ar12'])} points. **Decision rule (within ±2 points): {v12}.** [exp]\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0de30a16",
   "metadata": {},
   "source": [
    "## E1.3 — more loops than trained"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "142a1758",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "def verdict_extra(p):\n",
    "    lo, hi = p[\"ci95\"]\n",
    "    if lo > 0:\n",
    "        return \"contradicts \\\"no gain\\\"\"\n",
    "    if hi <= 0 or (lo <= 0 <= hi and p[\"diff\"] <= 0):\n",
    "        return \"supports \\\"no gain\\\"\"\n",
    "    return \"inconclusive\"\n",
    "\n",
    "\n",
    "sweep = {name: parse(name) for name in acc if parse(name)}\n",
    "others = [n for n in sweep if sweep[n][1] != 3]\n",
    "if not others:\n",
    "    lib.pending(\"E1.3\", \"no GSM8K run at a number of loops other than 3 in `runs/e1/summary.json` yet.\")\n",
    "else:\n",
    "    rows = []\n",
    "    for name, (m, R, rule) in sorted(sweep.items(), key=lambda kv: (kv[1][0], kv[1][1], kv[1][2])):\n",
    "        p = pairs.get(f\"{name} vs {m}-R3\")\n",
    "        if R == 3 or p is None:\n",
    "            stat, v = \"–\", \"reference\" if R == 3 else \"(no paired result)\"\n",
    "        else:\n",
    "            stat = f\"{pts(p['diff'])} {ci(p)}, p\\u00a0=\\u00a0{lib.pvalue(p['mcnemar_p'])}\"\n",
    "            v = (verdict_extra(p) if R > 3 else\n",
    "                 (\"supports \\\"deeper is better\\\"\" if p[\"ci95\"][1] < 0 else \"does not support \\\"deeper is better\\\"\")\n",
    "                 if R == 2 else \"descriptive\")\n",
    "        rows.append((MODEL[m], R, rule or \"trained\", pct(acc[name]),\n",
    "                     f\"{bpb[name]:.4f}\" if bpb.get(name) is not None else \"–\", stat, v))\n",
    "    lib.md(lib.table(rows, [\"model\", \"loops R\", \"routing\", \"GSM8K (%)\", \"WikiText bits/byte\",\n",
    "                            \"GSM8K vs R = 3 (points, 95% interval, McNemar)\", \"decision rule\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea759e5a",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "for name, (m, R, rule) in sweep.items():\n",
    "    assert (rule != \"\") == (m != \"pn06\" and R > 3)          # rules exist exactly where queries are missing\n",
    "    p = pairs.get(f\"{name} vs {m}-R3\")\n",
    "    if p is not None:\n",
    "        assert p[\"n\"] == 1319 and abs(p[\"acc_a\"] - acc[name]) < 1e-12 and abs(p[\"acc_b\"] - acc[f\"{m}-R3\"]) < 1e-12\n",
    "        assert p[\"ci95\"][0] <= p[\"diff\"] <= p[\"ci95\"][1]\n",
    "        assert abs(p[\"mcnemar_p\"] - lib.mcnemar_exact(p[\"only_a\"], p[\"only_b\"])) < 1e-12"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00eafaea",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if others:\n",
    "    beyond = {n: pairs[f\"{n} vs {sweep[n][0]}-R3\"] for n in sweep\n",
    "              if sweep[n][1] > 3 and f\"{n} vs {sweep[n][0]}-R3\" in pairs}\n",
    "    no_gain = [n for n, p in beyond.items() if verdict_extra(p) == \"supports \\\"no gain\\\"\"]\n",
    "    level = [n for n, p in beyond.items() if p[\"ci95\"][1] >= 0]\n",
    "    below = [n for n in sweep if sweep[n][1] < 3]\n",
    "    lowest_bpb = {m: min((n for n in bpb if parse(n) and parse(n)[0] == m), key=bpb.get) for m in (\"ar06\", \"pn06\")}\n",
    "    share = f\"all {len(beyond)}\" if len(no_gain) == len(beyond) else f\"{len(no_gain)} of {len(beyond)}\"\n",
    "    text = (f\"Beyond the trained depth the decision rule returns *supports \\\"no gain\\\"* in {share} cells: no gain \"\n",
    "            f\"detected. In {len(beyond) - len(level)} of them accuracy drops, with an interval below 0\")\n",
    "    if len(level) == 1:\n",
    "        m, R, rule = sweep[level[0]]\n",
    "        text += (f\"; the exception is {MODEL[m]} with `{rule}` at R = {R}, level with R = 3 \"\n",
    "                 f\"({pts(beyond[level[0]]['diff'])} points, interval {ci(beyond[level[0]])}), whose interval does not \"\n",
    "                 f\"exclude a gain of up to {pts(beyond[level[0]]['ci95'][1])} points\")\n",
    "    text += (f\". Below the trained depth all {len(below)} runs, at R = 1 or 2, score \"\n",
    "             f\"{max(100 * acc[n] for n in below):g}%. WikiText-2 bits per byte are lowest at R = 3 for both \"\n",
    "             \"0.6B models. [exp]\")\n",
    "    lib.md(text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87b31d54",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if others:\n",
    "    assert len(beyond) == 8 and no_gain == list(beyond) and level == [\"ar06-R4-cycle\"]\n",
    "    assert all(beyond[n][\"ci95\"][1] < 0 for n in beyond if n not in level)\n",
    "    assert len(below) == 5 and all(acc[n] == 0 for n in below)\n",
    "    assert lowest_bpb == {\"ar06\": \"ar06-R3\", \"pn06\": \"pn06-R3\"}\n",
    "assert lib.quote_check(lib.DIGEST, \"whose queries for the unseen depths R = 5–8 are newly initialised and trained on 0.5B tokens with the rest frozen\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34272d9a",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if others:\n",
    "    P = lib.PALETTE\n",
    "\n",
    "    def series(m, rule):\n",
    "        \"\"\"(R, run) for model m: plain runs up to R = 3, runs with the given rule beyond (PreNorm needs none).\"\"\"\n",
    "        return sorted((parse(n)[1], n) for n in acc if parse(n) and parse(n)[0] == m\n",
    "                      and ((parse(n)[1] <= 3 and not parse(n)[2]) or (parse(n)[1] > 3 and parse(n)[2] == rule)))\n",
    "\n",
    "    LINES = [(\"ar06\", \"repeat\", \"ARLoop-0.6B, repeat\", P[\"ar\"], \"-\", \"o\"),\n",
    "             (\"ar06\", \"cycle\", \"ARLoop-0.6B, cycle\", P[\"ar\"], \":\", \"o\"),\n",
    "             (\"ar12\", \"repeat\", \"ARLoop-1.2B, repeat\", lib.tint(P[\"ar\"], 0.55), \"-\", \"s\"),\n",
    "             (\"pn06\", \"\", \"PreNormLoop-0.6B\", P[\"pn\"], \"-\", \"o\")]\n",
    "    fig, axes = lib.figure(1, 2, figsize=(9.5, 3.3))\n",
    "    for ax, table, title, scale in ((axes[0], acc, \"GSM8K accuracy (%)\", 100),\n",
    "                                    (axes[1], bpb, \"WikiText-2 bits per byte\", 1)):\n",
    "        lib.style(ax)\n",
    "        for m, rule, label, color, ls, marker in LINES:\n",
    "            points = [(R, scale * table[n]) for R, n in series(m, rule) if table.get(n) is not None]\n",
    "            if len(points) > 1 and (rule != \"cycle\" or any(R > 3 for R, _ in points)):\n",
    "                ax.plot(*zip(*points), ls=ls, marker=marker, ms=4.5, lw=1.8, color=color, label=label)\n",
    "        ax.axvline(3, color=P[\"neutral\"], lw=0.8, ls=\"--\")\n",
    "        ax.set_xlabel(\"loops R at inference (trained: R = 3)\")\n",
    "        ax.set_title(title, fontsize=10)\n",
    "    axes[0].legend(frameon=False, fontsize=8, labelcolor=P[\"ink\"])\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n",
    "    lib.md(\"*GSM8K accuracy and WikiText-2 bits per byte against the number of loops, from `runs/e1/summary.json`; \"\n",
    "           \"the dashed line marks the trained R = 3. Beyond it ARLoop runs under a declared rule for its missing \"\n",
    "           \"routing parameters (`repeat` or `cycle`).*\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dacccdbd",
   "metadata": {},
   "source": [
    "The paper's own extrapolation study (App. D.2) used other models: full-history 140M/370M ARLoops\n",
    "trained with a per-sequence Poisson recurrence ($R \\le 4$), whose queries for the unseen depths\n",
    "$R = 5, \\dots, 8$ were newly initialised and trained on 0.5B tokens with the rest frozen **[paper]**.\n",
    "The released fixed-$R$ sliding-window models were not swept there (finding F4 of the digest); the\n",
    "table above is that sweep, under inference-only routing rules. Stage 1c trains the\n",
    "routing of a fourth loop instead ({doc}`stage1`).\n",
    "\n",
    "## E1.4 — where does ARLoop's router look?\n",
    "\n",
    "The probe records the depth-attention weights of ARLoop-0.6B for every routing call (mean over\n",
    "tokens of 64 GSM8K questions) and the norms and cosine similarities of the residual sources at the\n",
    "read-out; for PreNormLoop-0.6B it records the norm of the residual stream at the end of each loop."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b9e4ef9",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "cfg = lib.config(\"ARLoop-0.6B\")\n",
    "calls = lib.schedule(cfg)\n",
    "ra = lib.read_json(E1 / \"routing\" / \"ar06-R3\" / \"routing.json\")\n",
    "if ra is None or \"routing\" not in ra:\n",
    "    lib.pending(\"E1.4 (ARLoop-0.6B)\", \"`runs/e1/routing/ar06-R3/routing.json` is not there yet.\")\n",
    "else:\n",
    "    rec = ra[\"routing\"]\n",
    "    match = [r[\"sources\"] == c[\"ids\"] for r, c in zip(rec, calls)]\n",
    "    w0 = rec[0][\"weights\"]\n",
    "    emb = np.array(ra[\"embedding_share\"])\n",
    "    loops = [emb[1:36].mean(), emb[36:72].mean(), emb[72:108].mean()]   # call 0 is inert (F8): left out\n",
    "    embn = np.array(ra[\"embedding_share_norm_weighted\"]) if ra.get(\"embedding_share_norm_weighted\") else None\n",
    "    lib.md(f\"Routing calls recorded: {len(rec)} over {ra['n_prompts']} prompts. **Source sets:** the \"\n",
    "           f\"recorded sources agree with the replayed schedule of {{doc}}`../mechanism/m1_window` at \"\n",
    "           f\"{sum(match)} of {len(calls)} calls. **Call 0** (inert by construction, finding F8; left out of the \"\n",
    "           f\"per-loop means below): weights \"\n",
    "           f\"{', '.join(f'{w:.4f}' for w in w0)}. **Weight on the embedding source**, mean per loop: \"\n",
    "           f\"{', '.join(f'{x:.3f}' for x in loops)}; at the read-out {emb[-1]:.3f}\" +\n",
    "           (\"\" if embn is None else\n",
    "            f\". Weighted by the norm of each source (the mixture is taken before the norm, so \"\n",
    "            f\"weight × norm measures the contribution): {', '.join(f'{embn[a:b].mean():.3f}' for a, b in ((1, 36), (36, 72), (72, 108)))}\"\n",
    "            f\" per loop, {embn[-1]:.3f} at the read-out\") + \". [exp]\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83609e84",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ra is not None and \"routing\" in ra:\n",
    "    assert len(rec) == len(calls) == 109 and len(emb) == 109\n",
    "    assert all(abs(sum(r[\"weights\"]) - 1) < 1e-4 for r in rec)\n",
    "    assert all(abs(e - r[\"weights\"][0]) < 1e-12 for e, r in zip(emb, rec))\n",
    "    assert len(w0) == len(rec[0][\"sources\"])\n",
    "    if embn is not None:\n",
    "        assert len(embn) == 109 and all(abs(sum(r[\"norm_weighted\"]) - 1) < 1e-4 for r in rec)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce441f97",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ra is not None and \"routing\" in ra and all(match):\n",
    "    from matplotlib.colors import LinearSegmentedColormap\n",
    "\n",
    "    rows = [\"e\", \"b1\", \"b2\", \"b3\", \"b4\", \"b5\", \"p\"]\n",
    "    W = np.full((len(rows), len(calls)), np.nan)\n",
    "    for r, c in zip(rec, calls):\n",
    "        for label, w in zip(c[\"labels\"], r[\"weights\"]):\n",
    "            W[rows.index(label), c[\"call\"]] = w\n",
    "    P = lib.PALETTE                                    # ARLoop's routing: an indigo ramp, light to dark\n",
    "    ramp = LinearSegmentedColormap.from_list(\"ar\", [lib.tint(P[\"ar\"], t) for t in (0.08, 0.35, 0.65, 1.0)])\n",
    "    ramp.set_bad(P[\"paper\"])\n",
    "    fig, ax = lib.figure(figsize=(9, 2.8))\n",
    "    lib.style(ax, grid=None)\n",
    "    im = ax.imshow(W, aspect=\"auto\", interpolation=\"nearest\", cmap=ramp, vmin=0, vmax=1)\n",
    "    ax.set_yticks(range(len(rows)), [\"e (embedding)\", \"b1\", \"b2\", \"b3\", \"b4\", \"b5\", \"p (partial)\"], fontsize=8)\n",
    "    ax.set_xticks([0, 18, 36, 54, 72, 90, 108])\n",
    "    ax.set_xlabel(\"routing call s (108 = read-out); blank = not read\")\n",
    "    for b in (35.5, 71.5):\n",
    "        ax.axvline(b, color=P[\"ink\"], lw=0.8)\n",
    "    for side in (\"top\", \"right\", \"left\", \"bottom\"):\n",
    "        ax.spines[side].set_visible(False)\n",
    "    ax.tick_params(length=0)\n",
    "    cb = fig.colorbar(im, ax=ax, fraction=0.03, pad=0.01)\n",
    "    cb.ax.tick_params(colors=P[\"neutral\"], labelsize=8)\n",
    "    cb.set_label(\"mean routing weight\", color=P[\"neutral\"], fontsize=8)\n",
    "    cb.outline.set_visible(False)\n",
    "    fig.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cef4921f",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "def cos2(c):\n",
    "    s = f\"{c:.2f}\"\n",
    "    return \"0.00\" if s == \"-0.00\" else s.replace(\"-\", lib.MINUS)\n",
    "\n",
    "\n",
    "if ra is not None and \"routing\" in ra:\n",
    "    P = lib.PALETTE\n",
    "    fig, ax = lib.figure(figsize=(8.5, 2.7))\n",
    "    lib.style(ax)\n",
    "    ax.plot(range(len(emb)), emb, color=P[\"ar\"], lw=1.6, label=\"softmax weight on the embedding source\")\n",
    "    if embn is not None:\n",
    "        ax.plot(range(len(embn)), embn, color=P[\"ar\"], lw=1.4, ls=\":\", label=\"share weighted by the source norms\")\n",
    "    for b in (36, 72):\n",
    "        ax.axvline(b, color=P[\"neutral\"], lw=0.8, ls=\"--\")\n",
    "    ax.set_xlabel(\"routing call (dashed lines separate the loops; 108 = read-out)\")\n",
    "    ax.set_ylabel(\"weight on the embedding\")\n",
    "    ax.legend(frameon=False, fontsize=8, labelcolor=P[\"ink\"])\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n",
    "rp = lib.read_json(E1 / \"routing\" / \"pn06-R3\" / \"routing.json\")\n",
    "if rp is None:\n",
    "    lib.pending(\"E1.4 (PreNormLoop-0.6B)\", \"`runs/e1/routing/pn06-R3/routing.json` is not there yet.\")\n",
    "else:\n",
    "    lib.md(\"**Norm of the residual stream of PreNormLoop-0.6B** (mean over tokens and prompts) at the \"\n",
    "           \"embedding and at the end of each loop: \" +\n",
    "           \", \".join(f\"{x:.1f}\" for x in rp[\"norms\"]) + \". [exp]\")\n",
    "if ra is not None and \"norms\" in ra:\n",
    "    names = [\"e\", \"b1\", \"b2\", \"b3\", \"b4\", \"b5\", \"p\"]\n",
    "    lib.md(\"**ARLoop-0.6B's residual sources at the read-out** (embedding, the five committed blocks, the \"\n",
    "           \"partial block): mean norm and mean token-wise cosine similarity. [exp]\\n\\n\" +\n",
    "           lib.table([(n, f\"{ra['norms'][i]:.1f}\", *[cos2(c) for c in ra[\"cosine\"][i]])\n",
    "                      for i, n in enumerate(names)],\n",
    "                     [\"source\", \"norm\", *names]))\n",
    "    # item: the conclusions of E1.4, computed from the same files\n",
    "    cs = ra[\"cosine\"]\n",
    "    first = [cs[1][3], cs[3][5], cs[1][5]]                       # b1-b3, b3-b5, b1-b5: first halves of the loops\n",
    "    second = cs[2][4]                                            # b2-b4: second halves\n",
    "    across = [cs[i][j] for i in (1, 3, 5) for j in (2, 4)]       # first against second halves\n",
    "    ratio = [emb[a:b].mean() / embn[a:b].mean() for a, b in ((1, 36), (36, 72), (72, 108))] if embn is not None else None\n",
    "    lib.md(f\"**Reading** (descriptive). Blocks of the same half of different loops are nearly parallel (first halves \"\n",
    "           f\"{min(first):.2f}–{max(first):.2f}, second halves {second:.2f}), blocks of different halves are not \"\n",
    "           f\"({min(across):.2f}–{max(across):.2f}): the loops write similar blocks, which supports the paper's \"\n",
    "           \"explanation of why a short window is enough.\" +\n",
    "           (\"\" if ratio is None else\n",
    "            f\" Softmax weights overstate the embedding's role {min(ratio):.0f} to {max(ratio):.0f} times: weighted by \"\n",
    "            \"the norms, its contribution is small, so the window does not act as a strong input injection.\") + \" [exp]\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97ceb72c",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if rp is not None:\n",
    "    assert len(rp[\"norms\"]) == 1 + 3 and len(rp[\"cosine\"]) == 4\n",
    "if ra is not None and \"norms\" in ra:\n",
    "    assert len(ra[\"norms\"]) == 7 and len(ra[\"cosine\"]) == 7\n",
    "    assert min(first) > 0.8 and second > 0.75 and max(abs(x) for x in across) < 0.15    # \"nearly parallel ... not\"\n",
    "    if ratio is not None:\n",
    "        assert all(3 < r < 7 for r in ratio)                                                # \"overstate ... times\"\n",
    "    assert lib.quote_check(lib.DIGEST, \"Softmax weights overstate the\", \"the window does not act as a strong input injection\",\n",
    "                           \"This supports the paper's redundancy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1-r4-md",
   "metadata": {},
   "source": [
    "### One loop too many: where the read-out reads at R = 4\n",
    "\n",
    "Past the trained depth the two 0.6B models can also be compared with each other, at the same $R$.\n",
    "This comparison was added after the R = 4 accuracies had been seen, so it is exploratory and has no\n",
    "registered rule (`experiments/e1_release/PROTOCOL.md`, additions after full runs). **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1-r4-code",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "expl = {k.split(\": \", 1)[1]: p for k, p in pairs.items() if k.startswith(\"exploratory: \")}\n",
    "if not expl:\n",
    "    lib.pending(\"exploratory comparison\", \"no ARLoop-0.6B vs PreNormLoop-0.6B comparison beyond R = 3 in `runs/e1/summary.json` yet.\")\n",
    "else:\n",
    "    rows = []\n",
    "    for k, p in expl.items():\n",
    "        x, y = k.split(\" vs \")\n",
    "        rows.append((parse(x)[1], parse(x)[2], pct(acc[x]), pct(acc[y]), f\"{pts(p['diff'])} {ci(p)}\",\n",
    "                     lib.pvalue(p[\"mcnemar_p\"])))\n",
    "    r4 = {parse(k.split(\" vs \")[0])[2]: p for k, p in expl.items() if parse(k.split(\" vs \")[0])[1] == 4}\n",
    "    late = [acc[n] for k in expl for n in k.split(\" vs \") if parse(n)[1] > 4]\n",
    "    drop = {\"repeat\": acc[\"ar06-R3\"] - acc[\"ar06-R4-repeat\"], \"cycle\": acc[\"ar06-R3\"] - acc[\"ar06-R4-cycle\"],\n",
    "            \"pn\": acc[\"pn06-R3\"] - acc[\"pn06-R4\"]}\n",
    "    lib.md(lib.table(rows, [\"R\", \"ARLoop rule\", \"ARLoop-0.6B (%)\", \"PreNormLoop-0.6B (%)\",\n",
    "                            \"ARLoop − PreNormLoop (points, 95% interval)\", \"McNemar p\"]) +\n",
    "           f\"\\n\\nFrom R = 3 to R = 4 ARLoop-0.6B loses {100 * drop['repeat']:.2f} points with `repeat` and \"\n",
    "           f\"{100 * drop['cycle']:.2f} with `cycle`, PreNormLoop-0.6B {100 * drop['pn']:.2f}. At R = 4 ARLoop-0.6B is \"\n",
    "           f\"therefore ahead by {pts(r4['repeat']['diff'])} points (`repeat`) and {pts(r4['cycle']['diff'])} (`cycle`), \"\n",
    "           f\"against {pts(pairs[KEY]['diff'])} at R = 3: level gaps, not a gain from the extra loop. \"\n",
    "           f\"At R = 5 and 6 both models collapse (at most {100 * max(late):.2f}% for either).\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5116df6",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if expl:\n",
    "    assert set(r4) == {\"repeat\", \"cycle\"} and all(p[\"ci95\"][0] > 0 for p in r4.values())\n",
    "    assert len(late) == 4 and max(late) < 0.03\n",
    "    assert all(v > 0 for v in drop.values()) and drop[\"pn\"] > drop[\"repeat\"] > drop[\"cycle\"]      # \"loses ...\"\n",
    "    for rule in (\"repeat\", \"cycle\"):                                                            # level gaps add up\n",
    "        assert abs(r4[rule][\"diff\"] - (pairs[KEY][\"diff\"] + drop[\"pn\"] - drop[rule])) < 1e-9\n",
    "    for k, p in expl.items():\n",
    "        x, y = k.split(\" vs \")\n",
    "        assert parse(y) == (\"pn06\", parse(x)[1], \"\") and abs(p[\"acc_a\"] - acc[x]) < 1e-12 and abs(p[\"acc_b\"] - acc[y]) < 1e-12\n",
    "        assert abs(p[\"mcnemar_p\"] - lib.mcnemar_exact(p[\"only_a\"], p[\"only_b\"])) < 1e-12"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "207a6b28",
   "metadata": {},
   "source": [
    "A routing probe is consistent with these gaps (exploratory: descriptive, the same 64 prompts, not\n",
    "independently re-checked): ARLoop-0.6B at R = 4 under each rule for the missing routing parameters\n",
    "(queries and norms). The read-out's query is the trained one in every case; what changes is what\n",
    "loop 4 writes. The table gives the read-out's softmax weight on loop 3's last block (the open block at\n",
    "R = 3, the committed block $b_6$ at R = 4) and on loop 4's two blocks ($b_7$ and the open block), next\n",
    "to the GSM8K accuracy of the same configuration. **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5da54c7",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "probe = {name: lib.read_json(E1 / \"routing\" / name / \"routing.json\") for name in (\"ar06-R3\", \"ar06-R4-cycle\", \"ar06-R4-repeat\")}\n",
    "if any(v is None for v in probe.values()) or any(k not in acc for k in probe):\n",
    "    lib.pending(\"R = 4 routing probe\", \"needs `runs/e1/routing/ar06-R4-{cycle,repeat}/routing.json` and the matching GSM8K runs.\")\n",
    "else:\n",
    "    rows = []\n",
    "    for name, d in probe.items():\n",
    "        R = d[\"model\"][\"loops\"]\n",
    "        out = d[\"routing\"][-1]                               # the read-out call\n",
    "        assert len(d[\"routing\"]) == 36 * R + 1 and abs(sum(out[\"weights\"]) - 1) < 1e-3\n",
    "        w = dict(zip(out[\"sources\"], out[\"weights\"]))\n",
    "        assert max(w) == 2 * R                               # the open block is the last source\n",
    "        last3 = w.get(6, 0.0)                                # loop 3's second block\n",
    "        new = sum(x for b, x in w.items() if b > 6)          # loop 4's blocks (R = 4 only)\n",
    "        rows.append((R, d[\"model\"].get(\"rule\") or \"trained\", f\"{100 * last3:.1f}%\",\n",
    "                     f\"{100 * new:.1f}%\" if R > 3 else \"–\", f\"{100 * acc[name]:.2f}%\", d[\"job_id\"]))\n",
    "    lib.md(lib.table(rows, [\"loops R\", \"routing\", \"read-out on loop 3's last block\", \"on loop 4's blocks\",\n",
    "                            \"GSM8K\", \"probe job\"]))\n",
    "    cyc, rep = probe[\"ar06-R4-cycle\"][\"routing\"][-1], probe[\"ar06-R4-repeat\"][\"routing\"][-1]\n",
    "    assert dict(zip(cyc[\"sources\"], cyc[\"weights\"]))[6] > dict(zip(rep[\"sources\"], rep[\"weights\"]))[6]\n",
    "    lib.md(\"With `cycle` the read-out keeps reading loop 3's last block, and the accuracy stays at its R = 3 \"\n",
    "           \"level: under `cycle` it routes around the extra loop. With `repeat`, loop 4's blocks take a large share of \"\n",
    "           \"the read-out's weight, and the accuracy drops. PreNormLoop has no such switch: every update enters its \"\n",
    "           \"stream with weight 1.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd526bed",
   "metadata": {},
   "source": [
    "## Receipts\n",
    "\n",
    "Every run directory carries a `receipt.json`: job, node, GPU, versions, seconds, source hashes and,\n",
    "since the BOS correction, whether BOS was prepended, as measured on an encoded probe. The table\n",
    "lists them as found."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ef6bf43",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if not receipts:\n",
    "    lib.pending(\"receipts\", \"no `receipt.json` under `runs/e1/` yet.\")\n",
    "else:\n",
    "    rows, gpus = [], set()\n",
    "    for path in receipts:\n",
    "        r = json.loads(path.read_text())\n",
    "        m = r.get(\"model\") or {}\n",
    "        v = r.get(\"versions\") or {}\n",
    "        bos = {True: \"yes\", False: \"no\"}.get(r.get(\"bos_prepended\"), \"not measured\")\n",
    "        rows.append((f\"`{path.parent.relative_to(E1)}`\", r.get(\"task\", \"–\"), m.get(\"name\", \"–\"), m.get(\"loops\", \"–\"),\n",
    "                     m.get(\"rule\") or \"–\", bos, f\"{r['n_samples']:,}\" if isinstance(r.get(\"n_samples\"), int) else \"–\",\n",
    "                     r.get(\"job_id\", \"–\"), r.get(\"gpu\", \"–\"), r.get(\"seconds\", \"–\"),\n",
    "                     f\"torch {v.get('torch', '?')}, lm-eval {v.get('lm_eval', '?')}\"))\n",
    "    gpus = {row[8] for row in rows}\n",
    "    header = [\"run\", \"task\", \"model\", \"R\", \"rule\", \"BOS prepended (measured)\", \"sample records\", \"job\", \"GPU\",\n",
    "              \"seconds\", \"versions\"]\n",
    "    if len(gpus) == 1:                         # one GPU for every run: named once, not in every row\n",
    "        rows = [row[:8] + row[9:] for row in rows]\n",
    "        header = header[:8] + header[9:]\n",
    "    lib.md((f\"Every run used one {next(iter(gpus))}.\\n\\n\" if len(gpus) == 1 else \"\") +\n",
    "           lib.table(rows, header) +\n",
    "           \"\\n\\nA GSM8K run records every item once per answer filter (strict and flexible), so its sample records \"\n",
    "           \"are twice the number of items.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a70ed7d1",
   "metadata": {},
   "source": [
    "## Independent re-check\n",
    "\n",
    "In this project a result counts as established only after an independent re-check: a separate\n",
    "recount from the raw records, with code that does not reuse the analysis script."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8a0ea6a",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "RECHECK = E1 / \"referee.md\"\n",
    "recheck = RECHECK.read_text() if RECHECK.exists() else None\n",
    "if recheck is None:\n",
    "    lib.note(\"Not yet re-checked\", \"These numbers come straight from the run files; the independent re-check \"\n",
    "             \"(`runs/e1/referee.md`) is not there yet.\", \"warning\")\n",
    "else:\n",
    "    verdicts = [(name, detail.strip().rstrip(\".\")) for name, detail in\n",
    "                re.findall(r\"^- \\*\\*(E1\\.\\d|BOS control) ESTABLISHED:?(.*?)\\*\\*\", recheck, re.M)]\n",
    "    lib.note(\"Independent re-check\", f\"`{lib.rel(RECHECK)}`: every item re-scored from the raw generations and \"\n",
    "             \"every paired comparison recomputed with separate code. Established: \" +\n",
    "             \"; \".join(f\"{n} ({d})\" if d else n for n, d in verdicts) +\n",
    "             \". The routing probe (E1.4) is descriptive and was not re-checked.\", \"important\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1915070a",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if recheck is not None:\n",
    "    assert [n for n, _ in verdicts] == [\"E1.1\", \"E1.2\", \"E1.3\", \"BOS control\"]\n",
    "    assert lib.quote_check(RECHECK, \"does not import or reuse `analyze.py`\",\n",
    "                           \"Every item is re-scored from the raw generation\",\n",
    "                           \"every paired comparison in `runs/e1/summary.json` has the same difference\",\n",
    "                           \"Not re-checked here: E1.4 routing\")"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
