Gated Recurrent Networks

Dive into Deep Learning · §12.1

Gated Recurrent Networks: LSTM and GRU
vanishing gradients · sigmoid decay gates · memory cells · gate bias initialization · residual sequence mixers

Why Plain RNNs Lose Long-Range Grammatical Context

Motivation

\mathbf{h}_t = \tanh(\mathbf{W}_\textrm{hh}\mathbf{h}_{t-1} + \mathbf{W}_\textrm{xh}\mathbf{x}_t + \mathbf{b}_\textrm{h})

  • Full-State Overwriting: Every step multiplies \mathbf{h}_{t-1} by \mathbf{W}_\textrm{hh} and squashes it through \tanh.
  • Geometric Signal Decay: At w = 0.9, perturbations shrink to 0.9^{30} \approx 4\% across 30 steps and 0.9^{100} \approx 0.003\% across 100 steps.

Jacobian Products and the Spectral Radius Borderline

Vanishing & Exploding Gradients

\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-k}} = \prod_{s=t-k+1}^{t} \textrm{diag}(1 - \mathbf{h}_s^2)\,\mathbf{W}_\textrm{hh}

  • Contractive vs. Expansive Regimes: Since |1 - h_s^2| \le 1, powers scale as \rho^k (\rho = \max_i |\lambda_i(\mathbf{W}_\textrm{hh})|)—vanishing when \rho < 1 and exploding when \rho > 1.
  • Asymmetry of Failure: Clipping caps explosions, but cannot recover underflowed long-lag gradients.

From Unbounded Running Sums to Learned Decay Gates

The Gating Principle

c_t = f_t\, c_{t-1} + i_t\, \tilde{c}_t, \qquad \tau_{1/2} = \frac{\ln 2}{\ln(1/f)}

  • Elementwise Gradient Highway: Along the direct memory rail, \partial c_t / \partial c_{t-k} = \prod_{s=t-k+1}^t f_s \le 1 with no \mathbf{W}_\textrm{hh} matrix product.
  • Tunable Horizon: Holding f_t \approx 0.99–0.999 stretches the memory half-life from 1 step to 69–693 steps.

The Long Short-Term Memory (LSTM) Architecture

LSTM Mechanics

The LSTM (Hochreiter & Schmidhuber, 1997; Gers et al., 2000) maintains an internal memory cell \mathbf{c}_t \in \mathbb{R}^d and an exposed hidden state \mathbf{h}_t \in \mathbb{R}^d:

  • Three sigmoid gates in (0, 1)^d: Input gate \mathbf{i}_t, forget gate \mathbf{f}_t, and output gate \mathbf{o}_t each apply \sigma(\mathbf{W}_{\textrm{x}\cdot}\mathbf{x}_t + \mathbf{W}_{\textrm{h}\cdot}\mathbf{h}_{t-1} + \mathbf{b}_\cdot).
  • Candidate input node: \tilde{\mathbf{c}}_t = \tanh(\mathbf{W}_\textrm{xc}\mathbf{x}_t + \mathbf{W}_\textrm{hc}\mathbf{h}_{t-1} + \mathbf{b}_\textrm{c}) \in (-1, 1)^d.
  • Additive cell update & gated readout: \mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t with exposed state \mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t).

Decoupling Internal Storage from Exposed Output

Silent Retention & Gradient Highway

  • Silent Storage Until Needed: Holding f_t = 0.95, i_t = 0.1 preserves c_t = 0.71 while a closed output gate (o_t = 0.2) shields downstream layers (h_t = 0.12).
  • Bounding Cell Magnitude: Squashing \tanh(\mathbf{c}_t) at readout keeps \mathbf{h}_t \in (-1, 1)^d even when repeated writes push |c_t| > 1.
  • Direct Cell Jacobian: Along the top cell rail, \partial \mathbf{c}_t / \partial \mathbf{c}_{t-1} = \textrm{diag}(\mathbf{f}_t).

Fused 4-Gate Matrix Projection and Verification

LSTM Implementation

Because \mathbf{i}_t, \mathbf{f}_t, \tilde{\mathbf{c}}_t, and \mathbf{o}_t all read (\mathbf{x}_t, \mathbf{h}_{t-1}), stacking their weights into \mathbf{W}_\textrm{x} \in \mathbb{R}^{d_\textrm{in} \times 4d} and \mathbf{W}_\textrm{h} \in \mathbb{R}^{d \times 4d} computes all four pre-activations in one batched matrix product per step:

i, f, c_tilde, o = (x @ self.W_x + h @ self.W_h + self.b).chunk(4, -1)
c = torch.sigmoid(f) * c + torch.sigmoid(i) * torch.tanh(c_tilde)
h = torch.sigmoid(o) * torch.tanh(c)
max difference: 6.0e-08

Our from-scratch loop matches fused nn.LSTM to float32 rounding error (\sim 10^{-7}), so we use fused library kernels for training.

Gated Recurrent Units (GRU): Coupled Reset and Update

GRU Architecture

The GRU (Cho et al., 2014) merges the cell and hidden state into a single vector \mathbf{h}_t \in \mathbb{R}^d governed by two gates:

  • Reset gate \mathbf{r}_t & update gate \mathbf{z}_t: Both computed via \sigma(\mathbf{W}_{\textrm{x}\cdot}\mathbf{x}_t + \mathbf{W}_{\textrm{h}\cdot}\mathbf{h}_{t-1} + \mathbf{b}_\cdot).
  • Reset-filtered candidate: \mathbf{r}_t gates how much past state enters the nonlinear proposal: \tilde{\mathbf{h}}_t = \tanh\big(\mathbf{W}_\textrm{xh}\mathbf{x}_t + \mathbf{W}_\textrm{hh}(\mathbf{r}_t \odot \mathbf{h}_{t-1}) + \mathbf{b}_\textrm{h}\big)
  • Convex interpolation (i_t = 1 - f_t): \mathbf{h}_t = \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t

LSTM vs. GRU: Structural and Systems Trade-Offs

Architectural Comparison

  • State & Gate Count: LSTM carries two vectors (\mathbf{c}_t, \mathbf{h}_t) controlled by 3 independent gates (8d^2 params); GRU carries one vector \mathbf{h}_t with 2 gates (6d^2 params, 25\% smaller).
  • Bounding Mechanism: LSTM bounds \mathbf{h}_t via readout \tanh(\mathbf{c}_t), whereas GRU’s convex blend \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t keeps \mathbf{h}_t \in [-1, 1]^d automatically.

Synthetic Stress Test: The Delayed Recall Benchmark

Experimental Setup

Gated equations represent long memories, but does gradient descent actually discover them? We test retention on synthetic delayed recall:

  • Task structure: Step 1 presents a target symbol drawn from \{0, \ldots, 7\}, followed by T - 1 random filler tokens drawn from \{8, \ldots, 15\}. At step T, the network must classify the initial symbol (chance accuracy = 1/8 = 0.125).
  • Architecture (RecallModel): Token embedding (d_\textrm{in} = 32) \to single recurrent layer (d = 64, LeCun normal weights) \to linear classifier at step T, trained for 1{,}500 steps of Adam (\text{lr} = 3 \times 10^{-3}, batch size 128).
[[ 6 10 10  8  8  8]
 [ 5 14 13 15 12 12]] [[6]
 [5]]

Pitfall: Zero-Bias Gates Start with a 1-Step Memory

Initialization Hazard

  • One-Step Initial Half-Life: With \mathbf{b}_\textrm{f} = \mathbf{0}, gates start at \sigma(0) = 1/2, attenuating the direct gradient from step T to step 1 by 2^{-(T-1)}.
  • Underflow Wall at T \ge 50: While 2^{-19} \approx 1.9 \times 10^{-6} at T=20 survives in float32, 2^{-49} \approx 1.8 \times 10^{-15} at T=50 is rounded away when the state adds it to the O(1) contributions of recent steps.

Keep-Gate Initialization and Cell Magnitude Bounding

Chrono & Keep-Gate Bias

  • 100-Step Initial Horizon: Setting b_\textrm{f} = +5 starts gates at \sigma(5) \approx 0.9933 (\tau_{1/2} \approx 103 steps), preserving 0.9933^{50} \approx 71\% of the gradient across 50 steps.
  • Paired Input Bias (b_\textrm{i} = -5): Leaving b_\textrm{i} = 0 lets LSTM cells grow to |c_t| \le 0.5 / 0.0067 \approx 75; setting b_\textrm{i} = -b_\textrm{f} = -5 couples i_t = 1 - f_t so |c_t| \le 1.

