Module contents
Lesson 9 of 30Core 120 min

Message passing from scratch: forward, backward and graph batching

Build message passing from shared edge functions and invariant aggregation, derive gather and scatter adjoints, batch disjoint graphs, and compare NumPy with PyTorch and PyG.

After this lesson you can

  • Define a general message-passing layer and prove permutation equivariance.
  • Implement gather and scatter aggregation and their backward passes, including maximum ties.
  • Implement and check a message-passing layer with manual gradients.
  • Batch variable-size graphs as a disjoint union and compute graph readouts.
  • Describe computation trees, receptive fields and memory cost.
  • Compare the implementation with PyTorch and PyG.

Before you start

A shared local rule

In a graph, each edge can carry information from source to destination. A layer collects those messages at each node and applies the same rule across the graph. This computation avoids fixing a number of neighbors per node and preserves symmetry under renumbering.

The complete lab module is available for reuse: download mini_mp.py. Each lesson has an independent Python session: download the file and place it beside your local program to import its classes in another lab. Cells on this page also define its contents so they can run from start to finish.

Message, aggregation and update

In the message-passing framework, an edge u→vu\to v carries attributes euv\vb{e}_{uv} and node states at layer ℓ\ell are hu(ℓ)\vb{h}^{(\ell)}_u. One general form is

mu→v=ϕℓ(hv(ℓ),hu(ℓ),euv),av=⨁u∈N(v)mu→v,hv(ℓ+1)=γℓ(hv(ℓ),av).\vb{m}_{u\to v}=\phi_\ell(\vb{h}_v^{(\ell)},\vb{h}_u^{(\ell)},\vb{e}_{uv}),\quad \vb{a}_v=\mathop{\bigoplus}_{u\in N(v)}\vb{m}_{u\to v},\quad \vb{h}_v^{(\ell+1)}=\gamma_\ell(\vb{h}_v^{(\ell)},\vb{a}_v).

Here N(v)N(v) contains the sources of incoming edges to vv; parallel edges contribute one message per copy. Neighborhood aggregation ⨁\bigoplus must be invariant to multiset order, for example channelwise sum, mean or maximum. Functions and parameters are shared by nodes or edges of the same type.

InteractiveOne message-passing step
12345678
x[source] = [1, 0]
1
Gather
Aggregator
Source → destination1 → 2
PhaseGather
Select an edge, advance through gather, message, scatter and update, and change the aggregator. In this explicit example the message copies the source vector and the update adds the destination's previous state.

Sum retains multiplicity: for numbers, {1,1,2}\{1,1,2\} sums to 4 and {1,2}\{1,2\} sums to 3. Mean and maximum do not always distinguish it: {1,1}\{1,1\} and {1}\{1\} have equal means and maxima but different sums. Scalar sum also does not distinguish all multisets: {1,3}\{1,3\} and {2,2}\{2,2\} agree. This choice changes what information can survive, but alone does not characterize the whole network’s expressiveness.

Proof

Rename nodes by a permutation and apply the same renumbering to each edge’s endpoints, its attributes and feature rows. Incoming edges of old node vv correspond bijectively to those of the new node. Since ϕℓ\phi_\ell uses the same parameters, each renamed message equals its original counterpart. Invariant aggregation returns the same av\vb{a}_v despite reordering; shared γℓ\gamma_\ell then returns the same state in the renamed row. Thus output permutes like input. This is permutation equivariance, not invariance: node outputs move with nodes.

∎

Gather, scatter and their adjoints

In COO, edge_index has shape 2×E2\times E, first row src and second dst; a row of x[src] is an outgoing edge’s feature. If H∈Rn×d\mat{H}\in\R^{n\times d}, gather has shape E×dE\times d; a message function can convert it to E×dmE\times d_m. The gather-scatter duality appears by writing selection matrix S∈{0,1}E×n\mat{S}\in\{0,1\}^{E\times n} with Seu=1S_{eu}=1 when u=src(e)u=\mathrm{src}(e). Then gather is SH\mat{S}\mat{H}. For output gradient G\mat{G}, the vector-Jacobian product is S⊤G\mat{S}\T\mat{G}: sum by source index. Conversely, the adjoint of scatter-sum is gather by destination index. The chain rule explains both operations.

