{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "217fbd10",
   "metadata": {},
   "source": [
    "# Looped transformers and the residual stream"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "332079f3",
   "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\n",
    "import matplotlib\n",
    "matplotlib.use(\"module://matplotlib_inline.backend_inline\")\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b55828b",
   "metadata": {},
   "source": [
    "## A transformer is a sum of updates\n",
    "\n",
    "The paper's notation (§3.1) {cite}`arloop2026`: a *sublayer* is an attention or a feed-forward\n",
    "(FFN) module, a *layer* is one of each, so $L$ layers are $2L$ sublayers. With the PreNorm residual\n",
    "{cite}`xiong2020prenorm`, sublayer $i$ maps its input $h_{i-1}$ to\n",
    "\n",
    "$$\n",
    "h_i = h_{i-1} + f_i\\big(\\operatorname{Norm}(h_{i-1})\\big), \\qquad i = 1, \\dots, 2L,\n",
    "\\tag{1}\n",
    "$$\n",
    "\n",
    "and unrolling the recursion gives\n",
    "\n",
    "$$\n",
    "h_i = h_0 + \\sum_{j=1}^{i} f_j\\big(\\operatorname{Norm}(h_{j-1})\\big):\n",
    "$$\n",
    "\n",
    "every update enters every later state with coefficient 1. **[paper]**\n",
    "\n",
    "## Looping: depth without parameters\n",
    "\n",
    "A looped transformer applies the whole stack $\\mathcal S = \\mathcal F_{2L}\\circ\\dots\\circ\\mathcal F_1$\n",
    "(with $\\mathcal F_i$ the map of eq. (1)) $R$ times,\n",
    "\n",
    "$$\n",
    "y = \\operatorname{LMHead}\\circ\\mathcal S^{(R)}\\circ\\dots\\circ\\mathcal S^{(1)}(h_0),\n",
    "\\qquad \\mathcal S^{(1)} = \\dots = \\mathcal S^{(R)} = \\mathcal S,\n",
    "$$\n",
    "\n",
    "so the unrolled network has an effective depth of $2LR$ sublayers with only $2L$ distinct ones.\n",
    "The idea goes back to Universal Transformers {cite}`dehghani2019universal`; looped models learn\n",
    "algorithms well {cite}`yang2024looped`, can simulate chains of thought in latent space\n",
    "{cite}`saunshi2025latent`, and generalise better on controlled multi-hop reasoning tasks\n",
    "{cite}`kohli2026loop`. For the released models the configuration files give: **[code]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c31205e7",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "rows = []\n",
    "for name in lib.CHECKPOINTS:\n",
    "    cfg = lib.config(name)\n",
    "    rows.append((name, cfg[\"physical_layers\"], cfg[\"loop_count\"], cfg[\"num_hidden_layers\"],\n",
    "                 2 * cfg[\"physical_layers\"], lib.effective_sublayers(cfg)))\n",
    "lib.md(lib.table(rows, [\"model\", \"physical layers L\", \"loops R\", \"effective layers LR\",\n",
    "                        \"distinct sublayers 2L\", \"effective sublayers 2LR\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d93e3a6",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c06, c12 = lib.config(\"ARLoop-0.6B\"), lib.config(\"ARLoop-1.2B\")\n",
    "assert (c06[\"physical_layers\"], c06[\"loop_count\"], lib.effective_sublayers(c06)) == (18, 3, 108)\n",
    "assert (c12[\"physical_layers\"], c12[\"loop_count\"], lib.effective_sublayers(c12)) == (24, 3, 144)\n",
    "assert c06[\"num_hidden_layers\"] == 54 and c12[\"num_hidden_layers\"] == 72\n",
    "assert lib.config(\"PreNormLoop-0.6B\")[\"physical_layers\"] == 18\n",
    "assert 2 * c06[\"physical_layers\"] == 36 and 2 * c12[\"physical_layers\"] == 48"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47bad60a",
   "metadata": {},
   "source": [
    "So the released 0.6B models run 108 sublayers built from 36 distinct ones, and ARLoop-1.2B runs\n",
    "144 from 48.\n",
    "\n",
    "In a loop, the residual stream is the **only** memory that carries information from one pass to\n",
    "the next. Everything a later pass knows about what earlier passes computed has to survive in $h$.\n",
    "(The released models also re-supply each token's identity in every pass, through the *value\n",
    "residuals* of their attention: a gated token embedding added to the attention values at\n",
    "alternating layers, App. A.1.)\n",
    "\n",
    "## How earlier work stabilised the loop\n",
    "\n",
    "| design | update rule (as in the paper's App. E) | where it comes from |\n",
    "|---|---|---|\n",
    "| PreNorm | $h \\leftarrow h + f(\\operatorname{Norm}(h))$ | {cite}`xiong2020prenorm` |\n",
    "| Sandwich norm | $h \\leftarrow \\operatorname{Norm}\\big(h + f(\\operatorname{Norm}(h))\\big)$ | Huginn {cite}`geiping2025huginn`, Ouro {cite}`zhu2025ouro` |\n",
    "| DeepLoop | $h \\leftarrow \\operatorname{Norm}\\big(\\alpha h + f(\\operatorname{Norm}(h))\\big)$, $\\alpha = (2LR)^{1/2}$ | {cite}`li2026deeploop`, after DeepNet {cite}`wang2022deepnet` |\n",
    "| Parcae | between loops $s^{(r)} = \\mathcal S\\big(\\bar A s^{(r-1)} + \\bar B e\\big)$, $\\bar A = \\exp(\\Delta A)$, $A = \\operatorname{Diag}(-\\exp a)$ | {cite}`prairie2026parcae` |\n",
    "| input injection | the embedding $e$ is added back before each pass | {cite}`bansal2022injection`, Huginn |\n",
    "| ARLoop | softmax attention over earlier residual sources (next chapter) | {cite}`arloop2026`, after {cite}`kimi2026attnres` |\n",
    "\n",
    "Huginn-3.5B trains with a random number of loops (up to 64) on 0.8T tokens; Ouro uses 4 loops and\n",
    "7.7T tokens; Hyperloop {cite}`zeitoun2026hyperloop` is a further design in the same family. Our own\n",
    "`latent` programme used the retrofitted recurrence of {cite}`mcleish2025retrofitted` on a pretrained\n",
    "Qwen model; learned halting is examined critically in {cite}`wu2026halting`. **[paper, digest §1;\n",
    "the last two references are ours, not the paper's]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4b5ea7f",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(lib.DIGEST, \"Huginn-3.5B (random recurrence, up to 64 steps, 0.8T tokens)\",\n",
    "                       \"Ouro (4 loops, 7.7T tokens)\", \"DeepLoop (DeepNorm with exponent 1/2)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73a41163",
   "metadata": {},
   "source": [
    "## How large does the stream get?\n",
    "\n",
    "Under PreNorm every update is added with weight 1, and the next sublayer only sees the direction\n",
    "$\\operatorname{Norm}(h)$. Take the cleanest case: $h_0$ and all updates are unit vectors, each\n",
    "orthogonal to everything before it. Then $\\|h_i\\| = \\sqrt{1+i}$, and the newest update is only a\n",
    "fraction $1/\\sqrt{1+i}$ of the direction the next sublayer reads. A softmax mixture of sources whose\n",
    "norms are at most $B$ never exceeds $B$ (it is a convex combination). The demo below draws such\n",
    "updates in the 0.6B model's width and depth and compares three streams: the PreNorm sum, a softmax\n",
    "mixture over all earlier sources with random scores, and ARLoop's block attention residuals on the\n",
    "0.6B model's actual schedule of blocks and window (constructed in {doc}`mechanism/m1_window`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e47a9b72",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "demo = lib.stream_norm_demo(c06)\n",
    "n = lib.effective_sublayers(c06)\n",
    "s = np.arange(n + 1)                     # routing calls 0..n; call n is the read-out\n",
    "final, share = demo[\"prenorm\"][-1], 1 / demo[\"prenorm\"][-1]\n",
    "print(f\"PreNorm at the read-out ({n} updates): |h| = {final:.4f} = sqrt({n + 1})\")\n",
    "print(f\"  share of the newest update in the direction read: {share:.3f}\")\n",
    "print(f\"softmax mixture over all sources: max |h| = {demo['mixture'].max():.4f}\")\n",
    "print(f\"block attention residuals (0.6B schedule): max |h| = {demo['block'].max():.4f}\")\n",
    "print(f\"  largest source norm: {demo['bound'].max():.4f} = sqrt(19)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a571ce8a",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert np.allclose(demo[\"prenorm\"], np.sqrt(s + 1), atol=1e-9)           # |h| read by call s = sqrt(1 + s)\n",
    "assert f\"{final:.2f}\" == \"10.44\" and f\"{share:.3f}\" == \"0.096\" and n + 1 == 109\n",
    "assert demo[\"mixture\"].max() <= 1 + 1e-12\n",
    "assert (demo[\"block\"] <= demo[\"bound\"] + 1e-12).all()\n",
    "assert abs(demo[\"bound\"].max() - np.sqrt(19)) < 1e-9 and f\"{np.sqrt(19):.2f}\" == \"4.36\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ac4c684",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "P = lib.PALETTE\n",
    "fig, ax = lib.figure(figsize=(8, 3.4))\n",
    "lib.style(ax)\n",
    "curves = [(\"PreNorm sum\", demo[\"prenorm\"], P[\"pn\"]),                       # the PreNorm loop: gold\n",
    "          (\"softmax mixture, all sources\", demo[\"mixture\"], P[\"neutral\"]),  # a generic mixture: neutral\n",
    "          (\"block attention residuals, 0.6B schedule\", demo[\"block\"], P[\"ar\"])]  # ARLoop: indigo\n",
    "for label, y, color in curves:\n",
    "    ax.plot(s, y, color=color, lw=2, solid_capstyle=\"round\", label=label)\n",
    "    ax.annotate(f\"{y[-1]:.2f}\", (s[-1], y[-1]), xytext=(6, 0), textcoords=\"offset points\",\n",
    "                va=\"center\", fontsize=9, color=P[\"ink\"])\n",
    "for b in (36, 72):\n",
    "    ax.axvline(b, color=P[\"rule\"], lw=1)\n",
    "ax.set_xlabel(\"routing call s (loops start at 0, 36, 72; 108 is the read-out)\")\n",
    "ax.set_ylabel(\"norm of the state read\")\n",
    "ax.legend(frameon=False, fontsize=9, labelcolor=P[\"ink\"], loc=\"upper left\")\n",
    "ax.set_xlim(0, n + 9)\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6480293",
   "metadata": {},
   "source": [
    "With orthogonal unit updates the PreNorm stream reaches $\\sqrt{109} \\approx 10.44$ after the 108\n",
    "sublayers of the 0.6B model, and the newest update is only 0.096 of the direction the next sublayer\n",
    "reads. The softmax mixtures stay at or below the norm of their largest source: 1 for single\n",
    "updates, $\\sqrt{19}\\approx 4.36$ for ARLoop's first block, which holds the embedding and 18 updates\n",
    "**[num]**. Real updates are neither orthogonal nor of unit norm; E1.4 measures the stream norms of\n",
    "the released PreNormLoop-0.6B at the end of each loop ({doc}`tests/e1_release`). The point of the\n",
    "toy is the shape: a fixed-weight sum dilutes each new update, a learned mixture does not have to."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
