
EE 641 - Unit 6
Fall 2026
Sequences and Contextual Vectors
[Transformer] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, “Attention is all you need,” in Advances in Neural Information Processing Systems, vol. 30, 2017, pp. 5998–6008.
[Transformer] M. Phuong and M. Hutter, “Formal algorithms for transformers,” arXiv:2207.09238, 2022.
[Analysis] E. Voita, D. Talbot, F. Moiseev, R. Sennrich, and I. Titov, “Analyzing multi-head self-attention: Specialized heads do the heavy lifting, the rest can be pruned,” in Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, 2019, pp. 5797–5808.
[Analysis] M. Geva, R. Schuster, J. Berant, and O. Levy, “Transformer feed-forward layers are key-value memories,” in Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, 2021, pp. 5484–5495.
[Position] J. Su, M. Ahmed, Y. Lu, S. Pan, W. Bo, and Y. Liu, “RoFormer: Enhanced transformer with rotary position embedding,” Neurocomputing, vol. 568, art. 127063, 2024.
[Position] O. Press, N. A. Smith, and M. Lewis, “Train short, test long: Attention with linear biases enables input length extrapolation,” in International Conference on Learning Representations, 2022.
[Training] R. Xiong, Y. Yang, D. He, K. Zheng, S. Zheng, C. Xing, H. Zhang, Y. Lan, L. Wang, and T.-Y. Liu, “On layer normalization in the transformer architecture,” in Proceedings of the 37th International Conference on Machine Learning, PMLR vol. 119, 2020, pp. 10524–10533.
[Efficiency] T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Ré, “FlashAttention: Fast and memory-efficient exact attention with IO-awareness,” in Advances in Neural Information Processing Systems, vol. 35, 2022, pp. 16344–16359.
[Efficiency] Y. Tay, M. Dehghani, D. Bahri, and D. Metzler, “Efficient transformers: A survey,” ACM Computing Surveys, vol. 55, no. 6, pp. 1–28, 2023.
[Efficiency] W. Fedus, B. Zoph, and N. Shazeer, “Switch transformers: Scaling to trillion parameter models with simple and efficient sparsity,” Journal of Machine Learning Research, vol. 23, no. 120, pp. 1–39, 2022.

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}}}\]
Readout per task
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)\]
Targets per sequence
Causal outputs


Same token, two vectors
Contextual vector

Sentence
Latest-value sequence
Position as an input
Permutation matrix \(\mathbf{P}\): \(\mathbf{P}\mathbf{x}\) the same entries in a new order
Invariant: \(f(\mathbf{P}\mathbf{x}) = f(\mathbf{x})\)
Equivariant: \(f(\mathbf{P}\mathbf{x}) = \mathbf{P}\,f(\mathbf{x})\)
Order-dependent: neither

Layers by class

Recurrent
Convolutional
Attention over the same sequence
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\]
Order of the items

Cross-attention
Recurrent
Convolution and attention
Stacked layers, \(L\) of them

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

Path length, position 1 to position \(T\)
Gradient along the path
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)\) |


At \(d = 512\)

Transformer (Vaswani et al. 2017)
Components
Base model
Stacking

Read from “it”
Output of the read

Steps
Self-attention
Contextual states
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)\]
Grid


Sizes
Vectors per token, all from \(\mathbf{x}_t\)
Equal projections (hypothetical)

Step 1: scores
Step 2: weights
Step 3: outputs
Example, one coordinate per token
Row of “7”

Identity projections

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)\]
Other rows
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)\]
Contextual vector

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}\]
Row of “7”

Query and key projections
Tokens as rows
\[\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}\]
Batched, in PyTorch
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
Self-attention: queries and items reordered together, permutation matrix \(\mathbf{P}\) on the rows of \(\mathbf{X}\)
\[\mathrm{SA}(\mathbf{P}\mathbf{X}) = \mathbf{P}\,\mathrm{SA}(\mathbf{X})\]
Permutation equivariance

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

Tasks over one token sequence, 8 pairs
Models

Measured, 8 pairs, two seeds, 2,000 test sequences
Self-attention over tokens
Bound from value counts
Among these models, accuracy above that guess only where the input format or a recurrence pairs values with keys

