Module contents
Lesson 13 of 30Advanced 115 min

Expressivity I: Weisfeiler-Leman, GIN and graph kernels

Study 1-WL color refinement, its expressivity bound for message passing, injective aggregation, GIN and WL graph kernels through proofs and measured experiments.

After this lesson you can

  • Implement and compare joint 1-WL refinement on graphs.
  • Prove the 1-WL bound for standard message-passing networks.
  • Explain injective multiset aggregation and the assumptions behind GIN.
  • Identify graphs indistinguishable by 1-WL and construct a WL subtree kernel.
  • Evaluate graph classifiers with nested validation and interpret their limits.

Before you start

What a message-passing network can distinguish

Two programs can have different logic yet produce the same representation in a network that only observes a graph and its features. If an architecture necessarily assigns the same representation to two inputs, no subsequent adjustment of its weights can separate them. This expressivity limit does not say how well a model generalizes or guarantee that training and finite data find suitable parameters.

The 1-WL color refinement assigns each node an initial color representing its discrete feature. At each round it replaces the color with an injective encoding of its previous color and the multiset of neighbor colors:

cv(t+1)=hash⁡ ⁣(cv(t),sort⁡{cu(t):u∈N(v)}).c_v^{(t+1)}=\operatorname{hash}\!\left(c_v^{(t)},\operatorname{sort}\{c_u^{(t)}:u\in N(v)\}\right).

The hash represents equality of signatures and must not introduce accidental collisions. To compare graphs, use a shared dictionary, equivalent to refining their disjoint union. If color histograms differ in any round, the graphs are not isomorphic. If they match even after stabilization, 1-WL has not separated them: that does not prove isomorphism. The partition stabilizes when no class splits; color names can change even when the partition no longer does. Every round that changes the partition adds at least one class, so in a finite graph of nn nodes there are at most n−1n-1 strict splits from one initial class.

The signature retains the previous self color as well as neighbor colors. Thus a class never merges with a previously distinct class, even if identifiers are renumbered. Starting without labels, the first round groups by degree; later rounds distinguish increasingly deep configurations. A sorted signature exactly represents a finite multiset: omitting sorting would make equivalent lists depend on incidental edge order.

A direct implementation traverses edges and sorts colors in each neighborhood; its cost depends on degrees and the representation of signatures. More efficient partition refinement algorithms exist, but an operation called hash is not free and must not be treated as an equality test if it allows collisions. The exercise’s nested signatures avoid inconsistent identifiers across graphs at the cost of representations that can grow with depth. In a large system each signature can be interned in a shared dictionary, retaining correspondences between rounds.

InteractiveColor race between two graphs
Six-node cyclec01c02c03c04c05c06Two trianglesc01c02c03c04c05c06

Outer numbers identify nodes for editing edges; c indicates color. Signature: previous color and sorted list of neighbor colors. Different histograms prove non-isomorphism; equal ones do not prove isomorphism. Positions are not features.

Pair
0
Histogram A0:6
Histogram B0:6
Does WL distinguish?Not in this iteration
Signatures and colors are recomputed jointly for both graphs. Edges and catalog labels are explicit; positions only aid reading.

With identical initial features, all nodes of an dd-regular graph always receive the same color. A cycle of six nodes and two triangles have six nodes of degree two and identical histograms in every round, although one is connected and the other is not. They also differ in triangle count. The example shows 1-WL cannot compute those properties on all graphs; it does not claim that it can never recognize them in particular cases. Initial colors, edge labels and additional features can change the result.

The message-passing bound

The 1-WL bound for MPNNs is proved by induction when initial states are shared functions of initial color and messages and updates are shared functions with order-invariant aggregation. If two nodes have the same color in round t+1t+1, they had the same color in tt and the same neighbor colors with multiplicity. By the induction hypothesis their own states and multisets of neighbor states match; shared functions produce the same aggregated message and next state. Begin with equality of initial colors and repeat for each layer.

For graph classification, an invariant readout over node states likewise does not separate two equal color histograms under the same assumptions. Unique identifiers, edge features not included in refinement, global connections or higher-order operators change the available information; the conclusion cannot be applied without including them in the analysis. The bound concerns possibility of separation, not expected accuracy, numerical stability or generalization.