InteractiveGather and scatter are adjoints
n1n2n3e1e2e3e4
Matrix S (edges × nodes)
100
010
100
001
x = [1, 2, 3]
Sx = [1, 2, 1, 3]
Operation
Direction
Result[1, 2, 1, 3]
Switch between forward and backward. The selection matrix shows correspondences; two edges sharing a node accumulate gradients. For maximum, try a tie between two messages.

Mean divides the sum by the number of messages at each destination; backward divides the gradient by that same count before gathering it per edge. For maximum, the derivative is unique when each channel has a strict winner. At a tie the function is nondifferentiable: one valid subgradient splits equally among all maxima. The module adopts this convention and returns zero for a node without messages. Other libraries may select one winner or use another tie policy; check before comparing gradients.

For an unweighted undirected graph, summing with factor 1/dudv1/\sqrt{d_u d_v} per edge uses symmetric degree normalization. Mean aggregation uses factor 1/dv1/d_v for inputs of vv; these are different operations on unequal-degree graphs. Adding self-loops changes degrees and must precede calculating those factors. If the update already includes hv\vb{h}_v, an additional self-loop is a modeling choice rather than an automatic requirement.

A concrete layer and its backward pass

This lesson’s module uses input and output states of dimension dd, hidden dimension hh and one MLP per edge. With matrices multiplying rows on the right:

ze=[hsrc(e),hdst(e),ee],re=ReLU⁡(zeW1+b1),me=reW2+b2,hv′=hv+avWu+bu.\begin{aligned} \vb{z}_e&=[\vb{h}_{\mathrm{src}(e)},\vb{h}_{\mathrm{dst}(e)},\vb{e}_e],\\ \vb{r}_e&=\relu(\vb{z}_e\mat{W}_1+\vb{b}_1),\qquad \vb{m}_e=\vb{r}_e\mat{W}_2+\vb{b}_2,\\ \vb{h}'_v&=\vb{h}_v+\vb{a}_v\mat{W}_u+\vb{b}_u. \end{aligned}

W1\mat{W}_1 has shape (2d+de)×h(2d+d_e)\times h, W2\mat{W}_2 is h×hh\times h and Wu\mat{W}_u is h×dh\times d. The residual connection preserves dimension and lets an isolated node retain its state plus update bias. In backward, output gradient passes through Wu⊤\mat{W}_u\T, then the aggregation adjoint, then W2⊤\mat{W}_2\T, the ReLU mask and W1⊤\mat{W}_1\T. The source and destination parts of ze\vb{z}_e accumulate into input rows using two scatter-add operations, and the direct residual gradient is added.

For ReLU choose derivative zero at exactly zero input. A finite-difference check must avoid changes in the maximum winner and ReLU’s nondifferentiable point; ties are checked separately under the stated convention. Caches from two calls to forward can be retained with return_cache=True: in two branches such as DGI, sum parameter gradients from both before updating, and do not change weights between their forward and backward computations.

Receptive field and batches

The computation tree unrolls a node’s dependencies across KK layers. A copy per walk is distinct from a new node: two paths can reach the same node in the original graph. On a graph whose degree is bounded by Δ\Delta, the number of copies can grow like a geometric sum in Δ\Delta and KK, although a matrix implementation reuses per-node states. If two labeled trees and initial features are equal, a shared MPNN produces the same state at their roots by induction over layers. The converse is not automatic.

InteractiveThe tree each node sees
12345
11245124521341351

La rama discontinua lleva el estado previo del propio nodo. Igualdad de árboles supone características iniciales idénticas y agregación compartida; no afirma que todos los árboles distintos sean distinguibles.

Root
2
Copies in tree17
Roots with same tree1
Choose root and depth. Dashed branches carry the node's own previous state; others represent neighbors. The tree repeats nodes reached by distinct paths and marks roots with the same tree under identical initial features.

Storing one layer’s messages can cost O(Edm)O(E d_m), in addition to states, indices and caches. With many layers saved for backward, that term can dominate. Some linear operators allow messages to be fused or recomputed; the formula does not claim that all implementations store exactly the same tensors.

A disjoint-union batch concatenates node matrices and offsets graph gg‘s edge indices by the sum of earlier graph sizes. batch[i] stores which graph global node ii belongs to. No intercomponent connections appear if done correctly.

InteractiveBuild a batch
G1G2G3012345
  • Correct edge
  • Wrong index
x = [[1, 0], [1, 1], [2, 0], [2, 1], [2, 2], [3, 0]]
batch = [0, 0, 1, 1, 1, 2]
edge_index = [0, 1, 2, 3, 4] / [1, 0, 3, 4, 2]
Nodes6
Cross graphs0
Assigned to wrong graph0
Include or exclude graphs and enable the missing-offset error. The visualization uses zero-based global indices; the readout distinguishes edges crossing graphs from edges wholly placed in the wrong graph.

No edge crossing graphs is a necessary but insufficient check: an unshifted edge can lie entirely inside the previous graph. Also check that every edge belongs to its intended block. To obtain a per-graph output, a segment readout aggregates rows with the same batch value. Sum and mean express different assumptions: sum can preserve size, while mean can remove it. For an empty graph, state what each reduction returns.

Sparse form

If Avu\mat{A}_{vu} contains the weight of edge u→vu\to v and the message is linear and shared, H′=AHW\mat{H}'=\mat{A}\mat{H}\mat{W} can be evaluated using sparse-matrix dense-matrix multiplication (SpMM), without necessarily materializing a vector per edge. This A\mat{A} uses destination row and source column, the transpose of the source-row adjacency convention in the first lesson. If the message function depends on destination, attributes or per-edge nonlinearities, one SpMM generally no longer represents the same operation.

Lab: a mini framework in NumPy

The first cell contains exactly the downloadable module. It defines gather and its adjoints, three aggregators handling isolates and ties, batching, readout and MPLayer. PyTorch code is imported only when torch_layer_from_numpy is called in the local runtime.

[ ]Mini message-passing frameworkBrowser
"""Paso de mensajes reproducible para Oryon Learn.

edge_index[0] contiene orígenes y edge_index[1] destinos. Cada columna es
una arista. Las operaciones conservan multiaristas y admiten nodos aislados.
"""
import numpy as np


def gather(x, index):
    return np.asarray(x)[np.asarray(index, dtype=np.int64)]


def gather_backward(grad, index, n):
    out = np.zeros((n, grad.shape[1]), dtype=grad.dtype)
    np.add.at(out, np.asarray(index, dtype=np.int64), grad)
    return out


def scatter_sum(messages, dst, n):
    out = np.zeros((n, messages.shape[1]), dtype=messages.dtype)
    np.add.at(out, np.asarray(dst, dtype=np.int64), messages)
    return out


def scatter_mean(messages, dst, n):
    counts = np.bincount(np.asarray(dst, dtype=np.int64), minlength=n)
    out = scatter_sum(messages, dst, n)
    return out / np.maximum(counts[:, None], 1), counts


def scatter_max(messages, dst, n):
    """Máximo por destino y canal; sin mensajes devuelve cero.

    En empates la VJP elegida reparte por igual entre todos los ganadores.
    """
    dst = np.asarray(dst, dtype=np.int64)
    out = np.full((n, messages.shape[1]), -np.inf, dtype=messages.dtype)
    np.maximum.at(out, dst, messages)
    counts = np.bincount(dst, minlength=n)
    out[counts == 0] = 0
    winners = messages == out[dst]
    ties = np.zeros_like(out, dtype=np.int64)
    np.add.at(ties, dst, winners.astype(np.int64))
    return out, (dst, winners, ties)


def scatter_max_backward(grad_out, argmax, num_edges):
    dst, winners, ties = argmax
    if len(dst) != num_edges:
        raise ValueError('num_edges no coincide con el registro de máximos')
    return grad_out[dst] * winners / np.maximum(ties[dst], 1)


