{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "54e11151",
   "metadata": {},
   "source": [
    "# E2: the canary with attention over depth\n",
    "\n",
    "`latent`'s *canary* is a tiny looped model trained from scratch on a toy proof task: a cheap early\n",
    "warning before larger runs. E2 asks whether replacing its recurrence by ARLoop-style attention\n",
    "residuals changes how many **Lean-checked** certificates it writes, and how that number depends on\n",
    "the number of loops $R$ at test time (the protocol and the code write $r$; these notes write $R$\n",
    "throughout). The protocol (`experiments/e2_small/PROTOCOL.md`) was written\n",
    "before any E2 code ran. Everything below is computed from the run's raw files while the book is\n",
    "built."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58f33e3b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib, re, json\n",
    "from collections import defaultdict\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",
    "\n",
    "PROT = lib.PROTOCOL[\"E2\"]\n",
    "REFEREE = lib.RUNS / \"e2\" / \"referee.md\"\n",
    "referee = REFEREE.read_text() if REFEREE.exists() else None\n",
    "job = re.search(r\"job (\\d+)\", referee).group(1) if referee else None\n",
    "RES = lib.REPO / \"experiments\" / \"e2_small\" / \"results\" / job if job else None\n",
    "ready = bool(RES and (RES / \"summary.json\").exists() and (RES / \"analysis.json\").exists())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ecbd3a2",
   "metadata": {},
   "source": [
    "## The protocol in brief\n",
    "\n",
    "* **Task.** The `latent` addition-certificate canary: prompt `a+b=`, the model writes a compact\n",
    "  certificate (`c|r…rz;`), which is compiled and checked by the pinned Lean checker\n",
    "  `peano_lab_verify`. Splits: 93 training identities; tests iid (35), ood_depth (64, more successor\n",
    "  steps than ever seen in training) and ood_operand (32).\n",
    "* **Training.** Identical for every arm: 1,000 AdamW updates, width 64, three seeds (11, 29, 47).\n",
    "  The training recurrence is random, $R = 1 + \\text{Poisson}(\\lambda)$ with $\\lambda$ drawn from a\n",
    "  log-normal with mean 3 and log-sd 0.5, capped at 16; backpropagation is truncated to the last 4\n",
    "  applications of the core. At a given seed every loop arm sees the same batches and the same\n",
    "  sequence of $R$.\n",
    "* **Arms.** `latent-recurrent` (latent's model, unchanged: sandwich-norm core with an input-injection\n",
    "  adapter), `prenorm-loop` (a PreNorm core, no injection), `arloop-untied` (attention residuals over\n",
    "  depth with one query per effective sublayer, as in the paper, one residual block per core\n",
    "  application, window of 3 plus the embedding), `arloop-tied` (the same with the queries shared\n",
    "  across loops, **our variant**, defined for any $R$), and two untied controls\n",
    "  (`standard-parameter`, `standard-depth`).\n",
    "* **Evaluation.** Greedy decoding at $R \\in \\{1, 2, 4, 8, 16\\}$; the metric is the number of\n",
    "  certificates accepted by Lean. **Effect rule** (pre-registered): a paired 95% interval that\n",
    "  excludes 0 *and* the same non-zero sign in all three seeds; anything else is \"no effect detected\n",
    "  at this scale\". Evidence tier T4 (discovery). **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57a96b0a",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT, \"Splits from `data.examples()`: train 93, iid 35, ood_depth 64 (b in 8..11), ood_operand 32\",\n",
    "                       \"Seeds: **11, 29, 47**\", \"1,000 AdamW updates\", \"Width 64\",\n",
    "                       \"the last k = min(4, r) core applications carry gradients\",\n",
    "                       \"training recurrence r = 1 + Poisson(lognormal, mean 3, log-sd 0.5), capped at 16\",\n",
    "                       \"Loop arms at r ∈ {1, 2, 4, 8, 16}\",\n",
    "                       \"**Candidate effect (T4 discovery):** the 95 % interval excludes 0 **and** the per-seed differences have the same non-zero sign in all three seeds\",\n",
    "                       \"**Our variant, not the paper's.**\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7575789e",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if not ready:\n",
    "    lib.pending(\"E2 results\", \"The refereed result files of E2 (`runs/e2/referee.md` and \"\n",
    "                \"`experiments/e2_small/results/<job>/`) are not there yet; this page shows no numbers.\")\n",
    "else:\n",
    "    receipt = json.loads((RES / \"receipt.json\").read_text())\n",
    "    summary = json.loads((RES / \"summary.json\").read_text())\n",
    "    analysis = json.loads((RES / \"analysis.json\").read_text())\n",
    "    lib.md(f\"**Run.** WMI job {receipt['job_id']} ({receipt['slurm']['State'].lower()}, \"\n",
    "           f\"{receipt['gpu_seconds']} GPU-seconds) on one {receipt['device']}, torch {receipt['torch']}; \"\n",
    "           f\"checker `peano_lab_verify` SHA-256 `{receipt['verifier_sha256'][:12]}…`; seeds \"\n",
    "           f\"{', '.join(map(str, receipt['seeds']))}. Files: `{lib.rel(RES)}/`.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5101548b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    assert receipt[\"job_id\"] == job and receipt[\"seeds\"] == [11, 29, 47] and receipt[\"status\"] == \"completed\"\n",
    "    assert summary[\"split_sizes\"] == {\"train\": 93, \"iid\": 35, \"ood_depth\": 64, \"ood_operand\": 32}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fb06f26",
   "metadata": {},
   "source": [
    "## Lean-accepted certificates\n",
    "\n",
    "Recounted here from the raw prediction files (`<arm>-seed<seed>/predictions-r<r>.jsonl`): a\n",
    "certificate counts as accepted when the record says `lean_accepted` **and** the checker exited\n",
    "with code 0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8ff0379",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "SPLITS = (\"iid\", \"ood_depth\", \"ood_operand\")\n",
    "LOOP_ARMS = (\"latent-recurrent\", \"prenorm-loop\", \"arloop-untied\", \"arloop-tied\")\n",
    "CONTROLS = (\"standard-parameter\", \"standard-depth\")\n",
    "if ready:\n",
    "    seeds = summary[\"config\"][\"seeds\"]\n",
    "    rs = summary[\"config\"][\"evaluation_recurrences\"]\n",
    "    records = {}                                       # (arm, seed, r) -> {(split, a, b): accepted}\n",
    "    consistent = True\n",
    "    for arm in LOOP_ARMS + CONTROLS:\n",
    "        for seed in seeds:\n",
    "            for r in (rs if arm in LOOP_ARMS else [None]):\n",
    "                rows = [json.loads(line) for line in\n",
    "                        (RES / f\"{arm}-seed{seed}\" / f\"predictions-r{r}.jsonl\").read_text().splitlines() if line.strip()]\n",
    "                acc = {(row[\"split\"], row[\"a\"], row[\"b\"]): int(bool(row[\"lean_accepted\"]) and row[\"verifier_exit\"] == 0)\n",
    "                       for row in rows}\n",
    "                consistent &= all(acc[(row[\"split\"], row[\"a\"], row[\"b\"])] == int(bool(row[\"lean_accepted\"])) for row in rows)\n",
    "                records[(arm, seed, r)] = acc\n",
    "    n_items = {sp: summary[\"split_sizes\"][sp] * len(seeds) for sp in SPLITS}\n",
    "\n",
    "    def count(arm, r, split):\n",
    "        per = [sum(v for k, v in records[(arm, s, r)].items() if k[0] == split) for s in seeds]\n",
    "        return sum(per), per\n",
    "\n",
    "    rows = []\n",
    "    for arm in LOOP_ARMS + CONTROLS:\n",
    "        for r in (rs if arm in LOOP_ARMS else [None]):\n",
    "            cells = []\n",
    "            for sp in SPLITS:\n",
    "                tot, per = count(arm, r, sp)\n",
    "                cells.append(f\"{tot} ({'/'.join(map(str, per))})\")\n",
    "            rows.append((arm, r if r else \"–\", *cells))\n",
    "    lib.md(lib.table(rows, [\"arm\", \"R\", f\"iid (of {n_items['iid']})\", f\"ood_depth (of {n_items['ood_depth']})\",\n",
    "                            f\"ood_operand (of {n_items['ood_operand']})\"]) +\n",
    "           \"\\n\\nCell: total over the three seeds (per seed 11/29/47).\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c85ae1a",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    assert consistent                                  # lean_accepted and exit code 0 never disagree\n",
    "    assert n_items == {\"iid\": 105, \"ood_depth\": 192, \"ood_operand\": 96}\n",
    "    # the recount agrees with the builder's table in every cell\n",
    "    for cell in analysis[\"table\"]:\n",
    "        tot, per = count(cell[\"arm\"], cell[\"r\"], cell[\"split\"])\n",
    "        assert tot == cell[\"total\"] and per == [cell[\"per_seed\"][str(s)] for s in seeds] and cell[\"n\"] == n_items[cell[\"split\"]]\n",
    "    assert len(analysis[\"table\"]) == (4 * len(rs) + 2) * 3\n",
    "    at4 = {arm: count(arm, 4, \"iid\")[0] for arm in LOOP_ARMS}\n",
    "    assert at4 == {\"latent-recurrent\": 14, \"prenorm-loop\": 7, \"arloop-untied\": 10, \"arloop-tied\": 9}\n",
    "    assert all(count(\"latent-recurrent\", r, \"iid\")[0] == 14 for r in rs)\n",
    "    assert all(count(arm, r, \"ood_depth\")[0] == 0 for arm in LOOP_ARMS for r in rs)\n",
    "    assert all(count(arm, None, \"ood_depth\")[0] == 0 for arm in CONTROLS)\n",
    "    assert count(\"standard-parameter\", None, \"iid\")[0] == 11 and count(\"standard-depth\", None, \"iid\")[0] == 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "938a8f98",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    P = lib.PALETTE\n",
    "    # latent's decoder neutral; the PreNorm loop gold; the two ARLoop arms indigo (tied queries: dashed)\n",
    "    STYLE = {\"latent-recurrent\": (P[\"neutral\"], \"-\"), \"prenorm-loop\": (P[\"pn\"], \"-\"),\n",
    "             \"arloop-untied\": (P[\"ar\"], \"-\"), \"arloop-tied\": (P[\"ar\"], \"--\")}\n",
    "    fig, ax = lib.figure(figsize=(7.5, 3.2))\n",
    "    lib.style(ax)\n",
    "    xs = list(range(len(rs)))\n",
    "    for arm in LOOP_ARMS:\n",
    "        color, ls = STYLE[arm]\n",
    "        ys = [count(arm, r, \"iid\")[0] for r in rs]\n",
    "        ax.plot(xs, ys, color=color, ls=ls, lw=2, marker=\"o\", ms=5, mec=P[\"paper\"], mew=1.5, label=arm)\n",
    "    for arm, t in zip(CONTROLS, (0.75, 0.4)):\n",
    "        y = count(arm, None, \"iid\")[0]\n",
    "        ax.axhline(y, color=lib.tint(P[\"neutral\"], t), lw=1.5, label=f\"{arm} (no loop): {y}\")\n",
    "    ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True))\n",
    "    ax.set_xticks(xs, [str(r) for r in rs])\n",
    "    ax.set_xlabel(\"loops R at test time\")\n",
    "    ax.set_ylabel(f\"iid certificates accepted (of {n_items['iid']})\")\n",
    "    ax.set_ylim(0, 16)\n",
    "    ax.legend(frameon=False, fontsize=8, labelcolor=P[\"ink\"], loc=\"upper center\", bbox_to_anchor=(0.5, -0.22), ncol=3)\n",
    "    fig.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffded476",
   "metadata": {},
   "source": [
    "On the iid split at $R = 4$ (the mean training recurrence) Lean accepts 14 of 105 certificates\n",
    "from `latent-recurrent`, 10 from `arloop-untied`, 9 from `arloop-tied` and 7 from\n",
    "`prenorm-loop`; the reference arm accepts 14 at every $R$. No arm, seed or number of loops produces\n",
    "an accepted ood_depth certificate (0 of 192 per arm and $R$). **[exp]**\n",
    "\n",
    "## The pre-registered comparisons\n",
    "\n",
    "The primary family compares each new arm with `latent-recurrent` on iid at $R = 4$ and $R = 16$,\n",
    "paired over (seed, item). The statistics are recomputed here from the prediction files with the\n",
    "protocol's bootstrap (items resampled within each seed, 10,000 draws, seed 20261115)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b08c330",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "def vector(arm, r, split):\n",
    "    return {(s, a, b): v for s in seeds for (sp, a, b), v in records[(arm, s, r)].items() if sp == split}\n",
    "\n",
    "if ready:\n",
    "    primary = []\n",
    "    for arm in (\"prenorm-loop\", \"arloop-untied\", \"arloop-tied\"):\n",
    "        for r in (4, 16):\n",
    "            res = lib.paired_stratified(vector(arm, r, \"iid\"), vector(\"latent-recurrent\", r, \"iid\"), seeds)\n",
    "            primary.append((arm, r, res))\n",
    "    lib.md(lib.table([(f\"{arm} − latent-recurrent\", r, lib.signed(res['diff'], 3),\n",
    "                       f\"[{lib.signed(res['ci95'][0], 3)}, {lib.signed(res['ci95'][1], 3)}]\",\n",
    "                       \"/\".join(lib.signed(v, 0) for v in res[\"per_seed_count_diff\"].values()),\n",
    "                       f\"{res['only_x']}/{res['only_y']}\", lib.pvalue(res['mcnemar_p']),\n",
    "                       \"yes\" if res[\"candidate_effect\"] else \"no\") for arm, r, res in primary],\n",
    "                     [\"comparison (iid)\", \"R\", \"difference\", \"95% interval\", \"per seed (count)\",\n",
    "                      \"discordant\", \"McNemar p\", \"effect rule met\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9af23686",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    builder = {(c[\"x\"], c[\"y\"]): c for c in analysis[\"comparisons\"] if c[\"family\"] == \"primary\"}\n",
    "    assert len(builder) == len(primary) == 6\n",
    "    for arm, r, res in primary:\n",
    "        c = builder[(f\"{arm}@r{r}\", f\"latent-recurrent@r{r}\")]\n",
    "        assert c[\"split\"] == \"iid\" and c[\"n\"] == res[\"n\"] == 105 and c[\"candidate_effect\"] == res[\"candidate_effect\"]\n",
    "        assert abs(c[\"diff\"] - res[\"diff\"]) < 1e-12 and abs(c[\"mcnemar_p\"] - res[\"mcnemar_p\"]) < 1e-12\n",
    "        assert all(abs(u - v) < 1e-12 for u, v in zip(c[\"ci95\"], res[\"ci95\"]))\n",
    "        assert {int(k): v for k, v in c[\"per_seed_count_diff\"].items()} == res[\"per_seed_count_diff\"]\n",
    "    diffs = [res[\"diff\"] for _, _, res in primary]\n",
    "    assert not any(res[\"candidate_effect\"] for _, _, res in primary)\n",
    "    assert all(d < 0 for d in diffs) and all(res[\"ci95\"][0] < 0 <= res[\"ci95\"][1] for _, _, res in primary)\n",
    "    assert (f\"{min(diffs):.3f}\", f\"{max(diffs):.3f}\") == (\"-0.067\", \"-0.038\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac09cd3d",
   "metadata": {},
   "source": [
    "No primary comparison meets the effect rule. All six point estimates are negative (from −0.067 to\n",
    "−0.038 in accuracy, that is the new arms accept fewer certificates than latent's model), and every\n",
    "95% interval contains 0. The recomputation agrees in every field with the experiment's own analysis\n",
    "(`analysis.json`). **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bba7400",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "def run_label(s):\n",
    "    \"\"\"'arm@r4' -> 'arm at R = 4'; a control has no loops ('arm@rNone' -> 'arm').\"\"\"\n",
    "    arm, _, r = s.partition(\"@r\")\n",
    "    return arm if r in (\"\", \"None\") else f\"{arm} at R = {r}\"\n",
    "\n",
    "\n",
    "if ready:\n",
    "    secondary = [c for c in analysis[\"comparisons\"] if c[\"family\"] != \"primary\"]\n",
    "    hits = [c for c in secondary if c[\"candidate_effect\"]]\n",
    "    lib.md(f\"Secondary comparisons (descriptive, uncorrected, read from `analysis.json`): {len(secondary)}, \"\n",
    "           f\"of which {len(hits)} meet the rule:\\n\\n\" +\n",
    "           lib.table([(run_label(c[\"x\"]), run_label(c[\"y\"]), c[\"split\"],\n",
    "                       lib.signed(c['diff'], 3), f\"[{lib.signed(c['ci95'][0], 3)}, {lib.signed(c['ci95'][1], 3)}]\",\n",
    "                       \"/\".join(lib.signed(v, 0) for v in c[\"per_seed_count_diff\"].values())) for c in hits],\n",
    "                     [\"x\", \"y\", \"split\", \"difference\", \"95% interval\", \"per seed\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04b31758",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    assert len(secondary) == 114 and len(hits) == 4\n",
    "    below = [c for c in hits if c[\"y\"].startswith(\"latent-recurrent@\") and not c[\"x\"].startswith(\"latent-recurrent\")\n",
    "             and c[\"diff\"] < 0]                                    # a new arm below latent's decoder\n",
    "    above = [c for c in hits if c[\"x\"].startswith(\"latent-recurrent@\") and c[\"y\"].startswith(\"standard-depth\")\n",
    "             and c[\"diff\"] > 0]                                    # the decoder above the depth-matched control\n",
    "    assert len(below) == 3 and len(above) == 1 and not any(c[\"diff\"] > 0 and not c[\"x\"].startswith(\"latent\")\n",
    "                                                            for c in hits)\n",
    "    for c in secondary:                                # each flag follows the rule from its own fields\n",
    "        signs = {(v > 0) - (v < 0) for v in c[\"per_seed_count_diff\"].values()}\n",
    "        rule = (c[\"ci95\"][0] > 0 or c[\"ci95\"][1] < 0) and len(signs) == 1 and 0 not in signs\n",
    "        assert rule == c[\"candidate_effect\"]\n",
    "    new_arms = (\"prenorm-loop\", \"arloop-untied\", \"arloop-tied\")\n",
    "    assert not any(c[\"x\"].split(\"@\")[0] in new_arms and c[\"diff\"] > 0 for c in hits)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98040336",
   "metadata": {},
   "source": [
    "Among the 114 secondary comparisons four meet the rule: three put a new arm below latent's decoder,\n",
    "one puts the decoder above the depth-matched control, and none favours a new arm. With this many\n",
    "uncorrected tests they are leads at most.\n",
    "\n",
    "## Depth: does $R = 16$ change anything?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a498ca12",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    depth = {}\n",
    "    for arm in LOOP_ARMS:\n",
    "        x, y = vector(arm, 16, \"iid\"), vector(arm, 4, \"iid\")\n",
    "        depth[arm] = (sum(1 for u in x if x[u] > y[u]), sum(1 for u in x if x[u] < y[u]))\n",
    "    lib.md(lib.table([(arm, f\"{a}/{b}\") for arm, (a, b) in depth.items()],\n",
    "                     [\"arm\", \"iid items accepted only at R = 16 / only at R = 4\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f746ee6b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    assert depth[\"latent-recurrent\"] == (0, 0) and depth[\"arloop-tied\"] == (0, 0)\n",
    "    assert all(sum(v) <= 6 for v in depth.values())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bfd7f47",
   "metadata": {},
   "source": [
    "From $R = 4$ to $R = 16$ the reference arm and the tied-query arm accept exactly the same iid\n",
    "items; the two others change on a handful of items in both directions. Sixteen loops bring no\n",
    "detectable gain here. **[exp]**\n",
    "\n",
    "## Where does the read-out look?\n",
    "\n",
    "The experiment's analysis (`analysis.json`) records the routing weights of the read-out query at\n",
    "$R = 16$ (four sources: the embedding source $b_0$ and the three most recent blocks)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22956c7c",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    ro = [x for x in analysis[\"routing\"] if x[\"r\"] == 16]\n",
    "    lib.md(lib.table([(x[\"arm\"], x[\"seed\"], \", \".join(x[\"readout_sources\"]),\n",
    "                       f\"{x['readout_weights'][x['readout_sources'].index('b0')]:.2f}\") for x in ro],\n",
    "                     [\"arm\", \"seed\", \"sources of the read-out\", \"weight on b0\"]) +\n",
    "           \"\\n\\nUniform mixing over four sources would give 0.25.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42f5e270",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    assert len(ro) == 6 and all(len(x[\"readout_sources\"]) == 4 and x[\"readout_sources\"][0] == \"b0\" for x in ro)\n",
    "    b0 = [x[\"readout_weights\"][0] for x in ro]\n",
    "    assert min(b0) < 0.25 < max(b0)                    # no consistent preference for the embedding source"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26b33f06",
   "metadata": {},
   "source": [
    "The weight on the embedding source ranges from below to above the uniform 0.25 across seeds: no\n",
    "consistent preference for the embedding was learned at this scale.\n",
    "\n",
    "## Reproduction of latent's job 284986\n",
    "\n",
    "The unchanged arm is also a reproduction test: `latent-recurrent` and both controls at seeds 11\n",
    "and 29 must give exactly what `latent` recorded in its job 284986."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be6b66b3",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    rep = analysis[\"reproduction\"]\n",
    "    same, total = sum(x[\"identical_records\"] for x in rep), sum(x[\"n\"] for x in rep)\n",
    "    verdict = analysis[\"reproduction_verdict\"]\n",
    "    lib.md(f\"Item records identical to job 284986: **{same:,} of {total:,}** (fields: \"\n",
    "           f\"{verdict['record_fields']}); recurrence histograms identical: \"\n",
    "           f\"{'yes' if verdict['histograms_identical'] else 'no'}; largest difference in the logged loss \"\n",
    "           f\"history: {verdict['loss_history_max_abs_diff']}.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9928d80",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    assert same == total == verdict[\"records_compared\"] == 1834 and verdict[\"records_identical\"]\n",
    "    assert verdict[\"histograms_identical\"] and verdict[\"loss_history_max_abs_diff\"] == 0.0\n",
    "    assert lib.quote_check(REFEREE, \"1,834 / 1,834 item records identical\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa3e4f41",
   "metadata": {},
   "source": [
    "All 1,834 item records (prediction, Lean verdict, checker exit code, certificate hash) are\n",
    "identical to `latent`'s, across two torch versions on the same GPU model. An independent recount\n",
    "(`runs/e2/referee.md`) confirms this. **[exp]**\n",
    "\n",
    "## What E2 says, and what it does not"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60dca8fa",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    lib.note(\"Independent re-check\", f\"`{lib.rel(REFEREE)}`: a separate script recounted every cell from the raw \"\n",
    "             \"prediction files, and the reproduction of `latent` was checked record by record. Verdict: \"\n",
    "             f\"**{lib.recheck_verdict(referee)}**, that is, computational evidence from a small discovery run.\",\n",
    "             \"important\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "049a3270",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    assert lib.recheck_verdict(referee) == \"established as T4 evidence\"\n",
    "    assert lib.quote_check(REFEREE, \"`analyze.py`, from the raw `predictions-r*.jsonl`\",\n",
    "                           \"recomputed with a separate script: every cell of\", \"1,834 / 1,834\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c1f8cdb",
   "metadata": {},
   "source": [
    "At this scale attention over depth does not beat `latent`'s recurrent decoder on Lean-checked\n",
    "certificates, no arm gains detectably from more loops, and no arm generalises to the deeper\n",
    "ood_depth problems. This is \"no effect detected at this scale\", not evidence that attention residuals cannot\n",
    "help: the models are tiny (width 64, 1,000 updates, 93 training identities), the ARLoop arms differ\n",
    "from `latent-recurrent` in more than the residual (no adapter, PreNorm instead of sandwich norm),\n",
    "they have no value residuals (registered in the protocol), which the paper's App. A.1 and A.3 report\n",
    "its sliding window needs, they follow eq. (4) of the paper rather than the released code's first\n",
    "block, and training uses a\n",
    "random recurrence with truncated backpropagation, where the paper trains at a fixed $R$\n",
    "(`experiments/e2_small/RESULTS.md`, \"Caveats\"). The tied-query arm is our own variant. Stage 1b trains\n",
    "the same canary for longer ({doc}`stage1`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52304620",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT, \"Value residuals (used in all ARLoop runs, paper App. A.1) are **not** used\")\n",
    "assert lib.quote_check(lib.DIGEST, \"No arm has value residuals\", \"which the paper's App. A.1 and A.3 report its sliding window needs\")\n",
    "assert lib.quote_check(lib.REPO / \"experiments\" / \"e2_small\" / \"RESULTS.md\",\n",
    "                       \"Tiny scale and budget (width 64, 1000 updates, 93 training identities, 3 seeds)\",\n",
    "                       \"b1 = z1 + z2 as in paper Eq. 4\")"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
