Module contents
Stage 4 of 8Advanced 100 min

Graph classification, GIN and expressivity

Move from nodes to whole graphs: invariant readouts, GIN with bond attributes, and the ogbg-molhiv molecular benchmark with scaffold split. Implement the Weisfeiler-Leman test, construct pairs no message-passing GNN can distinguish, and check empirically with the trained network.

After this lesson you can

  • Implement sum, mean, max, and attention readouts and compare discriminative power.
  • Implement GIN with bond attributes and train it on ogbg-molhiv.
  • Implement the 1-WL test and find indistinguishable graph pairs.
  • Check that the trained network assigns the same output to those pairs.

Before you start

One vector for a whole molecule

A molecule has no privileged “first” node. If you renumber its atoms and adjust bond endpoints, a property prediction should remain the same. The network can compute per-atom representations equivariantly and then apply an order-invariant graph-level readout. In the disjoint union, the batch vector indicates each atom’s molecule; a segmented reduction obtains one vector per molecule without mixing graphs.

Sum preserves multiplicity: scalar states {1,3}\{1,3\} and {1,1,3,3}\{1,1,3,3\} produce 4 and 8, while mean and maximum produce 2 and 3 in both cases. If every node has constant feature 1, sum counts nodes; mean and maximum do not. This does not make every sum of arbitrary vectors injective: {1,3}\{1,3\} and {2,2}\{2,2\} sum to 4. Architecture expressivity also depends on how it constructs states before readout.

Readout attention can learn weights per node and is invariant if scoring, normalization, and summation are applied symmetrically. A normalized softmax gives a weighted mean: duplicating all identical states does not necessarily change the result. Concatenating graph size or using a sum can preserve count information. The choice should fit the task, not a universal aggregator hierarchy.

The next cell implements all four readouts over a segmented batch of nonempty graphs. Attention uses a fixed query for reproducibility; in a trainable network it could be learned. The first and second bags have the same values with different multiplicity: sum distinguishes them, but mean, maximum, and this normalized attention do not. The first and third have equal sum and mean, but differ in maximum and attention. Neither comparison demonstrates general injectivity of a learned architecture.

[ ]Four segmented readoutsBrowser
import numpy as np

def readouts(x, batch, query):
    rows=[]
    for graph_id in sorted(set(batch)):
        h=x[batch==graph_id]
        scores=h@query
        weights=np.exp(scores-scores.max()); weights/=weights.sum()
        rows.append((h.sum(axis=0),h.mean(axis=0),h.max(axis=0),
                     (weights[:,None]*h).sum(axis=0)))
    return np.asarray(rows)

x=np.array([[1.],[3.],[1.],[1.],[3.],[3.],[2.],[2.]])
batch=np.array([0,0,1,1,1,1,2,2])
r=readouts(x,batch,np.array([1.]))[:,:,0]
print('suma, media, máximo, atención por grafo:')
print(np.round(r,4))
assert np.allclose(r[:,0],[4,8,4])
assert np.allclose(r[:,1],[2,2,2]) and np.allclose(r[:,2],[3,3,2])
assert np.isclose(r[0,3],r[1,3]) and r[0,3]>r[2,3]

The disjoint union is needed so the readout does not mix molecules. Suppose a batch has two graphs: one has states [1,3][1,3] and the other [2,2,2][2,2,2]. The global sum of the five values is 10, but segmented sums are 4 and 6. The first answers a question about the whole batch; the latter feed two independent predictions. For an invariant result, renumbering nodes must permute batch along with features and correctly offset edge endpoints. Grouping by batch index does not depend on node order.

Size can be a desired signal or a spurious cue. A sum grows when a local structure repeats and can help model extensive properties; a mean may be more appropriate for an approximately intensive target. This is guidance, not a law: the preceding network and final function also transform that information. Ablating sum, mean, and maximum requires fixing the rest of the protocol and comparing on the same split, because changing aggregator and capacity together prevents attributing the difference to one alone.

Refining colors and comparing graphs

The one-dimensional Weisfeiler-Leman test (1-WL) initially assigns the same color to unattributed nodes, or colors matching their labels. At each step it replaces a node’s color with an injective label of its prior color and multiset of neighbor colors. Colors must be assigned consistently between both graphs: independent labels could give equal numbers to different structures.

InteractiveRefinement with a shared palette
  • Color 0
6-cycleTwo triangles
Histogram: color number and node count
Pair
0
Cycle histogram0: 6
Second graph histogram0: 6
Advance iterations. The six-cycle and two triangles retain the same histogram; change the second graph to a star and observe degree separation on the first step.

The six-cycle and two triangles have six degree-two nodes. If they begin with one color, all receive the same signature at each iteration; histograms match forever. They are not isomorphic: one has one connected component and the other two. By contrast a six-node star has one degree-five node and five degree-one nodes, while the cycle has six degree-two nodes; 1-WL separates them on the first step.

The algorithm never declares two graphs isomorphic merely because histograms match. Different histograms do prove they are not isomorphic; otherwise the test has reached a limitation. If initial attributes distinguish nodes or edges, they must be included in refinement, and the equal-color counterexample no longer implies the same result for every labeling.

A signature contains the prior self color as well as neighbors. Without it, nodes with different histories could merge simply because their current neighborhoods match; that would no longer be the same refinement. Sorting neighbor colors represents the multiset in this example: it preserves repetitions and discards adjacency-list order. Order is a representation choice, not an intrinsic node property.

To run the test to stabilization, work on the union of the graphs with a shared signature table. Because the signature retains the previous color, each new class is contained in a previous class: class count never decreases. If an iteration does not increase that count, the partition no longer refines, even if specific color names continue changing. A finite set of nn nodes has at most nn classes, so only finitely many strict refinements can occur. This differs from stopping after a small fixed number of network layers.

The example also shows that “more layers” and “greater reach” do not mean distinguishing every structure. After one layer a node aggregates immediate neighbors; after two it can incorporate two-hop information. But in the regular pair every node still sees the same signature at any depth, so widening the radius does not reveal the difference between one and two components. Adding a component feature could distinguish them, but then extra information enters the model: it would not be the same comparison of unattributed graphs.

[ ]Comparable 1-WL signaturesBrowser
from collections import Counter
import hashlib

def wl_hash(graph, iterations):
    colors = ['0'] * len(graph)
    for _ in range(iterations):
        signatures = [(colors[i], tuple(sorted(colors[j] for j in graph[i]))) for i in range(len(graph))]
        colors = [hashlib.sha256(repr(s).encode('utf-8')).hexdigest() for s in signatures]
    return tuple(sorted(Counter(colors).items()))

cycle = [[1,5],[0,2],[1,3],[2,4],[3,5],[4,0]]
triangles = [[1,2],[0,2],[0,1],[4,5],[3,5],[3,4]]
star = [[1,2,3,4,5],[0],[0],[0],[0],[0]]
for k in range(5):
    print('paso',k,'ciclo = triángulos:',wl_hash(cycle,k)==wl_hash(triangles,k),
          'ciclo = estrella:',wl_hash(cycle,k)==wl_hash(star,k))

The hash makes separately calculated signatures comparable and tuple serialization is deterministic in this example. A finite digest can collide: a mathematical proof uses an injective signature encoding or a shared table of complete signatures, not an assumption that SHA-256 collisions are impossible. The program represents a simple undirected graph with adjacency lists; it does not handle attributes, parallel edges, or directed graphs.

GIN and the message-passing limit

In a message-passing network, nodes with the same initial representation and same multiset of neighbor representations receive the same update if all use the same functions and an invariant aggregation. By induction over layers, nodes with the same 1-WL color have the same representation. If two graphs have the same color histogram at every step, any invariant readout of those states produces the same result under these assumptions. The limitation is structural and does not disappear by training for more epochs.

GIN for molecular classification proposes a sum followed by an MLP:

hi(ℓ+1)=MLP⁡ℓ ⁣((1+ϵℓ)hi(ℓ)+∑j∈N(i)hj(ℓ)).\begin{aligned} \vb{h}_i^{(\ell+1)}={}&\operatorname{MLP}_\ell\!\bigl((1+\epsilon_\ell)\vb{h}_i^{(\ell)}\\ &+\sum_{j\in N(i)}\vb{h}_j^{(\ell)}\bigr). \end{aligned}

Xu and colleagues show conditions under which injective aggregation and readout reach 1-WL’s discriminative capacity. This is an existence claim under assumptions about domain and multisets, not a guarantee that any finite MLP, its learned weights, or raw vector sum are injective. A practical GIN can be less expressive; its name does not make it exceed the 1-WL limit.

