Home / Deep Learning

What is LSTM?

By Updated

Take a microscopic look inside a single Long Short-Term Memory cell. Visualize the internal architecture, the conveyor belt, and the four gates that control memory.

Overview

Two states, not one

A simple recurrent cell has one hidden state, and it is completely rewritten at every timestep. An LSTM has two:

  • Cell state Ct — the long-term memory. It is modified only by addition and elementwise multiplication by a gate, never by a full matrix multiply.
  • Hidden state ht — the working output, a filtered view of the cell state, passed to the next layer and the next timestep.

The cell state is the important one. Because it is updated additively, information placed there at timestep 1 can reach timestep 500 essentially untouched — there is no repeated matrix multiplication to shrink it.

Waiting for Data...

Internal Flow

$C_{t-1} \to C_t$ (Cell State)
$H_{t-1} \to H_t$ (Hidden State)
$X_t$ (New Input Data)
Neural Network Gates (W)
Mathematical Operations
$\times$
Pointwise Multiplication
$+$
Pointwise Addition

What is LSTM?: A Practical Guide

An LSTM adds a separate memory channel that information can travel along unchanged, plus three learned gates deciding what to erase, what to add, and what to reveal. That additive path is why it remembers hundreds of steps.

The three gates

Each gate is a small sigmoid layer producing values in [0, 1], which then multiply a vector elementwise — 0 blocks completely, 1 passes completely, and everything between is a partial pass.

ft = σ(Wf·[ht−1, xt] + bf)   forget

it = σ(Wi·[ht−1, xt] + bi)   input

ot = σ(Wo·[ht−1, xt] + bo)   output

The cell state update is then two operations — erase, then write:

Ct = ft ⊙ Ct−1 + it ⊙ C̃t

ht = ot ⊙ tanh(Ct)

In a language model the forget gate might drop the previous subject’s gender when a new subject appears, the input gate writes the new one, and the output gate exposes it only when a pronoun actually needs to agree.

Why the gradient survives

The whole design rests on the additive update. Differentiating Ct with respect to Ct−1 gives ft — the forget gate itself, not a weight matrix.

So the gradient flowing back through the cell state is multiplied by the forget gate at each step. When the network learns to keep something, the forget gate sits near 1, and multiplying by roughly 1 many times preserves the gradient. Compare that with a simple RNN, where the same path is multiplied by Wh and a tanh derivative every step and decays geometrically.

This is the same principle as a residual connection: give the gradient an uninterrupted additive route, and depth stops destroying it.

A cell with a memory it can protect

A plain recurrent network overwrites its hidden state at every step. Whatever it knew about word one is repeatedly transformed, and after fifty steps almost nothing survives — gradients decay along the same path, so it cannot learn long-range dependencies either.

An LSTM adds a second, separately protected state: the cell state, which travels along the sequence with only additive updates and multiplicative gates deciding what enters and leaves.

Two states, two jobs:

  • Cell state c — long-term memory. Modified by addition, not by rewriting.
  • Hidden state h — the working output at each step, derived from the cell state.

Three gates control the flow, each a small neural network with a sigmoid output between 0 and 1 — 0 meaning "block completely", 1 meaning "let everything through":

GateQuestion it answers
ForgetWhat should I drop from memory?
InputWhat new information should I store?
OutputWhat part of memory should I expose now?

The equations, read as sentences

fᵗ = σ(Wᶠ·[hᵗ₋₁, xᵗ] + bᶠ)    forget gate

iᵗ = σ(Wᵢ·[hᵗ₋₁, xᵗ] + bᵢ)    input gate

gᵗ = tanh(Wᵕ·[hᵗ₋₁, xᵗ] + bᵕ)   candidate memory

cᵗ = fᵗ ⊙ cᵗ₋₁ + iᵗ ⊙ gᵗ    update the cell

oᵗ = σ(Wₒ·[hᵗ₋₁, xᵗ] + bₒ)    output gate

hᵗ = oᵗ ⊙ tanh(cᵗ)    produce the output

The line that matters most is the cell update. It is old memory scaled by the forget gate, plus new memory scaled by the input gate. Both operations are elementwise, so each dimension of the cell state is managed independently — one dimension can hold grammatical number while another tracks sentiment.

Note the two activations doing different jobs. Sigmoid produces gates, because a gate needs to be a fraction between 0 and 1. Tanh produces content, because content should be able to be negative.

Why this fixes vanishing gradients

In a plain RNN, the gradient flowing back through k steps is a product of k Jacobian factors. If those average below 1, the product decays exponentially.

The LSTM's cell state has a path where the derivative of cₜ with respect to cₜ₋₁ is simply the forget gate fₜ. If the forget gate is near 1 — the network has learned to keep this information — the gradient passes back essentially unchanged.

That is the same structural idea as a residual connection: an additive path with a derivative near 1, protecting the gradient from the multiplicative decay. It is why LSTMs handled sequences of hundreds of steps where plain RNNs managed ten.

It reduces the problem rather than eliminating it. Very long dependencies remain hard, and exploding gradients still occur, which is why gradient clipping is standard when training recurrent models.

The whole cell, one timestep at a time

An LSTM cell is four small networks and one running memory. All four are computed here on a real sequence, with the cell state printed at every step so you can see what it carries.

