{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bdc4a07f",
   "metadata": {},
   "source": [
    "# ARLoop: attention over depth for looped transformers — review and tests in the recurrent-proof regime\n",
    "\n",
    "**Seminar notes** for a 45-minute talk at the CCAI Agents seminar on Tuesday 2026-11-17, 14:00.\n",
    "Speaker: Bartosz Naskręcki. Audience: ML/AI researchers.\n",
    "\n",
    "The talk reviews Yuekun Yao, Yupei Du, Dawei Zhu and Huan Sun, *ARLoop: Fully-Open Pre-trained\n",
    "Looped Transformers with Attention Residuals*, arXiv:2611.05234 {cite}`arloop2026`, re-measures\n",
    "its claims on the released checkpoints, and tests the idea in the regime of our own `latent`\n",
    "programme: recurrent depth for checked proofs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80e8b980",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0acdd6f7",
   "metadata": {},
   "source": [
    ":::{admonition} The result in three lines\n",
    ":class: important\n",
    "* In a looped transformer the residual stream is the only memory that carries information from\n",
    "  one pass to the next, and PreNorm adds every update to it with weight 1. ARLoop replaces this\n",
    "  fixed sum by **softmax attention over depth** (the Attention Residuals of\n",
    "  {cite}`kimi2026attnres`) and finds that, for loops, a **sliding window** (the embedding and the\n",
    "  3 most recent residual blocks) is enough, as long as the model also has *value residuals*: a\n",
    "  gated token embedding added to the attention values at alternating layers\n",
    "  {cite}`zhou2025valueresidual` (its App. A.1 and A.3). **[paper]**\n",
    "* Controlled 140M/370M runs: the lowest validation perplexity among six residual designs at every\n",
    "  recurrence tried; at 0.6B (180B tokens, R = 3) it beats a matched PreNorm loop on 7 of 8\n",
    "  benchmarks (GSM8K {cite}`cobbe2021gsm8k` 40.9 vs 35.7); a 1.2B model (0.5T tokens) beats Huginn-3.5B on all 8.\n",
    "  **[paper]**\n",
    "* It does **not** make loops extrapolate: performance rises up to the trained recurrence and not\n",
    "  beyond, even with depth queries trained for the new depths. **[paper]**\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ec75899",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# Guards for the three lines (the tables are transcribed in seminar_lib and compared with the LaTeX\n",
    "# in the chapter on the paper's evidence).\n",
    "assert len(lib.TAB1) == 6 and {s for s, _ in lib.TAB1_COLS} == {\"140M\", \"370M\"}\n",
    "assert all(min(lib.TAB1, key=lambda m: lib.TAB1[m][c]) == \"ARLoop\"\n",
    "           and sorted(v[c] for v in lib.TAB1.values())[0] < sorted(v[c] for v in lib.TAB1.values())[1]\n",
    "           for c in range(len(lib.TAB1_COLS)))\n",
    "for name in (\"ARLoop-0.6B\", \"ARLoop-1.2B\"):\n",
    "    assert lib.config(name)[\"sw_blocks\"] == 3\n",
    "pair, big = lib.TAB3[\"ARLoop-0.6B\"], lib.TAB3[\"ARLoop-1.2B\"]\n",
    "assert pair[0] == 3 and pair[2] * 1000 == 180 and big[2] == 0.5\n",
    "assert len(lib.wins(\"ARLoop-0.6B\", \"PreNormLoop-0.6B\")) == 7\n",
    "assert lib.scores(\"ARLoop-0.6B\")[\"GSM8K\"] == 40.9 and lib.scores(\"PreNormLoop-0.6B\")[\"GSM8K\"] == 35.7\n",
    "assert len(lib.wins(\"ARLoop-1.2B\", \"Huginn-3.5B\")) == 8 == len(lib.BENCHMARKS)\n",
    "assert lib.quote_check(lib.DIGEST, \"Condition [paper: App. A.3, Tab. 7, and App. A.1; finding F11]: the window's edge needs value residuals\")\n",
    "if (lib.LATEX / \"main\" / \"appendix.tex\").exists():    # the definition of value residuals, as the paper gives it\n",
    "    assert lib.quote_check(lib.LATEX / \"main\" / \"appendix.tex\",\n",
    "                           \"at alternating effective layers (e.g., the 1st, 3rd, and 5th layers), we inject a gated token \"\n",
    "                           \"embedding into the value vectors of the self-attention sublayer.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffb4bd8f",
   "metadata": {},
   "source": [
    "Why this paper for this audience: in `latent` we retrofitted recurrence onto a pretrained Qwen\n",
    "model and found that extra passes rarely helped checked proofs and that learned stopping collapsed\n",
    "to a single pass ({doc}`latent`). ARLoop claims that the **residual design** affects how much later\n",
    "passes are used. That is a testable claim, and the released matched pair (ARLoop-0.6B and\n",
    "PreNormLoop-0.6B: same data, same backbone, only the residual path differs) lets us test it.\n",
    "\n",
    "## How to read these notes\n",
    "\n",
    "The paper itself, digested on one page, with every claim tagged and the findings register:\n",
    "{doc}`digest`. The chapters below follow the five parts of the talk: I the idea, II the paper's evidence, III\n",
    "the released checkpoints, IV checked proofs, V training more.\n",
    "\n",
    "| minutes | part | chapter | content |\n",
    "|---|---|---|---|\n",
    "| 0–⁠3:05 | I | this page and {doc}`latent` | the question of the talk: what decides whether an extra loop is used? |\n",
    "| 3:05–⁠7:15 | I | {doc}`looped` | looped transformers; the residual stream is the loop's only memory |\n",
    "| 7:15–⁠13:45 | I | {doc}`mechanism/mechanism` | attention over depth, blocks, the sliding window, one routing query per sublayer, a worked example |\n",
    "| 13:45–⁠19:25 | II | {doc}`evidence` | the paper's Tables 1–3, locality, extrapolation, cost |\n",
    "| 19:25–⁠28:55 | III | {doc}`tests/e1_release` | the GSM8K gap of the pair, more loops than trained, where the routing reads |\n",
    "| 28:55–⁠35:20 | IV | {doc}`tests/e2_canary`, {doc}`tests/e3_proofs` | E2 and E3: the idea in the checked-proof regime |\n",
    "| 35:20–⁠37:50 | IV | live demo (not in the notes) | one question, both models, several numbers of loops |\n",
    "| 37:50–⁠45 | V | {doc}`tests/stage1`, {doc}`latent`, {doc}`exercises` | training more: Stage 1, then the confirmatory proof run (Stage 4) and continued training at depth (Stage 2), both pending until re-checked ({doc}`tests/tests`); the research map, what next, questions |\n",
    "\n",
    ":::{admonition} Every number on these pages is computed\n",
    ":class: tip\n",
    "The computational chapters are notebooks stored **without outputs** and executed every time the\n",
    "book is built. Hidden `assert` cells stop the build if a recomputed value ever disagrees with the\n",
    "sentence that states it. The paper's tables are transcribed once, in the helper module listed in\n",
    "the appendix ({doc}`code`), and compared with the paper's LaTeX at build time whenever the\n",
    "(git-ignored) source is present. Numbers about models are never typed: they are read from the run\n",
    "files under `runs/` while the book is built, and a chapter whose files are missing says\n",
    "**pending** instead of guessing.\n",
    ":::\n",
    "\n",
    "Provenance tags, as in the {doc}`digest <digest>`: **[paper]** taken from the paper, not re-checked;\n",
    "**[code]** read in the released code or configuration (file given); **[exp]** measured by us and\n",
    "read from the result files under `runs/` or an experiment's result directory; **[num]** a small\n",
    "computation in these notes.\n",
    "\n",
    ":::{admonition} Seminar page\n",
    ":class: tip\n",
    "The talk's page, with the slides and these notes:\n",
    "<https://bnaskrecki.faculty.wmi.amu.edu.pl/loop/> ·\n",
    "[slides](https://bnaskrecki.faculty.wmi.amu.edu.pl/loop/slides/) (reveal.js; key S opens the\n",
    "speaker view).\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# Guard: the minutes column of the table above is the deck's segment plan (data-seg and data-timing of\n",
    "# every <section> in slides/build/NN_*.html, in order); a change of the deck's timing stops the build.\n",
    "import json, re\n",
    "deck = BOOK.parent / \"slides\" / \"build\"\n",
    "segs, t = [], 0\n",
    "for f in sorted(deck.glob(\"[0-9][0-9]_*.html\")):\n",
    "    for tag in re.findall(r\"<section\\b[^>]*>\", f.read_text(encoding=\"utf-8\")):\n",
    "        a = dict(re.findall(r'([\\w-]+)=\"([^\"]*)\"', tag))\n",
    "        if not segs or segs[-1][0] != a[\"data-seg\"]:\n",
    "            segs.append([a[\"data-seg\"], t, t])\n",
    "        t += int(a[\"data-timing\"])\n",
    "        segs[-1][2] = t\n",
    "assert t == 45 * 60, f\"the deck lasts {t} s\"\n",
    "mm = lambda s: f\"{s // 60}\" if s % 60 == 0 else f\"{s // 60}:{s % 60:02d}\"\n",
    "deck_rows = [f\"{mm(a)}–{mm(b)}\" for _, a, b in segs]\n",
    "me = json.loads((BOOK / \"intro.ipynb\").read_text(encoding=\"utf-8\"))\n",
    "table = \"\".join(next(c[\"source\"] for c in me[\"cells\"]\n",
    "                     if c[\"cell_type\"] == \"markdown\" and \"| minutes | part | chapter | content |\" in \"\".join(c[\"source\"])))\n",
    "mine = [m.replace(\"\\u2060\", \"\") for m in re.findall(r\"^\\| ([\\d:]+–\\u2060?[\\d:]+) \\|\", table, re.M)]   # word joiner: no break\n",
    "assert mine == deck_rows, (mine, deck_rows)\n"
   ],
   "id": "fd8da91c"
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
