from d2l import mxnet as d2l
from mxnet import np, npx
npx.set_np()A 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:
array([[-1.9775 , 2.469915 , -1.9954803 , 2.660422 ],
[ 1.6884806 , -0.6927535 , 0.9205742 , -1.7811027 ],
[-2.8398926 , 3.1179144 , 0.05061442, 2.2148812 ]])
Equivalently, concatenate input and hidden and multiply by the concatenated weight matrix. Same result, one matmul:
array([[-1.9775 , 2.469915 , -1.9954802 , 2.660422 ],
[ 1.6884806 , -0.69275343, 0.92057407, -1.7811027 ],
[-2.8398924 , 3.1179144 , 0.05061439, 2.2148812 ]])
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.