Math Foundations — Lecture 6
Attention score functions, self-attention, QKV projections, multi-head, positional encodings, residuals, layer norm, causal mask.
Attention score functions
All attention mechanisms compute a relevance score \(e\) between a query and a key, then softmax over keys.
Dot-product
Bilinear (general)
Learnable \(W\) allows the model to weight dimensions differently.
Additive (Bahdanau)
Projects query and key into a shared space, then scores with a learned vector \(\mathbf{b}\).
Scaled dot-product (Vaswani et al.)
For random unit-variance vectors in \(\mathbb{R}^{d_k}\), \(\mathbb{E}[\mathbf{q}^\top\mathbf{k}]=0\) but \(\mathrm{Var}[\mathbf{q}^\top\mathbf{k}]=d_k\). Dividing by \(\sqrt{d_k}\) restores unit variance → softmax stays in a non-saturated regime → healthier gradients.
Self-attention
Every position attends to every other position in the same sequence:
Output \(\mathbf{o}_i\) is a weighted average of all input vectors — weights determined by pairwise similarity.
Query, key, value projections
Instead of raw \(\mathbf{x}\), project into three roles:
In matrix form for all positions simultaneously:
where \(Q,K,V\in\mathbb{R}^{n\times d_k}\) (or \(d_v\) for values).
Multi-head attention
\(H\) heads, each with \(d_k=d_\text{model}/H\). Heads can specialise (e.g. one attends to syntax, another to coreference). Output projection \(W^O\in\mathbb{R}^{d_\text{model}\times d_\text{model}}\) mixes them.
Positional encodings
Self-attention is permutation-invariant. Add position information to inputs:
Sinusoidal (original Transformer)
Different frequencies per dimension; the model can learn to attend to relative positions.
Learned positional embeddings
A trainable vector per position index — simple and effective; limited to max seen length.
RoPE (rotary)
Rotates query/key pairs by position-dependent angles so that \(\mathbf{q}_m^\top\mathbf{k}_n\) depends only on \(m-n\). Preserves relative distance in cosine similarity.
Causal masking
For autoregressive decoding, position \(i\) must not see positions \(j>i\):
After softmax, \(\alpha_{ij}=0\) for future positions. Enables parallel training of all positions while preserving the autoregressive property.
Residual connections
Gradient flows directly through the addition, avoiding degradation in deep stacks. Also stabilises training by keeping the input "highway" intact.
Layer normalisation
Normalises activations per token; independent of batch size (unlike batch norm).
Transformer encoder block (summary)
where \(\mathrm{FFN}(\mathbf{a})=\mathrm{ReLU}(\mathbf{a}W_1+\mathbf{b}_1)W_2+\mathbf{b}_2\). Stack \(N\) such blocks (e.g. 6 in the original paper).
Cross-attention (decoder)
Decoder block has three sub-layers: masked self-attention, cross-attention, FFN.
Queries from the decoder, keys and values from the encoder — this replaces the single bottleneck vector of vanilla seq2seq.