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 carries attributes and node states at layer are . One general form is
Here contains the sources of incoming edges to ; parallel edges contribute one message per copy. Neighborhood aggregation 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.
Sum retains multiplicity: for numbers, sums to 4 and sums to 3. Mean and maximum do not always distinguish it: and have equal means and maxima but different sums. Scalar sum also does not distinguish all multisets: and 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 correspond bijectively to those of the new node. Since uses the same parameters, each renamed message equals its original counterpart. Invariant aggregation returns the same despite reordering; shared 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 , first row src and second dst; a row of x[src] is an outgoing edge’s feature. If , gather has shape ; a message function can convert it to . The gather-scatter duality appears by writing selection matrix with when . Then gather is . For output gradient , the vector-Jacobian product is : sum by source index. Conversely, the adjoint of scatter-sum is gather by destination index. The chain rule explains both operations.
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 per edge uses symmetric degree normalization. Mean aggregation uses factor for inputs of ; these are different operations on unequal-degree graphs. Adding self-loops changes degrees and must precede calculating those factors. If the update already includes , 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 , hidden dimension and one MLP per edge. With matrices multiplying rows on the right:
has shape , is and is . The residual connection preserves dimension and lets an isolated node retain its state plus update bias. In backward, output gradient passes through , then the aggregation adjoint, then , the ReLU mask and . The source and destination parts of 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 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 , the number of copies can grow like a geometric sum in and , 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.
Storing one layer’s messages can cost , 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 ‘s edge indices by the sum of earlier graph sizes. batch[i] stores which graph global node belongs to. No intercomponent connections appear if done correctly.
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 contains the weight of edge and the message is linear and shared, can be evaluated using sparse-matrix dense-matrix multiplication (SpMM), without necessarily materializing a vector per edge. This 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.
"""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.
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.
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.
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.
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.
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)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, , 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.
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.')npm run lab and open the connection link.Exercises
Step 1 of 2. What happens to the multiset of incoming messages for a renamed node?
Step 1 of 2. How is the loss differential written?
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):
passcollate(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):
passKey ideas
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.