3 Model Architecture 1 / 9
  1. In this chapter
  2. From RNNs to Attention
  3. Attention Basics
  4. Positional Encoding Explained
  5. Transformer Block Explained
  6. Modern LLM Architecture
  7. Efficient Attention
  8. Mixture of Experts (MoE)
  9. Long Context
  10. State Space Models and Hybrids
All chapters →

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.

Beginner 31 min read Updated Companion code ↓

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
  1. Why sequences need a special network
  2. RNN: the same function, applied again and again
  3. The gradient has a long way to travel
  4. A fixed-size state is a bottleneck
  5. Attention: let the decoder look back
  6. Self-attention: every position reads every position
  7. Summary and exercises
  8. Quick self-test
  9. Further reading
  10. FAQ

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 tt to depend only on what comes before. There are two natural ideas:

  • A fixed window: look at the last kk 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:

ht=tanh⁡(Whht−1+Wxxt+b),y^t=softmax(Woht)h_t=\tanh\big(W_h h_{t-1}+W_x x_t+b\big),\qquad \hat y_t=\mathrm{softmax}\big(W_o h_t\big)

hth_t is the hidden state at step tt, which you can think of as a summary of x1,…,xtx_1,\dots,x_t, and y^t\hat y_t is the resulting prediction of the next token. The three matrices Wh,Wx,WoW_h,W_x,W_o are shared across all time steps.

For training, unroll the recurrence in time: a sequence of length TT becomes a feed-forward network of depth TT 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 ∂ht/∂ht−1=diag(1−ht2) Wh\partial h_t/\partial h_{t-1}=\mathrm{diag}(1-h_t^{2})\,W_h, so

∂hT∂h0=∏t=1Tdiag(1−ht2) Wh\frac{\partial h_T}{\partial h_0}=\prod_{t=1}^{T}\mathrm{diag}\big(1-h_t^{2}\big)\,W_h

Pascanu et al. (2013) draw two conclusions from this product. If the largest singular value λ1\lambda_1 of WhW_h is below 1/γ1/\gamma (γ\gamma 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 WhW_h above 1 is only a necessary condition for exploding gradients, not a sufficient one.

A numerical experiment makes this concrete. Take Wh=ρQW_h=\rho Q with QQ a random orthogonal matrix (all singular values equal to ρ\rho), a 64-dimensional state and random inputs, and compute the spectral norm of ∂hT/∂h0\partial h_T/\partial h_0 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 −46.6-46.6 means 10−46.610^{-46.6}.

  • ρ=0.5\rho=0.5: the sufficient condition above holds; by T=10T=10 only 10−4.110^{-4.1} is left and at T=100T=100 it is 10−46.610^{-46.6}.
  • ρ=1.0\rho=1.0: every singular value is exactly 1 and the gradient still vanishes (10−19.310^{-19.3} at T=100T=100). The reason is that the derivative of tanh, 1−h21-h^2, is below 1, so every step multiplies by one more diagonal matrix of entries below 1.
  • ρ=1.5\rho=1.5: at T=10T=10 the gradient is still growing (10+0.210^{+0.2}), but by T=100T=100 it has fallen to 10−5.210^{-5.2}. 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.
  • ρ=2.0\rho=2.0 and 4.04.0: gradients explode, reaching 10+2.610^{+2.6} and 10+17.210^{+17.2} at T=100T=100.

Between vanishing and exploding there is only a narrow band of ρ\rho, 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 gradient's road: RNN's chain of products and attention's direct path Comparison diagram: on the left, in an RNN the loss sits at the last step and the gradient travels back along the h5-to-h0 chain, multiplying one Jacobian per step — exponentially vanishing when its norm is below one, exploding above; on the right, attention connects the decoder straight to every position, so the gradient arrives in one step with no chain of products. Bottom conclusion: exploding has a cheap fix (clipping); vanishing does not — the structure must change. The gradient's road: RNN's chain of products and attention's direct path Loss (at the last step) RNN: one chain, multiplied at every step forward h0 h1 h2 h3 h4 ×J ×J ×J backward: one Jacobian per step, ⊙J_t Attention: one step to every position Loss (at the last step) h0 h1 h2 h3 h4 loss reaches every position in one step, no chain exploding has a cheap fix (gradient clipping); vanishing does not — the structure must change (gating, attention)
Left: the RNN gradient returns from the last step along the chain, multiplying one Jacobian per step; the product makes long-range gradients vanish or explode exponentially. Right: attention lets the loss reach every position in one step — that is why it can train long-range dependencies.
## Gates: a path that does not multiply by small numbers

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:

ct=ft⊙ct−1+it⊙gt,ht=ot⊙tanh⁡(ct)c_t=f_t\odot c_{t-1}+i_t\odot g_t,\qquad h_t=o_t\odot\tanh(c_t)

it,ft,oti_t,f_t,o_t are sigmoid gates computed from the current input and the previous state (input, forget and output gate), and gtg_t is the candidate update. Along the direct cell-state path the gradient is multiplied at each step only by the forget gate ftf_t, 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: ht=zt⊙ht−1+(1−zt)⊙h~th_t=z_t\odot h_{t-1}+(1-z_t)\odot\tilde h_t.

Do gates really help? The next experiment measures the influence of the first input x1x_1 on the last state hTh_T, that is, the gradient norm of the sum of the components of hTh_T with respect to x1x_1. Inputs are random vectors and all models use PyTorch’s default initialization; only the forget-gate bias bfb_f of the LSTM is set by hand (at bf=0b_f=0 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 bf=0b_f=0 all decay exponentially, to 10−26.110^{-26.1}, 10−19.810^{-19.8} and 10−20.410^{-20.4} at T=100T=100; 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 bf=1b_f=1 the gradient at T=200T=200 is 10−14.210^{-14.2}, far better than the plain RNN’s 10−52.210^{-52.2} but still decaying; with bf=3b_f=3 it stays near 10−0.310^{-0.3} 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 bf=5b_f=5 the gradient grows slowly with TT (10+0.610^{+0.6} at T=200T=200): 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 tt waits for step t−1t-1, 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 ii it no longer relies on a single vector but takes a weighted average of the states h1,…,hLh_1,\dots,h_L of all positions of the encoder:

eij=a(si−1,hj),αij=exp⁡eij∑kexp⁡eik,ci=∑jαij hje_{ij}=a(s_{i-1},h_j),\qquad \alpha_{ij}=\frac{\exp e_{ij}}{\sum_{k}\exp e_{ik}},\qquad c_i=\sum_{j}\alpha_{ij}\,h_j

si−1s_{i-1} is the previous decoder state, aa is a small feed-forward network (the alignment model), αij\alpha_{ij} is the weight of output word ii on input position jj, and cic_i 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 cic_i as an “expected annotation” over all possible alignments. Luong et al. (2015) simplified the score to a dot product si⊤hjs_i^{\top}h_j, 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):

ModelAll sentencesSentences without unknown words
Basic encoder-decoder, 3013.9324.19
With attention (RNNsearch), 3021.5031.44
Basic encoder-decoder, 5017.8226.71
With attention (RNNsearch), 5026.7534.16
RNNsearch, 50, trained longer28.4536.15
Moses (phrase-based system)33.3035.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 tt whose strongest attention is exactly on position tt is 0.995, the mean weight on position tt 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 tt no longer depends on the output at position t−1t-1, so the whole sequence can be computed at once. For language-model training a causal mask (position tt may only see tokens ≤t\le t) 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).

Information paths in a recurrent network and in self-attention Top: a recurrent network. The hidden states of six positions form a chain, so the input at position 1 needs five recurrent steps to influence the state at position 6. Bottom: self-attention. Position 6 reads every earlier position directly, and position 1 is one step away. Recurrent network: information moves along a chain, 5 steps from position 1 to 6 h₁ h₂ h₃ h₄ h₅ h₆ x₁ x₂ x₃ x₄ x₅ x₆ Self-attention: every position reads all positions, 1 step from position 1 to 6 h₁ h₂ h₃ h₄ h₅ h₆ x₁ x₂ x₃ x₄ x₅ x₆
The path from position 1 to position 6 (amber). In the recurrent network it takes 5 recurrent steps and the gradient is multiplied 5 times; in self-attention position 6 reads position 1 directly, and likewise every other position.

Table 1 of Vaswani et al. compares the cost of several layer types (nn is the sequence length, dd the representation dimension):

Layer typeComplexity per layerSequential operationsMaximum path length
Self-attentionO(n2d)O(n^{2}d)O(1)O(1)O(1)O(1)
RecurrentO(nd2)O(nd^{2})O(n)O(n)O(n)O(n)

Self-attention brings both the number of sequential operations and the maximum path length down to constants. The price is O(n2d)O(n^{2}d) 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:

  1. 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).
  2. Gradients multiply Jacobians along time: singular values below 1 guarantee exponential decay, the derivative of tanh below 1 makes even an orthogonal WhW_h vanish, and the band of ρ\rho between vanishing and exploding is narrow (experiment 1).
  3. 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).
  4. 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).
  5. Self-attention makes the maximum path length and the number of sequential operations constant, at the cost of O(n2d)O(n^{2}d) 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:

  1. How many parameters do the single-layer nn.RNN, nn.GRU and nn.LSTM of experiment 2 have (16 input dimensions, 64 hidden units, and PyTorch keeps two bias vectors per gate)? Why are the ratios 1:3:4?
  2. If tanh in experiment 1 were replaced by the identity function, the norm of ∂hT/∂h0\partial h_T/\partial h_0 would be exactly ρT\rho^T. Compute log⁡10\log_{10} of it at T=100T=100 for ρ=0.5\rho=0.5 and ρ=2.0\rho=2.0, compare with the table of experiment 1, and say what tanh does.
  3. Table 1 gives O(n2d)O(n^{2}d) per layer for self-attention and O(nd2)O(nd^{2}) for a recurrent layer. Ignoring constants, what is their ratio for n=4096n=4096, d=1024d=1024? And for n=32768n=32768? What does it tell you?
Reference answers
  1. nn.RNN has 64×16+64×64+64+64=524864\times16+64\times64+64+64=5248 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.
  2. log⁡100.5100=−30.1\log_{10}0.5^{100}=-30.1 and log⁡102100=+30.1\log_{10}2^{100}=+30.1. The results in experiment 1 are −46.6-46.6 and +2.6+2.6: at ρ=0.5\rho=0.5 the derivative of tanh is below 1 and makes the decay faster; at ρ=2.0\rho=2.0 some units saturate, their derivative is close to 0, and the explosion is held back, reaching only 102.610^{2.6} at T=100T=100. So tanh makes even an orthogonal matrix vanish and also puts a brake on explosion, but the brake is not reliable: at ρ=4.0\rho=4.0 it still reaches 1017.210^{17.2}.
  3. The ratio is n/dn/d: 4 for n=4096n=4096 and 32 for n=32768n=32768. 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 dd, 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

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.