example_01.pyNumPy
Output

Experiments to try

  1. Count the cost of gating. Press Parameters and compare with a plain RNN of the same size. An LSTM has four weight matrices instead of one — three gates plus the candidate — so it needs roughly four times the parameters.
  2. Grow the state. Raise State Size and watch the count climb. Each of the four blocks is (d + h) × h, so the total is 4[(d + h)h + h].
  3. Follow one timestep. Press Simulate Cell Operation and trace the cell state along the top. It passes straight through, touched only by a multiply and an add — that unbroken line is the long-term memory path.
  4. Watch the gates open and close. During the simulation note that gate values are between 0 and 1 rather than binary. Gating is continuous, which is what makes it differentiable and therefore learnable.

Traps worth knowing

  • Initialising the forget-gate bias at zero. That puts the gate at 0.5, halving the cell state every step and destroying memory before training can fix it. Initialise it to 1 or 2 so the cell starts out remembering.
  • Reaching for an LSTM by default. A GRU merges the forget and input gates into one, uses about 25% fewer parameters, trains faster, and performs comparably on most tasks. Try it first.
  • Confusing cell state with hidden state. PyTorch returns both as a tuple; passing the wrong one to the next layer is a common and quiet bug.
  • Using an LSTM where attention belongs. For long documents a transformer both remembers further and parallelises, which an LSTM cannot.

In one line

An LSTM separates long-term memory (the cell state) from working output (the hidden state) and controls the flow between them with three learned sigmoid gates. Because the cell state is updated by addition and gated multiplication rather than a matrix multiply, the gradient travels back through it multiplied only by the forget gate — so when the model chooses to remember, it genuinely can, for hundreds of steps. The cost is four times the parameters of a simple cell, and a GRU usually gets most of the benefit for less.

Using one, and the shapes involved

import torch.nn as nn

lstm = nn.LSTM(input_size=300,       # embedding dimension
               hidden_size=256,
               num_layers=2,
               batch_first=True,
               bidirectional=False,
               dropout=0.2)          # applies between layers only

out, (h, c) = lstm(x)                # x: (batch, seq, 300)
# out: (batch, seq, 256)   -- the hidden state at every step
# h, c: (layers, batch, 256) -- the final states

Which output you use depends on the task. For classification, take the final hidden state (or a pooled version of all steps). For tagging or sequence-to-sequence, use the full out tensor.

Parameter count is worth knowing, because it explains why LSTMs are heavier than they look: four gates each need a weight matrix over the concatenated input and hidden state, giving 4 × ((input + hidden) × hidden + hidden). For 300-dimensional input and 256 hidden units that is about 570,000 parameters per layer.

For variable-length batches, use pack_padded_sequence so the LSTM does not process padding — otherwise the final hidden state reflects the padding rather than the last real token.

LSTM, GRU or transformer?

 LSTMGRUTransformer
Gates32None — attention instead
ParametersMost~25% fewerMost of all
Long-range dependenciesGoodGoodBest
Parallel across the sequenceNoNoYes
Streaming / constant memoryYesYesNo — KV cache grows
Small-data performanceGoodGoodNeeds more data

GRU merges the forget and input gates into a single update gate and drops the separate cell state. Fewer parameters, slightly faster, and empirically comparable on most tasks — the choice between them is usually not worth agonising over.

Transformers won for large-scale language work because they parallelise across the sequence and have constant path length between positions. But LSTMs remain a sensible choice for streaming inference with bounded memory, for small datasets, for on-device models, and for classical time-series work.

Questions people ask

Are LSTMs obsolete? Superseded for large-scale language modelling; still practical for streaming, small data, embedded use and time series.

What is the difference between the cell state and the hidden state? The cell state is protected long-term memory updated additively; the hidden state is the filtered output exposed at each step.

How many layers? One or two for most tasks. Deep stacks of LSTMs are hard to train and rarely pay off.

Why tanh and sigmoid rather than ReLU? Sigmoid bounds gates to 0–1, which is what a gate requires. Tanh bounds content to −1–1, which keeps the repeatedly-applied recurrence stable.

Do I need gradient clipping? Yes — recurrent models are the classic case for it.

Should I use a bidirectional LSTM? For classification and tagging where the whole input is available, yes — it usually helps. Never for generation or streaming, where the future is not available.

Recap in one screen

  • Two states: a protected cell state for long-term memory, a hidden state for the working output.
  • Three sigmoid gates decide what to forget, what to store and what to expose.
  • The cell updates additively, so ∂cₜ/∂cₜ₋₁ is the forget gate — near 1 means the gradient survives.
  • That additive path is the same idea as a residual connection, and it is what fixed vanishing gradients.
  • Superseded by transformers at scale; still the right tool for streaming, small data and on-device work.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. Without scrolling back — what is the one-line takeaway from this module?

  2. What does this module say about “Two states, not one”?

  3. What does this module say about “The three gates”?

Cheat sheet

What is LSTM?

Take a microscopic look inside a single Long Short-Term Memory cell. Visualize the internal architecture, the conveyor belt, and the four gates that control memory.

NLP · vizlearn.in/natural_language_processing/what_is_lstm.html

Further reading

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.