Linear parameter growth & hard cutoff: Concatenating m embeddings of width d adds d \times h weights per lag (+8{,}192 at d=64, h=128) while remaining blind to token t - m - 1.
Shared-weight recurrent state: An RNN compresses the prefix into a fixed-size vector \mathbf{h}_t \in \mathbb{R}^h updated with shared weights at every step—keeping parameter count and per-step compute O(1) at any length T.
Five shared parameter tensors:(\mathbf{W}_{\textrm{xh}}, \mathbf{W}_{\textrm{hh}}, \mathbf{b}_{\textrm{h}}, \mathbf{W}_{\textrm{hq}}, \mathbf{b}_{\textrm{q}}) are reused at every time step starting from \mathbf{H}_0 = \mathbf{0}.
Unrolling an RNN Across Time with Shared Weights
Temporal Unrolling & State Persistence
Unrolled across T time steps, an RNN is a T-layer deep feedforward network where every layer shares identical weights (\mathbf{W}_{\textrm{xh}}, \mathbf{W}_{\textrm{hh}}, \mathbf{b}_{\textrm{h}}):
Recurrent memory persistence: Even after input returns to 0, the initial impulse persists across time, decaying at a rate governed by \mathbf{W}_{\textrm{hh}}.
Why keep the two products separate: During teacher-forced training, all T window inputs \mathbf{X}_1, \ldots, \mathbf{X}_T are known up front.
Hoisting \mathbf{X}_{1:T}\mathbf{W}_{\textrm{xh}} out of the loop: Frameworks batch all T input projections into one (Tb \times d) \times (d \times h) GPU GEMM, leaving only \mathbf{H}_{t-1}\mathbf{W}_{\textrm{hh}} inside the sequential loop over t.
Expressive Power and the 512-Byte State Bottleneck
Theoretical Power vs. Systems Bottleneck
Replacing a finite window with a recursive hidden state creates a fundamental trade-off between unbounded horizon reach and finite state bandwidth:
Tasks impossible for any finite window m (Parity): Suppose a model must output at every step t whether the running sum of bits x_1 + \cdots + x_t is even or odd. Flipping bit x_{t-m} flips the true parity at step t without altering the last m bits (x_{t-m+1}, \ldots, x_t), so everym-window model fails on sequences of length T > m. A 2-unit threshold RNN solves parity for arbitrary T.
Constant 512-byte memory footprint: Because \mathbf{H}_t depends only on (\mathbf{H}_{t-1}, \mathbf{X}_t), older activations can be discarded during inference. With h = 128float32 units, the entire state of a sequence occupies 128 \times 4 = 512 bytes whether the prefix has 10 tokens or 10^6 tokens.
The lossy compression bottleneck: Every detail remembered from the entire past must squeeze through those 512 bytes—recording new information inevitably overwrites older state dimensions (unlike attention, whose KV cache grows as O(T)).
RNN Language Model Architecture & Teacher Forcing
End-to-End Language Model Pipeline
An RNN language model wraps the recurrent cell between an input embedding table \mathbf{E} \in \mathbb{R}^{|\mathcal{V}| \times d} and a vocabulary-sized output layer (\mathbf{W}_{\textrm{hq}}, \mathbf{b}_{\textrm{q}}):
Step-by-step forward pipeline:
Embedding lookup: Token IDs \mathbf{x}_t \in \{0, \ldots, |\mathcal{V}|-1\}^b select rows \mathbf{X}_t = \mathbf{E}[\mathbf{x}_t] \in \mathbb{R}^{b \times d} (equivalent to one-hot multiplication \textrm{one\_hot}(\mathbf{x}_t)\mathbf{E} in O(1) without multiplying zeros).
Teacher forcing: During training, step t always receives the ground-truth tokenx_t from the corpus, allowing all T cross-entropy losses in a window to be evaluated in one pass.
Where Do the Parameters and FLOPs Actually Live?
Parameter & Compute Accounting
Baseline model (|\mathcal{V}| = 1{,}027, d = 64, h = 128): Total 222{,}915 parameters and 156{,}032 multiply-adds (MACs) per token.
The recurrent cell is tiny (11.1\% params):\mathbf{W}_{\textrm{xh}}(8{,}192) and \mathbf{W}_{\textrm{hh}} + \mathbf{b}_{\textrm{h}}(16{,}512) account for just 24{,}704 parameters and 15.8\% of the compute.
Vocabulary layers dominate (88.9\% params): Embedding \mathbf{E}(65{,}728 params, O(1) gather) and output projection \mathbf{W}_{\textrm{hq}} + \mathbf{b}_{\textrm{q}}(132{,}483 params, 84.2\% of FLOPs) dominate the budget.
Implementing the Recurrent Cell from Scratch
From-Scratch Implementation
RNNScratch initializes \mathbf{W}_{\textrm{xh}}, \mathbf{W}_{\textrm{hh}} \sim \mathcal{N}(0, \sigma^2) with \sigma = 0.01 (so initial spectral radius \rho(\mathbf{W}_{\textrm{hh}}) \approx \sigma\sqrt{h} \approx 0.11, ensuring stable initial decay) and loops over the leading time axis of inputs of shape (num_steps, batch_size, num_inputs):
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))
Implementing the Recurrent Cell from Scratch (cont.)
From-Scratch Implementation
def forward(self, inputs, state=None):if state isNone:# 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, state
Embedding Lookup and Batched Output Projection
From-Scratch Language Model Wrapper
RNNLMScratch transposes batch-major token IDs X of shape (b, T) to time-major (T, b) before indexing self.E(\mathcal{N}(0, 1)), runs self.rnn, and projects all stacked hidden states (b, T, h) to logits (b, T, |V|) in one batched matrix product:
Embedding Lookup and Batched Output Projection (cont.)
From-Scratch Language Model Wrapper
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_qdef 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)returnself.output_layer(F.dropout(H, self.dropout, self.training))
Sanity-Checking Initial Perplexity: Because \mathbf{W}_{\textrm{hq}} \sim \mathcal{N}(0, 0.01^2) and \mathbf{b}_{\textrm{q}} = \mathbf{0}, an untrained model outputs near-zero logits, yielding uniform probabilities 1/|\mathcal{V}|, cross-entropy \approx \log(1{,}027) = 6.93 nats, and initial perplexity \approx 1{,}027.
Global Gradient Norm Clipping Stabilizes Updates
Optimization Safeguard
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 hostfor param in params: param.grad.mul_(scale)
Radial ball projection: Caps the global Euclidean gradient norm \|\mathbf{g}\| at \theta without distorting the update direction, preventing rare Jacobian spikes from catapulting weights out of the basin.
Training the Plain RNN Baseline with Clipping
Baseline Training & Bits-per-Byte Evaluation
We train the 222,915-parameter baseline (d = 64, h = 128, no dropout) on 50{,}000 overlapping 32-token windows (batch_size = 1024) for 10 epochs of SGD at \eta = 4 with global gradient clipping at \theta = 1:
validation perplexity 88.0
2.78 bytes/token, 2.32 bits per byte
Truncated window states: Each 32-token window initializes \mathbf{H}_0 = \mathbf{0}, capping backpropagation at 32 steps.
Convergence: Validation perplexity drops from 1{,}027 to about 85–100 after a bumpy first epoch; a perplexity of 95 corresponds to \log_2(95) / 2.78 \approx 2.36 bits per byte (while training loss drops faster as the 223k parameters overfit the 50k tokens).
initial validation perplexity 1027
Ablation: Catastrophic Instability Without Clipping
Why Gradient Clipping Is Essential
To isolate the effect of gradient clipping, we train three fresh unclipped instances of the exact same model at \eta = 4 and plot their validation perplexity trajectories against the clipped baseline:
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
Violent spikes: Without \theta = 1 clipping, exploding gradient steps hurl the parameters out of the basin, in some runs spiking validation perplexity far past the untrained level of 1{,}027.
Unreliable final convergence: Most unclipped runs at \eta = 4 finish above twice the clipped model’s perplexity.
Why Sparse Embedding Rows Barely Move Under SGD
Diagnosing the SGD Embedding Bottleneck
Measuring the relative Euclidean distance \|\mathbf{E}_{i,\textrm{final}} - \mathbf{E}_{i,\textrm{init}}\| / \|\mathbf{E}_{i,\textrm{init}}\| across all 1,027 rows of \mathbf{E} after 10 epochs of SGD exposes a striking optimization bottleneck:
mean change of an embedding row: 4.3% of its length
Sparse vs. dense gradient accumulation: Dense weights (\mathbf{W}_{\textrm{xh}}, \mathbf{W}_{\textrm{hh}}, \mathbf{W}_{\textrm{hq}}) accumulate gradient contributions from all b \times T = 1{,}024 \times 32 = 32{,}768 token positions in a minibatch, whereas embedding row \mathbf{E}_i receives gradient only from the few positions where token i appears.
Why uniform-step SGD stalls on \mathbf{E}: Dividing by 32{,}768 leaves rare and medium-frequency token rows with tiny updates (the average row moves about 4\% of its length over 10 epochs), so \mathbf{E} acts largely as a frozen random projection (adaptive optimizers like Adam rescale per-coordinate variance to move \mathbf{E} rapidly).
SGD remedy: Widen the random embedding basis from d = 64 \to 512 so \mathbf{W}_{\textrm{xh}} has 8\times richer features to read, and add dropout (emb_dropout = 0.1,dropout = 0.5) to curb overfitting.
Wider Embeddings + Dropout Reach ~2.1 Bits/Byte
Regularized Wider Model
Training RNNLMScratch with d = 512, h = 128, emb_dropout = 0.1, and dropout = 0.5(740{,}355 parameters) under the exact same SGD schedule (\eta = 4, \theta = 1, 10 epochs) cuts validation perplexity by a third:
validation perplexity 60.3, 2.13 bits per byte
Overfitting suppressed: Unlike the unregularized d = 64 baseline, dropout keeps the training and validation curves close: after 10 epochs the losses differ by about 0.3 nats instead of about 1.
Validation improvement: Validation perplexity falls from 85\text{--}100 to \sim 60, reducing bits per byte from 2.3\text{--}2.4 to \mathbf{\approx 2.1\text{ bpb}}.
Benchmarking the RNN Against Kneser–Ney n-Grams
Neural vs. Classical Count Baselines
How does our trained RNN (\approx 2.1 bpb) compare against interpolated Kneser–Ney n-grams (n = 2, 3, 4) trained on the exact same 50,000 BPE tokens and evaluated on val[32:]?
KN 2-gram: 2.24 bits per byte
KN 3-gram: 2.09 bits per byte
KN 4-gram: 2.08 bits per byte
A virtual tie at \approx 2.1 bpb: The 32-token-window RNN lands right alongside the Kneser–Ney trigram (2.09 bpb) and 4-gram (2.08 bpb) that look back only 2 or 3 tokens.
Complementary errors (Mikolov et al., 2011): Even at nearly equal overall bpb, the RNN (continuous semantic representations) and Kneser–Ney (exact lexical specificity) each beat the other on \approx 50\% of validation tokens; a 50/50 mixture 0.5\,P_{\textrm{RNN}} + 0.5\,P_{\textrm{KN}} improves over the standalone trigram by \approx 0.06 bpb.
Diagnosing the RNN’s Effective Context Horizon
Why the RNN Tied the Trigram
To uncover why a recurrent network fed 32 tokens of history failed to pull ahead of a 3-gram, we plot validation bits per byte separately at each window position k \in \{1, \ldots, 32\} (where position k conditions on k tokens of context):
Sharp drop from k = 1 \to 2, then flat: Validation loss drops from \approx 2.3 bpb at 1 token of context to \approx 2.14 bpb at 2 tokens, gains another 0.01–0.02 at 3, and then stays flat at \approx 2.12 bpb from position 4 through position 32.
Two candidate causes, not separated here:Optimization: gradients fade with every step back (§8.5); data: Kneser–Ney counts, which use no gradients, saturate at the same place (2.24 \to 2.09 \to 2.08 bpb for n = 2, 3, 4), so 50,000 tokens may hold little longer-range signal.
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]
Autoregressive Text Generation and Greedy Loops
Inference & Rollout Behavior
The predict method first runs a prefix warm-up loop feeding the user’s prompt tokens one by one to build \mathbf{H}_t, and then runs an autoregressive generation loop feeding each newly chosen token back in as the next step’s input:
@torch.inference_mode() # Generation needs no autograd graphdef predict(self, prefix, num_tokens, tok, device=None, temperature=0.0): outputs, state = tok.encode(prefix), Nonefor i inrange(len(outputs) -1): # Warm up on the prefix X = d2l.tensor([[outputs[i]]], device=device) _, state =self.rnn(self.embedding(X), state)for _ inrange(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)
Autoregressive Text Generation and Greedy Loops (cont.)
Inference & Rollout Behavior
'The Time Traveller,\nthe\nfrom the\nfound,\ntheir\nfound,\ntheir\nfound,\nt
heir\nfound,\ntheir\nfound,\ntheir\nfound,\ntheir\n'
Why Greedy Decoding (temperature=0.0) Loops: Because both the recurrent update and \operatorname*{argmax}_i o_i are deterministic functions, once the hidden state \mathbf{H}_t revisits a state near an earlier phrase, the trajectory locks into an infinite periodic cycle (§8.6).
Concise Implementation with Framework RNN Kernels
High-Level Framework APIs
The framework’s built-in RNN layer replaces our Python for X in inputs: loop with a fused kernel:
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 inself.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):returnself.rnn(inputs, H)
Concise Implementation with Framework RNN Kernels (cont.)
High-Level Framework APIs
RNNLM swaps in the built-in embedding and dense layers:
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):returnself.emb(X.T)def output_layer(self, hiddens):return d2l.swapaxes(self.linear(hiddens), 0, 1)
Verifying Concise RNNLM Training & Perplexity
Equivalence & Speedup
Matching the weight initializations (\mathcal{N}(0, 0.01^2) for cell and output weights, \mathcal{N}(0, 1) for embeddings) reproduces the validation perplexity (\sim 60) and the looping greedy rollout at a fraction of the Python loop runtime:
perplexity 59.6, "The Time Traveller.\n\n'I
had\nfossibly\nthere\nfoundly\nfossibly\nthere\nf"
Concept Check: Shapes, Scaling & Context Horizon
Check Your Understanding
Test your grasp of RNN parameter scaling, batched projections, and model ensembling:
Doubling Hidden State Dimension (h: 128 \to 256): If we double h from 128 to 256 while keeping d = 64 and |\mathcal{V}| = 1{,}027, by what exact factor (1\times, 2\times, 4\times) do the parameter counts of (a) \mathbf{E}, (b) \mathbf{W}_{\textrm{xh}} and \mathbf{W}_{\textrm{hq}}, and (c) \mathbf{W}_{\textrm{hh}} scale?
Batched Input Projection at Training vs. Inference: During teacher-forced training on a window of T = 32 steps, we can compute \mathbf{X}_{1:T}\mathbf{W}_{\textrm{xh}} for all 32 steps in a single matrix product before the time loop. Why does this optimization not apply during 32 steps of autoregressive text generation?
Why a 50/50 Probability Mixture Bounds Surprisal: Suppose on token A, P_{\textrm{RNN}}(A) = 0.50 and P_{\textrm{KN}}(A) = 0.02, while on token B, P_{\textrm{RNN}}(B) = 0.02 and P_{\textrm{KN}}(B) = 0.50. Compare the total bits of surprisal -\log_2 P(A) - \log_2 P(B) of each standalone model against their linear mixture P_{\textrm{mix}} = \frac{1}{2}P_{\textrm{RNN}} + \frac{1}{2}P_{\textrm{KN}}.
(a) 1\times(\mathbf{E} \in \mathbb{R}^{|\mathcal{V}| \times d} is independent of h); (b) 2\times(\mathbf{W}_{\textrm{xh}} \in \mathbb{R}^{d \times h} and \mathbf{W}_{\textrm{hq}} \in \mathbb{R}^{h \times |\mathcal{V}|} scale linearly with h); (c) 4\times(\mathbf{W}_{\textrm{hh}} \in \mathbb{R}^{h \times h} scales quadratically as h^2: 16{,}384 \to 65{,}536).
Sequential causal dependency: During generation, input token x_{t+1} is not known until step t finishes computing \mathbf{H}_t, projecting \mathbf{O}_t, and sampling x_{t+1}.
Standalone:-\log_2(0.50) - \log_2(0.02) \approx 1.00 + 5.64 = 6.64\text{ bits} for each model. Mixture:P_{\textrm{mix}}(A) = P_{\textrm{mix}}(B) = 0.26, costing 2 \times (-\log_2 0.26) \approx 3.89\text{ bits}(2.75 bits saved, because \frac{1}{2}(p+q) \ge \frac{1}{2}\max(p,q) never pays more than 1 bit over the better expert).