12.5 Selective State Space Models

The S4D layer of Section 12.4 treats every token at lag kk identically: an input from kk steps ago contributes to the present output with the fixed convolution weight KkK_k, 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 11 to ∼700\sim 700 steps across NN 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 Δt\Delta_t of the discretized SSM, along with the write vector Bt\mathbf{B}_t and read vector Ct\mathbf{C}_t, becomes a function of the current input xt\mathbf{x}_t. Setting Δt→0\Delta_t \to 0 freezes the state and ignores an uninformative filler token; setting Δt\Delta_t 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 O(log⁡2T)O(\log_2 T) 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 1,0241{,}024 filler tokens (0), into which 44 marked symbols (drawn uniformly from tokens 2..9) are inserted at random positions, followed by 44 query tokens (1) at the end. At the jj-th query token, the model must output the jj-th marked symbol in order (chance accuracy 1/8=0.1251/8 = 0.125). Because the symbol positions vary randomly from sequence to sequence, any time-invariant filter that weights inputs solely by lag T−sT - s must fail.

Figure 12.5.1:

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 models

We first benchmark two-block d2l.SeqLM models at width d=48d = 48 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 (≤0.20\le 0.20), whereas input-selective minGRU reaches between about 0.750.75 and 0.950.95, 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 (N=1N = 1) at rate λ=−1\lambda = -1 under zero-order hold (Section 12.4.1.2): ht=e−Δht−1+(1−e−Δ)xth_t = e^{-\Delta} h_{t-1} + (1 - e^{-\Delta}) x_t. Instead of treating Δ\Delta as a fixed parameter, compute Δt=softplus(st)=log⁡(1+est)>0\Delta_t = \textrm{softplus}(s_t) = \log(1 + e^{s_t}) > 0 from a linear projection st=w⊤xt+bs_t = \mathbf{w}^\top \mathbf{x}_t + b of the current token. Exponentiating −Δt-\Delta_t yields an exact algebraic identity:

e−Δt=e−log⁡(1+est)=11+est=σ(−st).(12.5.1)e^{-\Delta_t} = e^{-\log(1 + e^{s_t})} = \frac{1}{1 + e^{s_t}} = \sigma(-s_t). \tag{12.5.1}

Setting zt=σ(−st)z_t = \sigma(-s_t) turns the ZOH update into ht=ztht−1+(1−zt)xth_t = z_t h_{t-1} + (1 - z_t) x_t, the exact convex blend of MinGRU (Section 12.3.1.3, Theorem 1 of Gu and Dao (2023)). When a filler token produces st=−4.6s_t = -4.6, Δt≈0.01\Delta_t \approx 0.01 and zt=0.99z_t = 0.99 (retaining 99%99\% of the state, half-life 69 steps); when a marked symbol produces st=2s_t = 2, Δt≈2.1\Delta_t \approx 2.1 and zt≈0.12z_t \approx 0.12 (overwriting the state with the new symbol). Parameterizing the gate through Δt=softplus(st)\Delta_t = \textrm{softplus}(s_t) also makes S4D's multi-timescale initialization immediate: choosing the bias bb so softplus(b)∈[0.001,0.1]\textrm{softplus}(b) \in [0.001, 0.1] starts the gate at half-lives of 77 to 693693 steps, and, crucially, a single channel step size Δt,c\Delta_{t,c} can drive NN states with distinct rates λ1,…,λN\lambda_1, \ldots, \lambda_N simultaneously.

12.5.2.2 Write and Read Vectors#

Now give each of the layer's HH channels (H=2dH = 2d in Mamba) an NN-dimensional state vector ht(c)∈RN\mathbf{h}_t^{(c)} \in \mathbb{R}^N with rates λ=(λ1,…,λN)⊤\boldsymbol{\lambda} = (\lambda_1, \ldots, \lambda_N)^\top initialized to (−1,…,−N)⊤(-1, \ldots, -N)^\top. From the current HH-dimensional input xt\mathbf{x}_t, the layer computes per-channel step sizes Δt∈R+H\boldsymbol{\Delta}_t \in \mathbb{R}_+^H together with a shared write direction Bt∈RN\mathbf{B}_t \in \mathbb{R}^N and read direction Ct∈RN\mathbf{C}_t \in \mathbb{R}^N:

Δt=softplus(WΔxt+bΔ),Bt=WBxt,Ct=WCxt.\begin{aligned} \boldsymbol{\Delta}_t &= \textrm{softplus}(\mathbf{W}_\Delta \mathbf{x}_t + \mathbf{b}_\Delta), \\ \mathbf{B}_t &= \mathbf{W}_B \mathbf{x}_t, \qquad \mathbf{C}_t = \mathbf{W}_C \mathbf{x}_t. \end{aligned}

Each channel c∈{1,…,H}c \in \{1, \ldots, H\} then updates its NN states and reads out its output via:

ht(c)=eΔt,cλ⊙ht−1(c)+Δt,c xt,c Bt,yt,c=Ct⊤ht(c)+Dc xt,c.(12.5.2)\begin{aligned} \mathbf{h}_t^{(c)} &= e^{\Delta_{t,c} \boldsymbol{\lambda}} \odot \mathbf{h}_{t-1}^{(c)} + \Delta_{t,c}\, x_{t,c}\, \mathbf{B}_t, \\ y_{t,c} &= \mathbf{C}_t^\top \mathbf{h}_t^{(c)} + D_c\, x_{t,c}. \end{aligned} \tag{12.5.2}
Figure 12.5.2:

One step of the selective SSM. From the input xt\mathbf{x}_t of HH channels, three projections compute the step sizes Δt\boldsymbol{\Delta}_t (one per channel), the write vector Bt\mathbf{B}_t, and the read vector Ct\mathbf{C}_t (each of length NN). Row cc of the H×NH \times N state decays by eΔt,cλe^{\Delta_{t,c}\boldsymbol{\lambda}} and receives Δt,c xt,c Bt\Delta_{t,c}\, x_{t,c}\, \mathbf{B}_t; the output yt,cy_{t,c} reads that row with Ct\mathbf{C}_t and adds the skip term Dc xt,cD_c\, x_{t,c}.

Figure 12.5.2 shows where the three projections act: Δt\boldsymbol{\Delta}_t scales the rows of the state, one channel each, while Bt\mathbf{B}_t and Ct\mathbf{C}_t act along its columns and are shared by all channels. Following Gu and Dao (2023), (12.5.2) retains the exact ZOH decay eΔt,cλe^{\Delta_{t,c}\boldsymbol{\lambda}} while approximating the ZOH input weight (eΔλ−1)/λ(e^{\Delta\lambda} - 1)/\lambda by the first-order Euler weight Δt,c\Delta_{t,c} (which agrees when Δ∣λ∣≪1\Delta|\lambda| \ll 1 and allows large steps Δt,c\Delta_{t,c} to write with weight exceeding 1/∣λ∣1/|\lambda|; see Exercise 1). The shapes of all quantities in (12.5.2) are summarized below:

QuantityShapeComputed from
input xt\mathbf{x}_tHHthe layer's input at step tt
step sizes Δt\boldsymbol{\Delta}_tHH, one per channelxt\mathbf{x}_t, through rank-RR factored WΔ∈RH×H\mathbf{W}_\Delta \in \mathbb{R}^{H \times H}
write and read vectors Bt\mathbf{B}_t, Ct\mathbf{C}_tNN each, shared by all channelsxt\mathbf{x}_t, through WB,WC∈RN×H\mathbf{W}_B, \mathbf{W}_C \in \mathbb{R}^{N \times H}
rates λ\boldsymbol{\lambda}NN per channellearned parameters initialized to −1,…,−N-1, \ldots, -N
state ht(1),…,ht(H)\mathbf{h}_t^{(1)}, \ldots, \mathbf{h}_t^{(H)}H×NH \times Nthe recurrence (12.5.2)
output yt\mathbf{y}_tHHreadout with Ct\mathbf{C}_t plus skip Dcxt,cD_c x_{t,c}

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):

  1. An input projection Win\mathbf{W}_\textrm{in} expands the dd-dimensional input into two branches of width H=2dH = 2d.
  2. The first branch passes through a width-4 depthwise causal convolution and SiLU activation before entering the selective SSM—allowing Δt,Bt,Ct\boldsymbol{\Delta}_t, \mathbf{B}_t, \mathbf{C}_t to condition on a 4-token local window rather than a single isolated token.
  3. The SSM output is multiplied elementwise by the SiLU of the second branch and projected back to width dd via Wout\mathbf{W}_\textrm{out}.
  4. To save parameters, WΔ∈RH×H\mathbf{W}_\Delta \in \mathbb{R}^{H \times H} is factored through bottleneck rank R=⌈d/16⌉R = \lceil d / 16 \rceil.
