Graph Neural Networks: Message Passing Explained
Rows and columns work for tabular data, but a growing share of the world's structure is relational: molecules with atoms bonded in patterns, recommendations defined by who bought what, fraud rings connected through shared accounts, knowledge bases of entities and links. A graph neural network learns over that structure directly, letting each node gather information from its neighbors and update its own representation accordingly.
The unifying idea is message passing. Every layer, each node sends a message to its neighbors, aggregates what arrives, and combines it with its own state. Different GNN architectures are mostly different answers to three questions: how do you build a message, how do you aggregate (sum, mean, max, or attention), and how many rounds can you run before the representations blur into sameness.
This lesson derives message passing as a two-equation abstraction, then implements three concrete architectures â GCN, GAT, and GraphSAGE â covers the over-smoothing problem that limits depth, and maps architectures to application types.
From adjacency matrices to node features
A graph is a set of nodes with features (an n à d matrix) plus an adjacency structure describing which nodes connect. The simplest representation is a dense adjacency matrix where entry A_ij is 1 if an edge exists. Most implementations normalize it symmetrically â multiplying each side by the inverse square root of the node degrees â because unnormalized aggregation makes high-degree nodes blow up in magnitude.
Message passing formalizes one layer in two steps. First, aggregate: each node collects messages from its neighbors (and itself), usually by sum or mean. Second, update: the node combines its previous state with the aggregated message through a learned function. Stack these layers and information propagates hops outward â after k layers, node v's representation incorporates everything within k hops of it.
That hop-radius fact is the design lever. Too few layers and distant context never reaches the node; too many and every node has absorbed nearly the whole graph. Depth in GNNs is a semantic choice about how far apart relationships matter, not just a capacity knob.
Graph convolutions: the GCN baseline
The graph convolutional network takes the message-passing abstraction and specializes it to a single normalized-adjacency multiplication followed by a linear transform:
import torch
import torch.nn as nn
import torch.nn.functional as F
class GCNLayer(nn.Module):
def __init__(self, in_dim: int, out_dim: int, bias: bool = True):
super().__init__()
self.linear = nn.Linear(in_dim, out_dim, bias=bias)
def forward(self, x: torch.Tensor, adj_norm: torch.Tensor) -> torch.Tensor:
support = self.linear(x)
return adj_norm @ support
class GCN(nn.Module):
def __init__(self, in_dim: int, hidden: int, n_classes: int, dropout: float = 0.5):
super().__init__()
self.conv1 = GCNLayer(in_dim, hidden)
self.conv2 = GCNLayer(hidden, n_classes)
self.dropout = dropout
def forward(self, x: torch.Tensor, adj_norm: torch.Tensor) -> torch.Tensor:
h = F.relu(self.conv1(x, adj_norm))
h = F.dropout(h, self.dropout, training=self.training)
return F.log_softmax(self.conv2(x, adj_norm), dim=-1)
def normalize_adj(adj: torch.Tensor) -> torch.Tensor:
deg = adj.sum(dim=1)
inv_sqrt = torch.diag(deg.pow(-0.5))
inv_sqrt[torch.isinf(inv_sqrt)] = 0.0
return inv_sqrt @ adj @ inv_sqrt
gcn = GCN(in_dim=1433, hidden=16, n_classes=7)
adj_norm = normalize_adj(adj)
output = gcn(features, adj_norm)
GCN's elegance â one sparse matrix multiply per layer â is also its limitation: every node receives messages from every neighbor with equal weight. In a graph where some edges are noisy or irrelevant, uniform aggregation dilutes the signal. And the symmetric normalization makes the layer a form of smoothing: each update moves a node's representation toward the average of its neighborhood, which is exactly why depth eventually erases node identity.
Learning which neighbors matter: the GAT
A graph attention network replaces fixed aggregation weights with learned attention. Each node projects its features into queries, keys, and values; attention scores are computed only between connected nodes (non-edges are masked to negative infinity before softmax); and the aggregation uses those scores as weights.
class GATLayer(nn.Module):
def __init__(self, in_dim: int, out_dim: int, n_heads: int = 8,
dropout: float = 0.6, concat: bool = True):
super().__init__()
assert out_dim % n_heads == 0
self.n_heads = n_heads
self.head_dim = out_dim // n_heads
self.W = nn.Linear(in_dim, out_dim, bias=False)
self.attn = nn.Linear(2 * self.head_dim, 1, bias=False)
self.dropout = nn.Dropout(dropout)
self.concat = concat
def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor:
n = x.shape[0]
h = self.W(x).view(n, self.n_heads, self.head_dim)
e_src = h.unsqueeze(1).expand(n, n, self.n_heads, self.head_dim)
e_dst = h.unsqueeze(0).expand(n, n, self.n_heads, self.head_dim)
scores = self.attn(torch.cat([e_src, e_dst], dim=-1)).squeeze(-1)
mask = (adj == 0)
scores = scores.masked_fill(mask.unsqueeze(-1), float("-inf"))
alpha = F.softmax(scores, dim=1)
alpha = self.dropout(alpha)
out = torch.einsum("nmh,nhd->mhd", alpha, h)
if self.concat:
return out.reshape(n, -1)
return out.mean(dim=1)
gat = GATLayer(in_dim=1433, out_dim=64, n_heads=8)
Attention buys two things. It lets the model down-weight noisy edges automatically â useful in graphs where edge existence is a weak signal (a shared co-author does not imply collaboration relevance). And it produces inspectable weights: the attention distribution over neighbors can be visualized to see which connections drove a prediction, which matters in domains like drug interaction prediction where scientists want a rationale, not just a score.
Multi-head attention, concatenated as above, mirrors the transformer trick of letting different heads specialize in different neighbor patterns. Single-head attention with averaging is common in the final layer where dimensionality is constrained.
Scaling with GraphSAGE: sampling instead of full neighborhoods
GCN and GAT aggregate over the full neighborhood every layer, which makes their memory cost explode on large graphs. GraphSAGE (sample and aggregate) changes the unit of computation: fix the number of neighbors sampled per node per layer, aggregate over that fixed-size sample, and combine with the node's own state by concatenation.
class GraphSAGELayer(nn.Module):
def __init__(self, in_dim: int, out_dim: int, aggregator: str = "mean"):
super().__init__()
self.aggregator = aggregator
self.W = nn.Linear(in_dim * 2, out_dim)
def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor:
if self.aggregator == "mean":
neighbor = adj @ x
deg = adj.sum(dim=1, keepdim=True).clamp(min=1)
neighbor = neighbor / deg
elif self.aggregator == "max":
neighbor = adj.unsqueeze(-1) * x.unsqueeze(0)
neighbor = neighbor.max(dim=0).values
else:
neighbor = adj @ x
combined = torch.cat([x, neighbor], dim=-1)
return self.W(combined)
class GraphSAGE(nn.Module):
def __init__(self, in_dim: int, hidden: int, n_classes: int):
super().__init__()
self.l1 = GraphSAGELayer(in_dim, hidden)
self.l2 = GraphSAGELayer(hidden, n_classes)
def forward(self, x, adj):
return self.l2(F.relu(self.l1(x, adj)), adj)
GraphSAGE's deeper contribution is inductive learning: because aggregation is defined over arbitrary neighbors rather than a fixed adjacency matrix, a trained model can embed nodes in a graph it has never seen â essential for recommendation systems where new users arrive continuously. The aggregator choice (mean, max, LSTM over neighbors) is a hyperparameter with real effect; mean is robust, max captures salient features, and learned aggregators cost more but handle heterogeneous neighborhoods better.
Over-smoothing and the depth wall
Stack enough GCN layers and every node's representation converges toward the same vector. This is over-smoothing: repeated normalized aggregation is a diffusion process, and diffusions converge to a stationary distribution where distinctions are gone. Symptoms include validation accuracy that peaks at two or three layers and then falls, and embeddings that visualize as a single blob.
The remedies all break the symmetry of pure smoothing. Residual connections let a node carry its original state forward regardless of neighbor influence. Jumping knowledge architectures concatenate representations from all layers so the readout can choose per node how much context to use. PairNorm and specialized normalizations rescale features to prevent collapse during training. APPNP decouples propagation from transformation, applying personalized PageRank-style diffusion with a damping factor that provably cannot fully collapse node states.
The practical rule: if your task depends on node identity or local structure, keep the network shallow (2â4 layers) and widen it rather than deepening it. If it depends on long-range graph context, add explicit mechanisms for that context rather than adding layers and hoping.
Matching architectures to applications
| Task type | Output granularity | Typical architectures | Notes |
|---|---|---|---|
| Node classification | Per node | GCN, GAT, GraphSAGE | Citation networks, fraud accounts |
| Graph classification | Per graph | Pooling + any GNN (DiffPool, TopK) | Molecular properties, molecule toxicity |
| Link prediction | Per node pair | Embedding similarity on GNN output | Recommendation, knowledge completion |
| Community detection | Per node (cluster) | Spectral methods, deep graph clustering | Social analysis |
| Generative modeling | Whole graphs | Graph VAEs, diffusion on graphs | Drug discovery, circuit design |
For molecules, atom types are node features, bonds are edges, and the target might be solubility or toxicity â a graph-level task requiring pooling (sum or attention pooling over nodes) to produce one vector. For recommendation, bipartite user-item graphs with GraphSAGE-style aggregation give embeddings for cold-start nodes. For knowledge graphs, relation types become edge features and specialized variants like R-GCN handle multiple edge kinds.
Graph structure also changes what transfer learning means: pretrained GNNs on large molecule corpora are now routinely fine-tuned for downstream chemistry tasks, mirroring the pretraining recipe from language models. The message-passing abstraction is the common vocabulary that makes those transfers legible.
Common Mistakes
Stacking many GCN layers hoping for long-range context
Fix: Over-smoothing caps useful depth at a few layers; use residual or jumping-knowledge connections if you must go deeper.
Forgetting to normalize the adjacency matrix
Fix: Apply symmetric degree normalization â unnormalized sums let high-degree nodes dominate every layer.
Treating edge existence as uniformly meaningful
Fix: Use GAT-style attention or edge features when some connections are noisy or heterogeneous.
Applying dropout to node features but not attention weights
Fix: Drop out attention coefficients during training â it regularizes as effectively as feature dropout.
Pooling before enough message-passing rounds
Fix: Graph-level tasks need representations that have seen their full relevant neighborhood before pooling.
Key Takeaways
- GNNs learn by message passing: aggregate from neighbors, update own state, repeat for as many hops as the task needs.
- GCN is a normalized adjacency multiply â fast, but it smooths uniformly and weights all neighbors equally.
- GAT learns per-edge attention, trading compute for selective aggregation and inspectable rationales.
- GraphSAGE enables inductive, large-graph learning by sampling fixed-size neighborhoods instead of using all neighbors.
- Over-smoothing is the depth wall: keep GNNs shallow and add explicit mechanisms for long-range context.
- Match the architecture to output granularity â node, graph, or link â before tuning hyperparameters.