Module contents
Lesson 24 of 30Advanced 115 min

E(n)-equivariant networks for 3D geometry: SchNet, EGNN and PaiNN

Build geometric networks with invariant scalars and equivariant vectors, analyze chirality and energy-derived forces, and evaluate molecular models with measured limitations.

After this lesson you can

  • Specify Euclidean and permutation actions on geometric inputs and outputs.
  • Explain radial filtering, EGNN coordinate updates and vector channels.
  • Analyze geometric expressivity and reflection-sensitive chirality.
  • Derive force equivariance from invariant energy and assess conservativity.
  • Compare molecular energy and force experiments under explicit protocols.

Before you start

A physical system without a preferred origin

A molecule’s energy does not change when the laboratory rotates or changes its origin. A force, however, must rotate with the molecule. A LiDAR cloud or robot gripper also carries geometry, but the right symmetry depends on the task: gravity, chirality or an external frame can break some transformations. Before choosing a model decide how each input and output transforms.

A geometric graph has positions xi∈R3\vb x_i\in\R^3, scalar features hih_i and possibly vectors vi\vb v_i. A Euclidean transformation acts as xi↦Qxi+t\vb x_i\mapsto\mat Q\vb x_i+\vb t, vi↦Qvi\vb v_i\mapsto\mat Q\vb v_i and leaves scalars unchanged, with Q⊤Q=I\mat Q\T\mat Q=\mat I. Indices can be permuted jointly with positions, features and edges. E(3)E(3) includes reflections; SE(3)SE(3) restricts det⁡Q=1\det\mat Q=1. Equivariance requires transforming input then computing to match computing then transforming output.

The same definition extends to E(n)E(n) by replacing three coordinates with nn and taking Q∈O(n)Q\in O(n). In three dimensions a node permutation commutes with a global rigid transformation: the first changes indices and the second acts equally on all positions. Thus both symmetries can be checked separately and jointly. If some features are vectors, tensors or pseudoscalars, their rules must be part of the test; accidentally treating them as scalars changes the problem.

A radius graph connects pairs at distance less than rcr_c. The edge set is invariant under rigid motions except for numerical decisions exactly at the threshold. If an edge abruptly appears or disappears with a nonzero message, energy may be discontinuous. A cosine envelope smoothly vanishing at the cutoff avoids that message jump; derivatives and other graph dependencies must also be checked.

Radius controls a physical and computational choice. At roughly constant density expected neighbor count scales with sphere volume, proportional to rc3r_c^3 in three dimensions. Doubling radius can multiply it by roughly eight before boundary effects, correlations and neighbor limits. Multiple layers combine information beyond one radius, but do not make one layer directly observe every distant pair. Long-range forces may require separating a global contribution or using a specific representation with its own assumptions.

Each atom’s label travels with the node under permutation. For example, swapping two atoms of the same element should permute their forces without changing energy; swapping indices without also moving positions and species describes another input. In a radius graph limiting maximum neighbors can also introduce order-dependent tie breaking at equal distances. A symmetry test should include cases near those ties and cutoff, not just well-separated random configurations.

Invariant filters

Invariant geometric networks can start from distances rij=∥xi−xj∥r_{ij}=\|\vb x_i-\vb x_j\|. In SchNet radial functions expand each distance and a network produces a continuous filter modulating neighbor state. A representative form is

mi=∑jhj⊙W ⁣(ϕ(rij)),ϕk(r)=e−γ(r−μk)2c(r),\vb m_i=\sum_j \vb h_j\odot W\!\left(\phi(r_{ij})\right),\qquad \phi_k(r)=e^{-\gamma(r-\mu_k)^2}c(r),

with c(r)=12[cos⁡(πr/rc)+1]c(r)=\tfrac12[\cos(\pi r/r_c)+1] for r<rcr<r_c and zero outside. Distances and sum are invariant to rotations, reflections, translations and neighbor permutation if labels permute with nodes. A sum of atomic scalar contributions gives invariant energy. SchNet uses continuous filters and a differentiable energy surface; the radial expansion chosen here is a teaching version, not its full hyperparameters.

DimeNet incorporates angular information and directional messages between edges, allowing three-body relations; internal angles remain reflection invariant. Saying “uses distances” is insufficient to compare expressivity: graph, features, layer count and available information types matter.

