Transformers

EE 641 - Unit 6

Dr. Brandon Franzke

Fall 2026

Outline

Self-Attention

Sequences and Contextual Vectors

  • Order: invariance and equivariance

Attention as a Sequence Layer

  • Path length and parallel steps
  • Cost against recurrence

Self-Attention

  • Queries, keys and values from one sequence
  • Accuracy without position

Encoding Position

  • Learned, sinusoidal and rotary positions
  • Past the trained length

Multiple Heads

  • Splitting the width
  • What trained heads do

The Transformer

The Transformer Block

  • Residual stream
  • Feed-forward networks as memories
  • Layer normalization

The Transformer Decoder

  • Causal mask and KV cache
  • Translation results

Training the Transformer

  • Gradients at depth and warmup
  • Label smoothing

Cost at Length

  • Tiled attention
  • Sparse and linear attention
  • Retrieval
  • Fixed depth and parity

Scaling the Block

  • Examples and mixture of experts

Reading List

Sequences and Contextual Vectors

Transformers Map \(T\) Tokens to \(T\) Vectors

Map

\[f_\theta:\ (x_1, \ldots, x_T) \mapsto (\mathbf{z}_1, \ldots, \mathbf{z}_T), \qquad \mathbf{z}_t \in \mathbb{R}^{d_{\text{model}}}\]

  • \(d_{\text{model}}\): width of the vectors
  • One output vector per input position, for any \(T\), with the same \(\theta\)
  • \(\mathbf{z}_t\): a function of the whole sequence, or of positions up to \(t\) in a language model

Readout per task

  • Language model: \(p_\theta(x_{t+1} \mid x_1, \ldots, x_t)\) at each \(t\)
  • Tagging: one class per token
  • Translation: source vectors \(\mathbf{z}_1, \ldots, \mathbf{z}_S\) as a second input to a decoder, a map over the target prefix

Language-Model Loss Sums One Term per Position

Language model loss, one sequence of \(T\) tokens

\[\mathcal{L}(\theta) = -\sum_{t=1}^{T-1} \log p_\theta(x_{t+1} \mid x_1, \ldots, x_t)\]

  • One cross-entropy term per position, its target the next token
  • Targets: the input shifted by one position
  • No human-labeled data
  • Translation: the same sum over target positions, each also conditioned on the source

Targets per sequence

  • \(T - 1\), against one for a classifier of whole sequences

Causal outputs

  • \(\mathbf{z}_t\) computed from \(x_1, \ldots, x_t\) only
  • Otherwise \(x_{t+1}\), position \(t\)’s target, is part of its input
  • At generation: later tokens not yet produced

Contextual Vectors Depend on the Rest of the Sentence

Same token, two vectors

  • “it”: same word, same position in both sentences
  • Referent: “animal” with “tired”, “street” with “wide”
  • Deciding word: three positions after “it”
  • French translation: “il” or “elle”, the gender of the French noun, l’animal (m.) or la rue (f.)

Contextual vector

  • \(\mathbf{z}_t\): a function of the other tokens, in the example of the last one
  • Context from both sides of \(t\) in an encoder, from positions up to \(t\) in a language model
  • Distance to the deciding word: any

Reordering the Same Tokens Changes the Meaning

Sentence

  • “dog bites man”: dog the biter, man bitten
  • “man bites dog”: the same three tokens, roles exchanged
  • English active clauses: subject before the verb, object after it

Latest-value sequence

  • Query k26: answer the value after the later k26, 4 in one order and 0 in the other

Position as an input

  • Both pairs: the same multiset of tokens, different correct outputs
  • Model unaffected by order: one answer for both latest-value sequences, wrong on one

Functions Unaffected by Order Are Invariant or Equivariant

Permutation matrix \(\mathbf{P}\): \(\mathbf{P}\mathbf{x}\) the same entries in a new order

Invariant: \(f(\mathbf{P}\mathbf{x}) = f(\mathbf{x})\)

  • One output for the whole sequence, unchanged by any reordering
  • Mean, sum, maximum

Equivariant: \(f(\mathbf{P}\mathbf{x}) = \mathbf{P}\,f(\mathbf{x})\)

  • One output per position, reordered with its input, otherwise unchanged
  • Example: the same map \(g\) at every position, \(z_t = g(x_t)\)

Order-dependent: neither

  • Running sum \(z_t = z_{t-1} + x_t\): the linear recurrence with pole 1

Layers by class

  • Pooling over positions: invariant
  • Same network applied at each position: equivariant
  • Recurrence: order-dependent
  • Equivariant layers stacked: still equivariant
  • “dog” in “dog bites man” and in “man bites dog”: the same output from an equivariant model

Attention as a Sequence Layer

One Attention Read Connects a Position to All Positions

Recurrent

  • \(\mathbf{z}_t\) from \(x_t\) and the state at \(t - 1\)
  • Path from \(s\) to \(t\): \(t - s\) steps
  • Order: \(\mathbf{z}_t\) depends on \(x_1, \ldots, x_t\) through the sequence of steps

Convolutional

  • \(\mathbf{z}_t\) from the \(k\) positions up to \(t\)
  • Wider context: more layers
  • Order: relative order within the window, one weight per offset

Attention over the same sequence

  • Self-attention: queries, keys and values all from the sequence’s own positions
  • \(\mathbf{z}_t\): weighted sum over all positions
  • Path from any \(s\) to \(t\): one layer
  • Order: none, outputs reordered with the inputs

Attention Returns a Score-Weighted Average of Values

Read, one query over \(S\) stored items

\[e_s = \frac{\mathbf{q}^\top \mathbf{k}_s}{\sqrt{d_k}}, \qquad a_s = \mathrm{softmax}_s(e_s), \qquad \mathbf{c} = \sum_{s=1}^{S} a_s\,\mathbf{v}_s\]

  • Query: what is looked up
  • Key: what an item is matched on
  • Value: what an item returns
  • Learned projections: \(\mathbf{q} = \mathbf{W}_Q\,\mathbf{h}\), \(\mathbf{k}_s = \mathbf{W}_K\,\mathbf{h}_s\), \(\mathbf{v}_s = \mathbf{W}_V\,\mathbf{h}_s\)
  • One read per query, over all items at any distance, cost \(O(S(d_k + d_v))\)

Order of the items

  • Items reordered: read unchanged, invariant
  • Queries reordered: outputs reordered the same way, equivariant
  • Position in a read: only through the query and item vectors
    • Encoder-decoder: encoder states from a recurrence

Cross-attention

  • Queries from one sequence, keys and values from another
  • Encoder-decoder: query from the decoder state \(\mathbf{h}^{\text{dec}}_t\), items the encoder states \(\mathbf{h}^{\text{enc}}_s\)

Recurrent Layers Take \(T\) Sequential Steps

Recurrent

  • State at \(t\) computed from the state at \(t - 1\)
  • \(T\) steps, one after another

Convolution and attention

  • No output computed from another output of the same layer
  • All \(T\) positions in one batch of matrix products, in training and in an encoder
  • Generation: one new position per step, for these layers too

Stacked layers, \(L\) of them

  • Convolution and attention: \(L\) sequential steps
  • Recurrent: at least \(T + L - 1\), layer \(\ell\) at position \(t\) computed after layer \(\ell - 1\) at position \(t\)

Hardware

  • GPU: one product over all \(T\) positions has \(T\) times the parallel work of one recurrent step at the same batch size

Measured, LSTM encoder-decoder with a read, CPU, \(H = 64\), \(S = T\) from 24 to 96

  • Recurrences: 88 to 94 percent of forward time

Attention Path Length Is Independent of Distance

Path length, position 1 to position \(T\)

  • Recurrent: \(T - 1\) steps. At \(T = 50\): 49
  • Convolution, contiguous width \(k\): the window grows by \(k - 1\) per layer, \(\lceil (T - 1)/(k - 1) \rceil\) layers. At \(T = 50\), \(k = 3\): 25
  • Dilated convolution, gaps between kernel taps multiplied by \(k\) at each layer: \(O(\log_k T)\) layers
  • Attention: one layer at every \(T\)
  • Causal mask: one layer from earlier to later positions only

Gradient along the path

  • Gradient from position \(T\)’s loss to position 1, along one path: one Jacobian factor per step or layer
  • Recurrent: norm bounded by the product of \(T - 1\) factor norms, geometric in \(T\) when all are below or all above 1
  • Attention: one factor through the read, \(a_{T,1}\), at any distance

Attention Layer Complexity Grows as \(T^2 d\)

Per layer (Vaswani et al. 2017): sequence length \(n = T\), width \(d = d_{\text{model}}\), kernel width \(k\)

Layer Complexity per layer Sequential steps Maximum path length
Recurrent \(O(n d^2)\) \(O(n)\) \(O(n)\)
Convolutional (dilated) \(O(k n d^2)\) \(O(1)\) \(O(\log_k n)\)
Self-attention \(O(n^2 d)\) \(O(1)\) \(O(1)\)

  • Projections into queries, keys and values: \(O(n d^2)\), the same order as the recurrent layer

At \(d = 512\)

  • Attention term below the recurrent term while \(T < d = 512\), sentences of tens of tokens included
  • At \(T = 2048\): attention term \(2.1 \times 10^9\) against \(0.54 \times 10^9\) recurrent, constants omitted

Transformers Stack Self-Attention and Feed-Forward Layers

Transformer (Vaswani et al. 2017)

  • Encoder and decoder stacks of layers with one structure and separate weights, no recurrence

Components

  • Token embedding plus a position vector: the first \(T \times d_{\text{model}}\) input
  • Self-attention: one read per position over the sequence
  • Position-wise feed-forward network: the same two-layer network applied at each position
  • Decoder: self-attention restricted to positions up to its own, and cross-attention over the encoder’s output

Base model

  • \(N = 6\) layers per stack, \(d_{\text{model}} = 512\)
  • Feed-forward hidden width 2048
  • About 65 million parameters, one 37,000-token vocabulary for source and target

Stacking

  • Layers: \(T \times d_{\text{model}}\) in and out, so one layer’s output is a valid input to the next

Self-Attention

Reading Its Own Sentence Gives “it” a Contextual Vector

Read from “it”

  • Query: the vector at “it”
  • Items: all eleven tokens of the same sentence, “it” included
  • Weights set by hand: 0.45 on “animal” with “tired”, 0.45 on “street” with “wide”

Output of the read

  • New vector at “it”: the weighted sum, largest weight, 0.45, on the referent’s value
  • Next layer: takes the new vectors as input, the one at “it” with 0.45 of the referent’s value
  • One read from each of the eleven positions

Self-Attention Takes Queries and Items from One Sequence

Steps

  • Scores, softmax along each row, weighted sum
  • Only the source of the queries and the items changes

Self-attention

  • Queries, keys and values: all from one sequence’s vectors \(\mathbf{x}_t\)
  • Grid: positions against positions, \(T \times T\)

Contextual states

  • Encoder-decoder: encoder states contextual through the recurrence
  • Self-attention: contextual through the read, all positions at once

Self-Attention Computes One Read per Position

Definition

\[\mathbf{q}_t = \mathbf{W}_Q\,\mathbf{x}_t, \qquad \mathbf{k}_s = \mathbf{W}_K\,\mathbf{x}_s, \qquad \mathbf{v}_s = \mathbf{W}_V\,\mathbf{x}_s\]

\[\mathbf{z}_t = \sum_{s=1}^{T} a_{t,s}\,\mathbf{v}_s, \qquad a_{t,s} = \mathrm{softmax}_s\!\left(\frac{\mathbf{q}_t^\top \mathbf{k}_s}{\sqrt{d_k}}\right)\]

  • Every position supplies a query: \(T\) reads, each over all \(T\) positions, itself included
  • \(\mathbf{z}_t\): new vector at position \(t\), a function of all tokens in the sequence

Grid

  • Row \(t\): the read of position \(t\), over all \(T\) columns

Each Token Supplies a Query, a Key and a Value

Sizes

  • \(\mathbf{W}_Q, \mathbf{W}_K \in \mathbb{R}^{d_k \times d_{\text{model}}}\), \(\mathbf{W}_V \in \mathbb{R}^{d_v \times d_{\text{model}}}\), shared by all positions: \(d_{\text{model}}(2d_k + d_v)\) parameters, 786,432 at width 512

Vectors per token, all from \(\mathbf{x}_t\)

  • \(\mathbf{q}_t = \mathbf{W}_Q\,\mathbf{x}_t\): what position \(t\)’s read looks up. Row \(t\)
  • \(\mathbf{k}_t = \mathbf{W}_K\,\mathbf{x}_t\): what every read scores position \(t\) on. Column \(t\) of the scores
  • \(\mathbf{v}_t = \mathbf{W}_V\,\mathbf{x}_t\): what position \(t\) adds to a read. Column \(t\) of the weights scales \(\mathbf{v}_t\) in every output

Equal projections (hypothetical)

  • \(\mathbf{W}_Q = \mathbf{W}_K\): \(e_{t,s} = e_{s,t}\), so “it” scoring “animal” high forces “animal” to score “it” equally high
  • \(\mathbf{W}_K = \mathbf{W}_V\): what a token is matched on is also what it returns

Self-Attention Computes Scores, Weights and Outputs as Matrices

Step 1: scores

  • \(e_{t,s} = \mathbf{q}_t^\top \mathbf{k}_s / \sqrt{d_k}\) for all pairs of positions
  • Grid \(\mathbf{E} \in \mathbb{R}^{T \times T}\)

