Simple Algorithm
Deep Learning · Emergence · 30 min

The Expressive Power of GNNs

The Weisfeiler–Leman test, GIN and going beyond it.

Two disjoint triangles and a hexagon: six nodes and six edges each, every node with exactly two neighbors. One graph is connected and the other is not; one contains triangles and the other does not. Yet no message-passing network, however large and however trained, maps them to different outputs. This lesson pins down exactly what message passing can tell apart, using a graph-isomorphism test from 1968, proves that sum aggregation reaches that limit while mean and max fall short, and climbs the hierarchy of more powerful and more expensive models beyond it.

What you’ll learn

  • Run 1-WL color refinement, state what it can and cannot distinguish, and characterize it by tree homomorphism counts and counting logic.
  • Prove that sum aggregation over bounded multisets is injective, conclude that GIN is as discriminative as 1-WL, and state exactly what mean and max aggregation lose.
  • Explain the kk-WL hierarchy, the Cai–Fürer–Immerman construction and higher-order networks (kk-GNNs, invariant graph networks, PPGN), including the number of equivariant linear layers and their cost.
  • Compare cheaper routes beyond 1-WL (subgraph GNNs, random features, substructure counts, Laplacian encodings, graph transformers) and the limits on counting substructures.
  • Separate expressive power from generalization and from benchmark performance.

Color refinement

If 1-WL distinguishes two graphs, they are certainly not isomorphic; if it does not, they may or may not be. On typical graphs it is strong: for a uniformly random graph on nn nodes, the probability that two rounds already give every node its own color tends to 1 as nn grows (Babai, Erdős & Selkow, 1980), and then the graph is identified. Its failures are structured. Every node of a dd-regular graph sees its own color and dd neighbors of that same color, round after round, so 1-WL cannot distinguish any two dd-regular graphs with the same number of nodes.

DerivationWhy trees cannot see cycles
  1. hom⁡(T,G)=n d t−1\hom(T,G)=n\,d^{\,t-1}

    Count the homomorphisms from a tree TT with tt nodes into a dd-regular graph GG with nn nodes. Map one node of TT anywhere (nn choices); every further node, reached from its parent, must go to one of the dd neighbors of the parent's image:

  2. hom⁡(P3,C6)=hom⁡(P3,2K3)=24\hom(P_3,C_6)=\hom(P_3,2K_3)=24

    The count depends only on nn and dd, so all dd-regular graphs on nn nodes agree on every tree: the regular-graph failure again, now explained. For the hexagon and the two triangles (n=6n=6, d=2d=2), the path on 3 nodes has 6⋅22=246\cdot2^2=24 homomorphisms into each:

  3. hom⁡(C3,C6)=0 ≠ 12=hom⁡(C3,2K3)\hom(C_3,C_6)=0\ \ne\ 12=\hom(C_3,2K_3)

    A cycle is not a tree, and here its counts differ: the triangle maps into each triangle in 3!=63!=6 ways and not at all into the bipartite hexagon. Message passing is bounded by 1-WL, so it sees a graph only through its tree counts; information that only cycles carry, such as how many triangles a regular graph has, is out of its reach.

python
from collections import Counter

def wl_same(g1, g2, rounds=3):
    """1-WL on two graphs (adjacency lists) with one shared color table.
    Returns, per round, whether the two color histograms are equal."""
    colors, table, same = [[0] * len(g1), [0] * len(g2)], {}, []
    for _ in range(rounds):
        colors = [[table.setdefault((col[v], tuple(sorted(col[u] for u in adj[v]))), len(table))
                   for v in range(len(adj))] for adj, col in zip((g1, g2), colors)]
        same.append(Counter(colors[0]) == Counter(colors[1]))
    return same

def adjacency(n, edges):
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)
    return adj

hexagon = adjacency(6, [(i, (i + 1) % 6) for i in range(6)])
triangles = adjacency(6, [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3)])
print(wl_same(hexagon, triangles))        # [True, True, True]: 1-WL never tells them apart

The shared table plays the role of the injective hash: a node's new color is the index of the pair (own color, sorted neighbor colors). The decalin pair of the widget also gives True at every round, while 2- and 3-methylpentane give [True, False, False].

Message passing is exactly as strong as 1-WL

Part (a) follows by induction over the layers: two nodes with the same WL color always hold the same vector, because they start alike and receive equal multisets of neighbor vectors. Part (b) needs injective functions of multisets, and it is not obvious that a neural network can supply one with a simple sum.

DerivationSum aggregation can be injective
  1. f(x)=N−Z(x),∑x∈Mf(x)=∑k≥1ck N−k,ck=#{x∈M:Z(x)=k}<Nf(x)=N^{-Z(x)},\qquad\sum_{x\in M}f(x)=\sum_{k\ge1}c_k\,N^{-k},\qquad c_k=\#\{x\in M:Z(x)=k\}<N

    The feature values are countable, so number them with an injective Z:X→{1,2,… }Z:\mathcal X\to\{1,2,\dots\}, and let every neighborhood multiset MM have fewer than NN elements. Map each value to a power of 1/N1/N:

  2. M≠M′⟹∑x∈Mf(x)≠∑x∈M′f(x)M\ne M'\quad\Longrightarrow\quad\sum_{x\in M}f(x)\ne\sum_{x\in M'}f(x)

    The counts ckc_k are the base-NN digits of the sum, so the sum determines the multiset. Any function gg of the multiset is then ψ(∑xf(x))\psi\big(\sum_xf(x)\big) for some ψ\psi, which an MLP can approximate:

  3. hv(ℓ+1)=MLP(ℓ)((1+ϵ(ℓ))hv(ℓ)+∑u∈N(v)hu(ℓ))\mathbf h_v^{(\ell+1)}=\mathrm{MLP}^{(\ell)}\Big(\big(1+\epsilon^{(\ell)}\big)\mathbf h_v^{(\ell)}+\sum_{u\in\mathcal N(v)}\mathbf h_u^{(\ell)}\Big)

    The update also needs the node's own vector. Summing over {v}∪N(v)\{v\}\cup\mathcal N(v) would confuse a node of color aa with one neighbor of color bb and a node of color bb with one neighbor of color aa. Weighting the center by 1+ϵ1+\epsilon separates them: for infinitely many ϵ\epsilon, every irrational one included, (1+ϵ)f(c)+∑x∈Mf(x)(1+\epsilon)f(c)+\sum_{x\in M}f(x) is injective on pairs (c,M)(c,M). One MLP then models φ\varphi and ff together:

  4. This is the graph isomorphism network (GIN). With sum readouts of every layer, concatenated, it is as discriminative as 1-WL. In Xu et al.'s experiments a fixed ϵ=0\epsilon=0 fitted the training data as well as a learned ϵ\epsilon.

Predict before you look

Encode atoms by f(x)=10−Z(x)f(x)=10^{-Z(x)} with Z(C)=1Z(\mathrm C)=1, Z(N)=2Z(\mathrm N)=2, Z(O)=3Z(\mathrm O)=3, for neighborhoods of fewer than 10 atoms. What is ∑f\sum f over a carbon atom's neighbors C, C and O?

Show the answer

0.201

2×0.1+0.001=0.2012\times0.1+0.001=0.201. Read the decimal digits: 2 carbons, 0 nitrogens, 1 oxygen, so no two different neighborhoods can collide. Trained networks do not use this construction, which needs unbounded precision as the alphabet grows; it shows that a sum can be injective, whereas no choice of ff makes a mean or a max injective, since { ⁣{a} ⁣}\{\!\{a\}\!\} and { ⁣{a,a} ⁣}\{\!\{a,a\}\!\} always look the same to both.

Mean and max aggregation are permutation-invariant but not injective, and Xu et al. characterized exactly what they keep. A mean determines a multiset's distribution, the proportions of its elements: { ⁣{a,b} ⁣}\{\!\{a,b\}\!\} and { ⁣{a,a,b,b} ⁣}\{\!\{a,a,b,b\}\!\} always collide. A max determines only its underlying set: { ⁣{a,b} ⁣}\{\!\{a,b\}\!\} and { ⁣{a,b,b} ⁣}\{\!\{a,b,b\}\!\} collide. Even a sum fails if the map applied before it is a single layer ReLU⁡(Wx)\operatorname{ReLU}(W\mathbf x) without bias instead of an MLP: some pairs of distinct multisets give equal sums for every WW.

Climbing the hierarchy

To see more than 1-WL, color more than single nodes. The kk-dimensional test colors kk-tuples of nodes. Two tuples start with the same color when the subgraphs they induce are isomorphic with matching positions, and each round recolors a tuple (v1,…,vk)(v_1,\dots,v_k) by its own color together with, for every node ww, the colors of the kk tuples obtained by putting ww in position 1,…,k1,\dots,k. Two versions exist: the folklore test kk-FWL groups these kk colors per node ww, the oblivious kk-WL treats them separately. For k≥2k\ge2, kk-FWL is exactly as strong as (k+1)(k+1)-WL, and 2-WL is no stronger than 1-WL; "3-WL" in GNN papers therefore usually means 2-FWL.

