AI Logic

Architectures

Long Short-Term Memory (LSTM)

Updated:

Structure of LSTM. The top shows the overall flow with LSTMs laid out per time step (passing the cell state and hidden state to the next step); the bottom shows the inside of one time step (the forget, input, and output gates and the candidate, the cell state update, and the hidden state output)

Background and overview

LSTM (Long Short-Term Memory) is an RNN (recurrent neural network) with a "memory cell" that can hold information for a long time and "gates" that control writing to and reading from that memory. Hochreiter and Schmidhuber proposed it in 1997 and showed that it can learn relationships between inputs and outputs more than 1000 steps apart, which earlier RNNs could not learn.

An RNN reads a sequence (a sentence, speech, a time series, and so on) one element at a time by feeding its own output from the previous time step back in as input at the next step. However, when a simple RNN such as the Elman network is trained with backpropagation, the error signal shrinks exponentially as it travels back in time (vanishing gradient) or grows too large (exploding gradient). As a result, problems where an input dozens of steps earlier determines the answer could hardly be learned.

LSTM solved this problem with two ideas.

  • Memory cell: a linear unit connected to itself with a weight of 1, which creates a path along which the error can travel back in time without changing in size. The paper calls this the "constant error carousel (CEC)".
  • Gates: they multiply by values between 0 and 1 and decide, based on the input, "when to write" to the memory cell and "when to read" from it.

What is generally called "LSTM" today is this design with a forget gate added (Gers et al., 1999–2000). The forget gate erases memories that are no longer needed. PyTorch's nn.LSTM also uses this form.

LSTM was the standard model for a long time in speech recognition, handwriting recognition, machine translation (Sequence to Sequence), and other tasks, and from 2017 onward it was replaced by the Transformer in many fields.

Structure: computation at one time step

At each time step tt, LSTM takes the input xtx_t together with the hidden state ht−1h_{t-1} and cell state ct−1c_{t-1} from the previous time step, and outputs new hth_t and ctc_t. The top of the figure at the head of the article shows the overall flow laid out along time, and the bottom shows what happens inside one time step.

  • Cell state ctc_t: the memory kept for a long time. In the figure it is the line running from left to right across the top of the inner view, and it is updated only by multiplication and addition.
  • Hidden state hth_t: the output at that time step. It is used by the next layer or for prediction, and also in computing the gates at the next time step.

