CS224W

Lecture 18 · Tue 12/1 · slides PDF · lecture notes

Deep Generative Models for Graphs

Turn a graph into a sequence of "add node, add edges" decisions, learn it with an autoregressive model (GraphRNN), and steer generation toward goals like drug-likeness with a GNN policy trained by reinforcement learning (GCPN).

24
sectionstick "got it" as you go
21
figuresredrawn from the slides
interactive figuresplay with the ideas
5
self-check questionsplus flashcards
17′
reading time3,833 words, walkthrough aside

Before you start: review of the earlier sessions

The thread so far. Until now graphs were inputs; session 18 makes them outputs, reusing the RNN and RL ideas of session 17 and the GNN encoders of sessions 3–4.

What this session takes from earlier ones

  • Lecture 1: adjacency matrices: GraphRNN generates one column at a time
  • Lecture 3: GNN embeddings, which GCPN uses as the policy's state
  • Lecture 17: RLHF: the policy-gradient idea reappears in goal-directed generation

Those sessions in one minute each

Lecture 17 · Agents + Graphs — Building Intelligent and Collaborative Agents

Agents become more capable when their behaviour is optimised against the right signal: contrast successes and failures to learn how to use tools over knowledge graphs (AvaTaR), and reward responses by their long-term effect on a conversation with a human, not by single-turn preference (CollabLLM).

\[ R^{MT}(y_t\mid c_t)=\mathbb{E}_{(u_{t+1},y_{t+1},\dots)\sim\text{sim}}\Big[R\big(c_t,y_t,u_{t+1},y_{t+1},\dots\big)\Big]\approx\frac1S\sum_{s=1}^{S}R(\text{conv}_s) \]

Multiturn-aware reward: expected outcome of the whole conversation after response \(y_t\), estimated with \(S\) simulated continuations.

Lecture 1 · Introduction — Machine Learning with Graphs

A graph model must work for any number of nodes and give the same answer no matter how the nodes are numbered — everything else is a design choice about what the nodes and edges mean.

\[ G = (V, E, R, T), \qquad (v_i, r, v_j)\in E,\; r\in R,\; T(v_i)\ \text{= node type} \]

A homogeneous graph is the special case \(|R| = |T| = 1\). Permutation: relabelling nodes with a permutation matrix \(P\) turns \(A\) into \(PAP^\top\); a graph-level model \(f\) must satisfy \(f(PAP^\top, PX) = f(A, X)\).

Lecture 3 · Graph Neural Networks

A GNN layer = for every node, combine its own vector with an order-free aggregate of its neighbours' vectors, using weights shared across all nodes; stacking K layers lets information travel K hops.

\[ H^{(k+1)}=\sigma\big(D^{-1}A\,H^{(k)}W_k^\top + H^{(k)}B_k^\top\big) \]

Rows of \(H\) are node embeddings; \(D^{-1}A\) averages over neighbours; \(W_k\) transforms the neighbourhood message; \(B_k\) transforms the node itself.

Warm-up: answer these before you read on

Why is the reward-model loss "BPR in disguise"? from Lecture 17

Both maximise log σ(score of the preferred item − score of the other); only the inputs differ (responses versus items).

Name the three task levels and one concrete example of each. from Lecture 1

Node level (classify a protein's function), link level (recommend a product to a user), graph level (predict a molecule's toxicity).

Why can a GNN embed a node it has never seen? from Lecture 3

Because the parameters are the shared weight matrices, not per-node vectors; a new node just needs its features and its neighbours to build its computation graph.

What does STaRK measure that earlier benchmarks did not? from Lecture 17

Retrieval over semi-structured knowledge bases where a query mixes textual and relational constraints, so neither text search nor KG lookup alone suffices.

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

In short

Until now graphs were inputs. Now we generate them: realistic synthetic graphs (for insight, prediction, simulation and anomaly detection) and goal-directed graphs (molecules that are valid and score high on a property). The general recipe of generative modelling: learn \(p_{\text{model}}(G;\theta)\) close to the unknown \(p_{\text{data}}(G)\) by maximum likelihood, and be able to sample from it.

Autoregressive models use the chain rule: \(p(x)=\prod_t p(x_t\mid x_{<t})\). For graphs, \(x_t\) are actions. GraphRNN (2018) represents a graph + a node ordering as a sequence of sequences: a node-level RNN adds nodes; for each new node an edge-level RNN decides, one by one, whether it connects to each previous node. Train with teacher forcing and binary cross-entropy; sample at test time. A BFS node ordering makes it tractable: a new node only needs to look back at a small "frontier" of recent nodes.

GCPN (2018) generates molecules with a GNN policy (more expressive than an RNN state), checks chemical validity at each step, and uses reinforcement learning to maximise property scores (with step rewards for validity and a final reward for the property), combined with supervised imitation of real molecules.

The picture: GraphRNN as a sequence of sequences

GraphRNN: node-level and edge-level RNNs 1324 graph G, ordering π (BFS) node 2node 3node 4node 5? node-level RNN: "add a node" (state h_i) 1 110011 ↔1↔1↔2↔1↔2↔3 edge-level RNN: connect to node j? (Bernoulli) 2 train: teacher forcing + BCE on true 0/1 test: sample x ~ Bernoulli(y), feed back 3 EOS no edges →stop 4

How to read it (hover a step)

  1. Node-level RNN: each step adds a new node and produces a state that initialises the edge-level RNN; afterwards it is updated with the edge-level RNN's last hidden state.
  2. Edge-level RNN: for the new node \(i\), sequentially outputs probabilities "connect to node 1?", "connect to node 2?", … — the columns of the lower-triangular adjacency matrix. (Here: 2–1, 3–1, 4–2, 4–3 = a 4-cycle.)
  3. Training uses teacher forcing (feed the true previous decisions) with binary cross-entropy; testing samples each decision from its Bernoulli and feeds the sample back.
  4. If the edge-level RNN outputs EOS at its first step (new node connects to nothing), generation stops.

1 · Generative models: the setup

Why generate graphs? Insights (how graphs form), predictions (how they will evolve), simulations (new realistic instances), anomaly detection (is this graph normal?). Historically: (1) measure properties of real graphs, (2) traditional models with assumed formation processes (Erdős–Rényi, preferential attachment, Kronecker), (3) deep generative models that learn the formation process from data — this lecture. Encoders map graphs to embeddings; today we need decoders that output graph structure.

  • Task 1 — realistic generation: graphs similar to a given set (focus of the lecture).
  • Task 2 — goal-directed generation: optimise objectives under constraints (drug molecules).

Given samples \(x_i\sim p_{\text{data}}\): (1) density estimation: \(\theta^*=\arg\max_\theta\mathbb{E}_{x\sim p_{\text{data}}}\log p_{\text{model}}(x\mid\theta)\) (maximum likelihood); (2) sampling: typically draw noise \(z\sim N(0,1)\) and transform \(x=f(z;\theta)\) with a deep net. Autoregressive models do both with one model (VAEs and GANs use two): \(p_{\text{model}}(x;\theta)=\prod_{t=1}^n p_{\text{model}}(x_t\mid x_1,\dots,x_{t-1};\theta)\) — for graphs, \(x_t\) is the \(t\)-th action (add node, add edge).

Autoregressive models: the chain rule over actions. slide 16 ↗

2 · GraphRNN (You et al., ICML 2018)

A graph \(G\) with node ordering \(\pi\) maps uniquely to a sequence \(S^\pi=(S_1^\pi,\dots,S_n^\pi)\) with two levels: node-level (add nodes one at a time) and, inside each, edge-level (add edges between the new node and existing ones), e.g. \(S_4^\pi=(0,1,1)\): do not connect 4–1, connect 4–2, connect 4–3. Equivalently: the adjacency matrix, read column by column. Graph generation becomes sequence generation.

A graph + an ordering = a sequence of sequences. slide 22 ↗

RNN background

Two levels of RNN. slide 27 ↗

An RNN reads a sequence and updates a hidden state: \(s_t=\sigma(Wx_t+Us_{t-1})\), output \(y_t=Vs_t\) (GRU/LSTM cells are more expressive; the same principles apply to transformers). To generate: feed the previous output as the next input (\(x_{t+1}=y_t\)), start with an SOS token, stop with an EOS output.

Making it a probabilistic model

Deterministic feedback would always produce the same graph. Instead let \(y_t=p_{\text{model}}(x_{t+1}\mid x_{\le t})\) — a Bernoulli probability for one edge — and sample \(x_{t+1}\sim y_t\).

  • Training — teacher forcing: replace the inputs by the true sequence and compute the loss on each output: \(L=-[y^*\log y+(1-y^*)\log(1-y)]\); backpropagate through time across both RNNs.
  • Training: supervision at every step, backprop through time. slide 43 ↗
  • Test: sample each edge from the predicted distribution and feed GraphRNN's own predictions back.
  • Test: sample edges, feed back predictions. slide 45 ↗

3 · Tractability via BFS ordering, and evaluation

Problem: any node may connect to any prior node — the edge-level RNN must produce a full column for each new node (\(O(n^2)\) steps) and model very long-range dependencies; and there are \(n!\) orderings.

Solution: Breadth-First Search ordering. If node 4 doesn't connect to node 1 under BFS, then all of node 1's neighbours have already been visited — so node 5 and later can never connect to node 1. The edge-level RNN only needs to look back over a bounded frontier of \(M\) recent nodes ("2 steps instead of \(n-1\)"). Benefits: fewer orderings (from \(n!\) to the number of distinct BFS orderings) and far fewer edge steps — the adjacency matrix becomes a band.

BFS ordering: node 5 never connects to node 1; the adjacency becomes a band. slide 49 ↗
Prove the BFS claim: if node \(k\) (in BFS order) is not adjacent to node \(j\), and \(k\) is the first node after \(j\)'s last neighbour, why can no later node connect to \(j\)?

In BFS, every neighbour of \(j\) that comes after \(j\) is discovered while \(j\) is processed, so they receive consecutive indices in one block right after the nodes discovered by \(j\)'s predecessors. A later node \(k\) was discovered by some node processed after \(j\); if \(k\) were adjacent to \(j\), it would already have been discovered when \(j\) was processed — earlier. Contradiction. So once a new node skips \(j\), no later node connects to \(j\): each new node only looks back over the current BFS frontier, whose size \(M\) is estimated from data.

Evaluating generated graphs

Generated grids and community graphs vs baselines. slide 53 ↗

Compare a set of generated graphs to a set of real ones: (1) visual similarity — GraphRNN reproduces grids and community graphs that Kronecker, MMSB and Barabási–Albert baselines can't; (2) graph statistics similarity — compare distributions of degree, clustering coefficient and orbit (graphlet) counts, e.g. with Maximum Mean Discrepancy.

4 · GCPN: goal-directed molecule generation (NeurIPS 2018)

Goal: generate molecules that (1) optimise an objective (e.g. drug-likeness — a black box governed by physics we don't model), (2) obey rules (chemical valency), (3) are realistic (imitate a dataset). The black-box objective calls for reinforcement learning: an agent observes the environment, takes actions, receives rewards, and learns from the loop.

Graph Convolutional Policy Network = GNN (captures the current partial graph) + RL (steers toward objectives) + supervised training (imitate real molecules).

GraphRNN (RNN state) vs GCPN (GNN embeddings); overview. slide 63 ↗
  • Like GraphRNN: sequential, imitates data. Unlike it: the action is predicted from GNN node embeddings of the partial graph — more expressive than an RNN hidden state, but slower. New links are scored with a link head such as \(\text{Linear}(\text{Concat}(\mathbf h_u,\mathbf h_v))\).
  • Each step: (a) insert nodes (from a scaffold of atom types), (b, c) the GNN predicts which nodes to connect, (d) take the action and check chemical validity, (e, f) compute reward.
  • Reward = step reward (small positive for valid actions) + final reward (high desired property at the end).
  • Training: (1) supervised — imitate actions from real graphs with gradients; (2) RL — policy gradient (PPO) on rewards.

Results: property optimisation (penalised logP, QED) and constrained optimisation — edit a given molecule for a few steps to increase solubility in octanol (e.g. −8.32 → −0.71).

Constrained optimisation: improving a starting molecule. slide 68 ↗

The mathematics, step by step

Until now a model took a graph and returned a prediction. A generative model returns a graph. The mathematics is the probability of a graph, written so that it can be computed and sampled from one decision at a time. The cards go from the general principle (maximum likelihood, chain rule) to the specific factorisation of GraphRNN, the saving that breadth-first ordering buys, and the reward that steers generation in GCPN.

Symbols used in this session

symbolmeaningwhat kind of object
\(p_{\text{data}},\ p_{\text{model}}(\cdot;\theta)\)the unknown distribution the training graphs come from; the model's distribution with parameters \(\theta\)probability distributions over graphs
\(\pi\)a node ordering: which node is added first, second, …permutation of \(1..n\)
\(S^\pi\)the graph written as a sequence under ordering \(\pi\): \(S^\pi_i\) lists the edges from node \(i\) to the earlier nodessequence of binary vectors
\(S^\pi_{i,j}\)1 if node \(i\) is linked to the earlier node \(j\), else 0one binary decision
\(S^\pi_{<i}\)everything generated before node \(i\)the history
\(M\)how far back a new node may connect under breadth-first orderingwhole number
\(y_{i,j}\)the model's probability that \(S^\pi_{i,j}=1\)number in \((0,1)\)
\(R(G)\)reward of a generated graph in GCPN (validity, target property, realism)real number

1Maximum likelihood and the chain rule

\[ \theta^*=\arg\max_\theta\ \mathbb E_{x\sim p_{\text{data}}}\big[\log p_{\text{model}}(x;\theta)\big],\qquad p_{\text{model}}(x;\theta)=\prod_{t=1}^{T}p_{\text{model}}(x_t\mid x_1,\dots,x_{t-1};\theta) \]

In words. Choose the parameters under which the training graphs are most probable. To make that probability computable, write an object as a sequence of decisions and multiply the probability of each decision given the earlier ones.

Why it has this form. The first formula is the principle: a good model of the data assigns high probability to what was observed. The second is an identity (the chain rule of probability), true for any distribution, so nothing is lost by it. It turns one impossible problem, a distribution over all graphs, into many easy ones: a distribution over one yes/no decision at a time. Sampling follows the same order: draw \(x_1\), then \(x_2\) given \(x_1\), and so on.

With numbers. A sequence of three binary decisions \((1,0,1)\), for which the model gave probabilities of a 1 equal to \(0.8\), \(0.3\), \(0.6\) at the three steps: \(p=0.8\cdot(1-0.3)\cdot0.6=0.336\), \(\log p=-1.09\).

Watch out. The factorisation depends on the order of the decisions. For text the order is given; for a graph it must be chosen, and that choice is the difficulty of the next two cards.

2A graph as a sequence (GraphRNN)

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

In words. Fix an order of the nodes. Add the nodes one at a time; for each new node decide, one earlier node after another, whether to link to it. The probability of the graph in that order is the product of the probabilities of all these decisions.

Why it has this form. Under an ordering, the lower triangle of the adjacency matrix read row by row is a sequence of \(n(n-1)/2\) bits, and the chain rule applies. There are two levels: a node-level recurrent network carries the state of the graph built so far, and for each new node an edge-level recurrent network outputs the bits \(S_{i,1},S_{i,2},\dots\) one by one, each depending on the previous ones. The same graph corresponds to up to \(n!\) sequences, one per ordering; its true probability is the sum over all of them, which cannot be computed.

With numbers. Triangle with a tail in the order 1,2,3,4: node 2 → \((1)\); node 3 → \((1,1)\); node 4 → \((0,0,1)\). Six decisions in all, \(=4\cdot3/2\). With model probabilities \(0.9;\ 0.8,0.7;\ 0.2,0.1,0.6\) for a 1: \(p=0.9\cdot0.8\cdot0.7\cdot(1-0.2)\cdot(1-0.1)\cdot0.6=0.218\).

Watch out. Training uses teacher forcing: the network is fed the true earlier bits, not its own samples, and each output is penalised with binary cross-entropy against the true bit.

3Breadth-first ordering shortens the sequence

\[ 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) \]

In words. If the nodes are numbered in breadth-first order, a new node can only link to the last \(M\) nodes, so only those \(M\) decisions are made for it instead of one for every earlier node.

Why it has this form. In a breadth-first numbering, the neighbours of node \(j\) are all numbered before the neighbours of node \(j+1\). So if the new node \(i\) is not linked to some earlier node \(j\) that already has a later neighbour, it cannot be linked to anything before \(j\) either: links reach back only into a window (the current BFS frontier) of bounded size \(M\). Two savings follow: far fewer orderings to consider (only BFS ones instead of all \(n!\)) and \(O(Mn)\) decisions instead of \(O(n^2)\), with a history the recurrent network can actually remember.

With numbers. \(n=1000\) nodes. All pairs: \(1000\cdot999/2=499{,}500\) decisions. With \(M=10\): \(\sum_{i=2}^{1000}\min(i-1,10)=55+989\cdot10=9{,}945\), fifty times fewer. For \(n=5\), \(M=2\): \(1+2+2+2=7\) instead of \(10\).

Watch out. \(M\) must be at least the largest BFS frontier in the training graphs; a smaller \(M\) makes some training graphs impossible to generate.

4Steering generation with a reward (GCPN)

\[ \max_\theta\ \mathbb E_{G\sim\pi_\theta}\big[R(G)\big],\qquad R(G)=\sum_{\text{steps}}r_{\text{step}}+r_{\text{final}}(G) \]

In words. Treat building a graph as a game: each action adds an edge or a node, small rewards are given along the way for staying valid, and a final reward scores the finished graph on the property that is wanted. Train the policy to maximise the expected total.

Why it has this form. Maximum likelihood only imitates the training graphs. To get molecules that are better than the examples on some property (solubility, binding), the objective must mention that property, and a property computed by an external program has no gradient. Reinforcement learning needs only the value of the reward: it raises the probability of action sequences that led to high reward (policy gradient). In GCPN the policy is a GNN on the partial graph, and actions that would break chemical valency are rejected before they are scored.

With numbers. A generated molecule takes 20 steps, each valid: step rewards \(20\cdot0.05=1.0\). Final rewards: property score \(+2.5\), and \(+0.5\) from a discriminator for looking like a real molecule. \(R=4.0\). An episode ended early by an invalid action might total \(-1\).

Watch out. A reward on the property alone is exploited: the policy finds unrealistic graphs that score well. The validity checks and the realism term exist to prevent that.

Check yourself

Questions from the lecture, in order. Answer each one in your head (or on paper) before you open it. If one stumps you, follow the link to the walkthrough block it comes from.

Check yourself: why is "generate a graph" harder than "generate an image"? show answer

Hint: the output has variable size, and the same graph has many equivalent node orderings, so there is no fixed grid of pixels.

from Why generate graphs?

Check yourself: how many different sequences \(S^\pi\) describe the same 5-node graph, at most? show answer

One per ordering: up to \(5! = 120\); fewer if the graph has symmetries.

from GraphRNN idea: a graph as a sequence of sequences

Check yourself: at test time, what does the node RNN receive for the next node? show answer

The edge RNN's last hidden state after it processed the sampled edges of the current node.

from Putting it together: training and testing GraphRNN

Check yourself: in RL terms, what are the state, action and reward of GCPN? show answer

State: the partial molecule. Action: add an atom or a bond. Reward: validity at each step plus the property score at the end.

from Goal-directed generation and reinforcement learning

Lecture walkthrough reference · slide by slide · opens on demand

The whole lecture in order, grouped by topic. Every drawing on the slides is redrawn here as a clean figure (click the step buttons where a figure has them), the heading of each block links to the matching pages of the official PDF, and the Review section after the walkthrough ties this session to the earlier ones. Read this and you do not need the deck.

  1. Why generate graphs?
  2. Generation tasks and generative-model basics
  3. GraphRNN idea: a graph as a sequence of sequences
  4. RNN background and GraphRNN's two RNNs
  5. A probabilistic edge-level RNN and how to train it
  6. Putting it together: training and testing GraphRNN
  7. Tractability via BFS node ordering
  8. Evaluating generated graphs
  9. Goal-directed generation and reinforcement learning
  10. GCPN: architecture, reward and training
  11. Results and summary

Why generate graphs? slides 4-9 ↗

Slides 4–9: from learning on given graphs to generating new ones. slides 4-9 ↗

Until now the course has learned from graphs: we assumed the graph was given. Slide 4 shows three examples, a social network, an economic network and a communication network, and asks the new question: how are these graphs generated?

Slide 5 states the problem. We want to generate realistic graphs with a graph generative model: the model outputs a synthetic graph that should be similar (\(\approx\)) to a real graph. Applications: drug discovery and material design (a molecule is a graph), and social network modeling.

Slide 6 gives four reasons to study graph generation:

  • Insights: if a model can produce the graph, we understand how the graph forms.
  • Predictions: we can predict how the graph will evolve.
  • Simulations: we can run the same process to produce new graph instances.
  • Anomaly detection: we can decide whether a graph is normal or abnormal (a graph that the model finds very unlikely is suspicious).

Slide 7 places the lecture in history. Step 1: measure properties of real-world graphs (degree distribution, clustering, path lengths); a good generator must reproduce them. Step 2: traditional generative models (for example Erdős–Rényi, small-world, preferential attachment, Kronecker), each with its own assumption about how graphs form. Step 3: deep generative models, which learn the formation process from data. This lecture is step 3.

Slides 8–9 make the contrast with earlier lectures visual. The same GNN picture (graph convolutions, activation, regularization such as dropout, more graph convolutions) is drawn twice. On slide 8 the arrow goes left to right and the output is node embeddings: a deep graph encoder. On slide 9 the arrow is reversed and the output is the graph structure itself: a deep graph decoder. Today we build decoders.

Check yourself: why is "generate a graph" harder than "generate an image"? show answer

Hint: the output has variable size, and the same graph has many equivalent node orderings, so there is no fixed grid of pixels.

Generation tasks and generative-model basics slides 11-16 ↗

Slides 11–16: two generation tasks, the two goals of a generative model, and the chain rule that GraphRNN uses. slides 11-16 ↗

Slide 11 separates two tasks:

  • Task 1, realistic graph generation: produce graphs similar to a given set of graphs. This is the main focus of the lecture (GraphRNN).
  • Task 2, goal-directed graph generation: produce graphs that optimize given objectives or satisfy constraints, for example drug-molecule generation or optimization (GCPN, at the end).

Slide 12 formalizes Task 1. We are given graphs sampled from an unknown \(p_{\text{data}}(G)\). We want to (a) learn a distribution \(p_{\text{model}}(G)\) and (b) sample new graphs from it. The picture shows a box of training graphs labelled \(p_{\text{data}}(G)\), an arrow "Learn & Sample", and a box of similar-looking generated graphs labelled \(p_{\text{model}}(G)\).

Slide 13, the general setup. We have data points \(\{x_i\}\) (here, graphs) with \(x_i \sim p_{\text{data}}(x)\); the distribution itself is never known. The model \(p_{\text{model}}(x;\theta)\) has parameters \(\theta\). Two goals: (1) density estimation, make \(p_{\text{model}}(x;\theta)\) close to \(p_{\text{data}}(x)\); (2) sampling, be able to draw new \(x\) from \(p_{\text{model}}\). New graphs are exactly such samples.

Slide 14, goal (1): the key principle is maximum likelihood:

\[ \theta^* = \arg\max_\theta \ \mathbb{E}_{x\sim p_{\text{data}}} \log p_{\text{model}}(x\mid\theta) \]

In practice we maximize \(\sum_i \log p_{\text{model}}(x_i;\theta)\) over the observed points: find the model most likely to have generated the observed data.

Slide 15, goal (2): to sample from a complex distribution, the common approach is (1) sample simple noise \(z_i \sim N(0,1)\), then (2) transform it with a complex function, \(x_i = f(z_i;\theta)\). Then \(x_i\) follows a complex distribution. How do we design \(f\)? Use a deep neural network and train it on our data.

Slide 16 introduces the family used today: autoregressive models. Here the same \(p_{\text{model}}(x;\theta)\) does both density estimation and sampling (VAEs and GANs use two or more networks, each playing one role). The idea is the chain rule of probability:

\[ p_{\text{model}}(x;\theta) = \prod_{t=1}^{n} p_{\text{model}}(x_t \mid x_1,\dots,x_{t-1};\theta) \]

If \(x\) is a vector, \(x_t\) is its \(t\)-th dimension; if \(x\) is a sentence, \(x_t\) is the \(t\)-th word. For graphs, \(x_t\) is the \(t\)-th action: "add a node" or "add an edge". Computing the likelihood is easy (multiply the conditionals), and sampling is easy (draw \(x_1\), then \(x_2\) given \(x_1\), and so on).

GraphRNN idea: a graph as a sequence of sequences slides 18-23 ↗

Slides 18–23: with an ordering, a graph is a sequence of node additions, each of which is a sequence of edge decisions. slides 18-23 ↗

Slide 18 introduces GraphRNN (You, Ying, Ren, Hamilton, Leskovec, ICML 2018): generate a graph by sequentially adding nodes and edges. The figure shows a 5-node graph \(G\) (a square 1–2–4–3 with node 5 attached to 3 and 4) and its generation process \(S^\pi\): add node 1, add node 2 and connect it to 1, add node 3 and connect it to 1, add node 4 and connect it to 2 and 3, add node 5 and connect it to 3 and 4.

Slide 19: a graph \(G\) with a node ordering \(\pi\) maps uniquely to a sequence of node and edge additions \(S^\pi = (S^\pi_1,\dots,S^\pi_5)\), and back (the two arrows). Each \(S^\pi_i\) is the step that adds node \(i\) together with its edges to earlier nodes.

Slides 20–21: \(S^\pi\) has two levels (it is a sequence of sequences).

  • Node level: at each step a new node is added ("add node 1", …, "add node 5").
  • Edge level: each node-level step is itself a sequence; at each edge step we decide on one new edge. Example from slide 21: \(S^\pi_4 = (S^\pi_{4,1}, S^\pi_{4,2}, S^\pi_{4,3})\) = ("not connect 4,1", "connect 4,2", "connect 4,3") = \((0,1,1)\).

Slide 22 summarizes: a graph + a node ordering = a sequence of sequences. The node ordering is chosen at random (the lecture returns to this with BFS). The figure shows the graph next to its adjacency matrix. Reading the upper triangle column by column (left to right = node-level sequence) and, inside each column, top to bottom (edge-level sequence) gives exactly \(S^\pi\). Column 4 is highlighted: entries \(0,1,1\), i.e. node 4 connects to 2 and 3 but not to 1. Column 5 is \(0,0,1,1\).

Slide 23: we have turned graph generation into sequence generation. We must model two processes: (1) generate a state for a new node (node-level sequence), and (2) generate edges for the new node based on that state (edge-level sequence). Approach: use Recurrent Neural Networks (RNNs) for both. The same principles apply to Transformers.

Check yourself: how many different sequences \(S^\pi\) describe the same 5-node graph, at most? show answer

One per ordering: up to \(5! = 120\); fewer if the graph has symmetries.

RNN background and GraphRNN's two RNNs slides 24-30 ↗

Slides 24–30: the RNN cell, GraphRNN's two levels, and how an RNN generates a sequence. slides 24-30 ↗

Slide 24 recalls RNNs. They are built for sequential data. An RNN reads an input sequence \(x_1, x_2, \dots\) and updates hidden states \(s_0, s_1, s_2,\dots\); each hidden state summarizes all input seen so far. The update is done by an RNN cell, which also emits an output \(y_t\) at each step.

Slide 25 defines the cell. \(s_t\) is the state after step \(t\), \(x_t\) the input, \(y_t\) the output; \(W, U, V\) are trainable. In GraphRNN's edge-level model, \(s_t\), \(x_t\) and \(y_t\) are scalars (edge probabilities).

\[ \text{(1) update: } s_t = \sigma(W\cdot x_t + U\cdot s_{t-1}), \qquad \text{(2) output: } y_t = V\cdot s_t \]

More expressive cells exist: GRU, LSTM, and so on.

Slides 26–28: GraphRNN has a node-level RNN and an edge-level RNN. The node-level RNN produces the initial state for the edge-level RNN; the edge-level RNN then predicts, one by one, whether the new node connects to each previous node. The figure on slide 27 shows node-level states \(h_1,\dots,h_6\) (green arrows, "node-level update") starting from SOS, with the growing graph drawn above them. Under each \(h_i\) hangs a column: \(S^\pi_2=(1)\), \(S^\pi_3=(1,0)\), \(S^\pi_4=(0,1,1)\), \(S^\pi_5=(0,0,1,1)\) (blue arrows, "sample + edge-level update"). Slide 28 adds that after the edge-level RNN finishes its column, its result is used to update the node-level RNN state for the next node.

Slide 29 answers three questions about generating sequences with an RNN:

  • How to generate? Feed the previous output as the next input: \(x_{t+1} = y_t\).
  • How to start? Use a start-of-sequence token (SOS) as the first input, usually a vector of all zeros or all ones.
  • When to stop? Add an end-of-sequence (EOS) output. If EOS = 0 the RNN continues; if EOS = 1 it stops.

Slide 30 draws this: \(x_1 = \text{SOS}\), \(x_2 = y_1\), …, \(x_T = y_{T-1}\), and the last cell outputs EOS = 1. The slide ends with a problem: this model is deterministic. With the same start it always produces the same sequence, so it can only generate one graph. We need randomness.

A probabilistic edge-level RNN and how to train it slides 31-34 ↗

Slides 31–34: each edge-RNN step outputs a probability, the sample is fed back; at training time the true sequence replaces the samples. slides 31-34 ↗

Slide 31 makes the model stochastic (consider the edge-level RNN for now). Our goal is to model \(\prod_{t=1}^n p_{\text{model}}(x_t\mid x_1,\dots,x_{t-1};\theta)\). Let the output be a probability:

\[ y_t = p_{\text{model}}(x_{t+1}\mid x_1,\dots,x_t;\theta), \qquad x_{t+1}\sim y_t . \]

So each RNN step outputs the probability of one edge; we sample from it and feed the sample (not the probability) into the next step.

Slide 32 shows this for an already-trained edge-level RNN. \(y_t\) is a scalar that defines a Bernoulli distribution: value 1 with probability \(p\), value 0 with probability \(1-p\). Start with \(s_0 = \text{SOS}\), \(x_1 = \text{SOS}\). The first cell outputs \(y_1 = 0.9\); we sample \(x_2 \sim 0.9\) and get \(x_2 = 1\). The next cell outputs \(y_2 = 0.4\); we sample \(x_3\sim 0.4\) and get \(x_3 = 0\). The third outputs \(y_3 = 0.7\), and so on. The question at the bottom: how do we use training data \(x_1,\dots,x_n\)?

Slide 33, training. We observe a true edge sequence \(y^*\), for example \([0,0,1,\dots]\). The principle is teacher forcing: replace the inputs and the targets by the real sequence. In the figure, the model outputs \(y_1 = 0.9, y_2 = 0.4, y_3 = 0.7\), the targets are \(y_1^* = 0, y_2^* = 0, y_3^* = 1\), and the inputs are the true values \(x_2 = 0, x_3 = 0\), not the model's own samples. A loss is computed at every step.

Slide 34: the loss is binary cross-entropy:

\[ L = -\big[\,y_1^*\log(y_1) + (1-y_1^*)\log(1-y_1)\,\big] \]

If \(y_1^* = 1\), we minimize \(-\log y_1\), which pushes \(y_1\) up. If \(y_1^* = 0\), we minimize \(-\log(1-y_1)\), which pushes \(y_1\) down. In the example \(y_1^* = 0\) and \(y_1 = 0.9\), so the loss is large and training lowers \(y_1\). Since \(y_1\) is computed by the RNN, backpropagation adjusts the RNN parameters.

Why teacher forcing? Early in training, the model's own samples are mostly wrong; feeding them back would train later steps on nonsense prefixes. With true prefixes, every step gets a clean signal and the summed loss is exactly \(-\log p_{\text{model}}\) of the true sequence, i.e. maximum likelihood.

Putting it together: training and testing GraphRNN slides 35-46 ↗

Slides 35–43, training on the three-node graph, with the slide's numbers. Step through the node and edge RNN calls. slides 35-43 ↗
Slides 44–45, test time with the slide's numbers: samples replace teacher forcing. slides 44-45 ↗

Slide 35 gives the full plan:

  1. Add a new node: run the node RNN for one step; its output initializes the edge RNN.
  2. Add edges for the new node: run the edge RNN to predict whether the new node connects to each previous node.
  3. Add another node: use the last hidden state of the edge RNN to run the node RNN one more step.
  4. Stop: if the edge RNN outputs EOS at its first step, the new node connects to nothing, and graph generation stops.

Slides 36–43 walk through training on an observed graph with edges 1–2 and 1–3 (adjacency matrix rows \(0\,1\,1\); \(1\,0\,0\); \(1\,0\,0\)):

  • Slide 36: node 1 is in the graph; to add node 2, start the node RNN with SOS.
  • Slide 37: the edge RNN (started with SOS) predicts "will node 2 connect to node 1?" and outputs 0.5.
  • Slide 38: update the node RNN with the edge RNN's hidden state.
  • Slide 39: for node 3, the edge RNN outputs 0.6 for "connect to node 1?". By teacher forcing, the next input is the true answer, 1 (node 3 does connect to node 1). It then outputs 0.4 for "connect to node 2?".
  • Slide 40: update the node RNN again.
  • Slide 41: for node 4 the edge RNN's first output is EOS (here 0.4); since node 4 connects to nothing in the data, generation stops.
  • Slide 42: every prediction gets supervision from the ground truth (targets 1 for 2–1; 1 and 0 for node 3; EOS for node 4).
  • Slide 43: backprop through time: the red arrows show gradients accumulated across all time steps of both RNNs.

Slides 44–45 show test time: (1) sample each edge from its predicted distribution; (2) replace every input by GraphRNN's own previous prediction. In the example the edge RNN outputs 0.9 for 2–1 and samples 1; for node 3 it outputs 0.2 and 0.2 and samples 0 and 0; for the next node the EOS output 0.5 is sampled as EOS, so generation stops. Slide 45 shows the generated graph: edge 1–2, with node 3 isolated. This differs from the observed graph, which is fine: we sample from a distribution, we do not copy.

Slide 46, quick summary: generate a graph by generating a two-level sequence, and use RNNs to generate the sequences (node-level RNN across columns, edge-level RNN down each column of the adjacency matrix). Next: make GraphRNN tractable and evaluate it properly.

Check yourself: at test time, what does the node RNN receive for the next node? show answer

The edge RNN's last hidden state after it processed the sampled edges of the current node.

Tractability via BFS node ordering slides 48-51 ↗

Slides 48–51: a BFS ordering bounds how far back a new node can connect, turning the adjacency into a band and the edge RNN into a short sequence; the interactive figure below measures the bandwidth. slides 48-51 ↗

Slide 48 states the problem. With a random ordering, any node can connect to any prior node. So there are too many edge-generation steps: we must generate the full adjacency matrix, and the edge dependencies are complex and very long. The figure shows a random ordering of the 5-node graph, where node 5 may connect to any or all previous nodes, with the "recipe": add node 1, add node 2, add node 3, connect 3 with 2 and 1, add node 4, … How do we limit this complexity?

Slide 49: use a Breadth-First Search (BFS) node ordering. The recipe becomes: add node 1; add node 2; connect 2 with 1; add node 3; connect 3 with 1; add node 4; connect 4 with 3 and 2. The argument:

  • Node 4 does not connect to node 1.
  • In BFS, all of node 1's neighbors are visited right after node 1 is processed, so they have all appeared already.
  • Therefore node 5 and every later node will never connect to node 1.
  • So we only need memory of 2 "steps" (the recent frontier), not \(n-1\) steps.

Slide 50 lists the benefits: (1) fewer possible node orderings, from \(O(n!)\) to the number of distinct BFS orderings; (2) fewer edge-generation steps, because each new node looks at fewer previous nodes.

Slide 51 shows the effect on the adjacency matrix for \(N = 10\). Without BFS, the blue (possible-edge) region is the whole upper triangle: column \(i\) needs \(i-1\) entries, up to \(M = 9\) ("connectivity with all previous nodes"). With BFS, the blue region is a band along the diagonal of width \(M = 3\) ("connectivity only with nodes in the BFS frontier"). The edge RNN only needs to output \(M\) entries per column, so the work drops from \(O(n^2)\) to \(O(nM)\).

Evaluating generated graphs slides 52-54 ↗

Slides 52–54: evaluating generated graphs visually and with graph statistics. slides 52-54 ↗

Slide 52 poses the task: compare two sets of graphs, a training set and a generated set, and ask how similar they are. We need similarity metrics for graphs. Two solutions: (1) visual similarity and (2) graph statistics similarity.

Slide 53, visual similarity on grid graphs. Top row: three training grids. Middle row (red box): three GraphRNN samples, which are clearly grid-like (one is slightly distorted). Bottom row: baselines Kronecker, MMSB (mixed-membership stochastic block model) and B-A (Barabási–Albert). They look like random hairballs and miss the grid structure completely.

Slide 54, the same comparison on community graphs (graphs made of two dense clusters). GraphRNN samples show two clear communities joined by a few edges, like the training graphs. Among the baselines, MMSB (a block model, so built for communities) also shows two clusters, but Kronecker and B-A produce a single blob with no community split.

Intuition: traditional models hard-code one formation mechanism (preferential attachment, block structure, recursive self-similarity), so they can only produce graphs of that kind. GraphRNN learns the mechanism from examples, so it adapts to grids, communities or anything else in the training set.

Graph statistics similarity (option 2) is only named on slide 52. In the GraphRNN paper, one compares distributions of degree, clustering coefficient and orbit counts between the two sets with Maximum Mean Discrepancy (MMD). Visual inspection alone is not a metric: it does not scale and is subjective.

Goal-directed generation and reinforcement learning slides 56-60 ↗

Slides 56–60: goal-directed generation and why reinforcement learning fits a black-box objective. slides 56-60 ↗

Slide 56 moves to drug discovery (You, Liu, Ying, Pande, Leskovec, NeurIPS 2018). Question: can we learn a model that generates valid and realistic molecules with optimized property scores? Picture: Model → output molecule → that optimizes → Property, for example drug_likeness = 0.95.

Slide 57: we want graphs that

  • optimize a given objective (high scores), e.g. drug-likeness;
  • obey underlying rules (valid), e.g. chemical validity rules (an atom can only form a limited number of bonds);
  • are learned from examples (realistic), i.e. imitate a molecule dataset. GraphRNN already covered this part.

Slide 58 marks the hard part: the objective is a black box. Properties like drug-likeness are governed by physical laws that we assume are unknown to us. We can evaluate a molecule, but we cannot differentiate the score with respect to the model.

Slide 59: the tool for this is reinforcement learning (RL). An ML agent observes the environment, takes an action, and receives a positive or negative reward; it learns from this loop. The key idea: the agent learns directly from the environment, which is a black box to it. The diagram: ML Agent → Action → Environment → Observation, Reward → ML Agent.

Slide 60: the solution is the Graph Convolutional Policy Network (GCPN), which combines graph representation and RL. Its key components:

  • a graph neural network captures the structure of the partial graph;
  • reinforcement learning guides the generation toward the desired objectives;
  • supervised training imitates examples in the given dataset.
Check yourself: in RL terms, what are the state, action and reward of GCPN? show answer

State: the partial molecule. Action: add an atom or a bond. Reward: validity at each step plus the property score at the end.

GCPN: architecture, reward and training slides 61-66 ↗

Slides 61–66: GCPN replaces the RNN state by GNN embeddings and adds a reward so generation can be steered. slides 61-66 ↗

Slide 61 compares GCPN with GraphRNN. Common: both generate graphs sequentially and imitate a given dataset. Differences: (1) GCPN uses a GNN to predict the generation action. Pro: a GNN is more expressive than an RNN. Con: a GNN takes longer to compute. (2) GCPN also uses RL to direct generation toward our goals, which enables goal-directed generation.

Slide 62 shows the difference in pictures. GraphRNN predicts actions from RNN hidden states: from the partial graph 1–2, 1–3, the node RNN and three edge-RNN steps output 0, 1, 1, so node 4 connects to 2 and 3. The hidden state "captures the generated graph so far", but only implicitly. GCPN predicts actions from GNN node embeddings: run a GNN on the current graph (with the new node 4), get an embedding for every node, and score each possible link with the link prediction head from earlier lectures:

\[ \text{Head}_{\text{edge}}\big(\mathbf h_u^{(L)},\mathbf h_v^{(L)}\big) = \text{Linear}\big(\text{Concat}(\mathbf h_u^{(L)},\mathbf h_v^{(L)})\big). \]

Slide 63, overview of one GCPN step. (a) State \(G_t\) (a partial molecule of carbon atoms) plus a scaffold \(C\) of candidate atoms (here C, N, O) that can be inserted. (b) The GCPN policy \(\pi_\theta(a_t\mid G_t\cup C)\) runs message passing and computes node embeddings. (c) Sample an action \(a_t\sim\pi_\theta\): two node IDs to connect (one may be a new scaffold atom), an edge (bond) type, and a stop flag. (d) The environment updates the graph, \(p(G_{t+1}\mid G_t,a_t)\), and checks chemical validity. (e) New state \(G_{t+1}\). (f) Reward \(r_t\), shown as a step reward 0.1 and a final reward 0.

Slide 64, the reward:

  • Step reward: learn to take valid actions. At each step, give a small positive reward for a valid action.
  • Final reward: optimize the desired property. At the end, give a positive reward for a high property score.
\[ \text{Reward} = \text{Final reward} + \text{Step reward}. \]

Slide 65, training has two parts: (1) supervised training, which trains the policy to imitate actions taken in real observed graphs, using gradients (the same idea as GraphRNN); (2) RL training, which trains the policy to maximize rewards with a standard policy gradient algorithm (see any RL course, e.g. Stanford CS234).

Slide 66 draws both loops from a current graph \(G_t\). Top (supervised): GCPN runs one step to get a generated \(G_{t+1}\); the query dataset gives the real next graph \(G^*_{t+1}\); a cross-entropy loss (0.6 in the figure) gives the gradient. Bottom (RL): GCPN runs until stop to get a complete molecule \(G^*_T\); the environment returns step reward 0.1 and final reward 1; the policy gradient flows back into GCPN.

Results and summary slides 67-69 ↗

Slides 67–69: GCPN results and the lecture summary. slides 67-69 ↗

Slide 67, property optimization: generate molecules with a high score for a chosen property. (a) Penalized logP optimization: four generated molecules with scores 7.98, 7.48, 7.12 and 23.88*. The first three are long carbon chains with branches; the starred one (drawn in purple) is an unrealistic, heavily branched structure that exploits the score. (b) QED (drug-likeness) optimization: four ring-containing, drug-like molecules with scores 0.948, 0.945, 0.944 and 0.941.

Slide 68, constrained optimization: start from a given molecule and edit it for a few steps to raise the property score, here penalized logP, i.e. increase the solubility in octanol. One starting structure scores −8.32 and the finished one −0.71 (long alkyl chains were added). Another goes from −5.55 to −1.78.

Slide 69, summary of graph generation:

  • Complex graphs can be generated successfully by sequential generation with deep learning.
  • Each step makes a decision based on a hidden state, which can be implicit (a vector representation, decoded with an RNN, as in GraphRNN) or explicit (the intermediate generated graph, decoded with a GCN, as in GCPN).
  • Possible tasks: imitating a set of given graphs, and optimizing graphs toward given goals.

The 23.88* molecule is a useful warning: when a black-box reward is the only goal, RL finds strange solutions that score well but are not realistic. That is why GCPN keeps the supervised imitation term and the validity rewards.

Not shown (no new content): slides 1,2,3,10,17,47,55 — title page, announcements (milestone feedback, Colab and report deadlines, Medium usernames), section-divider title pages.

Review: what to keep from this session

Carried forward. Lecture 19 reviews the whole course and shows generation as the third output type in the framework figure; Lecture 21 covers geometric generation of 3D molecules.

Quick self-check

Why does GraphRNN need a node ordering?

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

What does teacher forcing change between training and test time?

During training the true previous edge is fed in; at test time the sampled edge is fed in, so the model must cope with its own samples.

Why does GCPN use RL rather than likelihood?

The objective (a chemical property) is a black box without a gradient, so the policy is trained with rewards.

Key idea

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.

Worked example: the likelihood of one generated graph

Generate the 4-cycle 1–2, 1–3, 2–4, 3–4 in BFS order (1, 2, 3, 4). Suppose the model outputs:

  1. Node 2: \(p(2\text{–}1)=0.9\) → sampled 1. Probability factor 0.9.
  2. Node 3: \(p(3\text{–}1)=0.6\) → 1; \(p(3\text{–}2)=0.3\) → 0. Factors 0.6 × 0.7.
  3. Node 4: \(p(4\text{–}1)=0.2\) → 0; \(p(4\text{–}2)=0.7\) → 1; \(p(4\text{–}3)=0.8\) → 1. Factors 0.8 × 0.7 × 0.8.
  4. Node 5: EOS (connects to nothing) with \(p=0.6\). Factor 0.6.
  5. \(p(S^\pi)=0.9\cdot0.42\cdot0.448\cdot0.6\approx0.10\). Training maximises \(\log p\) over the dataset's sequences; BCE per decision is exactly \(-\log\) of each factor.

Strictly speaking: \(p(G)=\sum_\pi p(G,\pi)\) sums over orderings — intractable, so GraphRNN trains on sampled BFS orderings (a lower bound / approximation). Later models (GRAN, diffusion models such as DiGress) generate blocks or whole graphs at once to reduce ordering issues.

Proof workshop: BFS order bounds how far back a new node can connect

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 the nodes of a connected graph by a BFS from a root, with levels \(L_0,L_1,\dots\) (distance from the root). Prove that every edge \(\{u,v\}\) joins nodes in the same level or in adjacent levels, and that if \(v\in L_\ell\) is added at position \(t\), every earlier neighbour of \(v\) has position at least \(t-(|L_{\ell-1}|+|L_\ell|)+1\). Conclude that GraphRNN needs to predict only \(M=\max_\ell(|L_{\ell-1}|+|L_\ell|)-1\) edge bits per step.

Hint 1
If \(u\in L_i\) and \(v\in L_j\) are adjacent, \(|d(r,u)-d(r,v)|\le1\).
Hint 2
BFS lists levels in order. An earlier neighbour of \(v\in L_\ell\) is in \(L_{\ell-1}\) or \(L_\ell\); everything between it and \(v\) in the order is in those two levels too.
Solution
Distances to the root differ by at most 1 across an edge (triangle inequality), so an edge joins levels \(i,j\) with \(|i-j|\le1\). BFS visits \(L_0\), then \(L_1\), and so on, so positions within \(L_{\ell-1}\cup L_\ell\) form a contiguous block of \(|L_{\ell-1}|+|L_\ell|\) positions ending no earlier than \(t\). An earlier neighbour \(u\) of \(v\) lies in \(L_{\ell-1}\cup L_\ell\), so \(u\) and \(v\) are both in that block and \(t-\mathrm{pos}(u)\le|L_{\ell-1}|+|L_\ell|-1\). The adjacency vector of \(v\) to earlier nodes therefore has its nonzero entries within the last \(M\) positions. \(\square\)

Why it matters. This turns an \(O(n)\)-wide prediction per step into an \(O(M)\)-wide one, and \(M\) is small for graphs with thin BFS levels (grids, molecules) but large for social graphs, whose BFS levels explode after two hops (the small-world property). It is a quantitative reason why generating realistic social networks is harder than generating molecules.

Sharper lens: orderings, noise and what "good" means

Not on the slides. Three or four points where the lecture 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

GraphRNN maximises a lower bound, over orderings it chose

A graph has no order, so its probability is a sum over all orderings that produce it: \(p(G)=\sum_\pi p(G,\pi)\), up to \(n!\) terms. GraphRNN trains on \(p(G,\pi)\) for sampled BFS orderings, which is a lower bound on \(\log p(G)\), and its probability mass is spread over the different sequences that describe one graph. Two consequences: the model cannot report the likelihood of a given graph, so it cannot be used directly for the anomaly detection that section 1 lists as a motivation, and results depend on the ordering family (BFS, DFS, canonical, uniform), which later work treats as a latent variable to be inferred (Chen et al., ICML 2021).

second viewpoint

Generate every edge at once: an equivariant denoiser has no ordering problem

The alternative that now dominates removes \(\pi\) altogether. Start from a random graph whose distribution does not depend on node labels, and repeatedly apply a denoising network that is permutation equivariant (a GNN or graph transformer). Then every intermediate distribution, and the final one, assigns equal probability to all relabellings of a graph. The proof is the induction that Lecture 21 writes out for rotations, with permutations in place of rotations. This is graph diffusion (EDP-GNN, Niu et al. 2020; DiGress, Vignac et al., ICLR 2023).

Two design choices carry over from the rest of the course. The noise must respect that graphs are discrete and sparse: DiGress uses the marginal transition in the figure, so the fully noised graph is a random graph with the right density, not a coin-flip graph. And the denoiser inherits Lecture 6's ceiling: a message-passing network cannot see the cycles it is supposed to complete, so DiGress feeds it cycle counts and spectral features at every step, the feature augmentation of Lecture 7. Discrete flow matching (in the Frontier section) keeps both ideas and makes sampling cheaper.

where it breaks

The goal-directed benchmarks were gamed; what counts as success now

GCPN's headline numbers are on penalised logP and QED. Penalised logP has no upper bound and grows with molecule size, so later methods "won" by emitting long carbon chains; QED saturates at 0.948, which many methods reach. A high score showed that the optimiser works, not that the molecule is useful. Three changes followed.

  • Sample, do not maximise. GFlowNets (Bengio et al., NeurIPS 2021) train a sequential constructor, as in GCPN, to produce object \(x\) with probability proportional to its reward. When the reward is an imperfect proxy for a wet-lab result, many diverse good candidates are worth more than one optimum of the proxy.
  • Harder oracles. Docking scores, synthesisability constraints and a budget on oracle calls.
  • Experimental evidence. GNoME (Nature 2023) used GNN energy models to propose 2.2 million crystal structures, about 381,000 of them on the predicted stability hull, and drew a critique that predicted stability is not the same as a new, useful material; MatterGen (Nature 2025) is a diffusion model conditioned on target properties; RFdiffusion (Nature 2023) generates protein backbones, in the line of work recognised by the 2024 Nobel Prize in Chemistry for computational protein design.

Lab: hands-on and practical tips

Try it live. In the Graph Explorer: set a real network against four random-graph models, statistic by statistic, the way generated graphs are evaluated. Each lesson has predict-then-check questions.

notebook · L18 generative models computes the likelihood of one generated graph, compares node orderings, trains a GraphRNN-lite and a GCPN-style RL generator.

