CS224W

Lecture 3 · Tue 9/29 · slides PDF · lecture notes

Graph Neural Networks

Replace the embedding lookup table with a neural network that lets every node repeatedly gather and transform messages from its neighbours.

25
sectionstick "got it" as you go
31
figuresredrawn from the slides
interactive figuresplay with the ideas
5
self-check questionsplus flashcards
18′
reading time3,980 words, walkthrough aside

Before you start: review of the earlier sessions

The thread so far. Sessions 1–2 described graphs and shallow embeddings; session 3 is the first real neural network on graphs, and the computation-graph picture here is reused by every lecture that follows.

What this session takes from earlier ones

  • Lecture 2: the encoder–decoder template: a GNN is a new encoder, the decoders and losses stay
  • Lecture 2: the limits of shallow embeddings that the GNN removes
  • Lecture 1: adjacency matrix and node features: the GCN layer is written in exactly those matrices

Those sessions in one minute each

Lecture 2 · Node Embeddings

Define similarity by co-occurrence on short random walks, then learn one vector per node so that dot products reproduce it — fast with negative sampling, but just a lookup table.

\[ \mathcal{L}=\sum_{u\in V}\sum_{v\in N_R(u)}\Big[-\log\sigma(\mathbf{z}_u^\top\mathbf{z}_v)-\sum_{i=1}^{k}\log\sigma(-\mathbf{z}_u^\top\mathbf{z}_{n_i})\Big] \]

\(N_R(u)\): multiset of nodes visited by walks from \(u\) under strategy \(R\) (uniform for DeepWalk, \(p,q\)-biased for node2vec); \(n_i\): negatives sampled ∝ degree; \(\sigma\): sigmoid.

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)\).

Warm-up: answer these before you read on

Why is a random walk a sensible definition of node similarity? from Lecture 2

It mixes local and higher-order neighbourhood information and is cheap: only the pairs that co-occur on walks need to be considered, not all |V|² pairs.

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).

What do p and q control in node2vec? from Lecture 2

The return parameter p penalises stepping back to the previous node; the in-out parameter q biases towards staying close (BFS, small q favours DFS). They trade off local versus structural similarity.

Why does a convolution on an image not transfer directly to a graph? from Lecture 1

A pixel has a fixed set of neighbours in a fixed order (a 3×3 window); a graph node has a variable number of neighbours and no canonical order, so a fixed filter cannot be slid over it.

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

In short

Shallow embeddings (Lecture 2) have \(O(|V|d)\) parameters, ignore features, and cannot embed a node they have never seen. A graph neural network fixes all three with one idea: a node's neighbourhood defines its computation graph.

At layer 0 each node holds its features. At every layer, each node takes its neighbours' current vectors, aggregates them with an order-independent operation (average, sum), passes the result through a small neural network, and combines it with its own vector. After \(K\) layers a node "knows" its \(K\)-hop neighbourhood.

The same weights are used at every node, so the model is inductive: it can embed new nodes or whole new graphs. And because aggregation ignores order, the model is automatically permutation equivariant — exactly what Lecture 1 demanded.

Also covered: the formal definitions of invariance/equivariance, the matrix form of a GCN layer, supervised vs unsupervised training, and why CNNs and Transformers are special GNNs. A deep-learning refresher (loss, SGD, backprop, MLP) closes the slide deck (slide 74–slide 88).

The picture: a node's computation graph

Unrolling the 2-layer computation graph of node A input graph ABCDEFG neighbours: A–B, A–C, A–D x_Ax_Ex_Gx_Ax_Ex_A layer 0 3 B C D layer 1 2 A → z_A layer 2 (output) 1 same W₁, B₁ in every orange box W₂, B₂ 4

How to read it (hover a step)

  1. The target node A's final embedding \(\mathbf{z}_A=\mathbf{h}_A^{(2)}\) is computed from its neighbours' layer-1 vectors.
  2. Each neighbour (B, C, D) first computes its own layer-1 vector by aggregating its neighbours. A box = "aggregate, then apply a neural network".
  3. Leaves are input features \(\mathbf{x}_v\). Node A appears among its own grandchildren — the tree is an unrolling, not the graph itself, and nodes repeat.
  4. All boxes at the same layer share weights. That's why the number of parameters doesn't grow with \(|V|\), and why we can embed unseen nodes.

1 · Permutation invariance and equivariance

Write a graph as \((A, X)\): adjacency matrix and feature matrix \(X\in\mathbb{R}^{|V|\times m}\). A graph with \(|V|\) nodes has \(|V|!\) different matrix representations. Relabelling by a permutation matrix \(P\) gives \((PAP^\top, PX)\).

  • Invariant (graph → vector): \(f(PAP^\top, PX)=f(A,X)\). Example: \(\mathbf{1}^\top X\) (sum of features).
  • Invariance versus equivariance. slide 30 ↗
  • Equivariant (graph → one vector per node): \(f(PAP^\top,PX)=P\,f(A,X)\). Examples: \(X\), and \(AX\) since \(PAP^\top PX = PAX\).

A GNN is a stack of equivariant layers, optionally ending with an invariant readout. An MLP on \([A, X]\) is neither — reorder the input and the output changes — and it has \(O(|V|)\) parameters and can't handle other sizes.

Prove that \(f(A,X)=AX\) is equivariant. Is \(f(A,X)=A^2X\)? Is \(f(A,X)=\max_{\text{rows}}(X)\)?

\(PAP^\top PX = PA(P^\top P)X = PAX\) because permutation matrices are orthogonal. For \(A^2X\): \((PAP^\top)^2PX = PAP^\top PAP^\top PX = PA^2X\) → equivariant; in general any polynomial in \(A\) times \(X\) is. Row-wise max is invariant: permuting rows doesn't change a column's maximum. Sum, mean and max are the three classic invariant set functions.

2 · Graph Convolutional Networks: aggregate neighbours

Kipf & Welling's insight (ICLR 2017): determine each node's computation graph from its neighbourhood, then propagate and transform information along it. The key design question is "what's in the box?" — the aggregation. The basic version: average the neighbours' messages, then apply a neural network.

Idea: the neighbourhood defines a computation graph. slide 36 ↗
\[ \mathbf{h}_v^{(0)}=\mathbf{x}_v,\qquad \mathbf{h}_v^{(k+1)}=\sigma\Big(\mathbf{W}_k\sum_{u\in N(v)}\frac{\mathbf{h}_u^{(k)}}{|N(v)|}+\mathbf{B}_k\,\mathbf{h}_v^{(k)}\Big),\qquad \mathbf{z}_v=\mathbf{h}_v^{(K)} \]

\(\mathbf{W}_k\): weights for the neighbourhood message; \(\mathbf{B}_k\): weights for the node's own (self) vector; \(\sigma\): non-linearity (ReLU); \(K\): number of layers. The average is permutation invariant, so for a given node the computation is invariant, and over all nodes the layer is equivariant (slide 44–slide 46).

The math of a GCN layer, annotated. slide 43 ↗

Matrix form — why GNNs run fast on GPUs

Stack embeddings as rows: \(H^{(k)}=[\mathbf{h}_1^{(k)}\dots\mathbf{h}_{|V|}^{(k)}]^\top\). Then \(\sum_{u\in N(v)}\mathbf{h}_u = A_{v,:}H\), and with the degree matrix \(D\):

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

The red part (\(\tilde A H W^\top\)) is neighbourhood aggregation, the blue part (\(HB^\top\)) is self-transformation. \(\tilde A\) is sparse, so one layer costs \(O(|E|\,d)\) with sparse-dense multiplication. Not every GNN has such a simple matrix form (e.g. attention, max aggregation).

Slides vs the original GCN paper

The lecture's GCN uses mean aggregation \(D^{-1}A\) plus a separate self term. Kipf & Welling's actual layer is \(H^{(k+1)}=\sigma(\hat A H^{(k)}W_k)\) with \(\hat A=\tilde D^{-1/2}(A+I)\tilde D^{-1/2}\): self-loops instead of a separate \(B\), and symmetric normalisation. Homework 1 uses the symmetric form. Both are "average-like"; the symmetric one down-weights edges between high-degree nodes.

3 · Training a GNN

The embedding \(\mathbf{z}_v\) is now a function of the input graph and the shared weights \(\Theta=\{W_k,B_k\}\). Feed it into any loss:

  • Supervised (e.g. "safe or toxic drug?" in a drug–drug interaction network): \(\mathcal{L}=-\sum_v y_v\log\sigma(\mathbf{z}_v^\top\theta)+(1-y_v)\log(1-\sigma(\mathbf{z}_v^\top\theta))\).
  • Supervised loss: encoder output, classifier weights, label. slide 54 ↗
  • Unsupervised / self-supervised: use the graph as supervision — \(\mathcal{L}=\sum_{u,v}\text{CE}(y_{u,v},\text{DEC}(\mathbf{z}_u,\mathbf{z}_v))\) where \(y_{u,v}=1\) if \(u,v\) are "similar" by any Lecture-2 definition (random walks, matrix factorisation, edges).

Model design in four steps (slide 55–slide 57): (1) define the aggregation, (2) define a loss on embeddings, (3) train on a batch of compute graphs, (4) generate embeddings for any node — even ones never trained on.

Shared parameters across all compute graphs. slide 58 ↗

Inductive capability

  • New graphs: train on the protein-interaction graph of organism A, embed organism B.
  • New nodes: Reddit, YouTube, Google Scholar get new nodes every second — compute their embeddings on the fly with no retraining.

Interactive tool from the slides: GNN 101 — watch a GCN run in your browser, layer by layer, with matrix and node-link views. Worth 20 minutes.

4 · GNNs subsume CNNs and Transformers

Write a 3×3 convolution as message passing over the 8 neighbour pixels plus the centre:

CNN = special GNN with fixed neighbour size and ordering. slide 68 ↗
\[ \text{CNN: } \mathbf{h}_v^{(l+1)}=\sigma\Big(\sum_{u\in N(v)}\mathbf{W}_l^{\,u}\,\mathbf{h}_u^{(l)}+\mathbf{B}_l\mathbf{h}_v^{(l)}\Big)\qquad \text{GNN: } \mathbf{h}_v^{(l+1)}=\sigma\Big(\mathbf{W}_l\sum_{u\in N(v)}\tfrac{\mathbf{h}_u^{(l)}}{|N(v)|}+\mathbf{B}_l\mathbf{h}_v^{(l)}\Big) \]

The one difference: a CNN can learn a different weight \(\mathbf{W}_l^{\,u}\) for each neighbour because pixels have a canonical relative position \((-1,-1),\dots,(1,1)\). A graph has no such order, so a GNN must share one \(\mathbf{W}_l\). GNNs subsume CNNs: a CNN is a GNN on a grid with fixed neighbour size and ordering — and therefore not permutation equivariant.

Transformers: self-attention lets every token attend to every other token. Its computation graph is a GNN on the complete graph of tokens, with attention weights as edge-dependent aggregation weights. (Positional encodings are what break the symmetry — Lecture 8 returns to this for graphs.)

A Transformer layer is a GNN on a fully connected "word" graph. slide 71 ↗
Context · Geometric Deep Learning

Bronstein's ICLR 2021 keynote (an optional reading) organises all of deep learning by symmetry: CNNs are equivariant to translations, GNNs to permutations, spherical CNNs to rotations. The "Erlangen programme" of deep learning — named after Felix Klein's 1872 programme that classified geometries by their symmetry groups. Architecture design becomes: pick the symmetry of your domain, then build layers that respect it.

The mathematics, step by step

A graph neural network is one formula applied at every node and repeated a few times. The cards build it up: the layer for one node, the same layer for all nodes at once as a matrix product, the reason the order of the nodes cannot matter, and the loss that trains the weights.

Symbols used in this session

symbolmeaningwhat kind of object
\(\mathbf x_v\)input features of node \(v\)vector in \(\mathbb R^{d_0}\)
\(\mathbf h_v^{(k)}\)embedding of node \(v\) after \(k\) layers; \(\mathbf h_v^{(0)}=\mathbf x_v\)vector in \(\mathbb R^{d_k}\)
\(H^{(k)}\)all embeddings after layer \(k\), stacked: row \(v\) is \(\mathbf h_v^{(k)\top}\)\(n\times d_k\) matrix
\(N(v)\)neighbours of \(v\); \(|N(v)|\) is its degreeset of nodes
\(W_k,\ B_k\)weights of layer \(k\): \(W_k\) transforms the neighbours' average, \(B_k\) the node's own vector. Shared by all nodes\(d_{k+1}\times d_k\) matrices; these are the parameters
\(\sigma\)non-linearity applied to every entry, usually ReLUfunction
\(A,\ D\)adjacency matrix; diagonal matrix with \(D_{vv}=|N(v)|\)\(n\times n\) matrices
\(\mathbf z_v\)final embedding \(\mathbf h_v^{(K)}\) after \(K\) layersvector
\(\mathbf y_v\)label of node \(v\) as a one-hot vectorvector in \(\{0,1\}^C\)

1One layer, seen from one node

\[ \mathbf{h}_v^{(k+1)}=\sigma\Big(W_k\sum_{u\in N(v)}\frac{\mathbf{h}_u^{(k)}}{|N(v)|}+B_k\,\mathbf{h}_v^{(k)}\Big),\qquad \mathbf h_v^{(0)}=\mathbf x_v \]

In words. To update a node: average its neighbours' current vectors, transform that average with one matrix, transform the node's own vector with another, add the two, and apply the non-linearity.

Why it has this form. The average is used because it does not depend on the order of the neighbours and works for any number of them. \(W_k\) and \(B_k\) do not carry an index \(v\): the same two matrices are used at every node, so the number of parameters does not depend on the size of the graph and the layer can be applied to nodes it has never seen. After one layer a node knows its neighbours; its neighbours also updated from their neighbours, so after \(K\) layers information has travelled \(K\) hops.

With numbers. A node with \(\mathbf h_v=(0,-4)\) has two neighbours with vectors \((1,0)\) and \((3,2)\). Their mean is \((2,1)\). With \(W=\begin{pmatrix}1&0\\1&1\end{pmatrix}\) the message is \(W(2,1)^\top=(2,3)\); with \(B=I\) the node's own part is \((0,-4)\). The sum is \((2,-1)\) and ReLU gives \(\mathbf h_v^{\text{new}}=(2,0)\).

Watch out. The superscript \((k)\) is a layer index, not a power. Every node is updated from the old vectors of layer \(k\), all at the same time.

2The same layer for all nodes at once

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

In words. Stack the node vectors as rows of a matrix. Multiplying by \(D^{-1}A\) replaces every row by the average of its neighbours' rows; multiplying by \(W_k^\top\) on the right transforms every row.

Why it has this form. Row \(v\) of \(AH\) is \(\sum_u A_{vu}\mathbf h_u^\top=\sum_{u\in N(v)}\mathbf h_u^\top\), the neighbours' sum; \(D^{-1}\) divides row \(v\) by \(|N(v)|\), making it the mean. The transpose appears because the node vectors are rows: the row vector \(\mathbf h^\top W^\top\) is the column vector \(W\mathbf h\) written as a row. Row \(v\) of the matrix formula is therefore exactly card 1. \(A\) is sparse, so the product costs time proportional to the number of edges.

With numbers. Path 1–2–3 with scalar features \(H=(1,2,6)^\top\): \[D^{-1}A=\begin{pmatrix}0&1&0\\ \tfrac12&0&\tfrac12\\ 0&1&0\end{pmatrix},\qquad D^{-1}A\,H=\begin{pmatrix}2\\3.5\\2\end{pmatrix}.\] Node 2 receives the mean of 1 and 6; the end nodes receive node 2's value. With \(W=B=1\) and no non-linearity, \(H^{\text{new}}=(3,\,5.5,\,8)^\top\).

Watch out. \(D^{-1}A\) (average) is not symmetric. Kipf and Welling's GCN uses \(D^{-1/2}AD^{-1/2}\) with self-loops added, which is symmetric and divides the message from \(u\) to \(v\) by \(\sqrt{d_ud_v}\).

3Why the numbering of the nodes cannot matter

\[ f(PAP^\top,PX)=P\,f(A,X)\quad\text{for every permutation matrix } P \]

In words. If the nodes are renumbered, the layer returns the same embeddings, renumbered in the same way. A graph-level output obtained by summing the rows is then unchanged.

Why it has this form. Renumbering turns \(A\) into \(PAP^\top\), \(D\) into \(PDP^\top\) and \(H\) into \(PH\). Insert these and use \(P^\top P=I\): \((PDP^\top)^{-1}(PAP^\top)(PH)=PD^{-1}P^\top PAP^\top PH=P\,D^{-1}AH\). The second term gives \(PHB^\top\). \(\sigma\) acts entry by entry, so it commutes with reordering rows. Hence the new output is \(P\) times the old one. A composition of equivariant layers is equivariant, so the whole network is.

With numbers. In the path example above, rename node 1 as 3 and node 3 as 1. The features become \((6,2,1)\); the layer returns \((8,5.5,3)\), which is \((3,5.5,8)\) in the new order. Each node got the number it had before; only its position in the list moved.

Watch out. Equivariance has a price: two nodes whose neighbourhoods look identical must receive the same embedding, whatever their position in the graph. Lectures 6 and 7 measure and repair this.

4The training loss

\[ \mathcal L=\sum_{v\in\text{train}}\text{CE}\big(\mathbf y_v,\ \text{softmax}(W_{\text{out}}\mathbf z_v)\big),\qquad \text{CE}(\mathbf y,\mathbf p)=-\sum_{c=1}^{C}y_c\log p_c \]

In words. Turn each labelled node's final embedding into class probabilities and pay minus the logarithm of the probability given to the correct class. Sum over the labelled nodes.

Why it has this form. Since \(\mathbf y_v\) is one-hot, only the true class survives in the sum: \(\text{CE}=-\log p_{\text{true}}\). This is zero when the model is certain and right, and grows without bound when it is certain and wrong. The loss is a differentiable function of all \(W_k,B_k\), so gradient descent trains every layer together. Unlabelled nodes do not appear in the sum but still take part in the computation, because their features flow into their labelled neighbours.

With numbers. Three classes, scores \(W_{\text{out}}\mathbf z_v=(2,1,0)\). Softmax: \((e^2,e^1,e^0)/(7.39+2.72+1)=(0.665,0.245,0.090)\). If the true class is the first, the loss is \(-\log0.665=0.41\); if it is the second, \(-\log0.245=1.41\).

Watch out. The sum runs only over training nodes. Validation and test nodes must be left out of the loss, although they stay in the graph (Lecture 5 treats this carefully).

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: is \(f(A,X)=\mathbf{1}^\top AX\) invariant? show answer

(Yes: an invariant function applied after an equivariant one is invariant.) This composition rule is exactly how GNNs are built.

from Permutation equivariance: node-level outputs move with the nodes

Check yourself: self-attention on a set of tokens without positional encodings is permutation equivariant. Why? show answer

Hint: the weights are computed from the token vectors only, and the sum over "all other tokens" has no order.

from Transformers as GNNs, and the lecture summary

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. Recap: shallow encoders and their three limits
  2. Deep graph encoders, and why graphs are hard for standard deep learning
  3. The deep-learning recipe and the graph setup
  4. A naive approach, and why convolutions do not transfer directly
  5. Permutation invariance: one graph, many matrices
  6. Permutation equivariance: node-level outputs move with the nodes
  7. GNNs are stacks of equivariant layers; MLPs are not
  8. The GCN idea: a node's neighbourhood defines its computation graph
  9. What is in the box? The GCN layer and its symmetry
  10. Model parameters and the matrix form
  11. Training a GNN: supervised and unsupervised losses
  12. Model design in four steps, and inductive capability
  13. GNNs subsume CNNs
  14. Transformers as GNNs, and the lecture summary
  15. Refresher: machine learning as optimisation, gradient descent and SGD
  16. Refresher: back-propagation, non-linearity and the MLP

Recap: shallow encoders and their three limits slides 3-7 ↗

Where Lecture 2 left us: a map f from nodes to ℝᵈ, learned as a plain lookup table, with its three limits (slide 6). slides 3-6 ↗

The lecture starts from where Lecture 2 ended. Slide 3 restates the goal of node embedding: learn a map \(f\) that sends every node to a point in \(\mathbb{R}^d\) so that nodes that are similar in the graph land close together. The picture shows a messy input graph on the left and a 2D scatter of node embeddings on the right, with the question "how do we learn \(f\)?".

Slide 4 recalls the encoder–decoder view: an encoder \(\mathrm{ENC}(u)=\mathbf{z}_u\) maps each node into the embedding space, and we want

\[ \text{similarity}(u,v)\;\approx\;\mathbf{z}_v^{\top}\mathbf{z}_u , \]

where the similarity function is something we "need to define" (random walks, adjacency, and so on). Slide 5 shows the simplest encoder, the shallow one: \(\mathbf{Z}\) is a \(d\times|V|\) matrix with one column per node, and encoding a node is just looking up its column.

Slide 6 lists the three problems with this lookup table:

  1. \(O(|V|d)\) parameters. Nothing is shared between nodes; every node owns its own vector. A graph with a billion nodes needs a billion vectors.
  2. Inherently transductive. A node that was not present during training has no column, so it gets no embedding. You must retrain.
  3. No node features. Many graphs carry rich attributes (a user's profile, a protein's sequence). The lookup table ignores them.

Slide 7 announces the fix for today: replace the lookup by a deep graph encoder, \(\mathrm{ENC}(v)=\) "multiple layers of non-linear transformations based on graph structure". Importantly, the decoder and similarity side of Lecture 2 stays the same: any of these deep encoders can be combined with the node-similarity functions from Lecture 2.

Check yourself: which of the three limits does weight sharing fix, and which does using \(\mathbf{x}_v\) as input fix?

Deep graph encoders, and why graphs are hard for standard deep learning slides 8-11 ↗

Slide 8, the target architecture: a stack of graph convolutions with activations and regularisation, producing an embedding for every node. slide 8 ↗
Slides 10–11: CNNs and sequence models assume a grid or a line. A network has neither a fixed neighbourhood size nor a reference point. slides 10-11 ↗

Slide 8 sketches the architecture we are aiming for: the input graph passes through a stack of "graph convolution" layers, each followed by an activation function and regularisation (for example dropout), and the output is a node embedding for every node. The callout adds that we can also embed subgraphs and whole graphs (by pooling node embeddings).

Slide 9 lists what such embeddings let us do:

  • Node classification — predict the type of a given node.
  • Link prediction — predict whether two nodes are linked.
  • Community detection — identify densely linked clusters of nodes.
  • Network similarity — measure how similar two (sub)networks are.

Slide 10 makes the main point of the motivation: the modern deep-learning toolbox (CNNs, RNNs, Transformers) is designed for simple sequences and grids. An image is a regular 2D grid of pixels; text or speech is a 1D line of tokens.

Slide 11 explains why networks break this toolbox. The figure puts a tangled network next to a pixel grid and a text chain. Networks are far more complex:

  • Arbitrary size and complex topology — there is no spatial locality like a grid; one node may have 2 neighbours, another 2,000.
  • No fixed node ordering or reference point — there is no "top-left pixel" or "first word".
  • Often dynamic (nodes and edges appear and disappear) and with multimodal features (text, images, numbers attached to nodes).

The second bullet is the deep one: almost the whole first half of the lecture is about how to build a network that does not depend on an arbitrary node order.

The deep-learning recipe and the graph setup slides 13,15-16 ↗

Slide 13: deep learning in one loop. Slide 16 fixes the notation used for the rest of the course. slides 13-16 ↗

Slide 13 is a one-slide summary of deep learning (the full refresher is at the end of the deck, slides 74–88). Training means solving

\[ \min_{\Theta}\; \mathcal{L}\big(\mathbf{y}, f_{\Theta}(\mathbf{x})\big), \]

where \(f\) can be a linear layer, an MLP, or another network — later, a GNN. The loop is: sample a minibatch of inputs \(\mathbf{x}\); run forward propagation to compute \(\mathcal{L}\); run back-propagation to get \(\nabla_{\Theta}\mathcal{L}\) by the chain rule; update \(\Theta\) with stochastic gradient descent; repeat for many iterations.

Slide 15 gives the plan for the "deep learning for graphs" part: first, local network neighbourhoods (aggregation strategies, computation graphs); then, stacking multiple layers (the model, its parameters, how to fit it, with simple supervised and unsupervised examples).

Slide 16 fixes notation used for the rest of the course:

  • \(V\): the vertex set; \(A\): the adjacency matrix (assume binary).
  • \(X\in\mathbb{R}^{|V|\times m}\): the matrix of node features (row \(v\) is the \(m\)-dimensional feature vector \(\mathbf{x}_v\)).
  • \(v\): a node in \(V\); \(N(v)\): the set of neighbours of \(v\).

Examples of node features: in social networks, the user profile and user image; in biological networks, gene expression profiles and gene functional information. When a dataset has no node features, two standard choices are (a) indicator vectors (a one-hot encoding of each node) or (b) a vector of constant 1, \([1,1,\dots,1]\).

The two choices behave very differently. One-hot features make the model as expressive as a lookup table, but it becomes transductive again (a new node has no one-hot slot). Constant features keep it inductive, but then the GNN can only use graph structure to tell nodes apart.

A naive approach, and why convolutions do not transfer directly slides 17-19 ↗

Slide 17, the naive approach: feed the rows of [A, X] into an MLP. It cannot handle other sizes and changes its answer when the nodes are renumbered. slide 17 ↗
Slides 18–19: a CNN works because a filter slides over a regular lattice; on a graph there is no sliding window and no fixed neighbour count. slides 18-19 ↗

Slide 17 tries the obvious idea. Write the 5-node example graph's adjacency matrix and append the feature column, giving one row per node of \([A, X]\). Feed these rows into a fully connected deep network. Done?

No. The slide lists three issues:

  1. \(O(|V|)\) parameters. The input layer has one weight per column, and there is one column per node.
  2. Not applicable to graphs of different sizes. A 6-node graph has a longer input row than the network was built for.
  3. Sensitive to node ordering. Swap the labels of two nodes and the rows and columns of \(A\) move; the network sees a different input and gives a different answer, although the graph is the same.

Slide 18 recalls how a CNN works on an image: a small filter (for example \(3\times3\)) slides over the pixel grid, and the same weights are applied at every position. A stack of such layers (convolution, subsampling, more convolutions, fully connected output) builds features of growing scope. The goal stated on the slide: generalise convolutions beyond simple lattices, and leverage node features (text, images).

Slide 19 shows the obstacle: "but our graphs look like this" — irregular graphs with a box marking a would-be "window". Two facts block a direct copy of the CNN:

  • There is no fixed notion of locality or sliding window on the graph: neighbourhoods differ in size and shape.
  • Graphs are permutation invariant: the node labels are arbitrary, so the answer must not depend on them.

Permutation invariance: one graph, many matrices slides 20-25 ↗

Slides 21–25: one graph, two node orderings. Colour marks the same node under both labellings; the feature rows and the adjacency pattern move, and a graph-level output must not. slides 21-25 ↗

Slide 20 starts with the task of embedding an entire graph. The key observation: a graph does not have a canonical ordering of its nodes. The same graph can be written with many different node orderings, and we want the learned embedding to be the same no matter how the nodes are numbered.

Slides 21–23 make this concrete with a 6-node graph A–F. Under "Order 1" the feature matrix \(X_1\) has rows A, B, …, F (each row drawn as a coloured bar), and the adjacency matrix \(A_1\) is a \(6\times6\) grid of shaded cells. Under "Order 2" the same graph is relabelled: the node that was A is now called something else, so the rows of \(X_2\) appear in a different colour order and the shaded pattern of \(A_2\) is shuffled. Slide 23's green callout states the requirement: the learned graph representation should be the same for Order 1 and Order 2.

Slide 24 formalises it. If \(f\) maps a graph \(G=(A,X)\) to a vector in \(\mathbb{R}^d\), then we need \(f(A_1,X_1)=f(A_2,X_2)\).

Slide 25 gives the definition. Relabelling the nodes is a permutation matrix \(P\) (a shuffle of the node order; example: \((A,B,C)\to(B,C,A)\)). It reorders the rows of \(X\) to \(PX\), and both the rows and the columns of \(A\) to \(PAP^{\top}\). A graph with \(|V|\) nodes has \(|V|!\) orderings.

\[ f:\mathbb{R}^{|V|\times|V|}\times\mathbb{R}^{|V|\times m}\to\mathbb{R}^{d}\ \text{ is permutation invariant if }\ f(A,X)=f(PAP^{\top},PX)\ \text{ for every permutation } P. \]

Here \(m\) is the feature dimension and \(d\) the output (graph-embedding) dimension.

Why \(PAP^\top\) and not \(PA\)? Entry \((i,j)\) of \(A\) says "node \(i\) links to node \(j\)". Renaming nodes must rename both the row index and the column index, so we permute rows (left multiply by \(P\)) and columns (right multiply by \(P^\top\)).

Permutation equivariance: node-level outputs move with the nodes slides 26-30 ↗

Slides 27–29, equivariance: node-level outputs are a matrix with one row per node; relabelling permutes the rows but each node keeps its own vector. slides 27-29 ↗
Slide 30, the summary with its three proved examples. slide 30 ↗

For node representations, \(f\) maps a graph to a matrix in \(\mathbb{R}^{|V|\times d}\): one \(d\)-dimensional embedding per node (slide 26). Now we cannot ask the output to stay identical under relabelling, because the rows are listed in the new order. What we want instead is shown on slides 27–28: take the brown node (called A in Order 1 and E in Order 2) — its embedding vector must be the same in both cases; likewise for the green node (C in Order 1, D in Order 2). In words: the vector of the node at the same position in the graph is the same; only its row index changes.

Slide 29 gives the definition:

\[ f:\mathbb{R}^{|V|\times|V|}\times\mathbb{R}^{|V|\times m}\to\mathbb{R}^{|V|\times d}\ \text{ is permutation equivariant if }\ P\,f(A,X)=f(PAP^{\top},PX)\ \text{ for every } P. \]

Slide 30 summarises both ideas and proves three examples:

  • Invariant (graph → vector): permute the input, the output stays the same.
  • Equivariant (graph → matrix): permute the input, the output is permuted in the same way.
  • \(f(A,X)=\mathbf{1}^{\top}X\) is invariant: \(f(PAP^\top,PX)=\mathbf{1}^\top PX=\mathbf{1}^\top X\), because \(\mathbf{1}^\top P=\mathbf{1}^\top\) (summing all rows does not care about their order).
  • \(f(A,X)=X\) is equivariant: \(f(PAP^\top,PX)=PX=Pf(A,X)\).
  • \(f(A,X)=AX\) is equivariant: \(f(PAP^\top,PX)=PAP^\top PX=PAX=Pf(A,X)\), using \(P^\top P=I\) (permutation matrices are orthogonal).
Check yourself: is \(f(A,X)=\mathbf{1}^\top AX\) invariant? show answer

(Yes: an invariant function applied after an equivariant one is invariant.) This composition rule is exactly how GNNs are built.

GNNs are stacks of equivariant layers; MLPs are not slides 31-34 ↗

Slide 31: a GNN is a composition of permutation-equivariant layers, optionally ending with an invariant readout. slide 31 ↗
Slide 32: shuffle the inputs of an MLP and its output changes. slide 32 ↗

Slide 31 (after Bronstein's ICLR 2021 keynote) states the structural principle: graph neural networks consist of multiple permutation equivariant / invariant functions. The figure shows the graph passing through several equivariant layers (yellow labels), each producing new node vectors on the same graph, and finally an invariant layer (blue label) that collapses everything to a single point — a graph-level output.

Slide 32 asks whether other architectures, for example MLPs, have this property. Answer: no. The figure shows the same three input numbers fed into an MLP in three different orders; the outputs differ. Switching the order of the input changes the output.

Slides 33–34 connect this to the naive approach of slide 17: this is exactly why feeding \([A,X]\) into an MLP fails for graphs — the MLP is neither invariant nor equivariant, and it also has a huge number of parameters and no inductive ability. Slide 34's green box gives the plan for the rest of the lecture: design graph neural networks that are permutation invariant / equivariant by passing and aggregating information from neighbours.

The GCN idea: a node's neighbourhood defines its computation graph slides 36-40 ↗

Slides 36–37 (Kipf and Welling 2017): the neighbourhood of the target node A defines its computation graph; grey boxes are small neural networks that aggregate the incoming vectors. slides 36-37 ↗
Slide 39: every node defines its own computation graph; the shapes differ because the neighbourhoods differ. Slide 40: a layer-k embedding sees k hops. slides 39-40 ↗

Slide 36 introduces Graph Convolutional Networks (Kipf and Welling, ICLR 2017). The idea in one sentence: a node's neighbourhood defines a computation graph. The left picture shows a target node \(i\) with rings at distance \(k=1\) and \(k=2\) (step "determine node computation graph"); the right picture shows information flowing along the edges towards \(i\) through two aggregators (step "propagate and transform information"). The goal: learn how to propagate information across the graph to compute node features.

Slide 37: the key idea is to generate node embeddings based on local network neighbourhoods. In the figure, target node A has neighbours B, C, D. To compute A, we take the vectors coming from B, C and D into a grey box; each of those is itself computed from its own neighbours (for example B from A and C; C from A, B, E, F; D from A).

Slide 38: nodes aggregate information from their neighbours using neural networks — every grey box is a small neural network.

Slide 39: every node defines its own computation graph based on its neighbourhood. The figure draws six different trees, one per node of the input graph. They have different shapes because the nodes have different neighbourhoods.

Slide 40: the model can be of arbitrary depth:

  • Nodes have embeddings at each layer.
  • The layer-0 embedding of node \(v\) is its input feature \(\mathbf{x}_v\).
  • The layer-\(k\) embedding gets information from nodes that are \(k\) hops away.

In the slide 40 tree for A: layer 2 is A itself; layer 1 is B, C, D; layer 0 holds the input features of their neighbours (\(\mathbf{x}_A,\mathbf{x}_C\) under B; \(\mathbf{x}_A,\mathbf{x}_B,\mathbf{x}_E,\mathbf{x}_F\) under C; \(\mathbf{x}_A\) under D). Note that A appears among its own leaves: the tree is an unrolling, and nodes repeat.

Depth here means the number of message-passing rounds, not the depth of the network inside each box. A 2-layer GNN sees exactly the 2-hop neighbourhood, however deep its inner MLPs are.

What is in the box? The GCN layer and its symmetry slides 41-46 ↗

Slide 43, the GCN layer annotated: average the neighbours, transform with W_k, add the transformed self vector, apply a non-linearity. slide 43 ↗
Slides 44–46: for one target node the GCN is permutation invariant; across all nodes it is equivariant, because every layer is built from an invariant aggregation plus shared weights. slides 44-46 ↗

Slide 41: different GNN models differ mainly in how they aggregate information across layers — "what is in the box?" Slide 42 gives the basic answer: (1) average the messages from neighbours, then (2) apply a neural network.

Slide 43 writes the full model (the "deep encoder"):

\[ \mathbf{h}_v^{(0)}=\mathbf{x}_v,\qquad \mathbf{h}_v^{(k+1)}=\sigma\Big(\mathbf{W}_k\sum_{u\in N(v)}\frac{\mathbf{h}_u^{(k)}}{|N(v)|}+\mathbf{B}_k\,\mathbf{h}_v^{(k)}\Big),\ \ k\in\{0,\dots,K-1\},\qquad \mathbf{z}_v=\mathbf{h}_v^{(K)}. \]

The annotations: \(\mathbf{h}_v^{(k)}\) is the embedding of \(v\) at layer \(k\); the fraction is the average of the neighbours' previous-layer embeddings; \(\sigma\) is a non-linearity (for example ReLU); \(K\) is the total number of layers; \(\mathbf{z}_v\) is the embedding after \(K\) layers of neighbourhood aggregation. The slide stresses that the summation (here, the average) is a permutation-invariant aggregation: the order of the neighbours does not matter.

Slides 44–46 check the symmetry of the whole GCN:

  • For one node (slide 44), the GCN that computes its embedding is invariant: the target node's tree uses shared weights, and the neighbour average does not care how the neighbours are ordered.
  • Over all nodes (slide 45), GCN computation is equivariant. The figure shows Order 1 and Order 2 of the graph, with feature matrices, adjacency matrices and output embedding matrices \(H_1, H_2\); the target node's row moves, but its colour (its vector) is the same.

Slide 46 spells out the argument in three steps: (1) the rows of the input features and of the output embeddings are aligned (row \(i\) in, row \(i\) out); (2) computing one node's embedding is invariant; (3) so after a permutation, a node's input row moves to a new position, and its output embedding — unchanged by step 2 — moves to the same position. That is equivariance.

Check yourself: replace the mean by "the first neighbour in the list". Which step of the argument breaks?

Model parameters and the matrix form slides 47-50 ↗

Slides 49–50: stacking the embeddings as rows turns the neighbour sum into A·H and the average into D⁻¹A·H, so one GNN layer is a sparse matrix product. slides 49-50 ↗

Slide 47 asks: how do we train the GCN to produce embeddings \(\mathbf{z}_A\)? We need a loss function on the embeddings.

Slide 48 repeats the update rule and highlights what is learned: the trainable weight matrices \(\mathbf{W}_k\) (for neighbourhood aggregation) and \(\mathbf{B}_k\) (for transforming the node's own hidden vector). \(\mathbf{h}_v^{(k)}\) is the hidden representation of \(v\) at layer \(k\), and \(\mathbf{z}_v=\mathbf{h}_v^{(K)}\) is the final embedding. We can feed these embeddings into any loss function and run SGD to train the weights.

Slide 49 shows that many aggregations are just (sparse) matrix operations. Stack the embeddings as rows: \(H^{(k)}=[\mathbf{h}_1^{(k)}\dots\mathbf{h}_{|V|}^{(k)}]^{\top}\). Then

\[ \sum_{u\in N(v)}\mathbf{h}_u^{(k)}=A_{v,:}\,H^{(k)} , \]

because row \(v\) of \(A\) has ones exactly at the neighbours of \(v\). Let \(D\) be the diagonal degree matrix, \(D_{v,v}=\deg(v)=|N(v)|\); its inverse is diagonal with \(D^{-1}_{v,v}=1/|N(v)|\). Therefore the neighbour average for all nodes at once is

\[ \Big[\textstyle\sum_{u\in N(v)}\frac{\mathbf{h}_u^{(k)}}{|N(v)|}\Big]_{v\in V}= D^{-1}AH^{(k)} . \]

Slide 50 rewrites the full update:

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

The red term \(\tilde A H^{(k)} W_k^\top\) is neighbourhood aggregation; the blue term \(H^{(k)}B_k^\top\) is self-transformation. The small figure shows red arrows from neighbours and a blue self-loop on the centre node. Since \(\tilde A\) is sparse, efficient sparse matrix multiplication can be used. Caveat on the slide: not all GNNs can be written in such a simple matrix form when the aggregation function is complex (for example attention or max).

Why \(W_k^\top\)? Each row of \(H\) is a row vector \(\mathbf{h}^\top\), and \((\mathbf{W}\mathbf{h})^\top=\mathbf{h}^\top\mathbf{W}^\top\).

Training a GNN: supervised and unsupervised losses slides 51-54 ↗

Slides 51–54: z_v is now a function of the graph, so any loss can sit on top; with labels use cross entropy, without labels use node similarity as the supervision. slides 51-54 ↗
Slide 54: the supervised loss, part by part: the GNN produces z_v, a linear classifier scores it, and cross entropy compares with the label. slide 54 ↗

Slide 51: the node embedding \(\mathbf{z}_v\) is a function of the input graph (and the weights). Two settings:

  • Supervised: minimise \(\min_\Theta \mathcal{L}(\mathbf{y}, f_\Theta(\mathbf{z}_v))\), where \(\mathbf{y}\) is a node label. \(\mathcal{L}\) can be L2 if \(y\) is a real number, or cross entropy if \(y\) is categorical.
  • Unsupervised: no node labels are available, so use the graph structure as the supervision.

Slide 52 gives one unsupervised idea: "similar" nodes should have similar embeddings,

\[ \min_{\Theta}\ \mathcal{L}=\sum_{z_u,z_v}\mathrm{CE}\big(y_{u,v},\,\mathrm{DEC}(\mathbf{z}_u,\mathbf{z}_v)\big), \]

where \(y_{u,v}=1\) when \(u\) and \(v\) are similar, \(\mathbf{z}_u=f_\Theta(u)\), and DEC is the dot product. The cross-entropy loss is \(\mathrm{CE}(\mathbf{y},f(\mathbf{x}))=-\sum_{i=1}^{C}y_i\log f_\Theta(\mathbf{x})_i\), with \(y_i\) and \(f_\Theta(\mathbf{x})_i\) the true and predicted values for class \(i\); the lower the loss, the closer the prediction is to the one-hot label. "Similar" can be anything from Lecture 2: random walks (node2vec, DeepWalk, struc2vec) or matrix factorisation. So DeepWalk with a GNN encoder is a valid model.

Slides 53–54 show the supervised case on an example: a drug–drug interaction network, where we want to classify each drug as "safe or toxic". Each drug's computation tree produces \(\mathbf{z}_v\), and the binary cross-entropy loss is

\[ \mathcal{L}=-\sum_{v\in V}\Big[y_v\log\big(\sigma(\mathbf{z}_v^{\top}\theta)\big)+(1-y_v)\log\big(1-\sigma(\mathbf{z}_v^{\top}\theta)\big)\Big]. \]

Slide 54 labels the parts: \(\mathbf{z}_v\) is the encoder output (node embedding), \(\theta\) are the classification weights, \(y_v\) is the node class label. The GNN weights and \(\theta\) are trained together, end to end.

Model design in four steps, and inductive capability slides 55-62 ↗

Slides 55–58: the four design steps, then the reason step 4 works: all compute graphs share the same per-layer parameters. slides 55-58 ↗
Slides 59–60, inductive capability: the trained aggregator transfers to a new graph, and a new node gets an embedding without retraining (Reddit, YouTube, Scholar). slides 59-60 ↗

Slides 55–57 summarise how to build and use a GNN, with a figure that grows step by step:

  1. Define a neighbourhood aggregation function (what is in the box).
  2. Define a loss function on the embeddings \(\mathbf{z}_A\).
  3. Train on a set of nodes, i.e. a batch of compute graphs (slide 56 shows three trees inside a pink box: the training nodes).
  4. Generate embeddings for nodes as needed — even for nodes we never trained on (slide 57 adds a blue box with new trees next to the training ones).

Slide 58 explains why step 4 works: the same aggregation parameters \(W_k, B_k\) are shared by all nodes. The figure shows the compute graph of node A and of node B; the boxes on the same level of both trees use the same "shared parameters". Consequence: the number of model parameters is sublinear in \(|V|\) (in fact independent of it), and we can generalise to unseen nodes.

Two kinds of inductive use:

  • New graphs (slide 59): train on one graph, generalise to an entirely unseen graph. Example: train on the protein interaction graph of model organism A and compute embeddings for newly collected data about organism B.
  • New nodes (slide 60): train with a snapshot; a new node arrives; compute its embedding. Reddit, YouTube and Google Scholar encounter new nodes all the time and need embeddings "on the fly", without retraining.

Slides 61–62 advertise GNN 101 (visual-intelligence-umn.github.io/GNN-101), a browser tool that visualises a GNN's inner workings at several levels of detail. Parameters are shown as heatmaps, the computation is animated, and hovering over a term in an equation highlights the matching part of the picture. Other functions: switch between GNN variants and tasks, and toggle between a node-link subgraph view and an adjacency-matrix view.

Inductive does not mean free: a new node's embedding still depends on its neighbours' features, so a node with no edges and no features gets an uninformative embedding.

GNNs subsume CNNs slides 64-68 ↗

Slides 65–68: write the convolution as message passing from the 8 neighbour pixels and the two formulas line up; the CNN only differs by having a separate weight per neighbour position. slides 65-68 ↗

Slide 64 asks how GNNs compare with Convolutional Neural Networks. Slide 65 shows a CNN layer with a \(3\times3\) filter sliding over an image (animation by Vincent Dumoulin) and writes it as

\[ \mathbf{h}_v^{(l+1)}=\sigma\Big(\sum_{u\in N(v)\cup\{v\}}\mathbf{W}_l^{\,u}\,\mathbf{h}_u^{(l)}\Big),\quad l\in\{0,\dots,L-1\}, \]

where \(N(v)\) is the set of 8 neighbour pixels of \(v\). Slide 66 draws the same pixel as a node in a graph with 8 neighbours plus a self-loop, and puts the two formulas side by side:

\[ \text{GNN: }\ \mathbf{h}_v^{(l+1)}=\sigma\Big(\mathbf{W}_l\sum_{u\in N(v)}\frac{\mathbf{h}_u^{(l)}}{|N(v)|}+\mathbf{B}_l\mathbf{h}_v^{(l)}\Big),\qquad \text{CNN (rewritten): }\ \mathbf{h}_v^{(l+1)}=\sigma\Big(\sum_{u\in N(v)}\mathbf{W}_l^{\,u}\mathbf{h}_u^{(l)}+\mathbf{B}_l\mathbf{h}_v^{(l)}\Big). \]

Slide 67 names the key difference: a CNN can learn a different weight \(\mathbf{W}_l^{\,u}\) for each neighbour \(u\) of pixel \(v\), because pixels can be put in a fixed order by their position relative to the centre: \(\{(-1,-1),(-1,0),(-1,1),\dots,(1,1)\}\). A graph has no such reference frame, so the GNN must use one shared \(\mathbf{W}_l\) and an order-free aggregation.

Slide 68 draws the conclusion:

  • A CNN is a special GNN with fixed neighbour size and ordering. The size of the filter is pre-defined in a CNN; the advantage of a GNN is that it processes arbitrary graphs where each node has a different degree.
  • A CNN is not permutation invariant/equivariant: switching the order of pixels leads to different outputs. On an image this is a feature, not a bug — "left of" really means something.

Transformers as GNNs, and the lecture summary slides 69-72 ↗

Slides 69–71: self-attention lets each token aggregate all others, so a Transformer layer is a GNN on a fully connected graph of words. slides 69-71 ↗

Slide 69 introduces the Transformer (Vaswani et al., "Attention is all you need", NeurIPS 2017), one of the most popular architectures for sequence modelling. Its key component is self-attention: every token attends to all the other tokens via matrix calculations. The figure shows the sentence "I am a Stanford student" with curved arrows from each word to every other word.

Slide 70 defines attention in general: given a set of vector values and a vector query, attention computes a weighted sum of the values, dependent on the query. Each token has a value vector (its representation) and a query vector (used to compute the attention scores, i.e. the weights in the sum). The figure shows two sentences, "The animal didn't cross the street because it was too tired" and "… too wide". In the first, the word "it" puts most attention on "animal"; in the second, on "street". The weights depend on the content, not on a fixed position.

Slide 71 gives the punchline: a Transformer layer is a special GNN that runs on a fully connected "word" graph. Since each word attends to all other words, the computation graph of a Transformer layer is identical to that of a GNN on the complete graph whose nodes are the words, with attention scores as the (learned, data-dependent) aggregation weights. A blog post explaining this is linked on the slide.

Slide 72 summarises the lecture:

  • Deep learning for graphs: multiple layers of embedding transformation; at every layer, the embedding from the previous layer is the input; each layer aggregates neighbour and self embeddings.
  • Graph Convolutional Network: mean aggregation; can be expressed in matrix form.
  • GNN is a general architecture: a CNN can be viewed as a special GNN (and so can a Transformer).
Check yourself: self-attention on a set of tokens without positional encodings is permutation equivariant. Why? show answer

Hint: the weights are computed from the token vectors only, and the sum over "all other tokens" has no order.

Refresher: machine learning as optimisation, gradient descent and SGD slides 74-80 ↗

Slides 76–80: cross entropy on a one-hot label, the training-set loss, and the gradient-descent and SGD updates. slides 76-80 ↗

The last part of the deck is a deep-learning refresher. Slide 74: in supervised learning we are given an input \(\mathbf{x}\) and want to predict a label \(\mathbf{y}\). The input can be a vector of real numbers, a sequence (natural language), a matrix (images), or a graph (possibly with node and edge features). We formulate the task as an optimisation problem.

Slide 75: \(\min_\Theta \mathcal{L}(\mathbf{y},f(\mathbf{x}))\) is the objective function. \(\Theta\) is the set of parameters (scalars, vectors, matrices; for example \(\Theta=\{Z\}\) in the shallow encoder). \(\mathcal{L}\) is the loss, for example the L2 loss \(\mathcal{L}(\mathbf{y},f(\mathbf{x}))=\lVert\mathbf{y}-f(\mathbf{x})\rVert_2\); others include L1, Huber, max-margin (hinge) and cross entropy.

Slide 76 works through cross entropy for classification. The label is one-hot, e.g. \(\mathbf{y}=(0,0,1,0,0)\) for class 3. The model outputs probabilities with a softmax, \(f(\mathbf{x})_i=e^{g(\mathbf{x})_i}/\sum_{j=1}^{C}e^{g(\mathbf{x})_j}\), e.g. \(f(\mathbf{x})=(0.1,0.3,0.4,0.1,0.1)\). Then

\[ \mathrm{CE}(\mathbf{y},f(\mathbf{x}))=-\sum_{i=1}^{C}y_i\log f(\mathbf{x})_i ,\qquad \mathcal{L}=\sum_{(\mathbf{x},\mathbf{y})\in\mathcal{T}}\mathrm{CE}(\mathbf{y},f(\mathbf{x})) \]

over the training set \(\mathcal{T}\). In the example only the class-3 term survives, giving \(-\log 0.4\).

Slide 77: the gradient \(\nabla_\Theta\mathcal{L}=(\partial\mathcal{L}/\partial\Theta_1,\partial\mathcal{L}/\partial\Theta_2,\dots)\) is the directional derivative in the direction of largest increase. Slide 78: gradient descent repeats \(\Theta\leftarrow\Theta-\eta\nabla_\Theta\mathcal{L}\). One step is an iteration. The learning rate \(\eta\) is a hyperparameter controlling the step size and can change during training (LR scheduling). Ideally we stop when the gradient is 0; in practice we stop when performance on a held-out validation set stops improving.

Slide 79: exact gradients need a sum over the entire dataset, which can have billions of points, so each step is very expensive. SGD instead uses a different random minibatch \(\mathcal{B}\) at each step. Slide 80 defines batch size (number of points per minibatch, e.g. number of nodes for node classification), iteration (one SGD step) and epoch (one full pass over the data; #iterations per epoch = dataset size / batch size). SGD is an unbiased estimator of the full gradient, but there is no guarantee on the rate of convergence, and the learning rate usually needs tuning. Improved optimisers: Adam, Adagrad, Adadelta, RMSprop.

Refresher: back-propagation, non-linearity and the MLP slides 81-88 ↗

Slides 83–87: back-propagation on a two-layer network, the two standard non-linearities, and the MLP layer. slides 83-87 ↗

Slide 81: in deep learning \(f\) can be very complex. Start simple with a linear function \(f(\mathbf{x})=W\cdot\mathbf{x}\), \(\Theta=\{W\}\). If \(f\) returns a scalar, \(W\) is a vector and \(\nabla_W f=(\partial f/\partial w_1,\partial f/\partial w_2,\dots)\). If \(f\) returns a vector, \(W\) is a matrix and \(\nabla_W f\) is the Jacobian, with entries \(\partial f_i/\partial w_{jk}\).

Slide 82: to minimise \(\mathcal{L}\) we need its gradient. Back-propagation works because \(\mathcal{L}\) is built from predefined building-block functions \(g(\cdot)\), each with a known derivative \(g'\); we evaluate these derivatives on the minibatch and combine them automatically.

Slide 83 uses the chain rule, \(\frac{df}{dx}=\frac{dg}{dh}\cdot\frac{dh}{dx}\), i.e. \(f'(x)=g'(h(x))\,h'(x)\), on \(f(\mathbf{x})=W_2(W_1\mathbf{x})\) with \(h(\mathbf{x})=W_1\mathbf{x}\) and \(g(\mathbf{z})=W_2\mathbf{z}\); for example \(\nabla_{\mathbf{x}}f=\frac{\partial f}{\partial(W_1\mathbf{x})}\cdot\frac{\partial(W_1\mathbf{x})}{\partial\mathbf{x}}\). Back-propagation = use the chain rule to propagate gradients of intermediate steps and finally get the gradient of \(\mathcal{L}\) with respect to \(\Theta\).

Slides 84–85 give the example of a 2-layer linear network with inputs \(x_1,x_2\). The loss sums the L2 loss over a minibatch: \(\mathcal{L}=\sum_{(\mathbf{x},\mathbf{y})\in\mathcal{B}}\lVert\mathbf{y}-f(\mathbf{x})\rVert_2\). The hidden layer \(h(\mathbf{x})=W_1\mathbf{x}\) is an intermediate representation, and \(f(\mathbf{x})=W_2h(\mathbf{x})\). Forward propagation goes \(\mathbf{x}\to h\) (multiply by \(W_1\)) \(\to g\) (multiply by \(W_2\)) \(\to\mathcal{L}\). Back-propagation starts from the loss and computes backwards:

\[ \frac{\partial\mathcal{L}}{\partial W_2}=\frac{\partial\mathcal{L}}{\partial f}\cdot\frac{\partial f}{\partial W_2},\qquad \frac{\partial\mathcal{L}}{\partial W_1}=\frac{\partial\mathcal{L}}{\partial f}\cdot\frac{\partial f}{\partial W_2}\cdot\frac{\partial W_2}{\partial W_1}. \]

(The second formula is the slide's shorthand; read it as "reuse \(\partial\mathcal{L}/\partial f\) and push it one more step back through \(W_2\) to the hidden layer, then to \(W_1\)".) The shared factor \(\partial\mathcal{L}/\partial f\) is computed once and reused — that reuse is why back-propagation is efficient.

Slide 86: \(W_2W_1\) is just another matrix, so \(f(\mathbf{x})=W_2W_1\mathbf{x}\) is still linear in \(\mathbf{x}\) no matter how many matrices we stack. We need non-linearity: ReLU \(\mathrm{ReLU}(x)=\max(x,0)\) (plot: zero for negative \(x\), the identity for positive) or the sigmoid \(\sigma(x)=1/(1+e^{-x})\) (an S-shaped curve from 0 to 1).

Slide 87: each layer of a multi-layer perceptron (MLP) combines a linear transformation and a non-linearity, \(\mathbf{x}^{(l+1)}=\sigma(W_l\mathbf{x}^{(l)}+\mathbf{b}^{l})\), where \(W_l\) maps layer \(l\) to layer \(l+1\) and \(\mathbf{b}^{l}\) is the bias. The figure: a 2-dimensional input \((x_1,x_2)\), a 3-dimensional hidden layer, a 1-dimensional output. Slide 88 repeats the full training recipe from slide 13: objective, minibatch, forward pass, back-propagation, SGD over many iterations.

Connection to the GNN: the "neural network in the box" of slide 42 is exactly one such MLP layer, \(\sigma(W\cdot\text{average}+B\cdot\text{self})\). Back-propagation flows through the computation tree of every training node, and the gradients for the shared \(W_k,B_k\) are summed over all the places where they appear.

Not shown (no new content): slides 1,2,12,14,35,63,73,89 — title page, announcements, outline slides and section-divider title pages that only repeat headings.

Review: what to keep from this session

Carried forward. Lecture 4 generalises this layer into a design space (message, aggregation, layer connectivity); Lecture 5 adds the training pipeline; Lecture 6 asks how expressive this aggregation can be.

Quick self-check

Why can a GNN embed a node it has never seen?

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 goes wrong if the aggregation is not permutation invariant?

The embedding would depend on the arbitrary order in which the neighbours are listed, so the same graph could receive different embeddings.

What does the self-loop (or the B matrix) do in the GCN layer?

It keeps the node's own previous vector in the update, so a node does not forget its own features while absorbing its neighbours'.

Key idea

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.

Worked example: one GCN layer by hand

Graph: edges 1–2, 1–3, 2–3, 3–4. Scalar features \(x=(1,2,3,4)\). Take \(W=1, B=1\), identity non-linearity.

  1. Neighbour means: node 1: \((2+3)/2=2.5\); node 2: \((1+3)/2=2\); node 3: \((1+2+4)/3\approx2.33\); node 4: \(3\).
  2. Add self: \(h^{(1)}=(3.5,\;4,\;5.33,\;7)\).
  3. Matrix check: \(D=\mathrm{diag}(2,2,3,1)\); \(D^{-1}A\,x\) gives exactly the neighbour means above.
  4. Relabel nodes 1↔4: you get the same four numbers, permuted the same way → equivariance in action.
  5. Second layer: node 1 now sees \(h^{(1)}_2,h^{(1)}_3\), which already contain node 4's feature → after 2 layers, node 1 "knows" node 4 (2 hops away).

Strictly speaking: with real weights \(W_k\in\mathbb{R}^{d_{k+1}\times d_k}\) and ReLU, the same structure holds per dimension. Notice also that repeated averaging pulls values together: iterate \(D^{-1}A\) many times and all nodes converge — the over-smoothing problem you prove in HW1 Q1.5.

In code (PyG)

import torch, torch.nn.functional as F
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
    def __init__(self, d_in, d_hid, n_cls):
        super().__init__()
        self.c1, self.c2 = GCNConv(d_in, d_hid), GCNConv(d_hid, n_cls)
    def forward(self, x, edge_index):
        x = F.relu(self.c1(x, edge_index))      # layer 1: aggregate 1-hop
        x = F.dropout(x, 0.5, self.training)
        return self.c2(x, edge_index)           # layer 2: now 2-hop
# loss = F.cross_entropy(out[data.train_mask], data.y[data.train_mask])

Proof workshop: Equivariance is one line of algebra

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. For a permutation matrix \(P\), relabelling a graph sends \((A,X)\mapsto(PAP^\top,PX)\). Prove that (a) \(f(A,X)=\sigma(AXW)\) is permutation equivariant, \(f(PAP^\top,PX)=Pf(A,X)\); (b) \(g(A,X)=\mathbf 1^\top f(A,X)\) is invariant; (c) a stack of equivariant layers is equivariant. Then find a 2-node example showing that an MLP on the flattened adjacency matrix \(\mathrm{vec}(A)\) is not invariant.

Hint 1
\(P^\top P=I\) and an element-wise \(\sigma\) commutes with permuting rows.
Hint 2
For (b): \(\mathbf 1^\top P=\mathbf 1^\top\). For the counterexample, take a directed edge \(1\to2\) and swap the two nodes.
Solution
(a) \(\sigma(PAP^\top PXW)=\sigma(PAXW)=P\sigma(AXW)\). (b) \(\mathbf 1^\top Pf=\mathbf 1^\top f\). (c) If \(f_1,f_2\) are equivariant, \(f_2(PAP^\top,f_1(PAP^\top,PX))=f_2(PAP^\top,Pf_1(A,X))=Pf_2(A,f_1(A,X))\). Counterexample: with \(A=\begin{pmatrix}0&1\\0&0\end{pmatrix}\), swapping gives \(\begin{pmatrix}0&0\\1&0\end{pmatrix}\); \(\mathrm{vec}\) changes from \((0,1,0,0)\) to \((0,0,1,0)\), and the MLP \(x\mapsto x_2\) outputs 1 then 0. \(\square\)

Why it matters. This is the whole design principle of the course: build layers that commute with relabelling, then any stack of them is safe. Everything that breaks equivariance on purpose later (node IDs, Laplacian eigenvectors, anchors in Lecture 7) pays a price in generalisation for a gain in expressiveness.

Sharper lens: how much room equivariance leaves

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

Counting the linear equivariant layers: 2 for sets, 15 for graphs

How many linear maps commute with every relabelling? For a set of scalars, \(\mathbb R^n\to\mathbb R^n\), exactly a 2-dimensional family: \(L=a\,I+b\,\mathbf 1\mathbf 1^\top\) (DeepSets, Zaheer et al. 2017). For a graph given as a matrix, \(\mathbb R^{n\times n}\to\mathbb R^{n\times n}\), Maron et al. (ICLR 2019) found a 15-dimensional family, for every \(n\ge4\). In general the equivariant linear maps \(\mathbb R^{n^k}\to\mathbb R^{n^l}\) have dimension \(\mathrm{Bell}(k+l)\), the number of set partitions of \(k+l\) elements: 2, 5, 15, 52, …

Why Bell numbers? (prove the case of sets first)
\(PL=LP\) for all permutations means \(L_{\pi(i)\pi(j)}=L_{ij}\): the entry depends only on the orbit of the index pair \((i,j)\) under \(S_n\). There are two orbits, \(i=j\) and \(i\ne j\), so \(L=a\,I+b'(\mathbf 1\mathbf 1^\top-I)\). For tensors the entries of \(L\) are indexed by \(k+l\) indices, and an orbit is decided by which indices are equal to which, that is, by a set partition of the \(k+l\) positions. One free parameter per partition gives \(\mathrm{Bell}(k+l)\).

The message-passing layer \(X\mapsto AX\) uses a small corner of this space. The rest (row and column sums, diagonals, transposes) is what "higher-order" GNNs use to pass the WL ceiling of Lecture 6, at \(O(n^2)\) memory.

second viewpoint

The same layer, read in the frequency domain

With self-loops, \(\hat A=I-\tilde L\), where \(\tilde L\) is the normalised Laplacian of the graph with self-loops. Expand a signal in the eigenvectors of \(\tilde L\): the component with eigenvalue ("frequency") \(\lambda\) is multiplied by \(1-\lambda\) in one layer and by \((1-\lambda)^K\) after \(K\) layers. Smooth components (\(\lambda\approx0\)) survive and oscillating ones die: a GCN layer is a low-pass filter. The self-loop matters: it shrinks the largest frequency below 2, so no component is multiplied by a number near \(-1\) and flipped at every layer (Wu et al. 2019).

Historically this was the route to the layer: spectral convolutions (Bruna et al. 2014), Chebyshev polynomial filters (Defferrard et al. 2016), and Kipf and Welling's first-order truncation. The lecture's "computation graph" story and the filter story describe one operator, and the second explains two later facts at once: over-smoothing (Lecture 4) is \((1-\lambda)^K\to0\), and such a layer helps on homophilous graphs, where labels are smooth signals, and hurts on heterophilous ones.

where it breaks

"K layers see K hops" hides how little they see

The receptive field is the set of nodes that can influence \(v\). How much they do is another matter. For a mean-aggregation GNN the expected sensitivity \(\partial\mathbf h_v^{(K)}/\partial\mathbf x_u\) is proportional to the probability that a \(K\)-step random walk from \(v\) ends at \(u\) (Xu et al. 2018, the Jumping Knowledge paper). In a neighbourhood that grows like \(d^K\), one distant node gets weight about \(d^{-K}\). A node being inside the receptive field therefore says little. Lecture 4's Sharper lens has an interactive version, and the two names for what goes wrong: under-reaching (too few layers to reach \(u\) at all) and over-squashing (enough layers, but \(u\)'s signal arrives divided by an exponential).

Lab: hands-on and practical tips

Try it live. In the Graph Explorer: watch a pulse spread one hop per layer and train a GCN on four labels. Each lesson has predict-then-check questions.

notebook · L03 GNNs computes one GCN layer by hand, tests equivariance numerically, implements GCN from scratch (matches PyG's GCNConv to 3e-8) and trains on Cora: GCN ≈ 0.79 vs MLP ≈ 0.54 with 140 labels.

Normalise, or your activations scale with degreePlain sum aggregation multiplies the signal by roughly the degree at every layer. In the notebook, five unnormalised layers on the karate club send hub node 0 to 25,499 and leaf node 11 to 3,390; with the symmetric GCN normalisation they stay at 1.69 and 0.58. Sum is the most expressive aggregator (Lecture 6), so scale it rather than drop it.
Over-smoothing is visible after two layersPlay with the mean-aggregation figure above: the spread of node values shrinks every layer, and repeated averaging converges to a degree-weighted constant. This is DeGroot consensus; the stubborn variant in Lecture 4 is the fix.
Inductive means weights, not nodesThe same \(W_k, B_k\) run on any graph. Test it: train on one half of Cora's nodes, score the other half with their edges included, and compare to the transductive number (the notebook finds them equal). Shallow embeddings cannot even attempt this test.
A two-layer GCN in six lines
class GCN(torch.nn.Module):
    def __init__(s, d, h, c): super().__init__(); s.c1, s.c2 = GCNConv(d, h), GCNConv(h, c)
    def forward(s, x, ei):
        x = F.dropout(F.relu(s.c1(x, ei)), 0.5, s.training)
        return s.c2(x, ei)
Everything else in the course is a change to what happens inside c1.

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 Kipf & Welling — Semi-Supervised Classification with Graph Convolutional Networks (ICLR 2017)

arXiv:1609.02907 · 14 pages · ~2 h · one of the most-cited ML papers of the decade
  • Read: §2 (the layer rule, Eq. 2, and the "renormalisation trick" \(A+I\)), §3 (the 2-layer model, Eq. 9 — memorise it).
  • Understand, don't derive: §2.1–2.2 — the path from spectral convolutions (Chebyshev polynomials, ChebNet) to the first-order approximation. This explains the word "convolutional".
  • Skim: §5 experiments (Cora, Citeseer, Pubmed — the classic citation benchmarks).

big picture Bronstein — Geometric Deep Learning: The Erlangen Programme of ML (ICLR 2021 keynote)

talk (~45 min) · companion book: Bronstein, Bruna, Cohen, Veličković, Geometric Deep Learning (arXiv:2104.13478)
  • Watch the talk once now; it gives you the "symmetry first" lens for the whole course.
  • Lookup in the book: §3 (geometric priors: invariance, equivariance, scale separation) and §5.3 (GNNs: convolutional / attentional / message-passing flavours — a taxonomy you'll meet again in Lecture 4).

textbook Hamilton, GRL book — Chapter 5 (The GNN model)

~25 pages
  • §5.1 neural message passing, §5.2 generalised neighbourhood aggregation (normalisation, set pooling), §5.3 update methods. Clearer than most papers.

Homework & Colabs connected to this lecture

Homework 1 · Q1 (GNN expressiveness) and Q3 (GCN) due Thu 10/15

  • Q1.1 How many layers before two nodes with different neighbourhoods get different embeddings? (Think: the computation tree must differ.)
  • Q1.3–1.4 Mean aggregation without weights ⇔ one step of a random walk: transition matrix \(D^{-1}A\); with a skip connection it becomes \(\tfrac12 I+\tfrac12 D^{-1}A\) (a lazy walk).
  • Q1.5 Over-smoothing: show \(h^{(l)}\) converges as \(l\to\infty\) for a connected, non-bipartite graph (irreducible + aperiodic Markov chain).
  • Q1.6 Design message/aggregate/update so a GNN executes BFS exactly (hint: max aggregation of 0/1 flags).
  • Q3 (with Lecture 6) isomorphism, sum vs mean vs max aggregation, and the WL upper bound.

Colab 2 (out Thu 10/8) preview

In previous offerings Colab 2 implemented a GCN in PyG for node property prediction on OGB ogbn-arxiv and graph property prediction on ogbg-molhiv. This lecture's code snippet is the core of it.

Self-check

Which function is permutation invariant?

  1. \(f(A,X)=AX\)
  2. \(f(A,X)=\mathbf{1}^\top X\)
  3. \(f(A,X)=X\)
  4. \(f(A,X)=A\)

\(\mathbf{1}^\top PX=\mathbf{1}^\top X\). The others are equivariant (or, for A, change to \(PAP^\top\)).

Why can a GCN embed a node that wasn't in the training graph?

  1. It stores one embedding per node
  2. It uses random walks at test time
  3. It uses the adjacency matrix as input features
  4. Its weights are shared across nodes and depend only on the local neighbourhood

Shared \(W_k,B_k\) + local computation graph ⇒ inductive.

A 3-layer GNN's embedding of node v depends on …

  1. nodes at most 3 hops from v
  2. exactly the nodes 3 hops away
  3. the whole graph
  4. only v's direct neighbours

Receptive field = K-hop neighbourhood (including closer nodes).

What prevents a GNN from learning a different weight per neighbour, as a CNN does?

  1. Memory limits
  2. Non-linearity
  3. Neighbours have no canonical order or fixed number
  4. Sparse adjacency

CNNs index neighbours by relative position; graphs can't.

In \(H^{(k+1)}=\sigma(D^{-1}AH^{(k)}W^\top+H^{(k)}B^\top)\), what does \(D^{-1}A\) do to \(H\)?

  1. Sums neighbours
  2. Averages neighbours
  3. Applies attention
  4. Normalises features to unit length

Row \(v\) of \(D^{-1}A\) has \(1/|N(v)|\) at each neighbour.

Flashcards (click to flip)

Equivariance (definition)
\(f(PAP^\top,PX)=Pf(A,X)\) for every permutation \(P\).
GCN layer (lecture form)
\(h_v^{k+1}=\sigma(W_k\,\mathrm{mean}_{u\in N(v)}h_u^k+B_kh_v^k)\)
Kipf–Welling normalisation
\(\tilde D^{-1/2}(A+I)\tilde D^{-1/2}\)
Why the naive MLP on [A, X] fails
O(|V|) params, fixed size only, sensitive to node order.
CNN vs GNN
CNN: weight per relative position. GNN: one shared weight, order-free aggregation.
Transformer as GNN
Message passing on the complete token graph with attention weights.

History & the bigger picture

  • 1997–2009 — early recursive/graph neural networks (Sperduti & Starita 1997; Gori, Monfardini, Scarselli 2005/2009): iterate a contraction map to a fixed point. Elegant, slow, ahead of the hardware.
  • 2013–2016 — spectral GNNs: Bruna et al. define convolution via the graph Laplacian's eigenvectors; Defferrard et al. (ChebNet) make it local with polynomials.
  • 2017 — the Cambrian year: GCN (Kipf & Welling), GraphSAGE (Hamilton et al.), MPNN (Gilmer et al., quantum chemistry), GAT (Veličković et al.). GCN is a first-order ChebNet — spectral and spatial views meet.
  • 2018–2019 — industrial adoption: PinSage at Pinterest (3 billion nodes); PyTorch Geometric and DGL make GNNs routine.
Philosophy · local rules, global behaviour

A GNN is a learned cellular automaton on an irregular lattice: identical local rules everywhere, global behaviour emerging from repetition. The same intellectual move appears in statistical physics (Ising models), in sociology (Schelling's segregation model — local preferences, global segregation) and in distributed computing (the LOCAL model, where what a node can compute in \(k\) rounds is exactly a function of its \(k\)-hop neighbourhood — a result GNN theorists later borrowed, see Loukas 2020).

Classic SNA bridge

In this lectureClassic SNA counterpartWhat carried over, what changed
Mean aggregation \(h_v \leftarrow \text{mean}_{u\in N(v)} h_u\)DeGroot (1974) opinion averaging; French (1956) and Harary (1959) on social powerIdentical update rule. DeGroot proved convergence to a consensus weighted by eigenvector centrality; that theorem is the over-smoothing result of Lecture 4, sixty years earlier.
A node's neighbourhood defines its computation graphEgo networks (Burt 1980s); the "local structure determines behaviour" thesis of structural sociologySNA measured ego networks by hand (density, constraint). A GNN learns which ego-network statistics matter, but only up to \(K\) hops: it cannot see global position (Lecture 7).
Weight sharing and inductivenessComparative network analysis: the same measure applied to every networkCentrality measures were always "inductive". Shallow embeddings lost that property; GNNs restore it, which is why they can score a brand-new account.
Permutation equivarianceStructural invariants; the taboo on using node labels in a structural measureWhat SNA enforced by convention, GNNs enforce by architecture.
Node features + structureAttribute homophily vs structural effects; "contextual" vs "compositional" effects in network autocorrelation models (Doreian 1989)Network autocorrelation models \(y = \rho W y + X\beta + \epsilon\) already mixed neighbours' outcomes with own attributes. A GCN layer \(\sigma(\tilde A X W)\) is a non-linear, multi-layer version of \(W X \beta\).
Bridge idea

Write the spatial autoregressive model \(y=\rho Wy+X\beta\) and a one-layer linear GCN side by side. Which parameter of the GCN plays \(\rho\)? What does the GCN lack (an explicit error term, hence no identification) and what does the SAR model lack (non-linearity, depth)? The comparison is a good first section for a thesis chapter bridging statistical SNA and graph ML.

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 2 · Homophily, balance & brokerage (message passing as neighbour averaging, and what it assumes about neighbours); Unit 8 · Epidemics & opinion dynamics (a GCN layer is one DeGroot step with learned weights); Unit 10 · Causality, interference & graph ML (the GCN layer the unit averages opinions with).

Connecting to your research

Running project. Section L02–L04 · community 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/rings-in-communities (hypotheses written before running): the same world through community detection and the Laplacian spectrum: reciprocal rings are their own communities and eigenvectors; co-amplification rings hide.

For SNA and neuro-symbolic directions
  • Inductiveness matters on Twitter: new accounts appear constantly; a GCN/GraphSAGE model can score a brand-new account from its first follows and its profile features — shallow embeddings cannot.
  • Over-smoothing as a social metaphor: repeated averaging is DeGroot's 1974 model of opinion dynamics (everyone updates to the average of their friends). Consensus in DeGroot = over-smoothing in GCNs. That bridge between social-influence models and GNN layers is a fertile proposal direction.
  • Neuro-symbolic: Q1.6 (BFS with a GNN) is a first taste of algorithmic alignment — GNNs that execute classical algorithms (Veličković's neural algorithmic reasoning).

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.

rings-in-communities

Question. Do coordinated rings look like tiny communities, or hide inside real ones? experiment folder ↗

Rings in 6 synthetic worlds. Unsupervised spectral localisation AUC 0.623 (co-amplify), 0.997 (reciprocal); a ring's conductance against random account sets of the same size (lower = more community-like).

design-transfer

Question. Are the best GNN designs on Cora also the best for bot detection and for real social networks? experiment folder ↗

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

96 GNN designs × 3 seeds per task. τ with Cora: CiteSeer +0.69, bots-reciprocal +0.17, bots-co-amplify -0.21, facebook-pages +0.32, lastfm-asia +0.39, twitch-en +0.08, deezer-europe +0.10. Read each τ against its task's ceiling.

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
karateZachary's karate club34club after the split (2)community detection, the course's running toy graph
twitch-enTwitch users, England (mature content)7,126streams mature content (2)a heterophilous social task; also DE, ES, FR, PTBR, RU for shift
lastfm-asiaLastFM Asia friendships7,624country (18)a homophilous social task
deezer-europeDeezer Europe friendships28,281gender (2)a hard heterophilous social task
facebook-pagesFacebook page-page (verified pages)22,470page type (4)a strongly homophilous social task
penn94Facebook100: Penn9441,554gender (2; 0 = missing)heterophily in a real friendship graph
coraCora citations2,708topic (7)the default GNN benchmark

Frontier 2025–26: what changed since the slides

ICML 2025Tuned classic GNNs match graph transformers — Luo, Shi & Wu gave GCN, GIN and GatedGCN six standard ingredients (edge features, normalisation, dropout, residuals, a feed-forward block, positional encodings) and ranked first on 8 of 14 graph-level datasets while running several times faster. The GCN of this lecture, properly trained, is still a top baseline in 2026.sources: arXiv:2502.09263
NeurIPS 2025 spotlightMessage Passing Complexity — Kemper, Wollschläger & Günnemann measure how hard a task is for message passing rather than only whether two graphs can be told apart; real tasks "rarely require expressivity beyond the basic WL test". The computation-graph picture of this lecture is the object their measure is defined on.sources: arXiv:2509.01254
ICML 2026 oralWhich algorithms can GNNs learn? — Wittig et al. give conditions under which training on small graphs provably generalises to any size (shortest paths, MST, knapsack) and prove some tasks unlearnable. Homework 1's "BFS with a GNN" exercise is the toy version of this research front (neural algorithmic reasoning).sources: arXiv:2602.13106
ICML 2026 spotlightBeyond ReLU: bifurcation, over-smoothing and topological priors — Among the 2026 papers on the pathologies of local aggregation, this one links the choice of non-linearity to whether depth collapses the representation. The lecture's \(\sigma\) is not a detail.sources: arXiv:2602.15634
Atlas · 2025–26The audits — Over-smoothing was found "mostly uncorrelated" with accuracy on common benchmarks (Kormann et al., venue unconfirmed) and a 2026 ICLR paper refuted several universal statements about depth and heterophily with formal counterexamples. The mathematics of this lecture was right; the empirical folklore built on it was not always.sources: arXiv:2505.15547
Open question to carryIf one GCN layer is a smoothing step and SGC (no non-linearities) often matches GCN, what exactly does the non-linearity buy, and on which graphs?
Frontiers · GCN is ChebNet simplified · watch message passing · tuned GNNs match transformers

Words & phrases

TermSimple meaningPersianIn context
subsumev.to include something as a special case of something largerدر بر گرفتن، شامل شدن"GNNs subsume CNNs and Transformers"
unrollingn.writing a repeated (recursive) computation out step by step as a tree or chainباز کردن (گسترش) محاسبهٔ بازگشتی"the tree is an unrolling, not the graph itself"
on the flyidiomimmediately, while the system is running, without preparing in advanceدرجا، در لحظه"compute their embeddings on the fly"
permutationn.a reordering; here, a relabelling of the nodesجایگشت"the output must not depend on the permutation of the nodes"
invariantadj.unchanged when the input is transformed (here, when nodes are relabelled)ناوردا"a graph-level readout must be invariant"
receptive fieldn.the set of nodes whose features can influence a node's outputمیدان دریافت"k layers give a k-hop receptive field"
weight sharingn.using the same parameters at every node, so the model size does not grow with the graphاشتراک وزن"weight sharing makes the GNN inductive"

Go deeper

  • Next: Lecture 4 — a general "message + aggregation" design space that contains GCN, GraphSAGE and GAT as points.
  • Original source: Gilmer et al. (2017), "Neural Message Passing for Quantum Chemistry" — coins the MPNN framework that Lecture 4 formalises.
  • Connection: Wu et al. (2019), "Simplifying GCN" (SGC) — drop the non-linearities, keep \(\hat A^K X W\), and accuracy barely drops. Ask yourself why; then compare with NetMF from Lecture 2.