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

Lets every token gather information from every other token in one step, with weights it computes from the tokens themselves.

Queries, keys and values

Each token xx is multiplied by three learned matrices, giving three new vectors: a query q=xWQq = x W_Q (what this token is looking for), a key k=xWKk = x W_K (what it offers to be found by) and a value v=xWVv = x W_V (what it passes on). The match between token ii and token jj is the dot product of ii’s query with jj’s key, divided by dk\sqrt{d_k}, where dkd_k 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, wj=esj/∑leslw_j = e^{s_j} / \sum_l e^{s_l}, 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.

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{Q K^\top}{\sqrt{d_k}}\right) V
(6-2)
QQ, KK, VV: the queries, keys and values of all NN tokens stacked as rows; dkd_k: the size of each query and key (d/hd/h per head when there are hh heads, below). Softmax acts on each row. The result has one row per token.
Figure 6-2. How much the selected region weighs every region, with toy weights; each row sums to 1. In a trained model, d is much larger and the weights are learned.
Example 6-2. Attention in six lines, then the built-in
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
  1. Random stand-ins for the three learned matrices WQW_Q, WKW_K, WVW_V, scaled by 1/d1/\sqrt{d}.
  2. Equation 6-2 with one head, so dk=dd_k = d. dim=-1 applies softmax along each row: for query ii, over all keys jj.
  3. [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 hh attention operations in parallel, each with its own smaller WQW_Q, WKW_K, WVW_V (size d×d/hd \times d/h), 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.

MultiHead⁡(X)=[head1,…,headh] WOheadr=Attention⁡(Qr,Kr,Vr)Qr,Kr,Vr=XWQ(r), XWK(r), XWV(r)\begin{aligned} \operatorname{MultiHead}(X) &= \big[\mathrm{head}_1, \dots, \mathrm{head}_h\big]\, W_O \\ \mathrm{head}_r &= \operatorname{Attention}(Q_r, K_r, V_r) \\ Q_r, K_r, V_r &= X W_Q^{(r)},\, X W_K^{(r)},\, X W_V^{(r)} \end{aligned}
(6-3)
XX holds the NN tokens as rows; the brackets concatenate the hh head outputs side by side, back to dd columns; WOW_O is the final d×dd \times d linear layer.

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

X←X+MultiHead⁡(LN⁡1(X))X←X+MLP⁡(LN⁡2(X))\begin{aligned} X &\leftarrow X + \operatorname{MultiHead}\big(\operatorname{LN}_1(X)\big) \\ X &\leftarrow X + \operatorname{MLP}\big(\operatorname{LN}_2(X)\big) \end{aligned}
(6-4)
One pre-norm block. LN⁡\operatorname{LN} is layer normalisation, with its own learned scale and shift in each step; the MLP and LN⁡\operatorname{LN} act on each token separately.
Example 6-3. One transformer block in PyTorch
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)
  1. nn.MultiheadAttention splits d=128d = 128 into 8 heads of 16 and includes the output layer WOW_O of Equation 6-3.
  2. 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.
  3. 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: N2N^2

The weight matrix has N×NN \times N 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 101210^{12}, 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.