{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-1 fw=all -->\n",
    "\n",
    "# Hybrid Architectures\n",
    "\n",
    "Every memory in this chapter has been a fixed block of numbers. We gated\n",
    "it, linearized it, made it selective, taught it to edit itself, and\n",
    "finally recognized it as a regressor fitting itself at test time — and\n",
    "none of that changed its size. that section ended\n",
    "on the question the whole chapter has been postponing: when the state is\n",
    "not enough, how much genuine attention must a model keep? This section\n",
    "answers with measurements. It is also the delivery of a promise made\n",
    "from the other side of the divide: the cache-relief map of\n",
    "that section ended with a rung it could only gesture at —\n",
    "interleave a few full-attention layers into a mostly recurrent stack, so\n",
    "that most layers pay no cache at all while a few retain exact recall —\n",
    "and that section called the bet on that rung \"that\n",
    "chapter's story\". This is that story.\n",
    "\n",
    "The plan follows the trade itself. First the *limit*: what a fixed state\n",
    "cannot do, with the counting theorem — conditions included — and the\n",
    "production symptoms that made hybrids necessary. Then the *price*: only\n",
    "attention layers pay a\n",
    "growing cache, an asymmetry worth a factor of eight in serving memory at\n",
    "long context. Then the *experiment*, the section's centerpiece: three\n",
    "matched models — pure linear recurrence, pure attention, and a hybrid\n",
    "differing by a single layer — swept until the fixed state saturates,\n",
    "with a language-modeling panel that shows why perplexity did not see the\n",
    "problem. Finally the *engineering*: the measured design rules from\n",
    "shipped systems, a recipe table from Jamba to Kimi Linear, and the\n",
    "distillation shortcut that turns a pretrained transformer into a hybrid\n",
    "for a fraction of the training bill.\n",
    "\n",
    "*Prerequisites: the KV-cache accounting of that section\n",
    "(the equation); the matrix state, its capacity\n",
    "proposition, and the duality of that section; and the\n",
    "recall task of that section.*"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-hybrid-architectures"
   },
   "source": [
    "%matplotlib inline\n",
    "from d2l import torch as d2l\n",
    "import math\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch import nn\n",
    "import torch.nn.functional as F"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-2 fw=all -->\n",
    "\n",
    "## What a Fixed State Cannot Do\n",
    "\n",
    "Selectivity fixed content-blindness. The delta rule fixed the additive\n",
    "write. Test-time learning fixed staleness. None of them fixed capacity,\n",
    "and none can: a state of $N$ numbers at any fixed numerical precision\n",
    "holds a bounded number of bits, and\n",
    "information theory does not care how cleverly the update rule was\n",
    "chosen. To reproduce $k$ arbitrary tokens from a vocabulary of size\n",
    "$V$, *something* in the model must hold $k \\log_2 V$ bits from the\n",
    "moment they appear to the moment they are needed. Our own measurements\n",
    "have circled this wall all chapter. The crowding proposition of\n",
    "that section is the wall seen from below: expected\n",
    "squared read\n",
    "error $(n-1)/d_k$ after $n$ random-key writes, interference growing\n",
    "linearly in\n",
    "how much you store. And the transition ladder of the table\n",
    "is the wall seen from the side: each rung changed what the state can\n",
    "*compute* — forgetting, erasure, reflections, group words — while the\n",
    "number of bits it holds never moved.\n",
    "\n",
    "@Jelassi.Brandfonbrener.Kakade.ea.2024 make the limit a theorem,\n",
    "using the purest recall task there is: copying. Both directions of their\n",
    "comparison carry conditions, so we state the two results together, with\n",
    "matching quantifiers.\n",
    "\n",
    "> **The copy bounds** [@Jelassi.Brandfonbrener.Kakade.ea.2024].\n",
    "> *Transformer, upper bound:* there is a depth-two transformer of width\n",
    "> $O(n \\log D)$ that copies any string over an alphabet of size $D$ up\n",
    "> to length $D^n$, *provided no length-$n$ substring repeats* — the\n",
    "> construction addresses the archive by hashed $n$-grams, and the\n",
    "> attention window over everything so far supplies the storage, growing\n",
    "> with the sequence. *Generalized SSM, lower bound:* any model that\n",
    "> pushes the sequence through a fixed, finite state set $\\mathcal{S}$ —\n",
    "> every architecture in this chapter, at any fixed precision — errs on\n",
    "> copying a string drawn *uniformly at random* from the $D^L$ strings of\n",
    "> length $L$ with probability at least $1 - |\\mathcal{S}|/D^L$; once the\n",
    "> state holds fewer than about $L \\log_2 D$ bits, it gets most such\n",
    "> copies wrong.\n",
    "\n",
    "Neither half reduces to \"attention remembers, recurrence cannot\". The\n",
    "upper bound is a construction, valid for strings without repeated\n",
    "$n$-grams; the lower bound is a counting argument over the uniform copy\n",
    "distribution, and it says nothing about a narrower workload — a state\n",
    "that stores just the strings its training distribution favors evades\n",
    "it. What the count does rule out is a fixed state that copies\n",
    "*arbitrary* strings much longer than its bit budget: there are $D^L$\n",
    "required outputs and only $|\\mathcal{S}|$ states to route them through,\n",
    "and no parameterization, gating, or training trick appears anywhere in\n",
    "that ratio. Empirically the crossover is not close: on synthetic\n",
    "phone-book\n",
    "lookup, the smallest transformer they test, at 410M parameters, beats a\n",
    "2.8B-parameter Mamba once the book exceeds roughly seventy entries.\n",
    "\n",
    "Where does the wall bite in real language?\n",
    "@Arora.Eyuboglu.Timalsina.ea.2024 located it with *multi-query\n",
    "associative recall* (MQAR): a stream writes key–value bindings, later\n",
    "re-presents keys in arbitrary order, and the model must produce each\n",
    "key's value — our overwrite task of that section,\n",
    "embedded in text. Across seventeen trained language models, 82% of the\n",
    "perplexity gap between efficient architectures and attention fell on\n",
    "the recall slice — the tokens whose prediction requires retrieving a\n",
    "binding seen once before. Attention solves MQAR at a width independent\n",
    "of sequence length; recurrent models solve it only while the bindings\n",
    "in play fit in their state — the crowding picture again, now\n",
    "diagnosed in the wild.\n",
    "\n",
    "At production scale the failure has a name. In NVIDIA's controlled\n",
    "8B-parameter comparison, a pure Mamba-2 model matched a transformer on\n",
    "perplexity and most benchmarks while scoring 29% on five-shot MMLU\n",
    "against the transformer's 46%, and its phone-book recall collapsed once\n",
    "the book grew past a few hundred tokens; the authors call the mode\n",
    "*fuzzy memory* — the model returns an answer that shares digits with\n",
    "the right one [@Waleffe.Byeon.Riach.ea.2024]. The practitioner's\n",
    "version of the diagnosis is blunter: ablate the few full-attention\n",
    "layers of a shipped hybrid and needle-in-a-haystack retrieval drops to\n",
    "roughly zero. A handful of full layers carries retrieval; the linear\n",
    "majority carries cheap throughput.\n",
    "\n",
    "@Gu.2025 offers a framing for this trade worth carrying to the\n",
    "end of the section. A recurrent state is a *brain*: a compressed,\n",
    "always-on working memory at constant cost per step, which must decide at\n",
    "write time what will matter later, and therefore forgets. The\n",
    "transformer's growing key–value cache is a *database*: a lossless log of\n",
    "everything, pay-per-query at ever-growing cost, which never has to\n",
    "predict what will matter because it keeps it all. Neither dominates,\n",
    "because they fail on different bills — the brain loses exact recall, the\n",
    "database loses the economics. The obvious synthesis, a brain in front of\n",
    "a database, is where production actually landed, and the rest of this\n",
    "section is about its terms.\n",
    "\n",
    "## The Economics\n",
    "\n",
    "If the fixed state loses the recall fight, why not concede and serve\n",
    "pure transformers? Because of the bill that that section\n",
    "measured: cache bytes $= 2 \\cdot n_\\textrm{layers} \\cdot n_\\textrm{kv}\n",
    "\\cdot d_\\textrm{head} \\cdot n \\cdot b$ times the element size,\n",
    "the equation, growing linearly in the context length\n",
    "$n$. The factor that matters here is $n_\\textrm{layers}$: *the cache is\n",
    "paid per attention layer*. A recurrent layer holds a state whose shape\n",
    "the equation fixes at $d_k \\times d_v$ numbers per head\n",
    "and whose bytes the per-layer formula the equation\n",
    "prices. Priced concretely, a Mamba-2 layer at $d_\\textrm{model} = 4096$\n",
    "with the usual expansion factor of two (so $d_\\textrm{inner} = 8192$)\n",
    "and state width $d_\\textrm{state} = 128$ carries $8192 \\cdot 128\n",
    "\\approx 1.05\\textrm{M}$ state elements — about 2 MB at the fp16\n",
    "serving precision that formula's headline uses, with the small\n",
    "convolution buffer adding another two percent\n",
    "— and that figure is the same at token one hundred and at token one\n",
    "million. A full-attention layer with grouped queries at the same width\n",
    "pays 4 KB *per token*: past a few hundred tokens the growing archive\n",
    "dwarfs the flat state, and by 128K context one attention layer holds\n",
    "512 MB against the recurrent layer's 2 MB.\n",
    "the figure draws the consequence for a whole model: replace\n",
    "most attention layers with recurrent ones and the memory bill drops by\n",
    "almost exactly the fraction of attention you removed, because the\n",
    "surviving attention layers are the only ones still paying rent.\n",
    "\n",
    "![Persistent decode state against context length for a 32-layer model at production width (GQA with $8$ key–value heads of dimension 128, Mamba-2-sized states, 16-bit). The count covers only the per-user state a server holds between decode steps — KV cache plus recurrent state — excluding parameters, activations, and workspace. A pure transformer's cache reaches 32 GB at 256K context; a pure recurrent stack stays near 64 MB at every length; a 4-of-32 hybrid pays the attention fraction of the transformer bill.](../img/mdl-modernrnn-hybrid-cache.svg)\n",
    "\n",
    "Those curves are not hypothetical: they are the memory column of\n",
    "Jamba's model card. At 256K context, Jamba — 4 attention layers out of\n",
    "32, the rest Mamba — reports a 4 GB key–value cache where the\n",
    "comparably sized Mixtral carries 32 GB and a Llama-2-70B-class\n",
    "transformer 128 GB [@Lieber.Lenz.Bata.ea.2024]. An eightfold saving\n",
    "on the resource that decides how many concurrent users fit on an\n",
    "accelerator (recall from that section that decode is\n",
    "bandwidth-bound, so cache bytes are also the currency of generation\n",
    "speed) is the kind of number that redraws architectures, and it comes\n",
    "from nothing more than the layer count in the equation.\n",
    "\n",
    "One structural remark before we measure the other side of the trade.\n",
    "The cache relief of that section came in flavors that\n",
    "*compose*: GQA and MLA shrink the width of each cached token, sliding\n",
    "windows bound its lifetime, quantization shrinks its bytes, and a\n",
    "deployment can apply all three to the same cache. Replacing attention\n",
    "with recurrence removes the growing term rather than shrinking it. The\n",
    "recurrent state is a tensor like any other — it can be quantized or held\n",
    "in lower precision too — but it is already constant in context length,\n",
    "so there is no growth left to attack; the contrast that matters is not\n",
    "compressible-versus-not but *what grows with context and what does not*.\n",
    "A hybrid gets both moves: the recurrent majority contributes only\n",
    "constant state, and the attention minority keeps a cache that GQA, MLA,\n",
    "and quantization still shrink (the recipe table below shows shipped\n",
    "hybrids doing exactly this). That is the last rung of the cache-relief\n",
    "map, delivered. What remains is the quantitative question the map could\n",
    "not answer: how few attention layers can a model keep and still recall\n",
    "like a transformer?\n",
    "\n",
    "## The Experiment: One Attention Layer Rescues Recall\n",
    "\n",
    "We answer at teaching scale, with machinery this book has already\n",
    "built. Three models, identical in every dimension — depth, width,\n",
    "heads, embeddings, MLPs, parameter count to within a percent (the model\n",
    "cell below prints the counts) — except\n",
    "for the token mixer inside each block. The task is MQAR, sized so that\n",
    "the sweep crosses the fixed state's capacity. The claim to test is the\n",
    "one the last two sections set up: recall should collapse for the pure\n",
    "recurrent stack when the bindings exceed what its state can hold, a\n",
    "single mid-stack attention layer should restore it, and language-model\n",
    "loss should barely notice any of it.\n",
    "\n",
    "### Three Matched Models\n",
    "\n",
    "The task generator is the one from that section with the\n",
    "re-binding knob removed and the *load* knob exposed: each sequence\n",
    "writes `num_pairs` distinct key–value bindings, then queries every key\n",
    "in random order. Sweeping `num_pairs` sweeps the number of bits the\n",
    "model must carry from write phase to query phase."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-three-matched-models-1"
   },
   "source": [
    "def make_recall(num_seqs, num_pairs, num_keys=64, num_values=32, seed=0):\n",
    "    \"\"\"Write num_pairs distinct bindings, then query each key once.\"\"\"\n",
    "    task_rng = np.random.default_rng(seed)\n",
    "    P, T = num_pairs, 2 * num_pairs\n",
    "    QUERY = num_values                    # A reserved \"query\" content token\n",
    "    keys = np.zeros((num_seqs, T), np.int64)\n",
    "    vals = np.full((num_seqs, T), QUERY, np.int64)\n",
    "    tgt = np.full((num_seqs, T), -1, np.int64)\n",
    "    for b in range(num_seqs):\n",
    "        ks = task_rng.choice(num_keys, size=P, replace=False)\n",
    "        vs = task_rng.integers(0, num_values, size=P)\n",
    "        keys[b, :P], vals[b, :P] = ks, vs\n",
    "        qorder = task_rng.permutation(P)\n",
    "        keys[b, P:] = ks[qorder]\n",
    "        tgt[b, P:] = vs[qorder]\n",
    "    return keys, vals, tgt                # tgt = -1 outside the query phase"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-3 fw=all -->\n",
    "\n",
    "The recurrent mixer is *scalar-gated* linear attention: an\n",
    "input-dependent decay $a_t$, one number per head per token, applied to a\n",
    "matrix state per head. On the decay ladder of\n",
    "the figure this is Mamba-2's rung\n",
    "[@Dao.Gu.2024], one below the per-coordinate diagonal gate that\n",
    "defines GLA proper [@Yang.Wang.Shen.ea.2024]; we take the scalar\n",
    "rung because it is the cheapest transition that forgets, and name the\n",
    "class for what it is: `ScalarGatedMixer`. We train it through the\n",
    "quadratic dual $\\mathbf{Y} = (\\mathbf{L} \\circ\n",
    "\\mathbf{Q}\\mathbf{K}^\\top)\\mathbf{V}$ of the equation,\n",
    "which that section verified equal to the recurrence to\n",
    "float32 rounding — so this is a genuine linear-recurrence model,\n",
    "computed the fast way.\n",
    "\n",
    "Three lines of the implementation are load-bearing, and each encodes a\n",
    "lesson that cost real debugging time, so we state them as prose rather\n",
    "than leaving them as comments. First, **a fresh gate must retain**.\n",
    "With a default-initialized gate the decay comes out around\n",
    "$a \\approx 0.5$ per token — a state half-life of one token — and the\n",
    "untrained model destroys the write phase before the query phase\n",
    "arrives; it then sits at chance recall for every load we test, and\n",
    "training rarely digs it out. Initializing the gate bias at $-4.5$ gives\n",
    "$a \\approx 0.99$, a half-life of about seventy tokens, and the problem\n",
    "disappears. Every production cell in this family makes the same move:\n",
    "S4D's small initial step sizes (that section), Mamba's\n",
    "$\\Delta$ bias, the retention bias we gave Gated DeltaNet in\n",
    "that section. Second, **mask before exponentiating**. The\n",
    "dual builds $\\mathbf{L}$ as $\\exp(\\textrm{cum}_i - \\textrm{cum}_j)$;\n",
    "above the diagonal that exponent is large and *positive*, and once\n",
    "training pushes some head's decay toward zero — which language modeling\n",
    "does within a few hundred steps — the $\\exp$ overflows to infinity and\n",
    "`inf * 0 = nan` kills the run. Masking with $-\\infty$ *before* the\n",
    "$\\exp$, as `segsum` did in that section, makes the upper\n",
    "triangle an exact zero instead. In our runs the recall task does not\n",
    "trigger this\n",
    "overflow; the language-modeling panel below does, reliably. A bug that\n",
    "only fires on one of your two benchmarks is the expensive kind. Third,\n",
    "**normalize the read-out**. The memory read $\\mathbf{S}_t^\\top\n",
    "\\mathbf{q}_t$ is a sum over everything the state has accumulated, so\n",
    "its scale grows with how much has been written — order $\\sqrt{T}$ at\n",
    "initialization — while the residual stream it joins does not. This\n",
    "family therefore normalizes the *output*, not a carried normalizer\n",
    "state (the design decision discussed in that section,\n",
    "and the RMSNorm inside our Gated DeltaNet cell): a per-head RMSNorm on\n",
    "the read-out before the output projection. Without it, our four-block\n",
    "stacks train erratically at this sequence length — in one framework\n",
    "the hybrid never leaves chance recall — because the untrained\n",
    "recurrent blocks flood the residual stream and the attention layer\n",
    "downstream never sees the tokens."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-three-matched-models-2"
   },
   "source": [
    "class ScalarGatedMixer(nn.Module):\n",
    "    \"\"\"Scalar-gated linear attention (Mamba-2's rung), via the dual.\"\"\"\n",
    "    def __init__(self, num_hiddens, num_heads):\n",
    "        super().__init__()\n",
    "        self.num_heads, self.d_head = num_heads, num_hiddens // num_heads\n",
    "        self.W_qkv = nn.Linear(num_hiddens, 3 * num_hiddens, bias=False)\n",
    "        self.W_g = nn.Linear(num_hiddens, num_heads)\n",
    "        nn.init.constant_(self.W_g.bias, -4.5)     # A fresh gate must retain\n",
    "        self.norm = nn.RMSNorm(self.d_head)        # Normalize the read-out\n",
    "        self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=False)\n",
    "\n",
    "    def forward(self, X, *_):\n",
    "        B, T, d = X.shape\n",
    "        q, k, v = self.W_qkv(X).reshape(B, T, self.num_heads, 3,\n",
    "                                        self.d_head).unbind(3)\n",
    "        log_a = -F.softplus(self.W_g(X))           # log a_t < 0, per head\n",
    "        cum = log_a.cumsum(1)\n",
    "        logL = cum[:, :, None, :] - cum[:, None, :, :]   # (B, T, T, heads)\n",
    "        causal = torch.tril(torch.ones(T, T, dtype=torch.bool,\n",
    "                                       device=X.device))\n",
    "        logL = logL.masked_fill(~causal[None, :, :, None], -torch.inf)\n",
    "        scores = torch.einsum('bihd,bjhd->bijh', q, k) / math.sqrt(self.d_head)\n",
    "        Y = torch.einsum('bijh,bjhd->bihd', torch.exp(logL) * scores, v)\n",
    "        return self.W_o(self.norm(Y).reshape(B, T, d))"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-4 fw=all -->\n",
    "\n",
    "The attention mixer needs no new code at all: it is the causal\n",
    "multi-head attention of that section, dropped into the\n",
    "configurable block of that section through its\n",
    "`attn_factory` hook — the same hook the GPT model itself uses. A stack\n",
    "is then a *string*: one letter per block, `'G'` for the scalar-gated\n",
    "recurrence, `'A'` for full attention. The entire architectural question\n",
    "of this section fits in three such strings."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-three-matched-models-3"
   },
   "source": [
    "LAYOUTS = {'linear': 'GGGG', 'attention': 'AAAA', 'hybrid': 'GGAG'}"
   ],
   "execution_count": 4,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-5 fw=all -->\n",
    "\n",
    "The hybrid places its one attention layer third of four — mid-stack,\n",
    "not first, a choice the design rules below will justify. Everything\n",
    "around the mixers (pre-norm residuals, MLPs, embeddings, readout) is\n",
    "identical across the three models; the key and value channels are\n",
    "embedded separately and summed, as in that section, plus\n",
    "a learned position embedding shared by all three (a `pos=False` switch\n",
    "drops it, and a guard in `forward` refuses sequences longer than the\n",
    "table — the first exercise relies on both)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-three-matched-models-4"
   },
   "source": [
    "def make_blocks(layout, num_hiddens, num_heads):\n",
    "    \"\"\"'G' = scalar-gated recurrence block, 'A' = full-attention block.\"\"\"\n",
    "    gated = lambda: ScalarGatedMixer(num_hiddens, num_heads)\n",
    "    attn = lambda: d2l.GPT.CausalAttention(num_hiddens, num_heads)\n",
    "    return nn.ModuleList([\n",
    "        d2l.TransformerBlock(num_hiddens, num_heads, norm='layer', act='gelu',\n",
    "                             attn_factory=attn if c == 'A' else gated)\n",
    "        for c in layout])\n",
    "\n",
    "class RecallModel(nn.Module):\n",
    "    def __init__(self, layout, num_keys, num_values, max_len,\n",
    "                 num_hiddens=32, num_heads=4, pos=True):\n",
    "        super().__init__()\n",
    "        self.key_emb = nn.Embedding(num_keys, num_hiddens)\n",
    "        self.val_emb = nn.Embedding(num_values + 1, num_hiddens)\n",
    "        self.pos_emb = nn.Embedding(max_len, num_hiddens) if pos else None\n",
    "        self.blocks = make_blocks(layout, num_hiddens, num_heads)\n",
    "        self.norm = nn.LayerNorm(num_hiddens)\n",
    "        self.head = nn.Linear(num_hiddens, num_values)\n",
    "\n",
    "    def forward(self, keys, vals):\n",
    "        X = self.key_emb(keys) + self.val_emb(vals)\n",
    "        if self.pos_emb is not None:\n",
    "            assert keys.shape[1] <= self.pos_emb.num_embeddings, \\\n",
    "                'sequence exceeds the position table: raise max_len'\n",
    "            X = X + self.pos_emb(torch.arange(keys.shape[1],\n",
    "                                              device=keys.device))\n",
    "        for blk in self.blocks:\n",
    "            X = blk(X)\n",
    "        return self.head(self.norm(X))\n",
    "\n",
    "for name, layout in LAYOUTS.items():\n",
    "    model = RecallModel(layout, num_keys=64, num_values=32, max_len=128)\n",
    "    print(f'{name:>10}: '\n",
    "          f'{sum(p.numel() for p in model.parameters()):,} parameters')"
   ],
   "execution_count": 5,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "    linear: 58,544 parameters\n attention: 57,984 parameters\n    hybrid: 58,404 parameters\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-6 fw=all -->\n",
    "\n",
    "The printed counts back the \"matched\" claim with numbers: 58,544\n",
    "(linear), 57,984 (attention), and 58,404 (hybrid) parameters — a spread\n",
    "of 560, just under one percent, coming from the gate projection and\n",
    "read-out norm that each scalar-gated mixer carries and the attention\n",
    "mixer does not. Parameter count is not the whole story of a fair\n",
    "comparison (the mixers do different amounts of compute per token, which\n",
    "the table prices), but it rules out the\n",
    "crudest confound: none of the recall differences below can come from\n",
    "one model simply being bigger.\n",
    "\n",
    "### The Recall Sweep\n",
    "\n",
    "Width is the experiment's one carefully chosen number. At\n",
    "`num_hiddens=32` with four heads, each head's state is $8 \\times 8$.\n",
    "The random-key proposition of that section — used here\n",
    "as a sizing heuristic, not as the theory of this model: a trained\n",
    "four-layer stack with learned keys is far from the proposition's single\n",
    "random-key memory — suggests a head crowds at order-eight bindings, so\n",
    "a sweep of `num_pairs` from 4 to 64 should cross the whole stack's\n",
    "capacity mid-sweep. (Widen the model and the cliff should move right;\n",
    "the counting bound above says it cannot disappear.) One\n",
    "protocol note: small-scale MQAR results are notoriously sensitive to\n",
    "the learning rate, so @Arora.Eyuboglu.Timalsina.ea.2024 sweep\n",
    "it per configuration and report the best. We piloted their grid\n",
    "$\\{3 \\times 10^{-4}, 10^{-3}, 3 \\times 10^{-3}\\}$ and pin the winner,\n",
    "$3 \\times 10^{-3}$, for every cell below; at $3 \\times 10^{-4}$,\n",
    "*every* architecture sits near chance at the largest loads, and a\n",
    "careless single-rate comparison at that setting would report no\n",
    "architecture gap at all. Optimization noise can manufacture or erase\n",
    "the effect you are looking for — sweep or pin deliberately, and say\n",
    "which."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-the-recall-sweep-1"
   },
   "source": [
    "def train_recall(layout, num_pairs, lr=3e-3, num_keys=64, num_values=32,\n",
    "                 epochs=16, batch_size=128):\n",
    "    device = d2l.try_gpu()\n",
    "    torch.manual_seed(0)\n",
    "    num_train = 8192 if num_pairs <= 16 else 16384\n",
    "    data = [torch.tensor(x, device=device) for x in\n",
    "            make_recall(num_train, num_pairs, num_keys, num_values, seed=1)\n",
    "            + make_recall(2048, num_pairs, num_keys, num_values, seed=2)]\n",
    "    Xk, Xv, y, Vk, Vv, Vy = data\n",
    "    model = RecallModel(layout, num_keys, num_values,\n",
    "                        2 * num_pairs).to(device)\n",
    "    opt = torch.optim.Adam(model.parameters(), lr=lr)\n",
    "    for epoch in range(epochs):\n",
    "        for i in torch.randperm(num_train, device=device).split(batch_size):\n",
    "            loss = F.cross_entropy(\n",
    "                model(Xk[i], Xv[i]).reshape(-1, num_values),\n",
    "                y[i].reshape(-1), ignore_index=-1)\n",
    "            opt.zero_grad(); loss.backward(); opt.step()\n",
    "    with torch.no_grad():\n",
    "        pred, mask = model(Vk, Vv).argmax(-1), Vy != -1\n",
    "        return float((pred[mask] == Vy[mask]).float().mean())\n",
    "\n",
    "loads = [4, 8, 16, 32, 64]\n",
    "recall = {name: [train_recall(layout, P) for P in loads]\n",
    "          for name, layout in LAYOUTS.items()}\n",
    "print(f\"{'pairs':>10}\" + ''.join(f'{P:>7}' for P in loads))\n",
    "for name, accs in recall.items():\n",
    "    print(f'{name:>10}' + ''.join(f'{a:>7.3f}' for a in accs))\n",
    "print(f\"{'chance':>10}\" + f'{1 / 32:>7.3f}' * len(loads))"
   ],
   "execution_count": 6,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "     pairs      4      8     16     32     64\n    linear  0.991  0.976  0.934  0.888  0.301\n attention  1.000  1.000  1.000  1.000  1.000\n    hybrid  1.000  1.000  1.000  1.000  1.000\n    chance  0.031  0.031  0.031  0.031  0.031\n"
     ]
    }
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-the-recall-sweep-2"
   },
   "source": [
    "d2l.set_figsize((5, 3))\n",
    "for name, marker in zip(LAYOUTS, ['o', 's', 'd']):\n",
    "    d2l.plt.semilogx(loads, recall[name], marker=marker, label=name, base=2)\n",
    "d2l.plt.axhline(1 / 32, color='black', lw=1, ls=':')\n",
    "d2l.plt.xlabel('key-value pairs per sequence')\n",
    "d2l.plt.ylabel('recall accuracy')\n",
    "d2l.plt.legend();\n",
    "assert min(recall['attention']) > 0.95 and min(recall['hybrid']) > 0.85\n",
    "assert recall['hybrid'][-1] > 0.95 > recall['linear'][-1]  # One layer rescues\n",
    "assert recall['linear'][-1] < 0.6      # The fixed state has saturated"
   ],
   "execution_count": 7,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"329.98125pt\" height=\"211.07625pt\" viewBox=\"0 0 329.98125 211.07625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-20T01:48:13.779406</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 211.07625 \nL 329.98125 211.07625 \nL 329.98125 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 43.78125 173.52 \nL 322.78125 173.52 \nL 322.78125 7.2 \nL 43.78125 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <defs>\n       <path id=\"mf9a4333271\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#mf9a4333271\" x=\"56.463068\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- $\\mathdefault{2^{2}}$ -->\n      <g transform=\"translate(50.863068 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_2\">\n      <g>\n       <use xlink:href=\"#mf9a4333271\" x=\"119.872159\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- $\\mathdefault{2^{3}}$ -->\n      <g transform=\"translate(114.272159 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \nQ 3050 2419 3304 2112 \nQ 3559 1806 3559 1356 \nQ 3559 666 3084 287 \nQ 2609 -91 1734 -91 \nQ 1441 -91 1130 -33 \nQ 819 25 488 141 \nL 488 750 \nQ 750 597 1062 519 \nQ 1375 441 1716 441 \nQ 2309 441 2620 675 \nQ 2931 909 2931 1356 \nQ 2931 1769 2642 2001 \nQ 2353 2234 1838 2234 \nL 1294 2234 \nL 1294 2753 \nL 1863 2753 \nQ 2328 2753 2575 2939 \nQ 2822 3125 2822 3475 \nQ 2822 3834 2567 4026 \nQ 2313 4219 1838 4219 \nQ 1578 4219 1281 4162 \nQ 984 4106 628 3988 \nL 628 4550 \nQ 988 4650 1302 4700 \nQ 1616 4750 1894 4750 \nQ 2613 4750 3031 4423 \nQ 3450 4097 3450 3541 \nQ 3450 3153 3228 2886 \nQ 3006 2619 2597 2516 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-33\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_3\">\n      <g>\n       <use xlink:href=\"#mf9a4333271\" x=\"183.28125\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- $\\mathdefault{2^{4}}$ -->\n      <g transform=\"translate(177.68125 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \nL 825 1625 \nL 2419 1625 \nL 2419 4116 \nz\nM 2253 4666 \nL 3047 4666 \nL 3047 1625 \nL 3713 1625 \nL 3713 1100 \nL 3047 1100 \nL 3047 0 \nL 2419 0 \nL 2419 1100 \nL 313 1100 \nL 313 1709 \nL 2253 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#mf9a4333271\" x=\"246.690341\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- $\\mathdefault{2^{5}}$ -->\n      <g transform=\"translate(241.090341 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_5\">\n      <g>\n       <use xlink:href=\"#mf9a4333271\" x=\"310.099432\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- $\\mathdefault{2^{6}}$ -->\n      <g transform=\"translate(304.499432 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \nQ 1688 2584 1439 2293 \nQ 1191 2003 1191 1497 \nQ 1191 994 1439 701 \nQ 1688 409 2113 409 \nQ 2538 409 2786 701 \nQ 3034 994 3034 1497 \nQ 3034 2003 2786 2293 \nQ 2538 2584 2113 2584 \nz\nM 3366 4563 \nL 3366 3988 \nQ 3128 4100 2886 4159 \nQ 2644 4219 2406 4219 \nQ 1781 4219 1451 3797 \nQ 1122 3375 1075 2522 \nQ 1259 2794 1537 2939 \nQ 1816 3084 2150 3084 \nQ 2853 3084 3261 2657 \nQ 3669 2231 3669 1497 \nQ 3669 778 3244 343 \nQ 2819 -91 2113 -91 \nQ 1303 -91 875 529 \nQ 447 1150 447 2328 \nQ 447 3434 972 4092 \nQ 1497 4750 2381 4750 \nQ 2619 4750 2861 4703 \nQ 3103 4656 3366 4563 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_6\">\n     <!-- key-value pairs per sequence -->\n     <g transform=\"translate(109.832031 201.796563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-6b\" d=\"M 581 4863 \nL 1159 4863 \nL 1159 1991 \nL 2875 3500 \nL 3609 3500 \nL 1753 1863 \nL 3688 0 \nL 2938 0 \nL 1159 1709 \nL 1159 0 \nL 581 0 \nL 581 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-79\" d=\"M 2059 -325 \nQ 1816 -950 1584 -1140 \nQ 1353 -1331 966 -1331 \nL 506 -1331 \nL 506 -850 \nL 844 -850 \nQ 1081 -850 1212 -737 \nQ 1344 -625 1503 -206 \nL 1606 56 \nL 191 3500 \nL 800 3500 \nL 1894 763 \nL 2988 3500 \nL 3597 3500 \nL 2059 -325 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-2d\" d=\"M 313 2009 \nL 1997 2009 \nL 1997 1497 \nL 313 1497 \nL 313 2009 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-76\" d=\"M 191 3500 \nL 800 3500 \nL 1894 563 \nL 2988 3500 \nL 3597 3500 \nL 2284 0 \nL 1503 0 \nL 191 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-75\" d=\"M 544 1381 \nL 544 3500 \nL 1119 3500 \nL 1119 1403 \nQ 1119 906 1312 657 \nQ 1506 409 1894 409 \nQ 2359 409 2629 706 \nQ 2900 1003 2900 1516 \nL 2900 3500 \nL 3475 3500 \nL 3475 0 \nL 2900 0 \nL 2900 538 \nQ 2691 219 2414 64 \nQ 2138 -91 1772 -91 \nQ 1169 -91 856 284 \nQ 544 659 544 1381 \nz\nM 1991 3584 \nL 1991 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-20\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \nL 1178 3500 \nL 1178 0 \nL 603 0 \nL 603 3500 \nz\nM 603 4863 \nL 1178 4863 \nL 1178 4134 \nL 603 4134 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-71\" d=\"M 947 1747 \nQ 947 1113 1208 752 \nQ 1469 391 1925 391 \nQ 2381 391 2643 752 \nQ 2906 1113 2906 1747 \nQ 2906 2381 2643 2742 \nQ 2381 3103 1925 3103 \nQ 1469 3103 1208 2742 \nQ 947 2381 947 1747 \nz\nM 2906 525 \nQ 2725 213 2448 61 \nQ 2172 -91 1784 -91 \nQ 1150 -91 751 415 \nQ 353 922 353 1747 \nQ 353 2572 751 3078 \nQ 1150 3584 1784 3584 \nQ 2172 3584 2448 3432 \nQ 2725 3281 2906 2969 \nL 2906 3500 \nL 3481 3500 \nL 3481 -1331 \nL 2906 -1331 \nL 2906 525 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-6b\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(54.285156 0)\"/>\n      <use xlink:href=\"#DejaVuSans-79\" transform=\"translate(115.808594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-2d\" transform=\"translate(173.238281 0)\"/>\n      <use xlink:href=\"#DejaVuSans-76\" transform=\"translate(206.697266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(265.876953 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(327.15625 0)\"/>\n      <use xlink:href=\"#DejaVuSans-75\" transform=\"translate(354.939453 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(418.318359 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(479.841797 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(511.628906 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(575.105469 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(636.384766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(664.167969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(705.28125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(757.380859 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(789.167969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(852.644531 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(914.167969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(955.28125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(987.068359 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(1039.167969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-71\" transform=\"translate(1100.691406 0)\"/>\n      <use xlink:href=\"#DejaVuSans-75\" transform=\"translate(1164.167969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(1227.546875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(1289.070312 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(1352.449219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(1407.429688 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_6\">\n      <defs>\n       <path id=\"m9b6f3367aa\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m9b6f3367aa\" x=\"43.78125\" y=\"170.837419\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_7\">\n      <!-- 0.0 -->\n      <g transform=\"translate(20.878125 174.636638) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_7\">\n      <g>\n       <use xlink:href=\"#m9b6f3367aa\" x=\"43.78125\" y=\"139.621935\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.2 -->\n      <g transform=\"translate(20.878125 143.421154) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m9b6f3367aa\" x=\"43.78125\" y=\"108.406452\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 0.4 -->\n      <g transform=\"translate(20.878125 112.20567) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#m9b6f3367aa\" x=\"43.78125\" y=\"77.190968\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 0.6 -->\n      <g transform=\"translate(20.878125 80.990186) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#m9b6f3367aa\" x=\"43.78125\" y=\"45.975484\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_11\">\n      <!-- 0.8 -->\n      <g transform=\"translate(20.878125 49.774703) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \nQ 1584 2216 1326 1975 \nQ 1069 1734 1069 1313 \nQ 1069 891 1326 650 \nQ 1584 409 2034 409 \nQ 2484 409 2743 651 \nQ 3003 894 3003 1313 \nQ 3003 1734 2745 1975 \nQ 2488 2216 2034 2216 \nz\nM 1403 2484 \nQ 997 2584 770 2862 \nQ 544 3141 544 3541 \nQ 544 4100 942 4425 \nQ 1341 4750 2034 4750 \nQ 2731 4750 3128 4425 \nQ 3525 4100 3525 3541 \nQ 3525 3141 3298 2862 \nQ 3072 2584 2669 2484 \nQ 3125 2378 3379 2068 \nQ 3634 1759 3634 1313 \nQ 3634 634 3220 271 \nQ 2806 -91 2034 -91 \nQ 1263 -91 848 271 \nQ 434 634 434 1313 \nQ 434 1759 690 2068 \nQ 947 2378 1403 2484 \nz\nM 1172 3481 \nQ 1172 3119 1398 2916 \nQ 1625 2713 2034 2713 \nQ 2441 2713 2670 2916 \nQ 2900 3119 2900 3481 \nQ 2900 3844 2670 4047 \nQ 2441 4250 2034 4250 \nQ 1625 4250 1398 4047 \nQ 1172 3844 1172 3481 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-38\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_6\">\n     <g id=\"line2d_11\">\n      <g>\n       <use xlink:href=\"#m9b6f3367aa\" x=\"43.78125\" y=\"14.76\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_12\">\n      <!-- 1.0 -->\n      <g transform=\"translate(20.878125 18.559219) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_13\">\n     <!-- recall accuracy -->\n     <g transform=\"translate(14.798438 128.119375) rotate(-90) scale(0.1 -0.1)\">\n      <use xlink:href=\"#DejaVuSans-72\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(38.863281 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(100.386719 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(155.367188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(216.646484 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(244.429688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(272.212891 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(304 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(365.279297 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(420.259766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-75\" transform=\"translate(475.240234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(538.619141 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(579.732422 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(641.011719 0)\"/>\n      <use xlink:href=\"#DejaVuSans-79\" transform=\"translate(695.992188 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_12\">\n    <path d=\"M 56.463068 16.093669 \nL 119.872159 18.437117 \nL 183.28125 25.110227 \nL 246.690341 32.20249 \nL 310.099432 123.868443 \n\" clip-path=\"url(#p9f57b84cdb)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    <defs>\n     <path id=\"mfc6c9a3f13\" d=\"M 0 3 \nC 0.795609 3 1.55874 2.683901 2.12132 2.12132 \nC 2.683901 1.55874 3 0.795609 3 0 \nC 3 -0.795609 2.683901 -1.55874 2.12132 -2.12132 \nC 1.55874 -2.683901 0.795609 -3 0 -3 \nC -0.795609 -3 -1.55874 -2.683901 -2.12132 -2.12132 \nC -2.683901 -1.55874 -3 -0.795609 -3 0 \nC -3 0.795609 -2.683901 1.55874 -2.12132 2.12132 \nC -1.55874 2.683901 -0.795609 3 0 3 \nz\n\" style=\"stroke: #1f77b4\"/>\n    </defs>\n    <g clip-path=\"url(#p9f57b84cdb)\">\n     <use xlink:href=\"#mfc6c9a3f13\" x=\"56.463068\" y=\"16.093669\" style=\"fill: #1f77b4; stroke: #1f77b4\"/>\n     <use xlink:href=\"#mfc6c9a3f13\" x=\"119.872159\" y=\"18.437117\" style=\"fill: #1f77b4; stroke: #1f77b4\"/>\n     <use xlink:href=\"#mfc6c9a3f13\" x=\"183.28125\" y=\"25.110227\" style=\"fill: #1f77b4; stroke: #1f77b4\"/>\n     <use xlink:href=\"#mfc6c9a3f13\" x=\"246.690341\" y=\"32.20249\" style=\"fill: #1f77b4; stroke: #1f77b4\"/>\n     <use xlink:href=\"#mfc6c9a3f13\" x=\"310.099432\" y=\"123.868443\" style=\"fill: #1f77b4; stroke: #1f77b4\"/>\n    </g>\n   </g>\n   <g id=\"line2d_13\">\n    <path d=\"M 56.463068 14.779052 \nL 119.872159 14.807631 \nL 183.28125 14.764763 \nL 246.690341 14.774289 \nL 310.099432 14.761191 \n\" clip-path=\"url(#p9f57b84cdb)\" style=\"fill: none; stroke: #ff7f0e; stroke-width: 1.5; stroke-linecap: square\"/>\n    <defs>\n     <path id=\"m2903586001\" d=\"M -3 3 \nL 3 3 \nL 3 -3 \nL -3 -3 \nz\n\" style=\"stroke: #ff7f0e; stroke-linejoin: miter\"/>\n    </defs>\n    <g clip-path=\"url(#p9f57b84cdb)\">\n     <use xlink:href=\"#m2903586001\" x=\"56.463068\" y=\"14.779052\" style=\"fill: #ff7f0e; stroke: #ff7f0e; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m2903586001\" x=\"119.872159\" y=\"14.807631\" style=\"fill: #ff7f0e; stroke: #ff7f0e; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m2903586001\" x=\"183.28125\" y=\"14.764763\" style=\"fill: #ff7f0e; stroke: #ff7f0e; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m2903586001\" x=\"246.690341\" y=\"14.774289\" style=\"fill: #ff7f0e; stroke: #ff7f0e; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m2903586001\" x=\"310.099432\" y=\"14.761191\" style=\"fill: #ff7f0e; stroke: #ff7f0e; stroke-linejoin: miter\"/>\n    </g>\n   </g>\n   <g id=\"line2d_14\">\n    <path d=\"M 56.463068 14.817157 \nL 119.872159 14.788579 \nL 183.28125 14.764763 \nL 246.690341 14.762382 \nL 310.099432 14.76 \n\" clip-path=\"url(#p9f57b84cdb)\" style=\"fill: none; stroke: #2ca02c; stroke-width: 1.5; stroke-linecap: square\"/>\n    <defs>\n     <path id=\"m8c6bcd8bf4\" d=\"M -0 4.242641 \nL 2.545584 0 \nL 0 -4.242641 \nL -2.545584 -0 \nz\n\" style=\"stroke: #2ca02c; stroke-linejoin: miter\"/>\n    </defs>\n    <g clip-path=\"url(#p9f57b84cdb)\">\n     <use xlink:href=\"#m8c6bcd8bf4\" x=\"56.463068\" y=\"14.817157\" style=\"fill: #2ca02c; stroke: #2ca02c; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m8c6bcd8bf4\" x=\"119.872159\" y=\"14.788579\" style=\"fill: #2ca02c; stroke: #2ca02c; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m8c6bcd8bf4\" x=\"183.28125\" y=\"14.764763\" style=\"fill: #2ca02c; stroke: #2ca02c; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m8c6bcd8bf4\" x=\"246.690341\" y=\"14.762382\" style=\"fill: #2ca02c; stroke: #2ca02c; stroke-linejoin: miter\"/>\n     <use xlink:href=\"#m8c6bcd8bf4\" x=\"310.099432\" y=\"14.76\" style=\"fill: #2ca02c; stroke: #2ca02c; stroke-linejoin: miter\"/>\n    </g>\n   </g>\n   <g id=\"line2d_15\">\n    <path d=\"M 43.78125 165.96 \nL 322.78125 165.96 \n\" clip-path=\"url(#p9f57b84cdb)\" style=\"fill: none; stroke-dasharray: 1,1.65; stroke-dashoffset: 0; stroke: #000000\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 43.78125 173.52 \nL 43.78125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 322.78125 173.52 \nL 322.78125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 43.78125 173.52 \nL 322.78125 173.52 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 43.78125 7.2 \nL 322.78125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"legend_1\">\n    <g id=\"patch_7\">\n     <path d=\"M 50.78125 113.877188 \nL 128.395313 113.877188 \nQ 130.395313 113.877188 130.395313 111.877188 \nL 130.395313 68.842813 \nQ 130.395313 66.842813 128.395313 66.842813 \nL 50.78125 66.842813 \nQ 48.78125 66.842813 48.78125 68.842813 \nL 48.78125 111.877188 \nQ 48.78125 113.877188 50.78125 113.877188 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_16\">\n     <path d=\"M 52.78125 74.94125 \nL 62.78125 74.94125 \nL 72.78125 74.94125 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n     <g>\n      <use xlink:href=\"#mfc6c9a3f13\" x=\"62.78125\" y=\"74.94125\" style=\"fill: #1f77b4; stroke: #1f77b4\"/>\n     </g>\n    </g>\n    <g id=\"text_14\">\n     <!-- linear -->\n     <g transform=\"translate(80.78125 78.44125) scale(0.1 -0.1)\">\n      <use xlink:href=\"#DejaVuSans-6c\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(27.783203 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(55.566406 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(118.945312 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(180.46875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(241.748047 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_17\">\n     <path d=\"M 52.78125 89.619375 \nL 62.78125 89.619375 \nL 72.78125 89.619375 \n\" style=\"fill: none; stroke: #ff7f0e; stroke-width: 1.5; stroke-linecap: square\"/>\n     <g>\n      <use xlink:href=\"#m2903586001\" x=\"62.78125\" y=\"89.619375\" style=\"fill: #ff7f0e; stroke: #ff7f0e; stroke-linejoin: miter\"/>\n     </g>\n    </g>\n    <g id=\"text_15\">\n     <!-- attention -->\n     <g transform=\"translate(80.78125 93.119375) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-61\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(61.279297 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(100.488281 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(139.697266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(201.220703 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(264.599609 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(303.808594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(331.591797 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(392.773438 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_18\">\n     <path d=\"M 52.78125 104.2975 \nL 62.78125 104.2975 \nL 72.78125 104.2975 \n\" style=\"fill: none; stroke: #2ca02c; stroke-width: 1.5; stroke-linecap: square\"/>\n     <g>\n      <use xlink:href=\"#m8c6bcd8bf4\" x=\"62.78125\" y=\"104.2975\" style=\"fill: #2ca02c; stroke: #2ca02c; stroke-linejoin: miter\"/>\n     </g>\n    </g>\n    <g id=\"text_16\">\n     <!-- hybrid -->\n     <g transform=\"translate(80.78125 107.7975) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-62\" d=\"M 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\nM 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2969 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-64\" d=\"M 2906 2969 \nL 2906 4863 \nL 3481 4863 \nL 3481 0 \nL 2906 0 \nL 2906 525 \nQ 2725 213 2448 61 \nQ 2172 -91 1784 -91 \nQ 1150 -91 751 415 \nQ 353 922 353 1747 \nQ 353 2572 751 3078 \nQ 1150 3584 1784 3584 \nQ 2172 3584 2448 3432 \nQ 2725 3281 2906 2969 \nz\nM 947 1747 \nQ 947 1113 1208 752 \nQ 1469 391 1925 391 \nQ 2381 391 2643 752 \nQ 2906 1113 2906 1747 \nQ 2906 2381 2643 2742 \nQ 2381 3103 1925 3103 \nQ 1469 3103 1208 2742 \nQ 947 2381 947 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-68\"/>\n      <use xlink:href=\"#DejaVuSans-79\" transform=\"translate(63.378906 0)\"/>\n      <use xlink:href=\"#DejaVuSans-62\" transform=\"translate(122.558594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(186.035156 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(227.148438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-64\" transform=\"translate(254.931641 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"p9f57b84cdb\">\n   <rect x=\"43.78125\" y=\"7.2\" width=\"279\" height=\"166.32\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-7 fw=all -->\n",
    "\n",
    "The three curves are the section's thesis in one picture. The pure\n",
    "linear-recurrence stack degrades as the load grows and collapses at 64\n",
    "pairs, where it recovers fewer than half of the queries — consistent\n",
    "with the crowding heuristic's cliff for $8 \\times 8$ states asked to\n",
    "hold 64 bindings, though read that as a diagnostic analogy: the\n",
    "proposition's random-key assumptions do not cover this trained,\n",
    "four-layer model. The pure attention stack scores 1.000 at every load\n",
    "in both frameworks' runs: its\n",
    "\"state\" at the query is the whole write phase, so load never crowds\n",
    "it. And the hybrid, three quarters of which is the same recurrence\n",
    "that just collapsed, tracks attention closely — in our PyTorch run it\n",
    "too scores 1.000 at every load; in JAX it dips to roughly 0.92–0.94\n",
    "mid-sweep\n",
    "and returns to 0.99–1.00 at the two largest loads, exactly the loads\n",
    "that break the linear stack. One mid-stack attention layer buys back\n",
    "the\n",
    "recall deficit at this scale — the miniature of the finding, in\n",
    "controlled studies at the hundred-million-parameter scale, that adding\n",
    "attention to a Mamba backbone lifts recall benchmarks by about thirty\n",
    "points while moving reasoning benchmarks by single digits\n",
    "[@Lee.Yu.Zhang.ea.2025].\n",
    "\n",
    "### The Language-Modeling Panel\n",
    "\n",
    "If the deficit is that dramatic, why did pure recurrent language models\n",
    "ever look competitive? Because the deficit hides from the training\n",
    "objective. We train the same three stacks — same widths, same blocks,\n",
    "nothing changed but the input pipeline — as character-level language\n",
    "models on *The Time Machine* of that section, with a\n",
    "128-character context so that the window is long enough for recall to\n",
    "matter in principle."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-the-language-modeling-panel"
   },
   "source": [
    "class CharLM(nn.Module):\n",
    "    def __init__(self, layout, vocab_size, max_len, num_hiddens=32,\n",
    "                 num_heads=4):\n",
    "        super().__init__()\n",
    "        self.emb = nn.Embedding(vocab_size, num_hiddens)\n",
    "        self.pos_emb = nn.Embedding(max_len, num_hiddens)\n",
    "        self.blocks = make_blocks(layout, num_hiddens, num_heads)\n",
    "        self.norm = nn.LayerNorm(num_hiddens)\n",
    "        self.head = nn.Linear(num_hiddens, vocab_size)\n",
    "\n",
    "    def forward(self, X):\n",
    "        pos = torch.arange(X.shape[1], device=X.device)\n",
    "        H = self.emb(X) + self.pos_emb(pos)\n",
    "        for blk in self.blocks:\n",
    "            H = blk(H)\n",
    "        return self.head(self.norm(H))\n",
    "\n",
    "def train_lm(layout, data, lr=3e-3):\n",
    "    device, vocab = d2l.try_gpu(), len(data.vocab)\n",
    "    torch.manual_seed(0)\n",
    "    model = CharLM(layout, vocab, data.num_steps).to(device)\n",
    "    opt = torch.optim.Adam(model.parameters(), lr=lr)\n",
    "    for X, y in data.train_dataloader():\n",
    "        X, y = X.to(device), y.to(device)\n",
    "        loss = F.cross_entropy(model(X).reshape(-1, vocab), y.reshape(-1))\n",
    "        opt.zero_grad(); loss.backward(); opt.step()\n",
    "    with torch.no_grad():\n",
    "        total = count = 0\n",
    "        for X, y in data.val_dataloader():\n",
    "            X, y = X.to(device), y.to(device)\n",
    "            total += float(F.cross_entropy(model(X).reshape(-1, vocab),\n",
    "                                           y.reshape(-1), reduction='sum'))\n",
    "            count += y.numel()\n",
    "    return total / count\n",
    "\n",
    "data = d2l.TimeMachine(batch_size=64, num_steps=128, num_train=51200,\n",
    "                       num_val=4096, tokenization='char')\n",
    "print(f\"{'model':>10} {'val loss':>9} {'bits/char':>10}\")\n",
    "lm_loss = {}\n",
    "for name, layout in LAYOUTS.items():\n",
    "    lm_loss[name] = train_lm(layout, data)\n",
    "    print(f'{name:>10} {lm_loss[name]:>9.2f} '\n",
    "          f'{lm_loss[name] / math.log(2):>10.2f}')\n",
    "assert max(lm_loss.values()) - min(lm_loss.values()) < 0.15"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "     model  val loss  bits/char\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "    linear      1.75       2.52\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " attention      1.83       2.64\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "    hybrid      1.76       2.54\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-8 fw=all -->\n",
    "\n",
    "All three land within roughly a tenth of a nat of one another — about\n",
    "a tenth\n",
    "of a bit per character — and in our runs the pure-linear stack matches\n",
    "or beats the pure-attention stack: the model that just\n",
    "collapsed on\n",
    "the recall sweep is, by the language-modeling objective, the equal of\n",
    "the models that aced it.\n",
    "This is the cautionary dissociation, and it is the single most\n",
    "important measurement in this section. Scope it first: one pass over\n",
    "one small corpus at one seed, so it demonstrates that perplexity *can*\n",
    "sit still while exact recall collapses, not that it always does. The\n",
    "larger-scale evidence says the dissociation is the rule, though:\n",
    "across seventeen trained language models most of the\n",
    "efficient-architecture perplexity gap concentrated on the rare recall\n",
    "tokens [@Arora.Eyuboglu.Timalsina.ea.2024], and in controlled\n",
    "hybrid-ratio sweeps recall climbs steeply with the attention fraction\n",
    "while perplexity barely responds [@Wang.Zhu.Abreu.ea.2025]. The\n",
    "mechanism is the same at both scales: next-character prediction on\n",
    "ordinary text is dominated by local structure that a compressed,\n",
    "always-on state models well, and the tokens that require exact\n",
    "long-range retrieval are too rare to move the average. Perplexity was\n",
    "blind to\n",
    "the recall deficit — which is why the field needed MQAR-style probes\n",
    "and needle-in-a-haystack evaluations to see it at all\n",
    "[@Arora.Eyuboglu.Timalsina.ea.2024; @Waleffe.Byeon.Riach.ea.2024],\n",
    "and why a perplexity-matched \"efficient\" model can quietly fail as a\n",
    "retrieval engine in production. Benchmark what you actually need.\n",
    "\n",
    "### The Memory Bill, Measured\n",
    "\n",
    "The third panel is the other side of the trade, on our own models. At\n",
    "generation time an attention layer must carry its keys and values for\n",
    "the whole context, the equation; a scalar-gated layer\n",
    "carries its\n",
    "$d_k \\times d_v$ state per head, full stop. As in\n",
    "the figure, we count only the *persistent decode state* —\n",
    "the bytes a server must hold for a user between decode steps.\n",
    "Parameters, activations, and workspace are excluded; they are nearly\n",
    "identical across the three stacks anyway, as the parameter counts\n",
    "above showed. Counting those bytes per model at\n",
    "our toy width (float32, batch of one):"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "hybrids-the-memory-bill-measured"
   },
   "source": [
    "num_heads, d_head, fp_bytes = 4, 8, 4\n",
    "kv_layer = lambda T: 2 * T * num_heads * d_head * fp_bytes\n",
    "state_layer = num_heads * d_head * d_head * fp_bytes\n",
    "\n",
    "lengths = 2 ** np.arange(6, 17)\n",
    "d2l.set_figsize((5, 3))\n",
    "for name, layout in LAYOUTS.items():\n",
    "    per_model = [sum(kv_layer(T) if c == 'A' else state_layer\n",
    "                     for c in layout) / 2**10 for T in lengths]\n",
    "    d2l.plt.loglog(lengths, per_model, label=name, base=2)\n",
    "d2l.plt.xlabel('context length (tokens)')\n",
    "d2l.plt.ylabel('persistent decode state (KiB)')\n",
    "d2l.plt.legend();"
   ],
   "execution_count": 9,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"329.778125pt\" height=\"211.07625pt\" viewBox=\"0 0 329.778125 211.07625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-20T01:48:59.928114</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 211.07625 \nL 329.778125 211.07625 \nL 329.778125 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 43.578125 173.52 \nL 322.578125 173.52 \nL 322.578125 7.2 \nL 43.578125 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <defs>\n       <path id=\"m39b495e16c\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m39b495e16c\" x=\"81.62358\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- $\\mathdefault{2^{7}}$ -->\n      <g transform=\"translate(76.02358 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n        <path id=\"DejaVuSans-37\" d=\"M 525 4666 \nL 3525 4666 \nL 3525 4397 \nL 1831 0 \nL 1172 0 \nL 2766 4134 \nL 525 4134 \nL 525 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-37\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_2\">\n      <g>\n       <use xlink:href=\"#m39b495e16c\" x=\"132.350852\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- $\\mathdefault{2^{9}}$ -->\n      <g transform=\"translate(126.750852 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-39\" d=\"M 703 97 \nL 703 672 \nQ 941 559 1184 500 \nQ 1428 441 1663 441 \nQ 2288 441 2617 861 \nQ 2947 1281 2994 2138 \nQ 2813 1869 2534 1725 \nQ 2256 1581 1919 1581 \nQ 1219 1581 811 2004 \nQ 403 2428 403 3163 \nQ 403 3881 828 4315 \nQ 1253 4750 1959 4750 \nQ 2769 4750 3195 4129 \nQ 3622 3509 3622 2328 \nQ 3622 1225 3098 567 \nQ 2575 -91 1691 -91 \nQ 1453 -91 1209 -44 \nQ 966 3 703 97 \nz\nM 1959 2075 \nQ 2384 2075 2632 2365 \nQ 2881 2656 2881 3163 \nQ 2881 3666 2632 3958 \nQ 2384 4250 1959 4250 \nQ 1534 4250 1286 3958 \nQ 1038 3666 1038 3163 \nQ 1038 2656 1286 2365 \nQ 1534 2075 1959 2075 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-39\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_3\">\n      <g>\n       <use xlink:href=\"#m39b495e16c\" x=\"183.078125\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- $\\mathdefault{2^{11}}$ -->\n      <g transform=\"translate(175.228125 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(109.116211 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m39b495e16c\" x=\"233.805398\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- $\\mathdefault{2^{13}}$ -->\n      <g transform=\"translate(225.955398 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \nQ 3050 2419 3304 2112 \nQ 3559 1806 3559 1356 \nQ 3559 666 3084 287 \nQ 2609 -91 1734 -91 \nQ 1441 -91 1130 -33 \nQ 819 25 488 141 \nL 488 750 \nQ 750 597 1062 519 \nQ 1375 441 1716 441 \nQ 2309 441 2620 675 \nQ 2931 909 2931 1356 \nQ 2931 1769 2642 2001 \nQ 2353 2234 1838 2234 \nL 1294 2234 \nL 1294 2753 \nL 1863 2753 \nQ 2328 2753 2575 2939 \nQ 2822 3125 2822 3475 \nQ 2822 3834 2567 4026 \nQ 2313 4219 1838 4219 \nQ 1578 4219 1281 4162 \nQ 984 4106 628 3988 \nL 628 4550 \nQ 988 4650 1302 4700 \nQ 1616 4750 1894 4750 \nQ 2613 4750 3031 4423 \nQ 3450 4097 3450 3541 \nQ 3450 3153 3228 2886 \nQ 3006 2619 2597 2516 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n       <use xlink:href=\"#DejaVuSans-33\" transform=\"translate(109.116211 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_5\">\n      <g>\n       <use xlink:href=\"#m39b495e16c\" x=\"284.53267\" y=\"173.52\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- $\\mathdefault{2^{15}}$ -->\n      <g transform=\"translate(276.68267 188.118438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(109.116211 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_6\">\n     <!-- context length (tokens) -->\n     <g transform=\"translate(124.63125 201.796563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-78\" d=\"M 3513 3500 \nL 2247 1797 \nL 3578 0 \nL 2900 0 \nL 1881 1375 \nL 863 0 \nL 184 0 \nL 1544 1831 \nL 300 3500 \nL 978 3500 \nL 1906 2253 \nL 2834 3500 \nL 3513 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-20\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-67\" d=\"M 2906 1791 \nQ 2906 2416 2648 2759 \nQ 2391 3103 1925 3103 \nQ 1463 3103 1205 2759 \nQ 947 2416 947 1791 \nQ 947 1169 1205 825 \nQ 1463 481 1925 481 \nQ 2391 481 2648 825 \nQ 2906 1169 2906 1791 \nz\nM 3481 434 \nQ 3481 -459 3084 -895 \nQ 2688 -1331 1869 -1331 \nQ 1566 -1331 1297 -1286 \nQ 1028 -1241 775 -1147 \nL 775 -588 \nQ 1028 -725 1275 -790 \nQ 1522 -856 1778 -856 \nQ 2344 -856 2625 -561 \nQ 2906 -266 2906 331 \nL 2906 616 \nQ 2728 306 2450 153 \nQ 2172 0 1784 0 \nQ 1141 0 747 490 \nQ 353 981 353 1791 \nQ 353 2603 747 3093 \nQ 1141 3584 1784 3584 \nQ 2172 3584 2450 3431 \nQ 2728 3278 2906 2969 \nL 2906 3500 \nL 3481 3500 \nL 3481 434 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-28\" d=\"M 1984 4856 \nQ 1566 4138 1362 3434 \nQ 1159 2731 1159 2009 \nQ 1159 1288 1364 580 \nQ 1569 -128 1984 -844 \nL 1484 -844 \nQ 1016 -109 783 600 \nQ 550 1309 550 2009 \nQ 550 2706 781 3412 \nQ 1013 4119 1484 4856 \nL 1984 4856 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6b\" d=\"M 581 4863 \nL 1159 4863 \nL 1159 1991 \nL 2875 3500 \nL 3609 3500 \nL 1753 1863 \nL 3688 0 \nL 2938 0 \nL 1159 1709 \nL 1159 0 \nL 581 0 \nL 581 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-29\" d=\"M 513 4856 \nL 1013 4856 \nQ 1481 4119 1714 3412 \nQ 1947 2706 1947 2009 \nQ 1947 1309 1714 600 \nQ 1481 -109 1013 -844 \nL 513 -844 \nQ 928 -128 1133 580 \nQ 1338 1288 1338 2009 \nQ 1338 2731 1133 3434 \nQ 928 4138 513 4856 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-63\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(54.980469 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(116.162109 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(179.541016 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(218.75 0)\"/>\n      <use xlink:href=\"#DejaVuSans-78\" transform=\"translate(278.523438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(337.703125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(376.912109 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(408.699219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(436.482422 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(498.005859 0)\"/>\n      <use xlink:href=\"#DejaVuSans-67\" transform=\"translate(561.384766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(624.861328 0)\"/>\n      <use xlink:href=\"#DejaVuSans-68\" transform=\"translate(664.070312 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(727.449219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-28\" transform=\"translate(759.236328 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(798.25 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(837.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6b\" transform=\"translate(898.640625 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(952.925781 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(1014.449219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(1077.828125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-29\" transform=\"translate(1129.927734 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_6\">\n      <defs>\n       <path id=\"m2a8d56c9a3\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m2a8d56c9a3\" x=\"43.578125\" y=\"155.16\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_7\">\n      <!-- $\\mathdefault{2^{3}}$ -->\n      <g transform=\"translate(25.378125 158.959219) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-33\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_7\">\n      <g>\n       <use xlink:href=\"#m2a8d56c9a3\" x=\"43.578125\" y=\"133.56\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- $\\mathdefault{2^{5}}$ -->\n      <g transform=\"translate(25.378125 137.359219) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m2a8d56c9a3\" x=\"43.578125\" y=\"111.96\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- $\\mathdefault{2^{7}}$ -->\n      <g transform=\"translate(25.378125 115.759219) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-37\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#m2a8d56c9a3\" x=\"43.578125\" y=\"90.36\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- $\\mathdefault{2^{9}}$ -->\n      <g transform=\"translate(25.378125 94.159219) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-39\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#m2a8d56c9a3\" x=\"43.578125\" y=\"68.76\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_11\">\n      <!-- $\\mathdefault{2^{11}}$ -->\n      <g transform=\"translate(20.878125 72.559219) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(109.116211 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_6\">\n     <g id=\"line2d_11\">\n      <g>\n       <use xlink:href=\"#m2a8d56c9a3\" x=\"43.578125\" y=\"47.16\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_12\">\n      <!-- $\\mathdefault{2^{13}}$ -->\n      <g transform=\"translate(20.878125 50.959219) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(64.580078 39.046875) scale(0.7)\"/>\n       <use xlink:href=\"#DejaVuSans-33\" transform=\"translate(109.116211 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_7\">\n     <g id=\"line2d_12\">\n      <g>\n       <use xlink:href=\"#m2a8d56c9a3\" x=\"43.578125\" y=\"25.56\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_13\">\n      <!-- $\\mathdefault{2^{15}}$ -->\n      <g transform=\"translate(20.878125 29.359219) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(0 0.684375)\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(64.580078 38.965625) scale(0.7)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(109.116211 38.965625) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_14\">\n     <!-- persistent decode state (KiB) -->\n     <g transform=\"translate(14.798438 163.173281) rotate(-90) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \nL 1178 3500 \nL 1178 0 \nL 603 0 \nL 603 3500 \nz\nM 603 4863 \nL 1178 4863 \nL 1178 4134 \nL 603 4134 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-64\" d=\"M 2906 2969 \nL 2906 4863 \nL 3481 4863 \nL 3481 0 \nL 2906 0 \nL 2906 525 \nQ 2725 213 2448 61 \nQ 2172 -91 1784 -91 \nQ 1150 -91 751 415 \nQ 353 922 353 1747 \nQ 353 2572 751 3078 \nQ 1150 3584 1784 3584 \nQ 2172 3584 2448 3432 \nQ 2725 3281 2906 2969 \nz\nM 947 1747 \nQ 947 1113 1208 752 \nQ 1469 391 1925 391 \nQ 2381 391 2643 752 \nQ 2906 1113 2906 1747 \nQ 2906 2381 2643 2742 \nQ 2381 3103 1925 3103 \nQ 1469 3103 1208 2742 \nQ 947 2381 947 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-4b\" d=\"M 628 4666 \nL 1259 4666 \nL 1259 2694 \nL 3353 4666 \nL 4166 4666 \nL 1850 2491 \nL 4331 0 \nL 3500 0 \nL 1259 2247 \nL 1259 0 \nL 628 0 \nL 628 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-42\" d=\"M 1259 2228 \nL 1259 519 \nL 2272 519 \nQ 2781 519 3026 730 \nQ 3272 941 3272 1375 \nQ 3272 1813 3026 2020 \nQ 2781 2228 2272 2228 \nL 1259 2228 \nz\nM 1259 4147 \nL 1259 2741 \nL 2194 2741 \nQ 2656 2741 2882 2914 \nQ 3109 3088 3109 3444 \nQ 3109 3797 2882 3972 \nQ 2656 4147 2194 4147 \nL 1259 4147 \nz\nM 628 4666 \nL 2241 4666 \nQ 2963 4666 3353 4366 \nQ 3744 4066 3744 3513 \nQ 3744 3084 3544 2831 \nQ 3344 2578 2956 2516 \nQ 3422 2416 3680 2098 \nQ 3938 1781 3938 1306 \nQ 3938 681 3513 340 \nQ 3088 0 2303 0 \nL 628 0 \nL 628 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-70\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(63.476562 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(166.113281 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(218.212891 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(245.996094 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(298.095703 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(337.304688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(398.828125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(462.207031 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(501.416016 0)\"/>\n      <use xlink:href=\"#DejaVuSans-64\" transform=\"translate(533.203125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(596.679688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(658.203125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(713.183594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-64\" transform=\"translate(774.365234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(837.841797 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(899.365234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(931.152344 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(983.251953 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(1022.460938 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(1083.740234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(1122.949219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(1184.472656 0)\"/>\n      <use xlink:href=\"#DejaVuSans-28\" transform=\"translate(1216.259766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-4b\" transform=\"translate(1255.273438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(1320.849609 0)\"/>\n      <use xlink:href=\"#DejaVuSans-42\" transform=\"translate(1348.632812 0)\"/>\n      <use xlink:href=\"#DejaVuSans-29\" transform=\"translate(1417.236328 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_13\">\n    <path d=\"M 56.259943 165.96 \nL 81.62358 165.96 \nL 106.987216 165.96 \nL 132.350852 165.96 \nL 157.714489 165.96 \nL 183.078125 165.96 \nL 208.441761 165.96 \nL 233.805398 165.96 \nL 259.169034 165.96 \nL 284.53267 165.96 \nL 309.896307 165.96 \n\" clip-path=\"url(#p0531cb67af)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_14\">\n    <path d=\"M 56.259943 122.76 \nL 81.62358 111.96 \nL 106.987216 101.16 \nL 132.350852 90.36 \nL 157.714489 79.56 \nL 183.078125 68.76 \nL 208.441761 57.96 \nL 233.805398 47.16 \nL 259.169034 36.36 \nL 284.53267 25.56 \nL 309.896307 14.76 \n\" clip-path=\"url(#p0531cb67af)\" style=\"fill: none; stroke: #ff7f0e; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_15\">\n    <path d=\"M 56.259943 141.682383 \nL 81.62358 132.163743 \nL 106.987216 122.046237 \nL 132.350852 111.599032 \nL 157.714489 100.97847 \nL 183.078125 90.268971 \nL 208.441761 79.514419 \nL 233.805398 68.737193 \nL 259.169034 57.948592 \nL 284.53267 47.154295 \nL 309.896307 36.357147 \n\" clip-path=\"url(#p0531cb67af)\" style=\"fill: none; stroke: #2ca02c; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 43.578125 173.52 \nL 43.578125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 322.578125 173.52 \nL 322.578125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 43.578125 173.52 \nL 322.578125 173.52 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 43.578125 7.2 \nL 322.578125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"legend_1\">\n    <g id=\"patch_7\">\n     <path d=\"M 50.578125 59.234375 \nL 128.192188 59.234375 \nQ 130.192188 59.234375 130.192188 57.234375 \nL 130.192188 14.2 \nQ 130.192188 12.2 128.192188 12.2 \nL 50.578125 12.2 \nQ 48.578125 12.2 48.578125 14.2 \nL 48.578125 57.234375 \nQ 48.578125 59.234375 50.578125 59.234375 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_16\">\n     <path d=\"M 52.578125 20.298438 \nL 62.578125 20.298438 \nL 72.578125 20.298438 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_15\">\n     <!-- linear -->\n     <g transform=\"translate(80.578125 23.798438) scale(0.1 -0.1)\">\n      <use xlink:href=\"#DejaVuSans-6c\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(27.783203 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(55.566406 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(118.945312 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(180.46875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(241.748047 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_17\">\n     <path d=\"M 52.578125 34.976563 \nL 62.578125 34.976563 \nL 72.578125 34.976563 \n\" style=\"fill: none; stroke: #ff7f0e; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_16\">\n     <!-- attention -->\n     <g transform=\"translate(80.578125 38.476563) scale(0.1 -0.1)\">\n      <use xlink:href=\"#DejaVuSans-61\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(61.279297 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(100.488281 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(139.697266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(201.220703 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(264.599609 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(303.808594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(331.591797 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(392.773438 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_18\">\n     <path d=\"M 52.578125 49.654688 \nL 62.578125 49.654688 \nL 72.578125 49.654688 \n\" style=\"fill: none; stroke: #2ca02c; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_17\">\n     <!-- hybrid -->\n     <g transform=\"translate(80.578125 53.154688) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-79\" d=\"M 2059 -325 \nQ 1816 -950 1584 -1140 \nQ 1353 -1331 966 -1331 \nL 506 -1331 \nL 506 -850 \nL 844 -850 \nQ 1081 -850 1212 -737 \nQ 1344 -625 1503 -206 \nL 1606 56 \nL 191 3500 \nL 800 3500 \nL 1894 763 \nL 2988 3500 \nL 3597 3500 \nL 2059 -325 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-62\" d=\"M 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\nM 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2969 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-68\"/>\n      <use xlink:href=\"#DejaVuSans-79\" transform=\"translate(63.378906 0)\"/>\n      <use xlink:href=\"#DejaVuSans-62\" transform=\"translate(122.558594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(186.035156 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(227.148438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-64\" transform=\"translate(254.931641 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"p0531cb67af\">\n   <rect x=\"43.578125\" y=\"7.2\" width=\"279\" height=\"166.32\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=hybrids-md-9 fw=all -->\n",
    "\n",
    "The attention stack's line grows linearly with context; the linear\n",
    "stack's is\n",
    "flat at four kilobytes at every length; and the hybrid's line grows\n",
    "with\n",
    "exactly one quarter of the attention stack's slope — one of its four\n",
    "layers still pays per token. That slope ratio *is* the attention\n",
    "fraction, and it is the entire economic content of the hybrid design:\n",
    "the figure is this same plot at production width, where the\n",
    "gap between the lines is measured in tens of gigabytes. Both sides of\n",
    "the trade are now on the table, from our own runs: the hybrid recalls\n",
    "like the attention model and pays like the recurrent one, plus one\n",
    "quarter of the rent.\n",
    "\n",
    "What the experiment shows: at this scale, on this diagnostic, one\n",
    "attention layer in four recovers pure attention's recall while paying\n",
    "a quarter of its growing state — with the caveats already given\n",
    "(single seeded runs, a learning rate the pilot sweep pinned, a\n",
    "capacity heuristic rather than a theorem). What it does not show: that\n",
    "the result transfers to billion-parameter models trained on language.\n",
    "For that, the ablation studies and shipped configurations of the next\n",
    "two sections are the evidence.\n",
    "\n",
    "## Design Rules, Measured\n",
    "\n",
    "Our experiment fixed one design by fiat: one attention layer in four,\n",
    "mid-stack, full attention, one recurrence. Each of those choices is an\n",
    "axis, and by now each has been swept — by ablation studies at the\n",
    "hundred-million-to-billion scale, and by the engineering teams whose\n",
    "models the recipe table below records. the figure shows\n",
    "where four representative systems landed.\n",
    "\n",
    "![Four shipped answers to \"where does the attention go?\", drawn from each release's config at the variant named in the label. Jamba 52B repeats a 1-attention-in-8 block; Nemotron-H 8B spreads 4 attention layers on an 11-layer period, none at the front; Samba 3.8B alternates Mamba with sliding-window attention only; Zamba2 7B re-enters two weight-shared attention blocks 13 times along an 81-layer Mamba-2 backbone.](../img/mdl-modernrnn-hybrid-stacks.svg)\n",
    "\n",
    "**How much attention?** Less than you would guess, with a measurable\n",
    "knee. The founding ablation is NVIDIA's 8B study\n",
    "[@Waleffe.Byeon.Riach.ea.2024]: sweeping the attention fraction,\n",
    "validation loss was best near 8% attention and *degraded above it* —\n",
    "more attention is not monotonically better — yielding the recipe\n",
    "(roughly 43% Mamba-2, 7% attention, 50% MLP layers) that Nemotron-H and\n",
    "Granite ship nearly verbatim. Sequential hybrids in production cluster\n",
    "at 8–12.5% full attention (Jamba and MiniMax at 12.5%, Nemotron-H near\n",
    "8%, Granite at 10%), with Hunyuan-TurboS lowest at 5.5%\n",
    "[@Hunyuan.Team.2025]. The gated-DeltaNet family sits deliberately\n",
    "higher: Qwen3-Next fixes one full-attention layer per four\n",
    "[@Qwen.Team.2025], and Kimi Linear's ablation of the ratio\n",
    "$\\{0{:}1, 1{:}1, 3{:}1, 7{:}1\\}$ places the knee at 3:1 — at 7:1\n",
    "training loss matched but validation degraded, at 1:1 nothing improved\n",
    "but the bill, and pure attention (0:1) was strictly worse\n",
    "[@Kimi.Team.2025b]. Controlled academic sweeps agree from the\n",
    "other side: recall climbs steeply with the attention fraction up to\n",
    "about 1:3 while perplexity stays nearly flat across the whole range\n",
    "[@Wang.Zhu.Abreu.ea.2025] — the ratio axis is a recall dial, not\n",
    "a perplexity dial, which is our dissociation panel again, now as a\n",
    "design tool.\n",
    "\n",
    "**Where does it go?** Evenly spread, and — in every report so far —\n",
    "not first.\n",
    "@Waleffe.Byeon.Riach.ea.2024 found no placement better than\n",
    "even spacing with the first layer recurrent; the systematic study of\n",
    "@Bae.Acun.Lin.ea.2025 is blunter — \"never place Transformer\n",
    "blocks at the front\" — and finds middle placement optimal, which is why\n",
    "our toy hybrid put its one attention layer third of four. Samba\n",
    "supplies the sharpest single datapoint: inserting one full-attention\n",
    "layer at the *front* of its stack made length extrapolation collapse\n",
    "(perplexity exploding by 16K context), where the same capacity spent\n",
    "elsewhere extrapolated to 256K [@Ren.Liu.Lu.ea.2024]. The shipped\n",
    "models agree: Nemotron-H's four attention layers sit at depths 8, 19,\n",
    "30, 41 of 52 [@NVIDIA.2025]; Granite's at 6, 16, 26, 36 of 40\n",
    "[@Granite.Team.2025]; Jamba's at 4, 12, 20, 28 of 32\n",
    "[@Lieber.Lenz.Bata.ea.2024]. None of these puts attention at\n",
    "layer one. Read the rule as a heuristic distilled from a handful of\n",
    "systematic studies plus shipped practice — consistent so far, but\n",
    "extracted from a young design space, not derived from anything.\n",
    "\n",
    "**Sequential or parallel?** Interleaving whole layers is not the only\n",
    "composition. Hymba runs attention heads and Mamba-2 heads *in parallel\n",
    "inside every layer*, on the same input, outputs normalized and fused —\n",
    "and its controlled ablation has the parallel form beating the\n",
    "equivalent sequential stack (45.2% against 44.1% average on its\n",
    "commonsense suite), the argument being that the two mixers see the same\n",
    "representation rather than each other's output\n",
    "[@Dong.Fu.Diao.ea.2024]. Falcon-H1 makes the same bet with a\n",
    "continuously tunable split of channels between the attention and SSM\n",
    "branches [@Zuo.Velikanov.Chahed.ea.2025], and the systematic\n",
    "comparison of @Bae.Acun.Lin.ea.2025 places intra-layer hybrids\n",
    "on the best quality-efficiency Pareto frontier, slightly ahead of\n",
    "inter-layer. Sequential remains the production default — it is simpler\n",
    "to schedule and to distill into — but the parallel results say the\n",
    "margin is real, not folklore.\n",
    "\n",
    "**Sharing the attention you keep.** Zyphra's Zamba pushes the economics\n",
    "one step further: a single attention block whose *weights are shared*,\n",
    "re-entered every six Mamba layers (thirteen times in the 7B model), so\n",
    "global attention costs one block of parameters; Zamba2 refines this to\n",
    "two shared blocks applied alternately, each re-entry specialized by a\n",
    "cheap LoRA adapter\n",
    "[@Glorioso.Anthony.Tokpanov.ea.2024; @Glorioso.Anthony.Tokpanov.ea.2024b].\n",
    "Parameter sharing is orthogonal to the sequential-parallel axis, and it\n",
    "sharpens the section's moral: if a few attention layers carry\n",
    "retrieval, perhaps they do not even need to be *different* layers.\n",
    "\n",
    "**The pieces interact.** The components of a hybrid are not chosen\n",
    "independently, and the cleanest evidence is a negative result. AI21\n",
    "tested Mamba-2 — larger state, better standalone model — inside Jamba\n",
    "and *rejected* it: the Mamba-1-plus-attention combination trained\n",
    "better, their hypothesis being that once full-attention layers can pool\n",
    "the entire context, the recurrence no longer needs the larger state\n",
    "that made Mamba-2 win in isolation [@Lieber.Lenz.Bata.ea.2024].\n",
    "The same report found no substantial quality difference between 1:3 and\n",
    "1:7 attention ratios at their scale, so they shipped the cheaper. Both\n",
    "decisions generalize: a hybrid's recurrent half should be judged *in\n",
    "the presence of* its attention half, and where quality saturates,\n",
    "economics decides. Sliding-window attention re-enters here as a middle\n",
    "option — Samba's alternation of Mamba with windowed attention contains\n",
    "no global layer at all, yet recovers most of the recall gap and\n",
    "extrapolates to 256K, because a little *local* exact attention is\n",
    "already most of what retrieval needs [@Ren.Liu.Lu.ea.2024], the\n",
    "production echo of Based's finding that a small sliding window plus a\n",
    "linear global memory recovers over 90% of full attention's recall\n",
    "[@Arora.Eyuboglu.Zhang.ea.2024].\n",
    "\n",
    "## The Recipe Table\n",
    "\n",
    "As in that section, we close the survey with the shipped\n",
    "configurations themselves — one row per production hybrid, verified\n",
    "against each model's technical report or released configuration. The\n",
    "convergence is looser than the transformer recipe's (this design space\n",
    "is younger), but the clustering is already unmistakable: a strong\n",
    "recurrence from the ladder of the table, roughly a tenth\n",
    "to a quarter of layers as attention, evenly spread and none first,\n",
    "with the attention layers wearing the cache compressions of\n",
    "that section.\n",
    "\n",
    "<!-- tbl-caption:Shipped hybrid recipes, 2024–2025. \"Attention\" counts full-attention layers (Samba's window-only attention noted); positions are 1-indexed. Layer counts follow each release's own convention — one entry per mixer block, so a Zamba2 entry is one backbone block and its 81 is not comparable to Jamba's 32 without the config; check the source config before comparing depths across rows. The context column gives the longest context the release claims to support (the configured maximum, where a config is public); training context and long-range evaluation length are different numbers, listed separately where the report distinguishes them (Samba trains at 4K and evaluates recall at 256K). For the recurrence column see that section and that section; for the attention variants see that section. -->\n",
    "\n",
    "| model | layers | attention: count, positions | attention variant | recurrence | context |\n",
    "|:--|:--|:--|:--|:--|:--|\n",
    "| Jamba (52B-A12B) [@Lieber.Lenz.Bata.ea.2024] | 32 | 4 (12.5%), at 4/12/20/28 | full, GQA $32{:}8$ | Mamba-1 | 256K |\n",
    "| Samba (3.8B) [@Ren.Liu.Lu.ea.2024] | 64 | none full; SWA every 2nd layer | SWA 2048, near-MQA | Mamba-1 | 4K train, 256K recall |\n",
    "| Zamba2 (7B) [@Glorioso.Anthony.Tokpanov.ea.2024b] | 81 | 13 re-entries of 2 *shared* blocks | full MHA $32{:}32$, LoRA per call | Mamba-2 | 4K |\n",
    "| Nemotron-H (8B) [@NVIDIA.2025] | 52 | 4 (7.7%), at 8/19/30/41 | full, GQA $32{:}8$ | Mamba-2 | 8K |\n",
    "| Granite 4.0-H (32B-A9B) [@Granite.Team.2025] | 40 | 4 (10%), at 6/16/26/36 | full, GQA $32{:}8$, NoPE | Mamba-2 | 128K |\n",
    "| MiniMax-01 (456B-A46B) [@MiniMax.2025] | 80 | 10 (12.5%), every 8th | full, GQA $64{:}8$ | lightning attention | 1M |\n",
    "| Qwen3-Next (80B-A3B) [@Qwen.Team.2025] | 48 | 12 (25%), every 4th | gated attn, GQA $16{:}2$ | gated DeltaNet | 262K |\n",
    "| Kimi Linear (48B-A3B) [@Kimi.Team.2025b] | 27 | 7 (26%), 3 KDA per MLA | MLA, NoPE | KDA (gated DeltaNet) | 1M |\n",
    "| Falcon-H1 (34B) [@Zuo.Velikanov.Chahed.ea.2025] | — | parallel: attn $\\parallel$ SSM channels, every layer | full, GQA | Mamba-2 | 256K |\n",
    "\n",
    "Read down the columns and the section's arguments reappear as shipped\n",
    "hardware. The recurrence column is the last three sections' family —\n",
    "Mamba-1/2 from that section, gated DeltaNet and its per-channel\n",
    "refinement KDA from that section (the cell we trained on\n",
    "our scoreboard is the one Qwen3-Next ships). The attention-variant\n",
    "column shows the composition argument in action: Kimi Linear pairs its\n",
    "recurrence with MLA, Granite and Kimi drop positional encodings on the\n",
    "attention layers (NoPE), Qwen3-Next keeps only 2 key–value heads — the\n",
    "surviving cache, being most of the memory bill, receives every\n",
    "compression that section taught. And the context column\n",
    "explains the investment: the models built for the longest contexts are\n",
    "hybrids of this table's shape, because the equation made\n",
    "the alternative a hardware bill.\n",
    "\n",
    "## Distillation, and Where This Leaves Us\n",
    "\n",
    "One practical question remains: must a hybrid be pretrained from\n",
    "scratch? No — a pretrained transformer can be *converted*, and the\n",
    "state-space duality explains why conversion has a head start without\n",
    "guaranteeing it. The duality of that section is an exact\n",
    "statement about *linear* attention: a semiseparable mixing matrix can\n",
    "be computed as a recurrence or as a masked matmul. A pretrained\n",
    "transformer's *softmax* attention is not in that family, so its weights\n",
    "are not a recurrence in disguise — but its projections and per-layer\n",
    "mixing patterns are close enough to serve as a *warm start*:\n",
    "initialize the student's recurrence from the attention projections and\n",
    "learn the rest. MOHAWK distills in\n",
    "three stages — match each layer's mixing matrix (the attention pattern\n",
    "against the recurrence's semiseparable approximation of it), then match\n",
    "hidden\n",
    "states, then fine-tune end to end — and turns Phi-1.5 into a\n",
    "Mamba-architecture model using about 3B tokens, under one percent of a\n",
    "from-scratch pretraining budget, with quality above same-size\n",
    "from-scratch Mamba models [@Bick.Li.Xing.ea.2024]. \"The Mamba in\n",
    "the Llama\" initializes the recurrence directly from the attention\n",
    "projections and converts Llama-3 into a hybrid, keeping a fraction of\n",
    "attention layers intact; quality falls smoothly as attention is\n",
    "removed, the shipped configuration keeps about a quarter, and the\n",
    "distilled hybrid still solves needle-in-a-haystack at twenty times its\n",
    "training length — while the zero-attention variant does not\n",
    "[@Wang.Paliotta.May.ea.2024]. Both are learned approximations,\n",
    "not exact conversions: the duality supplies the initialization and the\n",
    "layer-wise matching targets, and the distillation data supplies\n",
    "whatever softmax attention computed that a linear recurrence cannot.\n",
    "The retained attention layers are\n",
    "where the recall lives, which by this point in the section is\n",
    "not a surprise; it is the design rule, observed a third way.\n",
    "\n",
    "### The Chapter in One Table\n",
    "\n",
    "The chapter's architectures differ in what they compute; what they\n",
    "*charge* lines up in one table. Each row prices one layer of one\n",
    "architecture on the axes this section has been trading against each\n",
    "other: work and persistent state when decoding token $t$, work and\n",
    "sequential depth when training on a length-$T$ sequence, and whether\n",
    "the training-time parallel form computes the same function as the\n",
    "step-by-step form in real arithmetic (floating-point reassociation\n",
    "still changes rounding, which that section measured).\n",
    "Every \"constant cost\", \"linear time\", or \"same computation\" claim made\n",
    "along the way resolves to a cell here, and each row cites the section\n",
    "that established it.\n",
    "\n",
    "<!-- tbl-caption:Per-layer contracts of the chapter's architectures. $d$ = model width, $h$ = heads of dimension $d_k = d_v$, $N$ = SSM state width per channel, $C$ = chunk length, $t$ = decode position, $T$ = training sequence length. Work entries are leading-order; MLP, normalization, and projection costs shared by all rows are omitted. \"Exact\" means the parallel and sequential forms coincide in real arithmetic. -->\n",
    "\n",
    "| architecture | decode work per token | persistent decode state | training work | sequential depth | parallel form exact? |\n",
    "|:--|:--|:--|:--|:--|:--|\n",
    "| LSTM / GRU (that section) | $O(d^2)$ | $O(d)$: $\\mathbf{h}_t$ (and $\\mathbf{c}_t$) | $O(T d^2)$ | $T$ | none: nonlinearity inside the recurrence (minGRU removes it, that section) |\n",
    "| diagonal SSM, S4D (that section) | $O(d N)$ | $d N$ numbers | $O(T d N)$ work-efficient scan, or $O(T \\log T\\, d)$ FFT convolution (that section) | $O(\\log T)$ (that section) | yes |\n",
    "| Mamba-1 (that section) | $O(d N)$ | $d_\\textrm{inner} N$ numbers | $O(T d N)$ work-efficient scan | $O(\\log T)$ | yes: selective steps are still affine |\n",
    "| SSD / Mamba-2 (that section) | $O(h\\, d_k d_v)$ | $h\\, d_k d_v$ numbers | $O(T C d)$ chunked matmuls (that section) | $T/C$ | yes, verified to float rounding |\n",
    "| GLA (that section) | $O(h\\, d_k d_v)$ | $h\\, d_k d_v$ numbers | $O(T C d)$ chunked | $T/C$ | yes |\n",
    "| DeltaNet (that section) | $O(h\\, d_k d_v)$ | $h\\, d_k d_v$ numbers | $O(T C d)$ chunked WY | $T/C$ | yes: the WY form is exact algebra |\n",
    "| softmax attention (that section, that section) | $O(t\\, d)$ — grows | $2 t d$ numbers — grows (the equation) | $O(T^2 d)$ | $O(1)$ | trivially: the parallel form is the definition |\n",
    "| 1-in-4 hybrid (this section) | $\\tfrac{3}{4} O(h\\, d_k d_v) + \\tfrac{1}{4} O(t\\, d)$ | constant $+\\ \\tfrac14$ of the cache | mixed | per component | per component |\n",
    "\n",
    "Read across the attention row and the SSD row and the whole section\n",
    "reappears: attention pays $t$-dependent work and state for exact recall;\n",
    "the matrix-state family pays a constant for a bounded memory; the\n",
    "hybrid row is a convex combination with the attention fraction as the\n",
    "mixing weight. Read down the exactness column for the chapter's other\n",
    "running theme: every linear-recurrence training trick — scan, chunk,\n",
    "dual, WY — is a reassociation of the same arithmetic, not an\n",
    "approximation, which is what made their speed free of modeling cost.\n",
    "\n",
    "So: where does this leave the fixed state? This chapter gave it five\n",
    "upgrades, and this section drew its boundary. The fixed state lost the\n",
    "exact-recall fight — by a counting bound under its stated assumptions,\n",
    "and by a collapse\n",
    "measurable in an afternoon at width 32 — and it won the economics, not\n",
    "narrowly: flat kilobytes against gigabytes that grow with every\n",
    "token of context. Production stopped treating those as competing claims\n",
    "and shipped both, in proportions this section measured from three\n",
    "independent directions — ablation sweeps, shipped configurations, and\n",
    "distillation experiments, all pointing at a small attention minority\n",
    "carrying retrieval through a cheap recurrent majority. What this\n",
    "section did *not* cover is the systems story that makes the recurrent\n",
    "majority fast in practice — the chunked forms of\n",
    "that section living as fused kernels, which belongs to\n",
    "that section; and the pretraining and post-training of\n",
    "full-scale language models, hybrid or not, together with the serving\n",
    "stacks that exploit their mostly flat memory bill, which are the subject\n",
    "of the Language Models part. The pendulum question from this chapter's\n",
    "introduction — whether attention remains on top on January 1, 2027 —\n",
    "stays open. But notice what would settle it: not a better gate or a\n",
    "cleverer write rule, both of which this chapter taught, but whether a\n",
    "learned, compressed memory can be trusted with retrieval. That is the\n",
    "measured question, and you now own every tool it is measured with.\n",
    "\n",
    "## Summary\n",
    "\n",
    "A fixed-size state cannot perform unbounded exact recall: reproducing\n",
    "$k$ tokens from a vocabulary of $V$ requires $k \\log_2 V$ bits in the\n",
    "state, and a finite-state model's error on copying uniformly random\n",
    "length-$L$ strings is at least\n",
    "$1 - |\\mathcal{S}|/D^L$; the failure is measurable as fuzzy recall\n",
    "on phone-book and needle tasks long before it shows in perplexity. The\n",
    "economics run the other way: by the equation only\n",
    "attention layers pay a context-proportional cache, so a hybrid's\n",
    "persistent decode state\n",
    "is the attention fraction times the transformer's — Jamba's\n",
    "measured 4 GB against Mixtral's 32 GB at 256K. Our three matched stacks\n",
    "(parameter counts printed, spread under one percent)\n",
    "made both claims concrete: the pure scalar-gated stack's recall\n",
    "collapsed\n",
    "once the load crossed roughly its $8 \\times 8$-per-head state size, one\n",
    "mid-stack attention layer restored recall at the loads\n",
    "that broke it (1.000 throughout in our PyTorch run; 0.99–1.00 at the\n",
    "post-collapse loads in JAX, with a mid-sweep dip to roughly 0.92–0.94),\n",
    "language-modeling loss barely separated the three stacks (the\n",
    "pure-linear model matched or beat pure attention in our\n",
    "runs), and the persistent decode state grew\n",
    "with slope equal to the attention fraction. The shipped design rules:\n",
    "attention fractions cluster at 5–25%, with a measured knee near 1:3 for\n",
    "the DeltaNet family and near 8% for Mamba-2 hybrids; placement is even\n",
    "and, in every report so far, not front; parallel fusion and weight\n",
    "sharing are live\n",
    "refinements; and the components interact (Jamba chose Mamba-1 *because*\n",
    "attention was present). Pretrained transformers distill into hybrids\n",
    "for under a percent of the original token budget — a learned\n",
    "approximation the duality warm-starts, with the retained\n",
    "attention layers carrying recall. the table collects the\n",
    "per-layer cost and state contracts of every architecture in the\n",
    "chapter. Three implementation lessons from the\n",
    "experiment: initialize decay gates to retain, mask in log space before\n",
    "exponentiating a decay kernel, and normalize the memory read-out\n",
    "before it joins the residual stream.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. *Placement, self-discovered.* [extended] Rerun the recall sweep\n",
    "   with the\n",
    "   attention layer first (`'AGGG'`) and last (`'GGGA'`) instead of\n",
    "   mid-stack. Then probe length generalization — carefully, because\n",
    "   `RecallModel`'s learned position table is a confound: it is built\n",
    "   with `max_len = 2 * num_pairs`, so a longer evaluation sequence\n",
    "   would index past it (the guard in `forward` stops you), and even a\n",
    "   longer table leaves the extra rows untrained at evaluation time.\n",
    "   Remove the confound by dropping absolute positions: adapt\n",
    "   `train_recall` to build its models with `pos=False` — the recall\n",
    "   task is content-addressed, so none of the three mixers needs the\n",
    "   position table; verify this first by reproducing the sweep's\n",
    "   accuracy at `num_pairs=32`. Then extend `make_recall` to insert\n",
    "   filler tokens between the write and query phases (reserve one extra\n",
    "   key index for the filler and pass `num_keys=65`), train at zero\n",
    "   padding, and evaluate the same models on sequences padded by 32.\n",
    "   Which placement degrades, and does your\n",
    "   result match Samba's report that a single *front* attention layer\n",
    "   breaks length extrapolation [@Ren.Liu.Lu.ea.2024]?\n",
    "1. *Price a million tokens.* [conceptual] Using\n",
    "   the equation, compute\n",
    "   the persistent decode state at a 1M-token context, batch of one,\n",
    "   16-bit,\n",
    "   for three 48-layer models with $n_\\textrm{kv} = 8$ and\n",
    "   $d_\\textrm{head} = 128$: a pure transformer, a pure recurrent stack\n",
    "   whose per-layer state matches Mamba-2 at $d_\\textrm{model} = 4096$\n",
    "   (expansion two, $d_\\textrm{state} = 128$: $2 \\cdot 4096 \\cdot 128$\n",
    "   elements per the equation, ignoring the small\n",
    "   convolution buffer), and\n",
    "   a 12.5%\n",
    "   hybrid. How many concurrent 1M-token users fit in 80 GB of spare\n",
    "   HBM under each design? Compare your hybrid figure against Jamba's\n",
    "   published 4 GB at 256K.\n",
    "1. *The ratio axis.* [short-code] Sweep the attention fraction at\n",
    "   fixed depth:\n",
    "   layouts `'GGGG'`, `'GGAG'`, `'GAGA'`, `'AAAA'`. Plot recall at\n",
    "   `num_pairs=64` and decode memory at 64K context (from the\n",
    "   memory-panel cell) against the fraction. Where is the knee at this\n",
    "   scale, and how does it compare with Kimi Linear's reported 3:1\n",
    "   [@Kimi.Team.2025b]?\n",
    "1. *A window instead.* [extended] Replace the hybrid's full-attention\n",
    "   mixer with\n",
    "   sliding-window attention of window 16 (mask scores outside the\n",
    "   window before the softmax). At which loads does the windowed hybrid\n",
    "   match the full one, and where does it break? Explain both regimes:\n",
    "   at what load does every query's answer still sit within the window,\n",
    "   and what does this say about Samba's window-only design\n",
    "   [@Ren.Liu.Lu.ea.2024]?\n",
    "1. *Bit accounting.* [conceptual] The linear stack's total state is\n",
    "   $4$ layers\n",
    "   $\\times\\, 4$ heads $\\times\\, 8 \\times 8$ floats. Estimate its\n",
    "   capacity in bindings via the crowding heuristic of\n",
    "   that section (interference $(n-1)/d_k$ per head\n",
    "   against unit signal) and via raw bits ($k \\log_2 V$ at $V = 32$\n",
    "   values against one float carrying, say, 8 useful bits). Where do\n",
    "   the two accounts place the cliff, and where did the measured sweep\n",
    "   put it?\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-pytorch",
   "display_name": "d2l (PyTorch)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
