Module contents
Lesson 29 of 30Research 115 min

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

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 n!n! permutations of one matrix are summed, each orbit matrix appears ∣Aut⁡(G)∣|\operatorname{Aut}(G)| 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 ii 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.

InteractivePermutations and BFS orders
0123401234
Graph
0
Sequences120
Distinct matrices60
Nodes in order0 → 1 → 2 → 3 → 4
Change graph and enable the BFS restriction. The slider traverses every compatible labeled order and displays its matrix; symmetries explain why multiple sequences produce the same matrix.

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 m\vb{m}, a transition of type Qt=αtI+(1−αt)1m⊤\mat{Q}_t=\alpha_t\mat{I}+(1-\alpha_t)\vb{1}\vb{m}\T retains m\vb{m} as stationary distribution. If αt∈[0,1]\alpha_t\in[0,1], 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 q(zt∣zt−1)q(z_t\mid z_{t-1}) is known and the cumulative distribution from z0z_0 can be calculated. By Bayes, posterior q(zt−1∣zt,z0)q(z_{t-1}\mid z_t,z_0) is proportional to the product of forward probability of ztz_t from each candidate zt−1z_{t-1} and that candidate’s cumulative probability from z0z_0. During generation z0z_0 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.

InteractiveA known discrete bridge
C0C1O2C3Sampled atoms and bonds
7
0
0
Active edges5
P(O), node 00.459
P(bond), 0-10.541
Traverse a categorical reverse chain for four carbon or oxygen atoms and six possible bonds. Choose a node and pair to inspect probabilities; complementary categories have probability one minus the displayed value. The posterior assumes the final molecule is known: this is a privileged-information bridge, not a trained denoiser.

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.

InteractiveA learned QM9 trajectory
N0C1F2F3F4C5F6C7
Atom types
C0.25
N0.25
O0.25
F0.25
Bond types
absent0.25
single0.25
double0.25
triple0.25
16
0
0
Queried atom0
Queried pair0-1
This trajectory was selected among connected samples RDKit sanitized at the end. Move time from 16 to zero and choose an atom or pair: readouts show the categorical reverse distribution used for the visible state. Thickness distinguishes single, double and triple bonds; hydrogens are implicit. Intermediate states can be chemically invalid.

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 X∈Rn×3\mat{X}\in\R^{n\times3}, remove geometric center of mass with P=I−11⊤/n\mat{P}=\mat{I}-\vb{1}\vb{1}\T/n: Xc=PX\mat{X}_c=\mat{P}\mat{X}. Here all atoms have equal weight; a physical mass-weighted center requires another projection.

Sample Gaussian noise and project with the same P\mat{P}. Since P\mat{P} commutes with rotations acting on the right, centered noise has a rotation- and reflection-invariant distribution within subspace ∑ixi=0\sum_i\vb{x}_i=0. 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 3(n−1)3(n-1)-dimensional subspace, or configurations modulo translation: no normalized probability density on all R3n\R^{3n} is invariant to every translation.

InteractiveNoise without a center
0.00
Center norm0.0000
Seed9
A sample of eight three-dimensional Gaussian vectors is projected onto the screen; the orange point marks its geometric center. Compare before and after centering, rotate the set and change the seed. Rotation preserves distances and the zero center.

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 PP is symmetric and idempotent: P2=PP^2=P and P1=0P\vb{1}=0. 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 3(n−1)3(n-1) independent coordinates. For a transition with standard deviation σ\sigma, its log-density normalization term uses that dimension, not 3n3n. 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 SE(3)SE(3) 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.

[ ]Data and BFS ordersBrowser
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.

[ ]Fit the generator and SBMBrowser
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.

[ ]MMD of degree, clustering and three-node orbitsBrowser
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 4.77⋅10−74.77\cdot10^{-7} for predicted noise, 9.54⋅10−79.54\cdot10^{-7} for logits and 2.44⋅10−42.44\cdot10^{-4} 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

ProofInvariance by induction
Prove: If the initial distribution is invariant under a group and each transition equivariant, the distribution after any finite number of steps is invariant.
0
Let μ be an invariant distribution and K a kernel with K(gx, gA) = K(x, A).

Step 1 of 3. How is the one-step distribution expressed?

Numeric
In a labeled five-node path, how many distinct BFS sequences are possible when varying root and neighbor tie breaking?
Numeric
In a labeled five-node star, how many distinct BFS sequences are possible when varying root and tie breaking?
Quiz
A generator obtains 100 % validity and 0 % novelty relative to training. What can be concluded?
CodeProject and check the center
Implement 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
Shift+Enter to run
Key idea
Good generation respects symmetries and is evaluated with measures detecting invalidity, memorization and structural mismatch.