Week 09 · Attention and transformers
Implement scaled attention and verify that future tokens stay invisible.
← Week 8 · Subject contents · Week 10 →
Implement scaled attention and verify that future tokens stay invisible.
Work through the problem
For query Q, key K, and value V, attention computes softmax(QKᵀ/√dₖ)V row by row. The scale helps keep dot products from growing in magnitude as key dimension increases. Mask positions j>i with negative infinity before softmax so they receive zero mass.
In a two-token example with the first query and key both 1, the first attention row sees only its first key. Its output equals the first value regardless of the future value. The second row may attend to both. A transformer combines attention with a feedforward network and residual paths.
Attention gives future tokens zero weight.
Run the Python lab
import torch
Q = K = torch.tensor([[1.,0.],[0.,1.],[1.,1.]])
V = torch.tensor([[2.],[4.],[8.]])
def attend(v):
logits = [email protected]/(K.shape[-1]**.5)
blocked = torch.ones_like(logits,dtype=torch.bool).triu(1)
weight = logits.masked_fill(blocked,-torch.inf).softmax(-1)
return weight,weight@v
weights, result = attend(V)
changed = V.clone()
changed[-1] = 800
print(weights.round(decimals=3))
print("Outputs:",result.flatten().round(decimals=3).tolist())
assert torch.allclose(result[:-1],attend(changed)[1][:-1])
Output from the lab
tensor([[1.0000, 0.0000, 0.0000],
[0.3300, 0.6700, 0.0000],
[0.2480, 0.2480, 0.5030]])
Outputs: [2.0, 3.3399999141693115, 5.517000198364258]
Practice
- What happens if every entry in a row is masked?
Check your reasoning
- Softmax has no finite entry to normalize. Define a policy for empty contexts before taking softmax.
← Week 8 · Subject contents · Week 10 →
Further reading · Goodfellow, Bengio, and Courville · Deep Learning