For a triple k→j→ik\to j\to i, an angle can be obtained by the dot product of the two relative directions divided by their norms. A message on j→ij\to i can gather messages from edges k→jk\to j and weight them by distance and angle. Unlike a filter treating each distance separately, this observes a joint relation between two neighbors. The number of triples around a node of degree dd can grow as d(d−1)d(d-1): retaining angular information costs memory and time. DimeNet++ reduces some cost with projections and separate bases; it does not make angles distinguish mirror images.

A layer that moves coordinates

The EGNN of Satorras, Hoogeboom and Welling combines scalar messages with relative displacements. A representative layer, with normalization factor CiC_i, is

mij=ϕe(hi,hj,∥xi−xj∥2,aij),xi′=xi+Ci∑j∈N(i)(xi−xj)ϕx(mij),hi′=ϕh(hi,∑j∈N(i)mij).\begin{aligned} m_{ij}&=\phi_e(h_i,h_j,\|\vb x_i-\vb x_j\|^2,a_{ij}),\\ \vb x_i'&=\vb x_i+C_i\sum_{j\in N(i)}(\vb x_i-\vb x_j)\phi_x(m_{ij}),\\ h_i'&=\phi_h\left(h_i,\sum_{j\in N(i)}m_{ij}\right). \end{aligned}

Messages and ϕx\phi_x are invariant scalars. For xi∗=Qxi+t\vb x_i^*=\mat Q\vb x_i+\vb t, differences are Q(xi−xj)\mat Q(\vb x_i-\vb x_j) and their norms do not change. Thus mij∗=mijm_{ij}^*=m_{ij}, hi′∗=hi′h_i'^*=h_i' and xi′∗=Qxi′+t\vb x_i'^*=\mat Q\vb x_i'+\vb t. The same argument holds for reflection and permutation because the sum is order independent. If the radius graph is recomputed, neighbor selection must respect the same symmetry and handle ties consistently.

InteractiveCoordinates pass messages too
Apply then rotate1234
Rotate then apply1234
35
1.0
Show
Maximum equivariance error0.0000000000
Rotate a three-dimensional configuration projected onto the plane. Each displacement is a sum of relative vectors with scalar weights; compare applying before or after rotation.

The figure uses mij=exp⁡(−∥xi−xj∥2)m_{ij}=\exp(-\|\vb x_i-\vb x_j\|^2) and the mean of three messages; it is not a trained model. Magenta position is computed by both routes and the readout shows their numerical discrepancy. Message mean or normalization can avoid growth with degree, but does not guarantee stability: large weights, poorly scaled distances or long integrations can still explode.

Equivariance of each layer is preserved by composition provided all intermediate operations respect the same action. This does not mean the update is physical dynamics: moving coordinates within a network is a representation mechanism and does not itself conserve energy, momentum or interatomic distances. To check stability record displacement norms, minimum distances and gradients; a distance approaching zero can destabilize functions dividing by it. Regularization must be chosen without introducing a preferred axis.

Vectors and gates

Vector feature networks retain vic∈R3\vb v_{ic}\in\R^3 channels alongside scalars. A sum of vectors transformed with the same scalar weights remains equivariant, as does relative direction r^ij\hat{\vb r}_{ij} multiplied by a scalar distance function. PaiNN combines both sources and uses norms and scalar gates to update vector channels. GVP and vector neurons use other parameterizations; they are not synonyms.

ReLU applied independently to xx, yy and zz does not commute with arbitrary rotations. By contrast v↦g(h,∥v∥)v\vb v\mapsto g(h,\|\vb v\|)\vb v does when gg is an invariant scalar. Norm at zero requires numerical care and smooth regularization if derivatives are needed. PaiNN exploits these channels for tensor properties and spectra; this lab’s implementation is a small architecture-inspired variant, not a reproduction of published figures.

A gate need not learn three different spatial weights to orient a vector: the vector itself already carries direction. Scalar state decides how much of that channel to retain or combine. A dot product between vector channels produces another invariant scalar, and a scalar-weighted sum produces an equivariant vector. For an output such as dipole, the head can sum atomic vector contributions; for energy it must reduce to scalars. A correctly typed head guarantees transformation law, not that data and optimization determine magnitude well.

GVP combines scalar channels and collections of vectors to reason about protein structure. It mixes vector channels with weights shared across three coordinates and uses their norms as scalar information; later operations retain transformation law. Vector Neurons constructs equivariant analogues of linear layers, nonlinearities and pooling for point clouds. Both are parameterization strategies, with applications and rules distinct from PaiNN; comparing only family names does not establish equal features or capacity.

