Skip to content
E
Educatum

What's the motivation behind LSTM?

Curated by Educatum AI teamLast updated:
NLP
Direct Answer

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, ht=tanh⁡(Whhht−1+Wxhxt+b)\mathbf{h}_t = \tanh(W_{hh}\mathbf{h}_{t-1} + W_{xh}\mathbf{x}_t + \mathbf{b}), backpropagating error from time TT back to time tt multiplies Jacobians ∏k=t+1Tdiag⁡(1−hk2)Whh\prod_{k=t+1}^T \operatorname{diag}(1 - \mathbf{h}_k^2) W_{hh}. Because tanh⁡\tanh derivatives are at most 11 and typically <1< 1, this repeated product shrinks exponentially with T−tT - t (or explodes if the spectral radius of WhhW_{hh} exceeds 11), preventing early context from updating the model.

LSTMs introduce a dedicated cell state ct\mathbf{c}_t updated additively rather than purely through nonlinear matrix products:

ct=ft⊙ct−1+it⊙c~t\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t

where learned sigmoid gates—forget gate (ft\mathbf{f}_t), input gate (it\mathbf{i}_t), and output gate (ot\mathbf{o}_t)—regulate what information is retained, written, or exposed (ht=ot⊙tanh⁡(ct)\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)). When ft≈1\mathbf{f}_t \approx \mathbf{1}, 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 ∂LT∂ht\frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_t} as T−tT - t grows due to repeated Jacobian multiplication.
  • Long-Range Dependencies: Predictive relationships spanning dozens or hundreds of tokens or time steps.
  • Cell State (ct\mathbf{c}_t): Additive memory track carrying long-term context across steps with minimal distortion.
  • Gating Mechanisms: Differentiable sigmoid multipliers (ft,it,ot∈(0,1)d\mathbf{f}_t, \mathbf{i}_t, \mathbf{o}_t \in (0, 1)^d) controlling forgetting, writing, and reading.
  • Constant Error Carousel (CEC): Uninterrupted additive pathway through ct\mathbf{c}_t preserving gradient flow when forget gates stay near 11.

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 ct\mathbf{c}_t (setting ft≈1\mathbf{f}_t \approx 1 on irrelevant filler tokens and updating selectively via it\mathbf{i}_t), 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}")
  • 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 zt\mathbf{z}_t, offering fewer parameters than LSTM with often comparable accuracy.
  • Gradient Clipping: Bounds ∥∇L∥\|\nabla \mathcal{L}\| (clipnorm) to prevent exploding gradients in RNNs and LSTMs.
  • Transformers & Attention: Replace sequential recurrence with direct O(1)O(1) path-length self-attention between all pairs of tokens, enabling parallel training and stronger ultra-long-context scaling.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.