Hybrid Attention and State Space Models

Michael BrenndoerferNovember 17, 202641 min read

Combine attention and state space layers in one stack. Compare KV cache growth, recurrent state, prefill arithmetic, and the Jamba ratio evidence.

Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 134Hybrid Attention and State Space Models
Reading the full chapter · 12 sections · 41 min12 sections · 41 min

All 12 sections · 41 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Hybrid Attention and State Space Models

A long prompt can ask a decoder to keep track of a discussion and then recover a number mentioned early in it. A full-context attention layer can consult a separate representation of each earlier position. The layer stores keys and values for those positions, so its cache grows as the prompt gets longer.

A Mamba-1-style layer carries two fixed-shape buffers from one decode step to the next: the recurrent state and the short convolution history. The recurrence summarizes the prefix in its updated state. Two prefixes that leave the same complete carried state cannot be distinguished by its later updates when they receive the same subsequent inputs at the same positions.

A longer prompt increases the number of positions in a full-attention layer’s cache. In the Mamba-1-style layer modeled here, the recurrent state and convolution buffer keep the same shapes as the prompt grows.

A hybrid stack puts both mixers in the same residual stream. A few layers attend over token positions, while the remaining state-space layers use recurrent updates whose work grows linearly with sequence length at fixed width and state size. The architecture reduces the number of layers with a position-indexed cache while retaining attention at selected depths.

Jamba provides a concrete architecture to examine. Its first released model has 32 sequence-mixing layers arranged in four groups. Each group has one attention layer and seven Mamba layers, and some layers use a mixture of experts for their feed-forward computation. The released configuration supports 256K tokens. We use its 1:7 ratio to illustrate how the attention count affects cache capacity.

We will work through the following:

  • why the two layer types fail in complementary ways, and what "capacity" means for a recurrent state;
  • the three design axes (ratio, placement, and feed-forward type) and why the last one is independent of the first two;
  • what actually flows through a hybrid residual stack, and what that implies about where attention layers can help;
  • the prefill regime and the incremental decode regime, which have completely different cost structures;
  • what the Jamba, Jamba-1.5, and Waleffe et al. studies measured, with their denominators and controls made explicit;
  • a hand-checkable example where two sequences produce an identical recurrent state but are separated by one attention layer;
  • an executable cache model that finds when the key-value cache equals and then exceeds the combined recurrent and convolution state.

A measured result describes one evaluated model and workload. An arithmetic estimate describes the operation count or state capacity under stated assumptions. The chapter uses both to examine the effects of changing the mixer schedule.

Two Kinds of Memory

The previous chapter, State Space Models for Language, developed selective state-space layers. For one channel of a diagonal model, let xtx_t be the scalar input and ht∈RNh_t \in \mathbb{R}^N the updated state. The discretized transition aˉt\bar a_t and write vector bˉt\bar b_t each have NN components. The read vector ct∈RNc_t \in \mathbb{R}^N turns the updated state into the scalar readout yty_t.

ht=aˉt⊙ht−1+bˉtxt,yt=ct⊤ht.h_t = \bar a_t \odot h_{t-1} + \bar b_t x_t, \qquad y_t = c_t^\top h_t.

In Mamba-1, the full input vector to the state-space computation supplies the projections for the step size, write and read coefficients at each position. The step size for this channel converts its learned continuous rates into the discrete multipliers aˉt\bar a_t and also affects the discrete write bˉt\bar b_t. The scalar xtx_t in the equation is this channel's input. The equation gives the state readout within the mixer. At fixed channel count and state size, the number of stored recurrent-state elements stays fixed.

When a decoder processes the next token, that update uses the immediately preceding state. The state is a function of the prefix, but it gives no separate storage slot for position 3 or any other earlier position. Its fixed shape is what makes a recurrent update possible at a cost independent of the prefix length.

Gu and Dao, Mamba, Algorithm 2 and Section 3.3

A full-context attention head scores each available key with its query and uses the weights to combine the corresponding values. At position tt, use the score and value from position t′t' when t′≤tt'\le t. Scaling by the square root of the key dimension controls the size of the scores before softmax.

