Expressivity II: beyond Weisfeiler-Leman
Explore ways to exceed 1-WL expressivity through tuple states, marked subgraphs, structural counts and random features, comparing their guarantees and costs.
After this lesson you can
- Explain higher-order WL refinements and their computational costs.
- Show how marked views and substructure counts distinguish graphs that 1-WL cannot.
- Explain invariance in distribution for random node features.
- Relate homomorphism counts to expressivity.
- Compare architectures using measured costs and carefully controlled evaluation.
Before you start
The vanishing ring
In a molecule, the presence of a ring can matter for its property. In a call graph, a cycle can indicate a circular dependency. Yet 1-WL refinement starting with uniform features cannot distinguish the cycle from the disjoint union : both have six nodes, all of degree two. Every round gives the same color to all twelve nodes. An ordinary MPNN with shared functions and invariant readout inherits that impossibility, even with infinitely many layers.
The limit depends on initial information. If the network receives a triangle indicator, the task is different. The practical question is not “which architecture always wins?” but what additional information, cost and guarantee a particular distinction requires. The following map uses the same graph pair as a certificate; it does not propose a total ordering of all families.
Refining tuples
In the k-WL hierarchy, each state corresponds to an ordered tuple . Its initial color encodes equality between positions, edges and induced labels. For each position , the usual version forms the multiset of colors obtained by replacing with each ; the new signature contains the previous color and those separate multisets. The folklore version first groups the replacements using the same and then takes the multiset of those -tuples of colors. Retaining that correlation provides information lost when sorting each multiset separately.
Numbering conventions vary. Under the convention of Maron and colleagues, 2-FWL has the power of 3-WL; that does not mean a matrix of pairs is a matrix of triples. A graph of nodes has tuples, and a naive round examines replacements per tuple. Cai, Fürer and Immerman graphs give systematic separations between fixed hierarchy levels. The strict hierarchy is a statement about graph families of unbounded size, not that every increase in separates every particular pair.
Higher order and cost
Higher-order GNNs maintain tuple states and must transform them equivariantly under simultaneous permutation of indices. A network over pairs can store : with nodes and channels it needs numbers. The per-channel product
gathers correlated information through the same intermediate node . This operation enables PPGN to achieve 3-WL power under the assumptions of its theoretical construction, as shown by Maron et al.. For dense matrices, a conventional product costs and states , excluding activations, gradients and channel products. It does not follow from the expression that a particular implementation trained on finite data achieves the guarantee.
For example, in a simple adjacency matrix , counts common neighbors. If and are adjacent, that entry detects a triangle. An MPNN with only uniform node states cannot see which two neighbors are connected to each other. In the lab you will verify separation using a discrete version of 2-FWL, which stores exact signatures and does not require training a network.
Individualize and aggregate again
A subgraph GNN can generate a bag of views: in view it marks node , applies a shared MPNN and summarizes the view; finally it aggregates the views invariantly. The selection policy and architecture determine the method’s power. ESAN studies deletion policies and other equivariant views, as well as sampling to reduce cost; not all policies have the same guarantee.
In the first round, the marked node has two unmarked neighbors in both graphs. In those two neighbors are adjacent to each other; in they are not. In the second round their signatures differ: each neighbor of the marker sees another neighbor of the marker in the triangle, while in the hexagon it sees a more distant node. With a shared dictionary the histograms separate. The same conclusion holds for every root by each graph’s symmetry. Processing all roots and summing their representations gives an invariant operation, although marking one fixed root by index is not invariant in general.
Count before learning
Substructure counting adds to each node the number of copies of a pattern it participates in. In GSN the pattern and the node’s orbit within it are part of the design; computing patterns can be expensive even if the network receiving counts is local. Bouritsas et al. analyze these structural features and how they increase expressivity beyond 1-WL.
Proof
Suppose an ordinary MPNN counted triangles on all unlabeled simple graphs. Both and are 2-regular and have six nodes, so the induction for the 1-WL bound forces their readouts to match. But their triangle counts are zero and two respectively. The assumed function cannot exist. Every triangle in a simple graph is induced by its three vertices, so the argument covers that case.
∎In each node participates in zero triangles; in it participates in one. A sum over nodes gives six incidences, and dividing by three yields the two triangles. For rings of size five or six, define whether you count simple or induced cycles, how you avoid counting rotations and orientations multiple times, and what obtaining them costs. The structural label is not free.
Counting per node differs from storing only the global total. If two nodes participate in different numbers of pattern copies, a subsequent MPNN can combine that information with their features and neighborhood patterns. For a pattern with positions not equivalent by symmetry, GSN can separate the orbits of its automorphisms: being the center of a three-vertex path is not the same as being an endpoint. Copies must be counted with a consistent convention on isomorphisms to avoid accidentally multiplying them by the number of automorphisms.
A more powerful counter can also introduce a signal unavailable in production. If training uses counts calculated on the full graph and deployment lacks edges, the input distribution changes. For link prediction, counting substructures before splitting off test edges can leak the answer. First construct the observable graph for each split and compute structural features on it, including that operation’s cost in the budget.
Randomness: invariance of the law, not every sample
Random node features can break symmetries. If they are independent and identically distributed, jointly permuting features and graph preserves exact equivariance; if they are redrawn after permutation, two individual outputs can differ even though their distributions match. Abboud et al. prove universality under their assumptions and preservation of invariance in expectation. This does not guarantee that a trained finite network finds that function or that one sample is stable.
More precisely, for a fixed maximum of nodes and a real graph-invariant function on that bounded size, their theorem guarantees, for any , the existence of a randomized MPNN whose output is within of the target with probability at least , for each graph in the domain. This is a probabilistic approximation guarantee on a bounded finite domain, not a uniform guarantee for arbitrarily large graphs or a practical bound on parameter or data counts. Distributional invariance implies invariance of its expectation when it exists.
A concrete estimator illustrates the mechanism without claiming it is a trained network. For a vector of independent signs , , so
the triangle count of a simple graph. Three multiplications by are three linear message steps; the local product with and global sum perform the readout. This is not the general universality theorem. With independent samples, the variance of their mean is the single-sample variance divided by ; a particular seed may deviate and threshold accuracy need not grow monotonically in each realization.
The displayed accuracy uses another 128 independent repetitions per graph and a fixed threshold of one triangle. It measures this simulation, not the performance of a trained MPNN. The mean’s deviation is calculated across the 128 repetitions of the triangle pair. Increasing reduces theoretical variance, but the observed percentage in a finite collection can rise or fall as the control moves.
Homomorphisms and design decisions
A homomorphism from to preserves edges but can identify nonadjacent nodes of . Homomorphism counts from pattern families provide another language for characterizing distinctions: they are not automatically induced-subgraph counts. The homomorphism expressivity framework relates pattern families to model classes in the quantitative framework of Zhang et al.. Their work on biconnectivity directly studies cut vertices and bridges as structural properties. Each result requires its assumptions on inputs and architecture.
An example shows why the difference matters. Let be a path with three vertices and be simple. A homomorphic image chooses a central vertex and then two neighbors, which can coincide. Therefore . If all three vertices must be distinct, there are mappings, and each undirected path is counted twice. Since ,
Here counts copies not necessarily induced: a triangle has three two-edge paths. This subtraction removes images that identify endpoints. For a general pattern, its images under vertex identifications, called the spasm in the cited framework, are involved; the counting characterization uses that entire family, not just the original pattern’s homomorphism. The theorem concerns idealized model classes defined in the paper, not a particular MLP with trained weights.
Biconnectivity offers a different capacity test. A cut vertex increases the number of components when removed; a bridge edge does the same when the edge is removed. In Zhang et al., DSS-WL with node marking distinguishes these cases through aggregation across views, whereas the variant with only fixed-radius ego neighborhoods lacks the same guarantee. The proof uses the full cross-view aggregation rule: this lesson’s small bag separates our pair, but does not claim to reproduce all DSS-WL guarantees. A fixed set of connected patterns in SC-WL also does not generally solve those biconnectivity problems, although it can detect specific cycles. The comparison distinguishes a chosen local property from a guarantee for an arbitrary graph family.
GIN can reach 1-WL with sufficiently injective aggregation. GSN receives chosen counts; marking uses multiple views; PPGN maintains pairs. A particular k-GNN depends on whether it uses tuples or subsets and on its operations. A transformer with positional encoding has no single place: the encoding may already distinguish the pair, may be ambiguous due to spectral symmetries, or may break invariance if used incorrectly. Comparison only makes sense with the same data access and an explicit budget.
Expressivity represents a possibility, not a generalization result. For a task where known rings matter it may be cheaper to count short cycles and use an MPNN than to maintain all pairs. In ZINC the initial chemical and bond information matters; in molhiv the scaffold split and ROC-AUC require a different protocol. To compare results retain splits, features, parameter count and validation selection, and also measure preprocessing.
As published evidence, Bouritsas et al. report mean MAE 0.140 on ZINC for GSN without bond features and 0.115 using them, under their approximate budget of 100 000 parameters. On ogbg-molhiv, the same paper’s table gives test ROC-AUC 0.7707 for GIN with a virtual node and 0.7799 for a GSN variant based on that architecture. Pattern and epoch were chosen by validation. These are figures from that study, with variation between runs and its own protocols; they are not results of the following lab and do not establish that adding counts always improves an application. The study also observes that greater ability to distinguish nodes does not guarantee lower test error.
Lab: exact signatures
The following two implementations refine graphs jointly to share color names. They use undirected edges without loops or features. Integer assignment is an exact encoding of signatures, not a probabilistic hash.
import numpy as np
from collections import Counter
cycle=[(0,1),(1,2),(2,3),(3,4),(4,5),(5,0)]
triangles=[(0,1),(1,2),(2,0),(3,4),(4,5),(5,3)]
graphs=[cycle,triangles]
def adjacency(edges,n=6):
A=np.zeros((n,n),dtype=int)
for i,j in edges: A[i,j]=A[j,i]=1
return A
def refine_nodes(graphs,root=None,rounds=2):
mats=[adjacency(g) for g in graphs]
colors=[[int(v==root) if root is not None else 0 for v in range(6)] for _ in graphs]
history=[colors]
for _ in range(rounds):
sig=[[(c[v],tuple(sorted(c[u] for u in range(6) if A[v,u]))) for v in range(6)] for A,c in zip(mats,colors)]
keys=sorted(set(s for row in sig for s in row)); code={s:i for i,s in enumerate(keys)}
colors=[[code[s] for s in row] for row in sig]; history.append(colors)
return history
for root in [None,0]:
print('raíz',root,'histogramas',[[sorted(Counter(c).items()) for c in stage] for stage in refine_nodes(graphs,root)])
assert Counter(refine_nodes(graphs,None)[-1][0])==Counter(refine_nodes(graphs,None)[-1][1])
assert Counter(refine_nodes(graphs,0)[-1][0])!=Counter(refine_nodes(graphs,0)[-1][1])def fwl2(graphs,rounds=2):
mats=[adjacency(g) for g in graphs]; n=6
colors=[[[int(i==j)*2+int(A[i,j]) for j in range(n)] for i in range(n)] for A in mats]
history=[colors]
for _ in range(rounds):
signatures=[[[ (c[i][j],tuple(sorted((c[w][j],c[i][w]) for w in range(n)))) for j in range(n)] for i in range(n)] for c in colors]
keys=sorted(set(s for graph in signatures for row in graph for s in row)); code={s:i for i,s in enumerate(keys)}
colors=[[[code[s] for s in row] for row in graph] for graph in signatures]; history.append(colors)
return history
def histogram_pairs(c): return Counter(v for row in c for v in row)
out=fwl2(graphs)
print('2-FWL separa por ronda:',[histogram_pairs(a)!=histogram_pairs(b) for a,b in out])
for graph in graphs:
A=adjacency(graph); per_node=np.diag(A@A@A)//2
print('incidencias por nodo',per_node.tolist(),'triángulos',int(per_node.sum()//3))
assert histogram_pairs(out[-1][0])!=histogram_pairs(out[-1][1])To use cycles as features, enumerate simple cycles of lengths three to six and count each once: begin at its minimum vertex and choose one of the two orientations. This routine does not require the cycle to be induced. In large graphs the number of traversals can grow greatly, so preprocessing must be measured separately.
def cycle_counts(A,max_length=6):
n=len(A);counts=np.zeros((n,max_length-2),dtype=int)
for start in range(n):
def visit(path):
last=path[-1]
if len(path)>=3 and A[last,start] and path[1]<last:
for vertex in path: counts[vertex,len(path)-3]+=1
if len(path)==max_length:return
for nxt in range(start+1,n):
if A[last,nxt] and nxt not in path:visit(path+[nxt])
for nxt in range(start+1,n):
if A[start,nxt]:visit([start,nxt])
return counts
counts=[cycle_counts(adjacency(g)) for g in graphs]
print('C6, ciclos por nodo:',counts[0].tolist())
print('2C3, ciclos por nodo:',counts[1].tolist())
assert np.all(counts[0][:,3]==1) and np.all(counts[0][:,:3]==0)
assert np.all(counts[1][:,0]==1) and np.all(counts[1][:,1:]==0)The root bag must be aggregated without fixing a root by its index. This version records the refined histogram of each view, sorts the bag and checks separation for all six roots. The iteration count and color map are shared.
bags=[[],[]]
for root in range(6):
c=refine_nodes(graphs,root,2)[-1]
for g in range(2): bags[g].append(tuple(sorted(Counter(c[g]).items())))
print('firmas distintas por bolsa',len(set(bags[0])),len(set(bags[1])))
print('bolsas distintas',sorted(bags[0])!=sorted(bags[1]))
assert sorted(bags[0])!=sorted(bags[1])This discrete MPNN makes the construction explicit: it uses a one-hot vector per state, sums neighbor messages and injectively encodes the concatenation of self state and sum. It reproduces scatter_sum from the mini_mp.py framework, with source in the first row of edge_index and destination in the second; we include it in the cell so it also works without downloading files. The shared table is an exact update function on observed finite signatures, not a trained MLP or an injectivity guarantee in floating point for arbitrary inputs. Processing all twelve views at once ensures the same dictionary for every root and both graphs.
views=[(adjacency(graphs[g]),root,g) for g in range(2) for root in range(6)]
states=[np.eye(2,dtype=int)[[int(i==root) for i in range(6)]] for A,root,g in views]
def scatter_sum(messages,dst,n):
out=np.zeros((n,messages.shape[1]),dtype=messages.dtype)
np.add.at(out,np.asarray(dst,dtype=np.int64),messages)
return out
def aggregate_neighbors(A,h):
dst,src=np.nonzero(A)
return scatter_sum(h[src],dst,len(h))
for depth in range(2):
signatures=[np.concatenate([h,aggregate_neighbors(A,h)],axis=1) for (A,root,g),h in zip(views,states)]
keys=sorted({tuple(row) for table in signatures for row in table}); index={key:i for i,key in enumerate(keys)}
states=[np.eye(len(keys),dtype=int)[[index[tuple(row)] for row in table]] for table in signatures]
pooled=[h.sum(axis=0) for h in states]
bag0=np.stack(pooled[:6]).sum(0);bag1=np.stack(pooled[6:]).sum(0)
print('dimensión final',len(bag0),'bolsas diferentes',bool(np.any(bag0!=bag1)))
assert np.any(bag0!=bag1)The final sum is invariant to root order. Summing vectors of all views retains enough information to separate this particular pair; an architecture that compresses each view differently may lose it. With full views, the number of node states grows from to , and duplicating edges for each view adds approximately messages per layer.
Local lab: expressivity and prediction
Download comparar.py and checkpoint.py into the same folder. You need PyTorch with CUDA, PyTorch Geometric, NumPy and NetworkX. The program uses ZINC(..., subset=True) and its official splits of 10 000, 1000 and 1000 molecules. The first run downloads data; --root selects the folder. Every model uses atom categories, three GIN layers and the same width. The comparison omits bond types to keep shared input: it does not reproduce a full molecular benchmark that uses them.
The four variants are GIN, GIN with an independent normal scalar per node, a simple GSN with simple cycle counts of lengths 3 to 6, and GIN with all views of one marked root. The last averages view outputs. Counting enumerates each cycle once by its minimum node and orientation; its preparation time is not part of recorded training time. Random models are evaluated with eight initializations and their mean. Each epoch is selected by validation MAE; test is used only after selecting weights. CUDA timing and peak memory measurements belong to the run, not performance guarantees.
Equal width does not exactly equalize parameters: GSN adds a projection of four counts and random and marked variants add a scalar projection. Also, one view per root multiplies work even while reusing the same weights. Attributing an improvement to greater expressivity would also require controlling parameter budget, feature access and hyperparameter selection; this comparison is designed to let you inspect those factors, not isolate them all experimentally.
The second task generates 2000 simple ten-node graphs with varied edge probabilities and predicts triangle count. It uses 1600, 200 and 200 graphs for training, validation and test. The same seed fixes graphs, split and initialization, but variation across seeds and bias from choosing hyperparameters still require further experiments. The task illustrates the cost and usefulness of explicit counting: it does not demonstrate that an architecture generalizes better on all molecular graphs.
In our synthetic-task run with seed 42, 50 epochs per model and width 64, the following mean absolute errors were obtained. Weights were selected by validation and test evaluated afterward; the random variant averaged eight draws in evaluation.
| Variant | Validation MAE | Test MAE |
|---|---|---|
| GIN | 0.825 | 0.741 |
| GIN with randomness | 0.828 | 0.754 |
| Cycle counts | 0.335 | 0.282 |
| Marked roots | 0.830 | 0.751 |
| Variant | Time, s | CUDA peak, MiB |
|---|---|---|
| GIN | 122.2 | 18.16 |
| GIN with randomness | 183.2 | 18.16 |
| Cycle counts | 186.1 | 18.16 |
| Marked roots | 358.1 | 22.55 |
The GSN feature directly includes triangle incidences determining the label, so its advantage here is not a fair comparison of input information. The fact that a marked view can distinguish the proof pair does not guarantee that finite-width training learns to count in this distribution. One seed does not establish whether small differences between the other models are stable.
The table’s times and peaks come from that run on a shared GeForce RTX 3060, batch 16, PyTorch 2.11.0+cu128 and PyTorch Geometric 2.8.1; they include training, validation and final evaluation, but not prior graph and cycle preparation. Peak is PyTorch-allocated memory, not total card memory. The current implementation prepares marked views in vectorized form, so the earlier version’s time should not be used to predict the downloadable version’s time. Averaging eight evaluation draws adds work for the random variant.
On ZINC 12k all four variants ran for 50 epochs with seed 42 and batch 16, this time on single-thread CPU. A previous test with the same batch of 16 molecules showed that CPU was faster than CUDA for steps in this example under the observed shared load. Selection used validation MAE and test was evaluated afterward:
| Variant | Best epoch | Validation MAE | Test MAE |
|---|---|---|---|
| GIN | 45 | 0.412 | 0.432 |
| GIN with randomness | 47 | 0.420 | 0.442 |
| Cycle counts | 44 | 0.320 | 0.318 |
| Marked roots | 45 | 0.413 | 0.446 |
The run recorded approximately 287, 272, 245 and 3081 seconds respectively for training, validation and test, excluding prior cycle computation; the last resumed after interruption and the time excludes the pause. These are CPU times, not GPU times or CPU memory, and the machine was shared. GSN received additional structural features; the other variants do not receive exactly the same information. One seed and 50 epochs are insufficient to establish a robust ordering or reproduce an optimized benchmark.
To also measure GPU error, the best CPU-trained weights were loaded and the 1000 official test molecules evaluated on the RTX 3060 with batch 16. The first three models were reconstructed with the same 50-epoch protocol to retain their checkpoints; the roots model comes from the previous run. CUDA evaluation seed is 42 and the random variant averages eight draws per graph.
| Variant | CUDA test MAE | Evaluation, s |
|---|---|---|
| GIN | 0.43169 | 1.16 |
| GIN with randomness | 0.44182 | 4.81 |
| Cycle counts | 0.31772 | 0.85 |
| Marked roots | 0.44613 | 1.70 |
The timer covers evaluation only, synchronized with CUDA under shared load; it excludes training and cycle preparation. In the random variant, draws fixed for CUDA differ from those generated on CPU, so the two estimates do not use exactly the same random inputs. Maximum memory allocated during evaluation was approximately 9.7 MiB for the first three variants and 20.8 MiB for marked roots.
To compare CUDA cost per step, a real batch of 16 ZINC training molecules was also used. After two warm-up steps, five full forward, backward and Adam steps per variant were measured on the RTX 3060; each model was freed before starting the next. The vectorized marked-view version was used.
| Variant | Time per step, ms | CUDA peak, MiB |
|---|---|---|
| GIN | 32.88 | 18.60 |
| GIN with randomness | 38.19 | 18.60 |
| Cycle counts | 33.27 | 18.60 |
| Marked roots | 46.46 | 39.96 |
These figures are a brief single-batch test under shared load, not full-campaign times or a card constant. Peak measures memory allocated by the process during the steps, not total memory occupied by other applications. It excludes initial count preparation. Test evaluation with eight random-variant draws is also outside this timer.
python comparar.py --task synthetic --epochs 50 --output synthetic.json
python comparar.py --task zinc --root dataset --epochs 50 --output zinc.json
CUDA is used by default; add --device cpu to run on one CPU thread. To measure carefully, synchronize the GPU before reading the clock, record hardware and software, and repeat several seeds without choosing the best by test. The program records maximum PyTorch-allocated CUDA memory, which does not necessarily include all reserved memory or that of other processes. On CPU, zero indicates that run allocated no CUDA memory; it does not measure process RAM. On a shared GPU timings fluctuate. Cycle and view generation costs must be counted separately when deciding which model to deploy.
At the end of each epoch an .<modelo>.checkpoint file is saved alongside JSON with current parameters, best parameters, optimizer and random generators. Each variant keeps its own file. If interrupted, repeat the same command and output path to resume from the last complete epoch; models already written to JSON are retained. Use another path to change the experiment. Accumulated time includes recorded training phases, not time when the process was stopped.
Exercises
Step 1 of 3. What colors does 1-WL produce in the first round?
Step 1 of 3. What appears in the first round?