🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

LSTM and GRU: Gates That Keep Memory Alive

Neural NLPGated Recurrent UnitsđŸŸĸ Free Lesson

Why a plain cell forgets

A vanilla recurrent cell has exactly one path for information to travel: multiply by the recurrent matrix, add the input contribution, squash with tanh. Every step through that path applies the same linear map, so over forty steps the gradient is the recurrent matrix raised to the fortieth power, and unless its singular values sit within a whisker of one, the contribution of an early token to a later loss has vanished. The information is not merely attenuated — it is arithmetically gone, and no amount of data recovers it.

The fix pioneered by Hochreiter and Schmidhuber is structural rather than parametric: give the cell a second state that is written by explicit, learned, multiplicative gates, and let the default behaviour of that state be to do nothing at all. A gate outputting one preserves information exactly; a gate outputting zero deletes it; and crucially, a path that multiplies by one repeatedly does not decay. The gradient therefore has a route through time that is controlled by gate values the model itself learns to open.

This lesson walks each gate equation alongside its implementation, then compares the LSTM against its two-gate successor and shows how bidirectional and stacked configurations are assembled in practice.

The cell state as a highway

The LSTM separates a long-term cell state from a short-term hidden state. Three gates regulate the traffic between them: the forget gate decides what to discard from the cell state, the input gate decides which new candidates to write, and the output gate decides how much of the cell state becomes the hidden state exposed to the next layer.

GateEquation roleOutput rangeEffect at one
ForgetSigmoid over hidden and input0 to 1Keep everything from the past
InputSigmoid over hidden and input0 to 1Admit the candidate values
CandidateTanh over hidden and input−1 to 1Propose new content
Cell stateForget times old plus input times newUnboundedThe highway itself
OutputSigmoid over hidden and input0 to 1Expose part of the cell

The arithmetic of the cell update is the important line: C_t = f_t * C_(t-1) + i_t * C_tilde. It is a convex combination built from two independently learned gates, which means the model can leave the state untouched — setting the forget gate to one and the input gate to zero — for as many steps as the task requires. That is the property a vanilla cell structurally lacks. The output gate serves a different purpose: it prevents every intermediate value of the cell state from being forced to double as a representation suitable for the next layer, so the state can store something that is only useful later and expose something else in the meantime. This separation of storage from exposure is why the LSTM can hold a number for fifty steps and still produce a well-scaled hidden state at each one.

A complete forward pass

python
import torch
import torch.nn as nn

class ManualLSTMCell(nn.Module):
    def __init__(self, input_dim, hidden_dim):
        super().__init__()
        self.hidden_dim = hidden_dim
        self.W = nn.Linear(input_dim + hidden_dim, 4 * hidden_dim)

    def forward(self, x_t, state):
        h_prev, c_prev = state
        gates = self.W(torch.cat([x_t, h_prev], dim=1))
        f, i, o, g = gates.chunk(4, dim=1)
        f = torch.sigmoid(f)
        i = torch.sigmoid(i)
        o = torch.sigmoid(o)
        g = torch.tanh(g)
        c_t = f * c_prev + i * g          # the highway update
        h_t = o * torch.tanh(c_t)         # what the next layer sees
        return h_t, c_t

class LSTMTagger(nn.Module):
    def __init__(self, vocab, embed, hidden, tags, layers=2, dropout=0.3):
        super().__init__()
        self.embed = nn.Embedding(vocab, embed)
        self.lstm = nn.LSTM(embed, hidden, num_layers=layers,
                            batch_first=True, dropout=dropout,
                            bidirectional=True)
        self.head = nn.Linear(hidden * 2, tags)

    def forward(self, ids):
        x = self.embed(ids)
        out, (h, c) = self.lstm(x)
        return self.head(out)              # (batch, seq_len, tags)

model = LSTMTagger(vocab=30000, embed=128, hidden=256, tags=45)
batch = torch.randint(0, 30000, (8, 50))
print(model(batch).shape)                 # (8, 50, 45)

The manual cell exists to make one point visible: c_t receives an additive update, so gradients flowing backward through it pass through multiplication by gate values rather than through a fixed matrix power. If the gates learn to stay near one — which they do when the task rewards long memory — the gradient travels the full length of the sequence essentially undamped.

GRU: two gates, one state

The gated recurrent unit merges the forget and input gates into a single update gate and folds the cell state into the hidden state. The reset gate independently controls how much of the past enters the candidate computation, which lets the unit ignore irrelevant history when forming new content.

AspectLSTMGRU
GatesForget, input, outputUpdate, reset
StatesCell plus hiddenHidden only
Parameters per unit4 × (input + hidden + 1) × hidden3 × (input + hidden + 1) × hidden
Relative parameter count1.000.75
Training speedBaselineRoughly 25–30 percent faster
Quality on typical NLPMarginally aheadEffectively tied
Recommended whenData is plentiful, memory longLatency or memory constrained

