Thursday, November 12, 2026

Mamba State Space Models Explained: Selective State Spaces for Images and Time Series

Say a team wants a model that reads hour-long sensor recordings. At 100 readings per second, one recording is 360,000 time steps. A Transformer compares every step with every other step, so doubling the length roughly quadruples the attention work, and the memory it keeps during generation grows with every step it reads.

Mamba state space models were built for this kind of problem. Mamba is a sequence model, introduced by Albert Gu and Tri Dao in December 2023, that replaces attention with a selective state space layer: it carries a fixed-size memory through the sequence and decides, token by token, what to write into that memory and what to skip. Its cost grows linearly with sequence length. This article explains how selective state spaces work in plain terms, runs a working example in NumPy, and covers the vision and time-series variants that followed.

Key Takeaways

  • A state space model (SSM) reads a sequence one step at a time and keeps a fixed-size hidden state that summarizes everything seen so far.
  • Earlier SSMs such as S4 used the same update rule for every token. Mamba makes the update depend on the current token, which lets it keep important inputs and ignore filler.
  • Compute grows linearly with sequence length, and generation needs no growing cache, which is why the paper reports about 5 times higher inference throughput than Transformers.
  • The trade-off is memory: a fixed-size state cannot recall every earlier detail the way attention can, which is why hybrid models mix Mamba layers with some attention layers.
  • Vision Mamba (Vim) and VMamba adapt the idea to images, and S-Mamba applies it to multivariate time-series forecasting.

What Is a State Space Model?

A state space model is a model that maps an input sequence to an output sequence through a hidden state that is updated at every step. The idea comes from control theory, where it has been used for decades to track systems such as a moving vehicle or a circuit.

In its simplest discrete form, an SSM has two equations:

h_t = A_bar * h_{t-1} + B_bar * x_t    (update the state)
y_t = C * h_t                           (read the output)

Here x_t is the input at step t, h_t is the hidden state, and A_bar, B_bar and C are learned. A_bar decides how much of the old state to keep, and B_bar decides how much of the new input to write in. A neural SSM stacks many of these channels and layers, but each one follows this pattern.

The useful property is that the state has a fixed size. Whether the model has read 100 steps or 360,000, it carries the same amount of memory forward, so each new step costs the same.

What Problem Did Mamba Solve?

Structured state space models such as S4, also from Albert Gu and colleagues, were already fast on long sequences. They had one weakness that the Mamba paper names directly: they could not do content-based reasoning. Their A_bar and B_bar were the same for every token, so the model treated an important word and a filler word in exactly the same way.

Language is full of cases where that fails. To answer “What was the name mentioned at the start?”, a model has to store the name and ignore the hundreds of words that follow. A fixed update rule keeps blending every new token into the state, and the name fades.

The Mamba paper, “Mamba: Linear-Time Sequence Modeling with Selective State Spaces”, tested this with synthetic tasks such as selective copying and induction heads, where the model must remember specific tokens and skip the rest. Fixed SSMs struggle with these tasks, and the selective version solves them.

How Do Selective State Spaces Work?

A selective state space makes the SSM parameters functions of the input. In Mamba, the step size delta and the matrices B and C are computed from the current token by learned projections. The step size controls how the continuous parameters are turned into A_bar and B_bar at each step:

  • A large delta makes A_bar close to zero and B_bar close to one. The model forgets the old state and writes the current token in. In effect, it says “this token matters, focus on it.”
  • A tiny delta makes A_bar close to one and B_bar close to zero. The state passes through almost unchanged and the token is ignored.

The code below shows the effect with one channel and a one-number state. The sequence starts with one important value, 5.0, followed by filler. The first run uses a fixed step size, as S4 would. The second computes the step size from each token, as Mamba does (the rule 4 * |x| - 6 is hand-picked for the demo; in Mamba it is learned).

import numpy as np


def softplus(z):
    return np.log1p(np.exp(z))


