Hidden state and gated recurrence
What it is
An RNN processes a sequence one step at a time and passes a hidden state forward, so a token's representation can depend on preceding tokens. A plain RNN repeatedly applies the same transition, which makes gradients through many time steps prone to vanish or explode. LSTMs and GRUs add gates that decide what to retain, write, and forget; their nearly additive memory paths make long-range information easier, though not effortless, to preserve. For batched variable-length sequences, padding, masks, and hidden-state resets are part of the correctness contract.
Why it matters
They explain sequence modelling before attention and remain useful for small streaming or time-series tasks with strict latency budgets. They maintain only a compact state rather than an all-pairs attention matrix, but their sequential computation prevents the broad parallelism that made Transformers dominant for many offline language tasks.
In the real world: Reading a customer's transaction history one step at a time to spot unusual behaviour.
import torch
import torch.nn as nn
rnn = nn.LSTM(input_size=32, hidden_size=64, num_layers=2, batch_first=True)
x = torch.randn(8, 50, 32) # (batch, timesteps, features)
out, (h_n, c_n) = rnn(x)
out.shape, h_n.shape # (8, 50, 64), (2, 8, 64)Treating an RNN as order-aware after shuffling time steps. Its state only has meaning when the sequence order and sequence boundaries are correct.