{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4c094377",
   "metadata": {},
   "source": [
    "# Stage 1: the same tests after more training\n",
    "\n",
    "E1, E2 and E3 saw no use of extra loops. In each of them the models were trained little or not at\n",
    "all for the depth being tested: E1 measured the released models at numbers of loops they were never\n",
    "trained at, E2 trained the canary for 1,000 updates on 93 examples, and E3 tuned the 0.6B pair for\n",
    "512 LoRA updates. Stage 1 asks the next question: **if we train more, does looping start to pay\n",
    "off, and does ARLoop's attention over depth widen the effect?** It was approved and run on WMI on\n",
    "15 November 2026, in three parts. Each part has a\n",
    "protocol committed before its runs, and each result on this page passed an independent re-check\n",
    "before it entered these notes."
   ]
  },
  {
   "cell_type": "code",
   "id": "1f29e51f",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "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",
    "\n",
    "EXP = lib.REPO / \"experiments\"\n",
    "CAMPAIGN = lib.REPO / \"CAMPAIGN.md\"                       # the plan of the next experiments\n",
    "PROT_1A = EXP / \"e3_pair\" / \"PROTOCOL-ladder.md\"\n",
    "PROT_1B = EXP / \"e2_small\" / \"PROTOCOL-long.md\"\n",
    "PROT_1C = EXP / \"e1_release\" / \"PROTOCOL-loop4.md\"\n",
    "S1A, S1B, S1C = lib.RUNS / \"s1a\", lib.RUNS / \"s1b\", lib.RUNS / \"s1c\"\n",
    "E2RES = EXP / \"e2_small\" / \"results\"\n",
    "\n",
    "\n",
    "def text_or_none(path):\n",
    "    \"\"\"A part's re-check note, or None: no number of a part is shown before its note exists.\"\"\"\n",
    "    return path.read_text() if path.exists() else None\n",
    "\n",
    "\n",
    "def hms(s):\n",
    "    \"\"\"An sacct Elapsed field, [D-]HH:MM:SS, in seconds.\"\"\"\n",
    "    d, _, t = s.rpartition(\"-\")\n",
    "    h, m, sec = (int(x) for x in t.split(\":\"))\n",
    "    return (int(d) * 86400 if d else 0) + 3600 * h + 60 * m + sec\n",
    "\n",
    "\n",
    "def seq(xs, fmt=\"{}\"):\n",
    "    \"\"\"A comma-separated list of numbers, with typographic minus signs.\"\"\"\n",
    "    return \", \".join(fmt.format(x).replace(\"-\", lib.MINUS) for x in xs)\n",
    "\n",
    "\n",
    "def pct(x):                                    # an accuracy in %, two decimals (as in E1)\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",
    "# 1a: the training ladder (E3's harness and data)\n",
    "BASES, ARMS, LOOPS, RUNGS = (\"arloop\", \"prenorm\"), (\"native3\", \"random124\"), (1, 2, 3, 4), (512, 1024, 2048, 4096)\n",
    "NAME = {\"arloop\": \"ARLoop-0.6B\", \"prenorm\": \"PreNormLoop-0.6B\"}\n",
    "SHORT = {\"arloop\": \"ARLoop\", \"prenorm\": \"PreNorm\"}\n",
    "ref1a = text_or_none(S1A / \"referee.md\")\n",
    "ladder = lib.read_json(S1A / \"ladder.json\")               # written by experiments/e3_pair/analyze_ladder.py\n",
    "rec1a = lib.read_json(S1A / \"referee\" / \"s1a_recount.json\")\n",
    "rep1a = lib.read_json(S1A / \"referee\" / \"s1a_replay.json\")\n",
    "ready1a = all(x is not None for x in (ref1a, ladder, rec1a, rep1a))\n",
    "if ready1a:\n",
    "    cur = {(c[\"base\"], c[\"arm\"], c[\"updates\"], c[\"L\"]): c for c in ladder[\"curves\"]}\n",
    "\n",
    "# 1b: the canary trained longer (E2's code), next to E2's own run\n",
    "ref1b = text_or_none(S1B / \"referee.md\")\n",
    "rec1b = lib.read_json(S1B / \"referee\" / \"s1b_recount.json\")\n",
    "ref_e2 = text_or_none(lib.RUNS / \"e2\" / \"referee.md\")\n",
    "E2_JOB = re.search(r\"job (\\d+)\", ref_e2).group(1) if ref_e2 else None\n",
    "LONG = sorted(k for k in (rec1b or {}) if k.isdigit())    # the jobs that the 1b recount covers\n",
    "JOBS = ([E2_JOB] if E2_JOB else []) + LONG\n",
    "ready1b = bool(ref1b and rec1b and E2_JOB and LONG and all(\n",
    "    (E2RES / j / f).exists() for j in JOBS for f in (\"summary.json\", \"analysis.json\")))\n",
    "LOOP_ARMS = (\"latent-recurrent\", \"prenorm-loop\", \"arloop-untied\", \"arloop-tied\")\n",
    "if ready1b:\n",
    "    SUM = {j: json.loads((E2RES / j / \"summary.json\").read_text()) for j in JOBS}\n",
    "    ANA = {j: json.loads((E2RES / j / \"analysis.json\").read_text()) for j in JOBS}\n",
    "    UPD = {j: SUM[j][\"config\"][\"steps\"] for j in JOBS}\n",
    "\n",
    "# 1c: a trained fourth loop (E1's harness)\n",
    "ARMS_1C = {\"L4\": 4, \"C3\": 3, \"L4e\": 4, \"C3e\": 3}\n",
    "ref1c = text_or_none(S1C / \"referee.md\")\n",
    "loop4 = lib.read_json(S1C / \"loop4.json\")                 # written by experiments/e1_release/analyze_loop4.py\n",
    "rec1c = lib.read_json(S1C / \"referee\" / \"s1c_recount.json\")\n",
    "ready1c = all(x is not None for x in (ref1c, loop4, rec1c))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "9acd7d7f",
   "metadata": {},
   "source": [
    "## What counts as a result of looping\n",
    "\n",
    "The plan (`CAMPAIGN.md`), written before the runs, fixes what *a result of looping* means. It is\n",
    "one of two things, measured paired on the same items:\n",
    "\n",
    "1. **Within a model (sense 1):** in a model trained to work at several depths, accuracy rises with the number\n",
    "   of loops.\n",
    "2. **Between models (sense 2):** a model trained at more loops beats one trained at fewer, on the same data\n",
    "   and the same number of updates or tokens.\n",
    "\n",
    "| part | question | models | measure | protocol |\n",
    "|---|---|---|---|---|\n",
    "| 1a | Does training eight times longer lift E3's pair off the proof floor, and do more loops then help (sense 1)? | ARLoop-0.6B and PreNormLoop-0.6B with LoRA, as in {doc}`e3_proofs` | checked proofs and single steps | `experiments/e3_pair/PROTOCOL-ladder.md` |\n",
    "| 1b | Does the canary use depth when trained 10 and 30 times longer (sense 1)? | E2's six arms and three seeds, as in {doc}`e2_canary` | Lean-checked certificates | `experiments/e2_small/PROTOCOL-long.md` |\n",
    "| 1c | Does a fourth loop pay off once its routing is trained (sense 2)? | ARLoop-0.6B, the routing of one loop only, as in {doc}`e1_release` | GSM8K exact match | `experiments/e1_release/PROTOCOL-loop4.md` |\n",
    "\n",
    "These notes write $R$ for the number of loops throughout; the protocols and the code of 1a write\n",
    "$L$ (a value forced per evaluation suite), those of 1b $r$."
   ]
  },
  {
   "cell_type": "code",
   "id": "ce5a520b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "assert lib.quote_check(CAMPAIGN, \"**E1:** no training at R > 3.\", \"**E2:** 1,000 updates on 93 examples.\",\n",
    "                       \"**E3:** 512 LoRA updates.\",\n",
    "                       \"if we **train more**, does looping start to pay off, and does ARLoop's attention over depth widen the effect?\",\n",
    "                       \"1. In a model trained to work at several depths, accuracy rises with the number of loops.\",\n",
    "                       \"2. A model trained at more loops beats one trained at fewer loops, on the same data and the same \"\n",
    "                       \"number of updates or tokens.\",\n",
    "                       \"In random124 the model is trained to work at several depths.\")\n",
    "for p in (PROT_1A, PROT_1B, PROT_1C):\n",
    "    assert lib.quote_check(p, 'Approved by the speaker (\"start stage 1 now\", 2026-11-15).')\n",
    "assert lib.quote_check(PROT_1A, \"the training ladder (E3's harness, eight times the updates)\")\n",
    "assert lib.quote_check(PROT_1B, \"Does training 10 and 30 times longer:\", \"(sense 1 of `CAMPAIGN.md`)\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "efe8c746",
   "metadata": {},
   "source": [
    "## Proofs: E3's pair trained eight times longer (1a)\n",
    "\n",
    "E3 left both released 0.6B models at the proof floor after 512 LoRA updates ({doc}`e3_proofs`).\n",
    "1a repeats E3 with one change, the length of training (`experiments/e3_pair/PROTOCOL-ladder.md`,\n",
    "registered before any 1a run):\n",
    "\n",
    "* **As in E3:** both bases; both arms, `native3` (every update at $R = 3$) and `random124` ($R$\n",
    "  drawn from $\\{1, 2, 4\\}$ per update, latent's rule); seed 11; the same LoRA, data order, budgets,\n",
    "  harness and checker.\n",
    "* **The change:** the cosine schedule runs to **4,096 updates** instead of 512, with E3's warm-up\n",
    "  (32 updates), peak rate ($5 \\times 10^{-5}$) and floor ($5 \\times 10^{-6}$). The adapters after 1,024 and 2,048 updates are\n",
    "  kept; E3's own 512-update adapters are the first rung of the ladder.\n",
    "* **Evaluation, unchanged:** the 32 development proof targets at forced $R = 1, \\dots, 4$, and the\n",
    "  validity of one generated step on E3's frozen roster of 64 development rows. (Amendment 1 of the\n",
    "  protocol corrected its text, which had said all 1,523 rows; the code was never changed.)\n",
    "  Development split only; the test split stays sealed.\n",
    "* **Rules, fixed in advance.** (1) *Off the floor* if either base's `native3` adapter after 4,096\n",
    "  updates proves at least 3 of the 32 targets at $R = 3$; this is the gate for a confirmatory run.\n",
    "  (2) *More loops help* a base if its `random124` adapter after 4,096 updates makes more valid steps\n",
    "  at $R = 4$ than at $R = 1$, paired by row, with a Holm-adjusted exact McNemar p below 0.05 over\n",
    "  the two bases; proofs at $R = 4$ against $R = 1$ are only described when fewer than 5 targets are\n",
    "  discordant. (3) The learning curves are descriptive. (4) ARLoop against PreNorm is descriptive,\n",
    "  with one seed. Tier T4. **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "id": "69383d41",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "assert lib.quote_check(PROT_1A,\n",
    "                       \"Arms native3 (L = 3) and random124 (L drawn from {1, 2, 4} per update, latent's rule).\",\n",
    "                       \"Seed 11 only.\",\n",
    "                       \"The cosine runs to **4,096 updates** instead of 512. Warm-up (32), peak rate (5e-5), floor \"\n",
    "                       \"(5e-6), batch, LoRA, data order and depth draws are E3's.\",\n",
    "                       \"Adapters are kept after updates 1,024 and 2,048, and the final one after 4,096.\",\n",
    "                       \"E3's 512-update adapters are the ladder's first rung (already evaluated).\",\n",
    "                       \"Dev split only; the test split stays sealed.\",\n",
    "                       \"either base's native3 adapter after 4,096 updates accepts at least 3 of the 32 dev targets at L = 3.\",\n",
    "                       \"Rule 2a reads: single-step validity at L = 4 against L = 1, paired by the 64 roster rows (exact \"\n",
    "                       \"McNemar, two-sided, Holm over the two bases).\",\n",
    "                       \"\\\"More loops help\\\" if validity is higher at L = 4 and the Holm-adjusted p (over the two bases) is \"\n",
    "                       \"below 0.05.\",\n",
    "                       \"Descriptive if fewer than 5 targets are discordant.\",\n",
    "                       \"**ARLoop against PreNorm:** descriptive only, with one seed.\",\n",
    "                       \"The text was wrong about the row set; the code and the jobs are not changed.\",\n",
    "                       \"With 64 rows the test has little power: a null result is not evidence of no effect.\")\n",
    "GATE = int(re.search(r\"accepts at\\s+least (\\d+) of the 32 dev targets at L = 3\", PROT_1A.read_text()).group(1))\n",
    "DESC = int(re.search(r\"Descriptive if fewer than\\s+(\\d+) targets are discordant\", PROT_1A.read_text()).group(1))\n",
    "if ready1a:\n",
    "    receipts = {p.parent.name: json.loads(p.read_text())\n",
    "                for p in sorted((S1A / \"runs\").glob(\"*-s11-ladder/receipt.json\"))}\n",
    "    assert sorted(receipts) == sorted(f\"{b}-{a}-s11-ladder\" for b in BASES for a in ARMS)\n",
    "    for r in receipts.values():                 # the recipe is E3's except the length\n",
    "        rc = r[\"recipe\"]\n",
    "        assert r[\"state\"] == \"completed\" and r[\"steps_completed\"] == rc[\"steps\"] == RUNGS[-1]\n",
    "        assert (rc[\"warmup_steps\"], rc[\"learning_rate\"], rc[\"minimum_learning_rate\"]) == (32, 5e-05, 5e-06)\n",
    "        assert r[\"identity\"][\"seed\"] == 11 and sorted(r[\"kept_adapters\"]) == [str(u) for u in RUNGS[1:-1]]\n",
    "        assert r[\"updated_at\"].startswith(\"2026-11-15\")\n",
    "    full = [d for d in sorted((S1A / \"evals\").iterdir()) if d.is_dir() and not d.name.startswith(\"smoke\")]\n",
    "    T, = {json.loads(p.read_text())[\"targets\"] for d in full for p in d.glob(\"proofs-L*-summary.json\")}\n",
    "    ROWS, = {json.loads(p.read_text())[\"rows\"] for d in full for p in d.glob(\"steps-L*-summary.json\")}\n",
    "    CE_ROWS, = {json.loads(p.read_text())[\"all\"][\"rows\"] for d in full for p in d.glob(\"ce-L*.json\")}\n",
    "    assert len(full) == 12 and (T, ROWS) == (32, 64)\n",
    "    TRAIN_ROWS = json.loads((EXP / \"e3_pair\" / \"results\" / \"data\" / \"c4-smollm2-v1\" / \"audit.json\").read_text()\n",
    "                            )[\"splits\"][\"train\"][\"retained_rows\"]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "8d4423f7",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if not ready1a:\n",
    "    lib.pending(\"Stage 1a\", \"The refereed files of Stage 1a (`runs/s1a/ladder.json`, `runs/s1a/referee.md` and the \"\n",
    "                \"recount and replay in `runs/s1a/referee/`) are not all there yet; this section shows no numbers.\")\n",
    "else:\n",
    "    jobs = [l.split() for l in (S1A / \"sacct.txt\").read_text().splitlines() if l.strip()]\n",
    "    gpu_h = sum(hms(j[4]) for j in jobs if j[2] == \"gpu_csi\") / 3600\n",
    "    gpu, = {r[\"device\"][\"gpu\"] for r in receipts.values()}\n",
    "    n_train = sum(j[1].startswith(\"rc-s1a-train\") for j in jobs)\n",
    "    n_eval = sum(j[1].startswith((\"rc-s1a-eval\", \"rc-s1a-evsnap\")) for j in jobs)\n",
    "    lib.md(f\"**Runs.** {n_train} trainings and {n_eval} evaluation jobs on WMI, each on one {gpu}: \"\n",
    "           f\"{gpu_h:.1f} GPU-hours with the smoke test. All {len(jobs)} jobs of the stage, the analysis included, \"\n",
    "           \"completed with exit code 0. Files: `runs/s1a/`; the 512-update rung is E3's evaluation.\")\n",
    "    rows = [(f\"`{name}`\", f\"{r['steps_completed']:,}\",\n",
    "             \", \".join(f\"R = {k}: {v:,}\" for k, v in sorted(r[\"loops_histogram\"].items())),\n",
    "             f\"{r['train_loss_first8_mean']:.3f} → {r['train_loss_last8_mean']:.3f}\", f\"`{r['adapter_sha256'][:12]}…`\")\n",
    "            for name, r in receipts.items()]\n",
    "    lib.md(\"**Training receipts:**\\n\\n\" + lib.table(rows, [\"run\", \"updates\", \"loops drawn\",\n",
    "                                                           \"train loss, first 8 → last 8 updates\",\n",
    "                                                           \"final adapter SHA-256\"]))\n",
    "    g, r2 = ladder[\"rule1_gate\"], ladder[\"rule2\"]\n",
    "    lib.md(f\"**Rule 1, off the floor: {'yes' if ladder['rule1_off_floor'] else 'no'}.** After {RUNGS[-1]:,} updates the \"\n",
    "           f\"`native3` adapters prove {g['arloop']} (ARLoop) and {g['prenorm']} (PreNorm) of the {T} targets at R = 3; \"\n",
    "           f\"the gate asks for at least {GATE} in either base. **[exp]**\")\n",
    "    rows = [(SHORT[b], f\"{r['steps_valid_L4']} / {r['steps_valid_L1']}\", f\"{r['only_L4']} / {r['only_L1']}\",\n",
    "             f\"{r['mcnemar_p']:.4g}\", f\"{r['holm_p']:.4g}\", \"yes\" if r[\"more_loops_help\"] else \"no\",\n",
    "             f\"{r['proofs_L4']} / {r['proofs_L1']}\") for b, r in ((b, r2[b]) for b in BASES)]\n",
    "    lib.md(f\"**Rule 2, more loops after training** (`random124` after {RUNGS[-1]:,} updates, R = 4 against R = 1):\\n\\n\" +\n",
    "           lib.table(rows, [\"base\", f\"valid steps, R = 4 / R = 1 (of {ROWS})\", \"rows valid only at R = 4 / only at R = 1\",\n",
    "                            \"exact McNemar p\", \"Holm p (two bases)\", \"more loops help (rule 2)\",\n",
    "                            f\"proofs, R = 4 / R = 1 (of {T})\"]) +\n",
    "           f\"\\n\\nThe proofs are only described: fewer than {DESC} targets are discordant in either base. **[exp]**\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "1e99b4ef",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "if ready1a:\n",
    "    # the recount (separate code, raw records) agrees with the analysis in every suite and rule\n",
    "    assert not rec1a[\"mismatches\"] and len(rec1a[\"cells\"]) == len(ladder[\"curves\"]) == 64\n",
    "    assert rec1a[\"gate\"] == g and ladder[\"rule1_off_floor\"] == any(v >= GATE for v in g.values())\n",
    "    for b in BASES:\n",
    "        r = r2[b]\n",
    "        assert (rec1a[\"rule2\"][b][\"only_L4\"], rec1a[\"rule2\"][b][\"only_L1\"]) == (r[\"only_L4\"], r[\"only_L1\"])\n",
    "        assert abs(rec1a[\"holm\"][b] - r[\"holm_p\"]) < 1e-12 and r[\"rows\"] == ROWS\n",
    "        assert abs(r[\"mcnemar_p\"] - lib.mcnemar_exact(r[\"only_L4\"], r[\"only_L1\"])) < 1e-12\n",
    "        assert r[\"more_loops_help\"] == (r[\"steps_valid_L4\"] > r[\"steps_valid_L1\"] and r[\"holm_p\"] < 0.05)\n",
    "        assert r[\"proofs_only_L4\"] + r[\"proofs_only_L1\"] < DESC\n",
    "    ps = sorted((r2[b][\"mcnemar_p\"], b) for b in BASES)          # Holm over the two bases, recomputed\n",
    "    holm = {ps[0][1]: min(1.0, 2 * ps[0][0])}\n",
    "    holm[ps[1][1]] = max(holm[ps[0][1]], min(1.0, ps[1][0]))\n",
    "    assert all(abs(holm[b] - r2[b][\"holm_p\"]) < 1e-12 for b in BASES)\n",
    "    # the replay with the admitted checker confirms every accepted proof, and nothing else\n",
    "    assert not rep1a[\"problems\"] and rep1a[\"qed_total\"] == sum(c[\"accepted\"] for c in ladder[\"curves\"])\n",
    "    for (b, a, u, L), c in cur.items():\n",
    "        assert rep1a[\"cells\"][f\"{b}-{a}-u{u}-L{L}\"][\"replayed_qed\"] == c[\"accepted\"]\n",
    "        assert rec1a[\"cells\"][f\"{b}-{a}-u{u}-L{L}\"][\"accepted\"] == c[\"accepted\"]\n",
    "    # every evaluated adapter is the trained one (training receipts against evaluation records)\n",
    "    for b in BASES:\n",
    "        for a in ARMS:\n",
    "            r = receipts[f\"{b}-{a}-s11-ladder\"]\n",
    "            want = {RUNGS[-1]: r[\"adapter_sha256\"], **{u: r[\"kept_adapters\"][str(u)] for u in RUNGS[1:-1]}}\n",
    "            for u, h in want.items():\n",
    "                d = S1A / \"evals\" / (f\"{b}-{a}-s11-ladder\" + (\"\" if u == RUNGS[-1] else f\"-u{u}\"))\n",
    "                metas = list(d.glob(\"meta-*.json\"))\n",
    "                assert len(metas) == 1 and json.loads(metas[0].read_text())[\"adapter_sha256\"] == h\n",
    "    assert all(j[3] == \"COMPLETED\" and j[5] == \"0:0\" for j in jobs)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "31942837",
   "metadata": {},
   "source": [
    "### Learning curves (rule 3, descriptive)"
   ]
  },
  {
   "cell_type": "code",
   "id": "d9e342af",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if ready1a:\n",
    "    rows = []\n",
    "    for b in BASES:\n",
    "        for a in ARMS:\n",
    "            for u in RUNGS:\n",
    "                cells = [cur[(b, a, u, L)] for L in LOOPS]\n",
    "                rows.append((SHORT[b], f\"`{a}`\", f\"{u:,}\" + (\" (E3)\" if u == RUNGS[0] else \"\"),\n",
    "                             *(f\"{c['accepted']} · {c['accepted_actions_mean']:.1f} · {c['steps_valid']} · {c['ce_all']:.3f}\"\n",
    "                               for c in cells)))\n",
    "    lib.md(lib.table(rows, [\"base\", \"arm\", \"updates\", *(f\"R = {L}\" for L in LOOPS)]) +\n",
    "           f\"\\n\\nCell: accepted proofs (of {T}) · accepted actions per attempt · valid single steps (of {ROWS}) · \"\n",
    "           f\"development cross-entropy (nats per token, over all {CE_ROWS:,} development rows). From \"\n",
    "           \"`runs/s1a/ladder.json`. **[exp]**\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "0be66556",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "source": [
    "if ready1a:\n",
    "    P = lib.PALETTE\n",
    "    HUE = {\"arloop\": P[\"ar\"], \"prenorm\": P[\"pn\"]}               # one hue per base; more training is darker\n",
    "    fig, axes = lib.figure(1, 2, figsize=(7.5, 3.9), sharey=True)\n",
    "    for ax, b in zip(axes, BASES):\n",
    "        lib.style(ax)\n",
    "        for u, color in zip(RUNGS, lib.ramp(HUE[b], len(RUNGS))):\n",
    "            ax.plot(LOOPS, [cur[(b, \"random124\", u, L)][\"ce_all\"] for L in LOOPS], color=color, lw=2, marker=\"o\",\n",
    "                    ms=5, mec=P[\"paper\"], mew=1.5, label=f\"{u:,} updates\")\n",
    "        ax.set_title(f\"{NAME[b]}, random124\", fontsize=10)\n",
    "        ax.set_xticks(LOOPS)\n",
    "        ax.set_xlabel(\"loops R at test time\")\n",
    "        ax.legend(frameon=False, fontsize=7.5, labelcolor=P[\"ink\"], loc=\"upper center\", bbox_to_anchor=(0.5, -0.2), ncol=2)\n",
    "    axes[0].set_ylabel(\"development cross-entropy\\n(nats per token)\")\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n",
    "    lib.md(f\"*Development cross-entropy of the `random124` adapters against the number of loops at test time, one \"\n",
    "           f\"line per rung ({seq(f'{u:,}' for u in RUNGS)} updates, light to dark; the first is E3). From \"\n",
    "           f\"`runs/s1a/ladder.json`.*\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "ee0cd22b",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if ready1a:\n",
    "    nat3 = {b: [cur[(b, \"native3\", u, 3)][\"accepted\"] for u in RUNGS] for b in BASES}\n",
    "\n",
    "    def col(b, a, u, key):\n",
    "        return [cur[(b, a, u, L)][key] for L in LOOPS]\n",
    "\n",
    "    ap, av, ac = (col(\"arloop\", \"random124\", RUNGS[-1], k) for k in (\"accepted\", \"steps_valid\", \"ce_all\"))\n",
    "    pp, pv, pc = (col(\"prenorm\", \"random124\", RUNGS[-1], k) for k in (\"accepted\", \"steps_valid\", \"ce_all\"))\n",
    "    gap = {b: [cur[(b, \"random124\", u, 1)][\"ce_all\"] - cur[(b, \"random124\", u, 4)][\"ce_all\"] for u in RUNGS]\n",
    "           for b in BASES}\n",
    "    low = [cur[(b, \"native3\", u, L)] for b in BASES for u in RUNGS for L in (1, 2)]\n",
    "    ce_low = [c[\"ce_all\"] for c in low]\n",
    "    nat4 = {b: [cur[(b, \"native3\", u, 4)][\"steps_valid\"] for u in RUNGS] for b in BASES}\n",
    "    nat4p = [(b, u, cur[(b, \"native3\", u, 4)][\"accepted\"]) for b in BASES for u in RUNGS\n",
    "             if cur[(b, \"native3\", u, 4)][\"accepted\"]]\n",
    "    ce_nat = {b: (cur[(b, \"native3\", RUNGS[2], 3)][\"ce_all\"], cur[(b, \"native3\", RUNGS[3], 3)][\"ce_all\"]) for b in BASES}\n",
    "    loss = {}                                  # mean training loss over the 64 updates before 2,048 and before 4,096\n",
    "    for b in BASES:\n",
    "        m = [json.loads(l) for l in (S1A / \"runs\" / f\"{b}-native3-s11-ladder\" / \"metrics.jsonl\").read_text().splitlines()\n",
    "             if l.strip()]\n",
    "        by = {x[\"step\"]: x[\"train_loss\"] for x in m}\n",
    "        loss[b] = tuple(sum(by[s] for s in range(e - 63, e + 1)) / 64 for e in RUNGS[2:])\n",
    "    batch = receipts[\"arloop-native3-s11-ladder\"][\"recipe\"][\"effective_batch_size\"]\n",
    "    ar2, pr2 = r2[\"arloop\"], r2[\"prenorm\"]\n",
    "    lib.md(\"\\n\\n\".join([\n",
    "        f\"**Off the floor, in both bases** (rule 1). After {RUNGS[-1]:,} updates the `native3` adapters prove \"\n",
    "        f\"{g['arloop']} (ARLoop) and {g['prenorm']} (PreNorm) of the {T} targets at their trained depth, against \"\n",
    "        f\"{nat3['arloop'][0]} and {nat3['prenorm'][0]} in E3. Along the ladder ({seq(f'{u:,}' for u in RUNGS)} \"\n",
    "        f\"updates) they prove {seq(nat3['arloop'])} and {seq(nat3['prenorm'])}: not monotone, and with one seed and \"\n",
    "        f\"{T} targets one or two proofs are within noise.\",\n",
    "        f\"**More loops after training: not established** (rule 2, the registered measure: single-step validity). \"\n",
    "        f\"ARLoop's `random124` adapter is valid on \"\n",
    "        f\"{ar2['steps_valid_L4']} of {ROWS} rows at R = 4 against {ar2['steps_valid_L1']} at R = 1, and all \"\n",
    "        f\"{ar2['only_L4'] + ar2['only_L1']} discordant rows favour R = 4; but the Holm-adjusted p is {ar2['holm_p']:.4g}, \"\n",
    "        f\"not below 0.05. PreNorm's is valid on {pr2['steps_valid_L4']} against {pr2['steps_valid_L1']} (Holm p = \"\n",
    "        f\"{pr2['holm_p']:.4g}). With {ROWS} rows the test has little power, so this is not evidence of no effect.\",\n",
    "        f\"**Descriptively (one seed, not a registered result), ARLoop's random-depth adapter improves on all three \"\n",
    "        f\"measures as R grows; PreNorm's does not** (rule 3; figure above): a one-seed lead for ARLoop, below the \"\n",
    "        f\"registered threshold. At {RUNGS[-1]:,} updates, from R = 1 to R = 4, ARLoop's adapter proves {seq(ap)} targets, \"\n",
    "        f\"is valid on {seq(av)} rows and has a development cross-entropy of {seq(ac, '{:.3f}')} nats per token. \"\n",
    "        f\"PreNorm's proves {seq(pp)}, is valid on {seq(pv)} rows and has {seq(pc, '{:.3f}')}. The cross-entropy \"\n",
    "        f\"gained from R = 1 to R = 4 stays for ARLoop at every rung ({seq(gap['arloop'], '{:+.3f}')} at \"\n",
    "        f\"{seq(f'{u:,}' for u in RUNGS)} updates), while PreNorm's shrinks and reverses \"\n",
    "        f\"({seq(gap['prenorm'], '{:+.3f}')}).\",\n",
    "        f\"**Between models (sense 2, descriptive).** At R = 4 after {RUNGS[-1]:,} updates, the adapters trained at \"\n",
    "        f\"random depths prove {ap[-1]} (ARLoop) and {pp[-1]} (PreNorm) targets; those trained at R = 3 prove \"\n",
    "        f\"{cur[('arloop', 'native3', RUNGS[-1], 4)]['accepted']} and {cur[('prenorm', 'native3', RUNGS[-1], 4)]['accepted']}.\",\n",
    "        f\"**Trained at one depth, an adapter fails at shallower ones.** The `native3` adapters make no valid step at \"\n",
    "        f\"R = 1 or 2 at any rung, with a development cross-entropy of {min(ce_low):.2f} to {max(ce_low):.2f} nats per \"\n",
    "        f\"token there, as below the trained depth in E3. At R = 4 they stay valid on {seq(nat4['arloop'])} (ARLoop) \"\n",
    "        f\"and {seq(nat4['prenorm'])} (PreNorm) of the {ROWS} rows along the ladder, \"\n",
    "        + (f\"and accept a proof in {len(nat4p)} of those {len(BASES) * len(RUNGS)} suites (\"\n",
    "           + \"; \".join(f\"{SHORT[b]}, {u:,} updates: {n}\" for b, u, n in nat4p) + \").\" if nat4p else\n",
    "           \"but accept no proof there.\"),\n",
    "        f\"**The adapters overfit at the end of the schedule: the development cross-entropy rises, and the proofs do \"\n",
    "        f\"not consistently follow it.** From \"\n",
    "        f\"{RUNGS[2]:,} to {RUNGS[3]:,} updates the `native3` adapters' cross-entropy at R = 3 rises (ARLoop \"\n",
    "        f\"{ce_nat['arloop'][0]:.3f} → {ce_nat['arloop'][1]:.3f}, PreNorm {ce_nat['prenorm'][0]:.3f} → \"\n",
    "        f\"{ce_nat['prenorm'][1]:.3f}) while their training loss keeps falling (mean over the 64 updates before each \"\n",
    "        f\"rung: ARLoop {loss['arloop'][0]:.3f} → {loss['arloop'][1]:.3f}, PreNorm {loss['prenorm'][0]:.3f} → \"\n",
    "        f\"{loss['prenorm'][1]:.3f}). The {RUNGS[-1]:,} updates of {batch} rows make \"\n",
    "        f\"{batch * RUNGS[-1] / TRAIN_ROWS:.1f} passes over the {TRAIN_ROWS:,} training rows. **[exp]**\"]))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "7e0509fd",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "if ready1a:\n",
    "    # every verbal claim of the reading above, checked against the numbers\n",
    "    assert ladder[\"rule1_off_floor\"] and all(v >= GATE for v in g.values())            # \"in both bases\"\n",
    "    assert nat3[\"arloop\"][0] == nat3[\"prenorm\"][0] == 0                                  # E3 was at the floor\n",
    "    assert all(v != sorted(v) for v in nat3.values())                                    # \"not monotone\"\n",
    "    assert not any(r2[b][\"more_loops_help\"] for b in BASES)                              # \"not established\"\n",
    "    assert ar2[\"only_L1\"] == 0 < ar2[\"only_L4\"] and ar2[\"holm_p\"] >= 0.05                 # \"all ... favour L = 4\"\n",
    "    assert ap == sorted(ap) and ap[-1] > ap[0] and av == sorted(av) and av[-1] > av[0]  # ARLoop: more loops help\n",
    "    assert ac == sorted(ac, reverse=True) and ac[-1] < ac[0]\n",
    "    assert not any(pp) and pc[-1] > pc[0]                                                # PreNorm: no proof, CE worse\n",
    "    assert all(x > 0 for x in gap[\"arloop\"])                                             # \"stays at every rung\"\n",
    "    assert gap[\"prenorm\"] == sorted(gap[\"prenorm\"], reverse=True) and gap[\"prenorm\"][-1] < 0 < gap[\"prenorm\"][0]\n",
    "    assert not any(c[\"steps_valid\"] or c[\"accepted\"] for c in low)                       # \"no valid step\"\n",
    "    assert all(ce_nat[b][1] > ce_nat[b][0] and loss[b][1] < loss[b][0] for b in BASES)   # overfitting\n",
    "    assert any(nat3[b][3] > nat3[b][2] for b in BASES) and any(nat3[b][3] < nat3[b][2] for b in BASES)   # \"not consistently\""
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "f85cf767",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if ready1a:\n",
    "    lib.note(\"Independent re-check\",\n",
    "             f\"`runs/s1a/referee.md`. A separate script recounted all {len(rec1a['cells'])} suites from the raw \"\n",
    "             f\"per-target and per-row records: {len(rec1a['mismatches'])} disagreements with the analysis. Another replayed \"\n",
    "             f\"every recorded attempt with the admitted checker: {rep1a['replayed_attempts']:,} attempts with at least one \"\n",
    "             f\"action, {rep1a['qed_total']} kernel-checked QEDs, exactly the proofs that the harness accepted. Every \"\n",
    "             \"evaluated adapter is the one that its training receipt names. The cross-entropy values are the \"\n",
    "             \"evaluators' own: recomputing them needs the models.\", \"important\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "40bd71ed",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "if ready1a:\n",
    "    assert lib.quote_check(S1A / \"referee.md\",\n",
    "                           f\"{len(rec1a['cells'])} suites recounted: {len(rec1a['mismatches'])} disagreements with \"\n",
    "                           \"`ladder.json`.\",\n",
    "                           f\"{rep1a['replayed_attempts']:,} attempts with at least one action replayed. \"\n",
    "                           f\"{rep1a['qed_total']} reach a kernel-checked QED: exactly the {rep1a['qed_total']} that the \"\n",
    "                           \"harness accepted.\",\n",
    "                           \"Every evaluated adapter is the trained one\",\n",
    "                           \"One seed; 32 dev targets and a 64-row roster, so single proofs move the counts.\",\n",
    "                           \"The 1,024 and 2,048 rungs are snapshots of the 4,096-update schedule, taken while the \"\n",
    "                           \"learning rate was still high; the 512 rung is E3's own 512-update schedule.\",\n",
    "                           \"Re-checked by the coordinator with independent code\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "10c0ba00",
   "metadata": {},
   "source": [
    "**Limits.** One seed; 32 targets and a roster of 64 rows, so single proofs move the counts. The\n",
    "1,024- and 2,048-update rungs are snapshots of the 4,096-update schedule, taken while the learning\n",
    "rate was still high; the 512-update rung is E3's own schedule. Development split only."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acb5bdca",
   "metadata": {},
   "source": [
    "## The canary trained 10 and 30 times longer (1b)\n",
    "\n",
    "E2's canary showed no candidate effect after 1,000 updates ({doc}`e2_canary`). 1b runs E2\n",
    "unchanged except the number of updates, 10,000 and 30,000\n",
    "(`experiments/e2_small/PROTOCOL-long.md`). E2's learning rate is constant, so longer training is\n",
    "simply more updates: the same six arms and seeds (11, 29, 47), the same batches and depth draws,\n",
    "evaluation at $R \\in \\{1, 2, 4, 8, 16\\}$ with Lean-checked certificates. The rules, applied to\n",
    "each length separately: (1) E2's primary comparisons, each new arm against `latent-recurrent` at\n",
    "$R = 4$ and $R = 16$ on iid; (2) *extra loops after longer training*, $R = 16$ against $R = 4$\n",
    "within each arm, on iid and on ood_depth; both with E2's candidate-effect rule (a 95% interval\n",
    "that excludes 0 and the same non-zero sign in all three seeds); (3) ood_depth acceptances,\n",
    "descriptive; (4) the three lengths side by side, descriptive. **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "id": "2d1bd5fe",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "assert lib.quote_check(PROT_1B, \"E2's learning rate is constant, so longer training is simply more updates.\",\n",
    "                       \"10,000 updates (`configs/e2-long-10k.json`);\", \"30,000 updates (`configs/e2-long-30k.json`).\",\n",
    "                       \"six arms, seeds 11, 29 and 47;\", \"the same batches and depth draws per seed;\",\n",
    "                       \"evaluation at r ∈ {1, 2, 4, 8, 16} on iid, ood_depth and ood_operand, with Lean-checked certificates;\",\n",
    "                       \"each new arm against latent-recurrent, at r = 4 and r = 16 on iid.\",\n",
    "                       \"within each arm, r = 16 against r = 4 on iid and on ood_depth, paired over (seed, item).\",\n",
    "                       \"A candidate effect needs the 95% interval to exclude 0 *and* the same non-zero sign in all three seeds.\",\n",
    "                       \"**ood_depth acceptance per arm and r:** descriptive.\",\n",
    "                       \"**Length** (descriptive): 1,000 (E2), 10,000 and 30,000 updates side by side.\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "a7d03532",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "def total(j, arm, r, split):\n",
    "    \"\"\"(accepted, items) of one cell of a run's table (three seeds summed), from analysis.json.\"\"\"\n",
    "    hit = [t for t in ANA[j][\"table\"] if t[\"arm\"] == arm and t[\"r\"] == r and t[\"split\"] == split]\n",
    "    assert len(hit) == 1\n",
    "    return hit[0][\"total\"], hit[0][\"n\"]\n",
    "\n",
    "\n",
    "if not ready1b:\n",
    "    lib.pending(\"Stage 1b\", \"The refereed files of Stage 1b (`runs/s1b/referee.md`, its recount and \"\n",
    "                \"`experiments/e2_small/results/<job>/`) are not all there yet; this section shows no numbers.\")\n",
    "else:\n",
    "    N_IID = total(E2_JOB, LOOP_ARMS[0], 4, \"iid\")[1]\n",
    "    grow = {arm: [total(j, arm, 4, \"iid\")[0] for j in JOBS] for arm in LOOP_ARMS}\n",
    "    lib.md(f\"**Runs.** WMI jobs {' and '.join(LONG)} ({' and '.join(f'{UPD[j]:,}' for j in LONG)} updates), each on one \"\n",
    "           f\"{SUM[LONG[0]]['device']}, next to E2's job {E2_JOB} ({UPD[E2_JOB]:,} updates). Files: \"\n",
    "           \"`experiments/e2_small/results/<job>/`.\\n\\n\"\n",
    "           f\"**Accepted iid certificates at R = 4** (of {N_IID}, three seeds; rule 4). **[exp]**\\n\\n\" +\n",
    "           lib.table([(f\"`{arm}`\", *grow[arm]) for arm in LOOP_ARMS],\n",
    "                     [\"arm\", *(f\"{UPD[j]:,} updates\" for j in JOBS)]))\n",
    "    prim = {j: [c for c in ANA[j][\"comparisons\"] if c[\"family\"] == \"primary\"] for j in LONG}\n",
    "    dep = {j: {sp: [c for c in ANA[j][\"comparisons\"] if c[\"family\"] == \"secondary-depth-change\" and c[\"split\"] == sp]\n",
    "               for sp in (\"iid\", \"ood_depth\")} for j in LONG}\n",
    "    rows = []\n",
    "    for j in LONG:\n",
    "        d = [c[\"diff\"] for c in prim[j]]\n",
    "        rows.append((f\"{UPD[j]:,}\", f\"{sum(c['candidate_effect'] for c in prim[j])} of {len(prim[j])}\",\n",
    "                     f\"{lib.signed(min(d), 3)} to {lib.signed(max(d), 3)}\", lib.pvalue(min(c[\"mcnemar_p\"] for c in prim[j])),\n",
    "                     f\"{sum(c['candidate_effect'] for sp in dep[j] for c in dep[j][sp])} of \"\n",
    "                     f\"{sum(len(v) for v in dep[j].values())}\"))\n",
    "    lib.md(\"**Rules 1 and 2:**\\n\\n\" + lib.table(rows, [\"updates\", \"primary comparisons with a candidate effect\",\n",
    "                                                     \"new arm − latent-recurrent (accuracy)\", \"smallest McNemar p\",\n",
    "                                                     \"R = 16 against R = 4 with a candidate effect (iid, ood_depth)\"]))\n",
    "    rows = [(f\"`{arm}`\", *(f\"{c['only_x']} / {c['only_y']}\" for j in LONG\n",
    "                           for c in dep[j][\"iid\"] if c[\"x\"] == f\"{arm}@r16\")) for arm in LOOP_ARMS]\n",
    "    lib.md(\"**Depth within each arm** (iid items accepted only at R = 16 / only at R = 4, three seeds):\\n\\n\" +\n",
    "           lib.table(rows, [\"arm\", *(f\"{UPD[j]:,} updates\" for j in LONG)]) +\n",
    "           \"\\n\\nOn ood_depth no arm accepts a single item, at any R and either length, so every comparison there is \"\n",
    "           \"0 against 0. **[exp]**\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "ac3447d2",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "if ready1b:\n",
    "    # the three runs differ only in the number of updates (and their names and notes)\n",
    "    other = lambda cfg: {k: v for k, v in cfg.items() if k not in (\"steps\", \"name\", \"notes\", \"derived_from\")}\n",
    "    assert all(other(SUM[j][\"config\"]) == other(SUM[E2_JOB][\"config\"]) for j in LONG)\n",
    "    assert UPD[E2_JOB] < UPD[LONG[0]] < UPD[LONG[1]]\n",
    "    assert [UPD[j] for j in JOBS] == [1000, 10000, 30000]\n",
    "    # the table agrees with the per-run evaluations of summary.json and with the recount from the raw predictions\n",
    "    for j in JOBS:\n",
    "        for arm in LOOP_ARMS:\n",
    "            s = sum(sp[\"lean_accepted\"] for r in SUM[j][\"runs\"] if r[\"name\"] == arm for ev in r[\"evaluations\"]\n",
    "                    if ev[\"recurrence\"] == 4 for sp in ev[\"splits\"] if sp[\"split\"] == \"iid\")\n",
    "            assert s == total(j, arm, 4, \"iid\")[0]\n",
    "            if j in LONG:\n",
    "                assert rec1b[j][\"counts\"][f\"{arm}@r4:iid\"] == s\n",
    "    assert not rec1b[\"mismatches\"] and all(rec1b[j][\"ood_depth_accepted_loop_arms\"] == 0 for j in LONG)\n",
    "    assert all(not ANA[j][\"ood_depth_accepted\"] for j in JOBS)\n",
    "    assert all(len(prim[j]) == 6 and len(dep[j][\"iid\"]) == len(dep[j][\"ood_depth\"]) == 4 for j in LONG)\n",
    "    assert all(c[\"only_x\"] == c[\"only_y\"] == 0 for j in LONG for c in dep[j][\"ood_depth\"])\n",
    "    # each candidate flag follows the rule from its own fields\n",
    "    for j in LONG:\n",
    "        for c in prim[j] + dep[j][\"iid\"] + dep[j][\"ood_depth\"]:\n",
    "            signs = {(v > 0) - (v < 0) for v in c[\"per_seed_count_diff\"].values()}\n",
    "            assert c[\"candidate_effect\"] == ((c[\"ci95\"][0] > 0 or c[\"ci95\"][1] < 0) and len(signs) == 1 and 0 not in signs)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "54ac22ae",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if ready1b:\n",
    "    worst = {j: max(c[\"diff\"] for c in prim[j]) for j in LONG}\n",
    "    lib.md(\"\\n\\n\".join([\n",
    "        f\"**Training longer raises in-distribution accuracy in every arm** (accepted at R = 4: \"\n",
    "        + \"; \".join(f\"`{arm}` {' → '.join(map(str, grow[arm]))}\" for arm in LOOP_ARMS) + \").\",\n",
    "        f\"**No depth effect detected.** None of the {sum(len(dep[j][sp]) for j in LONG for sp in dep[j])} comparisons \"\n",
    "        \"of R = 16 against R = 4 meets the candidate rule, and no arm accepts an ood_depth item at either length.\",\n",
    "        f\"**No new arm (the PreNorm loop or either ARLoop arm) beats latent's decoder:** 0 of {len(prim[LONG[0]])} primary comparisons at either \"\n",
    "        f\"length, and every new arm's point estimate is below latent's (at most {lib.signed(max(worst.values()), 3)}). \"\n",
    "        \"On this canary, training more does not make looping pay off. **[exp]**\"]))\n",
    "    n_cmp = sum(len(rec1b[j][\"comparisons\"]) for j in LONG)\n",
    "    lib.note(\"Independent re-check\",\n",
    "             f\"`runs/s1b/referee.md`. A separate script recounted the Lean-accepted certificates from the raw predictions \"\n",
    "             f\"of every arm and seed, checked each acceptance against the verifier's exit code, and recomputed every \"\n",
    "             f\"primary and depth comparison: {n_cmp} comparisons, {len(rec1b['mismatches'])} disagreements.\", \"important\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "01b52adc",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "if ready1b:\n",
    "    assert all(v == sorted(v) and v[-1] > v[0] for v in grow.values())                    # \"raises ... in every arm\"\n",
    "    assert not any(c[\"candidate_effect\"] for j in LONG for sp in dep[j] for c in dep[j][sp])\n",
    "    assert not any(c[\"candidate_effect\"] for j in LONG for c in prim[j]) and max(worst.values()) < 0\n",
    "    assert lib.quote_check(S1B / \"referee.md\",\n",
    "                           f\"{n_cmp} comparisons, {len(rec1b['mismatches'])} disagreements with `analysis.json`.\",\n",
    "                           \"0 ood_depth acceptances at both lengths.\",\n",
    "                           \"It checks that every acceptance matches the verifier's exit code\",\n",
    "                           \"A tiny model can memorise the task without using depth.\",\n",
    "                           \"Re-checked by the coordinator with independent code\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "85097bc1",
   "metadata": {},
   "source": [
    "**Limits.** One toy task with 93 training examples and three seeds: a tiny model can memorise the\n",
    "task without using depth. As in E2, the ARLoop arms have no value residuals (registered), which the\n",
    "paper's App. A.1 and A.3 report its sliding window needs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fff3f7e3",
   "metadata": {},
   "source": [
    "## A trained fourth loop in ARLoop-0.6B, routing only (1c)\n",
    "\n",
    "E1.3 detected no gain from a fourth loop under the inference-only rules, and its exploratory probe\n",
    "was consistent with the trained read-out routing around the extra loop under `cycle`\n",
    "({doc}`e1_release`). 1c asks whether *training*\n",
    "loop 4's routing makes the fourth loop useful on GSM8K, beyond what the same training does without\n",
    "it (`experiments/e1_release/PROTOCOL-loop4.md`):\n",
    "\n",
    "* **L4:** four loops. Loop 4's 36 queries and 36 RMSNorm weights start as copies of loop 1's (E1's\n",
    "  `cycle` rule) and are trained; everything else is frozen, the final read-out included.\n",
    "* **C3, the control:** three loops. Loop 3's queries and norms start as the released ones and are\n",
    "  trained the same way.\n",
    "* **Data:** FineMath-4+, one shard, shuffled with seed 11; documents that share any 13-gram with a\n",
    "  GSM8K test question are removed; then the first 0.1B tokens, packed into 2,048-token sequences.\n",
    "  Same data, order, optimiser and seed in every arm.\n",
    "* **A second pair**, added by amendment 1 before any 1c result: **L4e** and **C3e**, the same arms,\n",
    "  but training the effective routing vector directly. The reason: in the loop-4 bank many routing\n",
    "  coordinates had query and norm weight both exactly 0, which training the two separately cannot\n",
    "  move (finding F10; the share is in the digest, §11).\n",
    "* **Evaluation:** E1's GSM8K harness (5-shot chain of thought, BOS prepended, flexible extract, all\n",
    "  1,319 test items) and WikiText-2 bits per byte. **Rule 1:** L4 at $R = 4$ against C3 at $R = 3$,\n",
    "  and L4e against C3e, paired over the items, with Holm correction over the two pairs; \"a trained\n",
    "  fourth loop pays off\" if at least one pair passes after correction and the other pair's point\n",
    "  estimate has the same sign. **Rule 2** compares each arm with E1's released model; **rule 3** is\n",
    "  the read-out's routing weights before and after training. Tier T4. **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "id": "b082a34e",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "assert lib.quote_check(PROT_1C,\n",
    "                       \"Only loop 4's 36 queries and 36 RMSNorm weights are trained (110,592 parameters).\",\n",
    "                       \"the final read-out query and norm stay frozen.\",\n",
    "                       \"Loop 4's queries and norms start as copies of loop 1's (E1's `cycle` rule) and are trained.\",\n",
    "                       \"Loop 3's queries and norms start as copies of the released ones and are trained.\",\n",
    "                       \"FineMath-4+ (`HuggingFaceTB/finemath`, configuration `finemath-4plus`, one shard), shuffled at \"\n",
    "                       \"document level with seed 11.\",\n",
    "                       \"Documents that share any 13-gram with a GSM8K test question are removed; the count is reported.\",\n",
    "                       \"Then the first 0.1B tokens, tokenised with the model's tokenizer, documents joined by EOS and \"\n",
    "                       \"packed into 2,048-token sequences.\",\n",
    "                       \"It uses the same data, order, optimiser, schedule and seed, but trains the effective routing \"\n",
    "                       \"vector e directly.\",\n",
    "                       \"lm-eval 0.4.12 `gsm8k_cot`, 5-shot, flexible-extract, greedy, at most 1,024 new tokens, BOS prepended.\",\n",
    "                       \"Rule 1 applies to both pairs (L4 against C3; L4e against C3e), with Holm correction over the two.\",\n",
    "                       \"L4 at R = 4 against C3 at R = 3, paired over the 1,319 items.\",\n",
    "                       \"\\\"A trained fourth loop pays off\\\" if at least one pair passes after correction and the other \"\n",
    "                       \"pair's point estimate has the same sign.\")\n",
    "if ready1c:\n",
    "    TR = {a: json.loads((S1C / \"train\" / a / \"receipt.json\").read_text()) for a in ARMS_1C}\n",
    "    AUD = json.loads((S1C / \"data\" / \"finemath4p-s00\" / \"audit.json\").read_text())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "458e9e30",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "REF_NAME = {\"ar06-R3\": \"released, R = 3\", \"ar06-R4-cycle\": \"released, R = 4 (`cycle`)\"}\n",
    "if not ready1c:\n",
    "    lib.pending(\"Stage 1c\", \"The refereed files of Stage 1c (`runs/s1c/loop4.json`, `runs/s1c/referee.md` and its \"\n",
    "                \"recount) are not all there yet; this section shows no numbers.\")\n",
    "else:\n",
    "    acc, acc1, bpb, bpb1 = loop4[\"accuracy\"], loop4[\"accuracy_e1\"], loop4[\"wikitext_bpb\"], loop4[\"wikitext_bpb_e1\"]\n",
    "    t = TR[\"L4\"]\n",
    "    n_items, = {r[\"n\"] for r in loop4[\"rule1\"].values()}\n",
    "    lib.md(f\"**Training.** Each arm made {t['updates_completed']:,} updates of \"\n",
    "           f\"{t['sequences_seen'] // t['updates_completed']} sequences of {AUD['packing']['sequence_length']:,} tokens \"\n",
    "           f\"({t['tokens_seen'] / 1e9:.2f}B tokens). The 13-gram filter removed {AUD['documents_removed']} of the \"\n",
    "           f\"{AUD['documents_seen']:,} documents read. Training receipts: `runs/s1c/train/<arm>/`.\\n\\n\" +\n",
    "           lib.table([(f\"**{a}**\", R, f\"{TR[a]['trainable_parameters']:,}\", pct(acc[a]), f\"{bpb[a]:.4f}\")\n",
    "                      for a, R in ARMS_1C.items()] +\n",
    "                     [(REF_NAME[k], int(re.search(r\"R(\\d)\", k).group(1)), 0, pct(acc1[k]), f\"{bpb1[k]:.4f}\")\n",
    "                      for k in REF_NAME],\n",
    "                     [\"arm\", \"loops R\", \"trained parameters\", f\"GSM8K (%), n = {n_items:,}\", \"WikiText-2 bits per byte\"]))\n",
    "    lib.md(\"**Rule 1** (paired over the items; Holm over the two pairs):\\n\\n\" +\n",
    "           lib.table([(k.replace(\" vs \", \" against \"), pts(r[\"diff\"]), f\"[{pts(r['ci95'][0])}, {pts(r['ci95'][1])}]\",\n",
    "                       f\"{r['only_a']} / {r['only_b']}\", lib.pvalue(r[\"mcnemar_p\"]), lib.pvalue(r[\"holm_p\"]),\n",
    "                       \"yes\" if r[\"passes\"] else \"no\") for k, r in loop4[\"rule1\"].items()],\n",
    "                     [\"pair\", \"difference (points)\", \"95% interval\", \"items solved only by the first / the second\",\n",
    "                      \"exact McNemar p\", \"Holm p\", \"passes\"]) +\n",
    "           f\"\\n\\nA trained fourth loop pays off: **{'yes' if loop4['rule1_pays_off'] else 'no'}**. **[exp]**\")\n",
    "    lib.md(\"**Rule 2** (each arm against E1's released model):\\n\\n\" +\n",
    "           lib.table([(k.split(\" vs \")[0] + \" against \" + REF_NAME[k.split(\" vs \")[1]], pts(r[\"diff\"]),\n",
    "                       f\"[{pts(r['ci95'][0])}, {pts(r['ci95'][1])}]\", lib.pvalue(r[\"mcnemar_p\"]))\n",
    "                      for k, r in loop4[\"rule2\"].items()],\n",
    "                     [\"comparison\", \"difference (points)\", \"95% interval\", \"exact McNemar p\"]))\n",
    "    r3 = loop4[\"rule3\"]\n",
    "    n_prompts, = {json.loads(q.read_text())[\"n_prompts\"] for q in (S1C / \"routing\").glob(\"*-*/routing.json\")}\n",
    "    lib.md(f\"**Rule 3** (the read-out's routing weights, mean over the tokens of {n_prompts} GSM8K prompts, before → \"\n",
    "           \"after training):\\n\\n\" +\n",
    "           lib.table([(f\"**{a}**\", f\"{100 * r3[f'{a}-init']['loop3_last_block']:.1f} → {100 * r3[f'{a}-final']['loop3_last_block']:.1f}\",\n",
    "                       f\"{100 * r3[f'{a}-init']['loop4_sources']:.1f} → {100 * r3[f'{a}-final']['loop4_sources']:.1f}\"\n",
    "                       if ARMS_1C[a] == 4 else \"–\") for a in ARMS_1C],\n",
    "                     [\"arm\", \"weight on loop 3's last block (%)\", \"weight on loop 4's sources (%)\"]))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "dda20211",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "if ready1c:\n",
    "    both = {**loop4[\"rule1\"], **loop4[\"rule2\"]}\n",
    "    # the recount (separate code, every item re-scored from the raw generations) agrees in every comparison\n",
    "    assert not rec1c[\"mismatches\"] and sorted(rec1c[\"comparisons\"]) == sorted(both)\n",
    "    for k, r in both.items():\n",
    "        c = rec1c[\"comparisons\"][k]\n",
    "        assert (c[\"only_a\"], c[\"only_b\"]) == (r[\"only_a\"], r[\"only_b\"]) and abs(c[\"mcnemar_p\"] - r[\"mcnemar_p\"]) < 1e-12\n",
    "        assert abs(r[\"mcnemar_p\"] - lib.mcnemar_exact(r[\"only_a\"], r[\"only_b\"])) < 1e-12 and r[\"n\"] == n_items\n",
    "    ps = sorted((r[\"mcnemar_p\"], k) for k, r in loop4[\"rule1\"].items())          # Holm over the two pairs, recomputed\n",
    "    holm = {ps[0][1]: min(1.0, 2 * ps[0][0])}\n",
    "    holm[ps[1][1]] = max(holm[ps[0][1]], min(1.0, ps[1][0]))\n",
    "    assert all(abs(holm[k] - r[\"holm_p\"]) < 1e-12 for k, r in loop4[\"rule1\"].items())\n",
    "    assert all(r[\"passes\"] == (r[\"diff\"] > 0 and r[\"holm_p\"] < 0.05) for r in loop4[\"rule1\"].values())\n",
    "    passed = [r for r in loop4[\"rule1\"].values() if r[\"passes\"]]\n",
    "    assert loop4[\"rule1_pays_off\"] == (bool(passed) and all(r[\"diff\"] > 0 for r in loop4[\"rule1\"].values()))\n",
    "    # every evaluated bank is the trained one; the rest of the model is untouched; one data stream for all arms\n",
    "    for a in ARMS_1C:\n",
    "        assert loop4[\"banks\"][a] == TR[a][\"bank_final\"][\"sha256\"] and TR[a][\"state\"] == \"completed\"\n",
    "        assert TR[a][\"updates_completed\"] == TR[a][\"updates_total\"] and TR[a][\"identity\"][\"seed\"] == 11\n",
    "        assert TR[a][\"frozen_parameters_sha256\"][\"start\"] == TR[a][\"frozen_parameters_sha256\"][\"end\"]\n",
    "        assert TR[a][\"updated_at\"].startswith(\"2026-11-15\")\n",
    "    assert len({(TR[a][\"updates_completed\"], TR[a][\"sequences_seen\"], TR[a][\"data\"][\"tokens_sha256\"]) for a in ARMS_1C}) == 1\n",
    "    assert TR[\"L4\"][\"trainable_parameters\"] == TR[\"C3\"][\"trainable_parameters\"] == 110592\n",
    "    # from the per-item samples, when present (they are not in git): the whole computation again\n",
    "    paths = {a: S1C / \"eval\" / \"gsm8k-bos\" / f\"{a}-R{R}\" / \"samples.jsonl\" for a, R in ARMS_1C.items()}\n",
    "    paths.update({k: lib.RUNS / \"e1\" / \"gsm8k-bos\" / k / \"samples.jsonl\" for k in REF_NAME})\n",
    "    em = {k: lib.samples_em(p) for k, p in paths.items()}\n",
    "    recomputed = all(em.values())\n",
    "    if recomputed:\n",
    "        # analyze_loop4.py's paired bootstrap draws the same n indices per resample from random.Random(seed),\n",
    "        # whatever the data; the draws are made once here and applied to every comparison (exact: sums of 0/±1)\n",
    "        import random\n",
    "        import numpy as np\n",
    "        seed, B = (int(v) for v in re.search(r\"def paired\\(a, b, seed=(\\d+), B=(\\d+)\\)\",\n",
    "                                              (EXP / \"e1_release\" / \"analyze_loop4.py\").read_text()).groups())\n",
    "        rng = random.Random(seed)\n",
    "        draws = np.array([[rng.randrange(n_items) for _ in range(n_items)] for _ in range(B)], dtype=np.int64)\n",
    "        for k, r in both.items():\n",
    "            x, y = k.split(\" vs \")\n",
    "            q = lib.paired(em[x], em[y], bootstrap=False)  # accuracies, difference, discordant items, McNemar\n",
    "            assert all(q[f] == r[f] for f in (\"n\", \"only_a\", \"only_b\"))\n",
    "            assert all(abs(q[f] - r[f]) < 1e-12 for f in (\"acc_a\", \"acc_b\", \"diff\", \"mcnemar_p\"))\n",
    "            ids = sorted(set(em[x]) & set(em[y]))\n",
    "            d = np.sort((np.array([em[x][i] - em[y][i] for i in ids])[draws]).sum(axis=1) / n_items)\n",
    "            assert all(abs(u - v) < 1e-12 for u, v in zip((d[int(0.025 * B)], d[int(0.975 * B) - 1]), r[\"ci95\"]))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "33e417e6",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if ready1c:\n",
    "    r1 = loop4[\"rule1\"]\n",
    "    last = [r3[f\"{a}-{w}\"][\"loop3_last_block\"] for a in ARMS_1C for w in (\"init\", \"final\")]\n",
    "    l4 = {a: (r3[f\"{a}-init\"][\"loop4_sources\"], r3[f\"{a}-final\"][\"loop4_sources\"]) for a in (\"L4\", \"L4e\")}\n",
    "    ctrl = {a: loop4[\"rule2\"][f\"{a} vs ar06-R3\"][\"diff\"] for a in (\"C3\", \"C3e\")}\n",
    "    near = max(abs(bpb[a] - bpb1[\"ar06-R3\"]) for a in (\"L4\", \"L4e\"))\n",
    "    lib.md(\"\\n\\n\".join([\n",
    "        f\"**No gain from a trained fourth loop.** Both pairs are slightly negative ({pts(r1['L4 vs C3']['diff'])} and \"\n",
    "        f\"{pts(r1['L4e vs C3e']['diff'])} points), and both intervals contain 0. The training itself is harmless: the \"\n",
    "        f\"loop-3 controls stay within {100 * max(abs(v) for v in ctrl.values()):.2f} points of the released model. At \"\n",
    "        f\"R = 4 it brings WikiText-2 from {bpb1['ar06-R4-cycle']:.4f} to {bpb['L4']:.4f} (L4) and {bpb['L4e']:.4f} (L4e) \"\n",
    "        f\"bits per byte, to within {near:.4f} of R = 3 ({bpb1['ar06-R3']:.4f}) but not below it.\",\n",
    "        f\"**The read-out suggests why.** It is frozen by design, and it keeps {100 * min(last):.0f}–\"\n",
    "        f\"{100 * max(last):.0f}% of its weight on loop 3's last block before and after training; loop 4's sources get \"\n",
    "        f\"{100 * l4['L4'][0]:.1f}% before and {100 * l4['L4'][1]:.1f}% (L4) or {100 * l4['L4e'][1]:.1f}% (L4e) after. \"\n",
    "        \"This is the released-model version of the paper's App. D.2 result ({doc}`../evidence`): retrained routing \"\n",
    "        \"does not buy extrapolation. It fits the project's hunch that attention over depth makes an extra loop \"\n",
    "        \"cheap to ignore, not useful. **[exp]**\"]))\n",
    "    lib.note(\"Independent re-check\",\n",
    "             f\"`runs/s1c/referee.md`. A separate script re-scored every GSM8K item of the four arms and of E1's two \"\n",
    "             f\"reference runs from the raw generations ({len(rec1c['accuracy'])} runs of {n_items:,} items, each item as \"\n",
    "             f\"recorded) and recomputed every comparison: {len(rec1c['comparisons'])} comparisons, \"\n",
    "             f\"{len(rec1c['mismatches'])} disagreements. \" +\n",
    "             (\"The statistics above were also recomputed here from the per-item samples, bootstrap intervals \"\n",
    "              \"included: identical.\" if recomputed else\n",
    "              \"The per-item samples are not in this checkout; the statistics are read from `runs/s1c/loop4.json`.\"),\n",
    "             \"important\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c24e0eae",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "if ready1c:\n",
    "    assert all(r[\"diff\"] < 0 and r[\"ci95\"][0] < 0 < r[\"ci95\"][1] for r in r1.values()) and not loop4[\"rule1_pays_off\"]\n",
    "    assert all(abs(v) < 0.005 for v in ctrl.values())                     # \"harmless\"\n",
    "    assert all(bpb1[\"ar06-R3\"] <= bpb[a] < bpb1[\"ar06-R4-cycle\"] for a in (\"L4\", \"L4e\"))\n",
    "    assert all(r3[f\"{a}-final\"][\"loop4_sources\"] < 0.05 for a in (\"L4\", \"L4e\")) and min(last) > 0.9\n",
    "    assert f\"{100 * l4['L4'][0]:.1f}\" == f\"{100 * l4['L4e'][0]:.1f}\"     # one \"before\" value: both start from loop 1\n",
    "    assert lib.quote_check(S1C / \"referee.md\",\n",
    "                           f\"{len(rec1c['comparisons'])} comparisons, {len(rec1c['mismatches'])} disagreements.\",\n",
    "                           f\"Each run's {n_items:,} items ({len(rec1c['accuracy'])} runs) re-score exactly as recorded.\",\n",
    "                           \"This is the released-model version of the paper's App. D.2 result: retrained routing does \"\n",
    "                           \"not buy extrapolation.\",\n",
    "                           \"Routing only, with the read-out frozen; 0.1B tokens; one seed; one model.\",\n",
    "                           \"Re-checked by the coordinator with independent code\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c42c95ed",
   "metadata": {},
   "source": [
    "**Limits.** Routing only, with the read-out frozen; 0.1B tokens; one seed; one model. Training the\n",
    "whole model at depth (Stage 2 below) remains the real test of whether a fourth loop can pay off."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ee88ac1",
   "metadata": {},
   "source": [
    "## What Stage 1 says, and what follows"
   ]
  },
  {
   "cell_type": "code",
   "id": "15723e28",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if not (ready1a and ready1b and ready1c):\n",
    "    lib.pending(\"Stage 1 summary\", \"shown once all three parts have passed their re-checks.\")\n",
    "else:\n",
    "    lib.md(\"\\n\".join([\n",
    "        f\"* **Training longer lifts the 0.6B pair off the proof floor** at its trained depth, in both bases: \"\n",
    "        f\"{ladder['rule1_gate']['arloop']} and {ladder['rule1_gate']['prenorm']} of {T} targets after {RUNGS[-1]:,} updates, against \"\n",
    "        f\"{nat3['arloop'][0]} and {nat3['prenorm'][0]} after {RUNGS[0]} (1a).\",\n",
    "        f\"* **A one-seed lead for ARLoop, below the registered threshold.** Its random-depth adapter proves more \"\n",
    "        f\"targets, makes more valid steps and has a lower cross-entropy at more loops (proofs {seq(ap)} at R = 1 \"\n",
    "        f\"to 4); PreNorm's does not. The registered test, single-step validity at R = 4 against R = 1 on {ROWS} rows, \"\n",
    "        f\"misses after Holm correction (p = {ladder['rule2']['arloop']['holm_p']:.4g}): a lead for a confirmatory run, \"\n",
    "        f\"not a result (1a).\",\n",
    "        f\"* **No depth effect detected elsewhere.** The canary trained {UPD[LONG[-1]] // UPD[E2_JOB]} times longer \"\n",
    "        \"shows none: no within-arm test of R = 16 against R = 4 meets the candidate rule (1b). Training the routing of \"\n",
    "        \"a fourth loop in the released ARLoop-0.6B does not pay off on GSM8K; the frozen read-out keeps routing around \"\n",
    "        \"it, a likely reason that Stage 2 tests by training the whole model (1c).\"]))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "e97015e6",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "gate = (\"its gate, rule 1 of 1a, is passed\" if ready1a and ladder[\"rule1_off_floor\"] else\n",
    "        \"only if 1a leaves the proof floor\")\n",
    "lib.md(\"Stages 4 and 2 were approved on 15 November and are being run before the talk; their results enter \"\n",
    "       \"these notes only after an independent re-check (until then they are pending on {doc}`tests`):\\n\\n\"\n",
    "       f\"* **Stage 4, a confirmatory run of the 1a lead** ({gate}): seeds 11, 29 and 47, both arms and both bases at \"\n",
    "       \"4,096 updates; the sealed test split of `latent`'s Campaign 4, opened once; the primary measures fixed in \"\n",
    "       \"advance (`experiments/e3_pair/PROTOCOL-confirm.md`).\\n\"\n",
    "       \"* **Stage 2, continued training at depth:** both 0.6B models with every parameter trained, at $R = 3$ \"\n",
    "       \"against $R = 4$, on the 0.1B FineMath-4+ tokens of 1c; GSM8K paired (`experiments/s2_depth/PROTOCOL.md`). \"\n",
    "       \"A reduced design: the random-depth arm is registered but runs only if a further GPU becomes free, and the \"\n",
    "       \"authors' stage-3 mixture could not be rebuilt in time.\\n\\n\"\n",
    "       \"Stage 3 comes after the talk: from scratch at 140M on FineWeb-Edu, ARLoop and PreNorm at $R = 1$ and \"\n",
    "       \"$R = 3$, with checkpoints at 1.4, 2.8, 5.6 and 11.2B tokens. Does the loop gain grow with the training \"\n",
    "       \"tokens, and faster with attention residuals?\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c01e9fdb",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "assert lib.quote_check(lib.REPO / \"experiments\" / \"e3_pair\" / \"PROTOCOL-confirm.md\",\n",
    "                       \"**Seeds 11, 29, 47**\", \"**4,096 updates** (Stage 1a's)\", \"## Data: the sealed C4 test split, opened once\")\n",
    "assert lib.quote_check(lib.REPO / \"experiments\" / \"s2_depth\" / \"PROTOCOL.md\",\n",
    "                       \"R = 3 against R = 4 for both bases. The random-depth arm (R from {2, 3, 4, 5} per update)\",\n",
    "                       \"is registered below but runs only if a further GPU becomes free without displacing Stage 4.\",\n",
    "                       \"every parameter trained\", \"Data: Stage 1c's audited FineMath-4+ shard\",\n",
    "                       \"0.1B tokens, one document removed by the 13-gram GSM8K filter\",\n",
    "                       \"not the authors' stage-3 mixture: rebuilding that mixture is not possible in\")\n",
    "assert lib.quote_check(CAMPAIGN,\n",
    "                       \"The paper's 140M recipe and code (`OSU-NLP-Group/ARLoop`) on FineWeb-Edu, 11.2B tokens.\",\n",
    "                       \"Arms: {PreNormLoop, ARLoop} × {R = 1, R = 3}.\", \"Checkpoints at 1.4, 2.8, 5.6 and 11.2B tokens.\",\n",
    "                       \"\\\"Looping pays off more with training\\\" if the gain grows across the four checkpoints, and \\\"more \"\n",
    "                       \"with attention residuals\\\" if it grows faster for ARLoop.\")"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