Neural networks follow the same ladder. kk-GNNs (Morris et al., 2019) pass messages between kk-element subsets of nodes, mirroring a set-based kk-WL, and stack 1-, 2- and 3-dimensional layers hierarchically. Invariant graph networks (Maron, Ben-Hamu, Shamir & Lipman, 2019) act on the whole n×nn\times n adjacency tensor, or on higher-order tensors, alternating linear layers that commute with relabeling and pointwise nonlinearities. How many such linear layers are there?

DerivationCounting equivariant linear layers
  1. Lπ(i)π(j)π(k)π(l)=Lijklfor all permutations πL_{\pi(i)\pi(j)\pi(k)\pi(l)}=L_{ijkl}\qquad\text{for all permutations }\pi

    A linear map on n×nn\times n matrices, L(X)ij=∑k,lLijklXklL(X)_{ij}=\sum_{k,l}L_{ijkl}X_{kl}, commutes with relabeling, L(PXP⊤)=P L(X)P⊤L(PXP^\top)=P\,L(X)P^\top for every permutation matrix PP, exactly when its coefficient tensor is unchanged by relabeling all four indices at once:

  2. dim⁡{L:Rnk→Rnl equivariant}=Bell(k+l),Bell(2), Bell(3), Bell(4)=2, 5, 15\dim\{L:\R^{n^k}\to\R^{n^l}\ \text{equivariant}\}=\mathrm{Bell}(k+l),\qquad\mathrm{Bell}(2),\,\mathrm{Bell}(3),\,\mathrm{Bell}(4)=2,\,5,\,15

    So LL is constant on each orbit of index tuples, and an orbit is fixed by which of the four indices are equal: an equality pattern, that is, a partition of {i,j,k,l}\{i,j,k,l\}. For n≥4n\ge4 every pattern occurs, and the indicator tensors of the patterns form a basis. Maps from order-kk to order-ll tensors have one basis element per partition of k+lk+l indices, once n≥k+ln\ge k+l:

  3. L(X)=∑p=115wp Ep(X)L(X)=\sum_{p=1}^{15}w_p\,E_p(X)

    For sets (k=l=1k=l=1), the two patterns i=ji=j and i≠ji\ne j give back Deep Sets' layer λI+γ11⊤\lambda I+\gamma\mathbf 1\mathbf 1^\top. For graphs (k=l=2k=l=2) the 15 basis maps EpE_p include the identity, the transpose, the diagonal, row and column sums broadcast along rows or columns, and the total sum broadcast everywhere; invariant readouts of a matrix (l=0l=0) are spanned by Bell(2)=2\mathrm{Bell}(2)=2 maps, the trace and the sum of all entries.

With linear layers of order kk and pointwise nonlinearities, these networks separate exactly the graphs that oblivious kk-WL separates (at least these: Maron, Ben-Hamu, Serviansky & Lipman, 2019; at most these: Geerts, 2020), so order 2 is no stronger than message passing. One nonlinear operation changes that. PPGN (Maron, Ben-Hamu, Serviansky & Lipman, 2019) interleaves MLPs on the feature channels with matrix products of n×nn\times n feature matrices, which mirror the update of 2-FWL, and reaches 2-FWL ("3-WL") power at O(n3)\order{n^3} time and O(n2)\order{n^2} memory per layer: provably beyond message passing, and costly on large graphs.

Cheaper ways past 1-WL

Cubic cost is out of reach for graphs with millions of nodes, so most practical models keep message passing and add one targeted signal that 1-WL lacks:

ApproachWhat is addedWhat it buysCost
Subgraph GNNs: ESAN (Bevilacqua et al., 2022)a shared GNN on a bag of subgraphs (each node or edge deleted, or ego-networks), aggregated equivariantlystrictly beyond 1-WL: deleting a node of the hexagon leaves a 5-node path, of the triangles an edge plus a triangle, which 1-WL separates in two rounds; node-based variants are at most as powerful as 2-FWL (Frasca et al., 2022)about nn times one GNN, or sampled subgraphs
Random node features (Sato, Yamada & Kashima, 2021; Abboud, Ceylan, Grohe & Lukasiewicz, 2021)random numbers appended to each node's inputuniversal approximation of invariant functions on graphs of a fixed size, with high probability; invariance holds only in expectationnone at run time; training must learn to ignore the noise
Substructure counts: GSN (Bouritsas, Frasca, Zafeiriou & Bronstein, 2023)for each node, counts of the small patterns it belongs to (cycles, cliques), by rolebeyond 1-WL for suitable patterns: one triangle per node in the triangles, none in the hexagonpattern counting, polynomial for fixed small patterns
Laplacian eigenvectors (Dwivedi et al., 2020)the first eigenvectors of the graph Laplacian as node featuresglobal structure: the hexagon's spectrum 0,1,1,3,3,40,1,1,3,3,4 differs from the triangles' 0,0,3,3,3,30,0,3,3,3,3; eigenvector signs (and bases of repeated eigenvalues) are arbitrary, so training flips signs at random or uses sign-invariant networks (Lim et al., 2022)an eigendecomposition: O(n3)\order{n^3} dense, less for a few eigenvectors of a sparse graph
Graph transformers: Graphormer (Ying et al., 2021), GraphGPS (Rampášek et al., 2022)attention between all pairs, biased by shortest-path distance and fed degree embeddings (Graphormer); message passing plus global attention plus positional encodings (GPS)distances separate the hexagon, with pairs 3 apart, from the triangles, with pairs not connected at allO(n2)\order{n^2} attention, or O(n+∣E∣)\order{n+\abs E} with linear attention in GPS
Each row breaks the hexagon-versus-triangles tie with a different kind of information. None of them is a free lunch: they add cost, randomness or design choices about which structures matter.

Graph theory offers other yardsticks. Zhang, Luo, Wang & He (2023) asked whether GNNs detect cut vertices and bridges, which linear-time algorithms find. Most existing architectures provably cannot; of those they examined, only the subgraph approach could. Their generalized distance WL adds distances to every aggregation: shortest-path distances handle bridges but not cut vertices, resistance distances handle cut vertices, using both handles every biconnectivity property they studied, and 2-FWL is at least as strong as either variant.

Check your understanding

Which change lets a message-passing network separate the hexagon from the two triangles?

  1. Doubling the number of layers
  2. Replacing mean by max aggregation
  3. Adding each node's number of triangles as an input feature
  4. Randomly dropping edges during training
Show the answer

C. Adding each node's number of triangles as an input feature

The triangle count is 0 at every node of the hexagon and 1 at every node of the triangles, so the first round already sees the difference: the idea behind substructure-count features. The other changes leave the network inside the WL bound, which maps the two graphs alike.

Expressivity is not the whole story

Separating graphs and approximating functions on them are two views of one property: a model class separates every pair of non-isomorphic graphs exactly when it can approximate every continuous permutation-invariant function on graphs (Chen, Villar, Chen & Bruna, 2019). The WL hierarchy therefore also ranks which functions models can represent in principle. It says nothing about which functions they learn from finite data, and there capacity cuts both ways: Morris, Geerts, Tönshoff & Grohe (2023) bound a GNN's VC dimension by the number of colors 1-WL produces and, for graphs of bounded size, tie it tightly to the number of graphs 1-WL can tell apart. More discrimination can mean more data needed.

The experimental record shows the same tension. In Xu et al.'s benchmarks, GIN fitted the training sets far better than mean and max variants, but its test accuracy was often close to GCN's: 76.2% against 76.0% on PROTEINS and 80.2% against 79.0% on COLLAB. Higher-order models and graph transformers report gains where rings and distances matter, as in molecules, but careful re-evaluations have also found well-tuned message-passing baselines closing much of a reported gap (Oversmoothing & Oversquashing describes one such case).

Key takeaways

  • 1-WL color refinement identifies almost all graphs but no pair of regular graphs of equal size and degree. It is equivalent to equal tree homomorphism counts and to the counting logic C2\mathsf C^2, and message passing can distinguish at most what it distinguishes.
  • Sum aggregation over bounded multisets of countable features is injective (f(x)=N−Z(x)f(x)=N^{-Z(x)} turns counts into digits), so GIN, hv′=MLP((1+ϵ)hv+∑uhu)\mathbf h_v'=\mathrm{MLP}\big((1+\epsilon)\mathbf h_v+\sum_u\mathbf h_u\big), matches 1-WL; a mean keeps only proportions and a max only the set of values.
  • The kk-WL hierarchy is strict at every level (Cai–Fürer–Immerman) and kk-FWL costs O(k2nk+1log⁡n)\order{k^2n^{k+1}\log n} time; invariant graph networks have Bell(k+l)\mathrm{Bell}(k+l) equivariant linear maps between order-kk and order-ll tensors, and PPGN reaches 2-FWL with matrix products in O(n3)\order{n^3}.
  • Cheaper routes past 1-WL add a specific signal: subgraphs, random node features, substructure counts, Laplacian eigenvectors or distance-aware attention. Plain message passing cannot induced-count any connected pattern with 3 or more nodes.
  • Expressive power is not generalization: separating more graphs raises the VC dimension, and benchmark gains are often smaller than the theory suggests.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Two non-isomorphic 4-regular graphs have 10 nodes each and no node features. What do 1-WL and a GIN do with them?

  1. 1-WL separates them after one round, because their edge sets differ
  2. 1-WL keeps identical histograms forever, so no message-passing GNN, GIN included, maps them to different embeddings
  3. 1-WL fails, but a GIN trained long enough separates them
  4. 1-WL separates them because their triangle counts differ
