Lesson 4.1 — Recurrent Neural Networks
Previous lesson · 3.4 Self-supervised & Contrastive Learning · Course contents · Next lesson · 4.2 Attention Mechanisms
Sequence Representation · Time and Batch Axes
The MLPs and CNNs in Chapters 1–3 mainly process individual examples. Sequence models also represent time or order, as in sensor histories, language tokens, and trajectories. Two histories can produce the same current observation, so accurate prediction may require earlier inputs.
In batch-first notation, B counts independent sequences, T is the sequence length, and D is the number of features per step. PyTorch’s nn.RNN, nn.LSTM, and nn.GRU default to batch_first=False and take input of shape (T, B, D). With batch_first=True, the input has shape (B, T, D) and the sequence output has shape (B, T, directions × H). The final hidden state always has shape (layers × directions, B, H), with H the hidden width per direction. For an LSTM without a projection, the final cell state has the same shape. The cell API takes a single input step of shape (B, D) and a hidden state of shape (B, H). LSTMCell also takes a cell state of shape (B, H).
Inspect a time slice across a batch
Sequence Tensor Inspector
Recurrent Computation · Hidden State & Shared Weights

Follow step 2 from the left plot to the right. Both current inputs are zero, yet the states still have opposite signs. This example starts at and uses the scalar update . Each quiet step carries forward seven tenths of the previous state. At step , the first pulse still contributes . The distance between the two traces measures how much the model can still distinguish the histories.
A learned recurrent cell can maintain several such distinctions. Unrolling it draws one copy of the computation per time step. Changing a weight changes the update at every step, which is why training adds gradient contributions from every use of that weight.
At each step, the recurrent network reads the current input and the previous hidden state. The same parameters update the state at every step. The hidden state h is a learned internal representation and need not correspond to a physical state or a Kalman filter posterior estimate.
The equations use column vectors. With examples stored as rows, the input projection is x @ W_x.T. The initial state can be zero, a learned parameter, or the final state of the preceding segment of a continuous trajectory. Reset the state between independent sequences to prevent information leakage. The player below unrolls a single hidden unit.
RNN Time-unrolling Player
The player uses t = 1 for the first update and h₀ for the initial state. The tensor slicing lab uses zero-based array indices. Sharing the weights keeps the parameter count independent of T. Standard backpropagation through the fully unrolled network stores intermediate states at each step.
RNN Architecture · Memory & Output Patterns
Many-to-one
The final hidden state summarizes the sequence for a single prediction. For example, the history of control inputs can be used to predict the final position.
Many-to-many
The network produces one output per time step, as in state prediction throughout a trajectory. A single output head can be shared across steps.
Encoder–decoder
An encoded state or context carries information from the input sequence to the decoder. The input and output sequences can have different lengths.
The scalar linear recurrence h_t = w h_{t-1} + u x_t is a first-order discrete-time system. With zero input, powers of w govern the remaining influence of the initial state. The zero state is asymptotically stable when |w| < 1. In a tanh RNN, local derivatives depend on the trajectory, and saturation bounds the activation while reducing its derivative.
Hidden State Memory Explorer
A negative recurrent weight alternates the sign of the initial state’s contribution in the linear recurrence. A nonzero initial state can diverge with zero input when |w| > 1. Tanh bounds the nonlinear hidden state. Pole analysis applies directly to linear systems and local linearizations.
BPTT · Backward Through the Time Axis
Unrolling an RNN exposes a computation graph whose time steps share parameters. For a squared-error loss applied at the final step, define δ_t = ∂L/∂a_t. The terminal loss propagates backward through the hidden states. Sum the contributions from every step to find the gradient of each shared parameter.
With supervision at the last step, the direct output gradients vanish at earlier steps. This lab uses y = h_T as its prediction and L = ½(h_T − target)² as its loss. With the hidden state serving directly as the output, the lab accumulates dw step by step and checks it with a centered finite difference.
Backpropagation Through Time
Truncated BPTT detaches the hidden state at fixed window boundaries. Forward computation still uses the carried state value, while gradients stop at each boundary. Shorter windows replace the full gradient with a truncated one and limit the memory and work per backward pass. Gradient clipping caps large gradients. Vanishing gradients require a different remedy.
h = h.detach() # truncate graph, preserve numerical state
# Do not detach at every step when learning long-term dependencies.
Long-term Dependencies · Jacobian Products
As in Lesson 2.3 on training stability, gradients pass through a product of Jacobians. For a tanh RNN, each factor combines the recurrent weights with the derivative of the current activation.
Return to the two pulse traces. In that linear example, nudging by a small amount moves the terminal state by times that amount. The same multiplier appears when a terminal loss sends a gradient back to the first pulse. In a tanh cell, each step has its own local multiplier. Their ordered product describes how a perturbation travels forward, and its transpose carries the loss gradient backward.
These equations assume supervision only at the final step. In a matrix recurrence, the product depends on the singular values and directions of its factors and how they vary across time. A single weight or eigenvalue only describes part of that behavior. The LSTM’s direct cell path has local multiplier f and can reduce decay. The full gradient also includes paths through the gates.
Long-term Dependency Simulator
log(0.5) / log(f) applies to the direct cell path with a constant forget gate satisfying 0 < f < 1.LSTM · Cell State & Three Gates
An LSTM adds a cell state c. The forget gate f controls retention, the input gate i controls the write, and the output gate o controls the exposed hidden state. The candidate cell content g uses tanh. PyTorch stores the parameters in i, f, g, o order, with separate biases for the input and recurrent transformations.
Recall the two pulse traces. Their separation shrank by a fixed factor on every quiet step. An LSTM can learn to treat a quiet interval differently from a new command. In one cell coordinate, a forget gate near one and an input gate near zero carry the stored value through a quiet step. At the next informative step the gates can admit a new write. The output gate separately controls how much of the stored value other computations can see.
The gates are H-dimensional vectors that act elementwise. Tanh and the output gate bound h, while c can grow across steps. Holding the other paths fixed, the derivative along the direct cell path is diag(f_t). A larger forget gate helps retain the cell state. Gradient stability also depends on the other paths.
LSTM Gate & Cell State
A standard single-layer LSTM without a projection has 4H(D + H + 2) parameters per direction, including two bias vectors of length 4H each. Count the output head separately.
GRU · Reset & Update Gates
A GRU keeps a single recurrent state. The reset gate r controls how the previous hidden state contributes to the candidate, and the update gate z sets the fraction of the previous state carried forward. PyTorch uses the reset-after convention, so the reset gate acts on the transformed previous hidden state. In general, the elementwise reset and the matrix multiplication cannot be interchanged.
GRU Gate Explorer
| Cell | Recurrent states | Cell parameters (two biases) |
|---|---|---|
| RNN | h | H(D+H+2) |
| LSTM | h,c | 4H(D+H+2) |
| GRU | h | 3H(D+H+2) |
The table counts PyTorch parameters for one layer and one direction without a projection. A bidirectional RNN uses future observations. Strictly causal online prediction requires an architecture that only reads the available history.
Engineering Experiment · Robot Dynamics with Hidden State
The synthetic system has two unobserved internal states, a and b. The model sees only the history of control inputs u and predicts the terminal output y_T. Each trajectory starts with a = b = 0. Controls are sampled uniformly from [−1, 1].
The experiment uses 32 training trajectories and 24 independently generated validation trajectories. The default configuration uses T = 12, H = 4, and 120 full-batch Adam updates at a learning rate of 0.025. The MLP baseline sees only the final input. The RNN, LSTM, and GRU see the full input sequence. The runs share the data, hidden width, optimizer, update budget, and random number generation scheme. Parameter counts and initialization shapes vary across architectures.
Train and Compare MLP, RNN, LSTM, and GRU
Results for the default settings
| Model | Parameters | Final training MSE | Final validation MSE |
|---|---|---|---|
| MLP | 13 | 0.094375 | 0.161051 |
| RNN | 33 | 0.001840 | 0.001939 |
| LSTM | 117 | 0.000217 | 0.000853 |
| GRU | 89 | 0.000448 | 0.001076 |
Reproducible PyTorch code
Save the script as rnn0401.py and run it with PyTorch installed. It uses nn.RNNCell, nn.LSTMCell, and nn.GRUCell to verify the browser implementation. Training uses float64 by default. Use the training button above to run the browser version with the selected settings, or change the arguments to run in the Python script.
import math
import torch
from torch import nn
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
class RNG:
def __init__(self, seed): self.s = seed & 0xffffffff
def __call__(self):
self.s = (1664525*self.s+1013904223)&0xffffffff
return self.s / 4294967296
def dataset(n,T,seed):
r=RNG(seed); X=[]; Y=[]
for _ in range(n):
a=b=0.; seq=[]
for t in range(T):
u=2*r()-1; seq.append([u])
a=.88*a+.3*u; b=.4*b+.2*u
X.append(seq); Y.append([a+.4*b+.1*u+.12*math.sin(2*a)])
return torch.tensor(X),torch.tensor(Y)
class Model(nn.Module):
def __init__(self,kind,H,seed):
super().__init__(); self.kind=kind; self.H=H
self.cell={'MLP':lambda:nn.Linear(1,H),'RNN':lambda:nn.RNNCell(1,H),'LSTM':lambda:nn.LSTMCell(1,H),'GRU':lambda:nn.GRUCell(1,H)}[kind]()
self.head=nn.Linear(H,1); r=RNG(seed+2000)
with torch.no_grad():
for name,p in self.ordered():
p.copy_(torch.tensor([0. if name.startswith('b') else .8*(r()-.5) for _ in range(p.numel())]).reshape_as(p))
def ordered(self):
if self.kind=='MLP':
return [('wx',self.cell.weight),('bx',self.cell.bias),('wo',self.head.weight),('bo',self.head.bias)]
return [('wx',self.cell.weight_ih),('wh',self.cell.weight_hh),('bx',self.cell.bias_ih),('bh',self.cell.bias_hh),('wo',self.head.weight),('bo',self.head.bias)]
def forward(self,x):
h=x.new_zeros(x.shape[0],self.H); c=h.clone()
if self.kind=='MLP': h=torch.tanh(self.cell(x[:,-1]))
else:
for t in range(x.shape[1]):
if self.kind=='LSTM': h,c=self.cell(x[:,t],(h,c))
else: h=self.cell(x[:,t],h)
return self.head(h)
def run(seed=3,T=12,H=4,lr=.025,updates=120):
x,y=dataset(32,T,seed); v,w=dataset(24,T,seed+1000)
result=[]
for kind in ['MLP','RNN','LSTM','GRU']:
m=Model(kind,H,seed); opt=torch.optim.Adam(m.parameters(),lr=lr); hist=[]
for t in range(updates+1):
loss=(m(x)-y).square().mean()
if t%10==0 or t==updates:
with torch.no_grad():
pred=m(v); hist.append(dict(t=t,train=loss.item(),val=(pred-w).square().mean().item(),pred=pred.flatten().tolist(),p=[p.flatten().tolist() for _,p in m.ordered()]))
if t<updates:
opt.zero_grad(); loss.backward(); opt.step()
result.append(dict(name=kind,hist=hist,params=sum(p.numel() for p in m.parameters())))
return result
if __name__=='__main__':
for q in run(): print(q['name'],q['params'],q['hist'][0]['val'],q['hist'][-1]['train'],q['hist'][-1]['val'])
Sequence API mapping
import torch
from torch import nn
x = torch.randn(32, 12, 1)
rnn = nn.LSTM(1, 4, batch_first=True)
out, (h, c) = rnn(x)
print(out.shape, h.shape, c.shape) # (32,12,4), (1,32,4), (1,32,4)
y = nn.Linear(4, 1)(out[:, -1]) # (32,1)
Draw the unrolled recurrence and annotate the tensor shapes. Check the initial states and data split, then compare the gate order, parameter layout, and gradients against the native PyTorch cells. Keep the evaluation protocol fixed when comparing architectures. Use a task that requires longer histories to assess long-term memory directly.
Authoritative References & Next Lesson
Lesson 4.2 introduces attention, which uses the current query to gather relevant information directly from multiple earlier positions.
Previous lesson · 3.4 Self-supervised & Contrastive Learning · Course contents · Next lesson · 4.2 Attention Mechanisms