Sign in

Long short-term memory (LSTM)

Long Short-Term Memory

Long short-term memory: a recurrent network with a gated cell state that carries information across many steps.

Overview

A recurrent network reads a sequence step by step and keeps a memory of what it has seen. In a plain recurrent network that memory is rewritten through a squashing function at every step, so early information and its gradient fade away fast. An LSTM keeps a second memory, the cell state, which is changed only by two gentle operations: scaling it down a little, and adding something new. Three gates, each a set of values between 0 and 1, control this. The forget gate decides what to keep, the input gate what to write, and the output gate what to reveal to the rest of the network. A value the forget gate keeps near 1 can survive for hundreds of steps.

A short history

Sepp Hochreiter and Jürgen Schmidhuber published the LSTM in 1997 to solve the vanishing gradient problem, which stopped plain recurrent networks from learning long-range dependencies. Felix Gers, Schmidhuber and Fred Cummins added the forget gate around 2000. Between about 2014 and 2017 LSTMs led speech recognition, handwriting recognition and machine translation, including Google's neural translation system of 2016, before Transformers displaced them.

How it works

  1. Start with a hidden state h0\mathbf{h}_0 and a cell state c0\mathbf{c}_0 of zeros.
  2. At each step compute the input gate it\mathbf{i}_t, forget gate ft\mathbf{f}_t and output gate ot\mathbf{o}_t with a sigmoid, and the candidate gt\mathbf{g}_t with tanh, all from xt\mathbf{x}_t and ht−1\mathbf{h}_{t-1}.
  3. Update the cell: ct=ft⊙ct−1+it⊙gt\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \mathbf{g}_t.
  4. Expose part of it as the hidden state: ht=ot⊙tanh⁡(ct)\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t).
  5. After the last step, pass the final hidden state through a dense layer: softmax for classification or a linear output for regression.
  6. Backpropagate through time to get the gradients, rescale them if their norm exceeds clip_norm, and update with Adam.

Watch out for

  • If the forget gate starts near 0.5, the cell loses half its content at every step and the network never learns long dependencies. A positive forget_bias keeps memory open early in training.
  • The additive cell stops gradients from vanishing but not from exploding, so a single batch can produce a huge step. Gradient clipping is there for that reason.
  • All sequences must have the same length, because this template has no masking. Zero padding is processed as real input.
  • An LSTM has four sets of gate weights and processes steps in order, so it is slower than a GRU and cannot be parallelised over time.

Use cases

When to use it

Sequence problems that need memory over tens to hundreds of steps: time series, event logs, short texts. Prefer it to a plain recurrent network, and to a GRU when the separate cell state helps.

In industry

Speech and voice
Speech recognition: mapping a stream of audio frames to text, a leading use of LSTMs in the mid 2010s.
Finance and operations
Forecasting a time series from a long window of past values and related signals.
Healthcare
Predicting patient deterioration from sequences of vital signs and lab results recorded over a stay.

Choosing it: what must hold

  • Ordered data in which information from many steps back still matters.
  • Enough training sequences to fit four sets of gate weights per layer.
  • Acceptance of step-by-step processing, which is slower to train than attention on parallel hardware.

When to choose something else

IfUse instead
You have a large corpus and need long contextA Transformer
You want fewer parameters and similar accuracyA GRU
Dependencies are short, a handful of stepsA plain RNN, or a model on a fixed window of lag features

