{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "afcf266d",
   "metadata": {},
   "source": [
    "# The window, block by block\n",
    "\n",
    "Which residual sources does each sublayer of the released ARLoop-0.6B actually read? The answer\n",
    "follows from four configuration values and the order of the bookkeeping in the forward pass. This\n",
    "page replays that bookkeeping (`seminar_lib.schedule`, listed in {doc}`../code`) for every routing\n",
    "call."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3218269",
   "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": "9eefdb1f",
   "metadata": {},
   "source": [
    "## The rule\n",
    "\n",
    "Read in the released code (digest §2) **[code]**, with $S$ the block size in sublayers:\n",
    "\n",
    "* the router of each sublayer reads the list `blocks + [partial]`; when the list is longer than the\n",
    "  window, it is cut to the embedding plus the `sw_blocks` most recent entries;\n",
    "* at the start of every effective layer $\\ell > 0$ with $\\ell \\equiv 0 \\pmod{S/2}$, the partial block\n",
    "  is committed as a new block, **after** the routing of that layer's attention sublayer and before\n",
    "  its update;\n",
    "* a last routing call (the read-out query) produces the state for the final norm and the LM head.\n",
    "\n",
    "Calls are numbered as in the code: $s = 2\\ell$ for the attention and $s = 2\\ell+1$ for the FFN\n",
    "sublayer of effective layer $\\ell = 0, 1, \\dots$; $z[s]$ is the update produced after call $s$ (the\n",
    "paper's $z_{s+1}$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ec232fa",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "cfg = lib.config(\"ARLoop-0.6B\")\n",
    "L, R, S, W = cfg[\"physical_layers\"], cfg[\"loop_count\"], cfg[\"attnres_block_size\"], cfg[\"sw_blocks\"]\n",
    "commits = lib.commit_layers(cfg)\n",
    "calls = lib.schedule(cfg)\n",
    "print(f\"physical_layers={L}, loop_count={R}, attnres_block_size={S} sublayers, sw_blocks={W}\")\n",
    "print(f\"effective layers {L * R}, sublayers {lib.effective_sublayers(cfg)}, routing calls {len(calls)}\")\n",
    "print(f\"a block every {S // 2} layers, committed at the start of layers {commits}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f13e6f4",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert (L, R, S, W) == (18, 3, 18, 3) and S // 2 == 9\n",
    "assert commits == [9, 18, 27, 36, 45] and len(calls) == 109\n",
    "assert [sum(1 for c in commits if (loop - 1) * L <= c < loop * L) for loop in (1, 2, 3)] == [1, 2, 2]\n",
    "assert sum(1 for c in commits if c >= L) == 4 and all(c % 9 == 0 for c in commits)\n",
    "assert calls[-1][\"kind\"] == \"readout\" and calls[-1][\"committed\"] == 5 and calls[-1][\"labels\"][-1] == \"p\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "504a5b95",
   "metadata": {},
   "source": [
    "So the window holds the embedding and **3** sources, and a residual block spans 9 layers. Blocks are\n",
    "committed at the start of effective layers 9, 18, 27, 36 and 45: two per loop, except in the first\n",
    "loop, which commits only at layer 9 because layer 0 opens the first block. Each loop still writes\n",
    "two blocks; the sixth block is never committed: it stays the partial block that the read-out reads.\n",
    "**[code + num]**\n",
    "\n",
    "## Who reads what"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c475a6d3",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "from matplotlib.colors import ListedColormap\n",
    "from matplotlib.patches import Patch\n",
    "\n",
    "rows = [\"e\", \"b1\", \"b2\", \"b3\", \"b4\", \"b5\", \"p\"]\n",
    "grid = np.zeros((len(rows), len(calls)), dtype=int)   # 0 not yet there, 1 committed but outside the window\n",
    "for rec in calls:                                     # 2 read, 3 read and contains h0 besides e (F6)\n",
    "    for k in range(1, rec[\"committed\"] + 1):\n",
    "        grid[k, rec[\"call\"]] = 1\n",
    "    for label, terms in zip(rec[\"labels\"], rec[\"terms\"]):\n",
    "        grid[rows.index(label), rec[\"call\"]] = 3 if (label != \"e\" and \"h0\" in terms) else 2\n",
    "\n",
    "P = lib.PALETTE\n",
    "SURFACE, OUT, READ, F6 = P[\"paper\"], lib.tint(P[\"neutral\"], 0.3), P[\"ar\"], P[\"err\"]   # F6 is a finding: carmine\n",
    "fig, ax = lib.figure(figsize=(9, 2.9))\n",
    "lib.style(ax, grid=None)\n",
    "ax.imshow(grid, aspect=\"auto\", interpolation=\"nearest\", cmap=ListedColormap([SURFACE, OUT, READ, F6]),\n",
    "          vmin=-0.5, vmax=3.5)\n",
    "ax.set_yticks(range(len(rows)), [\"e (embedding)\", \"b1\", \"b2\", \"b3\", \"b4\", \"b5\", \"p (partial)\"], fontsize=8)\n",
    "ax.set_xticks([0, 18, 36, 54, 72, 90, 108])\n",
    "ax.set_xlabel(\"routing call s (attention of layer l: s = 2l; FFN: s = 2l + 1; 108 = read-out)\")\n",
    "for b in (35.5, 71.5):\n",
    "    ax.axvline(b, color=P[\"ink\"], lw=0.8)\n",
    "ax.annotate(\"layer 36\", (72.5, -0.5), xytext=(72.5, -1.6), ha=\"center\", fontsize=8, color=P[\"neutral\"],\n",
    "            arrowprops={\"arrowstyle\": \"-\", \"color\": P[\"neutral\"], \"lw\": 0.8}, annotation_clip=False)\n",
    "for side in (\"top\", \"right\", \"left\", \"bottom\"):\n",
    "    ax.spines[side].set_visible(False)\n",
    "ax.tick_params(length=0)\n",
    "ax.legend(handles=[Patch(color=READ, label=\"read by the router\"),\n",
    "                   Patch(color=F6, label=\"read, and also contains h0 (F6)\"),\n",
    "                   Patch(color=OUT, label=\"committed, outside the window\")],\n",
    "          frameon=False, fontsize=8, loc=\"upper center\", bbox_to_anchor=(0.5, -0.32), ncol=3)\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a23c4f74",
   "metadata": {},
   "source": [
    "Each column is one routing call, each row one source; the vertical rules separate the three\n",
    "loops. The full list, with what each source sums, is below (expand the output)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30b66be3",
   "metadata": {
    "tags": [
     "hide-input",
     "hide-output"
    ]
   },
   "outputs": [],
   "source": [
    "def where(rec):\n",
    "    return \"read-out\" if rec[\"kind\"] == \"readout\" else f\"layer {rec['layer']} ({rec['kind']})\"\n",
    "\n",
    "lib.md(lib.table([(rec[\"call\"], where(rec), \", \".join(rec[\"labels\"]),\n",
    "                   \"; \".join(f\"{l} = {lib.describe_terms(t)}\" for l, t in zip(rec[\"labels\"], rec[\"terms\"])))\n",
    "                  for rec in calls], [\"call\", \"where\", \"sources read\", \"what they sum\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d26aea6",
   "metadata": {},
   "source": [
    "## Worked example: effective layer 36, the first layer of loop 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b9c9573",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "attn, ffn = calls[72], calls[73]\n",
    "for rec in (attn, ffn):\n",
    "    print(f\"call {rec['call']}, {where(rec)} reads:\")\n",
    "    for l, t in zip(rec[\"labels\"], rec[\"terms\"]):\n",
    "        print(f\"    {l} = {lib.describe_terms(t)}\")\n",
    "p_layers = sorted({t // 2 for t in attn[\"terms\"][-1]})\n",
    "print(f\"the partial block read by the attention sublayer holds layers {p_layers[0]}–{p_layers[-1]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00c35ffb",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert attn[\"layer\"] == ffn[\"layer\"] == 36 and attn[\"loop\"] == 3 and attn[\"layer\"] == 2 * L\n",
    "assert attn[\"labels\"] == [\"e\", \"b2\", \"b3\", \"p\"] and attn[\"committed\"] == 3\n",
    "assert (p_layers[0], p_layers[-1]) == (27, 35) and len(p_layers) == 9\n",
    "assert ffn[\"labels\"] == [\"e\", \"b3\", \"b4\", \"p\"] and ffn[\"terms\"][-1] == (72,) and ffn[\"committed\"] == 4\n",
    "assert ffn[\"terms\"][2] == attn[\"terms\"][3]            # b4 is the partial block the attention read\n",
    "assert lib.quote_check(lib.DIGEST, \"Before this sublayer the partial block holds layers 27–35\",\n",
    "                       \"then the partial is committed as $b_4$\",\n",
    "                       \"reads $\\\\{b_0, b_3, b_4, \\\\text{partial} = z_{\\\\text{attn},36}\\\\}$\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e932b61b",
   "metadata": {},
   "source": [
    "Before the attention sublayer of effective layer 36 the partial block holds layers 27–35. The\n",
    "attention router reads $\\{b_0, b_2, b_3, \\text{partial}\\}$: the embedding and the three most recent\n",
    "sources; $b_1$ is no longer visible. Then the partial block is committed as $b_4$, the attention\n",
    "update starts a new partial block, and the FFN router of the same layer reads\n",
    "$\\{b_0, b_3, b_4, z[72]\\}$, where $z[72]$ is the attention update of layer 36. This is the worked\n",
    "example of the digest, reproduced by the replay. **[code + num]**\n",
    "\n",
    "## The first block contains the embedding (finding F6)\n",
    "\n",
    "Eq. (4) of the paper defines $b_1 = \\sum_{j=1}^{S} z_j$. The released code starts the first block from\n",
    "the embedding (`blocks = [h0]`, `partial = h0`), so $b_1 = h_0 + \\sum_{j=1}^{S} z_j$ and the embedding\n",
    "is read through two sources until $b_1$ leaves the window. **[code]** The replay says when:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e91865c5",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "twice = [rec[\"call\"] for rec in calls if sum(\"h0\" in t for t in rec[\"terms\"]) >= 2]\n",
    "last_b1 = max(rec[\"call\"] for rec in calls if \"b1\" in rec[\"labels\"])\n",
    "cfg12 = lib.config(\"ARLoop-1.2B\")\n",
    "calls12 = lib.schedule(cfg12)\n",
    "last_b1_12 = max(rec[\"call\"] for rec in calls12 if \"b1\" in rec[\"labels\"])\n",
    "print(f\"ARLoop-0.6B: h0 is read through two sources at calls {twice[0]}..{twice[-1]}\")\n",
    "print(f\"    b1 is last read at call {last_b1}, {where(calls[last_b1])}\")\n",
    "print(f\"ARLoop-1.2B: commits at {lib.commit_layers(cfg12)}\")\n",
    "print(f\"    b1 is last read at call {last_b1_12}, {where(calls12[last_b1_12])}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7322e82",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert twice == list(range(0, 55)) and last_b1 == 54 and calls[54][\"layer\"] == 27 and calls[54][\"kind\"] == \"attn\"\n",
    "assert \"b1\" not in calls[55][\"labels\"] and calls[55][\"layer\"] == 27 and calls[55][\"kind\"] == \"ffn\"\n",
    "assert lib.commit_layers(cfg12) == [12, 24, 36, 48, 60]\n",
    "assert last_b1_12 == 72 and calls12[72][\"layer\"] == 36 and calls12[72][\"kind\"] == \"attn\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0054ac8f",
   "metadata": {},
   "source": [
    "In ARLoop-0.6B the embedding is read through two sources at calls 0 to 54: through the partial\n",
    "block up to call 18 (the attention sublayer of effective layer 9), then through $b_1$. The last call that reads $b_1$ is call 54, the\n",
    "attention sublayer of effective layer 27; from the FFN sublayer of layer 27 on, $b_1$ is outside the\n",
    "window. In ARLoop-1.2B (block every 12 layers) the same happens at effective layer 36. **[num]**\n",
    "This agrees with finding F6 of the digest, which records the same from a routing probe of the\n",
    "released model (smoke job 322097)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "728a025d",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "via_partial = [c[\"call\"] for c in calls if c[\"labels\"][-1] == \"p\" and \"h0\" in c[\"terms\"][-1]]\n",
    "assert via_partial == list(range(19)) and (calls[18][\"layer\"], calls[18][\"kind\"]) == (9, \"attn\")\n",
    "assert lib.quote_check(lib.DIGEST, \"last read by sublayer 54 (the attention sublayer of effective layer 27)\",\n",
    "                       \"smoke routing probe, job 322097\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a3d97fc",
   "metadata": {},
   "source": [
    "## The first router is inert (finding F8)\n",
    "\n",
    "At call 0 the router reads two copies of the same vector ($b_0 = h_0$ and the partial block\n",
    "$= h_0$). Equal sources get equal scores whatever the query, so the softmax weights are\n",
    "$\\tfrac12, \\tfrac12$ and the routed state is $h_0$: the query and the norm weight of call 0 cannot\n",
    "change the output, and they receive no gradient. This does not depend on F6: under eq. (4) call 0\n",
    "would read the embedding alone, with weight 1 whatever the query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ea91d8b",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(0)\n",
    "h0 = rng.standard_normal(cfg[\"hidden_size\"])\n",
    "outs = []\n",
    "for _ in range(5):                                    # five random queries and norm weights\n",
    "    q, g = rng.standard_normal(cfg[\"hidden_size\"]), rng.standard_normal(cfg[\"hidden_size\"])\n",
    "    V = np.stack([h0, h0])                            # call 0 reads b0 = h0 and partial = h0\n",
    "    scores = (V * (q * g)).sum(-1) / np.sqrt((V ** 2).mean(-1) + 1e-5)\n",
    "    w = np.exp(scores - scores.max()); w /= w.sum()\n",
    "    outs.append((w, w @ V))\n",
    "inert = 2 * cfg[\"hidden_size\"]\n",
    "print(\"weights at call 0 for five random (q, g):\")\n",
    "for w, _ in outs:\n",
    "    print(\"   \", np.round(w, 6))\n",
    "print(f\"inert routing parameters (query + norm weight of call 0): {inert:,}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1afabc9",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(np.allclose(w, [0.5, 0.5]) and np.allclose(y, h0) for w, y in outs)\n",
    "assert calls[0][\"terms\"] == [(\"h0\",), (\"h0\",)] and inert == 3072\n",
    "assert lib.quote_check(lib.DIGEST, \"the query and norm of sublayer 0 (3,072 parameters) are inert and receive no gradient\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "243c6567",
   "metadata": {},
   "source": [
    "So 3,072 of the routing parameters (the query and norm weight of call 0) have no effect in the\n",
    "released forward pass **[num]**. The digest records this as finding F8. The E1 routing probe\n",
    "records the weights of call 0 on the released model ({doc}`../tests/e1_release`).\n",
    "\n",
    "## The paper's version, for comparison\n",
    "\n",
    "With eq. (4) (first partial block empty, $b_1 = \\sum_{j\\le S} z_j$) the same replay gives identical\n",
    "source sets from call 1 on; only call 0 differs (it reads the embedding alone), and the embedding is\n",
    "then read through a single source everywhere."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "318d3d4f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "paper = lib.schedule(cfg, embedding_in_first_block=False)\n",
    "same = all(a[\"labels\"] == b[\"labels\"] for a, b in zip(calls[1:], paper[1:]))\n",
    "print(\"same source labels from call 1 on:\", same)\n",
    "print(\"call 0 reads:\", paper[0][\"labels\"])\n",
    "print(\"calls reading h0 twice:\", sum(sum(\"h0\" in t for t in r[\"terms\"]) >= 2 for r in paper))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83fba001",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert same and paper[0][\"labels\"] == [\"e\"] and len(paper) == len(calls)\n",
    "assert all(sum(\"h0\" in t for t in r[\"terms\"]) == 1 for r in paper)"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
