Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~9 min readGu & Dao · 2023

Mamba,
explained.

The Transformer conquered AI with one expensive habit: every token compares itself to every other token. Beautiful for quality, brutal for long inputs — double the length, quadruple the cost. For years, "just replace attention" was a graveyard of failed ideas. Mamba is the one that made the graveyard nervous: a sequence model that scales linearly, remembers with a compact state, and — for the first time — actually kept up on language.

The delta

What changes against every rung below: attention is replaced, not repaired

Rungs 1 to 3 all keep attention and change its bookkeeping. This rung changes the primitive. A state-space model carries a fixed-size state forward through the sequence, updating it at each token — which is recurrence, and therefore linear in sequence length with a per-token inference cost that does not grow at all. Against a transformer that is a different cost structure, not a cheaper one: no quadratic term, and no key-value cache that swells with every token generated.

Earlier state-space models had that cost structure and were not competitive on language, and this paper's diagnosis of why is the actual contribution. Their state update was the same at every position, which makes the recurrence expressible as a long convolution and therefore fast to train — but it means the model cannot decide to ignore a token or to hold on to one. It compresses everything at a fixed rate. Attention gets selectivity for free, because a query chooses what to look at.

The change is to make the state update a function of the current input: the model learns what to admit into the state and what to forget, per token. That breaks the convolution trick, since the operation is no longer the same at every position, so the paper pays for selectivity with a hardware-aware parallel scan that keeps the state in fast on-chip memory and never writes the full sequence of states out. Stated in the ladder's units: linear time and a constant-size inference state, with the content-dependence that made attention work in the first place.

01

Attention's quadratic tax

The Transformer's power comes from attention: at every layer, each token looks at every other token to decide what matters. That all-pairs comparison is why it's so good — and why it's so costly. For a sequence of length N, attention does on the order of N² work and memory. Double the context and the cost roughly quadruples.

For a paragraph, fine. For a whole book, a genome, an hour of audio, or a million-token context, that quadratic wall bites hard. Worse, generating text with a Transformer means caching the keys and values of every past token — memory that grows without bound as the output gets longer. The field wanted attention's quality without attention's scaling. Many tried; most produced models that were fast but noticeably dumber.

02

State-space models: an old idea, reborn

Mamba builds on state-space models (SSMs), a formalism borrowed from control theory. An SSM processes a sequence by carrying a hidden state — a compact summary of everything seen so far — and updating it with simple linear rules at each step, much like an RNN or a physical system evolving over time.

The crucial difference from attention: an SSM doesn't keep every past token around. It compresses the history into a fixed-size state. That's the whole efficiency story — a constant-size memory instead of a cache that grows with the sequence, and per-step cost that doesn't blow up with length. The problem, historically, was making that compressed state expressive enough to rival attention.

The update rule is a plain linear recurrence — carry a state h, fold in each input, read out an output:

Because the state is fixed-size and each step is O(1), the whole sequence is O(N) compute and O(1) memory — against attention's O(N²) and a KV cache that grows to O(N):

The state never grows with the sequence — that flat line is the entire pitch. The runnable version below computes it, and proves the recurrence equals a convolution (the trick that makes training parallel).

SSM — history compressed into a fixed-size state
x₁
→
stateupdated
→
x₂
→
stateupdated
→
…
→
state
fixed-size memory · linear-time updates
03

The best of RNN and CNN

A recurrence is great for cheap, one-step-at-a-time generation but painful to train — you can't parallelize across a sequence. Attention and convolutions parallelize beautifully for training but pay for it elsewhere. The prior SSM work (S4) found a remarkable trick: the same linear state-space model can be computed two ways.

During training, unroll the recurrence into a giant convolution and run the whole sequence in parallel on a GPU. During generation, run it as a step-by-step recurrence with a constant-size state. Same math, two modes — parallel where you want speed, recurrent where you want cheap inference. That duality is what makes SSMs practical rather than just elegant.

04

The breakthrough: selectivity

Earlier SSMs had a fatal flaw on language: their update rules were fixed — the same for every token, independent of content. That works for smooth signals like audio, but language needs judgment: skip the filler word "the," but hang on tightly to the subject you'll need ten sentences later. A model that treats every token identically can't do that, and that rigidity is why SSMs kept losing to attention on text.

Mamba's core contribution is selectivity: it makes the SSM's parameters input-dependent. The rules for what to remember, what to forget, and how much a token updates the state now change based on the token itself. Suddenly the model can choose to store important information and let irrelevant tokens flow past — content-aware memory. This one change is what finally closed the quality gap with Transformers on language.

The key intuition

Attention decides relevance by comparing all pairs (expensive but flexible). Mamba's selectivity decides, per token, how to update one compact state (cheap and, it turns out, flexible enough). It's a different route to the same skill: focusing on what matters.

05

Making selectivity fast on real hardware

Selectivity came with a catch. Making the parameters input-dependent broke the neat convolutional trick that made older SSMs fast — you can no longer precompute one fixed kernel. Mamba's answer is a hardware-aware parallel algorithm: a carefully written GPU scan that computes the selective recurrence efficiently while keeping the working state in fast on-chip memory (SRAM) and avoiding costly trips to slower GPU memory.

This is a recurring theme in modern deep learning — echoing FlashAttention. The algorithm on paper isn't enough; you have to co-design it with how GPUs actually move data. Mamba's speed comes as much from this systems engineering as from the math.

07

The limits

Compressing all history into a fixed-size state is efficient but lossy. Attention has perfect random access — it can reach back and read any earlier token exactly. Mamba only has whatever survived in its compressed state, so on tasks that need precise recall of a specific distant token (certain copying or in-context lookup tasks), pure SSMs can lag attention.

In practice, the strongest systems often go hybrid — interleaving Mamba-style SSM layers with a few attention layers to get linear efficiency plus occasional exact recall. And as a newer architecture, it lacks the Transformer's years of tooling, tricks, and ecosystem. It's a serious challenger, not (yet) a wholesale replacement.

08

Why it still matters

Mamba reopened a question many had considered closed: does the future of sequence modeling have to be attention? By showing an SSM could match Transformers on language while scaling linearly, it made non-attention architectures a live, credible research direction again — and pushed long-context modeling forward where quadratic cost had stalled it.

Its influence is already visible in hybrid models that blend SSM and attention layers, and in a renewed hunt for efficient architectures for very long sequences. Whether or not Mamba itself becomes dominant, it re-legitimized the search for something beyond attention — and that shift in the field's imagination is its real contribution.

Read next

Contrast with Attention Is All You Need (the architecture it challenges) and FlashAttention (making attention itself faster on hardware — the other route to efficiency).

How it works

How a Mamba block and its selective scan work, step by step

Mamba, by Albert Gu and Tri Dao, is a stack of identical blocks with no attention and no separate MLP. Each block wraps a selective state-space layer, which the paper calls S6, in a gated design.

one Mamba block input x, width D linear in-proj, D → 4D causal conv1d, k = 4 SiLU selective SSM scan, state N = 16 Δ, B, C per token SiLU gate × out-proj, 2D → D added to residual stream
The Mamba block: a gated branch around a selective state-space scan whose parameters are computed from each token.
  1. Project up and split. A linear layer expands the model width D by a factor of 2 per branch, producing two branches of width 2D.
  2. Mix locally. The main branch passes through a short causal depthwise convolution (kernel size 4) and a SiLU activation, so each channel sees its last few tokens before the state-space layer.
  3. Make the parameters functions of the token. From that branch, small linear projections produce, at every position, a step size Δ (one value per channel, through a low-rank projection and a softplus) and the input and output vectors B and C (N values each, shared across channels). The state matrix A stays an ordinary learned parameter that does not depend on the input: real, negative and diagonal, one per channel.
  4. Discretize per token. Zero-order hold turns the continuous parameters into a per-token recurrence, with Ā = exp(ΔA); for B̄ the reference implementation uses the simpler first-order ΔB. Because Δ depends on the token, so do Ā and B̄, even though A does not.
  5. Scan. Each of the 2D channels keeps an N-dimensional state, with N = 16 by default, and updates it as ht = Ātht−1 + B̄txt, reading out yt = Ctht plus a learned skip term.
  6. Gate and project down. The second branch goes through SiLU and multiplies the scan output element-wise. A final linear layer projects back to width D. Blocks are stacked with normalization and residual connections.
  7. Run the scan in fast memory. Time-varying parameters rule out the convolution trick that made earlier state-space models fast to train. The kernel loads Δ, A, B and C from GPU high-bandwidth memory into on-chip SRAM, discretizes and runs a parallel scan there, and writes only the outputs back. The expanded states are never stored; the backward pass recomputes them.
  8. Generate recurrently. At inference each block keeps only its scan state and its last few convolution inputs, a fixed size per sequence, so every new token costs the same however long the context is.

What Δ does

Δ is a learned, per-token gate. A large Δ drives Ā = exp(ΔA) toward zero, so the state is reset and the current token is written in strongly. A small Δ drives Ā toward 1 and B̄ toward 0, so the state persists and the token is effectively skipped. The paper shows that with a one-dimensional state, A = −1 and B = 1, the selective recurrence is exactly a classic gated RNN update with a sigmoid gate.

How it was trained

The language models were trained on the Pile with the GPT-NeoX tokenizer, at sizes from about 130M to 2.8B parameters. The main baseline is Transformer++, a strong LLaMA-style recipe with rotary embeddings, SwiGLU and RMSNorm, alongside other subquadratic architectures. Mamba uses no positional encoding: order comes from the recurrence itself.

The math

The selective state-space recurrence and its discretization

Δt = softplus(WΔxt + bΔ), Bt = WBxt, Ct = WCxt
Āt = exp(ΔtA), B̄t = (ΔtA)^−1(exp(ΔtA) − I) · ΔtBt
ht = Ātht−1 + B̄txt, yt = Ctht
with N = 1, A = −1, B = 1: ht = (1 − gt)ht−1 + gtxt, gt = σ(WΔxt + bΔ)
  • xt — the token's channel values after the convolution and SiLU.
  • Δt — the step size, one per channel, positive because of the softplus; the selection knob.
  • A — the input-independent state matrix: diagonal, real and negative, so exp(ΔA) is a decay between 0 and 1.
  • Bt, Ct — input-dependent N-vectors: how the token is written into the state, and how the state is read out.
  • ht — the N-dimensional state of one channel, the only thing carried forward.
  • gt — in the one-dimensional case, a sigmoid gate, which shows that selection generalizes RNN gating.

At the extremes: as Δ grows without limit, Ā goes to 0 and the state becomes the current input, a full reset. As Δ goes to 0, Ā goes to the identity and B̄ to 0, so the token is ignored and the state is carried unchanged. If Δ, B and C did not depend on x, as in S4, Ā and B̄ would be the same at every step, the recurrence would be a fixed convolution, and the layer could not choose what to keep.

The evidence

What Gu and Dao ran, and what Mamba showed

The paper tests selection on synthetic tasks built to need it, then on language, DNA and audio, and measures the kernel and inference speed separately.

TestSetupReported result
Selective copyingreproduce marked tokens scattered among random fillersselective layer near-perfect; time-invariant S4 and Hyena layers fail
Induction headstrained on 256-token sequencesMamba generalizes to about a million tokens; attention baselines degrade soon after the training length
Pile scaling, about 125M to 1.3Bagainst Transformer++first attention-free model to match it
Zero-shot downstream, Mamba-2.8Bagainst Pythia and RWKVbeats same-size models, roughly matches models twice its size
Generation throughputagainst a same-size Transformerabout 5× higher
Scan kernelagainst FlashAttention-2 and a naive scanfaster than FlashAttention-2 beyond 2K tokens; 20–40× faster than a standard PyTorch scan

On DNA, pretrained on the human genome, Mamba's perplexity kept improving as context grew toward a million base pairs, where a time-invariant baseline got worse. On audio it improved on prior state-space and autoregressive baselines.

The ablations locate the gain. Making Δ selective matters most; making B and C selective as well adds more. Increasing the state size N from 1 to 16 improves perplexity substantially only when B and C are selective, for about 1% more parameters. A real-valued A worked as well as a complex one on language.

The limits are scale and recall. The largest model is under 3B parameters, and later work by others, such as Zoology (Arora et al., 2023) and Repeat After Me (Jelassi et al., 2024), measured that fixed-state models fall behind attention at associative recall and verbatim copying. Hybrids such as AI21's Jamba interleave attention layers for exactly that reason.

Trade-offs

Mamba trade-offs: a fixed state against a growing cache

The choice between Mamba and attention is a choice of memory. A transformer keeps a key-value cache that grows by one entry per token per layer and can look any of them up exactly; Mamba keeps a fixed state per layer and keeps only what selection decided to write in. Everything else follows from that.

Transformer (FlashAttention)MambaHybrid, mostly SSM layers
Training compute in length NO(N²)O(N), parallel scanClose to O(N), plus the few attention layers
Per-token generation costGrows with contextConstantGrows slowly, only in attention layers
Memory per sequence while generatingCache grows linearly with NFixed: state plus a short convolution bufferCache only for the attention layers
Exact recall of a distant tokenYesOnly if it survived in the stateYes, through the attention layers
Kernels and toolingMature and portableRelies on a custom selective-scan kernelBoth

The constant state is what makes large batches and very long generations cheap: in the page's own worked example, one layer of a 1.4B Mamba carries about 65,000 state numbers against a 33.6-million-number cache for one transformer layer at 8,192 tokens. The price is lossy recall, which is why the designs that shipped keep a minority of attention layers.

In the wild

Where Mamba shows up in production

  • Hybrid language models

    AI21's Jamba interleaves Mamba layers with a minority of attention layers and mixture-of-experts feed-forward layers, the hybrid pattern the paper's recall limit predicts.

  • Pure state-space releases

    TII released Falcon Mamba 7B, an attention-free model, and Mistral released Codestral Mamba, a code model built on Mamba-2. In both, the cost of generating a token does not grow with the length of the input.

  • Libraries

    The authors' mamba-ssm package holds the selective-scan kernel, and Hugging Face Transformers includes MambaForCausalLM. Mamba-2, by the same authors, recasts the layer to use more matrix multiplication and run faster on current GPUs.

  • In interviews

    Typical questions: compare the memory a KV cache and a recurrent state need at a given length, explain why input-dependent parameters rule out the convolution trick, and say why a fixed-size state cannot guarantee verbatim recall. The capacity argument is the expected answer to the last one.

Since then

What the authors admit, and what happened next

The structural limit is not a bug and cannot be tuned away: a fixed-size state cannot losslessly retain an arbitrary amount of detail. A transformer's key-value cache is, in effect, a perfect transcript — costly, and perfect. A recurrent state is a summary. So on tasks that require verbatim recall of something specific from far back — copying, retrieving an exact string, the needle-in-a-haystack family — attention has an advantage that follows from information capacity rather than from training. This is measured, repeatedly, by others.

The evidence base at publication was also mid-scale. Claims about a new primitive at small scale have a poor historical record, and the honest position was that the comparison at frontier scale had not been run.

How it held up: as a component, decisively; as a replacement, not yet. What actually shipped is hybrids — mostly state-space layers with a minority of full attention layers interleaved — and the reason is exactly the admission above: the attention layers supply the exact recall the recurrent state cannot, and the recurrent layers supply the cheap long-range mixing attention cannot afford. Rungs 5 and 6 above are two further attempts at the same gap, which is the clearest sign that the gap is real and open.

SOLVE IT YOURSELF

Run the state-space model two ways

A state-space model is a linear recurrence, and its two superpowers are both computable here. First, the S4 duality: the step-by-step recurrence (cheap generation) and one big convolution (parallel training) produce byte-identical output — same model, two modes. Second, the complexity: watch attention's O(N²) compute and growing cache explode against the SSM's O(N) work and a state that never grows. At 8k tokens that's an 8,192× gap. Change the sequence or the SSM coefficients.

YOUR TASK

Write the body of ssm_recurrent. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. The recurrent and convolutional forms give identical output (S4 duality)
  2. The SSM state is constant-size regardless of sequence length
  3. Attention's memory grows with the sequence
  4. Attention is quadratic in N while the SSM is linear
  5. At long sequences the SSM does far less work than attention
CPython · WebAssembly
Questions

Questions people ask about Mamba

How does Mamba's selective scan work?

The selective scan computes the recurrence h_t = A-bar_t h_t-1 + B-bar_t x_t, y_t = C_t h_t, where the step size, B and C are computed from each token. Because those parameters change from step to step, the recurrence cannot be rewritten as one fixed convolution, which is how earlier state-space models trained in parallel. Mamba's kernel instead loads the parameters from GPU high-bandwidth memory into on-chip SRAM, discretizes them there, runs a work-efficient parallel scan, an associative prefix computation over the sequence, and writes only the outputs back to slow memory. The large expanded state is never stored; the backward pass recomputes it. The paper reports this is faster than FlashAttention-2 beyond 2K tokens and 20 to 40 times faster than a naive PyTorch scan.