Math foundations

  1. The three gates

    it=σ(Wixt+Uiht−1+bi),ft=σ(Wfxt+Ufht−1+bf),ot=σ(Woxt+Uoht−1+bo)\mathbf{i}_t = \sigma\big( W_i \mathbf{x}_t + U_i \mathbf{h}_{t-1} + \mathbf{b}_i \big), \quad \mathbf{f}_t = \sigma\big( W_f \mathbf{x}_t + U_f \mathbf{h}_{t-1} + \mathbf{b}_f \big), \quad \mathbf{o}_t = \sigma\big( W_o \mathbf{x}_t + U_o \mathbf{h}_{t-1} + \mathbf{b}_o \big)

    Each gate is a vector of values between 0 and 1, one per hidden unit, computed from the current input and the previous hidden state.

  2. Candidate content

    gt=tanh⁡(Wgxt+Ught−1+bg)\mathbf{g}_t = \tanh\big( W_g \mathbf{x}_t + U_g \mathbf{h}_{t-1} + \mathbf{b}_g \big)

    The new information that could be written to the cell, with values between -1 and 1.

  3. Cell state update

    ct=ft⊙ct−1+it⊙gt\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \mathbf{g}_t

    Keep a share of the old memory and add a share of the candidate. This additive form is the core of the LSTM.

  4. Hidden state

    ht=ot⊙tanh⁡(ct)\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)

    The output gate decides how much of the squashed cell is shown to the next step and to the output layer. The cell can hold a value without revealing it.

  5. Why gradients survive

    ∂ct∂ct−1=diag⁡(ft)+…⟹∂cT∂ck≈∏t=k+1Tdiag⁡(ft)\frac{\partial \mathbf{c}_t}{\partial \mathbf{c}_{t-1}} = \operatorname{diag}(\mathbf{f}_t) + \dots \qquad \Longrightarrow \qquad \frac{\partial \mathbf{c}_T}{\partial \mathbf{c}_k} \approx \prod_{t=k+1}^{T} \operatorname{diag}(\mathbf{f}_t)

    Along the cell, the gradient from one step to the previous is just the forget gate, with no weight matrix and no squashing. The omitted terms pass through the gates. With the forget gate near 1 the product stays near 1 over many steps.

  6. Gradient clipping

    g←g⋅min⁡(1,  c∥g∥)\mathbf{g} \leftarrow \mathbf{g} \cdot \min\left( 1,\; \frac{c}{\|\mathbf{g}\|} \right)

    Here g\mathbf{g} stands for all gradients as one vector. If its norm exceeds the limit cc it is scaled down to that norm, keeping its direction.

Symbols

xt\mathbf{x}_t
input at step t
ht\mathbf{h}_t
hidden state after step t
ct\mathbf{c}_t
cell state after step t
it,ft,ot\mathbf{i}_t, \mathbf{f}_t, \mathbf{o}_t
input, forget and output gates
gt\mathbf{g}_t
candidate content for the cell
W,U,bW, U, \mathbf{b}
input weights, recurrent weights and biases, one set per gate
σ\sigma
the sigmoid function
⊙\odot
element-wise product
TT
number of steps in the sequence
cc
clip_norm, the limit on the gradient norm

Worked by hand

One hidden unit with previous cell state ct−1=1.0c_{t-1} = 1.0. At this step ft=0.9f_t = 0.9, it=0.5i_t = 0.5, gt=0.4g_t = 0.4 and ot=0.6o_t = 0.6. Then compare how much gradient survives 20 steps along the cell for two values of the forget gate.

ct=0.9⋅1.0+0.5⋅0.4=0.9+0.2=1.1c_t = 0.9 \cdot 1.0 + 0.5 \cdot 0.4 = 0.9 + 0.2 = 1.1
ht=0.6⋅tanh⁡(1.1)=0.6⋅0.8005=0.480h_t = 0.6 \cdot \tanh(1.1) = 0.6 \cdot 0.8005 = 0.480
0.920=0.122,0.9920=0.8180.9^{20} = 0.122, \qquad 0.99^{20} = 0.818

The cell keeps most of its old value and adds a little. The cell holds 1.1 but shows only 0.48. Over 20 steps a forget gate of 0.9 passes 12 percent of the gradient and one of 0.99 passes 82 percent, which is why the forget gate should start open.

Visual example

Loading the example.

Try this

  • Raise the forget gate bias to 4.6, then lower it to 0, and compare what is left of step 1 at step 20.
  • Lower the output gate bias to -3: the cell keeps its value but the hidden state hides it.
  • Click each gate in the diagram, then move the inspected step to 2 to see the input gate close.

Code sample

import numpy as np
from impl import LSTM
from config import LSTMConfig