Local distances do not tell the whole story

Geometric expressivity depends on which relations cross layers. Consider C6C_6 as a regular unit-side hexagon and two distant unit-side equilateral triangles. Fix cycle edges. At every node the incident distance multiset is {1,1}\{1,1\}; a scalar message model with uniform initial features receives the same signature in both graphs and cannot distinguish them from those inputs.

Now update xi′=xi+a∑j∈N(i)(xi−xj)\vb x_i'=\vb x_i+a\sum_{j\in N(i)}(\vb x_i-\vb x_j) without reselecting edges. In the hexagon the sum is the vector from center to node; each edge scales by 1+a1+a. In a triangle it is three times that vector; each edge scales by 1+3a1+3a. A later layer reading new distances separates this example. This does not mean EGNN separates every geometric graph or mirror pair: the guarantee depends on architecture and symmetries. The GWL framework analyzes these distinctions under explicit assumptions.

Complete global distances have a different property from local edge distances. If D2D^2 contains all squared distances and J=I−11⊤/nJ=I-\vb1\vb1\T/n centers positions, the centered Gram matrix is recovered as G=−12JD2JG=-\tfrac12 JD^2J. Factoring GG reconstructs centered positions up to an orthogonal transformation, possibly including reflection. Thus all distances distinguish noncongruent configurations up to those symmetries, but do not give chirality sign. Complete matrix storage is quadratic and does not characterize an MPNN receiving only local distances.

InteractiveIdentical local distances, different updates
Hexagon
Two triangles
0.10
Hexagon edge1.100
Triangles edge1.300
Drawings use different scales for readability. Initially every edge has length 1; move the coefficient and compare calculated lengths after the update, keeping edges fixed.

Reflections and chirality

Reflections and chirality matter when two mirror images must receive different values. Three labeled vectors with a common origin have triple product χ=a⋅(b×c)\chi=\vb a\cdot(\vb b\times\vb c). Under Q∈O(3)\mat Q\in O(3) it transforms as χ↦det⁡(Q)χ\chi\mapsto\det(\mat Q)\chi: unchanged by proper rotations and sign-reversed by reflections. It is therefore a pseudoscalar, not an E(3)E(3)-invariant scalar.

InteractiveThree vectors and their mirror
Original123
Mirror image123
25
Illustrative model
Original output3.0
Mirror output3.0
The toy E(3) model sums squared distances; the SE(3) model uses the triple product. Rotate both configurations and compare outputs.

A scalar model strictly invariant to reflections assigns the same energy to both configurations. That suits many isolated energies without a chiral environment, but not every chiral label. If the three vectors have no distinguishable identity, their order must be defined compatibly with permutations: an arbitrarily ordered triple product can break invariance under node renumbering. Explicit-parity representations handle this distinction systematically.

Forces as gradients

Forces as gradients are calculated from differentiable scalar energy E(x1,…,xn)E(\vb x_1,\ldots,\vb x_n) via Fi=−∇xiE\vb F_i=-\nabla_{\vb x_i}E. If E(Qx+t)=E(x)E(\mat Q\vb x+\vb t)=E(\vb x), the chain rule gives ∇E(Qx+t)=Q∇E(x)\nabla E(\mat Q\vb x+\vb t)=\mat Q\nabla E(\vb x) and therefore Fi(Qx+t)=QFi(x)\vb F_i(\mat Q\vb x+\vb t)=\mat Q\vb F_i(\vb x). Force is conservative on the domain where EE is differentiable: work along a path depends only on endpoints.

Translation invariance also implies ∑iFi=0\sum_i\vb F_i=0: differentiate energy with respect to a common infinitesimal translation. Proper-rotation invariance implies zero total torque, ∑ixi×Fi=0\sum_i\vb x_i\times\vb F_i=0, without external fields supplying force or torque. These are verifiable consequences of energy symmetry, not conditions to impose on a system under a fixed external field. When training forces with autograd, optimization needs a second derivative, now with respect to parameters; a computation disconnecting the gradient graph cannot learn correctly from force loss.

