Lesson 12 · The primitives toolbox
Graphs, and choosing a primitive
The problem
Seven road junctions surround the pizza shop. Each one has a traffic level, from 0 (clear) to 3 (jammed). You want to predict the delay at each junction, in minutes.
Traffic spills over. A quiet junction next to a jammed one gets slow too. So a junction's delay depends on its own traffic and on the traffic at the junctions it's joined to.
Data shaped like this is a graph. Each junction is a node. Each road between two junctions is an edge. Two junctions joined by a road are neighbours. Molecules (atoms joined by bonds), social networks (people joined by friendships) and computer networks are graphs too.
Tap a junction to see its neighbours.
Shop: own traffic 1. Neighbours: Market 3, Park 0.
Neighbours’ average: (3 + 0) / 2 = 1.5
Delay = 2 × 1 + 1.5 = 3.5 min
Numbers in circles are traffic levels, 0 (clear) to 3 (jammed). Darker means busier. Dashed rings mark the neighbours.
The delays in this data follow one rule: twice your own traffic, plus the average traffic of your neighbours. The network doesn't know that rule. It has to learn it.
Why not flatten the map into a table?
The building blocks so far each expect a fixed shape. An MLP wants a list of numbers. You could number the junctions 0 to 6 and feed it the list of 7 traffic levels. Three things go wrong.
- The roads are missing. The list says nothing about which junctions are joined. The MLP has to discover the map from data.
- The numbering is arbitrary. Nothing makes the shop junction 0 rather than junction 5. Renumber the junctions and the MLP sees a different input, so it gives different answers.
- The size is fixed. An MLP built for 7 junctions can't read a map with 8.
A convolution doesn't fit either. It slides over a grid, where every cell has the same neighbours in the same places (up, down, left, right). Here, Shop has 2 neighbours and Market has 3, and they don't sit in fixed directions.
Message passing
The fix copies how traffic spreads. Each junction keeps a vector of numbers that describes it; here it starts as one number, its traffic level. Then, in one round, every junction does three things:
- Gather. Collect the vectors of its neighbours. These are the messages.
- Combine. Average them, so the result doesn't depend on how many neighbours there are, or in what order they're listed.
- Update. Mix the average with its own vector, using learned weights, to get its new vector.
This round is called message passing. The same weights are used at every junction, so it uses weight sharing, like a convolution's filter. A network built from rounds of message passing is a graph neural network (GNN).
Worked example
One round at the shop and the market
Shop. Its own traffic is 1. Its neighbours are Market (3) and Park (0). Their average is .
The maths
Write for junction 's vector, and for its set of neighbours. One round is
Read it back:
- The fraction is the combine step: add up the neighbours' vectors and divide by how many there are ().
- and are the learned weights, one for the junction's own vector and one for its neighbours' average. They're the same at every junction.
- is an activation function, such as ReLU, as in any layer.
In the worked example, the vectors are single numbers, , , and there's no activation. Training finds those two numbers from the 7 delays; the PyTorch code below does it.
Information spreads one road per round
After one round, a junction knows about its neighbours. After two rounds, its neighbours have already heard from their neighbours, so it knows about junctions two roads away. Each round reaches one road further.
Predict first
A jam starts at Hill, in the bottom-right corner of the map. After 2 rounds of message passing, which junctions' values have changed?
Check it below. Here every junction keeps half its own value and takes half its neighbours' average, so the numbers stay small and easy to read.
After 0 rounds: 1 of 7 junctions have heard about the jam at Hill.
Only the jammed junction has a value. Press the step button.
Each round, every junction: new value = 0.5 × own value + 0.5 × neighbours’ average. The same rule at every junction. Tap a junction to move the jam.
Things to notice:
- After rounds, a junction has heard from exactly the junctions within roads. From any junction on this map, 3 rounds reach everything.
- The value fades as it spreads, because each step averages it with zeros. A trained GNN learns its own weights, so it decides how much of what it hears to keep.
- A GNN with layers has rounds. Like a receptive field in a CNN, how far each node can see grows with depth.
Renumbering changes nothing
Number the junctions differently and a GNN gives every junction the same answer as before. Each junction's output depends only on its own vector and its neighbours' vectors, and averaging ignores the order of the neighbours.
Compare a table model: one fixed weight for every pair of positions in the list, 49 in all. It is the delay rule written out for the original numbering, so it's exact there. Shuffle the numbering and see what happens.
| # | junction | traffic | GNN | table model |
|---|---|---|---|---|
| 0 | Shop | 1 | 3.5 ✓ | 3.5 ✓ |
| 1 | Market | 3 | 7 ✓ | 7 ✓ |
| 2 | Bridge | 2 | 6.33 ✓ | 6.33 ✓ |
| 3 | Park | 0 | 2.33 ✓ | 2.33 ✓ |
| 4 | Station | 3 | 6.67 ✓ | 6.67 ✓ |
| 5 | School | 1 | 3 ✓ | 3 ✓ |
| 6 | Hill | 0 | 2 ✓ | 2 ✓ |
Both models give every junction its right delay.
The table model has one weight for each pair of row numbers (49 in all), fitted to the original numbering. The GNN has two weights, own and neighbours, used at every junction.
With the first shuffle, the table model gets 6 of the 7 junctions wrong. It learned "position 3 depends on positions 0, 1 and 4", which is true of one numbering and false of the others.
In the language of inductive bias, a GNN assumes that only the connections matter, not the numbering. Its outputs per junction move with the junctions when you renumber them: that's equivariance, this time to renumbering instead of shifts. To answer one question about the whole graph, such as "how congested is the map?", average the junctions' outputs. That answer doesn't change at all when you renumber, so it is invariant.
Predict first
You want to predict a property of a molecule (say, whether it dissolves in water) from its atoms and the bonds between them. Which building block fits best?
DigressionGraph networks in the real worldMolecules, and arrival times in Google Maps. · 2 min
Molecules. In 2017, Gilmer and colleagues at Google showed that many earlier networks for molecules were versions of one idea. They called it the message passing neural network. Atoms send messages along bonds, and the network predicts properties of the whole molecule. Their paper is "Neural Message Passing for Quantum Chemistry".
Arrival times. Google Maps predicts how long a trip will take with a GNN over the road network. The roads are split into stretches, and stretches that join up are neighbours, much like this lesson's map.
The team described it in "ETA Prediction with Graph Neural Networks in Google Maps" (Derrow-Pinion and others, 2021). Compared with the system it replaced, they report that the GNN cut badly wrong arrival times by over 40% in some cities, such as Sydney.
Attention is message passing on a full graph
Attention, from the sequences lesson, fits this picture. In attention, every word gathers from every other word, and the weights come from dot products. That is message passing on a graph where every node is joined to every other node, with a different weight on each edge.
This explains something from that lesson: attention on its own ignores word order. A graph with every node joined to every other has no order to see. Transformers add each word's position to its vector to bring order back.
DigressionTransformers as the general-purpose blockWhy attention now handles images, sequences and graphs, and what it costs. · 3 min
Each block in this level builds in an assumption. Attention builds in almost nothing: every item may look at every other item. So it can be used on almost any data, once the data is cut into items.
In 2020, Dosovitskiy and colleagues at Google cut images into 16 × 16 patches. They treated each patch as a word and fed the patches to a transformer.
Their paper, "An Image is Worth 16x16 Words", reports a clear trade-off. Transformers "lack some of the inductive biases inherent to CNNs", such as equivariance and looking at small patches. So they "do not generalize well when trained on insufficient amounts of data". Pretrained on 14 million to 300 million images, they matched or beat the best CNNs of the time on several image benchmarks. In their words, "large scale training trumps inductive bias".
That is the lesson of this whole level, from the other side. A strong assumption saves data when it's true. With enough data, a weaker assumption can learn what the strong one would have built in. There are transformer versions for graphs too, which add information about the connections to each node's vector.
Attention also has a cost: every item scores every other item, so the work grows with the square of the number of items. The Transformers course covers how it's used and made cheaper.
Choosing a primitive
That completes the toolbox. Each building block makes one assumption about the data, and it helps only when the assumption is true. So the choice starts with one question: what does a single example of your data look like?
One example of your data is…
Tap a row for the assumption behind it and where it’s taught.
The same map as a table:
| Data | Block | It assumes |
|---|---|---|
| Table of columns | Boosted trees, or an MLP | Columns have no order or neighbours |
| Grid (image) | Convolution | Nearby values belong together; patterns can be anywhere |
| Sequence | Recurrence or attention | Order matters; one rule at every position |
| Graph or set | GNN, or attention | Connections matter; numbering doesn't |
| Many categories | Embedding | Similar categories can share similar vectors |
| No labels | Autoencoder | The data lies near a smaller surface |
Real models often combine several. A model of pizza orders might use an embedding for each topping and attention over the customer's note. An MLP on top then mixes them with the distance and the hour. A GNN on molecules uses an MLP inside each update. The blocks are parts, not rival models.
For tables, the first choice is usually not a network at all. The lesson Choosing an architecture covers that, and how much data each choice needs.
In PyTorch
Stack the junctions' vectors as the rows of a matrix h, shape (7, d). Neighbours are stored in an adjacency matrix: a 7 × 7 grid with a 1 where a road joins two junctions and 0 elsewhere. Dividing each row by its sum turns it into an averaging matrix, a_mean. Then a_mean @ h computes every junction's neighbour average at once, with one matrix product.
def road_map(dtype: torch.dtype = torch.float32) -> tuple[list[str], torch.Tensor, torch.Tensor]:
"""Junction names, traffic levels (7, 1) and the averaging matrix (7, 7) of the shared road map."""
data = load("road-map")
names = [j["name"] for j in data["junctions"]]
traffic = torch.tensor([[j["traffic"]] for j in data["junctions"]], dtype=dtype) # (7, 1)
n = len(names)
adj = torch.zeros(n, n, dtype=dtype) # adj[v, u] = 1 if a road joins v and u
for road in data["roads"]:
adj[road["from"], road["to"]] = adj[road["to"], road["from"]] = 1
a_mean = adj / adj.sum(dim=1, keepdim=True) # each row sums to 1: "average my neighbours"
return names, traffic, a_meanOne round is then two matrix products, the same for every junction:
def message_passing_round(h: torch.Tensor, a_mean: torch.Tensor, w_self: torch.Tensor, w_nb: torch.Tensor) -> torch.Tensor:
"""h: (nodes, d_in). w_self, w_nb: (d_in, d_out). Returns (nodes, d_out)."""
messages = a_mean @ h # (nodes, d_in): row v is the average of v's neighbours
return h @ w_self + messages @ w_nb # the same two weight matrices at every nodeYou'll often see a shorter version, h = torch.relu((A @ h) @ W). There, A includes each junction as its own neighbour, so one weight matrix does both jobs.
As a layer, the two weights become two nn.Linear layers inside an nn.Module. Stacking two layers with a ReLU between them gives a GNN that sees two roads away:
class GraphLayer(nn.Module):
"""One round of message passing with learned weights: self part + neighbour part."""
def __init__(self, d_in: int, d_out: int) -> None:
super().__init__()
self.self_lin = nn.Linear(d_in, d_out) # own value (with a bias)
self.nb_lin = nn.Linear(d_in, d_out, bias=False) # neighbours' average
def forward(self, h: torch.Tensor, a_mean: torch.Tensor) -> torch.Tensor:
return self.self_lin(h) + self.nb_lin(a_mean @ h) # (nodes, d_out)
class TinyGNN(nn.Module):
"""Two rounds with a ReLU between them, so each junction hears from junctions 2 roads away."""
def __init__(self, d_in: int = 1, d_hidden: int = 8, d_out: int = 1) -> None:
super().__init__()
self.layer1 = GraphLayer(d_in, d_hidden)
self.layer2 = GraphLayer(d_hidden, d_out)
def forward(self, h: torch.Tensor, a_mean: torch.Tensor) -> torch.Tensor:
h = torch.relu(self.layer1(h, a_mean)) # (nodes, d_hidden)
return self.layer2(h, a_mean) # (nodes, d_out)The whole graph is one example, so each training step uses all 7 junctions. Train one GraphLayer on the delays with Adam and F.mse_loss:
def learn_delay_rule(steps: int = 1000, seed: int = 0) -> GraphLayer:
"""Fit one GraphLayer to the delays. The data were made with weights 2 (own) and 1 (neighbours)."""
torch.manual_seed(seed)
_, traffic, a_mean = road_map()
delay = message_passing_round(traffic, a_mean, torch.tensor([[2.0]]), torch.tensor([[1.0]])) # (7, 1)
layer = GraphLayer(1, 1)
optimizer = torch.optim.Adam(layer.parameters(), lr=0.1)
for _ in range(steps): # one graph, so every step uses all 7 junctions
optimizer.zero_grad()
loss = nn.functional.mse_loss(layer(traffic, a_mean), delay)
loss.backward()
optimizer.step()
return layerRunning the file prints the 7 delays, then the learned weights. They are 2.00 on the junction's own traffic, 1.00 on its neighbours' average and a bias of 0.00. The layer found the rule the data was made with. It also checks that renumbering the junctions moves the GNN's outputs with them.
For real graphs, use a library. PyTorch Geometric (torch_geometric) is the most widely used. It stores the edges as a list instead of a full matrix, which matters when a graph has millions of nodes. It also has many ready-made layers.
Common misconceptions
"A GNN needs every graph to have the same size." It doesn't. The same two weight matrices run at every node, so a GNN reads a graph with 7 nodes or 7 million.
"One round of message passing lets every node see the whole graph." One round reaches only the neighbours. A node roads away needs rounds, so far-apart nodes need a deep GNN.
"Renumbering the nodes changes a GNN's answer." Each node's output moves with the node, and nothing else changes. An MLP on a flattened table is the model whose answers change.
"A GNN learns a separate weight for each edge." It learns one set of weights, shared by all nodes and all edges. Attention is the variant that computes a different weight for each edge, fresh for every input.
"There's one best building block." Each block is best when its assumption fits your data. Real models often combine several.
Recap
- A graph is nodes joined by edges. Molecules, road maps and social networks are graphs, and their numbering is arbitrary.
- Message passing: every node gathers its neighbours' vectors, averages them, and updates its own vector with weights shared by all nodes. A GNN stacks rounds of it.
- After rounds, a node has heard from every node within edges.
- When you renumber the nodes, each node's answer moves with the node. A GNN also works on graphs of any size.
- Attention is message passing on a graph where every item is joined to every other.
- Choose a building block by asking what one example of your data looks like: table, grid, sequence, graph, categories, or unlabelled inputs.
- PyTorch names used:
torch.zeros, the@operator,nn.Linear,nn.Module,torch.relu,torch.optim.Adam,F.mse_loss. - Where each block goes next: Convolutional networks, Language and sequences, Transformers and Autoencoders. For tables, the trees are in ML fundamentals.