A simple construction illustrates why sum can preserve a multiset if the encoding is chosen well first. Number colors c1,c2,…c_1,c_2,\ldots and consider finite multisets of at most MM elements. Choose integer base B>MB>M and represent ckc_k by B−kB^{-k}. The sum is ∑knkB−k\sum_k n_k B^{-k}, where nkn_k counts occurrences of the color. Since each digit satisfies 0≤nk<B0\le n_k<B and only finitely many digits are nonzero, different multisets give different sums. This is an existence proof on that domain, not a numerically stable proposal for many colors or a floating-point injectivity guarantee.

The argument can be read in two directions. The previous induction gives an upper bound: message-passing states do not separate nodes that 1-WL keeps in the same class. The injectivity result gives a construction capable of preserving 1-WL distinctions under its assumptions. The first direction does not depend on an optimizer finding good weights; the second does not say a particular run finds them. Thus a test on the graph pair verifies an expected invariance, while high molecular ROC-AUC measures something else: predictive capacity on attributed data from a specific distribution.

The coefficient ϵ\epsilon weights self state differently before adding neighbors. If fixed to zero, self state is added with coefficient one; if learned, it can change during training. Adjusting ϵ\epsilon cannot recover information an input encoding has already made identical. Nor is it correct to conclude that two graphs separated by 1-WL will always be separated by the trained implementation: the finite MLP may poorly approximate the useful function or training may not find it.

In molecules bonds have attributes. A variant incorporates a bond encoding in each message before summing, for example ReLU⁡(hj+eji)\operatorname{ReLU}(\vb{h}_j+\vb{e}_{ji}). The bond encoder is shared across edges and the atom encoder across nodes. The two-regular-graph test uses identical attributes on all nodes and bonds: the trained model receives no extra cue to break symmetry. This does not claim the synthetic graphs represent physically valid molecules.

In the laboratory implementation, each encoded bond contributes to its destination node; index_add_ sums those messages independently of edge order. Each atom’s attributes pass through AtomEncoder, each bond’s through BondEncoder, and the network applies five layers with learned ϵ\epsilon. Each layer is followed by batch normalization and dropout; finally a segmented sum and linear layer produce one logit per molecule. If an undirected edge is represented both ways, each endpoint receives its own message. Duplicating an edge would change the sum, so bond format and multiplicity are part of input.

Batch normalization introduces an experimental nuance. During training its statistics depend on nodes sharing a minibatch, so changing grouping can change updates even with the same molecule set. In evaluation it uses accumulated statistics and disables dropout. Thus the cycle-versus-triangles comparison is made in eval mode: comparing two runs with different random masks would not cleanly test the structural property.

The 1-WL bound proof assumes shared functions applied to the graph under comparison. Batch statistics during training can also depend on other graphs present, so do not extend a proof for an individual function uncritically to minibatches with different contexts. In evaluation stored statistics are fixed. Nor should normalization be blamed for test-label leakage if eval is used correctly: the problem would be recalculating its statistics with evaluation data or incorporating them into training.

For a batch with VV nodes, EE directed edges, and width dd, forming and summing messages costs order EdEd operations, while MLP linear layers cost order Vd2Vd^2. Message and node activations need order (E+V)d(E+V)d space, plus parameters and optimizer states. These orders describe the sparse-aggregation implementation; they do not require constructing a dense V×VV\times V matrix. Actual time depends on size distribution, hardware, and available reduction operations.

ogbg-molhiv: target and split

OGB describes 41127 molecular graphs; nodes are atoms with nine categorical attributes and edges are bonds with their own attributes. The binary task predicts activity related to inhibition of HIV replication. The official evaluator uses ROC-AUC: the probability that a randomly chosen positive receives a higher score than a negative, with averaging for ties. It evaluates ranking over all split examples, not mean minibatch ROC-AUC.

For example, if positives receive scores 0.80.8 and 0.40.4 and negatives 0.70.7 and 0.20.2, three of four positive-negative pairs are correctly ordered and ROC-AUC is 0.750.75. If minibatches contain (0.8,0.7)(0.8,0.7) and (0.4,0.2)(0.4,0.2) respectively, each has ROC-AUC 1 and their mean is 1: cross-minibatch comparisons were omitted. Concatenating labels and scores before calling the evaluator avoids that error and avoids attempting ROC-AUC on a batch containing one class only.

