Graph and molecule generation: from GraphRNN to equivariant diffusion
Study graph generation under permutations, discrete and equivariant diffusion, and evaluation that detects memorization and structural mismatch.
After this lesson you can
- Relate labeled graph likelihood to permutation orbits and BFS sequences.
- Explain discrete graph diffusion and categorical reverse posteriors.
- Construct centered equivariant 3D diffusion and explain its density.
- Interpret invariant point attention and reflection-sensitive tasks.
- Evaluate generated structures with validity, novelty and distributional controls.
Before you start
- 25Graph autoencodersE(n)-equivariant graph neural networkPermutation invariance and equivarianceGraph transformer architectureEquivariant and invariant mapsData augmentation versus built-in equivariance
- 19Forward diffusion processDenoising score matchingConditional flow matchingAutoregressive factorizationVariational autoencoderMaximum mean discrepancy
- 24Homogeneous transform in SE(3)Frame transform tree
Generating a structure without naming it
A molecular graph does not change when its atoms are renumbered. An adjacency matrix does change when rows and columns are permuted. A model generating labeled matrices must handle that multiplicity when defining the probability of an unlabeled structure; comparing one chosen matrix can confuse an ordering’s probability with the graph’s.
Order, orbits and likelihood
The likelihood of an unlabeled graph is the sum of probabilities of distinct labeled matrices in its permutation orbit. If all permutations of one matrix are summed, each orbit matrix appears times due to the stabilizer; divide by that count. This assumes the model defines a distribution on fixed-size labeled matrices. A sequential representation may also have a different stopping and ordering convention.
Autoregressive graph generation models write a sequential factorization conditioned on what has been generated. GraphRNN decomposes node and edge formation and uses BFS-derived orders to reduce the sequence space. Root choice and neighbor order still matter: BFS does not define a unique order. Nor does it guarantee small bandwidth for every graph; it is a useful restriction for some families, not a universal compression theorem.
If the model generates node first and then its edges to previous nodes, sequence probability is the product of conditional decision probabilities and the stopping decision. Knowing one sequence probability exactly does not avoid summing over other sequences representing the same object. Sampling orders during training can distribute mass across representations, but the mean log probability of chosen orders is not automatically the unlabeled graph’s log probability.
A bandwidth restriction retains only connections between a new node and a limited number of predecessors. It reduces decision count, but if a true edge falls outside that window it is outside the generator family. The lab measures that fraction on ordered matrices before training: it signals lost representational capacity, not learned prediction error. Increasing bandwidth reduces this limitation at the cost of more decisions and compute.
A graph VAE producing a fixed-size matrix must solve generated-to-observed node matching when computing reconstruction. Approximate matching introduces another choice; canonical assignment can be unstable under small modifications or automorphisms.
Automorphism count depends on structure and preserved labels. If atom types are part of the graph, only permutations also preserving those types and bond categories count. An unlabeled five-node path has two automorphisms, identity and reflection; its 120 permutations give 60 distinct matrices. A star with four interchangeable leaves has 24 automorphisms and five distinct matrices. The figure contrasts those counts with BFS sequences, which answer a different question.
Discrete noise on nodes and edges
In discrete graph diffusion, each step applies a categorical transition matrix. For category marginal , a transition of type retains as stationary distribution. If , each row sums to one. Absent edges are also a category; in undirected graphs sample each unordered pair once and mirror the result in the matrix.
DiGress learns a transformer denoising node and edge categories and uses transitions preserving marginals. Denoiser permutation equivariance lets renumbering input renumber output, but the generated distribution is invariant only if the initial distribution and complete transitions respect that symmetry. The induction argument is developed at the end of the lesson.
A reverse transition is not obtained simply by changing the noise sign. In the forward process is known and the cumulative distribution from can be calculated. By Bayes, posterior is proportional to the product of forward probability of from each candidate and that candidate’s cumulative probability from . During generation is unknown: one option predicts a distribution over its categories and mixes conditional posteriors under that distribution. Each posterior must be normalized before its values are interpreted as probabilities.
Node pairs create a quadratic number of edge candidates. For small molecules a dense matrix is feasible; on large graphs it can be expensive and a sparse or hierarchical representation changes both cost and possible structure family. The “no bond” category often dominates pairs: low mean loss may correspond to predicting nearly everything absent. Separate errors by type and inspect degree, connectivity and valence as well as global loss.
The final state has C-C-O-C connectivity with implicit hydrogens. Intermediate states are sampled independently per category and may violate valence; the final transition recovers the conditioned structure. At finite time the figure’s initial state is taken from the forward distribution conditioned on that structure and approximates the uniform marginal, but is not exactly independent of it. A generative diffusion model must learn reconstruction without access to the final molecule.
The figure saves a run of discrete_qm9.py, a small network jointly denoising C, N, O and F types and absent, single, double or triple bonds. It trained for 30 epochs on 1024 QM9 graphs with eight heavy atoms and held out 256 for loss measurement. The process uses 16 categorical steps and samples each unordered pair once. Held-out loss was 1.014 in our run. Of 256 sampled graphs, 78 passed RDKit sanitization and connectivity; the displayed trajectory is the first of those samples, selected precisely for passing that filter. This selection is not an unconditional random sample and numbers are not published DiGress results.
Figure probabilities are reverse posteriors obtained by mixing the network’s initial-category predictions; at time 16 the uniform initial distribution is shown. The model does not know the final molecule during sampling, unlike the preceding bridge. RDKit’s criterion does not demonstrate physical stability or molecular utility, and one split cannot estimate performance uncertainty. Download the file and run python discrete_qm9.py --root datos/QM9; it requires PyTorch, PyG and RDKit and saves a checkpoint per epoch and the first connected valid trajectory if found.
Three-dimensional coordinates
EDM equivariant 3D diffusion combines continuous positions and discrete atom types. For positions , remove geometric center of mass with : . Here all atoms have equal weight; a physical mass-weighted center requires another projection.
Sample Gaussian noise and project with the same . Since commutes with rotations acting on the right, centered noise has a rotation- and reflection-invariant distribution within subspace . If each reverse transition is equivariant, the final distribution is invariant to those transformations too. Density is understood with respect to a measure on that -dimensional subspace, or configurations modulo translation: no normalized probability density on all is invariant to every translation.
An EGNN uses distances and scalar messages to construct vector displacements rotating with input. Subtracting the mean again from output prevents a numerical update shifting the center. Network equivariance does not guarantee chemical validity: types, distances, valences and bond reconstruction must be evaluated. Equivariant flow matching pursues the same symmetry through a velocity field under another training formulation.
Projection is symmetric and idempotent: and . Applied by column, it removes three degrees of freedom, one per coordinate, and retains position differences. Projecting an ordinary Gaussian gives a degenerate Gaussian in ambient space, but not in the centered subspace: there it has independent coordinates. For a transition with standard deviation , its log-density normalization term uses that dimension, not . This distinction matters when comparing probabilities, even if it does not change a test observing only the center.
A group also determines which transformations the model treats as equivalent. If an architecture uses only distances and combines relative vectors with invariant scalars, it can be reflection equivariant as well as rotation equivariant. For some molecules two reflected configurations are different enantiomers. Imposing reflection symmetry on a chirality-sensitive task may therefore erase relevant information; an architecture limited to proper rotations needs orientation-distinguishing features when that property matters.
Frames and attention in proteins
Invariant point attention combines scalar features with points expressed in rigid frames per residue. Each frame moves local points into global space; distances between them do not change under a common rigid motion. Weighting can transport information between residues while maintaining geometric consistency. Frames are elements of and compose under the same conventions as homogeneous transformations.
AlphaFold 2 and AlphaFold 3 solve different problems and use different architectures. Coordinate diffusion and rigid-motion augmentation are empirical design decisions; one cannot conclude every network without exact equivariance necessarily fails on unseen orientations. Exact equivariance and data augmentation are hypotheses compared under specific conditions and budgets.
To understand point attention, imagine each residue generates a query and key as local points. Their frames take them to the same global system and attention penalizes distances between points of different residues, combined with scalar scores. If the whole protein is rotated and translated together, both global images receive the same motion and their distances remain unchanged. The result can be expressed again in the receiving residue’s local frame. This explains distance-computation invariance; it does not mean every attention mechanism on coordinates is automatically invariant.
Evaluation resistant to memorization
Validity is the fraction of samples passing a defined criterion; uniqueness is the fraction of distinct structures among valid samples; novelty is the fraction of valid structures absent from training under a declared canonical representation. A memorizing generator can be valid and produce many unique structures if it memorizes many, but novelty will be zero. None of these metrics alone measures affinity, actual stability or utility.
MMD compares distributions using a kernel. Applied to degree, clustering or orbit histograms, it sees only selected statistics. The unbiased version can be negative in a finite sample; sample size and bandwidth matter. O’Bray et al. analyze problems with these metrics. Report definition, kernel, scale, graph count, uncertainty and a simple baseline; small differences without repetition are not a solid conclusion.
A good degree score does not guarantee reproduction of cycles, communities or connectivity. Conversely, a large MMD can arise from unsuitable bandwidth or small sample size. Before interpreting the comparison, check identical statistics and normalization for reference and samples, visualize both distributions and repeat over multiple seeds. Novelty also depends on equivalence: comparing noncanonical SMILES strings can count two spellings of one molecule as different structures.
Lab: community graphs and a sequential generator
Generate two communities of five nodes. Training and evaluation examples are separate, with community labels known only to fit the SBM baseline. The sequential generator does not receive those labels: it converts each connected graph to a BFS order and predicts previous edges within a bandwidth. Since bandwidth truncation can discard edges, we measure that fraction in the data rather than assume it is zero.
import numpy as np
import networkx as nx
from scipy.special import expit
rng=np.random.default_rng(12)
N=10; band=4
def make_graph(rng,pin=0.65,pout=0.08):
G=nx.Graph(); G.add_nodes_from(range(N))
for i in range(N):
for j in range(i+1,N):
if rng.random()<(pin if i//5==j//5 else pout): G.add_edge(i,j)
return G
def connected_samples(count,rng):
result=[]
while len(result)<count:
g=make_graph(rng)
if nx.is_connected(g): result.append(g)
return result
train=connected_samples(80,rng)
test=connected_samples(40,rng)
def bfs_order(g,rng):
root=int(rng.integers(N)); visited={root}; queue=[root]; order=[]
while queue:
u=queue.pop(0);order.append(u)
new=[v for v in g.neighbors(u) if v not in visited]
rng.shuffle(new)
visited.update(new);queue.extend(new)
return order
def ordered_matrix(g,rng):
order=bfs_order(g,rng)
return nx.to_numpy_array(g,nodelist=order,dtype=float)
matrices=[ordered_matrix(g,rng) for g in train]
lost=sum(sum(A[i,j] for i in range(N) for j in range(i) if i-j>band) for A in matrices)
total=sum(A.sum()/2 for A in matrices)
print('train/test',len(train),len(test),'fracción de aristas fuera de banda',lost/total)Each edge probability depends on the step and already-generated edges in the same row. This is a small autoregressive logistic regression, not full hierarchical GraphRNN. In training we use true previous edges; in generation we use previous samples, exposing it to accumulated errors.
def features(i,j,previous):
return np.array([1.,i/N,j/N,(i-j)/N,len(previous)/band,sum(previous)/band])
rows,labels=[],[]
for A in matrices:
for i in range(1,N):
previous=[]
for j in range(max(0,i-band),i):
rows.append(features(i,j,previous));labels.append(A[i,j]);previous.append(A[i,j])
X=np.array(rows); y=np.array(labels)
w=np.zeros(X.shape[1])
for _ in range(600):
w-=0.3*(X.T@(expit(X@w)-y)/len(y))
inside=sum(g.has_edge(i,j) for g in train for i in range(N) for j in range(i+1,N) if i//5==j//5)
outside=sum(g.has_edge(i,j) for g in train for i in range(N) for j in range(i+1,N) if i//5!=j//5)
nin=sum(1 for i in range(N) for j in range(i+1,N) if i//5==j//5)*len(train)
nout=sum(1 for i in range(N) for j in range(i+1,N) if i//5!=j//5)*len(train)
pin_hat,pout_hat=inside/nin,outside/nout
print('parámetros SBM ajustados:',pin_hat,pout_hat,'pérdida logística:',np.mean(np.logaddexp(0,X@w)-y*(X@w)))
def sample_auto(rng):
A=np.zeros((N,N))
for i in range(1,N):
previous=[]
for j in range(max(0,i-band),i):
bit=int(rng.random()<expit(features(i,j,previous)@w))
A[i,j]=A[j,i]=bit;previous.append(bit)
return nx.from_numpy_array(A)
auto=[sample_auto(rng) for _ in range(40)]
baseline=[make_graph(rng,pin_hat,pout_hat) for _ in range(40)]
print('conexos auto/SBM:',sum(nx.is_connected(g) for g in auto),sum(nx.is_connected(g) for g in baseline))Baseline generation is unconditioned, while reference data were conditioned on connectivity: comparison exposes a protocol mismatch. Repeating with a connectivity-conditioned baseline is a necessary ablation to separate that effect; do not discard disconnected samples without declaring it. Metrics here use every generated graph.
def summaries(g):
degrees=np.array([d for _,d in g.degree()])
degree=np.bincount(degrees,minlength=N)/N
clustering=np.histogram(list(nx.clustering(g).values()),bins=np.linspace(0,1,6))[0]/N
triangles=nx.triangles(g)
# Órbitas de tres nodos: participación como extremo y centro de camino inducido, y en triángulos.
center=[]; endpoint=[]; tri=[]
for v in g:
ns=list(g.neighbors(v))
center.append(sum(not g.has_edge(a,b) for ia,a in enumerate(ns) for b in ns[ia+1:]))
endpoint.append(sum(1 for u in ns for w in g.neighbors(u) if w!=v and not g.has_edge(v,w)))
tri.append(triangles[v])
orbit=np.array([np.mean(center),np.mean(endpoint),np.mean(tri)])/N**2
return degree,clustering,orbit
def mmd2(A,B,sigma=1.0):
def kernel(x,y): return np.exp(-np.sum((x[:,None,:]-y[None,:,:])**2,axis=-1)/(2*sigma**2))
aa,bb,ab=kernel(A,A),kernel(B,B),kernel(A,B)
return ((aa.sum()-np.trace(aa))/(len(A)*(len(A)-1))
+(bb.sum()-np.trace(bb))/(len(B)*(len(B)-1))-2*ab.mean())
reference=[summaries(g) for g in test]
for name,graphs in [('autoregresivo',auto),('SBM',baseline)]:
results=[]
for k in range(3):
A=np.array([x[k] for x in reference]); B=np.array([summaries(g)[k] for g in graphs])
results.append(mmd2(A,B))
print(name,'MMD² grado/clustering/órbitas',np.round(results,5))Reduced molecular diffusion on QM9
qm9_edm.py trains an equivariant-message denoiser on a PyG-loaded QM9 subset. It selects molecules of up to 16 atoms including hydrogens, splits 1500 for training and 300 for test with a fixed seed, and learns to predict centered-coordinate noise and atom types. Categorical transitions use a uniform marginal in this example, while positions follow a 20-step centered Gaussian process. It is a reduced EDM-inspired model, not its implementation or training budget.
Reverse sampling uses a categorical posterior mixed by predicted initial-type probabilities and a Gaussian transition with centered noise. It checks noise and logit equivariance and invariance of a transition’s log density on the centered subspace under an orthogonal transformation. To evaluate samples, RDKit attempts to reconstruct bonds from positions and types and sanitize the molecule. This definition allows disconnected fragments if RDKit sanitizes them; it does not require one connected molecule. The script’s reported atomic stability counts expected valences of reconstructed molecules over all generated atoms, assigning zero to atoms in samples whose reconstruction failed; it is not a physical stability measurement.
Install PyTorch, PyG and RDKit locally and run the downloaded file. By default it uses the QM9 cache under your home directory; if absent, PyG downloads it. You can pass another path and choose where to save the checkpoint:
python qm9_edm.py --root datos/QM9 --checkpoint qm9_edm_reducido.pt
In our one-seed, 30-epoch run RDKit sanitized 7 of 128 samples, 5.47 % validity under that criterion. All seven valid representations were distinct and absent from the 1500 training examples, but both fractions use only seven cases and can include fragments. The conservative fraction of atoms with expected valence was 3.11 %. Maximum observed errors under an orthogonal transformation were for predicted noise, for logits and for transition log density in single precision. This point numerical check does not prove exact invariance for all inputs or good chemical quality. The low result is an observation under this reduced budget, not EDM’s published result.
Exercises
Step 1 of 3. How is the one-step distribution expressed?
remove_com(x) for an array of shape (n, 3), with positive n, subtracting the geometric center without modifying input. Also implement verify_denoiser(x, denoiser, tol): center input, evaluate the callable and return whether its output has the same shape and coordinate mean norm at most tol. Do not center output before checking.import numpy as np
def remove_com(x):
pass
def verify_denoiser(x, denoiser, tol=1e-8):
pass