If a head directly predicts every force component, a local conservativity check examines Jacobian symmetry: twice-differentiable energy requires ∂Fa/∂xb=∂Fb/∂xa\partial F_a/\partial x_b=\partial F_b/\partial x_a. Checking a few components or points does not prove a global property. A direct head can be conservative if constructed with that constraint, and an energy-derived field can simulate poorly if learned energy is wrong. Separating model and integrator error is essential in trajectory evaluation.

InteractiveEnergy and direct forces
  • Gradient
  • Direct
  • Energy gradient
  • Biased direct force
200
0.02
Energy change, gradient0.0000
Energy change, direct0.2664
Fitted rotational coefficient0.080
Two models are fit to explicit synthetic samples: one derives a harmonic potential, the other receives a biased rotational component. The relative trajectory uses Verlet; energy difference includes numerical error.

The example uses two relative pair coordinates, unit mass and synthetic data. A potential E=k∥r∥2/2E=k\|\vb r\|^2/2 and direct field −kdr+ωJr-k_d\vb r+\omega J\vb r are least-squares fitted, with JJ a 90-degree rotation. The direct head’s four samples deliberately include ω=0.08\omega=0.08: the field has nonzero curl and uses a fixed planar orientation, so it is not a reflection-equivariant force. It does not demonstrate every direct head is nonconservative or replace a trained molecular simulation. Verlet has integration error even with conservative force; to compare time steps keep the product of step count and step size approximately fixed.

Lab: distances, layer and derivatives

[ ]Smooth cutoff and radial filterBrowser
import numpy as np
from scipy.spatial.transform import Rotation
def radius_graph(x,cutoff):
    d=np.linalg.norm(x[:,None,:]-x[None,:,:],axis=-1)
    return (d<cutoff)&(~np.eye(len(x),dtype=bool)),d
def radial(r,centers,cutoff,gamma=4.):
    c=np.where(r<cutoff,.5*(np.cos(np.pi*r/cutoff)+1),0.)
    return np.exp(-gamma*(r[...,None]-centers)**2)*c[...,None]
rng=np.random.default_rng(24);x=rng.normal(size=(5,3));Q=Rotation.random(random_state=24).as_matrix();t=np.array([2.,-3.,1.])
adj,d=radius_graph(x,3.);adj2,d2=radius_graph([email protected]+t,3.)
assert np.array_equal(adj,adj2) and np.allclose(d,d2)
centers=np.linspace(0,3,12); print('error radial',float(np.max(np.abs(radial(d,centers,3)-radial(d2,centers,3)))))

A scalar SchNet-like layer aggregates to node ii each neighbor jj state multiplied by a radial filter. In this single-channel version, W(r)=∑kwkϕk(r)W(r)=\sum_k w_k\phi_k(r); the residual retains hih_i. Basis derivative includes both Gaussian and cutoff. The implementation checks backward for positions, features and weights with central differences. It is not full SchNet and requires nonzero distances to differentiate the norm.

[ ]Continuous filter: forward and backwardBrowser
def radial_and_grad(r,centers,cutoff,gamma=4.):
    if not 0<r<cutoff: return np.zeros_like(centers),np.zeros_like(centers)
    gaussian=np.exp(-gamma*(r-centers)**2)
    c=.5*(np.cos(np.pi*r/cutoff)+1)
    dc=-np.pi/(2*cutoff)*np.sin(np.pi*r/cutoff)
    return gaussian*c,gaussian*(dc-2*gamma*(r-centers)*c)
def schnet_layer(x,h,w,centers,cutoff):
    y=h.copy()
    for i in range(len(x)):
        for j in range(len(x)):
            if i==j: continue
            r=np.linalg.norm(x[i]-x[j]);phi,_=radial_and_grad(r,centers,cutoff)
            y[i]+=h[j]*(w@phi)
    return y
def schnet_backward(x,h,w,centers,cutoff,g):
    dx=np.zeros_like(x);dh=g.copy();dw=np.zeros_like(w)
    for i in range(len(x)):
        for j in range(len(x)):
            if i==j: continue
            d=x[i]-x[j];r=np.linalg.norm(d)
            if r==0: raise ValueError('átomos coincidentes')
            phi,dphi=radial_and_grad(r,centers,cutoff)
            dh[j]+=g[i]*(w@phi);dw+=g[i]*h[j]*phi
            step=g[i]*h[j]*(w@dphi)*d/r;dx[i]+=step;dx[j]-=step
    return dx,dh,dw
xs=np.array([[0.,0.,0.],[.8,.3,0.],[.2,1.1,.4]])
hs=rng.normal(size=3);ws=rng.normal(size=12);gs=rng.normal(size=3)
dxs,dhs,dws=schnet_backward(xs,hs,ws,centers,3.,gs)
def scalar_loss(x,h,w): return gs@schnet_layer(x,h,w,centers,3.)
errors=[];eps=1e-6
for arr,grad,slot in [(xs,dxs,0),(hs,dhs,1),(ws,dws,2)]:
    for index in np.ndindex(arr.shape):
        plus=arr.copy();minus=arr.copy();plus[index]+=eps;minus[index]-=eps
        args=[xs,hs,ws];args[slot]=plus;up=scalar_loss(*args)
        args[slot]=minus;down=scalar_loss(*args)
        errors.append(abs((up-down)/(2*eps)-grad[index]))
print('error máximo backward filtro',max(errors))
assert max(errors)<1e-7
assert np.allclose(schnet_layer([email protected]+t,hs,ws,centers,3.),schnet_layer(xs,hs,ws,centers,3.))
for trial in range(10):
    transform=Rotation.random(random_state=rng).as_matrix()
    if trial%2: [email protected]([-1.,1.,1.])
    permutation=rng.permutation(len(xs));shift=rng.normal(size=3)
    xt=xs[permutation]@transform.T+shift;ht=hs[permutation];gt=gs[permutation]
    yt=schnet_layer(xt,ht,ws,centers,3.)
    dxt,dht,dwt=schnet_backward(xt,ht,ws,centers,3.,gt)
    assert np.allclose(yt,schnet_layer(xs,hs,ws,centers,3.)[permutation])
    assert np.allclose(dxt,dxs[permutation]@transform.T) and np.allclose(dht,dhs[permutation]) and np.allclose(dwt,dws)
print('diez transformaciones y permutaciones verificadas')

The following layer uses one scalar channel and a complete loopless graph. The backward pass implements the explicit chain rule for a scalar loss with arbitrary adjoints; it is checked by finite differences, not only a symmetry identity.

[ ]EGNN and backpropagation from scratchBrowser
def layer(x,h,a=.1):
    xp=x.copy(); hp=h.copy()
    for i in range(len(x)):
        for j in range(len(x)):
            if i==j: continue
            d=x[i]-x[j]; m=h[i]*h[j]+np.exp(-d@d)
            xp[i]+=a*m*d; hp[i]+=m
    return xp,hp
def backward(x,h,gx,gh,a=.1):
    dx=gx.copy(); dh=gh.copy()
    for i in range(len(x)):
        for j in range(len(x)):
            if i==j: continue
            d=x[i]-x[j]; e=np.exp(-d@d);m=h[i]*h[j]+e
            gm=a*(gx[i]@d)+gh[i]; gd=a*m*gx[i]-2*gm*e*d
            dx[i]+=gd;dx[j]-=gd;dh[i]+=gm*h[j];dh[j]+=gm*h[i]
    return dx,dh
x=rng.normal(size=(4,3));h=rng.normal(size=4);gx=rng.normal(size=x.shape);gh=rng.normal(size=h.shape)
xp,hp=layer(x,h);xr,hr=layer([email protected]+t,h)
print('error posición',np.max(np.abs(xr-([email protected]+t))),'error escalar',np.max(np.abs(hr-hp)))
assert np.allclose(xr,[email protected]+t) and np.allclose(hr,hp)
dx,dh=backward(x,h,gx,gh)
def loss(x,h):
    p,s=layer(x,h);return float((p*gx).sum()+s@gh)
eps=1e-6; errors=[]
for i in range(4):
    for j in range(3):
        E=np.zeros_like(x);E[i,j]=eps;errors.append(abs((loss(x+E,h)-loss(x-E,h))/(2*eps)-dx[i,j]))
    e=np.zeros_like(h);e[i]=eps;errors.append(abs((loss(x,h+e)-loss(x,h-e))/(2*eps)-dh[i]))
