Why Recurrence Hit a Wall: Long Dependencies and Attention
Train a GRU encoder-decoder to reverse digit sequences and watch its accuracy collapse as the sequences grow, because the whole input must pass through one fixed vector; add Bahdanau-style additive attention in a few lines, measure the recovery, read the attention weights, and see what attention left unsolved that the transformer took on.
Contentsand lesson path
On this page
- Why it matters
- The fixed-vector bottleneck
- Additive attention in a few lines
- Reading the attention weights
- Still recurrent: the step to the transformer
- Check your understanding
- Apply it
- Review prompt
Lessons of Sequence Models & RNNs
- From Text and Time Series to Tensors Concept · 20 min
- Recurrent Networks and Their Gates Concept · 20 min
- Lab: Sentiment Classification with Embeddings and an LSTM Lab · 30 min
- Worked Example: Forecasting with a GRU Without Peeking at the Future Worked example · 25 min
- Why Recurrence Hit a Wall: Long Dependencies and Attention Concept · 15 min
- Check: Sequences, Gates and Masks Knowledge check · 6 questions
What you will learn
- Explain vanishing and exploding gradients in recurrent networks, how gating and gradient clipping mitigate them, and why encoder-decoder attention was introduced.
Prerequisites: Deep Learning Fundamentals
01. Why it matters
Many sequence tasks map one sequence to another of a different length: translating a sentence, summarising a paragraph, turning speech into text. Around 2014 the standard design for these was the encoder-decoder, also called sequence-to-sequence (seq2seq). An encoder RNN reads the source and its final hidden state is handed to a decoder RNN, which generates the output one token at a time, each step taking the token it produced before. In that design, everything the decoder knows about the source has to fit into one vector of fixed size, however long the source is. Attention was invented to remove that limit, and it is the direct ancestor of the transformer.
This lesson makes the limit visible on a toy task: reverse a sequence of random digits. The task needs no knowledge of language, only memory, so any failure is a failure of the architecture. You need Python 3.12 and PyTorch 2 (CPU build). Each training run takes about a minute on one CPU thread, and the last digit of the outputs can differ on other CPUs or library versions.
02. The fixed-vector bottleneck
The model in seq2seq.py has a GRU encoder and a decoder built from nn.GRUCell, which computes one recurrent step at a time so that the loop can feed each prediction back in. Two terms describe that loop. During training the decoder gets the true previous digit as input, called teacher forcing; at test time it gets its own previous prediction, called greedy decoding, so one mistake can lead to more. Without attention, the decoder starts from the encoder's final state h_n[-1] and never sees the source again.
Training uses sequences of 4 to 20 digits, one length per batch, so no padding is needed. The test scores two things for each length: the share of digits that are right, and the share of sequences that are right in full. Ignore the attention parts of the file for now; the next section explains them. The script also accepts --attention, and gives the plain model a larger state (80 instead of 64) so that both versions have about the same number of weights.
import torch
from torch import nn
class AdditiveAttention(nn.Module):
"""Bahdanau-style score: v . tanh(W_s s + W_h h_j), one score per source step."""
def __init__(self, hidden, attn=32):
super().__init__()
self.W_s = nn.Linear(hidden, attn, bias=False)
self.W_h = nn.Linear(hidden, attn, bias=False)
self.v = nn.Linear(attn, 1, bias=False)
def keys(self, enc): # W_h h_j: once per source sentence
return self.W_h(enc)
def forward(self, s, enc, keys): # s: (B, H), enc: (B, T, H)
scores = self.v(torch.tanh(self.W_s(s).unsqueeze(1) + keys)).squeeze(-1)
weights = scores.softmax(dim=-1) # (B, T), rows sum to 1
context = (weights.unsqueeze(-1) * enc).sum(dim=1) # (B, H)
return context, weights
if __name__ == "__main__":
torch.manual_seed(0)
attn = AdditiveAttention(hidden=4, attn=3)
enc = torch.randn(2, 5, 4) # 2 sentences, 5 encoder states each
s = torch.randn(2, 4) # one decoder state per sentence
context, weights = attn(s, enc, attn.keys(enc))
print("weights:\n", weights.detach().numpy().round(3))
print("row sums:", weights.sum(-1).detach().numpy().round(3))
print("context shape:", tuple(context.shape))import sys
import torch
from torch import nn
from attention import AdditiveAttention
torch.set_num_threads(1)
SOS, VOCAB = 10, 11 # digits 0-9, plus a start token
def batch(n, length, gen):
src = torch.randint(0, 10, (n, length), generator=gen)
return src, src.flip(1) # the task: output the digits reversed
class Seq2Seq(nn.Module):
def __init__(self, use_attention, H):
super().__init__()
self.use_attention = use_attention
self.emb = nn.Embedding(VOCAB, 16)
self.encoder = nn.GRU(16, H, batch_first=True)
self.attn = AdditiveAttention(H) if use_attention else None
self.cell = nn.GRUCell(16 + (H if use_attention else 0), H)
self.out = nn.Linear(H * (2 if use_attention else 1), VOCAB)
def forward(self, src, tgt): # training: feed the true previous digit
enc, h_n = self.encoder(self.emb(src))
s = h_n[-1] # without attention: the only link to src
keys = self.attn.keys(enc) if self.use_attention else None
prev = torch.full((len(src),), SOS)
logits, maps = [], []
for i in range(tgt.shape[1]):
x = self.emb(prev)
if self.use_attention:
context, w = self.attn(s, enc, keys)
maps.append(w)
s = self.cell(torch.cat([x, context], dim=1), s)
logits.append(self.out(torch.cat([s, context], dim=1)))
else:
s = self.cell(x, s)
logits.append(self.out(s))
# teacher forcing in training, greedy decoding (own prediction) at test
prev = tgt[:, i] if self.training else logits[-1].argmax(1)
return torch.stack(logits, 1), maps
def train(use_attention, hidden, steps=1000):
torch.manual_seed(0)
gen = torch.Generator().manual_seed(0)
model = Seq2Seq(use_attention, hidden)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for step in range(steps):
length = int(torch.randint(4, 21, (1,), generator=gen)) # 4 to 20 digits
src, tgt = batch(64, length, gen)
logits, _ = model(src, tgt)
loss = nn.functional.cross_entropy(logits.reshape(-1, VOCAB), tgt.reshape(-1))
opt.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
return model
@torch.no_grad()
def accuracy(model, length):
model.eval()
src, tgt = batch(500, length, torch.Generator().manual_seed(1000 + length))
pred = model(src, tgt)[0].argmax(-1)
hit = pred == tgt
return hit.float().mean().item(), hit.all(1).float().mean().item()
if __name__ == "__main__":
use_attention = "--attention" in sys.argv
hidden = 64 if use_attention else 80 # similar numbers of weights
model = train(use_attention, hidden)
print("attention:", use_attention,
" parameters:", sum(p.numel() for p in model.parameters()))
for length in (5, 10, 15, 20):
digit, whole = accuracy(model, length)
print(f"length {length:2d}: digits right {digit:.3f}"
f" whole sequence right {whole:.3f}")
torch.save(model.state_dict(), "attention.pt" if use_attention else "plain.pt")python seq2seq.pyattention: False parameters: 48107
length 5: digits right 0.997 whole sequence right 0.992
length 10: digits right 0.755 whole sequence right 0.254
length 15: digits right 0.474 whole sequence right 0.000
length 20: digits right 0.349 whole sequence right 0.000Five digits are easy: almost every sequence is reversed correctly. At 10 digits only a quarter of the sequences survive, and from 15 digits on not a single one does, although 15 and 20 digits are well inside the training range. The digit accuracy at 20, 0.349, is only about three times the 0.1 of guessing. The 80 numbers of the final state cannot hold 20 digits in the right order precisely enough, and the gradients that should teach the encoder about early digits must cross the whole sequence and the whole output, as in recurrent networks and their gates. Bahdanau, Cho and Bengio pointed to exactly this in 2014: the translation quality of basic encoder-decoders fell quickly as sentences grew longer.
03. Additive attention in a few lines
The fix is to keep all encoder states h₁ … hₜ and let the decoder look back at them at every output step. Before producing output i, the decoder scores every source position j against its current state s: score = v · tanh(Wₛ s + Wₕ hⱼ). This is additive attention, from Bahdanau et al., named for the sum inside the tanh. A softmax turns the scores into attention weights that are positive and sum to 1, and the context vector is the weighted average of the encoder states. The decoder uses that context both as an extra input to its GRU cell and next to its state when it predicts the digit.
In attention.py, the class has three small weight matrices. keys() computes Wₕ hⱼ for every source position once per sentence, because the encoder states do not change while the decoder runs; only Wₛ s is recomputed at each step. The demo below runs it on random tensors to show the shapes.
python attention.pyweights:
[[0.21 0.17 0.217 0.146 0.257]
[0.212 0.142 0.317 0.136 0.193]]
row sums: [1. 1.]
context shape: (2, 4)Each sentence gets one row of five weights that sums to 1, and one context vector of the encoder's size, 4. With random weights the attention is spread out; training is what makes it sharp. Now train the same encoder-decoder with attention switched on.
python seq2seq.py --attentionattention: True parameters: 49499
length 5: digits right 0.997 whole sequence right 0.992
length 10: digits right 0.975 whole sequence right 0.922
length 15: digits right 0.931 whole sequence right 0.822
length 20: digits right 0.834 whole sequence right 0.576With about the same number of weights, the same data and the same 1,000 steps, whole-sequence accuracy at 15 digits goes from 0 to 0.822, and digit accuracy at 20 from 0.349 to 0.834. Accuracy still falls with length, because the model is small and briefly trained and greedy decoding lets one error cause others, but the collapse is gone.
04. Reading the attention weights
The decoder returns its attention weights at each step, so you can print where it looked while reversing one sequence of 8 digits. attn_map.py loads the weights saved by the last run.
import torch
from seq2seq import Seq2Seq
model = Seq2Seq(use_attention=True, H=64)
model.load_state_dict(torch.load("attention.pt", weights_only=True))
model.eval()
src = torch.tensor([[3, 1, 4, 1, 5, 9, 2, 6]])
with torch.no_grad():
logits, maps = model(src, src.flip(1))
weights = torch.stack(maps, 1)[0] # (output steps, source steps)
print("source: ", src[0].tolist())
print("prediction: ", logits.argmax(-1)[0].tolist())
print("attention weights (row = output step, column = source position):")
for i, row in enumerate(weights):
print(f" out {i}: " + " ".join(f"{w:.2f}" for w in row.tolist())
+ f" max at {row.argmax().item()}")python attn_map.pysource: [3, 1, 4, 1, 5, 9, 2, 6]
prediction: [6, 2, 9, 5, 1, 4, 1, 3]
attention weights (row = output step, column = source position):
out 0: 0.00 0.00 0.00 0.00 0.04 0.02 0.00 0.93 max at 7
out 1: 0.00 0.01 0.00 0.00 0.03 0.01 0.01 0.94 max at 7
out 2: 0.00 0.00 0.00 0.00 0.00 0.00 0.99 0.00 max at 6
out 3: 0.00 0.00 0.00 0.00 0.07 0.88 0.05 0.00 max at 5
out 4: 0.00 0.00 0.00 0.00 0.88 0.09 0.02 0.02 max at 4
out 5: 0.00 0.00 0.01 0.98 0.00 0.00 0.00 0.00 max at 3
out 6: 0.00 0.00 0.99 0.00 0.00 0.00 0.00 0.00 max at 2
out 7: 0.01 0.90 0.05 0.02 0.01 0.01 0.00 0.01 max at 1The reversal is correct, and the weights form a sharp anti-diagonal: almost all of each row sits on one position, moving from the end of the source towards the start. Look closely, though. Output 3 produces the 5 at position 4, but puts 0.88 of its weight on position 5. From output 1 on, the model mostly looks one position after the digit it writes. Its encoder reads left to right, so the state at position 5 most likely still carries a memory of the digit at position 4, and the model found that state useful. Attention weights show which encoder states the decoder mixed, not a guaranteed word-by-word alignment; Bahdanau et al. used an encoder that also reads backwards, so that each state describes its own token from both sides.
05. Still recurrent: the step to the transformer
Attention removed the bottleneck, but the model is still recurrent. The encoder computes hⱼ from hⱼ₋₁, so the 20 encoder steps run one after another, and so do the decoder steps. During training this sequential chain is the main cost, and it limits how much a GPU, which is fast when it can do many independent operations at once, can speed it up. Long-range information also still travels step by step inside the encoder.
The transformer (Vaswani et al., 2017) kept attention and removed the recurrence. Every position attends directly to every other position of the same sequence, called self-attention, so all positions of a training sequence can be computed in parallel and any two tokens are one step apart. It uses a cheaper scaled dot-product score instead of the additive one, and adds position information explicitly, since nothing in attention itself knows the order. The cost is that the number of scores grows with the square of the length. The next skill starts exactly there: attention as a soft lookup with queries, keys and values.
06. Check your understanding
07. Apply it
The practice project centres on a classifier or forecaster, but the same diagnosis applies whenever a model squeezes a long sequence into one vector.
- Make the encoder bidirectional (
bidirectional=True, and twice the size in the attention and the cell), retrain with attention, and check whether the weights inattn_map.pymove onto the digit being written. - Train both versions on lengths 4 to 10 only and test at 15 and 20, to separate the bottleneck from generalisation to unseen lengths.
- For your own LSTM or GRU classifier, replace
h_n[-1]with an attention-weighted average of alloutputstates, masked at the pads, and compare over three seeds.
08. Review prompt
Without looking back, describe an encoder-decoder and the single vector that links its two halves; explain why its accuracy falls with sequence length; write the additive attention score and say what the softmax and the context vector do; explain the difference between teacher forcing and greedy decoding; say what attention weights do and do not tell you; and explain what attention left sequential and how the transformer changed that.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.