Lesson 03 · Attention

One Vector Absorbs Its Context

"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

The five lessons; lesson 03 highlighted Both pipelines; the attention row is marked

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 four stages of attention built in chapter 3

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.

1The chain of this lesson

Definition · context vector The context vector z(i) of unit i is a new vector for i that is a weighted combination of all units of its group: z(i) = Σj αij x(j), with weights αij that sum to 1 over j. It is "x(i) enriched with what surrounds it".

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.

LLM Book Figure 3.7: the context vector of the second token is a weighted combination of all six input vectors

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)
Point cloud

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?

Definition · attention score (dot product) The attention score ωij measures how much unit i should look at unit j. The simplest score is the dot product of the two raw vectors, ωij = x(i) · x(j): large when the vectors point the same way.

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.

LLM Book Figure 3.8: the attention scores between the query token journey and every input token are dot products
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 § simple
code
query = 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)
Point cloud
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

Definition · attention weights (softmax) The attention weights αi· = softmax(ωi·) turn the row of scores of unit i into positive numbers that sum to 1: αij = exp(ωij) / Σk exp(ωik). The context vector is then z(i) = Σj αij x(j).

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.

LLM Book Figure 3.9: the scores are normalised with softmax to attention weights Book Figure 3.10: the context vector is the weighted sum of the inputs Book Figure 3.11: the full 6 by 6 matrix of attention weights, one row per query
⚙ torch.softmax(attn_scores, dim=-1), then attn_weights @ inputs · § simple (the 6 × 6 matrix is in the output above)
Point cloud

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

Definition · query, key, value (trainable projections) Three trainable matrices turn each input into three roles: query q = x Wq (what I look for), key k = x Wk (what I advertise), value v = x Wv (what I pass on). Scores become ωij = q(i) · k(j) and the context vector sums values, z(i) = Σj αij v(j).

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.

LLM Book Figure 3.14: queries, keys and values are obtained by multiplying each input with the three weight matrices
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, § asym
code
x_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)
Point cloud Three real points of patch 150 projected to queries, keys and values with 4 by 2 matrices, the matrices shown
⚙ 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

Definition · scaled dot-product attention Divide the scores by √dk, the key dimension, before the softmax: α = softmax(q kT / √dk). This is the attention of the original Transformer, of GPT-2, and of PTv3.

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.

LLM Book Figure 3.15: the score between the query and each key is a dot product Book Figure 3.16: the scores are scaled and normalised with softmax to attention weights
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 § scale
Point cloud The 3 by 3 score matrix of the three points and its row-wise softmax after dividing by the square root of 2, with one score computed by hand
⚙ torch.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

Definition · the attention layer (SelfAttention_v1) Put together: q, k, v projections → scaled scores → softmax → context vectors, for every unit at once as three matrix multiplications. The book's Listing 3.1 is this layer; PTv3's attention is the same layer with a fused qkv projection and a batch axis that means "which patch".

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).

LLM Book Figure 3.17: the context vector is the sum of the values weighted by the attention weights Book Figure 3.18: the whole computation as matrices: inputs X, weight matrices, queries, keys, values, attention weights, context vectors
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 § class
code (SelfAttention_v1)
class 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_vec
Point cloud The context vector of the second point as the weighted sum of the three value vectors, one coordinate computed by hand
scalar (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/PTv2) versus scalar attention (PTv3) PTv1 computes a weight per channel: αij = softmax(γ(q(i) − k(j) + δij)) ∈ ℝd, with an MLP γ on the subtraction and δij = θ(pi − pj) a learned function of the geometric offset. More expressive, but every pair needs an MLP evaluation and the weight tensor has a channel axis.
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 § vector

At 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.

2Try it

LLM · 6 × 6 attention weights

Hover a row of the heatmap.

Point cloud · 64 × 64 weights inside the patch

Hover a row i of the matrix: the scatter (top view of the patch) colours every point j by w_ij, the hovered point is ringed.

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.

3What this lesson established

Why does row "journey" of SelfAttention_v1 match the hand computation?

Same seed, same three matrices, same formula; the class only vectorises the loop over tokens.

Why does permuting the patch not change the attention output?

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.

Could PTv3 use vector attention with a 1 024-point patch?

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.