def fit_kernel(N, target, dt=0.05):
"""Fit the readout c of N states at S4D's rates to a target kernel."""
rate = -np.arange(1., N + 1)
a_bar, b_bar = np.exp(dt * rate), np.expm1(dt * rate) / rate
basis = a_bar ** np.arange(len(target))[:, None] * b_bar # K = basis @ c
c = np.linalg.lstsq(basis, target, rcond=None)[0]
K = basis @ c
return K, c, np.linalg.norm(K - target) / np.linalg.norm(target)
k = np.arange(100)
spike = (k == 20).astype(float) # Exactly the input 20 steps back
bump = np.exp(-(k - 20) ** 2 / 32) # About 20 steps back, give or take 4
print(' N peak spike |c| spike residual bump |c| bump residual')
for N in [1, 4, 16]:
K, c, spike_error = fit_kernel(N, spike)
_, c_bump, bump_error = fit_kernel(N, bump)
print(f'{N:2d} {K.argmax():4d} {np.abs(c).max():9.0e} '
f'{spike_error:14.2f} {np.abs(c_bump).max():8.0e} '
f'{bump_error:13.2f}')12.4 State Space Models
How long should a memory last? The subject of a sentence matters for a few words, the topic of a paragraph for a few hundred, and the identity of a character in a novel for an entire book. In principle, the minGRU of Section 12.3 can learn any of these timescales, yet its gates start near \(\sigma(0) = 1/2\) (a half-life of one step). Retaining a symbol over 1,000 steps requires a decay near \(0.999\) (half-life 693 steps), and a gradient carried back 1,000 steps through initial decays of \(1/2\) shrinks by \(2^{-1000}\), which underflows to zero in single precision. Nor does uniform gate initialization give each channel a diverse bank of timescales from the start.
Continuous-time dynamical systems provide a natural parameterization of multi-timescale decay. A state space model (SSM) treats each channel’s memory as a bank of continuous-time linear differential equations with distinct decay rates, sampled at discrete step size \(\Delta\). Discretizing the system yields a linear recurrence whose per-step decay is set by the product of a state rate and a channel step size—letting us initialize a wide spectrum of half-lives before training begins, give each channel \(N\) timescales at once, and evaluate time-invariant dynamics in parallel as a causal convolution via the FFT. Below we derive exact zero-order-hold discretization, implement the diagonal S4D layer of Gu, Gupta, et al. (2022), and test on 1,000-step delayed recall whether multi-timescale initialization is the key ingredient for long-range memory.
12.4.1 From Continuous Time to a Recurrence
12.4.1.1 Continuous-Time Dynamics
Start with a scalar state \(h(t)\) that decays at rate \(\lambda\) while driven by an input signal \(x(t)\):
\[h'(t) = \lambda\, h(t) + x(t). \tag{12.4.1}\]
With \(x(t) = 0\), the solution is \(h(t) = e^{\lambda t} h(0)\). Stability requires \(\lambda < 0\), so that \(h(t)\) decays exponentially (at \(\lambda = -1\), a fraction \(e^{-1} \approx 0.37\) remains after one unit of continuous time), whereas \(\lambda > 0\) grows without bound. Crucially, \(\lambda\) is a decay rate per unit of time, not per token step.
A state space model (SSM) generalizes Equation 12.4.1 to an \(N\)-dimensional state vector \(\mathbf{h}(t) \in \mathbb{R}^N\) driven by a scalar input \(x(t)\) and projected to a scalar output \(y(t)\):
\[ \begin{aligned} \mathbf{h}'(t) &= \mathbf{A}\, \mathbf{h}(t) + \mathbf{B}\, x(t), \\ y(t) &= \mathbf{C}\, \mathbf{h}(t) + D\, x(t), \end{aligned} \tag{12.4.2}\]
where \(\mathbf{B} \in \mathbb{R}^N\) projects the input into the state, the state matrix \(\mathbf{A} \in \mathbb{R}^{N \times N}\) evolves the state, \(\mathbf{C} \in \mathbb{R}^{1 \times N}\) reads it out, and \(D \in \mathbb{R}\) is a direct skip connection.
We restrict \(\mathbf{A} = \textrm{diag}(\lambda_1, \ldots, \lambda_N)\) to be diagonal, reducing Equation 12.4.2 to \(N\) independent copies of Equation 12.4.1 evolving at rates \(\lambda_1, \ldots, \lambda_N\) and linearly combined by \(\mathbf{C}\). While a dense \(\mathbf{A}\) costs \(O(N^2)\) per step and \(O(N^3)\) per associative scan combine, a diagonal \(\mathbf{A}\) costs \(O(N)\) scalar operations. Over the complex numbers, almost every matrix is diagonalizable and \(\mathbf{B}, \mathbf{C}\) absorb the eigenvector change of basis, so diagonal structure sacrifices almost no expressive power (Gu, Gupta, et al. 2022). Using real rates \(\lambda_n < 0\) drops oscillatory modes (\(\lambda = -\alpha + i\omega\), explored in the exercises) in exchange for purely real arithmetic.
An SSM layer processes a \(d\)-dimensional input sequence by running one such \(N\)-state system independently per coordinate (channel), giving a total layer state of \(d \times N\) numbers—\(N\) times larger than a minGRU of width \(d\).
12.4.1.2 Discretization
To apply Equation 12.4.2 to a discrete token sequence, we sample the system at intervals of step size \(\Delta\), so step \(t\) corresponds to continuous time \(t\Delta\). Holding the input constant at \(x_t\) over the interval \(((t-1)\Delta, t\Delta]\) (the zero-order hold, or ZOH, assumption) allows us to integrate Equation 12.4.1 exactly. Since \(\frac{\textrm{d}}{\textrm{d}t}(h + x_t/\lambda) = \lambda(h + x_t/\lambda)\), the shifted state \(h + x_t/\lambda\) decays by \(e^{\Delta\lambda}\) over one step: \(h_t + x_t/\lambda = e^{\Delta\lambda}(h_{t-1} + x_t/\lambda)\). Rearranging yields the exact discrete linear recurrence:
\[ \begin{aligned} h_t &= \bar{a}\, h_{t-1} + \bar{b}\, x_t, \\ \bar{a} &= e^{\Delta \lambda}, \qquad \bar{b} = \frac{e^{\Delta \lambda} - 1}{\lambda}. \end{aligned} \tag{12.4.3}\]
When \(\lambda = -1\), we have \(\bar{b} = 1 - \bar{a}\), so Equation 12.4.3 becomes the convex combination \(h_t = \bar{a}\, h_{t-1} + (1 - \bar{a})\, x_t\), identical to the minimal GRU update (Section 12.3.1.3) with \(\bar{a} = e^{-\Delta}\) acting as the update gate. The step size \(\Delta\) directly controls memory length: at \(\lambda = -1\), \(\Delta = 0.01\) gives \(\bar{a} = 0.990\) (half-life 69 steps), \(\Delta = 0.1\) gives \(\bar{a} = 0.905\) (half-life 7 steps), and \(\Delta = 1\) gives \(\bar{a} = 0.37\).
Parameterizing \(\lambda = -e^\theta < 0\) and \(\Delta > 0\) guarantees \(\bar{a} = e^{\Delta\lambda} \in (0, 1)\), just like a sigmoid gate. What is new is the factored structure of the half-life \(\ln 2 / (\Delta|\lambda|)\) (Figure 12.4.1): the \(N\) rates \(\lambda_1, \ldots, \lambda_N\) spread the states of a channel across distinct relative timescales, while the single channel step size \(\Delta\) dilates or compresses all \(N\) timescales together.
For a diagonal \(\mathbf{A}\), ZOH applies elementwise: \(\bar{a}_n = e^{\Delta \lambda_n}\) and \(\bar{b}_n = (e^{\Delta \lambda_n} - 1) b_n / \lambda_n\) (computed via expm1 to avoid catastrophic cancellation when \(\Delta\lambda_n\) is small; for the dense matrix exponential \(\bar{\mathbf{A}} = e^{\Delta\mathbf{A}}\), see Section 38.1.2.3).
Real-valued S4D initializes \(\lambda_n = -n\) for \(n = 1, \ldots, N\) (the diagonal of the HiPPO legendre projection matrix (Gu et al. 2020)) and draws each channel’s step size \(\Delta\) log-uniformly from \([0.001, 0.1]\). With \(N = 16\), initial half-lives span from under half a step (\(\Delta = 0.1, \lambda = -16\)) to 693 steps (\(\Delta = 0.001, \lambda = -1\)), covering the shaded band of Figure 12.4.1 before a single gradient step is taken.
12.4.1.3 The Convolutional Form
When \(\bar{a}_n\), \(\bar{b}_n\), and \(\mathbf{C}\) do not vary with token position \(t\), the system is linear time-invariant (LTI). Unrolling Equation 12.4.3 from \(\mathbf{h}_0 = \mathbf{0}\) shows that state \(n\) accumulates \(\sum_{k \ge 0} \bar{a}_n^k \bar{b}_n x_{t-k}\), and the readout \(\mathbf{C}\) sums the \(N\) states into a single causal convolution:
\[ \begin{aligned} y_t &= \sum_{k=0}^{t-1} K_k\, x_{t-k} + D x_t, \\ K_k &= \sum_{n=1}^{N} c_n \bar{a}_n^k \bar{b}_n. \end{aligned} \tag{12.4.4}\]
Each channel’s impulse response \(\mathbf{K} = (K_0, K_1, \ldots)\) is a linear combination of \(N\) decaying exponentials. A time-invariant SSM therefore admits three equivalent views (Figure 12.4.2):
- Continuous-time ODE, where parameters specify rates and step sizes;
- Discrete recurrence, used during autoregressive generation in \(O(1)\) time and state per token;
- Causal convolution, evaluated across all \(T\) training positions in \(O(T \log T)\) work via the Fast Fourier Transform (FFT). S4 (Gu, Goel, et al. 2022) used this convolutional view to solve the 16,384-step Path-X benchmark. Note that the convolutional view requires time-invariant dynamics, whereas the parallel scan of Section 12.3 works even when decays vary per token.
12.4.1.4 Timescales and Learned Kernels
What does a multi-state diagonal SSM add beyond setting a minGRU’s initial gate biases to match S4D’s decays? First, the single step size \(\Delta\) per channel scales all \(N\) timescales together, which Section 12.5 will make input-dependent. Second, combining \(N\) states via the readout \(\mathbf{C}\) lets each channel shape a convolutional kernel \(K_k = \sum_{n=1}^N c_n \bar{a}_n^k \bar{b}_n\) that is a sum of \(N\) exponentials rather than a single monotone decay.
How closely can \(N\) real exponentials approximate a non-monotone delay kernel? Suppose a channel needs to read the input from 20 steps back: either a sharp spike (\(K_{20} = 1\), zero elsewhere) or a smooth Gaussian bump around lag 20. A single state (\(N = 1\)) always peaks at lag \(0\). Below we fit the readout weights \(\mathbf{c}\) of \(N \in \{1, 4, 16\}\) states (at S4D rates \(\lambda_n = -n\) and fixed \(\Delta = 0.05\)) by least squares and inspect both the relative residual error \(\|\mathbf{K} - \textrm{target}\| / \|\textrm{target}\|\) and the magnitude of the required readout weights \(|\mathbf{c}|_\infty\).
N peak spike |c| spike residual bump |c| bump residual
1 0 7e-01 0.99 7e+00 0.90
4 17 1e+02 0.97 1e+03 0.55
16 20 2e+11 0.89 8e+10 0.03
def fit_kernel(N, target, dt=0.05):
"""Fit the readout c of N states at S4D's rates to a target kernel."""
rate = -np.arange(1., N + 1)
a_bar, b_bar = np.exp(dt * rate), np.expm1(dt * rate) / rate
basis = a_bar ** np.arange(len(target))[:, None] * b_bar # K = basis @ c
c = np.linalg.lstsq(basis, target, rcond=None)[0]
K = basis @ c
return K, c, np.linalg.norm(K - target) / np.linalg.norm(target)
k = np.arange(100)
spike = (k == 20).astype(float) # Exactly the input 20 steps back
bump = np.exp(-(k - 20) ** 2 / 32) # About 20 steps back, give or take 4
print(' N peak spike |c| spike residual bump |c| bump residual')
for N in [1, 4, 16]:
K, c, spike_error = fit_kernel(N, spike)
_, c_bump, bump_error = fit_kernel(N, bump)
print(f'{N:2d} {K.argmax():4d} {np.abs(c).max():9.0e} '
f'{spike_error:14.2f} {np.abs(c_bump).max():8.0e} '
f'{bump_error:13.2f}') N peak spike |c| spike residual bump |c| bump residual
1 0 7e-01 0.99 7e+00 0.90
4 17 1e+02 0.97 1e+03 0.55
16 20 2e+11 0.89 8e+10 0.03
With \(N = 1\), the kernel peaks at lag 0 and misses both targets. With \(N = 16\), the peak shifts to lag 20 and fits the smooth bump to 0.03 relative error, while the sharp spike remains poorly approximated (0.89 error). Look at |c|, however: achieving that fit with real exponentials requires readout weights around \(10^{11}\) of alternating sign that nearly cancel, because real exponentials \(e^{-n\Delta k}\) are severely ill-conditioned as a basis. Gradient descent from order-one weights cannot reach such cancellation, so real-valued SSM kernels remain broad averages over time windows (whereas complex oscillatory rates \(\lambda = -\alpha + i\omega\) provide an orthogonal Fourier-like basis; see Exercise 3).
12.4.2 A Diagonal State Space Layer
12.4.2.1 The S4D Layer
The S4D layer maintains \(N\) real states for each of its \(d\) channels. It parameterizes rates as \(\lambda_n = -e^{\theta_n} < 0\) (log_neg_rate) and step sizes via log_dt, fixes \(\mathbf{B} = \mathbf{1}\) (since only the product \(b_n c_n\) enters Equation 12.4.4 and \(\mathbf{C}\) is learned), and computes \((\bar{\mathbf{a}}, \bar{\mathbf{b}})\) in discretize via Equation 12.4.3.
class S4D(nn.Module):
"""A diagonal state space layer: N states per channel, fixed dynamics."""
def __init__(self, num_hiddens, num_states=16, dt_min=1e-3, dt_max=1e-1):
super().__init__()
d, N = num_hiddens, num_states
# lambda_n = -n for n = 1..N, stored as log(-lambda) to stay negative
self.log_neg_rate = nn.Parameter(
torch.log(torch.arange(1., N + 1)).repeat(d, 1))
self.log_dt = nn.Parameter( # Log-uniform in [dt_min, dt_max]
torch.rand(d, 1) * math.log(dt_max / dt_min) + math.log(dt_min))
self.C = nn.Parameter(torch.randn(d, N) / math.sqrt(N))
self.D = nn.Parameter(torch.ones(d))
def discretize(self):
"""Zero-order hold with B = 1: decays a_bar and input weights b_bar."""
rate = -torch.exp(self.log_neg_rate) # (d, N)
dt_rate = torch.exp(self.log_dt) * rate
return torch.exp(dt_rate), torch.expm1(dt_rate) / rateclass S4D(nnx.Module):
"""A diagonal state space layer: N states per channel, fixed dynamics."""
def __init__(self, num_hiddens, num_states=16, dt_min=1e-3, dt_max=1e-1,
*, rngs):
d, N = num_hiddens, num_states
# lambda_n = -n for n = 1..N, stored as log(-lambda) to stay negative
self.log_neg_rate = nnx.Param(
jnp.tile(jnp.log(jnp.arange(1., N + 1)), (d, 1)))
self.log_dt = nnx.Param( # Log-uniform in [dt_min, dt_max]
rngs.params.uniform((d, 1)) * math.log(dt_max / dt_min)
+ math.log(dt_min))
self.C = nnx.Param(rngs.params.normal((d, N)) / math.sqrt(N))
self.D = nnx.Param(jnp.ones(d))
def discretize(self):
"""Zero-order hold with B = 1: decays a_bar and input weights b_bar."""
rate = -jnp.exp(self.log_neg_rate[...]) # (d, N)
dt_rate = jnp.exp(self.log_dt[...]) * rate
return jnp.exp(dt_rate), jnp.expm1(dt_rate) / rateDuring training, the forward pass forms the length-\(T\) kernel Equation 12.4.4 for every channel and performs causal convolution via a zero-padded length-\(2T\) FFT (preventing circular wrap-around).
@d2l.add_to_class(S4D)
def forward(self, X): # X: (batch_size, num_steps, d)
T = X.shape[1]
a_bar, b_bar = self.discretize()
# All powers a_bar^k for k < T: d * N * T numbers held in memory
powers = a_bar.unsqueeze(-1) ** torch.arange(T, device=X.device)
K = ((self.C * b_bar).unsqueeze(-1) * powers).sum(1) # Kernel, (d, T)
Y = torch.fft.irfft(torch.fft.rfft(X, n=2 * T, dim=1) *
torch.fft.rfft(K.T, n=2 * T, dim=0), n=2 * T, dim=1)
return Y[:, :T] + self.D * X@d2l.add_to_class(S4D)
def __call__(self, X): # X: (batch_size, num_steps, d)
T = X.shape[1]
a_bar, b_bar = self.discretize()
# All powers a_bar^k for k < T: d * N * T numbers held in memory
powers = a_bar[..., None] ** jnp.arange(T)
K = ((self.C[...] * b_bar)[..., None] * powers).sum(1) # Kernel, (d, T)
Y = jnp.fft.irfft(jnp.fft.rfft(X, n=2 * T, axis=1) *
jnp.fft.rfft(K.T, n=2 * T, axis=0), n=2 * T, axis=1)
return Y[:, :T] + self.D[...] * XDuring autoregressive generation, step advances the \(d \times N\) recurrent state by one token in \(O(dN)\) time and constant memory.
@d2l.add_to_class(S4D)
def step(self, x, h):
"""One step: x is (batch_size, d); the state h is (batch_size, d, N)."""
a_bar, b_bar = self.discretize()
h = a_bar * h + b_bar * x.unsqueeze(-1)
return (h * self.C).sum(-1) + self.D * x, h@d2l.add_to_class(S4D)
def step(self, x, h):
"""One step: x is (batch_size, d); the state h is (batch_size, d, N)."""
a_bar, b_bar = self.discretize()
h = a_bar * h + b_bar * x[..., None]
return (h * self.C[...]).sum(-1) + self.D[...] * x, hLet us verify that the FFT convolution, the parallel linear_scan, and sequential step evaluation agree to single-precision floating-point tolerance.
layer = S4D(8, num_states=4)
X = torch.randn(2, 50, 8) # (batch_size, num_steps, d)
with torch.no_grad():
a_bar, b_bar = layer.discretize()
H = d2l.linear_scan(a_bar, b_bar * X.unsqueeze(-1)) # (batch, T, d, N)
Y_scan = (H * layer.C).sum(-1) + layer.D * X
h, Y_step = torch.zeros(2, 8, 4), []
for x in X.unbind(1):
y, h = layer.step(x, h)
Y_step.append(y)
Y_conv = layer(X)
Y_step = torch.stack(Y_step, 1)
print(f'convolution vs scan: {(Y_conv - Y_scan).abs().max():.1e}, '
f'convolution vs steps: {(Y_conv - Y_step).abs().max():.1e}')convolution vs scan: 2.4e-07, convolution vs steps: 2.4e-07
layer = S4D(8, num_states=4, rngs=nnx.Rngs(0))
X = jax.random.normal(jax.random.key(1), (2, 50, 8)) # (batch, T, d)
a_bar, b_bar = layer.discretize()
H = d2l.linear_scan(a_bar, b_bar * X[..., None]) # (batch, T, d, N)
Y_scan = (H * layer.C[...]).sum(-1) + layer.D[...] * X
h, Y_step = jnp.zeros((2, 8, 4)), []
for x in jnp.unstack(X, axis=1):
y, h = layer.step(x, h)
Y_step.append(y)
Y_conv = layer(X)
Y_step = jnp.stack(Y_step, 1)
print(f'convolution vs scan: {jnp.abs(Y_conv - Y_scan).max():.1e}, '
f'convolution vs steps: {jnp.abs(Y_conv - Y_step).max():.1e}')convolution vs scan: 2.4e-07, convolution vs steps: 2.4e-07
All three views match to \(\sim 10^{-7}\). Notice that for LTI layers, the FFT convolution avoids materializing the four-dimensional \((B, T, d, N)\) intermediate state tensor across the batch, requiring only the \((d, N, T)\) kernel powers.
12.4.2.2 Long-Range Recall
To test whether initial timescales govern long-range memory, we return to the delayed recall benchmark of Section 12.1 at delays of \(T = 100\) and \(T = 1{,}000\) steps, using identical blank fillers (blank_fillers=True) so the task tests pure retention duration rather than content-based filtering (Section 12.5).
We compare four configurations, which cross the layer with its initial timescales (Figure 12.4.3):
- Default
minGRU, whose gates start near \(1/2\); - Default
S4D(\(d = 64, N = 16\), \(\Delta \in [0.001, 0.1]\), half-lives up to 693 steps); S4D, short timescales, initialized with \(\Delta \in [0.1, 1.0]\) so no initial half-life exceeds 7 steps;minGRU, S4D timescales, whose update-gate biases are initialized viainit_timescalesso \(\sigma(b) = e^{-\Delta}\) with \(\Delta \in [0.001, 0.1]\) (\(b = -\log(e^\Delta - 1)\)), matching the slowest state of each S4D channel.
def init_timescales(layer, dt_min=1e-3, dt_max=1e-1):
"""Start a minGRU's gates at the decays exp(-dt) of S4D."""
dt = dt_min * (dt_max / dt_min) ** torch.rand(layer.W_z.bias.shape)
with torch.no_grad(): # sigmoid(b) = exp(-dt)
layer.W_z.bias.copy_(-torch.log(torch.expm1(dt)))
return layerdef init_timescales(layer, dt_min=1e-3, dt_max=1e-1, *, rngs):
"""Start a minGRU's gates at the decays exp(-dt) of S4D."""
dt = dt_min * (dt_max / dt_min) ** rngs.params.uniform(
layer.W_z.bias.shape)
layer.W_z.bias[...] = -jnp.log(jnp.expm1(dt)) # sigmoid(b) = exp(-dt)
return layerWe train two seeds of each model via d2l.train_delayed_recall (1,500 steps of Adam at learning rate \(3 \times 10^{-3}\)) and also print the slowest half-life \(\ln 2 / \min_{d,n}(\Delta|\lambda_n|)\) after training for the two S4D variants.
# (layer, embedding width): S4D keeps its width; the minGRUs map 32 to 64
layers = {
'minGRU': lambda: (d2l.MinGRU(32, 64), 32),
'S4D': lambda: (S4D(64), 64),
'S4D, short timescales': lambda: (S4D(64, dt_min=0.1, dt_max=1.0), 64),
'minGRU, S4D timescales': lambda: (
init_timescales(d2l.MinGRU(32, 64)), 32)}
def recall(make_layer, T):
"""Train a fresh model at delay T; return its test accuracy and layer."""
layer, num_inputs = make_layer()
model = d2l.RecallModel(layer, 64, num_inputs=num_inputs)
return d2l.train_delayed_recall(model, T, blank_fillers=True), layer
def slowest_half_life(layer): # ln 2 / min(dt |lambda|), in steps
rates = torch.exp(layer.log_dt + layer.log_neg_rate).detach()
return math.log(2) / rates.min().item()
runs = {name: {T: [recall(make_layer, T) for _ in range(2)] # Two runs each
for T in [100, 1000]} for name, make_layer in layers.items()}
print(f"{'accuracy':23s} {'T=100':^11s} {'T=1000':^11s}")
for name, by_T in runs.items():
print(f'{name:23s}', ' '.join(' '.join(f'{acc:5.2f}' for acc, _ in r)
for r in by_T.values()))
print('slowest half-life after training, in steps')
for name in ['S4D', 'S4D, short timescales']:
print(f'{name:23s}', ' '.join(' '.join(
f'{slowest_half_life(layer):5.0f}' for _, layer in r)
for r in runs[name].values()))accuracy T=100 T=1000
minGRU 0.12 0.12 0.13 0.13
S4D 1.00 1.00 1.00 1.00
S4D, short timescales 1.00 1.00 0.12 0.12
minGRU, S4D timescales 1.00 1.00 1.00 1.00
slowest half-life after training, in steps
S4D 1028 1190 3020 2552
S4D, short timescales 119 196 7 7
# (layer, embedding width): S4D keeps its width; the minGRUs map 32 to 64
layers = {
'minGRU': lambda rngs: (d2l.MinGRU(32, 64, rngs=rngs), 32),
'S4D': lambda rngs: (S4D(64, rngs=rngs), 64),
'S4D, short timescales': lambda rngs: (
S4D(64, dt_min=0.1, dt_max=1.0, rngs=rngs), 64),
'minGRU, S4D timescales': lambda rngs: (init_timescales(
d2l.MinGRU(32, 64, rngs=rngs), rngs=rngs), 32)}
def recall(make_layer, T):
"""Train a fresh model at delay T; return its test accuracy and layer."""
rngs = nnx.Rngs(d2l.get_key())
layer, num_inputs = make_layer(rngs)
model = d2l.RecallModel(layer, 64, num_inputs=num_inputs, rngs=rngs)
return d2l.train_delayed_recall(model, T, blank_fillers=True), layer
def slowest_half_life(layer): # ln 2 / min(dt |lambda|), in steps
rates = jnp.exp(layer.log_dt[...] + layer.log_neg_rate[...])
return math.log(2) / rates.min().item()
runs = {name: {T: [recall(make_layer, T) for _ in range(2)] # Two runs each
for T in [100, 1000]} for name, make_layer in layers.items()}
print(f"{'accuracy':23s} {'T=100':^11s} {'T=1000':^11s}")
for name, by_T in runs.items():
print(f'{name:23s}', ' '.join(' '.join(f'{acc:5.2f}' for acc, _ in r)
for r in by_T.values()))
print('slowest half-life after training, in steps')
for name in ['S4D', 'S4D, short timescales']:
print(f'{name:23s}', ' '.join(' '.join(
f'{slowest_half_life(layer):5.0f}' for _, layer in r)
for r in runs[name].values()))accuracy T=100 T=1000
minGRU 0.12 0.12 0.12 0.13
S4D 1.00 1.00 1.00 1.00
S4D, short timescales 1.00 1.00 0.12 0.12
minGRU, S4D timescales 1.00 1.00 1.00 1.00
slowest half-life after training, in steps
S4D 1318 1336 2216 2595
S4D, short timescales 147 134 8 7
The outcome tracks initial timescales rather than layer class: at \(T = 1{,}000\), both S4D and minGRU, S4D timescales achieve 100% accuracy across all runs, whereas default minGRU and S4D, short timescales remain stuck at chance (\(0.12\)). Notice why S4D, short timescales still succeeds at \(T = 100\): even though its slowest initial half-life is 7 steps, the attenuation over 99 steps is \(e^{-0.1 \times 99} \approx 5 \times 10^{-5}\), which remains above float32 precision and supplies enough gradient signal for Adam to stretch the slowest half-life to 100–200 steps. Over 999 steps, however, \(e^{-100} \approx 10^{-44}\) vanishes below machine precision, leaving the slowest half-life frozen near 7 steps.
Yet time-invariant dynamics have a fundamental blind spot: every token at lag \(k\) receives the exact same weight \(K_k\), regardless of whether that token was a crucial symbol or an uninformative filler. In Section 12.5, we combine S4D’s multi-timescale state bank with input-dependent selection by letting each token choose its own step size \(\Delta_t\).
12.4.3 Summary
Discretizing a continuous-time diagonal state space model \(\mathbf{h}'(t) = \mathbf{A}\mathbf{h}(t) + \mathbf{B}x(t)\) with rates \(\lambda_n < 0\) under zero-order hold at step size \(\Delta\) yields a linear recurrence with decays \(\bar{a}_n = e^{\Delta\lambda_n}\) and half-lives \(\ln 2 / (\Delta|\lambda_n|)\). Initializing \(\lambda_n = -n\) and drawing \(\Delta\) log-uniformly across \([0.001, 0.1]\) equips each channel of S4D with \(N\) exponentially decaying states spanning half-lives from under 1 step to nearly 700 steps. Because its parameters are time-invariant, S4D can be evaluated equivalently as an \(O(1)\)-state recurrence at inference time or as a causal convolution via the FFT during training. On 1,000-step delayed recall, starting with long-timescale decays (whether in S4D or transferred to minGRU gate biases) is the decisive factor that enables learning, though fixed dynamics still cannot selectively ignore irrelevant inputs.
12.4.4 Exercises
- [code] Discretization rules. The zero-order hold is one of several ways to turn Equation 12.4.1 into a recurrence. The forward Euler rule uses \(\bar{a} = 1 + \Delta\lambda\), the backward Euler rule \(\bar{a} = 1/(1 - \Delta\lambda)\), and the bilinear rule \(\bar{a} = (1 +
\Delta\lambda/2)/(1 - \Delta\lambda/2)\) (Section 38.2.3 studies the two Euler rules as solvers of a differential equation).
- For each rule, find the step sizes \(\Delta\) for which every \(\lambda < 0\) gives \(|\bar{a}| < 1\). Which rule can make a stable continuous system unstable?
- Show that backward Euler with \(\lambda = -1\) gives the update \(h_t = z h_{t-1} + (1 - z) x_t\) with \(z = \sigma(-\log\Delta)\), the blend of a GRU whose update gate has the negative logarithm of the step size as its pre-activation.
- Simulate the response of each rule to a unit step input for \(\lambda = -1\) and \(\Delta \in \{0.1, 1, 3\}\), and compare with the exact solution \(1 - e^{-t}\).
- [code] Delays and kernels. Use
fit_kernelto study which memories \(N\) real exponentials can represent.- Fit a unit spike at delays 5, 20, and 50 with \(N = 16\) states and \(\Delta = 0.05\). How does the error change with the delay? Relate your answer to the half-lives of the slowest and the fastest state.
- Fit the spike at delay 20 for step sizes \(\Delta\) between 0.01 and 0.2. Which \(\Delta\) fits best? What does this suggest about how a trained S4D should set the step size of a channel that needs a memory of a particular length?
- Fit \(\mathbf{c}\) by gradient descent from zero (Adam, a few thousand steps) instead of least squares. How close do you come to the least-squares error for the bump, and for the spike? What do the weights of the least-squares fits predict?
- [code] Complex rates. A state with the complex rate \(\lambda =
-\alpha + i\omega\), \(\alpha > 0\), decays while it rotates.
- Show that the zero-order hold gives \(\bar{a} = e^{-\alpha\Delta} e^{i\omega\Delta}\), and that two states with conjugate rates, input weights, and readout weights contribute a real kernel \(K_k = r\, e^{-\alpha\Delta k} \cos(\omega\Delta k + \varphi)\) for some \(r \ge 0\) and \(\varphi\). How many real parameters does such a pair have, and how many does a pair of real states have?
- Which kernels can such pairs represent that real rates cannot? Think of an input that repeats with a fixed period.
- Change
fit_kernelto use the complex rates \(\lambda_m = -1/2 + i\pi m\) for \(m = 0, \ldots, N-1\) (the S4D-Lin initialization of Gu, Gupta, et al. (2022)) and to fit the real part of the kernel. For the spike at delay 20, compare the error and the size of the weights with the fit of real rates, and explain the difference.
- [code] Convolution by the FFT. The forward pass of
S4Dpads the sequence and the kernel to length \(2T\) before the FFT.- Remove the padding, so that the FFT has length \(T\), and compare the outputs with those of
step. Which outputs are wrong, and what has been added to them? - What is the shortest padded length that gives the exact causal convolution? Why do implementations often round it up to a power of two?
- Remove the padding, so that the FFT has length \(T\), and compare the outputs with those of