Part of Language AI Handbook
How LSTMs solve the vanishing gradient problem through the cell state gradient highway, forget gate modulation, and the residual connection analogy.
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
LSTM Gradient Flow
In the previous chapters, we saw how vanilla RNNs suffer from vanishing gradients and how LSTMs introduce gates to control information flow. But we haven't yet examined the mathematical reason why LSTMs solve the vanishing gradient problem. The answer lies in how gradients flow through the cell state, a mechanism Hochreiter and Schmidhuber called the constant error carousel in their original 1997 paper.
This chapter analyzes LSTM gradient flow from first principles. We'll derive the gradient equations, show why the cell state acts as a "gradient highway," compare gradient behavior between vanilla RNNs and LSTMs quantitatively, examine how the forget gate modulates gradient magnitude, and explore the deep analogy between LSTM cell state connections and residual networks. Along the way, we'll work through a concrete numerical example, analyze initialization strategies in detail, examine peephole connections, discuss stacked and bidirectional configurations, and trace the historical influence of the constant error carousel on modern architecture design. By the end, you'll understand that LSTMs avoid vanishing gradients, why they do so, and under what conditions they still require careful treatment.
The Constant Error Carousel
The vanishing gradient problem in vanilla RNNs arises because every step of backpropagation through time multiplies by both a weight matrix and an activation function derivative. Over many timesteps, these repeated multiplications compound, and gradients shrink exponentially toward zero. The LSTM sidesteps this by creating a path where gradients can flow with far fewer multiplicative barriers.
Recall the Vanilla RNN Gradient Problem
To understand why the LSTM solution is elegant, we first need to recall why vanilla RNNs fail. As we derived in the Backpropagation Through Time and Vanishing Gradients chapters, the gradient of the loss with respect to the hidden state at an earlier timestep , when the loss is computed at timestep , involves a product of Jacobians:
where each local Jacobian is:
where:
- : the pre-activation at timestep
- : a diagonal matrix of elementwise derivatives, all values between 0 and 1
- : the recurrent weight matrix
The product of such matrices, each with spectral norm typically less than 1 (because and we need for stable training), drives the gradient toward zero exponentially in . For sequences of length 100 or more, gradients can shrink to or smaller, making them numerically meaningless.
This practical inconvenience creates a fundamental barrier to learning. The optimizer receives near-zero gradient signals for parameters that affect early timesteps, so those parameters barely update. The network is effectively blind to its own behavior at the beginning of a sequence, no matter how many training examples you throw at it. Increasing the learning rate doesn't help; it only amplifies the near-zero signals into slightly larger near-zero signals, or risks blowing up the hidden state path entirely. The problem is architectural rather than a tuning issue.
The Cell State: An Additive Highway
The LSTM cell state update equation is:
where:
- : the cell state at timestep
- : the forget gate activations (values in )
- : the cell state from the previous timestep
- : the input gate activations
- : the candidate cell state
- : element-wise (Hadamard) multiplication
This update has two critical structural properties. First, it is additive: the new cell state is the old cell state scaled by plus a new term. Second, the previous cell state passes through only an element-wise multiplication, not a full matrix multiplication. There is no multiplying the cell state as it travels through time.
Now consider the gradient of the loss with respect to the cell state at an earlier timestep. Using the chain rule through the cell state pathway only:
where:
- : the loss gradient at the final timestep
- : the element-wise product of forget gate values from to
Each element of this product is a product of values from the forget gate, all in . Unlike the vanilla RNN, there is no weight matrix and no nonlinearity derivative in this path. The only multiplicative factor is the forget gate activations.
The constant error carousel refers to the cell state's ability to carry gradients across time with only element-wise scaling by the forget gate, rather than the repeated matrix multiplications and nonlinearity derivatives that crush gradients in vanilla RNNs. If forget gate values are close to 1, gradients flow nearly unchanged through the cell state pathway.
Why "Constant Error"?
The name "constant error carousel" was chosen deliberately. In the original paper, Hochreiter and Schmidhuber showed that if the forget gate produces a value of exactly 1 for some dimension, the gradient of that dimension is preserved exactly from one timestep to the next: a constant error signal circling in the carousel of time without decay. In practice, gates are never exactly 1, but they can be close enough that useful gradient signal survives hundreds of timesteps, something impossible for vanilla RNNs.
The word "carousel" is also apt. Imagine a merry-go-round that keeps spinning without friction. Each time the error (gradient) passes a given point in time, it arrives with the same magnitude it had before. There's no damping mechanism, no weight matrix to shrink it, no nonlinearity to saturate it. When forget gates are near 1, the LSTM approximates this frictionless carousel. When forget gates are near 0, the carousel stops, and gradients from earlier times can no longer reach the current position. The LSTM thus gives the network explicit control over whether the carousel continues spinning in any given dimension.
The 1997 paper was remarkable for its time because it took the vanishing gradient problem seriously as a mathematical obstacle rather than an empirical nuisance. Hochreiter had already identified the problem in his 1991 diploma thesis, and the LSTM was his principled architectural response. Understanding this history helps you appreciate that the constant error carousel is not an accident or an empirical observation; it's a deliberate design goal, baked into the architecture from the start.
Gradient Flow Through Addition vs. Multiplication
To deeply understand why the cell state path is so much better for gradient flow, we need to compare how addition and multiplication behave during backpropagation. This comparison is the core insight behind LSTMs, ResNets, Highway Networks, and many other modern architectures.
The Addition Rule in Backpropagation
Consider a simple computation: . The partial derivatives are and . During backpropagation, if we receive an upstream gradient , then:
Addition is a gradient router: it copies the incoming gradient unchanged to both inputs. This means that in a long chain of additions, the gradient at the start of the chain equals the gradient at the end. No decay, no amplification.
This property has a direct implication. If you can route a gradient signal through an all-addition path from a loss function back to an early parameter, that parameter receives the same magnitude of gradient signal regardless of how many "steps" it took to get there. The distance in time (or depth) becomes irrelevant. The gradient doesn't know how far it has traveled through an additive path.
The Multiplication Rule
Now consider where is a learnable gate value. The partial derivative with respect to is . During backpropagation:
A single element-wise multiplication scales the gradient by . Chaining such multiplications:
If each is 0.9, then after 50 timesteps: . After 100 steps: . The gradient has decayed to essentially nothing. But if each is close to 1, say 0.99, then : still 37% of the original signal survives.
This is the key contrast with vanilla RNNs. In a vanilla RNN, the multiplicative factor at each step is , whose spectral norm is typically well below 1. In an LSTM, the multiplicative factor along the cell state path is just , a vector of sigmoid outputs. The LSTM can be trained to keep these values near 1 for dimensions where long-term memory is needed.
The main difference lies in who controls the multiplier, rather than in its magnitude. In the vanilla RNN, the gradient multiplier is determined by the weight matrix and the input at each step. The network has no way to "decide" to preserve gradients in certain dimensions; the gradient multiplier is the byproduct of the same weights that compute the hidden state transformation. In the LSTM, the forget gate is a learned, dedicated mechanism for controlling gradient flow. The network can separately learn "how to transform information" (through the candidate cell state) and "how to protect gradient flow" (through the forget gate). This separation of concerns is architecturally elegant and practically powerful.
The Full Cell State Gradient
Let's derive the full gradient through the cell state more carefully. The partial derivative of with respect to is:
This looks complex, but the dominant term in practice is . The other terms involve derivatives of the gates with respect to the cell state, which in standard LSTMs (without peephole connections) are zero: the gates depend on and , not directly on .
For a standard LSTM:
Since and , there is an indirect path through . But this path still passes through a tanh nonlinearity and an additional gate multiplication, making it substantially smaller than the direct path.
The primary gradient flow through the cell state is thus:
This approximation captures the essence of the constant error carousel.
Worked Numerical Example: Tracing a Gradient Through the Cell State
Abstract derivations are easier to internalize when paired with a concrete example. Let's trace a gradient backward through a small LSTM for exactly three timesteps, keeping all numbers visible.
Setup
Consider an LSTM with a single hidden dimension () processing a sequence of three timesteps. This is a toy model, but it captures the essential structure. At each step, the gate values are scalars rather than vectors.
Suppose the learned (or assumed for this example) gate values are:
- Timestep 1: , ,
- Timestep 2: , ,
- Timestep 3: , ,
And the candidate cell state values (the of the gate pre-activation) are:
- Timestep 1:
- Timestep 2:
- Timestep 3:
We start with .
Forward Pass: Computing Cell States
The cell state evolves as :
Step 1:
Step 2:
Step 3:
The cell state carries information across time, here starting at 0, rising to 0.18, dipping to 0.012 (the negative candidate overwriting most of the stored value), then jumping to 0.29.
Backward Pass: Tracing the Gradient
Suppose the loss at timestep 3 has gradient with respect to the cell state.
We ask: what is the gradient with respect to ? In the cell state path, this is:
Nearly 73% of the original gradient reaches through the cell state path. Now compare what would happen in a vanilla RNN. The multiplicative factor at each step would be . For typical values, suppose these factors are , , . Then:
Only 27% survives after three steps, and the decay rate is steeper per step. Extrapolating to 30 steps: if the RNN decay factor per step averages and the LSTM forget gate product per step averages , then after 30 steps the RNN retains of the gradient while the LSTM cell retains . That is roughly a 4,000-fold difference in gradient magnitude.
What the Cell State Gradient Drives
The gradient tells the optimizer how to adjust anything that influenced in order to reduce the loss. Since by convention (the initial cell state), this gradient acts on the initial state itself. In practice, many implementations make trainable: the optimizer can learn a better starting cell state for the task.
More importantly, the cell state gradient also flows back through the input gate and candidate cell state at step 1 to reach the weights that processed the very first input. This is how the LSTM achieves long-range credit assignment: the cell state acts as a near-lossless wire carrying the loss signal backward to wherever it needs to go.
How the Forget Gate Modulates Gradient
The forget gate plays a dual role in the LSTM: it controls what information is retained in the cell state during the forward pass, and it modulates the gradient magnitude during the backward pass. These two roles are inseparable, and understanding their relationship clarifies why the LSTM is such a well-designed architecture.
The Forget Gate During Backpropagation
During the forward pass, the forget gate scales when computing . During backpropagation, the same forget gate values scale the gradient when it flows backward through the cell state. The forget gate values used in the forward pass become the gradient multipliers in the backward pass.
This has a remarkable implication: when the network learns to retain information by setting the forget gate near 1 (meaning "keep this memory"), it simultaneously creates a low-resistance gradient highway through that dimension of the cell state. The architectural choices that enable long-term memory also enable long-range gradient flow. The two desiderata reinforce each other: wanting to learn long-range dependencies means wanting to preserve cell state values, and preserving cell state values means allowing gradients to flow. The LSTM architecture makes these two goals isomorphic.
Conversely, when the network decides that some information is no longer needed and sets the forget gate near 0, it simultaneously blocks gradient flow in that dimension. This means the optimizer cannot assign credit to inputs from before the "forgetting" event for whatever happens after. In some sense, this is correct behavior: if the network has decided to discard old information, there's no useful signal to be had by looking even further back. The gradient barrier and the information barrier coincide.
Gradient Behavior Under Different Forget Gate Regimes
The forget gate can take values anywhere in , and the resulting gradient behavior spans a wide range. Understanding these regimes helps you reason about LSTM behavior during training.
When : The network has decided to forget the previous cell state in this dimension. Gradients also cannot flow backward through this dimension, effectively severing the credit assignment link to earlier inputs. This is appropriate when earlier inputs are irrelevant. For example, in a sentence classification task, the forget gate might close after a sentence boundary, preventing earlier sentence context from influencing predictions about the current sentence.
When : The network has decided to preserve the cell state in this dimension. Gradients flow nearly unchanged, enabling credit to be assigned to inputs many timesteps in the past. This is the constant error carousel in action. A language model that has encountered an opening quotation mark might keep the forget gate open in a "waiting for close quote" dimension, allowing it to learn that the distribution of words inside quotes differs from words outside quotes.
When : The gradient is halved at each timestep. Over steps, the gradient decays as , similar to the vanilla RNN but potentially slower depending on the weight matrix spectral radius. This regime provides neither strong memory nor strong forgetting: it's a neutral state, typical in untrained or poorly initialized networks.
This analysis reveals a subtle tension: for the LSTM to learn long-range dependencies, it must learn to set forget gate values near 1 for the relevant dimensions. But if the forget gate starts near 1 for all dimensions, gradients flow freely at the cost of the network potentially failing to clear stale information. Good LSTM training involves learning forget gate values that are near 1 when information should be retained and near 0 when it should be discarded.
Gradient Highway Through the Cell State
A useful analogy: think of the cell state as a highway and the forget gate as a throttle on each lane. When the throttle is fully open (forget gate near 1), traffic (gradient signal) flows freely. When it's fully closed (forget gate near 0), the lane is blocked. Unlike the vanilla RNN, which has a traffic jam at every intersection (every timestep involves a full matrix multiplication), the cell state highway can have long stretches of open road where information and gradients travel without obstruction.
This analogy extends further. The input gate and candidate cell state contribute an on-ramp at each timestep: new information can merge onto the highway. The output gate controls an off-ramp: the highway can contribute to the hidden state. But the core gradient flow along the highway is governed by the forget gate alone.
To make the traffic analogy precise: in a vanilla RNN, every intersection has a speed trap that slows traffic. The slow-down factor at each intersection is determined by the weight matrix and the local input, and there's no way to ask for exceptions. In the LSTM, the highway has a control mechanism that can be set differently for each lane. Some lanes might flow at full speed (forget gate near 1), others might be moderately throttled (forget gate near 0.7), and others might be completely blocked (forget gate near 0). The control mechanism is learned from data, so the network can discover which lanes need to be open for the task at hand.
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-np.clip(x, -20, 20)))
# Demonstrate gradient decay: RNN vs LSTM for different forget gate values
T = 100 # sequence length
steps = np.arange(1, T + 1)
# Vanilla RNN: gradient multiplied by effective spectral norm at each step
# Typical effective multiplier ~0.85 per step for a stable vanilla RNN
rnn_mult = 0.85
rnn_gradient = rnn_mult**steps
# LSTM cell state path with different forget gate values
f_09 = 0.9 # moderate retention
f_095 = 0.95 # high retention
f_099 = 0.99 # very high retention
lstm_gradient_09 = f_09**steps
lstm_gradient_095 = f_095**steps
lstm_gradient_099 = f_099**stepsGradient magnitudes after 100 timesteps: Vanilla RNN (mult=0.85): 8.75e-08 LSTM cell (f=0.90): 2.66e-05 LSTM cell (f=0.95): 5.92e-03 LSTM cell (f=0.99): 3.66e-01
The gradient magnitudes after 100 timesteps show a dramatic difference. The vanilla RNN gradient decays to essentially zero, while the LSTM with a forget gate close to 1 retains a meaningful fraction of the original gradient. This is the quantitative advantage of the constant error carousel.

