Sequence modeling · 2017 · Ashish Vaswani et al.
Attention Is All You Need
Replace recurrence at the core of sequence transduction with parallel content-based interaction, while adding explicit position information.
How to read the original
- Read Model Architecture and distinguish encoder, decoder, and cross-attention.
- Read Scaled Dot-Product Attention and reconstruct one weighted sum.
- Read Positional Encoding and Why Self-Attention before making claims about order or parallelism.
Content interaction replaces a sequential recurrence
The Transformer paper proposes an encoder-decoder architecture built around attention and position-wise transformations rather than sequence-aligned recurrence. Queries compare with keys to determine how values are mixed. Position information and decoder masking provide different constraints: one represents order, while the other prevents access to forbidden future tokens. The original architecture is a translation model with both encoder and decoder; it should not be silently replaced by the later decoder-only pattern in a historical explanation.
Original reconstruction: one query and two values
Take a query q=(√2,0), keys k1=(ln 3,0) and k2=(0,0), and scalar values v1=4 and v2=12. The key dimension is d_k=2. Scaled dot products are q·k1/√2=ln 3 and q·k2/√2=0. Applying softmax gives weights exp(ln 3)/(3+1)=3/4 and exp(0)/(3+1)=1/4.
The attention result is (3/4)×4+(1/4)×12=6. A high compatibility score selects how strongly a value contributes; the key itself is not the returned value. If the query becomes zero, both scores become zero, both weights become one half, and the output becomes eight.
Now assume the second value belongs to a future position forbidden by a causal mask. Excluding that score before normalization gives weights one and zero, so the output is four. Multiplying a future token’s value by zero after computing an unmasked softmax is not generally equivalent: its score would still have changed the normalization denominator and reduced the allowed value’s weight.
For numerical stability, softmax can subtract the largest allowed score before exponentiation. This leaves ratios unchanged because the same factor cancels from numerator and denominator. A row with no allowed positions requires an explicit implementation policy; applying ordinary normalization to an empty or fully excluded set is not a meaningful probability distribution.
Position and permutation are separate issues
For a fixed query, swapping complete key/value pairs leaves the weighted result unchanged when no position-dependent information or mask changes. That is useful for set-like retrieval but insufficient to distinguish every word order. Position encodings alter the representations so the model can make use of sequence position. A causal mask alone supplies a different structural restriction and is not interchangeable with the paper’s positional encoding.
Multiple heads apply distinct learned projections before attention and combine their outputs afterward. This supplies multiple learned interaction spaces, but a head need not correspond neatly to one human grammatical category. Large attention weights are part of the computation; they are not automatically a faithful explanation of why the final prediction changed.
Interpret the computational advantage precisely
During training with known target sequences and a correct mask, many position calculations can proceed in parallel. Autoregressive generation still ordinarily chooses a token before using that chosen token to predict the next. Removing recurrence from the layer does not make an unknown generated sequence available all at once.
For ordinary full attention over T positions, the pairwise score array contains T² entries per head. Doubling T quadruples this count, even though projection and other layer costs have different scaling. Actual implementations may avoid materializing the complete matrix or use other attention patterns, but those are additional techniques rather than a reason to erase the underlying interaction model.
A strong exercise verifies dimensions, masks, normalization, and permutation behavior on tiny arrays before scaling. It then measures quality and resource use under the task, because an elegant attention calculation alone does not establish useful language behavior.
Reconstruction exercise
Use scores ln 2 and 0 with values 3 and 9. Calculate the unmasked attention output. Then mask the second position and compare correct pre-normalization masking with incorrectly zeroing its value after the unmasked softmax. Finally, state how a full score matrix changes when sequence length rises from 128 to 256.
Worked solution
Softmax assigns weights 2/3 and 1/3. The unmasked output is (2/3)×3+(1/3)×9=5. Correctly excluding the second score before normalization leaves one allowed position with weight one, so the output is three. Zeroing the second value after unmasked normalization instead yields (2/3)×3+(1/3)×0=2. The forbidden score still diluted the allowed contribution, so this is not the same masking operation. A full score matrix grows from 128²=16,384 entries to 256²=65,536 entries per head, four times as many. This count does not by itself predict total runtime or memory because kernels, batching, other layer operations, and whether scores are materialized also matter. It does identify the quadratic pairwise component that an implementation must manage.
Test the limits and transfer the idea
1. Proof and counterexample · allow 45 minutes
Prove what positional information changes
For a single self-attention head define Q = XW_Q, K = XW_K, V = XW_V and A(X) = softmax_row(QKᵀ/√d)V. There are no position embeddings or masks. Prove A(PX) = PA(X) for a permutation matrix P.
Check the claim using score matrix [[ln 3, 0], [0, ln 3]] and values (2, 10). Then give a counterexample when a fixed causal mask is applied: take both unmasked score rows to be (0,0), and compare the original and reversed value sequences. Explain why the counterexample concerns a fixed sequence-order mask, not an algebraic failure of softmax.
Get a starting hint
A row permutation changes which query is processed; a column permutation changes the order of keys. Softmax commutes with each permutation when its entire row is permuted.
Compare your reasoning with the worked solution
Permuting input rows gives Q′ = PQ, K′ = PK, and V′ = PV. Hence the new score matrix is P(QKᵀ/√d)Pᵀ. Row softmax obeys softmax_row(PSPᵀ) = P softmax_row(S) Pᵀ: each row is moved intact, while rearranging entries preserves its exponential sum. Multiplication by PV then cancels PᵀP and gives A(PX) = PA(X).
For the supplied scores the attention matrix is [[3/4,1/4],[1/4,3/4]], producing (4,8). Swapping both token rows yields output (8,4), precisely the swapped original output. This property is equivariance, not invariance: the outputs move with the inputs.
Now retain only keys at or before each query. Equal scores give original outputs (2,6): the first query sees only value 2 and the second averages both. Reversing the input under the same position-based mask gives (10,6). Swapping the original outputs would give (6,2), which differs. The fixed triangular mask is not conjugated along with the tokens; it assigns distinct roles to earlier and later positions.
This isolates one reason the Transformer needs an account of order. It does not prove that positional encodings are the only possible mechanism for order, nor that the paper's full encoder-decoder is permutation equivariant. Residual structure, positional signals, cross-attention inputs, and decoder masks must each be included before making a statement about the complete architecture.
Check your reasoning
- Uses both row and column permutations in the proof.
- Computes (4,8), (8,4), and the causal counterexample (2,6) versus (10,6).
- Distinguishes equivariance from invariance and states the model assumptions.
2. Derivation and numerical check · allow 40 minutes
Differentiate an attention decision
Let logits be s = (ln 2, 0, 0), scalar values v = (1,5,9), weights α = softmax(s), and output o = Σ αᵢvᵢ. Derive ∂o/∂sⱼ and evaluate every component. Explain why the gradient components sum to zero.
Mask the third key by excluding it from the normalization. Recompute the output and gradient, treating the masked logit as unable to affect the result. Check the unmasked derivatives with centered finite differences using Python's math library and step 10^-6. Identify what must change if values also depend on the differentiated variable.
Get a starting hint
Use ∂αᵢ/∂sⱼ = αᵢ(δᵢⱼ - αⱼ). Keep values constant when deriving the logit gradient.
Compare your reasoning with the worked solution
The initial weights are (1/2,1/4,1/4), so o = 1/2 + 5/4 + 9/4 = 4. Summing the softmax derivatives gives ∂o/∂sⱼ = αⱼ(vⱼ - o). The gradient is therefore (-3/2, 1/4, 5/4). Its components sum to zero because adding the same constant to every logit leaves softmax unchanged; a directional derivative along (1,1,1) must vanish.
After excluding the third key, the weights are (2/3,1/3,0), the output is 7/3, and the gradient is (-8/9,8/9,0). Masking means renormalizing the remaining keys, not computing the old output and deleting one contribution.
import math
s = [math.log(2), 0.0, 0.0]
v = [1.0, 5.0, 9.0]
def output(logits):
weights = [math.exp(x - max(logits)) for x in logits]
return sum(a*b for a,b in zip(weights,v)) / sum(weights)
eps = 1e-6
for j in range(3):
hi, lo = s.copy(), s.copy()
hi[j] += eps
lo[j] -= eps
print((output(hi) - output(lo)) / (2*eps))
The printed values approximate -1.5, 0.25, and 1.25. This checks a local attention calculation, not a Transformer training result. If a parameter changes both logits and values, the chain rule also includes Σ αᵢ ∂vᵢ/∂parameter; omitting that path gives an incomplete gradient.
Check your reasoning
- Derives αⱼ(vⱼ-o) instead of treating attention weights as constants.
- Recomputes normalization and obtains the masked gradient.
- Runs the numerical check and identifies the additional value path.
Check your understanding
With scores ln 3 and 0 and values 4 and 12, what is the output?
- 6
- 8
- 16
- 4
Explanation
The normalized weights are 3/4 and 1/4, giving 3+3=6.
Why must a forbidden position be excluded before softmax normalization?
- So every remaining position receives equal probability.
- So the value-vector magnitude can determine the denominator.
- Its score would otherwise change the weights of allowed values.
- Because masking after softmax automatically renormalizes the allowed weights.
Explanation
Zeroing a value afterward does not remove its contribution to the denominator.
Original paper and sources
Ashish Vaswani and coauthors. Attention Is All You Need. Advances in Neural Information Processing Systems, 2017.
Read the original paper →Read the primary paper: NeurIPS
- Attention Is All You Need: NeurIPS