def ssm_scan(x, delta, A=-1.0, B=1.0, C=1.0):
    """State space model with one channel and a one-number state.

    Zero-order-hold discretization, as in the Mamba paper:
      A_bar = exp(delta * A)
      B_bar = (exp(delta * A) - 1) / A * B
      h_t   = A_bar * h_{t-1} + B_bar * x_t
      y_t   = C * h_t
    """
    h, ys = 0.0, []
    for x_t, d_t in zip(x, delta):
        a_bar = np.exp(d_t * A)
        b_bar = (a_bar - 1.0) / A * B
        h = a_bar * h + b_bar * x_t
        ys.append(C * h)
    return np.array(ys)


# One important value followed by filler tokens.
x = np.array([5.0, 0.1, 0.2, 0.1, 0.3, 0.1])

# Fixed step size: every token is treated the same way (like S4).
fixed = ssm_scan(x, delta=np.full_like(x, 1.0))

# Selective step size: delta is computed from the token itself (like Mamba).
# A large input gets a large delta (overwrite the state); filler gets a tiny one (keep the state).
delta = softplus(4.0 * np.abs(x) - 6.0)
selective = ssm_scan(x, delta)

np.set_printoptions(precision=3, suppress=True)
print("delta per token:", delta)
print("fixed     y:", fixed)
print("selective y:", selective)

Output:

delta per token: [14.     0.004  0.006  0.004  0.008  0.004]
fixed     y: [3.161 1.226 0.577 0.276 0.291 0.17 ]
selective y: [5.    4.982 4.956 4.938 4.9   4.882]

With a fixed step size, the value 5.0 has faded to 0.17 after five filler tokens. With a selective step size, the model writes 5.0 into the state and keeps about 4.88 of it at the end, because each filler token gets a step size near zero. That is the whole idea of selection, in one channel.

Why Mamba Is Fast on GPUs

Selection has a cost. S4 could compute its output as one long convolution because its parameters never changed. Once the parameters depend on the input, that shortcut is gone, and a plain loop like the one above is slow on a GPU.

Gu and Dao solved this with a hardware-aware parallel scan. The recurrence is computed with a parallel scan algorithm, and the expanded state is kept in fast on-chip GPU memory instead of being written out to main GPU memory. The official state-spaces/mamba repository ships these CUDA kernels in the mamba-ssm package, so in practice you use its Mamba block rather than a hand-written loop.

Mamba vs Transformers: What Changes in Practice?

The Mamba block combines the selective SSM with a gated projection and a short convolution, and the full model stacks these blocks with no attention layers and no separate MLP blocks. The paper reports these results:

  • About 5 times higher inference throughput than Transformers of similar size.
  • Compute that scales linearly with sequence length, with gains on real data up to sequences of a million steps.
  • Strong results on language, audio and genomics. On language modeling, Mamba-3B outperformed Transformers of the same size and matched Transformers twice its size, both in pretraining and in downstream evaluation.

The practical difference shows up during generation. A Transformer stores keys and values for every past token, so memory grows as the output gets longer. Mamba carries only its fixed-size state, so the cost of the next token does not depend on how many tokens came before.

The trade-off is recall. Attention can look back at any earlier token exactly. A fixed-size state has to compress the past, so tasks that need exact retrieval of many earlier details can favor attention. This is why hybrid designs exist: the Mamba repository includes a mamba2attn-2.7b model that mixes Mamba-2 layers with attention layers, and AI21’s Jamba model also combines the two.

The same team followed up in 2024 with Mamba-2, described in “Transformers are SSMs” (Dao and Gu), which reframes the selective SSM through structured state space duality and allows larger state sizes with faster training.

Mamba for Images: Vim and VMamba

Images are not sequences, so applying Mamba to vision starts with the same trick the Vision Transformer uses: cut the image into patches and read them as a sequence of tokens. That raises two problems a text model does not have. A patch’s meaning depends on its position, and the patch that matters may come after the current one in the reading order.

