Linear Recurrences and Parallel Scans

Dive into Deep Learning · §12.3

Linear Recurrences and Parallel Associative Scans
affine state transitions · minimal GRU (minGRU) · associative prefix scans · complexity vs. attention

The GPU Parallelism Bottleneck of Nonlinear Recurrence

Motivation

  • Sequential Bottleneck: On T = 4{,}096 tokens, a nonlinear GRU launches 4{,}096 serial steps because step t waits for \mathbf{h}_{t-1} inside \tanh(\cdot).
  • The Linearization Breakthrough: Removing \mathbf{h}_{t-1} from the gates makes the transition affine (\mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t).
  • Logarithmic Depth: Affine transitions compose associatively in \log_2 4{,}096 = 12 parallel rounds.

Scalar Linear Recurrence as an Exponential Moving Sum

Linear Recurrence Basics

h_t = a\, h_{t-1} + x_t = \sum_{s=1}^{t} a^{t-s} x_s

  • Impulse Response: A unit pulse at s=1 decays geometrically as a^{t-1} with half-life \tau_{1/2} = \ln 2 / \ln(1/a).
  • Forward-Backward Symmetry: The backward sensitivity \partial h_t / \partial x_s = a^{t-s} matches the forward retention weight identically.

Input-Dependent Affine Vector Recurrences

Time-Varying Decays

\mathbf{h}_t = \mathbf{a}(\mathbf{x}_t) \odot \mathbf{h}_{t-1} + \mathbf{b}(\mathbf{x}_t)

  • Parallel Pre-Computation: Because \mathbf{a}_t, \mathbf{b}_t depend only on \mathbf{x}_t, all T gates and writes are computed in one batched GEMM.
  • Selective Clock Gating: Salient tokens set a_{t,i} \approx 0 to write new facts; filler tokens set a_{t,i} \approx 1 to freeze memory without decay.

Deriving the Minimal GRU (minGRU) from the Standard GRU

The minGRU Architecture

\mathbf{z}_t = \sigma(\mathbf{W}_\textrm{z}\mathbf{x}_t + \mathbf{b}_\textrm{z}), \quad \mathbf{h}_t = \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t

  • Drop Recurrent Gate Inputs: Removes \mathbf{W}_{\textrm{hz}}\mathbf{h}_{t-1}, \mathbf{W}_{\textrm{hr}}\mathbf{h}_{t-1}, and \mathbf{W}_{\textrm{hh}}(\mathbf{r}_t \odot \mathbf{h}_{t-1}) from the standard GRU (Feng et al., 2024).
  • Compact & Scan-Ready: Cuts parameters by 3\times (6d^2 \to 2d^2) and fits \mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t directly.

What One Linear Layer Loses—and What Depth Recovers

Expressivity Trade-Off

  • Single-Layer Blindness: Because \mathbf{z}_t = \sigma(\mathbf{W}_\textrm{z}\mathbf{x}_t + \mathbf{b}_\textrm{z}) cannot inspect \mathbf{h}_{t-1}, a 1-layer minGRU cannot tell whether a memory slot is already full and overwrites on later digits.
  • Depth Adds One Round of State Conditioning per Layer: In a 2-block stack, Layer 1’s state \mathbf{h}_t^{(1)} summarizes history so Layer 2’s gate \mathbf{z}_t^{(2)} can lock the slot while keeping parallel scan training.

Associative Composition of Affine State Transitions

Algebra of Parallel Scans

(\mathbf{a}_1, \mathbf{b}_1) \bullet (\mathbf{a}_2, \mathbf{b}_2) = (\mathbf{a}_1 \odot \mathbf{a}_2,\; \mathbf{a}_2 \odot \mathbf{b}_1 + \mathbf{b}_2)

  • Closure Under Composition: Composing two affine steps f_2(f_1(\mathbf{h})) produces a single affine pair (\mathbf{A}, \mathbf{B}) of width d in O(d) elementwise work.
  • Associative (Not Commutative): Grouping order does not matter, unlocking parallel tree reductions across time.

The Hillis–Steele Parallel Doubling Scan Schedule