What is inside a Mamba block?

A Mamba block takes the place of both the attention layer and the MLP of a Transformer layer. A linear projection expands the input into two branches, each twice the model width. The main branch goes through a causal depthwise one-dimensional convolution with kernel size 4, a SiLU activation, and the selective state-space layer, whose step size and B and C vectors are computed from the token. The second branch goes through SiLU and acts as a multiplicative gate on the scan's output. A final linear projection returns to the model width, and blocks are stacked with normalization and residual connections. There is no positional encoding and no attention anywhere in the model.

Which parameters are input-dependent in Mamba, and why is A not?

Three are computed from each token: the step size delta, one value per channel, and the vectors B and C, which control how the token enters the state and how the state is read out. The state matrix A stays a fixed learned parameter, diagonal and negative. It does not need to be input-dependent, because the discretized transition is exp of delta times A, so a token-dependent delta already makes the effective transition token-dependent: one learned decay rate per state dimension, scaled per token. The paper's ablations found delta to be the most important selective parameter, with B and C selective adding further gains, especially once the state size grows beyond 1.

What does delta do in Mamba?

Delta is the discretization step size, and in practice a gate. The discretized decay is exp of delta times A, with A negative. A large delta pushes that decay toward zero: the old state is mostly forgotten and the current token is written in strongly, so the model focuses on this input. A small delta keeps the decay near 1 and the input weight near 0, so the state carries through and the token is effectively skipped. Because delta is computed from each token through a softplus, the model learns which tokens to remember and which to pass over. With a one-dimensional state the update reduces exactly to a sigmoid-gated RNN.

Can Mamba recall information as precisely as attention?

Not in general, and the reason is capacity. Attention keeps every past key and value, so it can look up any earlier token exactly. Mamba compresses the whole history into a fixed-size state per layer, so whatever it did not keep is gone. Selection lets it keep what looks important, and on the paper's induction-heads task it generalized from 256-token training sequences to about a million tokens. But later studies such as Zoology (Arora et al., 2023) and Repeat After Me (Jelassi et al., 2024) showed fixed-state models falling behind attention on associative recall and verbatim copying as the amount to remember grows. That is why production hybrids interleave a few attention layers.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

A 1.4B Mamba has width D = 2,048, two-wide expansion and N = 16. How many state numbers does one layer carry per sequence, and how does that compare with one Transformer layer's key-value cache at d = 2,048 and 8,192 tokens?

Show answer

Mamba: 4,096 channels × 16 = 65,536 numbers, plus a tiny convolution buffer, at any length. Transformer: 2 × 2,048 × 8,192 ≈ 33.6 million. That is about 512× more, and the cache keeps growing with every token while the state does not.

With A = −1, what decay Ā does a token with Δ = 0.01 produce, against one with Δ = 5, and what does each mean for the state?

Show answer

Ā = e^−0.01 ≈ 0.990: the state keeps 99% of itself and the token barely enters. Ā = e^−5 ≈ 0.0067: the state is almost wiped and the token is written in. In the one-dimensional case the input weight is 1 − Ā, about 0.01 and 0.993.

Why can a selective SSM not be trained as one long convolution the way S4 is?

Show answer

A convolution applies the same kernel at every position, which requires Ā and B̄ to be constant over time. In Mamba they depend on each token through Δ, B and C, so the output at step t is a product of different matrices for every path. That is why Mamba needs a scan, made fast by keeping it in SRAM.

On induction heads Mamba was trained at 256 tokens and tested at about a million. By what factor did it extrapolate, and why can a recurrent state do this at all?

Show answer

2^20 / 2^8 = 4,096× the training length. The state has no position index that could go out of range, and the task needs only one stored association; selection lets the model write the key token in and hold it, however much filler follows.

Where this sits

Making the context long

Attention costs quadratic in sequence length. Six attempts to escape that, ending with two 2026 papers that give the model a memory instead.

  1. 1Transformer-XL2019
  2. 2Longformer2020
  3. 3Ring Attention2023
  4. 4Mamba2023
  5. 5Titans2025
  6. 6Engram2026

All 110 papers, in 19 ladders →

Finished this one? 0 / 110 Paper Breakdowns done
NextTitans Next on the “Making the context long” ladder · rung 5 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns