from d2l import jax as d2l
import jax
from jax import numpy as jnpA 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([[ 7.8358064 , -1.1775837 , -1.4894798 , -3.3220472 ],
[ 6.549281 , 1.0249726 , 0.38784432, -2.247775 ],
[ 3.1509278 , 0.7940084 , -1.0252644 , 0.93234503]], dtype=float32)
Equivalently, concatenate input and hidden and multiply by the concatenated weight matrix. Same result, one matmul:
Array([[ 7.8358064 , -1.1775837 , -1.4894797 , -3.322047 ],
[ 6.549281 , 1.0249726 , 0.38784423, -2.247775 ],
[ 3.1509278 , 0.7940084 , -1.0252644 , 0.9323451 ]], dtype=float32)
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.