Message-passing networks: learn the edge computation
消息传递神经网络
Train a continuous neural edge filter, differentiate all seven parameters and batch graphs without cross-graph messages.
message-passingStart with the problem
The general graph-neural-network chapter introduced shared messages and permutation symmetry. Here the design question is narrower: how should an edge’s geometry change the message, and how do several graphs share one training batch without becoming one graph?
Gilmer and colleagues describe learned message, update and readout functions. SchNet develops continuous filters for irregularly positioned objects. We build an original two-hidden-unit filter driven by squared distance, then train its parameters on one tiny graph. This isolates the edge computation; it is not a molecular benchmark or a reproduction of the complete SchNet architecture.
Definitions and derivation
Each node has coordinates xᵢ, scalar feature hᵢ and graph ID Bᵢ. Within each graph we use every directed pair except self. Two-element vectors a,b,v and scalar c give seven trainable parameters:
All messages read the old h, so the update is synchronous. The self term is added once. Squared distance is unchanged by translation, rotation and reflection; therefore the scalar filter is invariant to those operations. Distance scaling is different and generally changes it. The filter can be negative and is not an attention probability.
For a fixed graph, differentiate the filter through tanh:
The implementation orders parameters as a, b, v, c. It accumulates a seven-component derivative at each receiver. A sum readout and scalar squared-error target then yield:
This shows exactly where the training signal enters every directed edge. It is an ordinary chain-rule calculation, not a separate learning algorithm for graphs. A richer MPNN can condition messages on sender, receiver and edge attributes, use vector features, repeat layers and apply another readout.
Batching must preserve the graph partition. Concatenating coordinates and features is safe only if edges remain within graph IDs. For two three-node complete directed graphs there are twelve messages, not thirty. Their block-diagonal adjacency is implicit in the Bᵢ=Bⱼ condition. Sum readouts must also be computed per graph rather than across the whole batch when targets are graph-specific.
Run the calculation
Run the complete Python 3.12 / NumPy 1.26.4 program:
import numpy as np
def example():
return np.array([[0.,0],[1,0],[1,2]]),np.array([1.,2.,-1.]),np.array([.3,-.2,.1,.4,.5,-.6,.05])
def pass_messages(position,features,theta,batch=None):
x,h,t = [np.asarray(a,dtype=float) for a in (position,features,theta)]
if x.ndim != 2 or not 1 <= len(x) <= 12 or h.shape != (len(x),) or t.shape != (7,) or not all(np.isfinite(a).all() for a in (x,h,t)):
raise ValueError('Use small finite coordinates, scalar node features and seven filter parameters.')
group = np.zeros(len(x),dtype=int) if batch is None else np.asarray(batch)
if group.shape != (len(x),):raise ValueError('One graph ID per node is required.')
out = h.copy(); jac = np.zeros((len(x),7)); edges=0
for i in range(len(x)):
for j in range(len(x)):
if i==j or group[i]!=group[j]:continue
d2 = float(np.sum((x[i]-x[j])**2)); hidden = np.tanh(t[:2]*d2+t[2:4]); weight = hidden@t[4:6]+t[6]
out[i] += h[j]*weight
local = np.r_[t[4:6]*(1-hidden**2)*d2,t[4:6]*(1-hidden**2),hidden,1.]
jac[i] += h[j]*local; edges+=1
return out,jac,edges
def loss_grad(theta,target=1.5):
x,h,_ = example();out,jac,_ = pass_messages(x,h,theta);error=out.sum()-target
return .5*error**2,error*jac.sum(axis=0)
if __name__ == '__main__':
x,h,t=example();out,jac,edges=pass_messages(x,h,t);print('node outputs',out.round(9).tolist(),'graph sum',round(float(out.sum()),9),'directed messages',edges)
grouped,_,count=pass_messages(np.concatenate([x,x+10]),np.r_[h,h],t,[0,0,0,1,1,1]);print('batched graph sums',[round(float(grouped[:3].sum()),9),round(float(grouped[3:].sum()),9)],'messages',count)
start=loss_grad(t)[0]
for _ in range(60):loss,grad=loss_grad(t);t-=.01*grad
print('filter training loss',round(start,9),round(loss_grad(t)[0],9))
Actual output:
node outputs [0.410034561, 1.412718332, 1.250725931] graph sum 3.073478824 directed messages 6
batched graph sums [3.073478824, 3.073478824] messages 12
filter training loss 1.237917805 0.0
The original graph sum is 3.073478824. Duplicating the graph and translating the second copy by ten leaves both sums equal and exactly doubles the message count. Sixty updates of size 0.01 fit the illustrative target 1.5; the final loss rounds to zero at nine decimal places. There is only one training graph, so this is a gradient demonstration, with no held-out generalization claim.
With K hidden filter units, an explicit edge list takes O(EK) filter work and O(NK) accumulated parameter-derivative storage in this reference style. Our loop checks all N² pairs, even for a partitioned batch; production batching should construct valid edges directly. Increasing message depth increases the receptive field but also cost, and may compound numerical or information-loss effects.
When the method fails
Geometry must encode the intended relationships. A distance-only filter cannot distinguish mirror images from scalar inputs alone. A fixed neighborhood cutoff can introduce discontinuities when edges appear or disappear; a smooth filter does not by itself smooth a discontinuous graph-construction rule.
The learned graph sum is not automatically a physically valid energy, and this program does not compute forces. Energy conservation requires a suitable scalar energy and forces defined consistently as its negative coordinate gradient. Atom types, units, periodic boundaries, data splits and force labels would all need explicit treatment in a molecular application.
Exercises with answers
- How many directed messages do two separate three-node complete graphs use?
Answer 1: Twelve: each graph contributes 3×2. Connecting all six nodes would incorrectly create thirty.
- Why can the filter be negative?
Answer 2: It is a learned message coefficient with no softmax or positivity constraint; it is not a probability.
- What is the derivative with respect to output bias c?
Answer 3: Each filter derivative is one, then the graph derivative sums sender features over valid directed edges.
- Does fitting this one target establish molecular accuracy?
Answer 4: No. It only checks the training computation; molecular data, units, force consistency and independent evaluation are absent.
Sources and next steps
Gilmer physical pages 2–3 define the MPNN framework. SchNet physical page 3, Section 3 and Equation 2, defines a continuous filter multiplying neighbor features; its physical page 2 states the physical goals. Our two-unit squared-distance filter and batch tests are separate teaching calculations. Continue with equivariant networks to update coordinates as vectors, and graph neural networks for the general symmetry and expressivity discussion.
Make a prediction, then check
What prevents cross-graph messages in the example?
Learning objectives
- Differentiate a learned edge filter.
- Batch graphs while preserving graph-specific edges and readouts.
Prerequisites & connections
Explore related knowledge →References
- Neural Message Passing for Quantum Chemistry
Justin Gilmer; Samuel S. Schoenholz; Patrick F. Riley; Oriol Vinyals; George E. Dahl · 2017 - SchNet: A continuous-filter convolutional neural network for modeling quantum interactions — arXiv v2
Kristof T. Schütt; Pieter-Jan Kindermans; Huziel E. Sauceda; Stefan Chmiela; Alexandre Tkatchenko; Klaus-Robert Müller · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Neural Message Passing for Quantum Chemistry · Physical pages 2–3: learned message, update and readout definitions.
- SchNet: A continuous-filter convolutional neural network for modeling quantum interactions — arXiv v2 · Physical pages 2–3, Section 3 Equation 2: continuous filter generation and feature-wise neighbor multiplication; scoped physical goals.
Related topics