Message Passing from Scratch in PyTorch with index_add
One round of message passing does three things. For every edge it builds a message, usually from the source node's features. For every node it combines the messages that arrive there, with a sum, mean or max. Then it computes the node's new features from that combination, often together with the old features.
m_ij = φ(x_i, x_j) one message per edge i → j
a_j = AGG_{i ∈ N(j)} m_ij combine the messages arriving at j
x'_j = ψ(x_j, a_j) new state of node j
This message and update form follows Gilmer et al. and is generalised in the graph network framework of Battaglia et al.. N(j) is the set of nodes with an edge into j. In PyTorch the first step is an indexing operation and the second is one call to index_add_. This tutorial builds all three by hand on a five-node graph, traces the numbers, shows the mistakes that run without an error, and checks the result against a library layer. It needs only PyTorch until the comparison section, which uses TGraphX 1.5.1. The code blocks run in order on CPU.
The graph
Nodes are rows of a feature tensor x with shape [N, d]. Edges are columns of an integer tensor edge_index with shape [2, E]: row 0 holds the source i, row 1 the destination j.
import torch
x = torch.tensor([[1.0, 0.0], # node 0
[0.0, 2.0], # node 1
[5.0, 5.0], # node 2
[2.0, 1.0], # node 3
[3.0, 3.0]]) # node 4
edge_index = torch.tensor([[0, 1, 3, 2, 3, 4], # source i
[2, 2, 2, 4, 4, 0]]) # destination j
src, dst = edge_index
N, d = x.shape
E = edge_index.size(1)
print(N, E, d) # 5 6 2
Reading the columns: nodes 0, 1 and 3 send to node 2; nodes 2 and 3 send to node 4; node 4 sends to node 0. Nodes 1 and 3 receive nothing. The graph is directed: the edge 2 → 4 does not imply 4 → 2.
Step 1: gather one row per edge
The simplest message is a copy of the source features. Indexing x with the source row produces a tensor with one row per edge, in edge order:
messages = x[src] # [E, d]
for k in range(E):
print(f"edge {k}: {src[k].item()} -> {dst[k].item()} message {messages[k].tolist()}")
edge 0: 0 -> 2 message [1.0, 0.0]
edge 1: 1 -> 2 message [0.0, 2.0]
edge 2: 3 -> 2 message [2.0, 1.0]
edge 3: 2 -> 4 message [5.0, 5.0]
edge 4: 3 -> 4 message [2.0, 1.0]
edge 5: 4 -> 0 message [3.0, 3.0]
Node 3 has two outgoing edges, so its features appear twice. Memory for messages grows with the number of edges, not nodes. That is the main cost to keep in mind when features are large.
Step 2: add each message into its destination
Start with zeros for every node, then add row k of messages into row dst[k]:
agg_sum = torch.zeros(N, d)
agg_sum.index_add_(0, dst, messages) # for each k: agg_sum[dst[k]] += messages[k]
print(agg_sum.tolist())
# [[3.0, 3.0], [0.0, 0.0], [3.0, 3.0], [0.0, 0.0], [7.0, 6.0]]
Check node 2 by hand: (1,0) + (0,2) + (2,1) = (3,3). Node 4 gets (5,5) + (2,1) = (7,6). Node 0 receives only (3,3). Nodes 1 and 3 keep the zeros they started with.
The explicit loop does the same thing and is a useful reference when you are unsure about an indexing expression:
slow = torch.zeros(N, d)
for k in range(E):
slow[dst[k]] += messages[k]
assert torch.equal(slow, agg_sum)
The tempting one-liner is wrong
wrong = torch.zeros(N, d)
wrong[dst] += messages # looks like the loop, but is not
print(wrong.tolist()) # one message per destination survives
print(torch.equal(wrong, agg_sum)) # False
wrong[dst] += messages reads wrong[dst], adds, and writes the result back. When dst repeats an index, the writes overwrite each other instead of accumulating, and no error or warning appears. PyTorch documents the behaviour of such a put with duplicate indices as undefined. Use index_add_, or index_put_ with accumulate=True.
Mean and max
The mean needs the number of incoming edges per node. Count them with the same operation, and clamp the count so that nodes without incoming edges do not divide by zero:
count = torch.zeros(N).index_add_(0, dst, torch.ones(E))
print(count.tolist()) # [1.0, 0.0, 3.0, 0.0, 2.0]
agg_mean = agg_sum / count.clamp(min=1).unsqueeze(1)
print(agg_mean.tolist())
# [[3.0, 3.0], [0.0, 0.0], [1.0, 1.0], [0.0, 0.0], [3.5, 3.0]]
For the maximum, scatter_reduce_ with reduce="amax" does the grouping. It wants an index of the same shape as the source, so expand dst across the feature dimension:
index = dst.view(-1, 1).expand_as(messages) # [E, d]
agg_max = torch.zeros(N, d).scatter_reduce_(
0, index, messages, reduce="amax", include_self=False)
print(agg_max.tolist())
# [[3.0, 3.0], [0.0, 0.0], [2.0, 2.0], [0.0, 0.0], [5.0, 5.0]]
Two details deserve attention.
The maximum is taken separately in each feature position. Node 2 gets (2, 2): the first value comes from node 3 and the second from node 1. No single neighbour sent (2, 2).
include_self=False matters. With the default True, the initial zeros take part in the maximum, so any negative value is silently replaced by zero:
negative = -messages
right = torch.zeros(N, d).scatter_reduce_(0, index, negative, reduce="amax", include_self=False)
clipped = torch.zeros(N, d).scatter_reduce_(0, index, negative, reduce="amax")
print(right[2].tolist(), clipped[2].tolist()) # [-0.0, -0.0] [0.0, 0.0]
print(right[4].tolist(), clipped[4].tolist()) # [-2.0, -1.0] [0.0, 0.0]
Node 2's true maximum happens to be zero, so a test on that node alone would pass. Node 4 shows the bug.
Which aggregation?
All three ignore the order of the incoming edges, which is required because a graph has no natural neighbour order. They lose different information:
| Aggregation | Neighbours {1, 1} vs {1} |
{1, 3} vs {2, 2} |
Value for a node with no incoming edge here |
|---|---|---|---|
| sum | different (2 vs 1) | same (4) | 0 |
| mean | same (1) | same (2) | 0 (by the clamp) |
| max | same (1) | different (3 vs 2) | 0 (by initialisation) |
A zero for an isolated node is a convention of this code, not a mathematical fact: the maximum of an empty set is not zero.
Step 3: update the node state
The aggregate alone forgets the node's own features. A common update applies one linear map to the old state and another to the aggregate:
import torch.nn as nn
torch.manual_seed(0)
lin_self = nn.Linear(d, 4)
lin_neigh = nn.Linear(d, 4)
new_x = torch.relu(lin_self(x) + lin_neigh(agg_sum))
print(new_x.shape) # torch.Size([5, 4])
The output width (4) is independent of the input width (2). The number of nodes does not change.
The three steps as one module
Here is a complete layer. The message is a learned linear function of the concatenated source and destination features, the aggregation is selectable, and the update keeps a self term when you ask for it:
class MessagePassing(nn.Module):
def __init__(self, in_dim, out_dim, aggr="sum", self_term=True):
super().__init__()
if aggr not in ("sum", "mean", "max"):
raise ValueError(f"unknown aggr: {aggr!r}")
self.aggr = aggr
self.message_linear = nn.Linear(2 * in_dim, out_dim)
self.self_linear = nn.Linear(in_dim, out_dim) if self_term else None
def aggregate(self, messages, dst, num_nodes):
out = messages.new_zeros(num_nodes, messages.size(1))
if self.aggr == "max":
index = dst.view(-1, 1).expand_as(messages)
return out.scatter_reduce_(0, index, messages, reduce="amax", include_self=False)
out.index_add_(0, dst, messages)
if self.aggr == "mean":
count = messages.new_zeros(num_nodes)
count.index_add_(0, dst, messages.new_ones(dst.numel()))
out = out / count.clamp(min=1).unsqueeze(1)
return out
def forward(self, x, edge_index):
src, dst = edge_index
messages = self.message_linear(torch.cat([x[src], x[dst]], dim=1)) # phi
a = self.aggregate(messages, dst, x.size(0)) # AGG
if self.self_linear is None:
return a
return a + self.self_linear(x) # psi
torch.manual_seed(0)
layer = MessagePassing(2, 4, aggr="mean")
print(layer(x, edge_index).shape) # torch.Size([5, 4])
layer(x, edge_index).sum().backward()
print(layer.message_linear.weight.grad.shape) # torch.Size([4, 4])
Gradients flow through the indexing and through index_add_ without extra code.
Check it against a library layer
TGraphX has LinearMessagePassing, which computes m_ij = W [x_i ‖ x_j] + b, aggregates by sum, mean or max over incoming edges, and returns the aggregate. It has no self term, so compare it with self_term=False after copying the weights:
import tgraphx as tgx
for aggr in ("sum", "mean", "max"):
torch.manual_seed(1)
ours = MessagePassing(2, 4, aggr=aggr, self_term=False)
theirs = tgx.LinearMessagePassing((2,), (4,), aggr=aggr)
theirs.message_linear.load_state_dict(ours.message_linear.state_dict())
assert torch.allclose(ours(x, edge_index), theirs(x, edge_index))
print(aggr, "matches")
You can also reproduce the first, weight-free numbers: set the weight to copy the source half of the concatenation.
copy_source = tgx.LinearMessagePassing((2,), (2,), aggr="sum")
with torch.no_grad():
copy_source.message_linear.weight.copy_(torch.tensor([[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0]]))
copy_source.message_linear.bias.zero_()
assert torch.equal(copy_source(x, edge_index), agg_sum)
One caution about the library layer: its aggr string is not validated in 1.5.1, so a typo such as aggr="men" behaves as a sum. The module above raises instead.
Edge features, duplicate edges and self-loops
Edge features. If each edge carries a vector e_ij, store them as a [E, d_e] tensor whose row k belongs to column k of edge_index, and let the message see it. Nothing else changes. LinearMessagePassing does this when you build it with use_edge_features=True; its linear map then takes [x_i ‖ x_j ‖ e_ij], and in 1.5.1 it expects the edge feature width to equal the node feature width:
edge_attr = torch.tensor([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0],
[2.0, 0.0], [0.0, 2.0], [1.0, 1.0]]) # [E, d_e]
torch.manual_seed(4)
with_edges = tgx.LinearMessagePassing((2,), (4,), use_edge_features=True)
by_hand = with_edges.message_linear(torch.cat([x[src], x[dst], edge_attr], dim=1))
expected = torch.zeros(N, 4).index_add_(0, dst, by_hand)
assert torch.allclose(with_edges(x, edge_index, edge_features=edge_attr), expected)
without_edges = tgx.LinearMessagePassing((2,), (4,))
assert torch.equal(without_edges(x, edge_index, edge_features=edge_attr),
without_edges(x, edge_index)) # silently ignored
The last assertion is the trap: a layer built without use_edge_features=True accepts edge features and ignores them. When you reorder or filter edges, reorder edge_attr with the same index, or the values will describe the wrong edges.
Duplicate edges. A repeated column is a second message. It counts that neighbour twice in a sum and shifts a mean towards it, but leaves a maximum unchanged:
twice = torch.cat([edge_index, edge_index[:, :1]], dim=1) # edge 0 -> 2 again
print(torch.zeros(N, d).index_add_(0, twice[1], x[twice[0]])[2].tolist()) # [4.0, 3.0]
If repeated rows come from your data loading rather than from the problem, merge them before building the tensor.
Self-loops. Adding an edge j → j for every node puts the node's own state into the aggregate. That is a different design from the separate self term in step 3: with a loop, the node's own features share the weights and the aggregation with its neighbours; with a self term, they get their own linear map.
What it costs
The message tensor has E rows. For vector features with E = 1,000,000 edges and 64 output channels in float32, the messages alone take 1,000,000 × 64 × 4 bytes, which is 256 MB, and the concatenated source and destination input [E, 2d] is allocated before that. Time is linear in E for the gather, the message function and the accumulation. Nodes enter through the update and through the size of the output buffer.
Two rounds reach two hops
One round moves information along one edge. Applying a second round moves it along another. Gradients show which input nodes can influence an output. Node 4 receives from nodes 2 and 3 directly, and node 2 receives from 0, 1 and 3:
def influences(num_rounds, target=4):
z = x.clone().requires_grad_()
h = z
for _ in range(num_rounds):
h = torch.zeros_like(h).index_add_(0, dst, h[src]) + h # keep own state
h[target].sum().backward()
return (z.grad.abs().sum(dim=1) > 0).nonzero().flatten().tolist()
print(influences(1)) # [2, 3, 4]
print(influences(2)) # [0, 1, 2, 3, 4]
After one round node 4 depends on itself and its two in-neighbours. After two rounds it also depends on nodes 0 and 1, through node 2.
Two properties to test in your own layer
Reordering the edge columns must not change the output, and renaming the nodes must rename the outputs in the same way (permutation equivariance). Both tests are short and catch most indexing mistakes:
generator = torch.Generator().manual_seed(2)
edge_order = torch.randperm(E, generator=generator)
node_perm = torch.randperm(N, generator=generator) # old id -> new id
x_renamed = torch.empty_like(x)
x_renamed[node_perm] = x
edges_renamed = node_perm[edge_index]
with torch.no_grad():
for aggr in ("sum", "mean", "max"):
torch.manual_seed(3)
net = MessagePassing(2, 4, aggr=aggr)
base = net(x, edge_index)
assert torch.allclose(base, net(x, edge_index[:, edge_order]), atol=1e-6)
assert torch.allclose(net(x_renamed, edges_renamed)[node_perm], base, atol=1e-6)
print("edge order and node renaming checks passed")
A third mistake that neither test catches is aggregating at the wrong end. Using src instead of dst in the aggregation is still permutation equivariant; it just passes information backwards. Test one small graph whose answer you know by hand, as above.
On a GPU, index_add_ with repeated indices can add in a different order between runs, so results may differ in the last digits. Compare with a tolerance.
What changes for images and other tensors
Nothing in the gather and scatter steps assumes vectors. x[src] works for [N, C, H, W], and index_add_ adds whole tensors:
maps = torch.arange(5 * 2 * 3 * 3, dtype=torch.float32).view(5, 2, 3, 3)
tensor_sum = torch.zeros_like(maps).index_add_(0, dst, maps[src])
assert torch.equal(tensor_sum[2], maps[0] + maps[1] + maps[3])
print(maps[src].shape) # torch.Size([6, 2, 3, 3])
What changes is the rest: the count for a mean must be viewed as [N, 1, 1, 1], the linear message becomes a convolution, and the message buffer is E × C × H × W values. LinearMessagePassing accepts vectors only. Inside tensor message passing shows the layers written for feature maps, and the TGraphX architecture reference places them in the package.
How named layers fit this pattern
Most layers you meet are choices for the three functions:
- GCN copies the source features, weights each message by a number computed from node degrees, and sums. See the GCN layer worked by hand.
- GIN sums neighbours, adds the node's own state and applies an MLP.
- Attention layers compute a weight per edge from both endpoint features and normalise it over each node's incoming edges.
When not to write your own
A hand-written layer is the clearest way to learn the mechanism and is fine for a custom message function. A library earns its place when you need batching of many graphs, neighbour sampling, edge features handled consistently or a large set of tested layers. The article on raw PyTorch tensors versus a graph object discusses that trade-off for the data side.
Summary
Gather with x[src], build messages, accumulate with index_add_ on dst, then update. Use include_self=False for a scatter maximum, never accumulate with out[dst] += ..., and keep a hand-checked example in your tests.
References
- Justin Gilmer, Samuel S. Schoenholz, Patrick F. Riley, Oriol Vinyals and George E. Dahl. Neural Message Passing for Quantum Chemistry. ICML 2017.
- Peter W. Battaglia and co-authors. Relational inductive biases, deep learning, and graph networks. arXiv preprint, 2018.