Input vectors
Read from “7”
Where position is encoded
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}}}\]
Same token, two positions

Embedding scale

Input, k3, 7, k5, 2 at positions 1 to 4
Projections
Score, \(d_k = 4\)

Read from “7”
Output at “7”
Rule inside \(\mathbf{W}_Q\)

Same tokens, shifted by 3
Tasks
Added positions
In training

Model
Measured, two seeds, 20,000 training steps
Training
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}}}\]
Binary counting

Choice (Vaswani et al. 2017)
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}\]

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)\]
Without projections

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}}\]
Learned \(\mathbf{M}\)
Example with added positions

Insertion points
At A
At B
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)\]
Tokens k3, 7, k5, 2, \(\lambda = 0.5\)

On the grid
Slopes (Press et al. 2022)
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\]

Complex form
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\]
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\]
Beyond the training length
Example, one rotary pair: k3, 7, k5, 2, \(\theta = 60°\)
Shifted by 3 positions

Against added positions
One rate against many

Test
Measured, recall, 2,000 test sequences
Absolute against relative
Limits

Two needs at “it”
One head

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

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}})\]
More needed tokens

Two heads, each with its own projections
Row of “7” in each head

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

Convolution layer
Multi-head attention
Each head its own subspace
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
Base model (Vaswani et al. 2017)
Example, k3, 7, k5, 2

Projections
Scores and weights
Outputs
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 eachview(B, T, h, d_k): splits the last dimension into heads, no data movedtranspose(1, 2): heads beside the batch dimension, so @ runs once for all headsBack to one vector per position
transpose then reshape: the \(h\) outputs of width \(d_k\) side by side, \(d_{\text{model}}\) in allWo: the output projection \(\mathbf{W}_O\)
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}\]
One head’s contribution
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

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 |
BLEU differences
Heads and width per head
Limits

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
Syntactic heads, English to Russian, WMT data
Rare-word head

Pruning (Voita et al. 2019)
Encoder self-attention alone, 48 heads
All attention, 144 heads (48 encoder, 96 decoder), WMT data

Two sublayers
Around each sublayer
Across the \(N\) layers

Residual stream (Elhage et al. 2021)
Two kinds of addition
Width
One position
XOR of two coordinates
More 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\]
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\]

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

Output along \(x_1 + x_2\)
The ReLU applied at each position supplies the nonlinear map attention lacks

Convolution of width \(k = 1\)
Mixing across positions and coordinates
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\]
Example, two of three memories matched, \(d_{\text{model}} = 2\), \(d_{ff} = 3\)

Against the read
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)}}\]
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)}}\]


Batch normalization, one coordinate over the batch
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}\]
Scale of the residual stream

Pre-norm
\[\mathbf{y} = \mathbf{x} + \mathrm{SA}(\mathrm{LN}(\mathbf{x})), \qquad \mathbf{z} = \mathbf{y} + \mathrm{FFN}(\mathrm{LN}(\mathbf{y}))\]
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}))\]
The learned-position measurements use the pre-norm layer, with a final layer normalization before the readout
| 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\)
Base model
Neither count depends on \(T\)
Multiply-adds per layer, sequence length \(T\), \(d = d_{\text{model}}\), \(d_{ff} = 4d\)
Crossovers
At \(T = 50\), \(d = 512\)


Decoder layer, three sublayers, each sublayer’s output added to the residual stream
Compared with the encoder layer
Encoder-decoder and decoder-only
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)\]
Inputs and readouts
<s> as \(y_0\)Causal outputs, as in any language model


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
<s>: weight 1 on itself, the only position allowed<s> unmasked: \(\mathrm{softmax}(1, 2, 0, 1) = (0.20,\ 0.53,\ 0.07,\ 0.20)\), 0.80 of its weight on later positionsCost
Causal at every depth
Training
<s> le chat noir
Generation
Choosing the next token from the readout’s logits \(\mathbf{s} \in \mathbb{R}^{|\mathcal{V}|}\)
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)\]

Example, five logits \((2, 1, 0.5, 0, -1)\) at three temperatures
Generation step \(t\), without a cache
With a cache, per layer

