Module contents
Stage 6 of 8Advanced 110 min

E(n)-equivariant networks and molecular properties

Implement EGNN, a network equivariant to rotations, translations, and reflections using 3D coordinates, and train it on QM9 to predict quantum properties. Before training, write a numerical equivariance test that architecture changes must pass, and compare with a geometry-free GNN and one using coordinates without symmetry.

After this lesson you can

  • Implement an EGNN layer updating features and coordinates.
  • Write invariance and equivariance tests with random E(3) transformations.
  • Train on a QM9 property with target normalization and MAE in its units.
  • Compare with geometry-free models and rotational data augmentation.

Before you start

A molecule has no favorite axes

Rotating or translating a molecule does not change its HOMO energy. If a function predicts a scalar property of the molecule, it should return the same value in any orientation. If it predicts a physical vector such as force, that vector must rotate with the molecule. These are different requirements: the first is invariance and the second equivariance.

In the figure three points form an explicit geometric example, not a molecule or forces predicted by a trained model. For the first point we sum relative differences weighted by a distance function. We then compare that output on rotated input with the original output rotated. The “Fixed axes” alternative multiplies the vector by an anisotropic diagonal and generally breaks rotation equivariance.

InteractiveRotate input and output
  • Prediction after rotation
  • Original prediction rotated
Arrows enlarged 2.5 times; explicit model, not trained forces.
60
Vector function
Equivariance error norm0.00000
Move the rotation and change function. Arrows show the prediction on rotated input and the original prediction rotated; the readout quantifies their difference. You can orbit the 3D scene.

A well-chosen symmetry reduces the functions the model must learn and can improve data efficiency, but does not guarantee lower error on every task. If a property depends on an external field or orientation relative to a reference frame, imposing invariance without that context can remove relevant information.

The E(3) contract

A Euclidean transformation acts on positions as xi↦Qxi+t\vb x_i\mapsto\mat Q\vb x_i+\vb t, with Q⊤Q=I\mat Q\T\mat Q=\mat I. It permits rotations and reflections as well as translations. For a permutation π\pi of atoms, features and edge endpoints are permuted too. The numerical equivariance test checks, for node-level scalar outputs hh and updated positions x′x',

h(π(Qx+t))=πh(x),x′(π(Qx+t))=π(Qx′(x)+t).\begin{aligned} h(\pi(\mat Q\vb x+\vb t))&=\pi h(\vb x),\\ x'(\pi(\mat Q\vb x+\vb t))&=\pi(\mat Qx'(\vb x)+\vb t). \end{aligned}

A graph-level scalar output obtained by invariant sum or mean should remain equal. A finite test does not prove the property for all inputs but detects specific implementation errors. Include reflections with negative determinant, not just rotations; check absolute tolerances and coordinate scale. The laboratory program tests 100 transformations in float32, with permutations and translations, before and after EGNN training.

Transformations must also compose consistently. Applying (Q2,t2)(\mat Q_2,\vb t_2) first and then (Q1,t1)(\mat Q_1,\vb t_1) gives (Q1Q2,Q1t2+t1)(\mat Q_1\mat Q_2,\mat Q_1\vb t_2+\vb t_1). Order matters: translating then rotating generally differs from rotating then translating by the same vector. An equivariant function must respect the composed action, not merely pass one isolated rotation about the origin.

The condition Q⊤Q=I\mat Q\T\mat Q=\mat I includes matrices with determinant +1+1 and −1-1. The former preserve orientation and represent proper rotations; the latter include reflections. A network equivariant only to proper rotations need not behave correctly under reflection, and a reflection test detects that difference. Not every physical vector quantity transforms identically under reflection either: polar vectors and pseudovectors have different parities.

The output action must match the object type. For scalar energy the transformation is trivial: expect the same number. For updated coordinates translation is also added because they describe positions; for displacement or a free force apply Q\mat Q without adding t\vb t. Confusing position with vector can make an apparently reasonable test demand the wrong transformation. Chemical features such as atomic number are permuted with atoms but not rotated as coordinates.

Numerical tolerance is not a universal model property either. In exact arithmetic algebraic equality holds under the assumptions; in float32, summation order, position magnitude, and GPU implementation introduce rounding. A very large translation can destroy precision in small differences through cancellation. A useful test records maximum error, device, and precision, and adds cases with different permutations and sizes. The original experiment requires absolute error below 10−510^{-5} in all outputs; that criterion may fail as a feature’s magnitude grows, although relative and higher-precision checks can help diagnose why.

The implemented test uses one QM9 molecule and 100 generated transformations, 50 of each determinant sign. It checks features, coordinates, and scalar output before training and repeats the check with selected EGNN weights. A small maximum in that sample is evidence that no break was observed in those cases, not exhaustive proof for every molecule or scale. It can also pass with initial weights even if a later code change introduces a non-equivariant dependence; hence the post-training repeat.

In the actual run, EGNN completed 100 epochs, but the final absolute check failed: maximum feature error was 3,19⋅10−53{,}19\cdot10^{-5}, versus 9,54⋅10−79{,}54\cdot10^{-7} for coordinates and 1,43⋅10−61{,}43\cdot10^{-6} for scalar output. The checkpoint was saved although the assertion prevented summary writing. Re-evaluation of its best state yielded test MAE 0.07037 eV over 12831 molecules.

In an additional check fixed before measurement, with three training molecules and 100 transformations per molecule, each maximum error was divided by max⁡(1,max⁡∣esperado∣)\max(1,\max|\text{esperado}|) for that transformation and output type. Maximum scaled feature error was 1,82⋅10−61{,}82\cdot10^{-6} in float32 and 3,74⋅10−153{,}74\cdot10^{-15} in float64; both were below their fixed relative thresholds of 10−510^{-5} and 10−1010^{-10}. Coordinates and scalar were also below. This is compatible with rounding in these cases; it does not prove symmetry for every molecule or turn the original absolute criterion into a pass.

Building an EGNN layer

The EGNN implementation of Satorras, Hoogeboom, and Welling uses distances and relative vectors. For a message from jj to ii, a degree-mean version writes

mji=ϕe(hi,hj,∥xi−xj∥22),xi′=xi+1di∑j→i(xi−xj)⋅tanh⁡(ϕx(mji)),hi′=hi+ϕh ⁣(hi,1di∑j→imji).\begin{aligned} \vb m_{ji}&=\phi_e(\vb h_i,\vb h_j,\norm{\vb x_i-\vb x_j}_2^2),\\ \vb x'_i&=\vb x_i+\frac{1}{d_i}\sum_{j\to i}(\vb x_i-\vb x_j)\\ &\qquad\cdot\tanh(\phi_x(\vb m_{ji})),\\ \vb h'_i&=\vb h_i+\phi_h\!\left(\vb h_i,\frac{1}{d_i}\sum_{j\to i}\vb m_{ji}\right). \end{aligned}

For a node without neighbors, the program defines both sums as zero and uses denominator one. ϕe\phi_e, ϕx\phi_x, and ϕh\phi_h are shared functions; ϕx\phi_x returns a scalar. Mean and tanh are implementation choices to control scale, not mandatory identities for every EGNN. The first two layers update features and coordinates; the third updates only features, because a final position unused in readout would contribute no gradient to scalar prediction. Edges are all ordered pairs of distinct atoms within each molecule, never between molecules in a batch.

With one atom there are no relative differences to sum: the coordinate remains unchanged in that layer. Scalar state can still change through ϕh(hi,0)\phi_h(\vb h_i,\vb 0). Defining the empty aggregate is not equivalent to removing all node computation. This distinction matters when testing extreme sizes and avoids division by zero without inventing a self-neighbor absent from the graph.

The proof tracks each object. ∥Q(xi−xj)∥2=∥xi−xj∥2\norm{\mat Q(\vb x_i-\vb x_j)}^2=\norm{\vb x_i-\vb x_j}^2, so scalar inputs to ϕe\phi_e and messages do not change. Each relative difference becomes Q(xi−xj)\mat Q(\vb x_i-\vb x_j) and its scalar coefficients remain unchanged. The sum becomes Q\mat Q times the original sum; adding transformed position gives exactly Qxi′+t\mat Q\vb x'_i+\vb t. Shared sums and functions also respect node renumbering. An absolute position inside ϕe\phi_e would invalidate this argument.

Permutation is checked with equal care. When atoms are renumbered, edge j→ij\to i connects the corresponding new indices; each atom’s neighbor count is preserved. Messages are reordered, but destination sum or mean does not depend on summand order. Node states therefore reorder and mean readout produces the same scalar. Permuting positions without permuting atom types or edges is not simple renumbering: it changes the chemical input and need not preserve prediction.

Degree mean prevents aggregate magnitude growing linearly solely by adding identical neighbors, but can lose multiplicity information. This is an architecture choice, not a mandatory consequence of equivariance: a sum of scalar messages also respects symmetry. The experiment’s readout uses mean atom states; another rule or an extra size input may suit an extensive property. Matching symmetry does not automatically match model capacity or behavior on molecules of different sizes.

Reflection symmetry deserves attention. For orthogonal matrix Q\mat Q, (Qu)×(Qv)=det⁡(Q)Q(u×v)(\mat Q\vb u)\times(\mat Q\vb v)=\det(\mat Q)\mat Q(\vb u\times\vb v). The cross product is a pseudovector: reflection adds a sign. An architecture treating it as an ordinary vector is not E(3)-equivariant without adjusting output representation.

Parity also limits which properties can be learned. Mirror configurations have the same pairwise distances; a model with reflection-invariant input and scalar output cannot assign them different values without other information changing under reflection. If the physical property depends on a chiral environment, represent that environment or use an architecture with the appropriate transformation law. The stated symmetry is adopted for HOMO in this lesson’s protocol; this does not establish suitability for every molecular interaction.

An algebraic example of orientation is the scalar triple product u⋅(v×w)\vb u\cdot(\vb v\times\vb w) of three relative vectors. Under an orthogonal transformation it is multiplied by det⁡(Q)\det(\mat Q): it preserves sign under a proper rotation and reverses it under reflection. Pairwise distances do not retain that orientation sign. Incorporating an odd-parity quantity requires stating how output transforms; treating it as invariant scalar under all E(3) would destroy the very distinction intended.

Coordinates updated in a layer need not be interpreted as physical trajectories. Here they are learned internal variables preserving the transformation law. The model does not solve equations of motion or guarantee energy conservation merely by being equivariant. To predict physical forces from an energy, a common construction takes the negative gradient with respect to positions; it would need training and separate unit and consistency checks. The figure does not show that calculation.

If a differentiable energy satisfies E(Qx+t)=E(x)E(\mat Q\vb x+\vb t)=E(\vb x) for a fixed transformation, the chain rule implies its gradient with respect to transformed positions is the rotated original gradient. Thus −∇E-\nabla E transforms as a polar vector without adding translation. This deduction assumes differentiable scalar energy and consistently transformed positions; it does not make the figure’s illustrative arrows or this network’s internal displacements physical forces.

QM9, target, and units

Molecular property regression uses QM9 molecules and their coordinates. In the PyG QM9 interface, column 2 is the highest occupied molecular orbital energy, HOMO, in eV. The program processes 130831 graphs available in that load, fixes a permutation with seed 14, and assigns 100000 to training, 18000 to validation, and the remainder to test. These custom splits must be declared; they are not presented as a paper’s split.

Target mean μ\mu and standard deviation σ\sigma are calculated on training only. The network minimizes squared error on (y−μ)/σ(y-\mu)/\sigma; to report MAE each prediction is denormalized and absolute errors averaged in eV. An MAE of 0.03 eV equals 30 meV. With 1 Eh=27.2113862459811\,E_h=27.211386245981 eV according to CODATA 2022, it is approximately 0.00110248 hartree. Numerical comparison makes sense only if property, units, and split match.

Normalizing with statistics of all molecules incorporates validation and test information into training even if their labels are not used in loss. The final report stores μ\mu and σ\sigma; the checkpoint retains data and split identity, from which the program recalculates them on resumption. For independent inference also retain those statistics with weights. Squared loss penalizes large errors more than absolute loss, while the final metric here is MAE: improved normalized loss does not ensure every chemical subset improves. Epoch selection uses validation MAE in original units so the criterion is comparable across variants.

If z=(y−μ)/σz=(y-\mu)/\sigma and the network predicts z^\widehat z, prediction in original units is y^=μ+σz^\widehat y=\mu+\sigma\widehat z. For σ>0\sigma>0, each absolute error in eV is σ∣z^−z∣\sigma\abs{\widehat z-z}; the mean transforms likewise. Squared error instead scales by σ2\sigma^2. This checks metric conversion and avoids directly comparing normalized loss with MAE published in eV or meV.

The complete list of intra-molecule pairs has ∑gng(ng−1)\sum_g n_g(n_g-1) directed edges. This is manageable for small QM9 molecules, but cost becomes quadratic in large systems. A cutoff radius or neighbor list can reduce it; it also introduces boundary and discontinuity choices that must respect symmetries and be evaluated. Time, parameters, and edge count matter when comparing EGNN with SchNet, even if both receive the same positions and split.

The concrete implementation first constructs a Boolean N×NN\times N matrix, with NN equal to total batch atoms, to decide which pairs belong to the same molecule. It then extracts only intra-molecule pairs. Thus although the final edge count is ∑gng(ng−1)\sum_g n_g(n_g-1), that temporary step uses memory quadratic in total batch size. A segmented constructor could avoid the global matrix; changing it requires checking that it produces the same edges and does not mix molecules before comparing times.

Symmetry and regression laboratory

Download the QM9 experiment. It requires PyTorch, PyG, and RDKit for initial preparation; it uses CUDA if available. The program builds EGNN with explicit messages and coordinates, a geometry-free network with the same trainable parameter count, a network receiving centered fixed-axis coordinates, the same with rotation augmentation, and PyG SchNet as an additional reference. The geometry-free GNN uses a learnable scalar coefficient to modulate messages instead of updating coordinates in the first two layers: it matches parameter budget but not operations. The coordinate network adds a three-input projection; the program prints all counts.

python qm9_experiment.py --test-only
python qm9_experiment.py --model egnn --epochs 100 --output egnn.json --checkpoint egnn.pt
python qm9_experiment.py --model nograph --epochs 100 --output nograph.json --checkpoint nograph.pt
python qm9_experiment.py --model naive --epochs 100 --output naive.json --checkpoint naive.pt
python qm9_experiment.py --model naive_aug --epochs 100 --output naive-aug.json --checkpoint naive-aug.pt
python qm9_experiment.py --model schnet --epochs 100 --output schnet.json --checkpoint schnet.pt

The maximum is 100 epochs and patience 20; the state with lowest validation MAE is saved and test calculated afterwards. Each checkpoint also retains last epoch, optimizer, RNG, and data and split hashes; repeat the same command with --resume to continue an interrupted run. SchNet receives the same full pair list as interaction graph, but its architecture and parameter count may differ. Augmentation rotates each molecule independently during training; evaluation applies no augmentation. The program prints symmetry errors and per-epoch progress and writes the summary only if final assertions pass. For other variants, the initial test concerns a separate EGNN, not the variant model. A shortened run debugs the workflow, not model convergence.

If the absolute check stops output after saving an EGNN CPU checkpoint, this independent audit checks code hash and split, recalculates full test, and records both the original absolute result and scaled check in both precisions. Save qm9_symmetry_check.py beside qm9_experiment.py and run python qm9_symmetry_check.py --checkpoint egnn.pt --output simetria.json. It neither retrains nor changes the checkpoint; it preserves the failure rather than replacing it with a success claim.

Options --device cpu or --device cuda fix the device and --threads sets PyTorch threads. Ordinary resumption checks those choices and code hash; it does not accept a checkpoint from another device, thread count, or program. In the documented run, SchNet moved through an explicit verified CPU-to-CUDA checkpoint conversion after epoch 9; weights, optimizer, split, and batch RNG are retained, and the new CUDA RNG is declared. CPU and CUDA times are reported separately and conversion does not guarantee bitwise equality. Fastest thread count depends on machine and load.

For the augmented variant another explicit transition was used after epoch 80. The CPU-rotation version generates random matrices, QR decomposition, and orientation correction on CPU before moving them to the model device. In the recorded comparison, eight real batches retained indices, rotations, and CPU and sampler random states; loss, gradient, and parameter differences stayed within preset tolerances. A validation was interleaved as a workflow test, so that trial is not a full epoch or a guarantee of identical numerical trajectory. The checkpoint converter leaves prior state intact and requires evidence and hashes of both versions; run python migrate_aug_checkpoint.py --help for arguments. Evidence concerns the measured machine: check behavior on yours before treating a transition as equivalent.

For example, if you saved naive-aug.pt at epoch 80 and keep downloaded files together, you can convert a copy and continue with the same configuration:

python migrate_aug_checkpoint.py --source naive-aug.pt --destination naive-aug-cuda.pt --original-script qm9_experiment.py --candidate-script qm9_experiment_cpu_rotations.py --proof naive_aug_transition_probe.json --expected-epoch 80
python qm9_experiment_cpu_rotations.py --model naive_aug --epochs 100 --device cuda --threads 1 --checkpoint naive-aug-cuda.pt --output naive-aug-cuda.json --resume

Augmentation and built-in equivariance respond differently to a new orientation. The fixed-axis network receives some rotated versions during training and may learn to be less sensitive; it is not algebraically required to give the same value for every rotation. The augmentation program uses proper rotations, while the EGNN test includes reflections too. Improvement after augmentation does not establish exact invariance, and proven symmetry does not guarantee training finds low MAE.

The fixed-axis baseline centers each molecule by subtracting its mean position. This removes a common translation and respects atom renumbering, but the linear projection of centered coordinates can respond differently when axes change. It is more informative than a network that does not even respect translations: it separates that simple symmetry from rotation invariance still to be learned or built in.

SchNet uses distance-dependent interactions and serves as a reference for another molecular architecture; it is not simply EGNN under another name. The geometry-free network retains atom types and full connectivity but does not receive distances. Comparing it with EGNN asks what geometry contributes in these configurations, with the caveat that how some parameters are used differs. Interpretation requires split, units, parameter counts, seed, and selection criterion, not only the lowest test figure.

In our run with the fixed split, seed 0, and selection by lowest validation MAE, the following HOMO results were obtained. Values are in eV; test contains 12,831 molecules and was consulted after epoch selection:

ModelEpochVal.Test
EGNN1000.069520.07037
No geometry60.389610.39331
Fixed axes900.089290.08997
Axes + rotation930.079620.08014
SchNet930.058420.05765

EGNN and the geometry-free control each have 79,681 parameters; the two fixed-axis networks have 79,873 each, and SchNet has 68,033.

The downloadable summary retains complete figures, checkpoint hashes, and independent CPU test re-evaluations. This is one seed per configuration, not an interval across alternative trainings. The difference between fixed axes with and without augmentation describes these two runs and does not establish exact invariance. The geometry-free network also does not match EGNN operation by operation, though parameter count was matched. EGNN, geometry-free control, and augmented variant began on CPU; the latter moved to CUDA after epoch 80, with CPU-generated rotations. The unaugmented network moved from CPU to CUDA after epoch 33 and SchNet after epoch 9. Do not attribute one time or device to those mixed trajectories.

EGNN test was recalculated from its best checkpoint after the absolute assertion failure described above; the table value does not turn that failure into a passed check. In non-EGNN variants, the initial symmetry check printed by the program concerns a separate control EGNN, not the evaluated variant’s weights.

Exercises

Proof
Prove: The EGNN coordinate update is E(3)-equivariant under the text's assumptions.
0
Q is orthogonal; messages depend only on invariant scalar features and distances.

Step 1 of 2. What happens to squared distances?

Quiz
Does the cross product of two relative positions transform as an ordinary vector under reflection?
Numeric
Convert 0.03 eV to hartree using 1 hartree = 27.211386245981 eV.
Code
Implement random_e3(n,seed) and equivariance_error(model,batch). batch is an N×3 array; model(pos) returns (N×1 scalars, N×3 vectors). For ten transformations check scalar invariance and vector equivariance and return the largest absolute error.
import numpy as np
def random_e3(n,seed=0):
  ...
def equivariance_error(model,batch):
  ...
Shift+Enter to run
Key idea
Invariant distances and relative differences multiplied by scalars allow construction of an E(3)-equivariant update. Symmetry is a testable contract, not a substitute for evaluation with explicit units and splits.