Figure 12.5.3:

The Mamba layer. The input is projected to two branches of width H=2dH = 2d; 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 dd.

12.5.3.2 Training with a Scan#

Because (12.5.2) is still an affine recurrence ht=at⊙ht−1+bt\mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t over the H×NH \times N state at each step, d2l.linear_scan evaluates all TT states in parallel. However, expanding the state to H×NH \times N numbers per token multiplies activation memory by 2N2N: differentiating naively through ⌈log⁡2T⌉\lceil \log_2 T \rceil rounds of a doubling scan retains ∼2⌈log⁡2T⌉\sim 2\lceil \log_2 T \rceil tensors of shape (B,T,H,N)(B, T, H, N) (already ∼2 GB\sim 2\textrm{ GB} 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 gt=∂ℓ/∂ht\mathbf{g}_t = \partial \ell / \partial \mathbf{h}_t satisfies the reverse-time affine recurrence:

gt=∂ℓ∂ht∣direct+at+1⊙gt+1,\mathbf{g}_t = \frac{\partial \ell}{\partial \mathbf{h}_t}\Big|_\textrm{direct} + \mathbf{a}_{t+1} \odot \mathbf{g}_{t+1},

with parameter gradients ∂ℓ/∂bt=gt\partial \ell / \partial \mathbf{b}_t = \mathbf{g}_t and ∂ℓ/∂at=gt⊙ht−1\partial \ell / \partial \mathbf{a}_t = \mathbf{g}_t \odot \mathbf{h}_{t-1}. Thus the backward pass is simply a second call to linear_scan run in reverse time, requiring only the forward decays a\mathbf{a} and states h\mathbf{h} (two tensors instead of ∼20\sim 20; Mamba's fused CUDA kernel goes one step further by keeping h\mathbf{h} 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 T=100T = 100 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 ∼10−6\sim 10^{-6}.

12.5.3.3 Implementation#

SelectiveSSM implements (12.5.2), initializing dt_bias so softplus(dt_bias)\textrm{softplus}(\textrm{dt\_bias}) is distributed log-uniformly on [dt_min,dt_max]=[0.001,0.1][\textrm{dt\_min}, \textrm{dt\_max}] = [0.001, 0.1]. Passing selective=False replaces Δt,Bt,Ct\boldsymbol{\Delta}_t, \mathbf{B}_t, \mathbf{C}_t 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 Δt,cλ\Delta_{t,c}\boldsymbol{\lambda} and writes Δt,cut,cBt\Delta_{t,c} u_{t,c}\mathbf{B}_t of shape (batch_size, T, H, N), and the layer's forward pass to run adjoint_scan and contract the states with Ct\mathbf{C}_t:

@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 n

The Mamba module wraps SelectiveSSM in the two-branch architecture of Figure 12.5.3, expanding width dd to 2H=4d2H = 4d 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 (N=4N = 4 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 95%95\% or more and usually close to 100%100\%, ahead of minGRU. The non-selective control loses more than 3030 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 4,0964{,}096 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 s≤Ts \le T. In the unrolled recurrence hT=∑s=1T(∏r=s+1Tar)⊙bs\mathbf{h}_T = \sum_{s=1}^T (\prod_{r=s+1}^T \mathbf{a}_r) \odot \mathbf{b}_s, the Euclidean norm of position ss's decayed term ∥exp⁡(∑r=s+1Tlog⁡ar)⊙bs∥2\|\exp(\sum_{r=s+1}^T \log \mathbf{a}_r) \odot \mathbf{b}_s\|_2 measures how much of position ss's write survives in the state at step TT.

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 (≤1.6%\le 1.6\% 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 1,0251{,}025 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 axes
symbol 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 H=96H = 96 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 Δt,c\Delta_{t,c} of about 10−510^{-5}, so that they neither decay nor write, and their state is frozen. On the symbol the same channels take steps between about 0.10.1 and 1.51.5, and since the write Δt,c xt,c Bt\Delta_{t,c}\, x_{t,c}\, \mathbf{B}_t 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 d=256d = 256, 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 (3.99M3.99\textrm{M} 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 Mamba

Calling d2l.text_table trains two seeds of each architecture for 1,0001{,}000 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 1.301.30 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 0.050.05 nats/byte and parameter-matched minGRU, d=309 by 0.030.03 nats/byte. Because Mamba scans an H×N=512×16=8,192H \times N = 512 \times 16 = 8{,}192-number state per token (32×32\times larger than minGRU's 256-number state), its un-fused training step takes 2×2\times–4×4\times longer than minGRU, though at inference time that 32d32d-number state (plus 6d6d numbers for the width-4 convolution buffer) equals the KV cache of just 19 tokens of multi-head attention. Moreover, viewing Mamba's H×NH \times N state as an outer-product matrix memory St\mathbf{S}_t updated by (Δt⊙xt)Bt⊤(\boldsymbol{\Delta}_t \odot \mathbf{x}_t)\mathbf{B}_t^\top and queried by Ct\mathbf{C}_t 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 Δt=softplus(WΔxt+bΔ)\boldsymbol{\Delta}_t = \textrm{softplus}(\mathbf{W}_\Delta \mathbf{x}_t + \mathbf{b}_\Delta) and shared write and read vectors Bt,Ct\mathbf{B}_t, \mathbf{C}_t from each input token. For a single state (N=1N = 1), e−softplus(st)=σ(−st)e^{-\textrm{softplus}(s_t)} = \sigma(-s_t) recovers the MinGRU update gate; with NN states initialized at rates −1,…,−N-1, \ldots, -N and log-uniform Δ\Delta biases, Mamba combines content selection with multi-timescale memory. Differentiating the parallel scan via a reverse-time scan (adjoint_scan) avoids storing the O(log⁡2T)O(\log_2 T) intermediate doubling rounds. On selective copying, Mamba reaches 95%95\% accuracy or more (dropping by >30>30 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 0.030.03 nats/byte.

12.5.6 Exercises#

  1. The approximate write. Mamba keeps the decay eΔλe^{\Delta\lambda} of the zero-order hold but writes with weight Δ\Delta instead of (eΔλ−1)/λ(e^{\Delta\lambda} - 1)/\lambda.

    1. For λ=−1\lambda = -1, find the largest Δ\Delta for which the two weights differ by less than 10%.
    2. For one state with λ=−1\lambda = -1, 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 [−1,1][-1, 1] for which the state with weight Δ\Delta leaves that interval. What keeps the values of a trained Mamba model in range?
  2. Memory of the scan. For a Mamba layer with HH channels and NN states, a minibatch of BB sequences of length TT, 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 H=4096H = 4096, N=16N = 16, B=8B = 8, and T=8192T = 8192, and compare with the memory of a GPU.

  3. [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.

    1. Does it still copy the symbols? Compare with the minGRU.
    2. 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?
  4. [code] Which part must be selective? ●

    1. Between the two Mamba models of this section lie two more: input-dependent step sizes with fixed write and read vectors B\mathbf{B} and C\mathbf{C}, and fixed step sizes with input-dependent Bt\mathbf{B}_t and Ct\mathbf{C}_t. Train both, twice each. Which of them solve the task? Relate the result to the spike ratios measured above.
    2. 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?
  5. [code] Generation. Add a method step to SelectiveSSM and to Mamba that 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?

  6. [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.

    1. 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?
    2. 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.
    3. 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.

Discussions