Memory, \(N\) layers, \(d_{\text{model}} = h\,d_k\)
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\) |
Readout per step, after the last layer
Totals to generate \(T\) tokens

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}\]
Cost

Read

Encoder-decoder, source side
Encoder-decoder, target side
Decoder-only
Readout
\[p(y_t = w \mid y_{<t}, x) = \mathrm{softmax}_w\!\left(\mathbf{W}_{\text{emb}}\,\mathbf{z}_t\right)\]
Tied weights (Press and Wolf 2017, used by Vaswani et al. 2017)
Embedding scale (Vaswani et al. 2017)

Test (Vaswani et al. 2017)

Two sizes, training cost estimated as time \(\times\) 8 P100 GPUs \(\times\) 9.5 TFLOPS each
English-German
English-French
Limits

Setting
At \(5 \times 10^{-3}\), final accuracy
At \(5 \times 10^{-4}\)
Last-layer gradient norm at step 5, \(5 \times 10^{-3}\)

Gradient to the first layer’s weights, \(N\) layers
Gradient to the last layer’s feed-forward weights
Lower layers
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)\]
Backward pass
Example, \(\mathbf{x} = (1, 2, 3, 6)\) and \(2\mathbf{x}\)
In a stack

Pre-norm
Post-norm
Variance of the stream, pre-norm, \(2N\) additions
Effect on the gradient, last layer, computed at initialization

Deep post-norm
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\]
First-order prediction of the loss change

At 48 layers, \(\eta = 10^{-3}\)
Loss change per step, from Adam’s step
Computed at initialization, post-norm, 6 and 48 layers, width 64
Published (Brown et al. 2020, GPT-3, same data and tokens for all eight sizes)

\(\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

Decay after the peak
Values at \(d_{\text{model}} = 512\)
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\]
What it changes
Published (Xiong et al. 2020)

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\)
In the transformer (Vaswani et al. 2017)
Placement
Smoothed target (Szegedy et al. 2016), true token \(y\), vocabulary of \(V\) tokens
\[q_k = (1 - \epsilon)\,[k = y] + \frac{\epsilon}{V}\]
Best logits

Example, \(V = 5\), \(\epsilon = 0.1\)
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
BLEU: the decoded translation
What bounded confidence changes (Müller et al. 2019)

Setting
Time at \(T = 8{,}192\)
Memory at \(T = 8{,}192\)
Crossover
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\) |
At \(T = 8{,}192\), one head
Costs of the grid
Used once
Store or recompute, any layer
Consequence
One row in blocks, scores \(e_s\), values \(v_s\)
\[\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)\)
What was kept

FlashAttention (Dao et al. 2022)
Memory
Arithmetic and traffic
Published results

Sliding window (Longformer, Beltagy et al. 2020)
Path length
Wider receptive field without wider windows

Global positions (Longformer)
Strided pattern (Sparse Transformer, Child et al. 2019)
Fixed pattern
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}}\]
Feature-map similarity (Katharopoulos et al. 2020)
\[\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)}\]
Cost
Causal form

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

Memorizing Transformers (Wu et al. 2022)
Cost per query
Limits
Fixed number of sequential steps
Parity of a bit string, \(x_1, \ldots, x_T \in \{0, 1\}\)
Averaging read, uniform weights over \(T\) bits
| \(T\) | Change from one flipped bit |
|---|---|
| 10 | 0.1 |
| 100 | 0.01 |
| 1,000 | 0.001 |
Any fixed transformer (Hahn 2020)
Consequence
Bhattamishra et al. 2020, transformers of up to 4 layers and 4 heads against LSTMs
Delétang et al. 2023, trained on lengths up to 40, tested on 41 to 500
Constructions exist
What the read trades
Run, pending (data sweep on the remote machine)
Title and claim written from the result
Language-model targets
Counts

What the targets carry
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\]
At the deck’s base width, \(d_{\text{model}} = 512\), 6 layers
Widening the feed-forward network
At scale
Capacity and per-token compute grow together in a dense layer
Switch layer (Fedus et al. 2022), replacing the feed-forward sublayer
From the key-value view
Published (Switch-Base, 64 experts, against T5-Base)

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