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 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 computed from the current input and previous state. A unit whose gate stays near 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 :
A perturbation to reaches multiplied by a chain of step Jacobians :
For a single scalar unit, each factor is of magnitude at most . When , the product shrinks at least as fast as (at , to about over 30 steps and over 100 steps).
For a matrix , if its largest singular value is below , every factor contracts every vector and the product must vanish. Over many steps, matrix powers scale as , where the spectral radius (the largest eigenvalue magnitude) satisfies . If and the state remains small so 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 , 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, , for which at every lag . 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 and an input fraction multiplying new candidate content :
Along the direct memory path, the -step derivative is the product of the kept fractions, . At a constant keep fraction , a stored value decays as with a half-life of steps: roughly 7 steps at , 69 at , and 693 at . Setting preserves a value and its gradient indefinitely; setting flushes the cell in a single step.
In a layer of width , the memory becomes a vector accompanied by an exposed hidden state . Each gate computes a vector in via a sigmoid layer reading the current input and previous output :
Unlike a plain RNN, which multiplies the entire state by a dense matrix and applies at every step, the gated memory updates each coordinate by elementwise multiplication with its own learned factor . Because , gradients along the direct memory path cannot explode, and holding near prevents them from vanishing.
Two practical details remain. First, while , repeated writes can still cause the stored value to grow, so the LSTM applies a when reading out to . Second, under zero bias initialization, sigmoid gates start near (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 : an internal memory cell evolved purely by elementwise gating and addition, and an exposed hidden state that provides a gated, squashed view of to subsequent layers and to the next step's gates.
Three sigmoid gates, the input gate , forget gate , and output gate , control access to the cell:
A fourth projection with activation proposes the candidate input node . The cell and hidden state then update via elementwise multiplication ():
Separating from lets a unit hold information silently until it is needed: for instance, if with , , , and , the cell stays at while exposing only (Figure 12.1.1).
The LSTM memory cell. The previous output and the input feed four layers: three sigmoid gates and a input node. The cell 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 is simply (the top rail in Figure 12.1.1). The full derivative also includes indirect terms through and the gates, but the cell rail provides an unattenuated highway whenever stays near .
12.1.2.2 Implementation#
Because , , , and all read , we stack their weights into two matrices and , 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 (), 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 controlled by just two gates (a reset gate and an update gate ) while matching the LSTM on many sequence tasks (Chung et al., 2014):
The reset gate filters how much of enters the proposed candidate state:
The update gate then interpolates convexly between the old state and the candidate:
Equation (12.1.9) is the gated sum (12.1.3) with coupled forget and input gates (). Because each coordinate convexly blends two values in , stays bounded in without an extra output (Figure 12.1.2), and a GRU layer requires recurrent/input weights compared to an LSTM's . (Fused library GRUs apply after multiplying by so all recurrent matrix products can be batched into one call; see the exercises.)
The GRU cell. The reset gate filters the previous state inside the candidate ; 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 random filler tokens drawn from 8 other symbols (8–15), and at step the model must classify the initial symbol (chance accuracy ).
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 ) 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:
- Plain RNNs: one with LeCun normal recurrent weights () and a control with uniform weights on (variance of LeCun normal).
- Default LSTM and GRU: zero gate biases, so all gates start near (half-life 1 step).
- Keep-gate LSTM and GRU (
init_keep_gate): the LSTM forget-gate bias and GRU update-gate bias are initialized to (, half-life steps), and the LSTM input-gate bias is set to (). Pairing bounds the LSTM cell magnitude by across long filler runs so the output never saturates, matching the GRU's built-in 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 rnnNotice what simple arithmetic predicts for the default zero-bias gated networks: when every gate starts at , the direct path between step and step is attenuated by in both directions—roughly at (still resolvable in float32) but at . The state at step adds the symbol's contribution to the contributions of recent steps, so anything below float32's 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 and fail by , while the keep-gate variants should succeed across all delays up to .
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 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 (sitting right at the borderline where leading eigenmodes neither vanish nor explode when states are small), whereas the uniform default-scale matrix has spectral radius (shrinking states by per step). Now we train two seeds of all six models across delays .
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 , and they correct it for the LSTM:
- Default vs. keep-gate LSTM and GRU: With zero gate biases, the GRU succeeds at and both cells collapse to chance () at . The default LSTM, however, is already unreliable at , 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 , which puts at the edge of what training can recover. With
init_keep_gate, both achieve accuracy across every run at every delay up to . - Borderline vs. contracting plain RNN: Because the LeCun normal RNN starts with spectral radius , some seeds carry the symbol surprisingly far (even to ), though unreliably across seeds, whereas the default-scale RNN is hit-or-miss up to and fails on every seed from 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).
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 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 (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 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 trainedWe 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 , comparing a plain RNN, an LSTM, a GRU, and 8-head causal attention, plus a parameter-matched plain RNN widened to ( 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 GRUCalling 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:
- Residual stacking + gating: Simply placing 4 narrow RNN layers inside a pre-norm residual + MLP backbone reaches 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 nats/byte (to ), whereas widening the plain RNN to match the GRU's parameter count (
RNN, d=302) closes less than a third of that gap (about ). - Short-context utilization: Across all models in this 1,000-step, 128-byte regime, loss drops sharply from band
0-15to16-63and changes by less than 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 ) trails the recurrent mixers already in the first 16 bytes at this small training budget. - Step cost: Despite fused library loops, the LSTM and GRU take – 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 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 , surviving over long horizons only when its spectral radius sits near . Gated recurrent networks introduce an elementwise additive memory path controlled by learned sigmoid gates. The LSTM separates an internal memory cell (guarded by input, forget, and output gates) from the exposed state , while the GRU couples the forget and input gates () and filters the recurrent state via a reset gate on a single state vector. On synthetic delayed recall, initializing forget/update gates near (init_keep_gate) is decisive, turning chance accuracy at into recall at . On byte-level WikiText-103 inside a residual backbone (SeqLM), LSTM and GRU mixers outperform both equal-width and parameter-matched plain RNNs by – nats/byte, but their dependence on inside the gates still forces sequential steps during training.
12.1.6 Exercises#
-
Holding a value. Suppose that the character at step determines the prediction at a much later step , and that one LSTM unit is to carry it from to .
- State the value that each gate of that unit in (12.1.5) should take at step , at the steps strictly between and , and at step . Then do the same for the update gate of a GRU unit in (12.1.9).
- A sigmoid gate never reaches 1. Suppose that the forget gate's pre-activation stays at a constant , so that its value is at every step. What fraction of the stored value survives steps along the direct path? How large must be for 90% of the value to survive 1,000 steps?
- Show that a forget-gate bias of gives an initial forget gate of when the weights are zero, so that for large a stored value decays by a factor of about over steps. The chrono initialization of Tallec and Ollivier (2018) draws the forget-gate bias of each unit as , with uniform on , and sets . Show that with zero weights this makes , and compare the resulting cell update with (12.1.9).
-
Output squashing. The input node is already squashed by a , yet (12.1.6) applies to again before the output gate.
- Starting from , show that every entry of is smaller than in magnitude. Show further that if every forget-gate value is at most and every input-gate value at most , every entry stays below in magnitude, whatever is.
- Suppose that the output were 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?
-
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
in place of (12.1.8).
- Show that the two candidates agree for every and if and only if is diagonal. For a general , which reset-gate values still make them agree?
- The input products 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?
- [code] GRU from scratch. Write a class
GRUScratchby editingLSTMScratch: three heads following (12.1.7) and (12.1.8), the update (12.1.9), and a state that consists of alone.- 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.) - Remove the reset gate by fixing , and in a second layer remove the update gate by fixing . 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.
- 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
-
[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 , , and for the recurrent weights of the forget gate, the input gate, and the input node.
- The output gate depends on but not on . Using , derive the total derivative . Write it as the direct-path value plus a correction, and factor the correction into a term from step and the derivative .
- For which values of the gates, of , and of does the correction vanish? Which of these conditions can the network set through its gates while the cell is storing a value?
- 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 for every , by automatic differentiation, and compare it with the gradient carried by the direct path alone, which multiplies the gradient at elementwise by the product of the forget-gate values over the last steps. Where do the two curves part, and which is larger?
-
[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.
- 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
. Train
SeqLMwith such mixers in place of the LSTMs of Section 12.1.4.2, withtrain_text, and compare its validation loss with that of the forward model. Explain the number: which input does the backward layer read at position ? What could the model do at generation time, when the following bytes do not exist yet? - A leak-free bidirectional predictor of the byte combines the forward state after step with the backward state after step , so it models the probability of given all other bytes of the window. Show with a sequence of two binary tokens that the product of these conditionals over 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?
- 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
. Train