LSTM Gradient Flow › Worked Numerical Example: Tracing a Gradient Through the Cell State
Language AI HandbookAll chapters LSTM Gradient Flow › Worked Numerical Example: Tracing a Gradient Through the Cell StateOne section · Sections in this chapter4 / 17 ↓
Reading tools Definitions & inline links
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
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.