Transformer Alternatives: Mamba, RWKV, RetNet and More

Why attention gets expensive on long inputs, and how S4, Mamba, RWKV, RetNet, Jamba, linear attention and FlashAttention each try to fix it, from the papers.

By AI Agents DirectoryLast checked
Abstract geometric pattern of blue and green shapes

Most large language models today are built on the Transformer, and a long line of research has tried to replace or repair its most expensive part: attention. This explainer walks through the main contenders, namely state space models (S4, Mamba, Mamba-2), RWKV, RetNet, linear attention and hybrids such as Jamba, plus FlashAttention, which keeps attention but makes it cheaper to run. Each description comes from the original paper on arXiv and, where a model or library was released, from its official repository or model card.

The problem: attention grows with the square of the input

The Transformer, introduced in the 2017 paper “Attention Is All You Need”, dropped recurrence and convolution and relied on attention alone. In self-attention every token is compared with every other token. For a sequence of N tokens that means roughly N times N comparisons, so doubling the input length roughly quadruples the work and the memory for the attention matrix.

The papers covered here all start from that point. The RWKV authors describe Transformers as having memory and compute that scale quadratically with sequence length, while classic RNNs scale linearly but are hard to train in parallel. The FlashAttention paper calls Transformers “slow and memory-hungry on long sequences”. The Mamba paper notes that foundation models are “almost universally based on the Transformer”, and that earlier subquadratic designs had lagged attention on language.

There is a second, quieter cost at inference time. A Transformer generating text keeps a key-value cache that grows with every token in the context. Recurrent-style designs instead carry a fixed-size state, which is why several alternatives below advertise constant memory per generated token.

The alternatives at a glance

ApproachWhat it changesReleased code or weightsLicence
Linear attention (2020)Rewrites attention with kernel feature maps so cost is linear in lengthPaper and project pageNot covered here
S4 (2021)Replaces attention with a structured state space layerstate-spaces/s4Apache-2.0
Mamba (2023)Makes state space parameters depend on the inputstate-spaces/mambaApache-2.0
Mamba-2 (2024)Refines Mamba’s layer via a link between SSMs and attentionstate-spaces/mambaApache-2.0
RWKV (2023)RNN that trains in parallel like a TransformerBlinkDL/RWKV-LMApache-2.0
RetNet (2023)“Retention” with parallel, recurrent and chunked modesListed in microsoft/unilmMIT (repo)
Jamba (2024)Interleaves Transformer and Mamba layers, adds MoEai21labs/Jamba-v0.1Apache 2.0
FlashAttention (2022)Keeps exact attention, cuts GPU memory trafficDao-AILab/flash-attentionBSD-3-Clause

Linear attention: reorder the maths

Katharopoulos et al. (2020) express self-attention as a dot product of kernel feature maps. Because matrix multiplication is associative, the computation can be regrouped so the cost drops from O(N²) to O(N). The same reformulation lets an autoregressive Transformer run step by step like a recurrent network, which is why the paper is titled “Transformers are RNNs”. The authors report quality similar to standard Transformers alongside large speedups when generating very long sequences. RWKV and RetNet both build on this idea.

State space models: S4, Mamba and Mamba-2

A state space model comes from control theory. It describes a hidden state that evolves over time as input arrives, with matrices that map input to state and state to output. Once discretised, it can run as a recurrence (cheap at inference) or as a long convolution (parallel at training time).

S4. The S4 paper points out that earlier SSM approaches handled long-range dependencies well in principle but were too costly in compute and memory to be practical. S4 introduces a new parameterisation: the state matrix gets a low-rank correction so it can be diagonalised stably, which reduces the core calculation to a Cauchy kernel. The authors report strong results on the Long Range Arena benchmark, including the Path-X task with sequences of 16k steps.

Mamba. The Mamba paper by Albert Gu and Tri Dao argues that earlier subquadratic models could not do content-based reasoning, and fixes this by making the SSM parameters functions of the input. The model can then decide, token by token, what to keep and what to forget. That choice rules out the fast convolution trick, so the authors wrote a hardware-aware parallel algorithm that runs in recurrent mode instead. The full Mamba network contains no attention and no MLP blocks. The paper reports linear scaling in sequence length and faster inference than Transformers, and says the 3B Mamba model beats Transformers of the same size on language modelling.