rng = np.random.default_rng(0)
y = rng.integers(0, 3, size=300)
X = rng.normal(0, 0.3, size=(300, 20, 3))              # (n, steps, features)
X[:, 0, :] = np.eye(3)[y]                              # the label is shown only at the first step
net = LSTM(LSTMConfig(hidden_size=16, epochs=30)).fit(X, y)
print((net.predict(X) == y).mean())                    # it has to remember across 20 steps
print(net.hidden_states(X[:2]).shape)                  # (2, 20, 16)
Read the implementation (167 lines)
"""LSTM: long short-term memory network for sequences.

NumPy only, backpropagation through time written by hand. One LSTM layer reads a sequence step by step and a
dense layer maps its last hidden state to the output.

    i_t = sigmoid(...)   input gate        f_t = sigmoid(...)   forget gate
    g_t = tanh(...)      candidate         o_t = sigmoid(...)   output gate
    c_t = f_t * c_{t-1} + i_t * g_t        cell state: the additive path that carries long-range memory
    h_t = o_t * tanh(c_t)

Each gate is computed from x_t W + h_{t-1} U + b.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import LSTMConfig
except ImportError:  # run from the template's own folder
    from config import LSTMConfig


def _sigmoid(z: np.ndarray) -> np.ndarray:
    return 1.0 / (1.0 + np.exp(-np.clip(z, -60.0, 60.0)))


def _softmax(z: np.ndarray) -> np.ndarray:
    e = np.exp(z - z.max(axis=1, keepdims=True))
    return e / e.sum(axis=1, keepdims=True)


class LSTM:
    """Sequence model: LSTM layer, then a dense output on the last hidden state.

    task "classification": softmax and cross-entropy. task "regression": linear output and squared error.
    Parameters live in `params`: W (d, 4H), U (H, 4H), b (4H,) with the gates stacked in the order i, f, g, o,
    and the output layer V (H, k), c (k,).
    """

    def __init__(self, config: LSTMConfig | None = None) -> None:
        self.config = config or LSTMConfig()
        self.params: dict[str, np.ndarray] = {}
        self.classes_: np.ndarray | None = None
        self.loss_history: list[float] = []

    def _init_params(self, n_in: int, n_out: int) -> None:
        H = self.config.hidden_size
        rng = np.random.default_rng(self.config.seed)
        b = np.zeros(4 * H)
        b[H:2 * H] = self.config.forget_bias  # start with the forget gate open so memory survives early training
        self.params = {
            "W": rng.normal(0.0, np.sqrt(1.0 / n_in), size=(n_in, 4 * H)),
            "U": rng.normal(0.0, np.sqrt(1.0 / H), size=(H, 4 * H)),
            "b": b,
            "V": rng.normal(0.0, np.sqrt(1.0 / H), size=(H, n_out)),
            "c": np.zeros(n_out),
        }

    def forward(self, X: np.ndarray) -> tuple[np.ndarray, list]:
        """X: (n, T, d) -> (output (n, k) before any softmax, per-step cache). Initial h and c are zero."""
        X = np.asarray(X, dtype=float)
        H = self.config.hidden_size
        W, U, b = self.params["W"], self.params["U"], self.params["b"]
        h = np.zeros((X.shape[0], H))
        c = np.zeros((X.shape[0], H))
        cache = []
        for t in range(X.shape[1]):
            x = X[:, t, :]
            a = x @ W + h @ U + b
            i = _sigmoid(a[:, :H])
            f = _sigmoid(a[:, H:2 * H])
            g = np.tanh(a[:, 2 * H:3 * H])
            o = _sigmoid(a[:, 3 * H:])
            c_new = f * c + i * g
            tanh_c = np.tanh(c_new)
            cache.append((x, h, c, i, f, g, o, tanh_c))
            h, c = o * tanh_c, c_new
        return h @ self.params["V"] + self.params["c"], cache + [h]

    def hidden_states(self, X: np.ndarray) -> np.ndarray:
        """Hidden state after every step. X: (n, T, d) -> (n, T, H)."""
        _, cache = self.forward(X)
        return np.stack([step[1] for step in cache[1:-1]] + [cache[-1]], axis=1)

    def loss_and_grads(self, X: np.ndarray, T: np.ndarray) -> tuple[float, dict]:
        """Loss on a batch and its gradients by backpropagation through time.

        X: (n, T, d). T: (n, k) one-hot rows (classification) or values (regression).
        Returns (loss, {parameter name: gradient}).
        """
        U = self.params["U"]
        out, cache = self.forward(X)
        h_last = cache[-1]
        n_rows = len(out)
        if self.config.task == "classification":
            P = _softmax(out)
            loss = float(-np.sum(T * np.log(P + 1e-12)) / n_rows)
            d_out = (P - T) / n_rows
        else:
            loss = float(np.sum((out - T) ** 2) / n_rows)
            d_out = 2.0 * (out - T) / n_rows
        grads = {"V": h_last.T @ d_out, "c": d_out.sum(axis=0), "W": np.zeros_like(self.params["W"]),
                 "U": np.zeros_like(U), "b": np.zeros_like(self.params["b"])}
        dh = d_out @ self.params["V"].T
        dc = np.zeros_like(dh)
        for x, h_prev, c_prev, i, f, g, o, tanh_c in reversed(cache[:-1]):
            dc = dc + dh * o * (1.0 - tanh_c**2)
            da = np.hstack([dc * g * i * (1.0 - i), dc * c_prev * f * (1.0 - f), dc * i * (1.0 - g**2),
                            dh * tanh_c * o * (1.0 - o)])
            grads["W"] += x.T @ da
            grads["U"] += h_prev.T @ da
            grads["b"] += da.sum(axis=0)
            dh = da @ U.T
            dc = dc * f
        return loss, grads

    def fit(self, X: np.ndarray, y: np.ndarray) -> "LSTM":
        """Train with mini-batch Adam and gradient-norm clipping.

        X: (n, T, d) sequences. y: (n,) class labels, or (n,) / (n, k) values for regression.
        """
        cfg = self.config
        X = np.asarray(X, dtype=float)
        if X.ndim != 3:
            raise ValueError(f"X must have shape (n, steps, features), got {X.shape}")
        if cfg.task == "classification":
            self.classes_, idx = np.unique(np.asarray(y), return_inverse=True)
            T = np.eye(len(self.classes_))[idx]
        else:
            T = np.asarray(y, dtype=float).reshape(len(X), -1)
        self._init_params(X.shape[2], T.shape[1])
        rng = np.random.default_rng(cfg.seed + 1)
        m = {k: np.zeros_like(p) for k, p in self.params.items()}
        v = {k: np.zeros_like(p) for k, p in self.params.items()}
        step = 0
        self.loss_history = []
        for _ in range(cfg.epochs):
            order = rng.permutation(len(X))
            total = 0.0
            for start in range(0, len(X), cfg.batch_size):
                rows = order[start:start + cfg.batch_size]
                loss, grads = self.loss_and_grads(X[rows], T[rows])
                total += loss * len(rows)
                norm = np.sqrt(sum(np.sum(g**2) for g in grads.values()))
                scale = min(1.0, cfg.clip_norm / (norm + 1e-12))
                step += 1
                for name, g in grads.items():
                    g = g * scale
                    m[name] = 0.9 * m[name] + 0.1 * g
                    v[name] = 0.999 * v[name] + 0.001 * g * g
                    self.params[name] -= cfg.learning_rate * (m[name] / (1 - 0.9**step)) / (
                        np.sqrt(v[name] / (1 - 0.999**step)) + 1e-8)
            self.loss_history.append(total / len(X))
        return self

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """Class probabilities. X: (n, T, d) -> (n, n_classes). Classification only."""
        if self.config.task != "classification":
            raise ValueError("predict_proba is only defined for task='classification'")
        return _softmax(self.forward(X)[0])

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Class labels (n,), or regression values (n,) / (n, k). X: (n, T, d)."""
        out = self.forward(X)[0]
        if self.config.task == "classification":
            return self.classes_[out.argmax(axis=1)]
        return out[:, 0] if out.shape[1] == 1 else out
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
6, run with python3 -m unittest -v

Practice

Train LSTM on the README task, where the class is shown only at the first of 20 steps, with forget_bias=1.0 and then with forget_bias=-2.0. Compare loss_history and the final accuracy. Then use hidden_states on two sequences to see how the state changes after step 0.

Check on learning

  1. A plain recurrent network multiplies its state by a weight matrix and applies tanh at every step. Why does the gradient shrink over many steps there, and what is different along the LSTM cell?
    A way to think about it

    Write the factor that one step contributes to the gradient in each case. One includes the slope of tanh and a matrix, the other is a gate value the network can set close to 1.

  2. Why does starting with a forget bias of 1 help, when the network could in principle learn that value by itself?
    A way to think about it

    With bias 0 the gate starts at σ(0)\sigma(0). Work out how much of an early signal and of its gradient is left after 20 steps, and whether that is enough to learn from.

  3. The output gate lets the cell store a value without showing it. Give an example of a task where that is useful.
    A way to think about it

    Think of something read early in a sequence that should affect the output only at the end, and should not disturb the processing in between.

  4. A GRU has no separate cell state and fewer weights. On what kind of problem would you expect the LSTM's extra machinery to pay off, and how would you find out?
    A way to think about it

    Consider sequence length and how long information must be held. Then think about a fair comparison on held-out data with equal hidden size.