{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b9d0b3dc",
   "metadata": {},
   "source": [
    "# Stage 4: the depth lead, re-tested on unseen goals\n",
    "\n",
    "Stage 1a ({doc}`stage1`) trained the matched 0.6B pair longer than E3 and found a one-seed lead: with a random\n",
    "number of loops in training, ARLoop's adapter made more valid proof steps with more loops, PreNorm's did not, and\n",
    "the registered test missed after Holm correction. A lead is not a result. Stage 4 tests it once, as registered\n",
    "before any run (`experiments/e3_pair/PROTOCOL-confirm.md`): more seeds, and the test split of `latent`'s Campaign 4,\n",
    "sealed until then and opened exactly once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d357a13",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib, re, json\n",
    "\n",
    "BOOK = next(p for p in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents] if (p / \"seminar_lib.py\").exists())\n",
    "sys.path.insert(0, str(BOOK))\n",
    "sys.dont_write_bytecode = True   # keep book/ free of __pycache__\n",
    "import seminar_lib as lib\n",
    "import matplotlib\n",
    "matplotlib.use(\"module://matplotlib_inline.backend_inline\")\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "NAME = {\"arloop\": \"ARLoop-0.6B\", \"prenorm\": \"PreNormLoop-0.6B\"}\n",
    "SHORT = {\"arloop\": \"ARLoop\", \"prenorm\": \"PreNorm\"}\n",
    "BASES = (\"arloop\", \"prenorm\")\n",
    "\n",
    "\n",
    "def text_or_none(path):\n",
    "    \"\"\"A stage's re-check note, or None: no number of a stage 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 pts(x):                                    # a difference (a fraction) in signed points\n",
    "    return lib.signed(100 * x)\n",
    "\n",
    "PROT = lib.REPO / \"experiments\" / \"e3_pair\" / \"PROTOCOL-confirm.md\"\n",
    "S4 = lib.RUNS / \"s4\"\n",
    "ref4 = text_or_none(S4 / \"referee.md\")\n",
    "S4J = lib.read_json(S4 / \"s4.json\")                      # written by experiments/e3_pair/analyze_confirm.py\n",
    "REC = lib.read_json(S4 / \"referee\" / \"s4_recount.json\")\n",
    "REP = lib.read_json(S4 / \"referee\" / \"s4_replay.json\")\n",
    "ready = all(x is not None for x in (ref4, S4J, REC, REP))\n",
    "if ready:\n",
    "    P1, P3, P2, S1 = (S4J[k] for k in (\"P1\", \"P3\", \"P2\", \"S1\"))\n",
    "    T, N = S4J[\"proof_targets\"], S4J[\"roster_rows\"]\n",
    "    RC = lib.read_json(S4 / \"roster-counts.json\")             # the roster as drawn, from the opening job\n",
    "    assert RC is None or (RC[\"roster_sha256\"] == S4J[\"roster_sha256\"] and RC[\"latent_rows\"] + RC[\"extra_rows\"] == N)\n",
    "    SEEDS = sorted({r[\"seed\"] for r in S4J[\"S5\"]})\n",
    "    accepted = sum(r[\"test_accepted\"] for r in S4J[\"S5\"])\n",
    "    # the re-check confirms the analysis, and every verdict follows the registered rule\n",
    "    cell = lambda r: f\"{r['base']}-{r['arm']}-s{r['seed']}\" + (\"-ladder\" if r[\"seed\"] == 11 else \"\") + f\"-R{r['R']}\"  # noqa: E731\n",
    "    assert not REC[\"problems\"] and not REP[\"problems\"] and REP[\"qed_total\"] == REP[\"accepted_records\"]\n",
    "    assert all(REP[\"cells\"].get(cell(r), {}).get(\"replayed_qed\") == r[\"test_accepted\"] for r in S4J[\"S5\"])\n",
    "    assert P1[\"verdict\"] == (\"more loops help ARLoop\" if P1[\"holm_p\"] < 0.05 and P1[\"only_R4\"] > P1[\"only_R1\"]\n",
    "                             and P1[\"seeds_R4_ahead\"] >= 2 else \"not established\")\n",
    "    assert P3[\"verdict\"] == (\"ARLoop proves more\" if P3[\"holm_p\"] < 0.05 and P3[\"only_arloop\"] > P3[\"only_prenorm\"]\n",
    "                             and P3[\"seeds_arloop_ahead\"] >= 2 else \"PreNorm proves more\" if P3[\"holm_p\"] < 0.05\n",
    "                             and P3[\"only_prenorm\"] > P3[\"only_arloop\"] and P3[\"seeds_prenorm_ahead\"] >= 2\n",
    "                             else \"no detectable difference\")\n",
    "    assert P2[\"verdict\"] == (\"ARLoop gains more from loops than PreNorm\" if P2[\"ci95\"][0] > 0 and P2[\"mean\"] > 0\n",
    "                             else \"not established\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a43d533e",
   "metadata": {},
   "source": [
    "## The design\n",
    "\n",
    "* **Bases, arms, recipe:** ARLoop-0.6B and PreNormLoop-0.6B; arms `native3` (every update at $R = 3$) and\n",
    "  `random124` ($R$ drawn from $\\{1, 2, 4\\}$ per update, `latent`'s rule); Stage 1a's recipe with the cosine\n",
    "  schedule to 4,096 updates and no checkpoint selection.\n",
    "* **Seeds 11, 29 and 47.** Seed 11 reuses the four Stage 1a adapters unchanged; seeds 29 and 47 are new trainings.\n",
    "* **The test split, opened once:** `latent`'s own test targets, 48 by its pinned plan, and a single-step roster of\n",
    "  up to 256 rows: `latent`'s 128 test validation rows plus 16 rows per stratum drawn by a rule fixed in the protocol,\n",
    "  or all eligible rows where a stratum has fewer. One CPU job opened\n",
    "  it, only after all twelve adapters existed and their development records were written.\n",
    "* **Evaluation, as in E3:** the same harness and checker. Primary cells: `random124` at $R = 1$ and $R = 4$,\n",
    "  `native3` at $R = 3$, each with proofs and single steps; secondary cells as the queue allowed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38beb3b5",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT,\n",
    "                       \"and random124 (R drawn from {1, 2, 4} per update, latent's rule)\",\n",
    "                       \"**4,096 updates** (Stage 1a's). No checkpoint selection: the adapter after update 4,096 is evaluated.\",\n",
    "                       \"**Seeds 11, 29, 47**\",\n",
    "                       \"Seed 11: the four Stage 1a adapters at 4,096 updates, reused unchanged\",\n",
    "                       \"by its plan 48 targets\",\n",
    "                       \"**Single-step roster (256 rows):** latent's own 128 test validation rows (16 per stratum, by its \"\n",
    "                       \"plan) **plus 128\",\n",
    "                       \"the first 16. If a stratum has fewer eligible rows, all are taken and the roster is smaller\",\n",
    "                       \"runs once, in a CPU job that starts only after all twelve adapters exist\",\n",
    "                       \"**Primary cells, per adapter:** random124 at R = 1 and R = 4, native3 at R = 3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19560324",
   "metadata": {},
   "source": [
    "## The registered rules\n",
    "\n",
    "Paired units: (seed, roster row) for single steps and (seed, target) for proofs, pooled over the seeds; exact\n",
    "two-sided McNemar tests; Holm over the primary family, P1 and P3.\n",
    "\n",
    "* **P1, more loops help ARLoop** (the 1a lead): ARLoop's `random124` adapters, valid single steps at $R = 4$\n",
    "  against $R = 1$. \"More loops help ARLoop\" if the Holm-adjusted p is below 0.05, the pooled difference is\n",
    "  positive and at least two of the three seeds agree.\n",
    "* **P3, the pair at its trained depth:** `native3` at $R = 3$, accepted test proofs, ARLoop against PreNorm.\n",
    "* **P2 (secondary), the design contrast:** ARLoop's gain from $R = 1$ to $R = 4$ minus PreNorm's, with a paired\n",
    "  bootstrap interval over roster rows within seeds; \"ARLoop gains more\" if the interval lies above 0.\n",
    "* **Further secondaries:** PreNorm's own depth effect (S1), proofs at $R = 4$ against $R = 1$ (S2), how far the\n",
    "  attempts get (S3), `random124` against `native3` at $R = 4$ (S4), per-seed tables (S5)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec86de44",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT, \"The primary family is {P1, P3}, Holm-adjusted at 0.05.\",\n",
    "                       \"and at least 2 of the 3 seeds have more rows valid only at R = 4 than only at R = 1\",\n",
    "                       \"if the 95% interval excludes 0 and the mean is positive\",\n",
    "                       \"rows within each seed (10,000 resamples, seed 20261115)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7a105d3",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "407b71b6",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if not ready:\n",
    "    lib.pending(\"Stage 4\", \"The run is in progress. Its files (`runs/s4/s4.json`, the recount and the replay in \"\n",
    "                \"`runs/s4/referee/`) and its re-check note (`runs/s4/referee.md`) are not all there yet, so this \"\n",
    "                \"section shows no numbers.\")\n",
    "else:\n",
    "    jobs = [l.split() for l in (S4 / \"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",
    "    held = sum(hms(j[4]) for j in jobs if j[2] == \"gpu_csi\" and j[3].rstrip(\"+\") == \"TIMEOUT\") / 3600\n",
    "    other = sum(1 for j in jobs if j[3] != \"COMPLETED\" or j[5] != \"0:0\")   # named in the re-check note\n",
    "    ended = (\"all completed with exit code 0\" if not other else\n",
    "             f\"{len(jobs) - other} completed with exit code 0 and {other} ended otherwise (named in the re-check note)\")\n",
    "    def cells(cs):\n",
    "        \"\"\"['native3@R3', 'random124@R1', ...] -> '`native3` at R = 3; `random124` at R = 1 and 4'.\"\"\"\n",
    "        by = {}\n",
    "        for c in cs:\n",
    "            arm, R = c.split(\"@R\")\n",
    "            by.setdefault(arm, []).append(int(R))\n",
    "        return \"; \".join(f\"`{a}` at R = \" + (\", \".join(map(str, sorted(Rs)[:-1])) + f\" and {max(Rs)}\" if len(Rs) > 1\n",
    "                                              else str(Rs[0])) for a, Rs in by.items())\n",
    "    lib.md(f\"**Runs.** {len(jobs)} jobs on WMI, {ended}, {gpu_h:.1f} GPU-hours\" + (f\" ({held:.1f} of them one job held until its time limit)\" if held else \"\")\n",
    "           + f\"; seeds \"\n",
    "           f\"{', '.join(map(str, SEEDS))}; {T} test targets and a {N}-row roster\" + (\n",
    "               f\" ({RC['latent_rows']} of `latent`'s validation rows plus {RC['extra_rows']} drawn; \"\n",
    "               f\"{sum(v['eligible'] == 0 for v in RC['per_stratum'].values())} of the {len(RC['per_stratum'])} strata \"\n",
    "               \"had no eligible row)\" if RC else \"\") + \". Measured: \"\n",
    "           f\"{cells(S4J['measured_cells'])}\" + (f\"; not measured: {cells(S4J['not_measured'])}\"\n",
    "                                                 if S4J[\"not_measured\"] else \"\") + \". **[exp]**\")\n",
    "    rows = [(\"P1, more loops help ARLoop\", f\"{P1['only_R4']} / {P1['only_R1']}\", f\"{P1['units']:,}\",\n",
    "             lib.pvalue(P1[\"mcnemar_p\"]), lib.pvalue(P1[\"holm_p\"]), f\"{P1['seeds_R4_ahead']} of {len(SEEDS)} for R = 4\",\n",
    "             f\"**{P1['verdict']}**\"),\n",
    "            (\"P3, the pair at R = 3\", f\"{P3['only_arloop']} / {P3['only_prenorm']}\", f\"{P3['units']:,}\",\n",
    "             lib.pvalue(P3[\"mcnemar_p\"]), lib.pvalue(P3[\"holm_p\"]),\n",
    "             f\"ARLoop {P3['seeds_arloop_ahead']}, PreNorm {P3['seeds_prenorm_ahead']}\", f\"**{P3['verdict']}**\"),\n",
    "            (\"S1, PreNorm's depth effect\", f\"{S1['only_R4']} / {S1['only_R1']}\", f\"{S1['units']:,}\",\n",
    "             lib.pvalue(S1[\"mcnemar_p\"]), \"–\", f\"{S1['seeds_R4_ahead']} of {len(SEEDS)} for R = 4\", \"reported\")]\n",
    "    lib.md(\"**The registered tests** (P1: rows valid only at R = 4 / only at R = 1; P3: targets proved only by \"\n",
    "           \"ARLoop / only by PreNorm):\\n\\n\" + lib.table(rows, [\"test\", \"discordant\", \"paired units\", \"exact McNemar p\",\n",
    "                                                                \"Holm p\", \"seeds\", \"verdict\"]))\n",
    "    lib.md(f\"**P2, the design contrast (secondary):** ARLoop's gain from R = 1 to R = 4 minus PreNorm's, \"\n",
    "           f\"{pts(P2['mean'])} points [{pts(P2['ci95'][0])}, {pts(P2['ci95'][1])}] over {P2['units']:,} units: \"\n",
    "           f\"**{P2['verdict']}**\" + (\"; the interval lies below 0: here PreNorm gains more from loops than ARLoop\"\n",
    "                                     if P2[\"ci95\"][1] < 0 else \"\") + \". **[exp]**\")\n",
    "    prim = [r for r in S4J[\"S5\"] if \"dev_accepted\" in r]\n",
    "    rows = [(SHORT[r[\"base\"]], f\"`{r['arm']}`\", r[\"R\"], r[\"seed\"], f\"{r['test_accepted']} · {r['test_valid']}\",\n",
    "             \"–\" if r[\"dev_accepted\"] is None else f\"{r['dev_accepted']} · {r['dev_valid']}\") for r in prim]\n",
    "    lib.md(f\"**Per seed** (primary cells; accepted proofs · valid single steps; test of {T} targets and {N} rows, \"\n",
    "           \"development split as in Stage 1a):\\n\\n\" + lib.table(rows, [\"base\", \"arm\", \"R\", \"seed\", \"test\", \"development\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7cadcfe7",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    P = lib.PALETTE\n",
    "    HUE = {\"arloop\": P[\"ar\"], \"prenorm\": P[\"pn\"]}\n",
    "    xs = sorted({r[\"R\"] for r in S4J[\"S5\"] if r[\"arm\"] == \"random124\"})\n",
    "    k = len(SEEDS)\n",
    "    fig, axes = lib.figure(1, 2, figsize=(7.5, 3.4))\n",
    "    for ax, (key, title, f) in zip(axes, ((\"test_valid\", f\"invalid single steps (of {N} rows × {k} seeds)\",\n",
    "                                           lambda v: k * N - v),\n",
    "                                          (\"test_accepted\", f\"proofs (of {T} targets × {k} seeds)\", lambda v: v))):\n",
    "        lib.style(ax)\n",
    "        for b in BASES:\n",
    "            ys = [f(sum(r[key] for r in S4J[\"S5\"] if r[\"base\"] == b and r[\"arm\"] == \"random124\" and r[\"R\"] == R)) for R in xs]\n",
    "            ax.plot(xs, ys, color=HUE[b], lw=2, marker=\"o\", ms=5, mec=P[\"paper\"], mew=1.5, label=NAME[b])\n",
    "        ax.set_title(title, fontsize=10)\n",
    "        ax.set_xticks(xs)\n",
    "        ax.set_xlabel(\"loops R at test time\")\n",
    "        ax.set_ylim(bottom=0)\n",
    "    axes[0].legend(frameon=False, fontsize=8, labelcolor=P[\"ink\"])\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n",
    "    lib.md(\"*The `random124` adapters (trained with a random number of loops) on the test split, pooled over the seeds, \"\n",
    "           \"against the number of loops at test time. From `runs/s4/s4.json`.*\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f79c309",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    out = []\n",
    "    if P1[\"verdict\"] == \"more loops help ARLoop\":\n",
    "        out.append(f\"**More loops help ARLoop on unseen goals.** Its random-depth adapters are valid on {P1['only_R4']} \"\n",
    "                   f\"roster rows only at R = 4 against {P1['only_R1']} only at R = 1 ({pts(P1['diff'])} points); \"\n",
    "                   f\"{P1['seeds_R4_ahead']} of {len(SEEDS)} seeds agree. Stage 1a's lead is confirmed, as registered: \"\n",
    "                   \"a result of looping within a model ({doc}`sense 1 <stage1>`), for ARLoop. **[exp]**\")\n",
    "    else:\n",
    "        why = (\"This does not show that more loops cannot help ARLoop: it shows that no effect large enough for this \"\n",
    "               \"test appeared in these seeds.\" if P1[\"holm_p\"] >= 0.05 else\n",
    "               \"The difference goes the other way: on these rows one loop does better than four.\"\n",
    "               if P1[\"only_R1\"] > P1[\"only_R4\"] else\n",
    "               f\"The pooled difference passes Holm, but only {P1['seeds_R4_ahead']} of {len(SEEDS)} seeds \"\n",
    "               f\"{'favours' if P1['seeds_R4_ahead'] == 1 else 'favour'} R = 4, \"\n",
    "               \"and the registered rule needs two.\")\n",
    "        out.append(f\"**Stage 1a's lead is not confirmed.** ARLoop's random-depth adapters are valid on {P1['only_R4']} \"\n",
    "                   f\"rows only at R = 4 against {P1['only_R1']} only at R = 1 ({pts(P1['diff'])} points); Holm p = \"\n",
    "                   f\"{lib.pvalue(P1['holm_p'])}. {why} **[exp]**\")\n",
    "    out.append({\"no detectable difference\": f\"**At the trained depth, no detectable difference** in test proofs \"\n",
    "                f\"({P3['only_arloop']} targets only by ARLoop against {P3['only_prenorm']} only by PreNorm); \"\n",
    "                + (\"the pooled difference passes Holm, but fewer than two seeds agree, which the registered rule needs.\"\n",
    "                   if P3[\"holm_p\"] < 0.05 else \"with so few proofs a difference of a few targets is not excluded.\"),\n",
    "                \"ARLoop proves more\": f\"**At the trained depth, ARLoop proves more test goals** ({P3['only_arloop']} \"\n",
    "                f\"against {P3['only_prenorm']} discordant targets, Holm p = {lib.pvalue(P3['holm_p'])}).\",\n",
    "                \"PreNorm proves more\": f\"**At the trained depth, PreNorm proves more test goals** ({P3['only_prenorm']} \"\n",
    "                f\"against {P3['only_arloop']} discordant targets, Holm p = {lib.pvalue(P3['holm_p'])}).\"}[P3[\"verdict\"]])\n",
    "    cells = S4J[\"S3\"][\"cells\"]\n",
    "    skipped = REP.get(\"partial_files_skipped\", [])\n",
    "    meas = [c for c in cells.values() if c.get(\"measured\")]\n",
    "    out.append(f\"**How far the attempts get (S3, `k.e3-rollouts`):** measured in {len(meas)} of {len(cells)} cells; \"\n",
    "               f\"supported: **{'yes' if S4J['S3']['supported'] else 'no'}** (the rule needs ARLoop's attempts longer in all four \"\n",
    "               \"cells, each at Holm p < 0.05).\")\n",
    "    lib.md(\"\\n\\n\".join(out))\n",
    "    lib.note(\"Independent re-check\",\n",
    "             f\"`runs/s4/referee.md`. A separate script recounted every evaluated cell from the raw per-target and per-row \"\n",
    "             f\"records and recomputed P1, P3, P2's mean and the secondaries: {len(REC['problems'])} disagreements. Another \"\n",
    "             f\"replayed every recorded test attempt with the admitted checker: {REP['replayed_attempts']:,} attempts, \"\n",
    "             f\"{REP['qed_total']} kernel-checked QEDs, exactly the {REP['accepted_records']} accepted proofs\"\n",
    "             + (f\"; {len(skipped)} partial proof file{'s' if len(skipped) > 1 else ''} of \"\n",
    "                f\"{'stopped jobs' if len(skipped) > 1 else 'a stopped job'}, which the analysis does not count either, not \"\n",
    "                \"replayed\" if skipped else \"\") + \".\", \"important\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "946118ef",
   "metadata": {},
   "source": [
    "**Limits.** Three seeds of one recipe, one model size and one corpus. A null result bounds what three seeds can\n",
    "detect; it is not evidence that no effect exists. The test split of Campaign 4 is now used: it cannot serve another\n",
    "confirmatory test of these questions."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