This bound also works when a message function is complex: if it receives the same own and neighbor states, it must produce the same result for the induction’s correspondences. Depth determines how many refinement rounds can be imitated. Adding layers may reveal more distant differences, but no number of standard layers breaks the equivalence of a pair that 1-WL maintains indefinitely. Theoretical results assume exact equality; on hardware a tiny numerical difference alone is not robust separation.

Multisets and injectivity

Mean and maximum lose multiplicity information. For example, {a,b}\{a,b\} and {a,a,b,b}\{a,a,b,b\} have the same mean for any fixed encoding of aa and bb, and {a,b}\{a,b\} and {a,a,b}\{a,a,b\} share a maximum. Summing arbitrary values is not always injective either: 1+1=21+1=2.

InteractiveWhat each aggregator sees

A: ab

B: aabb

They differ. Matches: mean, maximum.

1
1
2
2
Sum A / B3 / 6
Mean A / B1.50 / 1.50
Maximum A / B2 / 2
Two multisets of tokens with values a=1 and b=2. All three operations are computed directly and collisions are highlighted.

Injective multiset aggregation requires choosing a suitable encoding. For a countable domain with indices x=1,2,…x=1,2,\ldots and multisets of size at most MM, take an integer base B>MB>M and f(x)=B−xf(x)=B^{-x}. The sum records multiplicities as digits smaller than BB: two distinct finite multisets differ at the first index where a digit changes, and that difference cannot be canceled by later indices. This construction is mathematical: in floating point small powers may disappear and a finite network does not automatically obtain exact injectivity.

In GIN, the update has the form

hv(t+1)=MLP⁡t ⁣((1+ϵt)hv(t)+∑u∈N(v)hu(t)).h_v^{(t+1)}=\operatorname{MLP}_t\!\left((1+\epsilon_t)h_v^{(t)}+\sum_{u\in N(v)}h_u^{(t)}\right).

The term ϵ\epsilon can distinguish the self state from certain neighbor combinations; it can be fixed or learned. The Graph Isomorphism Network theorem requires sufficiently injective functions and readout and assumptions about the domain. A particular MLP, seed or short training run does not guarantee achieving this. Concatenating sum readouts from multiple layers preserves information at different depths if the rest of the model can use it.

The distinction between a sum and an injective sum is essential. With one scalar per node, directly summing ordinary values can confuse distinct sets. The theoretical argument first constructs a transformation of each element and then sums; a trained MLP attempts to approximate a useful function on the observed domain. The sum is also sensitive to the number of elements: duplicating a multiset doubles its sum, while its mean stays the same. That sensitivity may be needed for counting, but also changes activation scale as graph size varies.

Combining the central node and its neighborhood needs to distinguish two roles: the self state and elements of the neighbor multiset. The factor 1+ϵ1+\epsilon separates these contributions in the GIN construction under suitable assumptions; choosing an arbitrary value does not make the layer injective on all data. A sum readout can count nodes if each contributes a constant, while a mean readout of constants does not distinguish sizes. These choices affect the task before looking at a test metric.

InteractiveGIN versus GCN on difficult pairs
AggregationInitial signal A / BProbability A / B
GIN-like sum9.000 / 7.3330.001 / 0.999
GCN normalization1.000 / 0.9930.500 / 0.500
SAGE-like mean4.000 / 4.0000.500 / 0.500

Before training the signal is centered using the pair mean and scaled by the maximum of 1 and the largest deviation. Probability is computed on the same two examples: it does not measure generalization. Identical signals cannot be separated with this parameterization.

Pair
100
TargetsA: 0 · B: 1
Two scalar layers and a logistic classifier train their weights on the displayed pair. This is a minimal control, not a benchmark of full networks.

In the simulation, the GIN-like sum signal, GCN normalization and SAGE-like mean are computed with two scalar layers and a mean readout. Each layer has a shared scalar weight and is trained along with the classifier weight and bias. The initial signal is centered using the pair’s mean and scaled by the maximum of one and the largest deviation to facilitate fitting; this computation uses both examples and is not an evaluation protocol. The table shows the uncentered signal and probabilities after the chosen steps. A different signal allows a threshold to separate the pair, but the optimizer may need more steps; an identical signal cannot separate the pair with this parameterization. The two regular six-node graphs remain indistinguishable in all three controls. Do not extrapolate an observation from this example to every parameterization or to generalization outside its two examples.

Confusable graphs and kernels

Families indistinguishable by 1-WL include non-isomorphic graphs with the same number of nodes and the same regular degree, starting from uniform colors. Connectivity or triangle counts cannot generally be inferred from their histograms. The constructions of Cai, Fürer and Immerman show more systematic limitations of fixed-order refinements; verifying a particular pair requires specifying its construction, not merely claiming two drawings look different.

Also C8C_8 and two disjoint copies of C4C_4 have eight nodes of degree two and are indistinguishable by uniform 1-WL. The second contains cycles of length four and the first does not. Therefore a standard MPNN under the same assumptions cannot decide that property for all graphs. An MPNN with an input that already encodes triangles, distances or identifiers has additional information: the bound must be applied to refinement with those same features.

The connection with logic and graph networks offers another perspective: on finite graphs, 1-WL equivalence is related to properties expressible in two-variable logic with counting quantifiers. This characterizes which distinctions are available, not a way to automatically derive a network’s error. Higher-order refinements consider tuples and can separate some pairs 1-WL confuses, but increase the number of states and cost; order, initialization and symmetries must be specified when comparing them.

The WL subtree kernel of Shervashidze and colleagues concatenates the color histograms of all rounds into a vector ϕ(G)\phi(G) and computes K(G,H)=ϕ(G)Tϕ(H)K(G,H)=\phi(G)^\mathsf T\phi(H). It is positive semidefinite because it is an explicit inner product. Colors need a consistent dictionary between training and evaluation; an unseen test signature can be added as a new coordinate with zero in training, without using test labels. Counting these patterns differs from counting arbitrary induced subtrees.

Other kernels compare walks or graphlets with different definitions and costs. A WL kernel plus an SVM is a useful classical baseline, not an automatic substitute for a network. On small benchmarks hyperparameter selection and splitting can dominate model differences. Nested cross-validation selects hyperparameters in internal folds of each outer training set and reserves the outer fold for evaluation once; do not choose the variant with the best outer result and present that same figure as an unbiased evaluation.

Normalizing the kernel by K(G,G)K(H,H)\sqrt{K(G,G)K(H,H)} removes the global scale of count vectors when norms are positive. That changes similarity and can reduce size information, much like feature normalization. Normalization uses the graphs’ own norms without using their labels. In the full space, a new evaluation signature contributes to its norm but has no matching training coordinate. A vectorizer that discards coordinates outside the training vocabulary also excludes them from that norm: this is another convention that must be documented.

MUTAG and PROTEINS node labels are discrete categories. In other tasks continuous features require an encoding or discretization whose fit must remain inside each fold’s training set. Including edge features requires extending the signature and using exactly the same convention in the comparator; the following experiments use structure and node labels without bond categories. Do not confuse two kernels with different input information, even if both are called WL.

Lab: refinement from scratch

This page’s runtime is independent of the previous lesson’s. The message-passing framework is available to download mini_mp.py; the GIN cell will reuse its gather and scatter_sum operations with the same source/destination convention.

[ ]Joint 1-WL refinementBrowser
import numpy as np
def wl(graphs, rounds):
    # Cada entrada es (n, aristas no dirigidas, colores iniciales).
    neighbors=[]; colors=[]
    for n,edges,initial in graphs:
        adj=[[] for _ in range(n)]
        for u,v in edges: adj[u].append(v); adj[v].append(u)
        neighbors.append(adj); colors.append(list(initial))
    history=[colors]
    for _ in range(rounds):
        signatures=[[(c[v],tuple(sorted(c[u] for u in adj[v]))) for v in range(len(c))] for c,adj in zip(colors,neighbors)]
        keys=sorted(set(s for row in signatures for s in row)); mapping={s:i for i,s in enumerate(keys)}
        colors=[[mapping[s] for s in row] for row in signatures]; history.append(colors)
    return history
cycle=(6,[(0,1),(1,2),(2,3),(3,4),(4,5),(5,0)],[0]*6)
triangles=(6,[(0,1),(1,2),(2,0),(3,4),(4,5),(5,3)],[0]*6)
path=(9,[(i,i+1) for i in range(8)],[0]*9)
for t,colors in enumerate(wl([cycle,triangles],4)):
    print('ronda',t,'ciclo',np.bincount(colors[0]).tolist(),'triángulos',np.bincount(colors[1]).tolist())
path_history=wl([path],5)
print('camino de 9: clases por ronda',[len(set(c[0])) for c in path_history])

For the nine-node path, 1, 2, 3, 4 and 5 classes appear in rounds 0 to 4. Round 5 confirms the partition no longer splits; depending on convention, this is described as four effective refinement rounds or five rounds executed to detect stabilization. Equivalence is checked between pairs of nodes, not by comparing color numbers that can be renamed.

The following generator constructs two CFI graphs over K4K_4. Each base vertex has four internal nodes corresponding to even selections of its three edges and two ports per edge. Corresponding ports of each edge are connected; one version swaps the two ends of one edge. Both graphs have 40 nodes and are 3-regular. A local isomorphism test verifies they are not isomorphic; 1-WL with uniform colors does not distinguish them because they are regular.

[ ]A concrete CFI pairBrowser
import itertools
def cfi(twist):
    base=list(itertools.combinations(range(4),2)); ports={}; edges=[]; count=0
    for v in range(4):
        neighbors=[u for u in range(4) if u!=v]
        for u in neighbors:
            for bit in (0,1): ports[v,u,bit]=count; count+=1
        for bits in itertools.product((0,1),repeat=3):
            if sum(bits)%2: continue
            internal=count; count+=1
            edges.extend((internal,ports[v,u,bit]) for u,bit in zip(neighbors,bits))
    for ei,(u,v) in enumerate(base):
        for bit in (0,1): edges.append((ports[u,v,bit],ports[v,u,bit ^ int(twist and ei==0)]))
    return count,edges,[0]*count
cfi_a,cfi_b=cfi(False),cfi(True)
for graph in (cfi_a,cfi_b):
    degree=np.bincount(np.asarray(graph[1]).ravel(),minlength=graph[0]); assert set(degree)=={3}
print('nodos y aristas',cfi_a[0],len(cfi_a[1])); print('colores conjuntos',[len(set(c[0]+c[1])) for c in wl([cfi_a,cfi_b],4)])

A direct kernel implementation adds a counter per round and color to the vector. In the example the vocabulary is built over the displayed set of graphs because only its Gram matrix is examined. In a separate predictive evaluation, learn the vocabulary in each training fold and transform the validation or test fold using that same vocabulary.

[ ]WL subtree kernelBrowser
def wl_features(graphs,rounds):
    history=wl(graphs,rounds); features=[]
    for i in range(len(graphs)):
        counts={}
        for t,colors in enumerate(history):
            for color in colors[i]: counts[t,color]=counts.get((t,color),0)+1
        features.append(counts)
    keys=sorted(set(k for row in features for k in row)); X=np.array([[row.get(k,0) for k in keys] for row in features],float)
    return X
features=wl_features([cycle,triangles,path],3); kernel=features@features.T
v=np.array([1.,-1.,.5]); quadratic=float(v@kernel@v)
print('Gram',kernel.astype(int).tolist(),'forma cuadrática',round(quadratic,6))
assert np.allclose(features[0],features[1]); assert np.isclose(quadratic,np.sum((features.T@v)**2))

This toy SVM is fitted and evaluated on the same three graphs, only to check the connection between the kernel and a classifier. The cycle and the two triangles receive the same label because they have exactly the same WL vector; they are not independent test data.

[ ]SVM on the calculated Gram matrixBrowser
from sklearn.svm import SVC
labels=np.array([0,0,1]); svm=SVC(kernel='precomputed',C=1).fit(kernel,labels)
print('predicciones de entrenamiento',svm.predict(kernel).tolist(),'soportes',svm.support_.tolist())
assert svm.predict(kernel)[0]==svm.predict(kernel)[1]

The following implementation uses gather and scatter_sum with the same semantics as the downloadable module. The MLP is a single transformation with ReLU to keep the example small; it does not claim to demonstrate injectivity. Two layers and a sum readout are compared on the six-node graphs, showing that the regular pair produces equal vectors for the same parameters.

[ ]NumPy GIN with message-passing primitivesBrowser
def gather(x,index): return np.asarray(x)[np.asarray(index,dtype=np.int64)]
def scatter_sum(messages,dst,n):
    out=np.zeros((n,messages.shape[1]),dtype=messages.dtype); np.add.at(out,dst,messages); return out
def gin_graph(graph,weights,epsilon=0.):
    n,edges,_=graph
    directed=np.asarray(edges+[(v,u) for u,v in edges],dtype=int).T
    x=np.ones((n,1)); pooled=[x.sum(axis=0)]
    for W,b in weights:
        messages=gather(x,directed[0]); agg=scatter_sum(messages,directed[1],n)
        x=np.maximum(((1+epsilon)*x+agg)@W+b,0); pooled.append(x.sum(axis=0))
    return np.concatenate(pooled)
weights=[(np.array([[.3,.8]]),np.array([.1,.2])),(np.array([[.4,.1],[.2,.5]]),np.array([.1,.1]))]
z1=gin_graph(cycle,weights); z2=gin_graph(triangles,weights)
print('GIN ciclo',z1.round(4).tolist(),'dos triángulos',z2.round(4).tolist())
assert np.allclose(z1,z2)

MUTAG and PROTEINS in the browser

The following evaluation uses the full MUTAG and PROTEINS graphs, exported from TU downloads with prepare_tu.py. Simple edges and node categories are retained; edge labels are omitted. The files are MUTAG and PROTEINS. Nested validation in this test uses two outer and two inner folds, with C∈{0.1,1}C\in\{0.1,1\}. It is split into cells to keep each computation within the browser budget. Run the cells in order.

Nested signatures become deterministic strings and represent histograms of three rounds, including the initial one. DictVectorizer fits its vocabulary on each inner or outer training set and discards unknown signatures when transforming validation or test; rows are then normalized and a linear SVM is trained. This convention is not identical to every possible kernel normalization: unknown features are also excluded from the norm. Outer folds do not participate in choosing CC.

[ ]Prepare signatures and nested validationBrowser
import numpy as np
from collections import Counter
from pyodide.http import pyfetch
from js import globalThis
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import normalize
from sklearn.svm import LinearSVC
try: origin=str(globalThis.location.origin)
except (AttributeError,TypeError): origin='http://localhost:4321'
async def load_tu(name):
    response=await pyfetch(origin+'/downloads/m25/l13/'+name.lower()+'.json')
    if not response.ok: raise RuntimeError('No se pudo descargar '+name)
    return await response.json()
def signatures(g):
    adj=[[] for _ in range(g['n'])]
    for u,v in g['edges']: adj[u].append(v);adj[v].append(u)
    colors=list(g['x']); out=Counter()
    for t in range(3):
        out.update(str((t,c)) for c in colors)
        colors=[(colors[v],tuple(sorted(colors[u] for u in adj[v]))) for v in range(g['n'])]
    return dict(out)
def prepare(graphs):
    return [signatures(g) for g in graphs],np.array([g['y'] for g in graphs])
def outer_fold(rows,y,fold):
    idx=np.arange(len(y)); outer=list(StratifiedKFold(2,shuffle=True,random_state=13).split(idx,y)); train,test=outer[fold]
    inner=StratifiedKFold(2,shuffle=True,random_state=14+fold); scores={.1:[],1.:[]}
    for tr,va in inner.split(train,y[train]):
        train_ids=train[tr]; val_ids=train[va]; vec=DictVectorizer()
        Xtr=normalize(vec.fit_transform([rows[i] for i in train_ids])); Xva=normalize(vec.transform([rows[i] for i in val_ids]))
        for c in scores:
            model=LinearSVC(C=c,random_state=13).fit(Xtr,y[train_ids]); scores[c].append(model.score(Xva,y[val_ids]))
    chosen=max(scores,key=lambda c:(np.mean(scores[c]),-c)); vec=DictVectorizer()
    Xtr=normalize(vec.fit_transform([rows[i] for i in train])); Xte=normalize(vec.transform([rows[i] for i in test]))
    model=LinearSVC(C=chosen,random_state=13).fit(Xtr,y[train]); score=model.score(Xte,y[test])
    print('fold',fold+1,'C',chosen,'exactitud',round(float(score),4)); return float(score)
[ ]Load TU dataBrowser
mutag=await load_tu('MUTAG'); proteins=await load_tu('PROTEINS')
print('grafos',len(mutag),len(proteins))
[ ]MUTAG signaturesBrowser
fm,ym=prepare(mutag); print('MUTAG',len(fm),'ejemplos')
[ ]Two MUTAG outer foldsBrowser
sm=[outer_fold(fm,ym,i) for i in range(2)]; print('MUTAG media',round(float(np.mean(sm)),4))
[ ]PROTEINS signaturesBrowser
fp,yp=prepare(proteins); print('PROTEINS',len(fp),'ejemplos')
[ ]First PROTEINS outer foldBrowser
sp=[outer_fold(fp,yp,0)]
[ ]Second PROTEINS outer foldBrowser
sp.append(outer_fold(fp,yp,1)); print('PROTEINS media',round(float(np.mean(sp)),4))

In the reproducible run with seed 13, MUTAG outer accuracies were 0.7979 and 0.7660, mean 0.7819; PROTEINS accuracies were 0.7145 and 0.7392, mean 0.7269. Both folds selected C=1C=1 in each dataset. Two folds are a quick check and their mean is not a benchmark estimate. The next local experiment uses more outer folds and another normalization, so the same figures should not be expected.

Local checks and nested evaluation

This cell requires NetworkX and rebuilds the CFI pair in an independent local session. It then enumerates all labeled simple 3-regular graphs of eight nodes by searching remaining degrees and groups them by isomorphism. This is a finite enumeration, not a proof based on a hand-selected list. The six classes have equal 1-WL histograms when all initial colors match.

[ ]CFI and eight-node 3-regular graphsLocal GPU
import itertools, networkx as nx
def cfi_graph(twist):
    base=list(itertools.combinations(range(4),2)); ports={}; g=nx.Graph()
    for v in range(4):
        neighbors=[u for u in range(4) if u!=v]
        for u in neighbors:
            for bit in (0,1): ports[v,u,bit]=('port',v,u,bit); g.add_node(ports[v,u,bit])
        for bits in itertools.product((0,1),repeat=3):
            if sum(bits)%2: continue
            node=('inner',v,bits); g.add_node(node)
            for u,bit in zip(neighbors,bits): g.add_edge(node,ports[v,u,bit])
    for i,(u,v) in enumerate(base):
        for bit in (0,1): g.add_edge(ports[u,v,bit],ports[v,u,bit ^ int(twist and i==0)])
    return g
a,b=cfi_graph(False),cfi_graph(True)
print('CFI: nodos/aristas',a.number_of_nodes(),a.number_of_edges(),'isomorfos',nx.is_isomorphic(a,b))
assert not nx.is_isomorphic(a,b) and set(dict(a.degree()).values())=={3} and set(dict(b.degree()).values())=={3}
def regular8():
    remaining=[3]*8; edges=[]
    def generate(v):
        while v<8 and remaining[v]==0: v+=1
        if v==8:
            yield tuple(edges); return
        candidates=[u for u in range(v+1,8) if remaining[u]>0]; need=remaining[v]
        for group in itertools.combinations(candidates,need):
            remaining[v]=0
            for u in group: remaining[u]-=1; edges.append((v,u))
            yield from generate(v+1)
            for u in reversed(group): remaining[u]+=1; edges.pop()
            remaining[v]=need
    yield from generate(0)
representatives=[]; count=0
for edges in regular8():
    count+=1; g=nx.Graph(); g.add_nodes_from(range(8)); g.add_edges_from(edges)
    if not any(nx.is_isomorphic(g,h) for h in representatives): representatives.append(g)
print('3-regulares: etiquetados',count,'clases no isomorfas',len(representatives))
assert count==19355 and len(representatives)==6
def wl_hash(edge_index,x,iterations):
    adj=[[] for _ in x]
    for src,dst in edge_index.T: adj[int(dst)].append(int(src))
    colors=list(x); result=[]
    for _ in range(iterations+1):
        counts={}
        for color in colors: counts[color]=counts.get(color,0)+1
        result.append(tuple(sorted(counts.items())))
        colors=[(colors[v],tuple(sorted(colors[u] for u in adj[v]))) for v in range(len(x))]
    return tuple(result)
import numpy as np
hashes=[]
for g in representatives:
    edges=list(g.edges()); directed=np.array(edges+[(v,u) for u,v in edges],int).T
    hashes.append(wl_hash(directed,[0]*8,4))
assert len(set(hashes))==1
print('hashes WL distintos entre las seis clases',len(set(hashes)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

This local cell directly compares the normalized Gram matrix calculated with histograms and GraKeL on ten MUTAG graphs. The folder can be chosen with ORYON_TU_ROOT; by default PyG downloads the data to dataset. The same collection builds both Gram matrices as an implementation check, not a predictive evaluation.

[ ]Compare custom kernel with GraKeLLocal GPU
import os, numpy as np, torch
from torch_geometric.datasets import TUDataset
from torch_geometric.data.data import Data,DataEdgeAttr,DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from grakel import GraphKernel
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    dataset=TUDataset(os.environ.get('ORYON_TU_ROOT','dataset'),'MUTAG')
graphs=[dataset[i] for i in range(10)]; colors=[[int(row.argmax()) for row in g.x] for g in graphs]; initial=[x[:] for x in colors]; adj=[]
for g in graphs:
    a=[set() for _ in range(g.num_nodes)]
    for u,v in g.edge_index.t().tolist(): a[v].add(u)
    adj.append(a)
features=[{} for _ in graphs]
for t in range(4):
    for i,row in enumerate(colors):
        for color in row: features[i][t,color]=features[i].get((t,color),0)+1
    signatures=[[(colors[i][v],tuple(sorted(colors[i][u] for u in adj[i][v]))) for v in range(len(colors[i]))] for i in range(len(graphs))]
    keys=sorted(set(s for row in signatures for s in row)); mapping={s:i for i,s in enumerate(keys)}
    colors=[[mapping[s] for s in row] for row in signatures]
keys=sorted(set(k for row in features for k in row)); X=np.array([[d.get(k,0) for k in keys] for d in features],float)
K=X@X.T; K/=np.sqrt(np.diag(K)[:,None]*np.diag(K)[None,:])
inputs=[[{i:{j:1 for j in neighbors} for i,neighbors in enumerate(a)},{i:c for i,c in enumerate(initial[k])}] for k,a in enumerate(adj)]
other=GraphKernel(kernel=[{'name':'weisfeiler_lehman','n_iter':3},{'name':'vertex_histogram'}],normalize=True).fit_transform(inputs)
print('diferencia máxima de Gram',float(np.abs(K-other).max())); assert np.allclose(K,other)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The maximum observed difference was zero. The full program download wl_nested.py runs GraKeL’s WL kernel and SVM with ten stratified outer folds, three inner folds and CC selection in each fold; the dictionary and kernel normalization are fitted only on inner or outer training data as appropriate. It requires PyTorch, PyG, GraKeL and scikit-learn. PyG manages the TU download and --root defines its data folder.

python wl_nested.py --root dataset --dataset MUTAG
python wl_nested.py --root dataset --dataset PROTEINS

In our run, MUTAG had 188 graphs and mean outer accuracy 0.86637 with population deviation across folds 0.07780; PROTEINS had 1113 graphs and 0.73583 with deviation 0.03781. The seed was 13, initial colors are node categories and candidate CC parameters are 0.01, 0.1, 1 and 10. These are ten folds of one split, not ten independent datasets. The deviation describes those folds and is not a confidence interval. Test categories are not used to fit the dictionary or select CC.

The program download gnn_nested.py compares GIN, GCN, SAGE and DeepSets with the same outer TU split; it selects learning rate in two inner folds. For molhiv it uses the official scaffold split and selects between two rates using validation for each seed. By default the code runs one epoch per candidate to keep the test economical: this respects data separation, but is a very short training diagnostic, not a reproduction of the budgets of Errica et al.. On molhiv it uses atom categories and omits bonds in these baselines. --epochs can be increased while retaining the same protocol without using test for selection.

python gnn_nested.py --root dataset --dataset MUTAG --model GIN
python gnn_nested.py --root dataset --dataset PROTEINS --model GCN
python gnn_nested.py --root dataset --dataset ogbg-molhiv --model SAGE

TU returns accuracy; molhiv returns ROC-AUC. Change --model among GIN, GCN, SAGE and DeepSets. The outer folds are the same for all four architectures, while inner selection and training are repeated separately. In OGB the ten repetitions share the same split and vary initialization and training order; thus deviation across seeds does not measure uncertainty over new splits.

In the run with one epoch per candidate, mean accuracies and population deviations across the ten outer folds were as follows:

ModelMUTAGPROTEINS
GIN0.66491 ± 0.022810.60734 ± 0.07897
GCN0.66491 ± 0.022810.59842 ± 0.01714
SAGE0.66491 ± 0.022810.59837 ± 0.00653
DeepSets0.66491 ± 0.022810.59566 ± 0.00895
WL + SVM0.86637 ± 0.077800.73583 ± 0.03781

In this test the four MUTAG networks essentially reached the majority-class frequency of each fold. The kernel uses three inner folds and the networks two, so neither budgets nor inner selections are identical. The results check the pipeline and show why one epoch does not permit a quality comparison; they do not justify a general ranking of model families.

For a WL baseline on molhiv without constructing a quadratic matrix of all pairs, download wl_molhiv.py. It extracts sparse histograms of three rounds, fits the vocabulary on training and trains a linear SVM; it selects between two CC values on validation and evaluates on test. It uses all atom categories as initial labels, without bond features. Signatures are encoded with deterministic SHA-256, whose collisions are theoretically possible; the vectorizer discards unknown validation and test signatures before normalization. Seeds affect only solver fitting and do not create new splits.

In the run with ten seeds and 92 937 training features, C=1C=1 was selected in all of them; mean test ROC-AUC was 0.78790 and population deviation across seeds rounded to 0.00000. Validation ROC-AUC was 0.78947. Since the same split is retained and the solver barely changes, this deviation does not estimate variability across datasets or scaffold splits.

The four networks also completed ten seeds on the same molhiv scaffold split, with one epoch per candidate and rate selection exclusively on validation:

ModelMean test ROC-AUCPopulation deviation across seeds
GIN0.344060.06592
GCN0.637600.01897
SAGE0.639660.02654
DeepSets0.645240.01513
WL + linear SVM0.787900.00000

These results correspond to the short run described, not converged models. The networks use atom categories and omit bond features; the WL baseline uses all categories as labels. Optimization budgets differ, so the table verifies the runs and their limits without establishing a general ranking among architectures.

python wl_molhiv.py --root dataset --repetitions 10

Exercises

Proof
Prove: Prove by induction that nodes with the same 1-WL color in round t have the same state after t layers of a shared MPNN.
0
Initial states depend only on initial colors; aggregation is order invariant.

Step 1 of 3. What is the base case?

Proof
Prove: Construct a scalar encoding whose sum is injective for multisets of natural numbers of size at most M.
0
Choose an integer base B greater than M and f(x)=B raised to minus x.

Step 1 of 2. What does each digit of the sum represent?

Numeric
Starting from a single color on a 9-node path, how many rounds produce a strict split before stabilization?
Quiz
For unlabeled graphs of variable size, what pair of properties can a suitable MPNN with sum readout obtain, even though it cannot generally decide triangles or connectivity?
Code
Implement wl_hash(edge_index, x, iterations) for an undirected graph: edge_index contains both directions, x contains integer initial colors. In each round sort the neighbor multiset and use deterministic nested signatures. Return histograms as sorted tuples of (signature, multiplicity) pairs, comparable across graphs without local dictionaries.
import numpy as np
def wl_hash(edge_index,x,iterations):
  pass
Shift+Enter to run

Key ideas

Key idea
1-WL bounds the separation of standard MPNNs; injective aggregation and readout under suitable assumptions attain that bound, without guaranteeing training or generalization.