Long Short-Term Memory (LSTM)
Long Short-Term Memory (LSTM) is a recurrent neural network architecture introduced by Hochreiter and Schmidhuber in 1997 that uses a gated cell state mechanism to selectively retain or discard information across arbitrarily long sequences, directly solving the vanishing gradient problem that crippled earlier RNNs. LSTMs remain foundational to sequence modeling in speech recognition, machine translation, and time-series forecasting, even as Transformers dominate many benchmarks. Remarkably, the LSTM's forget gate — now considered essential — was not in the original 1997 paper but was added by Gers et al. in 1999, meaning the architecture most practitioners use today is already a revision of the "original."
A standard RNN collapses all past information into a single hidden state vector, forcing every new input to overwrite the past — like writing on a whiteboard you must erase before adding anything new. The LSTM's breakthrough is maintaining a separate cell state (the "memory tape") that flows through time with only lightweight, multiplicative interactions: three learned gates decide what to forget, what to write, and what to read at each step. This means gradients can flow backward through time along the cell state highway with near-zero attenuation, making it possible to learn dependencies spanning hundreds of timesteps. The "aha moment": gating is just sigmoid-weighted element-wise multiplication — beautiful in its simplicity.
How It Works
An LSTM processes a sequence one timestep at a time. At step it receives input and the previous state tuple , then produces updated states . Every gate is a learned sigmoid applied to a linear combination of and .
Forget gate — decides what fraction of the old cell state to keep:
Explanation: Each element of independently gates how much of the corresponding cell-state dimension survives; 0 means "completely forget," 1 means "remember perfectly."
- , — learned weight matrices
- — bias (often initialized to 1 to encourage remembering at the start of training)
- — element-wise sigmoid
Input gate and candidate cell — decides what new information to write:
Explanation: modulates how strongly the candidate values are written into memory — the gate and candidate together act as a controlled write head.
Cell state update — the memory highway:
Explanation: The new cell state is an additive blend of the (gated) old memory and the (gated) new candidate, so gradients can flow backward through time via the term with no repeated matrix multiplication.
- — element-wise (Hadamard) product
Output gate and hidden state — decides what to expose:
Explanation: The hidden state is a tanh-compressed readout of the cell state, further filtered by , so the network can hold information in without necessarily broadcasting it downstream.
Gradient flow insight — the key reason LSTMs work is that the gradient of the loss with respect to an earlier cell state passes through the chain:
Explanation: Because this product involves only the forget gates — bounded scalars, not full Jacobian matrices — the gradient neither explodes nor vanishes as dramatically as in vanilla RNNs, provided the forget gates stay near 1.
PyTorch Implementation
```python import torch import torch.nn as nn
# Single-layer LSTM: input_size=128, hidden_size=256 lstm = nn.LSTM(input_size=128, hidden_size=256, num_layers=1, batch_first=True)
# x: (batch=32, seq_len=100, input_size=128) x = torch.randn(32, 100, 128)
# Initialize hidden and cell states h0 = torch.zeros(1, 32, 256) # (num_layers, batch, hidden) c0 = torch.zeros(1, 32, 256)
# Forward pass — output: (batch, seq_len, hidden) output, (hn, cn) = lstm(x, (h0, c0)) print(output.shape) # torch.Size([32, 100, 256]) print(hn.shape) # torch.Size([1, 32, 256]) print(cn.shape) # torch.Size([1, 32, 256])
# For stateful inference (e.g., streaming):
# detach states to truncate BPTT graph h0, c0 = hn.detach(), cn.detach() ``` ```python
# Manual LSTM cell (educational — shows every gate) class LSTMCell(nn.Module): def __init__(self, input_size, hidden_size): super().__init__() self.hidden_size = hidden_size
# Pack all four gate weight matrices into one for efficiency self.W = nn.Linear(input_size + hidden_size, 4 * hidden_size) def forward(self, x, state): h, c = state combined = torch.cat([x, h], dim=-1) # (batch, d + H) gates = self.W(combined) # (batch, 4H)
# Split into four equal chunks f, i, g, o = gates.chunk(4, dim=-1) f = torch.sigmoid(f) # forget gate i = torch.sigmoid(i) # input gate g = torch.tanh(g) # candidate o = torch.sigmoid(o) # output gate c_new = f c + i g h_new = o * torch.tanh(c_new) return h_new, c_new ```
Hochreiter, an Austrian computer scientist, identified the vanishing gradient problem rigorously in his 1991 diploma thesis — years before the community broadly recognized it — and co-invented LSTM with Jürgen Schmidhuber as a direct solution. His 1997 paper with Schmidhuber introduced the constant error carousel (the cell state), arguably the most consequential architectural idea in sequence modeling before the Transformer. A lesser-known fact: Hochreiter's diploma thesis advisor initially downplayed the vanishing gradient analysis, and the work went largely unnoticed for several years until the LSTM paper brought it to prominence.
Schmidhuber, a Swiss-German AI researcher at IDSIA in Lugano, co-authored the foundational 1997 LSTM paper and has spent decades working on meta-learning, neural program synthesis, and credit assignment across time. His group produced several LSTM extensions including peephole connections (Gers & Schmidhuber, 2000) and Connectionist Temporal Classification (CTC), which enabled the first practical end-to-end speech recognizers. Schmidhuber is famously outspoken about attribution in AI history, maintaining a detailed timeline of discoveries he argues the field has misattributed.
Intuition
Imagine you are a court stenographer transcribing a long legal proceeding. You have two tools: a notepad (the cell state ) and a speaking voice (the hidden state ). The notepad can hold important facts — a witness's name, a key date — across hours of testimony without degradation, because you simply underline things rather than rewriting them. Your voice, however, is selective: you only read aloud from the notepad when it's relevant to the current question. The three gates map naturally to this metaphor: the forget gate is you crossing out old facts that are no longer relevant ("the defendant's alibi has been disproven, strike it"); the input gate and candidate are you deciding whether and how strongly to write a new fact into the notepad; and the output gate is you deciding whether to mention what's on the notepad right now or stay quiet. The magic is that facts on the notepad survive unchanged until explicitly crossed out, so a name written at timestep 1 can be read at timestep 500 with no distortion — exactly what the additive cell-state update achieves mathematically.
Historical Development
Origins · 1 minhow this was discovered
Why It Matters
Prerequisites
What This Leads To
See Also
Recurrent Neural Networks · Gated Recurrent Unit · Transformer Architecture · Backpropagation Through Time · Sequence-to-Sequence Models