Hybrid Attention and State Space Models › Worked Example: Two Sequences, One State

Michael BrenndoerferNovember 17, 20268 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 134Hybrid Attention and State Space Models › Worked Example: Two Sequences, One State
Reading section 7 of 12 · Worked Example: Two Sequences, One State · 8 minSection 7 of 12 · 8 min

Section 7 of 12 · 8 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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.

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!

Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy