Chapter 3 · Model Architecture 3.1
From RNNs to Attention: Why the Transformer Appeared
An RNN squeezes history into one fixed-size state and computes it step by step, so gradients pass through a long chain of multiplications. Attention lets every position read every other position directly, in parallel. Experiments measure vanishing gradients, gating and the copy bottleneck.
After this page you will be able to
- Write the recurrence of an RNN, explain why it handles any sequence length, and say what backpropagation through time (BPTT) is.
- Explain why gradients vanish or explode over time, and read the roles of the spectral radius, the activation derivative and gating.
- Describe what path the gates of an LSTM or GRU build for the gradient, and why the forget-gate bias matters.
- Explain why a fixed-size state is a bottleneck, write the weighted sum behind attention, and say what self-attention improves (path length, parallelism) and what it costs.
On this page
A recurrent neural network (RNN) reads a sequence by keeping one fixed-size state vector and updating it after every token. That design has two fundamental problems. Information has to travel down a long chain to reach the place that needs it, and the gradient along that chain decays exponentially; and the computation must proceed one step after another, so it cannot be parallelized across the sequence. Attention answers both by letting every position read any other position directly: the path length drops to 1 and all positions are computed at the same time. The Transformer takes that idea to its end and drops the recurrence altogether. This page follows that line of history and measures each “why” with an experiment.
Why sequences need a special network
The feed-forward networks on the previous page have fixed input and output sizes, while text has variable length; a language model also needs the prediction at position to depend only on what comes before. There are two natural ideas:
- A fixed window: look at the last tokens only, concatenate them into a fixed-size vector and feed it to a feed-forward network (the neural language model of Bengio et al., 2003, does exactly this). It is simple, but everything outside the window is invisible, and a bigger window means more parameters.
- Recurrence: apply the same parameters at every position and carry what has been read in a state vector. The parameter count does not depend on the sequence length, so in principle any input length works.
RNNs take the second road.
RNN: the same function, applied again and again
The simplest RNN (Elman, 1990) does the same thing at every time step:
is the hidden state at step , which you can think of as a summary of , and is the resulting prediction of the next token. The three matrices are shared across all time steps.
For training, unroll the recurrence in time: a sequence of length becomes a feed-forward network of depth whose layers all have the same weights. Backpropagation on this unrolled graph, as on the previous page, is called backpropagation through time (BPTT). A long sequence is therefore a very deep network for training purposes, and the problem of multiplying gradients through many layers carries over unchanged.
The gradient has a long way to travel
Read the recurrent gradient calculation
The gradient of the loss with respect to an early state contains a product of Jacobians. For a tanh RNN the Jacobian of one step is , so
Pascanu et al. (2013) draw two conclusions from this product. If the largest singular value of is below ( is a bound on the derivative of the activation, 1 for tanh), every one-step Jacobian has norm below 1, and long-range gradients decay exponentially with distance (a sufficient condition). Conversely, a spectral radius of above 1 is only a necessary condition for exploding gradients, not a sufficient one.
A numerical experiment makes this concrete. Take with a random orthogonal matrix (all singular values equal to ), a 64-dimensional state and random inputs, and compute the spectral norm of directly.
import numpy as np
STEPS = (10, 50, 100, 200)
HEAD = " ".join(f"{'T=' + str(T):^11}" for T in STEPS)
def jacobian_logs(rho, T=200, n=64, seed=0):
r = np.random.default_rng(seed)
Q, _ = np.linalg.qr(r.normal(size=(n, n)))
# every singular value of W equals rho
W, U = rho * Q, r.normal(size=(n, n)) / np.sqrt(n)
h, J, logs = np.zeros(n), np.eye(n), {}
for t in range(1, T + 1):
h = np.tanh(W @ h + U @ r.normal(size=n))
J = np.diag(1 - h ** 2) @ W @ J # product of dh_t/dh_0
logs[t] = np.log10(np.linalg.norm(J, 2))
return logs
def cell(values):
return f"{np.mean(values):+7.1f}±{np.std(values):.1f}"
print("log10 of ‖∂h_T/∂h_0‖, mean±std over 5 seeds")
print(f"{'rho':<12}{HEAD}")
for rho in (0.5, 1.0, 1.5, 2.0, 4.0):
runs = [jacobian_logs(rho, seed=s) for s in range(5)]
print(f"{rho:<12}" + " ".join(
cell([run[T] for run in runs]) for T in STEPS))
log10 of ‖∂h_T/∂h_0‖, mean±std over 5 seeds
rho T=10 T=50 T=100 T=200
0.5 -4.1±0.1 -23.1±0.1 -46.6±0.1 -94.2±0.7
1.0 -1.3±0.1 -9.3±0.2 -19.3±0.3 -39.0±0.4
1.5 +0.2±0.1 -2.2±0.3 -5.2±0.6 -11.5±0.7
2.0 +1.0±0.2 +1.8±0.2 +2.6±0.2 +4.2±0.3
4.0 +2.8±0.2 +8.9±0.8 +17.2±1.4 +33.1±1.6
The numbers are base-10 logarithms, so means .
- : the sufficient condition above holds; by only is left and at it is .
- : every singular value is exactly 1 and the gradient still vanishes ( at ). The reason is that the derivative of tanh, , is below 1, so every step multiplies by one more diagonal matrix of entries below 1.
- : at the gradient is still growing (), but by it has fallen to . Part of the units are pushed into the saturated region of tanh, where the derivative is close to 0, and that pulls the growth back down.
- and : gradients explode, reaching and at .
Between vanishing and exploding there is only a narrow band of , and the band moves with the input (through how saturated the units are). This is what Bengio et al. (1994) meant: learning long-range dependencies by gradient descent is inherently hard. Exploding has a cheap remedy (gradient clipping, proposed by Pascanu et al., 2013; see Optimizers and Training Stability); vanishing has none, and the architecture has to change.
The long short-term memory network (LSTM, Hochreiter and Schmidhuber, 1997) adds a second state channel that is updated additively instead of being rewritten by a matrix product at every step:
are sigmoid gates computed from the current input and the previous state (input, forget and output gate), and is the candidate update. Along the direct cell-state path the gradient is multiplied at each step only by the forget gate , not by a weight matrix; when the forget gate is close to 1, the gradient flows back almost unchanged. The forget gate was added later by Gers et al. (2000). The gated recurrent unit (GRU) of Cho et al. (2014) does something similar with one update gate: .
Do gates really help? The next experiment measures the influence of the first input on the last state , that is, the gradient norm of the sum of the components of with respect to . Inputs are random vectors and all models use PyTorch’s default initialization; only the forget-gate bias of the LSTM is set by hand (at the forget gate starts near 0.5).
import torch
import torch.nn as nn
torch.set_num_threads(4)
# float32 would underflow to 0 near 1e-45
torch.set_default_dtype(torch.float64)
def reach(make, T, seeds=8):
logs = []
for s in range(seeds):
torch.manual_seed(s)
model = make()
x = torch.randn(32, T, 16, requires_grad=True)
out, _ = model(x)
out[:, -1].sum().backward() # gradient of h_T w.r.t. x_1
logs.append(x.grad[:, 0].norm(dim=1).log10().mean().item())
return cell(logs)
def lstm(forget_bias):
m = nn.LSTM(16, 64, batch_first=True)
with torch.no_grad(): # gate order: i, f, g, o
m.bias_ih_l0[64:128] = 0.0
m.bias_hh_l0[64:128] = forget_bias
return m
models = {"tanh RNN": lambda: nn.RNN(16, 64, batch_first=True),
"GRU": lambda: nn.GRU(16, 64, batch_first=True),
"LSTM b_f=0": lambda: lstm(0.0),
"LSTM b_f=1": lambda: lstm(1.0),
"LSTM b_f=3": lambda: lstm(3.0),
"LSTM b_f=5": lambda: lstm(5.0)}
print("log10 of ‖∂h_T/∂x_1‖, mean±std over 8 seeds")
print(f"{'':<12}{HEAD}")
for name, make in models.items():
print(f"{name:<12}" + " ".join(reach(make, T) for T in STEPS))
print("initial forget gate sigmoid(b_f):",
", ".join(f"b_f={b} -> {torch.sigmoid(torch.tensor(float(b))):.3f}"
for b in (0, 1, 3, 5)))
log10 of ‖∂h_T/∂x_1‖, mean±std over 8 seeds
T=10 T=50 T=100 T=200
tanh RNN -2.3±0.1 -12.9±0.5 -26.1±1.1 -52.2±2.3
GRU -2.0±0.1 -10.0±0.3 -19.8±0.6 -39.5±1.1
LSTM b_f=0 -2.4±0.1 -10.5±0.3 -20.4±0.8 -40.1±1.7
LSTM b_f=1 -1.2±0.1 -4.1±0.2 -7.6±0.5 -14.2±1.2
LSTM b_f=3 -0.3±0.0 -0.3±0.1 -0.3±0.2 -0.3±0.3
LSTM b_f=5 -0.2±0.0 +0.1±0.1 +0.3±0.1 +0.6±0.2
initial forget gate sigmoid(b_f): b_f=0 -> 0.500, b_f=1 -> 0.731, b_f=3 -> 0.953, b_f=5 -> 0.993
The widget below makes these two tables draggable: switch between “by rho” and “by gating”, drag T, and watch log10 ‖gradient‖ cross the dashed log10 = 0 line from vanishing to exploding — rho=1 still vanishes (tanh’s derivative is always below 1), b_f=3 pins the gradient near 10^-0.3.
- With the defaults, the tanh RNN, the GRU and the LSTM with all decay exponentially, to , and at ; gates alone do not solve the problem. Jozefowicz et al. (2015) make the same point: the usual initialization puts the forget gate near 0.5, which is a decay factor of 0.5 per step.
- Raising the forget-gate bias changes the picture. With the gradient at is , far better than the plain RNN’s but still decaying; with it stays near from 10 to 200 steps. This is why Jozefowicz et al. recommend initializing the forget-gate bias to 1 or 2, although it is only the starting value and training keeps adjusting it.
- With the gradient grows slowly with ( at ): the forget gate is almost always open and the cell becomes an integrator that only accumulates and never forgets. That is the risk at the other end.
Gates push the dependency length that can be learned from a dozen steps to a hundred or more, but the computation is still sequential: step waits for step , and training cannot be parallelized across the sequence.
A fixed-size state is a bottleneck
Machine translation has variable-length inputs and outputs. Sutskever et al. (2014) and Cho et al. (2014) used an encoder-decoder: an encoder RNN reads the whole source sentence and its last state stands for the sentence, and a decoder RNN starts from that vector and generates the translation word by word. Sutskever’s model is an LSTM with 4 layers of 1000 units, and the paper states that it uses 8000 real numbers to represent a sentence.
They also report an instructive effect: feeding the source sentence in reverse order lowers the test perplexity from 5.8 to 4.7 and raises BLEU from 25.9 to 30.6. Their explanation is that reversing puts the first words of the source close to the first words of the target, which creates many short-range dependencies and cuts the “minimal time lag”, so backpropagation finds it easier to connect the two ends. It is another sign that path length decides what can be learned.
In the same year Bahdanau et al. (2014) argued that squeezing all the information of a sentence into one fixed-length vector is a bottleneck in itself, citing the observation of Cho et al. that the performance of a basic encoder-decoder deteriorates rapidly as sentences get longer.
Attention: let the decoder look back
The idea of Bahdanau et al. is that when the decoder generates word it no longer relies on a single vector but takes a weighted average of the states of all positions of the encoder:
is the previous decoder state, is a small feed-forward network (the alignment model), is the weight of output word on input position , and is the context vector. Because a weighted average is differentiable, no alignment labels are needed: the gradient flows through the weights straight from the loss, and the whole system is trained jointly. The paper interprets as an “expected annotation” over all possible alignments. Luong et al. (2015) simplified the score to a dot product , which works as well and is cheaper; the experiment below uses the dot product.
The comparison of Bahdanau et al. on WMT’14 English-to-French translation (Table 1 of the paper, BLEU; the 30 and 50 in the model names are the sentence-length limits in words used during training):
| Model | All sentences | Sentences without unknown words |
|---|---|---|
| Basic encoder-decoder, 30 | 13.93 | 24.19 |
| With attention (RNNsearch), 30 | 21.50 | 31.44 |
| Basic encoder-decoder, 50 | 17.82 | 26.71 |
| With attention (RNNsearch), 50 | 26.75 | 34.16 |
| RNNsearch, 50, trained longer | 28.45 | 36.15 |
| Moses (phrase-based system) | 33.30 | 35.63 |
The attention model is clearly better in both settings, and the paper also plots BLEU by sentence length: the basic model degrades quickly as sentences get longer, while RNNsearch-50 shows no deterioration on sentences of 50 words or more. On all sentences, which include unknown words, RNNsearch still trails Moses; on sentences without unknown words it has caught up (34.16 against 35.63), and the longer-trained version is slightly ahead (36.15).
Those are results of large systems with many moving parts. The following toy task isolates the bottleneck and runs on a laptop: copying. The input is 4 to 32 random digits and the output must reproduce them. The encoder is a GRU, the decoder a GRUCell, and attention uses the dot-product form above. The two models are identical except for the attention; the decoder starts from the last encoder state, and the decoding length is known (a simplification that avoids an end-of-sequence token). Training uses Adam with 64 sequences per step and a length drawn at random between 4 and 32; evaluation uses independent test sets and greedy decoding without feeding in the answers. Three controls rule out “it just did not train long enough” and “the state is just too small”: 3 times as many training steps, a hidden state widened from 128 to 512 dimensions, and a second random seed.
import torch.nn.functional as F
torch.set_default_dtype(torch.float32)
V, E, BOS = 10, 32, 10 # 10 digits; BOS starts decoding
LENGTHS = (4, 8, 12, 16, 24, 32)
class Seq2Seq(nn.Module):
def __init__(self, attn, H):
super().__init__()
self.attn = attn
self.emb = nn.Embedding(V + 1, E)
self.enc = nn.GRU(E, H, batch_first=True)
self.dec = nn.GRUCell(E, H)
self.out = nn.Linear(2 * H if attn else H, V)
def forward(self, src, tgt=None): # teacher forcing if tgt given
enc, h = self.enc(self.emb(src)) # encoder state per position
s = h[0] # start from the last state
y = torch.full((src.shape[0],), BOS)
logits, aligns = [], []
for t in range(src.shape[1]):
s = self.dec(self.emb(y), s)
if self.attn: # dot-product attention
a = torch.softmax(torch.einsum("bh,blh->bl", s, enc), -1)
c = torch.einsum("bl,blh->bh", a, enc)
logits.append(self.out(torch.cat([s, c], -1)))
aligns.append(a)
else:
logits.append(self.out(s))
y = tgt[:, t] if tgt is not None else logits[-1].argmax(-1)
return torch.stack(logits, 1), aligns
def train(attn, H, steps, seed):
torch.manual_seed(seed)
model = Seq2Seq(attn, H)
opt = torch.optim.Adam(model.parameters(), lr=2e-3)
data = torch.Generator().manual_seed(1000 + seed) # own data seed
for _ in range(steps):
L = int(torch.randint(4, 33, (), generator=data))
x = torch.randint(0, V, (64, L), generator=data)
logits, _ = model(x, x) # copy: target is x
loss = F.cross_entropy(logits.reshape(-1, V), x.reshape(-1))
opt.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
return model
def test_set(L, n=500):
g = torch.Generator().manual_seed(5000 + L) # independent test set
return torch.randint(0, V, (n, L), generator=g)
def accuracy(model):
exact, token = [], []
for L in LENGTHS:
x = test_set(L)
with torch.no_grad():
ok = model(x)[0].argmax(-1) == x # greedy decoding
exact.append(ok.all(1).float().mean().item())
token.append(ok.float().mean().item())
return exact, token
configs = [(True, 128, 2000, 0), (True, 128, 2000, 1),
(False, 128, 2000, 0), (False, 128, 2000, 1),
(False, 128, 6000, 0), (False, 512, 2000, 0)]
trained = {cfg: train(*cfg) for cfg in configs}
results = {cfg: accuracy(m) for cfg, m in trained.items()}
titles = ("exact-match accuracy (whole sequence)", "per-digit accuracy")
for i, name in enumerate(titles):
print(f"{name}, 500 test sequences per length")
print(f"{'attn':<5}{'H':>4}{'steps':>6}{'seed':>5}{'params':>10} |"
+ "".join(f"{'L=' + str(L):>7}" for L in LENGTHS))
for cfg, res in results.items():
attn, H, steps, seed = cfg
n = sum(p.numel() for p in trained[cfg].parameters())
print(f"{'yes' if attn else 'no':<5}{H:>4}{steps:>6}{seed:>5}{n:>10,} |"
+ "".join(f"{v:7.3f}" for v in res[i]))
print()
se = (0.93 * 0.07 / 500) ** 0.5
print(f"standard error of an accuracy of 0.93 on 500 sequences: {se:.3f}")
for attn in (True, False):
r0, r1 = (results[(attn, 128, 2000, s)][0] for s in (0, 1))
gap = max(abs(x - y) for x, y in zip(r0, r1))
tag = 'yes' if attn else 'no'
print(f"attn={tag}: the two seeds differ by at most {gap:.3f}")
exact-match accuracy (whole sequence), 500 test sequences per length
attn H steps seed params | L=4 L=8 L=12 L=16 L=24 L=32
yes 128 2000 0 127,338 | 1.000 0.998 0.986 0.988 0.970 0.924
yes 128 2000 1 127,338 | 1.000 0.998 0.994 0.996 0.978 0.930
no 128 2000 0 126,058 | 1.000 0.662 0.092 0.002 0.000 0.000
no 128 2000 1 126,058 | 0.998 0.648 0.064 0.000 0.000 0.000
no 128 6000 0 126,058 | 0.998 0.918 0.430 0.034 0.000 0.000
no 512 2000 0 1,682,794 | 0.998 0.902 0.764 0.612 0.054 0.000
per-digit accuracy, 500 test sequences per length
attn H steps seed params | L=4 L=8 L=12 L=16 L=24 L=32
yes 128 2000 0 127,338 | 1.000 0.999 0.995 0.995 0.988 0.968
yes 128 2000 1 127,338 | 1.000 1.000 0.998 0.998 0.991 0.975
no 128 2000 0 126,058 | 1.000 0.871 0.626 0.481 0.337 0.282
no 128 2000 1 126,058 | 0.999 0.872 0.618 0.468 0.342 0.281
no 128 6000 0 126,058 | 0.999 0.975 0.854 0.663 0.456 0.359
no 512 2000 0 1,682,794 | 0.999 0.974 0.949 0.923 0.768 0.605
standard error of an accuracy of 0.93 on 500 sequences: 0.011
attn=yes: the two seeds differ by at most 0.008
attn=no: the two seeds differ by at most 0.028
Every number in the tables is a proportion over 500 test sequences; at an accuracy near 0.93 the sampling standard error is about 0.011.
- With attention (128 dimensions, 2000 steps): at length 32 the whole sequence is copied correctly in 0.924 and 0.930 of the cases (the two seeds), and the per-digit accuracy is 0.968 and 0.975. The two seeds differ by at most 0.008 in whole-sequence accuracy, less than the sampling error, so that difference is not interpreted.
- Without attention, same 128 dimensions and 2000 steps: at length 8 it still copies 0.662 and 0.648, at length 12 it drops to 0.092 and 0.064, and from length 16 on it is about 0; at length 32 the per-digit accuracy is only 0.282 and 0.281. The two seeds differ by at most 0.028 (at length 12), more than the sampling error, so read only the order of magnitude in that range, not which seed is ahead.
- Control 1, three times as many steps (6000): length 8 rises to 0.918, length 12 to 0.430, length 16 to 0.034, and length 24 and above stay at 0.000. Longer training pushes the copyable length out, but slowly.
- Control 2, a state widened to 512 dimensions (2000 steps; see the params column for the parameter counts): length 12 gives 0.764, length 16 gives 0.612, length 24 gives 0.054 and length 32 is still 0.000. A bigger state holds more, so the bottleneck does depend on the size of the state; but 4 times the width and many more parameters still did not copy a whole sequence at length 32.
The comparison supports one statement: on this toy task, with these hyperparameters and the same training budget, adding attention to the 128-dimensional model helps much more than widening the state fourfold or training three times longer. It does not generalize to “attention is always better”, and it is certainly not a statement about translation; without attention, a larger state and longer training keep improving, but the design of “squeeze everything into one vector” makes every extra digit more expensive.
What did the attention learn? For the first attention model, on test sequences of length 16, look at where the attention weights of each output step fall:
model = trained[configs[0]]
with torch.no_grad():
_, aligns = model(test_set(16))
A = torch.stack(aligns, 1) # (sequence, step t, position l)
pos = A.argmax(-1)
print(f"L=16: share of steps whose strongest attention is on position t: "
f"{(pos == torch.arange(16)).float().mean():.3f}")
print(f"mean weight on position t at step t: "
f"{A.diagonal(dim1=1, dim2=2).mean():.3f}")
print("positions attended in the first sequence:", pos[0].tolist())
L=16: share of steps whose strongest attention is on position t: 0.995
mean weight on position t at step t: 0.994
positions attended in the first sequence: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Nobody told the model how to align, and it learned a diagonal on its own: the share of steps whose strongest attention is exactly on position is 0.995, the mean weight on position is 0.994, and in the first sequence the 16 steps attend to positions 0 to 15 in order. The best alignment for copying is a monotonic diagonal. In real translation alignment is more varied: Bahdanau et al. note that English-French alignment is largely monotonic but has non-monotonic cases, for instance when translating European Economic Area into zone économique européenne the model first aligns with Area and then looks back one word at a time. The principle is the same: the weights are differentiable and the gradient pushes them toward the positions that help the task.
Self-attention: every position reads every position
Vaswani et al. (2017) made two changes to attention: queries, keys and values all come from the same sequence, which is self-attention, and the recurrence is dropped entirely, with position information added separately through positional encodings. The computation at position no longer depends on the output at position , so the whole sequence can be computed at once. For language-model training a causal mask (position may only see tokens ) lets a single forward pass produce the predictions and losses of all positions, which is what allowed Transformers to scale training (details in Attention Basics).
Table 1 of Vaswani et al. compares the cost of several layer types ( is the sequence length, the representation dimension):
| Layer type | Complexity per layer | Sequential operations | Maximum path length |
|---|---|---|---|
| Self-attention | |||
| Recurrent |
Self-attention brings both the number of sequential operations and the maximum path length down to constants. The price is compute per layer and, at inference, keeping the keys and values of all positions (the KV cache). For very long sequences that bill becomes the bottleneck, which is what Efficient Attention and Long Context are about. The ideas of RNNs have not disappeared either: linear attention and state space models recast “a fixed-size state with a per-step cost that does not grow with length” into forms that can be trained in parallel, and they are attracting attention again for long-sequence inference. That thread continues in State Space Models and Hybrid Architectures, which measures the capacity of a fixed-size state and checks the cache that hybrids save.
Summary and exercises
Key points:
- An RNN applies the same parameters at every step and squeezes the history into a fixed-size state; training unrolls the recurrence and runs backpropagation (BPTT).
- Gradients multiply Jacobians along time: singular values below 1 guarantee exponential decay, the derivative of tanh below 1 makes even an orthogonal vanish, and the band of between vanishing and exploding is narrow (experiment 1).
- Gates build an additive path for the gradient, but with a forget-gate bias of 0 they do not help; the gate has to start near 1 (experiment 2).
- A fixed-size state is a bottleneck and attention lets the decoder read every position; on the copy task, with the same encoder and decoder, only the model with attention copies long sequences (experiment 3).
- Self-attention makes the maximum path length and the number of sequential operations constant, at the cost of compute and a KV cache.
Quick self-test
1. After unrolling an RNN in time, what do its parameters look like?
- Every time step has its own set of parameters
- All time steps share one set of parameters, so the parameter count does not depend on the sequence length
- The parameter count grows in proportion to the sequence length
- Only the first time step has parameters
The unrolled network is as deep as the sequence is long, but every layer uses the same W_h, W_x and W_o. That is why an RNN can take any length, and why the gradient is multiplied by the same matrix again and again.
2. In experiment 1, with rho = 1.0 all singular values of W_h are 1. Why does only 10^-19.3 of the gradient remain after 100 steps?
- An orthogonal matrix turns the gradient into 0
- The tanh derivative 1 - h^2 is below 1, so every step multiplies by one more diagonal matrix with entries below 1
- The random inputs are too small
- float64 does not have enough precision
The Jacobian of one step is diag(1 - h^2) W_h. An orthogonal W_h keeps the norm, but the entries of diag(1 - h^2) lie between 0 and 1, and multiplying 100 of them is exponential decay. To avoid the decay W_h would have to amplify, which brings saturation or explosion, so the usable range of rho is narrow.
3. In experiment 2, what are the gradient norms of the first input with respect to the last state after 200 steps for an LSTM with forget-gate bias b_f = 0 and one with b_f = 3?
- Both about 10^-40
- About 10^-40 and 10^-0.3, the latter barely decayed
- Both barely decayed
- About 10^-0.3 and 10^+33
With b_f = 0 the forget gate starts near 0.5, which keeps half per step, and after 200 steps only 10^-40.1 is left, close to the GRU’s 10^-39.5. With b_f = 3 the forget gate is about 0.95, the gradient flows back along the additive path almost unchanged, and after 200 steps it is still 10^-0.3.
4. On the copy task, which setting gives the highest share of fully correct copies at length 32?
- No attention, 128 dimensions, 6000 training steps
- No attention, 512 dimensions, 2000 training steps
- With attention, 128 dimensions, 2000 training steps
- All three are about the same
At length 32 the model with attention reaches 0.924 and 0.930 (two seeds), and both of the others are 0.000. The comparison holds for this toy task and these hyperparameters only; it is not a general statement about attention.
5. Compared with an RNN, which two entries of Table 1 of Vaswani et al. does self-attention bring down to constants, and at what cost?
- Compute per layer and parameter count, at the cost of no parallelism
- Sequential operations and maximum path length, at the cost of O(n^2 d) compute per layer and a KV cache of all positions at inference
- Memory and latency, at the cost of vanishing gradients
- Parameter count and maximum path length, at the cost of not handling variable-length sequences
In Table 1 self-attention has O(1) sequential operations and O(1) maximum path length against O(n) for an RNN; but its compute per layer is O(n^2 d) against O(n d^2), and for very long sequences the former becomes the bottleneck.
Exercises:
- How many parameters do the single-layer
nn.RNN,nn.GRUandnn.LSTMof experiment 2 have (16 input dimensions, 64 hidden units, and PyTorch keeps two bias vectors per gate)? Why are the ratios 1:3:4? - If tanh in experiment 1 were replaced by the identity function, the norm of would be exactly . Compute of it at for and , compare with the table of experiment 1, and say what tanh does.
- Table 1 gives per layer for self-attention and for a recurrent layer. Ignoring constants, what is their ratio for , ? And for ? What does it tell you?
Reference answers
nn.RNNhas parameters; a GRU has 3 such sets of weights (update gate, reset gate, candidate state), 15,744 in total; an LSTM has 4 (input gate, forget gate, candidate, output gate), 20,992 in total. The ratio is 1:3:4, and the numbers above were checked with PyTorch.- and . The results in experiment 1 are and : at the derivative of tanh is below 1 and makes the decay faster; at some units saturate, their derivative is close to 0, and the explosion is held back, reaching only at . So tanh makes even an orthogonal matrix vanish and also puts a brake on explosion, but the brake is not reliable: at it still reaches .
- The ratio is : 4 for and 32 for . The longer the sequence is compared with the representation dimension, the more a self-attention layer costs relative to a recurrent layer; for sequences shorter than , self-attention is actually cheaper. This is only an order-of-magnitude estimate, since real speed also depends on how much parallelism the hardware can exploit, which is one reason self-attention does well on GPUs.
Further reading
- Elman, Finding structure in time (Cognitive Science, 1990): the simple recurrent network.
- Bengio, Simard and Frasconi, Learning long-term dependencies with gradient descent is difficult (IEEE TNN, 1994); Pascanu, Mikolov and Bengio, On the difficulty of training recurrent neural networks (2013): analysis of vanishing and exploding gradients, and gradient clipping.
- Hochreiter and Schmidhuber, Long short-term memory (1997); Gers, Schmidhuber and Cummins, Learning to forget (2000); Jozefowicz, Zaremba and Sutskever, An empirical exploration of recurrent network architectures (2015): the LSTM, the forget gate and the forget-gate bias.
- Cho et al., Learning Phrase Representations using RNN Encoder-Decoder (2014); Sutskever, Vinyals and Le, Sequence to Sequence Learning with Neural Networks (2014): the encoder-decoder and the GRU.
- Bahdanau, Cho and Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (2014); Luong, Pham and Manning, Effective Approaches to Attention-based Neural Machine Translation (2015): the start of attention and its dot-product form.
- Bengio et al., A Neural Probabilistic Language Model (JMLR, 2003): the fixed-window neural language model.
- Vaswani et al., Attention Is All You Need (2017); see also the paper explainer.
- Karpathy, The Unreasonable Effectiveness of Recurrent Neural Networks; Olah, Understanding LSTM Networks; Olah and Carter, Attention and Augmented Recurrent Neural Networks: visual explanations.
FAQ
- Why did the Transformer replace RNNs?
- There are three main reasons. Path length - in an RNN two tokens n positions apart are separated by n recurrent steps and the gradient is multiplied n times, while in attention any two positions are one step apart. Parallelism - step t of an RNN has to wait for step t-1, whereas attention is computed for all positions at once, which suits GPUs and large-scale training. Bottleneck - a fixed-size hidden state limits how much can be remembered, while attention keeps the representation of every position and reads what it needs. The price is compute that grows with the square of the sequence length, plus a KV cache at inference time.
- Do LSTM and GRU solve the vanishing gradient problem?
- They mitigate it without removing it. Gates give the gradient an additive path that barely decays while the forget gate is close to 1, so an LSTM can handle dependencies a hundred steps long. With the forget-gate bias at its default of 0, however, each step keeps only about half, and in the experiment on this page the gradient after 200 steps is still around 10^-40, no better in kind than a plain RNN. And however the gates are designed, the computation stays sequential.
- What does "attention" mean here, and does it relate to human attention?
- Here attention is just a differentiable weighted average. A query is scored against a key for every position, a softmax turns the scores into weights, and the values of all positions are summed with those weights. It models nothing about human attention; the name comes from the metaphor in Bahdanau et al. (2014) that the model "attends" to different source positions while translating each word. The weights can be drawn as alignment maps to see where the model looks, but a large weight is not the same as a large causal contribution to the output.
- Are RNNs still useful today?
- Yes. Linear attention, RWKV and state space models such as Mamba recast the idea of a fixed-size state with constant cost per step into forms that can be trained in parallel; at inference the memory and compute per generated token do not grow with the context, which makes them interesting for long-sequence and on-device use. For small sequence tasks (sensors, time series, small speech models) GRUs and LSTMs are also still in use.