Implementing and benchmarking both

The comparison that matters is empirical on your own sequence lengths, because the parameter saving of the GRU is fixed while the quality difference is data dependent.

python
import time

def benchmark(cell_name, steps=50):
    torch.manual_seed(0)
    rnn = (nn.LSTM if cell_name == "lstm" else nn.GRU)(
        128, 256, num_layers=2, batch_first=True, bidirectional=True)
    params = sum(p.numel() for p in rnn.parameters())
    x = torch.randn(32, steps, 128)
    # warm up
    rnn(x)
    t0 = time.perf_counter()
    for _ in range(20):
        rnn(x)
    dt = (time.perf_counter() - t0) / 20
    return params, dt

for name in ("lstm", "gru"):
    p, dt = benchmark(name)
    print(f"{name}: {p/1e6:.2f}M params, {dt*1000:.1f} ms per step-batch")

Running it on a GPU shows the gap shrinking, because the arithmetic is a small fraction of total step time once embedding lookup and the output projection are included; on CPU with long sequences the GRU's advantage is more pronounced. That is the honest basis for the usual recommendation: default to GRU under latency pressure, reach for the LSTM when you have the budget and a task that demonstrably rewards longer retained context.

Bidirectionality and stacking

Two extensions are almost always worth trying. A bidirectional RNN runs the sequence forward and backward with separate parameters and concatenates the two hidden states at every position, so the representation of token t sees both its left and its right context — which is a strict improvement for tagging and classification, and impossible for generation, where the future does not exist yet.

Stacking layers composes abstractions: the first layer learns character and affix patterns, the second learns phrasal patterns, and so on. In PyTorch this is a num_layers argument rather than manually chained modules, and the dropout argument applies between layers rather than within a cell.

python
bilstm = nn.LSTM(256, 256, num_layers=3, batch_first=True,
                 dropout=0.4, bidirectional=True)

x = torch.randn(16, 80, 256)
out, (h_n, c_n) = bilstm(x)
print(out.shape)       # (16, 80, 512)  <- both directions concatenated
print(h_n.shape)       # (6, 16, 256)   <- 3 layers x 2 directions

# read the final state of each direction for classification
fwd, bwd = h_n[-2], h_n[-1]
summary = torch.cat([fwd, bwd], dim=1)   # (16, 512)

One subtlety trips people up: with num_layers=3 and bidirectional=True, the hidden state tensor has six slices, ordered layer by layer and direction by direction. Indexing h_n[-1] grabs only the backward pass of the top layer rather than the concatenation you wanted, which produces a model that silently uses half its capacity.

💡Ablate before you justify the extra gates

Train the same model with a plain RNN, a GRU, and an LSTM at matched parameter counts. If the LSTM wins by less than the run-to-run variance, the honest conclusion is that the task does not need long memory — and the cheaper model ships.

Common Mistakes

Indexing the final hidden state incorrectly in a bidirectional stacked model

Fix: Concatenate h_n[-2] and h_n[-1] explicitly; h_n[-1] alone is only the backward direction of the top layer.

Assuming dropout applies inside the recurrence

Fix: PyTorch applies recurrent dropout only between layers, so add variational dropout separately if you need it within a step.

Choosing LSTM versus GRU by folklore

Fix: Ablate at matched parameter counts on your own sequence lengths and compare against run-to-run variance.

Using a bidirectional model for autoregressive generation

Fix: The backward pass reads the future, which is unavailable at inference; generation requires a unidirectional cell.

Best Practices

  • Start with a GRU under latency constraints and an LSTM when memory length is demonstrably the bottleneck
  • Concatenate both directions of the top layer rather than indexing a single slice
  • Ablate against a plain RNN at matched parameter counts to prove the gates earn their cost
  • Keep bidirectionality for understanding tasks and drop it for generation

Interview Questions

Q1: Why does the LSTM avoid the vanishing gradient problem?

The cell state receives an additive update gated by multiplicative sigmoid values, so a gradient flowing backward passes through a product of gate values rather than a matrix power, and gates near one let it travel undamped.

Q2: How does the GRU differ structurally from the LSTM?

It merges the forget and input gates into one update gate, folds the cell state into the hidden state, and adds a reset gate controlling the candidate, cutting parameters by roughly a quarter.

Q3: When is a bidirectional model invalid?

In autoregressive generation, because the backward pass conditions on future tokens that do not exist at inference time.

Key Takeaways

  • Gates convert an additive-only recurrence into one with learned multiplicative control over memory
  • The cell state update is a convex combination of past and candidate, which is why gradients survive length
  • GRU saves about a quarter of the parameters by merging gates and matching LSTM quality on most tasks
  • Bidirectionality helps tagging and classification and is invalid for generation
  • Stacking and correct hidden-state indexing matter as much as the choice of cell
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement