{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a5289179",
   "metadata": {},
   "source": [
    "# Exercises\n",
    "\n",
    "Several have computed answers: the computation is hidden below the exercise (click to show) and\n",
    "the answer is checked by the build."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9a08243b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib, math\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 numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1acfddd6",
   "metadata": {},
   "source": [
    "(ex-prenorm)=\n",
    "## Attention residuals contain PreNorm\n",
    "\n",
    "Show that with all $\\alpha_{i,j} = 1$ (no softmax) attention residuals reduce to the PreNorm\n",
    "recursion (1). Then show that with **uniform** softmax weights (all queries zero, their\n",
    "initial value in the released code: `modeling_arloop.py`, lines 112 and 115, `torch.zeros`) block attention residuals *without a window* produce exactly\n",
    "the same updates as PreNorm, because the RMSNorm before each sublayer removes the positive factor\n",
    "(exactly for $\\varepsilon = 0$; up to the RMSNorm's $\\varepsilon$ otherwise).\n",
    "Does this survive the released code's first block, which starts from the embedding (finding F6)?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eabf6397",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(1)\n",
    "d, n, S = 64, 12, 4                                    # width, sublayers, block size (sublayers)\n",
    "Ws = [rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(n)]\n",
    "f = lambda j, x: np.tanh(x @ Ws[j])                    # sublayer j\n",
    "norm = lambda x: x / np.sqrt((x ** 2).mean())          # RMSNorm (eps = 0, unit weight)\n",
    "h0 = rng.standard_normal(d)\n",
    "\n",
    "def prenorm():\n",
    "    h, Z = h0.copy(), []\n",
    "    for j in range(n):\n",
    "        Z.append(f(j, norm(h)))\n",
    "        h = h + Z[-1]\n",
    "    return Z\n",
    "\n",
    "def attnres_ones():                                    # every alpha = 1\n",
    "    sources, Z = [h0], []\n",
    "    for j in range(n):\n",
    "        Z.append(f(j, norm(sum(sources))))\n",
    "        sources.append(Z[-1])\n",
    "    return Z\n",
    "\n",
    "def block_uniform(first_block_has_embedding):          # zero queries -> uniform weights, full history\n",
    "    blocks, partial, Z = [h0], (h0.copy() if first_block_has_embedding else None), []\n",
    "    for j in range(n):\n",
    "        sources = blocks + ([partial] if partial is not None else [])\n",
    "        x = norm(np.mean(sources, axis=0))\n",
    "        if j > 0 and j % S == 0:                       # commit after the routing of an attention sublayer\n",
    "            blocks.append(partial)\n",
    "            partial = None\n",
    "        Z.append(f(j, x))\n",
    "        partial = Z[-1] if partial is None else partial + Z[-1]\n",
    "    return Z\n",
    "\n",
    "ref = prenorm()\n",
    "dev = lambda Z: max(np.abs(a - b).max() for a, b in zip(Z, ref))\n",
    "print(\"largest deviation of the updates z from PreNorm's:\")\n",
    "print(f\"    alpha = 1:                           {dev(attnres_ones()):.1e}\")\n",
    "print(f\"    uniform weights, eq. (4) blocks:     {dev(block_uniform(False)):.1e}\")\n",
    "print(f\"    uniform weights, code's first block: {dev(block_uniform(True)):.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4409588",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert dev(attnres_ones()) < 1e-12 and dev(block_uniform(False)) < 1e-12 and dev(block_uniform(True)) > 0.01"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d1529f6",
   "metadata": {},
   "source": [
    ":::{dropdown} Answer\n",
    "With $\\alpha_{i,j} = 1$ the state is $h_i = h_0 + \\sum_{j\\le i} z_j$, the unrolled form of (1). With\n",
    "uniform weights over the embedding, the completed blocks and the partial block, the mixture is\n",
    "$(h_0 + \\sum_j z_j)/(k+1)$ for $k+1$ sources: PreNorm's state times a positive number, which the\n",
    "RMSNorm removes. With the code's first block the embedding is counted twice, the mixture is\n",
    "$(2h_0 + \\sum_j z_j)/(k+1)$, and the identity fails from the second sublayer on. In the toy above\n",
    "the first two deviations are at rounding level and the third is not. **[num]**\n",
    ":::\n",
    "\n",
    "(ex-bounded)=\n",
    "## A softmax mixture cannot grow the stream\n",
    "\n",
    "Let $s_0, \\dots, s_m$ be sources with $\\|s_j\\| \\le B$ and $\\alpha$ a softmax vector. Show\n",
    "$\\big\\|\\sum_j \\alpha_j s_j\\big\\| \\le B$. Then compute $\\|h\\|$ at the read-out of PreNorm when the\n",
    "embedding and all updates are orthonormal, at the depths of both released ARLoop models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e5ce35d",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "for name in (\"ARLoop-0.6B\", \"ARLoop-1.2B\"):\n",
    "    n = lib.effective_sublayers(lib.config(name))\n",
    "    print(f\"{name}: {n} updates, read-out norm sqrt({n + 1}) = {math.sqrt(n + 1):.2f}, \"\n",
    "          f\"newest share {1 / math.sqrt(n + 1):.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3edc18b",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert f\"{math.sqrt(109):.2f}\" == \"10.44\" and f\"{math.sqrt(145):.2f}\" == \"12.04\"\n",
    "assert lib.effective_sublayers(lib.config(\"ARLoop-1.2B\")) + 1 == 145"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa5fc5fd",
   "metadata": {},
   "source": [
    ":::{dropdown} Answer\n",
    "By the triangle inequality, $\\|\\sum_j\\alpha_j s_j\\| \\le \\sum_j \\alpha_j\\|s_j\\| \\le B\\sum_j\\alpha_j = B$.\n",
    "For orthonormal $h_0, z_1, \\dots, z_n$, $\\|h_0 + \\sum z_j\\|^2 = 1 + n$: $\\sqrt{109} \\approx 10.44$ for\n",
    "the 108 sublayers of the 0.6B model and $\\sqrt{145} \\approx 12.04$ for the 144 of the 1.2B model,\n",
    "while attention residuals stay at or below the norm of their largest source. The stream norms of the real\n",
    "PreNormLoop-0.6B are measured in E1.4. **[num]**\n",
    ":::\n",
    "\n",
    "(ex-count)=\n",
    "## Count the routing parameters of ARLoop-1.2B\n",
    "\n",
    "From its configuration (`book/data/hf/ARLoop-1.2B/config.json`), count the depth-indexed routing\n",
    "parameters and compare with the parameter count of the checkpoint (the list of the other modules is\n",
    "in {doc}`mechanism/m2_parameters`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7678a2c4",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c12 = lib.config(\"ARLoop-1.2B\")\n",
    "routing = lib.routing_parameters(c12)\n",
    "backbone = sum(lib.backbone_parameters(c12).values())\n",
    "print(f\"2 x {c12['physical_layers']} x {c12['loop_count']} = {lib.effective_sublayers(c12)} sublayers\")\n",
    "print(f\"(2 x {lib.effective_sublayers(c12)} + 2) x {c12['hidden_size']} = {routing:,} routing parameters\")\n",
    "print(f\"backbone {backbone:,} + routing {routing:,} = {backbone + routing:,}\")\n",
    "print(f\"checkpoint (HF API): {lib.CHECKPOINTS['ARLoop-1.2B']['parameters']:,}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf805d46",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert routing == 593_920 and backbone + routing == lib.CHECKPOINTS[\"ARLoop-1.2B\"][\"parameters\"] == 1_208_655_360"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d8e3cc7",
   "metadata": {},
   "source": [
    ":::{dropdown} Answer\n",
    "$2 \\times 24 \\times 3 = 144$ effective sublayers, each with a query and a norm weight, plus the\n",
    "read-out pair: $290 \\times 2048 = 593{,}920$ routing parameters. Together with the backbone counted\n",
    "from the same configuration this gives 1,208,655,360, exactly the checkpoint's count (see\n",
    "{doc}`mechanism/m2_parameters`). **[code + num]**\n",
    ":::\n",
    "\n",
    "(ex-window)=\n",
    "## When does the first block leave the window?\n",
    "\n",
    "For block size $S$ sublayers and a window of $W$ sources besides the embedding, at which effective\n",
    "layer is $b_1$ read for the last time? Check the formula against the replay of the forward pass for\n",
    "the 0.6B model and windows $W = 2, \\dots, 6$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c2e7261",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "c06 = lib.config(\"ARLoop-0.6B\")\n",
    "per_block = c06[\"attnres_block_size\"] // 2\n",
    "last = {}\n",
    "for W in range(2, 7):\n",
    "    calls = lib.schedule({**c06, \"sw_blocks\": W})\n",
    "    seen = [c for c in calls if \"b1\" in c[\"labels\"]]\n",
    "    last[W] = seen[-1][\"layer\"] if seen[-1][\"kind\"] != \"readout\" else \"never dropped\"\n",
    "    n_sub = lib.effective_sublayers(c06)\n",
    "    if last[W] == \"never dropped\":\n",
    "        print(f\"W = {W}: b1 is never dropped (still read by the read-out, call {n_sub} = 2 × {n_sub // 2})\")\n",
    "    else:\n",
    "        print(f\"W = {W}: b1 last read at layer {last[W]} (formula W × S/2 = {W * per_block})\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93638049",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(last[W] == W * per_block for W in range(2, 6)) and last[6] == \"never dropped\"\n",
    "assert lib.config(\"ARLoop-0.6B\")[\"physical_layers\"] * lib.config(\"ARLoop-0.6B\")[\"loop_count\"] == 54 == 6 * per_block"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2597220f",
   "metadata": {},
   "source": [
    ":::{dropdown} Answer\n",
    "Blocks are committed every $S/2$ layers, $b_k$ at the start of layer $kS/2$. At the FFN sublayer of\n",
    "layer $WS/2$ the router sees $b_1, \\dots, b_W$ and a partial block, one source too many, and $b_1$\n",
    "drops out; its last reader is the attention sublayer of layer $WS/2$. For the 0.6B model\n",
    "($S/2 = 9$): layers 18, 27, 36, 45 for $W = 2, 3, 4, 5$; with $W = 6$ the 54 layers end before\n",
    "$b_1$ is dropped. With the released $W = 3$ that is layer 27 (and layer 36 for ARLoop-1.2B, where\n",
    "$S/2 = 12$). **[num]**\n",
    ":::\n",
    "\n",
    "(ex-gap)=\n",
    "## How large must the GSM8K gap be?\n",
    "\n",
    "The paper's GSM8K scores of the 0.6B pair are 40.9 and 35.7 on 1,319 items. Which numbers of solved\n",
    "items are consistent with these rounded percentages? If E1 finds the same net gap, for which numbers\n",
    "of discordant items (solved by exactly one model) is the exact McNemar test significant at 5%?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac7160ae",
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "N = 1319\n",
    "ar = [k for k in range(N + 1) if f\"{100 * k / N:.1f}\" == \"40.9\"]\n",
    "pn = [k for k in range(N + 1) if f\"{100 * k / N:.1f}\" == \"35.7\"]\n",
    "nets = sorted({a - p for a in ar for p in pn})\n",
    "print(\"ARLoop solved\", ar, \"items; PreNormLoop solved\", pn, \"items; net gap\", nets)\n",
    "limit = {}                     # the largest discordant count the totals allow: no item solved by both models\n",
    "for a in ar:\n",
    "    for p in pn:\n",
    "        limit[a - p] = max(limit.get(a - p, 0), a + p)\n",
    "allowed = {net: list(range(net, limit[net] + 1, 2)) for net in nets}     # same parity as the gap\n",
    "for net in nets:\n",
    "    sig = all(lib.mcnemar_exact((D + net) // 2, (D - net) // 2) < 0.05 for D in allowed[net])\n",
    "    print(f\"net gap {net}: discordant counts {net}–{limit[net]:,} (same parity) are possible; \"\n",
    "          f\"p < 0.05 for {'every one of them' if sig else 'not all of them'}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb7ef2e2",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert ar == [539, 540] and pn == [471] and nets == [68, 69]\n",
    "assert limit == {68: 1010, 69: 1011}\n",
    "for net in nets:\n",
    "    assert all(lib.mcnemar_exact((D + net) // 2, (D - net) // 2) < 0.05 for D in allowed[net])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6eb3d9ef",
   "metadata": {},
   "source": [
    ":::{dropdown} Answer\n",
    "40.9% of 1,319 is 539 or 540 items, 35.7% is 471, so the paper's gap is a net 68 or 69 items. The\n",
    "number of discordant items has the parity of the gap and is at most the sum of the two totals (when\n",
    "no item is solved by both models). For every discordant count the totals allow (the ranges are\n",
    "printed above) the exact McNemar test is significant at 5%: if E1 reproduces a gap of that size, it\n",
    "is not noise. Whether it reproduces is the question of E1.1 ({doc}`tests/e1_release`). **[num]**\n",
    ":::"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