Plain RNN Initialization: Borderline vs. Contracting

Spectral Radius Analysis

Before training, we also compare two initializations of a 64 \times 64 plain RNN recurrent matrix \mathbf{W}_\textrm{hh}:

 LeCun normal: spectral radius 1.02, largest singular value 2.01
default scale: spectral radius 0.62, largest singular value 1.10
  • LeCun normal (\mathcal{N}(0, 1/64)): By the circular law of random matrix theory, eigenvalues fill the unit disk (\rho \approx 1.02) even though the largest singular value is \approx 2.0. Small states along leading eigenmodes neither vanish nor explode.
  • Default uniform (\mathcal{U}[-1/8, 1/8]): Has 1/3 the variance of LeCun normal, giving spectral radius \rho \approx 0.62 and contracting every signal by \sim 0.6^k.

Delayed Recall Results Across 20 to 200 Time Steps

Empirical Results

Accuracy across two random seeds at delays T \in \{20, 50, 100, 200\} (chance = 0.125):

                          20        50       100       200
RNN                1.00/1.00 0.25/0.26 1.00/0.35 0.23/0.24
RNN, default scale 1.00/1.00 1.00/0.12 0.12/0.12 0.12/0.13
LSTM               0.61/0.22 0.12/0.12 0.12/0.13 0.12/0.12
GRU                1.00/1.00 0.12/0.12 0.13/0.13 0.13/0.13
LSTM, keep gate    1.00/1.00 1.00/1.00 1.00/1.00 1.00/1.00
GRU, keep gate     1.00/1.00 1.00/1.00 1.00/1.00 1.00/1.00

Initializing forget/update biases to +5 (keep gate) turns complete failure (0.12) at T \ge 50 into 1.00 accuracy across every seed and delay up to T = 200.

Why Gate Initialization Decides Long-Range Recall

Interpreting the Recall Sweep

Comparing the three model pairs in the delayed recall table isolates architecture from initialization:

  • Zero-bias LSTM & GRU: The GRU solves T = 20 (1.00) and the LSTM is unreliable there (0.2–1.00); both collapse to chance (0.12–0.14) at T \in \{50, 100, 200\} because a contribution of 2^{-49} is rounded away in float32.
  • Keep-gate LSTM & GRU: Identical architecture and parameter count, yet starting at \sigma(5) = 0.993 yields 1.00 accuracy on every run from T = 20 to T = 200.
  • Borderline vs. contracting plain RNN: The \rho \approx 1.02 LeCun RNN sporadically carries the symbol to T = 100 (with large variance between seeds), whereas the \rho \approx 0.62 uniform RNN is hit-or-miss up to T = 50 and fails from T = 100 onward.

Gates replace fragile whole-matrix eigenvalue tuning with per-unit learned decay, provided initial biases keep the gradient horizon open.

Fair Language Benchmarks via a Shared Residual Stack

The SeqLM Backbone

\mathbf{H} \leftarrow \mathbf{H} + \textrm{mixer}(\textrm{LN}(\mathbf{H})), \quad \mathbf{H} \leftarrow \mathbf{H} + \textrm{MLP}(\textrm{LN}(\mathbf{H}))

  • Controlled Architecture: Byte embedding \to 4 pre-norm residual blocks (d = 256, 4d GELU MLP) \to LayerNorm + output head on 128-byte WikiText-103 windows.
  • Isolating the Mixer: Only mixer(·) changes across §§12.1–12.8.

Byte-Level WikiText-103: Mixers Compared Head-to-Head

Language Modeling Benchmark

Two runs per configuration reporting parameters, overall validation loss (nats/byte), loss by window position band (0-15, 16-63, 64-127), and training step time:

                        validation        0-15       16-63      64-127   ms/step