The official split groups by scaffold, a molecular structural framework, to separate families of structures. It may be more demanding than a random split when deployment requires prediction for new families, but does not guarantee a lower metric on every dataset or replace temporal or prospective evaluation. The choice depends on which molecules will be available in the application. Validation selects epoch and test is reserved for the final report; the best seed is not selected using test.

ROC-AUC sets no decision threshold and does not itself communicate how many false positives a laboratory will have. If a confirmatory assay is costly, also study precision and recall under a test budget and relevant prevalence. We retain ROC-AUC because it is the official benchmark metric; any additional operational analysis should use a threshold chosen outside test and describe the molecule population. Also check missing labels and classes in each split, since ROC-AUC needs at least one positive and one negative.

Loss and metric play different roles. Binary cross-entropy uses each available label to fit logits; ROC-AUC ranks positive and negative examples without requiring calibrated probability scores. A model can rank better while assigning unreliable probabilities. The finite-label mask prevents treating a missing value as a class, but does not correct bias if missingness systematically depends on molecule or activity.

Seed dispersion also needs careful interpretation. Five trainings share training, validation, and test data, so their five results are not five independent test sets. The mean summarizes that series of optimizations and the deviation shows variation on the same split. Studying sensitivity to molecular family requires other justified splits or external evaluation; using the same test to choose among many architectures can also overfit researcher decisions even if the optimizer never reads its labels.

The OGB leaderboard presents a GIN reference of 0.7558 ± 0.0140 test ROC-AUC, with 1885206 parameters. This is a published result from another configuration: it is not a result of this lesson’s run or a guaranteed threshold for every budget.

In our run with the official split, batch 128, width 128, and up to 100 epochs, five seeds gave test ROC-AUC 0.7503, 0.7650, 0.7883, 0.7531, and 0.6861: mean 0.7486 and sample deviation 0.0380. All five outputs for the six-cycle versus two-triangle pair matched exactly at the precision used. Seed 0 trained on CPU for 29 epochs and then on an RTX 3060; CUDA RNG was reinitialized at migration, so this is not equivalent to a wholly GPU trajectory. Other seeds used CUDA. Per-seed results record validation-selected epochs and migration.

The observed mean is near the published reference, but our dispersion is greater and configuration is not identical. That proximity does not establish statistical equivalence or turn a five-seed result into a guarantee for another split or molecule.

Full training

Download the GIN program with bonds. It requires PyTorch, PyTorch Geometric, and OGB; it uses official AtomEncoder and BondEncoder but explicitly implements message calculation, sum aggregation, and GIN update. Output saves mean and deviation over five seeds, validation-selected epoch, and cycle/triangles score difference with trained weights. The first run downloads the public dataset; --root allows cache reuse. Default budget is five seeds, up to 100 epochs and patience 20, with batches of 128 and 128 hidden channels.

python molhiv_gin.py --epochs 100 --seeds 5 --batch-size 128 --hidden 128 --output resultados-molhiv.json

The program saves a checkpoint at each epoch’s end with optimizer, RNG, and data and split hashes. To resume after interruption use the same command with --resume; if you change budget or dataset, start another run with another checkpoint file.

A fair comparison must state architectural, batch-size, and selection differences from the reference work. With five seeds on one scaffold split, deviation describes training variation under that split, not uncertainty across all future molecule sets. The regular graph pair is evaluated with the model in eval mode, so dropout introduces no random differences.

Exercises

Proof
Prove: An MPNN with shared functions and invariant readout does not distinguish graphs that 1-WL keeps indistinguishable, if initial attributes match initial colors.
0
Assume aggregation depends only on the message multiset.

Step 1 of 3. What follows if two nodes have the same color after the next refinement?

Quiz
If all nodes have scalar state 1, which readout recovers node count without an additional input?
Quiz
Which conclusion about a scaffold split is justified?
Code
Implement wl_hash(graph,iterations) for a simple undirected graph given as a list of neighbor lists. Return a sorted tuple of (signature, count) pairs with signatures comparable across runs and graphs, starting from a common color.
from collections import Counter
import hashlib
def wl_hash(graph,iterations):
  ...
Shift+Enter to run
Key idea
GIN uses symmetric aggregation to learn over graphs; with shared functions its structural distinctions are limited by 1-WL. Molecular evaluation requires attributes, split, and metric appropriate to the problem.