{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a2d2ffed",
   "metadata": {},
   "source": [
    "# Stage 2: the whole model, trained at more loops\n",
    "\n",
    "Stage 1c ({doc}`stage1`) trained only the routing of a fourth loop in the released ARLoop-0.6B, with the read-out\n",
    "frozen, and found no gain on GSM8K. Stage 2 is the whole-model counterpart, registered before any run\n",
    "(`experiments/s2_depth/PROTOCOL.md`): both released 0.6B models trained further with every parameter, once at their\n",
    "own depth and once at one more loop, on the same data and the same number of updates. It asks for a result of\n",
    "looping between models (sense 2 of {doc}`stage1`): does a model trained at more loops beat one trained at fewer?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8056c87f",
   "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\" / \"s2_depth\" / \"PROTOCOL.md\"\n",
    "S2 = lib.RUNS / \"s2\"\n",
    "ref2 = text_or_none(S2 / \"referee.md\")\n",
    "D = lib.read_json(S2 / \"analysis\" / \"depth.json\")         # written by experiments/s2_depth/analyze_depth.py\n",
    "REC = lib.read_json(S2 / \"referee\" / \"s2_recount.json\")\n",
    "ready = all(x is not None for x in (ref2, D, REC))\n",
    "if ready:\n",
    "    r1, r2, r3 = D[\"rule1\"], D[\"rule2\"], D[\"rule3\"]\n",
    "    assert not REC[\"mismatches\"]\n",
    "    for b, r in r1.items():\n",
    "        assert r[\"passes\"] == (r[\"diff\"] > 0 and r[\"holm_p\"] < 0.05)\n",
    "        mine = REC[\"comparisons\"][f\"rule1 {b}\"]\n",
    "        assert (mine[\"only_a\"], mine[\"only_b\"]) == (r[\"only_a\"], r[\"only_b\"])\n",
    "    assert r2[\"arloop_gains_more\"] == (r2[\"ci95\"][0] > 0)\n",
    "    tr = D[\"training\"]\n",
    "    (U,), (TOK,) = {v[\"updates\"] for v in tr.values()}, {v[\"tokens\"] for v in tr.values()}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "716f85e9",
   "metadata": {},
   "source": [
    "## The design\n",
    "\n",
    "* **Models and arms:** ARLoop-0.6B and PreNormLoop-0.6B, every parameter trained; arm `R3` at the released depth\n",
    "  (the control) and arm `R4` at one more loop. ARLoop's routing for loop 4 starts as a copy of loop 1's (E1's\n",
    "  `cycle` rule) and is trained with everything else. A random-depth arm, with $R$ drawn per update from\n",
    "  $\\{2, 3, 4, 5\\}$, is registered to run only if a further GPU becomes free; by amendment 2 it runs for PreNorm\n",
    "  only (ARLoop's needs more memory than the free GPU has).\n",
    "* **Data and budget:** Stage 1c's audited FineMath-4+ shard (0.1B tokens, one document removed by the 13-gram GSM8K\n",
    "  filter), one pass, the same order and seed in every arm; not the authors' stage-3 mixture, which could not be\n",
    "  rebuilt in time.\n",
    "* **Hardware:** each model's two arms on one GPU, one after the other, so that each comparison stays on one GPU\n",
    "  type (on WMI; Helios's GH200 partition was down).\n",
    "* **Evaluation:** E1's GSM8K harness (5-shot chain of thought, BOS, flexible extract, all 1,319 test items) and\n",
    "  WikiText-2 bits per byte, for every trained model at $R = 3$ and $R = 4$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9202677",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT,\n",
    "                       \"ARLoop's 36 routing queries and 36 norm weights of loop 4 start as independent copies of loop 1's \"\n",
    "                       \"(E1's `cycle` rule; `depthmodel.py`)\",\n",
    "                       \"is registered below but runs only if a further GPU becomes free without displacing Stage 4.\",\n",
    "                       \"**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",
    "                       \"each base's two arms on one GPU, one after the other, so that each primary comparison is within \"\n",
    "                       \"one GPU type\",\n",
    "                       \"Helios's GH200 partition is down\",\n",
    "                       \"R drawn per update from {2, 3, 4, 5}\",\n",
    "                       \"to run the random-depth arm for PreNorm only.\",\n",
    "                       \"ARLoop's `Rrand` does not run.** ARLoop's training peaked at 35.14 GB at R = 4 (its metrics), more than the\",\n",
    "                       \"(gsm8k_cot, 5-shot, BOS, flexible extract, all 1,319 test items, greedy, <= 1,024 new tokens)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c480a871",
   "metadata": {},
   "source": [
    "## The registered rules\n",
    "\n",
    "* **Primary, per model:** the model trained at $R = 4$, run at $R = 4$, against the control trained at $R = 3$, run\n",
    "  at $R = 3$, paired over the GSM8K items (exact McNemar, paired bootstrap interval); Holm over the two models.\n",
    "  \"Training at depth makes the fourth loop pay off\" for a model if its difference is positive and its Holm-adjusted\n",
    "  p is below 0.05.\n",
    "* **Design contrast (secondary):** ARLoop's difference minus PreNorm's, with a paired bootstrap interval;\n",
    "  \"ARLoop gains more from depth training\" if the interval lies above 0.\n",
    "* **Further secondaries:** each trained model against its released model at the same $R$ (what the training does\n",
    "  without a change of depth), the cross-depth evaluations and WikiText-2.\n",
    "* **Random depth (rule 6, PreNorm only, descriptive):** the random-depth model's accuracy at each $R$ from 2 to 5,\n",
    "  and $R = 5$ against $R = 3$ with the paired statistics of E1; no decision rule."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86ade2b7",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT, \"Holm over the two bases. \\\"Training at depth makes the fourth loop pay off\\\" for a base if \"\n",
    "                             \"its difference is positive and its Holm-adjusted p is below 0.05.\",\n",
    "                       \"\\\"ARLoop gains more from depth training\\\" if the interval excludes 0 on the positive side.\",\n",
    "                       \"R = 5 against R = 3 with E1's paired statistics; descriptive.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7016a31",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc633733",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if not ready:\n",
    "    lib.pending(\"Stage 2\", \"The trainings and evaluations are in progress. Their files (`runs/s2/analysis/depth.json`, \"\n",
    "                \"the recount in `runs/s2/referee/`) and the re-check note (`runs/s2/referee.md`) are not all there yet, \"\n",
    "                \"so this section shows no numbers.\")\n",
    "else:\n",
    "    acc = D[\"accuracy\"]\n",
    "    gpus = {b: next(v[\"gpu\"] for k, v in tr.items() if k.startswith(b + \"-\")) for b in BASES}\n",
    "    lib.md(f\"**Runs.** {U:,} updates ({TOK / 1e9:.2f}B tokens) per training, one seed; ARLoop on one \"\n",
    "           f\"{gpus['arloop']}, PreNorm on one {gpus['prenorm']}. **[exp]**\")\n",
    "    rows = [(SHORT[b], f\"{100 * acc[f'{b}-R3-R3']:.2f}\", f\"{100 * acc[f'{b}-R4-R4']:.2f}\", pts(r1[b][\"diff\"]),\n",
    "             f\"[{pts(r1[b]['ci95'][0])}, {pts(r1[b]['ci95'][1])}]\", f\"{r1[b]['only_a']} / {r1[b]['only_b']}\",\n",
    "             lib.pvalue(r1[b][\"holm_p\"]), \"**pays off**\" if r1[b][\"passes\"] else \"**not established** (a loss)\"\n",
    "             if r1[b][\"diff\"] < 0 and r1[b][\"holm_p\"] < 0.05 else \"**not established**\") for b in BASES]\n",
    "    lib.md(\"**Primary:** GSM8K accuracy (%) of the control (trained and run at R = 3) and of the model trained and run \"\n",
    "           \"at R = 4, paired over the items; Holm over the two models.\\n\\n\" +\n",
    "           lib.table(rows, [\"model\", \"trained and run at 3\", \"trained and run at 4\", \"difference\", \"95% interval\",\n",
    "                            \"discordant\", \"Holm p\", \"verdict\"]))\n",
    "    lib.md(f\"**Design contrast (secondary):** ARLoop's difference minus PreNorm's, {pts(r2['diff'])} points \"\n",
    "           f\"[{pts(r2['ci95'][0])}, {pts(r2['ci95'][1])}]: \"\n",
    "           f\"**{'ARLoop gains more from depth training' if r2['arloop_gains_more'] else 'not established'}**\"\n",
    "           + (\"; the interval lies below 0: here PreNorm gains more from depth training than ARLoop\" if r2[\"ci95\"][1] < 0\n",
    "              else \"\") + \". **[exp]**\")\n",
    "    def side(s):\n",
    "        \"\"\"'arloop-R4-R3' -> 'trained at 4, run at 3'; 'released R3' -> 'released, run at 3'.\"\"\"\n",
    "        m = re.fullmatch(r\"(?:\\w+)-R(\\d|rand)-R(\\d)\", s)\n",
    "        if m:\n",
    "            return f\"trained at {m.group(1)}, run at {m.group(2)}\"\n",
    "        m = re.fullmatch(r\"released R(\\d)\", s)\n",
    "        return f\"released, run at {m.group(1)}\" if m else s\n",
    "\n",
    "    def label(k):\n",
    "        a, b = k.split(\" vs \")\n",
    "        return f\"{SHORT[a.split('-')[0]]}: {side(a)} against {side(b)}\"\n",
    "    rows = [(label(k), pts(v[\"diff\"]), f\"[{pts(v['ci95'][0])}, {pts(v['ci95'][1])}]\",\n",
    "             lib.pvalue(v[\"mcnemar_p\"])) for k, v in list(r3.items()) + list(D[\"rule4\"].items())]\n",
    "    lib.md(\"**Secondary comparisons** (training effect against the released model at the same R; cross-depth):\\n\\n\"\n",
    "           + lib.table(rows, [\"comparison\", \"difference\", \"95% interval\", \"exact McNemar p\"]))\n",
    "    if D[\"wikitext_bpb\"]:\n",
    "        wt, wr = D[\"wikitext_bpb\"], D[\"wikitext_bpb_released\"]\n",
    "        cols = [(\"R3\", 3), (\"R3\", 4), (\"R4\", 3), (\"R4\", 4)]\n",
    "        rows = [(SHORT[b], *(f\"{wt[f'{b}-{a}-R{l}']:.4f}\" if f\"{b}-{a}-R{l}\" in wt else \"–\" for a, l in cols),\n",
    "                 *(f\"{wr[f'{b}-R{l}']:.4f}\" if f\"{b}-R{l}\" in wr else \"–\" for l in (3, 4))) for b in BASES]\n",
    "        lib.md(\"**WikiText-2 bits per byte** (descriptive; lower is better):\\n\\n\" + lib.table(rows, [\n",
    "            \"model\", \"trained at 3, run at 3\", \"trained at 3, run at 4\", \"trained at 4, run at 3\", \"trained at 4, run at 4\",\n",
    "            \"released, run at 3\", \"released, run at 4\"]))\n",
    "    TASK = {\"gsm8k\": \"GSM8K\", \"wikitext\": \"WikiText-2\"}\n",
    "    gone = [f\"{TASK[t]}, {SHORT[r.split('-')[0]]} {side(r)}\" for t, r in (m.split(\" \", 1) for m in D[\"missing_secondary\"])]\n",
    "    if gone:\n",
    "        lib.md(\"**Not evaluated** (secondary): \" + \"; \".join(gone) + \".\")\n",
    "    # rule 6, descriptive: PreNorm's random-depth arm (amendment 2); ARLoop's did not run\n",
    "    RR = [int(x) for x in re.search(r\"R drawn per update from \\{([\\d, ]+)\\}\", PROT.read_text()).group(1).split(\", \")]\n",
    "    acc_rr = {R: acc[f\"prenorm-Rrand-R{R}\"] for R in RR if f\"prenorm-Rrand-R{R}\" in acc}\n",
    "    vs3 = {R: D[\"rule6\"][f\"prenorm-Rrand-R{R} vs prenorm-Rrand-R3\"] for R in RR\n",
    "           if f\"prenorm-Rrand-R{R} vs prenorm-Rrand-R3\" in D[\"rule6\"]}\n",
    "    rr_head = \"**Random depth, PreNorm only** (rule 6, descriptive: no decision rule; amendment 2). \"\n",
    "    if acc_rr:\n",
    "        rows = [(\"accuracy (%)\", *(f\"{100 * acc_rr[R]:.2f}\" if R in acc_rr else \"–\" for R in RR)),\n",
    "                (\"against R = 3, points\", *(pts(vs3[R][\"diff\"]) if R in vs3 else \"–\" for R in RR)),\n",
    "                (\"95% interval\", *(f\"[{pts(vs3[R]['ci95'][0])}, {pts(vs3[R]['ci95'][1])}]\" if R in vs3 else \"–\" for R in RR))]\n",
    "        missing = [str(R) for R in RR if R not in acc_rr]\n",
    "        lib.md(rr_head + \"PreNormLoop-0.6B trained the same way, but with a random number of loops in each update, from \"\n",
    "               f\"{min(RR)} to {max(RR)}, then evaluated on GSM8K at \"\n",
    "               + (\"each number of loops\" if not missing else \"R = \" + \", \".join(map(str, acc_rr))) + \":\\n\\n\"\n",
    "               + lib.table(rows, [\"random-depth PreNorm\", *(f\"R = {R}\" for R in RR)]) + \"\\n\\n\"\n",
    "               + (f\"Not evaluated at R = {', '.join(missing)} (the job ended first; `runs/s2/referee.md`). \" if missing else \"\")\n",
    "               + \"ARLoop's random-depth arm did not run (amendment 2). **[exp]**\")\n",
    "    else:\n",
    "        lib.md(rr_head + (\"Trained, but not evaluated\" if \"prenorm-Rrand\" in tr else \"No result: the training did not finish\")\n",
    "               + \" (`runs/s2/referee.md`). ARLoop's random-depth arm did not run.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1762fc58",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    P = lib.PALETTE\n",
    "    rows = [(f\"{NAME[b]}: 4 loops vs 3\", r1[b], P[\"ar\"] if b == \"arloop\" else P[\"pn\"]) for b in BASES]\n",
    "    rows.append((\"ARLoop minus PreNorm\", r2, P[\"ink\"]))\n",
    "    fig, ax = lib.figure(figsize=(7.5, 2.6))\n",
    "    lib.style(ax, grid=\"x\")\n",
    "    for i, (label, r, col) in enumerate(rows):\n",
    "        y = len(rows) - 1 - i\n",
    "        ax.plot([100 * r[\"ci95\"][0], 100 * r[\"ci95\"][1]], [y, y], color=col, lw=2.5, solid_capstyle=\"round\")\n",
    "        ax.plot([100 * r[\"diff\"]], [y], \"o\", color=col, ms=6, mec=P[\"paper\"], mew=1.5)\n",
    "    ax.axvline(0, color=P[\"ink\"], lw=1)\n",
    "    ax.set_yticks(range(len(rows)))\n",
    "    ax.set_yticklabels([r[0] for r in reversed(rows)], fontsize=9)\n",
    "    ax.set_xlabel(\"GSM8K difference, points (95% paired bootstrap interval)\")\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n",
    "    lib.md(\"*The primary comparisons and the design contrast. From `runs/s2/analysis/depth.json`.*\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "016483d8",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ready:\n",
    "    passed = [b for b in BASES if r1[b][\"passes\"]]\n",
    "    lost = [b for b in BASES if r1[b][\"diff\"] < 0 and r1[b][\"holm_p\"] < 0.05]      # described, not a registered verdict\n",
    "    worse = ((f\" Trained at one more loop, {' and '.join(NAME[b] for b in lost)} \"\n",
    "              + (\"does worse than its control.\" if len(lost) == 1 else \"do worse than their controls.\")) if lost else \"\")\n",
    "    if passed:\n",
    "        txt = (f\"**Training at depth makes the fourth loop pay off for {' and '.join(NAME[b] for b in passed)}:** trained \"\n",
    "               f\"at one more loop, {'the model' if len(passed) == 1 else 'each model'} beats its control trained at the \"\n",
    "               \"released depth, on the same data and updates. This is a result of looping between models \"\n",
    "               \"({doc}`sense 2 <stage1>`), with one seed. \")\n",
    "        txt += (\"ARLoop gains more than PreNorm (the design contrast).\" if r2[\"arloop_gains_more\"] else\n",
    "                \"PreNorm gains more than ARLoop (the design contrast's interval lies below 0, a direction the rule does \"\n",
    "                \"not test).\" if r2[\"ci95\"][1] < 0 else\n",
    "                \"Whether ARLoop gains more than PreNorm is not established (the design contrast).\") + worse + \" **[exp]**\"\n",
    "    else:\n",
    "        txt = (\"**No gain from training at depth is detected for either model** at this budget.\" + worse\n",
    "               + f\" One seed and {TOK / 1e9:.1f}B tokens do not exclude a gain with longer training. **[exp]**\")\n",
    "    lib.md(txt)\n",
    "    v6 = D[\"rule6\"].get(f\"prenorm-Rrand-R{max(RR)} vs prenorm-Rrand-R3\")\n",
    "    if v6:\n",
    "        how = (f\"higher at R = {max(RR)} than at R = 3\" if v6[\"ci95\"][0] > 0 else\n",
    "               f\"lower at R = {max(RR)} than at R = 3\" if v6[\"ci95\"][1] < 0 else\n",
    "               f\"not detectably different between R = {max(RR)} and R = 3\")\n",
    "        lib.md(f\"**Within PreNorm's random-depth model** (descriptive): accuracy is {how}, \"\n",
    "               f\"{pts(v6['diff'])} points [{pts(v6['ci95'][0])}, {pts(v6['ci95'][1])}]. A description of one model and one \"\n",
    "               \"seed, not a registered test (a result of looping within a model would be {doc}`sense 1 <stage1>`); it says \"\n",
    "               \"nothing about ARLoop. **[exp]**\")\n",
    "    lib.note(\"Independent re-check\",\n",
    "             f\"`runs/s2/referee.md`. A separate script re-scored every GSM8K item of every Stage 2 evaluation and of E1's \"\n",
    "             f\"released references from the raw generations and recomputed every comparison: \"\n",
    "             f\"{len(REC['comparisons'])} comparisons, {len(REC['mismatches'])} disagreements.\", \"important\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ca2588e",
   "metadata": {},
   "source": [
    "**Limits.** One seed; the 0.1B tokens of math text of Stage 1c, not the authors' pretraining mixture; one model\n",
    "size. The two models trained on different GPU types (each model's own comparison stays on one type). A null result\n",
    "bounds what this budget can detect; it is not evidence that no effect exists. The random-depth arm ran for PreNorm\n",
    "only and is read descriptively."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
