12.1 Gated Recurrent Networks

The plain recurrent network of Section 8.4.2 generates recognizable words and punctuation, yet its grammar unravels over more than a few words. Consider predicting the verb after "the keys to the cabinet in the hall": choosing "are" rather than "is" requires remembering that "keys", 30 characters back, is plural. Because a plain RNN overwrites its entire state at every step through the same recurrent matrix and tanh⁡\tanh nonlinearity, both the forward signal and the backward gradient decay rapidly over tens of steps. How can a recurrent network hold what it has read across hundreds of steps?

The solution introduced in the late 1990s is to let the network decide, unit by unit and step by step, what fraction of its state to keep via a gate: a vector of values in (0,1)(0, 1) computed from the current input and previous state. A unit whose gate stays near 11 passes both its stored content and the backward gradient across the step essentially unchanged. Below we build the two classic gated architectures, the long short-term memory (LSTM) and the gated recurrent unit (GRU), and evaluate them on synthetic delayed recall and on the byte-level WikiText-103 benchmark of Chapter 11. While gates solve long-range retention, their dependence on the previous state still forces sequential step-by-step training; Section 12.3 removes that bottleneck.

Throughout this chapter we write equations for a single sequence using column vectors, while the code processes minibatches of sequences with row vectors.

12.1.1 Gates#

12.1.1.1 Vanishing Gradients#

Recall from Section 8.5.1 how gradients propagate through a plain RNN with hidden state ht∈Rd\mathbf{h}_t \in \mathbb{R}^d:

ht=tanh⁡(Whhht−1+Wxhxt+bh).(12.1.1)\mathbf{h}_t = \tanh(\mathbf{W}_\textrm{hh} \mathbf{h}_{t-1} + \mathbf{W}_\textrm{xh} \mathbf{x}_t + \mathbf{b}_\textrm{h}). \tag{12.1.1}

A perturbation to ht−k\mathbf{h}_{t-k} reaches ht\mathbf{h}_t multiplied by a chain of kk step Jacobians Js=diag(1−hs2) Whh\mathbf{J}_s = \textrm{diag}(1 - \mathbf{h}_s^2)\,\mathbf{W}_\textrm{hh}:

∂ht∂ht−k=JtJt−1⋯Jt−k+1.(12.1.2)\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-k}} = \mathbf{J}_t \mathbf{J}_{t-1} \cdots \mathbf{J}_{t-k+1}. \tag{12.1.2}

For a single scalar unit, each factor is w(1−hs2)w(1 - h_s^2) of magnitude at most ∣w∣|w|. When ∣w∣<1|w| \lt 1, the product shrinks at least as fast as ∣w∣k|w|^k (at w=0.9w = 0.9, to about 4%4\% over 30 steps and ≤0.003%\le 0.003\% over 100 steps).

For a matrix Whh\mathbf{W}_\textrm{hh}, if its largest singular value is below 11, every factor contracts every vector and the product must vanish. Over many steps, matrix powers scale as ρk\rho^k, where the spectral radius ρ\rho (the largest eigenvalue magnitude) satisfies ρ≤∥Whh∥2\rho \le \|\mathbf{W}_\textrm{hh}\|_2. If ρ≈1\rho \approx 1 and the state remains small so tanh⁡\tanh is nearly linear, components along the leading eigenvectors can survive for many steps—a borderline regime we will observe in our experiments below. Away from ρ≈1\rho \approx 1, gradients either explode (which gradient clipping can cap) or vanish (which no post-hoc rescaling can recover).

12.1.1.2 An Additive Memory#

The simplest recurrence with unit Jacobian is a pure running sum, ct=ct−1+xtc_t = c_{t-1} + x_t, for which ∂ct/∂ct−k=1\partial c_t / \partial c_{t-k} = 1 at every lag kk. However, an unweighted sum never forgets: every past input remains superposed with equal weight, and the state's variance grows with sequence length.

12.1.1.3 Gates as Learned Decay#

To retain relevant inputs while discarding irrelevant ones, we let the network choose at each step a retention fraction ft∈(0,1)f_t \in (0, 1) and an input fraction it∈(0,1)i_t \in (0, 1) multiplying new candidate content c~t\tilde{c}_t:

ct=ft ct−1+it c~t.(12.1.3)c_t = f_t\, c_{t-1} + i_t\, \tilde{c}_t. \tag{12.1.3}

Along the direct memory path, the kk-step derivative is the product of the kept fractions, ∂ct/∂ct−k=∏s=t−k+1tfs\partial c_t / \partial c_{t-k} = \prod_{s=t-k+1}^t f_s. At a constant keep fraction ff, a stored value decays as fkf^k with a half-life of ln⁡2/ln⁡(1/f)\ln 2 / \ln(1/f) steps: roughly 7 steps at f=0.9f = 0.9, 69 at f=0.99f = 0.99, and 693 at f=0.999f = 0.999. Setting ft→1f_t \to 1 preserves a value and its gradient indefinitely; setting ft→0f_t \to 0 flushes the cell in a single step.

In a layer of width dd, the memory becomes a vector ct∈Rd\mathbf{c}_t \in \mathbb{R}^d accompanied by an exposed hidden state ht∈Rd\mathbf{h}_t \in \mathbb{R}^d. Each gate computes a vector in (0,1)d(0, 1)^d via a sigmoid layer reading the current input xt\mathbf{x}_t and previous output ht−1\mathbf{h}_{t-1}:

ft=σ(Wxfxt+Whfht−1+bf).(12.1.4)\mathbf{f}_t = \sigma(\mathbf{W}_\textrm{xf} \mathbf{x}_t + \mathbf{W}_\textrm{hf} \mathbf{h}_{t-1} + \mathbf{b}_\textrm{f}). \tag{12.1.4}

Unlike a plain RNN, which multiplies the entire state by a dense matrix Whh\mathbf{W}_\textrm{hh} and applies tanh⁡\tanh at every step, the gated memory updates each coordinate by elementwise multiplication with its own learned factor ft,j∈(0,1)f_{t,j} \in (0, 1). Because ft,j≤1f_{t,j} \le 1, gradients along the direct memory path cannot explode, and holding ft,jf_{t,j} near 11 prevents them from vanishing.

Two practical details remain. First, while ft≈1f_t \approx 1, repeated writes can still cause the stored value ctc_t to grow, so the LSTM applies a tanh⁡\tanh when reading ct\mathbf{c}_t out to ht\mathbf{h}_t. Second, under zero bias initialization, sigmoid gates start near σ(0)=1/2\sigma(0) = 1/2 (a half-life of a single step), so a gated network can represent long memories but does not start with them by default.

12.1.2 Long Short-Term Memory#

12.1.2.1 The Memory Cell#

The long short-term memory (LSTM) of Hochreiter and Schmidhuber (1997), augmented with the forget gate of Gers et al. (2000), builds a recurrent layer around (12.1.3). It maintains two vectors of width dd: an internal memory cell ct\mathbf{c}_t evolved purely by elementwise gating and addition, and an exposed hidden state ht\mathbf{h}_t that provides a gated, squashed view of ct\mathbf{c}_t to subsequent layers and to the next step's gates.

Three sigmoid gates, the input gate it\mathbf{i}_t, forget gate ft\mathbf{f}_t, and output gate ot\mathbf{o}_t, control access to the cell:

it=σ(Wxixt+Whiht−1+bi),ft=σ(Wxfxt+Whfht−1+bf),ot=σ(Wxoxt+Whoht−1+bo).(12.1.5)\begin{aligned} \mathbf{i}_t &= \sigma(\mathbf{W}_\textrm{xi} \mathbf{x}_t + \mathbf{W}_\textrm{hi} \mathbf{h}_{t-1} + \mathbf{b}_\textrm{i}),\\ \mathbf{f}_t &= \sigma(\mathbf{W}_\textrm{xf} \mathbf{x}_t + \mathbf{W}_\textrm{hf} \mathbf{h}_{t-1} + \mathbf{b}_\textrm{f}),\\ \mathbf{o}_t &= \sigma(\mathbf{W}_\textrm{xo} \mathbf{x}_t + \mathbf{W}_\textrm{ho} \mathbf{h}_{t-1} + \mathbf{b}_\textrm{o}). \end{aligned} \tag{12.1.5}

A fourth projection with tanh⁡\tanh activation proposes the candidate input node c~t=tanh⁡(Wxcxt+Whcht−1+bc)\tilde{\mathbf{c}}_t = \tanh(\mathbf{W}_\textrm{xc} \mathbf{x}_t + \mathbf{W}_\textrm{hc} \mathbf{h}_{t-1} + \mathbf{b}_\textrm{c}). The cell and hidden state then update via elementwise multiplication (⊙\odot):

ct=ft⊙ct−1+it⊙c~t,ht=ot⊙tanh⁡(ct).(12.1.6)\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t, \qquad \mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t). \tag{12.1.6}

Separating ct\mathbf{c}_t from ht\mathbf{h}_t lets a unit hold information silently until it is needed: for instance, if ct−1=0.8c_{t-1} = 0.8 with ft=0.95f_t = 0.95, it=0.1i_t = 0.1, c~t=−0.5\tilde{c}_t = -0.5, and ot=0.2o_t = 0.2, the cell stays at ct=0.71c_t = 0.71 while exposing only ht=0.2tanh⁡(0.71)=0.12h_t = 0.2\tanh(0.71) = 0.12 (Figure 12.1.1).

Figure 12.1.1:

The LSTM memory cell. The previous output ht−1\mathbf{h}_{t-1} and the input xt\mathbf{x}_t feed four layers: three sigmoid gates and a tanh⁡\tanh input node. The cell ct\mathbf{c}_t is updated additively, scaled by the forget gate, and the output gate controls what the rest of the network sees.

With the gates treated as fixed, the direct cell-to-cell Jacobian ∂ct/∂ct−1\partial \mathbf{c}_t / \partial \mathbf{c}_{t-1} is simply diag(ft)\textrm{diag}(\mathbf{f}_t) (the top rail in Figure 12.1.1). The full derivative also includes indirect terms through ht−1\mathbf{h}_{t-1} and the gates, but the cell rail provides an unattenuated highway whenever ft\mathbf{f}_t stays near 11.

12.1.2.2 Implementation#

Because it\mathbf{i}_t, ft\mathbf{f}_t, c~t\tilde{\mathbf{c}}_t, and ot\mathbf{o}_t all read (xt,ht−1)(\mathbf{x}_t, \mathbf{h}_{t-1}), we stack their weights into two matrices Wx∈Rdin×4d\mathbf{W}_\textrm{x} \in \mathbb{R}^{d_\textrm{in} \times 4d} and Wh∈Rd×4d\mathbf{W}_\textrm{h} \in \mathbb{R}^{d \times 4d}, compute a single matrix multiplication per input, and split the result into four chunks.

class LSTMScratch(nn.Module):
    """An LSTM layer computed one time step at a time."""
    def __init__(self, num_inputs, num_hiddens):
        super().__init__()
        self.num_hiddens = num_hiddens
        # Weights of i, f, c_tilde, and o, stacked along the last axis, with
        # variance 1 / fan-in
        self.W_x = nn.Parameter(torch.randn(num_inputs, 4 * num_hiddens)
                                / math.sqrt(num_inputs))
        self.W_h = nn.Parameter(torch.randn(num_hiddens, 4 * num_hiddens)
                                / math.sqrt(num_hiddens))
        self.b = nn.Parameter(torch.zeros(4 * num_hiddens))

    def forward(self, X):  # X: (batch_size, num_steps, num_inputs)
        h = c = torch.zeros(X.shape[0], self.num_hiddens, device=X.device)
        outputs = []
        for x in X.unbind(1):  # One time step at a time
            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)
            outputs.append(h)
        return torch.stack(outputs, 1)  # (batch_size, num_steps, num_hiddens)

To verify that LSTMScratch computes the exact same recurrence as the framework's LSTM layer, we copy the library weights into our class and compare outputs on a random batch.

The library layer is the fused nn.LSTM.

lstm = nn.LSTM(16, 32, batch_first=True)  # Stacks its weights as i, f, c~, o
cell = LSTMScratch(16, 32)
with torch.no_grad():
    cell.W_x.copy_(lstm.weight_ih_l0.T)
    cell.W_h.copy_(lstm.weight_hh_l0.T)
    cell.b.copy_(lstm.bias_ih_l0 + lstm.bias_hh_l0)
X = torch.randn(4, 9, 16)  # (batch_size, num_steps, num_inputs)
print(f'max difference: {(cell(X) - lstm(X)[0]).abs().max():.1e}')
max difference: 6.0e-08

The outputs agree to float32 rounding error (∼10−7\sim 10^{-7}), so we use the faster fused library layers from here on.

12.1.3 Gated Recurrent Units#

Does a gated layer really need two state vectors and three gates? The gated recurrent unit (GRU) of Cho et al. (2014) merges the cell and hidden state into a single vector ht\mathbf{h}_t controlled by just two gates (a reset gate rt\mathbf{r}_t and an update gate zt\mathbf{z}_t) while matching the LSTM on many sequence tasks (Chung et al., 2014):

rt=σ(Wxrxt+Whrht−1+br),zt=σ(Wxzxt+Whzht−1+bz).(12.1.7)\mathbf{r}_t = \sigma(\mathbf{W}_\textrm{xr} \mathbf{x}_t + \mathbf{W}_\textrm{hr} \mathbf{h}_{t-1} + \mathbf{b}_\textrm{r}), \qquad \mathbf{z}_t = \sigma(\mathbf{W}_\textrm{xz} \mathbf{x}_t + \mathbf{W}_\textrm{hz} \mathbf{h}_{t-1} + \mathbf{b}_\textrm{z}). \tag{12.1.7}

The reset gate filters how much of ht−1\mathbf{h}_{t-1} enters the proposed candidate state:

h~t=tanh⁡(Wxhxt+Whh(rt⊙ht−1)+bh).(12.1.8)\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). \tag{12.1.8}

The update gate zt\mathbf{z}_t then interpolates convexly between the old state and the candidate:

ht=zt⊙ht−1+(1−zt)⊙h~t.(12.1.9)\mathbf{h}_t = \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t. \tag{12.1.9}

Equation (12.1.9) is the gated sum (12.1.3) with coupled forget and input gates (ft=zt,it=1−ztf_t = z_t, i_t = 1 - z_t). Because each coordinate convexly blends two values in [−1,1][-1, 1], ht\mathbf{h}_t stays bounded in [−1,1][-1, 1] without an extra output tanh⁡\tanh (Figure 12.1.2), and a GRU layer requires 6d26d^2 recurrent/input weights compared to an LSTM's 8d28d^2. (Fused library GRUs apply rt\mathbf{r}_t after multiplying by Whh\mathbf{W}_\textrm{hh} so all recurrent matrix products can be batched into one call; see the exercises.)

Figure 12.1.2:

The GRU cell. The reset gate filters the previous state inside the candidate h~t\tilde{\mathbf{h}}_t; the update gate blends the old state and the candidate.

12.1.4 Training Gated Networks#

12.1.4.1 Delayed Recall#

The gated equations allow memories lasting hundreds of steps, but does gradient descent actually find them? We test retention directly on a synthetic delayed recall task: a sequence begins with one of 8 target symbols (0–7), followed by T−1T - 1 random filler tokens drawn from 8 other symbols (8–15), and at step TT the model must classify the initial symbol (chance accuracy 1/8=0.1251/8 = 0.125).

def delayed_recall(rng, batch_size, num_steps, num_symbols=8,
                   blank_fillers=False):
    """A symbol, then num_steps - 1 fillers; the target is the symbol."""
    Y = rng.integers(0, num_symbols, (batch_size, 1))  # One query, at the end
    X = rng.integers(num_symbols, 2 * num_symbols, (batch_size, num_steps))
    if blank_fillers:  # The same filler token at every step
        X[:] = num_symbols
    X[:, :1] = Y
    return X, Y

X, Y = delayed_recall(np.random.default_rng(0), 2, 6)
print(X, Y)
[[ 6 10 10  8  8  8]
 [ 5 14 13 15 12 12]] [[6]
 [5]]

