8.4 Recurrent Neural Networks
The count-based language models of Section 8.3 predict each token from a short window of immediate predecessors. A trigram model conditions only on the two preceding tokens; anything earlier in the document has zero influence on its prediction. Simply widening the window quickly hits a wall: a count table spanning 20 BPE tokens would have to track contexts, and even a neural network reading a fixed window of concatenated token embeddings (Bengio et al., 2003) remains blind to any token steps back while growing linearly in parameter count with .
In Section 8.1, we introduced a fundamentally different approach: a latent autoregressive model that compresses the entire history into a fixed-size hidden state vector and predicts the next token from that summary,
Under this recurrence, the computational cost per step stays constant no matter how long the prefix becomes. A recurrent neural network (RNN) parameterizes the transition function with a neural network layer whose weights are shared across all time steps (Elman, 1990). (Note that a hidden state carried across time steps differs from a feedforward hidden layer sitting between input and output within a single step.) In this section, we formulate the RNN language model, tally its parameters and compute, and implement it both from scratch and with high-level framework layers on The Time Machine.
8.4.1 Recurrent Neural Networks with Hidden States#
An RNN is easiest to understand by starting from a single-hidden-layer MLP (Section 4.1) and adding one recurrent connection. Given a minibatch of examples with features each, (we use for batch size throughout this chapter because denotes -gram order), an ordinary hidden layer with activation function computes
with and , followed by an output projection into logits.
Now suppose we receive a sequence of minibatch inputs indexed by time step . To let the hidden representation remember earlier steps, we feed the previous hidden state back into the layer via a recurrent weight matrix :
Because the same five parameter tensors (, , in the recurrent layer and , in the output layer) are reused at every step (starting from ), the parameter count is completely independent of sequence length (Figure 8.4.1). Viewed in unrolled form, an RNN running over steps is a -layer feedforward network whose layers all share the same weights.
An RNN with a hidden state, unrolled across three adjacent time steps. The same weights are reused at every step.
Notice that the two matrix products in (8.4.3) equal a single product of the horizontally concatenated inputs with the vertically stacked weights:
Libraries nevertheless keep the two products separate because during training all inputs are known up front, allowing across all steps to be batched outside the sequential time loop (exercise 1).
Furthermore, a recurrent state can solve tasks that are impossible for any fixed-window model, such as reporting at every step whether the running count of ones in a bit stream is even or odd (parity): flipping a bit older than any fixed window reverses the true parity while leaving the last bits unchanged, whereas a two-unit recurrent state tracks parity over arbitrary lengths.
8.4.1.1 Constant Memory per Step#
Because computing requires only and
, both memory and computation per step remain constant regardless
of sequence length: with float32 hidden units, the state of a
sequence occupies just 512 bytes whether the model has read ten tokens or a
million. That constant footprint is also an inherent lossy bottleneck—every
detail remembered from the prefix must pass through those 512 bytes, unlike
attention (Chapter 10), which retains representations of every
past token at a cost that grows with sequence length.
8.4.1.2 RNN Language Models and Teacher Forcing#
An RNN language model consumes one token id per step and predicts a distribution over the next token across all vocabulary entries (Figure 8.4.2). At step , the token ids in the minibatch look up their corresponding rows in a learned embedding table to form (mathematically identical to multiplying a one-hot matrix by , without materializing or multiplying by zeros). The recurrent layer updates , and defines in the chain-rule factorization (Section 8.3).
An RNN language model trained by teacher forcing over BPE tokens of The Time Machine. The target sequence is the input shifted forward by one token, so each step is trained to predict the next token.
Where do the parameters and FLOPs sit? For our BPE vocabulary of ids (1,024 BPE tokens plus three special tokens), embedding width , and hidden size :
| part | shape | parameters |
|---|---|---|
| embedding table | 65,728 | |
| input weight | 8,192 | |
| recurrent weight | 16,384 | |
| hidden bias | 128 | |
| output weight | 131,456 | |
| output bias | 1,027 | |
| total | 222,915 |
The recurrent layer accounts for just 24,704 parameters (11% of the model) and multiply-adds per token, whereas the vocabulary-sized embedding and output layers hold 89% of the parameters and the output projection alone costs multiply-adds.
During training, the input at every step is the ground-truth token from the corpus regardless of what the model predicted at the previous step—a regime known as teacher forcing. Because all ground-truth inputs in a window are known up front, the entire window's cross-entropy loss (the logarithm of perplexity) is evaluated in one forward pass. During generation, however, each sampled or greedy token is fed back in as the next input, exposing the rollout to its own errors just like our multistep sine-wave forecast in Section 8.1.
8.4.2 An RNN Language Model from Scratch#
We now implement the three components of this language model (the recurrent cell, the embedding lookup, and the output layer) from scratch.
8.4.2.1 The Recurrent Cell#
The RNNScratch class stores the parameters of (8.4.3) with
. We draw and
from with
and initialize to zero. At this scale, the spectral
radius of is roughly ,
so an untrained cell decays its past state rapidly and leaves training to grow
recurrent weights where needed.
class RNNScratch(d2l.Module):
"""The RNN model implemented from scratch."""
def __init__(self, num_inputs, num_hiddens, sigma=0.01):
super().__init__()
self.save_hyperparameters()
self.W_xh = nn.Parameter(
d2l.randn(num_inputs, num_hiddens) * sigma)
self.W_hh = nn.Parameter(
d2l.randn(num_hiddens, num_hiddens) * sigma)
self.b_h = nn.Parameter(d2l.zeros(num_hiddens))The forward pass loops over the leading time axis of inputs of shape
(num_steps, batch_size, num_inputs), initializing the hidden state to
zeros when none is supplied and returning the list of all per-step hidden
states alongside the final state.
@d2l.add_to_class(RNNScratch)
def forward(self, inputs, state=None):
if state is None:
# Initial state with shape: (batch_size, num_hiddens)
state = d2l.zeros((inputs.shape[1], self.num_hiddens),
device=inputs.device)
outputs = []
for X in inputs: # Shape of inputs: (num_steps, batch_size, num_inputs)
state = d2l.tanh(d2l.matmul(X, self.W_xh) +
d2l.matmul(state, self.W_hh) + self.b_h)
outputs.append(state)
return outputs, stateTo verify the recurrent cell's dimensions, we first run RNNScratch forward on
a dummy minibatch X of shape (num_steps, batch_size, num_inputs).
batch_size, num_inputs, num_hiddens, num_steps = 2, 16, 32, 100
rnn = RNNScratch(num_inputs, num_hiddens)
X = d2l.ones((num_steps, batch_size, num_inputs))
outputs, state = rnn(X)
We now define a check_shape helper (reused throughout later chapters) to
confirm that stacking outputs produces (num_steps, batch_size, num_hiddens)
and state has shape (batch_size, num_hiddens).
def check_shape(a, shape):
"""Check the shape of a tensor."""
assert a.shape == shape, \
f'tensor\'s shape {a.shape} != expected shape {shape}'
check_shape(d2l.stack(outputs, 0), (num_steps, batch_size, num_hiddens))
check_shape(state, (batch_size, num_hiddens))
8.4.2.2 The Embedding and Output Layers#
RNNLMScratch wraps a recurrent cell rnn with an embedding table E and an
output projection (W_hq, b_q), plus optional dropout rates on the
embeddings and hidden states. Embedding rows are initialized from
(matching unit-scale one-hot inputs) while output weights
use scale with zero bias, so an untrained model produces
near-zero logits and an initial perplexity close to . Subclassing
d2l.Classifier provides mean cross-entropy loss, and overriding
validation_step records that loss directly so its exponential gives
validation perplexity.
class RNNLMScratch(d2l.Classifier):
"""The RNN-based language model implemented from scratch."""
def __init__(self, rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0):
super().__init__()
self.save_hyperparameters()
self.sigma = getattr(rnn, 'sigma', 0.01) # Scale of the output weights
self.init_params()
def init_params(self):
self.E = nn.Parameter(
d2l.randn(self.vocab_size, self.rnn.num_inputs))
self.W_hq = nn.Parameter(
d2l.randn(self.rnn.num_hiddens, self.vocab_size) * self.sigma)
self.b_q = nn.Parameter(d2l.zeros(self.vocab_size))
def validation_step(self, batch):
return self.loss(self(*batch[:-1]), batch[-1])Because the data loader yields minibatches of shape (batch_size,
num_steps), embedding transposes the token ids before indexing E,
returning a (num_steps, batch_size, num_inputs) tensor whose leading axis
is time.
@d2l.add_to_class(RNNLMScratch)
def embedding(self, X):
# Output shape: (num_steps, batch_size, num_inputs)
return self.E[X.T]output_layer stacks the per-step states into shape (batch_size,
num_steps, num_hiddens) and applies the shared output projection in a
single batched matrix product, while forward chains embedding lookup,
dropout, the recurrent cell, and the output projection.
@d2l.add_to_class(RNNLMScratch)
def output_layer(self, rnn_outputs):
# A list of per-step states, or a tensor whose first axis is time
H = d2l.stack(list(rnn_outputs), 1) # (batch_size, num_steps, num_hiddens)
return d2l.matmul(H, self.W_hq) + self.b_q
@d2l.add_to_class(RNNLMScratch)
def forward(self, X, state=None):
embs = F.dropout(self.embedding(X), self.emb_dropout, self.training)
rnn_outputs, _ = self.rnn(embs, state)
H = d2l.stack(list(rnn_outputs), 0) # (num_steps, batch_size, num_hiddens)
return self.output_layer(F.dropout(H, self.dropout, self.training))Passing a dummy minibatch of token indices of shape (batch_size, num_steps)
through RNNLMScratch confirms that the returned logits tensor outputs has
shape (batch_size, num_steps, vocab_size).
model = RNNLMScratch(rnn, vocab_size=1024)
outputs = model(d2l.ones((batch_size, num_steps), dtype=d2l.int64))
check_shape(outputs, (batch_size, num_steps, 1024))8.4.3 Gradient Clipping#
Because an unrolled RNN applies the same transition Jacobian across steps, gradients can shrink or grow exponentially with (Section 8.5). A sudden gradient spike moves the parameters by Euclidean distance , overshooting the local region where the first-order Taylor approximation holds and undoing dozens of updates in a single step. Rather than shrinking across the board, gradient clipping caps the global gradient norm (computed jointly over all model parameters) at a threshold by projecting onto the ball of radius :
A gradient longer than is scaled back to length without changing its direction, and a shorter one is left alone (Figure 8.4.3).
Gradient clipping as a projection onto the ball of radius . The long gradient is rescaled to length along its own direction, whereas the gradient inside the ball is left unchanged.
Whenever gradient_clip_val is positive, d2l.Trainer (Section 2.4)
applies (8.4.4) right after backpropagation and before the
optimizer step.
The method below rescales each parameter's gradient in place.
@d2l.add_to_class(d2l.Trainer)
def clip_gradients(self, grad_clip_val, model):
params = [p for p in model.parameters() if p.requires_grad]
norm = torch.sqrt(sum(torch.sum(p.grad ** 2) for p in params))
scale = torch.clamp(grad_clip_val / norm, max=1.0) # no `if` on the host
for param in params:
param.grad.mul_(scale)8.4.4 Training and Evaluation#
d2l.TimeMachine (Section 8.3) encodes the 65,741 BPE tokens
of the novella and yields minibatches of overlapping windows—50,000
for training and 5,000 for validation, separated by a 32-window gap so no
validation token appears as a training target. Because each window starts from
, backpropagation is truncated to 32 steps
(Section 8.5).
data = d2l.TimeMachine(batch_size=1024, num_steps=32)
8.4.4.1 A Plain Model and the Role of Clipping#
We first instantiate our 222,915-parameter baseline model (, , no dropout) with SGD learning rate .
rnn = RNNScratch(num_inputs=64, num_hiddens=128)
model = RNNLMScratch(rnn, vocab_size=len(data.vocab), lr=4)Before training begins, we snapshot a NumPy copy of the random initial
embedding matrix model.E in E_init so we can measure how far SGD moves it.
E_init = d2l.numpy(model.E).copy()We next evaluate the untrained model's initial validation perplexity ppl_init
and then train model for 10 epochs with gradient clipping at
gradient_clip_val=1.
trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=1)
ppl_init = math.exp(trainer.evaluate(model, data)['loss'])
print(f'initial validation perplexity {ppl_init:.0f}')
trainer.fit(model, data)initial validation perplexity 1027
Exponentiating the final validation cross-entropy loss
trainer.history['val_loss'][-1] gives the trained baseline's validation
perplexity ppl_plain.
ppl_plain = math.exp(trainer.history['val_loss'][-1])
print(f'validation perplexity {ppl_plain:.1f}')validation perplexity 88.0
Initial validation perplexity sits near , and after ten epochs the clipped model reaches a validation perplexity of about 85 to 100, even though its loss often jumps well above the starting value during the first epoch (while training perplexity drops below half that value as the 222,915 parameters begin overfitting the 50,000 training tokens).
To see why gradient clipping is essential at , we define a helper
unclipped_model() that constructs a fresh baseline instance with the exact
same architecture and learning rate.
def unclipped_model():
return RNNLMScratch(RNNScratch(num_inputs=64, num_hiddens=128),
vocab_size=len(data.vocab), lr=4)We now train three independent unseeded instances without gradient clipping,
recording each run's epoch-by-epoch validation perplexities in ppl_runs and
reporting its peak and final values.
ppl_runs = []
for run in range(3): # Three unseeded runs, no clipping
trainer_unclipped = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer_unclipped.board.display = False # One plot for all runs below
trainer_unclipped.fit(unclipped_model(), data)
ppls = [math.exp(loss) for loss in trainer_unclipped.history['val_loss']]
ppl_runs.append(ppls)
print(f'run {run + 1}: highest {max(ppls):.3g}, final {ppls[-1]:.3g}')
finals = [ppls[-1] for ppls in ppl_runs]
print(f'{sum(f > 2 * ppl_plain for f in finals)} of 3 runs end above twice '
f'the clipped {ppl_plain:.3g}; finals from {min(finals):.3g} to '
f'{max(finals):.3g}')run 1: highest 1.28e+09, final 529
run 2: highest 4.26e+14, final 304
run 3: highest 782, final 219
3 of 3 runs end above twice the clipped 88; finals from 219 to 529
Plotting the three unclipped trajectories in ppl_runs against the clipped
baseline ppl_clipped on a logarithmic axis makes the instability
unmistakable.
ppl_clipped = [math.exp(loss) for loss in trainer.history['val_loss']]
d2l.plot(list(range(1, 11)), [ppl_clipped] + ppl_runs, 'epoch',
'validation perplexity', yscale='log',
legend=['clipped', 'run 1', 'run 2', 'run 3'],
legend_loc='outside', figsize=(5, 2.5))Without clipping, gradient spikes send validation perplexity jumping violently, sometimes far above the untrained baseline of 1,027, and most runs finish at more than twice the clipped model's perplexity. Converting our clipped validation perplexity to bits per byte (Section 8.3.2.4) divides by the average UTF-8 bytes per BPE token ():
ids = d2l.numpy(data.X[data.num_train:data.num_train+data.num_val, 0]).tolist()
bytes_per_token = len(data.tokenizer.decode(ids).encode('utf-8')) / len(ids)
print(f'{bytes_per_token:.2f} bytes/token, '
f'{math.log2(ppl_plain) / bytes_per_token:.2f} bits per byte')2.78 bytes/token, 2.32 bits per byte
8.4.4.2 Embeddings under SGD and a Wider Model with Dropout#
Inspecting how far each row of moved over the ten epochs of SGD
exposes a second bottleneck. We first extract the trained embedding table into
a NumPy array E_final.
E_final = d2l.numpy(model.E)Computing the relative Euclidean displacement change between E_final and
E_init across all vocabulary rows reveals how little each token vector moved.
change = (((E_final - E_init) ** 2).sum(1) / (E_init ** 2).sum(1)) ** 0.5
print(f'mean change of an embedding row: {change.mean():.1%} of its length')mean change of an embedding row: 4.3% of its length
Because row receives a gradient only from positions where token occurs, and the loss averages over all tokens in a minibatch, rare or moderate-frequency tokens receive tiny gradients under a uniform SGD learning rate, leaving almost frozen. While adaptive optimizers like Adam (Section 9.5) rescale per-coordinate step sizes to move embeddings much further (explored in the exercises), we can also address this directly within SGD: widening the embedding from to gives the densely updated input matrix a far richer random feature basis, while adding dropout (0.1 on embeddings, 0.5 on hidden states) curbs overfitting.
rnn = RNNScratch(num_inputs=512, num_hiddens=128)
model = RNNLMScratch(rnn, vocab_size=len(data.vocab), lr=4, dropout=0.5,
emb_dropout=0.1)We train this wider regularized model for 10 epochs using the same learning
rate lr=4 and clipping threshold gradient_clip_val=1.
trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)From the final validation loss we compute both the validation perplexity
ppl_scratch and the corresponding compression rate in bits per byte.
ppl_scratch = math.exp(trainer.history['val_loss'][-1])
print(f'validation perplexity {ppl_scratch:.1f}, '
f'{math.log2(ppl_scratch) / bytes_per_token:.2f} bits per byte')validation perplexity 60.3, 2.13 bits per byte
Validation perplexity drops from 85–100 down to around 60, cutting bits per byte from 2.3–2.4 to roughly 2.1.
8.4.4.3 Comparison with Kneser–Ney and Effective Context Horizon#
How does 2.1 bits per byte compare against interpolated Kneser--Ney smoothing
(Section 8.3.2.3)? The bits per byte that the Kneser--Ney
trigram reached in Section 8.3 cannot serve as the yardstick:
that number was measured on lowercased text stripped to letters and spaces,
whereas this section models the raw novella with its capitals, punctuation,
and line breaks. We therefore fit Kneser--Ney -grams
() on the exact same 50,000 BPE training tokens and evaluate them
on val[32:], where each token is scored as the final target of its 32-token
validation window.
first_tokens = d2l.numpy(data.X[:, 0]).tolist() # First token of each window
train = first_tokens[:data.num_train]
val = first_tokens[data.num_train:data.num_train + data.num_val]
lp_kns = {n: d2l.kneser_ney(train, val, len(data.vocab), n)[32:]
for n in (2, 3, 4)}
for n, lp in lp_kns.items():
bits = -sum(lp) / len(lp) / math.log(2)
print(f'KN {n}-gram: {bits / bytes_per_token:.2f} bits per byte')
lp_kn = lp_kns[3]
KN 2-gram: 2.24 bits per byte
KN 3-gram: 2.09 bits per byte
KN 4-gram: 2.08 bits per byte
To score our trained RNN on the exact same held-out tokens val[32:], we
select the slice [start:stop] of validation windows whose final target covers
val[32:].
start, stop = data.num_train, data.num_train + data.num_val - 32 # val[32:]
Running model in evaluation mode over data.X[start:stop] in batches of
1,024 windows collects the matrix logp of per-position target
log-probabilities across all 32 window steps.
model.eval()
with torch.inference_mode(): # Log-probability of every target
logp = d2l.numpy(torch.cat([
F.log_softmax(model(X.to(d2l.try_gpu())), -1).gather(
-1, Y.to(d2l.try_gpu())[..., None])[..., 0]
for X, Y in zip(data.X[start:stop].split(1024),
data.Y[start:stop].split(1024))]))The RNN and the trigram arrive at nearly the same average. Do they also make
the same predictions? The last column of logp scores the same tokens
val[32:] as lp_kn, so we can compare the two models token by token. We
also score their equal mixture ,
the usual way of combining a neural language model with a count-based one
(Mikolov et al., 2011).
lp_rnn, lp_tri = logp[:, -1], np.array(lp_kn)
lp_mix = np.logaddexp(lp_rnn, lp_tri) + math.log(0.5) # 0.5 P_RNN + 0.5 P_KN
for name, lp in [('RNN', lp_rnn), ('KN trigram', lp_tri), ('mixture', lp_mix)]:
print(f'{name}: {-lp.mean() / math.log(2) / bytes_per_token:.2f} '
'bits per byte')
print(f'RNN more confident on {np.mean(lp_rnn > lp_tri):.0%} of the tokens')RNN: 2.12 bits per byte
KN trigram: 2.09 bits per byte
mixture: 2.03 bits per byte
RNN more confident on 50% of the tokens
The two models tie on average, but not token by token. The RNN assigns the higher probability on about half the tokens and the trigram on the other half, and the mixture lands about 0.06 bits per byte below the trigram, ahead of both of its members.
A mixture can gain only where its members disagree, so the two models have learned partly different things about the text. That makes the tie more puzzling, not less. Why does a recurrent network reading 32 tokens of history land near the same bits per byte as a Kneser--Ney trigram that looks back only two tokens? To see how much context the trained RNN actually uses, we plot its average validation bits per byte at each window position against the Kneser--Ney trigram baseline.
bits = -logp.mean(0) / math.log(2) / bytes_per_token # One per position
kn_bits = -sum(lp_kn) / len(lp_kn) / math.log(2) / bytes_per_token
positions = np.arange(1, data.num_steps + 1)
d2l.plot(positions, [bits, [kn_bits] * data.num_steps],
'tokens of context', 'bits per byte', legend=['RNN', 'KN trigram'],
figsize=(4.5, 3))
print('bits per byte with 1, 2, 3, 4, 8, 32 tokens of context:',
[round(float(bits[k - 1]), 2) for k in (1, 2, 3, 4, 8, 32)])bits per byte with 1, 2, 3, 4, 8, 32 tokens of context: [2.3, 2.15, 2.13, 2.12, 2.12, 2.12]
The diagnostic curve explains the tie. Almost all of the gain arrives with the second token of context, which lowers the loss by about 0.15, from about 2.3 to about 2.14 bits per byte. The third token adds a hundredth or two, and from position 4 through 32 the curve is flat. Although the hidden state can depend on all 32 tokens in the forward pass, the trained model exploits only the last two or three.
Why so few? One explanation is optimization: the gradient that would teach the cell to use a distant token shrinks at every step on its way back, as we measure in Section 8.5. The other is data: 50,000 training tokens may hold little that can be learned about a token from those more than two or three positions before it. The Kneser--Ney models printed above speak for the second explanation. They are fit by counting, with no gradient that could vanish, and they saturate at the same place: the trigram improves on the bigram by 0.15 bits per byte, and the 4-gram improves on the trigram by only 0.01. Our experiment cannot tell the two explanations apart. A clean test needs a model whose gradients survive over long lags, trained on the same tokens, and Chapter 12 builds such models.
8.4.5 Text Generation#
Once trained, our language model generates text autoregressively via predict:
it first warms up the hidden state on the user's prefix tokens, then generates
num_tokens continuation tokens by feeding each chosen token back in as the
next input (using greedy argmax when temperature=0.0, or sampling from the
temperature-scaled softmax otherwise; see Section 8.6).
@d2l.add_to_class(RNNLMScratch)
@torch.inference_mode() # Generation needs no autograd graph
def predict(self, prefix, num_tokens, tok, device=None, temperature=0.0):
outputs, state = tok.encode(prefix), None
for i in range(len(outputs) - 1): # Warm up on the prefix
X = d2l.tensor([[outputs[i]]], device=device)
_, state = self.rnn(self.embedding(X), state)
for _ in range(num_tokens): # Generate num_tokens continuation tokens
X = d2l.tensor([[outputs[-1]]], device=device)
rnn_outputs, state = self.rnn(self.embedding(X), state)
logits = self.output_layer(rnn_outputs)[0, 0]
if temperature == 0: # Greedy: the highest-scoring token
token = logits.argmax()
else: # Sample from the softmax of logits / temperature
token = torch.distributions.Categorical(
logits=logits / temperature).sample()
outputs.append(int(token))
return tok.decode(outputs)Let us test model.predict with greedy decoding (temperature=0.0) by
generating a 50-token continuation from the prompt 'The Time Traveller'.
d2l.print_wrapped(repr(model.predict('The Time Traveller', 50,
data.tokenizer, d2l.try_gpu())))'The Time Traveller,\nthe\nfrom the\nfound,\ntheir\nfound,\ntheir\nfound,\nt
heir\nfound,\ntheir\nfound,\ntheir\nfound,\ntheir\n'
Because greedy decoding is deterministic, once the hidden state revisits a recent phrase it cycles through that loop indefinitely—a failure mode we study and fix in Section 8.6.
8.4.6 Concise Implementation#
Framework-supplied recurrent layers fuse the recurrent step and time loop into
optimized low-level kernels. The RNN module below matches the interface and
initialization of RNNScratch, and RNNLM subclasses RNNLMScratch by
swapping in built-in embedding and linear layers.
nn.RNN keeps two bias vectors, one for the input term and one for the
recurrent term. Their sum plays the role of , and
both start at zero.
class RNN(d2l.Module):
"""The RNN model implemented with high-level APIs."""
def __init__(self, num_inputs, num_hiddens, sigma=0.01):
super().__init__()
self.save_hyperparameters()
self.rnn = nn.RNN(num_inputs, num_hiddens)
for name, param in self.rnn.named_parameters():
if name.startswith('weight'):
nn.init.normal_(param, std=sigma)
else: # Both bias vectors start at zero
nn.init.zeros_(param)
def forward(self, inputs, H=None):
return self.rnn(inputs, H)nn.Embedding draws its rows from by default; the
weights of nn.Linear are set explicitly.
class RNNLM(d2l.RNNLMScratch):
"""The RNN-based language model implemented with high-level APIs."""
def init_params(self):
self.emb = nn.Embedding(self.vocab_size, self.rnn.num_inputs)
self.linear = nn.Linear(self.rnn.num_hiddens, self.vocab_size)
nn.init.normal_(self.linear.weight, std=self.sigma)
nn.init.zeros_(self.linear.bias)
def embedding(self, X):
return self.emb(X.T)
def output_layer(self, hiddens):
return d2l.swapaxes(self.linear(hiddens), 0, 1)To verify our high-level implementation, we instantiate RNN and RNNLM with
the same hyperparameters (, , and dropout).
rnn = RNN(num_inputs=512, num_hiddens=128)
model = RNNLM(rnn, vocab_size=len(data.vocab), lr=4, dropout=0.5,
emb_dropout=0.1)We now train RNNLM for 10 epochs with gradient_clip_val=1, running the
fused recurrent kernel at a fraction of the from-scratch wall-clock time.
trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)Finally, we report the concise model's validation perplexity ppl_concise
alongside a 30-token greedy continuation from 'The Time Traveller'.
ppl_concise = math.exp(trainer.history['val_loss'][-1])
pred = model.predict('The Time Traveller', 30, data.tokenizer, d2l.try_gpu())
d2l.print_wrapped(f'perplexity {ppl_concise:.1f}, {pred!r}')perplexity 59.6, "The Time Traveller.\n\n'I
had\nfossibly\nthere\nfoundly\nfossibly\nthere\nf"
8.4.7 Summary#
A recurrent neural network updates a fixed-size hidden state from the current input and previous state using weights shared across all time steps, achieving constant memory and compute per step at the cost of compressing history into a lossy state vector. An RNN language model pairs an embedding table, a recurrent cell, and a vocabulary-sized output projection (where 89% of our baseline's parameters reside), trained by teacher forcing to minimize per-token cross-entropy. Global gradient clipping ((8.4.4)) prevents exploding gradient spikes from derailing training at high learning rates. On The Time Machine, a wider embedding with dropout brings the SGD-trained RNN to bits per byte, tying an interpolated Kneser--Ney trigram: the trained vanilla RNN effectively exploits only the last two or three tokens of context. Section 8.5 measures how far its gradients reach.
8.4.8 Exercises#
-
Separating the input product. Let and be the input and the state in (8.4.3).
- During training, the inputs of a window are all known before the first time step is computed. Which of the two products and can be computed for all steps in a single matrix multiplication, and what are the shapes of its factors? Which product must stay inside the sequential loop over time steps, and why?
- Compare the work per step left inside the loop with the work per step of the concatenated form . During generation, the input at step is the token generated at step . Does the advantage of the separate form survive there?
-
Exposure bias. Teacher forcing (Section 8.4.1.2) conditions every training step on the true prefix, whereas generation conditions each step on the model's own earlier outputs. The resulting mismatch is called exposure bias (Ranzato et al., 2016).
- Suppose generation samples each token from the model's next-token distribution, and the model assigns probability to the correct next token whenever its prefix is correct. What is the probability that generated tokens contain no error? Evaluate it for and .
- Scheduled sampling (Bengio et al., 2015) exposes the model to its own outputs during training: at each step, with some probability, the input is a token sampled from the model's prediction at the previous step instead of the true token. Which property of teacher forcing that Section 8.4.1.2 relies on does this give up, and how does that change the computation of a training window?
-
A window inside a recurrence. The neural -gram reads a fixed window of the last input embeddings. Take to be the identity and in (8.4.3), and give the state units.
- Choose and so that, starting from , the state is the concatenation for every .
- Show that , and explain why this means that no input older than steps affects .
- For and , how many state units does this construction need? Explain what an RNN whose state has only 256 units must do instead of storing the window.
-
[code] Embedding lookup as a product. Let be an embedding table, and let hold the token ids of a minibatch of tokens.
- Compute the inputs once by selecting the rows of that indexes and once as the product of the one-hot matrix of with , and check that the two agree. Time both for with , and state how the running time of each grows with .
- Differentiate the sum of all entries of the selected rows with respect to by automatic differentiation. Which rows of the gradient are nonzero, and what does a row contain when its token occurs several times in the minibatch? For and ids drawn uniformly at random, estimate the fraction of rows that receive a nonzero gradient.
-
Parity beyond any window. ● Let be a sequence of bits, and let the desired output at step be the parity of .
- Show that no model that reads only the last inputs can produce the correct output at every step of a sequence longer than , whatever the finite .
- Let be a threshold activation. Construct an RNN of the form (8.4.3) with two hidden units whose output equals the parity at every step, for any sequence length. Give the weights, and show that one hidden unit does not suffice.
- How many bits of information about must the hidden state retain for the outputs at all later steps to be correct? Relate this to the description of the state as a lossy fixed-size summary in Section 8.4.1.1.
-
[code] Gradient clipping ablation.
d2l.Trainerapplies the projection (8.4.4) whenevergradient_clip_valis positive.- Record the norm of the gradient before clipping at every update of the first epoch, and plot it. How often does clipping act, and when?
- Most unclipped runs of this section jumped at
lr=4. Halve the learning rate until three unclipped runs in a row train without a jump in the validation perplexity. How does their validation perplexity after ten epochs compare with that of the clipped run atlr=4? What, then, does clipping make possible? - Replace by ReLU in
RNNScratchand train again, with and without clipping. Is clipping still needed? Explain the difference from the cell in terms of the range of the hidden state.
-
[code] Usable history. Every training window starts from a zero state, so the model is never trained to use more than
num_stepstokens of context, and the loss by position showed that it uses far fewer.predict, by contrast, carries the state across the whole prefix and every generated token. Evaluate the trained model on 512 consecutive validation tokens in two ways: resetting the state to zero every 32 tokens as in training, and carrying the state across all 512 tokens. Compare the average cross-entropy of the two. Does the carried state help, hurt, or make no difference, and what does the answer say about the states the model reaches beyond its training horizon? -
[code] Adam. Train the model with the wider embedding with the Adam optimizer of Section 9.5 instead of SGD: subclass
RNNLMScratch, overrideconfigure_optimizersto return Adam with learning rate 0.003, and keep clipping at 1.- With
emb_dropout=0.2, score the tokensval[32:]as in the comparison above, and compare its bits per byte with the SGD model, the Kneser–Ney trigram and 4-gram, and the mixture of the RNN and the trigram at . - Record the validation loss after every epoch, with
emb_dropout=0.1and with 0.2. At which epoch is it lowest, and what happens after that? - Measure again how far the embedding rows move during training. Why does Adam move them further than SGD does?
- With
-
[code] Vocabulary size and bits per byte. ● Retrain the model with the wider embedding for
vocab_size512, 1,024, 2,048, and 4,096 ind2l.TimeMachine. The number of windows depends on the vocabulary size, so split by fraction: build each dataset once to read offn = len(data.X), then build it again withnum_train=int(0.8 * n)andnum_val=n - int(0.8 * n). (Settingdata.num_trainafterwards would skip the step that keeps validation tokens out of the training targets.) Every model then trains and validates on about the same stretch of text. Their per-token perplexities are not comparable, so compare them by bits per byte.- Which vocabulary size gives the lowest bits per byte?
- How do the parameter counts of the embedding table and the output layer, and the length of the corpus in tokens, change with the vocabulary size? Which of these effects best explains the trend you measured?
-
[code] Cross-book generalization. ● Subclass
d2l.TimeMachineand override_downloadto return the text of a different H. G. Wells novel, such as The War of the Worlds (Project Gutenberg ebook 36). Train the tokenizer and the model on it.- Evaluate the model on held-out text of its own novel and on The Time Machine, encoding both with the new novel's tokenizer. Report perplexity and bits per byte for both.
- Write for the per-token surprisal and for the bytes per token of an evaluated text, so that bits per byte is . The ratio of bits per byte on The Time Machine (TM) to bits per byte on the held-out text of the new novel (own) factors as
The first factor reflects the model's predictions and the second the tokenizer's compression. Measure both factors. Which lies further from one?