State Space Models for Language › Worked Example

Michael BrenndoerferNovember 17, 20266 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 133State Space Models for Language › Worked Example
Reading section 9 of 13 · Worked Example · 6 minSection 9 of 13 · 6 min

Section 9 of 13 · 6 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The first NumPy example verifies that a fixed layer's recurrence and causal convolution give the same output within tolerance. The second uses a scalar state to show what happens when a programmed write must survive several updates.

A Fixed Linear SSM, Computed Two Ways

We construct a diagonal system with four stable modes, sample it with a zero-order hold, and then compute the output by (a) running the recurrence and (b) building the kernel and convolving. If the algebra in the previous sections is right, the two outputs agree to floating-point precision.

PythonIn [9]
CollapseExpand
import numpy as np

rng = np.random.default_rng(11)
N, L = 4, 24

# Draw four rate magnitudes from a log-uniform range.
a = -np.exp(rng.uniform(np.log(0.05), np.log(2.0), size=N))
B = rng.normal(size=N)
C = rng.normal(size=N)
D = 0.25
step = 0.1
ConsoleOut [10]
CollapseExpand
continuous rates a: [-0.0803 -0.3154 -0.4598 -0.0556]
input map B:        [-0.298 -0.527  0.57  -0.056]
readout map C:      [ 0.747 -1.847  1.567 -0.096]
direct path D:      0.25
step size Delta:    0.1

The rates are all negative, so every mode is stable and every discrete pole lies strictly inside the unit circle. Next we discretize with the zero-order hold from the earlier derivation.

PythonIn [11]
CollapseExpand
Abar = np.exp(step * a)  # diagonal of exp(Delta A)
Bbar = np.expm1(step * a) / a * B  # (integral of exp(tau A) dtau) B
ConsoleOut [12]
CollapseExpand
mode 0: a=-0.0803  Abar=0.9920  half-life=86.27 steps
mode 1: a=-0.3154  Abar=0.9690  half-life=21.98 steps
mode 2: a=-0.4598  Abar=0.9551  half-life=15.07 steps
mode 3: a=-0.0556  Abar=0.9945  half-life=124.71 steps

The printed half-lives tell you how quickly an existing contribution fades in each mode. Next, draw an input sequence and apply the recurrence from zero initial state.

PythonIn [13]
CollapseExpand
u = rng.normal(size=L)

x = np.zeros(N)
y_recurrent = np.empty(L)
for k in range(L):
    x = Abar * x + Bbar * u[k]
    y_recurrent[k] = C @ x + D * u[k]

The second computation builds the kernel taps Kˉj=CAˉ jBˉ\bar{K}_j = C\bar{A}^{\,j}\bar{B} and folds the direct path into the j=0j = 0 tap. Then it evaluates the causal convolution directly, in O(L2)O(L^2) fashion, which is fine at this scale.

PythonIn [14]
CollapseExpand
kernel = np.empty(L)
example_positions = np.arange(L)
power = np.ones(N)  # Abar^0
for j in range(L):
    kernel[j] = C @ (power * Bbar)
    power = power * Abar  # Abar^(j+1)
kernel[0] += D  # direct path lives on the first tap

y_conv = np.zeros(L)
for k in range(L):
    for j in range(k + 1):
        y_conv[k] += kernel[j] * u[k - j]

kernel_conv_matches = np.allclose(y_recurrent, y_conv, atol=1e-12, rtol=0.0)
assert kernel_conv_matches
ConsoleOut [15]
CollapseExpand
max |recurrent - convolution| = 4.441e-16
first six kernel taps: [0.4115 0.1548 0.1483 0.1421 0.1362 0.1305]
  of which the j=0 tap contains D = 0.25
recurrence matches causal convolution: True

The recurrence and causal convolution agree within the absolute tolerance of 10−1210^{-12}. In this run the maximum difference is about 4.44×10−164.44\times10^{-16} because the computations accumulate floating-point terms in a different order.

The plots show the first LL kernel taps and both output sequences. The model can use additional taps if it processes a longer sequence.

VisualizationsOut [16]
CollapseExpand
Bar chart of decaying convolution kernel taps.
Full taps $\bar{K}_j + D\,\mathbb{1}\{j=0\}$ of the discretized four-mode system.
Line plot of recurrent and convolution outputs whose curves overlap at the plot scale.
Output computed by the recurrence and by causal convolution. The two agree to floating-point precision.

The lag-zero bar includes the direct contribution D=0.25D=0.25. At other lags the bar is a signed sum of decaying modes. The recurrence and convolution output curves overlap at this plot scale.

A Hand-Programmed Read/Write Toy

A single state coordinate makes the effect of retention visible. Program a write at one position and multiply the state by a chosen retention factor at the other positions.

The scalar recurrence is xk=rkxk−1+wkx_k = r_k x_{k-1} + w_k, where rkr_k controls how much of the old state survives and wkw_k is the additive write. We program two actions.

  • Overwrite. At the write position, set rk=0r_k=0 and wk=vw_k=v so the new state equals vv.
  • Retain. At every other position, set wk=0w_k=0 and multiply the state by the chosen retention factor rkr_k.
PythonIn [17]
CollapseExpand
def run_toy(retain, write_at=8, tokens=64, value=1.0):
    """Overwrite a scalar state once and apply retention at all other positions."""
    x = 0.0
    trace = np.empty(tokens)
    for k in range(tokens):
        if k == write_at:
            x = value  # programmed overwrite
        else:
            x = retain * x  # zero write, retain part of the state
        trace[k] = x
    return trace


positions = np.arange(64)
retain_values = [1.0, 0.99, 0.95, 0.90]
traces = {r: run_toy(r) for r in retain_values}
trace_recent = run_toy(0.90, write_at=56)
ConsoleOut [18]
CollapseExpand
 retention    readout at k=63    relative to write
      1.00           1.000000              100.0%
      0.99           0.575355               57.5%
      0.95           0.059539                6.0%
      0.90           0.003043                0.3%

recent write at k=56 with retention 0.90: 0.478297 (47.8% of the written value)

The write at position 8 has 55 updates left before the readout at position 63. The remaining value is r55r^{55} for retention rr. At r=0.99r=0.99 about 58% survives, and at r=0.90r=0.90 about 0.3% survives. A write at position 56 undergoes only seven updates, so 0.9070.90^7 leaves about 48%.

In a learned selective layer, varying the step size changes the corresponding retention factor for that channel. For finite a<0a<0 and finite Δk>0\Delta_k>0, the exact exponential is strictly between zero and one. A small positive step brings it close to one. The toy uses both endpoints: rk=0r_k=0 discards the old state during an overwrite, and rk=1r_k=1 preserves it exactly when the write is zero.

VisualizationOut [19]
CollapseExpand
State traces after writes at positions 8 and 56. The retention-one trace remains level.
Four traces show retention after an overwrite at position 8. The dashed trace places the overwrite at position 56 and uses retention 0.90.

At position 8, each solid curve rises to one. Once written, its state declines geometrically at the selected retention factor, or stays at one for the ideal hold. The dashed curve moves the write to position 56.

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