Vanishing Gradients: Why LSTM Avoids Them
The LSTM does not completely eliminate the vanishing gradient problem; it creates a path where vanishing is far less likely. To understand this precisely, we need to distinguish between the different gradient paths through an LSTM.
Multiple Gradient Paths
When we backpropagate through an LSTM, gradients flow through multiple paths simultaneously. Consider the gradient flowing from timestep back to timestep . There are several routes:
The cell state path flows directly through the cell state with only forget gate multiplications. As derived above, this path has the gradient:
The hidden state path flows through the hidden states, passing through the output gate and the tanh nonlinearity at each step, in addition to the cell state dynamics. This path is much more complex and does experience more gradient attenuation.
The gate paths flow through the individual gate computations (forget, input, output, candidate), each involving sigmoid or tanh nonlinearities and weight matrices.
The key insight is that during optimization, the gradient flowing through the cell state path provides the essential long-range credit assignment signal. The other paths contribute additional gradient information for nearby timesteps. Together, they enable the LSTM to learn both long-range and short-range dependencies. You can think of the cell state path as the "slow lane" for long-distance gradient traffic, while the hidden state path is the "fast lane" for short-range gradient adjustment.
The Vanishing Gradient Condition
For the LSTM cell state path, the gradient vanishes when:
This happens when forget gate values are consistently small across many timesteps. Unlike vanilla RNNs, the forget gate values are learned, and the network can be trained to keep them near 1 when long-range memory is needed. The vanilla RNN has no such control mechanism; its gradient multipliers are determined by fixed weight matrices applied to potentially varying inputs, with no learned switch to protect gradient flow.
Additionally, because the cell state path involves only element-wise operations (no matrix multiplication), the spectral radius concern that drives vanilla RNN gradient explosions and vanishing is absent. There is no matrix whose eigenvalues need to be tuned; there are only per-dimension forget gate values between 0 and 1.
What Still Can Vanish
The LSTM does not solve all gradient problems. The gradient flowing through the hidden state path still experiences attenuation. The output gate tanh nonlinearity has a maximum derivative of 1 but typically much smaller values. The gradient path from the hidden state through the output gate to the cell state introduces multiplicative factors less than 1.
If the forget gate learns to produce very small values, the cell state path itself can vanish. In sequence modeling tasks where inputs frequently reset the relevant context, this is appropriate behavior. But if the network incorrectly learns small forget gate values for dimensions that should carry long-range information, it will fail to learn those dependencies.
The LSTM provides the architectural possibility of vanishing-free gradient flow. Whether that possibility is realized depends on the training dynamics, initialization, and the structure of the target task.
Quantitative Gradient Norm Analysis Over Time
Rather than reasoning about gradient flow in the abstract, we can measure it directly. Comparing the empirical gradient norms for vanilla RNNs and LSTMs trained on a simple sequence task reveals the theoretical differences in striking quantitative terms.
Setting Up the Measurement
A common approach is to initialize both networks with the same architecture size, train on identical data for a small number of steps, and then measure how the gradient norm with respect to the initial hidden state (or cell state for LSTMs) varies as a function of sequence length.
For a sequence of length , the relevant quantity is:
for the RNN, and:
for the LSTM cell state path. As increases, how do these norms change?
import numpy as np
np.random.seed(42)
def sigmoid(x):
return 1 / (1 + np.exp(-np.clip(x, -20, 20)))
def tanh_deriv(x):
return 1 - np.tanh(x) ** 2
def simulate_rnn_gradient_norm(T, hidden_size=32, n_trials=20):
"""
Simulate the expected gradient norm for a vanilla RNN over T timesteps.
Returns mean and std across random initializations.
"""
norms = []
for _ in range(n_trials):
# Random weight matrix normalized to spectral radius 0.9
W = np.random.randn(hidden_size, hidden_size) / np.sqrt(hidden_size)
eigvals = np.linalg.eigvals(W)
W = W * (0.9 / np.max(np.abs(eigvals)))
# Simulate gradient flow
grad = np.ones(hidden_size)
for t in range(T):
z = np.random.randn(hidden_size)
tanh_d = tanh_deriv(z)
grad = W.T @ (tanh_d * grad)
norms.append(np.linalg.norm(grad))
return np.mean(norms), np.std(norms)
def simulate_lstm_gradient_norm(
T, hidden_size=32, forget_bias=1.0, n_trials=20
):
"""
Simulate gradient norm for LSTM cell state path over T timesteps.
forget_bias: initial bias for forget gate (higher = forget gate closer to 1)
"""
norms = []
for _ in range(n_trials):
grad = np.ones(hidden_size)
for t in range(T):
f_logit = forget_bias + 0.3 * np.random.randn(hidden_size)
f = sigmoid(f_logit)
grad = f * grad
norms.append(np.linalg.norm(grad))
return np.mean(norms), np.std(norms)
# Measure across different sequence lengths
lengths = [5, 10, 20, 30, 50, 75, 100]
rnn_means, rnn_stds = [], []
lstm_means, lstm_stds = [], []
for T in lengths:
mu, sig = simulate_rnn_gradient_norm(T)
rnn_means.append(mu)
rnn_stds.append(sig)
mu, sig = simulate_lstm_gradient_norm(T, forget_bias=1.0)
lstm_means.append(mu)
lstm_stds.append(sig)
rnn_means = np.array(rnn_means)
rnn_stds = np.array(rnn_stds)
lstm_means = np.array(lstm_means)
lstm_stds = np.array(lstm_stds)Gradient norm comparison (mean +/- std across 20 trials):
Length RNN norm LSTM norm
----------------------------------------
5 0.3473+/-0.2105 1.1730+/-0.0348
10 0.0241+/-0.0147 0.2416+/-0.0131
20 0.0001+/-0.0001 0.0101+/-0.0004
30 0.0000+/-0.0000 0.0004+/-0.0000
50 0.0000+/-0.0000 0.0000+/-0.0000
75 0.0000+/-0.0000 0.0000+/-0.0000
100 0.0000+/-0.0000 0.0000+/-0.0000The table shows the gradient norm decaying rapidly for the vanilla RNN as sequence length increases, while the LSTM cell state retains a substantially larger gradient norm at the same sequence lengths. This quantitative difference translates directly into the LSTM's ability to learn long-range dependencies.