Step 2: weights

  • Softmax along the rows of \(\mathbf{E}\)
  • Grid \(\mathbf{A} \in \mathbb{R}^{T \times T}\), rows summing to one

Step 3: outputs

  • Row \(t\) of \(\mathbf{A}\) weights the values
  • One \(\mathbf{z}_t\) per position: \(\mathbf{Z} \in \mathbb{R}^{T \times d_v}\)
  • With \(d_v = d_{\text{model}}\): \(\mathbf{Z}\) the shape of \(\mathbf{X}\)

Step 1: One Score per Pair of Positions

Example, one coordinate per token

  • Tokens k3, 7, k5, 2: two key-value pairs
  • One coordinate per token: \(\mathbf{x}_{\text{k3}} = (2, 0, 0, 0)\), \(\mathbf{x}_{\text{k5}} = (0, 2, 0, 0)\), \(\mathbf{x}_{\text{7}} = (0, 0, 2, 0)\), \(\mathbf{x}_{\text{2}} = (0, 0, 0, 2)\)
  • Projections the identity: \(\mathbf{q}_t = \mathbf{k}_t = \mathbf{v}_t = \mathbf{x}_t\), \(d_k = 4\), \(\sqrt{d_k} = 2\)

Row of “7”

  • Against itself: \((2 \cdot 2)/2 = 2\)
  • Against k3, k5 and “2”: \(0\), no shared coordinate

Identity projections

  • A token matches only itself

Step 2: Softmax Normalizes the Grid Row by Row

Row of “7”

\[\mathrm{softmax}(0, 2, 0, 0) = \frac{(1,\ e^{2},\ 1,\ 1)}{e^{2} + 3} = (0.096,\ 0.711,\ 0.096,\ 0.096)\]

  • Rows summing to one: weights of one position’s read
  • Same weight on k3 and k5: scores from token vectors only, and neither vector marks adjacency

Other rows

  • 0.711 on the position itself, 0.096 on the others

Step 3: Outputs Are Weighted Sums of All Values

Output at “7”

\[\mathbf{z}_{\text{7}} = 0.096\,\mathbf{x}_{\text{k3}} + 0.711\,\mathbf{x}_{\text{7}} + 0.096\,\mathbf{x}_{\text{k5}} + 0.096\,\mathbf{x}_{\text{2}} = (0.19,\ 0.19,\ 1.42,\ 0.19)\]

  • Coordinate 3, from “7” itself: \(0.711 \cdot 2 = 1.42\)
  • Other tokens’ coordinates: \(0.096 \cdot 2 = 0.19\)

Contextual vector

  • \(\mathbf{z}_t\): weighted average of all token vectors, largest weight on its own with identity projections
  • Key coordinates in \(\mathbf{z}_{\text{7}}\): equal, \(0.19\) each

Which Tokens a Query Matches Depends on \(\mathbf{W}_Q\) and \(\mathbf{W}_K\)

Query projection mapping values onto keys, \(\mathbf{W}_K = \mathbf{W}_V = \mathbf{I}\)

\[\mathbf{W}_Q = \begin{bmatrix} 0 & 0 & 1 & 1 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{bmatrix}\]

  • Value coordinates 3 and 4 mapped onto key coordinates 1 and 2: \(\mathbf{q}_{\text{7}} = \mathbf{q}_{\text{2}} = (2, 2, 0, 0)\)
  • Key coordinates mapped to zero: \(\mathbf{q}_{\text{k3}} = \mathbf{q}_{\text{k5}} = \mathbf{0}\)

Row of “7”

  • Scores \((2, 0, 2, 0)\): weights \(\dfrac{e^2}{2e^2 + 2} = 0.44\) on each key, \(0.06\) on each value

Query and key projections

  • Set which tokens score high against a query: value tokens’ queries match key tokens
  • Grid not symmetric: \(\mathbf{W}_Q \ne \mathbf{W}_K\)
  • k3 and k5 weighted equally: token vectors contain no position

Matrix Form: \(\mathbf{Z} = \mathrm{softmax}(\mathbf{Q}\mathbf{K}^\top / \sqrt{d_k})\,\mathbf{V}\)

Tokens as rows

  • \(\mathbf{X} \in \mathbb{R}^{T \times d_{\text{model}}}\), row \(t\) is \(\mathbf{x}_t^\top\)
  • Row \(t\) of \(\mathbf{Q}\) is \((\mathbf{W}_Q \mathbf{x}_t)^\top = \mathbf{x}_t^\top \mathbf{W}_Q^\top\)

\[\mathbf{Q} = \mathbf{X}\mathbf{W}_Q^\top, \quad \mathbf{K} = \mathbf{X}\mathbf{W}_K^\top, \quad \mathbf{V} = \mathbf{X}\mathbf{W}_V^\top\]

\[\mathbf{Z} = \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}\]

  • Softmax along the rows
  • Vaswani et al. 2017 multiply on the right, by \(\mathbf{W}^Q \in \mathbb{R}^{d_{\text{model}} \times d_k}\): \(\mathbf{W}^Q = \mathbf{W}_Q^\top\)

Batched, in PyTorch

Wq = nn.Linear(d_model, d_k, bias=False)  # weight: (d_k, d_model) = W_Q
Q, K, V = Wq(X), Wk(X), Wv(X)             # (B, T, d_k), (B, T, d_k), (B, T, d_v)
A = (Q @ K.transpose(-2, -1) / d_k ** 0.5).softmax(-1)   # (B, T, T)
Z = A @ V                                                # (B, T, d_v)
  • nn.Linear stores \(\mathbf{W}_Q\) as \(d_k \times d_{\text{model}}\) and computes \(\mathbf{X}\mathbf{W}_Q^\top\)

Per sequence and layer

  • Projections: \(T\,d_{\text{model}}(2d_k + d_v)\) multiply-adds
  • Scores and outputs: \(T^2 (d_k + d_v)\)
  • Weights kept for the backward pass: \(T^2\) numbers

Permuting Tokens Permutes Their Outputs

Self-attention: queries and items reordered together, permutation matrix \(\mathbf{P}\) on the rows of \(\mathbf{X}\)

  • \(\mathbf{P}\mathbf{X}\) gives queries \(\mathbf{P}\mathbf{Q}\), keys \(\mathbf{P}\mathbf{K}\), values \(\mathbf{P}\mathbf{V}\), for any \(\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V\)
  • Scores \(\mathbf{P}\mathbf{Q}\mathbf{K}^\top\mathbf{P}^\top\): rows and columns reordered together
  • Softmax acts on each row alone, and treats a row’s entries alike: reordered rows give reordered rows of weights, reordered entries give reordered weights, so \(\mathbf{P}\mathbf{A}\mathbf{P}^\top\)
  • Outputs \(\mathbf{P}\mathbf{A}\mathbf{P}^\top\mathbf{P}\mathbf{V} = \mathbf{P}\mathbf{A}\mathbf{V}\), since \(\mathbf{P}^\top\mathbf{P} = \mathbf{I}\)

\[\mathrm{SA}(\mathbf{P}\mathbf{X}) = \mathbf{P}\,\mathrm{SA}(\mathbf{X})\]

Permutation equivariance

  • \(\mathbf{z}_t\): a function of \(\mathbf{x}_t\) and of the tokens regardless of order
  • Scope: no mask. With a causal mask, the read at position \(t\) covers \(t\) items, and outputs depend on position

Output of “7”: \((0.88,\ 0.88,\ 0.12,\ 0.12)\) after k3 and after k5

Token Recall Requires Pairing Values with Keys

Tasks over one token sequence, 8 pairs

  • Tokens: k v k v … then “?” and a query key
  • Keys from 40 symbols, values digits 0 to 9
  • Recall: keys distinct, answer the query key’s value
  • Latest value: keys twice each, answer the value at the later occurrence

Models

  • Read alone: pairs given as stored items, key and value joined by the input format
  • GRU + read: GRU over the pair tokens, query key projected separately, a read over the GRU’s per-token states
    • State at a value token computed right after its key
  • Self-attention: two layers over the token embeddings, no mask, answer taken at the query’s position
    • Pairing only from the tokens

Self-Attention Without Positions Is Bounded by Value Counts

Measured, 8 pairs, two seeds, 2,000 test sequences

  • Self-attention: recall 0.27 to 0.29, latest value 0.29
  • Read alone with pairs given, GRU + read: recall 1.00 and 1.00

Self-attention over tokens

  • Two layers, width 64, inputs added to outputs: still equivariant
  • Answer: a function of the query and the tokens regardless of order

Bound from value counts

  • Pairing unknown: every way of pairing the same 8 keys with the same 8 values is the same set of tokens, so the model gives one answer to all of them
  • Over those pairings, the answer equally likely to be any of the 8 value tokens, repeats counted
  • \(P(\text{answer} = v) = \mathrm{count}(v) / 8\)
  • Best guess: the most common value, expected accuracy \(\mathbb{E}[\max_v \mathrm{count}(v)] / 8\) = 0.30, the dashed line

Among these models, accuracy above that guess only where the input format or a recurrence pairs values with keys

Encoding Position

Token Embeddings Are the Same at Every Position

Input vectors

  • \(\mathbf{x}_t = \mathbf{e}(x_t)\): a function of the token only
  • Same token at two positions: the same vector
  • Every query, key, value and score computed from these vectors: none depends on position

Read from “7”

  • 0.44 on k3 and 0.44 on k5, in either order

Where position is encoded

  • Position vector: \(\mathbf{x}_t = \mathbf{e}(x_t) + \mathbf{p}_t\), before the first layer
  • Position in the score: a term in \(e_{t,s}\) computed from \(t\) and \(s\), token vectors unchanged

Learned Position Vectors Make Inputs Depend on Position

One vector per position

\[\mathbf{x}_t = \mathbf{e}(x_t) + \mathbf{p}_t, \qquad \mathbf{P} = \begin{bmatrix} \mathbf{p}_1^\top \\ \vdots \\ \mathbf{p}_{T_{\max}}^\top \end{bmatrix} \in \mathbb{R}^{T_{\max} \times d_{\text{model}}}\]

  • \(\mathbf{p}_t\): a row of a learned table, \(T_{\max}\, d_{\text{model}}\) parameters
  • Added once, before the first layer: every query, key and value depends on position

Same token, two positions

  • k26 at positions 1 and 5: two different input vectors

Embedding scale

  • Token vectors \(\sqrt{d_{\text{model}}}\,\mathbf{e}(x_t)\) (Vaswani et al. 2017), entries initialized at standard deviation \(d_{\text{model}}^{-1/2}\) in reference implementations: token coordinates of order 1, the order of the position vectors
  • Unit-variance embeddings with the \(\sqrt{d_{\text{model}}}\) factor instead: token coordinates about \(\sqrt{d_{\text{model}}}\) times the position coordinates

\(\mathbf{W}_Q\) Maps Position \(t\) to Position \(t - 1\)

Input, k3, 7, k5, 2 at positions 1 to 4

  • Token block: the four token vectors
  • Position block: \(2\,\mathbf{u}_t\), one table row per position, \(\mathbf{u}_t\) one-hot at \(t\)
  • \(\mathbf{x}_t = [\,\text{token};\ \mathbf{0}\,] + \mathbf{p}_t\)

Projections

  • Query: \(\mathbf{q}_t = \mathbf{W}_Q\,\mathbf{x}_t = 2\,\mathbf{u}_{t-1}\), the position one step back
  • Key: \(\mathbf{k}_s = 2\,\mathbf{u}_s\), the item’s own position
  • Value: the token block

Score, \(d_k = 4\)

  • \(\mathbf{q}_t^\top \mathbf{k}_s / 2 = 2\) when \(s = t - 1\), otherwise 0

Values Read the Key One Position Earlier

Read from “7”

  • Without positions: 0.44 on k3, 0.44 on k5
  • With positions: 0.71 on k3, the key one position earlier

Output at “7”

  • k3’s coordinate largest, 1.42 against 0.19 for the others

Rule inside \(\mathbf{W}_Q\)

  • One row per position: row \(t - 1\) has its 1 at position coordinate \(t\)
  • “One position back” written three times, once each for positions 2, 3 and 4

A Per-Position Rule Fails When the Sequence Shifts

Same tokens, shifted by 3

  • Positions 4 to 7: every row uniform at 0.25, the binding gone

Tasks

  • Both rules in offsets: a shifted sequence keeps its answer

Added positions

  • Rule stored per absolute position, one entry of \(\mathbf{W}_Q\) each
  • Positions 5 to 7: no entry, so no read

In training

  • Row \(\mathbf{p}_t\) enters the model only at position \(t\): its gradient is a sum over training sequences at least \(t\) long
  • Positions past the longest training sequence: rule never learned

Learned Positions Clear the Value-Count Bound

Model

  • Learned position vectors added to the token embeddings
  • Two layers, width 64, each self-attention plus a feed-forward network, with layer normalization
  • Recall and latest value with 4 pairs, 10 tokens per sequence

Measured, two seeds, 20,000 training steps

  • Recall: 1.00
  • Latest value: 1.00
  • Value-count bound at 4 pairs: 0.38
  • Same tasks without positions: 0.37 to 0.39 on recall, at the bound

Training

  • Above 0.94 by step 2,000 on both tasks and seeds

Sinusoidal Encoding: One Frequency per Coordinate Pair

Table (Vaswani et al. 2017), position \(p = 0, 1, 2, \ldots\), pair \(i = 0, \ldots, d_{\text{model}}/2 - 1\)

