LSTM, GRU & Seq2Seq
After this lesson, you will be able to:
- Explain why vanilla RNNs fail on long sequences — gradients shrink or explode exponentially with depth in time — and why this killed sequence models for two decades
- Walk through the LSTM cell: how the forget, input, and output gates use a separate cell state c_t as a 'gradient highway' so information can flow across hundreds of time steps without dying
- Compare LSTM and GRU and pick the right one — GRU has fewer parameters and trains faster, LSTM has more capacity for long-range dependencies; benchmarks show they are usually within 1-2% of each other
- Build a sequence-to-sequence encoder-decoder model with teacher forcing for training, and recognize the exposure-bias problem that makes inference brittle
- Trace how Bahdanau attention (2014) — letting the decoder look back at every encoder hidden state instead of one fixed context vector — quietly invented the architecture that would become the transformer three years later
Before you start
Don't worry if the gating math looks intimidating — every gate is just a sigmoid that outputs a number between 0 and 1, and you multiply it with a vector to control how much "flows through." Once you see the cell-state highway in action, the rest of the math falls into place.
#Why Vanilla RNNs Fail on Long Sequences
Recall the vanilla RNN update from the previous lesson:
Backpropagation through time (BPTT) computes ∂L/∂W by chaining the gradient through every step:
Where does the shrinking come from? Open the derivation to see each factor in that product and why its size is capped.
This is why pre-1997 sequence models could not learn long-range dependencies. LSTM was the fix.
#The LSTM: A Gradient Highway
LSTM (Long Short-Term Memory) introduced two innovations:
- A separate cell state c_t that flows through time with only multiplicative gating (no transformation) — gradients can travel along it without vanishing.
- Three gates (forget, input, output) — each a sigmoid that learns when to read, write, and erase.
#The LSTM Math, Step by Step
At each time step, an LSTM receives input x_t and the previous (h_, c_). It produces a new (h_t, c_t).
#The Forget Gate
The forget gate f_t looks at the previous hidden state and current input and outputs a vector of values in (0, 1) — one per cell-state dimension. Multiplying f_t element-wise with c_ decides which dimensions of the old cell state to keep (1) or erase (0).
#The Input Gate and Candidate Cell
The input gate i_t controls how much new information to write. The candidate cell value g_t (sometimes called \tilde_t) is the actual content to write — a tanh of a learned linear transform.
#The Cell State Update
Now combine: erase the parts you want to forget from old memory, then add the new content scaled by the input gate.
Why does an additive update protect the gradient? Open the derivation to compare it with the RNN factor from the previous derivation.
Move the sequence length, the RNN weight norm and the LSTM forget gate, and watch the RNN's surviving gradient die exponentially, far faster than the bound, while an LSTM with a forget gate near 1 keeps it alive for many steps.
#The Output Gate
Finally, the output gate o_t decides which parts of the (now updated) cell state to expose as the next hidden state h_t. The cell state goes through a tanh first to bring it back into a bounded range.
#Counting the Parameters
How big is an LSTM layer? Say the input x_t has m entries and the hidden state has n entries. The count follows from the four equations above, and the derivation is a short piece of bookkeeping.
#Putting It All Together
Try it! Open the Python REPL and type these lines yourself. PyTorch's LSTM is a one-liner:import torch; lstm = torch.nn.LSTM(input_size=10, hidden_size=20, num_layers=1); x = torch.randn(5, 3, 10); h, (h_n, c_n) = lstm(x); print(h.shape, h_n.shape, c_n.shape)— five time steps, batch of 3 sequences, 10-dim input, 20-dim hidden. PyTorch handles all the gates internally.
#GRU: A Simpler, Often-Equivalent Alternative
The GRU equations:
How does the GRU relate to the LSTM, and where does the "about 25% fewer parameters" come from? Open the derivation to see the two cells line up term by term.
#LSTM vs GRU: Which Should You Use?
| LSTM | GRU | |
|---|---|---|
| Parameters | More (4 gates worth) | ~25% fewer (3 gates worth) |
| States | Two (h, c) | One (h) |
| Long-range memory | Slightly better in theory | Comparable in practice |
| Training speed | Slower | Faster |
| Default? | Default for unknown problem | Default if you want speed |
You have a small dataset (~10K sequences) and limited GPU time. Your task is character-level text generation. Should you reach for LSTM or GRU first?
The right answer is GRU. With a small dataset, fewer parameters reduce overfitting risk. The faster training also lets you do more hyperparameter sweeps in the same wall-clock budget. Greff's empirical comparison showed GRU is the better default for resource-constrained settings.
#Sequence to Sequence: The Encoder-Decoder Pattern
The architecture, in pictures:
Source: "Hello world"
ENCODER (LSTM)
H → e → l → l → o → ' ' → w → o → r → l → d
\
c (context vector)
/
DECODER (LSTM)
<SOS> → "B" → "o" → "n" → "j" → "o" → "u" → "r" → <EOS>
Target: "Bonjour"
The decoder is autoregressive: at each step it takes the previously emitted token and the previous decoder hidden state, and predicts the next token's distribution.
#Teacher Forcing: How to Train a Decoder
This code needs PyTorch, and in places a GPU, so it cannot run on this page. Copy it to Google Colab to run it.
# Copy to Colab: needs torch, so it cannot run on this page.
# Build an LSTM cell from scratch (forget/input/output gates)
# Train it on character-level prediction, then compare with GRU
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
# === Hand-rolled LSTM cell ===
class LSTMCell(nn.Module):
def __init__(self, input_dim, hidden_dim):
super().__init__()
self.hidden_dim = hidden_dim
# One big linear layer for all 4 gates (efficient)
self.gates = nn.Linear(input_dim + hidden_dim, 4 * hidden_dim)
def forward(self, x_t, state):
h_prev, c_prev = state
combined = torch.cat([x_t, h_prev], dim=-1)
gates = self.gates(combined)
f, i, g, o = gates.chunk(4, dim=-1)
f = torch.sigmoid(f) # forget gate
i = torch.sigmoid(i) # input gate
g = torch.tanh(g) # candidate
o = torch.sigmoid(o) # output gate
c_t = f * c_prev + i * g # cell state update (the gradient highway)
h_t = o * torch.tanh(c_t) # hidden state output
return h_t, c_t
# === Train on character prediction ===
text = "the quick brown fox jumps over the lazy dog the quick brown fox jumps"
chars = sorted(set(text))
ch2i = {c: i for i, c in enumerate(chars)}
i2ch = {i: c for c, i in ch2i.items()}
V = len(chars)
# Convert to one-hot
data = torch.eye(V)[[ch2i[c] for c in text]] # (T, V)
H = 32
cell = LSTMCell(V, H)
out_proj = nn.Linear(H, V)
opt = torch.optim.Adam(list(cell.parameters()) + list(out_proj.parameters()), lr=0.05)
losses = []
for epoch in range(200):
h, c = torch.zeros(1, H), torch.zeros(1, H)
loss = 0.0
for t in range(len(data) - 1):
x_t = data[t].unsqueeze(0)
target = torch.tensor([ch2i[text[t + 1]]])
h, c = cell(x_t, (h, c))
logits = out_proj(h)
loss = loss + F.cross_entropy(logits, target)
opt.zero_grad(); loss.backward(); opt.step()
losses.append(loss.item())
if epoch % 50 == 0:
print(f"epoch {epoch:3d} loss={loss.item():.3f}")
print()
print("Final loss:", round(losses[-1], 3))
print()
# === Compare with PyTorch's built-in GRU on the same task ===
gru = nn.GRU(input_size=V, hidden_size=H, batch_first=True)
gru_proj = nn.Linear(H, V)
opt2 = torch.optim.Adam(list(gru.parameters()) + list(gru_proj.parameters()), lr=0.05)
x = data[:-1].unsqueeze(0) # (1, T-1, V)
y = torch.tensor([ch2i[c] for c in text[1:]]) # (T-1,)
for epoch in range(200):
out, _ = gru(x)
logits = gru_proj(out.squeeze(0))
loss = F.cross_entropy(logits, y)
opt2.zero_grad(); loss.backward(); opt2.step()
print("GRU final loss:", round(loss.item(), 3))
print()
print("Both models learned the pattern. LSTM has more parameters")
print("(4 gates worth) but GRU often matches accuracy with ~25% fewer params.")
print()
print("CHALLENGE: Add gradient clipping (torch.nn.utils.clip_grad_norm_)")
print("to the LSTM training loop. Does it help or hurt convergence?")Notes for going further:
# Gradient clipping for the LSTM training loop:
# torch.nn.utils.clip_grad_norm_(
# list(cell.parameters()) + list(out_proj.parameters()),
# max_norm=1.0
# )
# Insert AFTER loss.backward() and BEFORE opt.step().
#
# On this tiny task it makes little difference, but on long sequences
# (>200 steps) it is essential. Without clipping, exploding gradients
# can cause loss to spike to NaN. With clipping, training is stable.
# The gating in LSTM/GRU mostly fixes vanishing gradients, but it does
# NOT fix exploding gradients — those still need clipping.What to check: Verify both LSTM and GRU losses drop below 0.5 within 200 epochs. Confirm the LSTM cell's forget/input/output gates are computed correctly via chunk(4).
#Bahdanau Attention: The Seed of the Transformer
The vanilla seq2seq model has a fatal bottleneck: the entire source sentence has to fit into ONE fixed-size context vector. Translating a 50-word sentence? Compressed into the same 512-dim vector as a 5-word sentence. Information loss is catastrophic for long sentences.
Is that bottleneck a matter of taste or a hard limit? A counting argument gives a ceiling. Open the derivation.
The win was immediate: Bahdanau-attention seq2seq outperformed vanilla seq2seq by 5+ BLEU on long sentences and matched the state-of-the-art statistical MT systems on short ones. Three years later, Vaswani et al. asked: "what if attention is all we need?", and showed that you can drop recurrence entirely. The transformer was born from this insight.
#Common Mistakes
#Production Architecture
#Key Takeaways
- Vanishing gradients through time killed vanilla RNNs. The gradient is a product of T derivatives, and tanh derivatives < 1 collapse the product to zero before signals from 30+ steps ago can influence learning
- LSTM's cell state is a gradient highway. The additive update c_t = f_t ⊙ c_ + i_t ⊙ g_t has no nonlinearity on the main path, so gradients flow back unchanged when forget≈1 and input≈0; this is what lets LSTMs learn 100+ step dependencies
- GRU is a simpler, often-equivalent alternative. Merges forget and input into one update gate, drops the cell state, has ~25% fewer parameters; on most benchmarks matches LSTM within noise (Greff 2017)
- Seq2Seq turned a stack of phrase rules into a single network. Encoder LSTM compresses input, decoder LSTM generates output, trained end-to-end with teacher forcing; powered Google Translate from 2016 to the transformer era
- Bahdanau attention was the seed of the transformer. Letting the decoder look back at every encoder state with learned weights solved the fixed-context-vector bottleneck and inspired "Attention Is All You Need" three years later
#Quick Check
Why does the LSTM cell state c_t allow gradients to flow back through long sequences without vanishing?