3 Model Architecture 9 / 9
  1. In this chapter
  2. From RNNs to Attention
  3. Attention Basics
  4. Positional Encoding Explained
  5. Transformer Block Explained
  6. Modern LLM Architecture
  7. Efficient Attention
  8. Mixture of Experts (MoE)
  9. Long Context
  10. State Space Models and Hybrids
All chapters →

Chapter 3 · Model Architecture 3.9

State Space Models and Hybrids: Trading the KV Cache for a Fixed-Size State

Linear attention, state space models (Mamba) and the gated delta rule compress history into a fixed-size state: memory stays flat as context grows, but capacity is limited by the state size. Hybrids keep a few attention layers for exact recall; Jamba's KV cache is 1/8 of Mixtral's.

Advanced 47 min read Updated Companion code ↓

After this page you will be able to

  • Write linear attention, decay, state space models (SSMs), Mamba's selectivity and the delta rule in one state-update template, and say which term each one changes.
  • Explain why the recurrent form, the convolutional form and the parallel scan compute the same result, and which one training and inference each use.
  • Explain why a fixed-size state has limited capacity (about its dimension), and how additive writes, decay and the delta rule differ at overwriting old values.
  • Estimate the cache of a hybrid model at different context lengths from layer counts and per-layer state sizes, and explain why a few attention layers are kept.
  • Decide whether a workload suits an SSM or a hybrid: what it is good at, and why it still falls behind on copying, retrieval and in-context learning.
On this page
  1. Why replace the KV cache
  2. One recurrence, several ways to write it
  3. Experiment 1: parallel for training, recurrent for inference
  4. Experiment 2: how much can a fixed-size state remember
  5. Mamba and Mamba-2: making forgetting depend on content
  6. Hybrid architectures: keep only a few attention layers
  7. Experiment 3: the cache ledger for hybrids
  8. When to use them, and when not to
  9. Summary and exercises
  10. Quick self-check
  11. Further reading
  12. FAQ

State space models (SSMs), linear attention and the gated delta rule are one family: they keep a fixed-size state matrix as memory, update it once per token, and read the answer out of it. That is why their inference cost does not grow with context, whereas the KV cache of attention grows by one entry per token; the price is limited capacity, so when the state is full the model has to forget. Hybrid architectures (Jamba, Nemotron-H, Qwen3-Next) keep only a few attention layers and use such recurrent layers for the rest, trading cache size against exact recall. This page measures three things with experiments that run on a CPU: why these formulations compute the same result, how much a fixed-size state can remember, and how much cache a hybrid saves.

Why replace the KV cache

During autoregressive generation, attention reads the keys and values of all earlier tokens for every new token. They must stay in GPU memory; this is the KV cache, and its size is proportional to context length. For Llama-2-7B (32 layers, 32 KV heads, head dimension 128, bf16) each token needs 32×2×32×128×2=524,28832\times 2\times 32\times 128\times 2=524{,}288 bytes, that is 0.5 MiB (layers, K and V, KV heads, head dimension, 2 bytes per number). An 8K context takes 4 GiB and 256K takes 128 GiB; Experiment 3 checks these. Grouped-query attention (GQA) cuts the KV heads to 8 and the cache to a quarter, but it still grows linearly: counted at 256K context, Mistral-7B still needs 32 GiB, and every concurrent sequence needs its own copy.

Could the model keep a fixed-size state instead of every token? The previous page showed that this is exactly what RNNs do, and that they lose on training because it is sequential. The thread of this page is: linear attention, state space models and the delta rule rewrite “fixed state plus one update per step” into forms that train in parallel, so they get the inference cost of an RNN together with training efficiency close to a Transformer. The two kinds of memory side by side:

Attention (KV cache)Fixed-size state
What is storedKeys and values of every token, verbatimThe history compressed into a fixed-size matrix
MemoryGrows linearly with length nnIndependent of nn
Cost of a read per stepProportional to nnIndependent of nn
Exact recallYes, every token is still thereNo, it is lossy compression
Parallelism in trainingParallel along the sequence by defaultNeeds dedicated parallel algorithms (Experiment 1)

The cost sits in the last two rows. The Mamba paper states the trade-off plainly: how efficient and how effective a sequence model is depends on how well it compresses its state; efficient models must have a small state, while effective models must have a state that holds everything needed from the context (Gu and Dao, 2023). Experiment 2 turns that sentence into numbers.

One recurrence, several ways to write it

Let qt,kt∈Rdkq_t,k_t\in\mathbb{R}^{d_k} and vt∈Rdvv_t\in\mathbb{R}^{d_v} be the query, key and value of token tt. Linear attention (Katharopoulos et al., 2020) drops the softmax, and the history can then be accumulated into a dk×dvd_k\times d_v state matrix StS_t:

St=St−1+ktvt⊤,ot=St⊤qtS_t = S_{t-1} + k_t v_t^\top,\qquad o_t = S_t^\top q_t

A write is an outer product and a read is one matrix-vector product; both cost the same at every tt. Unrolling the recurrence gives ot=∑i≤t(qt⊤ki) vio_t=\sum_{i\le t}(q_t^\top k_i)\,v_i, which is causal attention without the softmax: linear attention only changes the order of summation. It accumulates kivi⊤k_iv_i^\top first and multiplies by qtq_t afterwards, so it no longer has to keep each kik_i and viv_i.

Almost every later model changes “how to write” and “how to forget” in this template. The table puts them in one notation (the literature does not use a single notation, and the transposition of the state differs):

MethodState updateHow it forgetsSource
Linear attentionSt=St−1+ktvt⊤S_t=S_{t-1}+k_tv_t^\topNeverKatharopoulos et al. 2020
Fixed decaySt=γSt−1+ktvt⊤S_t=\gamma S_{t-1}+k_tv_t^\topBy time, γ\gamma is a constantRetNet
Input-dependent decaySt=atSt−1+ktvt⊤S_t=a_tS_{t-1}+k_tv_t^\topBy content, ata_t computed from the current tokenMamba-2, GLA
Time-invariant SSMht=Aht−1+Bxth_t=Ah_{t-1}+Bx_t, yt=Chty_t=Ch_tAA is fixedS4
Selective SSMSame, but At,Bt,CtA_t,B_t,C_t computed from xtx_tBy contentMamba
Delta ruleSt=(I−βtktkt⊤)St−1+βtktvt⊤S_t=(I-\beta_tk_tk_t^\top)S_{t-1}+\beta_tk_tv_t^\topOnly rewrites the old value under the same keyDeltaNet
Gated delta ruleSt=αt(I−βtktkt⊤)St−1+βtktvt⊤S_t=\alpha_t(I-\beta_tk_tk_t^\top)S_{t-1}+\beta_tk_tv_t^\topDecay first, then rewriteGated DeltaNet, Qwen3-Next

A few remarks:

  • A decay at∈(0,1)a_t\in(0,1) fades old information proportionally. In Mamba-2, ata_t is one scalar per head; the decay of GLA is a vector with one entry per key dimension (Yang et al., 2023); RetNet’s decay is a constant.
  • Mamba uses different symbols (state hth_t, input xtx_t, matrices At,Bt,CtA_t,B_t,C_t computed from xtx_t), but its recurrence has the same shape ht=Atht−1+Btxth_t=A_th_{t-1}+B_tx_t; Mamba-2 restricts AtA_t to a scalar times the identity, which makes it the third row of the table (Dao and Gu, 2024).
  • In the delta rule, βt∈(0,1)\beta_t\in(0,1) is the write strength. The Qwen3NextGatedDeltaNet implementation in Hugging Face transformers 5.3.0 applies an L2 normalization to qtq_t and ktk_t before the gated delta update.

The delta rule is online learning. Treat SS as the weights of a linear model that predicts the value from the key: v^=S⊤k\hat v=S^\top k. One gradient step with learning rate β\beta on the loss 12∥S⊤k−v∥2\tfrac12\lVert S^\top k-v\rVert^2 gives S←S+β k (v−S⊤k)⊤S\leftarrow S+\beta\,k\,(v-S^\top k)^\top, which is the delta rule; the additive rule is a Hebbian write that ignores how much is already remembered. The memory is then a small model that keeps being trained while the sequence is read. Schlag et al. (2021) showed that linear attention is equivalent to a fast weight programmer and used the delta rule so that the model can correct the current mapping from keys to values; the Gated DeltaNet paper puts these update rules into one online-learning framework (Yang et al., 2024).

Experiment 1: parallel for training, recurrent for inference

These models are usable because the same computation has two equivalent forms: the recurrent form updates a state at every step, is used at inference and has fixed memory and per-step cost; the parallel form writes the whole sequence as matrix operations, is used in training and keeps GPUs busy. The code below checks six equivalences with NumPy on random data: T=16T=16 steps, dk=4d_k=4, dv=3d_v=3, SSM state size N=5N=5, and each check prints the largest absolute difference between the two forms. Environment: Apple M2 Max, Python 3.14.3, NumPy 2.4.2; small matrices on a CPU, each check takes under a second.

import numpy as np

rng = np.random.default_rng(0)
T, DK, DV, N = 16, 4, 3, 5      # steps, key size, value size, SSM state size
Q, K, V = (rng.normal(size=(T, d)) for d in (DK, DK, DV))
MASK = np.tril(np.ones((T, T)))  # causal mask


def err(a, b):
    return np.abs(np.asarray(a) - np.asarray(b)).max()

Q, K, V are random queries, keys and values, and MASK is the causal mask.

1. Linear attention. The parallel form is the masked score matrix (M⊙QK⊤)V(M\odot QK^\top)V (MM is the lower-triangular causal mask); the recurrent form is a running state SS.

# 1. linear attention: masked scores (parallel) vs a running state S
parallel = (MASK * (Q @ K.T)) @ V
S, rec = np.zeros((DK, DV)), []
for t in range(T):
    S = S + np.outer(K[t], V[t])            # write: S += k v^T
    rec.append(S.T @ Q[t])                  # read:  o = S^T q
print(f"linear attention, parallel vs recurrent   {err(parallel, rec):.1e}")
linear attention, parallel vs recurrent   5.3e-15

2. Adding decay. One scalar ata_t per step turns the mask into Lt,s=as+1as+2⋯atL_{t,s}=a_{s+1}a_{s+2}\cdots a_t (s≤ts\le t): what was written at position ss has been decayed by every aa between s+1s+1 and tt by the time it is read at position tt. This LL is a lower-triangular “1-semiseparable” matrix, and the Mamba-2 paper uses it to build the duality between SSMs and attention with a structured mask. The code computes LL from cumulative sums of logarithms, which avoids underflow of long products.

# 2. a scalar decay a_t per step: the mask becomes L[t,s] = a_{s+1}...a_t
a = rng.uniform(0.5, 1.0, size=T)
cum = np.cumsum(np.log(a))
L = np.tril(np.exp(cum[:, None] - cum[None, :]))
parallel = (L * (Q @ K.T)) @ V
S, rec = np.zeros((DK, DV)), []
for t in range(T):
    S = a[t] * S + np.outer(K[t], V[t])
    rec.append(S.T @ Q[t])
print(f"decay and mask, parallel vs recurrent     {err(parallel, rec):.1e}")
decay and mask, parallel vs recurrent     1.8e-15

3. Time-invariant SSM. State equation ht=Aht−1+Bxth_t=Ah_{t-1}+Bx_t and output yt=Chty_t=Ch_t, where A,B,CA,B,C do not depend on the input. Unrolling gives yt=∑j≥0CAjB xt−jy_t=\sum_{j\ge0}CA^jB\,x_{t-j}: the output is the input convolved with the kernel CAjBCA^jB. S4 exploits exactly this, training with a convolution and running inference as a recurrence (Gu et al., 2021).

# 3. time-invariant SSM: recurrence vs convolution with kernel C A^j B
A = np.diag(rng.uniform(0.3, 0.95, size=N))
B, C = rng.normal(size=N), rng.normal(size=N)
x = rng.normal(size=T)
h, y_rec = np.zeros(N), []
for t in range(T):
    h = A @ h + B * x[t]
    y_rec.append(C @ h)
kern = [C @ np.linalg.matrix_power(A, j) @ B for j in range(T)]
y_conv = [np.dot(kern[: t + 1][::-1], x[: t + 1]) for t in range(T)]
print(f"time-invariant SSM, recurrence vs conv    {err(y_rec, y_conv):.1e}")
time-invariant SSM, recurrence vs conv    6.7e-16

4. Selective SSM. Once at,bta_t,b_t depend on the input, the system is no longer time-invariant, there is no fixed kernel, and the convolutional form of the previous item breaks. But the recurrence ht=at⊙ht−1+bth_t=a_t\odot h_{t-1}+b_t is still linear, and “apply step one (a1,b1)(a_1,b_1), then step two (a2,b2)(a_2,b_2)” merges into an operation of the same kind:

(a2,b2)∘(a1,b1)=(a1a2,  a2b1+b2)(a_2,b_2)\circ(a_1,b_1)=(a_1a_2,\;a_2b_1+b_2)

This operation is associative, so a parallel scan applies: merge neighbouring segments in pairs, and TT steps need about log⁡2T\log_2T rounds (4 rounds for 16 steps in the code). Mamba uses this kind of scan, together with a fused kernel that keeps the state only in on-chip SRAM and with recomputation of intermediate states in the backward pass (Gu and Dao, 2023). The code below is the simplest version, Hillis-Steele, with O(Tlog⁡T)O(T\log T) total work; the paper cites the Blelloch-style scan whose work is O(T)O(T).

# 4. selective SSM (a_t, b_t depend on the input): loop vs parallel scan
At = rng.uniform(0.3, 0.99, size=(T, N))
Bt = rng.normal(size=(T, N)) * x[:, None]
h, seq = np.zeros(N), []
for t in range(T):
    h = At[t] * h + Bt[t]
    seq.append(h)
pa, pb, step, rounds = At.copy(), Bt.copy(), 1, 0
while step < T:                             # Hillis-Steele scan on (a, b)
    na, nb = pa.copy(), pb.copy()
    na[step:] = pa[step:] * pa[:-step]
    nb[step:] = pa[step:] * pb[:-step] + pb[step:]
    pa, pb, step, rounds = na, nb, step * 2, rounds + 1
print(f"selective SSM, loop vs parallel scan      {err(seq, pb):.1e}"
      f"  ({rounds} rounds for {T} steps)")
selective SSM, loop vs parallel scan      4.4e-16  (4 rounds for 16 steps)

5. The delta rule. Writing the same key again replaces the old value. Write v0v_0 into an empty state and then v1v_1 with the delta rule (β=1\beta=1, kk a unit vector): reading S⊤kS^\top k differs from v1v_1 by less than 1e-15, so what comes back is exactly the new value; the additive rule reads out v0+v1v_0+v_1, which differs from v1v_1 by 1.04, the largest component of v0v_0.