Vision Mamba (Vim), by Lianghui Zhu and colleagues and published at ICML 2024, handles this with bidirectional Mamba blocks, one scan forward and one backward, plus position embeddings. The authors report that Vim beats the DeiT vision Transformer on ImageNet classification and on detection and segmentation, and that at 1248 by 1248 pixels it runs 2.8 times faster than DeiT and uses 86.8% less GPU memory for batch feature extraction.

VMamba, published at NeurIPS 2024, takes a different route: its 2D selective scan reads the patch grid along four directions, so every patch gets context from all sides. Both models aim at the same benefit, which grows with resolution: higher-resolution images mean more patches, and Mamba’s cost grows linearly with that count, while attention’s grows with its square.

Mamba for Time Series Forecasting

Time series look like a natural fit, since they are already sequences and often very long ones. Research here is younger and results depend heavily on the dataset, so treat claims as starting points to test.

One example is “Is Mamba Effective for Time Series Forecasting?” by Zihan Wang and colleagues. Their S-Mamba model turns each variable’s history into a token with a linear layer, uses a bidirectional Mamba layer to model how variables relate to each other, and uses a feed-forward network for patterns over time. They compared it with nine other models on thirteen public datasets, including traffic, weather and electricity, and report leading accuracy at low compute cost.

For a production forecast, compare any deep model against plain baselines first. Our article on time series forecasting with VAEs covers another deep-learning approach, and the same rule applies: if a seasonal naive forecast is close, the extra complexity may not pay off.

Should You Use Mamba?

Mamba is worth testing when your sequences are long enough that attention becomes the bottleneck: long audio, genomic sequences, high-resolution images or sensor streams. The paper’s genomics results also explain why state space models show up in biological foundation models, where DNA sequences run far longer than typical text.

Plan for these practical points:

  • Hardware. The fast kernels in mamba-ssm need an NVIDIA GPU with CUDA (the repository also includes ROCm support for AMD). On CPU you would fall back to a slow reference loop.
  • Ecosystem. Transformers still have more pretrained checkpoints, tooling and tuning recipes. The Mamba repository offers base models from 130M to 2.8B parameters, trained on the Pile (one on SlimPajama) without instruction tuning.
  • Task fit. If your task depends on exact lookup of earlier details, test a hybrid model alongside a pure Mamba model.

Back to the Sensor Recordings

For the team with 360,000-step recordings, Mamba changes the budget. Each step costs the same no matter how long the recording runs, and the model can learn to write the rare important readings into its state and let routine readings pass through, exactly as the step size did in the NumPy example. The next move is a fair test: a Mamba model, a Transformer on downsampled data and a plain statistical baseline, scored on the same held-out recordings.

Frequently Asked Questions

Is Mamba a Transformer?

No. Mamba has no attention layers. It is a stack of blocks built around a selective state space layer, which carries a fixed-size state through the sequence instead of comparing every token with every other token. Hybrid models do combine Mamba layers with attention layers.

What Does “Selective” Mean in Mamba?

It means the state space parameters, including the step size and the B and C matrices, are computed from each input token. That lets the model decide per token whether to write it into memory or let it pass. Earlier SSMs used the same parameters for every token.

Can Mamba Run on a CPU?

The official mamba-ssm package is built for GPUs, and its fast selective scan needs CUDA or ROCm. The math itself is a simple recurrence, as the NumPy example shows, so it can run on a CPU, just much more slowly for real model sizes.

What Is the Difference Between Mamba and Mamba-2?

Mamba-2, by Tri Dao and Albert Gu (2024), keeps the selective idea but restructures the layer using what the authors call structured state space duality, which connects SSMs and a form of attention. This allows larger states and faster training on modern GPUs. Both are available in the same repository.

Disclaimer: The content on this website reflects the views of contributing authors and not necessarily those of Generative AI Lab. This site may contain sponsored content, affiliate links, and material created with generative AI. Thank you for your support.

Generative AI Lab mascot
Generative AI Lab Editorial Team
Articles researched, written and edited by the Generative AI Lab team. About Generative AI Lab

Must read

- Advertisement -spot_img

More articles

- Advertisement -spot_img

Latest articles