{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "36882378",
   "metadata": {},
   "source": [
    "# One query per effective sublayer: what it costs, what it fixes\n",
    "\n",
    "ARLoop's loop is weight-tied only in its transformer blocks: the routing is indexed by **effective**\n",
    "depth. This page counts the routing parameters from the configuration files of the released\n",
    "checkpoints (stored in `book/data/hf/`, pinned by revision and SHA-256) and checks the counts\n",
    "against the parameter totals reported by the Hugging Face API."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96da9c72",
   "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": "code",
   "execution_count": null,
   "id": "e9565a17",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "rows = []\n",
    "for name, ck in lib.CHECKPOINTS.items():\n",
    "    cfg = lib.config(name)   # checks the SHA-256 of the stored file\n",
    "    rows.append((name, f\"`{ck['repo']}`\", f\"`{ck['revision'][:8]}`\", f\"{ck['parameters']:,}\", f\"`{ck['config_sha256'][:12]}…`\"))\n",
    "lib.md(lib.table(rows, [\"model\", \"repository\", \"revision\", \"parameters (HF API)\", \"config.json SHA-256\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4717a9ce",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "SOURCE = lib.REPO / \"source\" / \"SOURCE.md\"\n",
    "for name, ck in lib.CHECKPOINTS.items():\n",
    "    assert lib.quote_check(SOURCE, f\"`{ck['repo']}` @ `{ck['revision']}` — {ck['parameters']:,} parameters\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6455182",
   "metadata": {},
   "source": [
    "## The 0.6B pair"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da342c4f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "c06 = lib.config(\"ARLoop-0.6B\")\n",
    "vec = lib.routing_vectors(c06)\n",
    "r06 = lib.routing_parameters(c06)\n",
    "gap = lib.CHECKPOINTS[\"ARLoop-0.6B\"][\"parameters\"] - lib.CHECKPOINTS[\"PreNormLoop-0.6B\"][\"parameters\"]\n",
    "print(\"effective sublayers 2 × physical_layers × loop_count =\", lib.effective_sublayers(c06))\n",
    "print(\"routing vectors:\", \" + \".join(f\"{v} {k}\" for k, v in vec.items()), \"=\", sum(vec.values()))\n",
    "print(f\"routing parameters: {sum(vec.values())} × hidden_size {c06['hidden_size']:,} = {r06:,}\")\n",
    "print(f\"parameter gap ARLoop-0.6B − PreNormLoop-0.6B (HF API): {gap:,}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fddeada",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.effective_sublayers(c06) == 108 and sum(vec.values()) == 218 and c06[\"hidden_size\"] == 1536\n",
    "assert r06 == 334_848 == gap\n",
    "assert lib.quote_check(lib.DIGEST, \"$218 \\\\times 1536 = 334{,}848$ parameters, **exactly** the difference\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "358ae5b9",
   "metadata": {},
   "source": [
    "The 108 effective sublayers of ARLoop-0.6B each carry a query and an RMSNorm weight, and the\n",
    "read-out carries one more of each: $218 \\times 1536 = 334{,}848$ routing parameters. This is\n",
    "**exactly** the difference between the parameter counts of ARLoop-0.6B and PreNormLoop-0.6B: the\n",
    "pair differs in the routing and in nothing else that has parameters. **[code + num]**\n",
    "\n",
    "The whole count follows from the configuration. With the module list of the released modeling code\n",
    "(tied embedding, one shared value embedding, per layer the attention projections, the SwiGLU\n",
    "matrices, two norms, and a value-embedding gate in every second layer; Q/K normalisation without\n",
    "parameters; `seminar_lib.backbone_parameters`), the three totals are reproduced to the last\n",
    "parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa00b472",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "rows, exact = [], []\n",
    "for name, ck in lib.CHECKPOINTS.items():\n",
    "    cfg = lib.config(name)\n",
    "    parts = lib.backbone_parameters(cfg)\n",
    "    routing = lib.routing_parameters(cfg) if \"sw_blocks\" in cfg else 0\n",
    "    total = sum(parts.values()) + routing\n",
    "    exact.append(total == ck[\"parameters\"])\n",
    "    rows.append((name, f\"{sum(parts.values()):,}\", f\"{routing:,}\", f\"{total:,}\", f\"{ck['parameters']:,}\",\n",
    "                 \"exact\" if total == ck[\"parameters\"] else \"**differs**\"))\n",
    "lib.md(lib.table(rows, [\"model\", \"backbone (from config)\", \"routing\", \"total\", \"HF API\", \"match\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0baea3fe",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(exact) and len(exact) == 3\n",
    "assert sum(lib.backbone_parameters(lib.config(\"ARLoop-0.6B\")).values()) == lib.CHECKPOINTS[\"PreNormLoop-0.6B\"][\"parameters\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b138c01",
   "metadata": {},
   "source": [
    "## ARLoop-1.2B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b2cf5c4",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "c12 = lib.config(\"ARLoop-1.2B\")\n",
    "r12 = lib.routing_parameters(c12)\n",
    "v12 = sum(lib.routing_vectors(c12).values())\n",
    "share06 = r06 / lib.CHECKPOINTS[\"ARLoop-0.6B\"][\"parameters\"]\n",
    "share12 = r12 / lib.CHECKPOINTS[\"ARLoop-1.2B\"][\"parameters\"]\n",
    "print(f\"ARLoop-1.2B: {lib.effective_sublayers(c12)} effective sublayers\")\n",
    "print(f\"    routing parameters {v12} × {c12['hidden_size']:,} = {r12:,}\")\n",
    "print(f\"share of the model: ARLoop-0.6B {100 * share06:.3f}%, ARLoop-1.2B {100 * share12:.3f}%\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5d165f8",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.effective_sublayers(c12) == 144 and v12 == 290 and c12[\"hidden_size\"] == 2048 and r12 == 593_920\n",
    "assert f\"{100 * share06:.3f}\" == \"0.057\" and f\"{100 * share12:.3f}\" == \"0.049\"\n",
    "assert lib.quote_check(lib.DIGEST, \"routing parameters $290 \\\\times 2048 = 593{,}920$\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e397f32",
   "metadata": {},
   "source": [
    "ARLoop-1.2B has 144 effective sublayers and $290 \\times 2048 = 593{,}920$ routing parameters. In\n",
    "both models the routing is about 0.05% of the parameters (0.057% and 0.049%). **[code + num]**\n",
    "\n",
    "## One effective vector per sublayer\n",
    "\n",
    "In the score $q_i^\\top\\operatorname{Norm}(z_j)$ the RMSNorm weight $g_i$ multiplies the query\n",
    "coordinate-wise, so only $q_i \\odot g_i$ matters: one effective routing vector per routing call\n",
    "**[code]**. The vector of call 0 is inert (finding F8; {doc}`m1_window`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "085a55d9",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "eff = (lib.effective_sublayers(c06) + 1) * c06[\"hidden_size\"]\n",
    "print(f\"effective routing vectors of ARLoop-0.6B: {lib.effective_sublayers(c06) + 1}\")\n",
    "print(f\"    {eff:,} effective parameters, of which {c06['hidden_size']:,} (call 0) cannot act\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90567b63",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert eff == 167_424 == r06 // 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6412bb7e",
   "metadata": {},
   "source": [
    "## More loops than trained\n",
    "\n",
    "PreNormLoop has no depth-indexed parameters, so it runs at any number of loops. ARLoop-0.6B has\n",
    "routing parameters (a query and a norm weight) for 108 sublayers and none for a fourth loop: running\n",
    "it at $R > 3$ needs a rule for the missing ones (finding F1 of the digest). The paper's App. D.2\n",
    "initialises new queries for the unseen depths and trains them with the rest of the model frozen; E1\n",
    "instead declares two inference-only rules (`experiments/e1_release/loopctl.py`), and E3 adds a\n",
    "trainable bank for loop 4."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "058700b9",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "trained = c06[\"loop_count\"]\n",
    "rows = [(k, lib.query_rule(k, trained, \"repeat\"), lib.query_rule(k, trained, \"cycle\")) for k in range(1, 7)]\n",
    "lib.md(lib.table(rows, [\"loop\", \"routing reused under `repeat`\", \"routing reused under `cycle`\"]))\n",
    "bank = 2 * c06[\"physical_layers\"] * c06[\"hidden_size\"]\n",
    "print(f\"E3's loop-4 bank: {2 * c06['physical_layers']} queries + {2 * c06['physical_layers']} norm weights\")\n",
    "print(f\"    = {2 * 2 * c06['physical_layers']} vectors = {2 * bank:,} parameters\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ede68e42",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert [r[1] for r in rows] == [1, 2, 3, 3, 3, 3] and [r[2] for r in rows] == [1, 2, 3, 1, 2, 3]\n",
    "assert 2 * bank == 110_592\n",
    "assert lib.quote_check(lib.PROTOCOL[\"E1\"], \"rule `repeat` (reuse loop 3's) and `cycle` (loop k reuses loop\")\n",
    "assert lib.quote_check(lib.PROTOCOL[\"E3\"], \"36 extra sublayer queries and 36 extra RMSNorm weights for loop 4\",\n",
    "                       \"initialised as FP32 copies of loop 3's\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2282fd50",
   "metadata": {},
   "source": [
    "Under `repeat`, loops 4, 5 and 6 reuse the queries and norm weights of loop 3; under `cycle`, loop 4\n",
    "reuses loop 1's, loop 5 loop 2's and loop 6 loop 3's. E3's bank for a fourth loop has 36 queries and 36 norm weights\n",
    "(110,592 parameters), initialised as copies of loop 3's and trained only in the random-depth arm.\n",
    "Whether any of this helps is an experimental question (see {doc}`E1 <../tests/e1_release>`,\n",
    "{doc}`E3 <../tests/e3_proofs>` and {doc}`Stage 1c <../tests/stage1>`). **[num]**"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