Our evaluation model (RecallModel) embeds tokens into 32 dimensions, runs a single recurrent layer of width 64, and applies a linear classifier at the final step. Throughout this chapter, we initialize all linear, convolutional, and recurrent weight matrices with LeCun normal initialization (variance 1/nin1 / n_\textrm{in}) and zero biases (Section 4.4).

init_lecun applies LeCun normal weights and zero biases across linear, convolutional, and recurrent modules, and Recurrent wraps PyTorch recurrent modules to return only the output sequence tensor.

def init_lecun(module):
    """LeCun normal weights and zero biases for all linear, convolutional,
    and recurrent layers."""
    for layer in module.modules():
        if isinstance(layer, (nn.Linear, nn.Conv1d)):
            fan_in = layer.weight[0].numel()  # Inputs of one output unit
            nn.init.normal_(layer.weight, std=fan_in ** -0.5)
            if layer.bias is not None:
                nn.init.zeros_(layer.bias)
        elif isinstance(layer, nn.RNNBase):  # Input and recurrent matrices
            for name, param in layer.named_parameters():
                if name.startswith('weight'):
                    nn.init.normal_(param, std=param.shape[1] ** -0.5)
                else:
                    nn.init.zeros_(param)
    return module

class Recurrent(nn.Module):
    """A batch-first recurrent layer that returns only its outputs."""
    def __init__(self, rnn):
        super().__init__()
        self.rnn = rnn

    def forward(self, X):
        return self.rnn(X)[0]

We compare six recurrent configurations in three pairs:

  1. Plain RNNs: one with LeCun normal recurrent weights (σ=1/64=1/8\sigma = 1/\sqrt{64} = 1/8) and a control with uniform weights on [−1/8,1/8][-1/8, 1/8] (variance 1/31/3 of LeCun normal).
  2. Default LSTM and GRU: zero gate biases, so all gates start near σ(0)=1/2\sigma(0) = 1/2 (half-life 1 step).
  3. Keep-gate LSTM and GRU (init_keep_gate): the LSTM forget-gate bias and GRU update-gate bias are initialized to +5+5 (σ(5)=0.993\sigma(5) = 0.993, half-life ≈100\approx 100 steps), and the LSTM input-gate bias is set to −5-5 (σ(−5)=1−σ(5)=0.007\sigma(-5) = 1 - \sigma(5) = 0.007). Pairing bi=−bfb_\textrm{i} = -b_\textrm{f} bounds the LSTM cell magnitude by σ(−5)/(1−σ(5))=1\sigma(-5)/(1 - \sigma(5)) = 1 across long filler runs so the output tanh⁡\tanh never saturates, matching the GRU's built-in 1−zt1 - \mathbf{z}_t coupling (see Jozefowicz et al. (2015) and the chrono initialization of Tallec and Ollivier (2018)).

The uniform control matches PyTorch's default nn.RNN initialization.

class RecallModel(nn.Module):
    """Embedding, a sequence layer, and a classifier at every position."""
    def __init__(self, layer, num_hiddens, vocab_size=16, num_inputs=32,
                 num_outputs=8):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, num_inputs)
        nn.init.normal_(self.embedding.weight, std=num_inputs ** -0.5)
        self.layer = layer
        self.head = init_lecun(nn.Linear(num_hiddens, num_outputs))

    def forward(self, X):  # Logits, (batch_size, num_steps, num_outputs)
        return self.head(self.layer(self.embedding(X)))

def init_keep_gate(rnn, bias=5.0):
    """Start an LSTM's forget gate, or a GRU's update gate, near one."""
    h = rnn.hidden_size
    with torch.no_grad():
        rnn.bias_ih_l0.zero_()  # Independent of the earlier initialization
        rnn.bias_hh_l0.zero_()
        rnn.bias_ih_l0[h:2 * h] = bias  # LSTM: i, f, c~, o; GRU: r, z, n
        if isinstance(rnn, nn.LSTM):
            rnn.bias_ih_l0[:h] = -bias  # Input gate near zero
    return rnn

Notice what simple arithmetic predicts for the default zero-bias gated networks: when every gate starts at 1/21/2, the direct path between step 11 and step TT is attenuated by 2−(T−1)2^{-(T-1)} in both directions—roughly 10−610^{-6} at T=20T = 20 (still resolvable in float32) but 10−1510^{-15} at T=50T = 50. The state at step TT adds the symbol's contribution to the O(1)O(1) contributions of recent steps, so anything below float32's ∼10−7\sim 10^{-7} relative precision is rounded away before the readout sees it, and the gradient that returns to the symbol's embedding is just as small. We therefore expect default LSTM/GRU to succeed at T=20T = 20 and fail by T=50T = 50, while the keep-gate variants should succeed across all delays up to T=200T = 200.

We save the training helpers train_queries, query_accuracy, and train_delayed_recall for reuse across all synthetic recall tasks in this chapter.

def train_queries(model, batch, num_steps, optimizer,
                  scheduler=None):
    """Train on fresh batches; the queries are the last Y.shape[1] steps."""
    device = next(model.parameters()).device
    for step in range(num_steps):
        X, Y = (torch.as_tensor(A, device=device) for A in batch(step))
        logits = model(X)[:, -Y.shape[1]:]  # Predictions at the queries
        loss = F.cross_entropy(logits.flatten(0, 1), Y.flatten())
        optimizer.zero_grad()
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        if scheduler is not None:
            scheduler.step()

