Session S16
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
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\;}\](T, T). Any two positions are one dot product apart, and all \(T\) rows come out at once: no serial loop.| S14's lack | what it means | the fix S14 named |
|---|---|---|
| 1 · No notion of order | shuffle the tokens of \(X\) and each token's output shuffles with it, unchanged otherwise | positional encodings |
| 2 · One lookup per position | one row of weights per query: one weighted average | multi-head attention |
| 3 · Linear in the values | once the weights are fixed, no nonlinearity acts on the values | stacked blocks with feedforward layers |
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.
| part | the question it answers |
|---|---|
| 1 · 2017: attention without recurrence | what did the Transformer keep, delete and add, and why did it matter? |
| 2 · Several lookups at once | how can one position read several others at once? Multi-head attention: shapes, code, the usual bug, the cost |
| 3 · Word order | how can a layer that cannot see order be given it? A derivation, positional encodings, a test; three generations of encodings |
| 4 · A block that stacks | what must surround attention so that layers stack? Three pieces, named today, assembled in S17 |
| 5 · Close | today's answer; HW3, which goes out at S18 |
The three bold questions answer the title page's question, one lack each. First, 2017.
Part 1 · 2017: attention without recurrence. S14's attention came from translation, where it connected two recurrent networks.
Today's Parts 2, 3 and 4 cover the structure added around attention, as the figure lists.
What the paper built (reading 3.3); each term is defined today or in S17.
Part 2 starts with the 8 heads: why one attention computation per layer is not enough.
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:
One row of weights per position gives one kind of lookup; the next page gives several.
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\]\(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.
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\).
| step | what it does | kind | result |
|---|---|---|---|
| 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 |
| split | 64 columns as 4 heads of 16; head axis moved forward | view, transpose | (B, 4, T, 16) |
| scores | dot products \(QK^\top\) per sequence and head, divided by \(\sqrt{16}\) | matrix product | (B, 4, T, T) |
| weights | softmax along each row, over the keys | softmax, per row | (B, 4, T, T) |
| head outputs | weights times \(V\), per sequence and head | matrix product | (B, 4, T, 16) |
| concatenate | the 4 heads side by side again | transpose, 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.
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)
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.The class divides by math.sqrt(self.d_head), not \(\sqrt{d_{\text{model}}}\): S14's argument with \(d_k=d_{\text{head}}\).
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 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
[:, None] makes the token numbers a column, so the sum broadcasts to (T, D) (S08).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
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.
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\)).
# 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.
Nothing in the formula assigns a role to a head; training does. What analyses of trained models report (reading 3.3):
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.
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.
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 next page shows why it holds, in five steps from S14's notation.
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.
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.
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.
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)\]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.
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.8126 | 0.5828 |
| ⋮ | |||
| 15 | \(3/5623\approx5.3\times10^{-4}\) | 0.0005 | 1.0000 |
The code on the next page builds this table for every position; the experiment prints rows 0 and 3.
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 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?
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']
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).
| scheme | parameters | past the trained length | encodes |
|---|---|---|---|
| fixed sinusoids (2017) | none | defined at any position; quality typically degrades | absolute position |
| learned embeddings (BERT, GPT-1/2/3) | a trainable table, a row per position | a hard ceiling at the table's size | absolute position |
| rotary (RoPE), 2021 | none | defined at any position; positions can be rescaled into the trained range | relative offset |
The third generation makes the offset the primitive; the next page shows how.
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):
RoPE acts on \(\mathbf{q}\) and \(\mathbf{k}\), never on \(\mathbf{v}\): position arrives where scores are computed.
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
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.
Part 4 · A block that stacks. S14's third lack: linear in the values once the weights are fixed. Made precise:
One page each, named today; S17 assembles them into the block.
First addition: around attention, and around the feedforward network, output the input plus the sublayer's result.
Residuals give the gradient a direct route to the early blocks of a deep stack.
Second addition. S07's LayerNorm standardizes each item's own features (a row); here the item is a token.
LayerNorm keeps each token's vector at a standard scale, whatever the batch or the sequence.
Third addition, the fix S14 named for its third lack: the feedforward network (FFN), a nonlinearity within each position.
Division of labor: attention mixes across positions; the FFN transforms within one, with about two-thirds of the parameters.
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 the three pieces; none is assembled yet.
Next comes the answer to the title page's question, one lack at a time.
Part 5 · Close. Back to the title page's question, one lack at a time.
Today's multi-head code is the middle of HW3.
view or reshape. Use view(B, T, n_heads, d_head), then transpose(1, 2) (reading 3.3).