Parallel Prefix Scan

  • Doubling stride schedule (Hillis & Steele, 1986): In round r = 0, 1, \ldots, \lceil \log_2 T \rceil - 1, every position t > 2^r combines with position t - 2^r in parallel: \text{stride } s = 1 \to 2 \to 4 \to \cdots \to 2^{\lceil\log_2 T\rceil - 1}
  • Doubling vs. work-efficient trees: Hillis–Steele performs O(T \log_2 T) combines across \lceil \log_2 T \rceil rounds, whereas Blelloch’s up-sweep/down-sweep tree (Blelloch, 1990) performs \sim 2T combines across 2\lceil \log_2 T \rceil rounds.

Implementing associative_scan and linear_scan

Scan Code Architecture

associative_scan slices earlier = x[:, :-s] and later = x[:, s:] at doubling strides s = 1, 2, 4, \ldots:

s = 1
while s < elems[0].shape[1]:  # Combine every position with the one s steps back
    earlier, later = tuple(x[:, :-s] for x in elems), 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
  • Handling initial states (h0): linear_scan(a, b, h0) folds a nonzero initial state \mathbf{h}_0 into the first step’s write (\mathbf{b}_1 \leftarrow \mathbf{a}_1 \odot \mathbf{h}_0 + \mathbf{b}_1) before launching the prefix scan, enabling chunk-by-chunk state passing.

Verifying the Parallel Scan Against Sequential Stepping

Scan Implementation

linear_scan(a, b, h0) folds an optional initial state \mathbf{h}_0 into the first write (\mathbf{b}_1 \leftarrow \mathbf{a}_1 \odot \mathbf{h}_0 + \mathbf{b}_1) and runs the associative prefix scan along the time axis:

def combine(earlier, later):
    (a1, b1), (a2, b2) = earlier, later
    return a1 * a2, a2 * b1 + b2
max deviation: 4.8e-07

Even on a non-power-of-two length (T = 100), the parallel scan and sequential loop agree to float32 rounding error (\sim 10^{-7}).

Evaluating minGRU on Byte-Level WikiText-103

Language Modeling Benchmark

Using our 4-block SeqLM benchmark (128-byte windows, 1{,}000 AdamW steps), we compare GRU (d = 256), minGRU (d = 256), and a parameter-matched minGRU, d=302 (3.81\text{M} parameters):

                           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 (2.76\text{M} vs. 3.81\text{M} params), minGRU trails GRU by \sim 0.05 nats/byte (1.35 vs. 1.30); matching parameter count (minGRU, d=302) closes the gap to \sim 0.03 nats/byte while beating the attention baseline (1.38).

Probing State Utility: The State-Reset Ablation

Inside the Trained Model

How much of minGRU’s prediction quality comes from context carried in \mathbf{h}_{t-1} versus current-token features in the residual stream? We evaluate the trained model with \mathbf{h}_{t-1} = \mathbf{0} forced at every step (StateReset, so \mathbf{h}_t = \mathbf{b}_t):

validation loss: 1.343 nats per byte, with the state reset at every step: 2.481
  • Over 1.1 nats/byte from recurrent memory: Zeroing the state degrades validation loss from 1.35 to 2.48 nats/byte—collapsing all the way back to the empirical byte-bigram baseline (2.45 nats/byte).

How Training Shifts the Distribution of Gate Half-Lives

Gate Timescale Analysis

Inspecting the update gates \mathbf{z}_t \in (0, 1)^d of the first minGRU block on a validation batch before and after 1{,}000 training steps:

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%
  • Emergence of word-scale memories: At initialization (\mathbf{b}_\textrm{z} = \mathbf{0}), only 1\%–2\% of gates exceed 0.9 (half-life \ge 7 bytes); training expands this share more than tenfold to \sim 18\%.
  • Why almost no gates exceed 0.99 (half-life 69 bytes): Over 128-byte windows, local word and phrase context dominates the loss, and zero-bias initialization starts far from the 0.99–0.999 regime—a limitation §12.4 addresses directly.

Asymptotic Complexity: GRU vs. Scan vs. Attention

Work, Depth, and Memory

  • Sequential GRU: \Theta(T d^2) FLOPs across \Theta(T) serial steps with \Theta(d) generation state.
  • Parallel minGRU Scan: \Theta(T d^2) projection FLOPs in \Theta(\log_2 T) depth while keeping \Theta(d) inference state.
  • Causal Attention Crossover: Pairwise attention scores (2T^2 d) overtake projections (8Td^2) once \mathbf{T > 4d}.