RNN          2,764,544 1.347/1.349 1.510/1.512 1.324/1.325 1.324/1.325 13/13
LSTM         4,343,552 1.292/1.293 1.488/1.490 1.266/1.267 1.263/1.264 32/38
GRU          3,817,216 1.297/1.299 1.490/1.492 1.271/1.273 1.269/1.271 34/38
attention    3,286,784 1.378/1.375 1.560/1.556 1.354/1.350 1.351/1.349 20/21
RNN, d=302   3,816,932 1.334/1.334 1.501/1.501 1.310/1.311 1.309/1.310 21/21

Dissecting the WikiText-103 Results and Step Latency

Quality vs. Step Cost

Three systems and modeling lessons emerge from the WikiText-103 benchmark:

  1. The residual stack closes the plain-RNN gap: Simply placing 4 narrow \tanh RNN layers inside SeqLM reaches \sim 1.35 nats/byte—matching Chapter 11’s 6-block SwiGLU GPT and outperforming the 4-block GELU attention stack (1.38) at this 1{,}000-step budget.
  2. Gating beats raw parameter scaling: Replacing the plain RNN with an LSTM or GRU lowers loss by 0.05 nats/byte to \sim 1.30, whereas widening the plain RNN to match the GRU’s 3.81\text{M} parameters (RNN, d=302) closes less than a third of that gap (\sim 1.33).
  3. Step cost: LSTM and GRU take 1.4\times–3\times longer per step than the plain RNN because each step computes three or four gate products instead of one. All three wait for \mathbf{h}_{t-1}; the length sweep of §12.3 isolates that cost.

Concept Check: Gate Half-Lives and Saturation Bounds

Check Your Understanding

Work out the following three design questions:

  1. If an LSTM forget gate is held at f_t = 0.99, what is its memory half-life in steps, and what fraction of a direct cell gradient survives k = 100 steps?
  2. Why does init_keep_gate set the LSTM input-gate bias to b_\textrm{i} = -5 alongside b_\textrm{f} = +5, whereas the GRU only needs b_\textrm{z} = +5?
  3. Why can gradient clipping stabilize an RNN with spectral radius \rho = 1.3, but cannot fix a zero-bias LSTM on 100-step delayed recall?

Answers:

  1. Half-life \tau_{1/2} = \ln 2 / \ln(1/0.99) \approx \mathbf{69\text{ steps}}; after 100 steps, 0.99^{100} \approx \mathbf{36.6\%} of the direct gradient survives.
  2. The GRU couples its input weight to 1 - z_t = 1 - \sigma(5) = \sigma(-5) automatically; in an LSTM, leaving b_\textrm{i} = 0 (i_t = 0.5) lets cell states grow up to 0.5 / (1 - 0.9933) \approx 75, saturating \tanh(c_t).
  3. Clipping rescales overly large gradients downward, whereas 2^{-99} \approx 1.6 \times 10^{-30} underflows to zero in float32 when summed with recent gradients—destroying directional information.

Summary: Plain vs. Gated Recurrent Architectures

Key Takeaways

Architecture / Setup Direct Memory Path Recurrent Params (d_\textrm{in}=d) T=200 Recall Accuracy WikiText-103 (nats/byte) Training Depth
Plain RNN (uniform scale) \tanh(\mathbf{W}_\textrm{hh}\mathbf{h}_{t-1} + \cdots), \rho \approx 0.62 2d^2 0.12 (chance) — T sequential steps
Plain RNN (LeCun normal) \tanh(\mathbf{W}_\textrm{hh}\mathbf{h}_{t-1} + \cdots), \rho \approx 1.02 2d^2 0.12–0.24 (up to 1.00 at T=100) 1.346–1.349 (1.332–1.337 at d=302) T sequential steps
LSTM (zero gate bias) \mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t, f_0 = 0.5 8d^2 0.12 (chance at T \ge 50) 1.292–1.296 T sequential steps
GRU (zero gate bias) \mathbf{h}_t = \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1-\mathbf{z}_t)\odot \tilde{\mathbf{h}}_t 6d^2 0.12–0.13 (chance at T \ge 50) 1.297–1.300 T sequential steps
LSTM / GRU (keep gate +5) Initial gate \sigma(5) = 0.993 (\tau_{1/2} \approx 103) 8d^2 / 6d^2 1.00 (all seeds) — T sequential steps