"journey" after "Your" is not "journey" in general; a point on a wheel and a point on a door can have identical features. Attention is the operator that mixes each vector with the others of its group. This lesson follows the book's six-word walk-through and runs the identical steps on three points of the car.
map · flow · code: code/llm/c03_attention.py, code/pc/c03_patch_attention.py · book: chapter 3, sections 3.3 and 3.4
Where we are. Inside the block, the attention row. The question: how does one vector absorb its context? The book's own map of this chapter is Figure 3.2: simplified self-attention → self-attention with trainable weights → causal attention → multi-head attention. Lesson 3 covers the first two, lesson 4 the last two.

Book Figure 3.2. The chain of chapter 3. We walk stages 1 and 2 here, and every stage exists unchanged in PTv3; only the input changes.
Why we need it: after lesson 2 each vector knows only itself and its position. Meaning is relational: the word needs its sentence, the point needs its neighbourhood. The context vector is the simplest way to let a vector carry information about others: an average, with the weights deciding who matters.
Six tokens, 3-d embeddings, the book's running example:
tensor([[0.4300, 0.1500, 0.8900],
[0.5500, 0.8700, 0.6600],
[0.5700, 0.8500, 0.6400],
[0.2200, 0.5800, 0.3300],
[0.7700, 0.2500, 0.1000],
[0.0500, 0.8000, 0.5500]])
shape: (6, 3) = (tokens, embedding dim)
The group is a patch (lesson 1): 64 points of the car, each a 4-d feature [x y z intensity], centred on the patch. The "tokens" of this patch:
patch 150 of 390: 64 points, extent [0.07 0.23 0.19] m features x: (64, 4) = (points in patch, [x y z intensity]) -- the 'tokens' of this patch
idx = patches[150]; feats = [xyz − mean, intensity] · c03_patch_attention.py § patch↓ an average needs weights — where do the α come from?
Why we need it: we need one number per pair, computed from the vectors alone, before any training. The dot product is that number, and it is where the two sides first disagree: for words it is a usable first guess; for raw coordinates it is meaningless, because it depends on where the origin is.
scores for 'journey' (raw dot products): tensor([0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865])
weights (softmax) : tensor([0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581]) sum = 1.0
context vector z_journey = sum_j w_j x_j: tensor([0.4419, 0.6515, 0.5683])
all 6x6 weights, one row per query:
tensor([[0.2098, 0.2006, 0.1981, 0.1242, 0.1220, 0.1452],
[0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581],
[0.1390, 0.2369, 0.2326, 0.1242, 0.1108, 0.1565],
[0.1435, 0.2074, 0.2046, 0.1462, 0.1263, 0.1720],
[0.1526, 0.1958, 0.1975, 0.1367, 0.1879, 0.1295],
[0.1385, 0.2184, 0.2128, 0.1420, 0.0988, 0.1896]])
attn_scores_2[i] = torch.dot(x_i, query); all at once inputs @ inputs.T · c03_attention.py § simplequery = inputs[1] # journey
attn_scores_2 = torch.empty(inputs.shape[0])
for i, x_i in enumerate(inputs):
attn_scores_2[i] = torch.dot(x_i, query)
print("scores for 'journey' (raw dot products):", attn_scores_2)
attn_weights_2 = torch.softmax(attn_scores_2, dim=0)
print("weights (softmax) :", attn_weights_2, " sum =", float(attn_weights_2.sum()))
context_vec_2 = (attn_weights_2[:, None] * inputs).sum(0)
print("context vector z_journey = sum_j w_j x_j:", context_vec_2)
attn_scores = inputs @ inputs.T
simple_weights = torch.softmax(attn_scores, dim=-1)
print("all 6x6 weights, one row per query:\n", simple_weights)raw dot-product weights, shape (64, 64) row sums: [1.0, 1.0, 1.0] same patch 100 m further along x -> max |change| in a weight: 0.204 (weights are <= 1) -> dot products of raw coordinates depend on where the origin is. Position must enter differently (concept 2 / xCPE).
Scanning the same car 100 m further down the road changes the raw weights by up to 0.2 (weights are at most 1). Scores on raw coordinates are not a property of the shape. Position has to enter through lesson 2's xCPE, and scores have to be computed on projected features.
torch.softmax(feats @ feats.T, dim=-1) vs the same with feats[:, 0] += 100 · c03_patch_attention.py § raw↓ scores are unbounded numbers — weights must be positive and sum to one
Why we need it: an average with weights that sum to 1 stays on the scale of the inputs, so the output of attention can be added back to its input (lesson 5's residual). Softmax also keeps every weight strictly positive and differentiable, which plain normalisation by the sum does not guarantee for negative scores.
torch.softmax(attn_scores, dim=-1), then attn_weights @ inputs · § simple (the 6 × 6 matrix is in the output above)Identical operation; the matrix is 64 × 64 for the patch. Each row sums to 1 (the row sums are printed in the output above). The interactive heatmap in section 2 is this matrix.
w = torch.softmax(scores, dim=-1); w.sum(-1) → 1.0 per row · § raw↓ raw dot products have no parameters and are symmetric — the model must be able to learn what to look for
Why we need it: with raw dot products, "journey" attending to "Your" equals "Your" attending to "journey", and nothing can be learned. The projections break the symmetry (the output below shows 1.27 one way, 1.35 the other), give the model parameters, and let the dimension change (3 → 2 here, 768 → 64 per head in GPT-2). For points they also make the score a function of learned features rather than raw coordinates.
query_2 = tensor([0.4306, 1.4551]) keys.shape = (6, 2) values.shape = (6, 2) scores : tensor([1.2705, 1.8524, 1.8111, 1.0795, 0.5577, 1.5440]) weights : tensor([0.1500, 0.2264, 0.2199, 0.1311, 0.0906, 0.1820]) (scaled by sqrt(d_k) = 1.4142 ) context : tensor([0.3061, 0.8210])
without projection: journey->Your 0.9544 Your->journey 0.9544 (symmetric) with projection : journey->Your 1.2705 Your->journey 1.3545 (asymmetric)
W_query = nn.Parameter(torch.rand(3, 2)) (seed 123), query_2 = x_2 @ W_query · c03_attention.py § trainable, § asymx_2 = inputs[1]
d_in, d_out = inputs.shape[1], 2
torch.manual_seed(123)
W_query = torch.nn.Parameter(torch.rand(d_in, d_out), requires_grad=False)
W_key = torch.nn.Parameter(torch.rand(d_in, d_out), requires_grad=False)
W_value = torch.nn.Parameter(torch.rand(d_in, d_out), requires_grad=False)
query_2 = x_2 @ W_query
keys = inputs @ W_key
values = inputs @ W_value
print("query_2 =", query_2, " keys.shape =", tuple(keys.shape), " values.shape =", tuple(values.shape))
attn_scores_2 = query_2 @ keys.T
print("scores :", attn_scores_2)
d_k = keys.shape[-1]
attn_weights_2 = torch.softmax(attn_scores_2 / d_k**0.5, dim=-1)
print("weights :", attn_weights_2, " (scaled by sqrt(d_k) =", round(d_k**0.5, 4), ")")
context_vec_2 = attn_weights_2 @ values
print("context :", context_vec_2)q, k, v = feats @ W_q, feats @ W_k, feats @ W_v with torch.rand(4, 2), seed 7 · c03_patch_attention.py (tiny example at the end of the script)↓ with projections the scores can be large, and softmax of large numbers is a one-hot — scale them
Why we need it: dot products of d-dimensional vectors grow like √d. Without the division a 1 024-d model's softmax saturates to a near one-hot vector, whose gradient is almost zero, and training stalls. The output below shows the same six scores ×32: one token takes 79 % of the weight and four get 0.
softmax(scores) : tensor([0.1401, 0.2507, 0.2406, 0.1157, 0.0687, 0.1842]) softmax(scores * 32) : tensor([0.0000, 0.7893, 0.2107, 0.0000, 0.0000, 0.0000]) <- near one-hot, gradients vanish softmax(scores*32 / 32) : tensor([0.1401, 0.2507, 0.2406, 0.1157, 0.0687, 0.1842]) <- dividing by sqrt(d_k) keeps it soft
torch.softmax(attn_scores_2 / d_k**0.5, dim=-1) · c03_attention.py § scaletorch.softmax(q @ k.T / 2**0.5, dim=-1) · same tiny example↓ weights times values gives the result — and a class makes it one line
Why we need it: written as matrices the whole layer is a few matmuls, which is what makes it fast on a GPU and lets fused kernels (FlashAttention) avoid storing the 1 024 × 1 024 weight matrix at all. That property is the reason PTv3 chose this exact form over PTv1's richer vector attention (next card).
tensor([[0.2996, 0.8053],
[0.3061, 0.8210],
[0.3058, 0.8203],
[0.2948, 0.7939],
[0.2927, 0.7891],
[0.2990, 0.8040]], grad_fn=<MmBackward0>)
shape: (6, 2) row 1 matches context_vec_2 above
SelfAttention_v1(d_in=3, d_out=2)(inputs) (Listing 3.1) · c03_attention.py § classclass SelfAttention_v1(nn.Module):
def __init__(self, d_in, d_out):
super().__init__()
self.d_out = d_out
self.W_query = nn.Parameter(torch.rand(d_in, d_out))
self.W_key = nn.Parameter(torch.rand(d_in, d_out))
self.W_value = nn.Parameter(torch.rand(d_in, d_out))
def forward(self, x):
keys = x @ self.W_key
queries = x @ self.W_query
values = x @ self.W_value
attn_scores = queries @ keys.T # omega
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
context_vec = attn_weights @ values
return context_vecscalar (dot-product) attention: weights (64, 64) context (64, 8) one weight per (query, key) pair; the same weight scales all 8 channels of v_j
attention(points[perm]) == attention(points)[perm]: True -> attention never sees the order. Serialization only decides WHO shares a patch.
Permute the patch and the output rows permute: attention never sees the serialization order. Lesson 1 only decided who shares the patch.
attn = softmax(q @ k.T / d**0.5); ctx = attn @ v on the 64-point patch · c03_patch_attention.py § scalar, § equivariance↓ the point-cloud literature had a richer operator — why PTv3 went back to this one
vector attention (PTv1): weights (64, 64, 8) context (64, 8) at PTv3 scale, patch 1024 and 64 channels per head: scalar weights per head: 1,048,576 numbers | vector weights: 67,108,864 numbers (64x more), plus an MLP per pair scalar attention is one matmul (fused kernels, FlashAttention); vector attention is not
w = softmax(gamma(q[:, None] − k[None] + theta(p_i − p_j)), dim=1) → shape (64, 64, 8) · c03_patch_attention.py § vectorAt the paper's patch size the vector weights are 64× more numbers than the scalar ones and cannot be one fused matmul. PTv3's bet is that scale (a 1 024-point patch, more data) buys back more than the richer operator gave; the paper's ablations support it.
Rows are queries in serialized order; each row is contrast-stretched. With untrained weights the bright columns are keys that attract every query, not spatial neighbours: position only enters through xCPE and training.
Same seed, same three matrices, same formula; the class only vectorises the loop over tokens.
Every query compares itself with every key and sums over them; a sum has no index order. The rows come back permuted the same way.
The weights would be 1 024 × 1 024 × 64 per head and need an MLP per pair; neither fits a fused kernel. The paper trades that expressiveness for a 64× larger receptive field.