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.5367, -0.1777, 2.4283, -0.5488],
[ 5.6435, -1.8725, 2.6781, 0.3557],
[ 3.8535, -1.2030, 3.6370, -1.0466]])
Equivalently, concatenate input and hidden and multiply by the concatenated weight matrix. Same result, one matmul:
tensor([[-0.5367, -0.1777, 2.4283, -0.5488],
[ 5.6435, -1.8725, 2.6781, 0.3557],
[ 3.8535, -1.2030, 3.6370, -1.0466]])
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.