Lesson 4.6 — Graph Neural Networks
Previous lesson · 4.5 Vision Transformer · Course overview · Next lesson · 4.7 State Space Sequence Models
Graph Representation · From Grids to Topology
A graph G = (V, E) has a node set and an edge set. A robot can use rigid links as nodes and joints as edges. A spring–mass system uses masses and springs. A sensor network can use physical or communication links. The topology specifies which objects interact and can vary across examples.
In this lesson, adjacency entry A[i, j] marks a message from node j to node i. The adjacency of an undirected graph is symmetric. A directed graph can have an asymmetric adjacency matrix. A sparse edge index stores source and destination rows. Each undirected edge usually contributes two directed messages. Add self-loops once when the layer calls for them. Renumbering nodes preserves the physical graph when features and edges are renumbered together.
Graph & Adjacency Matrix
Node, Edge & Graph Features
Node features can represent position, velocity, or mass. Edge features can represent relative displacement, stiffness, or damping. Graph-level features can describe a shared temperature or operating mode. Node IDs identify rows, while features describe the nodes and interactions. Define the sign of relative displacement using the message direction.
Batch graphs with a block-diagonal adjacency matrix or with a concatenated edge index and a graph ID for each node. Both layouts keep messages within their own graph. A dense batch with shape (B, N, D) is convenient when graphs share a node count. A graph can also have node-level, edge-level, or graph-level targets with corresponding output heads.
Node Feature Inspector
| Incoming node | Source position | Target position | Displacement |
|---|---|---|---|
| v1 | 0.3 | 1 | -0.7 |
| v3 | 0.8 | 1 | -0.2 |
| v5 | 0.5 | 1 | -0.5 |
Message Passing · Message → Aggregate → Update
One layer computes a message on each edge, aggregates the messages received by each node, and updates its representation. The message and update functions share parameters across the graph. Sum, mean, and max produce the same aggregate regardless of neighbor ordering.

Read every row as a prediction at C. The filled nodes mark original inputs that could influence it. In the first update, C reads the old features of B and D along with its own. B is simultaneously reading A, but C receives B’s updated representation only in the second update. Updating nodes in place would allow information to travel a different distance depending on the loop order.
There is also a physical reason to choose a particular aggregation. Let be the displacement of mass from equilibrium in a one-dimensional spring chain with identical stiffness . The force message from B to C is , and the one from D is . Pull both neighbors equally to the right while holding C fixed and the two forces add. Move them equally far in opposite directions and the forces cancel. A sum has exactly this behavior. A mean divides by the number of neighbors and needs that count to recover total force for varying degrees.
Each layer propagates information at most one edge. After L layers a node can depend on its L-hop neighborhood, though the model can discard some information. Mean aggregation normalizes by the number of neighbors. Sum aggregation preserves additive quantities, such as the total contribution of several springs. An isolated node can use a zero aggregate or receive a message through a self-loop.
Inspect the messages received by a selected node
Message Passing Animation
Graph Convolutional Networks · Degree Normalization
A standard GCN on an undirected graph adds self-loops and uses symmetrically normalized adjacency to aggregate features before a shared linear map and activation. The degree factors adjust the scale of contributions from highly connected nodes. Symmetric normalization can produce row sums different from one.
For a binary adjacency, an active edge has weight 1 / √(dᵢdⱼ) under symmetric normalization. If self-loops are disabled, define the inverse square root of a zero degree as zero for isolated nodes. This lab uses graphs without isolated nodes. Mean aggregation uses a row-normalized adjacency, and sum uses the raw adjacency. Sparse aggregation costs roughly O(E d) for feature width d. The node projection adds O(N d_in d_out), while a dense adjacency uses N² entries.
GCN Normalization Player
Kipf and Welling derive the operator in the GCN paper and discuss the normalization choices.
GraphSAGE & Graph Attention · Learnable Aggregation
A typical GraphSAGE mean layer concatenates a node’s own features with the mean neighbor features, then applies a shared map. Training may sample neighbors to bound computation. How well the learned aggregator transfers to unseen graphs is an empirical question.
Graph attention assigns a content-dependent weight to each permitted edge. The softmax is restricted to neighbors, including a self-loop in this lab. The original GAT uses an additive score with a learned feature projection and Leaky ReLU. Lesson 4.2 shows scaled dot-product attention over a dense sequence.
Graph Attention Explorer
| Incoming node | Score | Weight | Weighted value |
|---|---|---|---|
| v0 | 3 | 0.4377 | 0.4377 |
| v1 | 1.6 | 0.1079 | 0.0324 |
| v3 | 2.6 | 0.2934 | 0.2347 |
| v5 | 2 | 0.161 | 0.0805 |
Permutation Equivariance under Node Relabeling
Relabel the graph by applying the same permutation P to the feature rows and both adjacency axes. Shared message functions and order-independent aggregation make the node outputs follow that same permutation.
When the nodes are relabeled, the degree matrix and adjacency are permuted together. The normalized GCN operator therefore satisfies N(PAPᵀ) = P N(A) Pᵀ. Multiplication by the permuted features gives N(A′) X′ W = P N(A) X W. A shared pointwise activation commutes with the row permutation.
A permutation-invariant readout turns the reordered node outputs into the same graph representation. This property concerns node labels. Translation, rotation, and SE(3) equivariance concern geometric transformations. Permuting feature rows alone changes their assignment to the graph and is a different operation.
Permutation Equivariance
Graph-level Prediction · Pooling & Oversmoothing
A graph-level readout combines a variable number of nodes into a fixed-width vector. Sum can express accumulated quantities, mean can express averages, and max can capture extremes while losing multiplicity information.
Repeated neighbor averaging can make node representations converge toward one another, a form of oversmoothing. On a finite connected undirected graph with self-loops, the random-walk operator is aperiodic and converges to a degree-weighted consensus. Removing self-loops can cause oscillations on bipartite graphs. This experiment isolates repeated averaging. Learned transformations and residual paths can change the behavior in trained models. Oversquashing is the compression of many distant messages through a limited representation.
Graph Pooling & Oversmoothing
Engineering Experiment · Coupled System Dynamics
The synthetic system is a graph of one-dimensional masses with positions q_i and velocities v_i. Each undirected edge contributes a unit-stiffness interaction. The discrete update below gives the next-step velocity.
Each edge sends a relative displacement q_j − q_i. Sum the incoming messages at node i and feed the aggregate, position, and velocity to a shared MLP. This message-passing model encodes part of the known dynamics in its input features. The local baseline supplies zero for the aggregate and keeps the same stored parameter count and training budget. Its effective input and degrees of freedom differ.
| Train graphs | Validation graphs | Shared parameters |
|---|---|---|
| 32 | 24 | 21 |
Each training graph starts from a six-node ring with random added edges. Positions and velocities are drawn independently from a uniform distribution on [−1, 1]. Generate 32 training graphs and 24 validation graphs using independent seeds. The default uses seed 3, 160 full-batch Adam updates, and learning rate 0.025. Click Train to compute the checkpoints. Changing the evaluation node count generates a differently sized validation graph set while keeping the training graphs fixed.
Live GNN Dynamics Training
Actual default benchmark (PyTorch)
| Model | Train MSE | Validation MSE |
|---|---|---|
| Message passing + shared MLP | 0.001778 | 0.002870 |
| Local-only (zero aggregate) | 0.042096 | 0.054281 |
The same learned graph model gives MSE 0.002509 on eight-node synthetic graphs generated at the same validation seed. This demonstrates evaluation at another node count under the specified generator. The informed aggregate is useful for this target, so the comparison measures the effect of providing that feature. Generalization to different topologies or stiffnesses, multi-step prediction, and closed-loop behavior require separate experiments.
Reproducible PyTorch implementation
Save the script as gnn0406.py and run it with PyTorch installed. Dense adjacency makes the update easy to compare with the manual browser implementation. Larger graphs can use sparse scatter or index_add to accumulate messages.
import torch
from torch import nn
from math import sqrt
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
class RNG:
def __init__(self, seed): self.s=seed
def __call__(self):
self.s=(1664525*self.s+1013904223)%2**32
return self.s/2**32
def data(count, seed, n=6):
r=RNG(seed); A=[]; X=[]; Y=[]
for _ in range(count):
a=torch.zeros(n,n)
for i in range(n): a[i,(i+1)%n]=a[(i+1)%n,i]=1
for i in range(n):
for j in range(i+2,n):
if not a[i,j] and r()<.22: a[i,j]=a[j,i]=1
x=torch.tensor([[2*r()-1,2*r()-1] for i in range(n)])
d=a@x[:,0]-a.sum(1)*x[:,0]
y=.92*x[:,1]+.20*d-.08*x[:,0]+.04*torch.sin(2*x[:,0])
A.append(a); X.append(x); Y.append(y)
return torch.stack(A),torch.stack(X),torch.stack(Y)
class Model(nn.Module):
def __init__(self,seed):
super().__init__();r=RNG(seed)
self.w=nn.Parameter(torch.tensor([[ (2*r()-1)*sqrt(6/7) for j in range(4)] for i in range(3)]))
self.b=nn.Parameter(torch.zeros(4))
self.v=nn.Parameter(torch.tensor([(2*r()-1)*sqrt(6/5) for j in range(4)]))
self.c=nn.Parameter(torch.zeros(1))
def forward(self,a,x,neighbor=True):
q=x[...,0]; d=(a@q.unsqueeze(-1)).squeeze(-1)-a.sum(-1)*q
z=torch.cat([x,(d if neighbor else torch.zeros_like(d)).unsqueeze(-1)],-1)
return torch.tanh(z@self.w+self.b)@self.v+self.c
def run(seed=3,lr=.025,steps=160,neighbor=True):
tr=data(32,seed);va=data(24,seed+1000); m=Model(seed+2000); opt=torch.optim.Adam(m.parameters(),lr=lr); hist=[]
for i in range(steps+1):
l=(m(tr[0],tr[1],neighbor)-tr[2]).square().mean()
if i%10==0 or i==steps:
with torch.no_grad():
vl=(m(va[0],va[1],neighbor)-va[2]).square().mean()
hist.append(dict(t=i,tr=l.item(),va=vl.item(),p={k:v.detach().tolist() for k,v in m.named_parameters()}))
if i==steps:break
opt.zero_grad();l.backward();opt.step()
perm=torch.arange(6).flip(0);a,x,_=va
torch.testing.assert_close(m(a[:,perm][:,:,perm],x[:,perm],neighbor),m(a,x,neighbor)[:,perm])
return m,hist
if __name__=='__main__':
for neighbor in [True,False]:
m,h=run(neighbor=neighbor);print(neighbor,h[0]['va'],h[-1]['tr'],h[-1]['va'])
m,_=run();a,x,y=data(24,1003,8);print('8 node shift',((m(a,x)-y)**2).mean().item())
AI-native verification workflow
Compute messages, aggregates, and feature shapes for one node. Inspect edge direction, duplicate edges, self-loops, and whether batching preserves graph boundaries. Compare the GCN output with matrix multiplication and check its permutation error after relabeling. For the dynamics comparison, hold the training set fixed, change access to neighbor information, and evaluate both models on the same graphs.
Authoritative References
GCN · Kipf & Welling
Original paperGraphSAGE · Hamilton et al.
Original paperGAT · Veličković et al.
Original paperMessage Passing · Gilmer et al.
Original paperLesson 4.7 moves from interactions on a graph to state updates over time. It connects continuous dynamics with discretization, convolution, and selective state space models.
Previous lesson · 4.5 Vision Transformer · Course overview · Next lesson · 4.7 State Space Sequence Models