Deep LearningDeep Learning Comparison Series

How do LSTM and GRU architectures differ in their gates, parameters, and sequence-learning trade-offs?

Question 308 of 314 · Updated

On this page

LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) are gated recurrent architectures for learning dependencies in ordered data. LSTM carries a separate cell state and hidden state, controlled by three gates. GRU carries one hidden state, controlled by two gates. GRU usually has fewer parameters; LSTM provides more explicit separation between stored memory and exposed output. Neither is universally superior.

1. Why gated recurrent networks?#

A vanilla recurrent neural network (RNN) updates a hidden state using the current input and previous state:

LaTeX

Backpropagation through time repeatedly applies derivatives through the recurrent chain. These products can shrink toward zero (vanishing gradients) or grow excessively (exploding gradients), making distant sequence dependencies difficult to learn. Gated architectures learn how much information to retain, update, and expose.

2. LSTM: separate cell and hidden states#

An LSTM carries two vectors:

  • Cell state : internal memory passed across time steps.
  • Hidden state : exposed representation used by the next step, upper layer, or prediction head.

Its four learned transformations are the input gate, forget gate, candidate memory, and output gate:

LaTeX

Sigmoid outputs values between 0 and 1; tanh outputs values between −1 and 1; ⊙ means element-wise multiplication. Gates are soft, learned controls for each state dimension.

  • Forget gate : controls how much old cell memory remains. Near 1 retains; near 0 removes most.
  • Input gate : controls how much candidate information is written.
  • Candidate : proposes new content; it is not a gate.
  • Output gate : controls how much updated cell memory is exposed as . It does not directly erase .

Numerical example: one LSTM component#

LaTeX
LaTeX

The cell retains 0.6 units of old memory and writes 0.2 units of candidate content. Its exposed hidden output is:

LaTeX

The cell state is 0.8, while the hidden state is approximately 0.398. They are related but not interchangeable.

3. GRU: one state and two gates#

A GRU has no separate cell state. Its hidden state carries recurrent memory. It uses:

  • Reset gate : controls how much previous hidden information contributes when forming the candidate.
  • Update gate : mixes the old hidden state with the candidate.

Using the convention in PyTorch's GRU documentation:

LaTeX

Here is the candidate hidden state. Under this convention, near 1 mostly retains the old state; near 0 mostly adopts the candidate. Some papers and implementations reverse the update-gate mixing convention. Always inspect the equation before interpreting .

Numerical example: one GRU component#

LaTeX
LaTeX

The GRU retains 70% of the old state and takes 30% of the candidate. The reset gate affects candidate formation; it does not directly erase the stored hidden state.

4. Gate-by-gate comparison#

PurposeLSTMGRU
Retain old memoryForget gateUpdate gate (this convention)
Control new contentInput gate scales candidateUpdate gate mixes candidate and old state
Control prior-state access for candidateNo separate reset gateReset gate
Separately control exposed outputOutput gateNo separate output gate
Candidate
Persistent stateCell and hidden Hidden

The gates are not one-to-one equivalents. LSTM input and forget gates independently control writing and retaining. GRU's update gate couples the old-versus-new mixture.

5. Parameter-count calculations#

Let I be input feature size and H be hidden size. For a standard, single-layer, unidirectional PyTorch recurrent layer with biases enabled:

LSTM: four input matrices (4HI), four recurrent matrices (4H²), and two bias vectors of length 4H (8H):

LaTeX

GRU: three input matrices (3HI), three recurrent matrices (3H²), and two bias vectors of length 3H (6H):

LaTeX

Some simplified textbook counts use one bias vector, producing 4H(I+H+1) and 3H(I+H+1). PyTorch stores separate input-hidden and hidden-hidden bias vectors when bias=True. With bias=False, remove the bias terms.

Worked example#

For I=128 and H=256:

  • LSTM: 4 × 256 × (128 + 256) + 8 × 256 = 395,264 parameters.
  • GRU: 3 × 256 × (128 + 256) + 6 × 256 = 296,448 parameters.

This GRU has 98,816 fewer parameters, approximately 25% fewer. That does not guarantee 25% lower latency. Kernel fusion, memory traffic, hardware, precision, sequence length, batch size, and framework implementation affect runtime.

For multiple layers, calculate each layer separately. In a bidirectional stack, later layers receive twice the previous layer's hidden width. Projection LSTMs also change the count. Do not reuse the single-layer formula blindly.

6. Gradient flow and long-range dependencies#

For an LSTM, holding gate values fixed to understand the direct cell-state path:

LaTeX

Across several steps, the direct path contains a product of forget-gate values. If they remain close to 1, useful gradients can travel farther with less repeated nonlinear transformation than in a vanilla RNN. If forget gates are small, the path still shrinks. Other gradient paths and gate derivatives also matter.

A GRU's update equation creates a learned route for retaining the previous hidden state. When the update gate favors retention, information and gradient can pass through that route. The full derivative also includes gate and candidate dependencies. GRUs reduce some optimization difficulties; they do not guarantee gradients never vanish or explode.

Both models may still need gradient clipping, careful initialization, suitable sequence lengths, and validation on long-horizon examples. LSTM offers a more explicit memory channel; GRU's compact state is sufficient for many tasks.

7. Sequence-learning and computational trade-offs#

Consider LSTM when:

  • Separate control over stored memory and exposed output is a useful inductive bias.
  • Long temporal dependencies matter and the extra state/gates may help.
  • You want a well-established baseline for forecasting, speech, or sequence classification.

Consider GRU when:

  • Parameter count or model size is constrained.
  • A simpler gated recurrent baseline is desirable.
  • Validation shows the compact state mechanism captures the task's dependencies.

Neither is automatically faster or more accurate. GRUs have fewer parameters and gate computations, but wall-clock speed depends on fused kernels, device, precision, batch/sequence shapes, and library implementation. Benchmark both on deployment hardware using validation quality, throughput, p95/p99 latency, memory, and cost.

Recurrent models process time steps sequentially within each direction, limiting parallelism across sequence positions. For very long sequences, compare them with architectures offering parallel sequence processing or attention, when suitable for the task.

8. Bidirectional variants#

A bidirectional LSTM or GRU runs one recurrence left-to-right and another right-to-left, then combines their outputs. It can use past and future context at each position. This can help offline text/audio labeling, document classification, and retrospective sensor analysis.

Causal limitation: a bidirectional model uses future observations relative to a position. It is unsuitable for strictly real-time forecasting or streaming prediction when future values are unavailable. Use a unidirectional model for those settings.

For a bidirectional layer, output width is typically 2H because forward and reverse hidden outputs are concatenated. A single layer's parameter count is roughly doubled for the same input width and hidden size.

9. PyTorch implementations#

PyTorch provides torch.nn.LSTM and torch.nn.GRU. With batch_first=True, inputs use [batch, sequence_length, input_size].

PYTHON
import torch from torch import nn x = torch.randn(32, 50, 128) # batch, time, features lstm = nn.LSTM(128, 256, num_layers=1, batch_first=True) lstm_output, (lstm_h_n, lstm_c_n) = lstm(x) gru = nn.GRU(128, 256, num_layers=1, batch_first=True) gru_output, gru_h_n = gru(x) print(lstm_output.shape) # [32, 50, 256] print(lstm_h_n.shape) # [1, 32, 256] print(lstm_c_n.shape) # [1, 32, 256] print(gru_output.shape) # [32, 50, 256] print(gru_h_n.shape) # [1, 32, 256] def count_parameters(module): return sum(p.numel() for p in module.parameters() if p.requires_grad) print(count_parameters(lstm)) # 395264 print(count_parameters(gru)) # 296448

Important API details:

  • LSTM returns output and (, ); GRU returns output and .
  • batch_first changes input/output layout, not final-state layout.
  • bidirectional=True adds a direction dimension to final states and doubles output feature width.
  • PyTorch's recurrent dropout is applied between stacked recurrent layers, not after the final layer. With num_layers=1, this inter-layer dropout has no effect.
  • For padded variable-length batches, investigate pack_padded_sequence and pad_packed_sequence so padding is not treated as genuine sequence content.

10. Common mistakes#

  1. Treating hidden state and cell state as synonyms. Only LSTM has a separate cell state.
  2. Saying GRU has input, forget, and output gates. Its standard form uses reset and update gates plus a candidate.
  3. Misreading the update gate. In the PyTorch convention here, larger retains more previous hidden state; other formulations reverse the mixing convention.
  4. Assuming the reset gate erases memory. It changes the candidate's access to prior state; the update gate controls the old/new mixture.
  5. Comparing parameter counts with inconsistent bias assumptions. PyTorch has two bias vectors per gate group when bias=True.
  6. Assuming fewer parameters always means lower latency. Benchmark actual throughput and tail latency.
  7. Expecting LSTM to eliminate vanishing gradients. It provides a more favorable path, not a guarantee.
  8. Using bidirectional recurrence for online prediction, causing future-information leakage.
  9. Confusing output and final-state shapes. Check batch_first, layer count, directions, and return structure.
  10. Assuming dropout works on a one-layer recurrent module. PyTorch recurrent dropout applies between stacked layers.

11. Practical selection checklist#

  1. Build both baselines with the same input pipeline, data split, and prediction head.
  2. Match hidden size first, then compare under similar parameter or latency budgets.
  3. Evaluate metrics by sequence length and important data slices; aggregate scores can hide failures on long sequences.
  4. Benchmark training time, inference throughput, p95/p99 latency, peak memory, and cost on target hardware.
  5. Check causal correctness, padding/masking, state initialization, and behavior when sequences are truncated or streamed.
  6. Keep the simpler/faster model only if quality remains acceptable under real operating constraints.

Practical rule: start with GRU when a compact recurrent baseline is desirable; start with LSTM when separate memory and output control is a useful inductive bias. Let controlled validation and deployment benchmarks decide. Dataset and training setup often matter more than the architecture label.

12. Further reading#

  • Hochreiter & Schmidhuber (1997), *Long Short-Term Memory*, Neural Computation: https://doi.org/10.1162/neco.1997.9.8.1735
  • Cho et al. (2014), *Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation*: https://arxiv.org/abs/1406.1078
  • PyTorch LSTM documentation: https://docs.pytorch.org/docs/stable/generated/torch.nn.LSTM.html
  • PyTorch GRU documentation: https://docs.pytorch.org/docs/stable/generated/torch.nn.GRU.html
  • Dive into Deep Learning, LSTM and GRU: https://d2l.ai/chapter_recurrent-modern/lstm.html

Key takeaway: LSTM uses three gates and a separate cell state; GRU uses two gates and a single hidden state. GRU is usually smaller, while LSTM offers more explicit memory control. Both are gated approaches to recurrent sequence learning; the best choice is empirical.

Related questions

Explore other topics:Machine LearningLarge Language Models