def aggregate(messages, dst, n, mode='sum'):
    if mode == 'sum':
        return scatter_sum(messages, dst, n), (mode, np.asarray(dst, dtype=np.int64), None)
    if mode == 'mean':
        out, counts = scatter_mean(messages, dst, n)
        return out, (mode, np.asarray(dst, dtype=np.int64), counts)
    if mode == 'max':
        out, cache = scatter_max(messages, dst, n)
        return out, (mode, np.asarray(dst, dtype=np.int64), cache)
    raise ValueError('agregador desconocido')


def aggregate_backward(grad, cache):
    mode, dst, aux = cache
    if mode == 'sum':
        return grad[dst]
    if mode == 'mean':
        return grad[dst] / np.maximum(aux[dst, None], 1)
    return scatter_max_backward(grad, aux, len(dst))


def collate(graphs):
    """Concatena pares (x, edge_index), desplazando índices por grafo."""
    xs, es, batches = [], [], []
    offset = 0
    for graph_id, (x, edge_index) in enumerate(graphs):
        x = np.asarray(x)
        e = np.asarray(edge_index, dtype=np.int64)
        if e.ndim != 2 or e.shape[0] != 2:
            raise ValueError('edge_index debe tener forma (2, E)')
        if e.size and (e.min() < 0 or e.max() >= len(x)):
            raise ValueError('índice fuera del grafo local')
        xs.append(x); es.append(e + offset)
        batches.append(np.full(len(x), graph_id, dtype=np.int64))
        offset += len(x)
    if not xs:
        raise ValueError('el lote no puede estar vacío')
    return np.concatenate(xs), np.concatenate(es, axis=1), np.concatenate(batches)


def readout(x, batch, num_graphs, mode='sum'):
    return aggregate(np.asarray(x), np.asarray(batch), num_graphs, mode)[0]


class MPLayer:
    """Mensaje MLP y actualización residual; d de entrada y salida coinciden.

    forward puede devolver una caché explícita para diferenciar varias ramas
    (por ejemplo, entradas original y corrupta en DGI) antes de un paso SGD.
    """
    def __init__(self, d, hidden, edge_dim=0, aggregation='sum', seed=0):
        if aggregation not in ('sum', 'mean', 'max'):
            raise ValueError('agregador desconocido')
        self.d, self.hidden, self.edge_dim, self.aggregation = d, hidden, edge_dim, aggregation
        r = np.random.default_rng(seed)
        self.params = {
            'W1': r.normal(0, 1/np.sqrt(2*d+edge_dim), (2*d+edge_dim, hidden)),
            'b1': np.zeros(hidden),
            'W2': r.normal(0, 1/np.sqrt(hidden), (hidden, hidden)),
            'b2': np.zeros(hidden),
            'Wu': r.normal(0, 1/np.sqrt(hidden), (hidden, d)),
            'bu': np.zeros(d),
        }
        self.cache = None

    def forward(self, x, edge_index, edge_attr=None, return_cache=False):
        x = np.asarray(x, dtype=float)
        e = np.asarray(edge_index, dtype=np.int64)
        if x.ndim != 2 or x.shape[1] != self.d or e.ndim != 2 or e.shape[0] != 2:
            raise ValueError('formas incompatibles de x o edge_index')
        src, dst = e
        if e.size and (e.min() < 0 or e.max() >= len(x)):
            raise ValueError('índice de nodo fuera de rango')
        if edge_attr is None:
            edge_attr = np.zeros((e.shape[1], self.edge_dim), dtype=x.dtype)
        edge_attr = np.asarray(edge_attr, dtype=float)
        if edge_attr.shape != (e.shape[1], self.edge_dim):
            raise ValueError('forma incompatible de edge_attr')
        z = np.concatenate([gather(x, src), gather(x, dst), edge_attr], axis=1)
        p = self.params
        pre = z @ p['W1'] + p['b1']
        hidden = np.maximum(pre, 0)
        messages = hidden @ p['W2'] + p['b2']
        agg, agg_cache = aggregate(messages, dst, len(x), self.aggregation)
        out = x + agg @ p['Wu'] + p['bu']
        cache = (x, src, dst, z, pre, hidden, agg, agg_cache)
        self.cache = cache
        return (out, cache) if return_cache else out

    def backward(self, grad_out, cache=None):
        if cache is None:
            cache = self.cache
        if cache is None:
            raise ValueError('llama a forward antes de backward')
        x, src, dst, z, pre, hidden, agg, agg_cache = cache
        g = np.asarray(grad_out, dtype=float)
        if g.shape != x.shape:
            raise ValueError('gradiente de salida de forma incompatible')
        p = self.params
        grads = {'Wu': agg.T @ g, 'bu': g.sum(axis=0)}
        gmsg = aggregate_backward(g @ p['Wu'].T, agg_cache)
        grads['W2'] = hidden.T @ gmsg; grads['b2'] = gmsg.sum(axis=0)
        gpre = (gmsg @ p['W2'].T) * (pre > 0)
        grads['W1'] = z.T @ gpre; grads['b1'] = gpre.sum(axis=0)
        gz = gpre @ p['W1'].T
        grads['x'] = g + gather_backward(gz[:, :self.d], src, len(x)) + gather_backward(gz[:, self.d:2*self.d], dst, len(x))
        grads['edge_attr'] = gz[:, 2*self.d:]
        return grads

    def step(self, grads, lr):
        for name in self.params:
            self.params[name] -= lr * grads[name]


def torch_layer_from_numpy(layer):
    """Crea el equivalente PyTorch solo cuando el runtime local lo tiene."""
    import torch
    from torch import nn

    class TorchMPLayer(nn.Module):
        def __init__(self, source):
            super().__init__()
            self.d, self.edge_dim, self.aggregation = source.d, source.edge_dim, source.aggregation
            for name, value in source.params.items():
                self.register_parameter(name, nn.Parameter(torch.as_tensor(value.copy(), dtype=torch.float64)))

        def forward(self, x, edge_index, edge_attr=None):
            src, dst = edge_index
            if edge_attr is None:
                edge_attr = x.new_zeros((src.numel(), self.edge_dim))
            z = torch.cat((x[src], x[dst], edge_attr), dim=1)
            msg = torch.relu(z @ self.W1 + self.b1) @ self.W2 + self.b2
            n = x.shape[0]
            if self.aggregation == 'max':
                index = dst[:, None].expand_as(msg)
                initial = x.new_full((n, msg.shape[1]), -torch.inf)
                agg = initial.scatter_reduce(0, index, msg, reduce='amax', include_self=False)
                counts = torch.bincount(dst, minlength=n)
                agg = torch.where(counts[:, None] > 0, agg, torch.zeros_like(agg))
            else:
                agg = x.new_zeros((n, msg.shape[1])).index_add(0, dst, msg)
                if self.aggregation == 'mean':
                    counts = torch.bincount(dst, minlength=n).clamp_min(1)
                    agg = agg / counts[:, None]
            return x + agg @ self.Wu + self.bu

    return TorchMPLayer(layer)

The following checks include an isolated node and tied maxima. The gradient check uses a seeded direction and avoids ReLU discontinuities and winner changes; below we compare all parameters with autograd.

