Graph data and message passing from scratch
Build the core library: COO graph data structure, GPU gather and scatter operations, a message-passing base class, and batching graphs as a disjoint union. Verify against dense adjacency multiplication and PyTorch Geometric, and measure performance.
After this lesson you can
- Represent graphs with COO edges, attributes, and reproducible splits.
- Implement message passing with index_select and scatter_add in PyTorch.
- Group graphs into minibatches as a disjoint union with a membership vector.
- Verify equivalence to dense computation and compare performance with PyTorch Geometric.
Before you start
One message per edge, not a matrix per graph
A citation network may have thousands of nodes but only a small fraction of possible pairs connected. If dense adjacency occupies bytes in float32, doubling quadruples memory even if citations per article do not change. An edge list instead needs space proportional to . The representation affects both memory and the operations we can perform.
The figure makes the central operation visible. A message takes the source node’s value and deposits it at the destination. After processing all incoming edges, the destination sum equals its neighbor aggregation. Notice that a node with no incoming edges receives zero; it does not disappear from the result.
The data contract
A graph data pipeline preserves connectivity, features, and metadata under an explicit convention. Here edge_index has shape (2, E), 64-bit integers, source in row 0 and destination in row 1. x has shape (N, F); edge_attr, if present, has first dimension E and aligns with edge_index columns. Edge order does not change an exact sum, but does change correspondence with attributes.
The adjacency for multiplying by x has equal to the number of edges from to . Thus sums source features arriving at . An undirected graph is normally represented in both directions; one column sends a message only one way. Self-loops and duplicate edges have meaning: the following code counts them as many times as they appear.
COO stores two indices per edge. CSR groups columns by row and adds row pointers, favoring destination-wise operations once the structure is built and sorted. Conversion has a cost, and for messages depending on arbitrary attributes, generic sparse multiplication may not express the desired operation. Review sparse formats and orientation before comparing results.
For a concrete cost, with nodes, edges, and width , edge_index uses bytes if each index is int64, and float32 features use bytes. This implementation’s explicit message array adds bytes: on a large graph it can exceed both indices and features. The result adds bytes and backward may store additional tensors. These counts exclude allocator overhead, attributes, weights, and temporary buffers. Sparse adjacency alone does not ensure the entire training fits in memory.
COO has no mathematical requirement to sort columns. If you sort, apply the same permutation to edge_attr and any per-edge weights. Coalescing combines repeated coordinates: it can be valid if the operation sums weights linearly, but generally is not equivalent to independently applying a nonlinear function to two edge attributes and then summing. The contract must state whether repetitions are data, errors, or real multiedges.
Splits are part of the contract: save training, validation, and test indices, the seed, and dataset version. In transductive classification a node mask can coexist with the full graph, but validation and test labels do not enter training loss. PyG provides Planetoid(root, name="Cora"), which downloads public data and provides masks; the next lesson uses its protocol. Never generate a new evaluation split without identifying it as such.
Gather, message, and scatter
Message passing with scatter applies a shared function to each edge and then reduces by destination. For a general layer, with edge and attribute ,
This decomposition is the framework of Gilmer and colleagues. index_select gathers (gather) source and destination rows for each COO column; index_add_ scatters and adds (scatter) message rows into the destination accumulator. Functions and share parameters across nodes and edges, not positions in an ordered list. The general framework supports different aggregations; we start with sum to have an exact dense oracle in real arithmetic.
In floating point, summing in a different order can give small differences. On GPU parallel operations may use atomics and order can vary. For debugging enable torch.use_deterministic_algorithms(True) and check the behavior of your version and device: it may choose another implementation or reject an operation without a deterministic alternative. Numerical tolerance does not excuse systematic orientation differences.
Distinguishing aggregation from update avoids a design error: an isolated node produces zero aggregate, but can preserve or transform its own feature. Adding self-loops is another way to include that information and changes the effective graph. Do not do both accidentally when comparing layers. Nor assume sum and mean are interchangeable: sum preserves multiplicity information and mean normalizes by degree. At a zero-degree node, mean needs a convention; in the exercise it returns zero.
If inputs are and there are edges, gather produces and scatter returns . If changes width to , the accumulator must be , not . Indices are discrete and receive no gradient; features and parameters do. Backward through a destination sum distributes each destination’s gradient to its messages, and backward through gather accumulates again at their sources. A gradient test can therefore detect errors a visual check of one output might miss.
Laboratory: core and tests
You need local Python with PyTorch and PyTorch Geometric; choose CUDA if available. Cells share state and run in order. The class checks shapes and indices before sending tensors to the device; in production you would validate once on loading, not at every training step. index_add_ is differentiable with respect to messages. The interface allows overriding message and update without confusing summation with the learned transformation.
from dataclasses import dataclass
import torch
from torch import nn
@dataclass
class Graph:
x: torch.Tensor
edge_index: torch.Tensor
edge_attr: torch.Tensor | None = None
def validate(self):
assert self.x.ndim == 2
e = self.edge_index
assert e.dtype == torch.long and e.ndim == 2 and e.shape[0] == 2
assert e.device == self.x.device
assert e.numel() == 0 or (int(e.min()) >= 0 and int(e.max()) < len(self.x))
assert self.edge_attr is None or (self.edge_attr.shape[0] == e.shape[1] and self.edge_attr.device == self.x.device)
return self
class MessagePassing(nn.Module):
def message(self, x_src, x_dst, edge_attr):
return x_src
def update(self, x, aggregate):
return aggregate
def forward(self, graph):
x, edges = graph.x, graph.edge_index
src, dst = edges[0], edges[1]
msg = self.message(x.index_select(0, src), x.index_select(0, dst), graph.edge_attr)
out = msg.new_zeros((x.shape[0], msg.shape[1]))
out.index_add_(0, dst, msg)
return self.update(x, out)
print('torch', torch.__version__, 'CUDA', torch.cuda.is_available())npm run lab and open the connection link.A specific public load checks the contract before training. root is a cache you choose and PyG downloads files if missing. Masks included in split="public" are the public Planetoid split; they do not replace other splits or make a result inductive. The PyG Planetoid documentation identifies these masks and dataset size. edge_index follows the source-to-target convention. Keep y and masks separate from Graph, since the layer must not access labels.
from pathlib import Path
from torch_geometric.datasets import Planetoid
root = Path.home() / '.cache' / 'oryon' / 'datasets' / 'Planetoid'
cora = Planetoid(str(root), name='Cora', split='public')[0]
public_graph = Graph(cora.x, cora.edge_index).validate()
train, valid, test = cora.train_mask, cora.val_mask, cora.test_mask
assert not (train & valid).any() and not (train & test).any() and not (valid & test).any()
print('nodos, aristas, características:', cora.num_nodes, cora.num_edges, cora.num_node_features)
print('máscaras train, validación, prueba:', int(train.sum()), int(valid.sum()), int(test.sum()))npm run lab and open the connection link.Now construct a dense reference that accumulates duplicates. Assigning A[dst, src] = 1 would lose them and invalidate the test. We check random graphs, an empty graph, and gradients. Dense computation serves as a small oracle, not a scalable solution.
torch.manual_seed(14)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
layer = MessagePassing().to(device)
errors = []
for n, e in [(5, 0), (17, 75), (64, 300), (128, 500)]:
x = torch.randn(n, 7, device=device, requires_grad=True)
edges = torch.randint(n, (2, e), device=device)
graph = Graph(x, edges).validate()
dense = x.new_zeros((n, n))
dense.index_put_((edges[1], edges[0]), x.new_ones(e), accumulate=True)
sparse_out = layer(graph)
dense_out = dense @ x
errors.append((sparse_out - dense_out).abs().max().item())
gs, = torch.autograd.grad(sparse_out.square().sum(), x, retain_graph=True)
gd, = torch.autograd.grad(dense_out.square().sum(), x)
assert torch.allclose(gs, gd, atol=1e-5, rtol=1e-5)
print('error máximo:', max(errors))
assert max(errors) < 1e-5npm run lab and open the connection link.The dense comparison tests one particular message case. The next test checks another contract property: when permuting rows of x, endpoints must be transformed with the inverse permutation. perm[new] = old, so inverse[old] = new. We also reorder edge columns without changing multiplicity.
n, e = 23, 130
x = torch.randn(n, 5, device=device)
edges = torch.randint(n, (2, e), device=device)
perm = torch.randperm(n, device=device)
inverse = torch.empty_like(perm)
inverse[perm] = torch.arange(n, device=device)
edge_order = torch.randperm(e, device=device)
old = layer(Graph(x, edges))
new = layer(Graph(x[perm], inverse[edges[:, edge_order]]))
print('error de equivariancia:', (new - old[perm]).abs().max().item())
assert torch.allclose(new, old[perm], atol=1e-5, rtol=1e-5)npm run lab and open the connection link.A message function using attributes
The oracle checks only messages identical to the source feature. To check the general interface, now consider scalar message and update . In a learned network you could replace this expression with a shared MLP; here we choose an explicit function so the result can be verified by hand. With x=[2,3,5], edges 0→1, 2→1, 1→2, and weights 1, 2, 0.5, messages are -1, 4, -1, sums 0, 3, -1, and output 2, 6, 4.
class WeightedDifference(MessagePassing):
def message(self, x_src, x_dst, edge_attr):
return edge_attr * (x_src - x_dst)
def update(self, x, aggregate):
return x + aggregate
gx = torch.tensor([[2.], [3.], [5.]], device=device, requires_grad=True)
ge = torch.tensor([[0, 2, 1], [1, 1, 2]], device=device)
weights = torch.tensor([[1.], [2.], [0.5]], device=device)
wg = Graph(gx, ge, weights).validate()
out = WeightedDifference()(wg)
assert torch.allclose(out, torch.tensor([[2.], [6.], [4.]], device=device))
out.sum().backward()
assert torch.allclose(gx.grad.flatten(), torch.tensor([2., -1.5, 2.5], device=device))
print('salida:', out.detach().flatten().cpu().tolist())
print('gradiente:', gx.grad.flatten().cpu().tolist())npm run lab and open the connection link.The gradient of the sum of outputs is [2, -1.5, 2.5]: differentiating the three outputs, , , and . An error swapping source and destination can preserve every tensor shape and go unnoticed; this directed example detects reversal. The attribute is per edge, not per node. If you reorder ge, reorder weights with the same permutation.
Disjoint union and graph readout
Graph minibatching concatenates features and offsets each graph’s indices by the sum of preceding graph sizes. The batch vector assigns each node to its graph; it creates no edges between graphs. The result is a block-diagonal adjacency matrix, but it need never be materialized. A scatter over batch obtains each graph’s node sum. For a mean, divide by node count with an explicit convention for empty graphs.
def batch_graphs(graphs):
if not graphs:
raise ValueError('Se requiere al menos un grafo')
for g in graphs:
g.validate()
attrs = [g.edge_attr is not None for g in graphs]
if any(attrs) and not all(attrs):
raise ValueError('Todos los grafos deben tener atributos de arista o ninguno')
offsets, total = [], 0
for g in graphs:
offsets.append(total)
total += len(g.x)
x = torch.cat([g.x for g in graphs])
edges = torch.cat([g.edge_index + offset for g, offset in zip(graphs, offsets)], dim=1)
batch = torch.cat([torch.full((len(g.x),), i, dtype=torch.long, device=x.device)
for i, g in enumerate(graphs)])
ea = torch.cat([g.edge_attr for g in graphs]) if all(attrs) else None
return Graph(x, edges, ea).validate(), batch
g1 = Graph(torch.tensor([[2.], [3.]], device=device), torch.tensor([[0], [1]], device=device))
g2 = Graph(torch.tensor([[5.], [7.], [11.]], device=device), torch.tensor([[1, 2], [0, 1]], device=device))
bg, membership = batch_graphs([g1, g2])
joined = layer(bg)
assert torch.equal(joined, torch.cat([layer(g1), layer(g2)]))
readout = bg.x.new_zeros((2, 1)).index_add_(0, membership, joined)
print('aristas desplazadas:', bg.edge_index.cpu().tolist(), 'sumas:', readout.flatten().cpu().tolist())npm run lab and open the connection link.The second graph begins at index 2. Without the offset, its message would end up in the first graph and the concatenation check would fail. The membership vector serves graph readout, not determining which nodes are neighbors.
To reverse batching you also need each graph’s sizes or pointers. batch identifiers are positions within the batch, not global identities. If a graph has no nodes, the membership vector alone cannot distinguish it from an absent graph: store graph count and a readout convention. The previous function accepts empty tensors provided their dimensions and devices are compatible, but requires at least one Graph object.
With sum reduction, graph output is invariant to node order, while intermediate node outputs are equivariant. Invariant means the final vector does not change under renumbering; equivariant means output rows are renumbered in the same way. Confusing the terms leads to incorrect tests: comparing rows without applying the corresponding permutation would reject a correct implementation.
Comparison with PyG and benchmark
The PyG interface uses the same source_to_target flow for COO. We compare exactly the same operation, without additional weights, self-loops, or normalization. The benchmark measures only forward with data already on device: data creation, transfer, and preparation are excluded. It includes warmup and explicit synchronization because CUDA executes asynchronously; see benchmark methodology. Results depend on GPU, version, and concurrent load and do not guarantee a fixed factor on other machines.
from torch_geometric.nn import MessagePassing as PyGMessagePassing
import time
class PyGSum(PyGMessagePassing):
def __init__(self):
super().__init__(aggr='add')
def forward(self, x, edge_index):
return self.propagate(edge_index, x=x, size=(len(x), len(x)))
def message(self, x_j):
return x_j
pyg = PyGSum().to(device)
n, e, f = 10000, 200000, 32
torch.manual_seed(14)
x = torch.randn(n, f, device=device)
edges = torch.randint(n, (2, e), device=device)
g = Graph(x, edges).validate()
with torch.no_grad():
a, b = layer(g), pyg(x, edges)
delta = (a - b).abs().max().item()
assert torch.allclose(a, b, atol=1e-5, rtol=1e-5)
def measure(fn, warm=5, repeats=20):
for _ in range(warm):
fn()
if device.type == 'cuda': torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(repeats):
fn()
if device.type == 'cuda': torch.cuda.synchronize()
return (time.perf_counter() - t0) / repeats
own = measure(lambda: layer(g))
reference = measure(lambda: pyg(x, edges))
print('dispositivo:', device, 'error PyG:', delta)
print('aristas/s propias y PyG:', round(e / own), round(e / reference))
print('cociente tiempos propio/PyG:', round(own / reference, 3))npm run lab and open the connection link.The next benchmark reduces size so the dense matrix fits comfortably. Its construction is excluded from timing, as is COO construction, and output equality is checked first. This compares the aggregation kernel at this size, not loading or a trained task.
small_n, small_e, small_f = 2048, 30000, 32
sx = torch.randn(small_n, small_f, device=device)
se = torch.randint(small_n, (2, small_e), device=device)
sg = Graph(sx, se).validate()
adj = sx.new_zeros((small_n, small_n))
adj.index_put_((se[1], se[0]), sx.new_ones(small_e), accumulate=True)
with torch.no_grad():
assert torch.allclose(layer(sg), adj @ sx, atol=1e-5, rtol=1e-5)
sparse_t = measure(lambda: layer(sg))
dense_t = measure(lambda: adj @ sx)
print('bytes adyacencia densa:', adj.numel() * adj.element_size())
print('bytes índices COO:', se.numel() * se.element_size())
print('aristas/s scatter y denso:', round(small_e / sparse_t), round(small_e / dense_t))npm run lab and open the connection link.A dense matrix can be faster at moderate size because it uses highly optimized matrix multiplication, even though it stores and multiplies many zeros. Its edges per second are a comparison unit for this input, not the number of operations performed by the dense product. Changing density or width changes amortization and the crossover point. Always measure the configuration of interest and also record memory and construction if they are part of the workflow being optimized.
Throughput comparisons make sense only with the same , , , type, and operation. A slower version may do additional work, such as gathering destinations unused by this identity message. Do not confuse CPU launch time with GPU work. The experiment records a ratio; it does not turn the goal of being within a factor of two into a universal law. If your run does not meet it, investigate with a profiler and retain the result.
Exercises
import torch
def scatter_mean(src, index, dim_size):
...Step 1 of 2. What happens to incoming edges of a renumbered node?