Attention as a dynamic content-based lookup
In feedforward layers, weights are static connections learned during training. In self-attention, the weights connecting tokens are computed dynamically on the fly based on token compatibility. Each input token representation is projected into three subspaces:
- Query (Q): what information token i is searching for.
- Key (K): what features or context token j advertises.
- Value (V): the actual content payload transmitted if attended to.
The matrix formulation evaluates all pairs simultaneously:
Enable JavaScript to use this local playground. The explanation and sources below work without it.
Tensor shape progression across a single layer
For an input sequence of length T with model dimension d and H attention heads (head dimension ), shapes progress through the attention mechanism as follows:
| Tensor | Expression | Shape | Description |
|---|---|---|---|
| X | Input embeddings | [T, d] | Batch of T token vectors of width d |
| WQ, WK, WV | Projection weights | [d, d] | Learned linear projection matrices |
| Qh, Kh, Vh | [T, dk] | Per-head projected queries, keys, and values | |
| Sh | [T, T] | Pairwise scaled compatibility scores | |
| Ph | [T, T] | Row-normalized attention probability weights (∑ⱼ Pij = 1) | |
| Oh | [T, dk] | Weighted combination of values for head h | |
| Oconcat | [T, d] | Concatenated outputs across all H heads | |
| Y | [T, d] | Final linear output projection |
Variance derivation: why divide by √d_k?
Assume components of query q and key k are independent, zero-mean, unit-variance random variables: and . The dot product is .
For each term, independence gives:
Because the components are mutually independent, the variance of the sum is the sum of the variances:
As head dimension increases (e.g. ), unscaled dot products have standard deviation . Dividing by scales variance back to 1.0:
The Softmax Jacobian and gradient saturation
Why does unscaled variance matter? The derivative of the row-wise softmax with respect to input score is:
When scores have large variance, the largest score completely dominates the exponential sum, driving its probability while all other probabilities . At , . At , . The entire Jacobian matrix approaches zero, completely vanishing the gradient signal flowing back into Q and K. Scaling by prevents this saturation trap.
Causal masking
In autoregressive generation (GPT-style decoders), token i must not attend to future tokens . An additive attention mask M is applied to scores before softmax:
Causal Mask M (T = 4): Softmax Attention Weights P:
j=0 j=1 j=2 j=3 j=0 j=1 j=2 j=3
i=0 ┌ 0 -∞ -∞ -∞ ┐ i=0 ┌ 1.0 0 0 0 ┐
i=1 │ 0 0 -∞ -∞ │ ──▶ i=1 │ p10 p11 0 0 │
i=2 │ 0 0 0 -∞ │ i=2 │ p20 p21 p22 0 │
i=3 └ 0 0 0 0 ┘ i=3 └ p30 p31 p32 p33 ┘
Because , future entries receive identically zero attention probability weight, preventing information leakage from future tokens during parallel teacher-forced training.
Layer FLOPs: when does attention dominate the FFN?
Consider a standard Transformer layer with sequence length T, model dimension d, and feedforward intermediate dimension . Counting multiply-accumulate operations (2 FLOPs per MAC):
- Q, K, V projections:
- Attention score matrix ():
- Value aggregation ():
- Output projection ():
- Feedforward layer ():
Total layer FLOPs:
Attention FLOPs exceed linear projection FLOPs when:
For standard 7B/8B models where d = 4096, attention compute only dominates once sequence length tokens. At short contexts (), over 85% of total compute is spent in the feedforward projections.
The Pre-Norm Transformer block
Original Transformers placed LayerNorm after the residual addition (Post-LN: ), which suffered from gradient vanishing and required warmup learning rate schedules. Modern models adopt Pre-LN (or Pre-RMSNorm):
x ──┬─────────────────────────────(+)──▶
│ ▲
▼ │
RMSNorm ──▶ Attention ──▶ W_O ────┘
│
├──┬──────────────────────────(+)──▶ output
│ │ ▲
│ ▼ │
│ RMSNorm ──▶ FFN (SwiGLU) ────┘
▼
In Pre-LN, the identity highway is uninterrupted across the entire depth of the network. Gradients flow back from the loss directly to early token embeddings without attenuation.
Interactive Micro-Transformer Trainer
Train a 2-layer, 2-head Micro-Transformer on algorithmic sequence tasks (Sequence Reversal, Identity Copy, Sorting). Observe how attention weights self-organize along the anti-diagonal for sequence reversal, and inspect the impact of causal versus bidirectional masking.
Configuration & Controls
Multi-Head Attention Heatmaps (Head 1 & Head 2)
Training on Reverse causes attention to concentrate along the anti-diagonal (position 0 attends to position 3). Under a Causal Mask, position 0 cannot attend ahead, demonstrating why bidirectional context is required for non-autoregressive tasks.
Sources and further reading
- Vaswani et al. (2017), Attention Is All You Need
- Xiong et al. (2020), On Layer Normalization in the Transformer Architecture (Pre-LN analysis)
- Shazeer (2019), Fast Transformer Decoding: One Write-Head is All You Need (MQA)
- Ainslie et al. (2023), GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints