Sam Austinon November 17, 202614 min read

Graph Neural Networks Explained: Message Passing in Plain English

Graph Neural Networks Explained: Message Passing in Plain English
Contents

Figure 1: Graph Neural Networks Explained: Message Passing in Plain English — a graph is not a table with extra columns, it is a set of things plus the relationships that change what those things mean

Your data is not a table. A molecule is atoms connected by bonds. A road network is intersections connected by streets. A fraud ring is accounts connected by transactions. Flatten any of those into rows and columns and you throw away the thing that matters most: who connects to whom.

Graph neural networks keep that structure, and one idea powers almost all of them: message passing. This post shows the idea on four nodes you can work out on paper, then in fifteen lines of PyTorch I actually ran, then in the failure modes that decide whether a GNN helps or hurts.

Why Ordinary Networks Struggle With Graphs

Standard networks expect fixed shapes. Convolutional networks expect a grid of pixels. Recurrent networks expect a sequence. Graphs break both assumptions:

  • Variable size — one molecule has 12 atoms, another has 80.
  • No natural order — nobody decides which node is "first", and any model that depends on node order is broken by definition.
  • Irregular connections — one node has two neighbours, another has two hundred.

So a GNN needs a rule that works for any node, with any number of neighbours, in any order. Message passing is that rule.

Graph Vocabulary in 30 Seconds

  • Nodes (vertices) — the entities: users, atoms, intersections.
  • Edges — the relationships between them.
  • Node features — a vector per node, such as an atom's type or a user's profile.
  • Edge features (optional) — details about the relationship: bond type, road length, transaction amount.

In PyTorch Geometric, an undirected graph is usually stored as two directed edges, one in each direction. That convention is a landmine for train/test splits, and I come back to it under leakage below.

Message Passing: The Whole Idea

Picture a group chat among neighbours. Each round, every person reads what their neighbours said, summarises it, and updates their own opinion. After a few rounds, each person's view reflects their whole local neighbourhood, not just their own information.

Every message-passing layer does three things:

  1. Message — each neighbour sends information, usually its feature vector, optionally transformed.
  2. Aggregate — the node combines the incoming messages, typically with a sum, mean, or max.
  3. Update — the node merges that summary with its own previous features, usually through a small neural network layer.

Why sum, mean, or max? Because they are order-independent. Whether node B or node C speaks first, the result is identical — and that is exactly what a graph demands, since it has no canonical node order. Swap in a function that cares about order and your model's output changes when you renumber the nodes.

Layers Define How Far You See

One layer lets a node hear from its direct neighbours. Two layers expose it to its two-hop neighbourhood, because the second round passes along what the first round already mixed in. After K layers, a node's representation captures its K-hop neighbourhood.

Think of K as "how many handshakes away can I hear?" The general framework behind this is the Message Passing Neural Network (MPNN), which describes GCN, GraphSAGE, and GAT as different choices of message function and aggregation function [1].

A Tiny Example You Can Do by Hand

Take four nodes with one number each, connected like this: A–B, A–C, C–D.

        B(3)
         |
A(1) --- C(5) --- D(9)

Starting features: A = 1, B = 3, C = 5, D = 9. Rule: each node averages its own feature with its neighbours' features — a simplified GCN-style update with no learned weights.

Layer 1:

Node Own Neighbours Mean
A 1 3, 5 (1 + 3 + 5) / 3 = 3.00
B 3 1 (3 + 1) / 2 = 2.00
C 5 1, 9 (5 + 1 + 9) / 3 = 5.00
D 9 5 (9 + 5) / 2 = 7.00

Layer 2, using 3, 2, 5, 7:

Node Own Neighbours Mean
A 3 2, 5 (3 + 2 + 5) / 3 = 3.33
B 2 3 (2 + 3) / 2 = 2.50
C 5 3, 7 (5 + 3 + 7) / 3 = 5.00
D 7 5 (7 + 5) / 2 = 6.00

Watch the spread. The gap between the largest and smallest value shrinks from 8 at the start, to 5 after layer 1, to 3.5 after layer 2. Keep going and every node drifts toward the same number. I ran it out to twelve rounds:

round   A       B       C       D      spread
  0   1.000   3.000   5.000   9.000    8.000
  1   3.000   2.000   5.000   7.000    5.000
  2   3.333   2.500   5.000   6.000    3.500
  3   3.611   2.917   4.778   5.500    2.583
  4   3.769   3.264   4.630   5.139    1.875
  6   3.972   3.702   4.428   4.698    0.997
  8   4.079   3.935   4.321   4.465    0.529
 12   4.166   4.125   4.234   4.275    0.149

Every value converges to exactly 4.2 — the degree-weighted average of the four starting numbers — and the spread falls to 0.15. That drift is over-smoothing, and it is why depth in GNNs works differently from depth in CNNs. Real GNNs add learned weights and nonlinearities, so they do not collapse this fast — but the pull toward similarity is real, and it sets the ceiling on how deep you can go.

The Famous Flavours: GCN, GraphSAGE, GAT

The three popular architectures differ only in how they compute and weight messages.

  • GCN (Graph Convolutional Network) — averages neighbour features with a symmetric degree normalisation, then applies a learned transformation [2]. Simple, fast, and the right baseline for a homogeneous graph.
  • GraphSAGE — samples a fixed number of neighbours instead of using all of them, and learns the aggregation [3]. Sampling makes it practical on very large graphs and supports inductive learning, meaning it can embed nodes it never saw during training, at the cost of sampling variance.
  • GAT (Graph Attention Network) — learns an attention score per edge, so important neighbours count more [4]. Use it when neighbour relevance varies a lot.
  • GIN (Graph Isomorphism Network) — designed for maximum expressive power among message-passing models.
  • R-GCN — handles relational data with several edge types.

My default: GCN first as a baseline, GraphSAGE if the graph is huge, GAT if neighbours clearly differ in importance. Then compare on the same split rather than trusting a leaderboard.

What GNNs Predict

Three task shapes cover most of graph learning:

  • Node classification — label each node, such as "fraudulent account".
  • Link prediction — decide whether an edge should exist, such as "will these two users connect?"
  • Graph classification or regression — one value per graph, such as a molecule's toxicity.

The same message-passing backbone feeds all three, and only the output head and loss function change.

Message Passing in Code

Here is the layer from scratch in plain PyTorch. I ran it on the four-node graph above:

import torch

def message_passing(x, edge_index, W):
    """x: (N, F) node features; edge_index: (2, E) with rows [src, dst]."""
    src, dst = edge_index
    msgs = x[src]                                   # message: neighbor's features
    agg = torch.zeros_like(x).index_add_(0, dst, msgs)   # sum messages per node
    deg = torch.zeros(x.size(0)).index_add_(
        0, dst, torch.ones(src.size(0))).clamp(min=1)
    agg = (x + agg) / (deg + 1).unsqueeze(-1)       # mean over self + neighbors
    return torch.relu(agg @ W)                      # update

The + 1 in the denominator is the self-loop. Without it the layer computes x + mean(neighbours), which is a different function and does not match the hand calculation — the original version of this snippet had exactly that bug and produced [5, 4, 10, 14] instead of [3, 2, 5, 7]. Counting yourself in the average is the whole difference between a GCN layer and a neighbour sum.

Running it with W set to the identity reproduces the tables exactly:

layer 1: [3.000, 2.000, 5.000, 7.000]
layer 2: [3.333, 2.500, 5.000, 6.000]

Shuffling the edge order leaves the output bit-identical, which is the order-independence claim made concrete. Swap index_add_ for a for loop that appends messages in edge order and that property disappears.

The standard route uses PyTorch Geometric on the Cora citation dataset. PyG is not installed in my environment, so I could not run this one — treat it as a starting point and check it against the current documentation:

import torch, torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import GCNConv

dataset = Planetoid(root="data/Cora", name="Cora")
data = dataset[0]

class GCN(torch.nn.Module):
    def __init__(self, hidden=16):
        super().__init__()
        self.conv1 = GCNConv(dataset.num_features, hidden)
        self.conv2 = GCNConv(hidden, dataset.num_classes)

    def forward(self, x, edge_index):
        x = F.relu(self.conv1(x, edge_index))
        x = F.dropout(x, p=0.5, training=self.training)
        return self.conv2(x, edge_index)

model = GCN()
opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

for epoch in range(200):
    model.train()
    opt.zero_grad()
    out = model(data.x, data.edge_index)
    loss = F.cross_entropy(out[data.train_mask], data.y[data.train_mask])
    loss.backward()
    opt.step()

model.eval()
pred = model(data.x, data.edge_index).argmax(dim=1)
acc = (pred[data.test_mask] == data.y[data.test_mask]).float().mean()
print(f"test accuracy: {acc:.3f}")

Two layers means two hops. Change GCNConv to SAGEConv or GATConv and the training loop is unchanged.

Where GNNs Break

Over-Smoothing

Stack layers and node representations converge toward indistinguishable vectors. The four-node table above is the mechanism in miniature: a little smoothing helps neighbours agree, too much makes every node look the same. The depth at which it bites depends on the graph and the model, so the honest answer is to sweep depth from one to six layers and plot accuracy [5].

Over-Squashing

Long-range information has to squeeze through narrow paths. When a node's K-hop neighbourhood grows exponentially but its vector stays fixed-size, distant signals get compressed through bottleneck edges and simply vanish [5]. This is the failure mode that depth cannot fix, because adding layers is what causes it.

Heterophily

Message passing assumes connected nodes look alike. When they do not — fraudsters linking to normal accounts, dating graphs, protein interactions between different functions — plain averaging actively mixes the wrong labels together [5]. Check the homophily of your edges before blaming the architecture: if most edges connect different classes, a GCN has no reason to work.

Limited Expressiveness

Standard message passing cannot distinguish some graph structures that are genuinely different. Sum-aggregation GNNs are bounded by the 1-WL colour-refinement test, so certain non-isomorphic graphs produce identical embeddings [5]. Attention and higher-order aggregations raise the ceiling, but they do not remove it.

Scale

Real graphs have millions of nodes, and neighbour counts explode with depth: a node with 50 neighbours has 2,500 two-hop neighbours. GraphSAGE-style sampling tames this [3], and PyG provides batching, neighbourhood sampling, and sparse message passing for GPUs.

This is the bug that quietly inflates results. If you store each undirected edge twice, a random split can put one direction in training and the other in testing, so the model has effectively seen the answer. Split by undirected edge, never by directed copy, and remove test edges from the graph used for message passing.

Beyond Message Passing: Graph Transformers

Newer models let every node attend to every other node. The GPS framework combines local message passing with global self-attention [5], and it exists as GPSConv in PyG. Global attention shortens the path between distant nodes, which is the direct answer to over-squashing — but the cost is quadratic in the number of nodes, so it is a tool for medium-sized graphs, not billion-edge ones.

Do You Even Need a GNN?

Build a tabular baseline first. Take node features, drop the edges, train gradient-boosted trees or a small MLP, and compare on the same split. If the GNN cannot beat it, the graph is not adding information at your scale, and the simpler model wins on latency, cost, and debuggability.

I ran that comparison on a synthetic graph with three communities and deliberately weak node features. A plain MLP scored 0.349 and a two-layer GCN scored 0.854, winning 20 of 20 random graphs — but when I raised the between-community edge probability, the GCN collapsed to 0.359 and the advantage disappeared. The full experiment is in Graph Machine Learning for Beginners.

Where GNNs Show Up in Practice

  • Drug discovery and biomedicine — molecules as graphs of atoms and bonds, for property prediction and generative design.
  • Fraud detection — accounts and transactions as a graph, where a ring is visible as a dense cluster.
  • Recommendation — users and items as a bipartite graph, with link prediction as the task.
  • Traffic forecasting — road networks as a graph, with speed per sensor as node features.
  • Chip placement — netlists are graphs of components and wires, and placement is an optimisation over them.

A Practical Learning Path

  1. Compute the four-node example above until the pattern feels obvious. It takes ten minutes and makes every architecture below readable.
  2. Run the plain-PyTorch snippet and confirm it reproduces [3, 2, 5, 7].
  3. Run the Cora tutorial and reproduce roughly the paper's 81% test accuracy [2].
  4. Swap in GAT and GraphSAGE, and compare across several seeds rather than one.
  5. Vary depth from 1 to 6 layers and plot accuracy to watch over-smoothing.
  6. Build the MLP baseline on node features alone, and compare.
  7. Try link prediction, with a leak-free split by undirected edge.
  8. Pick a real problem from your own domain and model it as a graph.

Common Pitfalls

  • Stacking many layers. Start with two or three; depth is the most common self-inflicted wound.
  • Skipping the non-graph baseline. You cannot prove the graph helps without it.
  • Leaking edges in link prediction. Split by undirected edge, and strip test edges from the message-passing graph.
  • Ignoring graph structure quality. Wrong edges teach wrong patterns faster than a better model can fix them.
  • Using one seed. Graph benchmarks vary a lot at small scale; report a mean over several runs.
  • Treating GAT as always better. Attention costs compute and does not always win.
  • Forgetting scale. Full-graph training breaks on big graphs; plan for sampling from day one.
  • Assuming homophily. Measure whether neighbours actually share labels before choosing an averaging model.

Best Book to Read

CoverBookDescriptionGet it
Cover of “Graph Representation Learning” Graph Representation Learningby William L. Hamilton the compact, mathematically careful treatment of node embeddings, the GCN, GraphSAGE, and the theory behind message passing, from the author of the GraphSAGE paper. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read it after the four-node example, not before. The book is short but dense, and the hand calculation gives every formula something concrete to attach to.

Wrapping Up

Message passing is three steps: each node collects messages from its neighbours, aggregates them with an order-independent function, and updates itself. Stack K layers and each node summarises its K-hop neighbourhood. GCN, GraphSAGE, and GAT differ only in how they compute and weight those messages.

Do the four-node example on paper this week. Then run the PyTorch snippet, confirm [3, 2, 5, 7], and vary the number of layers. If accuracy drops as you add layers, you have watched over-smoothing happen with your own eyes.

Frequently Asked Questions

What is message passing in a graph neural network?

Each layer has every node collect messages from its neighbours, combine them with an order-independent function such as sum, mean, or max, and update its own representation. Stacking K layers means each node ends up with a summary of its K-hop neighbourhood.

Why does mean aggregation work on a graph?

Because mean, sum, and max do not care about order. A node has no natural first or last neighbour, so any aggregation function that changes when you reorder the neighbours would be undefined. Order independence is the whole reason those three functions are the default choice.

What is the difference between GCN, GraphSAGE, and GAT?

GCN averages neighbours with a fixed degree-normalised weight, which is fast but treats every neighbour alike. GraphSAGE samples a fixed number of neighbours and learns the aggregation, so it can embed nodes it never saw during training. GAT learns an attention weight per edge, so important neighbours count more.

Why do deeper GNNs get worse?

Repeated averaging pulls node representations toward each other until they are nearly indistinguishable, which is over-smoothing. In the four-node example the spread between the largest and smallest value falls from 8 to 5 to 3.5 over two rounds and to 0.15 by round twelve. Most GNNs therefore use two or three layers.

How do I know whether I need a GNN at all?

Train a baseline that sees only node features, such as an MLP or gradient-boosted trees, and compare on the same split. If the GNN cannot beat it, the edges are not adding information at your scale, and the simpler model is the right answer.

Sources

  • [1] Gilmer et al., Neural Message Passing for Quantum Chemistry — the MPNN framework that unifies GCN, GraphSAGE, and GAT as choices of message and update function: arxiv.org
  • [2] Kipf and Welling, Semi-Supervised Classification with Graph Convolutional Networks — the GCN layer, symmetric normalisation, and the Cora benchmark: arxiv.org
  • [3] Hamilton, Ying, and Leskovec, Inductive Representation Learning on Large Graphs — GraphSAGE, neighbour sampling, and inductive inference: arxiv.org
  • [4] Veličković et al., Graph Attention Networks — learned attention weights over neighbours: arxiv.org
  • [5] Depth, expressiveness, and long-range limits, collected in one place: Li, Han, and Wu, Deeper Insights into Graph Convolutional Networks (over-smoothing) arxiv.org; Alon and Yahav, On the Bottleneck of Graph Neural Networks (over-squashing) arxiv.org; Xu et al., How Powerful are Graph Neural Networks? (the 1-WL ceiling) arxiv.org; Zhu et al., Beyond Homophily in Graph Neural Networks arxiv.org; Rampášek et al., Recipe for a General, Powerful, Scalable Graph Transformer (GPS) arxiv.org

What are You Looking For?

esc