Start from the classical generatorsER, BA and SBM (figure above) are each a one-statistic model: Poisson degrees, a power-law tail, planted communities. Before a deep generator, check which classical model already reproduces your statistic; if SBM matches modularity and BA matches the degree tail, the deep model must beat both at once.
BFS ordering bounds the lookbackIn the ordering figure above the adjacency matrix becomes banded under BFS, so the edge-level RNN only looks back M steps. Compute M (the maximum BFS bandwidth over your training graphs) before training; it fixes the output size.
Evaluate with more than MMD on degreeMMD rankings flip with the kernel choice (O'Bray et al. 2022). Report degree, clustering, motif counts and spectral statistics, plus a real-vs-fake classifier (PolyGraph Discrepancy, ICLR 2026). For social graphs add community-level statistics; mesoscale structure is what current metrics miss.
Cascades have no ordering ambiguityA retweet cascade grows in time order, so the n! problem disappears: autoregressive generation is the natural model. Use it for virality forecasting from the early cascade.

Readings & lookup guide

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

Concise written version of the lectures; the walkthrough above cites it page by page.

read first You, Ying, Ren, Hamilton, Leskovec — GraphRNN: Generating Realistic Graphs with Deep Auto-regressive Models (ICML 2018)

  • Read: §2.2–2.3 (sequence representation; the hierarchical RNN; GraphRNN-S vs full), §2.4 (BFS ordering and Proposition 1 — the frontier argument), §4 (MMD-based evaluation on degree, clustering, orbit counts).

goal-directed You, Liu, Ying, Pande, Leskovec — Graph Convolutional Policy Network for Goal-Directed Molecular Graph Generation (NeurIPS 2018)

  • Read: §3 (MDP formulation: states = partial graphs, actions = link/scaffold choices, valency checks), rewards (step + final + adversarial), PPO training with expert pretraining; Fig. 1.

beyond Vignac et al. — DiGress: Discrete Denoising Diffusion for Graph Generation (ICLR 2023) · Hamilton GRL book Ch. 8–9

arXiv:2209.14734 · GRL book chapters on traditional and deep generative models
  • Diffusion models are the modern successor: permutation-equivariant, no node ordering. Chapter 8 of the GRL book reviews ER, SBM and preferential attachment — useful SNA background.

Homework & deadlines

Colab 4 due Tue 12/1 · Colab 5 due Thu 12/3 · Final project report due Thu 12/10 (no late periods)

The course also publishes project blog posts on Medium — students submit their Medium usernames.

Self-check

GraphRNN represents a graph as …

  1. a set of node embeddings
  2. a sequence of node additions, each with a sequence of edge decisions
  3. a random walk
  4. an adjacency spectrum

Sequence of sequences \(S^\pi\) for a node ordering \(\pi\).

Teacher forcing means …

  1. sampling from the model during training
  2. using a teacher network
  3. feeding the true previous decisions as inputs during training
  4. forcing EOS

Replace inputs/outputs by the real sequence and compute loss.

Why does BFS ordering help GraphRNN?

  1. New nodes only need to consider a bounded frontier of recent nodes
  2. It makes graphs acyclic
  3. It removes the node-level RNN
  4. It guarantees valid molecules

Band-limited adjacency; also fewer orderings.

GCPN predicts actions from …

  1. RNN hidden states
  2. random walks
  3. a fixed scaffold only
  4. GNN node embeddings of the partial graph

More expressive than RNN states, slower to compute.

GCPN's reward is …

  1. only the final property
  2. step rewards for valid actions + final property reward
  3. negative log-likelihood
  4. graph edit distance

Reward = final reward + step reward.

Flashcards (click to flip)

Two goals of generative models
Density estimation (max likelihood) and sampling.
Autoregressive factorisation
\(p(x)=\prod_t p(x_t\mid x_{<t})\); for graphs, \(x_t\) = actions.
GraphRNN's two RNNs
Node-level (adds nodes, initialises edge RNN) and edge-level (connect to each previous node?).
Stop criterion
Edge RNN outputs EOS at its first step → stop.
Evaluate generated graphs
Visual similarity + statistics (degree, clustering, orbits) via MMD.
GCPN training
Supervised imitation + policy gradient (PPO) on rewards.

History & the bigger picture

  • 1959–60 — Erdős–Rényi random graphs: the first generative model; elegant, unrealistic (no clustering, Poisson degrees).
  • 1983 — stochastic block models (Holland, Laskey, Leinhardt) — from sociology! 1998 — Watts–Strogatz small worlds; 1999 — Barabási–Albert preferential attachment; 2010 — Kronecker graphs (Leskovec et al.).
  • 2018 — deep generative graph models: GraphVAE, GraphRNN, GCPN, JT-VAE (molecules). 2019 — GRAN. 2022–2023 — graph diffusion (GDSS, DiGress); today, generative models design proteins (RFdiffusion) and materials (GNoME).
Science & society · generating molecules, generating networks

Goal-directed generation is double-edged: the same RL loop that maximises drug-likeness could, with a different reward, maximise toxicity — Urbina et al. (2022, Nature Machine Intelligence) showed a drug-discovery model, inverted, proposed thousands of potential chemical-weapon-like molecules in hours. Responsible research practice (access control, reward auditing) is part of the field now. For social networks, realistic graph generators enable privacy-preserving synthetic data — and also synthetic bot networks.

Classic SNA bridge

In this lectureClassic SNA counterpartWhat carried over, what changed
Learn \(p(G)\) and sample new graphsRandom graph models as null hypotheses: ER (1959), configuration model, SBM (Holland, Laskey & Leinhardt 1983, from sociology), ERGMs (Frank & Strauss 1986)SNA used generative models to test hypotheses ("is this clustering more than chance?"); deep generators are used to produce data. The ERGM, \(P(G)\propto\exp(\theta^\top s(G))\), is the explicit-likelihood ancestor GraphRNN replaced with an autoregressive factorisation.
GraphRNN: a graph as a sequence of node additionsNetwork growth models: preferential attachment (Price 1976; Barabási–Albert 1999); triadic-closure growth (Jin, Girvan & Newman 2001)Growth models add nodes one at a time with a hand-written rule; GraphRNN learns the rule. Comparing what the RNN learned with preferential attachment and closure is the interpretability question.
BFS ordering and the frontier MSnowball sampling waves; the "boundary" of a growing networkA BFS wave is a snowball-sample wave. The frontier M is the size of the current wave, which SNA already tracked when estimating hidden populations.
Evaluating generated graphs by statisticsMotif significance profiles (Milo et al. 2004); the triad census as a network fingerprintSNA compared networks by profiles of small-subgraph counts; the generation literature is rediscovering that degree and clustering alone are not a fingerprint.
Goal-directed generation (GCPN)Network interventions and design: "what network should we build?" (Valente 2012); the Musco et al. least-polarising networkDesigning a graph to optimise an objective is network intervention. The least-polarising network problem (convex, Lecture 11's frontier) is a goal-directed generation problem with a social reward.
Bridge idea

Fit an ERGM with triangle and degree terms, an SBM, and a GraphRNN-lite to the same retweet network. Compare them on the full motif significance profile and on community statistics, not only on degree MMD. Then try to explain the deep generator's samples with the ERGM's terms: which mechanistic rules (closure, popularity, homophily) does the deep model implicitly learn? That is a neuro-symbolic study of network formation.

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 4 · Random graphs & small worlds (random-graph models as the baselines of graph generation); Unit 5 · Heavy tails & the scale-free debate (generative models of graphs, from preferential attachment to learned ones); Unit 6 · Communities & statistical network models (the stochastic block model as a generative model).

Connecting to your research

For SNA
  • Synthetic social graphs: if you can't share your X/Twitter data, a generator trained on it (with privacy guarantees) can produce shareable graphs with the same degree/clustering/community statistics — useful for reproducibility.
  • Mechanistic vs learned models: SNA's formation models (preferential attachment, triadic closure, homophily) are interpretable hypotheses; deep generators fit better but explain less. Comparing them on cascade or follow-graph growth is a neat neuro-symbolic study: which mechanistic rules does the deep model implicitly learn?
  • Cascade generation: a retweet cascade grows node by node in time order — a natural fit for GraphRNN-style autoregressive models (no ordering ambiguity!).

Frontier 2025–26: what changed since the slides

ICML 2025 → 2026Discrete flow matching displaced diffusion; RL fine-tuning arrived — DeFoG (discrete flow matching) follows DiGress (discrete diffusion); Graph-GRPO (ICML 2026) applies RL with verifiable rewards to flow models (95.0% valid-unique-novel on planar graphs in 50 steps). The GCPN idea of this lecture (RL on a graph generator) is back on top of a much better base model.sources: arXiv:2410.04263 · arXiv:2603.10395
NeurIPS 2025AutoGraph: graphs as token sequences for a decoder-only transformer — Flattens graphs into sequences with no O(n²) adjacency, the "LLM-ification" of GraphRNN's sequence-of-sequences. The node-ordering question of this lecture becomes a tokenisation question.
NeurIPS 2025 spotlightIs noise conditioning necessary? A unified theory of unconditional graph diffusion — A theory spotlight on what diffusion models on graphs actually need. Methods that respect discreteness beat continuous relaxations of the adjacency matrix: the graph-specific lesson of the whole line.
ICLR 2026PolyGraph Discrepancy: evaluation as its own front — Train real-vs-fake classifiers to get a bounded lower bound on the Jensen–Shannon distance, replacing kernel-dependent MMD rankings. Evaluation of generated graphs is now a research topic, not a table.sources: arXiv:2510.06122
Atlas · generationThe open question for social networks — Generated social networks for simulation need realistic mesoscale structure (motifs, simplicial closure, communities); the atlas asks whether current metrics capture it. Generating higher-order structure directly is listed as open.
Open question to carryHow should one evaluate generated social graphs? Degree and clustering MMD can be gamed; community structure, motif profiles and temporal statistics are what a synthetic X graph must reproduce to be useful for privacy-preserving sharing or for simulation.
Frontiers · classical generators · generation followed images

Words & phrases

TermSimple meaningPersianIn context
autoregressiveadj.generating each part conditioned on all previously generated partsخودبازگشتی"Autoregressive models use the chain rule"
valencyn.(chemistry) the number of bonds an atom can formظرفیت (شیمیایی)"obey rules (chemical valency)"
likelihoodn.the probability a model assigns to the observed dataدرست‌نمایی"the likelihood of one generated graph"
generative modeln.a model that can produce new samples resembling the dataمدل مولد"GraphRNN is a generative model of graphs"
node orderingn.the sequence in which nodes are generatedترتیب گره‌ها"BFS node ordering"
validityn.whether a generated object obeys the rules (for molecules, valence)اعتبار"a validity reward at every step"

Go deeper

  • Next: Lecture 19 — conclusion and the GNN design space revisited.
  • Modern generators: Liao et al. (2019) GRAN (block-wise autoregression with GNNs); Vignac et al. (2023) DiGress (discrete diffusion).
  • Open question: how should one evaluate generated graphs? MMD on a few statistics can be gamed; recent work (O'Bray et al. 2022) shows evaluation choices change rankings.