LSTM, step by step.
All five chapters, including worked answers and static lab comparisons. This edition loads no JavaScript.
01
Remembering a sequence
A later decision may depend on an earlier event. A recurrent state carries something forward.
The cue is no longer in front of you
Imagine six events: a cue, two quiet gaps, a counter-cue, another gap, and a request to read the state. At the last step, the current event says only “read.” To respond to the earlier cue, a system needs a state that survives between steps.
We will use this invented sequence throughout. Its event names are a teaching story, not text being encoded by a trained model. Later, we will prescribe one numerical coordinate and inspect exactly what survives, changes, and becomes visible.
Invented signal story, not trained behavior. The signed stems mark the two candidate writes used later in the lab; their time positions stay fixed. Whether either cue survives depends on the state updates.
The question is not just whether the first cue can persist. What should happen when the counter-cue arrives? And can stored state remain present even when the system exposes nothing?
One update, used repeatedly
A recurrent neural network, or RNN, updates a state using the current input and a previous state. The same learned parameters are reused at successive positions; the inputs and states change. The state is a numerical representation, not a literal archive of every earlier event. See the recurrent update and unrolled computation in Pascanu, Mikolov, and Bengio, §1.1.
Write the current input vector as and the hidden state as . The subscript counts sequence steps. An update takes and and produces , which becomes available to the next step.
A plain tanh RNN, in one equation
One common baseline mixes the input and previous hidden state, then applies , a function that squashes each value between −1 and 1:
The matrices and bias are learned parameters. They have no time subscript because this update reuses them. This is a plain tanh RNN, not the definition of every recurrent architecture. The PyTorch RNN equations use the same idea, with the bias written in two parts.
Separate carrying from exposing
An LSTM—Long Short-Term Memory—is itself an RNN architecture. Its update separates a carried cell state from an exposed hidden state, using learned multipliers called gates. We will study the standard form shown in the LSTM equations, without peephole connections or an output projection.
Start with what one step computes. Once the distinction between storage and exposure is clear, the sequence—and the reason this structure can help learning—will be easier to follow.
02
Inside the cell
Keep some old state, add a proposed write, then decide how much to expose.
Two states, three different jobs
The cell state is the carried state. The hidden state is a transformed, gated view of it. Both are vectors with coordinates; the input has coordinates. We use column vectors.
The gates act coordinate by coordinate, not as one global yes/no decision:
- Forget gate : how much of the previous cell value to retain.
- Input gate : how much of a proposed value to write. That proposal is the candidate , which can be positive or negative.
- Output gate : how much of the transformed cell value to expose as hidden state.
A gate value is a multiplier, not a probability that an event is true or important. The candidate is not a fourth sigmoid gate.
Retain + write = new cell state
First multiply the old cell state by the forget gate. Separately multiply the candidate by the input gate. Add those contributions:
The symbol means elementwise multiplication: multiply matching coordinates. Then expose part of a squashed version of the new state:
Follow the heavy cell-state route: multiply, then add. The branch to h reads the new cell through tanh and the output gate. This diagram shows update arithmetic; chapter 5 gives the shared learned gate calculations.
These are the standard cell and hidden-state updates. Notice the addition: admitting a candidate does not automatically replace the old state. A negative write can offset a positive retained value. The forget and input gates are separate; they do not have to sum to one.
Bounded multipliers, not a bounded cell
A learned cell computes its gates with sigmoid and its candidate with tanh. For finite real inputs, mathematical sigmoid is strictly between 0 and 1, and tanh is strictly between −1 and 1. These ranges follow from their sigmoid and tanh definitions; floating-point saturation can round to an endpoint.
That does not bound to this interval: its update adds two terms. For example, an old cell value of 1 with becomes . The standard hidden state is bounded coordinatewise between −1 and 1 because it uses and an output multiplier.
Holding the other gate and candidate values fixed, changing changes current , not current . In a learned recurrent cell, however, helps compute future gates, so later cell states can change. Our next experiment deliberately removes that feedback to isolate the arithmetic.
Why specify which LSTM?
The name covers a family. Hochreiter and Schmidhuber's 1997 LSTM used input/output gates and a fixed cell self-connection. The later forget-gate extension is described in Gers, Schmidhuber, and Cummins's 2000 journal paper. The exact modern equations above should not be attributed unchanged to the original paper.
03
Gates over time
Keep the six events fixed. Change one multiplier and trace the consequence.
A controlled coordinate—not a trained model
This lab directly prescribes one scalar coordinate, starting from . The candidate sequence is +1, 0, 0, −1, 0, 0. The first input gate is 1; the counter-cue's input gate is the control ; the others are zero. The same selected and apply at all six steps.
There are no trained weights, text encoder, or learning algorithm here. Exact gate values 0 and 1, and candidates −1 and 1, are idealized limiting values chosen to make retention and cancellation inspectable—not finite mathematical sigmoid/tanh outputs.
Before changing anything, predict: if you set output exposure to zero, will the cell state disappear too? Then compare the cell and hidden traces. The step control selects a calculation to inspect; it does not change the trajectory.
Keep. Write. Expose.
One scalar cell · prescribed gates · no trained network
Make a prediction (optional)
● Cell c□ Hidden h
Fixed scale for this toy. Overlapping circle/square marks mean the states coincide. Select a step below.
Step 4 · counter-cue Previous cell 0.810 · candidate -1.000
Hidden h = 1.0 × tanh(0.729) = 0.622
The counter-cue proposes −1. The input multiplier admits 0.0 of that negative write; it is added to retained memory.
Step 4: cell 0.729, hidden 0.622. Final cell 0.590, hidden 0.530. The counter-cue is blocked; the original cue is only scaled by retention. Changing output leaves c unchanged here because future gates are prescribed independently of h.
Gates and candidates are hand-set, independently of h. Exact gate 0/1 and candidate ±1 are limiting idealizations, not finite-real sigmoid/tanh values. This is forward arithmetic, not training or a measured gradient. Calculations use full precision; visible values round to three decimals. A learned LSTM can feed h into future gates, unlike this experiment.
Inspect every step's values
| Step / event | g | i | c | h |
|---|---|---|---|---|
| 1 · cue | 1.000 | 1.000 | 1.000 | 0.762 |
| 2 · gap | 0.000 | 0.000 | 0.900 | 0.716 |
| 3 · gap | 0.000 | 0.000 | 0.810 | 0.670 |
| 4 · counter-cue ← inspecting | -1.000 | 0.000 | 0.729 | 0.622 |
| 5 · gap | 0.000 | 0.000 | 0.656 | 0.576 |
| 6 · read | 0.000 | 0.000 | 0.590 | 0.530 |
Static comparisons: keep, fade, cancel, hide
Same prescribed sequence; different multipliers. These final-step comparisons remain available without scripts.
| Case | f | i₄ | o | c₆ | h₆ |
|---|---|---|---|---|---|
| Keep the cue | 1.0 | 0.0 | 1.0 | 1.000 | 0.762 |
| Let it fade | 0.5 | 0.0 | 1.0 | 0.031 | 0.031 |
| Admit counter-cue | 1.0 | 1.0 | 1.0 | 0.000 | 0.000 |
| Close output | 1.0 | 0.0 | 0.0 | 1.000 | 0.000 |
Closing output hides the cell from h; it does not erase the toy cell. Admitting the equal, opposite counter-cue at f=1 cancels the cell rather than proving that nothing was written.
Follow the first write
At the defaults, , , and . The first write makes . Each later step keeps nine tenths of what remains, with no new write. At the selected fourth step:
There are three transitions after the first write—not four. Lower and watch that contribution fade faster. Set to see idealized perfect retention in this fixed-gate example. Neither curve measures a trained model's ability to remember a task.
A write can oppose what is already there
With , raise from 0 to 1. Step 4 admits the candidate −1: the retained +1 and the written −1 cancel. The resulting zero does not mean that nothing was written.
Now set and lower to zero. Every hidden value becomes zero, while the cell retains the cue. In this toy, future gates and candidates are prescribed independently of hidden state, so the entire cell trajectory is unchanged. A learned LSTM need not preserve that future invariance.
Track both contributions to the final step
The first write crosses five subsequent transitions to reach step 6. The negative write at step 4 crosses two. Their contributions add:
With the defaults, . The display rounds to three decimals; calculations use the unrounded values. This is an exact decomposition of the prescribed sequence, not a general formula for every LSTM input.
Repeated multiplication explains forward retention. A related question appears during training: can a later error still influence an earlier computation?
04
A path for gradients
The carry route can preserve a learning signal. It does not guarantee unlimited memory or easy training.
Two directions, two different questions
In a forward pass, we ask: what state results from these inputs? During training, we also ask: how would a small change in an earlier quantity affect a later loss? A derivative expresses local sensitivity; gradients collect such sensitivities for the parameters being trained.
Across many recurrent steps, gradient contributions involve products of stepwise derivatives. These can shrink or grow strongly, making optimization difficult—the vanishing and exploding gradient problems. This is not simply another name for a stored number fading in the forward pass. Pascanu, Mikolov, and Bengio, §§1–2 analyze these temporal products.
Isolate the direct carry path
Look only at the direct cell-state route and hold gate and candidate values fixed. A small change then passes through the carry term as:
For one scalar coordinate, call the sensitivity along this restricted path from step to step . Applying the chain rule repeatedly gives:
The product symbol means “multiply the forget values over these transitions.” Near-one factors can preserve this route's sensitivity better than repeatedly multiplying by small factors. This calculation is not the full recurrent derivative: it leaves out paths through hidden states and learned gate/candidate computations.
Derived fᵏ, with no new writes and gates held fixed. The same product describes the direct cell-state sensitivity under those assumptions—not the full LSTM gradient or measured memory performance. k counts transitions after the starting value; f=1 is an idealized limit.
What the curves do—and do not—show
With constant , the restricted sensitivity after transitions is . The same factor describes the forward retention of an existing cell contribution when no new writes occur:
These two interpretations share an algebraic factor, but answer different questions. The figure is an analytic fixed-gate comparison, not a measured training curve, gradient norm, or memory-capacity score.
The additive cell route provides a way for a signal to travel without repeatedly traversing a squashing operation on that route. Learned gates, other recurrent paths, the output transformation, and the task loss still matter. An LSTM does not eliminate every vanishing or exploding gradient problem, or guarantee that a distant cue will be learned.
So far we have chosen multipliers by hand. To turn this mechanism into a model, the next question is who chooses them—and how.
05
From cell to model
Learned weights choose the gates. A separate task readout turns hidden features into a prediction.
The same weights, new decisions
In the standard cell, concatenate the previous hidden state and current input into . The semicolon means stacking the column vectors. Learned weighted sums plus biases produce three gates and the candidate:
Here is sigmoid. These are the standard gate equations written with combined input/hidden matrices. The previous cell state enters the subsequent retain/write update; it does not directly enter these gate equations in our no-peephole variant.
Check the vector sizes
With input width and state width , has coordinates. Each combined matrix has shape , and each bias has coordinates. Thus every gate and candidate has the same width as the cell state.
This is a mathematical convention, not a requirement for a library's physical weight or bias layout. Each coordinate gets its own multipliers; they need not correspond to human-named facts.
The parameters are shared across steps, but and vary, so the resulting gates can vary. An ordinary forward pass changes states, not weights. Training uses a loss, computes gradients through the unrolled computation—backpropagation through time, or BPTT—and updates the shared parameters. See §1.1 and Fig. 2; our lab performs none of that training.
The output gate is not the answer
An LSTM produces hidden-state features. A separate task readout can turn selected features into a prediction—for example, a forecast at each step or a classification from a final hidden state. That design choice is distinct from the internal output gate. The documented LSTM outputs are states; Gers et al., §2.1, Eq. (7) give an example with a separate output layer.
In our cue story, “read” is only an inspection point. No task head interprets the cell as a word, an answer, or a probability. To build a predictive system, we would need an input representation, a readout, a training objective, and evaluation on the actual task.
Try a new update
Leave the lab's fixed sequence. Suppose the previous cell value is , with , , , and . What are the retained contribution, written contribution, new cell state, and hidden state?
Then stipulate one more step with , , and . What becomes visible? The exact endpoints are the same idealization used in the lab.
Work through the answer
The hidden value is zero, but the cell value is not. At the stipulated next step, the entire cell value is retained and no new value is written:
A closed output gate did not erase the current cell. We could read it later because the next gates were stipulated. A learned recurrent model could choose different next gates as a consequence of the changed hidden state.
Keep the mechanism in view
An LSTM is a learned recurrent update with a useful separation: retain old state, write a candidate, expose a transformed view. Cell state and hidden state are related, but not interchangeable.
When reading an LSTM diagram or implementation, trace those two states first. Then ask what computes the gates, where the prediction comes from, and which assumptions support any claim about long-term memory.
Glossary
- LSTM
- Long Short-Term Memory, a recurrent neural-network architecture. This guide uses separate forget, input, and output gates, a tanh candidate, and no peepholes or projection.
- Recurrent state
- A numerical state passed between sequence steps. Shared parameters update it from new input and previous state.
- Input
- The current input vector, with coordinates in this guide. The lab's event labels are not encoded text.
- Cell state
- The carried vector updated by adding a retained contribution and a gated candidate. It is not globally constrained to the tanh range.
- Hidden state
- The exposed vector in the standard non-projected form. It also feeds future gate and candidate computations.
- Forget gate
- A coordinatewise multiplier on the previous cell state. Larger values retain more of that value at the current step.
- Input gate
- A coordinatewise multiplier on the candidate write. It need not be the complement of the forget gate.
- Candidate
- A proposed signed value, computed with tanh in the standard cell. It is distinct from the sigmoid gates.
- Output gate
- A multiplier controlling exposure as current hidden state—not the model's final answer. A change can affect later learned gates through hidden-state feedback.
- Elementwise product
- Multiplication of matching vector coordinates, preserving the vector's shape.
- Sigmoid and tanh
- Activation functions. For finite real inputs, sigmoid lies strictly in and tanh in . Exact endpoints in the lab are prescribed idealizations.
- Direct-path sensitivity
- The derivative along the explicit cell carry route when gates and candidates are held fixed. Its forget-gate product is not the full recurrent derivative.
- BPTT
- Backpropagation through time: differentiating the unrolled recurrent computation to obtain loss gradients for shared parameters.
- Task readout
- A separate transformation from chosen hidden features to predictions appropriate to a task. No task head is executed here.
Sources
- PyTorch 2.8 — LSTM
Opening equations, input/output definitions, and projection distinction. Source for the standard no-peephole, non-projected update taught here; not a claim about the latest release.
- PyTorch 2.8 — RNN
Plain tanh recurrent update and parameter reuse in the time loop. LSTM is also an RNN architecture.
- On the difficulty of training recurrent neural networks
Pascanu, Mikolov, and Bengio (2013), §§1–2, equations (1)–(5), and Fig. 2. Unrolled computation, BPTT, and temporal gradient products; not evidence that this toy trained a network.
- Long Short-Term Memory
Hochreiter and Schmidhuber (1997), §4 and Fig. 1. Historical original architecture, not the exact modern forget-gate equations.
- Learning to Forget: Continual Prediction with LSTM
Gers, Schmidhuber, and Cummins (2000). Journal record for the later forget-gate extension; this date is not a claim of first public appearance.
- Learning Precise Timing with LSTM Recurrent Networks
Gers, Schraudolph, and Schmidhuber (2002), §§2–3. Forget-gate history, cell-output feedback, and a separate output layer. Its own output equation differs from this guide, so it is not the source for our tanh hidden-state equation.
- PyTorch 2.8 — Sigmoid
Function definition supporting the finite-real range of gate multipliers.
- PyTorch 2.8 — Tanh
Function definition supporting the finite-real candidate and squashed-state ranges.