# 5. delta rule: a write under the same key replaces the old value
k = K[0] / np.linalg.norm(K[0])
S = np.outer(k, V[0])                       # write v0 into an empty state
S = S + np.outer(k, V[1] - S.T @ k)         # delta write of v1, beta = 1
print(f"delta rule, read after v0 then v1: error  {err(S.T @ k, V[1]):.1e}")
S = np.outer(k, V[0]) + np.outer(k, V[1])   # additive: both pile up
print(f"additive,   read after v0 then v1: error  {err(S.T @ k, V[1]):.2f}")
delta rule, read after v0 then v1: error  8.9e-16
additive,   read after v0 then v1: error  1.04

6. The gated delta rule. St=αt(I−βtktkt⊤)St−1+βtktvt⊤S_t=\alpha_t(I-\beta_tk_tk_t^\top)S_{t-1}+\beta_tk_tv_t^\top has two ways to be written: decay first, then read, correct and write back with the delta rule (the order of the recurrent implementation of Qwen3-Next in Hugging Face), or fold αt(I−βtktkt⊤)\alpha_t(I-\beta_tk_tk_t^\top) into one transition matrix and multiply.

# 6. gated delta rule: read-modify-write vs one transition matrix
g, beta = rng.uniform(0.8, 1.0, size=T), rng.uniform(0.2, 1.0, size=T)
Kn = K / np.linalg.norm(K, axis=1, keepdims=True)
S1, S2 = np.zeros((DK, DV)), np.zeros((DK, DV))
for t in range(T):
    S1 = g[t] * S1                                          # forget
    S1 = S1 + beta[t] * np.outer(Kn[t], V[t] - S1.T @ Kn[t])  # delta write
    M = g[t] * (np.eye(DK) - beta[t] * np.outer(Kn[t], Kn[t]))
    S2 = M @ S2 + beta[t] * np.outer(Kn[t], V[t])
print(f"gated delta rule, two forms               {err(S1, S2):.1e}")
gated delta rule, two forms               3.3e-16

Both write the same state. The second form is the starting point of the chunkwise parallel training algorithm: a product of such transition matrices has a compact representation, which the parallel-DeltaNet work writes as a product of Householder matrices (Yang et al., 2024).

How to read these numbers:

  • The largest of the six errors is 5.3e-15 and the smallest is 3.3e-16, all at the level of double-precision rounding, so these formulations are not approximations but the same function. The last digits vary a little with the NumPy and BLAS versions.
  • This is why these models get both benefits: recurrence at inference with a fixed cost per step, and a parallel or chunkwise form in training. Real training kernels sit between the two, with matrix multiplications inside a chunk and a recurrence that passes the state between chunks; the chunkwise algorithms of RetNet, GLA and Mamba-2 follow this idea.
  • The first three items also expose a limit: the convolutional form requires a fixed kernel, so a time-invariant SSM cannot look at content; removing the limit takes the scan of item 4, at the price of losing the FFT shortcut.

Experiment 2: how much can a fixed-size state remember

The equivalences answer “how to compute”; the next question is “how much is remembered”. Write nn (key, value) pairs one after another into a fixed-size state (take dk=dv=dd_k=d_v=d), then read the values back with the keys.

With the additive rule the read-out is v^i=S⊤ki=vi+∑j≠i(ki⊤kj) vj\hat v_i=S^\top k_i=v_i+\sum_{j\ne i}(k_i^\top k_j)\,v_j: besides the value we want, the other n−1n-1 values leak in, weighted by the inner products between keys. For random unit keys the mean of the squared inner product is 1/d1/d, so the noise energy is about (n−1)/d(n-1)/d and the cosine between the read-out and the truth is about

cos⁡≈11+(n−1)/d\cos\approx\frac{1}{\sqrt{1+(n-1)/d}}

When nn is much smaller than dd the noise is small; when nn and dd are of the same order the read-out is drowned by the other values. If the keys are orthonormal (at most dd of them) the cross terms vanish, and the additive rule stores exactly dd pairs; this is what “the capacity of a fixed-size state is about its dimension” means. Schlag et al. (2021) and the Gated DeltaNet paper both point out this bound: beyond it “memory collisions” become inevitable and exact retrieval suffers.

Design: keys are random unit vectors (orthonormal keys are tested separately); values are drawn from a codebook of 256 candidates, like a vocabulary; after a read, the nearest codebook entry by cosine is taken, and a pair counts as remembered only if that entry is right. Four ways of storing and reading are compared: additive; the delta rule (β=1\beta=1, each key written once); softmax attention, which keeps all nn pairs and reads with a softmax of inverse temperature 40 (my choice, standing for a well-trained, sharp attention); and the additive rule with orthonormal keys, the ideal case. Each cell is the mean of 200 random draws.

import numpy as np

CODE, TRIALS = 256, 200     # 256 candidate values; trials per setting


def unit(x):
    return x / np.linalg.norm(x, axis=-1, keepdims=True)


def make(rng, d, n, orthonormal=False):
    """n keys, n values drawn from a codebook, and the codebook itself."""
    if orthonormal:
        k = np.linalg.qr(rng.normal(size=(d, d)))[0][:n]
    else:
        k = unit(rng.normal(size=(n, d)))
    code = unit(rng.normal(size=(CODE, d)))
    ids = rng.integers(CODE, size=n)
    return k, code[ids], code, ids


def additive(k, v):
    return k.T @ v                           # S = sum of k_i v_i^T


def delta(k, v):
    S = np.zeros((k.shape[1], v.shape[1]))
    for ki, vi in zip(k, v):
        S += np.outer(ki, vi - S.T @ ki)     # replace what is under ki
    return S


def nearest(r, code):
    return (unit(r) @ code.T).argmax(1)


def cell(x, width=8):
    if x is None:
        return f"{'-':>{width}s}"
    return f"{x:{width}d}" if isinstance(x, int) else f"{x:{width}.3f}"
def recall(d, n, seed):
    rng = np.random.default_rng(seed)
    names = ("additive", "delta", "softmax", "orthonormal")
    acc, cos = {m: [] for m in names}, []
    for _ in range(TRIALS):
        k, v, code, ids = make(rng, d, n)
        S = additive(k, v)
        cos.append((unit(k @ S) * v).sum(1).mean())
        acc["additive"].append((nearest(k @ S, code) == ids).mean())
        acc["delta"].append((nearest(k @ delta(k, v), code) == ids).mean())
        w = np.exp(40 * (k @ k.T))           # softmax over the whole cache
        w /= w.sum(1, keepdims=True)
        acc["softmax"].append((nearest(w @ v, code) == ids).mean())
        if n <= d:                           # n orthonormal keys need n <= d
            k, v, code, ids = make(rng, d, n, orthonormal=True)
            hit = nearest(k @ additive(k, v), code) == ids
            acc["orthonormal"].append(hit.mean())
    return np.mean(cos), {m: np.mean(a) if a else None for m, a in acc.items()}


