from d2l import torch as d2l
import torchA recurrent neural network carries a hidden state \mathbf{h}_t across time steps, a learned summary of all input seen so far:
\mathbf{h}_t = \phi(\mathbf{W}_{xh}\mathbf{x}_t + \mathbf{W}_{hh}\mathbf{h}_{t-1} + \mathbf{b}).
Same weights at every step, so the parameter count is constant regardless of sequence length. Unbounded effective context (in principle), with no fixed-size window like an n-gram.
An RNN unrolled across three time steps; the same weights are reused at every step.
The naive form: two matrix multiplies, summed:
tensor([[-0.4572, 1.4166, -2.1468, 2.9581],
[ 1.5332, -0.2667, -0.5472, 1.0990],
[-1.2867, -3.9960, 3.3861, -2.9322]])
Equivalently, concatenate input and hidden and multiply by the concatenated weight matrix. Same result, one matmul:
tensor([[-0.4572, 1.4166, -2.1468, 2.9581],
[ 1.5332, -0.2667, -0.5472, 1.0990],
[-1.2867, -3.9960, 3.3861, -2.9322]])
The concatenate-then-multiply form is what most framework RNN implementations actually do.
Targets are the inputs shifted forward by one token; each step predicts the next token.
Train on gold prefixes; generate on the model’s own outputs. That mismatch is the rollout-error problem again.