def query_accuracy(model, X, Y):
    """Fraction of queries answered correctly."""
    device = next(model.parameters()).device
    X, Y = (torch.as_tensor(A, device=device) for A in (X, Y))
    with torch.inference_mode():
        return (model(X)[:, -Y.shape[1]:].argmax(-1) == Y).float().mean()

def train_delayed_recall(model, num_steps, blank_fillers=False):
    """Train with Adam at rate 0.003 on 1,500 fresh batches of 128 sequences
    of delayed recall; return the accuracy on 2,048 new sequences."""
    task = lambda rng, n: delayed_recall(rng, n, num_steps,
                                         blank_fillers=blank_fillers)
    rng = np.random.default_rng(0)
    model.to(d2l.try_gpu())
    train_queries(model, lambda step: task(rng, 128), 1500,
                  torch.optim.Adam(model.parameters(), lr=3e-3))
    return float(query_accuracy(model, *task(np.random.default_rng(1), 2048)))

Before training, let us also check the spectral radius and largest singular value of the two 64×6464 \times 64 plain RNN initializations:

rng, n = np.random.default_rng(0), 64  # n hidden units
for name, W in (('LeCun normal', rng.normal(0, n ** -0.5, (n, n))),
                ('default scale', rng.uniform(-n ** -0.5, n ** -0.5, (n, n)))):
    print(f'{name:>13}: spectral radius {np.abs(np.linalg.eigvals(W)).max():.2f},'
          f' largest singular value {np.linalg.norm(W, 2):.2f}')
 LeCun normal: spectral radius 1.02, largest singular value 2.01
default scale: spectral radius 0.62, largest singular value 1.10

The LeCun normal matrix has spectral radius 1.021.02 (sitting right at the ρ≈1\rho \approx 1 borderline where leading eigenmodes neither vanish nor explode when states are small), whereas the uniform default-scale matrix has spectral radius 0.620.62 (shrinking states by ∼0.6\sim 0.6 per step). Now we train two seeds of all six models across delays T∈{20,50,100,200}T \in \{20, 50, 100, 200\}.

def recurrent(layer, keep_gate=False):
    """A batch-first layer, 32 inputs to 64 hidden units, LeCun-initialized."""
    layer = init_lecun(layer(32, 64, batch_first=True))
    return init_keep_gate(layer) if keep_gate else layer

def rnn_default_scale():  # The recurrent matrix as nn.RNN draws it
    rnn = recurrent(nn.RNN)
    nn.init.uniform_(rnn.weight_hh_l0, -64 ** -0.5, 64 ** -0.5)
    return rnn

layers = {'RNN': lambda: recurrent(nn.RNN),
          'RNN, default scale': rnn_default_scale,
          'LSTM': lambda: recurrent(nn.LSTM), 'GRU': lambda: recurrent(nn.GRU),
          'LSTM, keep gate': lambda: recurrent(nn.LSTM, keep_gate=True),
          'GRU, keep gate': lambda: recurrent(nn.GRU, keep_gate=True)}
delays = [20, 50, 100, 200]
print(' ' * 18, ' '.join(f'{T:>9d}' for T in delays))
for name, layer in layers.items():
    runs = [[train_delayed_recall(RecallModel(Recurrent(layer()), 64), T)
             for _ in range(2)] for T in delays]
    print(f'{name:18s}', ' '.join(f'{a:.2f}/{b:.2f}' for a, b in runs))
                          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

The results confirm the analysis for the GRU and for every delay T≥50T \ge 50, and they correct it for the LSTM:

  • Default vs. keep-gate LSTM and GRU: With zero gate biases, the GRU succeeds at T=20T = 20 and both cells collapse to chance (0.120.12) at T≥50T \ge 50. The default LSTM, however, is already unreliable at T=20T = 20, where the arithmetic predicted success. That estimate counted only the forget gates. We did not isolate the cause, but the likely one is that the LSTM's symbol must also enter the cell through a half-open input gate and leave it through a half-open output gate and a tanh⁡\tanh, which puts T=20T = 20 at the edge of what training can recover. With init_keep_gate, both achieve 1.001.00 accuracy across every run at every delay up to T=200T = 200.
  • Borderline vs. contracting plain RNN: Because the LeCun normal RNN starts with spectral radius ρ≈1\rho \approx 1, some seeds carry the symbol surprisingly far (even to T=100T = 100), though unreliably across seeds, whereas the ρ≈0.62\rho \approx 0.62 default-scale RNN is hit-or-miss up to T=50T = 50 and fails on every seed from T=100T = 100 onward. Gates with well-initialized biases turn hit-or-miss spectral retention into dependable, per-unit memory control.

12.1.4.2 Gated Networks on Text#

In Section 11.2.3.2, a single wide plain RNN fell behind a multi-block GPT after the first few bytes of context and never caught up. To compare sequence mixers on equal footing, without confounding recurrence against residual depth and positionwise MLPs, we place every mixer in this chapter inside the same pre-norm residual backbone (SeqLM), matching Section 11.1: token embedding, a stack of blocks each applying H = H + mixer(norm(H)) followed by a two-layer GELU MLP H = H + mlp(H), and a final layer norm and linear output head (Figure 12.1.3).

Figure 12.1.3:

The shared backbone SeqLM. A block adds the output of a mixer, and then of an MLP, to the residual stream, each after its own layer normalization. Only the mixer changes from one model of this chapter to the next; the language models stack L=4L = 4 blocks.