head = ["d", "n", "n/d", "cos", "pred", "additive", "delta", "softmax"]
print("".join(f"{h:>9s}" for h in head) + f"{'orthonormal':>13s}")
gap = 0.0
for d in (16, 64):
    for n in (d // 4, d // 2, d, 2 * d, 4 * d):
        cos, acc = recall(d, n, 1000 * d + n)
        pred = 1 / np.sqrt(1 + (n - 1) / d)  # predicted cosine, additive
        gap = max(gap, abs(cos - pred))
        row = [d, n, n / d, cos, pred, acc["additive"], acc["delta"],
               acc["softmax"]]
        print("".join(cell(x, 9) for x in row)
              + cell(acc["orthonormal"], 13))
print(f"largest |cos - pred| in the table: {gap:.3f}")
        d        n      n/d      cos     pred additive    delta  softmax  orthonormal
       16        4    0.250    0.920    0.918    0.998    0.968    1.000        1.000
       16        8    0.500    0.840    0.834    0.938    0.867    1.000        1.000
       16       16    1.000    0.724    0.718    0.715    0.593    1.000        1.000
       16       32    2.000    0.586    0.583    0.383    0.305    1.000            -
       16       64    4.000    0.449    0.450    0.167    0.157    1.000            -
       64       16    0.250    0.902    0.900    1.000    1.000    1.000        1.000
       64       32    0.500    0.825    0.821    1.000    0.996    1.000        1.000
       64       64    1.000    0.712    0.710    0.999    0.895    1.000        1.000
       64      128    2.000    0.581    0.579    0.963    0.530    1.000            -
       64      256    4.000    0.448    0.448    0.724    0.262    1.000            -
largest |cos - pred| in the table: 0.006

How to read the table:

  1. The prediction matches. Over the whole table the predicted read-out cosine pred and the measured cos differ by at most 0.006, from the first-order approximation of the formula plus sampling noise.
  2. Exact recall falls as n/dn/d grows. At d=64d=64 the additive rule is almost perfect up to n=dn=d (0.999), reaches 0.963 at n=2dn=2d and 0.724 at n=4dn=4d; at d=16d=16 the decline comes earlier, 0.715 at n=dn=d and only 0.167 at n=4dn=4d. At the same cosine of about 0.58, d=64d=64 recalls 0.963 but d=16d=16 only 0.383: the cosines between the other codebook entries and the read-out spread around 0 with a standard deviation of about 1/d1/\sqrt d, so in a low dimension a wrong entry sometimes comes closer than the right one. A larger codebook has more wrong entries and makes the same cosine less sufficient.
  3. The delta rule is not better here. Each key is written once, and the keys are random and overlap, and every write corrects the difference between the current read-out and the target, so later corrections disturb values that were already written. At d=64d=64, n=2dn=2d its recall is 0.530, below the 0.963 of the additive rule; with orthonormal keys the correction term is always zero, the two rules coincide, and both are exact for n≤dn\le d. The delta rule earns its keep in the next test, not here.
  4. Softmax attention is at 1.000 throughout: it keeps all nn pairs, so capacity does not depend on dd, at the price of a cache that grows linearly with nn.

The noise floor: redo the whole table with three other seeds and look at the largest fluctuation of each column.

# Repeat the recall table with three other seeds; report the largest spread.
spread = {"cos": 0.0, "additive": 0.0, "delta": 0.0, "softmax": 0.0}
for d in (16, 64):
    for n in (d // 4, d // 2, d, 2 * d, 4 * d):
        runs = [recall(d, n, 1000 * d + n + 17 * (r + 1)) for r in range(3)]
        for name in spread:
            vals = [r[0] if name == "cos" else r[1][name] for r in runs]
            spread[name] = max(spread[name], max(vals) - min(vals))
print("largest spread over 3 reruns (max - min): "
      + "  ".join(f"{k} {v:.3f}" for k, v in spread.items()))
largest spread over 3 reruns (max - min): cos 0.004  additive 0.015  delta 0.015  softmax 0.000

So differences below 0.015 are not interpreted; the gaps between the additive and delta rows in the table (for example 0.963 against 0.530 at d=64d=64, n=2dn=2d) are far larger than this noise.

How much a fixed-size state remembers: read-out cosine and exact recall Two panels, both with the ratio n/d of stored pairs to state dimension on a logarithmic horizontal axis from 0.25 to 4. Left, cosine between the read-out and the true value: measured points for d=16 and d=64 sit on the predicted curve, about 0.71 at n/d=1 and 0.45 at n/d=4. Right, exact recall: softmax attention stays at 1.00; the additive state at d=64 falls from 1.00 at n/d=0.25 to 0.72 at n/d=4; the delta rule is lower still under the same single write per key, 0.26 at n/d=4. The d=16 curves fall in the same way, earlier. d=16 measured d=64 measured prediction additive delta rule softmax attention solid: d=64, dashed: d=16 Cosine between read-out and truth 0.25 0.5 1 2 4 0.4 0.6 0.8 1.0 n = d stored pairs n divided by state dimension d Exact recall (nearest codeword is right) 0.25 0.5 1 2 4 0.00 0.25 0.50 0.75 1.00 n = d stored pairs n divided by state dimension d
Data from the recall output above; each point is the mean of 200 random draws and reruns with other seeds move it by at most 0.015. Left: the additive read-out cosine matches the prediction 1/√(1+(n−1)/d). Right: with random keys written once, the delta rule is no better than adding, and softmax attention keeps every pair so it does not depend on n/d.

Overwriting old values. In real sequences the same key is written again and again: a variable is reassigned, an entity’s attribute is updated. The latest value should then be what is read back. The test below has mm live keys, each written 16 times on average with a random value each time, and finally reads the latest value of every key. It compares the additive rule, two fixed decay rates (a factor 0.95 or 0.99 per step) and the delta rule, with d=64d=64.

def store(d, m, per_key, seed):
    """m live keys, each written per_key times on average; read the latest."""
    rng = np.random.default_rng(seed)
    rules = {"additive": 1.0, "decay .95": 0.95, "decay .99": 0.99}
    acc = {name: [] for name in [*rules, "delta"]}
    for _ in range(TRIALS // 2):
        k = unit(rng.normal(size=(m, d)))
        code = unit(rng.normal(size=(CODE, d)))
        keys = rng.integers(m, size=m * per_key)
        ids = rng.integers(CODE, size=m * per_key)
        latest = dict(zip(keys, ids))        # later writes win
        live = np.array(sorted(latest))
        truth = np.array([latest[i] for i in live])
        for name, gamma in rules.items():
            S = np.zeros((d, d))
            for kk, ii in zip(keys, ids):
                S = gamma * S + np.outer(k[kk], code[ii])
            acc[name].append((nearest(k[live] @ S, code) == truth).mean())
        S = np.zeros((d, d))
        for kk, ii in zip(keys, ids):
            S += np.outer(k[kk], code[ii] - S.T @ k[kk])
        acc["delta"].append((nearest(k[live] @ S, code) == truth).mean())
    return {name: np.mean(a) for name, a in acc.items()}


print("".join(f"{h:>10s}" for h in ["keys", "writes", "additive",
                                    "decay .95", "decay .99", "delta"]))
for m in (8, 16, 32, 64):
    res = store(64, m, 16, 7000 + m)
    print(cell(m, 10) + cell(m * 16, 10) + "".join(cell(x, 10)
                                                    for x in res.values()))
      keys    writes  additive decay .95 decay .99     delta
         8       128     0.064     0.810     0.264     1.000
        16       256     0.067     0.814     0.482     1.000
        32       512     0.071     0.641     0.653     0.988
        64      1024     0.052     0.412     0.645     0.820
  • Additive: 0.052 to 0.071, about one in sixteen. Every key was written about 16 times, so the read-out is a superposition of 16 values and the latest is only one share of it.
  • A fixed decay helps, but the right rate depends on how fast writes arrive. With 8 keys a decay of 0.95 gives 0.810 and 0.99 only 0.264, because the old values have not faded; with 64 keys it reverses, 0.95 drops to 0.412 because it fades too fast and keys that were not rewritten recently are drowned out, and 0.99 reaches 0.645. A decay forgets by time and cannot know what should be kept.
  • The delta rule forgets by content: a write first reads what is under that key and then replaces it. It scores 1.000 for 8 and 16 keys, 0.988 for 32 keys, and 0.820 when the number of live keys reaches dd (64); with random, non-orthogonal keys the capacity is somewhat below dd.
  • This explains why Gated DeltaNet combines the two: the gate erases globally when needed, and the delta rule updates one association precisely. Its paper calls the two mechanisms complementary: gating enables rapid memory erasure while the delta rule facilitates targeted updates.

The limits need to be stated: the keys are random and not learned; in real models keys and values are learned, βt\beta_t and αt\alpha_t depend on the input, and there are many heads and many layers; here β\beta is fixed at 1 and there is no learned gate. So these numbers show mechanisms and do not predict which model is better.

The widget below turns experiment 2 into something you can run yourself: pick the state size and the write rule, rerun the Monte Carlo, and watch the readout cosine hug the prediction 1/√(1+(n−1)/d) on its way down, the exact recall collapse once n passes the capacity — and why softmax attention stays at exactly 1.

Mamba and Mamba-2: making forgetting depend on content

The problem with a fixed decay in Experiment 2 is that one rate cannot suit every content and every write speed. Mamba (Gu and Dao, 2023) answers with selectivity: the parameters Δ,B,C\Delta,B,C that decide “what to write and how much to forget” are computed from the current token. The paper uses two synthetic tasks to show the weakness of time-invariant models: Selective Copying, which asks the model to remember a few tokens at varying positions and filter out the rest, and Induction Heads, which asks it to retrieve an answer from context. A time-invariant model has fixed dynamics and cannot pick information by content; a global convolution can solve the vanilla copying task (it only needs time-awareness) but has difficulty with Selective Copying, because the spacing between inputs and outputs varies and a static kernel cannot model it.

Selectivity breaks the convolutional form (item 4 of Experiment 1), so Mamba does three pieces of engineering: a fused kernel that keeps the state only in on-chip SRAM, a parallel scan, and recomputation of intermediate states in the backward pass. Mamba-2 (Dao and Gu, 2024) goes one step further: it restricts AtA_t to a scalar times the identity (the shape of item 2 of Experiment 1), which gives a matrix-multiplication form that can use tensor cores. In the paper’s own words, this slightly decreases expressive power in return for significant training efficiency. The three generations side by side:

ModelTreatment of A,B,CA,B,CHow it is computedResult reported in the paper
S4 (2021)Fixed; AA is a structured matrix with a low-rank correctionConvolution for training, recurrence for inferenceState of the art on every Long Range Arena task at the time, generation about 60 times faster than Transformers
Mamba (2023)Computed from the current input (selective)Parallel scan in a fused kernelInference throughput 4 to 5 times that of a Transformer of similar size
Mamba-2 (2024)Selective, with AtA_t a scalar times the identityChunked matrix multiplications (SSD)Core layer 2 to 8 times faster than Mamba’s scan, states more than 8 times larger

The numbers in the table are reported by the respective papers under their own measurement setups; they are not reproduced on this page.

Hybrid architectures: keep only a few attention layers

The conclusion of Experiment 2 is that a fixed state cannot store verbatim, so on tasks that need exact copying, exact retrieval and in-context learning a pure SSM has a structural weakness. Several independent studies agree:

  • Zoology (Arora et al., 2023): attention-free gated-convolution models trail attention models by up to 2.1 perplexity points, and 82% of the gap comes from recalling what was mentioned earlier in the context (associative recall); a 70M-parameter attention model beats a 1.4B-parameter gated-convolution model on associative recall.
  • Jelassi et al. (2024): they prove that a two-layer Transformer can copy strings of exponential length while a fixed-size state is fundamentally limited, and on pretrained large models Transformers clearly beat SSMs at copying and retrieval.
  • Waleffe et al. (2024): at 8B parameters and the same data (up to 3.5T tokens), pure Mamba and Mamba-2 match or exceed Transformers on many tasks but fall behind on tasks that need strong copying or in-context learning (5-shot MMLU, Phonebook) and on long-context reasoning; a hybrid with 43% Mamba-2, 7% attention and 50% MLP layers beats the 8B Transformer on all 12 standard tasks, by 2.65 points on average, and is predicted to generate up to 8 times faster.
  • The Jamba ablations (1.3B parameters, 250B tokens): in few-shot classification on IMDB, pure Mamba often does not answer in the format of the examples (“Very Good”, “3/10”), while the hybrid follows the format like a Transformer, even with only 1 attention layer in every 8. An attention-to-Mamba ratio of 1:3 or 1:7 made virtually no difference in performance, so the more compute-efficient 1:7 was chosen.

So the hybrid design follows naturally: most layers use a fixed state for cheap mixing and compression, and a few attention layers recall verbatim. Public hybrids make different choices:

ModelLayer compositionShare of attention layers
Jamba-v0.1 (AI21, 2024)4 blocks of 8 layers: 1 attention and 7 Mamba; every second MLP is a 16-expert top-2 MoE4/32 = 12.5%
Nemotron-H-8B (NVIDIA, 2025)52 layers: 24 Mamba-2, 24 MLP, 4 attention4/52 = 7.7%
Qwen3-Next-80B-A3B (Alibaba, 2025)48 layers: in every 4 layers, 3 Gated DeltaNet and 1 attention12/48 = 25.0%
MiniMax-01 (2025)One softmax attention block after every 7 lightning attention (linear attention) blocks, plus MoE, 456B total and 45.9B active parameters1/8
Samba (Microsoft, 2024)Mamba interleaved layer by layer with sliding-window attentionWindowed attention
Zamba (Zyphra, 2024)A Mamba backbone with one shared attention moduleOne copy in the parameters
Griffin (Google DeepMind, 2024)Gated linear recurrences plus local attentionLocal attention
Kimi Linear (Kimi Team, 2025)KDA (Gated DeltaNet with finer-grained gating) and MLA mixed layer by layer, 48B total and 3B active parametersSee the paper

The layer counts and ratios of the first three rows come from each model’s config.json, and Experiment 3 uses them to compute caches; the other rows come from the abstracts or bodies of the papers.

Experiment 3: the cache ledger for hybrids

The KV cache per token comes only from attention layers and is attention layers×2×KV heads×head dimension×2\text{attention layers}\times2\times\text{KV heads}\times\text{head dimension}\times2 bytes; recurrent layers contribute a fixed-size state independent of length. The code below plugs the layer counts, head counts and state dimensions from the config.json of seven public models into this formula, with numbers counted in bf16. Llama-2-7B, Mistral-7B and Mixtral-8x7B are the pure-attention references, Jamba-v0.1, Nemotron-H-8B and Qwen3-Next-80B are hybrids, and Mamba-2.8B is a pure SSM.

In the header, KV B/tok is the KV bytes per token, rec the number of recurrent layers, state MiB the size of the fixed state, and the columns on the right are the total cache per sequence at different context lengths (GiB). How the state is sized: Jamba and Mamba use d_inner × (d_state + d_conv) numbers per layer; a Nemotron-H Mamba-2 layer has heads × head dimension × d_state plus a convolution state; a Qwen3-Next Gated DeltaNet layer has one 128×128 matrix for each of 32 value heads plus a convolution state.

GIB, MIB, BYTES = 2**30, 2**20, 2           # numbers are stored as bf16
CONTEXTS = [8 * 1024, 128 * 1024, 256 * 1024, 1024 * 1024]
rows = []     # name, layers, attention layers, KV bytes per token,
              # recurrent layers, fixed state bytes


def add(name, layers, attn, kv_heads, head_dim, rec=0, per_layer=0):
    kv = attn * 2 * kv_heads * head_dim * BYTES   # K and V, every token
    rows.append((name, layers, attn, kv, rec, rec * per_layer * BYTES))


# Fields below come from each model's config.json on the Hugging Face Hub.
add("Llama-2-7B", 32, 32, 32, 128)          # 32 layers, 32 KV heads
add("Mistral-7B", 32, 32, 8, 128)           # 32 layers, 8 KV heads
add("Mixtral-8x7B", 32, 32, 8, 128)

# Jamba-v0.1: attention where layer % 8 == 4, Mamba elsewhere.
# Mamba state per layer: d_inner x (d_state + d_conv) numbers.
attn = sum(i % 8 == 4 for i in range(32))
add("Jamba-v0.1", 32, attn, 8, 128, 32 - attn, 2 * 4096 * (16 + 4))

# Mamba-2.8B: 64 Mamba layers, d_inner 5120, d_state 16, d_conv 4.
add("Mamba-2.8B", 64, 0, 0, 0, 64, 5120 * (16 + 4))

# Nemotron-H-8B: M = Mamba-2, * = attention, - = MLP (no cache).
pattern = "M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"
heads, hdim, d_state, groups = 128, 64, 128, 8
conv_channels = heads * hdim + 2 * groups * d_state
add("Nemotron-H-8B", len(pattern), pattern.count("*"), 8, 128,
    pattern.count("M"), heads * hdim * d_state + conv_channels * 4)

# Qwen3-Next-80B-A3B: full attention in every 4th layer, Gated DeltaNet
# in the rest. State: 32 value heads x (128 x 128), plus the conv state.
attn = sum((i + 1) % 4 == 0 for i in range(48))
add("Qwen3-Next-80B", 48, attn, 2, 256, 48 - attn,
    32 * 128 * 128 + (2 * 16 * 128 + 32 * 128) * 4)


def tag(n):
    return "1M" if n == 1024 * 1024 else f"{n // 1024}K"


head = f"{'model':15s}{'layers':>7s}{'attn':>5s}{'KV B/tok':>10s}"
head += f"{'rec':>5s}{'state MiB':>11s}"
print(head + "".join(f"{tag(n):>8s}" for n in CONTEXTS) + "   (GiB)")
for name, layers, a, kv, r, st in rows:
    cells = "".join(f"{(kv * n + st) / GIB:8.2f}" for n in CONTEXTS)
    print(f"{name:15s}{layers:7d}{a:5d}{kv:10d}{r:5d}{st / MIB:11.2f}" + cells)
print()
for name, layers, a, kv, r, st in rows:
    if a and r:
        print(f"{name:15s} attention {a}/{layers} = {a / layers:.1%} of the "
              f"layers, recurrent {r}/{layers} = {r / layers:.1%}")
model           layers attn  KV B/tok  rec  state MiB      8K    128K    256K      1M   (GiB)
Llama-2-7B          32   32    524288    0       0.00    4.00   64.00  128.00  512.00
Mistral-7B          32   32    131072    0       0.00    1.00   16.00   32.00  128.00
Mixtral-8x7B        32   32    131072    0       0.00    1.00   16.00   32.00  128.00
Jamba-v0.1          32    4     16384   28       8.75    0.13    2.01    4.01   16.01
Mamba-2.8B          64    0         0   64      12.50    0.01    0.01    0.01    0.01
Nemotron-H-8B       52    4     16384   24      49.88    0.17    2.05    4.05   16.05
Qwen3-Next-80B      48   12     24576   36      38.25    0.22    3.04    6.04   24.04

Jamba-v0.1      attention 4/32 = 12.5% of the layers, recurrent 28/32 = 87.5%
Nemotron-H-8B   attention 4/52 = 7.7% of the layers, recurrent 24/52 = 46.2%
Qwen3-Next-80B  attention 12/48 = 25.0% of the layers, recurrent 36/48 = 75.0%

Table 1 of the Jamba paper gives the KV cache at 256K context in 16 bit. The code below recomputes it and checks:

# Jamba paper, Table 1: KV cache at 256K tokens, 16 bit ("GB" in the paper)
paper = {"Llama-2-7B": 128, "Mistral-7B": 32, "Mixtral-8x7B": 32,
         "Jamba-v0.1": 4}
by = {row[0]: row for row in rows}
print("Jamba paper, Table 1: KV cache at 256K tokens")
for name, ref in paper.items():
    ours = by[name][3] * 256 * 1024 / GIB
    print(f"{name:15s} paper {ref:4d}   recomputed {ours:7.2f}")
ratio = by["Mixtral-8x7B"][3] / by["Jamba-v0.1"][3]
print(f"Mixtral / Jamba KV bytes per token: {ratio:.1f}x "
      f"(= 32 layers / {by['Jamba-v0.1'][2]} attention layers)")
Jamba paper, Table 1: KV cache at 256K tokens
Llama-2-7B      paper  128   recomputed  128.00
Mistral-7B      paper   32   recomputed   32.00
Mixtral-8x7B    paper   32   recomputed   32.00
Jamba-v0.1      paper    4   recomputed    4.00
Mixtral / Jamba KV bytes per token: 8.0x (= 32 layers / 4 attention layers)
KV cache and recurrent state versus context length (per sequence, bf16) Log-log line chart, horizontal axis context length from 1K to 1M tokens, vertical axis cache per sequence in GiB. At 1M tokens: Llama-2-7B about 512 GiB, Mistral-7B and Mixtral about 128 GiB, Qwen3-Next-80B about 24 GiB, Jamba and Nemotron-H about 16 GiB, Mamba-2.8B only its fixed state of about 0.01 GiB. At 256K, Llama-2-7B needs 128 GiB and Jamba 4 GiB. A dashed horizontal line marks 80 GiB. KV cache and recurrent state versus context length (per sequence, bf16) 1K 4K 16K 64K 256K 1M 0.01 0.1 1 10 100 1000 80 GiB Llama-2-7B (32 KV heads) Mistral-7B and Mixtral (8 KV heads) Qwen3-Next-80B (12 attention layers) Jamba and Nemotron-H (4 attention layers) Mamba-2.8B (no attention) context length (tokens) GiB
Each line is KV bytes per token times length plus the fixed recurrent state, from the setup output above. Jamba and Nemotron-H have the same KV bytes per token (4 attention layers, 8 KV heads, head dimension 128), so their lines coincide and differ only in a fixed state of a few tens of MiB.

How to read these numbers:

  • They match the paper item by item: 128, 32, 32, 4. The “GB” in the paper is in fact 2302^{30} bytes, that is GiB. Mixtral and Jamba have the same number of KV heads and head dimension, so the ratio of KV bytes per token is exactly 8.0, equal to 32 layers over 4 attention layers.
  • At 256K: Llama-2-7B 128 GiB, Mixtral 32 GiB, Jamba 4.01 GiB, Nemotron-H-8B 4.05 GiB, Qwen3-Next-80B 6.04 GiB, and Mamba-2.8B only its fixed 0.01 GiB.
  • The cache curve of a hybrid is still a straight line, just with a small slope: 16,384 KV bytes per token (Jamba, Nemotron-H) or 24,576 (Qwen3-Next), against 524,288 for Llama-2-7B.
  • The fixed state is a few tens of MiB (Jamba 8.75, Nemotron-H 49.88, Qwen3-Next 38.25) and does not depend on length. At very short contexts it is a large share of the cache, for example Nemotron-H-8B at 8K has 128 MiB of KV plus 49.88 MiB of state; from 128K on it can be ignored.
What this ledger does not include

It counts only bytes of cache, not weights, activations or the paging overhead of an inference engine. The state is counted in bf16, and an implementation may store states in higher precision; doubling a few tens of MiB does not change the conclusion. The config.json of Mistral-7B-v0.1 has sliding_window=4096, and an implementation with a rolling cache never needs more than 4,096 tokens, which is 0.5 GiB; Table 1 of the paper and the table above count the full length. Throughput and latency depend on kernel implementations and are not measured here either: Samba reports 3.73 times the throughput of a same-size GQA Transformer for 128K prompts, Nemotron-H reports up to 3 times faster inference, and Kimi Linear reports up to 6 times the decoding throughput at 1M context; these are measurements by the paper authors on their own hardware.

When to use them, and when not to

ScenarioLean towardsWhy
Very long context, many concurrent sequences, cost-sensitive inferenceA hybridThe cache grows only with the few attention layers, and the fixed state does not depend on length (Experiment 3)
Verbatim copying, exact retrieval in long documents, few-shot in-context learningEnough full-attention layers, or retrieve first and put the result in contextA fixed state is lossy and exact recall falls as n/dn/d grows (Experiment 2); pure SSMs fall behind on such tasks (Jelassi et al. 2024; Waleffe et al. 2024)
Short context (a few thousand tokens), training with limited computeA standard TransformerThe cache is not yet the bottleneck, and kernels, tooling and experience are the most mature
Wanting to reuse an existing inference engine and quantization schemeCheck engine support firstA hybrid has to manage both a KV cache that grows with length and a fixed-size state

Two engineering points follow from the structure itself:

  • A state cannot be sliced like KV. A KV cache is stored per token, so it can be paged and shared by prefix; a state is a compression of the whole prefix, and reusing a prefix means saving a state snapshot at the end of that prefix.
  • Parallel kernels decide training efficiency. Chunkwise algorithms use matrix multiplications inside a chunk and pass the state between chunks; they are much newer than attention kernels, and their quality decides whether the theoretical linear complexity becomes real speed. The Jamba paper adds two lessons: the model needs no explicit positional encoding, and Mamba layers need a special normalization to train stably at scale.

Summary and exercises

  • Linear attention, SSMs and the delta rule are variants of one template St=AtSt−1+…S_t=A_tS_{t-1}+\dots and change how to write and how to forget. In Experiment 1 the six equivalences differ by at most 5.3e-15, so using the parallel form for training and the recurrent form for inference is not an approximation.
  • A fixed state is lossy compression with capacity about its dimension. The cosine of an additive read-out is about 1/1+(n−1)/d1/\sqrt{1+(n-1)/d}; storing n=256n=256 pairs at d=64d=64 drops exact recall from 1.000 to 0.724, while softmax attention stays at 1.000 at the price of a cache that grows linearly with length.
  • Overwriting old values takes content-dependent forgetting. The best fixed decay depends on how fast writes arrive (0.95 is better with 8 keys, 0.99 with 64); the delta rule replaces by content and is near perfect up to 32 keys; Mamba’s selectivity and the gate of Gated DeltaNet make forgetting depend on the input.
  • Hybrids cut the cache to a fraction: Jamba is 1/8 of Mixtral (4.01 GiB against 32 GiB at 256K), and both the cost and the gain come from keeping just 4 attention layers; the paper’s ablations show that these few layers are enough to keep in-context learning.
  • The key question for choosing is whether the task needs verbatim recall. If it does, keep enough attention; if only the compressed meaning matters, a fixed state is a good deal.

Quick self-check

1. What does “linear” in linear attention refer to?

  • The attention weights are a linear function of the input
  • Without the softmax the history accumulates into a fixed-size state, the cost per step does not depend on how much has been read, and total compute grows linearly with length
  • The model has only one layer
  • The KV cache is replaced by a linear layer

Unrolling St=∑i≤tkivi⊤S_t=\sum_{i\le t}k_iv_i^\top gives causal attention without the softmax, accumulated first and multiplied by qtq_t afterwards, so no kik_i or viv_i needs to be kept. Softmax attention reads tt keys per step and its total compute grows quadratically.

2. In Experiment 1, why can the convolutional form of a time-invariant SSM not be used in Mamba?

  • Convolution has no GPU implementation
  • Selectivity makes At,Bt,CtA_t,B_t,C_t depend on the input, so there is no fixed kernel; fortunately the recurrence is still linear and a parallel scan applies
  • The state dimension is too large
  • Convolution requires the sequence length to be a power of 2

The convolutional form requires the kernel CAjBCA^jB not to vary with position, and input-dependent parameters break that; (a2,b2)∘(a1,b1)=(a1a2, a2b1+b2)(a_2,b_2)\circ(a_1,b_1)=(a_1a_2,\,a_2b_1+b_2) is associative, and 16 steps need 4 rounds of scan.

3. In Experiment 2, an additive state with d=64d=64 stores n=256n=256 random key-value pairs. About what are the cosine to the truth and the exact recall?

  • Cosine close to 1 and recall 1.000, because the state is large enough
  • Cosine about 0.448 and recall 0.724
  • Cosine 0 and recall 0
  • Cosine 0.9 and recall 0.5

1/1+255/64≈0.4481/\sqrt{1+255/64}\approx0.448, and the table measures 0.448 too, with recall 0.724 (the codebook has only 256 candidates, and most reads at cosine 0.448 are still recognised).

4. Why is the delta rule far better than the additive rule when the same key is written repeatedly, yet no better when each key is written once?

  • The delta rule uses a larger state
  • The delta rule reads the old value under the key before replacing it, so an overwrite is clean; when each key is written once there is no old value to replace, and random keys overlap so the correction disturbs values already written
  • The additive rule cannot write the same key
  • The two tests used different random seeds

In the overwrite test the additive rule scores only 0.052 to 0.071 while the delta rule scores 1.000, 1.000, 0.988 and 0.820; in the single-write table at d=64d=64, n=2dn=2d the delta rule gets 0.530, below the 0.963 of the additive rule.

5. Which statements agree with Experiment 3?

  • Jamba has only 4 attention layers producing KV, so its KV bytes per token are 1/8 of Mixtral’s
  • The fixed recurrent state does not depend on context length; the state of Nemotron-H-8B is about 49.88 MiB
  • The cache of a hybrid model does not grow with context length
  • Replacing all attention layers with Mamba layers does not make a model worse at copying and retrieval

The cache of a hybrid still grows linearly with length, just with a small slope (16,384 bytes per token for Jamba). The last statement disagrees with Zoology, Jelassi et al., Waleffe et al. and the Jamba ablations.

6. An application must quote clauses verbatim from a 128K-token contract and answer retrieval-style questions. Which choice is safer?

  • Pure Mamba, because its cache is the smallest
  • A model that keeps enough full-attention layers, or retrieving first and putting the relevant clauses into context
  • Any architecture is the same
  • Reducing the state dimension

A fixed state is lossy compression, and exact recall is its weakness (Experiment 2, and the conclusion of Jelassi et al. 2024). The memory saved in the cache does not buy back the verbatim content that was compressed away.

Exercises:

  1. At 256K tokens, how large are the KV cache and the recurrent state of Qwen3-Next-80B for one sequence, and what is the total?
  2. Change Jamba from 4 attention layers to 8 (24 Mamba layers, everything else the same). What is the cache at 256K, and how does it compare with Mixtral’s 32 GiB?
  3. With state dimension d=128d=128, store n=512n=512 random unit key-value pairs with the additive rule. About what is the cosine between the read-out and the truth? Which rows of Experiment 2 does it equal, and why?
  4. Prove that the gated delta rule written as “decay first, then write with the delta rule” is equivalent to multiplying by the single transition matrix αt(I−βtktkt⊤)\alpha_t(I-\beta_tk_tk_t^\top).
  5. Design: a coding assistant has to complete code in a repository of 100,000 tokens and reference function names from other files. Pure attention, pure SSM or hybrid? Give your reasons and the experiment you would use to check them.
Reference answers
  1. The KV cache is 6.00 GiB, the state 38.25 MiB, and the total 6.04 GiB. 12 attention layers with 2 KV heads of dimension 256 give 12×2×2×256×2=24,57612\times2\times2\times256\times2=24{,}576 bytes per token, times 262,144 tokens; each of the 36 Gated DeltaNet layers has a state of 32×128×128+(2×16×128+32×128)×432\times128\times128+(2\times16\times128+32\times128)\times4 numbers, at 2 bytes each.
  2. The KV cache is 8.00 GiB and the state 7.50 MiB (24 Mamba layers), so the total is 8.01 GiB, a quarter of Mixtral’s. The cost is 4 fewer Mamba layers and 4 more attention layers, which doubles the KV bytes per token to 32,768.
  3. About 0.448, the same as the two rows with n/d=4n/d=4 in Experiment 2 (the last rows for d=16d=16 and d=64d=64): the cosine depends only on n/dn/d, not on dd itself. So making the state larger alone does not change the consequence of storing a fixed multiple of the state dimension.
  4. Decay first: S′=αtSt−1S'=\alpha_tS_{t-1}. Then the delta write: St=S′+βtkt(vt−S′⊤kt)⊤=(I−βtktkt⊤)S′+βtktvt⊤S_t=S'+\beta_tk_t(v_t-S'^\top k_t)^\top=(I-\beta_tk_tk_t^\top)S'+\beta_tk_tv_t^\top. Substituting S′=αtSt−1S'=\alpha_tS_{t-1} gives St=αt(I−βtktkt⊤)St−1+βtktvt⊤S_t=\alpha_t(I-\beta_tk_tk_t^\top)S_{t-1}+\beta_tk_tv_t^\top, whose right-hand side is the transition matrix αt(I−βtktkt⊤)\alpha_t(I-\beta_tk_tk_t^\top) times St−1S_{t-1} plus the write term. Item 6 of Experiment 1 checks this on random data.
  5. A reasoning path: completion needs verbatim copying of function names and exact retrieval from far-away files, which is the weak spot of a fixed state, so not a pure SSM. A 100K KV cache is affordable for one sequence and becomes a bottleneck only at high concurrency, so if cost is the main tension choose a hybrid and keep enough attention layers, otherwise use a standard Transformer plus retrieval. To check: build a function-name recall test set, vary the repository length from short to long, compare the recall, the cache per sequence and the throughput of the two architectures, and hold out repositories that are disjoint from the training data.

The numbers above come from the code on this page, run after the script of Experiment 3:

GIB, MIB = 2**30, 2**20
N = 256 * 1024                                  # 256K tokens

# Exercise 1: Qwen3-Next-80B at 256K tokens
kv = 12 * 2 * 2 * 256 * 2 * N                   # 12 attention layers
state = 36 * (32 * 128 * 128 + (2 * 16 * 128 + 32 * 128) * 4) * 2
print(f"1. KV {kv / GIB:.2f} GiB, state {state / MIB:.2f} MiB, "
      f"total {(kv + state) / GIB:.2f} GiB")

# Exercise 2: Jamba with 8 attention layers and 24 Mamba layers
kv = 8 * 2 * 8 * 128 * 2 * N
state = 24 * 2 * 4096 * (16 + 4) * 2
print(f"2. KV {kv / GIB:.2f} GiB, state {state / MIB:.2f} MiB, "
      f"total {(kv + state) / GIB:.2f} GiB")

# Exercise 3: additive state, d = 128, n = 512 random unit keys
print(f"3. predicted cosine {1 / (1 + (512 - 1) / 128) ** 0.5:.3f}")
1. KV 6.00 GiB, state 38.25 MiB, total 6.04 GiB
2. KV 8.00 GiB, state 7.50 MiB, total 8.01 GiB
3. predicted cosine 0.448

Further reading

FAQ

Will Mamba replace the Transformer?
The evidence supports "hybrid", not "replace". Pure SSMs fall behind Transformers trained on the same data on tasks that need verbatim copying, exact retrieval from long documents and few-shot in-context learning (Jelassi et al. 2024; Waleffe et al. 2024). With a few attention layers mixed into Mamba-2 layers, the 8B model of Waleffe et al. beat the same-data 8B Transformer on all 12 standard tasks by 2.65 points on average and is predicted to generate up to 8 times faster. Jamba, Nemotron-H and Qwen3-Next are all hybrids, not pure SSMs.
How are linear attention, SSMs and Mamba related?
They are all recurrent models with a fixed-size state and one update per token, and differ only in how they write and how they forget. Linear attention never forgets, RetNet uses a constant decay, Mamba-2 makes the decay depend on the current token, DeltaNet uses the delta rule to overwrite the old value under the same key, and Gated DeltaNet does both. The Mamba-2 paper (Dao and Gu, 2024) goes further and shows that SSMs and attention with a structured mask are two decompositions of the same class of matrices, called state space duality (SSD). Experiment 1 on this page checks with NumPy that the parallel and recurrent forms of these rules give the same result.
Why do hybrids still keep a few attention layers?
Because a fixed-size state is lossy compression. In Experiment 2, an additive state with d=64 that stores 256 random key-value pairs reads back with cosine 0.448 to the truth, and exact recall falls from 1.000 to 0.724; softmax attention keeps every pair and stays at 1.000 in the same test. The Jamba ablations also show that pure Mamba often ignores the answer format of few-shot examples, while a hybrid with one attention layer in every eight follows it.
Why is an SSM's cost per step independent of length at inference, yet training can still be parallel?
Inference uses the recurrent form, where each new token updates the fixed-size state once, so the cost does not depend on how many tokens came before. Training uses an equivalent parallel form. A time-invariant SSM is a convolution, and selective SSMs and decayed linear attention can use a parallel scan or a chunkwise algorithm (matrix multiplications inside a chunk, a state passed between chunks). Experiment 1 checks the forms numerically; they agree to about 1e-15.
How is compressing the KV cache (GQA, MLA) different from switching to a fixed-size state?
GQA and MLA shrink the cache per token, but the cache still grows linearly with length; a fixed-size state makes the cache independent of length, at the price of being lossy. In numbers, Mistral-7B uses 8 KV heads against 32 in Llama-2-7B, which is 4 times smaller, yet still needs 32 GiB at 256K context; Jamba keeps the same 8 KV heads but only 4 attention layers and needs 4.01 GiB at the same length (including 8.75 MiB of Mamba state). The two approaches can be combined.