One time step is computed as follows (the equations of PyTorch's nn.LSTM).

  1. From xtx_t and ht−1h_{t-1}, compute the three gates (forget ftf_t, input iti_t, output oto_t) with Sigmoid. Their values lie between 0 and 1.
  2. Also from xtx_t and ht−1h_{t-1}, compute the candidate gtg_t to write to the cell with Tanh. Its values lie between −1 and 1.
  3. Multiply the old cell state by the forget gate (forget), add the candidate multiplied by the input gate (write), and obtain the new cell state ctc_t.
  4. Pass ctc_t through tanh and multiply by the output gate (read) to obtain the hidden state hth_t.
ft=σ(Wifxt+Whfht−1+bf)it=σ(Wiixt+Whiht−1+bi)gt=tanh⁡(Wigxt+Whght−1+bg)ot=σ(Wioxt+Whoht−1+bo)ct=ft⊙ct−1+it⊙gtht=ot⊙tanh⁡(ct)\begin{aligned} f_t &= \sigma(W_{if} x_t + W_{hf} h_{t-1} + b_f) \\ i_t &= \sigma(W_{ii} x_t + W_{hi} h_{t-1} + b_i) \\ g_t &= \tanh(W_{ig} x_t + W_{hg} h_{t-1} + b_g) \\ o_t &= \sigma(W_{io} x_t + W_{ho} h_{t-1} + b_o) \\ c_t &= f_t \odot c_{t-1} + i_t \odot g_t \\ h_t &= o_t \odot \tanh(c_t) \end{aligned}

Here σ\sigma is the sigmoid function and ⊙\odot is the element-wise product (in PyTorch's equations, the bias is split into two terms, one on the input side and one on the hidden-state side).

ComponentSymbolRole
Forget gateftf_tDecides how much of the old memory ct−1c_{t-1} to keep (0 erases it, 1 keeps it as is)
Input gateiti_tDecides how much of the candidate gtg_t to write to the cell
Candidategtg_tThe new content to write
Output gateoto_tDecides how much of the cell content to expose as hth_t

Because all four are computed from the same inputs xt,ht−1x_t, h_{t-1}, PyTorch stores the weights for all four in a single matrix (weight_ih_l0 has shape (4*hidden_size, input_size)). Compared with a simple RNN of the same size, the number of weights is about four times larger.

The cell state is easier to picture as a notebook. The forget gate is the "eraser", the input gate is "whether to write", and the output gate is "which part of the notebook to read aloud right now". Unless something is erased or added, the notebook itself is carried over to the next page (time step) with its content unchanged.

The original 1997 LSTM differs from today's form in the following ways.

  • It has no forget gate. The internal state of the cell only accumulates onto its previous value, as in sc(t)=sc(t−1)+yin(t) g(netc(t))s_c(t) = s_c(t-1) + y^{in}(t)\,g(net_c(t)).
  • Several cells that share an input gate and an output gate are treated as one "memory cell block".
  • Some experiments omit the output gate or the input activation function.

Without a forget gate, a cell cannot erase its own memory and reset its state. The forget gate was added so that the model could learn tasks that require reading long, unsegmented sequences continuously.

How it is trained

LSTM is usually trained with BPTT (Backpropagation Through Time), which applies backpropagation to the network unrolled along time.

  1. Read the sequence one time step at a time from the start and compute ht,cth_t, c_t at each step. The initial h0,c0h_0, c_0 are usually set to 0.
  2. Depending on the task, make predictions from the hth_t of every time step or from the hTh_T of the last step, and compute the loss (cross-entropy for classification).
  3. Compute the gradient of the loss going back from the last time step to the first, and update the weights shared across all time steps.

Training in the original paper differs slightly from this. It used a computationally cheap method (a variant of RTRL) that propagates the error into the past only inside the memory cell (CEC) and truncates the error after one time step along the gate and input paths. Thanks to this truncation, the cost per time step and per weight is O(1)O(1), and no storage proportional to the sequence length is needed. Later, full BPTT that propagates the error back along every path (Graves and Schmidhuber, 2005) came into use, and current implementations follow it.

The paper gives two practical tips for training.

  • Start the output gate bias at a negative value: this keeps the memory cell from being used early in training for purposes other than "remembering across time" (such as always emitting a constant value).
  • Start the input gate bias close to 0: if the input stays positive (or negative), the internal state of the cell drifts and grows, which makes the gradients small.

Why it can learn long-range dependencies

In a simple RNN the error vanishes because every step back in time multiplies it by "the derivative of the activation function × the weight". Going back qq steps multiplies this factor qq times.

∣f′(net)⋅w∣<1 : shrinks exponentially in q; >1 : grows exponentially\left| f'(net) \cdot w \right| < 1 \ \text{: shrinks exponentially in} \ q \text{;}\ > 1 \ \text{: grows exponentially}

The paper's analysis notes that the maximum of the derivative of the logistic sigmoid is 0.25, so as long as the absolute values of the weights are below 4.0 (which is usually the case early in training), the error vanishes exponentially over time. Larger initial weights do not help, because the derivative shrinks faster.

LSTM's answer is to create a path along which the error does not shrink through multiplication.

  • Constant error carousel (CEC): to keep the error constant, it is enough to keep the per-step factor f′(net) wf'(net)\,w always equal to 1. To do so, use the identity as the activation function and fix the self-connection weight at 1.0. Then both the cell value and the error are preserved unchanged across time.
  • Input gate: with the CEC alone, the same input weights must both "write the needed information" and "avoid corrupting the memory with irrelevant inputs", and these goals conflict during learning. The input gate decides separately when to write.
  • Output gate: similarly, it decides when to read, so that the memory content does not disturb other units for which it is currently irrelevant.

In terms of today's LSTM equations, the main term of the derivative of the cell update ct=ft⊙ct−1+it⊙gtc_t = f_t \odot c_{t-1} + i_t \odot g_t with respect to ct−1c_{t-1} is ftf_t. What multiplies the error as it goes back one step through the cell state is neither a weight matrix nor an activation derivative, but the value of the forget gate itself. While the forget gate is close to 1, the error passes through almost unchanged, and it approaches 0 only when the memory should be discarded.

This idea of "updating the state by addition to create a path along which the gradient flows unchanged" also carries over to the residual connections of the later ResNet and the gated shortcuts of Highway Networks.

Experimental results

The original paper compared LSTM with other RNN training methods on artificial tasks with long time lags. Success was defined, for example, as staying below an error limit set for each task on 10,000 consecutive sequences.

Task 2a: remember the first symbol for pp steps and answer at the end (average of 18 trials)

MethodTime lag ppFraction of successful trialsSequences until success
RTRL478%1,043,000
RTRL100%> 5 million
RTRL1000%> 5 million
BPTT1000%> 5 million
Neural sequence chunker10033%32,400
LSTM100100%5,040

Conventional RTRL and BPTT failed completely even with a time lag of 10 steps, while LSTM succeeded in every trial with a time lag of 100 steps and also learned faster (the RTRL row with p=4p=4 is for a learning rate of 1.0).

Task 2c: remember for more than 1000 steps among noise symbols (LSTM, average of 20 trials)

Minimum time lag qqNumber of noise symbols ppSequences until success
505030,000
10010031,000
20020033,000
50050038,000
1,0001,00049,000

Increasing the time lag 20-fold, from 50 to 1,000, increased the number of sequences needed for learning by less than a factor of 2. The paper states that BPTT and RTRL cannot solve this task.

On the embedded Reber grammar (predicting the next symbol, average of 30 trials), Elman's network had a success rate of 0% and Recurrent Cascade-Correlation 50%, while LSTM reached 97–100% depending on settings such as the learning rate, and needed fewer sequences to succeed.

Greff et al. (2017) later examined the effect of each LSTM component with 5400 experiments on three tasks: speech recognition (TIMIT), handwriting recognition (IAM Online), and polyphonic music modeling (JSB Chorales).

  • None of the eight modifications (removing one gate, removing the peephole connections (connections that also feed the cell state into the gate computation; Gers and Schmidhuber, 2000), merging the input and forget gates into one, and so on) was significantly better than the standard LSTM.
  • Removing the forget gate or the output activation function (the tanh in the hth_t equation) significantly hurt performance. These two are the most important components.
  • Merging the input and forget gates as ft=1−itf_t = 1 - i_t, or removing the peephole connections, hardly hurt performance.

Practical notes

Keep the following points in mind when using LSTM.

  • It cannot be parallelized along time: computing time step tt requires ht−1,ct−1h_{t-1}, c_{t-1}, so the computation must proceed sequentially over the length of the sequence. For long sequences or large datasets, it takes longer to train than the Transformer.
  • Watch out for padding when batching sequences of different lengths: if the model also reads the padded part, the final hTh_T is affected by the padding. In PyTorch, pack_padded_sequence lets the model read only the true length.
  • Add dropout between layers with the dropout argument: nn.LSTM(..., num_layers=2, dropout=0.2) applies dropout to the output of every layer except the last. To apply it to the connections along time, use Variational Dropout or Zoneout.
  • It is poor at exact counting: the original paper notes that tasks such as distinguishing "whether a signal occurred 99 or 100 steps ago" probably require a separate counting mechanism.

Setting batch_first=True in PyTorch's nn.LSTM changes the shape of the input and output only. h_n and c_n keep the shape (num_layers × num_directions, batch, hidden_size), with the batch on the second axis. Take the hidden state of the last layer with h_n[-1].

output and h_n are different things. output is hth_t of the last layer at every time step. h_n is hth_t of every layer at the last time step. When the LSTM is bidirectional (bidirectional=True), the last axis of output becomes 2 * hidden_size, the concatenation of the forward and backward directions.

Comparison with other models

Comparing the main sequence models from the same viewpoints gives the following.

ModelHow memory is keptGatesParallel computation along timeLong-range dependencies
Elman network (simple RNN)Hidden state onlyNoneNot possibleHard to learn because of vanishing gradients
LSTMCell state and hidden stateThree: forget, input, outputNot possibleLearnable through the cell-state path
GRUHidden state onlyTwo: update, resetNot possibleControlled by gates (whether it beats LSTM depends on the task)
TransformerNone (looks at every position directly)None (attention)PossibleConnected directly by a single attention step

GRU is a simplified version of LSTM that merges the input and forget gates into a single "update gate" and does not use the output activation function or peephole connections. In the experiments of Greff et al., the variant that merged the input and forget gates also performed almost the same as the standard LSTM.

Rough guidelines for choosing are as follows.

  • Little data, sequences of moderate length, or processing one time step at a time (streaming, etc.): LSTM or GRU is a good fit. The computation and memory per time step are constant regardless of sequence length.
  • Fewer parameters wanted: try GRU. With one gate fewer, it also has fewer weights.
  • Training on large amounts of data, or handling long contexts at once: the Transformer is the mainstream choice. It can be parallelized along time, but its computation and memory grow with the square of the sequence length.
  • Using context from both before and after in the sequence (part-of-speech tagging, etc.): use a bidirectional RNN that combines forward and backward LSTMs.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm

"""
Task: remember the first symbol of a sequence and answer it at the end (a small example similar to Task 2 in the paper that needs no data download)
Example: [A, 5, 2, 8, ..., 3] -> A, [B, 7, 1, 4, ..., 9] -> B. The symbols in between are noise
"""

# Hyperparameters
seq_len = 50            # time lag to remember
num_noise = 10          # number of noise symbols (0-9)
num_classes = 2         # number of first-symbol types (A=10, B=11)
embed_dim = 16
hidden_size = 64
batch_size = 64
steps = 2000
learning_rate = 1e-3

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


def make_batch(n):
  label = torch.randint(0, num_classes, (n,))
  noise = torch.randint(0, num_noise, (n, seq_len - 1))
  x = torch.cat([(label + num_noise).unsqueeze(1), noise], dim=1)  # put the answer symbol at the start
  return x.to(device), label.to(device)


class LSTMClassifier(nn.Module):
  def __init__(self):
    super().__init__()
    self.embed = nn.Embedding(num_noise + num_classes, embed_dim)
    # batch_first=True: input and output have shape [batch, time, feature]
    self.lstm = nn.LSTM(input_size=embed_dim, hidden_size=hidden_size,
                        num_layers=1, batch_first=True)
    self.head = nn.Linear(hidden_size, num_classes)

  def forward(self, x):                      # x: [B, T]
    e = self.embed(x)                        # [B, T, embed_dim]
    output, (h_n, c_n) = self.lstm(e)        # h_0, c_0 start at 0 if not given
    # output: [B, T, hidden_size]  h_t of the last layer at every time step
    # h_n, c_n: [num_layers, B, hidden_size]  batch stays on the 2nd axis even with batch_first
    return self.head(h_n[-1])                # classify from the hidden state of the last layer at the last time step


model = LSTMClassifier().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop
model.train()
for step in tqdm(range(steps)):
  x, y = make_batch(batch_size)
  optimizer.zero_grad()
  loss = criterion(model(x), y)
  loss.backward()
  optimizer.step()

# Evaluation (nn.LSTM itself does not change between train/eval, but switch to eval in case dropout is used)
model.eval()
x, y = make_batch(1000)
with torch.no_grad():
  accuracy = (model(x).argmax(dim=1) == y).float().mean().item()
print(f"Accuracy: {accuracy * 100:.2f}%")

FAQ

Q. Should I use LSTM or GRU?
A.

On many tasks their performance is close, and which one is better depends on the data. GRU has two gates and correspondingly fewer weights. LSTM keeps the cell state and hidden state separate, so it can control memory and output independently. If unsure, try both and compare them on validation data.

Q. Why do the gates use the sigmoid function?
A.

The sigmoid outputs values between 0 and 1, so when multiplied it acts as a fraction of "how much to let through". 0 blocks completely and 1 passes everything through. On the other hand, the candidate gtg_t and the output use tanh, which takes values between −1 and 1, so that both positive and negative values can be stored.

Q. Are `output[:, -1]` and `h_n[-1]` the same?
A.

For a unidirectional LSTM on unpadded sequences, they have the same value. Both are the hidden state of the last layer at the last time step. However, in a bidirectional LSTM, the backward part of output[:, -1] is the value at the "first time step", and with pack_padded_sequence the last position of output is padding, so using h_n is safer.

References

  1. Hochreiter, S., & Schmidhuber, J. (1997). Long Short-Term Memory. Neural Computation, 9(8), 1735–1780.
  2. Gers, F. A., Schmidhuber, J., & Cummins, F. (2000). Learning to Forget: Continual Prediction with LSTM. Neural Computation, 12(10), 2451–2471.
  3. Greff, K., Srivastava, R. K., Koutník, J., Steunebrink, B. R., & Schmidhuber, J. (2017). LSTM: A Search Space Odyssey. IEEE Transactions on Neural Networks and Learning Systems, 28(10), 2222–2232. arXiv:1503.04069.
  4. PyTorch. torch.nn.LSTM.