yt=∑t′≤texp⁡(qt⋅kt′/d)∑s≤texp⁡(qt⋅ks/d)⏟wt,t′ vt′y_t = \sum_{t' \le t} \underbrace{\frac{\exp(q_t \cdot k_{t'} / \sqrt{d})}{\sum_{s \le t} \exp(q_t \cdot k_s / \sqrt{d})}}_{w_{t,t'}} \, v_{t'}

where:

  • qtq_t: the query vector at position tt
  • kt′k_{t'}: the key vector at position t′t'
  • vt′v_{t'}: the value vector at position t′t'
  • dd: the key/query dimension, used in the d\sqrt{d} scaling
  • wt,t′w_{t,t'}: the attention weight from position tt to position t′t', normalized over all s≤ts \le t
  • yty_t: the attention output at position tt

At decode time, the layer can retain its projected key and value vectors for each prefix position. The query scores the cached keys and the output combines the cached values. A position can receive a large attention weight, and the retrieved value remains a learned representation of that position.

Attention-to-state-space ratio

The number of attention layers relative to the number of state space layers in a hybrid stack, usually written as a pair such as 1:7. It is a design hyperparameter, comparable to depth or width, and its best value depends on the model scale, the token budget, the data, and the workload the model will serve. It is not a property of either layer type.

What the bottleneck costs

Suppose a recurrent decoder carries SS state elements of 16 bits each, including all input-dependent state that will affect later outputs. There are at most 216S2^{16S} stored bit patterns. If there are more candidate prefixes of the same length than stored patterns, at least two prefixes must map to the same state. At the same position with the same next input, a deterministic recurrence and readout produce the same result for those prefixes.

An update can merge prefixes even when their number is below the upper bound. Identical subsequent inputs keep the states equal. The example below shows a collision with four positions. Attention preserves a separate projected representation for each retained position.

Arora et al. introduced multi-query associative recall, in which the input contains key–value pairs and later queries ask for values bound to keys. Jelassi et al. studied exact string copying and length generalization. Those diagnostics ask whether a model can retain and use particular pieces of a prefix. The comparison depends on the models, training data, and task, including how many distractors an example contains.

Use exact retrieval tests when an application needs to reproduce particular values or strings. Perplexity on natural text averages a different kind of error and can conceal a failure on a small set of long-distance dependencies.

Why the two combine well

In this stack, selective state-space layers summarize a prefix in recurrent state and attention layers can consult representations of individual positions. Both mixers fit the same residual-stream shape.

  • Residual stream. Each mixer reads the stream, produces an update of the same shape, and adds it back. Each layer keeps its own projections, normalization, and decode state. Residual Connections describes the shared residual path.
  • Causal prediction. The recurrence and the attention mask both limit the mixer to the available prefix. A hybrid and a causal Transformer can use the same next-token objective. At position tt, either model can predict token t+1t+1 using inputs through position tt.
  • Mixer accounting. At fixed widths, full attention contributes O(L2)O(L^2) prefill work per layer and an O(L)O(L) cache. A state-space layer contributes O(L)O(L) prefill work and a decode state whose size is independent of LL. Sum these operations or stored bytes across the layers using the corresponding per-layer estimates.

Replacing an attention layer removes its prefill and KV-cache terms and adds the recurrent layer's work and fixed decode state. The net change depends on the sequence length and both layers' dimensions.

The Design Space

You can set the mixer's layer count and placement and choose the feed-forward sublayer for each block. Each choice changes a different aspect of the model and can be tested with the other choices fixed.

Axis 1: the ratio

This ratio counts attention mixers against state-space mixers. A 1:7 schedule uses one attention layer per seven state-space layers. Holding total mixer depth fixed, a lower attention count reduces the number of position-indexed caches. The effects on quality depend on the models and tasks. Jamba's experiments compared 1:3 and 1:7 at one model scale.

Two cautions apply to every ratio you read:

  • The denominator matters. A 1:7 ratio counts eight sequence mixers. If all eight mixers have separate feed-forward sublayers and an author counts those sublayers too, the attention fraction is 1/161/16 of all counted sublayers rather than 1/81/8 of the mixers.
  • Ratios are scale-dependent. Compare models at the same training budget and scale before attributing a quality change to the ratio. Jamba-1.5 reports a ratio comparison and a larger single-ratio comparison separately.

Axis 2: placement

Given a fixed number of attention layers, where do they go?

  • Periodic. Place one attention layer every kk layers. Jamba places one every eight. The attention-layer indices have a regular spacing.
  • Prefix. Place attention near the beginning. The first attention layers have fewer preceding blocks to transform their inputs. Later layers still process those attention outputs.
  • Suffix. Place attention near the end. Its projections come from representations produced by more preceding blocks. The model can consult earlier positions at those late layers if their stored projections carry the relevant information.

A placement experiment needs a fixed ratio. With the same number of attention layers, you can test whether retrieval benefits from having attention earlier, later, or at several depths. The placement diagram below gives three schedules from which to construct that comparison.

Axis 3: the feed-forward sublayer

The feed-forward sublayer in the blocks described here acts at one position at a time. The sequence mixer supplies cross-position interactions. Choose a dense or expert feed-forward network separately from the choice of attention or a state-space mixer.

  • Attention with a dense feed-forward network, as in a standard Transformer.
  • State space with a dense feed-forward network, as in the Mamba layers of Jamba's ratio ablations.
  • Attention with a mixture of experts, as in a sparse Transformer.
  • State space with a mixture of experts, as in selected Jamba layers.

In the released Jamba-v0.1 schedule, the four attention layers have dense feed-forward networks. Every expert feed-forward network follows a Mamba mixer. The mixer schedule determines how many layers store attention keys and values, and expert routing determines which expert weights participate for each token. Comparing an expert hybrid with a dense attention model varies both choices. Jamba-v0.1 configuration

Active parameters

Active parameters participate in the forward pass for a token. Each routed token uses its selected experts along with the shared weights. Total parameters count all experts. Changing a mixer can also change the parameter count because attention and state-space blocks use different projections.

We will return to mixture-of-experts in Part XXXIII. The accounting examples vary mixers and leave their feed-forward costs outside the calculation.

What Flows Through a Hybrid Stack

To reason about hybrids at all, you need a precise picture of the data path. Using pre-norm residual blocks (see Pre-Norm vs Post-Norm), a hybrid stack looks like this. At a state space layer ℓ\ell:

u(ℓ)=x(ℓ)+SSM(ℓ) ⁣(LN(x(ℓ)))u^{(\ell)} = x^{(\ell)} + \mathrm{SSM}^{(\ell)}\!\left(\mathrm{LN}(x^{(\ell)})\right)

and at an attention layer ℓ\ell:

u(ℓ)=x(ℓ)+Attn(ℓ) ⁣(LN(x(ℓ)))u^{(\ell)} = x^{(\ell)} + \mathrm{Attn}^{(\ell)}\!\left(\mathrm{LN}(x^{(\ell)})\right)

followed in both cases by the feed-forward sublayer,

x(ℓ+1)=u(ℓ)+FFN(ℓ)(LN(u(ℓ)))x^{(\ell+1)} = u^{(\ell)} + \mathrm{FFN}^{(\ell)}(\mathrm{LN}(u^{(\ell)}))

where:

  • x(ℓ)x^{(\ell)}: the residual stream entering layer ℓ\ell, a matrix of shape L×dmodelL \times d_{\text{model}}
  • LN(⋅)\mathrm{LN}(\cdot): layer normalization applied across the model dimension
  • SSM(ℓ)\mathrm{SSM}^{(\ell)}: the state space sequence-mixing sublayer at layer ℓ\ell
  • Attn(ℓ)\mathrm{Attn}^{(\ell)}: the attention sequence-mixing sublayer at layer ℓ\ell
  • u(ℓ)u^{(\ell)}: the intermediate residual stream after the sequence-mixing sublayer
  • FFN(ℓ)\mathrm{FFN}^{(\ell)}: the feed-forward sublayer at layer ℓ\ell
  • x(ℓ+1)x^{(\ell+1)}: the residual stream passed to the next layer, of shape L×dmodelL \times d_{\text{model}}

Both mixer choices preserve the shape of the residual stream. That lets a hybrid interleave them in a stack with a common interface.

The two mixer types keep different state between decode steps.

  • An attention layer reads its own input stream. It projects the vector at each position to a key and a value. At layer 20, those vectors can depend on the prior 19 layers. A deep attention layer works with these learned representations. Each decode step reads from that layer's cache of earlier projections.
  • Each state-space layer carries its own recurrent state. That state depends on the prefix of its input stream. Its state slots correspond to features, while the input stream gives the layer a representation per position. Replacing a mixer can change the representations and state in the layers above it.
  • A recurrence can merge two prefixes at the current position while an earlier position still differs. During prefill, later layers see the per-position stream. During decoding, they consult the keys and values kept by their attention layers. An earlier token can still affect the answer if a projection retained the distinguishing information. The example below makes the distinction precise.

A hybrid gives selected layers the ability to combine representations from different positions through attention. Increasing the attention count gives more layers that ability and adds a separate cache for each full-attention layer.

Gradients

Both mixers have a shortcut around their computation in a residual block. The derivative of each residual update includes the identity and a contribution from the mixer branch. The mixers can have different backward implementations. The Mamba paper describes a selective scan and recomputation to limit intermediate storage, while the Jamba report describes additional normalization used to stabilize its larger hybrid. Evaluate training stability alongside loss and compute when changing the mixer schedule.

Prefill and Decode Are Different Regimes

Prefill processes the prompt and supplies the next-token distribution at the last prompt position. The decoder uses that distribution to choose the first output token. Incremental decode then consumes that token and extends the saved state to predict the next one. Profile the two phases separately to find which operations or memory transfers limit the workload. Sarathi-Serve

Prefill

During prefill, each layer processes a prompt of LL tokens. Attention can build queries, keys and values for the prompt in parallel. A selective state-space layer can use a parallel scan to evaluate the recurrence over the prompt. Each approach still needs a way to pass the resulting state to decode.

Consider the operation counts of one attention mixer and one Mamba-1-style mixer. The attention projections are linear in LL at fixed width. Full causal attention has L(L+1)/2L(L+1)/2 accessible query–key pairs, because position tt has tt available keys. Counting fixed work per pair gives a term that grows quadratically. A hybrid with some full attention retains that quadratic term, with fewer layers contributing to it.

The two large projections in the state-space mixer also grow linearly with LL at fixed width. At fixed state dimension and convolution width, its convolution and discrete state update do fixed work at each position. The prefill example below compares just the projections and attention pair products, with the terms left out listed alongside the count. For a long prompt, a smaller count of full-attention layers can substantially reduce the mixer arithmetic.

Decode

During incremental decoding, each sequence contributes one new position at a time. In a memory-bandwidth-limited workload, the cache and model weights contribute to the bytes a device must move. Batching can reuse weights across sequences. Kernel layout and on-chip reuse determine how persistent state translates to traffic.

For full-context attention, each step scores available prefix keys and combines their associated values. A prefix of length LL has 2Lnkvdhead2L n_{\text{kv}}d_{\text{head}} stored scalars per layer and sequence. Grouped-query attention shares each key and value head across several query heads, which reduces nkvn_{\text{kv}} relative to using one key and value head per query head.

For the Mamba-1-style layer modeled here, the recurrent state holds dinner×dstated_{\text{inner}}\times d_{\text{state}} scalars. The assumed convolution cache holds dinner×dconvd_{\text{inner}}\times d_{\text{conv}} scalars. Both shapes are fixed as LL changes. The two states can have distinct storage precision in a real implementation.

For each full-context attention layer, the persistent KV cache grows with the number of retained positions. Each modeled Mamba-1 layer adds a fixed recurrent state and convolution buffer. The cache example adds these terms across the stack.

The number of allocated bytes does not specify how often those bytes are transferred from device memory. The accounting below computes capacity. Runtime bandwidth needs a workload and a measurement.

What the Evidence Actually Says

The studies below address different questions. Their strongest comparisons match the training and evaluation setup within an experiment. The scope of a measurement stays with the models and budget used to produce it.

The original Jamba architecture. The released v0.1 model uses four groups of eight sequence-mixing layers, with one attention layer and seven Mamba layers in each group. Its expert feed-forward networks occur every second layer, at zero-based indices 1, 3, and so on. Attention appears at indices 4, 12, 20, and 28, so each attention layer has a dense feed-forward network. Each mixture routes a token to two of 16 experts. The authors report 52 billion total parameters, 12 billion active parameters, and a supported context of 256K tokens. Retrieval quality still needs to be evaluated across lengths and tasks.

Lieber et al., Jamba, Sections 2 and 3.1

Two experiments on layer ratios. The original report and Appendix C.1 of the 2025 Jamba-1.5 paper present the same core comparisons. The smaller experiment trained 1.3B-parameter models for 250B tokens. It compared two attention-to-Mamba ratios, 1:3 and 1:7, alongside pure-attention and pure-Mamba baselines. The hybrids had no mixture of experts. They reached the same reported OpenLLM aggregate score of 37.2, while their individual benchmark scores varied. The authors chose 1:7 because the lower attention count reduced compute and retained similar reported performance. The 7B-parameter experiment trained for 50B tokens and compared the chosen 1:7 hybrid with both pure baselines. It found a lower training loss for the hybrid. That experiment tested one hybrid ratio. The optimum could move with dataset, scale, token budget, or workload.

Lieber et al., Jamba, Section 6.1, Tables 4–5 and Lenz et al., Jamba-1.5, Appendix C.1, Tables 7–8

The empirical study by Waleffe et al. The authors explored layer fractions at 130M parameters and checked the attention-fraction trend at 840M before training their 8B-class models. One 8B-class hybrid has 4 attention, 24 Mamba-2, and 28 MLP layers. Because their layer count includes MLP layers, attention accounts for 4/56≈7.1%4/56 \approx 7.1\% of all layers and 4/28≈14.3%4/28 \approx 14.3\% of sequence-mixing layers. A comparison with Jamba's ratio should use the second denominator.

After training the compared models for 3.5 trillion tokens, Table 7 reports mean scores of 55.82 for Mamba-2-Hybrid and 53.17 for the Transformer, a difference of 2.65 points. The means use 13 score columns from 12 benchmarks because MMLU has separate zero-shot and five-shot columns. Pure Mamba-2 scored higher than the hybrid on some individual benchmarks. Figure 5 estimates the speedup for generating one token at batch size 32. Measure end-to-end throughput on the target runtime before extrapolating that estimate.

Waleffe et al., An Empirical Study of Mamba-based Language Models, Sections 4.1–4.3, Figure 5, Tables 6–7

To isolate placement, compare two hybrids with the same mixer counts but move where their attention layers occur. To isolate the count, vary the ratio and hold the feed-forward design fixed, then document any changes to width or heads used to keep parameter counts comparable. For serving measurements, report the prefill and decode phases separately, along with batch size, context length, output length, precision, hardware, and attention kernel.

Worked Example: Two Sequences, One State

To see the mechanism rather than the benchmark numbers, we can build the smallest possible case. Use a scalar recurrence with a fixed decay:

st=a st−1+xt,s0=0,a=0.5s_t = a\, s_{t-1} + x_t, \qquad s_0 = 0, \qquad a = 0.5

where:

  • sts_t: the scalar recurrent state at position tt
  • st−1s_{t-1}: the scalar recurrent state at the previous position
  • xtx_t: the scalar input at position tt
  • aa: the fixed decay factor, set to 0.50.5
  • s0s_0: the initial state, set to 00

The Mamba-1-style mixer described above uses input-dependent decay, dstated_{\text{state}} recurrent coordinates per channel, and learned input and output projections. This example uses one scalar state and a fixed decay so that we can construct and check the collision by hand.

Now consider two four-token sequences:

  • Sequence A: x=(1, 1, 0, 0)x = (1,\ 1,\ 0,\ 0)
  • Sequence B: x=(0, 0, 0.75, 0)x = (0,\ 0,\ 0.75,\ 0)

Running the recurrence with a=0.5a = 0.5 and s0=0s_0 = 0:

Two input sequences reach the same recurrent state at the third and fourth positions.
positionxt(A)x_t^{(A)}st(A)s_t^{(A)}xt(B)x_t^{(B)}st(B)s_t^{(B)}
11.001.00000.000.0000
21.001.50000.000.0000
30.000.75000.750.7500
40.000.37500.000.3750

At t=4t = 4 the two states are identical, s4=0.375s_4 = 0.375, despite the sequences sharing almost nothing. A decoder that reads only the state at position 4, plus the current token (which is 00 in both cases), cannot tell them apart. The history has been compressed into a collision. Sequence A wrote its information early and let the decay shrink it; sequence B wrote its information late and at a smaller magnitude. The states already agree at position 3. The same input at position 4 gives the same update in both sequences.

Add one attention layer with two input features per position. Keep the input value xtx_t in the first feature. In the second, add the input and the state to get zt=xt+stz_t=x_t+s_t. The query and key each select ztz_t, while the value selects xtx_t. This gives the following scalar keys.

  • z(A)=(2.0, 2.5, 0.75, 0.375)z^{(A)} = (2.0,\ 2.5,\ 0.75,\ 0.375)
  • z(B)=(0.0, 0.0, 1.5, 0.375)z^{(B)} = (0.0,\ 0.0,\ 1.5,\ 0.375)

At position 4 both query scalars equal 0.3750.375. The keys and values differ at earlier positions. The two queries thus produce different distributions over the earlier values. In this example their weighted sums are different.

The implementation below checks the collision and tests that appending a future token leaves the earlier attention outputs unchanged. The causal mask includes the current position.

Setting up the recurrence

First, the recurrence and the two sequences. Everything here is deterministic and needs no downloads.

PythonIn [3]
CollapseExpand
import numpy as np

DECAY = 0.5


def run_recurrence(x, decay=DECAY):
    """s_t = decay * s_{t-1} + x_t with s_0 = 0."""
    s = np.zeros(len(x), dtype=float)
    prev = 0.0
    for t, xt in enumerate(x):
        prev = decay * prev + xt
        s[t] = prev
    return s

The function returns the state at every position, not just the last one, because we want to inspect the trajectory.

PythonIn [4]
CollapseExpand
seq_a = np.array([1.0, 1.0, 0.00, 0.0])
seq_b = np.array([0.0, 0.0, 0.75, 0.0])

state_a = run_recurrence(seq_a)
state_b = run_recurrence(seq_b)

resid_a = seq_a + state_a  # residual stream: token plus state
resid_b = seq_b + state_b
ConsoleOut [5]
CollapseExpand
position     : [1 2 3 4]
x_A          : [1. 1. 0. 0.]
s_A          : [1.    1.5   0.75  0.375]
x_B          : [0.   0.   0.75 0.  ]
s_B          : [0.    0.    0.75  0.375]

final states identical : True
final residual identical: True
first residual identical: False

The output confirms the collision. Both sequences end at s4=0.375s_4 = 0.375, and because the fourth token is zero in both, the residual stream at position 4 also matches. Only the earlier positions retain any distinguishing information.

Adding one causal attention layer

The toy attention layer has one head with scalar queries and keys. Their dot product is ordinary multiplication. At position 4 the softmax runs over four scores, including the score for position 4 itself. The query and key projections select the second feature of (xt,zt)(x_t,z_t), and the value projection selects the first. The output is a weighted sum of the visible input values.

PythonIn [6]
CollapseExpand
def causal_readout(h, v, query_pos):
    """One head, scalar keys. Attends only to positions <= query_pos."""
    q = h[query_pos]
    keys = h[: query_pos + 1]
    vals = v[: query_pos + 1]

    scores = q * keys  # dot product with d = 1
    scores = scores - scores.max()  # numerically stable softmax
    weights = np.exp(scores) / np.exp(scores).sum()
    return float(weights @ vals), weights

The slice h[: query_pos + 1] is the masking: positions after the query are never touched. This is the same causal constraint described in Attention Masking, just enforced by array indexing instead of an additive mask.

PythonIn [7]
CollapseExpand
out_a, weights_a = causal_readout(resid_a, seq_a, query_pos=3)
out_b, weights_b = causal_readout(resid_b, seq_b, query_pos=3)
ConsoleOut [8]
CollapseExpand
attention weights, sequence A: [0.2962 0.3573 0.1854 0.1611]
attention weights, sequence B: [0.2038 0.2038 0.3577 0.2346]

readout at position 4, A: 0.6536
readout at position 4, B: 0.2683
readouts differ        : True

The two readouts differ even though the queries are identical. Sequence A assigns about 0.6540.654 total weight to positions 1 and 2, whose values are both 11. In sequence B the largest individual weight, about 0.3580.358, is at position 3, whose value is 0.750.75. The readouts are weighted mixtures, approximately 0.6540.654 for A and 0.2680.268 for B.

Note what this does and does not show. It shows that a single attention layer, given residual-stream access, can separate two prefixes that a scalar recurrence merges. It does not show that hybrids achieve better perplexity, that one attention layer per eight is optimal, or that this toy recurrence resembles Mamba in any quantitative way. It is a mechanism illustration.

Verifying causality

Append one token and check whether the first four readouts stay the same. Then change an existing input at position 1 to test whether the example can respond to a change inside the allowed prefix.

PythonIn [9]
CollapseExpand
def full_causal_readout(x, v):
    h = x + run_recurrence(x)
    return np.array([causal_readout(h, v, t)[0] for t in range(len(x))])


baseline = full_causal_readout(seq_a, seq_a)

# Append a future token with a large value and a large value payload.
extended_x = np.concatenate([seq_a, [5.0]])
extended_v = np.concatenate([seq_a, [7.0]])
extended = full_causal_readout(extended_x, extended_v)

# Sanity check that the test is not vacuous: perturb a past token.
perturbed_x = seq_a.copy()
perturbed_x[0] = 0.5
perturbed = full_causal_readout(perturbed_x, perturbed_x)
ConsoleOut [10]
CollapseExpand
future token leaves earlier outputs unchanged: True
perturbing position 1 changes output at position 4: True

Appending the fifth entry leaves the first four readouts unchanged in this check. The recurrence at position tt uses only inputs through tt, and the attention slice uses only keys and values through tt. Together these two facts make every readout a function of its prefix. Changing the first input changes the readout at position 4 in the second check.

Visualizing the collision

The first plot shows the scalar keys from the two prefixes. The second shows how their differences affect the weights for the query at position 4.

VisualizationsOut [12]
CollapseExpand
Grouped bar chart of scalar keys at four positions for two sequences, matching at the last position.
Scalar keys for two sequences under the toy recurrence. The scalar key differs at positions 1 through 3. The keys coincide at position 4, where the states and input values agree.
Grouped bar chart of attention weights over four positions for two sequences, with visibly different distributions.
Attention weights at query position 4. The query vector is identical for both sequences, yet the weight distributions differ because the keys at earlier positions differ.

The left figure shows equal scalar keys at position 4 and different keys at each earlier position. The right figure shows the attention weights formed from those keys. Prefixes that give the same last state can still yield different attention outputs when earlier projections differ.

Code: Cache Accounting

At what context length does the key-value cache exceed the combined recurrent and convolution state? The calculation first finds where the two payloads are equal, then finds the first whole-token length where the KV cache is larger.

What this accounting excludes

The calculation counts persistent keys and values, recurrent state, and convolution state. It leaves out model and expert weights, communication buffers, transient activations, workspaces, and padding or allocator overhead. All BB sequences in the batch have the same length and each stored element uses the same number of bytes. Unequal lengths or different storage precision require separate terms.

Byte formulas

Each quantity has a different shape and a different scaling in LL. The formulas below use:

  • LL: the number of retained positions per sequence, counting the prompt and generated tokens already processed by the model
  • nattnn_{\text{attn}}: the number of attention layers
  • nssmn_{\text{ssm}}: the number of state space layers
  • nkvn_{\text{kv}}: the number of key-value heads (grouped-query attention)
  • dheadd_{\text{head}}: the dimension per attention head
  • dinnerd_{\text{inner}}: the state space inner width
  • dstated_{\text{state}}: the state size per channel
  • dconvd_{\text{conv}}: the short-convolution history length
  • BB (batch size) and nbytesn_{\text{bytes}}: batch size and bytes per element, which cancel in the crossover
PythonIn [13]
CollapseExpand
def kv_cache_bytes(L, cfg):
    """Key and value payload across attention layers for an equal-length batch."""
    return (
        2
        * cfg["batch"]
        * cfg["n_attn_layers"]
        * L
        * cfg["n_kv_heads"]
        * cfg["d_head"]
        * cfg["nbytes"]
    )


def recurrent_state_bytes(cfg):
    """Recurrent state payload across state-space layers and sequences."""
    return (
        cfg["batch"]
        * cfg["n_ssm_layers"]
        * cfg["d_inner"]
        * cfg["d_state"]
        * cfg["nbytes"]
    )


def conv_state_bytes(cfg):
    """Short convolution history kept per state space layer."""
    return (
        cfg["batch"]
        * cfg["n_ssm_layers"]
        * cfg["d_inner"]
        * cfg["d_conv"]
        * cfg["nbytes"]
    )

The factor of 2 in the key-value formula counts one key tensor and one value tensor per attention layer. Each modeled Mamba-1 layer has a recurrent state and a separate convolution buffer with an allocated history width.

We now instantiate a configuration in the spirit of a 50B-class hybrid: width 4096, expansion factor 2, four attention layers and 28 state space layers, grouped-query attention with eight key-value heads of dimension 128, and bfloat16 storage.

PythonIn [14]
CollapseExpand
CFG = dict(
    batch=1,
    n_attn_layers=4,  # attention layers
    n_ssm_layers=28,  # state space layers
    n_kv_heads=8,  # grouped-query attention
    d_head=128,
    d_inner=8192,  # 2 * d_model, d_model = 4096
    d_state=16,
    d_conv=4,
    nbytes=2,  # bfloat16
)

The layer dimensions match the public Jamba-v0.1 configuration. The calculation assumes two bytes per stored element across the KV cache, recurrent state, and convolution buffer. To apply it to another deployment, use the model's dimensions and the runtime's storage precisions.

PythonIn [15]
CollapseExpand
def human(nbytes):
    value = float(nbytes)
    for unit in ["B", "KiB", "MiB", "GiB", "TiB"]:
        if abs(value) < 1024.0:
            return f"{value:.2f} {unit}"
        value /= 1024.0
    return f"{value:.2f} PiB"


kv_one_token = kv_cache_bytes(1, CFG)
rec_state = recurrent_state_bytes(CFG)
conv_state = conv_state_bytes(CFG)
ConsoleOut [16]
CollapseExpand
KV cache per retained token    : 16.00 KiB
recurrent state, all layers    : 7.00 MiB
convolution state, all layers  : 1.75 MiB
constant part of the state     : 8.75 MiB

The four attention layers add 16 KiB of KV cache per retained token. Across all 28 state-space layers, the recurrent state uses 7 MiB and the convolution buffers use 1.75 MiB.

Deriving the crossover

A positive within-hybrid crossover requires a growing KV cache and a positive combined recurrent and convolution payload. Batch size and bytes per element cancel because both sides share those positive factors. The equality point L∗L^* can be fractional. The first integer length where the KV cache is larger is ⌊L∗⌋+1\lfloor L^*\rfloor+1. Use the component formulas to compare pure stacks. An all-attention stack has no fixed state in this accounting, and an all-state-space stack has no KV cache.

2 nattn L nkv dhead=nssm dinner(dstate+dconv)2 \, n_{\text{attn}} \, L \, n_{\text{kv}} \, d_{\text{head}} = n_{\text{ssm}} \, d_{\text{inner}} \left(d_{\text{state}} + d_{\text{conv}}\right) L∗=nssm dinner(dstate+dconv)2 nattn nkv dheadL^{*} = \frac{n_{\text{ssm}} \, d_{\text{inner}} \left(d_{\text{state}} + d_{\text{conv}}\right)}{2 \, n_{\text{attn}} \, n_{\text{kv}} \, d_{\text{head}}}

where:

  • L∗L^{*}: the positive real-valued equality point for the KV cache and the combined recurrent and convolution state
  • nattnn_{\text{attn}}: the number of attention layers
  • nssmn_{\text{ssm}}: the number of state space layers
  • nkvn_{\text{kv}}: the number of key-value heads
  • dheadd_{\text{head}}: the dimension per attention head
  • dinnerd_{\text{inner}}: the state space inner width
  • dstated_{\text{state}}: the state size per channel
  • dconvd_{\text{conv}}: the short-convolution history length
  • the factor of 2 accounts for the key and value tensors
PythonIn [17]
CollapseExpand
from fractions import Fraction


def crossover_length(cfg):
    """Return the equality length for positive KV and fixed-state components."""
    numerator = (
        cfg["n_ssm_layers"] * cfg["d_inner"] * (cfg["d_state"] + cfg["d_conv"])
    )
    denominator = 2 * cfg["n_attn_layers"] * cfg["n_kv_heads"] * cfg["d_head"]
    if denominator <= 0:
        raise ValueError("The KV cache must have a positive per-token slope")
    if numerator <= 0:
        raise ValueError(
            "The combined recurrent and convolution payload must be positive"
        )
    return Fraction(numerator, denominator)


L_star = crossover_length(CFG)
first_overtake = L_star.numerator // L_star.denominator + 1
fixed_state = rec_state + conv_state
assert kv_cache_bytes(first_overtake - 1, CFG) <= fixed_state
assert kv_cache_bytes(first_overtake, CFG) > fixed_state
ConsoleOut [18]
CollapseExpand
equality point                  : 560 tokens
first length with larger KV cache: 561 tokens
state at 1 token                : 8.77 MiB
state at equality               : 17.50 MiB
state at 262144 tokens           : 4.01 GiB

At 560 tokens, the four attention layers use the same 8.75 MiB as the recurrent and convolution states combined. At 561 tokens, the KV cache first exceeds that fixed payload. At 262,144 tokens, the KV term alone is 4 GiB.

When attention layers share a cache layout and precision, the all-attention stack's KV term scales with its layer count and the hybrid's KV term scales with its smaller attention count. With 32 versus four attention layers, their KV terms differ by a factor of eight at every length. Add the hybrid's fixed state to compare total persistent decode state. The hybrid's fraction of the all-attention total approaches 4/32=12.5%4/32=12.5\% as LL grows, which is a reduction approaching 87.5%87.5\% in the counted state.

The same accounting makes the ratio trade-off visible at a fixed long context. The next figure fixes the context at 256K tokens and varies the layer count while holding total depth at 32.

PythonIn [19]
CollapseExpand
# Attention counts span the 1:15, 1:7, 1:3, 1:1, and pure-attention endpoints.
# Total depth is fixed at 32 layers; n_ssm is the complement. Context is fixed at 262144.
ATTENTION_COUNTS = np.array([2, 4, 8, 16, 32])
CONTEXT_FOR_RATIO = 262144
ratio_bytes = []
for n_attn in ATTENTION_COUNTS:
    cfg = dict(CFG)
    cfg["n_attn_layers"] = int(n_attn)
    cfg["n_ssm_layers"] = int(32 - n_attn)
    ratio_bytes.append(
        kv_cache_bytes(CONTEXT_FOR_RATIO, cfg)
        + recurrent_state_bytes(cfg)
        + conv_state_bytes(cfg)
    )
ratio_bytes = np.array(ratio_bytes)
ratio_gib = ratio_bytes / (1024**3)
ratio_labels = [f"{int(n)}:{32 - int(n)}" for n in ATTENTION_COUNTS]
VisualizationOut [20]
CollapseExpand
Bar chart of decode-state bytes at 256K tokens across attention ratios.
Persistent decode state at 262,144 tokens for 32-layer stacks. Each additional attention layer adds a KV cache and replaces one layer's fixed recurrent and convolution state. At this length the KV term dominates the total.

Comparing three stacks at equal depth

Compare three equal-depth stacks. The all-attention stack has 32 attention layers. The hybrid has four attention layers and 28 state-space layers. The all-state-space stack has 32 state-space layers.

The equal-stack crossover concerns replacing 28 attention layers with 28 state-space layers. Divide both sides by 28 to compare the growing KV term and the constant state term for a single layer. This gives 80 tokens with the assumed layer dimensions. At that length all three totals agree. At longer lengths, each replaced layer reduces the total state, and the all-state-space stack uses the smallest state payload of the three.

PythonIn [21]
CollapseExpand
def stack_bytes(length, n_attn, n_ssm, cfg):
    layer_counts = dict(cfg, n_attn_layers=n_attn, n_ssm_layers=n_ssm)
    return (
        kv_cache_bytes(length, layer_counts)
        + recurrent_state_bytes(layer_counts)
        + conv_state_bytes(layer_counts)
    )


attention_layer = dict(CFG, n_attn_layers=1)
ssm_layer = dict(CFG, n_ssm_layers=1)
stack_crossover = (
    recurrent_state_bytes(ssm_layer) + conv_state_bytes(ssm_layer)
) / kv_cache_bytes(1, attention_layer)
PythonIn [22]
CollapseExpand
lengths = np.unique(np.round(np.logspace(0, np.log10(262144), 240)).astype(int))
mib = 2**20
pure_attn = stack_bytes(lengths, 32, 0, CFG) / mib
hybrid = stack_bytes(lengths, 4, 28, CFG) / mib
pure_ssm = np.full(lengths.shape, stack_bytes(1, 0, 32, CFG) / mib)
assert stack_bytes(stack_crossover, 32, 0, CFG) == stack_bytes(
    stack_crossover, 4, 28, CFG
)
ConsoleOut [23]
CollapseExpand
Equal per-stack state at 80 tokens
All-attention to hybrid state ratio at 262,144 tokens: 7.98x
VisualizationOut [24]
CollapseExpand
Log-log chart of three stack totals. The totals meet at 80 tokens. In the hybrid, the KV cache equals its fixed state at 560 tokens. The all-state-space line stays flat.
Three equal-depth stacks have equal persistent decode state at 80 tokens with these layer dimensions. The two components inside the hybrid match at 560 tokens. These crossovers compare different quantities.

At one token, the 32-layer attention stack uses the smallest state payload. After 80 tokens the ordering reverses. The hybrid's curve bends because it combines constant and linear terms. At long lengths its KV term dominates and the ratio of all-attention to hybrid state approaches eight. The plot holds model width and per-layer storage fixed and counts neither parameters nor execution time.

An idealized prefill model

Use the widths from the cache example and count a multiply and an addition as two floating point operations. Write dd for the model width and dkd_k for the combined width of the grouped key heads, also the combined width of the grouped value heads. The query and output matrices each map between two dd-dimensional spaces. The key and value projections map from width dd to dkd_k. The terms for those four matrices are 4Ld24Ld^2 for query and output and 4Lddk4Ldd_k for key and value.

For each of the L(L+1)/2L(L+1)/2 valid pairs, the score uses a query–key product and the value is scaled and added to the output. Summed across query heads, the leading operation count is about 4d4d per pair. Here we count exactly the valid pairs. An actual kernel can do more work on padded blocks. The selective mixer has two input projections from dd to the expanded width did_i and one output projection back to dd. Denote the two partial estimates by FattnF_{\mathrm{attn}} and FssmF_{\mathrm{ssm}}.

Fattn(L)=4Ld2+4Lddk+2dL(L+1),Fssm(L)=6Lddi.\begin{aligned} F_{\mathrm{attn}}(L) &= 4Ld^2 + 4Ldd_k + 2dL(L+1),\\ F_{\mathrm{ssm}}(L) &= 6Ldd_i . \end{aligned}

This estimate includes three projection products for the state-space layer. Its internal parameter projections, causal convolution, state updates, and gating add work outside the estimate. The attention estimate omits the softmax and score transformations. Both estimates omit the feed-forward layer and normalization. The estimates count arithmetic and do not predict elapsed time.

Both expressions have a common factor 2Ld2Ld for positive LL and dd. Divide by it to compare 2d+2dk+L+12d+2d_k+L+1 to 3di3d_i. The two estimates match at L=3di−2(d+dk)−1L=3d_i-2(d+d_k)-1 if that gives a positive length. The formula concerns the listed operations, so other costs can move the crossover for two implemented mixers.

PythonIn [25]
CollapseExpand
def attn_layer_flops(length, model_width, kv_width):
    q_and_o = 4 * length * model_width**2
    k_and_v = 4 * length * model_width * kv_width
    pair_products = 2 * model_width * length * (length + 1)
    return q_and_o + k_and_v + pair_products


def ssm_layer_flops(length, model_width, inner_width):
    return 6 * length * model_width * inner_width
PythonIn [26]
CollapseExpand
d_model = 4096
kv_width = CFG["n_kv_heads"] * CFG["d_head"]
d_inner = CFG["d_inner"]
attention_pair_crossover = 2 * (d_model + kv_width) - 1
flop_cross = 3 * d_inner - 2 * (d_model + kv_width) - 1

flop_lengths = np.unique(np.round(np.logspace(2, 6, 200)).astype(np.int64))
attn_f = attn_layer_flops(flop_lengths, d_model, kv_width)
ssm_f = ssm_layer_flops(flop_lengths, d_model, d_inner)

projection_work = 4 * attention_pair_crossover * d_model * (d_model + kv_width)
pair_work = (
    2 * d_model * attention_pair_crossover * (attention_pair_crossover + 1)
)
assert projection_work == pair_work
assert attn_layer_flops(flop_cross, d_model, kv_width) == ssm_layer_flops(
    flop_cross, d_model, d_inner
)
ConsoleOut [27]
CollapseExpand
Equal attention projection and pair work at 10,239 tokens
Equal attention-mixer and state-space projection estimates at 14,335 tokens

With model width 4,096, combined key or value width 1,024, and state-space inner width 8,192, attention projection work equals attention pair work at 10,239 tokens. From 10,240 through 14,334 tokens, pair work is already larger than attention projection work, while the attention total is still smaller than the state-space projection estimate. The two mixer estimates meet at 14,335 tokens. Above that point, the attention total is larger.

VisualizationOut [28]
CollapseExpand
Log-log chart of attention and state-space mixer operation counts intersecting near fourteen thousand tokens, with attention rising faster above that point.
Idealized operation counts for one attention mixer and the input and output projections of one Mamba-style mixer. The model counts the accessible causal attention pairs and omits several other operations in both mixers.

Where the attention layers go

Compare three hypothetical schedules with four attention layers and 28 state-space layers. Move the attention layers between the schedules, while keeping their count and the width of each mixer fixed. The periodic schedule shows the four attention positions listed in the original Jamba checkpoint configuration.

PythonIn [29]
CollapseExpand
n_layers = 32
patterns = {
    "Periodic": [4, 12, 20, 28],
    "Prefix": [0, 1, 2, 3],
    "Suffix": [28, 29, 30, 31],
}

placement_grid = np.zeros((len(patterns), n_layers), dtype=int)
for row, attention_positions in enumerate(patterns.values()):
    placement_grid[row, attention_positions] = 1
VisualizationOut [30]
CollapseExpand
Three rows identify the four attention layers among 32 mixer layers, distributed periodically or clustered at the beginning or end.
Three schedules with four attention layers. They add the same number of position-indexed caches when their attention layers and serving configuration match.

The schedules have different depths at which an attention layer can first combine representations across positions. The periodic pattern also leaves several state-space layers between attention layers. The placements alone give no quality ranking. To measure the effect, compare these schedules under the same training setup and evaluate the tasks and prompt lengths that matter for serving.

Jamba-v0.1 model configuration

Limitations and Impact

Remaining full-attention layers still scale with context. Their caches grow linearly in sequence length and their prefill pair count is quadratic. With a smaller attention count and a matched cache layout per layer, the hybrid pays for fewer copies of that growing cache. The state-space layers add fixed-size state. The saving estimates in this chapter count persistent state and leave model weights and transient workspace outside their scope.

Layer composition changes the work a serving stack has to do. A typical hybrid has separate kernels for attention and state updates. Their performance depends on batching, precision, layout, and the hardware generation. Even an accurate operation count cannot tell you whether a machine spends more time on matrix products, bandwidth, or launch overhead. Compare time to first token and time per output token on the same workload. For prefix reuse, retain the attention cache and the matching recurrent and convolution states at the reused endpoint, or regenerate the states by replaying the necessary input.

A retrieval experiment measures a particular workload. A copying or name-and-number diagnostic has an exact answer that is easy to score. Broader evaluations can ask whether a model uses the right passage in a long document, follows the answer format, or integrates information from multiple positions. A good result on one diagnostic is a reason to run the next appropriate test.

The practical gain is a design with fewer attention layers in which later positions can still read individually represented prior positions. Jamba uses that arrangement at a 256K supported context length. The particular placement, ratio, and use of experts remain choices to test with the target data, budget, and serving workload.

Summary

  • A full-context attention layer retains keys and values indexed by position. A Mamba-1-style layer carries a fixed-shape recurrent state and convolution buffer. The hybrid keeps direct attention to retained positions at selected depths.
  • In the scalar example, different histories gave the same final recurrent state and current input. A causal attention layer produced different outputs because its earlier keys and values differed.
  • The 4+28 hybrid's key-value cache equals its recurrent and convolution state at 560 tokens and first exceeds it at 561. The equal-depth stack comparison crosses at 80 tokens.
  • Prefill arithmetic and decode-state capacity need separate estimates. Actual runtime performance also depends on the hardware, kernel implementations, and workload.
  • Jamba's 1:7 attention-to-Mamba ratio came from experiments. Read every ratio with its denominator, and identify the training or serving conditions before drawing a comparison.

Key Parameters

The key parameters for hybrid attention and state space models are:

  • n_attn_layers / n_ssm_layers: The number of attention and state space layers. The attention count scales the growing term in the cache model.
  • d_inner: The state space inner width. Larger values increase the recurrent-state size and the prefill projection cost.
  • d_state gives the number of recurrent coordinates per channel. At fixed precision, more coordinates increase the recurrent payload and the upper bound on its representable bit patterns.
  • n_kv_heads gives the number of key-value heads. At fixed head width and storage precision, fewer heads shrink the cache.
  • d_conv gives the number of convolution-history entries allocated per channel. It sets the size of the separate convolution buffer, which stays fixed as context length grows.

The next chapter, Token-Free and Byte-Level Language Models, takes a different route away from the fixed subword vocabulary, and the one after that turns to diffusion, where the sequential order of generation itself is rethought. Both face the same methodological demand that this chapter has tried to model: name the workload, name the denominator, and separate the measurement from the prediction.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about hybrid attention and state space models.

Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 6

Comparing Architecture Families Fairly

Learn how to compare Transformer, SSM, and hybrid architectures fairly with matched compute, bits per byte, roofline cost models, and clustered uncertainty.

64 min read
Language AI Handbook · Vol. 6

Blockwise and Semi-Autoregressive Generation

Explore semi-autoregressive block generation, blockwise parallel decoding, and exact speculative sampling with acceptance and residual repair rules.

42 min read
Language AI Handbook · Vol. 6

Token-Free and Byte-Level Language Models

Explore token-free byte-level language models: UTF-8 encoding, byte factorization, patching architectures like ByT5, CANINE, MEGABYTE, BLT, and fair evaluation.

54 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026hybridattention, author = {Michael Brenndoerfer}, title = {Hybrid Attention and State Space Models}, year = {2026}, url = {https://mbrenndoerfer.com/writing/hybrid-attention-state-space-models-cache-accounting}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-11-25} }
APAAcademic
Michael Brenndoerfer (2026). Hybrid Attention and State Space Models. Retrieved from https://mbrenndoerfer.com/writing/hybrid-attention-state-space-models-cache-accounting
MLAAcademic
Michael Brenndoerfer. "Hybrid Attention and State Space Models." 2026. Web. November 25, 2026. <https://mbrenndoerfer.com/writing/hybrid-attention-state-space-models-cache-accounting>.
CHICAGOAcademic
Michael Brenndoerfer. "Hybrid Attention and State Space Models." Accessed November 25, 2026. https://mbrenndoerfer.com/writing/hybrid-attention-state-space-models-cache-accounting.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Hybrid Attention and State Space Models'. Available at: https://mbrenndoerfer.com/writing/hybrid-attention-state-space-models-cache-accounting (Accessed: November 25, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Hybrid Attention and State Space Models. https://mbrenndoerfer.com/writing/hybrid-attention-state-space-models-cache-accounting
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy