AI Foundations for Developers COURSE·LESSON 16 OF 410 completed

Attention: A Worked Example

Select relevant information using learned comparisons

Attention lets a token combine information from other allowed positions. Learned transformations produce queries, keys, and values. A query is compared with keys to generate scores; normalized scores weight the values. These names describe roles in a calculation, not separate databases.

Scaled dot-product attention is softmax(QKᵀ / sqrt(d_k))V, where d_k is the key dimension. The scaling helps control score magnitudes. A mask can prohibit access to particular positions.

One query, two pieces of information

Let q=[1,0], k1=[1,0], k2=[0,1], v1=[10,0], and v2=[0,20]. The dot products are 1 and 0. After division by sqrt(2), scores are approximately 0.707 and 0. Softmax turns them into weights about 0.670 and 0.330. The weighted value is approximately [6.70,6.60].

python
import math

scores = [1 / math.sqrt(2), 0]
# Subtract the maximum for numerical stability.
weights = [math.exp(s - max(scores)) for s in scores]
weights = [w / sum(weights) for w in weights]
values = [[10, 0], [0, 20]]
output = [sum(w*v[j] for w, v in zip(weights, values))
          for j in range(2)]
print([round(w, 3) for w in weights])  # [0.67, 0.33]
print([round(x, 2) for x in output])  # [6.7, 6.6]

Run this in the Python compiler. Increasing the first score concentrates weight on the first value.

Causal attention and multiple heads

During ordinary next-token training, a causal mask prevents each position from using future tokens. Without it, the model could see the answer it is supposed to predict. Padding masks prevent artificial padding positions from being treated as meaningful input.

Multiple heads perform attention in different learned subspaces and combine their results. One head is not guaranteed to correspond to a human concept such as grammar. Attention weights are useful to inspect but do not by themselves provide a complete causal explanation of a model's answer.

Full attention over n tokens forms an n×n score relationship per head, giving quadratic sequence interactions. Optimized implementations can reduce memory traffic and avoid materializing some intermediates without changing the underlying attention operation.

Checkpoint with answers

Are attention outputs just copies of the highest-weight token? No. They are weighted combinations of value vectors.

Why mask future positions during causal training? To preserve the prediction problem instead of leaking its target.

Reference

Attention Is All You Need introduced the transformer architecture. The arithmetic above is an original miniature illustration.

Learn at your own pace0 / 41 lessons complete