Lesson 4.2 — Attention Mechanisms
Previous lesson · 4.1 Recurrent Neural Networks · Course index · Next lesson · 4.3 Transformer Architecture
Attention Motivation · Content-dependent Aggregation
Suppose two sensors estimate the position of a carriage on a rail. Each record has a key describing its sensing conditions and a value giving its position estimate. A query encodes the conditions we want to match. Comparing it with both keys gives two scores. Softmax turns those scores into shares of one read.

The open circles are the two reported positions, and . The diamond is the output. Read each of the lower rows as a single change to the top row.
- Change the query. The two reports stay put. A stronger match to key A moves the diamond toward A.
- Edit B's reported position, with both keys and the query fixed. The diamond stays three quarters of the way from A to B. Moving B by one unit moves the read by three quarters of a unit.
With two records, the weighted sum has a geometric interpretation. Write for the scaled match scores. A score difference gives B three times A's weight.
For vector values the same equation places the output on a line segment in value space. With more records, each query row forms a convex combination of the available values. These weights describe how this head combines its projected values. Learning a reliable sensor confidence would require a suitable objective and data.
Change a query direction or a single value in a four-record read
Weighted Information Retrieval
| Key | Dot product |
|---|---|
| K0 | 1.638 |
| K1 | 1.147 |
| K2 | -1.179 |
| K3 | -0.983 |
Query, Key & Value · Learned Linear Projections
Separate trainable linear projections produce Q, K, and V from the input representations. The training objective determines which features those projections learn. The equations use row vectors and omit the biases.
Q and K must have the same last dimension. V may have a different last dimension and must have the same sequence length as K. PyTorch stores nn.Linear weights in (out_features, in_features) order, so Linear(X) computes X @ weight.T + bias. Separate projections can extract different features from the same input.
QKV Projection Inspector
| Input feature | Input | Weight | Product |
|---|---|---|---|
| 0 | 1 | 0.8 | 0.8 |
| 1 | 0.5 | -0.3 | -0.15 |
| 2 | -0.2 | 0.1 | -0.02 |
q_proj.weight.shape to confirm the weight layout, then check Q, K, and V before they are reshaped. Lesson 4.3 covers splitting the heads and projecting their outputs.Similarity Scores · Dot Product & Additive Attention
The dot product is a bilinear score that depends on vector directions and magnitudes. It operates on the original vectors without the normalization used in cosine similarity. The standard additive attention score uses learned projections and a nonlinear layer.
The additive scoring demo fixes W_a = U_a = I, uses an all-ones vector for w_a, and sets b_a = 0. This gives a simplified nonlinear score with fixed parameters. Each row contains one query's scores against all keys.
Similarity Matrix Player
| Coordinate | Query value | Key value | Contribution |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 1 | 0.2 | 0 | 0 |
Scaled Dot-product Attention · Scale, Softmax, Aggregate
If the coordinates of q and k are mutually independent with zero mean and unit variance, the dot product has variance d_k. Its standard deviation grows as √d_k, so softmax can concentrate on a single key and yield small derivatives. Dividing the scores by √d_k corrects this scale under the stated assumptions. Learned queries and keys can depart from these assumptions.
Compute softmax along the key axis (dim=-1). Subtracting each row's maximum prevents overflow in the exponentials. For a fixed row of finite scores, increasing the positive divisor brings the probabilities closer to uniform. Entropy measures how concentrated the weights are.
Scaled Dot-product Attention
| Key | Raw scores |
|---|---|
| K0 | 6.962 |
| K1 | 0.787 |
| K2 | 4.219 |
| K3 | -5.468 |
Attention Masks · Causal & Padding
A mask determines which keys each query can read. With aligned positions in the same sequence, a causal mask blocks future keys (j > i). A padding mask blocks padded keys. When both apply, a position must satisfy both masks. Apply the mask to the scores before softmax so the allowed weights are normalized over the remaining keys.
Ordinary softmax is undefined when a query row contains only −∞. The demo explicitly sets such a row's weights and output to zero. Check the attention API's behavior when a real model can produce fully masked rows. A key padding mask covers invalid keys. Handle padded queries at the output or loss stage.
Causal & Padding Mask Explorer
F.scaled_dot_product_attention, True allows a position. In nn.MultiheadAttention, True blocks a position in both attn_mask and key_padding_mask. Convert the mask convention when switching APIs. A floating-point additive mask uses 0 for allowed positions and −∞ for blocked positions.Self-attention & Cross-attention · Input Sources
Self-attention
Q, K, and V come from the same input X, typically through separate projections. The output has the same sequence length as X.
Cross-attention
Q comes from the query sequence X_q. K and V come from a second sequence X_kv. The sequences can have different lengths. The output has one row per query.
Control queries in a robot can retrieve information from visual patch tokens, producing one context vector per query. Self-attention without position encodings or masks is permutation equivariant. Reordering the input tokens reorders the output rows in the same way. Lesson 4.3 explores how position information affects the computation.
Self-attention vs. Cross-attention
Attention Backpropagation · VJP & Computational Cost
Let G = ∂L/∂O. Use the matrix gradients from Lesson 1.6 and the softmax Jacobian from Lesson 2.1. Differentiate O = AV first, then propagate the gradient through A and S to Q and K.
The projection gradients above are written for one example. Sum their contributions over the batch for shared parameters. In self-attention, sum the three projection paths into the shared input. In cross-attention, the source input receives both the K and V paths. With a fixed mask, blocked positions have zero attention weights and zero score gradients. Fully masked rows use the zero-output convention described above.
Attention Backpropagation
Time & Memory Complexity
These are multiply–accumulate counts for one head, excluding projections and softmax. Counting multiplication and addition separately gives roughly two FLOPs per MAC. At fixed width, dense self-attention computation grows quadratically with sequence length. A fused kernel can save memory by avoiding a materialized score matrix while still performing quadratic attention computation.
Engineering Experiment · Content-addressable Sensor Retrieval
Each synthetic sample provides four scalar sensor values and their associated keys in random order. Each key is a one-hot type indicator with uniform noise. The query is a noisy one-hot indicator of the requested type. The model learns to predict the value associated with the requested key using scalar regression MSE. The correct key index is reserved for evaluation.
WQ and WK are each 4 × 4 and use no bias, giving 32 trainable parameters. The model reads the values directly. The experiment uses full-batch Adam, 64 training examples and 32 independently generated validation examples from a deterministic linear congruential generator. The baseline assigns weight 1/4 to every key. The correct key index is used to report top-1 retrieval and the mean weight on the correct key. The four slots model synthetic retrieval of a sensor reading by type.
Live Content-addressable Retrieval
| Key | Value | Weight × value |
|---|---|---|
| K0 | -0.373 | -0.078 |
| K1 | 0.441 | 0.138 |
| K2 | -0.912 | -0.203 |
| K3 · target | -0.206 | -0.053 |
View projection matrices and this sample's Q and K
Default experiment (actual PyTorch run)
| Initial validation MSE | Final validation MSE | Retrieval top-1 |
|---|---|---|
| 0.269405 | 0.000251 | 100% |
The uniform-weight baseline has MSE 0.271899. After training, the mean weight on the correct key is 0.979898. These results describe one small synthetic retrieval run at the default seed and use the validation split. Generalization to real control tasks would require separate evaluation, and causal interpretation of the weights would require additional evidence.
PyTorch Implementation · Reproducible Training
Save the script below as attention0402.py and run it with PyTorch installed. The comparison against native SDPA uses its default dropout_p=0, with True marking allowed positions in the boolean keep mask. The script uses float64 for the numerical check.
import math
import torch
from torch import nn
import torch.nn.functional as F
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
D=4
def rng(seed):
s=seed & 0xffffffff
def draw():
nonlocal s
s=(1664525*s+1013904223)&0xffffffff
return s/2**32
return draw
def data(seed,n,noise):
r=rng(seed); q=[]; k=[]; v=[]; y=[]; ids=[]
for _ in range(n):
order=list(range(D))
for i in range(D-1,0,-1):
j=int(r()*(i+1)); order[i],order[j]=order[j],order[i]
target=int(r()*D)
q.append([float(j==target)+noise*(2*r()-1) for j in range(D)])
k.append([[float(j==a)+noise*(2*r()-1) for j in range(D)] for a in order])
values=[2*r()-1 for _ in range(D)]; v.append(values)
idx=order.index(target); ids.append(idx); y.append(values[idx])
return tuple(torch.tensor(a) for a in (q,k,v,y,ids))
class Retriever(nn.Module):
def __init__(self,seed):
super().__init__(); r=rng(seed)
self.Wq=nn.Parameter(torch.tensor([.5*(2*r()-1) for _ in range(16)]).reshape(4,4))
self.Wk=nn.Parameter(torch.tensor([.5*(2*r()-1) for _ in range(16)]).reshape(4,4))
def forward(self,q,k,v):
Q=q@self.Wq; K=k@self.Wk
a=(torch.einsum('bd,bjd->bj',Q,K)/math.sqrt(D)).softmax(-1)
return (a*v).sum(-1),a
def run(seed=7,noise=.15,lr=.03,updates=120):
train=data(seed+100,64,noise); valid=data(seed+200,32,noise)
model=Retriever(seed); opt=torch.optim.Adam(model.parameters(),lr=lr)
hist=[]
for t in range(updates+1):
with torch.no_grad():
stats=[]
for q,k,v,y,idx in (train,valid):
pred,a=model(q,k,v)
stats.append(((pred-y).square().mean().item(),(a.argmax(-1)==idx).double().mean().item(),a.gather(1,idx[:,None]).mean().item()))
hist.append(dict(train=stats[0][0],val=stats[1][0],acc=stats[1][1],mass=stats[1][2],p=[p.detach().flatten().tolist() for p in model.parameters()]))
if t==updates: break
q,k,v,y,_=train; pred,_=model(q,k,v)
loss=F.mse_loss(pred,y); opt.zero_grad(); loss.backward(); opt.step()
baseline=(valid[2].mean(-1)-valid[3]).square().mean().item()
print('uniform baseline',baseline,'initial',hist[0]['val'],'final',hist[-1]['val'],'accuracy',hist[-1]['acc'],'mass',hist[-1]['mass'])
return hist
if __name__=='__main__':
run()
q=torch.randn(2,3,4,requires_grad=True)
k=torch.randn(2,5,4,requires_grad=True)
v=torch.randn(2,5,2,requires_grad=True)
# Boolean mask in SDPA: True means allowed (unlike nn.MultiheadAttention).
keep=torch.ones(3,5,dtype=torch.bool); keep[:,-1]=False
scores=q@k.transpose(-1,-2)/math.sqrt(4)
a=scores.masked_fill(~keep,-torch.inf).softmax(-1)
out=a@v
torch.testing.assert_close(out,F.scaled_dot_product_attention(q,k,v,attn_mask=keep))
out.square().mean().backward()
print('SDPA forward verified, gradients:',q.grad.norm().item(),k.grad.norm().item(),v.grad.norm().item())
NumPy forward & backward reference
This standalone function implements the unmasked case with 2D matrices for a single example. Supply the upstream gradient of the output as G. Lab 07 shows how to handle gradients at masked positions.
import numpy as np
def attention(Q, K, V, G):
scale = Q.shape[-1] ** -0.5
S = (Q @ K.T) * scale
E = np.exp(S - S.max(axis=-1, keepdims=True))
A = E / E.sum(axis=-1, keepdims=True)
O = A @ V
dV = A.T @ G
dA = G @ V.T
dS = A * (dA - (A*dA).sum(axis=-1, keepdims=True))
dQ = (dS @ K) * scale
dK = (dS.T @ Q) * scale
return O, A, dQ, dK, dV
Authoritative References & Next Lesson
Attention Is All You Need
Vaswani et al. (2017), Sections 3.2.1–3.2.3, on scaled dot-product attention, multi-head attention, and their applications.
Original paperPyTorch official docs
Scaled dot-product attention · MultiheadAttention
Check mask conventions, batch dimensions, and dropout.
Chapter 12 of Understanding Deep Learning is the main reference. Lesson 4.3 combines multi-head attention, positional encoding, RoPE, feed-forward networks, residual connections, and normalization in a complete Transformer block.
Previous lesson · 4.1 Recurrent Neural Networks · Course index · Next lesson · 4.3 Transformer Architecture