ML Systems Lab Open interactive version →
Intermediate 31 min read RNNLSTMGRUvanishing gradientsequential data

RNNs & LSTMs

Vanishing gradient in sequences, gate mechanisms, hidden state, when to still use them

Convolution's bias — nearby elements are related, and that relationship repeats — extends to 1D sequences too, but only within a fixed-size kernel's reach. Some sequences need a dependency that reaches arbitrarily far back. Try to classify the sentiment of "The movie was not good." Process it token by token with a vanilla RNN. At each step, the hidden state h_t is updated: h_t = tanh(W_h · h_{t-1} + W_x · x_t). Tokenized by word, "not" is the 4th token and "good" is the 5th, so the hidden state that captures "not" is h_4. By the time the model reaches "good" and computes the loss from h_5, the gradient of that loss with respect to h_4 must travel back through exactly 1 Jacobian matrix — one per timestep of separation, and here the two tokens are only one timestep apart. Each Jacobian for the tanh activation has a spectral radius that, on average, is less than 1, so every additional timestep of separation multiplies in another shrinking factor: if each Jacobian contributes a factor of 0.5, a 4-timestep separation shrinks the gradient by 0.5⁴ = 0.0625, and a 20-timestep separation shrinks it by 0.5²⁰ ≈ 10⁻⁶. In a longer review — say one where "not" sits 20 tokens before the word the sentiment hinges on — the signal from that early token cannot reach the loss gradient strongly enough to update the corresponding weights.

The LSTM was designed specifically to defeat this. Rather than passing the gradient only through the hidden state h_t, it adds a cell state C_t with an additive update path: C_t = f_t ⊙ C_{t-1} + i_t ⊙ g_t. The forget gate f_t ∈ (0, 1) decides how much of the previous cell state to keep. The gradient of C_t with respect to C_{t-1} is f_t — and the LSTM can learn to keep f_t near 1 for timesteps where memory should be preserved. When f_t ≈ 1, the gradient flows backward through the cell state unchanged, giving the early token a direct path to the loss. The input gate i_t decides what new information to write to the cell state -- that new information is the candidate cell value g_t = tanh(W_g · [h_{t-1}, x_t]), a tanh-squashed candidate update (the LSTM's analogue of the GRU's new_h_t below), and i_t decides how much of g_t actually gets written in. The output gate o_t decides what to expose as the hidden state h_t = o_t ⊙ tanh(C_t). The GRU achieves similar behavior with three weight matrices instead of the LSTM's four (~25% fewer parameters): a reset gate r_t decides how much of the previous hidden state feeds into a new candidate state, new_h_t = tanh(W · [r_t ⊙ h_{t-1}, x_t]), and an update gate z_t then controls the mix between the old state and that candidate, h_t = (1 - z_t) ⊙ h_{t-1} + z_t ⊙ new_h_t, so z_t near 0 preserves the old state much like the LSTM's forget gate near 1, while z_t near 1 writes in the candidate — empirically comparable performance to the LSTM on most tasks.

NOT this. "Transformers made RNNs obsolete." For offline NLP with the full sequence available, transformers win on almost every benchmark. But RNNs remain the correct tool for streaming inference: when you are processing an audio stream, a live trading feed, or a robotics sensor reading, you do not have the full sequence at inference time. Transformer attention requires all positions to be present simultaneously — O(n²) memory to compute the attention matrix. An RNN processes each new token in O(1) with fixed memory. For sequences beyond ~16K tokens where attention memory becomes prohibitive, or for tasks with strict sequential causality and real-time constraints, the RNN is not a fallback — it is the right architecture.

Key points

Takeaway

The LSTM's cell state is an additive gradient highway: when the forget gate stays near 1, the gradient flows back through hundreds of steps without shrinking — the one mechanism that vanilla RNNs lack and the reason LSTMs remain the right choice for any task where inference is sequential, real-time, and the full sequence is not available.

Recap

Check your understanding

Q1. An LSTM processes a sequence of length 200. Where does the gradient come from for updating W_h (the hidden-to-hidden weight) at timestep 1?

Q2. What is the key mathematical difference between an LSTM cell and a GRU cell? Select the TWO correct statements.

Q3. Teacher forcing trains RNNs with ground-truth tokens as inputs, but at test time, the model uses its own predictions. What problem does this cause?

Try it interactively

ML Systems Lab is a free interview-prep platform for ML engineers — work through the full interactive module, quizzes, and drills.

Open ML Systems Lab →