12.5 Selective State Space Models
The S4D layer of Section 12.4 treats every token at lag identically: an input from steps ago contributes to the present output with the fixed convolution weight , whether that input was the key noun of a paragraph or a comma. Natural language requires content-based selection: most tokens can be discarded quickly, while a few critical tokens must be written strongly and held across hundreds of steps at positions that vary from sentence to sentence. Can a state space model decide, token by token, what to keep and for how long?
Two models from earlier sections each hold half of the answer:
MinGRU(Section 12.3) computes its decay gate from the current input token, so it can keep one token and overwrite the next, but its gates start with a one-step half-life and each channel holds only a single scalar state.S4D(Section 12.4) starts with half-lives spanning to steps across states per channel, but its dynamics are time-invariant.
Selective state space models, introduced with the Mamba architecture by Gu and Dao (2023), unify the two: the step size of the discretized SSM, along with the write vector and read vector , becomes a function of the current input . Setting freezes the state and ignores an uninformative filler token; setting large writes a salient token and decays what the state held before. Because the dynamics now vary by step, the FFT convolution no longer applies, but the parallel associative scan of Section 12.3 still trains the layer in rounds. Below we benchmark S4D and MinGRU on selective copying, show that a 1-state selective SSM is mathematically equivalent to a MinGRU gate, build SelectiveSSM and Mamba with a memory-efficient custom backward scan (adjoint_scan), inspect how a trained Mamba layer populates its state, and evaluate it on byte-level WikiText-103.
12.5.1 Selective Copying#
The synthetic selective copying benchmark of Gu and Dao (2023) isolates content-dependent retention (Figure 12.5.1). In our setup, a sequence consists of filler tokens (0), into which marked symbols (drawn uniformly from tokens 2..9) are inserted at random positions, followed by query tokens (1) at the end. At the -th query token, the model must output the -th marked symbol in order (chance accuracy ). Because the symbol positions vary randomly from sequence to sequence, any time-invariant filter that weights inputs solely by lag must fail.
The selective copying task. A few marked symbols (color) are scattered among filler tokens (grey) at positions that change from sequence to sequence; at the query tokens, the model must output the symbols in order.
def copy_batch(batch_size, num_fillers=1024, num_marked=4, num_symbols=8,
device=None):
"""Symbols at random positions among fillers, then query tokens."""
X = torch.zeros(batch_size, num_fillers + num_marked, dtype=torch.long,
device=device)
X[:, num_fillers:] = 1 # Query tokens
Y = torch.randint(2, 2 + num_symbols, (batch_size, num_marked),
device=device)
positions = torch.rand(batch_size, num_fillers, device=device).argsort(1)
X.scatter_(1, positions[:, :num_marked].sort(1).values, Y)
return X, Y
X, Y = copy_batch(2, num_fillers=12)
print(X, Y, sep='\n')tensor([[0, 0, 0, 7, 0, 2, 7, 0, 6, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 7, 7, 0, 0, 9, 5, 0, 0, 0, 0, 1, 1, 1, 1]])
tensor([[7, 2, 7, 6],
[7, 7, 9, 5]])
To evaluate models on selective copying, train_copy trains a network for 1,500 steps of Adam (lr=3e-3, batch size 64) using d2l.train_queries and evaluates query accuracy across 1,024 fresh test sequences:
torch.set_float32_matmul_precision('high') # fp32 matmuls may use tf32
def train_copy(model):
"""Train for 1,500 steps on fresh batches of selective copying; return
the test accuracy."""
num_steps = 1500
device = d2l.try_gpu()
model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=3e-3)
d2l.train_queries(model, lambda step: copy_batch(64, device=device),
num_steps, optimizer)
X, Y = copy_batch(1024, device=device)
return float(torch.stack([d2l.query_accuracy(model, X_i, Y_i) # In parts
for X_i, Y_i in zip(X.split(128), Y.split(128))
]).mean())The wrapper copy_runs trains num_runs=2 independent seeds of an architecture, prints its parameter count and test accuracies, and returns the trained models:
def copy_runs(name, make_model, num_runs=2):
"""Train num_runs fresh models; print their accuracies; return them."""
models = [make_model() for _ in range(num_runs)]
accuracies = [train_copy(model) for model in models]
print(f'{name:20s} {d2l.num_params(models[0]):6,} parameters, accuracy '
+ ', '.join(f'{acc:.2f}' for acc in accuracies))
return modelsWe first benchmark two-block d2l.SeqLM models at width using time-invariant d2l.S4D versus input-selective d2l.MinGRU as the sequence mixer:
models = {}
for name, mixer in (('S4D', lambda: d2l.S4D(48)),
('minGRU', lambda: d2l.MinGRU(48, 48))):
models[name] = copy_runs(name, lambda: d2l.SeqLM(
10, 48, [mixer() for _ in range(2)]))S4D 42,058 parameters, accuracy 0.17, 0.14
minGRU 48,202 parameters, accuracy 0.94, 0.94
As predicted, time-invariant S4D stays near chance (), whereas input-selective minGRU reaches between about and , depending on the run. Notice why minGRU succeeds here despite starting with one-step gate half-lives (which failed on 1,000-step fixed-delay recall in Section 12.4): in selective copying, marked symbols occasionally land close to the queries, providing short-horizon gradients that progressively teach the gates to hold symbols across longer filler spans (Exercise 6).
12.5.2 Selective Dynamics#
12.5.2.1 Input-Dependent Step Sizes#
We build the selective SSM in two steps. First, consider a single channel with a single state () at rate under zero-order hold (Section 12.4.1.2): . Instead of treating as a fixed parameter, compute from a linear projection of the current token. Exponentiating yields an exact algebraic identity:
Setting turns the ZOH update into , the exact convex blend of MinGRU (Section 12.3.1.3, Theorem 1 of Gu and Dao (2023)). When a filler token produces , and (retaining of the state, half-life 69 steps); when a marked symbol produces , and (overwriting the state with the new symbol). Parameterizing the gate through also makes S4D's multi-timescale initialization immediate: choosing the bias so starts the gate at half-lives of to steps, and, crucially, a single channel step size can drive states with distinct rates simultaneously.
12.5.2.2 Write and Read Vectors#
Now give each of the layer's channels ( in Mamba) an -dimensional state vector with rates initialized to . From the current -dimensional input , the layer computes per-channel step sizes together with a shared write direction and read direction :
Each channel then updates its states and reads out its output via:
One step of the selective SSM. From the input of channels, three projections compute the step sizes (one per channel), the write vector , and the read vector (each of length ). Row of the state decays by and receives ; the output reads that row with and adds the skip term .
Figure 12.5.2 shows where the three projections act: scales the rows of the state, one channel each, while and act along its columns and are shared by all channels. Following Gu and Dao (2023), (12.5.2) retains the exact ZOH decay while approximating the ZOH input weight by the first-order Euler weight (which agrees when and allows large steps to write with weight exceeding ; see Exercise 1). The shapes of all quantities in (12.5.2) are summarized below:
| Quantity | Shape | Computed from |
|---|---|---|
| input | the layer's input at step | |
| step sizes | , one per channel | , through rank- factored |
| write and read vectors , | each, shared by all channels | , through |
| rates | per channel | learned parameters initialized to |
| state | the recurrence (12.5.2) | |
| output | readout with plus skip |
12.5.3 The Mamba Layer#
12.5.3.1 Projections, Convolution, and Gate#
The Mamba block (Gu and Dao, 2023) wraps the selective SSM inside channel-mixing projections, a width-4 depthwise causal convolution, and a SwiGLU-style multiplicative output gate (Figure 12.5.3):
- An input projection expands the -dimensional input into two branches of width .
- The first branch passes through a width-4 depthwise causal convolution and SiLU activation before entering the selective SSM—allowing to condition on a 4-token local window rather than a single isolated token.
- The SSM output is multiplied elementwise by the SiLU of the second branch and projected back to width via .
- To save parameters, is factored through bottleneck rank .
The Mamba layer. The input is projected to two branches of width ; one passes through a short causal convolution, a SiLU, and the selective SSM, whose step sizes and write and read vectors are computed from its input; the other, through a SiLU, gates the result. A final projection returns to width .
12.5.3.2 Training with a Scan#
Because (12.5.2) is still an affine recurrence over the state at each step, d2l.linear_scan evaluates all states in parallel. However, expanding the state to numbers per token multiplies activation memory by : differentiating naively through rounds of a doubling scan retains tensors of shape (already per layer in our small copying model, and hundreds of gigabytes at LLM scale).
We can avoid storing the intermediate scan rounds by noting that the backpropagated state gradient satisfies the reverse-time affine recurrence:
with parameter gradients and . Thus the backward pass is simply a second call to linear_scan run in reverse time, requiring only the forward decays and states (two tensors instead of ; Mamba's fused CUDA kernel goes one step further by keeping in on-chip SRAM and recomputing it during the backward pass, as discussed in Section 13.4). Let us implement adjoint_scan with a custom backward pass and verify it against standard autograd.
class AdjointScan(torch.autograd.Function):
"""linear_scan whose backward pass is a second scan, run backward."""
@staticmethod
def forward(ctx, a, b):
h = d2l.linear_scan(a, b)
ctx.save_for_backward(a, h)
return h
@staticmethod
def backward(ctx, grad_h):
a, h = ctx.saved_tensors
# g_t = grad_h_t + a_{t+1} g_{t+1}: a linear recurrence from the end
a_next = torch.cat([a[:, 1:], torch.ones_like(a[:, :1])], 1)
g = d2l.linear_scan(a_next.flip(1), grad_h.flip(1)).flip(1)
h_prev = torch.cat([torch.zeros_like(h[:, :1]), h[:, :-1]], 1)
return g * h_prev, g
def adjoint_scan(a, b):
"""All states of h_t = a_t * h_{t-1} + b_t, differentiated by a scan."""
return AdjointScan.apply(a.expand_as(b), b)We verify on random sequences of length that differentiating adjoint_scan matches standard autograd through d2l.linear_scan to float32 precision:
a = torch.rand(2, 100, 8, requires_grad=True)
b = torch.randn(2, 100, 8, requires_grad=True)
w = torch.randn(2, 100, 8) # A loss that weights every state
grads_scan = torch.autograd.grad((d2l.linear_scan(a, b) * w).sum(), (a, b))
grads_adjoint = torch.autograd.grad((adjoint_scan(a, b) * w).sum(), (a, b))
deviation = max(float((g1 - g2).abs().max())
for g1, g2 in zip(grads_scan, grads_adjoint))
print(f'max deviation: {deviation:.1e}')max deviation: 1.4e-06
The custom reverse-time scan gradient matches autograd to .
12.5.3.3 Implementation#
SelectiveSSM implements (12.5.2), initializing dt_bias so is distributed log-uniformly on . Passing selective=False replaces with learned per-channel constants (an LTI control inside the exact same Mamba block).
class SelectiveSSM(nn.Module):
"""A diagonal SSM with N states for each of num_channels channels. Its
step sizes and write and read vectors depend on the input, or, with
selective=False, are learned constants of each channel."""
def __init__(self, num_channels, dt_rank, num_states=16, dt_min=1e-3,
dt_max=1e-1, selective=True):
super().__init__()
H, N, R = num_channels, num_states, dt_rank
self.selective = selective
self.log_neg_rate = nn.Parameter( # Rates -1, ..., -N in every channel
torch.log(torch.arange(1., N + 1)).repeat(H, 1))
dt = dt_min * (dt_max / dt_min) ** torch.rand(H)
dt_bias = dt + torch.log(-torch.expm1(-dt)) # softplus(dt_bias) = dt
if selective:
self.W_dt = nn.Sequential( # Step size per channel, rank R
nn.Linear(H, R, bias=False), nn.Linear(R, H))
self.W_B = nn.Linear(H, N, bias=False) # Write vector
self.W_C = nn.Linear(H, N, bias=False) # Read vector
d2l.init_lecun(self)
with torch.no_grad(): # Small up-projection, step sizes dt
nn.init.uniform_(self.W_dt[1].weight, -R ** -0.5, R ** -0.5)
self.W_dt[1].bias.copy_(dt_bias)
else: # Fixed dynamics: S4D with a learned write vector
self.dt_bias = nn.Parameter(dt_bias)
self.B = nn.Parameter(torch.ones(H, N))
self.C = nn.Parameter(torch.randn(H, N) / math.sqrt(N))
self.D = nn.Parameter(torch.ones(H))We next add log_coefficients to compute the per-step log-decays and writes of shape (batch_size, T, H, N), and the layer's forward pass to run adjoint_scan and contract the states with :
@d2l.add_to_class(SelectiveSSM)
def log_coefficients(self, U):
"""Log-decays and writes, each of shape (batch_size, T, H, N)."""
if self.selective: # Step sizes (batch_size, T, H), write vectors
dt, B = F.softplus(self.W_dt(U)), self.W_B(U).unsqueeze(-2)
else: # One step size and one write vector per channel
dt, B = F.softplus(self.dt_bias), self.B
b = (dt * U).unsqueeze(-1) * B
log_a = dt.unsqueeze(-1) * -torch.exp(self.log_neg_rate)
return log_a.expand_as(b), b
@d2l.add_to_class(SelectiveSSM)
def forward(self, U): # U: (batch_size, num_steps, num_channels)
log_a, b = self.log_coefficients(U)
H = adjoint_scan(torch.exp(log_a), b) # States, (batch_size, T, H, N)
C = self.W_C(U).unsqueeze(-2) if self.selective else self.C # Read
return torch.einsum('...n,...n->...', H, C) + self.D * U # Sum over nThe Mamba module wraps SelectiveSSM in the two-branch architecture of Figure 12.5.3, expanding width to via W_in, applying the causal depthwise conv and SiLU on the SSM branch, gating with silu(Z), and projecting back via W_out:
class Mamba(nn.Module):
"""The Mamba layer: a gated selective SSM between two projections."""
def __init__(self, num_hiddens, num_states=16, expand=2, conv_width=4,
**ssm_args):
super().__init__()
H = expand * num_hiddens
self.W_in = nn.Linear(num_hiddens, 2 * H, bias=False)
self.conv = nn.Conv1d(H, H, conv_width, groups=H, # One per channel
padding=conv_width - 1)
self.W_out = nn.Linear(H, num_hiddens, bias=False)
d2l.init_lecun(self) # The SSM, built next, has its own init
self.ssm = SelectiveSSM(H, math.ceil(num_hiddens / 16), num_states,
**ssm_args)
def ssm_input(self, X):
"""The input of the SSM and the gate branch."""
U, Z = self.W_in(X).chunk(2, -1)
U = self.conv(U.transpose(1, 2))[..., :X.shape[1]] # Keep it causal
return F.silu(U.transpose(1, 2)), Z
def forward(self, X): # X: (batch_size, num_steps, num_hiddens)
U, Z = self.ssm_input(X)
return self.W_out(self.ssm(U) * F.silu(Z))12.5.4 Trained Mamba Models#
12.5.4.1 Selective Copying with Mamba#
We now train Mamba ( states per channel) alongside its non-selective ablation Mamba, not selective (selective=False, keeping the exact same projections, width-4 convolution, and SiLU gate) on selective copying:
for name, selective in (('Mamba', True), ('Mamba, not selective', False)):
# Compiled, since eagerly each round of the scan would be its own kernel
models[name] = copy_runs(name, lambda: d2l.SeqLM(10, 48, [
torch.compile(Mamba(48, num_states=4, selective=selective))
for _ in range(2)]))Mamba 71,242 parameters, accuracy 0.99, 1.00
Mamba, not selective 70,090 parameters, accuracy 0.38, 0.29
Mamba copies nearly every symbol: its accuracy is or more and usually close to , ahead of minGRU. The non-selective control loses more than percentage points and scatters widely from run to run, which matches the ablation reported in Gu and Dao (2023). The projections, the convolution, and the gate are the same in both models, so the difference is due to selection alone. Exercise 3 tests zero-shot length extrapolation to fillers.
12.5.4.2 Contributions to the State#
To see how Mamba retains the four marked symbols while ignoring fillers, we decompose the final state at the first query token into the contribution of each earlier position . In the unrolled recurrence , the Euclidean norm of position 's decayed term measures how much of position 's write survives in the state at step .
def state_contributions(log_a, b):
"""Size of each position's term in the final state of h = a h + b."""
cum = log_a.cumsum(1)
terms = torch.exp(cum[:, -1:] - cum) * b # Decayed to the last step
return torch.linalg.vector_norm(terms.flatten(2), dim=-1) # (batch, T)Adding log_coefficients to d2l.S4D exposes its per-step log-decays and writes in the same (batch_size, T, d, N) format as SelectiveSSM:
@d2l.add_to_class(d2l.S4D)
def log_coefficients(self, X):
"""Log-decays and writes of the recurrence, each (batch_size, T, d, N)."""
rate = -torch.exp(self.log_neg_rate)
log_a = torch.exp(self.log_dt) * rate # log a_bar = dt * lambda
b_bar = torch.expm1(log_a) / rate
return log_a.expand(*X.shape, -1), b_bar * X.unsqueeze(-1)Which of the two layers should we look at? Nothing in the training tells a model where to do its selecting, so we probe both. layer_contributions runs the blocks below a given layer, extracts that layer's log-decays and writes on a test sequence X truncated at the first query token (X[:, :-3]), and evaluates state_contributions. We apply it to both layers of S4D and of both trained Mamba runs:
def layer_contributions(model, X, layer):
"""Contributions to the state of a layer at the last step of X."""
H = model.embedding(X)
for i in range(layer): # The blocks below it, as in the forward pass
H = H + model.mixers[i](model.norms[i](H))
H = H + model.mlps[i](H)
mixer, X = model.mixers[layer], model.norms[layer](H)
if isinstance(mixer, d2l.S4D):
return state_contributions(*mixer.log_coefficients(X))
U, _ = mixer.ssm_input(X) # Mamba: what its selective SSM reads
return state_contributions(*mixer.ssm.log_coefficients(U))
X, _ = copy_batch(1, device=d2l.try_gpu())
X = X[:, :-3] # Up to the first query token
probed = {'S4D': models['S4D'][0], 'Mamba, run 1': models['Mamba'][0],
'Mamba, run 2': models['Mamba'][1]} # Both trained Mamba runs
with torch.inference_mode(): # Both layers of each model
contributions = {(name, layer): layer_contributions(model, X, layer)[0]
for name, model in probed.items() for layer in (0, 1)}Because the width-4 causal convolution spreads each marked symbol across up to 4 consecutive positions, symbol_windows collects the 4-position window starting at each symbol ( of the sequence). For each layer we print the share of the final state that originates in those windows. For each model we then plot the contribution of all positions in the layer with the larger share:
def symbol_windows(X, width=4):
"""Positions of each symbol and the width - 1 after it, without repeats."""
starts = (X[0] > 1).nonzero().flatten() # The four symbols
offsets = torch.arange(width, device=X.device)
windows = (starts[:, None] + offsets).flatten()
windows = windows.unique() # Windows of nearby symbols may overlap
return windows[windows < X.shape[1]] # A window may reach past the end
windows = symbol_windows(X)
print(f'symbol windows: {len(windows) / X.shape[1]:.1%} of the positions')
share = {key: float(c[windows].sum() / c.sum())
for key, c in contributions.items()}
print('share of the state from them layer 1 layer 2')
for name in probed:
print(f'{name:28s} {share[name, 0]:7.2f} {share[name, 1]:7.2f}')
best = {name: max((0, 1), key=lambda layer: share[name, layer])
for name in probed} # The layer that selects more
curves = {f'{name}, layer {layer + 1}': contributions[name, layer]
for name, layer in best.items()}
d2l.plot(torch.arange(X.shape[1]), [(c / c.max()).cpu() for c in
curves.values()],
'position', 'contribution to the state',
legend=list(curves), yscale='log', figsize=(6, 3),
legend_loc='outside') # The curves fill the axessymbol windows: 1.6% of the positions
share of the state from them layer 1 layer 2
S4D 0.03 0.01
Mamba, run 1 0.94 0.90
Mamba, run 2 0.70 0.68
The share depends on where the symbols happen to fall in one sequence. A local measure is the spike ratio: the maximum contribution inside a symbol's 4-step window, divided by the contribution of the filler token immediately preceding it. We compute its median over the symbols of 64 fresh test sequences, again in both layers:
X_test = copy_batch(64, device=X.device)[0][:, :-3] # 64 new sequences
rows, starts = (X_test[:, 1:] > 1).nonzero(as_tuple=True) # The symbols,
starts = starts + 1 # not at position 0
window = (starts[:, None] + torch.arange(4, device=X.device)).clamp(
max=X_test.shape[1] - 1) # A window may reach past the end
def spike_ratio(c): # Median over the symbols
return float((c[rows[:, None], window].amax(1) / c[rows, starts - 1])
.median())
print(f'spike ratio, median over {len(rows)} symbols layer 1 layer 2')
with torch.inference_mode():
for name, model in probed.items():
spikes = [spike_ratio(layer_contributions(model, X_test, layer))
for layer in (0, 1)]
print(f'{name:36s} {spikes[0]:9,.1f} {spikes[1]:9,.1f}')spike ratio, median over 256 symbols layer 1 layer 2
S4D 27.8 1.5
Mamba, run 1 2,933.1 5,654.5
Mamba, run 2 1,416.0 4,980.2
The profile of S4D follows recency: it rises smoothly toward the end of the sequence, and the symbol windows supply only a few percent of the state, not much more than their share of the positions. A symbol does stand out from the filler before it, by a factor of a few tens at most, because a fixed filter can respond more strongly to one token than to another. It cannot hold that token for longer. In Mamba, a layer that selects lifts the symbols above the neighboring fillers by a factor of several hundred to tens of thousands, and the four windows supply a large part of its state, often most of it. Training does not decide in advance which layer this is. In some runs both layers select; in others only one does, it may be either, and the spike ratio of the other layer is then no larger than that of S4D. This is why the tables list both layers and the plot shows the more selective one.
How does a layer produce such a spike? The natural guess is that it takes a large step on every symbol, which writes the symbol and flushes the fillers before it. The step sizes of the trained models say otherwise. Averaged over the channels, the step on a symbol is usually no larger than the step on a filler. Selection is the work of very few channels: each symbol is carried by two or three of them. On fillers these channels take steps of about , so that they neither decay nor write, and their state is frozen. On the symbol the same channels take steps between about and , and since the write is proportional to the step, the symbol enters the state at full strength. Such a step also decays what the channel held before, but only by a small factor, and erasing the preceding fillers adds little to the spike. Selection here is a strong write into a few frozen channels, not a flush of the state.
12.5.4.3 Language Modeling#
Finally, we compare Mamba, minGRU, and attention on our byte-level WikiText-103 benchmark (d2l.SeqLM, 4 blocks at width , 128-byte windows, 1,000 steps). We first load the 128-byte WikiText103 stream:
data = d2l.WikiText103(batch_size=64, num_steps=128)Next we define text_model(mixer, d) and configure the four experimental arms, including a parameter-matched minGRU, d=309 ( parameters) that matches Mamba's expanded-channel parameter count:
def text_model(mixer, d): # 256 byte values; four blocks of width d
return d2l.SeqLM(256, d, [mixer(d) for _ in range(4)]).to(d2l.try_gpu())
mamba = lambda d: torch.compile(Mamba(d)) # Compiled, as in the copying
min_gru = lambda d: d2l.MinGRU(d, d)
attention = lambda d: d2l.AttentionMixer(d, num_heads=8)
arms = {'Mamba': (mamba, 256), 'minGRU': (min_gru, 256),
'attention': (attention, 256),
'minGRU, d=309': (min_gru, 309)} # As many parameters as MambaCalling d2l.text_table trains two seeds of each architecture for steps and tabulates validation loss across window position bands alongside step latency:
trained = d2l.text_table(text_model, arms, data) validation 0-15 16-63 64-127 ms/step
Mamba 3,989,248 1.298/1.297 1.488/1.488 1.272/1.272 1.269/1.268 69/69
minGRU 2,764,544 1.349/1.346 1.523/1.521 1.324/1.321 1.325/1.321 27/27
attention 3,286,784 1.378/1.383 1.557/1.559 1.354/1.359 1.351/1.357 21/21
minGRU, d=309 3,991,918 1.325/1.328 1.509/1.509 1.300/1.302 1.298/1.301 27/28
Mamba reaches nats/byte—matching the full LSTM and GRU of Section 12.1.4.2 while training via a parallel scan, and outperforming equal-width minGRU by nats/byte and parameter-matched minGRU, d=309 by nats/byte. Because Mamba scans an -number state per token ( larger than minGRU's 256-number state), its un-fused training step takes – longer than minGRU, though at inference time that -number state (plus numbers for the width-4 convolution buffer) equals the KV cache of just 19 tokens of multi-head attention. Moreover, viewing Mamba's state as an outer-product matrix memory updated by and queried by leads directly to the matrix-state recurrences and chunked matrix-multiply training of Section 12.6.
12.5.5 Summary#
Time-invariant state space models weight past inputs purely by lag and fail on content-selective tasks such as selective copying. Selective state space models compute per-channel step sizes and shared write and read vectors from each input token. For a single state (), recovers the MinGRU update gate; with states initialized at rates and log-uniform biases, Mamba combines content selection with multi-timescale memory. Differentiating the parallel scan via a reverse-time scan (adjoint_scan) avoids storing the intermediate doubling rounds. On selective copying, Mamba reaches accuracy or more (dropping by points when selectivity is disabled), which it owes to a few channels that stay frozen on fillers and write each symbol with a large step, and on byte-level WikiText-103 it matches the full LSTM and GRU while outperforming a parameter-matched MinGRU by nats/byte.
12.5.6 Exercises#
-
The approximate write. Mamba keeps the decay of the zero-order hold but writes with weight instead of .
- For , find the largest for which the two weights differ by less than 10%.
- For one state with , write vector 1, and the exact weight, show that a state that starts at zero stays within the interval spanned by zero and the inputs it has seen. Find a sequence of inputs in for which the state with weight leaves that interval. What keeps the values of a trained Mamba model in range?
-
Memory of the scan. For a Mamba layer with channels and states, a minibatch of sequences of length , and 32-bit numbers, count the bytes that backpropagation stores for the scan, (a) through the rounds of the doubling scan, (b) with the adjoint scan, and (c) with a kernel that stores only the inputs of the layer and recomputes the states. Evaluate the three for , , , and , and compare with the memory of a GPU.
-
[code] Longer sequences. Evaluate the Mamba model trained with 1,024 positions before the queries on sequences with 2,048 and 4,096 (
num_fillers), without retraining.- Does it still copy the symbols? Compare with the minGRU.
- For each channel of the more selective layer, compute the decay of its slowest state over 1,000 filler tokens. How many channels can carry a symbol across 4,096 fillers?
-
[code] Which part must be selective? ●
- Between the two Mamba models of this section lie two more: input-dependent step sizes with fixed write and read vectors and , and fixed step sizes with input-dependent and . Train both, twice each. Which of them solve the task? Relate the result to the spike ratios measured above.
- In the trained Mamba model, replace the step sizes of both layers at the four positions starting at each symbol (the windows measured above) by their median over the filler positions, so that no layer can write the symbols with a large step. How much does the accuracy drop? Repeat with the step sizes at all other positions replaced by their median over the windows, so that no layer can skip the fillers. Then intervene on one layer at a time. Does the result agree with the shares measured above?
-
[code] Generation. Add a method
steptoSelectiveSSMand toMambathat processes one token, given the state of the SSM and the last three inputs of the convolution, and returns the output and the new state. Check that stepping through a sequence reproduces the outputs of the forward pass. How many numbers does the layer carry from token to token? -
[code] Short initial memories. The minGRU learned to copy although its gates start with a memory of about one step. Test the explanation that the symbols closest to the queries teach the gates.
- Record the minGRU's gates on filler tokens before and after training, and, for the trained model, its accuracy on each query separately, sorted by the distance between the symbol and its query. Which symbols does it copy best?
- Train the Mamba model with step sizes initialized between 0.5 and 1
(
dt_min=0.5, dt_max=1.0), so that every state starts with a memory of at most two steps. Does it learn to copy the symbols within the training budget? If so, plot the step sizes of the first layer on filler tokens before and after training. - Repeat both with 4,096 positions before the queries, where a symbol near a query is rarer, and with the minGRU initialized as in the long-range recall experiment of Section 12.4.