Mamba-2. The Mamba-2 paper shows that SSMs and variants of attention are closely related through structured semiseparable matrices, a framework the authors call state space duality. They use it to design a faster core layer that stays competitive with Transformers on language modelling. The official repository ships both blocks under Apache-2.0 and now also includes a later Mamba-3 paper. Its basic usage example, from the README:

import torch
from mamba_ssm import Mamba

batch, length, dim = 2, 64, 16
x = torch.randn(batch, length, dim).to("cuda")
model = Mamba(
    d_model=dim, # Model dimension d_model
    d_state=16,  # SSM state expansion factor
    d_conv=4,    # Local convolution width
    expand=2,    # Block expansion factor
).to("cuda")
y = model(x)
assert y.shape == x.shape

The README lists Linux, Python 3.10+ and PyTorch 1.12+ as core requirements, with an NVIDIA GPU and CUDA 11.6+ for the CUDA selective-scan build.

RWKV: an RNN that trains like a Transformer

RWKV (Receptance Weighted Key Value) uses a linear attention mechanism so the same model can be written either as a Transformer, for parallel training, or as an RNN, for inference with constant compute and memory per token. The paper scaled it to 14 billion parameters and reports performance in line with similarly sized Transformers.

The RWKV-LM repository (Apache-2.0) has since moved on to RWKV-7 “Goose”, which it describes as attention-free, linear-time and constant-space with no KV cache. The README also states that RWKV is a Linux Foundation AI project.

RetNet: one mechanism, three ways to compute it

Microsoft’s Retentive Network paper derives a link between recurrence and attention and proposes a “retention” mechanism with three equivalent forms:

  • Parallel, used for training so the whole sequence is processed at once.
  • Recurrent, used for decoding, with O(1) cost per step, which the authors say improves throughput, latency and GPU memory.
  • Chunkwise recurrent, for long inputs: each chunk is encoded in parallel and chunks are summarised recurrently, giving linear complexity.

The authors pitch RetNet as a successor to the Transformer for large language models. It is listed under model architecture work in Microsoft’s unilm repository.

Hybrids: Jamba

Rather than pick one side, Jamba from AI21 interleaves Transformer layers with Mamba layers and adds mixture-of-experts (MoE) in some of them to raise capacity without activating every parameter on each token. If MoE is new to you, see our explainer on mixture of experts in LLMs.

According to the Jamba-v0.1 model card, the base model has 12B active and 52B total parameters, supports a 256K-token context, and can hold up to 140K tokens on a single 80GB GPU. The licence is Apache 2.0. The card recommends transformers 4.40.0 or later and installing mamba-ssm and causal-conv1d for the optimised kernels, and notes that the model must be on a CUDA device. AI21 marks v0.1 as a base model and points users to the later Jamba-1.5 releases.

FlashAttention: keep attention, fix the memory traffic

Not every effort removes attention. FlashAttention argues that the real bottleneck is moving data between the GPU’s large but slow high-bandwidth memory and its small, fast on-chip SRAM. It computes exact attention in tiles so far fewer reads and writes hit HBM. Unlike approximate methods, the output does not change; only the execution does.

FlashAttention-2 improves how work is split across GPU thread blocks and warps, and parallelises a single attention head across thread blocks. The author reports about twice the speed of the first version. The official repository (BSD-3-Clause) also offers FlashAttention-3 for Hopper GPUs and FlashAttention-4 for Hopper and Blackwell.

FlashAttention helps the Transformer directly, and it also influenced the alternatives: the Mamba README describes its hardware-aware implementation as being in the spirit of FlashAttention.

How to think about the trade-offs

The papers frame the choices in similar terms:

  • Training parallelism versus cheap inference. RNNs were cheap to run but slow to train; Transformers were the reverse. RWKV, RetNet and linear attention all try to get both by offering two equivalent ways to compute the same layer.
  • Fixed state versus full memory. A fixed-size state keeps memory flat however long the input gets, but the model must compress what it has seen. Mamba’s selection mechanism is the authors’ answer to choosing what to keep.
  • Replace or combine. Jamba keeps some attention layers alongside Mamba layers; the Mamba-2 paper argues the two families are closer than they look.
  • Optimise what exists. FlashAttention does not change the architecture at all, so it drops into existing Transformer code.

For practical ways to stretch a standard model’s context today, see our guide to context window optimisation, and for shrinking models to cut serving cost, our overview of quantisation and compression. If you are choosing a model to run yourself, our roundup of open-source LLMs covers the licensing side.

#Transformer architecture#State space models#Mamba#RWKV#FlashAttention
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.