Graph neural networks: messages, symmetry and blind spots
图神经网络
Run weighted message passing, verify node-relabeling equivariance and construct two different graphs with identical embeddings.
graph-neural-networksStart with the problem
A molecule, a citation network and a transport map do not come with the regular pixel grid used by an image convolution. A graph neural network updates representations using the connections supplied by the graph. What counts as a neighbor, what an edge means and what is predicted must be specified before choosing an aggregation rule.
Gilmer and colleagues organize several graph models into message passing and readout phases. We use that framework for a small weighted directed graph. The parameters could be learned, but this chapter fixes them to inspect the forward computation and its structural limits; it does not report a trained classifier’s accuracy.
Definitions and derivation
Let each node have a row-vector feature hᵥ. Every edge is an ordered (source,destination) pair with scalar weight w. Transform source features with M, sum incoming messages, combine them with a separate self transformation S, and apply tanh:
The graph-level readout g sums node outputs. Node prediction can instead use each h′ᵥ directly. An isolated node still receives its self transformation; it does not disappear. Parallel edges contribute repeatedly, so deduplicating them changes this model. Updates are synchronous: all messages use the old features, not a mixture of already-updated and old nodes.
Node IDs are bookkeeping, not input features here. Relabeling every node with a permutation P, while relabeling the graph consistently, should only permute node outputs:
This is equivariance at node level and invariance after the sum readout. It follows because shared transformations and an order-independent sum commute with relabeling. Floating-point accumulation order can create tiny numerical differences without changing the algebraic statement.
An invariant aggregator can still lose information:
Raw sums cannot distinguish every multiset, and means can lose multiplicity. Xu and colleagues connect graph distinguishability to injective aggregation and the Weisfeiler–Lehman framework under stated assumptions. This does not mean that simply summing arbitrary raw features is injective.
For a stronger counterexample, compare a six-node cycle with two disconnected triangles. Give every node identical features and use the same rule in both graphs. Every node has two neighbors, so after one layer all nodes again share one value; induction repeats this at every layer. Both graphs have six nodes, so their sum readouts also agree. Connectedness differs, but this message-passing setup cannot detect it.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program first updates a three-node weighted chain and one isolated node. It then permutes node IDs and compares the two regular-graph counterexamples for four layers.
import numpy as np
M = np.array([[.5,-.25],[.1,.4]])
S = np.array([[.2,.3],[-.3,.2]])
def layer(features,edges,weights):
h,edges,weights = np.asarray(features,dtype=float),np.asarray(edges),np.asarray(weights,dtype=float)
if edges.size == 0:edges = np.empty((0,2),dtype=int)
if h.ndim != 2 or h.shape[1] != 2 or not 1 <= len(h) <= 16 or edges.ndim != 2 or edges.shape[1] != 2 or edges.dtype.kind not in 'iu' or len(edges)>256 or weights.shape != (len(edges),):
raise ValueError('Use small two-feature nodes and integer (source,destination) edges.')
if not np.isfinite(h).all() or not np.isfinite(weights).all() or (edges.size and (edges.min()<0 or edges.max()>=len(h))):
raise ValueError('Use finite data and valid node indices.')
messages = h@M; aggregate = np.zeros_like(h)
for (source,destination),weight in zip(edges,weights):aggregate[destination] += weight*messages[source]
return np.tanh(h@S+aggregate)
def example():
return np.array([[1,0],[0,1],[1,1],[.5,-.5]],dtype=float),np.array([[0,1],[1,0],[1,2],[2,1]]),np.array([1,1,2,2],dtype=float)
def permute(h,edges,order):
order = np.asarray(order,dtype=int); inverse = np.empty_like(order); inverse[order] = np.arange(len(order))
return h[order],inverse[edges]
def cycle_edges(groups):
result = []
for group in groups:
for i,node in enumerate(group):
nxt = group[(i+1)%len(group)]; result += [(node,nxt),(nxt,node)]
return np.array(result,dtype=int)
def graph_embedding(edges,steps=4):
h = np.ones((6,2)); weights = np.ones(len(edges))
for _ in range(steps):h = layer(h,edges,weights)
return h.sum(axis=0)
if __name__ == '__main__':
h,edges,weights = example(); out = layer(h,edges,weights)
order = [2,0,3,1]; ph,pe = permute(h,edges,order)
print('node updates',out.round(9).tolist(),'graph sum',out.sum(axis=0).round(9).tolist())
print('permutation discrepancy',float(np.max(np.abs(layer(ph,pe,weights)-out[order]))))
cycle = graph_embedding(cycle_edges([list(range(6))]))
triangles = graph_embedding(cycle_edges([[0,1,2],[3,4,5]]))
print('six-cycle / two-triangle embeddings',cycle.round(9).tolist(),triangles.round(9).tolist())
print('raw-feature sum collision',sum([0,2]),sum([1,1]))
Actual output:
node updates [[0.291312612, 0.604367777], [0.885351648, 0.244918662], [0.099667995, 0.861723159], [0.244918662, 0.049958375]] graph sum [1.521250918, 1.760967974]
permutation discrepancy 0.0
six-cycle / two-triangle embeddings [3.88884413, 1.056295672] [3.88884413, 1.056295672]
raw-feature sum collision 2 2
For node 1, the pre-tanh vector is (1.4,0.25), combining its self term with one message from node 0 and a double-weight message from node 2. The isolated node’s pre-tanh vector is (0.25,0.05). Relabeling discrepancy is zero in this run. The six-cycle and two-triangle graph sums coincide, as predicted by the structural argument.
For N nodes, E edges and d-dimensional features, precomputing shared linear messages costs O(Nd²), then aggregation costs O(Ed). An accumulator needs O(Nd) storage; it is not necessary to store every edge message separately. More general edge-dependent message networks can have different costs. Repeating L local layers expands information flow to at most L hops without extra global operations.
When the method fails
The supplied edges can be wrong, incomplete or inappropriate for the prediction target. Connecting test labels or future events into a training graph can create leakage even when node-feature arrays look clean. Data splitting must reflect whether the task predicts new labels on a known graph or generalizes to new nodes and graphs.
More layers do not automatically solve structural indistinguishability, and repeated aggregation may blur useful differences. Positional features, edge information, higher-order methods or global operations can change the expressive setting; the regular-graph proof applies to the explicitly described local model with identical initial features. Attention and normalized graph convolution are particular message choices, not universal cures for missing structural information.
Exercises with answers
- What does an isolated node receive in this model?
Answer 1: Its self transformation followed by tanh, with zero incoming aggregate.
- Why must edges be relabeled along with features?
Answer 2: Otherwise the permutation changes which entities are connected, rather than merely renaming the same graph.
- Can raw sum aggregation distinguish
{0,2}from{1,1}?
Answer 3: No. Both sum to two; richer feature maps need their own injectivity assumptions.
- Why do six-cycle and two-triangle embeddings remain equal here?
Answer 4: Identical initial features and degree two keep every node state equal at every layer, and both graphs have six nodes.
Sources and next steps
Gilmer’s physical pages 2–3 provide message/update/readout definitions and the readout’s permutation requirement. Xu’s physical page 4 supplies the scoped expressivity discussion and injectivity conditions. The weighted chain, relabeling tests and regular-graph proof are original teaching examples. Continue with graph convolutions and graph attention for two different neighborhood-weighting rules.
Make a prediction, then check
What does permutation equivariance require?
Learning objectives
- Verify node equivariance and graph-readout invariance.
- Construct a structural collision under explicit feature assumptions.
Prerequisites & connections
Explore related knowledge →References
- Neural Message Passing for Quantum Chemistry
Justin Gilmer; Samuel S. Schoenholz; Patrick F. Riley; Oriol Vinyals; George E. Dahl · 2017 - How Powerful are Graph Neural Networks? — arXiv v3
Keyulu Xu; Weihua Hu; Jure Leskovec; Stefanie Jegelka · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Bilingual SVGs generated with Matplotlib 3.9.1 from executed article functions: input-dependent state retention, regular-graph collisions and static/dynamic attention score rankings. Figures and samples are hash-bound. Parameters are illustrative, graph IDs are not features, and scores are not probabilities.
Source locations checked:
- Neural Message Passing for Quantum Chemistry · Physical pages 2–3, Section 2 Equations 1–3: weighted/local messages, updates and permutation-invariant graph readout.
- How Powerful are Graph Neural Networks? — arXiv v3 · Physical page 4, Lemma 2/Theorem 3 discussion: WL-limited aggregation models and injectivity assumptions, including countable-feature qualifications.
Related topics