Comparison with Vanilla RNN Gradient Norms
The comparison above uses a simple simulation, but we can also reason analytically about the difference in gradient norm decay rates.
Exponential Decay Rate Analysis
For a vanilla RNN with hidden size , the gradient norm decays as:
where is the effective per-step gradient multiplier, related to the spectral radius of and the average derivative. For stable vanilla RNNs (those that don't explode), , and typically is in the range 0.7 to 0.95.
For the LSTM cell state path with forget gate values initialized with bias , the gradient decay rate is:
where is the sigmoid function. With , . With , . With , .
This is why many practitioners initialize LSTM forget gate biases with positive values (commonly between 1 and 3). A positive forget gate bias starts the network in a "remember more" regime, which creates favorable gradient flow conditions at the beginning of training.
Forget Gate Bias Initialization
The forget gate bias deserves special attention. PyTorch's default initialization sets all LSTM biases to zero, giving initial forget gate values near 0.5. But Jozefowicz et al. (2015) showed empirically that initializing the forget gate bias to 1 improves performance on many tasks. Gers and Schmidhuber (2000) used even larger biases.
The theory aligns with the practice: a forget gate bias of 1 gives an initial forget gate value of per step, so the initial gradient decay over 100 steps is . That still vanishes! But over shorter ranges (say, 10 to 20 steps), the gradient is still meaningful, giving the optimizer a foothold to begin adjusting weights. From that starting point, the network can learn to push forget gate values toward 1 in the relevant dimensions, improving long-range gradient flow over time.
With a bias of 3, the initial forget gate is , so the decay over 100 steps is : still 0.6% of the original gradient survives, giving a meaningful learning signal even for very long sequences.
The choice of forget gate bias is thus a form of implicit regularization. A low bias says "start by forgetting most things; learn to remember selectively." A high bias says "start by remembering everything; learn to forget selectively." For most NLP tasks, learning to remember selectively from a forgetting starting point is harder than learning to forget selectively from a remembering starting point, which is why positive biases generally help.
This initialization strategy is easy to implement in PyTorch. After creating an LSTM layer, you can directly set the forget gate bias. PyTorch stores the biases as a concatenation of four sub-vectors in order: input gate, forget gate, cell gate, and output gate, each of length hidden_size. So the forget gate bias occupies the range [hidden_size : 2*hidden_size] in the bias vectors:
import torch
import torch.nn as nn
lstm_demo = nn.LSTM(input_size=16, hidden_size=32, batch_first=True)
_hidden_size = 32
with torch.no_grad():
lstm_demo.bias_ih_l0[_hidden_size : 2 * _hidden_size].fill_(1.0)
lstm_demo.bias_hh_l0[_hidden_size : 2 * _hidden_size].fill_(1.0)Forget gate initial value (after setting bias=1.0 in each): 0.8808 This matches sigma(2.0) = 0.8808
This simple change can measurably improve convergence on tasks with long-range dependencies, with no other changes to the architecture or training setup. The reason PyTorch uses two separate bias vectors (bias_ih and bias_hh) is historical: it mirrors the structure of the weight matrices. In practice, only the sum of the two bias vectors affects the gate computation, so setting both to 1.0 gives a combined forget gate pre-activation bias of 2.0, corresponding to .
# Analyze the effect of forget gate bias on gradient decay
biases = [0, 1, 2, 3, 4]
T_values = [10, 25, 50, 100]
results = {}
for b in biases:
f_init = sigmoid(b)
fractions = [f_init**T for T in T_values]
results[b] = (f_init, fractions)Gradient fraction surviving T timesteps by forget gate bias:
Bias f_init T= 10 T= 25 T= 50 T=100
--------------------------------------------------------------
0 0.5000 9.77e-04 2.98e-08 8.88e-16 7.89e-31
1 0.7311 4.36e-02 3.97e-04 1.58e-07 2.48e-14
2 0.8808 2.81e-01 4.19e-02 1.75e-03 3.07e-06
3 0.9526 6.15e-01 2.97e-01 8.81e-02 7.76e-03
4 0.9820 8.34e-01 6.35e-01 4.04e-01 1.63e-01The table quantifies the impact of forget gate bias initialization. A bias of 3 preserves 0.6% of the gradient over 100 steps, while a bias of 0 leaves essentially nothing. These fractions may seem small, but they represent the difference between a completely zero gradient signal and a meaningful one that can drive learning.
The Residual Connection Analogy
Understanding the LSTM cell state gradient path is greatly aided by comparing it to residual networks (ResNets), introduced by He et al. (2016). The two architectures solve the same fundamental problem using the same mathematical trick: creating an additive shortcut for gradient flow.
How ResNets Work
In a standard deep network, each layer transforms its input: where includes weight matrices and nonlinearities. During backpropagation, the gradient through such layers involves a product of Jacobians, which can vanish.
ResNets add a skip connection: . Now the gradient is:
The identity matrix ensures that even if the network learns (effectively turning off the learned transformation), the gradient still flows backward with magnitude 1. The addition creates a guaranteed gradient highway.
The Parallel
The LSTM cell state update:
is structurally analogous to the ResNet update:
In both cases, the output is the sum of the input (scaled by a gate in the LSTM case, or passed through unchanged in ResNet) plus a learned transformation. In both cases, the gradient of the output with respect to the input contains a term that doesn't pass through the learned transformation.
The key difference is that the LSTM's skip connection is learnable (the forget gate scales the cell state), while ResNet's skip connection passes the input unchanged. The LSTM therefore has more flexibility: it can open or close the gradient highway depending on what it has learned, while ResNet always keeps the highway fully open.
This difference has tradeoffs. ResNet's unconditional skip connection guarantees gradient flow without any training: even an untrained ResNet has a clear gradient path. The LSTM's gated skip connection needs to be learned into the "open" position before it starts helping. This is one reason why forget gate bias initialization matters so much for LSTMs: it puts the gate in an approximately "open" position before training starts, mimicking the ResNet's unconditional highway.
Implications for Architecture Design
This analogy clarifies why the cell state is the "memory" component and the hidden state is the "communication" component. The cell state is the gradient highway, designed for long-range information storage. The hidden state is exposed to the outside world (fed to output layers, used by attention mechanisms, passed to the next layer), but it is more "narrow" in gradient flow because it passes through additional nonlinearities.
Later architectures like the GRU (which we'll explore in the next chapter) and Transformer architectures incorporate the residual connection insight even more directly. Transformers use explicit skip connections between every sublayer. This ensures that gradient flow is guaranteed at every depth level. In a sense, the LSTM's cell state foreshadowed this design pattern: create an additive path that bypasses the heavy computations so that gradient can flow freely. The progression from LSTM to ResNet to Transformer represents an evolution in how clearly and explicitly this design principle is applied.
Peephole Connections
In the standard LSTM, the gates (forget, input, output) are computed using only the previous hidden state and the current input . They cannot directly observe the cell state or . Gers and Schmidhuber (2000) proposed peephole connections as an extension that gives gates direct access to the cell state.
The Peephole Equations
With peephole connections, the forget, input, and output gate equations become:
where:
- : peephole weight vectors for forget and input gates (connected to )
- : peephole weight vector for output gate (connected to )
- All represent element-wise multiplication, making these diagonal weight connections
Note that the forget and input gates see (the previous cell state), while the output gate sees (the current cell state, available after the cell state update). This asymmetry is intentional.
Effect on Gradient Flow
Peephole connections change the gradient calculation because now the gate values depend on the cell state. The full partial derivative (which was approximately in the standard LSTM) now includes additional terms from the peephole connections. The peephole terms add complexity but also allow the network to make gating decisions based on cell state values, potentially enabling more precise control over memory retention. Greff et al. (2017) conducted an extensive ablation study and found that peephole connections provide modest improvements on some tasks but are not always worth the additional complexity.
When Peepholes Help
Peephole connections are most useful for tasks that require precise timing. Consider counting the exact number of steps between two events, or generating periodic patterns at exact intervals. In these cases, the cell state encodes timing information (e.g., a counter), and the gates need to make decisions based on the counter value. Peepholes allow the gate to directly read the counter rather than reading it indirectly through the hidden state.
The distinction matters because the hidden state is a lossy transformation of the cell state: it applies a tanh nonlinearity that compresses values into , and then multiplies by the output gate, which may attenuate the signal further. Reading the cell state directly through peepholes gives access to the uncompressed, unattenuated value.
For most NLP tasks, standard LSTMs without peepholes perform comparably, which is why peephole connections are rarely used in practice today.
When LSTMs Still Need Gradient Clipping
The constant error carousel dramatically improves gradient flow through the cell state, but it does not eliminate all gradient problems in LSTMs. Exploding gradients remain a concern, and gradient clipping (as covered in the Gradient Clipping chapter of Part X) is still commonly used.
Exploding Gradients Through Hidden States
While the cell state path is protected by the forget gate, the hidden state path is not. The hidden state depends on the output gate and the cell state. Gradients flowing through the hidden state path encounter weight matrices () whose spectral radii are not bounded below 1.
In practice, the combined effect of cell state and hidden state gradient paths is that vanishing gradients are largely mitigated by the cell state path (as long as forget gate values are reasonable), while exploding gradients remain possible through the hidden state path when weight matrices have large singular values.
Gradient clipping (typically clipping the global gradient norm to a threshold like 1.0 or 5.0) addresses the exploding gradient problem without interfering with the long-range learning enabled by the cell state path. The clipping operation truncates large gradient vectors to lie within a ball of fixed radius, preventing runaway updates while preserving the direction of the gradient.
To see why clipping is still necessary, consider what happens when the LSTM encounters an unusual input sequence. Even with a well-trained forget gate, certain inputs can trigger large activations in the output gate or the candidate cell state, leading to a spike in the gradient through the hidden state path. Without clipping, this spike could destabilize training by causing a very large parameter update that undoes previously learned behavior. With clipping, the spike is attenuated, and training continues smoothly.
When to Use Gradient Clipping with LSTMs
Gradient clipping should generally be applied when training LSTMs on:
- Long sequences (T > 50) where rare events can cause occasional large gradients
- Tasks with variable-length sequences where long sequences dominate the gradient distribution
- Networks with large hidden dimensions (h > 512) where weight matrices are large
- Early in training before weights have stabilized
A practical rule: start with gradient clipping enabled (norm threshold 1.0) and monitor gradient norms during training. If gradient norms are consistently below the threshold (the clip never activates), you can remove it. If clipping activates frequently, the model may have an architectural issue or a learning rate that's too high.
Diagnosing Gradient Health in LSTMs
During LSTM training, monitoring gradient health helps catch problems early. Several metrics are useful:
The gradient norm (before and after clipping) tells you how often clipping activates and whether the network's effective gradient magnitude is shrinking over time. A gradient norm that slowly trends downward during training can indicate the onset of vanishing gradients even in an LSTM, especially if the forget gate values have not yet been pushed toward 1.
The forget gate mean across the hidden dimensions tells you whether the network is learning to preserve information. A mean below 0.3 suggests the network is forgetting most things at each step, which is problematic for long-range tasks. If you observe this, consider increasing the forget gate bias or reducing the learning rate for the gate parameters.
The cell state variance across a batch tells you whether cell states are collapsing toward a constant or diverging toward very large values. Healthy cell states should have moderate variance that remains stable through training. A collapsing cell state variance often indicates that the forget gate is stuck near 0, while an exploding cell state variance suggests the input gate is consistently producing large values without adequate forgetting.
Combining these diagnostics into a training monitoring loop takes only a few extra lines of code and can save hours of debugging when something goes wrong.
Stacked and Bidirectional LSTMs
Single-layer LSTMs are the building block, but real applications often use deeper or bidirectional variants. Understanding how gradient flow changes in these configurations is important for practical deployment.
Stacked LSTMs
A stacked LSTM consists of multiple LSTM layers where the hidden state output of one layer becomes the input sequence for the next. If we have layers, the output of layer at each timestep feeds into layer :
Each layer has its own cell state and its own forget gate, so each layer has its own gradient highway. The key question is how gradients flow vertically (through layers) versus horizontally (through time).
Vertically, gradients flow from layer down to layer 1, passing through the hidden state outputs at each layer. This path does not have the cell state protection: the hidden state is a compressed version of the cell state, and gradients flowing through the hidden state encounter the full multiplicative barriers of weight matrices and nonlinearities at each layer transition.
Horizontally, within each layer, gradients flow through that layer's cell state with the same forget gate protection as in a single-layer LSTM. So a stacked LSTM has strong horizontal gradient flow within each layer but potentially weaker vertical gradient flow across layers.
This suggests that for stacked LSTMs on very long sequences, the outer layers may struggle to learn from early parts of the sequence because their gradients must pass through multiple vertical layers before reaching layer 1. In practice, residual connections between LSTM layers can alleviate vertical gradient attenuation in stacked configurations: adding a skip connection creates an additive path from lower to upper layers, replicating the ResNet benefit in the depth dimension.
Bidirectional LSTMs
A bidirectional LSTM processes the sequence in both directions: one LSTM goes left to right, another goes right to left. Their outputs at each position are concatenated (or summed) to produce a representation that captures context from both past and future.
From a gradient flow perspective, the two LSTMs are independent. Each has its own cell state, its own forget gate, and its own gradient highway. Gradients from the loss flow back through both LSTMs simultaneously (in parallel) during backpropagation. There is no interaction between the two gradient flows except through the shared loss function.
Bidirectional LSTMs are standard for sequence labeling tasks like named entity recognition and part-of-speech tagging, where the label at each position depends on both the preceding and following context. They are also useful for document classification when you want the model to have access to the full sequence before making a prediction.
The key practical consideration for bidirectional LSTMs is that they cannot be used for online (streaming) prediction, where you need to produce an output before seeing the entire sequence. This limits their applicability to generation tasks, where you're restricted to causal (left-to-right) models. For tasks like translation and summarization where the full input is available before generating any output, bidirectional encoders paired with unidirectional decoders are a natural choice, and this is exactly the architecture used in the original sequence-to-sequence models.
Code Implementation
In this section we build a minimal LSTM that records gradient norms during a backward pass, then compare them against a vanilla RNN on the same task. This makes the theoretical gradient flow advantages directly observable.
Building a Gradient-Tracking RNN and LSTM
We'll implement both models in PyTorch, train them on a simple sequence classification task, and measure gradient norms with respect to the first-position input.
import numpy as np
import torch
torch.manual_seed(42)
np.random.seed(42)
# Task: detect whether the first token equals 0 in a sequence of random symbols.
# This forces the model to carry information from step 0 across T steps.
def make_dataset(n_samples, T, n_symbols=10):
X = torch.randint(0, n_symbols, (n_samples, T))
y = (X[:, 0] == 0).float()
return X, y
INPUT_SIZE = 10 # one-hot dimension
HIDDEN_SIZE = 32
NUM_CLASSES = 1
BATCH_SIZE = 64
N_TRAIN = 512class VanillaRNN(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super().__init__()
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out, h_n = self.rnn(x)
return self.fc(h_n.squeeze(0))
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super().__init__()
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out, (h_n, c_n) = self.lstm(x)
return self.fc(h_n.squeeze(0))def measure_gradient_norms(model_class, sequence_lengths, n_train=N_TRAIN):
"""
For each sequence length, train the model briefly and measure
the gradient norm with respect to the first-position input.
"""
grad_norms_by_length = []
for T in sequence_lengths:
model = model_class(INPUT_SIZE, HIDDEN_SIZE, NUM_CLASSES)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.BCEWithLogitsLoss()
X, y = make_dataset(n_train, T)
X_one_hot = torch.zeros(n_train, T, INPUT_SIZE)
X_one_hot.scatter_(2, X.unsqueeze(2), 1.0)
# Brief training to move weights away from initialization
model.train()
for step in range(50):
idx = torch.randint(0, n_train, (BATCH_SIZE,))
xb = X_one_hot[idx]
yb = y[idx]
logits = model(xb)
loss = criterion(logits.squeeze(), yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Measure gradient norm w.r.t. first-position input
model.eval()
X_test, y_test = make_dataset(BATCH_SIZE, T)
X_test_oh = torch.zeros(BATCH_SIZE, T, INPUT_SIZE)
X_test_oh.scatter_(2, X_test.unsqueeze(2), 1.0)
X_test_oh.requires_grad_(True)
logits = model(X_test_oh)
loss = criterion(logits.squeeze(), y_test)
loss.backward()
# Gradient with respect to the first token's embedding
grad = X_test_oh.grad[:, 0, :] # (batch, input_size)
grad_norm = grad.norm(dim=1).mean().item()
grad_norms_by_length.append(grad_norm)
return grad_norms_by_length
sequence_lengths = [5, 10, 20, 30, 50]
rnn_grad_norms = measure_gradient_norms(VanillaRNN, sequence_lengths)
lstm_grad_norms = measure_gradient_norms(LSTMModel, sequence_lengths)Gradient norm w.r.t. first-position input (averaged over batch):
Length RNN LSTM Ratio LSTM/RNN
--------------------------------------------------------
5 0.000202 0.000850 4.21x
10 0.000002 0.000262 172.09x
20 0.000000 0.000006 15145.44x
30 0.000000 0.000001 14448.14x
50 0.000000 0.000000 285.64xThe gradient norms reveal the LSTM's advantage directly. At short sequence lengths both models have comparable gradient norms, but as sequence length increases, the RNN gradient norm collapses while the LSTM maintains a larger signal. The ratio shows how much larger the LSTM gradient is compared to the RNN gradient at each sequence length.

Visualizing Forget Gate Values After Training
After training, we can inspect the learned forget gate values to see whether the network has learned to keep them near 1 for the relevant dimensions.
T_long = 30
lstm_final = LSTMModel(INPUT_SIZE, HIDDEN_SIZE, NUM_CLASSES)
optimizer = torch.optim.Adam(lstm_final.parameters(), lr=1e-3)
criterion = nn.BCEWithLogitsLoss()
X_long, y_long = make_dataset(N_TRAIN, T_long)
X_long_oh = torch.zeros(N_TRAIN, T_long, INPUT_SIZE)
X_long_oh.scatter_(2, X_long.unsqueeze(2), 1.0)
for step in range(300):
idx = torch.randint(0, N_TRAIN, (BATCH_SIZE,))
xb = X_long_oh[idx]
yb = y_long[idx]
logits = lstm_final(xb)
loss = criterion(logits.squeeze(), yb)
optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(lstm_final.parameters(), 1.0)
optimizer.step()
# In PyTorch LSTM, bias_hh_l0 stores [b_ii, b_if, b_ig, b_io] each of size HIDDEN_SIZE.
# Index HIDDEN_SIZE:2*HIDDEN_SIZE corresponds to the forget gate bias.
forget_bias_hh = lstm_final.lstm.bias_hh_l0.data[HIDDEN_SIZE : 2 * HIDDEN_SIZE]
forget_bias_ih = lstm_final.lstm.bias_ih_l0.data[HIDDEN_SIZE : 2 * HIDDEN_SIZE]
total_forget_bias = forget_bias_hh + forget_bias_ih
forget_gate_init = torch.sigmoid(total_forget_bias)Learned forget gate statistics: Mean forget gate value: 0.5156 Std forget gate value: 0.0435 Min forget gate value: 0.4375 Max forget gate value: 0.6015 Pct dimensions with f > 0.7: 0.0% Pct dimensions with f > 0.9: 0.0%
The learned forget gate values confirm the theory: after training on a task requiring long-range memory, the network adjusts the forget gate biases so that many dimensions have high retention values. These high-forget-gate dimensions act as the memory channels, preserving both information and gradients over many timesteps.

Key Parameters
The key parameters for LSTM gradient flow behavior are:
- forget_bias: Initial bias for the forget gate. Values between 1 and 3 are common. Higher values create better initial gradient flow conditions and are recommended for tasks with long sequences.
- hidden_size: The number of dimensions in the cell state. Larger hidden sizes provide more capacity for both memory storage and gradient flow.
- gradient clip norm: The global gradient norm threshold for clipping. Typically 1.0 to 5.0. Applied to prevent exploding gradients through the hidden state path.
- sequence length: The practical limit for gradient flow depends on the forget gate values. At f=0.95 per step, meaningful gradients survive up to 50 to 100 steps. At f=0.99, up to several hundred steps.
Historical Context and Influence
The constant error carousel appeared in print in 1997, in the journal Neural Computation. At that time, sequence modeling was dominated by Hidden Markov Models and early connectionist approaches, and the vanishing gradient problem was widely acknowledged as a severe obstacle but not yet solved in a principled way. The LSTM paper made several contributions simultaneously: it diagnosed the problem mathematically, designed an architecture that addressed it, and demonstrated the architecture on tasks that required memory of hundreds of timesteps, tasks that were completely out of reach for vanilla RNNs.
The 1997 paper did not yet include the forget gate. The original LSTM used a constant memory cell with only input and output gates, relying on a linear recurrence to prevent gradient decay. The forget gate was added by Gers et al. in 2000 in their "Learning to Forget: Continual Prediction with LSTM" paper. This addition turned out to be critical: without the ability to actively forget, the LSTM cell state would accumulate information indefinitely, causing problems for tasks with natural reset points like paragraph boundaries or topic changes.
The decade following the original paper saw steady but moderate adoption. LSTMs were applied to handwriting recognition, speech recognition, and language modeling, achieving state-of-the-art results in each domain. But the breakthrough that brought LSTMs into mainstream NLP was the sequence-to-sequence architecture introduced by Sutskever et al. in 2014. By using one LSTM to encode a source sentence into a fixed-size hidden state and another LSTM to decode the target sentence from that hidden state, they achieved dramatic improvements in machine translation.
The Attention Mechanism, introduced by Bahdanau et al. in 2015, extended sequence-to-sequence LSTMs further by allowing the decoder to attend to all encoder hidden states, rather than only the final one. This addressed a bottleneck in the LSTM encoder: the final hidden state could only carry a limited amount of information about the full input sequence. Attention made the encoder's entire hidden state sequence available to the decoder, dramatically improving performance on long sentences. The combination of LSTMs with attention became the dominant architecture for sequence-to-sequence tasks until Transformers arrived in 2017.
Understanding this historical progression is valuable because it illuminates the design decisions embedded in modern architectures. The Transformer's attention mechanism can be seen as taking the skip-connection insight from LSTM cell states and the attention insight from Bahdanau to their logical conclusion: every position can directly attend to every other position without any sequential bottleneck. The residual connections in Transformers mirror the LSTM cell state's additive gradient highway. The layer normalization in Transformers addresses the same training stability concern that motivated forget gate bias initialization in LSTMs. These connections are not coincidental; they reflect a continuous evolutionary thread in how the field has approached gradient flow and training stability.
Limitations and Impact
The constant error carousel was a breakthrough when introduced in 1997. It provided a principled solution to the vanishing gradient problem that had stymied sequence modeling for years, and it directly enabled the LSTM to achieve state-of-the-art results on tasks requiring memory of hundreds to thousands of timesteps.
The gradient highway through the cell state does not completely solve the vanishing gradient problem. It relocates the difficulty. Whether gradients can flow depends on the learned forget gate values. If the network doesn't learn to open the gradient highway when needed (either due to poor initialization, a difficult optimization landscape, or irrelevant long-range dependencies), vanishing gradients remain possible. The LSTM provides the capability; training provides the realization.
The residual connection analogy turned out to be deeply predictive. When He et al. introduced ResNets in 2015, they were solving the same problem in feed-forward networks. Transformer architectures then applied residual connections at every sublayer, creating explicit gradient highways throughout the network depth. The principle that "addition enables gradient flow" connects the LSTM cell state, ResNet skip connections, and Transformer layer norms into a unified design philosophy.
One important limitation is that the LSTM cell state gradient highway only helps for the cell state dimension. The hidden state, which is the actual output of the LSTM at each step and the interface with the rest of the network, still experiences more gradient attenuation. For tasks where fine-grained hidden state representations matter (like sequence labeling, where the hidden state at each position is used for prediction), the gradient advantage may be less pronounced than the theory suggests.
Another limitation is computational: the four-gate architecture of the LSTM is computationally expensive compared to vanilla RNNs. Each timestep requires four matrix multiplications instead of one. This cost motivated the development of the GRU (covered in the next chapter), which achieves similar gradient flow improvements with two gates instead of four, reducing computation by roughly half. For tasks where the cell state bottleneck is not needed (tasks with moderate sequence lengths and relatively simple memory requirements), the GRU is often a better choice on computational grounds.
A third limitation is that LSTMs process sequences sequentially: each timestep must complete before the next can start. This sequential dependency prevents parallelization across the time dimension, which is a major performance bottleneck for modern GPU hardware. Transformers, which process all positions simultaneously through matrix operations, are dramatically faster to train on hardware designed for parallel computation. This parallelism advantage, more than any fundamental capability difference, is the primary reason Transformers have displaced LSTMs for most NLP tasks.
Despite these limitations, LSTMs remain the canonical example of how to engineer gradient flow. Their influence extends beyond RNNs: the idea of creating learnable gating mechanisms that can open or close gradient pathways appears in Highway Networks, ResNets, attention mechanisms, and numerous other architectures. Understanding the LSTM gradient flow analysis illustrates a fundamental design principle for deep networks.
The constant error carousel also highlights a broader lesson about neural network design: the gradient flow problem and the representation learning problem are deeply intertwined. A good architecture is not just one that can represent the required computations; it's one where the optimization process can efficiently discover the right parameters. The LSTM showed that these two goals can be addressed together through careful architectural choices, and this insight has guided the design of architectures from ResNets to Transformers.
Summary
The LSTM constant error carousel solves the vanishing gradient problem by creating an additive pathway for gradient flow through the cell state. Key takeaways:
- The cell state update is additive: . Addition copies gradients unchanged, while multiplication scales them.
- The gradient through the cell state path decays only as a product of forget gate values, not as a product of weight matrix Jacobians and nonlinearity derivatives.
- The forget gate plays a dual role: it controls memory retention in the forward pass and modulates gradient magnitude in the backward pass. Learning to retain information means learning to preserve gradients.
- Forget gate bias initialization matters. Biases of 1 to 3 create favorable gradient flow conditions at the start of training and are recommended for tasks with long sequences.
- The cell state gradient path is directly analogous to the residual connection in ResNets: both use addition to create a gradient highway that bypasses the learned transformations.
- Peephole connections allow gates to observe the cell state directly, enabling more precise timing-based control, at the cost of additional parameters.
- Exploding gradients remain possible through the hidden state path. Gradient clipping (norm threshold 1.0 to 5.0) is still recommended for LSTM training on long sequences.
- The GRU, covered in the next chapter, achieves similar gradient flow improvements with a simpler two-gate architecture that reduces computational cost.
- Stacked LSTMs have strong horizontal gradient flow within each layer but may exhibit weaker vertical gradient flow across layers; residual connections between layers address this.
- Bidirectional LSTMs process sequences in both directions and provide representations that capture context from past and future, but cannot be used for online (streaming) prediction.
- LSTMs process sequences sequentially, which prevents parallelization across time and is the primary reason Transformers have displaced them for most NLP tasks at scale.
- The principle that "addition creates gradient highways" connects LSTM cell states, ResNet skip connections, and Transformer residual connections into a unified design philosophy for deep networks.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about LSTM gradient flow and the constant error carousel.
LSTM Gradient Flow Quiz
Reference
Citation details
Cite or share this article.
Continue with the full handbook
This chapter is part of Language AI Handbook. Use the handbook page to browse the complete table of contents and continue reading in sequence.
Explore Language AI HandbookStay up to date
Get articles, book updates, and news delivered to your inbox.
No spam, unsubscribe anytime.
Join the community
Sign in to remove popups, track your reading progress, and join the discussion.

Comments
No comments yet. Be the first to share your thoughts!