From State Space Models to Mamba-2: Working Through SSD
The line that slowed me down in the Mamba-2 blog series was $Q\,\mathrm{cumsum}(K^\top V)$. If you compute $K^\top V$ as an ordinary matrix product, the token axis disappears. What, then, are you taking a cumulative sum over?
The answer is to keep one outer product per token, then accumulate them along the sequence. That small distinction explains both the state in linear attention and the chunked algorithm in Mamba-2. This post works through the derivation, then traces what happens to a six-token sequence in the reference PyTorch implementation. It is a companion to the Mamba-2 series on Tri Dao’s blog. Part I: The Model · Part II: The Theory · Part III: The Algorithm
What does a state-space layer store?
Consider a single SSD head. Token $t$ supplies an input $X_t\in\mathbb R^P$, a write vector $B_t\in\mathbb R^N$, a read vector $C_t\in\mathbb R^N$, and a scalar retention factor $a_t\in \mathbb{R}$. Treat these vectors as columns. The state $H_t\in\mathbb R^{N\times P}$ updates as
\[Z_t=B_tX_t^\top,\qquad H_t=a_tH_{t-1}+Z_t,\qquad Y_{t,:}=C_t^\top H_t.\]$B_tX_t^\top$ is an outer product. If $X_t$ has two features, the update has two columns, $X_{t,1}B_t$ and $X_{t,2}B_t$. Each feature has its own state column, and the head shares the same $a_t,B_t,C_t$ across those columns. Given those coefficients, this operation mixes positions independently for each input feature. In the full block, learned projections mix features and produce input-dependent coefficients. The learned parameters that generate them are shared across positions. Mamba-2 Part I
The sequence length $T$ counts the tokens we process. The state stays $N\times P$ as $T$ grows. To process another token, we need the previous state and that token’s new coefficients.
From the recurrence to a matrix over tokens
Assume $H_0=0$. After three tokens,
\[\begin{align*} H_1 &= Z_1 \\ H_2 & = a_2 Z_1 + Z_2 \\ H_3&=a_3a_2 Z_1+a_3 Z_2+Z_3. \end{align*}\]The write $Z_1$ enters at token 1, then goes through the decays at tokens 2 and 3. More generally, the amount of the write at $s$ that survives through $t$ is
\[L_{ts}= \begin{cases} \displaystyle\prod_{j=s+1}^{t}a_j,&s\leq t,\\ 0,&s>t. \end{cases}\]The diagonal is $1$ because a write enters after its own token’s decay is applied to the old state. The upper triangle is $0$ because future writes contribute nothing. Here $L$ multiplies the scores. The additive $-\infty$ mask familiar from softmax attention belongs to a different operation.
Read the state with $C_t$ and substitute the outer products:
\[Y_{t,:}=C_t^\top\sum_{s\leq t}L_{ts}B_sX_s^\top=\sum_{s\leq t} L_{ts}(C_t^\top B_s)X_s^\top.\]Stack $B_t^\top$, $C_t^\top$, and $X_t^\top$ into the rows of $B$, $C$, and $X$. The score $C_t^\top B_s$ is entry $(t,s)$ of $CB^\top$, so we get
\[Y=\left[L\odot(CB^\top)\right]X.\]This is Equation (3) in Mamba-2 Part II, with the output multiplication written explicitly. The scalar transition is what lets $L_{ts}$ sit outside the dot product. With general matrix transitions $A_t$, the coefficient instead involves $C_t^\top A_t\cdots A_{s+1}B_s$.
From the matrix back to the recurrence
Use the attention names $Q=C$, $K=B$, and $V=X$. Fix output token $t$ and output feature $p$. The contraction in Part II is
\[Y_{tp} = \sum_s\sum_n Q_{tn}K_{sn}V_{sp}L_{ts} = \sum_n Q_{tn}\underbrace{\left(\sum_s L_{ts}K_{sn}V_{sp}\right)}_{H_t[n,p]}.\]Here $s$ indexes source tokens and $n$ indexes state coordinates. On the other hand, summing over $n$ first gives a score for each pair of tokens. Summing over $s$ first gives a whole state matrix for each output position.
With the ordinary causal mask $L_{ts}=\mathbf 1[s\le t]$, the state is a prefix sum:
\[H_t=\sum_{s=1}^{t}K_{s,:}^\top V_{s,:}=K_{1:t,:}^\top V_{1:t,:},\qquad Y_{t,:}=Q_{t,:}H_t,\]where $K_{s,:}\in\mathbb{R}^{1\times N}$ and $V_{s,:}\in\mathbb{R}^{1\times P}$ are $s$-th row of $K$ and $V$, respectively. Thus, each $K_{s,:}^\top V_{s,:}$ is an $N\times P$ outer product at one token. These are the matrices that cumsum adds. A full $K^\top V$ is already their total sum. You can compute every prefix efficiently by adding one new outer product to the previous prefix, at a cost of $O(TNP)$ for the full sequence. Computing every prefix product independently would repeat the work.
For SSD, $L_{ts}=a_tL_{t-1,s}$ for every $s<t$, and $L_{tt}=1$. Therefore
\[H_t = \sum_{s<t}a_tL_{t-1,s}Z_s+Z_t = a_tH_{t-1}+Z_t.\]The same scalar $a_t$ applies to all earlier contributions. That’s what lets the code carry one state forward. Mamba-2 Part II
What exp(segsum(A)) actually computes
From here on, A means the variable in the reference code. It holds the logarithms of the discrete retention factors $\log a_t$. Consider the chunk $[4,5,6]$. Taking the cumulative sum inside this chunk gives
The version of segsum shown first in Part III inserts a singleton dimension after or before this vector. The resulting shapes are $3\times1$ and $1\times3$. Broadcast subtraction computes $p_t-p_s$ at entry $(t,s)$. The mask replaces entries with $s>t$ by $-\infty$. Then exp acts elementwise:
For example, row 6, column 4 is $\exp(\log(a_4a_5a_6)-\log a_4)=a_5a_6$. The factor $a_4$ cancels because the write at token 4 enters after the old state has been scaled by $a_4$. The $-\infty$ in segsum becomes $0$ in $L$ because $e^{-\infty}=0$.
The reference repository also includes a more stable implementation. It builds one cumulative sum per source column, starting just after that source position. In both versions, the mathematical result is the sum of log decays over the segment $(s,t]$. Computing the sum directly avoids subtracting nearly equal prefix sums. Part III: Stability · Reference implementation
Follow token 5 through the SSD implementation
Use six tokens and a chunk length of three. The chunks are $[1,2,3]$ and $[4,5,6]$. In the code, b is batch, c is chunk, l is position within a chunk, h is head, p is input/output feature, and n is state coordinate. An einsum sums over index letters absent from its output. A letter such as c that survives keeps the operands aligned at the same chunk.
The initial rearrangement splits the sequence axis into c,l. It puts A in layout (b,h,c,l) for cumsum and segsum, which work along the last axis. B and C use (b,c,l,h,n), while X uses (b,c,l,h,p). The states in the code have trailing axes p,n, so each stored matrix is the transpose of the $H_t\in\mathbb R^{N\times P}$ used in the equations. The selected code lines below follow the reference implementation. Minimal SSD source
1. Compute the outputs from writes in the same chunk
Y_diag = torch.einsum("bclhn,bcshn,bhcls,bcshp->bclhp", C, B, L, X)
Here l is the destination token within a chunk and s is the source. If we fix a batch item, a chunk, and a head, the summation is simplified as
This line sums over n to form the read–write dot product $C_t^\top B_s$, and over s to combine the decayed writes. For the chunk $[4,5,6]$ in our example, destination token 5 is the second position within the chunk. The einsum sums over all three source positions, but the corresponding row of $L_{5,:}$ is $[a_5,1,0]$. So only two terms survive:
The output has shape (b,c,l,h,p). We have an output vector at every token, even though the code can compute the chunks independently at this stage.
2. Summarize each chunk’s writes in one state
decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
states = torch.einsum("bclhn,bhcl,bclhp->bchpn", B, decay_states, X)
The slice -1: keeps a length-one position axis, so the final log prefix broadcasts across all positions. The subtraction and exponentiation produce $[a_5a_6,a_6,1]$ for the second chunk. This is the last row of its local decay matrix. It tells us how far each write has to travel to reach the end of the chunk.
The einsum sums over l and keeps p,n.
Let’s fix a batch, chunk, and head dimension:
\[\begin{align*} \text{states}[p,n]= \sum_{l}B[l,n]\text{decay_states}[l]X[l,p]. \end{align*}\]Recall that the decay_states for the second chunk is $[a_5a_6, a_6, 1]$. Then entry $(p,n)$ in the local state for the second chunk $[4,5,6]$ is
In the notation used here, the whole state is $S_2=a_5a_6Z_4+a_6Z_5+Z_6$. It contains just the second chunk’s writes, accumulated as if the state entering that chunk were zero. The tensor states holds $[S_1,S_2]$ and has shape (b,2,h,p,n). The $2$ is the number of chunks in this example.
3. Pass states between chunks
if initial_states is None:
initial_states = torch.zeros_like(states[:, :1])
states = torch.cat([initial_states, states], dim=1)
decay_chunk = torch.exp(segsum(F.pad(A_cumsum[:, :, :, -1], (1, 0))))
new_states = torch.einsum("bhzc,bchpn->bzhpn", decay_chunk, states)
states, final_state = new_states[:, :-1], new_states[:, -1]
states[:, :1] keeps a chunk axis of length one. That gives the default zero state the right shape to prepend along the chunk axis. After cat, the input states are $[H_0,S_1,S_2]$.
Constructing decay_chunk. Recall that A_cumsum has shape (b,h,c,l): batch, head, chunk, and position within the chunk. Our two chunks of three tokens give shape (b,h,2,3). For a fixed batch item and head, A_cumsum[b,h] is a $2\times3$ matrix with one row per chunk:
In A_cumsum[:, :, :, -1], the third : keeps every chunk and -1 selects the last position within each chunk. Because -1 is an integer index, it fixes that position and removes its axis. Each chunk row now contributes one scalar, so the shape changes from (b,h,2,3) to (b,h,2).
Write $d_1=a_1a_2a_3$ and $d_2=a_4a_5a_6$, so the selected values are $[\log d_1,\log d_2]$ for this batch item and head. Then F.pad(..., (1, 0)) adds a zero on the left, giving one entry for each boundary: before token 1, after token 3, and after token 6.
The prefix-subtraction version of segsum starts from that padded vector and takes a new cumulative sum, across chunk boundaries. The original A_cumsum reset at the start of each chunk. These new prefixes accumulate from the start of the sequence:
Broadcast subtraction takes the destination prefix minus the source prefix. For example, the entry with row “after token 6” and column “after token 3” is $(\log d_1+\log d_2)-\log d_1=\log d_2$. After masking the upper triangle, the log matrix is
\[\operatorname{segsum}\big([0,\log d_1,\log d_2]\big)= \begin{bmatrix} 0 & -\infty & -\infty\\ \log d_1 & 0 & -\infty\\ \log d_1+\log d_2 & \log d_2 & 0 \end{bmatrix}.\]Exponentiating elementwise turns a sum of log decays into a product. Each diagonal $0$ becomes $1$, meaning a contribution stays at the same boundary without any extra decay. Each $-\infty$ becomes $0$, so later chunks contribute nothing to earlier boundaries. The resulting matrix is decay_chunk, which the next line applies to $[H_0,S_1,S_2]$:
\(\underbrace{
\begin{bmatrix}
1&0&0\\
d_1&1&0\\
d_2d_1&d_2&1
\end{bmatrix}}_{\texttt{decay_chunk}}
\begin{bmatrix}H_0\\S_1\\S_2\end{bmatrix}=
\begin{bmatrix}H_0\\H_3\\H_6\end{bmatrix}.\)
The columns are sources: the initial state, the first chunk’s local state at its end, and the second chunk’s local state at its end. The rows are the destinations where we want the complete state. To compute $H_6$, $S_1$ must cross the second chunk and pick up $d_2$. $S_2$ is already at the destination and gets weight $1$. Each matrix entry multiplies an entire state, coordinate by coordinate. That’s why the einsum sums over the source boundary c and keeps the state axes p,n.
Finally, new_states[:, :-1] gives $[H_0,H_3]$, one incoming state per chunk. The last entry $H_6$ is saved separately in final_state. A continuation can start from it.
4. Read the incoming state at each destination token
state_decay_out = torch.exp(A_cumsum)
Y_off = torch.einsum("bclhn,bchpn,bhcl->bclhp", C, states, state_decay_out)
Fix a batch item, a chunk, and a head. The einsum then sums over the state coordinates $n$:
state_decay_out gives the decay from the chunk entrance to each destination token. For the chunk $[4,5,6]$, exponentiating the cumulative log decays gives $[a_4,\ a_4a_5,\ a_4a_5a_6]$. All three tokens read the same incoming state $H_3$, but each applies its own decay. The shared chunk index c pairs tokens 1–3 with $H_0$ and tokens 4–6 with $H_3$.
For token 5 and a fixed feature $p$, the code takes a dot product over n:
Add this to the contribution from step 1 and recover the full output:
\[\begin{aligned} Y_{5,:} &=\underbrace{C_5^\top(a_5Z_4+Z_5)}_{\text{current chunk}} +\underbrace{C_5^\top(a_4a_5H_3)}_{\text{earlier chunks}}\\ &=C_5^\top\big[a_5(a_4H_3+Z_4)+Z_5\big]. \end{aligned}\]The last line is just two recurrent updates starting from $H_3$. The reference code adds Y_diag and Y_off, merges the chunk and position axes, and returns the output and final state.
Follow the two contributions to token 5
At token 5, SSD reads an incoming state from tokens 1–3 and adds the output from writes at tokens 4 and 5. Follow the two paths down to see how the four stages in Part III fit together. Mamba-2 Part III
S₁
H₃ = d₁H₀ + S₁
Y_off[5] = C₅ᵀ(a₄a₅H₃)
Y_diag[5] = C₅ᵀ(a₅Z₄ + Z₅)
Y₅ = Y_off[5] + Y_diag[5]
To connect the left path to the block matrix, follow just the write from token 2. It enters $S_1$ as $a_3 Z_2$, is included in $H_3$ at the shared boundary, and picks up $a_4a_5$ on the way to token 5. The yellow factor for this pair is $1$ because the first chunk ends where the second begins. In the matrix product, the factors appear in reverse order to the path in the figure:
\[M_{5,2}= \underbrace{(a_4a_5)C_5^\top}_{\text{blue}} \;\underbrace{1}_{\text{yellow}}\; \underbrace{a_3B_2}_{\text{green}}.\]Why arrange the computation this way?
Steps 1 and 2 can run across all chunks in parallel because they depend only on local inputs. Once step 3 supplies the incoming states, step 4 can also run across all chunks in parallel. That exposes matrix multiplications for the accelerator while reducing the recurrence to one update per chunk. The reference implementation shows step 3 with a dense matrix over boundaries. With a fixed chunk length, that particular step still grows quadratically in the number of chunks. The optimized implementation uses a scan to perform the state passing. Mamba-2 Part III
References
-
Tri Dao and Albert Gu. Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality. ICML 2024.