What's the motivation behind LSTM?
Long Short-Term Memory (LSTM) networks were designed to overcome the vanishing gradient problem that prevents standard Recurrent Neural Networks (RNNs) from learning long-range dependencies during Backpropagation Through Time (BPTT). Standard RNNs repeatedly multiply hidden states by recurrent weight matrices and tanh derivatives at every step, causing gradients from distant inputs to decay exponentially. LSTMs introduce an additive cell-state highway controlled by input, forget, and output gates, enabling gradients and memory signals to persist across many time steps.
Study Card: Motivation behind LSTM Networks
Direct Answer
Long Short-Term Memory (LSTM) networks (Hochreiter & Schmidhuber, 1997) were created to solve the vanishing gradient problem in standard Recurrent Neural Networks (RNNs) over long sequences.
In a vanilla RNN, , backpropagating error from time back to time multiplies Jacobians . Because derivatives are at most and typically , this repeated product shrinks exponentially with (or explodes if the spectral radius of exceeds ), preventing early context from updating the model.
LSTMs introduce a dedicated cell state updated additively rather than purely through nonlinear matrix products:
where learned sigmoid gates—forget gate (), input gate (), and output gate ()—regulate what information is retained, written, or exposed (). When , the cell state acts as a Constant Error Carousel (CEC) allowing gradients to flow smoothly across long horizons. (Note that LSTMs mitigate vanishing gradients; exploding gradients are still handled via gradient clipping, and Transformers or state-space models are often preferred for massive context parallelism.)
Key Terms
- Vanishing Gradient in BPTT: Exponential decay of as grows due to repeated Jacobian multiplication.
- Long-Range Dependencies: Predictive relationships spanning dozens or hundreds of tokens or time steps.
- Cell State (): Additive memory track carrying long-term context across steps with minimal distortion.
- Gating Mechanisms: Differentiable sigmoid multipliers () controlling forgetting, writing, and reading.
- Constant Error Carousel (CEC): Uninterrupted additive pathway through preserving gradient flow when forget gates stay near .
Example
Consider sentiment classification on a movie review: "I walked in skeptical after hearing mixed reviews, the theater was packed, the popcorn was stale, ... [30 neutral sentences] ..., yet the film turned out to be a masterpiece." A vanilla RNN loses gradient signal from early sentiment words across dozens of intervening neutral tokens during BPTT. An LSTM can keep relevant contextual state preserved in (setting on irrelevant filler tokens and updating selectively via ), bridging long-range dependencies accurately.
Code Implementation
import numpy as np
import tensorflow as tf
tf.random.set_seed(42)
# Compare gradient retention across T=40 time steps: ||d(h_T) / d(x_t)||
T = 40
x = tf.Variable(tf.random.normal((1, T, 4), dtype=tf.float32))
rnn = tf.keras.layers.SimpleRNN(16, return_sequences=True)
lstm = tf.keras.layers.LSTM(16, return_sequences=True)
# Initialize weights (bias on LSTM forget gate defaults to 1.0 in Keras, aiding memory)
_ = rnn(x)
_ = lstm(x)
with tf.GradientTape() as tape:
out_rnn = rnn(x)[:, -1, :] # Final time-step hidden state
loss_rnn = tf.reduce_sum(out_rnn ** 2)
grad_x_rnn = tape.gradient(loss_rnn, x).numpy()[0] # shape (T, 4)
with tf.GradientTape() as tape:
out_lstm = lstm(x)[:, -1, :]
loss_lstm = tf.reduce_sum(out_lstm ** 2)
grad_x_lstm = tape.gradient(loss_lstm, x).numpy()[0]
rnn_norms = np.linalg.norm(grad_x_rnn, axis=1)
lstm_norms = np.linalg.norm(grad_x_lstm, axis=1)
print("Gradient norm of final step output w.r.t. input x_t:")
print(f"SimpleRNN -> t=0 (oldest): {rnn_norms[0]:.3e}, t=39 (latest): {rnn_norms[-1]:.3e}")
print(f"LSTM -> t=0 (oldest): {lstm_norms[0]:.3e}, t=39 (latest): {lstm_norms[-1]:.3e}")
Related Concepts
- Backpropagation Through Time (BPTT): Unrolls recurrent networks across time steps to compute gradients, sharing weights across steps.
- Gated Recurrent Unit (GRU): Merges cell and hidden states and combines forget/input control into an update gate , offering fewer parameters than LSTM with often comparable accuracy.
- Gradient Clipping: Bounds (
clipnorm) to prevent exploding gradients in RNNs and LSTMs. - Transformers & Attention: Replace sequential recurrence with direct path-length self-attention between all pairs of tokens, enabling parallel training and stronger ultra-long-context scaling.