CS224W

Bonus page · built from the lecture notes (PDF) — topics this year's slides don't cover

Bonus B: Geometry, Subgraphs and Trust

Three ideas the 2024 notes add beyond this year's slides: GNNs that respect the symmetry of 3D space (rotate a molecule and its energy must not change), subgraphs and motifs as the building blocks of networks (found fast with order embeddings), and explanations that say which edges and features made a GNN decide (GNNExplainer, fidelity).

30
sectionstick "got it" as you go
5
figuresredrawn from the slides
interactive figuresplay with the ideas
5
self-check questionsplus flashcards
46′
reading time10,171 words, walkthrough aside

Before you start: review of the earlier sessions

The thread so far. The second bonus page extends the invariance idea of sessions 6–8 to geometry, the structural encodings of session 7 to motifs, and the trust theme of session 14 to explanations.

What this session takes from earlier ones

  • Lecture 6: permutation invariance and injective aggregation, extended to rotations and translations
  • Lecture 7: structural encodings and graphlets, which motif counting formalises
  • Lecture 18: graph generation, extended to 3D molecules
  • Lecture 14: trust and uncertainty, continued with explanations

Those sessions in one minute each

Lecture 6 · Theory of GNNs — How Expressive Are They?

A message-passing GNN is at most as powerful as the 1-WL test; it reaches that bound exactly when every aggregation is injective on multisets — which sum aggregation with MLPs (GIN) achieves and mean/max do not.

\[ \mathbf{h}_v^{(k+1)}=\text{MLP}^{(k)}\Big((1+\epsilon^{(k)})\,\mathbf{h}_v^{(k)}+\sum_{u\in N(v)}\mathbf{h}_u^{(k)}\Big) \]

GIN layer. For graph classification, GIN reads out with a sum over nodes at every layer and concatenates them (the paper's readout).

Lecture 7 · Designing Powerful Graph Encoders — Breaking the WL Limit

Message passing can only see what its initial features let it see: give nodes structural features (closed walks, cycles, eigenvectors) to go beyond WL on structure, and distances to random anchor sets to make embeddings position-aware.

\[ C^{(0)}=\big[\mathrm{diag}(A^0),\ \mathrm{diag}(A^1),\ \dots,\ \mathrm{diag}(A^{D-1})\big]\in\mathbb{N}_0^{N\times D} \]

\((A^k)_{vv}\) = number of closed walks of length \(k\) from \(v\). Since \(\mathrm{tr}(A^k)=\sum_n\lambda_n^k\), these features carry spectral information that constant inputs cannot reach.

Lecture 18 · Deep Generative Models for Graphs

Generate a graph as a sequence of decisions — nodes, then edges to earlier nodes — learned autoregressively (GraphRNN, made tractable by BFS ordering); add a GNN policy, validity checks and RL rewards to steer generation toward goals (GCPN).

\[ p(G,\pi)=p(S^\pi)=\prod_{i=1}^{n}\ \prod_{j=\max(1,i-M)}^{i-1} p\big(S^\pi_{i,j}\mid S^\pi_{<i},S^\pi_{i,<j}\big) \]

\(S^\pi_{i,j}\in\{0,1\}\): is new node \(i\) connected to earlier node \(j\)? With BFS ordering, only the last \(M\) nodes need to be considered.

Lecture 14 · Advanced Topics in GNNs — In-Context Learning and Relational Foundation Models

Foundation models for graphs need a universal input format: PRODIGY turns any few-shot graph task into link prediction on a prompt graph; the Relational Transformer turns any database task into masked-cell prediction over (value, column, table) tokens — and both are pretrained on self-generated tasks in that same format.

\[ \hat y_q=\arg\max_{c}\ \cos\big(\mathbf h_{\text{label }c},\ \mathbf h_{q}\big)\qquad\qquad \text{token}_{cell}=\phi_{\text{dtype}}(\text{value})+\text{LM}(\text{column of table}) \]

Warm-up: answer these before you read on

Why is injectivity the key property of an aggregator? from Lecture 6

If two different multisets of neighbour vectors map to the same aggregated vector, the two nodes become indistinguishable from that layer on, so information is lost.

Why can a message-passing GNN with constant features not distinguish a node on a triangle from a node on a square? from Lecture 7

Both see a degree-two neighbour at every iteration of colour refinement; the cycle length is never visible to 1-WL.

Why does GraphRNN need a node ordering? from Lecture 18

The chain rule needs a sequence; the ordering turns the unordered graph into one, and BFS makes that sequence short-range.

How does PRODIGY turn classification into link prediction? from Lecture 14

Label nodes are added to the task graph; a query node is classified by predicting which label node it should be linked to.

More questions from every session you have reached, with spaced repetition: the cumulative review.

In short

This bonus page covers three chapters of the 2024 lecture notes that this year's slides do not: geometric graph learning (notes ch. 17), subgraph matching and motifs (ch. 18) and trustworthy graph AI (ch. 21). One thread joins them: each asks how to put structure we already know into a GNN. In geometry the structure is a symmetry group. In subgraph matching it is a partial order ("is contained in"). In explainability it is a small subgraph that a human can read.

1. Geometric GNNs. A molecule is a graph whose nodes also have 3D coordinates. If you rotate or translate the molecule, its energy stays the same (invariant) and its forces rotate with it (equivariant). Invariant GNNs (SchNet, DimeNet) only feed the network distances and angles, which do not change under rotation. Equivariant GNNs (PaiNN) also carry vector features that rotate together with the input. Geometric diffusion (GeoDiff) generates 3D shapes of molecules by learning to remove noise with an equivariant network.

2. Subgraphs and motifs. A motif is a small pattern that appears in a real network much more often than in a random network with the same degrees. Its significance is a Z-score; the vector of Z-scores (the significance profile) is a fingerprint of a network's domain. Exact subgraph matching is NP-hard, so neural subgraph matching trains a GNN so that "query is a subgraph of target" becomes "query embedding \(\le\) target embedding in every coordinate" (an order embedding). SPMiner then grows frequent motifs greedily in that embedding space.

3. Explainability. GNNExplainer learns a soft mask over edges and features so that the masked graph keeps the model's prediction while the mask stays small. Explanations are judged by fidelity: does the prediction change when you remove the explanation (necessity, \(\text{fid}^+\)), and does the explanation alone keep the prediction (sufficiency, \(\text{fid}^-\))? The characterisation score combines both.

The picture: subgraph matching as an order in embedding space

Neural subgraph matching with order embeddings 0dim 1dim 2 1 target neighbourhood G_T, anchor t (red) query 1query 2 GNN anchor → z ≥ 0 2 z_t z_q1 z_q ≤ z_t: subgraph 3 z_q2 violation E(q,t) = Σᵢ max(0, z_q[i] − z_t[i])² 4

How to read it (hover a step)

  1. Decompose and anchor. Around a node \(t\) of the big target graph, take its \(k\)-hop neighbourhood (here a "bowtie": two triangles sharing \(t\)). Each query also has an anchor node, chosen by the user. Query 1 (a triangle) is contained in the bowtie with its anchor mapped to \(t\). Query 2 (a 4-cycle) is not: the bowtie has no 4-cycle.
  2. Embed. One shared GNN maps every anchored graph to a vector \(z\) with non-negative entries (the embedding of the anchor node is the embedding of the whole anchored graph).
  3. Read the order. The GNN is trained so that "\(G_Q\) is a subgraph of \(G_T\)" holds exactly when \(z_Q\le z_T\) in every coordinate. Geometrically, all subgraphs of \(G_T\) live in the box between the origin and \(z_T\). Query 1 lands inside the box: predicted "yes".
  4. Measure the violation. Query 2 sticks out of the box along dimension 1. The squared amount it sticks out, summed over dimensions, is the violation \(E(q,t)\). Training pushes \(E\) to 0 for true subgraph pairs and above a margin \(\alpha\) for non-subgraph pairs. At test time, predict "subgraph" when \(E\lt\epsilon\).

1 · Geometric graphs and symmetry

Setting (notes p.93). An ordinary attributed graph is \(G=(A,S)\): \(A\) is the \(n\times n\) adjacency matrix and \(S\in\mathbb R^{n\times f}\) holds \(f\) scalar features per node (for an atom: its type and charge). A geometric graph adds positions: \(G=(A,S,R)\) with \(R\in\mathbb R^{n\times d}\), so node \(i\) sits at a point \(r_i\in\mathbb R^d\) (usually \(d=3\)). A molecule is the standard example: atoms are nodes, bonds are edges with features \(a_{ij}\) (bond type), and sometimes we know each atom's 3D position \(r_i\). Proteins, materials and point clouds are other examples.

The problem: coordinates are arbitrary

Coordinates depend on the frame you choose: where you put the origin and how you orient the axes. The same molecule, rotated by 90°, gives a completely different matrix \(R\). A normal GNN that takes \(r_i\) as plain input features would give a different output for the rotated copy, even though physically nothing changed. We want the model to know the symmetry of space.

Invariance and equivariance

Let \(\rho\) be a transformation (for example a rotation), acting on inputs as \(\rho_X\) and on outputs as \(\rho_Y\). A function \(F:X\to Y\) is

  • equivariant if \(F\circ\rho_X=\rho_Y\circ F\): transforming the input and then applying \(F\) gives the same as applying \(F\) and then transforming the output. Transformation and model commute.
  • invariant if \(F\circ\rho_X=F\): the output does not change at all. (Invariance is the special case where \(\rho_Y\) is the identity.)

Physics gives examples of both (notes p.94). The energy of a molecule is a single number; rotating the molecule leaves it unchanged, so it is invariant. The force on each atom is a 3D vector; rotate the molecule and the forces rotate with it, so they are equivariant: \(F(QR)=Q\,F(R)\) for a rotation matrix \(Q\).

The symmetry group for 3D geometric graphs is SE(3), the special Euclidean group: all rigid motions \(r\mapsto Qr+b\) with \(Q\) a rotation (\(Q^\top Q=I\), \(\det Q=1\)) and \(b\in\mathbb R^3\) a translation. "Special" means no reflections (\(\det Q=+1\)). (E(3) also allows reflections; mirror-image molecules can behave differently, so the choice matters.)

Two ways to get symmetry

  1. Data augmentation. Use any model and train it on many randomly rotated and translated copies of every example. The model may learn the symmetry approximately. This is expensive (many copies) and gives no guarantee.
  2. Build the symmetry into the architecture. Design layers that are invariant or equivariant by construction. This shrinks the search space: the model never wastes capacity learning that rotated molecules are the same molecule. This leads to two classes: invariant GNNs (learn invariant scalar features) and equivariant GNNs (learn equivariant vector/tensor features).
Which of these quantities are SE(3)-invariant: (a) \(r_i\), (b) \(r_i-r_j\), (c) \(\lVert r_i-r_j\rVert\), (d) the angle between \(r_j-r_i\) and \(r_k-r_i\)? Which are equivariant?

(a) \(r_i\mapsto Qr_i+b\): neither invariant nor rotation-equivariant in the simple sense, because the translation \(b\) is added. (b) \((Qr_i+b)-(Qr_j+b)=Q(r_i-r_j)\): the translation cancels, so relative positions are translation-invariant and rotation-equivariant. (c) \(\lVert Q(r_i-r_j)\rVert=\lVert r_i-r_j\rVert\) because rotations preserve length: invariant. (d) Angles are computed from dot products, and \((Qu)^\top(Qv)=u^\top Q^\top Qv=u^\top v\): invariant. This is why geometric GNNs work with relative positions, distances and angles, never with raw coordinates.

2 · Invariant GNNs: SchNet and DimeNet

Continuous-filter convolution

On an image, a convolution filter has one weight per grid offset ("one pixel left, one up"). Atoms are not on a grid: the offset \(r_i-r_j\) can be any real vector. So the filter must be a function of the offset, not a lookup table. A continuous-filter convolution (notes p.94) is

\[ h_i^{(l+1)}=(H^{(l)}*W^{(l)})_i=\sum_j h_j^{(l)}\odot W^{(l)}(r_i-r_j). \]
  • \(h_j^{(l)}\in\mathbb R^f\): the feature vector of atom \(j\) at layer \(l\); \(H^{(l)}\) stacks them.
  • \(W^{(l)}:\mathbb R^d\to\mathbb R^f\): the filter-generating function, a small neural network that turns a relative position into a weight vector.
  • \(\odot\): element-wise product. Each feature channel of the neighbour is scaled by its own weight.
  • The sum runs over neighbours \(j\) (in practice all atoms within a cutoff radius).

This is just message passing where the message from \(j\) to \(i\) is "neighbour features, re-weighted by where the neighbour is".

SchNet: only distances

If \(W\) took the full vector \(r_i-r_j\), the layer would not be rotation-invariant. SchNet (2017) makes it invariant by scalarising: \(W\) only sees the distance \(d_{ij}=\lVert r_i-r_j\rVert\). The distance is first expanded in radial basis functions, \[ e_k(r_i-r_j)=\exp\!\big(-\gamma\,(d_{ij}-\mu_k)^2\big),\qquad k=1,\dots,K, \] and an MLP maps the vector \((e_1,\dots,e_K)\) to the filter. Here \(\mu_k\) are fixed centres spread over the useful distance range and \(\gamma\) sets the width of each bump. (The notes' formula is printed without the square; the standard SchNet radial basis is Gaussian in \(d_{ij}-\mu_k\), as above.)

Why the expansion? A single number \(d_{ij}\) is a poor input for an MLP at the start of training: the network would need many layers to carve it into "very close", "bonded", "far". The Gaussian bumps do this carving for free: each \(e_k\) is large only when \(d_{ij}\) is near \(\mu_k\), like a soft one-hot encoding of the distance (notes: "to curb the initial training difficulties").

Mini-example. Centres \(\mu=(1.0, 1.5, 2.0)\) Å and \(\gamma=10\). A bond of length 1.5 Å gives \(e=(e^{-2.5}, 1, e^{-2.5})\approx(0.08, 1, 0.08)\). A distance of 1.1 Å gives \((e^{-0.1}, e^{-1.6}, e^{-8.1})\approx(0.90, 0.20, 0.0003)\). Different distances light up different channels.

DimeNet: distances and angles

Using only distances throws away angular information about how bonds are arranged. DimeNet (2020) passes messages along edges and includes the angle between consecutive bonds \(k\to j\to i\) in the message. Angles are still invariant, so the model stays invariant.

The limit of invariant features

Distances and angles are not a complete description of 3D shape. The notes' example is cis- and trans-1,2-dichloroethene: two molecules with the same atoms and bonds, where the two chlorine atoms sit on the same side (cis) or opposite sides (trans) of the double bond. Local distance and angle sets can coincide, but the molecules are different (they are geometric isomers). To tell them apart, the model needs directional information: which way vectors point relative to each other.

Lecture notes figure, page 95
Geometric isomers: the left pair has identical local distances and angles (α), so an invariant model sees them as the same. The right pair shows the directional information (vectors such as \((r_x,r_y)\) and \((-r_x,-r_y)\)) that separates them. notes p.95 ↗

The general limitation (notes p.94): an invariant GNN only works well if its input features already contain every needed interaction between directions. Anything that requires comparing directions across several hops is lost when you reduce each edge to a scalar.

Invariant vs. equivariant outputs under a rotation of a molecule. The energy is a scalar: it must not change (invariance, SchNet-style). Forces are vectors: they must rotate with the molecule (equivariance, PaiNN-style). A model that predicts both must treat the two kinds of output differently, which is what scalar and vector channels do.

3 · Equivariant GNNs: PaiNN

An equivariant GNN keeps two kinds of features at every node: scalars \(s_i\in\mathbb R^F\) (invariant: they do not change under rotation) and vectors \(v_i\in\mathbb R^{F\times 3}\) (equivariant: under a rotation \(Q\), each of the \(F\) channels rotates, \(v_i\mapsto v_iQ^\top\)). PaiNN (2021) is the example in the notes (p.94–95). Each layer adds residual updates: \[ s_i^{(l+1)}=s_i^{(l)}+\Delta s_i^{(l)},\qquad v_i^{(l+1)}=v_i^{(l)}+\Delta v_i^{(l)}. \]

The scalar message is a continuous-filter convolution with a distance-only filter, just like SchNet: \[ \Delta s_i^{(l)}=\sum_j \phi_s\big(s_j^{(l)}\big)\odot W_s\big(\lVert r_{ij}\rVert\big). \] The vector message has two parts: \[ \Delta v_i^{(l)}=\underbrace{\sum_j v_j^{(l)}\odot\phi_{vv}\big(s_j^{(l)}\big)\odot W_{vv}\big(\lVert r_{ij}\rVert\big)}_{\text{rescale neighbour's vectors}}+\underbrace{\sum_j \phi_{vs}\big(s_j^{(l)}\big)\odot W_{vs}\big(\lVert r_{ij}\rVert\big)\,\frac{r_{ij}}{\lVert r_{ij}\rVert}}_{\text{new vectors along the bond direction}}. \] \(r_{ij}=r_i-r_j\) is the relative position; \(\phi_s,\phi_{vv},\phi_{vs}\) are MLPs on scalars; \(W_s,W_{vv},W_{vs}\) are filter networks on distances.

Why this is equivariant

Look at what each term multiplies. Every weight (\(\phi(\cdot)\), \(W(\cdot)\)) is computed from scalars and distances, which are invariant. Those invariant weights multiply either an existing vector \(v_j\) or the unit vector \(r_{ij}/\lVert r_{ij}\rVert\), both of which rotate with the input. "Invariant number × equivariant vector" is equivariant, and a sum of equivariant vectors is equivariant. So rotating the molecule rotates every \(v_i\) and leaves every \(s_i\) unchanged, at every layer. Translations cancel because only differences \(r_i-r_j\) appear. The key design rule: never apply a nonlinearity directly to vector components (that would break rotation); apply nonlinearities only to scalars, and use scalars to gate vectors.

PaiNN also has an "update" block that mixes the scalar and vector channels inside a node, for example via the norms \(\lVert v_i\rVert\) and dot products \(\langle Uv_i, Vv_i\rangle\), which are invariant and can feed back into the scalars. The notes print the initialisation as \(s^{(0)}=0,\ v^{(0)}=e_i\); in the PaiNN paper the scalars start from an embedding of the atom type and the vectors start at zero (the first vectors are created by the bond-direction term).

Invariant outputs from an equivariant network: how would you predict the energy (a scalar) and the forces (vectors) with PaiNN?

Energy: after the last layer, apply an MLP to each \(s_i\) and sum over atoms; the result is invariant. Forces: either read them from the vector features (an equivariant linear map of \(v_i\)), or, as is common in practice, take \(F_i=-\partial E/\partial r_i\). The gradient of an invariant function with respect to positions is automatically equivariant, and it guarantees energy conservation.

Invariant vs equivariant, in one sentence. Invariant models throw away direction at the input and keep only numbers that cannot change; equivariant models keep direction all the way through, at the cost of more careful (and more expensive) layers.

4 · Geometric generative models: conformations by diffusion

Geometric generative models are used for molecule and protein design, biomolecule structure prediction and simulating how proteins and drug molecules bind (notes p.95).

The task: molecular conformation generation

Input: a molecular graph \(\mathcal G\) (atoms and bonds, no positions). Output: a conformation \(C\), i.e. 3D coordinates for every atom, that is physically stable. One molecule can fold into several stable shapes, so this is a distribution \(p(C\mid\mathcal G)\), not a single answer. Physics says stable shapes follow the Boltzmann distribution \[ p(C)\propto\exp\!\big(-E(C)/T\big), \] where \(E(C)\) is the energy of the shape and \(T\) the temperature (in energy units). Low-energy shapes are exponentially more likely; higher temperature flattens the distribution. The model must learn to sample from this distribution.

Diffusion models in four lines

  1. Forward process (fixed, no learning). Take a real sample \(x_0\) and destroy it gradually with noise over time steps \(t=0,\dots,T\): \(x_t=\mu_t x_0+\sigma_t\epsilon\), with \(\epsilon\sim\mathcal N(0,I)\). \(\mu_t\) shrinks and \(\sigma_t\) grows with \(t\), so \(x_T\) is almost pure noise.
  2. Reverse process (learned). Train a network to undo one step: given \(x_t\), predict \(x_{t-1}\) (equivalently, predict the noise \(\epsilon\) that was added).
  3. Sampling. Start from pure noise \(x_T\) and apply the learned denoiser step by step down to \(x_0\).
  4. Why it works. Each step is a small, easy correction; chaining many small corrections can produce a complex distribution.

GeoDiff

GeoDiff (2022) applies this to conformations. The forward process \(q(C^{(t)}\mid C^{(t-1)})\) adds Gaussian noise to the atom positions. The model learns the reverse \(p_\theta(C^{(t-1)}\mid\mathcal G, C^{(t)})\), conditioned on the molecular graph. The denoising network is an equivariant GNN. This matters: if you rotate the noisy input, the predicted correction must rotate too. Then the learned distribution over shapes is itself rotation-invariant: the model never prefers one orientation of the molecule over another.

Lecture notes figure, page 96
Geometric diffusion: the reverse chain \(C^T\to\cdots\to C^0\) turns random coordinates into a molecule's 3D shape; each arrow is the learned step \(p_\theta(C^{t-1}\mid\mathcal G,C^t)\), and the dashed arrow is the fixed noising step \(q(C^t\mid C^{t-1})\). notes p.96 ↗
The denoiser is equivariant and the starting noise \(\mathcal N(0,I)\) is rotation-invariant. Show that the final distribution of \(C^0\) is rotation-invariant.

Induction on the chain. \(p(C^T)\) is invariant: \(\mathcal N(0,I)\) has the same density at \(QC\) and \(C\). If the step kernel is equivariant, \(p_\theta(QC^{t-1}\mid QC^t)=p_\theta(C^{t-1}\mid C^t)\), then \(p(QC^{t-1})=\int p_\theta(QC^{t-1}\mid C')p(C')\,dC'\); substitute \(C'=QC^t\) (a rotation has Jacobian 1) to get \(\int p_\theta(QC^{t-1}\mid QC^t)p(QC^t)\,dC^t=\int p_\theta(C^{t-1}\mid C^t)p(C^t)\,dC^t=p(C^{t-1})\). So every marginal, including \(p(C^0)\), is invariant. (Translations are handled separately, by keeping the centre of mass at zero.)

5 · Subgraphs, isomorphism and network motifs

Subgraphs are the building blocks of networks: they help to characterise and to tell apart different kinds of networks. In chemistry, functional groups (such as –OH) are subgraphs that decide much of a molecule's behaviour (notes p.97).

Definitions

Let \(G=(V,E)\).

  • Node-induced subgraph: choose nodes \(V'\subseteq V\) and keep every edge of \(G\) among them: \(E'=\{(u,v)\in E: u,v\in V'\}\). (Also just "induced subgraph".)
  • Edge-induced subgraph: choose edges \(E'\subseteq E\) and keep the nodes they touch: \(V'=\{v\in V:\exists u,\ (v,u)\in E'\}\).

Example: in a triangle \(\{a,b,c\}\), the node set \(\{a,b,c\}\) induces the full triangle. The path \(a\)–\(b\)–\(c\) is an edge-induced subgraph (edges \(ab, bc\)) but not a node-induced one, because inducing on \(\{a,b,c\}\) must also keep the edge \(ac\).

Graph isomorphism. \(G_1=(V_1,E_1)\) and \(G_2=(V_2,E_2)\) are isomorphic if there is a bijection \(f:V_1\to V_2\) with \((u,v)\in E_1\iff(f(u),f(v))\in E_2\). The complexity of finding \(f\) is famously open: no polynomial algorithm is known, and it is not known to be NP-hard. Subgraph isomorphism: \(G_2\) is subgraph-isomorphic to \(G_1\) if some subgraph of \(G_2\) is isomorphic to \(G_1\); we then say "\(G_1\) is a subgraph of \(G_2\)". This problem is NP-hard (it contains, for example, the clique problem).

Motifs

A network motif is a recurring, significant pattern of interconnections (notes p.97):

  • Pattern: a small node-induced subgraph.
  • Recurring: it is found many times (we need a definition of frequency).
  • Significant: it is more frequent than expected in a suitable random graph (we need a null model).

Classic examples (notes Fig. 18.1): the feed-forward loop (\(a\to b\), \(b\to c\), and also \(a\to c\)) in neuron networks, where it filters out short "noise" signals; the parallel loop in food webs; the single-input module (one regulator controlling many genes) in gene control networks. In social networks the closest relative is the triangle: triadic closure ("friends of friends become friends") makes triangles strongly over-represented.

Frequency

Let \(G_Q\) be a small query graph and \(G_T\) the target graph. Overlapping occurrences are allowed.

  • Graph-level frequency: the number of distinct node subsets \(V_T'\subseteq V_T\) whose induced subgraph is isomorphic to \(G_Q\).
  • Node-level (anchored) frequency: pick an anchor \(v\in V_Q\). Count the nodes \(u\in V_T\) such that some subgraph of \(G_T\) is isomorphic to \(G_Q\) with the isomorphism mapping \(u\) to \(v\). Each \(u\) counts once, however many copies it sits in.

Why two definitions? Graph-level counts can explode. Take a star with one centre and 100 leaves, and let \(G_Q\) be a star with 6 leaves. Every choice of 6 leaves gives an induced copy, so the graph-level frequency is \(\binom{100}{6}\approx1.2\times10^9\). The node-level frequency with the anchor at the query's centre is just 1 (only the centre can play that role). Node-level counts are robust and, as section 6 shows, match how GNNs embed anchored neighbourhoods. A dataset of many graphs is treated as one big disconnected \(G_T\).

Null models: what is "random"?

  • Erdős–Rényi \(G_{n,p}\): \(n\) nodes; each edge appears independently with probability \(p\). Degrees are binomial, which is unrealistic for social graphs (they have hubs). Comparing a social network to \(G_{n,p}\) would make almost every pattern look "significant" just because of the hubs.
  • Configuration model: keep the real graph's degree sequence. Give each node as many "spokes" (half-edges) as its degree, then pair up all spokes uniformly at random. The result \(G^{\text{rand}}\) has exactly the same degrees as \(G^{\text{real}}\). (Self-loops and multi-edges may appear; they are rare in large sparse graphs and are usually discarded.)
  • Switching: start from the real graph and repeat \(Q\cdot|E|\) times (\(Q\) large, e.g. 100): pick two edges \((a,b),(c,d)\) at random and rewire them to \((a,d),(c,b)\), but only if this creates no self-loop or multi-edge. Every node keeps its degree, so the result is a random graph with the same degree sequence. It is the slowest method.

Degree-preserving models ask the right question: "is this pattern frequent beyond what the degrees alone explain?" They deliberately destroy everything else, such as clustering (notes p.99: you must decide which properties not to preserve).

Significance: Z-scores and the significance profile

For motif \(i\), let \(N_i^{\text{real}}\) be its count in the real graph, and \(\bar N_i^{\text{rand}}\), \(\operatorname{Std}(N_i^{\text{rand}})\) the mean and standard deviation of its count over many random graphs from the null model. Then \[ Z_i=\frac{N_i^{\text{real}}-\bar N_i^{\text{rand}}}{\operatorname{Std}(N_i^{\text{rand}})},\qquad SP_i=\frac{Z_i}{\sqrt{\sum_j Z_j^2}}. \] \(Z_i\gt 0\): over-represented (a motif); \(Z_i\lt 0\): under-represented (an "anti-motif"). The significance profile \(SP\) is the vector of Z-scores normalised to unit length. Larger graphs tend to give larger Z-scores, so normalising lets you compare networks of very different sizes: only the relative significance of the patterns remains.

Toy example. Suppose a follower graph has 500 triangles, and 100 degree-preserving random graphs have on average 200 triangles with standard deviation 50. Then \(Z_\triangle=(500-200)/50=6\): triangles are strongly over-represented. If the open triad (a path of length 2) has \(Z=-2\) and these are the only two patterns, \(SP=(6,-2)/\sqrt{40}\approx(0.95,-0.32)\).

Lecture notes figure, page 100
Significance profiles (Milo et al., Science 2004) over 13 directed 3-node subgraphs: networks from the same domain (gene regulation, neurons, web and social, word adjacency) have similar profiles, so the profile is a domain fingerprint. notes p.100 ↗

Extensions: directed or undirected, coloured (node types) or not, temporal or static motifs; and variations in the frequency definition, the significance test and the null model (notes p.99).

Do one switching step on the path a–b–c–d (edges ab, bc, cd), choosing the edges ab and cd. Which rewirings are allowed, and what happens to the degrees?

There are two ways to swap endpoints. (1) \((a,b),(c,d)\to(a,d),(c,b)\): the new edge cb duplicates the existing edge bc, a multi-edge, so this switch is rejected. (2) \((a,b),(d,c)\to(a,c),(d,b)\): the edges become ac, bc, bd, which is simple, so it is accepted; the path a–b–c–d becomes the path a–c–b–d. Degrees before and after: a 1, b 2, c 2, d 1. Every accepted switch removes one edge end from each of a, b, c, d and gives one back, so every degree is preserved.

Motif over-representation in the running project's synthetic X world (notebooks/project/retweet_thread.py, seed 0): observed counts against a degree-preserving randomisation of the retweet graph (mean of 5 null graphs, error bars ±1 sd). Reciprocal dyads are 2× the null (Z ≈ 31); triangles of mutual ties are 30× (Z ≈ 42), and almost half of them sit inside the planted rings. A motif is a count against a null, never a raw count.

6 · Neural subgraph matching with order embeddings

Problem (notes p.100). Given a large target graph \(G_T\) (possibly disconnected) and a connected query \(G_Q\): is \(G_Q\) a subgraph of \(G_T\)? Exact algorithms are exponential in the worst case. The neural approach (NeuroMatch) trains a GNN to predict the answer, using node-anchored subgraphs. The idea is to use the geometry of the embedding space to mirror the logic of subgraph isomorphism.

Step 1: decompose into anchored neighbourhoods

  1. For each node \(v\) of \(G_T\), extract the \(k\)-hop neighbourhood around \(v\) (for example by BFS), with \(v\) as the anchor.
  2. Do the same for the query \(G_Q\), around its user-chosen anchor.
  3. Embed every anchored neighbourhood with a GNN. The embedding of the anchor node is the embedding of the anchored subgraph.

The answer is "yes" if the query fits inside the neighbourhood of some target node. A \(k\)-layer GNN only sees \(k\) hops, so a query whose radius around the anchor exceeds \(k\) cannot be captured (notes p.102).

Step 2: order embeddings

Define a partial order on \(\mathbb R^D\): \(u\le v\) iff \(u_i\le v_i\) for every coordinate \(i\). Subgraph isomorphism is also a partial order on graphs, with the same three properties (notes Fig. 18.5):

  • Transitivity: \(G_1\subseteq G_2\) and \(G_2\subseteq G_3\) imply \(G_1\subseteq G_3\). In the embedding: \(z_1\le z_2\le z_3\) implies \(z_1\le z_3\).
  • Anti-symmetry: \(G_1\subseteq G_2\) and \(G_2\subseteq G_1\) imply \(G_1\cong G_2\). In the embedding: \(z_1\le z_2\le z_1\) implies \(z_1=z_2\).
  • Closure under intersection: the trivial one-node graph is a subgraph of everything. In the embedding: the origin (embeddings are forced to be non-negative) is below every point, and any two points have a common lower bound, their coordinate-wise minimum.

So if the GNN maps "\(\subseteq\)" to "\(\le\)", these logical properties hold for free in the geometry. Checking a candidate pair is then just \(D\) comparisons, instead of an NP-hard search.

Lecture notes figure, page 101
Order embedding space: the target neighbourhood (red square) dominates query 1 (green, below-left in every coordinate, so query 1 is a subgraph) but not query 2 (orange, to the right). notes p.101 ↗

Step 3: the loss

We want \(\forall i:\ z_q[i]\le z_t[i]\iff G_Q\subseteq G_T\). The amount by which a pair violates the order is \[ E(G_q,G_t)=\sum_{i=1}^{D}\max\big(0,\ z_q[i]-z_t[i]\big)^2. \] \(E=0\) exactly when \(z_q\le z_t\). The loss is a max-margin loss: \[ L(G_q,G_t)=\begin{cases}E(G_q,G_t) & \text{if } G_q\subseteq G_t \ \text{(positive pair: push the violation to 0)}\\ \max\big(0,\ \alpha-E(G_q,G_t)\big) & \text{if } G_q\not\subseteq G_t \ \text{(negative pair: violation at least } \alpha)\end{cases} \] with margin \(\alpha\gt 0\). Why cap the negative loss at \(\alpha\)? Without the cap, the network could lower the loss forever by pushing negative pairs infinitely far apart, which would dominate training and teach nothing useful (notes p.102). Once a negative pair is "far enough" (\(E\ge\alpha\)), it contributes zero.

Mini-example. \(D=2\), \(\alpha=1\). Target \(z_t=(3,1)\). Query A: \(z_A=(1,0.5)\), so \(E=0\): predicted subgraph. Query B: \(z_B=(2,2)\), so \(E=\max(0,-1)^2+\max(0,1)^2=1\). If B really is not a subgraph, its loss is \(\max(0,1-1)=0\): already fine. If B is a subgraph, the loss is 1 and the gradient pushes \(z_B[2]\) down (or \(z_t[2]\) up).

Step 4: training data

Each iteration samples a target \(G_T\), a positive query \(G_Q^+\) and a negative query \(G_Q^-\) (notes p.103):

  • Positive: sample an induced subgraph of \(G_T\) by BFS sampling. Start with \(S=\{v\}\), visited \(V=\emptyset\). At each step, let \(N(S)\) be all neighbours of \(S\); add a random 10% of \(N(S)\setminus V\) to \(S\) and put the rest into \(V\). After \(K\) steps, take the subgraph induced by \(S\), anchored at \(v\). Typically 3–5 BFS layers, trading runtime against accuracy.
  • Negative: corrupt \(G_Q\) by adding or removing nodes and edges so that it is no longer a subgraph.

Half the pairs are positive and half negative. At inference, embed the anchored query and every anchored target neighbourhood, and predict "subgraph" if \(E(G_Q,G_T)\lt\epsilon\). Target embeddings can be precomputed once and reused for many queries.

Why does the method answer "is \(G_Q\) contained with its anchor at \(v\)?" rather than "how many copies are there?" — and how would you use it to estimate the node-level frequency?

Each target embedding describes one anchored neighbourhood, so the comparison \(z_Q\le z_{N(v)}\) answers a yes/no question per anchor. Summing over anchors gives exactly the node-level (anchored) frequency: \(\#\{v: z_Q\le z_{N(v)}\}\). Graph-level counts (how many copies) would need the full isomorphism map, which the embedding does not give. This is why the anchored definition fits neural methods.

Order embeddings for subgraph matching. Every graph is a point; "q is a subgraph of t" is predicted iff z_q ≤ z_t in every coordinate, i.e. t lies in the shaded quadrant above and to the right of q. Transitivity comes free from the geometry (proof workshop below). Training only has to push non-subgraphs out of the quadrant, penalised by E(q,t) = ‖max(0, z_q − z_t)‖².

7 · Mining frequent motifs: SPMiner

Problem (notes p.103): among all graphs with \(k\) nodes, find the \(r\) with the highest frequency in \(G_T\). Classic methods must (1) enumerate all size-\(k\) connected subgraphs and (2) count each type, which needs isomorphism tests. Both explode combinatorially, so exact motif counting is feasible only for small sizes (about 3 to 7 nodes).

SPMiner reuses the order embedding from section 6:

  1. Decompose \(G_T\) into overlapping node-anchored neighbourhoods.
  2. Embed them into the order embedding space with the trained subgraph-matching GNN.
  3. Estimate frequency fast. For a candidate motif \(G_Q\) with embedding \(z_Q\), count the sampled neighbourhoods \(G_N\) whose embedding lies in its supergraph region: \[ S_E=\{\,z_N:\ z_Q\le z_N,\ G_N\subseteq G_T\,\}. \] Every neighbourhood above-right of \(z_Q\) contains the motif, so \(|S_E|\) estimates the node-level frequency. No isomorphism tests are needed.
  4. Motif walk (a greedy, beam-search-like procedure):
    • Pick a random start node \(u\) in \(G_T\); set \(S=\{u\}\).
    • Repeatedly add one neighbour (in \(G_T\)) of some node of \(S\). Among the candidates, choose the one whose new motif (the subgraph induced by \(S\)) keeps \(|S_E|\) largest. Equivalently, minimise the total violation: the sum of \(E(G_Q,G_N)\) over neighbourhoods \(G_N\) that are not above \(z_Q\).
    • Stop when \(S\) reaches the target size \(k\).
Lecture notes figure, page 104
SPMiner: decompose \(G_T\) into anchored neighbourhoods, embed them in order embedding space (the same encoder as neural subgraph matching), then grow frequent patterns step by step. notes p.104 ↗

Intuition for the walk. Adding a node can only make a motif bigger, so its embedding moves up and to the right, and fewer neighbourhoods lie above it. The walk picks, at each step, the growth direction that loses the fewest neighbourhoods. In the notes' Fig. 18.7 the red dots move from the dense lower-left of the cloud (small, common patterns) toward the upper right, and the shaded supergraph region of the final motif still contains many blue neighbourhood points. This lets the method target motifs far larger than exact counting allows (the notes' example: the most common motifs with 20 nodes).

The search is greedy, so it can miss the true top motif; running several walks from different start nodes (a beam) reduces this risk. Accuracy also depends on how well the encoder has learned the order: false "yes" answers inflate \(|S_E|\).

8 · Explainability: what and why

Trustworthy AI covers explainability, fairness, robustness and privacy; for graphs, the role of topology in each was long unexplored (notes p.114). The notes' chapter focuses on explainability.

Deep models are black boxes. Explainable AI (XAI) is the umbrella term for research that opens them. Why we want it (notes p.114):

  • Trust: people accept a prediction more readily when they can see the reason.
  • Causality: attribute importance suggests causes ("attribute X makes the outcome Y"), which can generate scientific hypotheses. (Careful: importance for the model is not automatically causal in the world.)
  • Transferability: before deploying on new data, we need to know whether the model's reasoning will still hold there.
  • Fair and ethical decisions: society needs to check that the reasons for a decision are acceptable (e.g. a loan refusal).

What makes a model explainable?

  • Importance values: scores for input features, pixels, words, nodes or edges.
  • Attributions: simple relationships between the prediction and the inputs.
  • Concepts and prototypes: explanations in terms of human concepts or typical examples.

Some models are explainable by design. Linear regression \(y=w_1x_1+\dots+w_dx_d\): the weight \(w_i\) is the effect of feature \(x_i\) on the prediction. Decision trees: each internal node is a readable logical test. Dimension reduction lets us look at the data and the class boundary. For black-box models we use add-on methods:

  • Proxy (surrogate) model: learn an interpretable model that imitates the black box locally around one input (the idea behind LIME).
  • Saliency map: the gradient of the output with respect to the input; large gradients mark sensitive inputs.
  • Attention weights: visualise them in transformers or GAT. (They give "some" explanation, but high attention does not always mean high importance.)

Settings: instance-level explanations explain one input \(x\) and its prediction \(\hat y\); model-level explanations describe what the model does over a dataset or a whole class.

Explanations for graphs

For a GNN, an explanation is an important subgraph plus a small subset of node features that play a crucial role in the prediction (notes p.116). Two different goals:

  • Explain the phenomenon: what makes a molecule toxic, in reality?
  • Explain the model: why does this model recommend no loan for person X?

The two coincide only when the model is right for the right reasons. This distinction returns in section 10.

9 · GNNExplainer: learn a mask

GNNExplainer (2019) is post-hoc and model-agnostic: train any GNN as usual and save it; at test time, explain its prediction on a given instance. It works for node classification, link prediction and graph classification, and for many architectures (GCN, GAT, GraphSAGE, gated graph sequence networks, graph networks). It explains structure (which edges) and features (which feature dimensions) together (notes p.116).

Setting (node classification)

  • \(G_c(v)\): the computation graph of node \(v\), i.e. its \(L\)-hop neighbourhood for an \(L\)-layer GNN; \(A_c(v)\) its adjacency matrix; \(X_c(v)=\{x_u:u\in G_c(v)\}\) its node features.
  • The trained GNN \(\phi\) gives a distribution \(P_\phi(Y\mid A_c(v),X_c(v))\) over labels.
  • The explainer outputs \((\hat A,\hat X^F)\): a subgraph \(\hat G\subseteq G_c(v)\) with adjacency \(\hat A\), and features \(\hat X^F=\{x_u^F:u\in\hat G\}\) where \(F\) is a mask that removes unimportant feature dimensions.

Objective: mutual information

The mutual information of two random variables measures how much knowing one reduces uncertainty about the other: \[ I(X,Y)=D_{KL}\big(P_{(X,Y)}\,\Vert\,P_X\otimes P_Y\big)=H(X)-H(X\mid Y)=H(Y)-H(Y\mid X). \] It is 0 exactly when \(X\) and \(Y\) are independent, and symmetric. \(H\) is entropy (uncertainty). A good explanation should carry as much information about the prediction as possible: \[ \max_{\hat G}\ I\big(Y,(\hat G,\hat X^F)\big)=H(Y)-H\big(Y\mid A=\hat A,\ X=\hat X^F\big). \] For a fixed trained model, \(H(Y)\) is a constant, so this means: choose the subgraph and features that make the model most certain of its prediction, i.e. minimise the conditional entropy.

From discrete to continuous

There are exponentially many subgraphs, so we cannot try them all. GNNExplainer treats the explanation as a distribution over subgraphs, which (1) can capture several plausible explanations and (2) turns a discrete search into a continuous optimisation. It learns a real matrix \(M\) (one entry per edge) and uses the soft mask \[ A_c\odot\sigma(M), \] where \(\sigma\) is the sigmoid, squashing each entry to \([0,1]\): roughly "probability that this edge is kept". The expected-adjacency approximation \(\mathbb E[H(\cdot\mid\tilde A)]\approx H(\cdot\mid\mathbb E[\tilde A])\) is used, even though \(H\) is not convex (notes p.117). Features get a mask \(\sigma(F)\) in the same way.

The full objective (notes p.118): \[ \min_{M,F}\ -\log P_\phi\big(Y=y\mid A=A_c\odot\sigma(M),\ X=\hat X^F\big)\ +\ \lambda_1\sum\sigma(M)\ +\ \lambda_2\sum\sigma(F). \] The first term keeps the prediction confident (it is the cross-entropy for the predicted class \(y\)); the two regularisers make the masks small, so the explanation is concise. \(\lambda_1,\lambda_2\) trade fidelity against size. After optimisation, threshold \(A_c\odot\sigma(M)\) to get the discrete explanation \(\hat G\).

Lecture notes figure, page 118
Top: the relaxed adjacency matrix \(A_c\odot\sigma(M)\) before and after training, and the explanation subgraph \(G_S\) after thresholding. Bottom: the post-hoc pipeline: a mask-generation algorithm produces feature, edge and node masks; the masked graph is fed to the frozen GNN; the objective compares its prediction with the original. notes p.118 ↗

Which graph to mask: node classification, the node's computation graph; link prediction, the union of the two endpoints' computation graphs; graph classification, the whole graph.

Alternatives (notes p.118): GNN saliency maps (gradients of the output score with respect to edges or features) and GAT attention scores. Both are cheaper, but gradients are local (they measure sensitivity, not the effect of removing an edge) and attention may not reflect importance.

Why is a mask on the computation graph enough to explain node \(v\)? What happens if the explainer keeps an edge 3 hops away from \(v\) in a 2-layer GNN?

An \(L\)-layer GNN's output at \(v\) depends only on nodes within \(L\) hops: that is \(G_c(v)\). An edge 3 hops away never enters the computation of a 2-layer GNN, so its mask entry has zero gradient from the prediction term; only the size penalty acts on it, pushing it to 0. So restricting to \(G_c(v)\) loses nothing and saves computation.

BA-Shapes, the standard synthetic benchmark for explainers: a Barabási–Albert base graph (grey) with five-node "house" motifs attached. A node's label is its role in a house (top, middle, bottom) or "base". For the target node (orange) the ground-truth explanation is its house's edges (red). GNNExplainer learns a soft mask over edges; its quality is how much mask weight falls on the red edges.

10 · Evaluating explanations: fidelity and characterisation

Usually there is no ground-truth explanation, and evaluation has several dimensions: the goal (phenomenon or model), the masking type, and the kind of explanation (sufficient or necessary) (notes p.120). The GraphFramEx framework (diagram on notes p.119) separates the two goals: it trains the GNN, generates a mask with either the true label or the prediction as target, turns the mask into an explanation, and scores it with the characterisation score.

  • Phenomenon focus: the target is the true label \(y\). Does the explanation capture the real reason?
  • Model focus: the target is the model's own prediction \(\hat y\). Does the explanation capture why the model said what it said?

Fidelity

Let \(S\) be the explanation subgraph, \(G_S\) the graph with only \(S\) kept, and \(G_{C\setminus S}\) the graph with \(S\) removed. Over \(N\) explained instances: \[ \text{fid}^+=\frac1N\sum_{i=1}^N\Big(\mathbb 1(\hat y_i=y_i)-\mathbb 1\big(\hat y_i^{G_{C\setminus S}}=y_i\big)\Big),\qquad \text{fid}^-=\frac1N\sum_{i=1}^N\Big(\mathbb 1(\hat y_i=y_i)-\mathbb 1\big(\hat y_i^{G_S}=y_i\big)\Big). \] \(\hat y_i\) is the prediction on the full graph and \(y_i\) the target (true label or model prediction, depending on the focus). Fidelity measures how much correctness you lose.

  • \(\text{fid}^+\) (remove the explanation): high means removing \(S\) destroys the prediction, so \(S\) is necessary. Ideal: \(\text{fid}^+\to1\).
  • \(\text{fid}^-\) (keep only the explanation): low means \(S\) alone reproduces the prediction, so \(S\) is sufficient. Ideal: \(\text{fid}^-\to0\).

Characterisation score

To summarise both in one number, take a weighted harmonic mean of \(\text{fid}^+\) and \(1-\text{fid}^-\): \[ c=\frac{w_++w_-}{\dfrac{w_+}{\text{fid}^+}+\dfrac{w_-}{1-\text{fid}^-}}=\frac{(w_++w_-)\,\text{fid}^+\,(1-\text{fid}^-)}{w_+(1-\text{fid}^-)+w_-\,\text{fid}^+}, \] usually with \(w_+=w_-=1\). Like the F1 score, the harmonic mean is high only if both parts are high. (The notes' first fraction prints \(w_-/\text{fid}^-\) in the denominator; the second, expanded form shows it must be \(w_-/(1-\text{fid}^-)\).)

Worked example. Explain 10 correctly predicted nodes (so \(\mathbb 1(\hat y_i=y_i)=1\) for all). Removing the explanation flips 6 predictions: \(\text{fid}^+=6/10=0.6\). Keeping only the explanation, 9 of 10 stay correct: \(\text{fid}^-=1/10=0.1\). Then \(c=\dfrac{2\cdot0.6\cdot0.9}{0.9+0.6}=\dfrac{1.08}{1.5}=0.72\). The explanation is quite sufficient but only moderately necessary: the model can often find another route to the same answer when \(S\) is gone.

Other criteria and other kinds of explanation

  • Quality: high fidelity and characterisation. Stability: similar explanations across random seeds of the optimisation. Complexity: short, readable explanations.
  • Counterfactual explanations: what minimal change would move the instance to a different class? ("If these three edges were missing, this account would be classified as human.")
  • Model-level explanations: what do all instances of a class have in common, for example a typical subgraph the model associates with "toxic"?
An explainer returns the whole computation graph as the "explanation". What are its \(\text{fid}^-\), its \(\text{fid}^+\), and why is it still useless?

Keeping everything reproduces the original prediction: \(\text{fid}^-=0\) (perfectly sufficient). Removing everything leaves an empty graph, which usually breaks the prediction: \(\text{fid}^+\) is high. So the characterisation score can look excellent. But the explanation has maximal complexity and tells a human nothing. This is why fidelity must be read together with explanation size (sparsity), and why GNNExplainer penalises mask size.

The two fidelities, as three versions of the same graph. Fid+ asks whether the explanation is necessary: remove it, and does the prediction change? Fid− asks whether it is sufficient: keep only it, and does the prediction survive? In the L21 notebook GNNExplainer is always necessary (fid+ = 1.0) but sufficient only about half the time (fid− ≈ 0.47). One number cannot say both.

Key idea

Build known structure into graph learning. Symmetry: make layers invariant or equivariant to rotations and translations, so a model of molecules cannot depend on the coordinate frame. Order: embed anchored subgraphs so that "is a subgraph of" becomes "is below-left of", turning an NP-hard check into coordinate comparisons. Readability: explain a GNN by the smallest subgraph and feature set that keep its prediction, and test explanations by removing them and by keeping only them.

\[ \underbrace{F(Q R+b)=Q\,F(R)}_{\text{equivariance}}\qquad \underbrace{E(q,t)=\sum_i\max(0,z_q[i]-z_t[i])^2}_{\text{order violation}}\qquad \underbrace{\min_{M}\ -\log P_\phi\big(y\mid A_c\odot\sigma(M)\big)+\lambda\textstyle\sum\sigma(M)}_{\text{GNNExplainer}} \]

All three replace an expensive or ill-defined discrete question (all frames, all subgraphs, all explanations) with a continuous object that gradient descent can handle.

The mathematics, step by step

Three topics, each with its own piece of mathematics: symmetry under rotations for molecules, an order relation between embeddings for subgraph matching, and information theory for explanations. The cards keep the three apart and give each formula its small numeric check.

Symbols used in this session

symbolmeaningwhat kind of object
\(r_i\)position of atom \(i\) in spacevector in \(\mathbb R^3\)
\(r_{ij},\ d_{ij}\)\(r_i-r_j\) and its length \(\lVert r_{ij}\rVert\)vector; non-negative number
\(R\)a rotation: \(R^\top R=I\), \(\det R=1\)\(3\times3\) matrix
\(s_i,\ v_i\)scalar features and vector features of atom \(i\)invariant numbers; vectors that rotate with the molecule
\(\odot\)entry-by-entry productoperation
\(N_i^{\text{real}},\ N_i^{\text{rand}}\)number of occurrences of motif \(i\) in the real graph, and in a randomised graphcounts
\(z_q,\ z_t\)embeddings of the query graph and of the target graphvectors in \(\mathbb R^D\) with non-negative entries
\(H(Y)\)entropy of the prediction \(Y\): \(-\sum_cp_c\log p_c\)non-negative number
\(I(X,Y)\)mutual information: how much knowing \(X\) reduces the uncertainty about \(Y\)non-negative number

1Invariance and equivariance to rotation and translation

\[ \text{invariant: } f(Rr_1+t,\dots,Rr_n+t)=f(r_1,\dots,r_n)\qquad \text{equivariant: } f(Rr_1+t,\dots)=R\,f(r_1,\dots,r_n) \]

In words. Turning or shifting a molecule must not change a predicted number such as its energy (invariant), and must turn a predicted vector such as a force in the same way (equivariant).

Why it has this form. Coordinates depend on where the origin is and how the axes point, which is as arbitrary as the numbering of nodes in Lecture 1. A model that is not built to respect this has to learn it from data, by seeing each molecule in many orientations. Distances \(d_{ij}=\lVert r_i-r_j\rVert\) are unchanged by rotations and translations, so any function of distances alone is invariant. Difference vectors \(r_{ij}\) are unchanged by translation and rotate with \(R\), so they are the building blocks of equivariant outputs.

With numbers. Atoms at \(r_1=(1,0)\) and \(r_2=(0,0)\) (in the plane, for brevity). Rotate by 90° and shift by \((5,5)\): \(r_1'=(5,6)\), \(r_2'=(5,5)\). Distance: \(1\) before and after (invariant). Difference vector: \((1,0)\) before, \((0,1)\) after, i.e. the old one rotated by 90° (equivariant).

Watch out. Reflections are a separate question: distances are also unchanged by mirroring, so a model built only on distances cannot tell a molecule from its mirror image.

2An invariant layer: filters that depend on distance only (SchNet)

\[ h_i^{(l+1)}=\sum_j h_j^{(l)}\odot W^{(l)}(r_i-r_j),\qquad W^{(l)}=\text{MLP}\big(e_1(d_{ij}),\dots,e_K(d_{ij})\big),\quad e_k(d_{ij})=\exp\!\big(-\gamma\,(d_{ij}-\mu_k)^2\big) \]

In words. Each atom sums its neighbours' feature vectors, each multiplied entry by entry by a filter. The filter is computed by a small network from the distance between the two atoms, after the distance has been expanded into \(K\) bump functions centred at \(\mu_1,\dots,\mu_K\).

Why it has this form. This is message passing in which the edge weight is a learned, continuous function of distance, instead of the 0/1 of an adjacency matrix. Because the filter sees only \(d_{ij}\), rotating or shifting the molecule changes nothing: every layer's output is invariant. A network fed the raw number \(d_{ij}\) learns slowly; the radial basis expansion turns one number into \(K\) features, each active in its own range of distances, so the filter can respond differently to a bond at 1.1 Å and a contact at 3 Å.

With numbers. \(d_{ij}=1.2\), centres \(\mu=(1,2)\), \(\gamma=10\): \(e_1=\exp(-10\cdot0.04)=0.67\), \(e_2=\exp(-10\cdot0.64)=0.002\). The first bump is active, the second silent. At \(d_{ij}=1.9\) it is the reverse: \(e_1=0.0003\), \(e_2=0.90\).

Watch out. Invariant features cannot carry direction, so the model cannot output a vector directly; forces are obtained as the negative gradient of the predicted energy with respect to the positions.

3An equivariant layer: scalars and vectors together (PaiNN)

\[ \Delta v_i=\sum_j v_j\odot\phi_{vv}(s_j)\odot W_{vv}(\lVert r_{ij}\rVert)+\sum_j\phi_{vs}(s_j)\odot W_{vs}(\lVert r_{ij}\rVert)\,\frac{r_{ij}}{\lVert r_{ij}\rVert},\qquad v_i\leftarrow v_i+\Delta v_i \]

In words. Each atom keeps invariant scalars and also vectors. Its vectors are updated by two sums: the neighbours' vectors rescaled by invariant factors, and new vectors pointing along the direction to each neighbour, also scaled by invariant factors.

Why it has this form. Rule: an invariant number times a vector that rotates with the molecule is again a vector that rotates with it, and so is a sum of such vectors. The factors \(\phi(s_j)\) and \(W(\lVert r_{ij}\rVert)\) are invariant; \(v_j\) and the unit vector \(r_{ij}/\lVert r_{ij}\rVert\) rotate. So \(\Delta v_i\) rotates with the molecule: the layer is equivariant. The scalars are updated from invariant quantities only, including lengths and dot products of the vectors, so they stay invariant. Directional information, such as the angle between two bonds, is now available to the model.

With numbers. Atom \(i\) has neighbours in directions \((1,0)\) and \((0,1)\) with invariant weights \(2\) and \(1\): \(\Delta v_i=2\cdot(1,0)+1\cdot(0,1)=(2,1)\). Rotate the molecule by 90°: directions become \((0,1)\) and \((-1,0)\), same weights, \(\Delta v_i=(-1,2)\), which is \((2,1)\) rotated by 90°.

Watch out. A non-linearity applied to each coordinate of a vector would break equivariance; vectors may only be scaled by functions of invariants.

4Motif significance

\[ Z_i=\frac{N_i^{\text{real}}-\bar N_i^{\text{rand}}}{\operatorname{Std}(N_i^{\text{rand}})},\qquad SP_i=\frac{Z_i}{\sqrt{\sum_j Z_j^2}} \]

In words. Count a small pattern in the real graph. Count it in many random graphs with the same degrees. The z-score says how many standard deviations the real count lies above (or below) the random average. Dividing all z-scores by their overall length gives a profile that can be compared across graphs.

Why it has this form. A raw count means nothing: a dense graph has many triangles by chance. The randomised graphs (degree-preserving rewiring) say what the degrees alone would produce; what is left is structure beyond degree. Larger graphs give larger z-scores for the same tendency, so the vector of z-scores is normalised to length 1; the significance profile then describes the shape of a network's local structure.

With numbers. Zachary's karate club has 45 triangles; rewired versions have \(38\pm5\): \(Z=(45-38)/5=1.4\), mildly more than chance. With two motifs and z-scores \((3,-4)\): \(SP=(3,-4)/5=(0.6,-0.8)\).

Watch out. The result depends on the null model. Against random graphs that keep only the number of edges (not the degrees), almost every real network shows a huge triangle z-score, most of which is explained by hubs.

5Subgraph matching as an order between embeddings

\[ E(G_q,G_t)=\sum_{i=1}^{D}\max\big(0,\ z_q[i]-z_t[i]\big)^2,\qquad G_q\subseteq G_t\ \Longleftrightarrow\ z_q[i]\le z_t[i]\ \text{for all } i \]

In words. Embed graphs so that 'is a subgraph of' becomes 'is smaller in every coordinate'. The violation \(E\) is zero when the query's embedding is below the target's everywhere, and grows with every coordinate in which it sticks out.

Why it has this form. Being a subgraph is a partial order: it is transitive (a part of a part is a part) and antisymmetric. Coordinate-wise \(\le\) on vectors is a partial order with the same properties, so the geometry can represent the relation exactly, which a distance (symmetric) cannot. Training uses a max-margin loss: for true pairs minimise \(E\); for false pairs require \(E\ge\alpha\), i.e. \(\max(0,\alpha-E)\). At test time, the NP-hard matching problem is replaced by one comparison of vectors.

With numbers. \(z_t=(3,2)\). Query \(z_q=(1,2)\): \(\max(0,-2)^2+\max(0,0)^2=0\), predicted to be a subgraph. Query \(z_q=(4,1)\): \(\max(0,1)^2+\max(0,-1)^2=1\), predicted not to be. With margin \(\alpha=2\), that negative pair still costs \(\max(0,2-1)=1\).

Watch out. The embedding answers 'is there a match?' approximately and fast; it does not return which nodes match, and false positives are possible.

6Explanation as mutual information (GNNExplainer)

\[ \max_{G_S}\ I\big(Y,(G_S,X_S)\big)=H(Y)-H\big(Y\mid G=G_S,\ X=X_S\big)\quad\Longleftrightarrow\quad\min_{G_S}\ H\big(Y\mid G=G_S,X=X_S\big) \]

In words. Find the small subgraph (and subset of features) that tells the most about the model's prediction. Since the uncertainty of the prediction on the full graph is fixed, this is the same as finding the subgraph on which the model is most certain of that prediction.

Why it has this form. Mutual information is the reduction in uncertainty, \(I(X,Y)=H(Y)-H(Y\mid X)\). \(H(Y)\) does not depend on the subgraph, so maximising \(I\) means minimising the conditional entropy. Searching over subgraphs is combinatorial, so each edge gets a continuous mask value \(\sigma(m_{uv})\in(0,1)\) that multiplies its entry of the adjacency matrix, and the mask is optimised by gradient descent, with penalties that keep it small and close to 0 or 1. The edges whose mask stays near 1 are the explanation.

With numbers. Two classes. If the model predicts \((0.5,0.5)\) the entropy is \(\log2=0.69\). On a candidate subgraph it predicts \((0.9,0.1)\): entropy \(-0.9\log0.9-0.1\log0.1=0.33\). On another, \((0.99,0.01)\): \(0.06\). The second subgraph explains more.

Watch out. The explanation describes the model, not the world: it shows what the model used, which may be a shortcut or an artefact of the data.

7Checking an explanation: fidelity

\[ \text{Fid}^{+}=p\big(\hat y\mid G\big)-p\big(\hat y\mid G\setminus G_S\big),\qquad \text{Fid}^{-}=p\big(\hat y\mid G\big)-p\big(\hat y\mid G_S\big) \]

In words. Remove the explanation from the graph and see how far the probability of the original prediction falls (should be a lot). Keep only the explanation and see how far it falls (should be little).

Why it has this form. An explanation is a claim that these edges matter and the rest do not, and both halves can be tested by intervening on the input and re-running the model. A random set of edges of the same size is the baseline: an explanation is only informative if its removal hurts much more than removing random edges.

With numbers. In this site's Graph Explorer, on Cora with a GCN: removing the 5 highest-ranked edges of a node's computation graph lowers the predicted probability by about \(0.36\); removing 5 random edges of the same computation graph lowers it by about \(0.01\).

Watch out. Removing edges produces graphs unlike those seen in training; part of any drop may come from that shift and not from the importance of the removed edges.

Review: what to keep from this session

Carried forward. These three topics are good project directions; the Frontier section on each page lists where the 2025–26 literature has gone.

Quick self-check

What distinguishes an invariant from an equivariant geometric model?

An invariant output does not change under rotation (energy); an equivariant output rotates with the input (forces).

How does an order embedding encode subgraph containment?

If A is a subgraph of B then every coordinate of z_A is at most the corresponding coordinate of z_B; containment becomes a comparison of vectors.

What does GNNExplainer optimise?

A mask over edges (and features) that keeps the prediction's mutual information with the output high while the mask is small.

Worked example: a motif test and an explanation on one small graph

A small directed retweet network: accounts \(a,b,c,d,e\) with edges \(a\to b\), \(b\to c\), \(a\to c\), \(c\to d\), \(a\to d\), \(d\to e\). (Edge \(x\to y\): \(y\) retweets \(x\).)

  1. Count feed-forward loops (FFL: \(x\to y\), \(y\to z\), \(x\to z\)). Check every triple with a 2-step path: \((a,b,c)\): \(a\to b\to c\) and \(a\to c\): yes. \((a,c,d)\): \(a\to c\to d\) and \(a\to d\): yes. \((b,c,d)\): \(b\to c\to d\), but no \(b\to d\): no. \((c,d,e)\): no \(c\to e\): no. So \(N_{\text{FFL}}^{\text{real}}=2\).
  2. Node-level frequency with anchor = the FFL's source \(x\): only \(a\) plays this role in both loops, so it is 1. With anchor = the sink \(z\): \(c\) and \(d\), so 2.
  3. Significance. Suppose degree-preserving random graphs give on average \(0.5\) FFLs with standard deviation \(0.5\) (toy numbers). Then \(Z_{\text{FFL}}=(2-0.5)/0.5=3\): over-represented. In real data, a burst of FFLs anchored at one source often means that a group of accounts amplifies one source together.
  4. Explain a classifier. A GNN labels \(d\) as a "coordinated amplifier". GNNExplainer returns the edges \(\{c\to d, a\to d, a\to c\}\) (one FFL ending at \(d\)). Remove them: \(d\) only has \(d\to e\) left, and the prediction flips (necessary). Keep only them: the prediction stays (sufficient). This instance contributes 1 to the \(\text{fid}^+\) sum and 0 to the \(\text{fid}^-\) sum.
Check yourself: is the 3-node subgraph on \(\{a,b,c\}\) node-induced or only edge-induced when you take edges \(a\to b, b\to c\)? show answer

Only edge-induced: inducing on \(\{a,b,c\}\) must also include \(a\to c\), which gives the FFL.

Proof workshop: Why subgraph matching needs an asymmetric geometry

One problem in olympiad style. Give it fifteen minutes on paper before you open the first hint; the hints are graded, so open them one at a time.

Problem. Order embeddings predict "\(q\) is a subgraph of \(t\)" iff \(z_q\le z_t\) coordinate-wise, scored by \(E(q,t)=\lVert\max(0,z_q-z_t)\rVert^2\). Prove: (a) \(\le\) on \(\mathbb R^d\) is a partial order (reflexive, antisymmetric, transitive), and "is isomorphic to a subgraph of" is a preorder on graphs; (b) \(E(q,t)=0\iff z_q\le z_t\); (c) no symmetric score, \(s(q,t)=s(t,q)\) (for example \(z_q^\top z_t\)), can be thresholded to represent the subgraph relation on a family containing a graph and a proper subgraph of it.

Hint 1
(a) Check the three properties coordinate by coordinate; for graphs, compose embeddings. (b) A sum of squares is zero iff each term is.
Hint 2
(c) Take \(q\subsetneq t\): "\(q\subseteq t\)" is true, but "\(t\subseteq q\)" is false (\(t\) has more edges or nodes). What does symmetry force?
Solution
(a) Reflexive: \(z\le z\). Antisymmetric: \(z\le z'\) and \(z'\le z\) give equality coordinate-wise. Transitive: \(z_i\le z'_i\le z''_i\). For graphs, the identity is a subgraph embedding (reflexive), and composing injective edge-preserving maps gives one (transitive). (b) \(E=\sum_i\max(0,z_{q,i}-z_{t,i})^2=0\) iff every \(z_{q,i}\le z_{t,i}\). (c) A threshold rule says "\(q\subseteq t\)" iff \(s(q,t)\ge\theta\). Then \(s(q,t)\ge\theta\) (true) and \(s(t,q)<\theta\) (false), contradicting \(s(q,t)=s(t,q)\). \(\square\)

Why it matters. This is Lecture 10's DistMult lesson in another setting: a symmetric score cannot express an asymmetric relation. Choosing the geometry of an embedding space is choosing which logical properties (here a partial order) hold by construction, so the model cannot violate them. That is a neuro-symbolic design move, and it extends to box embeddings for rules and hyperbolic embeddings for hierarchies.

Sharper lens: how much geometry is enough

Not in the lecture notes. Three or four points where the chapter rounds something off: the exact statement, a second way to see it, and where it stops being true. Each is short and has a pointer for going further.

precise statement

Distances and angles are provably incomplete, and blind to mirror images

Section 2's cis/trans example is an instance of a theorem. Describe each atom by the multiset of its neighbour distances (SchNet), or of distances and angles (DimeNet). Pozdnyakov et al. (Physical Review Letters 2020) constructed pairs of different atomic environments that agree on all of these two- and three-body descriptors and still have different energies. No amount of training fixes it; the input does not contain the answer. Completeness needs higher body order (four-body terms such as dihedral angles, and beyond) or features that keep direction. The "geometric WL test" (Joshi et al., ICML 2023) arranges these models in a hierarchy that mirrors Lecture 6's: invariant layers correspond to the weak end, equivariant layers of increasing order to the stronger rungs.

A second blind spot is simpler. Distances and unsigned angles do not change under reflection, so a model built from them gives a molecule and its mirror image the same output. For energies that is correct. For anything involving a chiral partner, such as binding to a protein, it is wrong, as the two forms of thalidomide showed. Telling them apart needs a signed quantity: a dihedral angle with orientation or a triple product \((\mathbf a\times\mathbf b)\cdot\mathbf c\). That is the practical content of choosing \(SE(3)\) over \(E(3)\) in section 1.

second viewpoint

Vectors are the first rung: the ladder of irreducible representations

PaiNN carries scalars and vectors. In the language of representation theory these are the \(l=0\) and \(l=1\) irreducible representations of the rotation group; \(l=2\) objects have 5 components (a symmetric traceless matrix), \(l=3\) have 7, and each rotates by its own Wigner matrix. Why would a network need more than vectors?

A two-atom example where vectors see nothing
Place two identical neighbours at \(+\mathbf x\) and \(-\mathbf x\) from an atom. PaiNN's bond-direction term sums unit vectors weighted by functions of distance: \(w\,\hat{\mathbf x}+w\,(-\hat{\mathbf x})=\mathbf 0\). The same holds for a tetrahedral or octahedral shell. At first order the atom cannot tell "two neighbours on a line" from "no directional information", although the environments differ in shape. The \(l=2\) feature \(\sum_j w\,(\hat{\mathbf r}_j\hat{\mathbf r}_j^\top-\tfrac13I)\) does not cancel: it records the axis.

Tensor field networks, NequIP and MACE build messages from such higher-order features and combine them with the Clebsch–Gordan rule, the same rule that adds angular momenta in quantum mechanics (\(l_1\otimes l_2\) decomposes into \(|l_1-l_2|,\dots,l_1+l_2\)). The gain is angular resolution per layer, and with it data efficiency: NequIP reached the accuracy of invariant models with orders of magnitude fewer training structures.

where it breaks

Is built-in symmetry necessary? The counter-evidence since 2024

Section 1 says augmentation is expensive and gives no guarantee. Both remain true, and the trade has still shifted at large scale. AlphaFold 3 (2024) dropped AlphaFold 2's equivariant structure module for a standard transformer trained on randomly rotated and translated copies. A controlled study (Brehmer et al. 2024, "Does equivariance matter at scale?") found equivariant networks more data-efficient at every size, while a non-equivariant transformer with augmentation closed most of the gap given enough data and compute. Some recent universal interatomic potentials go the same way and predict forces directly instead of differentiating an energy, giving up exact energy conservation for speed.

A rule that fits the evidence: build the symmetry in when data is scarce or the guarantee is the point (long molecular-dynamics runs, where a small non-conservative force accumulates); consider learning it when data is abundant and inference cost dominates. Either way, test it: rotate the inputs and measure how much the outputs move.

where it breaks

Fidelity scores query the model where it was never trained

\(\text{fid}^+\) and \(\text{fid}^-\) delete edges and ask the model again. The edited graph (a molecule missing a bond, a user whose strongest ties are gone) can be unlike anything in the training data, so the change in the prediction mixes two things: the importance of what was removed and the model's arbitrary behaviour off its data distribution. An explanation can score well by producing strange subgraphs. Robust variants perturb randomly around the explanation, or retrain on the perturbed distribution, before measuring (Zheng et al., ICLR 2024).

The other common yardstick, agreement with a planted "ground-truth" motif as in BA-Shapes, has its own flaw: a model can be correct using different evidence than the planted motif, in which case a faithful explainer is marked wrong (Faber et al., KDD 2021). When an explanation is meant as a scientific claim, as in the antibiotic example of Lecture 1's Sharper lens, the test that counts is an intervention in the world: change the substructure and measure again.

Lab: hands-on and practical tips

Try it live. In the Graph Explorer: test whether triangles are over-represented against degree-preserving rewiring and explain a GCN's prediction by removing edges, with a fidelity check. Each lesson has predict-then-check questions.

notebook · L21 geometry, subgraphs, trust builds invariant and equivariant layers, computes motif Z-scores, trains order embeddings for subgraph matching, and runs GNNExplainer with fidelity scores.

The null model is the resultIn the motif figure above, the karate club's 45 triangles against a degree-preserving null gives a Z-score; the number changes with the null (ER vs configuration model vs SBM). Report which null you used; a motif is only significant relative to a stated model of chance.
Order embeddings make transitivity freeIf query ≤ target coordinate-wise encodes "is a subgraph of", then A ⊆ B ⊆ C holds by geometry without being trained. Check the violation rate on held-out pairs; it is the honest metric for neural subgraph matching.
Explanations are judged by fidelity, twice\(\text{fid}^+\): does removing the explanation change the prediction (necessity)? \(\text{fid}^-\): does the explanation alone keep it (sufficiency)? Report both plus stability across seeds; a masked subgraph is out of distribution for the model, so single numbers mislead.
Equivariance is a unit testRotate the input coordinates, run the geometric layer, and check that invariant outputs are unchanged and vector outputs rotated, to numerical precision. If the test fails, the "equivariant" model is not.

Practice

  1. Invariance check. Show that one SchNet layer \(h_i'=\sum_j h_j\odot W(\lVert r_i-r_j\rVert)\) is invariant under any rigid motion \(r\mapsto Qr+b\), and that the PaiNN term \(\sum_j a_{ij}\,r_{ij}/\lVert r_{ij}\rVert\) (with invariant scalars \(a_{ij}\)) is rotation-equivariant.
    Answer

    \((Qr_i+b)-(Qr_j+b)=Q(r_i-r_j)\) and \(\lVert Qu\rVert=\lVert u\rVert\), so every distance is unchanged, hence every filter value and every \(h_i'\) is unchanged. For the vector term: \(\sum_j a_{ij}\,Qr_{ij}/\lVert Qr_{ij}\rVert=Q\sum_j a_{ij}\,r_{ij}/\lVert r_{ij}\rVert\), because \(a_{ij}\) and the norms are invariant and \(Q\) is linear. Output rotates with input.

  2. Configuration model. Degree sequence \((2,2,1,1)\) for nodes \(a,b,c,d\). How many spokes and edges are there? List every simple graph with this degree sequence, and give one pairing of spokes that produces a non-simple graph.
    Answer

    Spokes = sum of degrees = 6, so 3 edges. If \(a\) and \(b\) were not adjacent, \(b\) would need two neighbours among \(c,d\), but then \(a\) also needs both, and \(c,d\) have degree 1. So \(a\)–\(b\) is an edge, and \(c,d\) attach one each to \(a\) and \(b\): the two simple graphs are the paths c–a–b–d and d–a–b–c. A non-simple pairing: join \(a\)'s two spokes to each other (a self-loop) and \(b\)'s two spokes to \(c\) and \(d\). Such outputs are discarded (or tolerated in large sparse graphs, where they are rare). Small graphs show why the simple-graph constraint matters.

  3. Order embedding geometry. \(z_1=(1,2)\), \(z_2=(2,3)\), \(z_3=(3,1)\). Which pairs are predicted as subgraph relations? What does the model predict about a graph whose embedding is \(\min(z_2,z_3)\)?
    Answer

    \(z_1\le z_2\) (1≤2, 2≤3): \(G_1\subseteq G_2\). \(z_1\) vs \(z_3\): 2>1, so no; \(z_3\) vs \(z_1\): 3>1, so no. \(z_2\) vs \(z_3\): incomparable. \(\min(z_2,z_3)=(2,1)\) is below both \(z_2\) and \(z_3\): the model predicts that this graph is a common subgraph of \(G_2\) and \(G_3\). This is the "closure under intersection" property in geometric form.

  4. Fidelity from a table. Four instances, targets all class 1. Full-graph predictions: 1, 1, 1, 0. Without the explanation: 0, 1, 0, 0. With only the explanation: 1, 1, 0, 0. Compute \(\text{fid}^+\), \(\text{fid}^-\) and \(c\) (with \(w_\pm=1\)).
    Answer

    \(\mathbb 1(\hat y=y)\) = 1,1,1,0. Without \(S\): 0,1,0,0, so differences 1,0,1,0 and \(\text{fid}^+=2/4=0.5\). Only \(S\): 1,1,0,0, so differences 0,0,1,0 and \(\text{fid}^-=1/4=0.25\). \(c=2\cdot0.5\cdot0.75/(0.75+0.5)=0.75/1.25=0.6\).

Readings & lookup guide

lecture notes CS224W course notes (Leni Aniva, Autumn 2024 — in your course folder)

The source of this page.

read first Ying, Bourgeois, You, Zitnik, Leskovec — GNNExplainer: Generating Explanations for Graph Neural Networks (NeurIPS 2019)

  • Read: §4 (the mutual-information objective, the continuous mask relaxation, the regularisers including mask entropy), and the synthetic benchmarks (BA-Shapes, tree-cycles) where ground-truth motifs are planted.

subgraphs Ying, Lou, You, Wen, Wang, Leskovec — Neural Subgraph Matching (NeuroMatch, 2020)

  • Read: the order-embedding objective, the anchored decomposition, and the training-data sampling. SPMiner (frequent motif mining in order embedding space) is a follow-up by the same group.

geometry Schütt et al. — SchNet (2017) · Schütt, Unke, Gastegger — PaiNN (ICML 2021) · Xu et al. — GeoDiff (ICLR 2022)

  • SchNet: continuous-filter convolution and radial basis expansion. PaiNN: the scalar/vector message and update blocks. GeoDiff: the equivariant denoising chain for conformations.

overview Duval et al. — A Hitchhiker's Guide to Geometric GNNs for 3D Atomic Systems (2023) · Bronstein, Bruna, Cohen, Veličković — Geometric Deep Learning (2021)

  • The guide sorts geometric GNNs into invariant, scalarisation-based equivariant (PaiNN, EGNN) and spherical-tensor (e3nn, MACE) families. The GDL "proto-book" puts symmetry at the centre of all deep learning.

evaluation & classics Amara et al. — GraphFramEx (LoG 2022) · Milo et al. — Network Motifs (Science 2002) and Superfamilies of Evolved and Designed Networks (Science 2004) · Vendrov et al. — Order-Embeddings (ICLR 2016)

arXiv:2206.09677 · Milo et al. have no arXiv versions · arXiv:1511.06361
  • GraphFramEx defines the phenomenon/model focus and the characterisation score. Milo et al. introduce motifs and significance profiles. Vendrov et al. invented order embeddings (for images and captions).

Self-check

The potential energy of a molecule, as a function of its atom positions, is …

  1. equivariant to rotations
  2. invariant to rotations and translations
  3. neither
  4. invariant to rotations only if the molecule is symmetric

Energy is a scalar that does not depend on the coordinate frame; forces are the equivariant quantity.

Why can SchNet not tell cis- from trans-1,2-dichloroethene reliably?

  1. It ignores atom types
  2. It uses too few layers
  3. It reduces geometry to distances, which lose directional information
  4. It is not permutation-invariant

Scalarising relative positions gives up angles and directions; equivariant models (PaiNN) keep vector features.

The configuration model and the switching method both preserve …

  1. the degree sequence
  2. the clustering coefficient
  3. the number of triangles
  4. the diameter

They randomise everything except the degrees, so motif significance is measured beyond what degrees explain.

In neural subgraph matching, the negative-pair loss is \(\max(0,\alpha-E)\) rather than \(-E\) because …

  1. \(E\) can be negative
  2. it makes positives and negatives symmetric
  3. it is faster to compute
  4. otherwise the model could push negatives infinitely far and stop learning anything useful

Once a negative pair violates the order by at least \(\alpha\), it contributes nothing.

An explanation with \(\text{fid}^-\approx0\) and \(\text{fid}^+\approx0\) is …

  1. necessary but not sufficient
  2. sufficient but not necessary
  3. both sufficient and necessary
  4. neither

Keeping it alone preserves the prediction (sufficient), but removing it does not change the prediction (not necessary): the model has another route.

Flashcards (click to flip)

Equivariant vs invariant
\(F\circ\rho_X=\rho_Y\circ F\) vs \(F\circ\rho_X=F\). Forces vs energy.
SE(3)
Rotations (det +1) and translations of 3D space: rigid motions without reflection.
PaiNN's rule
Invariant weights (from scalars and distances) × equivariant vectors (\(v_j\), \(r_{ij}/\lVert r_{ij}\rVert\)); no nonlinearity on vector components.
Z-score and SP
\(Z_i=(N^{\text{real}}_i-\bar N^{\text{rand}}_i)/\text{Std}\); \(SP=Z/\lVert Z\rVert\) compares networks of different sizes.
Order embedding
\(G_Q\subseteq G_T\iff z_Q\le z_T\) coordinate-wise; violation \(E=\sum\max(0,z_q-z_t)^2\).
Fidelity
fid+ (remove S) high = necessary; fid− (keep only S) low = sufficient; characterisation = harmonic mean of fid+ and 1−fid−.

History & the bigger picture

  • 1872 — Klein's Erlangen programme: a geometry is the study of the invariants of a transformation group. Geometric deep learning (Bronstein et al., 2021) applies the same idea to neural networks: choose the symmetry group first, then the architecture.
  • 1970s — the triad census (Holland and Leinhardt) in sociology: counting all 16 directed 3-node configurations in social networks and comparing them with random baselines. This is the direct ancestor of network motifs. 2002 — Milo et al. coin "network motifs" for gene, neural and food-web networks; 2004 significance profiles and "superfamilies" of networks.
  • 1971 — Cook lists subgraph isomorphism among the first NP-complete problems; 1976 — Ullmann's algorithm, the classic backtracking matcher. 2015 — Babai announces a quasi-polynomial algorithm for graph isomorphism, the biggest step on that open problem in decades. 2016 order embeddings; 2020 NeuroMatch.
  • 2017 — SchNet; 2020 — DimeNet; 2021 — EGNN, PaiNN, and AlphaFold 2 (whose structure module is SE(3)-equivariant) solves much of protein structure prediction; 2022 — GeoDiff; then diffusion for proteins (RFdiffusion, 2023).
  • 2016 — LIME (local surrogate models); 2017 — SHAP; 2019 — GNNExplainer, then PGExplainer, SubgraphX and GraphFramEx-style evaluation (2022).
Law, science and society · who is owed an explanation?

Explainability is not only a technical wish. The EU's GDPR (2018) started a long debate about a "right to explanation" for automated decisions, and the EU AI Act (2024) adds transparency duties for high-risk systems such as credit scoring. In philosophy of science, Hempel's deductive-nomological model said that to explain is to derive the event from laws; saliency maps and masks offer something weaker, a relevance claim about one model, not a law about the world. That is exactly the gap between "explaining the model" and "explaining the phenomenon" in section 10. For social platforms the stakes are political: when an account is suspended as a "bot" by a GNN, a subgraph explanation is evidence that can be checked, contested, or misused to evade detection.

Classic SNA bridge

In this lectureClassic SNA counterpartWhat carried over, what changed
Network motifs and significance profilesThe triad census (Holland & Leinhardt 1970s) and its comparison with random baselines; structural balance countsDirect ancestry: motifs are the triad census generalised to larger patterns and other domains. SNA's theory of which triads should be over-represented (balance, transitivity, status) gives motif Z-scores a sociological reading.
Neural subgraph matching (order embeddings)Cohesive subgroups: cliques, k-cores, k-plexes (Seidman 1983); clique-finding in sociograms (Luce & Perry 1949)SNA enumerated cohesive subgroups exactly on small networks; neural matching trades exactness for scale. The partial order "is contained in" is the lattice of subgroups SNA drew by hand.
GNNExplainer: a small subgraph that keeps the predictionCase-based network analysis; "the ego network that explains the outcome"Sociologists explained an outcome by the structure around the person; GNNExplainer finds the structure around the node that explains the model. Explaining the model and explaining the phenomenon are different things, as the page itself stresses.
Geometric (E(3)-equivariant) GNNsSpatial networks; distance-dependent tie formation (gravity models; Festinger's propinquity 1950)Geometric GNNs put coordinates into message passing; spatial SNA always had them (propinquity, geography of ties). Equivariance to rotation is the molecular case of "only distances matter".
Trust: robustness, fairness, explanationsEthics of network data (Borgatti & Molina 2003); the right to explanation (GDPR 2018)SNA debated consent and harm in network studies before GNNs existed. The trust cluster adds adversaries (node injection) and formal guarantees (certification), but the questions about who is affected are the old ones.
Bridge idea

Compute the directed triad census and 4-node motif Z-scores for retweet, reply and mention graphs around one event, weekly. A sudden rise of feed-forward loops or dense co-retweet cliques around one source is a coordination signal with a 1970s pedigree. Then ask a GNN bot detector for explanations on the same accounts and check whether the explanatory subgraphs are the over-represented motifs; agreement would ground a neural explanation in a classical structural theory.

Go deeper in the SNA course. The twelve-unit course on social network analysis in this repository gives the classic side of this lecture in full, with labs and real-data analyses: Unit 7 · Cascades, contagion & influence (small temporal patterns (motifs) as signatures of how something spread); Unit 11 · Polarization, algorithms & misinformation (subgraph patterns and trust: detecting coordination, and knowing when not to believe the detector).

Connecting to your research

Running project. Section L21 · motifs of notebooks/project/retweet_thread.py applies this lecture to one synthetic X world with coordinated rings, the same graph across the whole course.

Research extension. experiments/motif-signatures (hypotheses written before running): which motifs give rings away: mutual triangles for reciprocal rings, repeated co-retweets with one partner for co-amplification rings; a time-shuffled synchrony null flags organic cascades, not rings.

For SNA
  • Motifs in X/Twitter: compute the directed triad census (or 3–4 node motif Z-scores against a degree-preserving null) for retweet, reply and mention graphs separately. Their significance profiles are a compact way to compare platforms, topics or time periods, and sudden changes can signal coordinated campaigns (many feed-forward loops or dense "co-retweet" cliques around one source).
  • Neural subgraph matching at scale: exact counting of 5–8 node patterns on millions of accounts is infeasible; order embeddings let you query "where does this coordination pattern occur?" over all anchored neighbourhoods quickly, and SPMiner can discover patterns you did not know to look for.
  • Explainable bot detection: a GNN bot detector should come with explanations (which interactions and which profile features drove the label). Report fidelity and characterisation scores, and check stability across seeds, before trusting them. Distinguish "model" explanations (debugging the detector) from "phenomenon" explanations (claims about how bots behave).
For neuro-symbolic AI
  • Logic as geometry: order embeddings encode a symbolic relation (a partial order) as a geometric one; box and cone embeddings for knowledge-graph reasoning follow the same pattern. Transitivity comes for free from the geometry rather than from training.
  • Symmetry as prior knowledge: equivariance is a hard constraint derived from physics, the cleanest example of injecting symbolic knowledge into a neural architecture.
  • Explanations as rules: model-level explanations (typical subgraphs per class) can be turned into readable rules, a path from a trained GNN back to symbolic descriptions.

From the experiments: results and datasets

Generated by scripts/sync_guides.py from the experiments' committed results and the dataset catalogue; rerun it (make sync-guides) after an experiment changes.

motif-signatures

Question. Which small patterns give rings away, and does timing help? experiment folder ↗

Verdicts (hypotheses written before running): H1 refuted, H2 supported, H3 refuted, H4 refuted.

Each pattern alone as an unsupervised ring score (0.5 = chance). Best for co-amplification rings: co-retweet: max with one partner (0.810).

conformal-shift

Question. Do conformal guarantees hold when bots change tactics, or when a platform changes country? experiment folder ↗

Verdicts (hypotheses written before running): H1 supported, H2 supported, H3 supported, H4 supported; H8 supported, H9 supported, H10 refuted, H11 supported.

Synthetic tactic shifts, α = 0.05. Marginal coverage of all accounts stays 0.94–0.96 while bot coverage collapses under co-amplification and early detection; recalibrating on 20 labelled bots restores it.
Real shift (gl.datasets.twitch): calibrated on England, tested on other countries. Worst class under Mondrian: DE 0.87, ES 0.89, FR 0.79, PTBR 0.91, RU 0.91. 200 labelled local accounts restore it.

Datasets for this session

From the repo's catalogue (gl.datasets; the full list with sources and licences is in data/README.md). Load one with gl.datasets.graph(name), temporal(name) or node_data(name).

namedatasetnodesground truthgood for
polblogsUS political blogs 20041,490leaning: liberal / conservativepolarisation, homophily, the classic SBM / spectral benchmark
ego-facebookFacebook ego networks (combined)4,039—friendship structure: high clustering, triangles, motifs
email-eu-coreEU research institution e-mail1,005department (42)community detection and node classification with ground truth
higgs-retweetHiggs boson Twitter: retweet graph256,491—who retweeted whom around one event (weights = retweets)
higgs-activityHiggs boson Twitter: timestamped RT / mention / reply304,691edge kind RT / MT / REreal retweet cascades with timestamps: load as a World (higgs_world)

Frontier 2025–26: what changed since the slides

ICLR 2026Self-explaining GNNs can explain the wrong thing — Azzolin et al.: even models built to explain themselves can produce explanations disconnected from their decision process. An October 2026 preprint answers with compiled GNNs whose reasoning is known by construction, giving sound ground truth. Masked-subgraph explanations face an evaluation crisis.
NeurIPS 2025 oralGnnXemplar: natural-language rules for global GNN interpretability — Pick exemplar nodes by coverage maximisation; an LLM turns their neighbourhoods into rules per class, validated with a 60-person user study. If a GNN class equals a logic fragment (Lecture 6), explaining a trained model means finding its formula; sound Datalog-rule extraction follows.sources: arXiv:2509.18376
ICML 2026 spotlightFoundations of equivariant deep learning: unifying graph and sheaf neural networks — Sheaf neural networks mature into a unifying theory of equivariant deep learning; the trivial sheaf is GCN and diffusion to global sections explains over-smoothing and escapes it on heterophilous graphs. Geometric deep learning's "choose the symmetry group first" now covers the graph case too.sources: arXiv:2607.03798
2025–26Molecules: a Goodhart reckoning, weather the exception — Low test error of force fields no longer predicts simulation behaviour and datasets are highly redundant; GraphCast and GenCast beat operational weather forecasting because evaluation was dense, honest and physical. The symmetry ladder (invariant → equivariant → higher body order) of this page is intact; the benchmarks were not.
Atlas · trustBot detectors are attacked by node injection — BOCLOAK-style attacks on GNN bot detectors and the LLM-bot arms race pushed detection back to relational and coordination signals. Explanations for a bot label are evidence that can be checked, contested, or used to evade.
Open question to carryHow do you evaluate an explanation for a real social network where no ground-truth reason exists? Fidelity measures faithfulness to the model, not truth about the world; planted-motif benchmarks, compiled GNNs or counterfactual user studies are the candidates.
Frontiers · explanations moved to an evaluation crisis · sheaves explain over-smoothing · a GNN is systematic with respect to its logic

Words & phrases

TermSimple meaningPersianIn context
commutev.(maths) to give the same result in either orderجابه‌جاپذیر بودن"transformation and model commute"
rigidadj.not bending; a rigid motion moves an object without changing its shape or sizeصُلب"all rigid motions r ↦ Qr + b"
conformationn.the 3D shape that a molecule takes in spaceصورت‌بندی فضایی (کانفورمیشن)"output: a conformation C"
over-representedadj.appearing more often than expected by chanceبیش‌ازحد حاضر / فراوان‌تر از انتظار"triangles strongly over-represented"
post-hocadj.done after the fact; applied to a model after it has been trainedپسینی، پس از رویداد"GNNExplainer is post-hoc"
fidelityn.faithfulness; how truly something reflects the originalوفاداری، دقت در بازنمایی"Fidelity measures how much correctness you lose"
subgraph isomorphismn.the question whether one graph appears inside anotherیکریختی زیرگراف"subgraph isomorphism is NP-complete"
motifn.a small subgraph that appears more often than chance predictsنقش‌مایه (موتیف)"motif Z-scores against a random baseline"
partial ordern.a reflexive, antisymmetric, transitive relation, where some pairs may be incomparableترتیب جزئی"order embeddings encode a partial order"
explainabilityn.how well the reasons for a model's output can be shown and checkedتوضیح‌پذیری"GNNExplainer for explainability"

Go deeper

  • Previous: Bonus A — traditional features, label propagation and scaling. Its graphlet counts and WL colours are the classical side of this page's motifs.
  • Beyond scalarisation: spherical-tensor equivariant models (Tensor Field Networks, e3nn, MACE) carry higher-order features; Satorras et al. (2021) EGNN is the simplest equivariant layer (arXiv:2102.09844).
  • Subgraph GNNs: counting substructures is a way to go beyond the WL limit: GNNs given subgraph counts as features (GSN) or run on many node-deleted subgraphs (ESAN) separate graphs that plain message passing cannot.
  • Open question: how do you evaluate an explanation for a real social network where no ground-truth reason exists? Fidelity measures faithfulness to the model, not truth about the world. Can planted-motif benchmarks or counterfactual user studies close this gap?