↓ Skip to main content

Sequence models without attention: from state space models to Mamba

·1725 words·9 mins
Yenjia Chen
Author
Yenjia Chen
Deep learning, medical AI, data science, and mathematics.

What is a sequence model?
#

A sequence model can be seen as a function that maps one sequence to another, and the Transformer is the classic example. Models of this kind handle many types of problems and data, including text, images, audio and video. For example:

  • Language models: GPT, Claude, Gemini and others
  • Vision-language models: LLaVA, and LLaVA-Med, which I covered in another article
  • Image models: the many vision transformers

Most of these state-of-the-art models are built on Transformers, which means one architecture can handle problems in different modalities. Take LLaVA: an image is encoded into feature vectors by a vision encoder, text is turned into tokens by a tokenizer, and then a single Transformer-based model can classify, or act as a chatbot. ViT does something similar.

Why are Transformers so convenient?
#

A Transformer block consists of multi-head attention, layer norm, feed forward (MLP), dropout and skip connections. Multi-head attention is the most important part.

The parts of a Transformer block: multi-head attention, layer norm, feed forward, dropout and skip connections
A Transformer block (from Build a Large Language Model From Scratch)

Once you have a Transformer block, scaling the model up is easy: stack more blocks, or use a Mixture of Experts (MoE, such as Mixtral 8×7B). Model size can be adjusted to whatever you need. This simplicity is one reason Transformer-based models became so popular.

Scaling laws
#

Transformers also come with an important rule of thumb, scaling laws. These are empirical observations that let you predict a model’s performance before training, from the dataset size, total compute and model size.

DeepMind’s Chinchilla scaling law is one of the best known. Here LL can be read as the loss, NN is the number of model parameters, and DD is the number of training tokens:

L(N,D)=E+AN0.34+BD0.28,E=1.69, A=406.4, B=410.7L(N, D) = E + \frac{A}{N^{0.34}} + \frac{B}{D^{0.28}}, \quad E = 1.69,\ A = 406.4,\ B = 410.7

Its main conclusion is that for a fixed compute budget, model size and the number of training tokens should be scaled in equal proportion, at roughly 20 training tokens per parameter. In other words, growing the model and the data together should lower the loss. The figure below is from OpenAI’s earlier scaling-law study: test loss falls steadily as compute, data and parameters increase.

Three log-log plots of test loss falling as compute, dataset size and parameters increase
Figure 1 from Kaplan et al. (2020)

The limits of Transformers
#

Transformers have proved powerful across many applications, and their performance improves readily with more resources. But there is a problem: because of attention, the computation grows quadratically with the context length. So the number of input and output tokens is capped, and they are hard to apply directly to long sequences such as video.

There are two mainstream answers for long sequences:

  1. Retrieval-Augmented Generation (RAG) works like an extension: it retrieves data from an external database and gives a tailored answer. It’s like being allowed a cheat sheet in an exam. You have to organize and condense the information onto the sheet beforehand so you can find what you need during the exam.
  2. A larger context window lets the model read more tokens at once, for example a context window of a million tokens.

Either way, it is better to cut the computation so that replies over long sequences come faster. Mamba is designed to handle long sequences efficiently in both training and inference.

State space models
#

Before Mamba, we need to meet its predecessors. We start with the state space model (SSM), which comes from control theory and describes a dynamic system with differential equations:

x′(t)=Ax(t)+Bu(t)y(t)=Cx(t)+Du(t)\begin{aligned} x'(t) &= Ax(t) + Bu(t) \\ y(t) &= Cx(t) + Du(t) \end{aligned}

Here u(t)u(t) is the input signal, x(t)x(t) is the state, and y(t)y(t) is the output. AA is the state matrix, which multiplies the state; BB and CC are the input and output matrices; DD acts like a skip connection and is usually set to 0 to drop the term.

Block diagram of a state space model: the input u passes through B, an integrator and feedback matrix A to form the state x, then C to give the output y, with D a shortcut from input to output
Block diagram of a state space model

The idea of an SSM is to remember past information in a smaller state, a bit like an RNN. That is how it handles long sequences.

Discretization: the recurrent and convolutional views
#

The most important step in an SSM is discretization, because it determines how efficient training and inference are. After discretization, the continuous system can be turned into two views.

The first is the recurrent view. Discretizing with the trapezoid (bilinear) method and a step size Δ\Delta turns the system into a recurrence:

xk=Aˉxk−1+Bˉuk,Aˉ=(I−Δ2A)−1(I+Δ2A)yk=Cˉxk,Bˉ=(I−Δ2A)−1ΔB,Cˉ=C\begin{aligned} x_k &= \bar{A}x_{k-1} + \bar{B}u_k, & \bar{A} &= (I - \tfrac{\Delta}{2}A)^{-1}(I + \tfrac{\Delta}{2}A) \\ y_k &= \bar{C}x_k, & \bar{B} &= (I - \tfrac{\Delta}{2}A)^{-1}\Delta B, \quad \bar{C} = C \end{aligned}

At inference time we can generate outputs with this formula. The next output depends only on the current state and the current input, so inference is very efficient, just like an RNN.

The second is the convolutional view. Unrolling the recurrence writes the output as a convolution of the input with a kernel:

y=Kˉ∗u,Kˉ=(CˉBˉ, CˉAˉBˉ, …, CˉAˉL−1Bˉ)y = \bar{K} \ast u, \qquad \bar{K} = (\bar{C}\bar{B},\ \bar{C}\bar{A}\bar{B},\ \dots,\ \bar{C}\bar{A}^{L-1}\bar{B})

During training the whole sequence is known, so the convolution can be computed in parallel. This is where SSMs differ from RNNs, which must be trained one step at a time.

The matrix A and HiPPO
#

In an SSM, BB and CC are learnable, and the choice of AA is crucial. The convolution kernel needs Aˉk\bar{A}^k, which is still expensive, so AA should ideally be a normal matrix: normal matrices are unitarily diagonalizable, which makes powers easy to compute.

SSMs also initialize AA with the HiPPO (High-Order Polynomial Projection Operator) matrix. The HiPPO matrix is derived from a specific measure and helps the state remember earlier information; the proofs and experiments are in an earlier paper by the same author. The version used in S4 (HiPPO-LegS) is:

Ank=−{2n+1 2k+1n>kn+1n=k0n<kA_{nk} = -\begin{cases} \sqrt{2n+1}\,\sqrt{2k+1} & n > k \\ n + 1 & n = k \\ 0 & n < k \end{cases}

This matrix is not normal, though. The authors decompose it into a normal matrix plus a low-rank matrix, then use their algorithm to speed up both the recurrent and the convolutional computation. Empirically, SSMs initialized with HiPPO perform well, but not when AA is initialized randomly.

Structured state space models (S4)
#

Put all this together and you get S4:

S4 = SSM + HiPPO + Structured matrices

That is, use a state space model, replace AA with the HiPPO matrix, and learn the parameters with structured matrices and a dedicated algorithm.

Three aspects of S4: a continuous state space, the HiPPO matrix for long-range dependencies, and the recurrent and convolutional discrete representations
Three aspects of S4 (from Albert Gu’s talk)

S4 has some useful properties:

  • Resolution invariance: because the model comes from a continuous system, it can be trained on low-resolution data and used on high-resolution data. This is especially handy for audio, where lowering the sample rate speeds up training.
  • Efficient training: training can use the convolution and run in parallel.
  • Efficient inference: inference can use the recurrence.

Mamba
#

Mamba: Linear-Time Sequence Modeling with Selective State Spaces by Albert Gu and Tri Dao (code on GitHub) sets out to solve the problems that attention brings. It adds two improvements on top of SSMs:

  1. A selective mechanism, which lets the model decide, based on the input, what to focus on or ignore.
  2. A hardware-aware algorithm, which designs the computation around the GPU’s memory hierarchy.

According to the paper, Mamba reaches 5× higher inference throughput than Transformers and state-of-the-art results across modalities such as language, audio and genomics. It is also the first attention-free model to match Transformer performance: Mamba-3B outperforms Transformers of the same size.

Notation and discretization
#

The Mamba paper uses slightly different notation: hh is the state, xx the input, and yy the output. The continuous and discretized systems are:

h′(t)=Ah(t)+Bx(t)ht=Aˉht−1+Bˉxty(t)=Ch(t)yt=Cht\begin{aligned} h'(t) &= Ah(t) + Bx(t) & \qquad h_t &= \bar{A}h_{t-1} + \bar{B}x_t \\ y(t) &= Ch(t) & \qquad y_t &= Ch_t \end{aligned}

Here the discretization is the zero-order hold (ZOH):

Aˉ=exp⁡(ΔA),Bˉ=(ΔA)−1(exp⁡(ΔA)−I)⋅ΔB\bar{A} = \exp(\Delta A), \qquad \bar{B} = (\Delta A)^{-1}\left(\exp(\Delta A) - I\right) \cdot \Delta B

Discretization is deeply tied to the continuous-time system, which gives the model extra properties such as resolution invariance and keeps it properly normalized. The figure below shows the state space model inside Mamba. The orange part is the state; AA extracts features and information from the state, and BB and CC handle the input and output.

Selective state space model: the input x_t is projected to produce B_t, C_t and Δ_t, which update the state h together with A before producing y_t; the computation runs in GPU SRAM
Selective state space model (Figure 1 of the Mamba paper)

The first improvement: the selective mechanism
#

In S4, AA, BB, CC and Δ\Delta don’t depend on the input; the model is time-invariant. Mamba makes BB, CC and Δ\Delta depend on the input by adding the sequence length LL as a dimension in the algorithm, so the model becomes time-varying:

Comparison of the S4 and S6 algorithms: in S6, B, C and Δ gain a sequence-length dimension L and are computed from the input, so they can only be computed recurrently with a scan
S4 and S6, which adds selection (Algorithms 1 and 2 of the Mamba paper)

where:

sB(x)=LinearN(x)sC(x)=LinearN(x)sΔ(x)=BroadcastD(Linear1(x))τΔ=softplus\begin{aligned} s_B(x) &= \mathrm{Linear}_N(x) \\ s_C(x) &= \mathrm{Linear}_N(x) \\ s_\Delta(x) &= \mathrm{Broadcast}_D(\mathrm{Linear}_1(x)) \\ \tau_\Delta &= \mathrm{softplus} \end{aligned}

sBs_B, sCs_C and sΔs_\Delta are linear layers, τΔ\tau_\Delta is softplus (a smooth approximation of ReLU), and the selective mechanism lives mainly in sΔs_\Delta and τΔ\tau_\Delta.

The selective mechanism is related to gating in RNNs. Theorem 1 of the paper looks at a special case: when N=1N = 1, A=−1A = -1, B=1B = 1, sΔ=Linear(x)s_\Delta = \mathrm{Linear}(x) and τΔ=softplus\tau_\Delta = \mathrm{softplus}, the selective SSM recurrence becomes:

gt=σ(Linear(xt))ht=(1−gt) ht−1+gt xt\begin{aligned} g_t &= \sigma(\mathrm{Linear}(x_t)) \\ h_t &= (1 - g_t)\,h_{t-1} + g_t\,x_t \end{aligned}

This is very similar to the forget gate in an RNN: a gate decides what to keep, the past state or the current input. The proof is in the paper’s appendix.

The second improvement: a hardware-aware algorithm
#

Once the selective mechanism is added, Aˉ\bar{A} and Bˉ\bar{B} change over time, so the model can no longer be trained as a convolution. The authors solve this with three classic techniques:

  • Kernel fusion
  • Parallel scan
  • Recomputation

Parallel scan is the most important; it is also used to compute linear RNNs. The real bottleneck is not the arithmetic but the I/O between two kinds of GPU memory: HBM (High Bandwidth Memory) and SRAM (Static Random-Access Memory), and SRAM is much faster than HBM. The main idea is to compute the key steps, discretization and the scan, in SRAM to reduce I/O.

Mamba’s architecture
#

H3 is one branch of SSM work. Mamba combines H3 with a gated MLP into a single Mamba block; the gated MLP is often used as an alternative to self-attention with fewer parameters. Mamba blocks can be stacked just like Transformer blocks.

The H3 block and a gated MLP combined into the Mamba block
The Mamba block (Figure 3 of the Mamba paper)

Results
#

The first experiment covers scaling laws on The Pile with models from 125M to 1.3B parameters. Mamba follows scaling laws just like Transformers do, with similar results at longer sequence lengths.

Scaling laws on The Pile at sequence lengths 2048 and 8192: Mamba’s perplexity matches or beats Transformer++
Scaling laws (Figure 4 of the Mamba paper)

The second is efficiency. Thanks to the hardware-aware algorithm, Mamba’s scan is faster than both FlashAttention-2 and convolution, which gives Mamba higher inference throughput, about five times that of a Transformer.

Left: time of scan, convolution and attention as sequence length grows; right: inference throughput of Mamba and Transformers at different batch sizes
Efficiency benchmarks (Figure 8 of the Mamba paper)

Conclusion
#

Mamba starts from state space models, uses HiPPO and S4 to lay the groundwork for remembering long sequences and computing efficiently, adds a selective mechanism so the model can choose what to remember based on content, and wins back efficiency with a hardware-aware algorithm.

For me, the most interesting thing about this paper is that it offers a path beyond attention. Attention-free sequence models are worth following, worth trying for training and inference, and could even be used to build foundation models.

References
#

  1. Albert Gu and Tri Dao. Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv preprint arXiv:2312.00752, 2023.
  2. Albert Gu, Karan Goel, and Christopher Ré. Efficiently Modeling Long Sequences with Structured State Spaces. arXiv preprint arXiv:2111.00396, 2021.
  3. Jordan Hoffmann et al. Training Compute-Optimal Large Language Models. arXiv preprint arXiv:2203.15556, 2022.
  4. Jared Kaplan et al. Scaling Laws for Neural Language Models. arXiv preprint arXiv:2001.08361, 2020.
  5. Haotian Liu, Chunyuan Li, Qingyang Wu, and Yong Jae Lee. Visual Instruction Tuning. Advances in Neural Information Processing Systems, 2023.
  6. Alexey Dosovitskiy et al. An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. arXiv preprint arXiv:2010.11929, 2020.
  7. Sebastian Raschka. Build a Large Language Model From Scratch.
  8. Loïck Bourdois. Introduction to State Space Models (SSM).
  9. Albert Gu’s talk on S4, 2022.