class SeqLM(nn.Module):
    """A language model of residual blocks: a sequence mixer, then an MLP."""
    def __init__(self, vocab_size, num_hiddens, mixers):
        super().__init__()
        d = num_hiddens
        self.embedding = nn.Embedding(vocab_size, d)
        nn.init.normal_(self.embedding.weight, std=d ** -0.5)  # Unit length
        self.mixers = nn.ModuleList(mixers)
        self.norms = nn.ModuleList([nn.LayerNorm(d) for _ in mixers])
        self.mlps = nn.ModuleList([nn.Sequential(
            nn.LayerNorm(d), nn.Linear(d, 4 * d), nn.GELU(),
            nn.Linear(4 * d, d)) for _ in mixers])
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, vocab_size)
        for module in (self.mlps, self.head):  # Mixers initialize themselves
            init_lecun(module)

    def forward(self, X):
        H = self.embedding(X)  # (batch_size, num_steps, num_hiddens)
        for norm, mixer, mlp in zip(self.norms, self.mixers, self.mlps):
            H = H + mixer(norm(H))
            H = H + mlp(H)
        return self.head(self.norm(H))  # (batch_size, num_steps, vocab_size)

Our attention baseline within SeqLM is AttentionMixer, which wraps causal multi-head attention with RoPE (Section 11.2, Section 10.4), LeCun normal initialization, and an optional depthwise causal convolution over (Q,K,V)(\mathbf{Q}, \mathbf{K}, \mathbf{V}) (used later in Section 12.8).

class AttentionMixer(d2l.CausalAttention):
    """Causal multi-head attention, with rotary positions unless rope is
    False, as a sequence mixer; with conv_width, a causal convolution per
    channel first mixes each query, key, and value with those of the
    previous steps."""
    def __init__(self, num_hiddens, num_heads, conv_width=None, rope=True):
        super().__init__(num_hiddens, num_heads, rope=rope)
        d = 3 * num_hiddens  # Channels of q, k, and v; one filter each
        self.conv = None if conv_width is None else nn.Conv1d(
            d, d, conv_width, groups=d, padding=conv_width - 1)
        init_lecun(self)  # Like every mixer of the chapter

    def qkv(self, X, offset=0, tables=None):
        B, T, _ = X.shape
        QKV = self.W_qkv(X)
        if self.conv is not None:  # Causal: drop the last conv_width - 1 steps
            QKV = self.conv(QKV.mT)[..., :T].mT
        q, k, v = (u.reshape(B, T, self.num_heads, -1).transpose(1, 2)
                   for u in QKV.chunk(3, -1))
        if self.rope:
            q, k = (d2l.rope(u, offset, tables=tables) for u in (q, k))
        return q, k, v  # Each (batch_size, num_heads, num_steps, head width)

We also save three evaluation helpers used across the chapter. First, loss_by_position computes the mean validation cross-entropy in nats at each position of the context window:

@torch.inference_mode()
def loss_by_position(model, data):
    """Mean validation loss in nats at each position of the window."""
    device = next(model.parameters()).device
    total, count = 0, 0
    for X, Y in data.val_dataloader():
        logits = model(X.to(device))  # (batch, T, V)
        total += F.cross_entropy(logits.transpose(1, 2), Y.to(device),
                                 reduction='none').sum(0)
        count += len(X)
    return (total / count).tolist()

Next, train_text trains a model for 1,000 steps of AdamW (100-step warmup to 2×10−32 \times 10^{-3} followed by cosine decay), and text_table runs two seeds per configuration to report parameter count, overall and position-band (0-15, 16-63, 64-127) validation losses, and milliseconds per step:

def train_text(model, data, lr=2e-3, num_steps=1000):
    """Train a language model with LMOptimizer; return its validation loss
    in nats at each position and its milliseconds per training step."""
    optimizer = d2l.LMOptimizer(model, lr=lr, num_steps=num_steps, warmup=100)
    # One untimed call of 50 steps warms up (JAX compiles), the rest is timed
    bench = d2l.Benchmark(lambda: d2l.train_steps(model, data, optimizer, 50),
                          warmup=1, repeats=num_steps // 50 - 1)
    return loss_by_position(model, data), 1000 * bench.time / 50

def text_table(make_model, arms, data, num_runs=2, num_steps=1000):
    """Train num_runs fresh models make_model(*args) for each arm (a name
    and its args) for num_steps steps; print the parameters, the validation loss of every run,
    its losses at early, middle, and late positions of the window, and the
    milliseconds per step. Return the trained models of each arm."""
    T = data.num_steps
    bands = [(0, T // 8), (T // 8, T // 2), (T // 2, T)]
    width = max(len(name) for name in arms)
    header = ['validation'] + [f'{a}-{b - 1}' for a, b in bands]
    print(' ' * (width + 12), *(f'{h:>11}' for h in header), '  ms/step')
    trained = {}
    for name, args in arms.items():
        models = [make_model(*args) for _ in range(num_runs)]
        runs = [train_text(model, data, num_steps=num_steps)  # (losses, ms)
                for model in models]
        columns = [[np.mean(loss) for loss, _ in runs]] + [
            [np.mean(loss[a:b]) for loss, _ in runs] for a, b in bands]
        print(f'{name:{width}s} {d2l.num_params(models[0]):11,d}',
              *('/'.join(f'{v:.3f}' for v in column) for column in columns),
              '/'.join(f'{ms:.0f}' for _, ms in runs))
        trained[name] = models
    return trained

We now benchmark our recurrent and attention mixers on byte-level WikiText-103 (d2l.WikiText103, windows of 128 bytes, batch size 64):

data = d2l.WikiText103(batch_size=64, num_steps=128)

Each text_model stacks 4 residual blocks at width d=256d = 256, comparing a plain RNN, an LSTM, a GRU, and 8-head causal attention, plus a parameter-matched plain RNN widened to d=302d = 302 (3.81M3.81\textrm{M} parameters, matching the GRU stack):

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 SeqLM(256, d, [mixer(d) for _ in range(4)]).to(d2l.try_gpu())

rnn = lambda d: Recurrent(init_lecun(nn.RNN(d, d, batch_first=True)))
lstm = lambda d: Recurrent(init_lecun(nn.LSTM(d, d, batch_first=True)))
gru = lambda d: Recurrent(init_lecun(nn.GRU(d, d, batch_first=True)))
attention = lambda d: AttentionMixer(d, num_heads=8)
arms = {'RNN': (rnn, 256), 'LSTM': (lstm, 256), 'GRU': (gru, 256),
        'attention': (attention, 256),
        'RNN, d=302': (rnn, 302)}  # As many parameters as the GRU

Calling text_table trains two runs of each arm and prints the side-by-side comparison:

trained = text_table(text_model, arms, data)
                        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

Three findings stand out from the table:

  1. Residual stacking + gating: Simply placing 4 narrow tanh⁡\tanh RNN layers inside a pre-norm residual + MLP backbone reaches ∼1.35\sim 1.35 nats/byte—already matching the 6-block SwiGLU GPT of Section 11.2. Replacing the plain RNN mixer with an LSTM or GRU lowers validation loss by a further 0.050.05 nats/byte (to ∼1.30\sim 1.30), whereas widening the plain RNN to match the GRU's parameter count (RNN, d=302) closes less than a third of that gap (about 1.331.33).
  2. Short-context utilization: Across all models in this 1,000-step, 128-byte regime, loss drops sharply from band 0-15 to 16-63 and changes by less than 0.0050.005 beyond byte 16. Here the gates earn their lead by managing short-range byte context more effectively rather than by carrying 100-step memories; the attention stack (about 1.381.38) trails the recurrent mixers already in the first 16 bytes at this small training budget.
  3. Step cost: Despite fused library loops, the LSTM and GRU take 1.4×1.4\times–3×3\times longer per training step than the plain RNN. The cause is the work inside each step: three or four gate products where the plain RNN computes one. It is not the sequential evaluation, because the plain RNN waits for the previous step's hidden state ht−1\mathbf{h}_{t-1} in the same way. At 128 steps that dependence is not yet the dominant cost, so this table cannot show it. The length sweep of Section 12.3.4 isolates it: there the GRU's step time grows more than fifteenfold between 512 and 16,384 tokens.

12.1.5 Summary#

In a plain recurrent network, signals and gradients pass through a product of step Jacobians governed by a single shared matrix Whh\mathbf{W}_\textrm{hh}, surviving over long horizons only when its spectral radius sits near 11. Gated recurrent networks introduce an elementwise additive memory path ct=ftct−1+itc~tc_t = f_t c_{t-1} + i_t \tilde{c}_t controlled by learned sigmoid gates. The LSTM separates an internal memory cell ct\mathbf{c}_t (guarded by input, forget, and output gates) from the exposed state ht\mathbf{h}_t, while the GRU couples the forget and input gates (1−zt1 - \mathbf{z}_t) and filters the recurrent state via a reset gate rt\mathbf{r}_t on a single state vector. On synthetic delayed recall, initializing forget/update gates near 11 (init_keep_gate) is decisive, turning chance accuracy at T≥50T \ge 50 into 100%100\% recall at T=200T = 200. On byte-level WikiText-103 inside a residual backbone (SeqLM), LSTM and GRU mixers outperform both equal-width and parameter-matched plain RNNs by 0.030.03–0.050.05 nats/byte, but their dependence on ht−1\mathbf{h}_{t-1} inside the gates still forces TT sequential steps during training.

12.1.6 Exercises#

  1. Holding a value. Suppose that the character at step ss determines the prediction at a much later step tt, and that one LSTM unit is to carry it from ss to tt.

    1. State the value that each gate of that unit in (12.1.5) should take at step ss, at the steps strictly between ss and tt, and at step tt. Then do the same for the update gate of a GRU unit in (12.1.9).
    2. A sigmoid gate never reaches 1. Suppose that the forget gate's pre-activation stays at a constant bb, so that its value is σ(b)\sigma(b) at every step. What fraction of the stored value survives kk steps along the direct path? How large must bb be for 90% of the value to survive 1,000 steps?
    3. Show that a forget-gate bias of log⁡(T−1)\log(T - 1) gives an initial forget gate of 1−1/T1 - 1/T when the weights are zero, so that for large TT a stored value decays by a factor of about ee over TT steps. The chrono initialization of Tallec and Ollivier (2018) draws the forget-gate bias of each unit as log⁡u\log u, with uu uniform on [1,Tmax−1][1, T_\textrm{max} - 1], and sets bi=−bf\mathbf{b}_\textrm{i} = -\mathbf{b}_\textrm{f}. Show that with zero weights this makes ft+it=1\mathbf{f}_t + \mathbf{i}_t = 1, and compare the resulting cell update with (12.1.9).
  2. Output squashing. The input node c~t\tilde{\mathbf{c}}_t is already squashed by a tanh⁡\tanh, yet (12.1.6) applies tanh⁡\tanh to ct\mathbf{c}_t again before the output gate.

    1. Starting from c0=0\mathbf{c}_0 = \mathbf{0}, show that every entry of ct\mathbf{c}_t is smaller than tt in magnitude. Show further that if every forget-gate value is at most fmax<1f_\textrm{max} \lt 1 and every input-gate value at most imaxi_\textrm{max}, every entry stays below imax/(1−fmax)i_\textrm{max} / (1 - f_\textrm{max}) in magnitude, whatever tt is.
    2. Suppose that the output were ht=ot⊙ct\mathbf{h}_t = \mathbf{o}_t \odot \mathbf{c}_t instead. After many steps of accumulation, what happens to the gate pre-activations at the next step, and what does that do to the gradients that flow through the gates?
  3. Reset before or after. The fused GRU layers of deep learning frameworks apply the reset gate after the recurrent matrix product. Apart from the placement of the bias terms, they compute the candidate

h~t=tanh⁡(Wxhxt+rt⊙(Whhht−1)+bh)\tilde{\mathbf{h}}_t = \tanh(\mathbf{W}_\textrm{xh} \mathbf{x}_t + \mathbf{r}_t \odot (\mathbf{W}_\textrm{hh} \mathbf{h}_{t-1}) + \mathbf{b}_\textrm{h})

in place of (12.1.8).

  1. Show that the two candidates agree for every rt\mathbf{r}_t and ht−1\mathbf{h}_{t-1} if and only if Whh\mathbf{W}_\textrm{hh} is diagonal. For a general Whh\mathbf{W}_\textrm{hh}, which reset-gate values still make them agree?
  2. The input products Wx⋅xt\mathbf{W}_{\textrm{x}\cdot} \mathbf{x}_t of all steps can be computed as one large product before the recurrence starts. Under each form of the candidate, how many matrix products involving the previous state must each step perform one after the other? Why do fused GRU kernels use the form above?
  1. [code] GRU from scratch. Write a class GRUScratch by editing LSTMScratch: three heads following (12.1.7) and (12.1.8), the update (12.1.9), and a state that consists of ht\mathbf{h}_t alone.
    1. Copy the weights of the library GRU layer into your layer, as we did for the LSTM, and compare the outputs. They will not agree. Use the previous exercise to change one line of your layer so that they do. (Also keep the last third of bias_hh_l0, the recurrent bias of the candidate, as a separate vector inside the reset gate, or zero it before copying.)
    2. Remove the reset gate by fixing rt=1\mathbf{r}_t = \mathbf{1}, and in a second layer remove the update gate by fixing zt=0\mathbf{z}_t = \mathbf{0}. Before training, predict from (12.1.9) which removal hurts delayed recall more. Then run the experiment of Section 12.1.4.1 and check your prediction.
  1. [code] The cell's other paths. ● Consider an LSTM with one input and one hidden unit, so that every quantity in (12.1.5) and (12.1.6) is a scalar, and write whfw_\textrm{hf}, whiw_\textrm{hi}, and whcw_\textrm{hc} for the recurrent weights of the forget gate, the input gate, and the input node.

    1. The output gate ot−1o_{t-1} depends on ht−2h_{t-2} but not on ct−1c_{t-1}. Using ht−1=ot−1tanh⁡(ct−1)h_{t-1} = o_{t-1} \tanh(c_{t-1}), derive the total derivative dct/dct−1\textrm{d}c_t / \textrm{d}c_{t-1}. Write it as the direct-path value ftf_t plus a correction, and factor the correction into a term from step tt and the derivative dht−1/dct−1\textrm{d}h_{t-1} / \textrm{d}c_{t-1}.
    2. For which values of the gates, of c~t\tilde{c}_t, and of ct−1c_{t-1} does the correction vanish? Which of these conditions can the network set through its gates while the cell is storing a value?
    3. Train an LSTM on delayed recall at a delay where it succeeds. For one test sequence, compute the norm of the gradient of the loss with respect to the cell cT−k\mathbf{c}_{T-k} for every kk, by automatic differentiation, and compare it with the gradient carried by the direct path alone, which multiplies the gradient at cT\mathbf{c}_T elementwise by the product of the forget-gate values over the last kk steps. Where do the two curves part, and which is larger?
  2. [code] Bidirectional leak. ● A recurrent layer can also read the sequence backward. A bidirectional network (Schuster and Paliwal, 1997) runs a second layer from the last step to the first and concatenates the outputs of the two, so that the representation of each position depends on the whole sequence. This helps whenever the whole input is given, as in tagging the words of a sentence or encoding a sentence for translation. A language model is another matter.

    1. Build a bidirectional mixer by running a second LSTM over the reversed sequence, reversing its outputs, concatenating them with those of a forward LSTM, and projecting the result back to width dd. Train SeqLM with such mixers in place of the LSTMs of Section 12.1.4.2, with train_text, and compare its validation loss with that of the forward model. Explain the number: which input does the backward layer read at position tt? What could the model do at generation time, when the following bytes do not exist yet?
    2. A leak-free bidirectional predictor of the byte xtx_t combines the forward state after step t−1t-1 with the backward state after step t+1t+1, so it models the probability of xtx_t given all other bytes of the window. Show with a sequence of two binary tokens that the product of these conditionals over tt need not sum to one over all sequences. What does this imply for using the product to score whole sequences, or to report a perplexity?

Discussions