\[\mathrm{PE}[p, 2i] = \sin(p\,\theta_i), \qquad \mathrm{PE}[p, 2i+1] = \cos(p\,\theta_i), \qquad \theta_i = 10000^{-2i/d_{\text{model}}}\]

  • Pair \(i\): a point on the unit circle, advancing by angle \(\theta_i\) per position
  • Rates from 1 radian per position down to periods near \(2\pi \cdot 10^4\) positions
  • No learned parameters, defined at every position

Binary counting

  • Low bits flip fast, high bits slowly
  • Sinusoids: the same pattern, with smooth values in \([-1, 1]\)
  • Rate from one pair to the next: a factor \(10000^{-2/d_{\text{model}}}\), 0.965 at \(d_{\text{model}} = 512\), against 0.5 from one bit to the next

Choice (Vaswani et al. 2017)

  • Learned table and sinusoids within 0.1 BLEU on the development set
  • Sinusoids chosen for possible use on sequences longer than any in training

Shifting Position by \(s\) Rotates the Encoding

Angle addition for pair \(i\), \(\alpha = p\,\theta_i\), \(\beta = s\,\theta_i\)

\[\sin(\alpha + \beta) = \sin\alpha\cos\beta + \cos\alpha\sin\beta, \qquad \cos(\alpha + \beta) = \cos\alpha\cos\beta - \sin\alpha\sin\beta\]

Matrix form

\[\begin{bmatrix} \mathrm{PE}[p+s, 2i] \\ \mathrm{PE}[p+s, 2i+1] \end{bmatrix} = \begin{bmatrix} \cos s\theta_i & \sin s\theta_i \\ -\sin s\theta_i & \cos s\theta_i \end{bmatrix} \begin{bmatrix} \mathrm{PE}[p, 2i] \\ \mathrm{PE}[p, 2i+1] \end{bmatrix}\]

  • \(\mathrm{PE}[p + s] = R_s\,\mathrm{PE}[p]\), \(R_s\) block diagonal with one \(2 \times 2\) rotation per pair
  • Example with sinusoidal positions: \(\mathbf{W}_Q = R_{-1}\) on the position coordinates gives \(\mathbf{q}_t = \mathrm{PE}[t - 1]\) at every \(t\), “one position back” in a single matrix
  • \(R_s\) depends on the shift \(s\) alone, the same at every starting position \(p\)
  • \(R_s^\top R_s = \mathbf{I}\): the encoding’s length the same at every position

Sinusoidal Dot Products Depend Only on the Offset

Two positions \(m\) and \(n\)

\[\mathrm{PE}[m]^\top \mathrm{PE}[n] = \sum_{i} \big(\sin m\theta_i \sin n\theta_i + \cos m\theta_i \cos n\theta_i\big) = \sum_{i} \cos\big((n - m)\,\theta_i\big)\]

  • A function of \(n - m\) only: the same at every starting position
  • Largest at \(n = m\), \(d_{\text{model}}/2\)
  • Cosine even: same value at offsets \(+s\) and \(-s\)
  • Earlier and later indistinguishable: latest value needs that distinction

Without projections

  • Identity for \(\mathrm{PE}[m]^\top \mathrm{PE}[n]\) alone
  • Attention compares \(\mathbf{q}_m^\top \mathbf{k}_n\), after projections and after the token vectors are added

With Added Encodings, Scores Depend on Absolute Positions

Score with added encodings, \(\mathbf{x}_m = \mathbf{e}_m + \mathbf{p}_m\), \(\mathbf{M} = \mathbf{W}_Q^\top \mathbf{W}_K\)

\[\mathbf{x}_m^\top \mathbf{M}\, \mathbf{x}_n = \underbrace{\mathbf{e}_m^\top \mathbf{M}\, \mathbf{e}_n}_{\text{content}} + \underbrace{\mathbf{e}_m^\top \mathbf{M}\, \mathbf{p}_n}_{\text{content-position}} + \underbrace{\mathbf{p}_m^\top \mathbf{M}\, \mathbf{e}_n}_{\text{position-content}} + \underbrace{\mathbf{p}_m^\top \mathbf{M}\, \mathbf{p}_n}_{\text{position}}\]

  • Content: the score without positions
  • Mixed terms: a token against an absolute position
  • Position term, sinusoidal \(\mathbf{p}_m = R_m\,\mathrm{PE}[0]\): \(\mathbf{p}_m^\top \mathbf{M}\,\mathbf{p}_n = \mathrm{PE}[0]^\top R_m^\top \mathbf{M} R_n\,\mathrm{PE}[0]\)
  • \(\mathbf{M}\) commuting with every \(R_s\): \(R_m^\top \mathbf{M} R_n = \mathbf{M} R_{n-m}\), a function of \(n - m\) alone

Learned \(\mathbf{M}\)

  • No constraint that it commutes with the rotations
  • Score: a function of the tokens, of \(m\) and of \(n\) separately
  • Relative position only through the values of \(\mathbf{W}_Q\) and \(\mathbf{W}_K\) after training

Example with added positions

  • \(\mathbf{M}\) acts on the position coordinates only: content and mixed terms 0
  • Position term: the whole rule, one entry of \(\mathbf{W}_Q\) per absolute position

Applying Position at the Score Leaves Token Vectors Unchanged

Insertion points

  • A: learned and sinusoidal tables, added to \(\mathbf{e}(x_t)\)
  • B: a bias on the score, or a rotation of \(\mathbf{q}\) and \(\mathbf{k}\)

At A

  • Position inside every query, key and value
  • Score: content, position and their mixed terms, the mixed terms absolute

At B

  • Token vectors, and so the values, free of position
  • Score: content plus a position term built from the two positions
  • Position term written in the offset: one rule for all positions

ALiBi Subtracts a Penalty Proportional to Distance

Attention with Linear Biases, ALiBi (Press et al. 2022), causal attention, \(s \le t\)

\[e_{t,s} = \frac{\mathbf{q}_t^\top \mathbf{k}_s}{\sqrt{d_k}} - \lambda\,(t - s)\]

  • \(\lambda > 0\): a fixed slope, not learned
  • Ratio of two weights in one row: \(a_{t,s} / a_{t,s'} = \exp(e_{t,s} - e_{t,s'})\), the normalizer cancelling
  • Same content scores, one step farther: penalty larger by \(\lambda\), weight smaller by a factor \(e^{-\lambda}\)

Tokens k3, 7, k5, 2, \(\lambda = 0.5\)

  • Read from “2”, content alone: k3 and k5 equal
  • With the penalty: 0.60 on k5, 0.22 on k3, the nearer key

On the grid

  • Penalty constant along each diagonal, defined at every distance

Slopes (Press et al. 2022)

  • One slope per head, a geometric sequence across heads: large slopes weight near keys, small slopes far keys
  • Designed for test sequences longer than any in training

Rotating Queries and Keys Makes the Score Depend on the Offset

Rotary position embedding, RoPE (Su et al. 2021), pair \(i\) of a query or key at position \(p\), \(\theta_i = 10000^{-2i/d_k}\)

\[\begin{bmatrix} x'_{2i} \\ x'_{2i+1} \end{bmatrix} = \begin{bmatrix} \cos p\theta_i & -\sin p\theta_i \\ \sin p\theta_i & \cos p\theta_i \end{bmatrix} \begin{bmatrix} x_{2i} \\ x_{2i+1} \end{bmatrix}, \qquad \tilde{\mathbf{q}}_m = \boldsymbol{\Phi}_m \mathbf{q}_m, \quad \tilde{\mathbf{k}}_n = \boldsymbol{\Phi}_n \mathbf{k}_n\]

Score

\[\tilde{\mathbf{q}}_m^\top \tilde{\mathbf{k}}_n = \mathbf{q}_m^\top \boldsymbol{\Phi}_m^\top \boldsymbol{\Phi}_n\, \mathbf{k}_n = \mathbf{q}_m^\top \boldsymbol{\Phi}_{n - m}\, \mathbf{k}_n\]

  • \(\boldsymbol{\Phi}_p\): every pair rotated by \(p\,\theta_i\), so \(\boldsymbol{\Phi}_m^\top \boldsymbol{\Phi}_n = \boldsymbol{\Phi}_{n-m}\)
  • Score: content \(\mathbf{q}_m, \mathbf{k}_n\) and the offset \(n - m\), no absolute position
  • Earlier and later score differently in general: offset \(s\) gives \(\mathbf{q}^\top \boldsymbol{\Phi}_s \mathbf{k}\), offset \(-s\) gives \(\mathbf{q}^\top \boldsymbol{\Phi}_{-s} \mathbf{k} = \mathbf{k}^\top \boldsymbol{\Phi}_s \mathbf{q}\), equal only for special \(\mathbf{q}, \mathbf{k}\)
  • Added sinusoids, \(\mathrm{PE}[m]^\top \mathrm{PE}[n]\): the case \(\mathbf{q} = \mathbf{k} = \mathrm{PE}[0]\), the same in both directions
  • Applied in every attention layer, to queries and keys only

Complex form

  • Pair as \(z = x_{2i} + j\,x_{2i+1}\), rotation as multiplication by \(e^{j p \theta_i}\)
  • Pair’s term in the score: \(\mathrm{Re}\big[\overline{q\,e^{j m \theta_i}}\; k\,e^{j n \theta_i}\big] = \mathrm{Re}\big[\bar q\, k\, e^{j (n - m) \theta_i}\big]\), position only through \(n - m\)

Rotation Leaves No Absolute Terms in the Score

Position added to \(\mathbf{q}\) and \(\mathbf{k}\)

\[(\mathbf{q}_m + \mathbf{p}_m)^\top (\mathbf{k}_n + \mathbf{p}_n) = \mathbf{q}_m^\top \mathbf{k}_n + \mathbf{q}_m^\top \mathbf{p}_n + \mathbf{p}_m^\top \mathbf{k}_n + \mathbf{p}_m^\top \mathbf{p}_n\]

  • Mixed terms \(\mathbf{q}_m^\top \mathbf{p}_n\) and \(\mathbf{p}_m^\top \mathbf{k}_n\): content against one absolute position
  • Same four terms as with encodings added to the token vectors

Position as a rotation of \(\mathbf{q}\) and \(\mathbf{k}\)

\[(\boldsymbol{\Phi}_m \mathbf{q}_m)^\top (\boldsymbol{\Phi}_n \mathbf{k}_n) = \mathbf{q}_m^\top \boldsymbol{\Phi}_{n-m}\, \mathbf{k}_n\]

  • One term: content compared through a rotation by the offset
  • A sum leaves terms in each position separately. A product of rotations leaves only their difference

Beyond the training length

  • Defined at every offset. Offsets longer than any in training never seen

Rotary Weights Are Unchanged When the Sequence Shifts

Example, one rotary pair: k3, 7, k5, 2, \(\theta = 60°\)

  • Same \(\mathbf{q}\) for every token, \(\mathbf{k}\) at angle \(\theta\) from it
  • Score \(2\cos\big((n - m + 1)\,\theta\big)\): largest at the key one position before the query

Shifted by 3 positions

  • Same offsets, same scores, identical grids
  • “7” reads k3 at 0.70 at either starting position

Against added positions

  • Added: the rule stored per position, binding gone at positions 4 to 7
  • Rotary: the rule in one pair of projections, the same at every starting position

One rate against many

  • One rate, \(\theta = 60°\): offsets \(s\) and \(s + 6\) rotate by the same angle, so the score cannot tell them apart
  • RoPE’s \(d_k/2\) rates \(\theta_i\): one angle per pair. The slowest pair alone separates any two offsets less than its period apart, about 47,000 positions at \(d_k = 64\)

Rotary Positions Extrapolate Past the Trained Positions

Test

  • Same 4 pairs, moved later by filler tokens: trained with 0 to 2 fillers, positions up to 11, tested with up to 32, positions up to 41
  • Two layers, width 64, two seeds per method

Measured, recall, 2,000 test sequences

  • Learned table: 0.97 to 0.98 with no shift, 0.10 to 0.19 at a shift of 8
  • Sinusoids: 0.94 to 1.00 with no shift, 0.11 to 0.26 at 8
  • Rotary: 0.79 to 1.00 at 8, 0.56 to 0.86 at 32. One seed reached only 0.80 even unshifted
  • No positions: 0.37 to 0.39 at every shift, the order-blind bound

Absolute against relative

  • Learned rows past position 11: never in a training sequence, so never trained
  • Sinusoids: defined at every position, but the added-encoding score depends on absolute positions, and the trained weights never saw these
  • Rotary: score from content and offset alone, the same offsets at any starting position

Limits

  • One task, a 4-pair input, two seeds
  • Sinusoids were chosen for use beyond the training lengths. Defined there is not the same as accurate there

Multiple Heads

The Vector at “it” Depends on Two Different Tokens

Two needs at “it”

  • Referent: “animal”, whose content the pronoun stands for
  • Deciding word: “tired”, which selects the referent
  • Different tokens, for different reasons

One head

  • One softmax row per position: one weighting of the sentence
  • Weight on “animal” and on “tired”: shared out of a total of one
  • Weights set by hand: 0.40 on each, the rest thinly spread

One Head Spreads Its Weight over Both Neighbours

Example, one query on both neighbours: k3, 7, k5, 2 at positions 1 to 4

  • Position coordinates as in the position section, keys the position block, values the token block, \(d_k = 4\)
  • Query at position \(t\): \(2\,\mathbf{u}_{t-1} + 2\,\mathbf{u}_{t+1}\), both neighbours at once

Row of “7”

  • Scaled scores, \(\mathbf{q}^\top\mathbf{k}/2\): 2 against k3 and against k5, 0 elsewhere
  • Weights: \(\dfrac{e^2}{2e^2 + 2} = 0.44\) on each neighbour, 0.06 on each other token
  • Each neighbour less than half
  • One needed token alone: 0.71, as in the position section

One Head’s Output Is the Same in Either Order

Output at “7”

\[\mathbf{z}_{\text{7}} = 0.44\,\mathbf{v}_{\text{k3}} + 0.44\,\mathbf{v}_{\text{k5}} + 0.06\,(\mathbf{v}_{\text{7}} + \mathbf{v}_{\text{2}})\]

  • Both neighbours’ values added into the same four coordinates
  • k3 before and k5 after, or the reverse: the same sum
  • The sum records which tokens, not which neighbour each was

More needed tokens

  • \(k\) tokens matched equally by one row: each less than \(1/k\) of the weight
  • Each value a smaller share of one mixed vector
  • Any value width: one weight row gives one weighted sum

Two Heads Weight the Neighbours Separately

Two heads, each with its own projections

  • Head 1: \(\mathbf{q}_t = 2\,\mathbf{u}_{t-1}\), the previous position, the position section’s \(\mathbf{W}_Q\)
  • Head 2: \(\mathbf{q}_t = 2\,\mathbf{u}_{t+1}\), the next position
  • Keys and values as before, in each head

Row of “7” in each head

  • Head 1: 0.71 on k3
  • Head 2: 0.71 on k5
  • Each head’s softmax concentrates on its one token: no division of weight between the needs

Concatenated Head Outputs Distinguish the Two Orders

Output at “7”, head 1’s coordinates then head 2’s

  • k3 7 k5 2: k3’s value in the first half, k5’s in the second
  • k5 7 k3 2: the halves exchanged
  • Previous and next neighbour in different coordinates

Against one head

  • One head: both values summed into the same coordinates
  • Two heads: one value per head, side by side

Multiple Heads Resemble Multiple Convolution Filters

Convolution layer

  • Several filters over the same window, each output channel one pattern of weights
  • Filters fixed by position offset, the same at every position

Multi-head attention

  • Several reads from the same position, each head one weighting of the sequence
  • Projections shared across positions, weights recomputed from content and position at every position

Each head its own subspace

  • Own \(\mathbf{W}_{Q,i}, \mathbf{W}_{K,i}\): its own score function
  • Own \(\mathbf{W}_{V,i}\): its own projection of each token’s value

Multi-Head Attention Splits the Width into \(h\) Heads

Head \(i\), \(i = 1, \ldots, h\)

\[\mathbf{Q}_i = \mathbf{X}\mathbf{W}_{Q,i}^\top, \quad \mathbf{K}_i = \mathbf{X}\mathbf{W}_{K,i}^\top, \quad \mathbf{V}_i = \mathbf{X}\mathbf{W}_{V,i}^\top\]

\[\mathbf{H}_i = \mathrm{softmax}\!\left(\frac{\mathbf{Q}_i \mathbf{K}_i^\top}{\sqrt{d_k}}\right)\mathbf{V}_i \in \mathbb{R}^{T \times d_v}\]

Combined

\[\mathbf{Z} = [\,\mathbf{H}_1\ \cdots\ \mathbf{H}_h\,]\, \mathbf{W}_O^\top, \qquad \mathbf{W}_O \in \mathbb{R}^{d_{\text{model}} \times h\,d_v}\]

Sizes

  • \(h\): the number of heads
  • \(d_k = d_v = d_{\text{model}}/h\): the width divided among the heads
  • \(\mathbf{W}_{Q,i}, \mathbf{W}_{K,i}, \mathbf{W}_{V,i} \in \mathbb{R}^{d_k \times d_{\text{model}}}\): one set per head

Base model (Vaswani et al. 2017)

  • \(d_{\text{model}} = 512\), \(h = 8\), \(d_k = d_v = 64\)

Example, k3, 7, k5, 2

  • \(d_{\text{model}} = 8\) (4 token, 4 position coordinates), \(h = 2\), \(d_k = d_v = 4\)

Heads Attend in Parallel and Recombine Through \(\mathbf{W}_O\)

Projections

  • One \(d_{\text{model}}\)-wide projection each for \(\mathbf{Q}\), \(\mathbf{K}\), \(\mathbf{V}\)
  • Columns \((i - 1)\,d_k + 1\) to \(i\,d_k\): head \(i\)

Scores and weights

  • One \(T \times T\) grid per head
  • Each grid from its head’s queries and keys

Outputs

  • Head outputs side by side: the concatenation
  • \(\mathbf{W}_O\): back to \(d_{\text{model}}\)

Reshaping to \([B, h, T, d_k]\) Makes Heads a Batch Dimension

B, T, d_model = X.shape
d_k = d_model // h
# one d_model-wide projection = all h heads stacked
Q = Wq(X).view(B, T, h, d_k).transpose(1, 2)   # (B, h, T, d_k)
K = Wk(X).view(B, T, h, d_k).transpose(1, 2)
V = Wv(X).view(B, T, h, d_k).transpose(1, 2)
A = (Q @ K.transpose(-2, -1) / d_k ** 0.5).softmax(-1)   # (B, h, T, T)
H = (A @ V).transpose(1, 2).reshape(B, T, d_model)       # heads side by side
Z = Wo(H)                                                # (B, T, d_model)

view and transpose

  • Wq = nn.Linear(d_model, d_model): the \(h\) matrices \(\mathbf{W}_{Q,i}\) stacked, \(d_k\) rows each
  • view(B, T, h, d_k): splits the last dimension into heads, no data moved
  • transpose(1, 2): heads beside the batch dimension, so @ runs once for all heads

Back to one vector per position

  • transpose then reshape: the \(h\) outputs of width \(d_k\) side by side, \(d_{\text{model}}\) in all
  • Wo: the output projection \(\mathbf{W}_O\)

\(\mathbf{W}_O\) Has One Block of Columns per Head

Output projection

\[\mathbf{z}_t = \mathbf{W}_O\, [\,\mathbf{h}_{1,t};\ \ldots;\ \mathbf{h}_{h,t}\,] = \sum_{i=1}^{h} \mathbf{W}_O^{(i)}\, \mathbf{h}_{i,t}\]

  • \(\mathbf{W}_O^{(i)}\): the \(d_v\) columns that multiply head \(i\)’s output
  • Output: a sum of one term per head, each head mapped back to the full width

One head’s contribution

  • Head \(i\) removed: its block of columns set to zero
  • Every other head’s term unchanged

Attention Memory Grows with the Number of Heads

Per layer, \(d_{\text{model}} = 512\)

One head, \(d_k = 512\) 8 heads, \(d_k = 64\)
Weights of \(\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V, \mathbf{W}_O\), biases excluded \(4 \cdot 512^2 = 1{,}048{,}576\) \(1{,}048{,}576\)
Score multiply-adds \(T^2 \cdot 512\) \(8 \cdot T^2 \cdot 64 = T^2 \cdot 512\)
Weights stored for the backward pass \(T^2\) \(8\,T^2\)

Cost per layer

  • Width divided, not added: \(h\,d_k = d_{\text{model}}\)
  • Memory: one \(T \times T\) grid per head
  • Each head’s query and key: \(d_k\) numbers, 64 instead of 512

Translation Quality Peaks at 8 to 16 Heads

Vaswani et al. 2017: base model, English to German, newstest2013 (development set), all else fixed

Heads \(h\) \(d_k = d_v\) BLEU Perplexity
1 512 24.9 5.29
4 128 25.5 5.00
8 64 25.8 4.92
16 32 25.8 4.91
32 16 25.4 5.01
  • Computation held constant across rows (§3.2.2 of the paper)

BLEU differences

  • One head: 0.9 BLEU below the best setting
  • 8 and 16 heads: equal BLEU, perplexity within 0.01
  • 32 heads at \(d_k = 16\): lower again

Heads and width per head

  • Splitting the width into several heads helps, at equal parameters and computation
  • Past a point, narrower heads lose: 16-dimensional queries and keys per head
  • A head’s \(T \times T\) score matrix \(\mathbf{Q}_i \mathbf{K}_i^\top\) has rank at most \(d_k\): at \(d_k = 16\), fewer score patterns available over sentences longer than 16 tokens (Bhojanapalli et al. 2020)

Limits

  • No variance reported, development set, differences of 0.3 to 0.9 BLEU

Some Trained Heads Have Identifiable Roles

Patterns set by hand to show each role, not Voita et al.’s data

Voita et al. 2019: Transformer base, English to Russian, German and French, 6 layers of 8 encoder heads, WMT data (news translation) and OpenSubtitles (film subtitles)

Positional heads

  • Largest weight at relative position \(-1\) or \(+1\) at least 90% of the time
  • Average largest weight above 0.8

Syntactic heads, English to Russian, WMT data

  • Verb to object: best head 78% correct against 41% for the most frequent offset
  • Subject to verb: 52% against 35%

Rare-word head

  • One head in the first layer, largest weight on the least frequent token

Most Trained Heads Can Be Pruned

Pruning (Voita et al. 2019)

  • A gate on each head, fine-tuned from the trained model with a penalty on open gates
  • Gates end almost fully open or fully closed

Encoder self-attention alone, 48 heads

  • WMT data: 10 heads kept, within 0.15 BLEU of all 48
  • OpenSubtitles: 4 heads kept, within 0.25 BLEU
  • 17 heads kept: positional, syntactic and rare-word heads all still present

All attention, 144 heads (48 encoder, 96 decoder), WMT data

  • 75 kept: 29.62 against 29.6 for all
  • 26 kept: 28.90, 0.7 BLEU lower

The Transformer Block

A Transformer Layer Is Two Sublayers with Residual Connections

Two sublayers

  • Self-attention: each position’s vector a read over all positions
  • Position-wise feed-forward network: one two-layer map applied at each position

Around each sublayer

  • Residual connection: the sublayer’s output added to its input
  • Layer normalization: each position’s vector rescaled to zero mean and unit variance, then a learned scale and shift

Across the \(N\) layers

  • Same structure in every layer, separate weights in each: \(\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V, \mathbf{W}_O, \mathbf{W}_1, \mathbf{W}_2\) per layer
  • Depth adds parameters, unlike a recurrence, which reuses its weights at every step

Sublayers Add Their Outputs to One Stream per Position

Residual stream (Elhage et al. 2021)

  • One vector per position, carried from the embedding to the readout
  • Sublayer: reads the stream through layer normalization, adds its output: \(\mathbf{x} \leftarrow \mathbf{x} + F(\mathrm{LN}(\mathbf{x}))\)
  • No sublayer replaces the stream. What earlier layers added stays in the sum

Two kinds of addition

  • Attention: adds to stream \(t\) a mix of values from all streams
  • Feed-forward network: adds to stream \(t\) a function of stream \(t\) alone

Width

  • Every sublayer reads and adds \(d_{\text{model}}\) coordinates: the stream is the layer’s \(T \times d_{\text{model}}\) interface

With One Position, Self-Attention Is a Linear Map

One position

  • Weight on itself: \(a_{1,1} = 1\)
  • Output \(\mathbf{z} = \mathbf{W}_V\,\mathbf{x}\): a linear map of the token’s vector, for any \(\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V\)

XOR of two coordinates

  • Token vector \(\mathbf{x} = (x_1, x_2) \in \{0, 1\}^2\), target \(x_1 \oplus x_2\)
  • Targets 0 at \((0, 0)\) and \((1, 1)\), 1 at \((0, 1)\) and \((1, 0)\)
  • No line separates the two classes: no linear map gives the target, so no attention layer does

More positions

  • Each output a weighted average of value vectors, inside their convex hull
  • Weights: nonlinear in the inputs through the softmax, but they set only the mix
  • Each value vector \(\mathbf{W}_V\mathbf{x}_s\): a linear map of one position’s vector, the only per-position computation in the layer

Feed-Forward Networks Share One Map Across Positions

Position-wise feed-forward network

\[\mathrm{FFN}(\mathbf{x}_t) = \mathbf{W}_2\,\mathrm{ReLU}(\mathbf{W}_1\,\mathbf{x}_t + \mathbf{b}_1) + \mathbf{b}_2\]

  • \(\mathbf{W}_1 \in \mathbb{R}^{d_{ff} \times d_{\text{model}}}\), \(\mathbf{W}_2 \in \mathbb{R}^{d_{\text{model}} \times d_{ff}}\)
  • \(d_{ff} = 4\,d_{\text{model}}\): 2048 in the base model, 256 in the measured model
  • Same \(\mathbf{W}_1, \mathbf{W}_2\) at all positions: equivariant
  • Nonlinear in each position’s vector, through the ReLU

All positions in one product, tokens as rows, \(\mathbf{X} \in \mathbb{R}^{T \times d_{\text{model}}}\)

\[\mathrm{FFN}(\mathbf{X}) = \mathrm{ReLU}(\mathbf{X}\mathbf{W}_1^\top + \mathbf{b}_1)\,\mathbf{W}_2^\top + \mathbf{b}_2\]

  • Same weights for every row
  • Hidden activations: \(T \times d_{ff}\), four times the stream’s width, kept for the backward pass
ffn = nn.Sequential(nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model))
Z = ffn(X)   # X: (B, T, d_model), nn.Linear acts on the last dimension at every position

Two ReLU Units Compute XOR