[ ]Adjoints, ties and equivarianceBrowser
edges = np.array([[0,1,2,0,3],[1,2,1,2,1]], dtype=np.int64)
x = np.random.default_rng(8).normal(size=(5,3))
attr = np.random.default_rng(9).normal(size=(5,2))
probe = np.random.default_rng(10).normal(size=(5,3))
msgs = np.array([[2.,1.],[2.,4.],[1.,4.]])
out, saved = scatter_max(msgs, np.array([0,0,0]), 2)
grad = scatter_max_backward(np.array([[6.,8.],[99.,99.]]), saved, 3)
assert np.allclose(out, [[2,4],[0,0]])
assert np.allclose(grad, [[3,0],[3,4],[0,4]])
for mode in ('sum','mean','max'):
    layer = MPLayer(3,4,edge_dim=2,aggregation=mode,seed=4)
    y, cache = layer.forward(x,edges,attr,return_cache=True)
    grads = layer.backward(probe,cache)
    direction = np.random.default_rng(11).normal(size=x.shape)
    eps = 1e-6
    plus = np.sum(layer.forward(x+eps*direction,edges,attr)*probe)
    minus = np.sum(layer.forward(x-eps*direction,edges,attr)*probe)
    numerical = (plus-minus)/(2*eps)
    analytical = np.sum(grads['x']*direction)
    perm = np.array([4,0,2,1,3]); inverse = np.argsort(perm)
    assert np.allclose(layer.forward(x[perm],inverse[edges],attr), y[perm])
    assert np.isclose(numerical,analytical,rtol=1e-5,atol=1e-5)
    print(mode, 'gradiente direccional:', round(analytical,6), 'equivarianza: sí')
print('máximo:',out.tolist(),'gradiente con empate:',grad.tolist())

To check parameters too, perturb all of them in a known direction and compare the directional derivative with the inner product of their gradients. Restore original weights after each evaluation.

[ ]Parameter gradients by finite differencesBrowser
for mode in ('sum','mean','max'):
    layer=MPLayer(3,4,edge_dim=2,aggregation=mode,seed=4)
    y,cache=layer.forward(x,edges,attr,return_cache=True)
    grads=layer.backward(probe,cache)
    rng=np.random.default_rng(12)
    directions={name:rng.normal(size=value.shape) for name,value in layer.params.items()}
    original={name:value.copy() for name,value in layer.params.items()}
    analytical=sum(np.sum(grads[name]*directions[name]) for name in layer.params)
    eps=1e-6
    for name in layer.params: layer.params[name][...] = original[name]+eps*directions[name]
    plus=np.sum(layer.forward(x,edges,attr)*probe)
    for name in layer.params: layer.params[name][...] = original[name]-eps*directions[name]
    minus=np.sum(layer.forward(x,edges,attr)*probe)
    for name in layer.params: layer.params[name][...] = original[name]
    numerical=(plus-minus)/(2*eps)
    assert np.isclose(numerical,analytical,rtol=1e-5,atol=1e-5)
    print(mode, 'gradiente de parámetros:',round(analytical,6), 'coincide')

The next cell batches graphs of two and three nodes, including an isolate. The displayed batch starts at zero, as does edge_index.

[ ]Disjoint union and readoutBrowser
g1=(np.array([[1.,0.],[0.,1.]]),np.array([[0,1],[1,0]]))
g2=(np.array([[2.,0.],[0.,2.],[1.,1.]]),np.array([[0,1],[1,0]]))
X,E,batch=collate([g1,g2])
assert np.all(batch[E[0]]==batch[E[1]])
print('edge_index:',E.tolist(),'batch:',batch.tolist())
print('suma por grafo:',readout(X,batch,2,'sum').tolist())
print('media por grafo:',readout(X,batch,2,'mean').tolist())

Now train two layers with custom SGD to predict distance to the marked node, truncated at 2, on nine-node paths. Train with marks at even positions and evaluate odd positions. The task uses two hops: one layer cannot distinguish certain interior nodes seeing exactly the same one-hop attributes even though one is distance 2 and another farther away. This small experiment checks forward and backward flow; it does not establish generalization to arbitrary graphs.

[ ]Two hops with SGD from scratchBrowser
n = 9
path_edges = np.array([(a,b) for u in range(n-1) for a,b in ((u,u+1),(u+1,u))],dtype=int).T
layers = [MPLayer(2,8,seed=3), MPLayer(2,8,seed=4)]
head = np.random.default_rng(0).normal(0,0.1,size=(2,1))
bias = np.zeros(1)
train_markers, test_markers = [0,2,4,6,8], [1,3,5,7]

def sample(marker):
    features = np.ones((n,2)); features[:,0] = 0; features[marker,0] = 1
    target = np.minimum(np.abs(np.arange(n)-marker),2)[:,None].astype(float)
    return features,target

