Recurrent state and BPTT
Quick answer
A recurrent neural network (RNN) reads a sequence one step at a time. Its hidden state summarizes earlier inputs, and the same parameters are reused at every step. Backpropagation through time (BPTT) differentiates through this repeated computation. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Scalar recurrence and BPTT
import torchw=torch.tensor(0.5,requires_grad=True)h=torch.tensor(0.)for x in (1.,2.,3.): h=w*h+x print(h.item())h.backward()print(w.grad.item())Expected output (locally tested): 1.0 2.5 4.25 3.0. The gradient sums both paths through w.
How it works
For a simple RNN, h_t = tanh(W_x x_t + W_h h_(t-1) + b). Here x_t is the current feature vector, h_t is the state, and W_x and W_h are learned matrices. For a batch-first PyTorch RNN, inputs have shape (batch, time, input_size); outputs have shape (batch, time, hidden_size) for a one-layer unidirectional model, and final hidden state has shape (1, batch, hidden_size). A readout can use each valid state for next-token prediction or the last valid state for sequence classification. For intuition, replace tanh with the identity and use scalar h_t = wh_(t-1)+x_t. Unrolling three steps with h_0=0 gives h_3=w²x_1+wx_2+x_3; its derivative with respect to the shared w is 2w*x_1+x_2. BPTT accumulates contributions through every use of the same parameter. In truncated BPTT, detach the carried state at chunk boundaries to limit gradient history; the forward value is preserved, but earlier gradients are cut. Reset state between independent sequences. For forecasting, only use information available at the prediction time.
Native batch-first RNN
import torchrnn=torch.nn.RNN(2,3,batch_first=True)y,h=rnn(torch.zeros(4,5,2))print(tuple(y.shape),tuple(h.shape))Expected output (locally tested): (4, 5, 3) (1, 4, 3). Five time steps per sequence; batch_first does not change the hidden-state layout.
Common mistakes
Do not confuse batch and time axes or assume final padded output is the last valid state. Do not detach each step when the task requires learning long dependencies. Carrying hidden states between unrelated examples can leak information.
Practice and next steps
Trace the linear recurrence by hand and derive its shared-weight gradient. Compare full and truncated backpropagation, then inspect the native RNN output shape.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Recurrent state and BPTT — knowledge check
Apply recurrent state and bptt to small examples and debugging scenarios.
What is reused across time?
What is the output shape for batch=4,time=5,hidden=3?
What does BPTT accumulate?
What does detach do at a chunk boundary?
What is appropriate for unrelated sequences?