Graph Neural Networks
Message passing on graphs, from molecules to social networks.
A molecule, a social network and a road map share one awkward property: their parts come in no natural order. There is no first atom and no top-left friend, so neither a convolution nor an MLP on a flattened table fits them. This lesson builds the networks that do fit: message passing, the graph convolution derived from spectral filters, sampled and attention-weighted neighborhoods, and readouts that turn a whole graph into one vector.
What you’ll learn
- Describe graph data by an adjacency matrix and node features, name the node-, edge- and graph-level tasks, and show why GNN layers must be permutation-equivariant and readouts permutation-invariant.
- Write the message-passing framework (message, aggregation, update), implement a layer with one message per edge, and count its cost.
- Derive the GCN propagation rule from first-order spectral filters, including the renormalization trick, and compare it with GraphSAGE's sampled aggregators and GAT's attention.
- Build graph-level predictions with sum, mean or max readouts and hierarchical pooling, and connect them to Deep Sets.
- Explain how depth sets a node's receptive field, why most GNNs stay shallow, and where GNNs have been applied with documented results.
Graphs, tasks and the symmetry to respect
A graph has nodes joined by edges. Store the edges in the adjacency matrix , with when and are joined, and the node features in the rows of ; edges can carry features as well, such as bond types in a molecule. Node has neighbors and degree , collected in the diagonal matrix .
Three kinds of task recur:
- Node level: classify each paper in a citation network by topic, or each account as a bot. Often transductive: one large graph, a few labeled nodes, predictions for the rest.
- Edge level: predict missing or future links, such as which item a user will save next.
- Graph level: predict a property of a whole graph, such as a molecule's toxicity or energy, from a dataset of many small graphs. Usually inductive: the test graphs were never seen in training.
These requirements rule out the obvious designs. An MLP on the flattened matrix can give a different output for each of the up to numberings of one graph, and it only accepts graphs of one size. Sorting the nodes into a canonical order first does not rescue it: no polynomial-time algorithm is known that computes a canonical order for every graph, and a small edit can reshuffle the order completely. A graph neural network (GNN) instead builds the symmetry into every layer, much as a convolution builds in translations: an inductive bias that removes what need not be learned (Bronstein, Bruna, Cohen & Veličković, 2021).
Which of these maps a graph's node features (rows in node-index order) to a vector that does not depend on how the nodes are numbered?
- The first row of
- All rows of concatenated in index order
- The sum of the rows of
- An MLP applied to the flattened adjacency matrix
Show the answer
C. The sum of the rows of
Addition is commutative: for every permutation matrix , because . A mean or an elementwise maximum over the rows works for the same reason; these are the readouts of a later step.
Message passing
Almost every GNN fits one template, which Gilmer, Schoenholz, Riley, Vinyals & Dahl (2017) named message passing. At layer each node holds a vector , starting from . Every edge computes a message, every node combines its incoming messages with a permutation-invariant aggregation such as a sum, and an update function produces the next vector. After layers, a readout pools the nodes for graph-level tasks:
Take the simplest instance: sum aggregation and linear messages, with applied elementwise. With the node vectors as the rows of , the neighbor sums are the rows of :
Relabel the nodes. Because , the neighbor sums are relabeled along with the nodes:
An elementwise commutes with reordering rows, so the layer is equivariant, and so is any stack of such layers. Ending with a sum, mean or max over all nodes makes the whole network invariant. The same argument works for any message, update and aggregation that treat all nodes alike.
Each layer moves information one edge further. After layers, depends only on the nodes within hops of , its receptive field in the language of convolutions. A layer costs one message per edge and one update per node, for width and linear maps, so sparse graphs with millions of nodes are cheap to process.
Graph convolutions: GCN, GraphSAGE and GAT
Which messages, and which weights? Three designs from 2017–2018 remain the standard baselines. The first comes from signal processing on graphs.
Treat a node signal like a sound. The normalized Laplacian has eigenvalues in , and its eigenvectors play the role of Fourier modes: smooth across edges for small eigenvalues, oscillating for large ones. A spectral filter rescales each mode (Bruna, Zaremba, Szlam & LeCun, 2014), but it needs the eigendecomposition and dense products with , per signal:
Make the filter a polynomial of degree in , expanded in Chebyshev polynomials for numerical stability (Defferrard, Bresson & Vandergheynst, 2016). Since whenever and are more than hops apart, the filter is -localized, and it costs sparse products, :
Keep only , approximate (so ), and tie the two coefficients, , to leave one parameter per filter:
This operator has eigenvalues in , so applying it layer after layer can blow signals and gradients up or shrink them. The renormalization trick swaps it for the normalized adjacency with self-loops, whose eigenvalues lie in . With input channels and filters, , this is the graph convolutional network (GCN) layer:
Read entrywise, node averages itself and its neighbors with weights , then applies a shared linear map: the spectral story ends in a very local rule. A two-layer GCN reached 81.5% accuracy on the Cora citation network from 20 labeled papers per class, and the paper's depth experiments found 2 or 3 layers best, with models deeper than 7 layers hard to train without residual connections.
import torch
def gcn_norm(edge_index, n):
"""edge_index: (2, E) long tensor listing both directions of every edge."""
loops = torch.arange(n).repeat(2, 1)
ei = torch.cat([edge_index, loops], dim=1) # A + I
deg = torch.zeros(n).index_add_(0, ei[1], torch.ones(ei.size(1)))
w = deg[ei[0]].rsqrt() * deg[ei[1]].rsqrt() # 1 / sqrt(d_u d_v), self-loops counted
return ei, w
class GCNLayer(torch.nn.Module):
def __init__(self, d_in, d_out):
super().__init__()
self.lin = torch.nn.Linear(d_in, d_out, bias=False)
def forward(self, x, ei, w):
h = self.lin(x) # transform first: O(n d_in d_out)
src, dst = ei
msg = w[:, None] * h[src] # one message per edge: O(|E| d_out)
out = torch.zeros_like(h).index_add_(0, dst, msg) # sum the messages at each node
return torch.relu(out)A GCN layer written edge by edge. edge_index lists the endpoints of every directed edge and index_add_ sums the messages arriving at each node, so the dense matrix is never formed. Libraries such as PyTorch Geometric and DGL provide these scatter operations, with many layer types built in.
GraphSAGE (Hamilton, Ying & Leskovec, 2017) keeps a node apart from its neighborhood and concatenates the two, , then rescales to unit length. The aggregator is a mean, an LSTM run over a random ordering of the neighbors, or an elementwise max after a one-layer network. is a fixed-size uniform sample of , drawn afresh for each layer, so the cost of a minibatch no longer depends on the degrees. The model embeds nodes it never saw, even whole new graphs: it is inductive, while the original GCN was trained on one fixed graph.
In GraphSAGE's experiments a 2-layer model drew a fresh sample of neighbors at each layer: 10 for the second layer and 25 for the first. Each update also uses the node's own vector from the layer below. At most how many nodes, the target included, enter the computation of one embedding?
Show the answer
286 nodes
The target's second-layer update needs the first-layer vectors of the target itself and of its 10 sampled neighbors, and each of those 11 vectors aggregates its own sample of 25: at most nodes, whatever the degrees ( forgets the target's own first-layer sample). Their Reddit graph had 232,965 posts with an average degree of 492: without sampling, the 2-hop computation tree of an average post would have about entries, more than the graph has nodes. (The paper names the sizes by layer, and , and its minibatch algorithm expands from the target with the 10 first.)
A graph attention network (GAT; Veličković et al., 2018) lets each node weight its neighbors with learned attention, like self-attention restricted to the graph's edges:
Brody, Alon & Yahav (2022) found a limitation hidden in that score. Split : then , and since LeakyReLU and softmax are increasing, every query ranks the nodes by the same number ; the query only sharpens or flattens the distribution. They call this static attention. GATv2 swaps the order of operations, , so the score is a small MLP of the pair and each query can rank its neighbors differently; in their evaluation GATv2 outperformed GAT across 11 OGB and other benchmarks at matched parameter cost.
| Layer | Weight on neighbor in node 's update | The node itself | Known for |
|---|---|---|---|
| GCN | , fixed by the degrees | through the self-loop | spectral derivation; semi-supervised node classification |
| GraphSAGE (mean) | over a sampled set | concatenated separately | inductive minibatch training on large graphs |
| GAT | , a softmax of learned scores | inside the softmax | different weights for different neighbors |
| GIN | (a plain sum), followed by an MLP | the most discriminative message passing (The Expressive Power of GNNs) |
From nodes to whole graphs
For a graph-level prediction, a readout pools the final node vectors into one vector, and it must be permutation-invariant. The simplest readouts are a sum, a mean or an elementwise max over the nodes, followed by an MLP. That is exactly the architecture of Deep Sets for functions of sets (Zaheer et al., 2017):
The choice of pooling matters. A sum keeps counts: two carbon atoms contribute twice as much as one. A mean keeps only proportions, so a molecule and two copies of it get the same vector. A max keeps only which feature values occur at all. Gilmer et al. also used set2set, an attention-based pooling, and a virtual node (their "master node") joined to every node, which gives every pair of nodes a 2-hop connection and the network a global scratch space.
Hierarchical pooling coarsens the graph step by step, like the pooling layers of a CNN. DiffPool (Ying et al., 2018) learns a soft assignment of the nodes to clusters with a second GNN, whose output passes through a softmax in each row:
You predict the total energy of molecules of very different sizes. Total energy is extensive: it grows roughly in proportion to the number of atoms. Which readout fits best?
- The mean over atoms
- The max over atoms
- The sum over atoms
- The vector of the first atom
Show the answer
C. The sum over atoms
A sum of per-atom contributions, , scales with the number of atoms as the target does. SchNet and the interatomic potentials of Equivariant Networks for 3D Geometry pool atomwise energies in exactly this way.
Depth, scale and where GNNs are used
Depth sets the receptive field, so long-range tasks seem to call for deep GNNs. Yet most GNNs use two to a handful of layers, for two reasons that the Emergence lessons develop. Repeated averaging drives all node vectors in a connected graph toward one another until neighbors are indistinguishable, oversmoothing: keep adding mean layers in the widget above and the club's energy falls below 5% of its start by layer 6, as the Activation lesson's two communities also showed. And when a node's receptive field grows exponentially with depth while its vector keeps a fixed size, information from far away is squeezed through a few edges, oversquashing.
Scale brings an engineering version of the same problem: a -layer computation reaches the whole -hop neighborhood, which in a social graph can be a large part of the graph. Sampling, as in GraphSAGE, and precomputing propagated features are the usual fixes.
Key takeaways
- Graphs have no node order: node-level layers must be permutation-equivariant, , and graph-level readouts invariant. Message passing with shared functions and a sum, mean or max over neighbors has both properties.
- A message-passing layer computes one message per edge, aggregates per node and updates per node, at a cost of ; layers see exactly the -hop neighborhood.
- GCN is a first-order spectral filter with the renormalization trick, ; GraphSAGE concatenates a node with an aggregate of sampled neighbors for inductive minibatch training; GAT learns attention weights over neighbors, though its scores rank the neighbors in the same order for every query.
- Graph-level predictions pool node vectors with a sum, mean or max (Deep Sets' ) or hierarchically with learned clusters; a sum keeps counts and extensive quantities, a mean only proportions.
- Most GNNs use a few layers: depth widens the receptive field but brings oversmoothing and oversquashing. GNNs have documented results on molecules, recommendation, physical simulation, weather, traffic and protein structure.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Relabeling the nodes replaces by . A GNN layer outputs one vector per node. Which property must it have?
Show the answer
B.
Node outputs must move with their nodes: equivariance. Message passing has it because every node runs the same computation on its own vector and the multiset of its neighbors' vectors.
Why does the GCN layer propagate with rather than the first-order filter ?
- Adding self-loops makes the adjacency matrix sparser
- It turns the layer into an attention mechanism
- The renormalized matrix has eigenvalues in instead of , so repeated propagation cannot amplify any component of the signal
- It makes each layer reach two hops instead of one
Show the answer
C. The renormalized matrix has eigenvalues in instead of , so repeated propagation cannot amplify any component of the signal
The first-order filter's eigenvalues reach , so layers can amplify some components by up to ; Kipf & Welling noted that repeated application can cause numerical instabilities and exploding or vanishing gradients. Renormalizing with self-loops keeps the spectrum in while still mixing each node with its neighbors.
The information needed to classify node sits only at nodes 6 hops away. What can a 2-layer message-passing GNN do with it?
- Use it after enough training epochs
- Nothing: 's output depends only on nodes within 2 hops
- Use it through the self-loops
- Use it if the aggregation is a sum rather than a mean
Show the answer
B. Nothing: 's output depends only on nodes within 2 hops
Each layer extends the receptive field by one hop, so a 2-layer network computes 's output from its 2-hop neighborhood alone. Reaching 6 hops needs 6 layers, or a change to the graph such as a virtual node joined to every node.
In a GAT layer the score of neighbor for query is . What follows?
- Every query ranks its candidate neighbors in the same order, by
- Each query can rank its neighbors in whatever order the task needs
- All neighbors always receive equal weights
- The attention weights of a node need not sum to one
Show the answer
A. Every query ranks its candidate neighbors in the same order, by
The query enters only through the shift , the same for all candidates, and LeakyReLU and softmax are increasing. So the order of the scores is global; the query only sharpens or flattens the weights. Brody, Alon & Yahav (2022) call this static attention, and GATv2 removes it by applying after the nonlinearity.
Why does GraphSAGE sample a fixed number of neighbors per node and layer instead of using all of them?
- Sampling makes the network exactly as powerful as the Weisfeiler–Leman test
- A mean over a large neighborhood is undefined
- Sampling makes the embeddings invariant to how the nodes are numbered
- To keep the cost and memory of a minibatch bounded whatever the degrees, since full multi-hop neighborhoods can cover much of a large graph
Show the answer
D. To keep the cost and memory of a minibatch bounded whatever the degrees, since full multi-hop neighborhoods can cover much of a large graph
With samples of 10 and 25, one embedding involves at most 286 nodes, while the full 2-hop computation tree of an average Reddit post in their data would have more entries than the graph has nodes. The price is noise from sampling, which training tolerates, and the gain is minibatch training on graphs of any size.
Go deeper
- The Expressive Power of GNNs · The Weisfeiler–Leman test, GIN and going beyond it.
- Oversmoothing & Oversquashing · Why deep GNNs blur features, and bottlenecks that block long-range information.
- Equivariant Networks for 3D Geometry · Rotation-equivariant message passing for molecules, materials and proteins.
Further reading
- J. Gilmer, S. S. Schoenholz, P. F. Riley, O. Vinyals & G. E. Dahl, "Neural message passing for quantum chemistry," ICML (2017).
- T. N. Kipf & M. Welling, "Semi-supervised classification with graph convolutional networks," ICLR (2017).
- W. L. Hamilton, R. Ying & J. Leskovec, "Inductive representation learning on large graphs," NeurIPS (2017).
- P. Veličković, G. Cucurull, A. Casanova, A. Romero, P. Liò & Y. Bengio, "Graph attention networks," ICLR (2018).
- W. L. Hamilton, Graph Representation Learning (Morgan & Claypool, 2020).