Session S16

Transformer I

S14's self-attention lets every position read every other position in one step. It still cannot see word order, runs only one lookup per position, and has no nonlinearity of its own. What does it need before it can replace an RNN?

Deep Learning · CS 4715/5715 · University of Idaho

S14 built self-attention and named three things it still lacks

Today starts where S14 ended, with its attention formula, in which each query and key has \(d_k\) entries.

\[\boxed{\;\operatorname{attention}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V\;}\]
  • Self-attention: \(Q=XW_Q\), \(K=XW_K\), \(V=XW_V\) from one sequence \(X\) of \(T\) tokens, \(d\) numbers each; scores (T, T). Any two positions are one dot product apart, and all \(T\) rows come out at once: no serial loop.
S14's lackwhat it meansthe fix S14 named
1 · No notion of ordershuffle the tokens of \(X\) and each token's output shuffles with it, unchanged otherwisepositional encodings
2 · One lookup per positionone row of weights per query: one weighted averagemulti-head attention
3 · Linear in the valuesonce the weights are fixed, no nonlinearity acts on the valuesstacked blocks with feedforward layers

Today changes the layer first, then its input, then what surrounds it

Today takes the three lacks in a different order: first the attention layer itself (lack 2), then what goes into it (lack 1), then what wraps it (lack 3). Part 1 first places the 2017 paper that made all three changes.

partthe question it answers
1 · 2017: attention without recurrencewhat did the Transformer keep, delete and add, and why did it matter?
2 · Several lookups at oncehow can one position read several others at once? Multi-head attention: shapes, code, the usual bug, the cost
3 · Word orderhow can a layer that cannot see order be given it? A derivation, positional encodings, a test; three generations of encodings
4 · A block that stackswhat must surround attention so that layers stack? Three pieces, named today, assembled in S17
5 · Closetoday's answer; HW3, which goes out at S18

The three bold questions answer the title page's question, one lack each. First, 2017.

In 2017 the Transformer deleted the recurrence, kept the attention and added structure

Part 1 · 2017: attention without recurrence. S14's attention came from translation, where it connected two recurrent networks.

By 20162017 decoderdecoderdecoder encoderencoderencoder decoderdecoderdecoder encoderencoderencoder attention deleted kept added several headsPart 2positional encodingsPart 3residual connectionsPart 4normalizationPart 4feedforward layersPart 4
  • Vaswani et al., "Attention Is All You Need" (NeurIPS 2017): delete the recurrence, keep the attention, and add the structure a deep stack of attention needs to train.
  • The model translated better than the recurrent state of the art, and because every position is processed in parallel, it trained in a fraction of the time (reading 3.3).

Today's Parts 2, 3 and 4 cover the structure added around attention, as the figure lists.

The original model had about 65M parameters and set a new state of the art in translation

What the paper built (reading 3.3); each term is defined today or in S17.

  • Base configuration: 6 encoder + 6 decoder layers; model width \(d_{\text{model}}=512\), the numbers per token (S14's \(d\)); 8 attention heads (Part 2); feedforward width \(d_{\text{ff}}=2048\) (Part 4); about 65M parameters.
  • Result: state-of-the-art translation quality on English–German and English–French (BLEU, an automatic score against human reference translations).
  • Why it matters: the same block, scaled up and stacked deeper, kept working. Nearly a decade later it is the architecture of essentially every large language model (LLM).

Part 2 starts with the 8 heads: why one attention computation per layer is not enough.

One head gives one weighted average, but a word may need three others

Part 2 · Several lookups at once. S14's second lack: each position gets one row of weights, so one weighted average. In this sentence, wrote needs its subject, its object and its adverb:

Thestudentwhoreadthepaperwrotethecodequickly 1/31/31/3 one output for wrote: ⅓ vstudent + ⅓ vcode + ⅓ vquickly
  • wrote's query gives one row of weights over the 10 tokens and one output \(\sum_i\alpha_i\mathbf{v}_i\). Suppose the row puts \(1/3\) on each of the three words: the subject's, object's and adverb's values are added into one vector.
  • The row sums to 1: more weight on student means less on code and quickly.

One row of weights per position gives one kind of lookup; the next page gives several.

Multi-head attention runs \(h\) smaller heads and concatenates them

Run S14's attention formula \(h\) times in parallel, each head with its own learned projections into \(d_{\text{head}}\) dimensions:

\[\mathrm{head}_j=\operatorname{attention}\!\left(XW_Q^{(j)},\,XW_K^{(j)},\,XW_V^{(j)}\right),\qquad j=1,\dots,h\] \[\operatorname{MultiHead}(X)=\operatorname{Concat}(\mathrm{head}_1,\dots,\mathrm{head}_h)\,W_O,\qquad d_{\text{head}}=d_{\text{model}}/h\]
(1)(2)(3)(4) attentionattentionattentionattention ×=×= X WQ, WK, WV WO Q, K, V MultiHead(X) concatenate T × 64 64 × 644 × 16 columns T × 64 eachcut into 4 heads T × 16T × 16 T × 64 64 × 64mixes the heads T × 64

\(d_{\text{model}}\) is S14's \(d\), and \(h\) is n_heads.

Each head's softmax runs on its own scores: one head can weight student, another code.

Multi-head attention is matrix products, a split, a softmax and a merge

The formula on reading 3.3's sizes, with a batch of \(B\) sequences of \(T\) tokens: \(d_{\text{model}}=64\), \(h=4\), \(d_{\text{head}}=16\).

stepwhat it doeskindresult
input\(X\): 64 numbers per token(B, T, 64)
project\(Q=XW_Q\), \(K=XW_K\), \(V=XW_V\)matrix product(B, T, 64) each
split64 columns as 4 heads of 16; head axis moved forwardview, transpose(B, 4, T, 16)
scoresdot products \(QK^\top\) per sequence and head, divided by \(\sqrt{16}\)matrix product(B, 4, T, T)
weightssoftmax along each row, over the keyssoftmax, per row(B, 4, T, T)
head outputsweights times \(V\), per sequence and headmatrix product(B, 4, T, 16)
concatenatethe 4 heads side by side againtranspose, view(B, T, 64)
\(W_O\)times \(W_O\), \(64\times64\)matrix product(B, T, 64)

Every head sees all \(T\) tokens: heads split the 64 features, not the sequence. In and out (B, T, 64); the split and the merge only move numbers.

Reading 3.3's class projects once, splits, attends and merges

The table as code; H in the comments is n_heads. Imports: math, torch, torch.nn as nn, torch.nn.functional as F. Not shown: the reading's causal argument and its two mask lines (S17).


class MultiHeadSelfAttention(nn.Module):
    def __init__(self, d_model, n_heads):
        super().__init__()
        assert d_model % n_heads == 0
        self.n_heads = n_heads
        self.d_head = d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model)   # Q, K, V in one matmul
        self.proj = nn.Linear(d_model, d_model)      # output projection W_O
    def forward(self, x):
        B, T, D = x.shape
        q, k, v = self.qkv(x).chunk(3, dim=-1)
        # (B, T, D) -> (B, n_heads, T, d_head)
        def split(t):
            return t.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
        q, k, v = split(q), split(k), split(v)
        scores = q @ k.transpose(-2, -1) / math.sqrt(self.d_head)  # (B, H, T, T)
        attn = F.softmax(scores, dim=-1)
        out = attn @ v                                             # (B, H, T, d_head)
        out = out.transpose(1, 2).contiguous().view(B, T, D)       # concat heads
        return self.proj(out)
  

Running the steps one at a time reproduces the class's output

A habit for HW3 (out at S18): know the shape after every line. Here the forward's steps run one at a time on the class's own layers, \(B=2\), \(T=8\), printing each shape:


# math, torch, F, MultiHeadSelfAttention: the previous page
mha = MultiHeadSelfAttention(d_model=64, n_heads=4)
x = torch.randn(2, 8, 64)                         # (B, T, d_model)
q, k, v = mha.qkv(x).chunk(3, dim=-1)
qh, kh, vh = (t.view(2, 8, 4, 16).transpose(1, 2) for t in (q, k, v))
scores = qh @ kh.transpose(-2, -1) / math.sqrt(16)
heads = F.softmax(scores, dim=-1) @ vh
cat = heads.transpose(1, 2).contiguous().view(2, 8, 64)
out = mha.proj(cat)
for name, t in [("x", x), ("q", q), ("q split", qh), ("scores", scores),
                ("heads", heads), ("concat", cat), ("out", out)]:
    print(f"{name:8}{tuple(t.shape)}")
print(torch.equal(out, mha(x)))
  

x       (2, 8, 64)
q       (2, 8, 64)
q split (2, 4, 8, 16)
scores  (2, 4, 8, 8)
heads   (2, 4, 8, 16)
concat  (2, 8, 64)
out     (2, 8, 64)
True
  
  • chunk(3, dim=-1): three equal parts of the last axis. view: the same numbers, a new shape. transpose(1, 2): swap axes 1 and 2. contiguous(): a copy in the order view needs.
  • @ on 4-axis tensors: one matrix product per (sequence, head). True: the step-by-step run equals mha(x) bit for bit.

Each head divides by \(\sqrt{d_{\text{head}}}\), as S14's variance argument requires

The class divides by math.sqrt(self.d_head), not \(\sqrt{d_{\text{model}}}\): S14's argument with \(d_k=d_{\text{head}}\).

  • A head's \(\mathbf{q}\cdot\mathbf{k}\) sums \(d_{\text{head}}\) products (independent entries, mean 0, variance 1): variance \(d_{\text{head}}\). Divided by \(\sqrt{d_{\text{head}}}\): \(d_{\text{head}}/(\sqrt{d_{\text{head}}})^2=1\). Every head's softmax starts unsaturated.
q · k: 16 products variance 16 variance 1 variance 1/4 = 1/h ÷ √dhead = √16 = 4÷ √dmodel = √64 = 8 this classflatter weights

HW3's scaled_dot_product_attention takes \(d_k\) from q.shape[-1] (its docstring): on the split queries, that is \(d_{\text{head}}\).

Each head is S14's attention formula at width \(d_{\text{head}}\), scale included.

The usual HW3 bug gives the right shape with the wrong rows

The class splits in two calls; a single view gives the same shape and is HW3's usual bug (reading 3.3). A tensor whose entries name their origin, \(10\cdot\text{token}+\text{feature}\): \(B=1\), \(T=3\), \(d_{\text{model}}=4\), \(h=2\), so \(d_{\text{head}}=2\).


import torch
B, T, D, h = 1, 3, 4, 2
x = (10 * torch.arange(T)[:, None] + torch.arange(D)).view(B, T, D)
right = x.view(B, T, h, D // h).transpose(1, 2)   # (1, 2, 3, 2)
wrong = x.view(B, h, T, D // h)                   # (1, 2, 3, 2)
print(x[0])
print(right[0, 0])                       # head 0, right split
print(wrong[0, 0])                       # head 0, one view
  
token 0token 1token 2 0123101112132021222301101120210123101112132021222301231011 x[0] right: x.view(B, T, h, D // h) .transpose(1, 2) head 0: features 0–1 of tokens 0, 1, 2 wrong: one view refills the shape in memory order. x[0] row 0row 1row 2 row 0row 1row 2 token 0, features 2–3token 1, features 0–1 The cells hold what print(x[0]), print(right[0, 0]) and print(wrong[0, 0]) give.
  • [:, None] makes the token numbers a column, so the sum broadcasts to (T, D) (S08).
  • Same shape, no error here: a model built this way trains, but its loss plateaus far above a correct one's (reading 3.3).

A test checks that head \(j\) holds every token's \(j\)-th feature slice

The shape did not catch the bug; a test with a known answer does. In head \(j\), token \(t\)'s row must be token \(t\)'s features \(j\,d_{\text{head}}\) to \((j+1)\,d_{\text{head}}-1\):


# torch, x, right, wrong, D, h: the previous page
d_head = D // h
for name, heads in [("right", right), ("wrong", wrong)]:
    ok = all(torch.equal(heads[:, j], x[:, :, j * d_head:(j + 1) * d_head])
             for j in range(h))
    print(name, ok)
  

right True
wrong False
  
  • HW3's packed layout (one qkv layer, then chunk): the one view raises an error that suggests .reshape(...), and reshape(B, n_heads, T, d_head) runs with these same wrong rows; HW3's test_mha_head_split_manual catches it.

Right shapes and running code do not catch a wrong split; a known answer does, as S14's row sums caught the wrong axis.

Any number of heads costs the same parameters and multiply-adds

Several heads, at what price? The class's parameters sit in qkv (\(W_Q\), \(W_K\), \(W_V\) side by side) and proj (\(W_O\)).

WQ h = 1h = 4h = 8 WK, WV and WO are cut the same way. Cutting columns does not change the count: 4(642 + 64) = 16,640. attention weights h = 1: T2 numbersh = 4: h · T2 numbers
  • Scores: \(h\) heads, \(T^2\) dot products each, of length \(d_{\text{head}}\): \(h\cdot T^2\cdot d_{\text{head}}=T^2\,d_{\text{model}}\) multiply-adds (S14's MACs), as for one head of width \(d_{\text{model}}\). Weights times \(V\): likewise.

# torch, MultiHeadSelfAttention: the class page
for h in [1, 4, 8]:
    m = MultiHeadSelfAttention(d_model=64, n_heads=h)
    print(h, sum(p.numel() for p in m.parameters()))
  

1 16640
4 16640
8 16640
  

\(h\) places to look, for the parameters and multiply-adds of one full-width head.

Some trained heads take nameable roles, and many can be pruned

Nothing in the formula assigns a role to a head; training does. What analyses of trained models report (reading 3.3):

previous token matching brackets resists naming (a(b)) Rows are queries and columns are keys; a darker cell is a larger weight. These are idealized patterns, not a trained model's weights.
  • Some heads take recognizable roles (previous token, matching brackets, the verb of a clause, the noun a pronoun refers to); others show patterns that resist naming.
  • Not all heads carry weight: Michel, Levy & Neubig, "Are Sixteen Heads Really Better than One?" (NeurIPS 2019): a substantial fraction of heads in trained translation and language models can be pruned after training with little loss; a core cannot.
  • In practice: n_heads is a mild hyperparameter; keep \(d_{\text{head}}\) large enough for informative dot products, typically 64 or more in production models.

Heads give a layer room for several lookups; training decides what each one looks up.

Self-check on heads, shapes and parameters

The 2017 base model's sizes, \(d_{\text{model}}=512\) and \(h=8\), with this part's formulas.

(a) What is \(d_{\text{head}}\)?

(b) The scores' shape for a batch of \(B=2\) sequences of \(T=10\) tokens?

(c) The four projections' parameter count? Does it change at \(h=16\)?

(a) \(512/8=64\).

(b) (2, 8, 10, 10): one \(T\times T\) matrix per sequence and head.

(c) \(4(512^2+512)=1{,}050{,}624\); unchanged at \(h=16\) (\(d_{\text{head}}=32\)): no \(h\) in the formula.

That settles several lookups. Next comes S14's first lack, word order.

Shuffle the tokens, and the outputs shuffle the same way

Part 3 · Word order. S14's first lack: shuffle the tokens of \(X\) and each token's output shuffles with it, unchanged otherwise. S14 showed it for one query, with key and value rows permuted together; in self-attention every token is also a query, so a shuffle moves the queries too.

  • The claim: shuffling the input tokens shuffles the output vectors the same way. Self-attention is permutation-equivariant.
self-attentionself-attention dogydogbitesybitesmanymanmanymanbitesybitesdogydog same vector
  • Dog gets the same output whether it bites or is bitten. For language, that is disqualifying.

The next page shows why it holds, in five steps from S14's notation.

Five steps show that \(\operatorname{attn}(PX)=P\,\operatorname{attn}(X)\)

S14's self-attention is \(\operatorname{attn}(X)=\operatorname{softmax}(S)\,V\) with \(S=QK^\top/\sqrt{d_k}\). A shuffle is a permutation matrix \(P\): the identity with its rows reordered.

  1. \(PX\) reorders the rows of \(X\): man bites dog is \(PX\) with \(P=\left[\begin{smallmatrix}0&0&1\\0&1&0\\1&0&0\end{smallmatrix}\right]\). Every permutation matrix has \(P^\top P=I\) (\(P^\top\) moves every row back).
  2. Projections: \((PX)W_Q=P(XW_Q)=PQ\), likewise \(PK\), \(PV\): each token's query, key and value move with it.
  3. SPSP⊤ dogbitesmanmanbitesdog dogbitesmanmanbitesdog rows and columns reordered alike
    Scores: \((PQ)(PK)^\top/\sqrt{d_k}=PSP^\top\).
  4. The softmax works on each row alone; reordering a row's entries reorders its weights (the exponentials' sum is unchanged): \(\operatorname{softmax}(PSP^\top)=P\operatorname{softmax}(S)P^\top\).
  5. Output: \(P\operatorname{softmax}(S)P^\top PV=P\operatorname{softmax}(S)V=P\operatorname{attn}(X)\), as \(P^\top P=I\).

The outputs move with the tokens, but their average does not

The derivation used three facts: the same \(W_Q\), \(W_K\), \(W_V\) for every token, a row-by-row softmax, and nothing that depends on position. So the claim needs its condition.

  • Precisely: self-attention is permutation-equivariant when there are no positional signals and no order-dependent mask (S17's causal mask is one: position \(t\) sees only positions up to \(t\)). Multi-head attention meets the same conditions (every head does, and \(W_O\) acts on each row alone), so it is equivariant too.
  • A pooled readout is invariant: with \(Y=\operatorname{attn}(X)\) and \(\mathbf{1}\) a column of \(T\) ones, the mean over positions \(\tfrac1T\mathbf{1}^\top Y\) does not change: \(\tfrac1T\mathbf{1}^\top PY=\tfrac1T\mathbf{1}^\top Y\), since \(\mathbf{1}^\top P=\mathbf{1}^\top\).
  • Two words: equivariant, the outputs move with the inputs; invariant, a summary does not move.

To see order, a token's vector must depend on where it stands, so that a shuffle changes more than the order of the rows.

The fix adds a position-dependent vector to every token's embedding

Before the first layer, add to each token's embedding (the row of a learned table indexed by the token's id; reading 3.1) a positional encoding \(\mathrm{PE}\) that depends only on the position: \(\mathbf{x}_{\mathrm{pos}}+\mathrm{PE}_{\mathrm{pos}}\). The 2017 paper's \(\mathrm{PE}\) is fixed sinusoids, for dimension pair \(i=0,\dots,d_{\text{model}}/2-1\):

\[\mathrm{PE}_{\mathrm{pos},\,2i}=\sin\!\left(\mathrm{pos}/10000^{2i/d_{\text{model}}}\right),\qquad \mathrm{PE}_{\mathrm{pos},\,2i+1}=\cos\!\left(\mathrm{pos}/10000^{2i/d_{\text{model}}}\right)\]
embeddingPEposinput dog+=pos 0bites+=pos 1man+=pos 2 The tokens move; the position vectors stay. pos 0pos 3pos 15 pair 0 (fast) PE at dmodel = 32 pair 15 (slow) +10−1

Pair \(i\) has wavelength \(2\pi\cdot10000^{2i/d_{\text{model}}}\): \(2\pi\) for pair 0, up to nearly \(10000\cdot2\pi\) for large \(d_{\text{model}}\). Positions one or two apart get close vectors.

  • The symmetry breaks: a shuffled sentence enters as \(PX+\mathrm{PE}\), not \(P(X+\mathrm{PE})\). The tokens move; the position vectors stay.

Position 3's encoding by hand, with \(d_{\text{model}}=32\)

Before testing the fix, one row by hand at the size the test uses, \(d_{\text{model}}=32\): 16 pairs, pair \(i\)'s angle \(\mathrm{pos}/10000^{2i/32}=\mathrm{pos}/10000^{i/16}\), each pair dividing by \(10000^{1/16}\approx1.778\) once more. Row \(\mathrm{pos}=3\):

\(i\)angle \(3/10000^{i/16}\)sin, dim \(2i\)cos, dim \(2i+1\)
0\(3\)0.1411−0.9900
1\(3/1.778=1.687\)0.9933−0.1160
2\(3/\sqrt{10}=0.9487\)0.81260.5828
⋮
15\(3/5623\approx5.3\times10^{-4}\)0.00051.0000
  • Row 0: every angle is 0, every pair \((\sin0,\cos0)=(0,1)\); the row is \((0,1,0,1,\dots)\).
  • Rows 0 and 3 differ strongly in the fast pairs, by less than 0.01 in the six slowest (\(i=10\) to 15).

The code on the next page builds this table for every position; the experiment prints rows 0 and 3.

The test needs a one-head layer and the sinusoids in PyTorch

The claim is testable, so test it (reading 3.3's script). SelfAttention is S14's self-attention, one head, \(d_k=d\); sinusoidal_pe builds the table:


import math, torch, torch.nn as nn, torch.nn.functional as F
class SelfAttention(nn.Module):
    def __init__(self, d):
        super().__init__()
        self.q = nn.Linear(d, d); self.k = nn.Linear(d, d); self.v = nn.Linear(d, d)
    def forward(self, x):
        s = self.q(x) @ self.k(x).transpose(-2, -1) / math.sqrt(x.shape[-1])
        return F.softmax(s, dim=-1) @ self.v(x)
def sinusoidal_pe(T, d):
    pos = torch.arange(T, dtype=torch.float32).unsqueeze(1)
    i = torch.arange(0, d, 2, dtype=torch.float32)  # the formula's 2i: 0, 2, ..., d-2
    angles = pos / (10000 ** (i / d))  # (T, 1) / (d/2,) -> (T, d/2)
    pe = torch.zeros(T, d)
    pe[:, 0::2] = torch.sin(angles)  # even columns
    pe[:, 1::2] = torch.cos(angles)
    return pe
  

unsqueeze(1) turns positions (T,) into a column (T, 1); 0::2 takes columns 0, 2, 4, …, and 1::2 columns 1, 3, 5, ….

The experiment shuffles six tokens, with and without \(\mathrm{PE}\)

The rest of reading 3.3's script, with SelfAttention and sinusoidal_pe from the previous page.


torch.manual_seed(0)
d_model, T = 32, 6
attn = SelfAttention(d_model)
x = torch.randn(1, T, d_model)          # 6 "tokens"
perm = torch.tensor([3, 1, 5, 0, 2, 4]) # a shuffle of positions
y = attn(x)
y_perm = attn(x[:, perm, :])
print(f"no PE:  max |attn(shuffled x) - shuffle(attn(x))| = "
      f"{(y_perm - y[:, perm, :]).abs().max().item():.8f}")
pe = sinusoidal_pe(T, d_model).unsqueeze(0)
z = attn(x + pe)
z_perm = attn(x[:, perm, :] + pe)
print(f"with PE: max |attn(shuffled x+PE) - shuffle(attn(x+PE))| = "
      f"{(z_perm - z[:, perm, :]).abs().max().item():.8f}")
pe_t = sinusoidal_pe(T, d_model)
print(f"\nPE row 0, first 6 dims: {[f'{v:.4f}' for v in pe_t[0, :6]]}")
print(f"PE row 3, first 6 dims: {[f'{v:.4f}' for v in pe_t[3, :6]]}")
  

By the derivation, should each of the two differences be about 0, or clearly not 0?

The difference is \(1.2\times10^{-7}\) without \(\mathrm{PE}\) and 0.144 with it

Answer: about 0 without \(\mathrm{PE}\), since \(\operatorname{attn}(PX)=P\,\operatorname{attn}(X)\); clearly not 0 with it. The printout:


no PE:  max |attn(shuffled x) - shuffle(attn(x))| = 0.00000012
with PE: max |attn(shuffled x+PE) - shuffle(attn(x+PE))| = 0.14426041

PE row 0, first 6 dims: ['0.0000', '1.0000', '0.0000', '1.0000', '0.0000', '1.0000']
PE row 3, first 6 dims: ['0.1411', '-0.9900', '0.9933', '-0.1160', '0.8126', '0.5828']
  
no PEwith PE 1.2 × 10−7 0.144 about 1.2 × 106 times larger 10−810−610−410−2100 PE rows 0 and 3, dims 0–5 row 0010101row 30.1411−0.99000.9933−0.11600.81260.5828
  • Without PE the two outputs agree to float32 rounding: the layer cannot see order. With PE they differ: position now matters.
  • Row 3 is the row computed by hand.

Positional encodings went from sinusoids to learned tables to rotations

The sinusoids pass the test, and they label absolute positions. Two more schemes followed; which one a model uses decides how it behaves past its training length, and a model card states it (reading 3.3).

schemeparameterspast the trained lengthencodes
fixed sinusoids (2017)nonedefined at any position; quality typically degradesabsolute position
learned embeddings
(BERT, GPT-1/2/3)
a trainable table, a row per positiona hard ceiling at the table's sizeabsolute position
rotary (RoPE), 2021nonedefined at any position; positions can be rescaled into the trained rangerelative offset
  • Language mostly cares about relative offsets: "the adjective two tokens back" is a useful pattern; "the adjective at position 41" is not. A learned table does not know that 7 relates to 8 as 107 relates to 108.

The third generation makes the offset the primitive; the next page shows how.

RoPE rotates \(\mathbf{q}\) and \(\mathbf{k}\) by position, so the score depends on \(n-m\)

Rotary position embedding (RoPE; Su et al., 2021) adds nothing to the embedding: in every attention layer it rotates each (even, odd) pair of query and key dimensions by an angle proportional to the position. One pair, frequency \(\theta\) (pair \(i\)'s \(10000^{-2i/d}\), as in the sinusoids):

  1. Rotation by angle \(a\): \(R(a)=\left[\begin{smallmatrix}\cos a&-\sin a\\\sin a&\cos a\end{smallmatrix}\right]\); rotations add angles, \(R(a)R(b)=R(a+b)\), and \(R(a)^\top=R(-a)\).
  2. Query at position \(m\): \(R(m\theta)\,\mathbf{q}\). Key at position \(n\): \(R(n\theta)\,\mathbf{k}\).
  3. Dot product: \((R(m\theta)\mathbf{q})^\top R(n\theta)\mathbf{k}=\mathbf{q}^\top R(-m\theta)R(n\theta)\,\mathbf{k}=\mathbf{q}^\top R\big((n-m)\theta\big)\,\mathbf{k}\).
  4. For fixed \(\mathbf{q}\) and \(\mathbf{k}\), the score depends only on \(n-m\). Summed over the pairs, each with its own \(\theta\), it still does. In a real sequence \(\mathbf{q}\) and \(\mathbf{k}\) also vary with the token, so the score carries both content and offset.

RoPE acts on \(\mathbf{q}\) and \(\mathbf{k}\), never on \(\mathbf{v}\): position arrives where scores are computed.

RoPE gives the same score at offset 2 wherever the pair sits

Reading 3.3's script: \(d=8\), random \(\mathbf{q}\), \(\mathbf{k}\) (seed 0), rotated as derived; then the same \(\mathbf{q}\), \(\mathbf{k}\) with sinusoids added, \((\mathbf{q}+\mathrm{PE}_m)\cdot(\mathbf{k}+\mathrm{PE}_n)\):


score q.k with RoPE applied, at various (query pos m, key pos n):
  m =   3, n =   1  (m - n = 2):  score = 5.9478093347
  m =  13, n =  11  (m - n = 2):  score = 5.9478093347
  m = 103, n = 101  (m - n = 2):  score = 5.9478093347
  m =   5, n =   1  (m - n = 4):  score = 4.7051479015
  m =  54, n =  50  (m - n = 4):  score = 4.7051479015
  m =   9, n =   1  (m - n = 8):  score = 5.6683275369

score (q + PE[m]).(k + PE[n]) with additive sinusoidal encodings:
  m =   3, n =   1  (m - n = 2):  score = 12.0287056485
  m =  13, n =  11  (m - n = 2):  score = 8.2543303859
  m = 103, n = 101  (m - n = 2):  score = 7.0843151351
  
start: q, k R(mθ)q R(nθ)k (m − n)θ = 2 m = 3, n = 1 score 5.9478093347 m = 13, n = 11 score 5.9478093347 m = 103, n = 101 score 5.9478093347
  • RoPE: offset 2 gives the same score at \(m=3\), 13 and 103, to all ten decimals; offsets 4 and 8 get their own values.
  • Added sinusoids: the offset-2 score drifts from 12.03 to 7.08.
  • RoPE is used by the Llama family, GPT-NeoX and most current open-weight models. ALiBi (attention with linear biases; Press et al., ICLR 2022) instead subtracts a distance-proportional penalty from the scores.

Self-check on shuffles, sinusoids and RoPE

Three questions on this part, one each on the derivation, the sinusoids and the schemes.

(a) No \(\mathrm{PE}\): average the outputs over positions for dog bites man and for man bites dog. Same or different, and why?

(b) \(d_{\text{model}}=32\): \(\mathrm{PE}\) at \(\mathrm{pos}=1\), dimensions 0 and 1?

(c) Which scheme scores a query at \(m\) and a key at \(n\) by \(n-m\) alone (fixed \(\mathbf{q}\), \(\mathbf{k}\))?

(a) Same: the outputs are the same three vectors reordered, and a mean ignores order (\(\mathbf{1}^\top P=\mathbf{1}^\top\)).

(b) Pair 0, angle \(1\): \(\sin1\approx0.8415\), \(\cos1\approx0.5403\).

(c) RoPE: \(R(m\theta)^\top R(n\theta)=R((n-m)\theta)\); added sinusoids drifted, 12.03 to 7.08.

That settles word order. Next comes S14's third lack, what a deep stack needs.

A deep stack of attention still needs three additions

Part 4 · A block that stacks. S14's third lack: linear in the values once the weights are fixed. Made precise:

X XWQXWKXWV scoressoftmax Σi αi vi WO output α nonlinear: the weights depend on X Given α, this path is linear in V: no elementwise nonlinearity acts within a position.
  • Three additions around attention (reading 3.3): residual connections and layer normalization, so that a deep stack trains; a per-position feedforward network, the nonlinearity each position lacks (S14's named fix).

One page each, named today; S17 assembles them into the block.

A residual connection adds the input to the sublayer's output, as in S10

First addition: around attention, and around the feedforward network, output the input plus the sublayer's result.

(B, T, d_model)(B, T, d_model) sublayer+identity IJFI + JF
  • Around attention and around the feedforward network, every sublayer computes \(\mathbf{x}+\operatorname{sublayer}(\mathbf{x})\), so its output shape must equal its input shape.
  • S10's caveat: the identity term helps; it does not guarantee a large gradient, since the factors \(I+J\) still multiply across blocks.
  • He et al. introduced it for vision in 2016 (S10's ResNets); the Transformer uses it in every block.

Residuals give the gradient a direct route to the early blocks of a deep stack.

Layer normalization standardizes each token's own feature vector

Second addition. S07's LayerNorm standardizes each item's own features (a row); here the item is a token.

dmodel T one token:μ, σ2 over itsdmodel features S07's BatchNorm: a column 391117−7−117−1.4−0.20.21.4 x x − μ (x − μ)/σ − μμ = 10 ÷ σσ = 5 σ2 = (49 + 1 + 1 + 49)/4 = 25 The result is at the initial γ = 1, β = 0; ε = 10−5 changes no printed digit.
  • Each token's output is \((x-\mu)/\sqrt{\sigma^2+\epsilon}\), times a learned scale \(\gamma\), plus a learned shift \(\beta\) (Ba, Kiros & Hinton, 2016).
  • No batch statistics: a token's output depends only on its own numbers; the same computation for any batch size or sequence length, in training and evaluation (S07).

LayerNorm keeps each token's vector at a standard scale, whatever the batch or the sequence.

The feedforward network applies one two-layer MLP at every position

Third addition, the fix S14 named for its third lack: the feedforward network (FFN), a nonlinearity within each position.

Linear(d, 4d) · ReLU/GELU · Linear(4d, d) d4dd the same weights at every position; no mixing across positions parameters at d = 512, biases included 2/3 FFN2,099,712attention1,050,624
  • \(d_{\text{ff}}=4\,d_{\text{model}}\) by convention. The nonlinearity was ReLU in 2017 and is GELU (S02's smooth version of ReLU) in most modern models.
  • With \(d=d_{\text{model}}\), the FFN has \(d\cdot4d+4d\cdot d=8d^2\) parameters and attention \(4d^2\) (biases aside), so the FFN holds \(8d^2/12d^2=2/3\).

Division of labor: attention mixes across positions; the FFN transforms within one, with about two-thirds of the parameters.

Self-check on LayerNorm, the FFN and the whole block

Three questions on Part 4; the last one also uses Part 3's derivation.

(a) LayerNorm on (B, T, d_model): over which axis are \(\mu\) and \(\sigma^2\) taken? Does a token's output depend on other tokens?

(b) GPT-2 small's sizes, \(d_{\text{model}}=768\), \(d_{\text{ff}}=3072\): the FFN's parameters, the attention's, and the FFN's share?

(c) No \(\mathrm{PE}\): shuffle the tokens entering a block of today's pieces. What happens to its output?

(a) The last axis, \(d_{\text{model}}\), per token. No: only on its own numbers.

(b) FFN \(2\cdot768\cdot3072+3072+768=4{,}722{,}432\); attention \(4(768^2+768)=2{,}362{,}368\); share \(\approx0.67\) (reading 3.3's GPT-2 count prints both).

(c) Shuffled the same way: \(PX+\operatorname{attn}(PX)=P\,(X+\operatorname{attn}(X))\), and LayerNorm and the FFN apply one map to every row. Still permutation-equivariant: \(\mathrm{PE}\) stays necessary.

Today named three pieces, and S17 assembles them into the block

Today named the three pieces; none is assembled yet.

(B, T, d_model)(B, T, d_model) identityidentity multi-headattentionLayerNormFFNLayerNorm++ Where LayerNorm goes is S17's question: post-norm (2017) or pre-norm.
  • Next session (S17): the block is assembled and the LayerNorm placement is compared, post-norm (as drawn) against pre-norm.
  • Then verified end to end with the causal-mask test: edit a later token, and the outputs at earlier positions must not change.
  • Then the model families, BERT against GPT, and tokenization: what exactly a token is.

Next comes the answer to the title page's question, one lack at a time.

Positional encodings, multi-head attention and three additions answer today's question

Part 5 · Close. Back to the title page's question, one lack at a time.

  • Positional encodings give the layer word order. Without them \(\operatorname{attn}(PX)=P\,\operatorname{attn}(X)\), derived and measured (\(1.2\times10^{-7}\)); with sinusoids added, the difference is 0.144. RoPE makes the score depend on the offset.
  • Multi-head attention gives each position several lookups. Its \(h\) heads, each S14's attention formula in \(d_{\text{head}}=d_{\text{model}}/h\) dimensions with its own projections, are concatenated and mixed by \(W_O\), which gives \(h\) places to look for the parameters and multiply-adds of one full-width head.
  • Residual connections, LayerNorm and a per-position FFN supply the nonlinearity and let the layers stack. The residual connections (S10's identity path) and LayerNorm over each token's features let a deep stack train; the FFN is the nonlinearity inside each position. All three are named today and assembled in S17.

HW3 asks you to build a Transformer from scratch

Today's multi-head code is the middle of HW3.

  • HW3 (Transformer from scratch) goes out in two sessions (S18) and is due at S22.
  • You implement: scaled dot-product attention (S14) → multi-head attention (today; each head divides by \(\sqrt{d_{\text{head}}}\), its own \(d_k\)) → the full block (S17) → a tiny language model, trained and sampled from.
  • HW3's tests check your attention the same way the readings do: hand-checkable weight cases and perturbation tests, not just shapes.
  • Usual HW3 bug: splitting heads with one view or reshape. Use view(B, T, n_heads, d_head), then transpose(1, 2) (reading 3.3).
  • Everything runs on CPU in seconds; reading 3.3's scripts are your reference implementations.

For next time

  • Next session (S17), Monday: Transformer II: the full block, BERT vs. GPT, tokenization.
  • Read: 3.4 Transformer II (and finish 3.3 Transformer I).
  • Project: the proposal is due in three weeks, at the end of the S23 week; build it on your pre-proposal feedback.
  • In two sessions (S18): HW2 due · HW3 (Transformer from scratch) out.
  • Quiz 3 (Module 3, at S23) covers today's material.