Wall-Clock Scaling Across Sequence Lengths to 16,384

Hardware Benchmark

Forward + backward runtime (ms) in float16 at width d = 256 with total tokens per batch held constant at B \times T = 65{,}536 as T sweeps from 512 to 16{,}384:

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

Doubling Scan Memory Traffic vs. Quadratic Attention

PyTorch Scaling Analysis

With total batch tokens fixed at B \times T = 65{,}536, an ideal linear-time layer has a completely horizontal curve:

  • Sequential GRU (O(T) depth): Slowest at every length, growing >15\times from T = 512 to 16{,}384 because doubling T doubles the number of dependent kernel steps while halving batch parallelism B.
  • Compiled minGRU (doubling scan): Performs \lceil \log_2 T \rceil memory passes (9 rounds at T = 512 to 14 rounds at T = 16{,}384), rising by less than 50\% across a 32\times increase in sequence length.
  • Causal attention (O(T^2 d) work): Stays flat up to T = 2{,}048 while projections and fixed overheads dominate, crosses the doubling scan near T = 4{,}096, and climbs toward 2\times per doubling—trailing minGRU by 2.5\times at T = 16{,}384.

Concept Check: Scan Depth, Closure, and Crossover

Check Your Understanding

Answer these three questions on linear recurrences and parallel scans:

  1. For a sequence of length T = 16{,}384, how many parallel rounds does the Hillis–Steele doubling scan take compared to a sequential loop, and what is the binary combine result of (0.5, 1) \bullet (0.5, 2)?
  2. Why does a dense matrix transition \mathbf{h}_t = \mathbf{A}_t \mathbf{h}_{t-1} + \mathbf{b}_t (\mathbf{A}_t \in \mathbb{R}^{d \times d}) become prohibitively expensive to scan at d = 256, even though matrix composition is associative?
  3. In our constant-token benchmark (B \times T = 65{,}536, d = 256), why does GRU runtime double each time T doubles even though its total FLOP count B T d^2 is constant?

Answers:

  1. \log_2 16{,}384 = \mathbf{14\text{ rounds}} (vs. 16{,}383 sequential steps); (0.5, 1) \bullet (0.5, 2) = (0.5 \times 0.5,\; 0.5 \times 1 + 2) = \mathbf{(0.25, 2.5)}.
  2. Composing two dense transitions requires a matrix-matrix product \mathbf{A}_2 \mathbf{A}_1 costing O(d^3) FLOPs instead of O(d) elementwise multiplies (d^2 = 65{,}536\times more work per combine).
  3. Every step of the GRU waits for \mathbf{h}_{t-1} and pays a fixed kernel/synchronization latency, so doubling T doubles the sequential critical-path latency.

Summary: Linear Recurrences and Associative Scans

Key Takeaways

Mechanism / Model Mathematical Definition Key Scaling & Modeling Property
Affine Vector Recurrence \mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t Unrolls to \sum_{s \le t} (\prod_{r=s+1}^t \mathbf{a}_r) \odot \mathbf{b}_s; forward & gradient decay at same rate
Minimal GRU (MinGRU) \mathbf{z}_t = \sigma(\mathbf{W}_\textrm{z}\mathbf{x}_t + \mathbf{b}_\textrm{z}), \mathbf{b}_t = (1-\mathbf{z}_t)\odot\tilde{\mathbf{h}}_t Drops \mathbf{h}_{t-1} from gates (2d^2 params); trails GRU by 0.03 nats/byte at equal size
Associative Combine (\bullet) (\mathbf{a}_1, \mathbf{b}_1) \bullet (\mathbf{a}_2, \mathbf{b}_2) = (\mathbf{a}_1 \odot \mathbf{a}_2, \mathbf{a}_2 \odot \mathbf{b}_1 + \mathbf{b}_2) Compresses any block of steps into one pair of width d in O(d) work
Doubling vs. Tree Scan \lceil \log_2 T \rceil vs. 2\lceil \log_2 T \rceil parallel rounds O(T \log T) vs. O(T) combines; flat wall-clock time up to T = 16{,}384
Attention Crossover 8Td^2 projections vs. 2T^2 d attention scores Quadratic attention cost dominates once T \gtrsim 4d and grows linearly with T per token