print('error máximo backward',max(errors));assert max(errors)<1e-7
[ ]Reflection and permutationBrowser
R=np.diag([-1.,1.,1.]);perm=np.array([2,0,3,1]);xx,hh=layer([email protected],h);px,ph=layer(x[perm],h[perm])
print('reflexión',float(np.max(np.abs([email protected]))),'permutación',float(np.max(np.abs(px-xp[perm]))))
assert np.allclose(xx,[email protected]) and np.allclose(hh,hp) and np.allclose(px,xp[perm]) and np.allclose(ph,hp[perm])
for trial in range(10):
    transform=Rotation.random(random_state=rng).as_matrix()
    if trial%2: transform=transform@R
    perm=rng.permutation(len(x));shift=rng.normal(size=3)
    p,s=layer(x[perm]@transform.T+shift,h[perm])
    assert np.allclose(p,xp[perm]@transform.T+shift) and np.allclose(s,hp[perm])
print('diez transformaciones y permutaciones verificadas')
[ ]Gated scalar and vector channelsBrowser
def vector_layer(x,h,v):
    n=len(x); hn=h.copy(); vn=v.copy()
    for i in range(n):
        for j in range(n):
            if i==j: continue
            d=x[i]-x[j]; w=np.exp(-d@d)
            hn[i]+=w*h[j];vn[i]+=w*(v[j]+h[j]*d)
    gate=1/(1+np.exp(-hn)); norm=np.sqrt((vn*vn).sum(axis=1)+1e-12)
    return hn+.1*norm,gate[:,None]*vn
v=rng.normal(size=x.shape);hs,vs=vector_layer(x,h,v)
hq,vq=vector_layer([email protected]+t,h,[email protected])
print('error escalar y vectorial',np.max(np.abs(hs-hq)),np.max(np.abs([email protected])))
assert np.allclose(hq,hs) and np.allclose(vq,[email protected])

Finally, fit a linear radial layer to atom pairs whose energy follows Lennard-Jones. This example learns only a function of one distance; it does not claim to be multilayer SchNet training. Cutoff is fixed at 3 and both train and test use distances between 1 and 2.5 in reduced units.

[ ]Fit a radial potential to Lennard-JonesBrowser
train_r=rng.uniform(1.,2.5,128);test_r=rng.uniform(1.,2.5,64)
def lj(r): return 4*(r**-12-r**-6)
centers=np.linspace(0,3,24)
features=radial(train_r,centers,3.,gamma=6.)
coeff=np.linalg.lstsq(features,lj(train_r),rcond=1e-8)[0]
prediction=radial(test_r,centers,3.,gamma=6.)@coeff
print('MAE de energía reducida en test',float(np.mean(np.abs(prediction-lj(test_r)))))
def learned_energy(pos):
    d=np.linalg.norm(pos[0]-pos[1]);return float((radial(np.array([d]),centers,3.,gamma=6.)@coeff)[0])
pair=np.array([[0.,0.,0.],[1.35,0.,0.]])
assert np.isclose(learned_energy(pair),learned_energy([email protected]+t))
print('energía de ejemplo',learned_energy(pair))

Local lab: rMD17 energy and forces

This check uses PyTorch Geometric SchNet with a custom edge constructor so it does not depend on a particular radius-search implementation. Search is quadratic and suits small molecules; a spatial neighbor list is preferable at scale. Energy and force are checked under a rotation without claiming the random model is trained.

[ ]PyG SchNet with explicit edgesLocal GPU
import torch
from torch_geometric.nn import SchNet
torch.manual_seed(24)
def radius_pairs(pos,batch):
    n=len(pos);distance2=((pos[:,None,:]-pos[None,:,:])**2).sum(-1)
    mask=(batch[:,None]==batch[None,:]) & (distance2<25.) & (~torch.eye(n,dtype=torch.bool,device=pos.device))
    src,dst=torch.where(mask);edge=torch.stack([src,dst])
    return edge,torch.linalg.vector_norm(pos[src]-pos[dst],dim=-1)
model=SchNet(hidden_channels=16,num_filters=16,num_interactions=2,num_gaussians=12,cutoff=5.,interaction_graph=radius_pairs)
z=torch.tensor([6,1,8,1]);pos=torch.tensor([[0.,0.,0.],[1.,0.,0.],[.2,1.,0.],[.1,.2,1.]],requires_grad=True)
R=torch.tensor([[0.,-1.,0.],[1.,0.,0.],[0.,0.,1.]])
E0=model(z,pos);F0=-torch.autograd.grad(E0.sum(),pos)[0]
rotated=(pos.detach()@R.T+torch.tensor([1.,2.,-1.])).requires_grad_(True)
E1=model(z,rotated);F1=-torch.autograd.grad(E1.sum(),rotated)[0]
print('errores energía y fuerza',(E1-E0).detach().abs().max().item(),([email protected]).abs().max().item())
assert torch.allclose(E1,E0,atol=1e-6) and torch.allclose(F1,[email protected],atol=1e-6)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

PyG also provides DimeNet++, which constructs messages between edge pairs and uses triple angles. To make this small example work even without compiled extensions, its two enumeration routines are temporarily replaced by dense PyTorch versions; the network and filters remain PyG’s. This is a teaching adaptation quadratic in edge count, not an efficient alternative for large datasets. Original functions are restored afterward and a nonzero output initialization is used so the test does not pass through identically zero energy.

[ ]PyG DimeNet++ with explicit triplesLocal GPU
import importlib
import torch
dm=importlib.import_module('torch_geometric.nn.models.dimenet')
def dense_radius(pos,r,batch=None,max_num_neighbors=32):
    n=pos.shape[0];d2=((pos[:,None]-pos[None,:])**2).sum(-1)
    same=torch.ones((n,n),dtype=torch.bool,device=pos.device) if batch is None else batch[:,None]==batch[None,:]
    src,dst=torch.where(same & (d2<r*r) & ~torch.eye(n,dtype=torch.bool,device=pos.device))
    if n-1>max_num_neighbors: raise ValueError('ejemplo sin truncamiento de vecinos')
    return torch.stack((src,dst))
def dense_triplets(edge_index,num_nodes):
    source,target=edge_index
    ji,kj=torch.where((source[:,None]==target[None,:]) & (target[:,None]!=source[None,:]))
    return target,source,target[ji],source[ji],source[kj],kj,ji
old_radius,old_triplets=dm.radius_graph,dm.triplets
try:
    dm.radius_graph,dm.triplets=dense_radius,dense_triplets
    torch.manual_seed(24)
    model=dm.DimeNetPlusPlus(hidden_channels=8,out_channels=1,num_blocks=1,int_emb_size=4,
        basis_emb_size=4,out_emb_channels=8,num_spherical=2,num_radial=3,cutoff=5.,output_initializer='glorot_orthogonal')
    z=torch.tensor([6,1,8,1]);pos=torch.tensor([[0.,0.,0.],[1.,0.,0.],[.2,1.,0.],[.1,.2,1.]],requires_grad=True)
    edge=dense_radius(pos,5.);triplet=dense_triplets(edge,len(z));assert edge.shape[1]==12 and len(triplet[2])==24
    R=torch.tensor([[0.,-1.,0.],[1.,0.,0.],[0.,0.,1.]])
    e0=model(z,pos);f0=-torch.autograd.grad(e0.sum(),pos)[0]
    moved=(pos.detach()@R.T+torch.tensor([1.,2.,-1.])).requires_grad_(True)
    e1=model(z,moved);f1=-torch.autograd.grad(e1.sum(),moved)[0]
    print('aristas',edge.shape[1],'tripletes',len(triplet[2]),'energía',e0.detach().item())
    print('errores energía y fuerza',(e1-e0).detach().abs().max().item(),([email protected]).abs().max().item())
    assert e0.detach().abs().max()>1e-8 and torch.allclose(e1,e0,atol=1e-5) and torch.allclose(f1,[email protected],atol=1e-5)
finally:
    dm.radius_graph,dm.triplets=old_radius,old_triplets
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Download potenciales.py and checkpoint.py into the same folder. The program downloads and SHA-256 verifies rMD17 aspirin split 01 published by its authors. Each file has 1000 configurations; at most 800 from training are used and 200 reserved for validation. The 1000-configuration test remains separate. Energies are in kcal/mol, forces in kcal/mol/Å and positions in Å. Configurations come from a trajectory and are not independent observations: do not interpret a random split as an out-of-distribution guarantee.

An EGNN already trained on 200 configurations was also checked on eight test examples and ten transformations combining permutation, translation, rotations and reflections. In float32 maximum absolute discrepancy was 1.07×10−41.07\times10^{-4} for energy and 6.72×10−46.72\times10^{-4} for forces; four of ten force tests failed allclose with absolute and relative tolerances 10−410^{-4}. Converting those same weights and positions to float64 before transforming gave maxima 1.71×10−131.71\times10^{-13} and 1.20×10−121.20\times10^{-12} respectively, and all passed. This sample illustrates numerical precision’s effect on checking; it does not demonstrate symmetry for all inputs or replace the layer proof.

