Hybrid Attention and State Space Models › Worked Example: Two Sequences, One State
Language AI HandbookAll chapters To see the mechanism rather than the benchmark numbers, we can build the smallest possible case. Use a scalar recurrence with a fixed decay:
where:
- : the scalar recurrent state at position
- : the scalar recurrent state at the previous position
- : the scalar input at position
- : the fixed decay factor, set to
- : the initial state, set to
The Mamba-1-style mixer described above uses input-dependent decay, 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:
- Sequence B:
Running the recurrence with and :
| position | ||||
|---|---|---|---|---|
| 1 | 1.00 | 1.0000 | 0.00 | 0.0000 |
| 2 | 1.00 | 1.5000 | 0.00 | 0.0000 |
| 3 | 0.00 | 0.7500 | 0.75 | 0.7500 |
| 4 | 0.00 | 0.3750 | 0.00 | 0.3750 |
At the two states are identical, , despite the sequences sharing almost nothing. A decoder that reads only the state at position 4, plus the current token (which is 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 in the first feature. In the second, add the input and the state to get . The query and key each select , while the value selects . This gives the following scalar keys.
At position 4 both query scalars equal . 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]Expand
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 sThe function returns the state at every position, not just the last one, because we want to inspect the trajectory.
PythonIn [4]Expand
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_bConsoleOut [5]Expand
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 , 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 , and the value projection selects the first. The output is a weighted sum of the visible input values.
PythonIn [6]Expand
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), weightsThe 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]Expand
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]Expand
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 total weight to positions 1 and 2, whose values are both . In sequence B the largest individual weight, about , is at position 3, whose value is . The readouts are weighted mixtures, approximately for A and 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]Expand
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]Expand
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 uses only inputs through , and the attention slice uses only keys and values through . 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]Expand


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.
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!