# Mamba: linear-time sequence modeling with selective state spaces

> Mamba makes a state space model's Δ, B and C depend on the current token (selection) and runs it with a hardware-aware scan: linear cost in length, fixed-size state at inference. We recompute its parameters and Table 3, then compare LTI and selective SSMs on selective copying.

- URL: https://dmxsf.com/en/blog/mamba-linear-time-sequence-modeling-with-selective-state-spaces/
- [DMXSF](https://dmxsf.com/en/about/)
- Published: 2023-12-12
- Updated: 2026-11-13
- Paper notes
- Paper: [Mamba: Linear-Time Sequence Modeling with Selective State Spaces](https://arxiv.org/abs/2312.00752) (Albert Gu, Tri Dao · arXiv, 2023)

“Mamba: Linear-Time Sequence Modeling with Selective State Spaces” (Albert Gu and Tri Dao, Carnegie Mellon University and Princeton University, arXiv 2312.00752, called the Mamba paper below) argues that structured state space models (SSMs) fall behind attention because their parameters do not change with the input (they are linear time-invariant, LTI), so they cannot decide by content what to remember and what to ignore. Its remedy is to compute Δ, B and C from the current token, the **selection mechanism**. That breaks the convolution form, so the paper adds a parallel scan that keeps the state only in on-chip GPU memory (SRAM), and merges the gated MLP and the SSM into one homogeneous Mamba block. The resulting network has no attention and no separate MLP layer: training time and memory grow linearly with length, and inference updates one fixed-size state per step. The paper reports that on the Pile its scaling curves up to 1.3B parameters match the strong Transformer++ recipe, and that Mamba-2.8B (called “Mamba-3B” in the text) has a zero-shot average of 63.3, above Pythia-2.8B at 59.1 and also above Pythia-6.9B at 61.7.

This page does two things. **Checking:** we recompute the numbers that can be recomputed (we read arXiv v2, 31 May 2024). The parameter count reproduces exactly from the block structure and equals the Hugging Face checkpoint totals for all 5 sizes (difference 0). Theorem 1 holds exactly under ZOH discretization (error 6.7e-16), but the official code uses $\bar B=\Delta B$, which the paper never mentions, and in the paper's initialization range 76.4% of the combinations differ by more than 1%. Two rows of Table 3 have averages that do not match their columns, and “best at every size” holds against same-size opponents but against the four 6-7B models only in 4 of 9 columns. **Small-scale reproduction:** we rerun the paper's Selective Copying task on a laptop, swapping the sequence layer inside one Mamba-style block between an LTI diagonal SSM, an LTI global convolution and three selective variants, with 3 seeds each. After 3000 steps S6 reaches 99.5% exact match on selective copying with random positions (three seeds between 99.0 and 99.8), LTI global conv gets 77.2% and the LTI diagonal SSM 16.3%; but with 3 times as many steps the LTI models catch up to 95.6% and 80.5%, so at this small scale selection mainly shows up as faster, steadier learning rather than LTI never learning it (the paper's setting is much harsher, and its LTI layers reach at most 57.0%). The variant that selects only $B$ and $C$ (93.6%) beats the one that selects only $\Delta$ (80.6%), but the three-seed ranges overlap, so that is only a hint.

## Why this paper is worth reading

- **It is the first time the “no attention” line caught up with Transformers in language modeling in a serious way.** Linear attention, gated convolutions, recurrent models and structured SSMs all try to escape the quadratic cost, and the paper's abstract judges that they do worse than attention on modalities such as language. Mamba's scaling curve is the first attention-free one to match Transformer++ (paper Figure 4, models from 125M to 1.3B).
- **It turns “why old SSMs fail” into a testable claim.** Two synthetic tasks (selective copying and induction heads) each expose one blind spot of LTI models, and Tables 1 and 2 use the same block structure and change only the sequence layer, which isolates the effect of selection cleanly.
- **It is a systems paper.** Selection breaks convolutions, and the paper brings the recurrence back to speed with kernel fusion, a parallel scan and recomputation. Without that step you would not see why Mamba is usable on GPUs and not only linear on paper.
- **Its numbers can be checked.** Parameter counts, training budgets, the averages of two tables and the proof of the theorem can be recomputed in a few lines, and the code differs from the paper in ways worth knowing (see “Hands-on check” below).
- **It shaped the hybrid-architecture debate.** A fixed state loses on tasks that need verbatim recall, and Mamba-2, Jamba and NVIDIA's comparison all start from there; today's talk about KV caches and long context often uses it as the reference (see [State space models and hybrid architectures](https://dmxsf.com/en/wiki/architecture/state-space-and-hybrid/)).
- **Neighbors on this site.** The quadratic cost of attention: [Attention Is All You Need](https://dmxsf.com/en/blog/attention-is-all-you-need/) and [efficient attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/). The bottleneck of recurrent models: [from RNNs to attention](https://dmxsf.com/en/wiki/architecture/from-rnn-to-attention/). The cache arithmetic at inference: [KV cache](https://dmxsf.com/en/wiki/inference/kv-cache/). Today's architecture choices: [modern LLM architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/).

## Background: state space models and the LTI trap

A state space model (SSM) comes from control theory: an input $x(t)$ passes through a hidden state $h(t)$ and becomes an output $y(t)$. Equation (1) of the paper is

$$
\begin{aligned}
h'(t) &= A\,h(t) + B\,x(t) \\
y(t) &= C\,h(t)
\end{aligned}
$$

Language is a sequence of discrete tokens, so the model is first **discretized**: a step size $\Delta$ turns the continuous parameters $(\Delta, A, B)$ into discrete ones $(\bar A, \bar B)$. The zero-order hold (ZOH) rule of equation (4) is

$$
\begin{aligned}
\bar A &= \exp(\Delta A) \\
\bar B &= (\Delta A)^{-1}\big(\exp(\Delta A) - I\big)\cdot \Delta B
\end{aligned}
$$

After discretization there are two equivalent ways to compute the model. As a **recurrence**, $h_t=\bar A h_{t-1}+\bar B x_t$ and $y_t=C h_t$: each step depends only on the previous state, which suits autoregressive inference. As a **convolution**, unrolling the recurrence gives the output as the input convolved with a kernel of length $L$, $\bar K=(C\bar B,\,C\bar A\bar B,\,\dots,\,C\bar A^{k}\bar B,\,\dots)$, so $y=x*\bar K$, which lets training compute the whole sequence in parallel.

> [!IMPORTANT] Linear time-invariance (LTI)
> What equations (1) to (3) share is that the dynamics do not change with time: $(\Delta, A, B, C)$ are the same at every step, which is why a “kernel” exists at all. S4 and its variants are efficient because of this. The price is that one kernel acts at every position, so the model **treats inputs by position and cannot treat them by content**.

In a structured SSM, $A$ is a structured $N\times N$ matrix (diagonal in practice), every input channel has its own $N$-dimensional state, and the $D$ channels hold $D\cdot N$ state numbers in total; the paper puts $N$ at roughly 10 to 100 and Mamba uses 16, so the state is a factor $N$ larger than the input and output. The convolution form has one big advantage: training never needs to materialize that $N$-times-larger state, it just generates the kernel.

The paper uses two synthetic tasks to show what LTI cannot do (its Figure 2). **Selective copying:** a few tokens to remember are scattered among noise tokens at positions that differ from sample to sample, and the model must output them in order. The standard copying task, with fixed positions, is easy for an LTI model once the kernel has exactly the right length; with random positions the kernel would have to change with the content, which an LTI model cannot do. **Induction heads:** the sequence has shown “A B” earlier, and when “A” appears again the model must predict “B”. This associative recall is thought to be closely tied to in-context learning in large models (Olsson et al., arXiv 2209.11895).

Table 1 of the paper asks whether gating is enough. Many works argue that the multiplicative gates in H3 and Mamba already make a model data-dependent; the paper replies that a gate does not act along the sequence axis and cannot change the spacing between tokens, and that what helps is selection (changing S4 into S6). In the table, “Model” names the original model for that combination, “Arch.” is the block structure and “Layer” the sequence layer inside it:

| Block | Sequence layer | Selective copying accuracy (%) |
| --- | --- | --- |
| No gate | S4 (LTI) | 18.3 |
| No gate | S6 | 97.0 |
| H3 | S4 (LTI) | 57.0 |
| H3 | Hyena (LTI) | 30.1 |
| H3 | S6 | 99.7 |
| Mamba | S4 (LTI) | 56.4 |
| Mamba | Hyena (LTI) | 28.4 |
| Mamba | S6 | 99.8 |

Read the table within each group: with the block fixed and only the sequence layer changed, the LTI layers S4 and Hyena reach at most 57.0%, while S6 reaches 97.0%, 99.7% and 99.8%. The paper's setting is sequence length 4096, a vocabulary of 16 tokens (including the noise token), 16 data tokens to memorize, 2 layers with $D=64$, and 400K training steps (appendix E.1).

## Method: selection, the scan and the Mamba block

### Selection: let Δ, B and C depend on the input

Algorithm 1 (S4) and Algorithm 2 (S6) differ by a few lines, and putting them side by side is clearest (batch is the batch size, $L$ the sequence length):

| | S4 (Algorithm 1) | S6 (Algorithm 2) |
| --- | --- | --- |
| $A$ | $(D, N)$, parameter | $(D, N)$, parameter, still independent of the input |
| $B$ | $(D, N)$, parameter | $(\text{batch}, L, N)$, $s_B(x)=\mathrm{Linear}_N(x)$ |
| $C$ | $(D, N)$, parameter | $(\text{batch}, L, N)$, $s_C(x)=\mathrm{Linear}_N(x)$ |
| $\Delta$ | $(D)$, $\tau_\Delta(\text{parameter})$ | $(\text{batch}, L, D)$, $\tau_\Delta(\text{parameter}+s_\Delta(x))$ |
| Computation | recurrence or convolution (time-invariant) | recurrence only, i.e. a scan (time-varying) |

Here $s_\Delta(x)=\mathrm{Broadcast}_D(\mathrm{Linear}_1(x))$ and $\tau_\Delta=\mathrm{softplus}$. A few details:

- **$B$ and $C$ are shared across the $D$ channels**; only $\Delta$ has one value per channel. The projection of $\Delta$ is squeezed to 1 dimension and then broadcast because “this token should be ignored” should hold for all channels at once (the explanation after Theorem 1).
- In practice this projection is generalized to a low-rank one, $s_\Delta(x)=\mathrm{Linear}_D(\mathrm{Linear}_R(x))$, with $R$ a small fraction of $D$; the official implementation uses $R=\lceil D/16\rceil$.
- $A$ uses the S4D-Real initialization $A_n=-(n+1)$, real rather than complex, and the paper initializes $\Delta$ as $\tau_\Delta^{-1}(\mathrm{Uniform}([0.001, 0.1]))$.

### Why Δ is the core: it is the RNN gate

Theorem 1 of the paper: when $N=1$, $A=-1$, $B=1$, $s_\Delta=\mathrm{Linear}(x)$ and $\tau_\Delta=\mathrm{softplus}$, the selective SSM recurrence is

$$
\begin{aligned}
g_t &= \sigma\big(\mathrm{Linear}(x_t)\big) \\
h_t &= (1-g_t)\,h_{t-1} + g_t\,x_t
\end{aligned}
$$

The proof is a short ZOH calculation: with $\Delta_t=\mathrm{softplus}(z_t)$ ($z_t$ is the linear projection), $\bar A_t=\exp(-\Delta_t)=1/(1+e^{z_t})=1-\sigma(z_t)$ and $\bar B_t=-(\exp(-\Delta_t)-1)=1-\bar A_t=\sigma(z_t)$. That is the update of the classic gated RNN. So the paper takes the position that discretization is the principle behind heuristic gating, and $\Delta$ plays the role of a generalized gate. Section 3.5.2 of the paper gives three mechanistic effects of selection and an interpretation of each parameter:

| Effect or parameter | The paper's reading |
| --- | --- |
| Variable spacing | Filters out noise tokens between useful inputs (such as filler words like “um”); a gate $g_t\to 0$ ignores the input |
| Filtering context | A selective model can reset its state at any time and drop irrelevant history, so in principle more context is always better; global convolutions and LTI models cannot do this |
| Boundary resetting | When independent sequences are packed together, attention separates them with a mask and LTI models bleed information across; a selective SSM can reset at the boundary ($\Delta_t\to\infty$) |
| $\Delta$ | Controls how much to focus on or ignore the current input: a large $\Delta$ resets the state and focuses on the current input, a small one keeps the state and ignores the input |
| $A$ | Could also be selective, but it acts only through $\bar A=\exp(\Delta A)$ together with $\Delta$, so selectivity in $\Delta$ is enough; the paper leaves it out for simplicity |
| $B$, $C$ | Finer control over letting an input into the state and the state into the output, i.e. modulating the recurrence by content and by context (the hidden state) |

### A hardware-aware scan: never write the expanded state back to memory

Selection costs the convolution form: $\Delta$, $B$ and $C$ vary with time, so there is no fixed kernel to compute in advance. Back at the recurrence itself, a naive implementation computes the state of shape $(\text{batch}, L, D, N)$ in full and writes it to GPU high-bandwidth memory (HBM), a factor $N$ larger than the input and output. The paper makes two observations: the naive recurrence costs $O(BLDN)$ FLOPs against $O(BLD\log L)$ for the convolution, and the recurrence has the smaller constant, so for long sequences and a modest $N$ it can even use fewer FLOPs; the real difficulties are the sequential nature of a recurrence and its huge memory traffic. The remedy is three classical techniques:

1. **Kernel fusion.** Load $(\Delta, A, B, C)$ from slow HBM into fast SRAM, do the discretization and the recurrence in SRAM, and write only the output of shape $(\text{batch}, L, D)$ back to HBM. Memory traffic drops by a factor $O(N)$, and the paper says the speedup in practice is 20 to 40 times.
2. **Parallel scan.** The recurrence $h_t=\bar A_t h_{t-1}+\bar B_t x_t$ is not a convolution but is still associative, so a work-efficient parallel scan algorithm can parallelize it (see [parallel scan](https://dmxsf.com/en/glossary/#parallel-scan)).
3. **Recomputation.** The intermediate states needed by the backward pass are not saved; the backward pass reads the inputs back from HBM and recomputes them in SRAM. The paper's accounting (mixed-precision training) is that a selective SSM layer stores about 16 bytes of activations per token, an attention layer with FlashAttention about 12 bytes and an MLP layer about 20 bytes, so two SSM layers need about as much activation memory as one attention layer plus one MLP layer.

The speed numbers (the scan is faster than FlashAttention-2 beyond sequence length 2K and 20 to 40 times faster than a standard PyTorch scan; end-to-end inference throughput is 4 to 5 times that of a similar-size Transformer) are all the paper's measurements on an A100. This page has no GPU and did not check them; the “Hands-on check” below only covers numbers that can be worked out cleanly on a CPU.

### The Mamba block

The paper merges the H3 block (an SSM block built on the idea of linear attention) with the gated MLP of the Transformer into one block, and the whole network just repeats it, with normalization and residual connections:

*Figure: Figure 1: The Mamba block and one step of the selective SSM. Left: one block merges a gated MLP and an SSM, with E=2. Right: Delta, B and C are computed from the current token while A is a fixed parameter; the state update follows Algorithm 2 of the paper (the official code uses Delta times B for B-bar).*

The input is linearly mapped to $2ED$ dimensions and split into two branches, where $E$ is an expansion factor that the paper fixes at $E=2$. The $x$ branch goes through a depthwise convolution (width 4 in the official implementation) and SiLU and then into the selective SSM; the $z$ branch goes through SiLU and acts as a gate, multiplying the SSM output element-wise, and a last linear map returns to $D$ dimensions. Most parameters sit in the two linear projections: $2ED^2$ for the input projection and $ED^2$ for the output projection, $3ED^2$ in total, and the SSM's own parameters (the projections of $\Delta$, $B$ and $C$ and the matrix $A$) are much smaller. With $E=2$, two Mamba blocks hold $2\times 3\times 2D^2=12D^2$ parameters, the same as the $12D^2$ of one multi-head attention layer plus one MLP layer in a Transformer. The paper adds that SiLU is chosen so that the gated MLP becomes the popular SwiGLU.

## What the paper reports

### Synthetic tasks

**Selective copying** (Table 1 above) has been covered. For **induction heads** the paper trains on sequences of length 256 with a vocabulary of 16 and 2-layer models ($D=64$ for Mamba and $D=128$ for the others), and tests on sequence lengths from $2^6=64$ up to $2^{20}=1{,}048{,}576$. Table 2 and appendix Table 11 give each model's test accuracy; below are 6 of the test lengths (✓ is the paper's mark for perfect generalization, ✗ means out of memory):

| Model | 256 (trained) | 512 | 1K | 4K | 16K | 1M |
| --- | --- | --- | --- | --- | --- | --- |
| Multi-head attention (absolute positions) | 100.0 | 58.6 | 26.6 | 9.8 | 7.8 | ✗ |
| Multi-head attention (RoPE) | 100.0 | 83.6 | 31.3 | 8.6 | 5.5 | ✗ |
| Multi-head attention (xPos) | 100.0 | 99.6 | 67.6 | 7.0 | 7.8 | ✗ |
| H3 | 100.0 | 80.9 | 39.5 | 14.8 | 5.9 | 7.4 |
| Hyena | 100.0 | ✓ | 44.1 | 6.6 | 7.0 | 9.8 |
| Mamba (74K parameters) | 100.0 | ✓ | ✓ | ✓ | ✓ | ✓ |

The paper's conclusion is that Mamba solves the task perfectly and generalizes to sequences of 1 million tokens, 4000 times the training length, while no other method goes beyond 2 times. Keep in mind that the models compared are small 2-layer ones, the task is synthetic, and Mamba has only 74K parameters.

### Language modeling: scaling laws and zero-shot

The scaling-law experiments train models from 125M to 1.3B parameters on the Pile following the Chinchilla protocol (about 20 tokens per parameter, checked against Table 12 below), at sequence lengths 2048 and 8192, and compare the standard Transformer (GPT-3 architecture), the stronger Transformer++ (RoPE, SwiGLU, RMSNorm, no biases, higher learning rates) and sub-quadratic architectures such as Hyena, RWKV, RetNet and H3++ (Figure 4). The paper concludes that Mamba scales better than the other attention-free models and is the first one to match Transformer++, more clearly as sequences get longer; RWKV and RetNet are missing at 8K because the lack of efficient implementations caused out-of-memory errors or unrealistic compute.

The zero-shot evaluation (Table 3) compares Mamba with Pythia, RWKV and others trained on the Pile. Below are 5 columns of the group from 2.8B to 7.4B (Pile perplexity, lower is better; the rest are accuracies; “-” means the paper gives no value):

| Model | Pile ppl | LAMBADA | HellaSwag | Arc-E | Average |
| --- | --- | --- | --- | --- | --- |
| Pythia-2.8B | 6.73 | 64.7 | 59.3 | 64.1 | 59.1 |
| RWKV-3B | 7.00 | 63.9 | 59.6 | 67.8 | 59.6 |
| Mamba-2.8B | 6.22 | 69.2 | 66.1 | 69.7 | 63.3 |
| GPT-J-6B | - | 68.3 | 66.3 | 67.0 | 63.0 |
| OPT-6.7B | - | 67.7 | 67.2 | 65.6 | 62.9 |
| Pythia-6.9B | 6.51 | 67.1 | 64.0 | 67.3 | 61.7 |
| RWKV-7.4B | 6.31 | 67.2 | 65.5 | 67.8 | 62.5 |

The abstract says “Mamba-3B's quality matches that of Transformers twice its size (4 points higher average on common-sense reasoning than Pythia-3B, even exceeding Pythia-7B)”. The numbers fit: 63.3 is 4.2 above 59.1 and 1.6 above Pythia-6.9B's 61.7. The check below shows where the edges of that sentence are.

### Other modalities and efficiency

The paper also pretrains on DNA sequences and audio waveforms and reports that Mamba beats SaShiMi, Hyena and Transformers, with performance still improving as context grows to a million tokens (this is the paper's own account and this page did not check those two parts). The efficiency section (4.5) reports two things: the scan operator is faster than FlashAttention-2 beyond sequence length 2K and 20 to 40 times faster than PyTorch's standard scan; and end-to-end, having no KV cache allows much larger batches, so throughput is 4 to 5 times that of a similar-size Transformer, with the example that an (untrained) Mamba-6.9B would have higher throughput than a 5-times-smaller Transformer-1.3B. The measurement setting is a prompt of 2048 tokens, 128 generated tokens and an A100 80GB, against a standard Transformer implementation from Hugging Face.

### Ablations

The paper runs a set of ablations at about 350M parameters and Chinchilla token counts (Tables 6 to 10, metric Pile perplexity, lower is better). Table 6 compares block structure and sequence layer: in the H3 block the three LTI layers (Hyena 10.24, S4 complex 10.30, S4 real 10.34) are about the same and S6 drops to 8.95; in the Mamba block the LTI layers give 10.75, 10.54 and 10.56 and S6 gives 8.69. So the block structure matters little, and whether the sequence layer is selective or LTI is the key. Table 7 makes $\Delta$, $B$ and $C$ selective one at a time:

| $\Delta$ selective | $B$ selective | $C$ selective | Perplexity |
| --- | --- | --- | --- |
| no | no | no | 10.93 |
| no | yes | no | 10.15 |
| no | no | yes | 9.98 |
| yes | no | no | 9.81 |
| yes | yes | yes | 8.71 |

The paper concludes that $\Delta$ matters most and that the three together are synergistic; the table has no row for “$B$ and $C$ selective, $\Delta$ not”, which is the cell the small experiment below fills in. Table 10 varies the state dimension $N$ (the $\Delta$ projection fixed at 64): with $B$ and $C$ not selective, going from $N=1$ to 16 only lowers perplexity from 9.88 to 9.81; with them selective it falls from 9.73 to 8.71, a drop of more than 1.0, for about 1% more parameters (1.2% in the check below). Only selective $B$ and $C$ can use a larger state. Table 8 compares initializations of $A$: S4D-Lin (complex) 9.16, $A_n=-1/2$ 8.85, S4D-Real 8.71 and random 8.71. Table 9 is about the projection dimension of $\Delta$: the paper says even projecting to 1 dimension gives a clear gain (9.12 down to 8.97), and 64 dimensions reach 8.71.

## Hands-on check: recompute the paper's numbers

The script trains nothing and only does arithmetic: it copies the paper's tables and formulas into code and compares them with the real parameter counts of the Hugging Face checkpoints and with the official code. Seven parts, in the order of the output: the training budget of Table 12, counting parameters from the block structure and reconciling with the Hub, the parameter columns of Tables 9 and 10, a numerical check of Theorem 1, ZOH against the official $\bar B=\Delta B$, the averages and the “best” claim of Table 3, and state size against the KV cache. Environment: Python 3.14.3, NumPy 2.4.2, CPU; checkpoint configurations come from the `config.json` files of `state-spaces/mamba-*-hf` and the parameter totals from the Hub metadata (queried on 13 November 2026).

<details>
<summary>Full code (about 252 lines)</summary>

```python
"""Recheck the Mamba paper (arXiv v2): training budget, parameter
counts, Theorem 1, discretization, the Table 3 averages and best-in-class
claim, and state size"""
import math

import numpy as np

def pad(s, width):
    """pad to a display width (CJK counts two)"""
    return s + " " * (width - sum(2 if ord(c) > 0x2e80 else 1 for c in s))

# ---- 1 ----
print("1. Table 12: budget of the scaling-law runs")
TOK = 2 ** 19  # paper: 0.5M tokens per step, taken as 2^19
T12 = [("125M", 125e6, 4800, 2.5e9), ("350M", 350e6, 13500, 7e9),
       ("760M", 760e6, 29000, 15e9), ("1.3B", 1.3e9, 50000, 26e9)]
print("   " + pad("size", 7) + pad("steps", 8)
      + pad("steps x 2^19", 14) + pad("paper", 8)
      + "tokens/param")
worst = 0.0
for name, p, steps, paper in T12:
    tok = steps * TOK
    worst = max(worst, abs(tok / paper - 1))
    print("   " + pad(name, 7) + pad(f"{steps:,}", 8)
          + pad(f"{tok / 1e9:.2f}B", 14) + pad(f"{paper / 1e9:.1f}B", 8)
          + f"{paper / p:.1f}")
print(f"   largest gap {worst:.1%}; with 0.5M = 500,000, "
      f"4800 steps give only {4800 * 5e5 / 1e9:.2f}B")

# ---- 2 ----
print("\n2. Counting parameters from the block, checked against the Hub")

def mamba_params(d, layers, vocab=50280, e=2, n=16, k=4, r=None):
    ed = e * d
    r = math.ceil(d / 16) if r is None else r
    parts = {"in_proj": d * 2 * ed, "conv1d (w+b)": ed * k + ed,
             "x_proj": ed * (r + 2 * n), "dt_proj (w+b)": r * ed + ed,
             "A_log": ed * n, "D": ed, "out_proj": ed * d, "norm": d}
    per = sum(parts.values())
    return parts, per, layers * per + vocab * d + d

# config: config.json of state-spaces/mamba-*-hf; 
# totals: Hub API field safetensors.total, queried 2026-11-13
CK = [("130M", 768, 24, 129_135_360), ("370M", 1024, 48, 371_516_416),
      ("790M", 1536, 48, 793_204_224), ("1.4B", 2048, 48, 1_372_178_432),
      ("2.8B", 2560, 64, 2_768_345_600)]
parts, per, total = mamba_params(768, 24)
print("   130M (D=768, 24 layers), parameters per layer")
for key, v in parts.items():
    print(f"     {key:<14}{v:>10,}  {v / per:6.1%}")
print(f"     {'per layer':<14}{per:>10,}")
print(f"   24 x {per:,} + 50,280 x 768 + 768 = {total:,}")
print("   " + pad("size", 6) + pad("formula", 15)
      + pad("Hub", 15) + pad("diff", 6) + pad("3ED^2/layer", 12)
      + "embed")
for name, d, layers, hub in CK:
    _, per, total = mamba_params(d, layers)
    print("   " + pad(name, 6) + pad(f"{total:,}", 15) + pad(f"{hub:,}", 15)
          + pad(f"{total - hub}", 6) + pad(f"{3 * 2 * d * d / per:.1%}", 12)
          + f"{50280 * d / total:.1%}")
_, per, _ = mamba_params(768, 24)
tf = 12 * 768 ** 2
more = 2 * per / tf - 1
print(f"   two Mamba blocks {2 * per:,} vs one Transformer layer "
      f"12D^2 = {tf:,} (+{more:.1%})")

# ---- 3 ----
print("\n3. Parameter columns of Tables 9, 10 (D=1024, 48 layers)")
T9 = {0: 358.9, 1: 359.1, 2: 359.3, 4: 359.7, 8: 360.5, 16: 362.1,
      32: 365.2, 64: 371.5}
T10 = {1: 367.1, 2: 367.4, 4: 368.0, 8: 369.1, 16: 371.5}

def params_m(r=64, n=16):
    return mamba_params(1024, 48, n=n, r=r)[2] / 1e6

head = ("formula", "paper", "match")
print("   " + pad("Delta projection r (0 = none)", 32)
      + pad(head[0], 10) + pad(head[1], 8) + head[2])
for r, paper in T9.items():
    mine = params_m(r=r)
    ok = abs(mine - paper) < 0.05 + 1e-9
    print("   " + pad(str(r), 32) + pad(f"{mine:.2f}", 10)
          + pad(f"{paper:.1f}", 8) + ("yes" if ok else "no"))
print("   " + pad("state dimension N", 32)
      + pad(head[0], 10) + pad(head[1], 8) + head[2])
for n, paper in T10.items():
    mine = params_m(n=n)
    ok = abs(mine - paper) < 0.05 + 1e-9
    print("   " + pad(str(n), 32) + pad(f"{mine:.2f}", 10)
          + pad(f"{paper:.1f}", 8) + ("yes" if ok else "no"))
extra = params_m(n=16) / params_m(n=1) - 1
print(f"   N from 1 to 16 adds only {extra:.1%} to the parameters")

# ---- 4 ----
print("\n4. Theorem 1: a selective SSM with N=1, A=-1, B=1 is a gated RNN")
rng = np.random.default_rng(0)
T = 500
x = rng.normal(size=T)
w, b = rng.normal(), rng.normal()
z = w * x + b
delta = np.log1p(np.exp(z))  # softplus
A, Bp = -1.0, 1.0
h_zoh = h_euler = h_gate = 0.0
err_zoh = err_euler = 0.0
for t in range(T):
    a_bar = math.exp(delta[t] * A)
    b_zoh = (a_bar - 1.0) / A * Bp  # (dA)^-1 (exp(dA) - 1) dB
    b_euler = delta[t] * Bp
    g = 1.0 / (1.0 + math.exp(-z[t]))
    h_zoh = a_bar * h_zoh + b_zoh * x[t]
    h_euler = a_bar * h_euler + b_euler * x[t]
    h_gate = (1.0 - g) * h_gate + g * x[t]
    err_zoh = max(err_zoh, abs(h_zoh - h_gate))
    err_euler = max(err_euler, abs(h_euler - h_gate))
print(f"   {T} random inputs, w={w:.3f}, b={b:.3f}")
print(f"   ZOH: max |h_ssm - h_gate| = {err_zoh:.1e}")
print(f"   official code, B-bar = delta*B (Euler): max error {err_euler:.2f} "
      f"(delta up to {delta.max():.2f})")

# ---- 5 ----
print("\n5. Discretization: ZOH in the paper versus delta*B in the code")
An = -(np.arange(16) + 1.0)  # S4D-Real
dts = np.exp(np.linspace(math.log(1e-3), math.log(1e-1), 1000))
ratio = np.expm1(np.outer(dts, An)) / np.outer(dts, An)
print("   init range: A_n = -(n+1), n = 0..15; delta in [0.001, 0.1]")
print(f"   B_zoh / B_euler = (exp(dA) - 1) / (dA): min {ratio.min():.3f}, "
      f"median {np.median(ratio):.3f}")
for tol in (0.01, 0.1):
    share = (np.abs(ratio - 1) > tol).mean()
    print(f"   (delta, n) pairs differing by more than {tol:.0%}: {share:.1%}")

# ---- 6 ----
print("\n6. Table 3: the averages and the best-in-class claim")
COLS = ["Pile ppl", "LAMBADA ppl", "LAMBADA acc", "HellaSwag", "PIQA", "Arc-E",
        "Arc-C", "WinoGrande"]
R3 = [
    ("Hybrid H3-130M", None, 89.48, 25.77, 31.7, 64.2, 44.4, 24.2, 50.6, 40.1),
    ("Pythia-160M", 29.64, 38.10, 33.0, 30.2, 61.4, 43.2, 24.1, 51.9, 40.6),
    ("Mamba-130M", 10.56, 16.07, 44.3, 35.3, 64.5, 48.0, 24.3, 51.9, 44.7),
    ("Hybrid H3-360M", None, 12.58, 48.0, 41.5, 68.1, 51.4, 24.7, 54.1, 48.0),
    ("Pythia-410M", 9.95, 10.84, 51.4, 40.6, 66.9, 52.1, 24.6, 53.8, 48.2),
    ("Mamba-370M", 8.28, 8.14, 55.6, 46.5, 69.5, 55.1, 28.0, 55.3, 50.0),
    ("Pythia-1B", 7.82, 7.92, 56.1, 47.2, 70.7, 57.0, 27.1, 53.5, 51.9),
    ("Mamba-790M", 7.33, 6.02, 62.7, 55.1, 72.1, 61.2, 29.5, 56.1, 57.1),
    ("GPT-Neo 1.3B", None, 7.50, 57.2, 48.9, 71.1, 56.2, 25.9, 54.9, 52.4),
    ("Hybrid H3-1.3B", None, 11.25, 49.6, 52.6, 71.3, 59.2, 28.1, 56.9, 53.0),
    ("OPT-1.3B", None, 6.64, 58.0, 53.7, 72.4, 56.7, 29.6, 59.5, 55.0),
    ("Pythia-1.4B", 7.51, 6.08, 61.7, 52.1, 71.0, 60.5, 28.5, 57.2, 55.2),
    ("RWKV-1.5B", 7.70, 7.04, 56.4, 52.5, 72.4, 60.5, 29.4, 54.6, 54.3),
    ("Mamba-1.4B", 6.80, 5.04, 64.9, 59.1, 74.2, 65.5, 32.8, 61.5, 59.7),
    ("GPT-Neo 2.7B", None, 5.63, 62.2, 55.8, 72.1, 61.1, 30.2, 57.6, 56.5),
    ("Hybrid H3-2.7B", None, 7.92, 55.7, 59.7, 73.3, 65.6, 32.3, 61.4, 58.0),
    ("OPT-2.7B", None, 5.12, 63.6, 60.6, 74.8, 60.8, 31.3, 61.0, 58.7),
    ("Pythia-2.8B", 6.73, 5.04, 64.7, 59.3, 74.0, 64.1, 32.9, 59.7, 59.1),
    ("RWKV-3B", 7.00, 5.24, 63.9, 59.6, 73.7, 67.8, 33.1, 59.6, 59.6),
    ("Mamba-2.8B", 6.22, 4.23, 69.2, 66.1, 75.2, 69.7, 36.3, 63.5, 63.3),
    ("GPT-J-6B", None, 4.10, 68.3, 66.3, 75.4, 67.0, 36.6, 64.1, 63.0),
    ("OPT-6.7B", None, 4.25, 67.7, 67.2, 76.3, 65.6, 34.9, 65.5, 62.9),
    ("Pythia-6.9B", 6.51, 4.45, 67.1, 64.0, 75.2, 67.3, 35.5, 61.3, 61.7),
    ("RWKV-7.4B", 6.31, 4.38, 67.2, 65.5, 76.1, 67.8, 37.5, 61.0, 62.5),
]
GROUPS = [("130M", 0, 3), ("370M", 3, 6), ("790M", 6, 8), ("1.4B", 8, 14),
          ("2.8B", 14, 20)]
bad, gap = [], 0.0
for row in R3:
    mean = sum(row[3:9]) / 6  # plain mean of the six accuracies
    gap = max(gap, abs(mean - row[9]))
    if abs(mean - row[9]) > 0.05 + 1e-9:
        bad.append((row[0], mean, row[9]))
print(f"   {len(bad)} of {len(R3)} rows differ from the recomputed mean "
      f"by over 0.05; largest gap {gap:.3f}")
for name, mean, paper in bad:
    print(f"     {name}: recomputed {mean:.2f}, paper {paper}")
LOWER = {0, 1}  # the two perplexities: lower is better
n_best = n_tie = n_cmp = 0
for gname, lo, hi in GROUPS:
    rows = R3[lo:hi]
    m = next(r for r in rows if r[0].startswith("Mamba"))
    for ci, col in enumerate(COLS):
        vals = [(r[1 + ci], r[0]) for r in rows if r[1 + ci] is not None]
        sign = -1 if ci in LOWER else 1
        n_cmp += 1
        best = max(sign * v for v, _ in vals)
        winners = [nm for v, nm in vals if sign * v == best]
        if sign * m[1 + ci] < best:
            print(f"     {gname} {col}: Mamba is not the best ({winners[0]})")
        else:
            n_best += 1
            if len(winners) > 1:
                n_tie += 1
                other = [w for w in winners if not w.startswith("Mamba")][0]
                print(f"     {gname} {col}: tied ({m[1 + ci]} = {other})")
print(f"   Mamba is best or tied in {n_best} of {n_cmp} cells (size, column); "
      f"ties: {n_tie}")
m28, big = R3[19], R3[20:24]
wins, rest = [], []
for ci, col in enumerate(COLS + ["Average"]):
    idx = 1 + ci
    sign = -1 if ci in LOWER else 1
    vals = [(r[idx], r[0]) for r in big if r[idx] is not None]
    if sign * m28[idx] > max(sign * v for v, _ in vals):
        wins.append(col)
    else:
        top = max(vals, key=lambda p: sign * p[0])
        f = "{:.2f}" if ci in LOWER else "{:.1f}"
        a, b = f.format(top[0]), f.format(m28[idx])
        rest.append(f"{col}: {top[1]} {a} vs {b}")
k, n = len(wins), len(wins) + len(rest)
print(f"   Mamba-2.8B vs the four 6-7B models, best in {k}/{n} columns:")
print(f"     {', '.join(wins)}")
print("     trailing columns (rival vs Mamba-2.8B)")
for line in rest:
    print(f"       {line}")

# ---- 7 ----
print("\n7. State size: Mamba's fixed state versus Pythia's KV cache")
# Pythia layers and widths from EleutherAI/pythia-* config.json, same day
PY = {"160M": (12, 768), "410M": (24, 1024), "1B": (16, 2048),
      "1.4B": (24, 2048), "2.8B": (32, 2560)}
PAIRS = [("130M", "160M"), ("370M", "410M"), ("790M", "1B"),
         ("1.4B", "1.4B"), ("2.8B", "2.8B")]
print("   " + pad("Mamba", 7) + pad("Pythia", 8) + pad("Mamba state", 16)
      + pad("KV/token", 14) + "break-even")
for mname, pname in PAIRS:
    _, d, layers, _ = next(c for c in CK if c[0] == mname)
    # official per-layer state: SSM state ED x N plus conv cache ED x d_conv
    state = layers * 2 * d * (16 + 4)
    pl, pd = PY[pname]
    kv = 2 * pl * pd
    print("   " + pad(mname, 7) + pad(pname, 8) + pad(f"{state:,}", 16)
          + pad(f"{kv:,}", 14) + f"{state / kv:.2f}")
_, d, layers, _ = CK[4]
state = layers * 2 * d * (16 + 4)
kv = 2 * 32 * 2560
mib, kv2k = state * 2 / 2 ** 20, kv * 2048
kib, be8 = kv2k * 2 / 2 ** 20, state / (kv / 8)
print(f"   Mamba-2.8B state: {state:,} numbers, {mib:.2f} MiB at 16 bits")
print(f"   Pythia-2.8B KV cache at 2,048 tokens: {kv2k:,} numbers, "
      f"{kib:.0f} MiB")
print(f"   hypothetical 8x fewer KV heads (GQA): break-even {be8:.0f} tokens")
ED, NS = 2 * d, 16
big_t, io = 8 * 2048 * ED * NS, 8 * 2048 * ED
gib = 2 * big_t * 4 / 2 ** 30
print(f"   expanded state in GPU memory (B=8, L=2048, ED={ED}, N={NS})")
print(f"     {big_t:,} numbers per tensor, {big_t // io}x the input; "
      f"Abar and Bbar*x: {gib:.1f} GiB (fp32)")
```

</details>

### Training budget and parameter counts

```text
1. Table 12: budget of the scaling-law runs
   size   steps   steps x 2^19  paper   tokens/param
   125M   4,800   2.52B         2.5B    20.0
   350M   13,500  7.08B         7.0B    20.0
   760M   29,000  15.20B        15.0B   19.7
   1.3B   50,000  26.21B        26.0B   20.0
   largest gap 1.4%; with 0.5M = 500,000, 4800 steps give only 2.40B
```

The training budget of Table 12 matches the paper: steps times $2^{19}\approx 0.52$M tokens per step deviates by at most 1.4% over the four sizes, at about 20 tokens per parameter, in line with the Chinchilla protocol. If “0.5M” is read as 500,000, the 4800 steps of the 125M model give only 2.40B and do not match the 2.5B in the paper, so each batch is $2^{19}$ tokens.

```text
2. Counting parameters from the block, checked against the Hub
   130M (D=768, 24 layers), parameters per layer
     in_proj        2,359,296   62.6%
     conv1d (w+b)       7,680    0.2%
     x_proj           122,880    3.3%
     dt_proj (w+b)     75,264    2.0%
     A_log             24,576    0.7%
     D                  1,536    0.0%
     out_proj       1,179,648   31.3%
     norm                 768    0.0%
     per layer      3,771,648
   24 x 3,771,648 + 50,280 x 768 + 768 = 129,135,360
   size  formula        Hub            diff  3ED^2/layer embed
   130M  129,135,360    129,135,360    0     93.8%       29.9%
   370M  371,516,416    371,516,416    0     94.4%       13.9%
   790M  793,204,224    793,204,224    0     94.9%       9.7%
   1.4B  1,372,178,432  1,372,178,432  0     95.2%       7.5%
   2.8B  2,768,345,600  2,768,345,600  0     95.3%       4.6%
   two Mamba blocks 7,543,296 vs one Transformer layer 12D^2 = 7,077,888 (+6.6%)
```

**The parameter count reproduces exactly.** A layer has 8 groups of parameters (input projection, depthwise convolution, the projection of $x$, the projection of $\Delta$, $A$, $D$, output projection, normalization); at 130M a layer has 3,771,648, and with the embedding and the final norm the total is 129,135,360, exactly equal to the Hub; the 370M, 790M, 1.4B and 2.8B sizes also differ by 0. The input and output projections make up 93.8% to 95.3% of a layer, consistent with the paper's “the bulk is $3ED^2$”; the embedding is 29.9% of the 130M model and only 4.6% at 2.8B. Two Mamba blocks have 7,543,296 parameters and one Transformer layer's $12D^2$ is 7,077,888, so the former is 6.6% larger: the paper's “two blocks match $12D^2$” is a correspondence in order of magnitude, not an equality, and the extra is the SSM's own parameters and the convolution.

```text
3. Parameter columns of Tables 9, 10 (D=1024, 48 layers)
   Delta projection r (0 = none)   formula   paper   match
   0                               358.93    358.9   yes
   1                               359.13    359.1   yes
   2                               359.33    359.3   yes
   4                               359.72    359.7   yes
   8                               360.51    360.5   yes
   16                              362.08    362.1   yes
   32                              365.22    365.2   yes
   64                              371.52    371.5   yes
   state dimension N               formula   paper   match
   1                               367.09    367.1   yes
   2                               367.39    367.4   yes
   4                               367.98    368.0   yes
   8                               369.16    369.1   no
   16                              371.52    371.5   yes
   N from 1 to 16 adds only 1.2% to the parameters
```

**The parameter columns of Tables 9 and 10 almost all match.** With one formula (the $\Delta$ projection dimension $r$ or the state dimension $N$ varies, everything else fixed), 12 of the 13 numbers agree with the paper. The odd one is the $N=8$ row of Table 10: the formula gives 369.16, which rounds to 369.2, while the paper prints 369.1, a difference only in the last digit; I did not find the reason (perhaps truncation) and it changes no conclusion. Going from $N=1$ to 16 adds only 1.2% to the total parameters, matching the paper's “only about 1% more parameters”.

### Theorem 1 and discretization

```text
4. Theorem 1: a selective SSM with N=1, A=-1, B=1 is a gated RNN
   500 random inputs, w=1.293, b=0.454
   ZOH: max |h_ssm - h_gate| = 6.7e-16
   official code, B-bar = delta*B (Euler): max error 10.55 (delta up to 4.43)
```

**Theorem 1 holds exactly under ZOH.** On 500 steps of random input the selective SSM and the gated RNN differ by at most 6.7e-16, which is floating-point error. But the official code is not implemented this way:

```text
5. Discretization: ZOH in the paper versus delta*B in the code
   init range: A_n = -(n+1), n = 0..15; delta in [0.001, 0.1]
   B_zoh / B_euler = (exp(dA) - 1) / (dA): min 0.499, median 0.967
   (delta, n) pairs differing by more than 1%: 76.4%
   (delta, n) pairs differing by more than 10%: 26.2%
```

**The official discretization differs from the paper's equation (4).** In the `state-spaces/mamba` repository (the reference implementation in `selective_scan_interface.py` and `mamba_simple.py`, read in November 2026) $\bar A$ is still $\exp(\Delta A)$, but $\bar B\,x$ is `delta * B * u`, that is $\bar B=\Delta B$ (a first-order Euler approximation), not the $(\Delta A)^{-1}(\exp(\Delta A)-I)\Delta B$ of equation (4). The ratio of the two is $(e^{\Delta A}-1)/(\Delta A)$: over the paper's initialization range ($A_n=-(n+1)$ for $n=0$ to 15 and $\Delta$ from 0.001 to 0.1) it is at least 0.499 with a median of 0.967, and 76.4% of the $(\Delta,n)$ combinations differ by more than 1% and 26.2% by more than 10%. In training $B$ is learned and its scale can absorb the difference, so this need not affect quality; but the “exactly a gated RNN” of Theorem 1 holds only for ZOH and only approximately for the official implementation when $\Delta$ is small (in the 500-step test above, the maximum deviation with $\bar B=\Delta B$ is 10.55, where $\Delta$ reaches 4.43). The initialization of $\Delta$ in the code also differs from the literal text: the code draws $\log\Delta$ uniformly between $\log 0.001$ and $\log 0.1$ (log-uniform), while the paper writes $\mathrm{Uniform}([0.001, 0.1])$. My small experiment follows the code on both points.

### Table 3 and state size

```text
6. Table 3: the averages and the best-in-class claim
   2 of 24 rows differ from the recomputed mean by over 0.05; largest gap 1.667
     Mamba-370M: recomputed 51.67, paper 50.0
     Mamba-790M: recomputed 56.12, paper 57.1
     130M WinoGrande: tied (51.9 = Pythia-160M)
   Mamba is best or tied in 40 of 40 cells (size, column); ties: 1
   Mamba-2.8B vs the four 6-7B models, best in 4/9 columns:
     Pile ppl, LAMBADA acc, Arc-E, Average
     trailing columns (rival vs Mamba-2.8B)
       LAMBADA ppl: GPT-J-6B 4.10 vs 4.23
       HellaSwag: OPT-6.7B 67.2 vs 66.1
       PIQA: OPT-6.7B 76.3 vs 75.2
       Arc-C: RWKV-7.4B 37.5 vs 36.3
       WinoGrande: OPT-6.7B 65.5 vs 63.5
```

**Two rows of Table 3 have averages that do not match.** “Average” is the mean of the six accuracy columns (LAMBADA, HellaSwag, PIQA, Arc-E, Arc-C, WinoGrande). Of 24 rows, 22 agree with the recomputation to within 0.05; Mamba-370M recomputes to 51.67 and the paper prints 50.0; Mamba-790M recomputes to 56.12 and the paper prints 57.1. I compared these two on the PDF page and the paper does print them that way. Neither changes the ranking: the 51.67 for 370M is still above its same-size opponents, and 56.12 for 790M is above Pythia-1B's 51.9.

**“Best at every size” depends on the opponent.** Within a size group (130M, 370M, 790M, 1.4B and 2.8B each against opponents of the same size), Mamba is best or tied for best in 40 of the 40 (size, column) cells, with one tie (WinoGrande at 130M, 51.9, the same as Pythia-160M). But the abstract says “matches Transformers twice its size”: against the four 6-7B models (GPT-J-6B, OPT-6.7B, Pythia-6.9B, RWKV-7.4B), Mamba-2.8B is best in only 4 of 9 columns (Pile perplexity, LAMBADA accuracy, Arc-E and the average); it loses LAMBADA perplexity to GPT-J-6B (4.10 against 4.23), HellaSwag and PIQA to OPT-6.7B, Arc-C to RWKV-7.4B and WinoGrande to OPT-6.7B. “Average equal to a twice-larger model” holds; “better across the board” does not.

```text
7. State size: Mamba's fixed state versus Pythia's KV cache
   Mamba  Pythia  Mamba state     KV/token      break-even
   130M   160M    737,280         18,432        40.00
   370M   410M    1,966,080       49,152        40.00
   790M   1B      2,949,120       65,536        45.00
   1.4B   1.4B    3,932,160       98,304        40.00
   2.8B   2.8B    6,553,600       163,840       40.00
   Mamba-2.8B state: 6,553,600 numbers, 12.50 MiB at 16 bits
   Pythia-2.8B KV cache at 2,048 tokens: 335,544,320 numbers, 640 MiB
   hypothetical 8x fewer KV heads (GQA): break-even 320 tokens
   expanded state in GPU memory (B=8, L=2048, ED=5120, N=16)
     1,342,177,280 numbers per tensor, 16x the input; Abar and Bbar*x: 10.0 GiB (fp32)
```

**Mamba's state is fixed and the KV cache is not.** With the inference cache of the official implementation (16 SSM states per channel per layer plus a width-4 convolution cache), Mamba-2.8B holds 6,553,600 numbers, 12.5 MiB at 16 bits, whatever the length; Pythia-2.8B stores 163,840 numbers per token, so the two are equal at the 40th token and at 2,048 tokens it holds 335,544,320 numbers, 640 MiB. The break-even is 40 to 45 tokens at all five sizes: Mamba has about twice as many layers as a same-size Transformer (two blocks correspond to one layer), the state per layer is $ED\times 20=40D$ numbers and a Transformer stores $2D$ numbers per token per layer, so the ratio is about $2\times 20=40$; Mamba-790M against Pythia-1B differ in hidden size and give 45. If the opponent used GQA with an eighth of the KV heads (hypothetical, Pythia has none) the break-even would be 320 tokens, still far below any real context. The last lines are the cost in the other direction: if the expanded state were written back to memory (batch 8, length 2048), each tensor would hold 1.34 billion numbers, 16 times the input, and two tensors would take 10.0 GiB (fp32), which is exactly what the hardware-aware scan avoids.

## Hands-on reproduction: what selection actually buys

Table 1 of the paper swaps only the sequence layer inside a fixed block, to isolate the effect of selection. We do the same thing at a scale a laptop CPU can train in minutes: the **task** is selective copying, the **block** is a Mamba-style block (LayerNorm, input projection, a width-4 depthwise convolution, the sequence layer, multiplication with a SiLU gate, output projection, residual), and the **variable** is the sequence layer, in five versions:

| Sequence layer | What it is |
| --- | --- |
| LTI diagonal SSM | $\Delta$, $B$, $C$ are all fixed parameters ($B$ and $C$ per channel), the S4 family's form |
| LTI global conv | one free convolution kernel per channel, as long as the sequence; it can express any LTI map, so it is the stronger LTI control |
| Selective $\Delta$ only | $\Delta$ is computed from the current token, $B$ and $C$ are fixed |
| Selective $B$, $C$ only | $B$ and $C$ are computed from the current token (shared across channels), $\Delta$ is fixed; this is the cell Table 7 of the paper does not have |
| S6 (all selective) | $\Delta$, $B$, $C$ are all computed from the current token, i.e. Algorithm 2 |

The table below lists how this differs from the paper. It is a small toy for seeing the mechanism, not a way to confirm or refute the paper's claims at length 4096:

| | Paper (Table 1, Appendix E.1) | Here |
| --- | --- | --- |
| Task | length 4096, vocabulary 16 (including the noise token), memorize 16 data tokens | 6 data tokens (values 1 to 8) placed at random among 32 positions, the rest noise 0, then a delimiter and 6 blank slots to fill in order |
| Model | 2 layers, $D=64$, three block designs | 2 Mamba-style blocks, $D=32$, $E=2$, $N=8$, 17,098 to 18,890 parameters |
| Comparison | swap only the sequence layer: S4, Hyena (LTI) vs S6 | five sequence layers inside the same block |
| Training | 400K steps, batch 64, constant learning rate 1e-4 | 3000 steps (LTI controls also get 9000), batch 64, learning rate 3e-3, 100 warm-up steps then cosine to 10% |
| Repeats | one number per cell | 3 seeds per cell, mean and min-max |
| Metric | accuracy | 1000 fixed test strings, a string counts only if all 6 tokens are right; per-token accuracy listed separately |

There is also a control task, **fixed-position copying** (the classic Copying task): the data tokens always occupy the first 6 positions and everything else is unchanged. The selective variants use the official code's $\bar B=\Delta B$ and its log-uniform initialization of $\Delta$ (see the checks above); sharing $B$ and $C$ across channels is the selective design (the shape in Algorithm 2 of the paper), while fixed $B$ and $C$ get one copy per channel (the shape in Algorithm 1). The LTI models get 3 times as many steps to separate "learns slowly" from "cannot learn". Chance level is 12.5% per token and 0.0004% per string.

The script first runs two checks. The loop version (a scan unrolled with `unbind`) differs from an einsum reference in the style of the official `selective_scan_ref` by at most 2.2e-16 (double precision); and the causality test replaces the last 12 inputs and finds that the first 20 outputs change by 0. Environment: Apple M2 Max, CPU, 6 processes with 1 thread each running in parallel, every job with its own fixed seed so that results do not depend on scheduling; Python 3.14.3, PyTorch 2.10.0, NumPy 2.4.2. On another machine or PyTorch version, individual numbers may differ slightly.

<details>
<summary>Full code (about 225 lines)</summary>

```python
"""Small-scale rerun of the Selective Copying task in the Mamba paper:
inside one Mamba-style block, swap the SSM for an LTI diagonal SSM, an LTI
global convolution and three selective variants, 3 seeds each (CPU)"""
import math
import time
from concurrent.futures import ProcessPoolExecutor

import numpy as np
import torch
import torch.nn.functional as F
from torch import nn

D, E, N, KER, LAYERS = 32, 2, 8, 4, 2
L, K, V = 32, 6, 8  # input length, tokens to copy, data symbols 1..V
DELIM, T = V + 1, L + 1 + K
STEPS, BATCH, LR, SEEDS = 3000, 64, 3e-3, (0, 1, 2)
# layer type, selective Delta, selective B and C
KINDS = {"lti_ssm": ("ssm", False, False), "lti_conv": ("conv", False, False),
         "sel_delta": ("ssm", True, False), "sel_bc": ("ssm", False, True),
         "s6": ("ssm", True, True)}
NAMES = {"lti_ssm": "LTI diagonal SSM",
         "lti_conv": "LTI global conv",
         "sel_delta": "selective Delta only",
         "sel_bc": "selective B, C only",
         "s6": "S6 (all selective)"}
TASKS = {"copy": False, "selective": True}
# rows per task: (model, steps); LTI models also get 3x the steps as a check
ROWS = {"copy": [(k, STEPS) for k in ("lti_ssm", "lti_conv", "s6")],
        "selective": [(k, STEPS) for k in KINDS]
        + [("lti_ssm", 3 * STEPS), ("lti_conv", 3 * STEPS)]}

def batch(rng, bs, selective):
    """K data tokens among L positions (rest 0), a delimiter, K blanks"""
    x = np.zeros((bs, T), dtype=np.int64)
    y = np.zeros((bs, K), dtype=np.int64)
    for i in range(bs):
        pos = np.sort(rng.choice(L, K, replace=False)) if selective \
            else np.arange(K)
        data = rng.integers(1, V + 1, K)
        x[i, pos] = data
        y[i] = data
    x[:, L] = DELIM
    return torch.from_numpy(x), torch.from_numpy(y)

class SSM(nn.Module):
    """diagonal SSM: Delta, B, C are
    input-dependent (selective) or fixed parameters (LTI)"""

    def __init__(self, sel_delta, sel_bc):
        super().__init__()
        ed, self.r = E * D, math.ceil(D / 16)
        self.sd, self.sb = sel_delta, sel_bc
        self.A_log = nn.Parameter(
            torch.log(torch.arange(1, N + 1.0)).repeat(ed, 1))
        self.D = nn.Parameter(torch.ones(ed))
        dt = torch.exp(torch.rand(ed) * (math.log(0.1) - math.log(1e-3))
                       + math.log(1e-3))
        self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))
        width = (self.r if sel_delta else 0) + (2 * N if sel_bc else 0)
        if width:
            self.x_proj = nn.Linear(ed, width, bias=False)
        if sel_delta:
            self.dt_proj = nn.Linear(self.r, ed, bias=False)
        if not sel_bc:
            self.B = nn.Parameter(torch.randn(ed, N) / math.sqrt(N))
            self.C = nn.Parameter(torch.randn(ed, N) / math.sqrt(N))

    def gates(self, x):
        b, t, ed = x.shape
        proj = self.x_proj(x) if self.sd or self.sb else None
        if self.sd:
            dt, proj = proj.split([self.r, proj.shape[-1] - self.r], -1)
            delta = F.softplus(self.dt_proj(dt) + self.dt_bias)
        else:
            delta = F.softplus(self.dt_bias).expand(b, t, ed)
        if self.sb:
            Bm, Cm = proj.split([N, N], -1)
            return delta, Bm[:, :, None, :], Cm[:, :, None, :]
        return delta, self.B, self.C

    def forward(self, x):
        delta, Bm, Cm = self.gates(x)
        A = -torch.exp(self.A_log)
        dA = torch.exp(delta[..., None] * A).unbind(1)
        dBx = (delta[..., None] * Bm * x[..., None]).unbind(1)
        Cs = Cm.unbind(1) if self.sb else [Cm] * x.shape[1]
        h, ys = x.new_zeros(x.shape[0], x.shape[2], N), []
        for i in range(x.shape[1]):
            h = dA[i] * h + dBx[i]
            ys.append((h * Cs[i]).sum(-1))
        return torch.stack(ys, 1) + x * self.D

class GlobalConv(nn.Module):
    """LTI: one free kernel of length T per channel"""

    def __init__(self):
        super().__init__()
        self.k = nn.Parameter(torch.randn(E * D, 1, T) / math.sqrt(T))
        self.D = nn.Parameter(torch.ones(E * D))

    def forward(self, x):
        y = F.conv1d(F.pad(x.transpose(1, 2), (T - 1, 0)), self.k,
                     groups=x.shape[2])
        return y.transpose(1, 2) + x * self.D

class Block(nn.Module):
    def __init__(self, kind):
        super().__init__()
        layer, sd, sb = KINDS[kind]
        self.norm = nn.LayerNorm(D)
        self.inp = nn.Linear(D, 2 * E * D, bias=False)
        self.conv = nn.Conv1d(E * D, E * D, KER, groups=E * D,
                              padding=KER - 1)
        self.ssm = GlobalConv() if layer == "conv" else SSM(sd, sb)
        self.out = nn.Linear(E * D, D, bias=False)

    def forward(self, u):
        x, z = self.inp(self.norm(u)).chunk(2, -1)
        x = F.silu(self.conv(x.transpose(1, 2))[..., :u.shape[1]])
        y = self.ssm(x.transpose(1, 2)) * F.silu(z)
        return u + self.out(y)

class Model(nn.Module):
    def __init__(self, kind):
        super().__init__()
        self.emb = nn.Embedding(V + 2, D)
        self.blocks = nn.Sequential(*[Block(kind) for _ in range(LAYERS)])
        self.norm = nn.LayerNorm(D)
        self.head = nn.Linear(D, V + 2)

    def forward(self, x):
        return self.head(self.norm(self.blocks(self.emb(x))))

def scan_ref(u, delta, A, B, C, Dskip):
    """follows the official selective_scan_ref, written with einsum"""
    dA = torch.exp(torch.einsum("bld,dn->bldn", delta, A))
    dBu = torch.einsum("bld,bln,bld->bldn", delta, B, u)
    h, ys = u.new_zeros(u.shape[0], u.shape[2], A.shape[1]), []
    for i in range(u.shape[1]):
        h = dA[:, i] * h + dBu[:, i]
        ys.append(torch.einsum("bdn,bn->bd", h, C[:, i]))
    return torch.stack(ys, 1) + u * Dskip

def run(job):
    kind, task, seed, steps = job
    torch.set_num_threads(1)
    torch.manual_seed(seed)
    rng = np.random.default_rng(100 + seed)
    model = Model(kind)
    opt = torch.optim.Adam(model.parameters(), lr=LR)
    sched = torch.optim.lr_scheduler.LambdaLR(
        opt, lambda s: min(1, (s + 1) / 100)
        * (0.1 + 0.45 * (1 + math.cos(math.pi * s / steps))))
    for _ in range(steps):
        x, y = batch(rng, BATCH, TASKS[task])
        loss = F.cross_entropy(model(x)[:, -K:].reshape(-1, V + 2),
                               y.reshape(-1))
        opt.zero_grad()
        loss.backward()
        opt.step()
        sched.step()
    x, y = batch(np.random.default_rng(999), 1000, TASKS[task])
    with torch.no_grad():
        hit = model(x)[:, -K:].argmax(-1) == y
    return (100 * hit.all(1).float().mean().item(),
            100 * hit.float().mean().item())

def pad(s, width):
    """pad to a display width (CJK counts two)"""
    return s + " " * (width - sum(2 if ord(c) > 0x2e80 else 1 for c in s))

def main():
    t0 = time.time()
    torch.manual_seed(0)
    m = SSM(True, True).double()
    x = torch.randn(2, 20, E * D, dtype=torch.double)
    delta, Bm, Cm = m.gates(x)
    ref = scan_ref(x, delta, -torch.exp(m.A_log), Bm[:, :, 0], Cm[:, :, 0],
                   m.D)
    gap = (m(x) - ref).abs().max().item()
    print(f"max gap, scan vs einsum reference: {gap:.1e}")
    print(pad("model", 24) + pad("params", 10)
          + "causality (change 12 inputs, change in the first 20 outputs)")
    for kind in KINDS:
        net = Model(kind).double()
        a = torch.randint(0, V + 2, (4, T))
        b = a.clone()
        b[:, 20:] = torch.randint(0, V + 2, (4, T - 20))
        gap = (net(a) - net(b))[:, :20].abs().max().item()
        n_par = sum(p.numel() for p in net.parameters())
        print(pad(NAMES[kind], 24) + pad(f"{n_par:,}", 10) + f"{gap:.1e}")
    jobs = [(k, t, s, n) for t in ROWS for k, n in ROWS[t] for s in SEEDS]
    jobs.sort(key=lambda j: -j[3])  # start the long jobs first
    with ProcessPoolExecutor(6) as pool:
        res = dict(zip(jobs, pool.map(run, jobs)))
    title = {"copy": "fixed-position copying (classic Copying)",
             "selective": "selective copying (random positions)"}
    for task in ROWS:
        print(f"\n{title[task]}")
        print(f"batch {BATCH}, 1000 fixed test strings; (min-max) over 3 seeds")
        print(f"a number after a model name is its step count, default {STEPS}")
        print(pad("model", 28) + pad("exact match %", 22)
              + "per-token %")
        for kind, n in ROWS[task]:
            ex, tk = zip(*[res[(kind, task, s, n)] for s in SEEDS])
            name = NAMES[kind] + (f" {n}" if n != STEPS else "")
            print(pad(name, 28)
                  + pad(f"{np.mean(ex):5.1f} ({min(ex):.1f}-{max(ex):.1f})", 22)
                  + f"{np.mean(tk):5.1f} ({min(tk):.1f}-{max(tk):.1f})")
    mins = (time.time() - t0) / 60
    print(f"\nchance: {100 / V:.1f}% per token, "
          f"{100 * V ** -K:.4f}% per string; wall time {mins:.0f} min")

if __name__ == "__main__":
    main()
```

</details>

Output (about 25 minutes, covering 24 selective-copying runs, 6 of them with 9000 steps, and 9 fixed-position runs):

```text
max gap, scan vs einsum reference: 2.2e-16
model                   params    causality (change 12 inputs, change in the first 20 outputs)
LTI diagonal SSM        17,098    0.0e+00
LTI global conv         18,890    0.0e+00
selective Delta only    17,610    0.0e+00
selective B, C only     17,098    0.0e+00
S6 (all selective)      17,610    0.0e+00

fixed-position copying (classic Copying)
batch 64, 1000 fixed test strings; (min-max) over 3 seeds
a number after a model name is its step count, default 3000
model                       exact match %         per-token %
LTI diagonal SSM             15.2 (5.3-26.5)       74.7 (67.9-82.4)
LTI global conv             100.0 (100.0-100.0)   100.0 (100.0-100.0)
S6 (all selective)          100.0 (100.0-100.0)   100.0 (100.0-100.0)

selective copying (random positions)
batch 64, 1000 fixed test strings; (min-max) over 3 seeds
a number after a model name is its step count, default 3000
model                       exact match %         per-token %
LTI diagonal SSM             16.3 (8.0-31.5)       74.7 (69.8-83.5)
LTI global conv              77.2 (74.0-81.2)      95.3 (94.7-96.2)
selective Delta only         80.6 (61.7-93.9)      96.3 (92.4-98.9)
selective B, C only          93.6 (81.9-99.8)      98.8 (96.6-100.0)
S6 (all selective)           99.5 (99.0-99.8)      99.9 (99.8-100.0)
LTI diagonal SSM 9000        80.5 (75.9-87.8)      96.1 (94.9-97.8)
LTI global conv 9000         95.6 (95.0-96.3)      99.2 (99.0-99.3)

chance: 12.5% per token, 0.0004% per string; wall time 25 min
```

*Figure: Figure 2: Exact-match accuracy on 1000 fixed test strings after training, with a different sequence layer inside the same Mamba-style block (a trailing number is the step count of a longer run). Gray is LTI, blue lets only some parameters be selective and pink is S6.*

**Reading the numbers.**

- **The selective variants learn fast, and consistently.** At 3000 steps S6 reaches 99.5% exact match, with the three seeds between 99.0 and 99.8, the only range that does not overlap any other variant's; selective $B$, $C$ only reaches 93.6% (81.9 to 99.8) and selective $\Delta$ only 80.6% (61.7 to 93.9), and both have a seed that barely learned. LTI global conv gets 77.2% (74.0 to 81.2) and the LTI diagonal SSM 16.3% (8.0 to 31.5).
- **LTI is not "unable", it is slow.** With 3 times as many steps (9000), LTI global conv rises to 95.6% (95.0 to 96.3), above the $B$, $C$ variant at 3000 steps, and the LTI diagonal SSM rises from 16.3% to 80.5%. This agrees in direction with the paper but not in size: there (length 4096, 16 data tokens, 400K steps) the LTI layers reach at most 57.0%. Here the sequence has only 32 positions and 6 data tokens, a much easier task, and a gated 2-layer block has enough ways to assemble an answer; we did not analyze how. So at this scale selection shows up first as "better results in the same number of steps", not "LTI can never learn it". Seeing the gap of the paper takes much longer sequences and many more data tokens.
- **Fixed-position copying really is the LTI strength.** LTI global conv scores 100.0% on fixed-position copying for all three seeds but only 77.2% once the positions are random, which is exactly the argument of Figure 2 in the paper (a kernel of the right length solves it, random positions break that); S6 is near perfect on both tasks (100.0% and 99.5%). The LTI diagonal SSM manages only 15.2% (5.3 to 26.5) even on fixed positions: it has 8 real decay states, and a sum of exponentials cannot build an exact delay, so this row mostly reflects the diagonal SSM's expressiveness and learning difficulty, not selection.
- **Which matters more, $B$, $C$ or $\Delta$? On this task, $B$, $C$.** 93.6% against 80.6%, but the three-seed ranges overlap (81.9 to 99.8 against 61.7 to 93.9), so this is only a hint. In the paper's language-modeling ablation (Table 7), selective $\Delta$ alone (9.81) beats selective $B$ alone (10.15) or selective $C$ alone (9.98), and the paper calls $\Delta$ the most important parameter; that is another task at another scale, and the table has no "selective $B$ and $C$" row, so neither result confirms or refutes the other. What we can say is that selecting all three (99.5%) beats any subset, in line with the paper's remark that multiple selective parameters together synergize.
- **Limits of samples and tuning.** 3 seeds per cell, 1000 test strings (one string is 0.1 percentage point), a single learning rate (3e-3, not tuned per model), and the 3x-steps control for LTI is not a tuned comparison either. The LTI models would probably do better with more careful tuning, so these numbers only say that "under the same hyperparameters the selective variants converge faster".

## Limits and what came next

- **Scale.** The paper's scaling laws stop at 1.3B and the zero-shot comparison at 2.8B; the discussion itself says the evaluation is below the size of most strong open-source LLMs (Llama, and RWKV and RetNet have been evaluated at 7B and beyond), that it “remains to assess whether Mamba still compares favorably at these larger sizes”, and that scaling SSMs may involve engineering challenges and model adjustments the paper does not discuss.
- **Fixed state versus verbatim recall.** The state has only $D\cdot N$ numbers, and however long the input, the information it can hold is bounded. Jelassi et al. (arXiv 2402.01032) prove that a two-layer Transformer can copy strings of exponential length while models with a fixed-size state are fundamentally limited by it, and observe on pretrained large models that Transformers do dramatically better at copying and retrieval. NVIDIA trained 8B Mamba, Mamba-2 and Transformer models on the same data (arXiv 2406.07887): pure SSMs match or exceed Transformers on many tasks but lag on tasks that need strong copying or in-context learning (such as 5-shot MMLU and Phonebook) and on long-context reasoning; the 8B Mamba-2-Hybrid (43% Mamba-2, 7% attention, 50% MLP) beats the 8B Transformer on all 12 standard tasks (+2.65 points on average) and is predicted to be up to 8 times faster at generation.
- **The continuous-discrete trade-off.** The paper's “no free lunch” section admits that selection overcomes the weakness of SSMs on discrete data such as text and DNA but can hurt on data where LTI models excel (continuous signals such as audio), and its ablation on audio shows the trade-off.
- **Complex versus real.** The paper uses real-valued SSMs by default, which work for all but one of its tasks, and conjectures that complex values help continuous modalities but not discrete ones.
- **Speed numbers depend on hardware and implementation.** The 20-40 times and 4-5 times are A100 results against the PyTorch and Hugging Face implementations of the time; Transformer inference today (continuous batching, PagedAttention, GQA, MLA) is much stronger than the paper's baseline, and the comparison needs repeating with same-generation implementations (see [KV cache](https://dmxsf.com/en/wiki/inference/kv-cache/)).
- **Follow-ups.** Mamba-2 (arXiv 2405.21060) introduces state space duality, and its core layer is 2 to 8 times faster than Mamba's selective SSM while staying competitive with Transformers in language modeling; Jamba (arXiv 2403.19887) is a large hybrid that interleaves Transformer and Mamba layers and adds mixture-of-experts. These directions are covered in [State space models and hybrid architectures](https://dmxsf.com/en/wiki/architecture/state-space-and-hybrid/).

## What to take away

1. **LTI treats inputs by position, not by content.** One kernel acts at every position, and tasks like selective copying, where positions are random and content decides what stays, are out of reach; the selection mechanism makes $\Delta$, $B$ and $C$ functions of the current token.
2. **$\Delta$ is a generalized RNN gate.** Theorem 1 ties it exactly to the classic gated RNN (under ZOH): a large $\Delta$ resets the state and a small one keeps it, while $B$ and $C$ give finer control over writing and reading.
3. **Selection brought a systems problem, and the paper solved the systems problem.** With no convolution, kernel fusion, a parallel scan and recomputation run the recurrence in SRAM; never materializing the $(\text{batch}, L, D, N)$ state is why it is fast.
4. **State size is Mamba's asset and its ceiling.** A fixed $D\cdot N$ numbers make inference cost independent of length (this page computes 12.5 MiB for Mamba-2.8B, smaller than Pythia's KV cache after 40 tokens) and also make it lose on tasks that need verbatim recall, which is the gap hybrid architectures fill.
5. **Read papers with a calculator.** The parameter count reproduces exactly, two rows of Table 3 do not match, the official discretization differs from equation (4), and “matches a twice-larger model” holds for the average only; each is a few lines of code to find.

## Further reading

- Paper: [Mamba: Linear-Time Sequence Modeling with Selective State Spaces](https://arxiv.org/abs/2312.00752); official code: [state-spaces/mamba](https://github.com/state-spaces/mamba).
- Predecessors: [S4: Efficiently Modeling Long Sequences with Structured State Spaces](https://arxiv.org/abs/2111.00396); [H3: Hungry Hungry Hippos](https://arxiv.org/abs/2212.14052); [Hyena Hierarchy](https://arxiv.org/abs/2302.10866); [In-context Learning and Induction Heads](https://arxiv.org/abs/2209.11895).
- Follow-ups and comparisons: [Mamba-2: Transformers are SSMs](https://arxiv.org/abs/2405.21060); [Jamba: A Hybrid Transformer-Mamba Language Model](https://arxiv.org/abs/2403.19887); [Repeat After Me: Transformers are Better than State Space Models at Copying](https://arxiv.org/abs/2402.01032); [An Empirical Study of Mamba-based Language Models](https://arxiv.org/abs/2406.07887).
- On this site: [State space models and hybrid architectures](https://dmxsf.com/en/wiki/architecture/state-space-and-hybrid/), [efficient attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/), [KV cache](https://dmxsf.com/en/wiki/inference/kv-cache/), [modern LLM architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/), [Attention Is All You Need](https://dmxsf.com/en/blog/attention-is-all-you-need/), [FlashAttention](https://dmxsf.com/en/blog/flashattention-fast-and-memory-efficient-exact-attention/).

## FAQ

### What is Mamba, and how is it different from a Transformer?

Mamba (Gu and Dao, arXiv 2312.00752) is a sequence model without attention. Its core is a structured state space model with a selection mechanism (a selective SSM, abbreviated S6 in the paper). It squeezes the whole history into one fixed-size state that is updated once per token, so training time and memory grow linearly with sequence length and each inference step costs the same however much has been read. A Transformer keeps the keys and values of the whole history (the KV cache) and reads all of it at every step. The key change is that Δ, B and C are computed from the current token, so the model can decide by content whether to remember or ignore it.

### What is the selection mechanism, and why does it matter that SSM parameters depend on the input?

A classic SSM is linear time-invariant (LTI): every step uses the same parameters, which makes it equivalent to one fixed convolution kernel that treats inputs by position, not by content. Selection makes Δ (step size), B (write) and C (read) functions of the current token: a large Δ resets the state toward the current token and a small Δ leaves the state almost untouched, skipping the token. With N=1, A=−1 and B=1 it is exactly a gated RNN (Theorem 1 of the paper). In this page's small experiment (6 data tokens placed at random among 32 positions, to be copied in order), after 3000 steps S6 reaches 99.5% exact match, LTI global conv 77.2% and the LTI diagonal SSM 16.3%; with 3 times as many steps the LTI models catch up to 95.6% and 80.5%, so at small scale selection first shows up as faster learning, not as LTI being unable to do the task.

### Is Mamba actually better than a Transformer?

In the paper's settings yes, within limits: on the Pile its scaling curves up to 1.3B parameters match the strong Transformer++ recipe, and Mamba-2.8B has a zero-shot average of 63.3 against 59.1 for Pythia-2.8B and 61.7 for Pythia-6.9B. Our recomputation shows that against the four 6-7B models Mamba-2.8B is best in only 4 of 9 columns. At larger scale and on tasks that need verbatim copying or in-context learning, later studies (Jelassi et al. 2024, Waleffe et al. 2024) found pure SSMs behind Transformers; hybrid architectures are what combine the benefits of both.

### How large is Mamba's state, and how much does it save compared with a KV cache?

Using the cache of the official implementation (16 SSM states plus 4 convolution states per channel per layer), Mamba-2.8B holds 64 layers × 5120 channels × 20 = 6,553,600 numbers, 12.5 MiB at 16 bits, whatever the length. Pythia-2.8B stores 163,840 numbers per token, so the two are equal after 40 tokens and the KV cache is 640 MiB at 2,048 tokens. The paper reports 4-5 times the inference throughput of a similar-size Transformer on an A100; that is the paper's own measurement and this page has no GPU to check it.

### How are Mamba, Mamba-2 and Jamba related?

Mamba-2 (Dao and Gu, arXiv 2405.21060) introduces state space duality (SSD), which ties SSMs to variants of attention; its core layer refines Mamba's selective SSM and the paper reports it as 2-8 times faster. Jamba (AI21, arXiv 2403.19887) interleaves Transformer and Mamba layers and adds mixture-of-experts, with strong results up to 256K tokens of context. In NVIDIA's comparison (arXiv 2406.07887) an 8B Mamba-2-Hybrid (43% Mamba-2, 7% attention, 50% MLP layers) beats the 8B Transformer on all 12 standard tasks, by 2.65 points on average.