Feed-forward network, \(d_{\text{model}} = d_{ff} = 2\)

  • Hidden units: \(h_1 = \mathrm{ReLU}(x_1 + x_2)\), \(h_2 = \mathrm{ReLU}(x_1 + x_2 - 1)\), from \(\mathbf{W}_1 = \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}\), \(\mathbf{b}_1 = (0, -1)\)
  • Output first coordinate: \(h_1 - 2h_2\), from \(\mathbf{W}_2 = \begin{bmatrix} 1 & -2 \\ 0 & 0 \end{bmatrix}\)

Four inputs

  • \((0, 0)\): hidden \((0, 0)\), output 0
  • \((0, 1)\) and \((1, 0)\): hidden \((1, 0)\), output 1
  • \((1, 1)\): hidden \((2, 1)\), output \(2 - 2 = 0\)
  • Outputs 0, 1, 1, 0: the XOR

Output along \(x_1 + x_2\)

  • Rises to 1, then falls to 0: no linear function does both
  • \(h_2\) turns on at \(x_1 + x_2 = 1\) and turns the output back down

The ReLU applied at each position supplies the nonlinear map attention lacks

Feed-Forward Networks Are Two Convolutions of Width One

Convolution of width \(k = 1\)

  • A kernel covering one position: \(\mathbf{z}_t\) from \(\mathbf{x}_t\) alone
  • Channels in, channels out: \(d_{\text{model}}\) to \(d_{ff}\), then \(d_{ff}\) to \(d_{\text{model}}\)
  • Same kernel at every position: the \(1 \times 1\) convolution of image networks, on a sequence

Mixing across positions and coordinates

  • Attention: combines positions, linear in the values, coordinates mixed only by \(\mathbf{W}_V\) and \(\mathbf{W}_O\)
  • Feed-forward network: one position at a time, nonlinear in its coordinates

Feed-Forward Networks Are Unnormalized Key-Value Memories

Feed-forward network as a sum over \(d_{ff}\) memories (Geva et al. 2021)

\[\mathrm{FFN}(\mathbf{x}) = \sum_{i=1}^{d_{ff}} \mathrm{ReLU}(\mathbf{k}_i^\top \mathbf{x} + b_i)\,\mathbf{u}_i\]

  • \(\mathbf{k}_i\): row \(i\) of \(\mathbf{W}_1\), matched against the input
  • \(\mathbf{u}_i\): column \(i\) of \(\mathbf{W}_2\), added in proportion to the match

Example, two of three memories matched, \(d_{\text{model}} = 2\), \(d_{ff} = 3\)

  • Keys \(\mathbf{k}_1 = (1, 0)\), \(\mathbf{k}_2 = (0, 1)\), \(\mathbf{k}_3 = (-1, -1)\), biases 0
  • Values \(\mathbf{u}_1 = (0, 2)\), \(\mathbf{u}_2 = (3, 0)\), \(\mathbf{u}_3 = (1, 1)\)
  • Input \(\mathbf{x} = (0.2, 1.0)\): matches \((0.2,\ 1.0,\ 0)\) after the ReLU
  • Output \(0.2\,\mathbf{u}_1 + 1.0\,\mathbf{u}_2 = (3.0,\ 0.4)\)

Against the read

  • Read: weights over positions, normalized by softmax
  • Feed-forward network: weights over \(d_{ff}\) learned memories, unnormalized, zero below the ReLU’s threshold

Residual Connections Add the Identity to the Layer Jacobian

Gradients through a stack, layers \(\mathbf{x}^{(\ell)} = F_\ell(\mathbf{x}^{(\ell - 1)})\)

\[\frac{\partial \mathcal{L}}{\partial \mathbf{x}^{(0)}} = \frac{\partial \mathcal{L}}{\partial \mathbf{x}^{(L)}}\, \mathbf{J}_L \cdots \mathbf{J}_1, \qquad \mathbf{J}_\ell = \frac{\partial F_\ell}{\partial \mathbf{x}^{(\ell - 1)}}\]

  • Norm of the product at most the product of the norms: at most \(c^L\) when every \(\|\mathbf{J}_\ell\| \le c < 1\)
  • Example: 24 factors of norm 0.8 give \(0.8^{24} \approx 0.005\)

Residual connection

\[\mathbf{x}^{(\ell)} = \mathbf{x}^{(\ell - 1)} + F_\ell(\mathbf{x}^{(\ell - 1)}), \qquad \mathbf{J}_\ell = \mathbf{I} + \frac{\partial F_\ell}{\partial \mathbf{x}^{(\ell - 1)}}\]

  • With \(\mathbf{A}_\ell = \partial F_\ell / \partial \mathbf{x}^{(\ell - 1)}\): the product of \((\mathbf{I} + \mathbf{A}_\ell)\) expands into a sum over the \(2^L\) subsets of layers, the identity term among them
  • Gradient to the input: a direct term, whatever the layers’ Jacobians
  • In the residual stream: the identity term is the gradient carried down the stream itself

Layer Normalization Averages over One Position’s Coordinates

Batch normalization, one coordinate over the batch

  • Mean and variance over sequences and positions
  • Padding inside the statistics unless masked
  • Statistics change with batch size and length mix
  • Inference: running averages from training, not the batch’s own statistics

Layer normalization, one position over its coordinates

\[\mathrm{LN}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \boldsymbol{\beta}, \quad \mu, \sigma^2 \text{ over the } d_{\text{model}} \text{ coordinates}\]

  • Example: \(\mathbf{x} = (1, 2, 3, 6)\), \(\mu = 3\), \(\sigma^2 = 3.5\), output \((-1.07,\ -0.53,\ 0,\ 1.60)\) with \(\boldsymbol{\gamma} = \mathbf{1}\), \(\boldsymbol{\beta} = \mathbf{0}\)
  • \(\boldsymbol{\gamma}, \boldsymbol{\beta} \in \mathbb{R}^{d_{\text{model}}}\): learned scale and shift
  • Same computation in training and inference, at any batch size or length
  • Same map at all positions: equivariant

Scale of the residual stream

  • Every sublayer adds an output to it: roughly independent additions grow its variance about linearly with depth, its scale as the square root
  • Each sublayer reads a normalized copy, at the same scale in every layer

Pre-Norm Normalizes the Branch, Post-Norm the Stream

Pre-norm

\[\mathbf{y} = \mathbf{x} + \mathrm{SA}(\mathrm{LN}(\mathbf{x})), \qquad \mathbf{z} = \mathbf{y} + \mathrm{FFN}(\mathrm{LN}(\mathbf{y}))\]

  • Residual stream never normalized: additions only, the identity in each Jacobian
  • Final layer normalization before the readout

Post-norm (Vaswani et al. 2017)

\[\mathbf{y} = \mathrm{LN}(\mathbf{x} + \mathrm{SA}(\mathbf{x})), \qquad \mathbf{z} = \mathrm{LN}(\mathbf{y} + \mathrm{FFN}(\mathbf{y}))\]

  • Residual stream normalized after every addition

The learned-position measurements use the pre-norm layer, with a final layer normalization before the readout

Feed-Forward Weights Are Two Thirds of an Encoder Layer

Component Shapes Weights Share
Attention \(\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V, \mathbf{W}_O\): \(4 \times 512 \times 512\) 1,048,576 33.3 percent
Feed-forward \(\mathbf{W}_1, \mathbf{W}_2\): \(2 \times 512 \times 2048\) 2,097,152 66.6 percent
Layer normalization \(\boldsymbol{\gamma}, \boldsymbol{\beta}\), twice: \(4 \times 512\) 2,048 0.1 percent
Layer 3,147,776
Six-layer encoder 18,886,656

Per layer, \(d = d_{\text{model}}\), \(d_{ff} = 4d\)

  • Attention: \(4d^2\)
  • Feed-forward: \(2\,d\,d_{ff} = 8d^2\)
  • Feed-forward share: \(8 / 12\), two thirds, at any \(d\)

Base model

  • 12 feed-forward networks, six per stack: 25.2 million of about 65 million parameters
  • Decoder layer, with a second attention sublayer: feed-forward one half of its weights

Neither count depends on \(T\)

Feed-Forward Computation Dominates on Short Sequences

Multiply-adds per layer, sequence length \(T\), \(d = d_{\text{model}}\), \(d_{ff} = 4d\)

  • Projections \(\mathbf{Q}, \mathbf{K}, \mathbf{V}\) and \(\mathbf{W}_O\): \(4Td^2\)
  • Scores and weighted sums: \(2T^2 d\)
  • Feed-forward network: \(2\,T\,d\,d_{ff} = 8Td^2\)

Crossovers

  • Scores above the projections beyond \(T = 2d\)
  • Scores above the feed-forward network beyond \(T = 4d\): 2048 at \(d = 512\)
  • Leading terms alone, \(T^2 d\) against \(T d^2\): equal at \(T = d\). With the constants: \(4d\)

At \(T = 50\), \(d = 512\)

  • Feed-forward 105 million, projections 52 million, scores 2.6 million
  • Sentence-length inputs: the feed-forward network is most of the multiply-adds

The Transformer Decoder

Decoder Layers Add a Causal Mask and a Cross-Attention Sublayer

Decoder layer, three sublayers, each sublayer’s output added to the residual stream

  • Masked self-attention: each target position reads itself and earlier target positions
  • Cross-attention: each target position reads every source position, keys and values from the encoder’s output
  • Feed-forward network: as in the encoder layer

Compared with the encoder layer

  • Encoder: no mask, every source position reads every other
  • Weights per layer: \(16d^2\) in the decoder (two attention sublayers, \(4d^2\) each, feed-forward \(8d^2\)), \(12d^2\) in the encoder

Encoder-decoder and decoder-only

  • Encoder-decoder, translation: the encoder reads the source, the decoder writes the target
  • Decoder-only, language models: no encoder, no cross-attention, masked self-attention over one sequence

Decoders Compute One Conditional Distribution per Target Position

Chain rule over the target, source \(x\), target \(y_1, \ldots, y_T\)

\[p(y \mid x) = \prod_{t=1}^{T} p(y_t \mid y_1, \ldots, y_{t-1},\, x)\]

  • Translation’s factorization: each target token conditioned on the source and the target before it
  • Loss: \(-\sum_t \log p(y_t \mid y_{<t}, x)\), one term per factor

Inputs and readouts

  • Input at position \(t\): \(y_{t-1}\), with a start token <s> as \(y_0\)
  • Readout at position \(t\): the factor for \(y_t\)
  • Inputs at positions after \(t\) are \(y_t, y_{t+1}, \ldots\): the token the factor predicts and what follows it

Causal outputs, as in any language model

  • Readout \(t\) from inputs at positions \(1, \ldots, t\) only. Unmasked self-attention at \(t\) reads input \(t + 1\), which is \(y_t\), the token factor \(t\) predicts

  • Shaded: what each factor conditions on. The lower triangle
  • Red: inputs holding the factor’s own token (“answer”) or later ones

Masked Softmax Puts Zero Weight on Later Positions

Masked scores, mask mechanics as in batched attention: \(-\infty\) above the diagonal, zero weight after the softmax

  • \(\mathrm{softmax}(\mathbf{Q}\mathbf{K}^\top / \sqrt{d_k} + \mathbf{M})\,\mathbf{V}\), \(M_{t,s} = 0\) for \(s \le t\), \(-\infty\) otherwise

  • \(e^{-\infty} = 0\): no weight above the diagonal, each row summing to one over its prefix

  • Matrix form: \(\mathrm{softmax}(\mathbf{Q}\mathbf{K}^\top / \sqrt{d_k} + \mathbf{M})\,\mathbf{V}\), \(M_{t,s} = 0\) for \(s \le t\), \(-\infty\) otherwise

Rows of the example, masked against unmasked

  • Row “noir”: \(\mathrm{softmax}(0, 1, 2, 1) = (0.07,\ 0.20,\ 0.53,\ 0.20)\), all four positions allowed
  • Row <s>: weight 1 on itself, the only position allowed
  • Row <s> unmasked: \(\mathrm{softmax}(1, 2, 0, 1) = (0.20,\ 0.53,\ 0.07,\ 0.20)\), 0.80 of its weight on later positions

Cost

  • Same \(T \times T\) product as unmasked, no added parameters
  • \(T(T - 1)/2\) of the \(T^2\) scores computed and then given zero weight: about half the score work unused at large \(T\)

One Masked Pass Computes All \(T\) Conditionals

Causal at every depth

  • Masked self-attention: output at \(t\) from positions \(1, \ldots, t\)
  • Cross-attention: query from position \(t\), keys and values from the source only
  • Feed-forward network, layer normalization, residual: each position on its own
  • So if every input to a layer at position \(s\) depends only on \(y_{<s}\) and \(x\), so does every output: by induction, the readout at \(t\) depends only on \(y_{<t}\) and \(x\), for any number of layers

Training

  • Input: the true target shifted right, <s> le chat noir
  • One forward pass: all \(T\) readouts, all \(T\) loss terms
  • Teacher forcing: every factor conditioned on the true previous tokens

  • Recurrent decoder on the same inputs: \(T\) sequential steps per sentence

Generation

  • No target: input at position \(t\) is the model’s own previous token, one position per step
  • Training never shows a prefix containing the model’s own mistake: the teacher-forcing mismatch of the recurrent decoder, unchanged

Temperature Rescales the Logits Before Sampling

Choosing the next token from the readout’s logits \(\mathbf{s} \in \mathbb{R}^{|\mathcal{V}|}\)

  • Greedy: the highest-scoring token, \(\arg\max_w s_w\)
  • Beam search: several partial outputs kept per step, as in the sequence-to-sequence decoder
  • Sampling: a token drawn from \(p_w = \mathrm{softmax}_w(s_w / \tau)\)
  • Top-\(k\) sampling: the draw restricted to the \(k\) highest-scoring tokens

Temperature \(\tau\): one division before the softmax

\[\frac{p_w}{p_v} = \frac{e^{s_w / \tau}}{e^{s_v / \tau}} = \exp\!\left(\frac{s_w - s_v}{\tau}\right)\]

  • Normalizer cancels: every probability ratio set by a logit gap divided by \(\tau\). Ranking unchanged
  • \(\tau = 1\): the model’s own distribution
  • \(\tau < 1\): gaps enlarged. As \(\tau \to 0\) the top token’s ratio to every other grows without bound: greedy
  • \(\tau > 1\): gaps shrunk. As \(\tau \to \infty\) every ratio tends to 1: uniform

Example, five logits \((2, 1, 0.5, 0, -1)\) at three temperatures

  • Top two logits, gap 1: ratio \(e^{1/\tau}\), 7.39 at \(\tau = 0.5\), 2.72 at \(\tau = 1\), 1.65 at \(\tau = 2\)
  • Top token’s probability: 0.83 at \(\tau = 0.5\), 0.56 at \(\tau = 1\), 0.37 at \(\tau = 2\)

KV Caches Store Earlier Positions’ Keys and Values per Layer

Generation step \(t\), without a cache

  • The stack rerun on all \(t\) tokens, only the last readout used
  • Rows \(1\) to \(t - 1\) of every layer: recomputed, unchanged
  • Unchanged because of the mask: position \(s\) never reads a later position

With a cache, per layer

  • Kept: \(\mathbf{K}, \mathbf{V}\) of positions \(1, \ldots, t - 1\), shape \([B, h, t - 1, d_k]\)
  • New position only: its query, key and value, appended
  • One row of scores against \(t\) keys: no causal mask needed, every key at position \(t\) or earlier
q, k, v = Wq(x_t), Wk(x_t), Wv(x_t)          # new position: (B, h, 1, d_k)
K = torch.cat([K_cache, k], dim=2)           # (B, h, t, d_k)
V = torch.cat([V_cache, v], dim=2)
a = (q @ K.transpose(-2, -1) / d_k ** 0.5).softmax(-1)   # (B, h, 1, t)
z_t = a @ V                                  # (B, h, 1, d_k)

Memory, \(N\) layers, \(d_{\text{model}} = h\,d_k\)

  • Keys and values: \(2 \cdot N \cdot t \cdot d_{\text{model}}\) numbers per sequence
  • \(N = 6\), \(d_{\text{model}} = 512\), \(t = 2048\): 50 MB in 32-bit floats, against 260 MB for the base model’s weights

KV Caching Cuts a Generation Step from \(O(t\,d^2 + t^2 d)\) to \(O(d^2 + t\,d)\)

Multiply-adds per layer at step \(t\), \(d = d_{\text{model}}\), \(d_{ff} = 4d\)

Rerun the stack Cached
Projections and feed-forward \(12\,t\,d^2\) \(12\,d^2\)
Scores and weighted sums, unmasked pairs only \(t(t + 1)\,d\) \(2\,t\,d\)
  • Cached step: the new position’s own work, plus one row of attention over \(t\) keys
  • The cache removes the factor \(t\) from the projections and feed-forward network
  • Cached step: projections dominate up to \(t = 6d\), the score row after

Readout per step, after the last layer

  • \(|\mathcal{V}|\,d_{\text{model}}\) multiply-adds: 18.9 million at \(|\mathcal{V}| = 37{,}000\), about nine times one layer’s feed-forward network at one position
  • Unaffected by the cache: computed once per generated token

Totals to generate \(T\) tokens

  • Rerun: \(\sum_{t \le T} 12\,t\,d^2 \approx 6\,T^2 d^2\) and \(\sum_{t \le T} t^2 d \approx T^3 d / 3\)
  • Cached: \(12\,T\,d^2\) and \(\sum_{t \le T} 2\,t\,d \approx T^2 d\)

Cross-Attention Reads the Encoder Output from Every Decoder Layer

Shapes, target length \(T\), source length \(S\)

\[\mathbf{Q} = \mathbf{Y}\mathbf{W}_Q^\top \in \mathbb{R}^{T \times d_k}, \quad \mathbf{K} = \mathbf{H}\mathbf{W}_K^\top, \ \mathbf{V} = \mathbf{H}\mathbf{W}_V^\top \in \mathbb{R}^{S \times d_k}\]

  • \(\mathbf{Y}\): the decoder stream entering the sublayer. \(\mathbf{H}\): the encoder’s last-layer output, the same for every decoder layer
  • Weights: a \(T \times S\) grid, target positions against source positions, no mask
  • Own \(\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V, \mathbf{W}_O\) per decoder layer: \(4d^2\) weights

Cost

  • Scores and sums: \(2\,T\,S\,d\) per layer
  • \(\mathbf{H}\) does not depend on the target: \(\mathbf{K}, \mathbf{V}\) from \(\mathbf{H}\) computed once per source and layer, reused at every generation step, \(2 \cdot N \cdot S \cdot d_{\text{model}}\) numbers

Read

  • “noir” after “chat”: French order differs, and the read follows the source word, not the position
  • Weights set by hand

Encoder, Decoder and Decoder-Only Stacks Read Different Positions

Encoder-decoder, source side

  • Every source position reads the whole source, both directions
  • “black” reads “cat”, the word after it

Encoder-decoder, target side

  • Target positions read the earlier target, and the whole source through cross-attention

Decoder-only

  • Source positions (blue rows) read only earlier source positions: “black” reads “the” and itself, not “cat”
  • Source vectors: each from its prefix only, one direction, where the encoder’s use both
  • Target positions read the whole source and the earlier target, by self-attention alone
  • One stack, no cross-attention

Tied Weights Share One Matrix Between Embedding and Readout

Readout

\[p(y_t = w \mid y_{<t}, x) = \mathrm{softmax}_w\!\left(\mathbf{W}_{\text{emb}}\,\mathbf{z}_t\right)\]

  • \(\mathbf{W}_{\text{emb}} \in \mathbb{R}^{|\mathcal{V}| \times d_{\text{model}}}\), \(\mathcal{V}\) the vocabulary: one row per token
  • Logit of token \(w\): its row against the top of the stream at position \(t\)

Tied weights (Press and Wolf 2017, used by Vaswani et al. 2017)

  • One matrix for the source embedding, the target embedding and the readout
  • A token’s input vector is also the vector its prediction is scored against
  • EN-DE, one 37,000-token vocabulary: 37.9 million weights saved

Embedding scale (Vaswani et al. 2017)

  • Input embeddings multiplied by \(\sqrt{d_{\text{model}}}\), 22.6 at \(d_{\text{model}} = 512\). Readout unscaled
  • Entries initialized at standard deviation \(d_{\text{model}}^{-1/2}\) in reference implementations: squared row length about \(d_{\text{model}} \cdot d_{\text{model}}^{-1} = 1\) at the readout, input coordinates of size \(\sqrt{d_{\text{model}}} \cdot d_{\text{model}}^{-1/2} = 1\)
  • Sinusoidal position values in \([-1, 1]\): the same order as the scaled embedding coordinates they are added to

Transformers Translated Better Than Recurrent Models at Lower Cost

Test (Vaswani et al. 2017)

  • Translation with the encoder-decoder, against the strongest recurrent (GNMT) and convolutional (ConvS2S) systems of 2017
  • English-German, 4.5 million sentence pairs. English-French, 36 million
  • Measured: BLEU on the WMT 2014 test sets, and the floating-point operations spent on training
  • Decoding: beam of 4, candidate scores length-normalized with exponent 0.6

Two sizes, training cost estimated as time \(\times\) 8 P100 GPUs \(\times\) 9.5 TFLOPS each

  • Base, \(d_{\text{model}} = 512\), 65M parameters: 12 hours, \(3.3 \times 10^{18}\)
  • Big, \(d_{\text{model}} = 1024\), 213M parameters: 3.5 days, \(2.3 \times 10^{19}\)

English-German

  • Base 27.3, above GNMT 24.6 and ConvS2S 25.16, at about a seventh and a third of their training cost
  • Big 28.4, at GNMT’s training cost

English-French

  • Big 41.8, above GNMT 39.92 and ConvS2S 40.46, at about a sixth of their cost
  • Base 38.1, below both baselines

Limits

  • One task family, one test set per language pair
  • BLEU: n-gram overlap with one reference translation
  • Cost estimated from time and hardware, not counted
  • Big EN-FR: 41.0 in the conference proceedings, 41.8 in the later arXiv versions
  • Baseline ensembles (26.30 and 26.36 on EN-DE, 41.16 and 41.29 on EN-FR): below big on both pairs

Training the Transformer

At a High Learning Rate, Post-Norm Training Collapses Unless Warmed Up

Setting

  • Eight layers of the measured model (width 64, one head), recall with 4 pairs, 4,000 steps
  • Adam (\(\beta_2 = 0.98\)), no gradient clipping, three seeds per condition

At \(5 \times 10^{-3}\), final accuracy

  • Post-norm: 0.09 to 0.11, chance. Loss 2.30 to 2.31: \(\ln 10\), the same 0.1 on every value
  • Post-norm, 500-step warmup: 0.28 to 0.33
  • Pre-norm: 0.30 to 0.33
  • Both below the value-count bound, 0.38: collapse avoided, pairing not learned

At \(5 \times 10^{-4}\)

  • Post-norm: 0.99 to 1.00. With warmup: 0.98 to 1.00
  • Pre-norm: 0.69 to 1.00, one seed slower

Last-layer gradient norm at step 5, \(5 \times 10^{-3}\)

  • Post-norm 0.43 to 0.52, pre-norm 0.09 to 0.14

Last-Layer Gradients Cross One Normalization in Either Placement

Gradient to the first layer’s weights, \(N\) layers

Gradient to the last layer’s feed-forward weights

  • Post-norm: through the normalization after the last addition. Its input: a stream renormalized at every layer, the same scale at any depth
  • Pre-norm: through the final normalization before the readout. Its input: the whole stream, every addition summed
  • Each: one crossing, one multiplication by that normalization’s Jacobian

Lower layers

  • Post-norm: one more normalization per addition on the way down
  • Pre-norm: the identity path, additions only, then the final normalization

Normalization Divides the Gradient by Its Input’s Scale

Jacobian of layer normalization, \(\hat{\mathbf{y}} = (\mathbf{x} - \mu)/\sigma\), \(\boldsymbol{\gamma} = \mathbf{1}\), \(\boldsymbol{\beta} = \mathbf{0}\)

\[\frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{x}} = \frac{1}{\sigma}\left(\mathbf{I} - \frac{1}{d}\,\mathbf{1}\mathbf{1}^\top - \frac{1}{d}\,\hat{\mathbf{y}}\hat{\mathbf{y}}^\top\right)\]

  • Bracket: removes the mean and the component along \(\hat{\mathbf{y}}\), the two directions the output cannot change in
  • Factor \(1/\sigma\): the input’s scale
  • Input scaled by \(c\): same \(\hat{\mathbf{y}}\), same bracket, Jacobian divided by \(c\)

Backward pass

  • Gradient passed back: \((\partial \hat{\mathbf{y}} / \partial \mathbf{x})^\top\) times the gradient arriving
  • An input twice as large passes back half the gradient

Example, \(\mathbf{x} = (1, 2, 3, 6)\) and \(2\mathbf{x}\)

  • \(\sigma\): 1.87 and 3.74
  • Output, both: \((-1.07,\ -0.53,\ 0,\ 1.60)\)
  • \(\partial \hat y_4 / \partial x_4\): 0.0573 and 0.0286
  • \(\partial \hat y_4 / \partial x_1\): 0.0955 and 0.0477
  • Every entry halved

In a stack

  • The divisor at each normalization: the scale of the stream it reads
  • Post-norm: a stream renormalized after every addition, the same scale everywhere
  • Pre-norm’s final normalization: the stream after all \(2N\) additions

Pre-Norm’s Final Normalization Shrinks Last-Layer Gradients with Depth

Pre-norm

  • Stream: 11.7 after layer 1, 20.4 after layer 24, each addition adding variance
  • Final normalization divides by the stream’s growing scale, on every gradient’s identity path
  • Last-layer gradient: 0.27 at 6 layers, 0.13 at 48

Post-norm

  • Stream: 8.0 after every layer, renormalized
  • Last-layer gradient: 0.45 at 6 layers, 0.47 at 48, no factor shrinking with depth
  • Xiong et al. 2020: post-norm’s last-layer gradient bounded independently of depth, pre-norm’s bound shrinking as \(1/\sqrt{N}\)

Scaled Initialization Fixes the Pre-Norm Stream Scale

Variance of the stream, pre-norm, \(2N\) additions

  • Plain: each sublayer reads a normalized copy, so every addition has about the same variance \(v\): about \(2N\,v\) on top of the input’s variance, the growth from 11.7 to 20.4 over 24 layers
  • Sublayer output weights scaled by \(1/\sqrt{2N}\) at initialization: each addition \(v / (2N)\), total about \(v\) at any depth
  • Scaled, 24 layers: 11.4 to 11.6 at every layer
  • GPT-2: residual-layer weights scaled by \(1/\sqrt{N_{\text{res}}}\), \(N_{\text{res}}\) the number of residual layers, \(2N\) here (Radford et al. 2019)

Effect on the gradient, last layer, computed at initialization

  • Plain: 0.27 at 6 layers, 0.13 at 48
  • Scaled: 0.32 at 6 layers, 0.22 at 48
  • Falls less with depth: the final normalization’s divisor no longer grows
  • Still falls, 0.32 to 0.22: the stream’s scale is one factor of several
  • Only the initialization changes: training can grow the weights

Deep post-norm

  • Admin (Liu et al. 2020): post-norm’s reliance on each residual branch amplifies parameter updates into large output changes
  • Admin’s rescaled initialization: 60 encoder and 12 decoder layers on English-French, 43.80 BLEU against 43.10 for pre-norm, plain post-norm failing
  • DeepNet (Wang et al. 2022): \(\mathrm{LN}(\alpha\,\mathbf{x} + G(\mathbf{x}))\) with \(\alpha > 1\), and branch weights scaled down by \(\beta < 1\) at initialization, as in the \(1/\sqrt{2N}\) scaling: 1,000 layers trained

Adam’s First Step Leaves the Loss’s Linear Range at Depth

Adam, per coordinate, gradient \(g_t\), learning rate \(\eta\)

\[\theta_t = \theta_{t-1} - \eta\,\frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon}, \qquad \hat m_1 = g_1,\ \ \hat v_1 = g_1^2\]

  • Step 1: \(\pm\eta\) in every coordinate with \(g_1 \ne 0\), the sign of \(g_1\), whatever its size
  • Early steps: \(\hat v_t\) from a handful of gradients, so steps near \(\pm\eta\) in directions set by a few batches (Liu et al. 2020, RAdam)

First-order prediction of the loss change

  • \(\Delta \mathcal{L} \approx \mathbf{g}^\top \Delta\boldsymbol{\theta} = -\eta \sum_i |g_i| = -\eta\,\|\mathbf{g}\|_1\)
  • Grows with the number of parameters and with the gradient’s size: larger in post-norm, larger in deeper stacks
  • Valid only while the step stays where the loss is close to linear

At 48 layers, \(\eta = 10^{-3}\)

  • Post-norm: predicted -3.55, actual +0.06
  • Pre-norm: predicted -1.80, actual +0.04
  • At step 1, gradient clipping bounds \(\mathbf{g}\), not the step: Adam’s step stays \(\pm\eta\)

Larger Transformers Train at Smaller Peak Learning Rates

Loss change per step, from Adam’s step

  • \(\Delta\mathcal{L} \approx -\eta\,\|\mathbf{g}\|_1\): a sum over every parameter, each moved by about \(\eta\)
  • More parameters: more terms in the sum, a larger change for the same \(\eta\)
  • Per parameter, \(\|\mathbf{g}\|_1 / P\) about the same at both depths: the rise is the parameter count
  • Same first-order change per step: \(\eta\) smaller as the parameter count grows

Computed at initialization, post-norm, 6 and 48 layers, width 64

  • \(\|\mathbf{g}\|_1\): 444 at 0.28M parameters, 3,555 at 2.19M

Published (Brown et al. 2020, GPT-3, same data and tokens for all eight sizes)

  • 125M parameters: \(6.0 \times 10^{-4}\). 1.3B: \(2.0 \times 10^{-4}\). 175B: \(0.6 \times 10^{-4}\)
  • Batch from 0.5M to 3.2M tokens over the same range

\(\eta \propto 1/P\) would predict a 1,400-fold drop from 125M to 175B parameters. GPT-3’s rates fall 10-fold, set per size

Warmup Limits Early Steps to the Loss’s Linear Range

Decay after the peak

  • Near a minimum: each batch’s gradient mostly noise around a small mean
  • Adam divides by \(\sqrt{\hat v_t}\), the noise’s own scale, and \(\hat m_t\) averages about 10 batches at \(\beta_1 = 0.9\), too few to cancel the noise: steps a steady fraction of \(\eta\), however small the mean gradient
  • Weights keep moving by amounts proportional to \(\eta\): decaying \(\eta\) shrinks the motion
  • Cosine decay (Loshchilov and Hutter 2017): from the peak to near zero along half a cosine, the common alternative to \(s^{-1/2}\)

Values at \(d_{\text{model}} = 512\)

  • Step 1: \(1.7 \times 10^{-7}\). Step 4,000: \(7.0 \times 10^{-4}\), the peak. Step 100,000: \(1.4 \times 10^{-4}\)

Schedule (Vaswani et al. 2017)

\[\eta(s) = d_{\text{model}}^{-1/2}\,\min\!\big(s^{-1/2},\ s \cdot w^{-3/2}\big), \qquad w = 4000\]

  • Linear rise for \(s \le w\), decay as \(s^{-1/2}\) after, the two equal at \(s = w\)

What it changes

  • First steps: \(\pm\eta\) with \(\eta\) near zero, inside the region where the gradient predicts the loss
  • Adam’s \(\hat v_t\): an average over about 50 steps at \(\beta_2 = 0.98\), settled long before the peak

Published (Xiong et al. 2020)

  • Pre-norm trained without warmup, post-norm did not reach the same result without it

Dropout Perturbs Sublayer Outputs Before the Addition

Measured (Vaswani et al. 2017, base model, development set)

\(p\) Perplexity BLEU
0.0 5.77 24.6
0.1 4.92 25.8
0.2 4.95 25.5

Dropout, rate \(p\)

  • Training: each coordinate set to zero with probability \(p\), the rest multiplied by \(1/(1 - p)\), so the expected value is unchanged
  • Evaluation: no dropout, the full vector

In the transformer (Vaswani et al. 2017)

  • On each sublayer’s output, before it is added to the stream
  • On the sum of embedding and position, in both stacks
  • \(p = 0.1\) in the base model, \(0.3\) in the big English-German model

Placement

  • On the stream after the first addition: a dropped coordinate zeroes that coordinate of the input and of every earlier addition, and cuts the identity path there
  • On a branch: only that sublayer’s addition perturbed, the identity path intact
  • On the embedding-plus-position sum: the stream then holds only the input

Label Smoothing Makes the Optimal Logit Gap Finite

Smoothed target (Szegedy et al. 2016), true token \(y\), vocabulary of \(V\) tokens

\[q_k = (1 - \epsilon)\,[k = y] + \frac{\epsilon}{V}\]

  • Mass \(\epsilon\) moved off the one-hot target, spread evenly over all \(V\) tokens
  • Loss: \(-\sum_k q_k \log p_k = (1 - \epsilon)\,(-\log p_y) + \epsilon \cdot\) (cross-entropy against the uniform distribution)

Best logits

  • Softmax: a logit gap is the log of a probability ratio, \(s_y - s_k = \log(p_y / p_k)\)
  • Cross-entropy smallest at \(p = q\), so the best gap is \[\log\frac{q_y}{q_{\text{other}}} = \log\!\Big(1 + \frac{V(1 - \epsilon)}{\epsilon}\Big)\]
  • One-hot target, \(\epsilon = 0\): loss still falling as the gap grows, no finite best gap
  • \(\epsilon = 0.1\): gap 3.83 at \(V = 5\), 12.7 at \(V = 37{,}000\)

Example, \(V = 5\), \(\epsilon = 0.1\)

  • Target: 0.92 on the true token, 0.02 on each of the other four
  • Best gap: \(\log(0.92 / 0.02) = \log 46 = 3.83\)

Label Smoothing Raised Perplexity and BLEU Together

Measured (Vaswani et al. 2017, base model, development set)

\(\epsilon\) Perplexity BLEU
0.0 4.67 25.3
0.1 4.92 25.8
0.2 5.47 25.7

Perplexity: measured against the one-hot target

  • Mixing a model’s distribution with the uniform one, \(p = (1 - \epsilon)\,p^* + \epsilon / V\): the true token’s probability at least \((1 - \epsilon)\) times \(p^*\)’s
  • Perplexity at most \(1/(1 - \epsilon)\) times \(p^*\)’s: 1.11 at \(\epsilon = 0.1\), 1.25 at \(\epsilon = 0.2\)
  • Measured: \(4.92 / 4.67 = 1.05\) and \(5.47 / 4.67 = 1.17\), within those ratios
  • Training targets put \(1 - \epsilon + \epsilon/V\) on the true token, below 1 by design

BLEU: the decoded translation

  • Greedy decoding: the top-ranked token at each step, rank only
  • Beam search: candidates ranked by summed log-probabilities, so calibration matters
  • Vaswani et al.: smoothing “hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score”

What bounded confidence changes (Müller et al. 2019)

  • Calibration: predicted probabilities closer to observed frequencies, which helps beam search
  • Representations of one class drawn into tight clusters
  • Teachers trained with smoothing distill worse into students: the logits lose how similar the wrong classes are to each other

Cost at Length

Attention Core Dominates Layer Time and Memory at Long Sequences

Setting

  • One layer at \(d_{\text{model}} = 512\), 8 heads of 64, feed-forward width 2,048, one sequence, 32-bit floats
  • Apple M3 Max GPU (Metal backend), forward and backward, median of 10 runs, two replicate measurements agreeing within 0.1 ms on the attention core

Time at \(T = 8{,}192\)

  • Attention core 120 ms, feed-forward 11.5, projections 6.1
  • Core: 87 percent of the layer’s time

Memory at \(T = 8{,}192\)

  • Core: 2,164 MB, against 151 MB for the rest of the layer
  • Weight grid \(h \cdot T^2 \cdot 4\) bytes \(= 8 \cdot 8192^2 \cdot 4 = 2{,}147\) MB: nearly all of it

Crossover

  • Core passes the feed-forward network between \(T = 512\) and \(1{,}024\): 1.1 against 1.4 ms at 512, 2.4 against 2.1 at 1,024
  • Multiply-add count, block section: \(T = 4d = 2{,}048\)
  • Time crosses below half the count’s crossover: the count leaves out the softmax’s exponentials and the grid’s trips through memory

Weight Grids Are Stored but Used Once

One head, standard attention, \(T\) positions, \(d_k = 64\)

Step Multiply-adds Numbers to and from main memory
\(\mathbf{E} = \mathbf{Q}\mathbf{K}^\top / \sqrt{d_k}\) \(T^2 d_k\) write \(T^2\)
\(\mathbf{A} = \mathrm{softmax}(\mathbf{E})\) \(T^2\) exponentials read \(T^2\), write \(T^2\)
\(\mathbf{Z} = \mathbf{A}\mathbf{V}\) \(T^2 d_v\) read \(T^2\)
  • Kept for the backward pass: \(\mathbf{A}\), \(T^2\) numbers

At \(T = 8{,}192\), one head

  • Arithmetic: \(2 \cdot 8192^2 \cdot 64 = 8.6 \times 10^9\) multiply-adds
  • Traffic: \(4 \cdot 8192^2 = 2.7 \times 10^8\) numbers, 1.07 GB in 32-bit floats
  • Matrix products: 64 multiply-adds per number of the grid written or read
  • Softmax: about one exponential per two numbers moved: its time set by memory traffic, not arithmetic

Costs of the grid

  • Storage: \(\mathbf{A}\) held from the forward pass to the backward pass, \(h\,T^2\) numbers per layer
  • Traffic: the grid written twice and read twice through main memory

Used once

  • Each row of \(\mathbf{A}\): computed from one query, used for one weighted sum
  • No other step needs the grid itself: only its rows’ weighted sums \(\mathbf{Z}\)
  • Backward pass: needs \(\mathbf{A}\) or the means to recompute it

Store or recompute, any layer

  • Gradient checkpointing (Chen et al. 2016): keep each layer’s input only, rerun the layer’s forward pass during the backward pass
  • Memory: one \(T \times d_{\text{model}}\) input per layer, instead of every intermediate tensor
  • Cost: about one extra forward pass, training compute up by about a third

Consequence

  • An algorithm that never writes \(\mathbf{E}\) or \(\mathbf{A}\) to main memory removes both the storage and most of the traffic, at the same forward arithmetic

Softmax Rows Can Be Computed One Block at a Time

One row in blocks, scores \(e_s\), values \(v_s\)

  • Keep a running maximum \(m\), a running sum \(\ell = \sum_s e^{e_s - m}\), a running weighted sum \(\mathbf{a} = \sum_s e^{e_s - m}\,\mathbf{v}_s\)
  • New block, new maximum \(m' \ge m\): rescale the old sums by \(e^{m - m'}\), add the block’s terms
  • After the last block: output \(\mathbf{a} / \ell\), the softmax-weighted sum exactly
  • Same identity as the row-maximum subtraction of stable softmax: \(e^{e_s - m}\) for any \(m\), corrected when \(m\) changes

\[\ell' = \ell\,e^{m - m'} + \sum_{s \in \text{block}} e^{e_s - m'}, \qquad \mathbf{a}' = \mathbf{a}\,e^{m - m'} + \sum_{s \in \text{block}} e^{e_s - m'}\,\mathbf{v}_s\]

Online softmax normalizer: Milakov and Gimelshein 2018

Worked row, scores \((2, 0, 1 \mid 3, 1)\), scalar values \((1, 0, 2 \mid 3, 1)\)

  • Block 1: \(m = 2\), \(\ell = 1 + e^{-2} + e^{-1} = 1\.503\), \(a = 1 + 0 + 2e^{-1} = 1\.736\)
  • Block 2: \(m' = 3\), old sums rescaled by \(e^{2 - 3} = 0\.368\)
  • \(\ell' = 1\.503 \cdot 0\.368 + 1 + e^{-2} = 1\.688\)
  • \(a' = 1\.736 \cdot 0\.368 + 3 + e^{-2} = 3\.774\)
  • Output \(a' / \ell' = 2\.235\): the full softmax gives 2.235

What was kept

  • \(m\), \(\ell\) and the vector \(\mathbf{a}\) per row between blocks, never the row of weights

Tiled Attention Stores No \(T \times T\) Grid

FlashAttention (Dao et al. 2022)

  • Blocks of \(\mathbf{Q}\), \(\mathbf{K}\), \(\mathbf{V}\) loaded into on-chip memory, one tile of scores computed there, running statistics updated, the tile discarded
  • Output exactly \(\mathrm{softmax}(\mathbf{Q}\mathbf{K}^\top)\mathbf{V}\)

Memory

  • Stored: the output and two statistics per row, \(m\) and \(\ell\): extra memory linear in \(T\)
  • Backward pass: tiles of \(\mathbf{E}\) and \(\mathbf{A}\) recomputed from \(\mathbf{Q}\), \(\mathbf{K}\), \(\mathbf{V}\) and the stored statistics

Arithmetic and traffic

  • Same \(O(T^2 d)\) multiply-adds, plus the recomputation
  • Main-memory accesses \(\Theta(T^2 d^2 / M)\) against \(\Theta(T d + T^2)\), \(M\) the on-chip memory size
  • Attention in GPT-2 medium, 1,024 tokens, batch 64, A100 GPU, FlashAttention against standard: 75.2 against 66.6 GFLOPs, 4.4 against 40.3 GB read and written, 7.3 against 41.7 ms

Published results

  • 3× training speedup on GPT-2 at 1,024 tokens
  • Up to 20× less memory than exact attention baselines, growing linearly with \(T\)

Local Windows Cut the Grid to \(T \times w\) Entries

Sliding window (Longformer, Beltagy et al. 2020)

  • Each position reads \(w/2\) positions on each side
  • Entries: about \(T\,w\) instead of \(T^2\), arithmetic and memory \(O(T\,w)\)
  • Pretrained with \(w = 512\) at up to \(T = 4{,}096\): one eighth of the grid

Path length

  • Reach per layer: \(w/2\) positions in each direction
  • Positions \(s\) and \(t\): \(\lceil |t - s| / (w/2) \rceil\) layers apart
  • \(T = 4{,}096\), \(w = 512\): the two ends 16 layers apart. Longformer-base: 12 layers
  • The trade of a convolution without dilation: cost linear in \(T\), path growing as distance over \(w/2\)

Wider receptive field without wider windows

  • Dilated windows: gaps of \(\delta\) between the positions read, reach \(\delta\,w/2\) per layer
  • Different window widths per layer: 32 in the lowest layers to 512 in the highest, in the character-level models

Global and Strided Positions Restore Short Paths

Global positions (Longformer)

  • A few positions read every position and are read by every position: the task’s chosen tokens, such as the classification token or the question in question answering
  • Any two positions: two layers apart, through a global position
  • Added entries: about \(2\,g\,T\) for \(g\) global positions, still linear in \(T\)

Strided pattern (Sparse Transformer, Child et al. 2019)

  • Two kinds of read: the previous \(r\) positions, and every \(r\)-th earlier position
  • Stride \(r = \sqrt{T}\): any earlier position two steps away, one strided step to its block, one local step inside it
  • Entries per row at most \(2\sqrt{T}\): \(O(T\sqrt{T})\) in all

Fixed pattern

  • Which pairs can ever be compared, set before the content is seen

Linear Attention Replaces the Exponential with a Feature-Map Product

Softmax read as a kernel

\[\mathbf{z}_t = \frac{\sum_s \mathrm{sim}(\mathbf{q}_t, \mathbf{k}_s)\,\mathbf{v}_s}{\sum_s \mathrm{sim}(\mathbf{q}_t, \mathbf{k}_s)}, \qquad \mathrm{sim}(\mathbf{q}, \mathbf{k}) = e^{\mathbf{q}^\top \mathbf{k} / \sqrt{d_k}}\]

  • Kernel regression’s form: a weighted average with weights from a similarity, normalized

Feature-map similarity (Katharopoulos et al. 2020)

  • \(\mathrm{sim}(\mathbf{q}, \mathbf{k}) = \phi(\mathbf{q})^\top \phi(\mathbf{k})\), \(\phi(x) = \mathrm{elu}(x) + 1\) per coordinate: positive, so weights stay non-negative

\[\mathbf{z}_t^\top = \frac{\phi(\mathbf{q}_t)^\top \Big(\sum_s \phi(\mathbf{k}_s)\,\mathbf{v}_s^\top\Big)}{\phi(\mathbf{q}_t)^\top \sum_s \phi(\mathbf{k}_s)}\]

  • Bracketed sums: the same for every \(t\), computed once

Cost

  • Softmax: the \(T \times T\) grid first, \(O(T^2 d)\)
  • Feature map: \(\sum_s \phi(\mathbf{k}_s)\mathbf{v}_s^\top\) first, a \(d_k \times d_v\) matrix, \(O(T\,d_k\,d_v)\) per head, no grid
  • Softmax per head: \(O(T^2 d_k)\). Feature map cheaper once \(T > d_k\), in the leading terms

Causal form

  • Sums over \(s \le t\): \(\mathbf{S}_t = \mathbf{S}_{t-1} + \phi(\mathbf{k}_t)\,\mathbf{v}_t^\top\), \(\mathbf{u}_t = \mathbf{u}_{t-1} + \phi(\mathbf{k}_t)\)
  • Output from \(\mathbf{S}_t\) and \(\mathbf{u}_t\) alone: a recurrence with a \(d_k \times d_v\) state
  • Generation: constant time and memory per token, no growing cache
  • \(\mathbf{S}_t\): a sum of outer products, rank at most \(d_k\). Past \(d_k\) positions the keys overlap, and their values mix in the read: the fixed-size state of the recurrent encoder again

Feature-Map Weights Are Flatter Than Softmax Weights

Row “7”, \(\phi(\mathbf{x}_{\text{7}}) = (1, 1, 3, 1)\)

  • Similarities: 8 to each other token, 12 to itself: weights 0.22 and 0.33
  • Softmax of the same scores: 0.096 and 0.711

Why flatter

  • Softmax: weight ratio \(e^{\Delta e}\), unbounded in the score gap
  • Feature map: weight ratio \(12/8 = 1.5\), the ratio of two positive dot products, growing linearly with the dot-product gap, not exponentially

Retrieval Reads the Top-\(k\) Keys from an External Store

Memorizing Transformers (Wu et al. 2022)

  • One layer of 12, near the top, reads two sources: the local context of 512 positions, and an external store of (key, value) pairs from earlier text, up to 262K per head
  • From the store: the \(k = 32\) pairs with the highest scores against the query, by approximate nearest-neighbour search (about 90 percent recall)
  • Mix: learned gate per head, \(\sigma(b_g)\), between the two reads
  • Which pairs are read: chosen by content, unlike a fixed sparse pattern

Cost per query

  • Search plus a 32-entry softmax, against a softmax over 262K entries

Limits

  • No gradient into the store: its keys and values fixed once written
  • Top-\(k\) cut: entries outside the 32 get no weight and no gradient

Flipping One Input Changes a Soft Read by \(O(1/T)\)

Fixed number of sequential steps

  • \(L\) layers: \(L\) rounds of reads, whatever \(T\) is
  • The parallel step count of the attention layer, read the other way: no more sequential steps for a longer input

Parity of a bit string, \(x_1, \ldots, x_T \in \{0, 1\}\)

  • Answer: 1 if the number of ones is odd
  • Flipping any single bit flips the answer
  • Recurrent unit: a one-bit state flipped at every 1, exact at any \(T\) in \(T\) steps

Averaging read, uniform weights over \(T\) bits

  • Output: the fraction of ones
  • One bit flipped: the output moves by \(1/T\)
\(T\) Change from one flipped bit
10 0.1
100 0.01
1,000 0.001

Any fixed transformer (Hahn 2020)

  • Soft attention, fixed layers and heads, Lipschitz components: exchanging one input symbol changes the last layer’s activation by \(O(1/T)\)
  • Parity next-symbol prediction: cross-entropy tends to chance as \(T\) grows
  • Hard attention: parity and two-bracket matching not recognized for all lengths
  • Layers, heads or weight norms have to grow with \(T\)

Consequence

  • Parity’s answer depends on every bit equally, and each bit’s effect on a read shrinks as \(1/T\)

Transformers Trained on Parity Fall to Chance Past the Training Lengths

Bhattamishra et al. 2020, transformers of up to 4 layers and 4 heads against LSTMs

  • Score: strings with every next-character prediction correct
  • Training lengths 2 to 50: transformer 68.7%, LSTM 100%
  • Lengths 51 to 100: transformer 0.0%, LSTM 100%
  • No positional encoding: parity not recognized at any length

Delétang et al. 2023, trained on lengths up to 40, tested on 41 to 500

  • Accuracy, best of 10 seeds: transformer 52.0%, recurrent network and LSTM 100%
  • Chance: 50%

Constructions exist

  • Two layers and two heads recognize parity at any length (Chiang and Cholak 2022)
  • Confidence still tends to chance as the length grows, the \(O(1/T)\) bound again
  • Layer normalization with \(\epsilon = 0\) removes the decay, a setting not used in training

What the read trades

  • Any distance in one step, all positions in parallel: one read over all \(T\) inputs
  • The same averaging dilutes any single input’s effect as \(T\) grows
  • A recurrent state carries one bit exactly across any length, at \(T\) sequential steps

Scaling the Block

Placeholder: The Block Against Recurrent + Read on Few Examples

Run, pending (data sweep on the remote machine)

  • Latest-value task, 4 pairs, fixed training sets of 1,000 to 50,000 sequences
  • Block: two pre-norm layers of width 64, learned positions, 95,946 parameters. Recurrent + read: GRU of width 152 with a read over its states, about 93,000
  • 8,000 steps per run, accuracy on 2,000 fresh sequences, two seeds per point

Title and claim written from the result

Unlabeled Text Supplies a Target at Every Position

Language-model targets

  • Loss of the language model: one term per position, the next token as the target
  • Sequence of \(T\) tokens: \(T - 1\) targets, no labels
  • Decoder-only stack: all \(T - 1\) trained in one masked pass

Counts

  • English-German translation data: 4.5 million sentence pairs, each pair one human-made translation
  • GPT-3 training text: 300 billion tokens (Brown et al. 2020), about one target per token
  • Latest-value sweep: at most 50,000 sequences, one answer each

What the targets carry

  • Whatever structure the text has: word order, agreement, facts stated in it
  • The same loss on any text, with no task chosen in advance

Every Token Pays for Every Weight

Forward pass, per token (Kaplan et al. 2020)

\[C_{\text{forward}} \approx 2N + 2\,n_{\text{layer}}\,n_{\text{ctx}}\,d_{\text{model}} \ \text{FLOPs}, \qquad N \approx 12\,n_{\text{layer}}\,d_{\text{model}}^2\]

  • \(2N\): one multiply-add per weight, every weight used for every token
  • Second term: the scores and weighted sums, growing with context length \(n_{\text{ctx}}\)
  • Training: about \(6N\) per token, the backward pass about twice the forward

At the deck’s base width, \(d_{\text{model}} = 512\), 6 layers

  • \(N = 6 \cdot 12 \cdot 512^2 = 18\.9\) million: as many multiply-adds per token
  • Feed-forward networks: 12.6 million of them, two thirds

Widening the feed-forward network

  • Width \(4d\) to \(16d\): four times the memories of the key-value view
  • Per layer: \(4d^2 + 8d^2 = 12d^2\) becomes \(4d^2 + 32d^2 = 36d^2\)
  • Every token’s cost three times larger, for every token, whether its output uses the new memories or not

At scale

  • 175 billion weights (GPT-3): about \(3.5 \times 10^{11}\) FLOPs per token forward
  • Training on 300 billion tokens: \(6 \cdot 1.75 \times 10^{11} \cdot 3 \times 10^{11} \approx 3.2 \times 10^{23}\) FLOPs

Capacity and per-token compute grow together in a dense layer

Routing Sends Each Token to One of Many Feed-Forward Networks

Switch layer (Fedus et al. 2022), replacing the feed-forward sublayer

  • \(E\) experts: \(E\) feed-forward networks of the usual width
  • Router: logits \(\mathbf{h} = \mathbf{W}_r\,\mathbf{x}\), \(\mathbf{W}_r \in \mathbb{R}^{E \times d_{\text{model}}}\), probabilities \(p_i = \mathrm{softmax}_i(\mathbf{h})\)
  • Each token to its highest-probability expert \(i\): output \(p_i\,E_i(\mathbf{x})\), the expert’s output scaled by its gate value
  • Gate value in the output: the router trained by the loss through \(p_i\)

From the key-value view

  • A token’s feed-forward output draws on few memories strongly
  • Experts: groups of memories, a token reading one group

Published (Switch-Base, 64 experts, against T5-Base)

  • Same quality in one seventh of the pretraining time, same multiply-adds per token
  • Largest model: 1.6 trillion parameters, 2,048 experts

At \(E = 4\), \(d_{\text{model}} = 512\), per layer

  • Weights: 9.4 million, against 3.1 dense
  • Multiply-adds per token: 3.15 million, against 3.15 dense