python potenciales.py --root rmd17 --sizes 50 200 800 --epochs 100 --output potenciales.json

The comparison constructs a SchNet-like radial network, an EGNN with updated positions and a teaching scalar/vector-channel PaiNN-like variant, all with three layers and 32 channels. It computes forces with autograd from energy; loss sums squared energy error and 100 times force error per component. Energy is centered using training mean, selection uses validation force MAE and test is evaluated afterward. Short dynamics use velocity Verlet and report total-energy range with explicit units. A short-term stability check does not demonstrate a physically correct long-term trajectory.

With seed 42, batch 8 and 100 epochs per combination, a GeForce RTX 3060 run produced the following errors on 1000 test configurations. Training sizes are nested subsets of the same split; 200 validation configurations are distinct.

Model and training sizeEnergy MAEForce MAE
SchNet, 5024.7239.240
EGNN, 5020.88514.344
PaiNN, 5018.7035.118
SchNet, 2003.8325.511
EGNN, 20059.1939.259
PaiNN, 20025.3933.019
SchNet, 80010.9162.762
EGNN, 80024.1443.552
PaiNN, 8008.6711.605

Energy is in kcal/mol and force in kcal/mol/Å. These are small implementations, one molecule and one seed: they are not official paper figures and do not establish a general ranking. Several configurations selected the last epoch, so the budget does not demonstrate convergence. Energy error need not decrease with force error: selection used force, not energy.

For the three models with 800 examples, resources and total-energy variation observed in a test trajectory were:

ModelCUDA peak, MiBEnergy range
SchNet39.70.00362
EGNN51.20.00412
PaiNN54.90.00376

Peak is PyTorch memory allocated to the process, not total card memory. Recorded train, validation and test times were approximately 1090, 1099 and 788 seconds respectively, under differing shared-load conditions; they should not be interpreted as a controlled speed comparison. Range is maximum minus minimum total energy in kcal/mol over 100 steps of 0.1 fs, started from rest at a test configuration. Small variation in those 10 fs does not guarantee force accuracy or long-trajectory stability.

Coefficient 100 is an optimization choice for these units and loss normalization, not a physical constant. Changing kcal/mol to another unit without adjusting scales alters energy-force balance. A reference constant added to energy also does not change its gradient: centering training values facilitates fitting without changing forces. For deployment save that mean with weights and add it back to energy prediction.

Current and best model state, optimizer and random generators are saved after every epoch in an .<modelo>.<tamaño>.checkpoint file alongside results; each configuration keeps its own file. Repeat the same command after interruption to recover the last complete epoch and retain finished models. Change output path when changing budget, seed or batch.

Exercises

Proof
Prove: Prove equivariance of the lesson's EGNN layer to Euclidean motions and permutations.
0
Messages use only invariant scalars and distances; functions and aggregation are shared across nodes.

Step 1 of 3. What happens to position differences under x transforms to Qx+t?

Proof
Prove: Prove that the negative gradient of invariant energy transforms as a vector.
0
Energy is differentiable and Q is orthogonal.

Step 1 of 3. What equality is differentiated with respect to original coordinates?

Numeric
Approximate a protein as 300 residues of 8 atoms each in a homogeneous medium of density 0.05 atoms per cubic Å, without boundary effects or correlations. With radius 5 Å, approximately how many directed messages do you expect?
Quiz
Which statement best matches geometric outputs?
Quiz
For scalar energy of small molecules without a chiral environment and with limited budget, what is a coherent starting point?
Quiz
You need to predict the vector dipole of neutral molecules and want it to rotate with them. What output is appropriate?
Quiz
A label assigns opposite signs to two enantiomers. What design can express it?
Code
Implement e3_equivariance_errors(model,pos,h), where model receives positions (n,3) and scalars (n,) and returns (updated positions, scalars). Return maximum errors for keys rotation, reflection, translation and permutation. Use a fixed scipy rotation, reflection, translation and permutation; compare scalar outputs too.
import numpy as np
from scipy.spatial.transform import Rotation
def e3_equivariance_errors(model,pos,h):
  pass
Shift+Enter to run

Key ideas

Key idea
A geometric network must respect each output type’s transformation: distances for scalars, relative vectors or equivariant channels for directions, and energy gradients for conservative forces.