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 → constant parameter count regardless of sequence length. Unbounded effective context (in principle), no fixed-size window like n-grams.
An RNN with a hidden state.
The naive form: two matrix multiplies, summed:
tensor([[-5.8173, -2.5874, 0.1608, -1.1563],
[-0.2778, 0.2293, -3.7569, -2.0525],
[ 0.7006, -0.6336, -1.7256, -0.7766]])
Equivalently — concatenate input and hidden, multiply by the concatenated weight matrix — same result, one matmul:
tensor([[-5.8173, -2.5874, 0.1608, -1.1563],
[-0.2778, 0.2293, -3.7569, -2.0525],
[ 0.7006, -0.6336, -1.7256, -0.7766]])
The “concat then multiply” form is what most framework RNN implementations actually do.
Input “machin”, target “achine” — same RNN, target shifted by one.
The next two sections build this end-to-end (from scratch + concise).