def mse(marker):
    h,y = sample(marker)
    for layer in layers:
        h = layer.forward(h,path_edges)
    return np.mean((h @ head + bias-y)**2)

before = (np.mean([mse(i) for i in train_markers]),np.mean([mse(i) for i in test_markers]))
for epoch in range(400):
    for marker in train_markers:
        x0,y=sample(marker)
        h1=layers[0].forward(x0,path_edges)
        h2=layers[1].forward(h1,path_edges)
        prediction=h2 @ head + bias
        gp=2*(prediction-y)/n
        gh=gp @ head.T; gw=h2.T @ gp; gb=gp.sum(axis=0)
        g2=layers[1].backward(gh); g1=layers[0].backward(g2['x'])
        layers[1].step(g2,0.005); layers[0].step(g1,0.005)
        head-=0.005*gw; bias-=0.005*gb
after = (np.mean([mse(i) for i in train_markers]),np.mean([mse(i) for i in test_markers]))
print('MSE inicial train/test:',np.round(before,6).tolist())
print('MSE final train/test:',np.round(after,6).tolist())
assert after[0] < before[0] and after[1] < before[1]

In one execution with those seeds, training MSE fell from 3.186375 to 0.009329 and held-out-position MSE from 3.045340 to 0.010528. These are losses from this small example and execution; evaluation keeps the same graph and changes the mark position, so it does not test generalization to new graphs.

From NumPy to PyTorch and PyG

The local runtime is a separate session from the browser. The hidden setup cell reproduces the same module so local checks are self-contained; in an external program you can import the downloaded file instead of copying it.

The PyTorch version uses index_add for sum and mean, and scatter_reduce for maximum. The PyG subclass expresses the same rule through propagate and message: x_j is source and x_i destination. Outputs and gradients are compared using the same weights and inputs for all three aggregators.

[ ]NumPy, PyTorch and MessagePassingLocal GPU
import torch
from torch_geometric.nn import MessagePassing

class PyGCopy(MessagePassing):
    def __init__(self, source):
        super().__init__(aggr={'sum':'add','mean':'mean','max':'max'}[source.aggregation], node_dim=0)
        self.reference = torch_layer_from_numpy(source)

    def forward(self, x, edge_index, edge_attr):
        aggregated = self.propagate(edge_index, x=x, edge_attr=edge_attr, size=(len(x),len(x)))
        return x + aggregated @ self.reference.Wu + self.reference.bu

    def message(self, x_i, x_j, edge_attr):
        model=self.reference
        z=torch.cat((x_j,x_i,edge_attr),dim=1)
        return torch.relu(z @ model.W1 + model.b1) @ model.W2 + model.b2

edge_index=np.array([[0,1,2,0,3],[1,2,1,2,1]],dtype=np.int64)
x_np=np.random.default_rng(8).normal(size=(5,3))
edge_np=np.random.default_rng(9).normal(size=(5,2))
upstream=np.random.default_rng(10).normal(size=(5,3))
for mode in ('sum','mean','max'):
    layer=MPLayer(3,4,edge_dim=2,aggregation=mode,seed=4)
    expected,cache=layer.forward(x_np,edge_index,edge_np,return_cache=True)
    grad=layer.backward(upstream,cache)
    standard=torch_layer_from_numpy(layer)
    pyg=PyGCopy(layer)
    results=[]
    for model in (standard,pyg):
        xt=torch.tensor(x_np,requires_grad=True)
        et=torch.tensor(edge_np,requires_grad=True)
        result=model(xt,torch.tensor(edge_index),et)
        (result*torch.tensor(upstream)).sum().backward()
        assert np.allclose(result.detach().numpy(),expected,atol=1e-10)
        assert np.allclose(xt.grad.numpy(),grad['x'],atol=1e-9)
        assert np.allclose(et.grad.numpy(),grad['edge_attr'],atol=1e-9)
        parameters=model.reference if isinstance(model,PyGCopy) else model
        for name in layer.params:
            assert np.allclose(getattr(parameters,name).grad.numpy(),grad[name],atol=1e-9)
        results.append(float(torch.max(torch.abs(result.detach()-torch.tensor(expected)))))
    print(mode, 'diferencia máxima PyTorch/PyG:',results)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next experiment measures a simpler operation, summing source features, so scatter and SpMM compute exactly the same result. It uses float32, d=32d=32, seeded directed edges and GPU if available. Time and memory depend on device and other tasks and are shown as measurements from your execution. Incremental memory is measured after preparing indices, features and the sparse matrix; it excludes constructing that matrix. GPU atomic reductions can vary slightly in floating point.

[ ]Scatter versus SpMM on GPULocal GPU
if torch.cuda.is_available():
    device='cuda'; torch.manual_seed(17)
    for m in (10_000,100_000,1_000_000):
        n=10_000; d=32
        src=torch.randint(n,(m,),device=device)
        dst=torch.randint(n,(m,),device=device)
        features=torch.randn(n,d,device=device)
        A=torch.sparse_coo_tensor(torch.stack((dst,src)),torch.ones(m,device=device),(n,n)).coalesce()
        def scatter_run():
            return torch.zeros_like(features).index_add_(0,dst,features[src])
        def spmm_run():
            return torch.sparse.mm(A,features)
        first=scatter_run(); second=spmm_run(); torch.cuda.synchronize()
        assert torch.allclose(first,second,atol=1e-4,rtol=1e-4)
        del first,second
        def measure(fn):
            for _ in range(2): out=fn()
            del out; torch.cuda.synchronize()
            baseline=torch.cuda.memory_allocated()
            torch.cuda.reset_peak_memory_stats()
            start=torch.cuda.Event(enable_timing=True); end=torch.cuda.Event(enable_timing=True)
            start.record()
            for _ in range(5): out=fn()
            end.record(); torch.cuda.synchronize()
            ms=start.elapsed_time(end)/5
            peak=(torch.cuda.max_memory_allocated()-baseline)/1e6
            del out
            return round(ms,4),round(peak,2)
        print('aristas:',m,'scatter ms/MB:',measure(scatter_run),'SpMM ms/MB:',measure(spmm_run))
        del src,dst,features,A
else:
    print('No hay CUDA: ejecuta esta celda en un laboratorio con GPU para medir el rango solicitado.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: A shared layer with invariant aggregation is equivariant to a node permutation.
0
The permutation is applied to features and both endpoints of every edge; attributes travel with their edge.

Step 1 of 2. What happens to the multiset of incoming messages for a renamed node?

Proof
Prove: The VJP of gather with selection matrix S is scatter-add with the same indices.
0
Let y = Sx and let g be the gradient of a loss with respect to y.

Step 1 of 2. How is the loss differential written?

Numeric
A layer stores a float32 edge tensor of shape (50 million, 256). How many decimal GB does it occupy? One GB equals 10⁹ bytes.
Numeric
If three independent tensors like the previous one are retained for backward, how many decimal GB do they occupy in total?
Quiz
Compare scalar multisets {1, 1, 2} and {1, 2}. Which aggregators distinguish them?
Code
Implement scatter_max_backward(grad_out, argmax, num_edges). argmax is (dst, winners, ties): edge destinations, an (E,d) Boolean winner matrix per channel, and winner counts per destination and channel (n,d). Split ties equally; nodes without neighbors contribute no gradient.
import numpy as np
def scatter_max_backward(grad_out, argmax, num_edges):
  pass
Shift+Enter to run
Code
Implement collate(graphs) for a nonempty list of (x, edge_index) pairs, each x of shape (n_g,d) and each edge_index of shape (2,E_g) with valid local indices. Return x, offset edge_index and batch with each node's graph index.
import numpy as np
def collate(graphs):
  pass
Shift+Enter to run

Key ideas

Key idea
An MPNN shares a local rule and aggregates messages invariantly, so its node outputs are equivariant to renumbering. Gather and scatter are adjoint operations in backward.

The explicit implementation allows dimensions, gradients and batches to be verified; a production version can use SpMM when the message is linear and does not require materializing per-edge attributes.