12.3 Linear Recurrences and Parallel Scans
The gated networks of Section 12.1 can retain information over hundreds of steps, yet they still process a sequence one token after another because each step's gates and candidate depend on the previous state . On a sequence of tokens, a GRU executes sequential updates, leaving most of a GPU idle during training while a Transformer processes all positions in parallel via large matrix multiplications. Can a recurrent network retain -state autoregressive generation while training across all positions in parallel?
Yes—as soon as the gates and candidate depend only on the current input , making the recurrence linear (or more precisely, affine) in . Affine updates can be composed associatively just like prefix sums (Hillis and Steele, 1986), evaluating all states in parallel rounds. Below we progress from a scalar decay to the minimal GRU (MinGRU) of Feng et al. (2024), implement the parallel associative scan, evaluate MinGRU on byte-level WikiText-103, and benchmark wall-clock scaling against both sequential GRUs and causal attention up to tokens.
12.3.1 Linear Recurrences#
12.3.1.1 A Single Decaying Number#
Start with a scalar state that retains a fixed fraction of its previous value and adds the input :
Unrolling (12.3.1) expresses directly in terms of past inputs:
Every is an exponentially weighted moving average of past inputs with half-life steps ( steps at ; steps at ), and the gradient decays at the exact same rate.
12.3.1.2 Input-Dependent Decay#
Generalizing to a vector state with input-dependent elementwise decay and write vector yields the affine recurrence:
Unrolling (12.3.3) replaces the power by the cumulative product of intermediate decays:
Because and depend only on , all decay and write vectors can be computed in parallel across the entire sequence before the recurrence runs. And because each , past writes can be selectively preserved () or flushed () without ever exploding.
12.3.1.3 The Minimal GRU#
Look at the three places where the previous state enters the standard GRU of Section 12.1.3:
followed by . Dropping the three marked recurrent dependencies (which eliminates the reset gate altogether) yields the minimal GRU (minGRU) of Feng et al. (2024):
This is an affine recurrence (12.3.3) with decay and write , cutting the layer's parameter count from to . While a single minGRU layer cannot condition its gate on what is already in , stacking multiple minGRU blocks with positionwise MLPs recovers part of that ability without sacrificing parallel evaluation across time: the gates of each layer see the states of the layer below. This gives one round of state-dependent gating per layer, where a GRU has one at every step. Section 12.7.3.5 measures what a fixed number of rounds cannot do.
12.3.2 Parallel Scans#
12.3.2.1 Composing Affine Steps#
Evaluating the unrolled sum (12.3.4) naively for all would take operations. Instead, we exploit the associativity of function composition. Represent step 's affine map by the pair . Applying step 1 followed by step 2 yields , which is another affine map with coefficients:
Because function composition is associative and the composite of any block of steps is still a single pair of the same size, computing from reduces to an associative prefix scan under (with read from the second component of the -th prefix).
12.3.2.2 The Doubling Schedule#
Figure 12.3.1 illustrates the parallel doubling schedule of Hillis and Steele (1986) on steps. In round , every position combines with the position at stride behind it. After rounds, every position holds its complete prefix.
A parallel scan on eight steps. Each box shows which steps its value combines, meaning steps 1 to 4. In every round each position combines with the position a fixed stride back (blue arrows), and the stride doubles from round to round; dashed arrows copy a value unchanged. Teal boxes hold complete prefixes. After rounds every position does.
The Hillis–Steele doubling schedule performs combines across parallel rounds, whereas the work-efficient up-sweep/down-sweep tree schedule of Blelloch (1990) performs combines across shrinking rounds.
We write the concise doubling schedule as associative_scan.
12.3.2.3 Implementation#
linear_scan computes all states of (12.3.3) along the time axis (axis 1), folding an optional initial state into the first write .
def associative_scan(combine, elems):
"""All prefixes of elems under an associative combine; time is axis 1."""
s = 1
# Autograd keeps the tensors of every round for the backward pass
while s < elems[0].shape[1]: # Combine every position with the one s back
earlier = tuple(x[:, :-s] for x in elems)
later = tuple(x[:, s:] for x in elems)
elems = tuple(torch.cat([x[:, :s], y], 1)
for x, y in zip(elems, combine(earlier, later)))
s *= 2
return elems
def linear_scan(a, b, h0=None):
"""All states of h_t = a_t * h_{t-1} + b_t; time is the second axis."""
a = a.expand_as(b) # Decays may omit axes on which they do not vary
if h0 is not None: # Fold the initial state into the first step
b = torch.cat([a[:, :1] * h0.unsqueeze(1) + b[:, :1], b[:, 1:]], 1)
def combine(earlier, later):
(a1, b1), (a2, b2) = earlier, later
return a1 * a2, a2 * b1 + b2
return associative_scan(combine, (a, b))[1]Let us verify linear_scan against a sequential step-by-step loop on length (a non-power of two).
def sequential_scan(a, b):
h, states = torch.zeros_like(b[:, 0]), []
for a_t, b_t in zip(a.unbind(1), b.unbind(1)):
h = a_t * h + b_t
states.append(h)
return torch.stack(states, 1)
a, b = torch.rand(4, 100, 8), torch.randn(4, 100, 8)
print(f'max deviation: '
f'{(linear_scan(a, b) - sequential_scan(a, b)).abs().max():.1e}')max deviation: 4.8e-07
The parallel scan and sequential loop agree to float32 rounding tolerance ().
12.3.3 A Linear Recurrent Language Model#
12.3.3.1 The minGRU on Text#
Wrapping linear_scan around two linear projections ( and ) implements MinGRU (12.3.5) as a drop-in sequence mixer for d2l.SeqLM.
class MinGRU(nn.Module):
"""The minimal GRU: its gate and candidate read only the input."""
def __init__(self, num_inputs, num_hiddens):
super().__init__()
self.W_z = nn.Linear(num_inputs, num_hiddens) # Update gate (decay)
self.W_h = nn.Linear(num_inputs, num_hiddens) # Candidate state
d2l.init_lecun(self)
def coefficients(self, X):
"""Decays a_t and writes b_t of the linear recurrence."""
Z = torch.sigmoid(self.W_z(X))
return Z, (1 - Z) * torch.tanh(self.W_h(X))
def forward(self, X): # X: (batch_size, num_steps, num_inputs)
return linear_scan(*self.coefficients(X))How much modeling quality does dropping from the gates cost on byte-level WikiText-103? Using the exact setup of Section 12.1.4.2 (4 blocks of d2l.SeqLM, 128-byte windows, 1,000 steps), we first define text_model and the three comparison arms: GRU (, parameters), minGRU at equal width (, parameters), and minGRU widened to equal parameter count (minGRU, d=302, parameters):
torch.set_float32_matmul_precision('high') # fp32 matmuls may use tf32
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())
gru = lambda d: d2l.Recurrent(d2l.init_lecun(nn.GRU(d, d, batch_first=True)))
min_gru = lambda d: MinGRU(d, d)
arms = {'GRU': (gru, 256), 'minGRU': (min_gru, 256),
'minGRU, d=302': (min_gru, 302)} # As many parameters as the GRUWe load the 128-byte WikiText103 dataset, run d2l.text_table across all three arms, and retain the first trained minGRU model for inspection:
data = d2l.WikiText103(batch_size=64, num_steps=128)
trained = d2l.text_table(text_model, arms, data)
model = trained['minGRU'][0] # The model we look inside below validation 0-15 16-63 64-127 ms/step
GRU 3,817,216 1.299/1.300 1.490/1.491 1.273/1.274 1.270/1.271 33/32
minGRU 2,764,544 1.343/1.348 1.520/1.520 1.319/1.323 1.317/1.324 26/26
minGRU, d=302 3,816,932 1.328/1.329 1.508/1.507 1.303/1.304 1.301/1.303 26/28
At equal width (), minGRU finishes nats/byte behind GRU ( vs. ), and at equal parameter count (minGRU, d=302) it closes about two fifths of the gap (), landing right alongside the plain RNN of Section 12.1.4.2 while beating the attention baseline () and training via a parallel scan rather than a sequential loop.
12.3.3.2 Inside the Trained Model#
To check how much minGRU relies on its recurrent state, we evaluate the trained model with its state zeroed before every step (StateReset, so depends only on the current byte).
class StateReset(nn.Module):
"""A minGRU layer whose state is reset to zero before every step."""
def __init__(self, layer):
super().__init__()
self.layer = layer
def forward(self, X):
return self.layer.coefficients(X)[1]
layers = model.mixers
loss = np.mean(d2l.loss_by_position(model, data))
model.mixers = nn.ModuleList([StateReset(layer) for layer in layers])
reset = np.mean(d2l.loss_by_position(model, data))
model.mixers = layers
print(f'validation loss: {loss:.3f} nats per byte, '
f'with the state reset at every step: {reset:.3f}')validation loss: 1.343 nats per byte, with the state reset at every step: 2.481
Zeroing the state raises validation loss from to nats/byte (essentially the nats/byte empirical byte-bigram baseline of Section 11.2), confirming that over nats/byte comes from context carried in the state.
We can also inspect the distribution of update-gate decays in the first block before and after training. Adding first_mixer_input to d2l.SeqLM lets us extract the normalized token embeddings fed to the first mixer.
@d2l.add_to_class(d2l.SeqLM)
def first_mixer_input(self, X):
"""What the first mixer reads: the normalized token embeddings."""
return self.norms[0](self.embedding(X))Passing a validation minibatch through first_gates on both an untrained minGRU and our trained model tabulates the fraction of update gates exceeding , , and :
def first_gates(model, X): # Gates of the first layer
return model.mixers[0].coefficients(model.first_mixer_input(X))[0]
X, _ = next(iter(data.val_dataloader())) # Validation text
X = X.to(next(model.parameters()).device)
with torch.inference_mode():
Z_init = first_gates(text_model(min_gru, 256), X) # Untrained
Z = first_gates(model, X)
print('gate above half-life in steps share at initialization trained')
for g in (0.5, 0.9, 0.99):
print(f'{g:10} {math.log(2) / -math.log(g):17.0f} '
f'{(Z_init > g).float().mean():23.1%} '
f'{(Z > g).float().mean():7.1%}')gate above half-life in steps share at initialization trained
0.5 1 49.0% 53.4%
0.9 7 1.3% 17.1%
0.99 69 0.0% 0.1%
Training increases the share of gates with half-life bytes () more than tenfold (from to about ), matching the word-level timescales needed over 128-byte windows, while almost no gates reach (half-life 69 bytes) from zero-bias initialization.
12.3.4 Cost against Attention#
12.3.4.1 Work, Depth, and Memory#
Table 12.3.1 compares the asymptotic training work, sequential depth, and autoregressive generation state of one layer of width across tokens.
| Layer | Training work | Steps in a row | Memory at generation |
|---|---|---|---|
| GRU, one step at a time | |||
| minGRU, doubling scan | |||
| minGRU, work-efficient scan | |||
| Causal attention | a few matrix products |
Both GRU and minGRU perform projection work and carry an state vector during decoding, but minGRU reduces sequential training depth from matrix-vector steps to elementwise scan rounds. Causal attention has sequential depth during training, but its attention score and mixing work grows quadratically as (crossing its projection FLOPs around ) and its inference KV cache grows linearly as .
12.3.4.2 Measured Cost#
To see where these scaling laws cross on real hardware, we time a forward-plus-backward pass in float16 at width keeping the total token count per batch fixed at as sequence length sweeps from to . With total tokens fixed, any layer whose cost is strictly linear in will have a flat curve, while a layer dominated by sequential steps or pairwise work will double its runtime each time doubles.
d, tokens = 256, 65536 # Width; tokens per call, in sequences of length T
device, half = d2l.try_gpu(), torch.float16 # 16-bit floats throughout
timed = {'GRU': d2l.Recurrent(nn.GRU(d, d, batch_first=True)),
'minGRU': torch.compile(MinGRU(d, d)),
'attention': d2l.CausalAttention(d, num_heads=4)}
for layer in timed.values():
layer.to(device, half)
def time_call(layer, T):
"""Milliseconds for a forward and backward pass over tokens / T
sequences of length T."""
X = torch.randn(tokens // T, T, d, device=device, dtype=half,
requires_grad=True)
return 1000 * d2l.Benchmark(lambda: layer(X).float().sum().backward(),
warmup=1, repeats=3).timeSweeping time_call across sequence lengths compares the wall-clock runtime of GRU, minGRU, and attention on log–log axes:
lengths = [512, 1024, 2048, 4096, 8192, 16384]
times = {name: [time_call(layer, T) for T in lengths]
for name, layer in timed.items()}
print('T ', *(f'{T:>7d}' for T in lengths))
for name, ms in times.items():
print(f'{name:9s}', *(f'{t:7.1f}' for t in ms))
d2l.plot(lengths, list(times.values()), 'sequence length',
'milliseconds per call', legend=list(times), xscale='log',
yscale='log', figsize=(4.5, 3))T 512 1024 2048 4096 8192 16384
GRU 20.2 35.6 69.7 113.3 197.6 425.6
minGRU 4.0 4.3 4.5 5.0 5.2 5.6
attention 2.1 2.4 3.2 4.7 7.9 13.7
The empirical scaling curves match Table 12.3.1:
GRU: slowest at every length, growing more than from to because its sequential steps cannot be parallelized across time.minGRU: nearly flat across the entire 32-fold increase in sequence length.attention: nearly flat up to where projections and memory traffic dominate, then bending upward toward per doubling once the attention term takes over.
The doubling scan of minGRU grows by under ; attention, faster at short lengths, crosses it near and trails it by about at .
What minGRU still lacks is a structured way to initialize and control multi-timescale memories—the question Section 12.4 addresses via continuous-time state space models.
12.3.5 Summary#
Removing the previous state from a recurrent layer's gates yields an affine recurrence whose steps compose associatively via . An associative scan evaluates all states in parallel rounds during training while preserving -state sequential updates during decoding. Applied to the GRU, this simplification produces MinGRU, which matches a parameter-matched plain RNN on byte-level WikiText-103 (about nats/byte behind a full GRU) while training at nearly constant per-token time up to tokens—over an order of magnitude faster than a sequential GRU and several times faster than quadratic attention at long contexts.
12.3.6 Exercises#
-
Closure under composition. A parallel scan needs more than associativity: the composite of any run of steps must be described by as many numbers as a single step, so that every combine costs the same.
- Generalize (12.3.6) to the recurrence with dense matrices , keeping the factors of each product in the right order. Count the multiply-adds of one combine and of one sequential step. Compare the total work of the doubling scan, about combines, with that of the loop at and . What does the comparison suggest about dense transition matrices?
- For the scalar step , show that the composite of two steps with is not of the form for any and . What would a scan have to store to represent the composite of steps?
-
[code] The direct route. For scalar decays, the unrolled sum (12.3.4) can be evaluated without a scan, from cumulative products and one cumulative sum.
- Show that . Implement it with a
library
cumprodandcumsumand compare it withlinear_scanin 32-bit floats on decays drawn near 0.9. At what length does it fail, and why does the scan not fail there? - Feng et al. (2024) repair the formula by working with logarithms of the decays and of the writes, replacing the sum by a cumulative log-sum-exp. Implement the repair. What does it require of the signs of the writes, and how do the authors arrange it?
- Show that . Implement it with a
library
-
[code] Candidate nonlinearity.
MinGRUkeeps a on the candidate , whereas Feng et al. (2024) use a linear candidate.- Starting from , write each coordinate of as a weighted sum of the candidates . Show that the weights are nonnegative and sum to at most one, and derive a bound on that holds at every length, with and without the .
- Remove the , train the language model of this section twice
with
d2l.train_text, and compare its validation loss with the two runs ofMinGRU. Is the difference larger than the spread between runs? Relate what you observe to your bound.
-
[code] State passing.
linear_scanaccepts an initial state, so a long sequence can be processed in pieces.- Split a sequence of length into chunks of length , run the scan on each chunk starting from the final state of the previous one, and check that the concatenated states match a single call on the whole sequence.
- Now stop gradients through the carried state at every chunk boundary. The states do not change. Which contributions to the gradient of the loss at step disappear, and which dependencies can the trained model still use when it generates text? Compare with truncated backpropagation through time (Section 8.5).
-
[code] Work-efficient scans. ● A recursive schedule does less work than the doubling schedule: combine adjacent pairs, which halves the sequence; scan the half-length sequence recursively, which yields every second prefix; then obtain each remaining prefix with one more combine.
- For , count the combines and the rounds of combines of each schedule, and compare both with the steps of the loop at .
- Implement both schedules with slicing, check both against
sequential_scan, and time them at the lengths of the measurement in Section 12.3.4. Does the ratio of times follow the ratio of combines? Explain why it might not at short lengths.