Self-attention and the transformer
Each token is updated by a weighted sum over all tokens, with weights computed from the tokens.
Outcome: Compute queries, keys and values, and read an attention-weight matrix; assemble a transformer block: attention, MLP, residuals and layer norm; explain the O(N²) cost and how attention differs from message passing.
Builds on Tokens, Graph networks and MeshGraphNets
A token on its own knows only its own point. To predict the pressure at the trailing edge, the model has to use what happens at the leading edge, the tip and the root.
DefinitionSelf-attention
Queries, keys and values
Each token is multiplied by three learned matrices, giving three new vectors: a query (what this token is looking for), a key (what it offers to be found by) and a value (what it passes on). The match between token and token is the dot product of ’s query with ’s key, divided by , where is the size of each query and key, to keep the numbers in a sensible range. This is the scaled dot-product attention of Vaswani et al. (2017), whose transformer the rest of this lesson builds.
The scores are turned into weights with softmax: exponentiate each score and divide by the sum, , so the weights are positive and add up to 1. Scores [2, 1, 0] become weights [0.67, 0.24, 0.09]. Each token's output is the weighted sum of all values.
import torch
import torch.nn.functional as F
N, d = 1000, 64
x = torch.randn(N, d) # N tokens
Wq, Wk, Wv = (torch.randn(d, d) / d**0.5 for _ in range(3))1
q, k, v = x @ Wq, x @ Wk, x @ Wv # three linear maps
w = torch.softmax(q @ k.T / d**0.5, dim=-1) # (N, N)2
out = w @ v # (N, d)
# The built-in gives the same result, without returning w.
same = F.scaled_dot_product_attention(q[None], k[None],3
v[None])[0]
print(torch.allclose(out, same, atol=1e-5)) # True
- Random stand-ins for the three learned matrices , , , scaled by .
[None]adds a batch axis. The built-in divides by the square root of the last dimension by default.
Example 6-2 prints True: the six lines and the built-in agree to within 1e-5.
Several heads
One attention head gives each token one set of weights, which has to average different relations together. Multi-head attention runs attention operations in parallel, each with its own smaller , , (size ), and concatenates their outputs, then mixes them with one more linear layer. Each head learns its own weighting; nothing ties a head to a physical relation. The cost is about the same as one head of full size.
The transformer block
A transformer is a stack of identical blocks. Each block does two things: multi-head self-attention, where tokens exchange information, then an MLP applied to every token separately, where each token processes what it gathered.
Each step is wrapped in a residual connection (add the result to the input, as in graph networks) and preceded by layer normalisation (Ba, Kiros and Hinton, 2016), which rescales each token's numbers to zero mean and unit variance, then applies a learned scale and shift. This helps deep stacks train. Normalising before each step (pre-norm) is the usual choice in recent models; the original transformer normalised after each residual, which can train less stably in deep stacks (Xiong et al. 2020).
import torch
from torch import nn
class Block(nn.Module):
def __init__(self, d=128, heads=8):
super().__init__()
self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = nn.MultiheadAttention(1
d, heads, batch_first=True)
self.mlp = nn.Sequential(nn.Linear(d, 4 * d),
nn.SiLU(), nn.Linear(4 * d, d))
def forward(self, x): # x: (B, N, d)
h = self.n1(x)
# Tokens exchange information...
a = self.attn(h, h, h, need_weights=False)[0]2
x = x + a
# ...then each token is updated on its own.
return x + self.mlp(self.n2(x))3
print(Block()(torch.randn(2, 1000, 128)).shape) # (2, 1000, 128)
- The same normalised tokens serve as queries, keys and values: that is what makes it self-attention. The call returns the output and the weights;
[0]keeps the output. - The second line of Equation 6-4: normalise, apply the MLP to each token, add.
Example 6-3 prints torch.Size([2, 1000, 128]): a block returns tokens of the shape it was given, so blocks can be stacked.
The cost:
The weight matrix has entries. For the aircraft's 8,000 points that is 64 million per head, manageable. For a car surface with 1,000,000 points it is , about 2 TB in 16-bit numbers for one head of one layer. The rest of this unit covers ways around it.
Attention against a graph network
A graph network reaches one hop per layer along fixed mesh edges, at a cost linear in the number of edges. Attention reaches every token in one layer and learns which ones matter, but it has no built-in notion of neighbours. Position enters only through the tokens: through their features or, with RoPE (rotary position embeddings), by rotating each query and key by angles that depend on position, so that the score between two tokens depends on their relative position.