Show the answer

B. 1-WL keeps identical histograms forever, so no message-passing GNN, GIN included, maps them to different embeddings

Every node starts gray and sees four gray neighbors, so every round gives all nodes of both graphs one common color. By the WL bound no message-passing network does better. Separating them needs other information: substructure counts, positional encodings or higher-order layers.

Question 2

Which two neighborhoods can a mean aggregator never tell apart, whatever function it averages?

  1. { ⁣{a} ⁣}\{\!\{a\}\!\} and { ⁣{b} ⁣}\{\!\{b\}\!\}
  2. { ⁣{a,b} ⁣}\{\!\{a,b\}\!\} and { ⁣{b,c} ⁣}\{\!\{b,c\}\!\}
  3. { ⁣{a,b} ⁣}\{\!\{a,b\}\!\} and { ⁣{a,a,b} ⁣}\{\!\{a,a,b\}\!\}
  4. { ⁣{a,b} ⁣}\{\!\{a,b\}\!\} and { ⁣{a,a,b,b} ⁣}\{\!\{a,a,b,b\}\!\}
Show the answer

D. { ⁣{a,b} ⁣}\{\!\{a,b\}\!\} and { ⁣{a,a,b,b} ⁣}\{\!\{a,a,b,b\}\!\}

Both have the same distribution, half aa and half bb, so 12(f(a)+f(b))=14(2f(a)+2f(b))\tfrac12(f(a)+f(b))=\tfrac14(2f(a)+2f(b)) for every ff. A mean keeps proportions and forgets the count; a sum keeps both.

Question 3

What did Cai, Fürer & Immerman (1992) prove about the Weisfeiler–Leman hierarchy?

  1. For every kk there are non-isomorphic graphs with O(k)\order{k} nodes that kk-FWL cannot distinguish, so no fixed dimension identifies all graphs
  2. 3-FWL identifies every graph
  3. 1-WL and 2-FWL have the same power
  4. kk-FWL runs in linear time for every fixed kk
Show the answer

A. For every kk there are non-isomorphic graphs with O(k)\order{k} nodes that kk-FWL cannot distinguish, so no fixed dimension identifies all graphs

Their construction shows the hierarchy is strict and never ends: each dimension has its own blind spots. Many classes are still identified at a small dimension, planar graphs at 3, but not all graphs.

Question 4

What does the VC-dimension analysis of Morris, Geerts, Tönshoff & Grohe (2023) imply about making a GNN more expressive?

  1. Nothing: expressive power and generalization are unrelated
  2. More expressive GNNs always generalize better
  3. Capacity grows with discrimination: for graphs of bounded size the VC dimension is tightly tied to the number of graphs 1-WL can tell apart, so separating more graphs can demand more training data
  4. The VC dimension depends only on the number of layers
Show the answer

C. Capacity grows with discrimination: for graphs of bounded size the VC dimension is tightly tied to the number of graphs 1-WL can tell apart, so separating more graphs can demand more training data

Separating more graphs means a larger hypothesis class. They bound the VC dimension by the number of colors 1-WL produces and, for bounded graph order, tie it tightly to the number of 1-WL-distinguishable graphs; without a bound on the order, the bit length of the weights controls it. Expressivity is capacity, not a guarantee of low test error.

Further reading

  • K. Xu, W. Hu, J. Leskovec & S. Jegelka, "How powerful are graph neural networks?," ICLR (2019).
  • C. Morris, M. Ritzert, M. Fey, W. L. Hamilton, J. E. Lenssen, G. Rattan & M. Grohe, "Weisfeiler and Leman go neural: higher-order graph neural networks," AAAI (2019).
  • H. Maron, H. Ben-Hamu, H. Serviansky & Y. Lipman, "Provably powerful graph networks," NeurIPS (2019).
  • Z. Chen, L. Chen, S. Villar & J. Bruna, "Can graph neural networks count substructures?," NeurIPS (2020).
  • C. Morris, Y. Lipman, H. Maron, B. Rieck, N. M. Kriege, M. Grohe, M. Fey & K. Borgwardt, "Weisfeiler and Leman go machine learning: the story so far," Journal of Machine Learning Research 24 (2023).