Graph Neural Networks

A graph neural network computes each node's vector from its neighbours, with the same weights for every node. Told the sides of only members 1 and 34, a two-layer GCN places 30.2 of the other 32 karate members right. With no graph it places 15.7; with shuffled friendships, 12.0. All three are averages over 200 runs.

Press Train and watch two known sides spread through the club. Then take the graph away, then shuffle the friendships. Then we build it piece by piece: the layer, the tree, the normalization, the matrix form, its gradient, and new members.

You need a little Python, matrix multiplication and what a gradient is. Lectures 1 and 2 help. We build the rest from zero.

Lecture 3, "Graph neural networks", of Stanford CS224W, Machine Learning with Graphs (Fall 2026, Jure Leskovec, with guest instructor Charilaos Kanatsoulis), slides. Previous: Lecture 2, Node Embeddings. Next: Lecture 4, A General Perspective on GNNs.

Spread two labels through the club

100 steps

Illustrative toy on real ties: Zachary's 34 members and 78 friendships (via NetworkX). The club has no node features, so each member's input is one-hot, as in Kipf and Welling's karate example. The GCN trains in your browser: two layers, 4 hidden numbers, tanh, Adam at 0.01, 100 full-batch steps, cross-entropy on members 1 and 34 only. "No graph" is the same network with the identity in place of the graph. The bars are this run; 30.2, 15.7 and 12.0 of 32 are averages over 200 runs.

Chapter 0

Number the Nodes, Break the Model

Feed the adjacency matrix to an ordinary network, renumber the nodes, and watch its answers change

Lecture 2 gave each node its own column in a table. That costs |V| × d numbers, shares nothing between nodes, ignores node features, and has no vector for a new node. We want a deep encoder that fixes all four.

The obvious try: put the features X beside the adjacency matrix A. Feed row v of [A, X] to an ordinary multilayer perceptron (MLP), a stack of dense layers. The lecture names three problems. The parameter count grows with |V|. A graph of another size does not fit. And the answer depends on how you numbered the nodes.

Renumber the same graph

Each node shows its row number and two purple scores: a fixed MLP's (top) and one GNN layer's. Pick another numbering: the graph stays, the matrix rows move.

Illustrative toy. The MLP reads row v of [A, x] (7 numbers) and has 3 tanh units with fixed made-up weights; we train nothing. The GNN is Chapter 1's layer with W = 0.6 and B = 0.4. Input features x = 0.9, 0.3, 0.7, 0.5, 0.2, 0.6, the same as the Code Labs.

A graph has no first node. The six-node graph has 6! = 720 numberings of one graph; the karate club has 34!, about 3 × 1038. Each node should get the same vector under all of them.

Write that as a test. Call the adjacency matrix A and the feature matrix X, one row per node. A renumbering is a permutation matrix P: a 0/1 matrix that moves each row to its new place. Call the model f; it returns one row per node.

Say it aloud

P times f of A and X equals f of P A P-transpose and P X.

P
P the permutation: a 6 × 6 matrix of 0s and 1s that moves row i to row π(i).
f(A, X)
f of A and X the model's output in the old numbering: one row of scores per node.
f( · )
f of the same model, run on the renumbered graph.
P A PT
P A P-transpose the adjacency matrix in the new numbering: rows and columns both move.
P X
P X the features in the new numbering: only the rows move.
In plain words

Renumber the nodes, then run f. Or run f, then renumber its output rows. If both give the same table, f is permutation equivariant. A whole-graph output that never changes is permutation invariant: the sum of X's rows is one; A X is equivariant.

With numbers

From the device. The hub sits in row 5 under order 1 and row 3 under order 2. The GNN gives it 0.495 both times. The MLP gives it 0.036, then 0.997. Over all 720 orders the MLP's hub score takes 15 different values, from 0.007 to 0.997. The MLP fails the test.

Symptom: predictions change after someone re-sorts the node list.

Measure: score one graph under two numberings: the device's MLP moves the hub from 0.036 to 0.997. On the club, a 16-unit first layer has (34 + 1) × 16 = 560 weights and no slot for a 35th member.

Fix: build only from steps that ignore order, such as a mean over neighbours, with the same weights for every node. That is a GNN.

The road

  1. One layer: average the neighbours, transform, repeat.
  2. Computation graph: every node grows its own tree, with shared weights.
  3. GCN: Kipf and Welling's self-loops and symmetric normalization.
  4. Matrix form: one sparse product per layer.
  5. Training: a loss on a few labelled nodes.
  6. Gradient: the error flows back along the same edges.
  7. Showcase: train the club with every knob.
  8. Inductive: a vector for a member the model never saw.
  9. CNN, attention: two famous networks as special GNNs.
  10. Field guide: the numbers, the code and the road ahead.
Why does an MLP that reads row v of [A, X] fail on graphs?

Chapter 1

Average the Neighbours, Then Transform

Collect the neighbours' vectors, average them, and pass the average through weights every node shares

The lecture's idea: a node's neighbourhood decides its vector. Each node averages its neighbours' vectors, and a small neural network combines that average with the node's own vector. One pass is one layer; stack K of them.

Call node v's vector after layer k hv(k); layer 0 is its features, hv(0) = xv. Call v's neighbours N(v) and their count |N(v)|. Each layer learns two weight matrices: Wk for the neighbours' average and Bk for v's own vector. σ is a nonlinearity, such as ReLU.

Say it aloud

h-v at layer k equals sigma of: W-k times one over the size of N of v, times the sum over u in N of v of h-u at layer k minus one; plus B-k times h-v at layer k minus one.

hv(k)
h-v at layer k node v's new vector. After the last layer K it is the embedding zv.
σ
sigma the nonlinearity, applied to every entry. Here ReLU.
Wk
W-k layer k's weights for the neighbours' message. One matrix, shared by every node.
1/|N(v)|
one over the size of N of v divide by the number of neighbours, so the sum becomes an average.
Σu∈N(v)
the sum over u in N of v add one term for each neighbour u. A sum has no order.
hu(k−1)
h-u at layer k minus one neighbour u's vector from the layer before: the message u sends.
Bk
B-k layer k's weights for the node's own vector, also shared.
hv(k−1)
h-v at layer k minus one v's own vector from the layer before.
In plain words

Each neighbour u sends its vector h-u. Node v averages them. Multiply the average by W-k and v's old vector by B-k. Add the two and apply sigma. Do this for every node at once; that is one layer.

With numbers

The device's graph with one number per node, W = 0.6, B = 0.4 and ReLU. Hub v5 has neighbours v1, v2, v3 and v4, holding 0.3, 0.7, 0.5 and 0.2. Their average is 1.7 / 4 = 0.425. So h-5 = max(0, 0.6 × 0.425 + 0.4 × 0.6) = 0.255 + 0.24 = 0.495.

Run one layer by hand

Blue dots are messages. Run a layer: the messages travel first, then every node updates. Tap a node to read its sum. Then switch the average to a plain sum.

W = 0.6
B = 0.4

Illustrative toy: one number per node instead of a vector, so W and B are single numbers. Inputs are the Code Labs' x = 0.9, 0.3, 0.7, 0.5, 0.2, 0.6.

Two things make this a GNN and not an MLP. The average ignores order, so the layer passes Chapter 0's test. And Wk, Bk are the same for every node, so the parameter count does not grow with the graph. With 16 numbers per vector, one layer holds 2 × 16 × 16 = 512 weights, for 34 nodes or 34 million.

The Code Lab uses a common variant: v joins its own average (Chapter 3's self-loop), and B still adds v's value. You write the division.

Symptom: the hub's value grows layer after layer while the quiet nodes stay small.

Measure: with a plain sum, hub v5 reaches 1.26 after one layer and 3.04 after two. With the average it holds at 0.495 and 0.51.

Fix: divide by the neighbour count, or use the symmetric version of Chapter 3. A node's degree should not make its signal louder.

Why can one GNN layer run on a graph of any size?

Chapter 2

Every Node Grows Its Own Tree

Unroll the layers for one node, and see which members reach its vector and how often

Unroll the layers for one node v. Its layer-2 vector needs its neighbours' layer-1 vectors. Each of those needs that neighbour's own neighbours at layer 0. Drawn out, this is a tree: the computation graph of v. The leaves hold input features. Each level up is one layer, and v sits at the root.

Grow a member's tree

Tap a member. Left: the members within K hops light up. Right: its tree, root on top, input features (yellow) at the bottom. Then add a layer.

K = 2

Real ties, exact counts. A slot is one place in the tree. Level k holds one slot for each walk of k steps from the root, so members repeat. Past 90 slots, a level shows its count.

Each node gets a differently shaped tree. But every slot on level k runs the same Wk and Bk. Same weights, different shapes: that is how one model serves a member with 1 friend and a member with 16.

The tree counts paths, not members. Member 12 has one friend, member 1. At K = 2 its tree has 1 + 1 + 16 = 18 slots: the root, member 1, and member 1's 16 friends, member 12 among them. It reads 17 distinct members' features. K layers reach exactly the members within K hops. The club's longest shortest path is 5 hops, so 5 layers let every member hear every other.

Symptom: mini-batch training slows to a crawl as you add a layer.

Measure: a mini-batch builds each node's tree on its own. Member 1's tree has 17 slots at K = 1, 86 at K = 2 and 688 at K = 3, all to cover 34 members. A node with 1,000 friends could need a million slots at K = 2.

Fix: sample a fixed number of neighbours per level. GraphSAGE samples 25, then 10, so a two-layer tree has at most 250 leaves (Hamilton, Ying and Leskovec, 2017).

A GNN has K = 3 layers. Which members can change node v's final vector?

Chapter 3

Kipf and Welling's Normalization

Add a self-loop, then scale every message by both ends' degrees

Kipf and Welling's 2017 paper gave the layer its best-known form, the graph convolutional network (GCN). It makes two changes. First, it adds a self-loop to every node: Ã = A + I. Node v becomes its own neighbour, so Bk merges into Wk. Second, it scales each message by the degrees at both ends.

Call v's degree counting the self-loop d̃v = |N(v)| + 1. The message from u to v is shrunk by 1/√(d̃u d̃v).

Say it aloud

h-v at layer k equals sigma of the sum over u in N of v together with v, of W-k times h-u at layer k minus one, divided by the square root of d-tilde-u times d-tilde-v.

hv(k)
h-v at layer k node v's new vector.
σ
sigma the nonlinearity, such as ReLU.
Σu∈N(v)∪{v}
the sum over u in N of v together with v one term per neighbour, plus one for v itself (the self-loop).
Wk
W-k the one weight matrix of layer k, shared by all nodes. There is no separate B.
hu(k−1)
h-u at layer k minus one the vector u sends.
√(d̃u d̃v)
the square root of d-tilde-u times d-tilde-v both ends' degrees, each counting its self-loop. A message between two busy nodes is shrunk most.
In plain words

Every node u in v's neighbourhood, v included, sends W-k times its vector. Shrink each message by the square root of d-tilde-u times d-tilde-v. Add them and apply sigma.

With numbers

Hub v5 has d-tilde 5 and v1 has d-tilde 4. The weight on their edge is 1/√20 = 0.224, the same in both directions. A plain row average would give 1/5 = 0.2 from v1 into v5, but 1/4 = 0.25 from v5 into v1.

Compare three ways to weight a message

The grid is the propagation matrix: row v holds the weights v gives each sender. The node fills are the values after applying it R times, with no learned weights. Raise R under each rule.

R = 1

Exact arithmetic on the illustrative six-node graph, inputs x = 0.9, 0.3, 0.7, 0.5, 0.2, 0.6. Hub v5 has 4 neighbours.

Why both degrees? Dividing by the sender's √d̃ stops a hub from shouting into every neighbour. Dividing by the receiver's √d̃ keeps a busy node's total in scale. The matrix stays symmetric. Kipf and Welling compared propagation rules on three citation graphs. On Cora, this "renormalization trick" scored 81.5%, against 80.5% for the normalized adjacency without self-loops and 55.1% for an MLP with no graph (their Table 3).

Symptom: values explode as layers stack, before training learns any weight.

Measure: apply each matrix 8 times to the device's inputs. The plain sum reaches 31,324. The row average settles at 0.54 and the symmetric matrix at 0.62.

Fix: normalize the propagation matrix, and keep the layer count small. Kipf and Welling found 2 or 3 layers best on their citation graphs.

What does the symmetric weight 1/√(d̃u d̃v) do that the row average 1/d̃v does not?

Chapter 4

All Nodes at Once

Stack every node's vector into a matrix, and run a whole layer as two matrix products

A loop over nodes is slow. Stack every node's vector as one row of a matrix H(k), with |V| rows and dk columns. Now a whole layer is two matrix products and one nonlinearity.

Call the diagonal matrix of the degrees d̃v D̃. The normalized adjacency of Chapter 3 is then  = D̃−1/2 à D̃−1/2. It depends only on the graph, so compute it once. Wk has dk−1 rows and dk columns.

Say it aloud

H at layer k equals sigma of D-tilde to the minus one half, A-tilde, D-tilde to the minus one half, times H at layer k minus one, times W-k.

H(k)
H at layer k every node's new vector, one per row: |V| × dk.
σ
sigma the nonlinearity, applied to every entry.
D̃−1/2 Ã D̃−1/2
D-tilde to the minus one half, A-tilde, D-tilde to the minus one half Â, "A-hat": entry (v, u) is 1/√(d̃u d̃v) if an edge joins u and v or u = v, else 0. Mostly zeros.
H(k−1)
H at layer k minus one the vectors from the layer before. H(0) = X.
Wk
W-k the layer's weights, dk−1 × dk: the only thing this layer learns.
In plain words

Multiply A-hat by H: each row becomes the weighted sum of its neighbours' rows. Multiply the result by W-k: the same transform acts on every node's vector. Apply sigma to every entry.

With numbers

The device: two features per node, W-k = [[0.8, −0.3], [0.2, 0.9]]. Row v5 of A-hat H, first feature: 0.224 × 0.3 + 0.224 × 0.7 + 0.258 × 0.5 + 0.258 × 0.2 + 0.2 × 0.6 = 0.524. Its second feature is 0.639. Times W's first column: 0.524 × 0.8 + 0.639 × 0.2 = 0.547.

Multiply a layer, and find who changed

Tap a row of H, or a button, to raise that node's two features to 1. The output rows that change flash: only the node and its neighbours. Tap again to restore.

Exact arithmetic on the illustrative graph. H's columns are x and 1 − x. σ = ReLU; every output here is positive, so ReLU changes nothing.

The shapes: [|V| × |V|] [|V| × dk−1] [dk−1 × dk] gives [|V| × dk]. Â is sparse. The club's has 190 non-zero cells out of 1,156, 16%.

The lecture's own layer keeps B, with D the plain degrees: H(k) = σ(D−1A H(k−1) WkT + H(k−1) BkT). Not every GNN fits one product: an aggregator such as an LSTM must run per node.

Symptom: the layer runs out of memory on a large graph.

Measure: a dense  for 106 nodes has 1012 cells: 4 TB at 4 bytes each. Stored sparse, with 10 neighbours per node, it has about 1.1 × 107 non-zeros.

Fix: keep  as an edge list, such as PyTorch Geometric's edge_index, and use a sparse-times-dense product.

In H(k) = σ(Â H(k−1) Wk), which factor does the learning?

Chapter 5

Learn From a Few Labels

Put a loss on the few nodes you know, and let the graph carry what training learns to the rest

The vectors zv = hv(K) mean nothing until a loss shapes them. The lecture gives two settings. Supervised: some nodes have labels, such as a drug that is safe or toxic, and a classifier on zv predicts them. Unsupervised: no labels, so the graph supervises; nodes that Lecture 2 calls similar should get large dot products.

For the supervised case, call the labelled nodes VL. The last layer outputs one score per class, and a softmax turns the scores into probabilities. Call node v's predicted probabilities ŷv and its true class yv.

Say it aloud

L equals minus one over the size of V-L, times the sum over v in V-L, of log y-hat-v at class y-v.

L
L the cross-entropy loss. 0 means every labelled node got its true class with certainty.
1/|VL|
one over the size of V-L divide by the number of labelled nodes, to get an average.
Σv∈VL
the sum over v in V-L one term per labelled node. Unlabelled nodes add nothing here.
log
log the natural logarithm. A probability near 0 gives a large negative log, so a confident mistake costs most.
ŷv, yv
y-hat-v at class y-v the probability the model gives node v's true class.
In plain words

For each labelled node v, look up the probability the model gives its true class y-v. Take the log and flip the sign. Average over V-L. That is L.

With numbers

With made-up numbers: the model gives member 1 a 0.80 chance of Mr. Hi's side and member 34 a 0.90 chance of the president's side. L = −(log 0.80 + log 0.90) / 2 = (0.223 + 0.105) / 2 = 0.164.

Choose the labels, then train

Solid fills with a ring are the labelled members. Choose a set and press Train. The curve is the loss; the bar counts unlabelled members placed right. Try one label.

The hero's model and code: two GCN layers, 100 steps. Averages over 200 runs, unlabelled members right: one label 48.5%, two labels 94.5%, four labels 96.7%.

This is semi-supervised learning. The loss reads only VL, but the forward pass runs on every node. Unlabelled members sit in the labelled members' computation trees, and they receive what training learns through the same layers. Kipf and Welling labelled 20 nodes per class on Cora: 140 of 2,708 papers, 5.2%. Their GCN reached 81.5% test accuracy (their Table 2).

Symptom: the model puts every member on one side.

Measure: label only member 1. The loss falls toward 0 by predicting Mr. Hi's side for everyone. That is right for 16 of the 33 unlabelled members, 48.5%.

Fix: label at least one node of every class, and more where the classes meet.

The loss sums only over labelled nodes. How do unlabelled nodes get good predictions?

Chapter 6

The Error Flows Back Along the Edges

Derive the gradient of one GCN layer, and see the error travel the same edges in reverse

Training needs the gradient: how L changes when each weight changes. Take one GCN layer before its nonlinearity, Z = Â H W. Call the error at the output G = ∂L/∂Z, one row per node. For softmax with cross-entropy, row v of G is (ŷv − one-hot of yv) / |VL| on labelled rows, and 0 elsewhere.

Apply the chain rule entry by entry:

Zvj = Σi (ÂH)vi Wij, so ∂Zvj/∂Wij = (ÂH)vi, and ∂L/∂Wij = Σv (ÂH)vi Gvj.

Say it aloud

d-L by d-W equals A-hat H, transposed, times G.

∂L/∂W
d-L by d-W the gradient: how much L rises per unit of each weight. Same shape as W.
(Â H)T
A-hat H, transposed the aggregated inputs this layer saw, one column per node.
G
G the error at each node's output; 0 at unlabelled outputs of the last layer.
In plain words

For each weight, multiply each node's aggregated input by that node's error G, and add over the nodes. A weight moves most when it saw large inputs at nodes with large errors.

With numbers

The device's toy: one number per node, one weight w = 2, an offset of −1 and a sigmoid. Labels: v0 is class A (y = 1), v3 is class B (y = 0). At v0, A-hat x = 0.589 and σ = 0.544, so G-0 = (0.544 − 1) / 2 = −0.228. At v3, A-hat x = 0.408 and G-3 = 0.227. So d-L by d-w = 0.589 × (−0.228) + 0.408 × 0.227 = −0.041, as a finite difference confirms.

The same rule gives the error at the layer's input, which the layer below needs.

Say it aloud

d-L by d-H equals A-hat transposed, times G, times W transposed.

∂L/∂H
d-L by d-H the error at each node's input: how L moves if that node's vector moves.
ÂT
A-hat transposed the same edges, run backward.  is symmetric, so it is  itself.
G
G the error at the outputs, as above.
WT
W transposed carries the error from output columns back to input columns.
In plain words

Turn each node's error G into input units with W-transpose. Then send it back along the edges, with the same weights the forward pass used. A node far from every labelled node gets nothing.

With numbers

Same toy. Node v4 is two hops from both v0 and v3, so its gradient is exactly 0. Node v1 neighbours both: it gets 2 × (0.289 × −0.228 + 0.289 × 0.227) = −0.0005, a pull and a push that nearly cancel. Node v0 gets −0.152: raise its input and the loss falls.

Send the error back, then step

Tap a node to cycle its label: none, A, B. Labelled nodes show their error. Blue bars are the gradient each node's input receives. Press Step to move w downhill.

w = 2.0

Illustrative toy: z = w · (Âx)v − 1, a sigmoid, and binary cross-entropy averaged over labelled nodes. Step size 2.

Stack K layers and the error travels K hops: the computation tree read backward. In the hero, all 34 members sit within 2 hops of member 1 or 34, so every member's first-layer weights get gradient.

Symptom: a node's prediction never moves during training.

Measure: check its gradient. In the device, v4's input gradient is exactly 0 with one layer, because no labelled node is within one hop.

Fix: add a label nearer to it, or a layer; each layer also blurs.

With one GCN layer, which inputs get a non-zero gradient?

Chapter 7

Train a GCN on the Club, Every Knob

Set the depth, the propagation rule and the labels, train, and find what breaks the model

Here is the whole pipeline with the knobs of the last six chapters. Choose how many layers, which propagation matrix, and how many labels. Train. The loss and the score update as it learns.

Train the club your way

Fill is the predicted side; red rings are wrong. Choose a rule, set the layers, then press Train. Try the plain sum with 8 layers, and no graph.

K = 2

Illustrative toy on real ties, the hero's code: one-hot inputs, 4 hidden numbers, tanh, Adam at 0.01, 100 steps. Averages over 200 runs with two labels, of the other 32: symmetric K = 2, 30.2; K = 8, 30.85. Row average K = 2, 30.5. Plain sum K = 2, 29.9; K = 8, 25.4 (worst run 13). No graph, 15.7. Shuffled, 12.0.

Three things to find. With no graph, the network learns members 1 and 34 and guesses the rest: 15.7 of 32. With the plain sum, values grow with every layer, tanh saturates, and at 8 layers the average falls to 25.4 with a worst run of 13. With shuffled friendships, each member keeps its number of friends but not who they are. More members now sit nearer the wrong hub (12 against 9, with 11 ties), so the score falls below a coin flip, to 12.0.

Symptom: member 9 lands on the wrong side in every run.

Measure: member 9 has 5 friends: 1, 3, 31, 33 and 34. Three are on the president's side, so its messages lean that way.

Fix: no depth or rule fixes it, because the ties point the other way. Zachary's record says member 9 joined Mr. Hi anyway. A GNN learns from structure, and some labels do not follow structure.

Why does the plain sum fail at 8 layers while the symmetric rule holds?

Chapter 8

New Members, No Retraining

Add a member the model never saw, and compute its vector from its friends with the same weights

A confession about the hero. It gave each member a one-hot input: a 1 in its own slot. So the first weight matrix has one row per member, a lookup table in disguise, and the hero cannot handle a new member either. The lecture's rule for graphs without features is exactly this: one-hot vectors, or a constant 1.

Give nodes real features and the GNN becomes inductive: it computes a vector for any node from its features and its neighbours. Here each member's feature is a survey answer, +1 for Mr. Hi's side and −1 for the president's, wrong 30% of the time (Lecture 1's toy). Two layers of the lecture's layer, with one number per node, have four weights in all: W1, B1, W2 and B2.

Add member 35

Small yellow marks are survey answers (+ or −). Choose member 35's answer, then tap members to make them its friends. The GNN places it at once; the lookup table has no column for it.

Illustrative toy on real ties. The survey is one fixed draw at 30% noise. We trained the weights W1 = 4.67, B1 = 0.78, W2 = 6.45, B2 = 0.40 once on this survey (gradient descent on cross-entropy, all 34 labels); they do not change here. Layer 1 uses tanh; the sign of layer 2 is the side.

On its training survey the model places 33 of 34. On 200 fresh surveys it never saw, it places 27.96 of 34 on average (82%), against 23.6 (69%) for the answers alone. New features, same four numbers.

Now member 35 joins members 1, 2 and 3, and answers "president". Its friends answered +1, −1 and +1, an average of 1/3. Layer 1 gives tanh(4.67 × 0.333 + 0.78 × (−1)) = tanh(0.777) = 0.651. Layer 2 averages its friends' new layer-1 values, 0.472, so z = 6.45 × 0.472 + 0.40 × 0.651 = 3.31: Mr. Hi's side, chance 0.965. The friends outvoted the answer.

Inductive also means new graphs. GraphSAGE trained on 20 protein-interaction graphs and labelled proteins in two graphs it never saw (Hamilton, Ying and Leskovec, 2017). The lecture's example: train on one organism's protein graph, then embed data newly collected from another.

Symptom: adding one member changes another member's prediction.

Measure: when member 35 joins members 1, 2 and 3, member 20 flips side: it is two hops from 35, inside its new reach.

Fix: this is correct behaviour, not a bug. After the graph changes, recompute every node within K hops of the change.

A GNN was trained on yesterday's graph. A new user signs up today with a profile and three friends. What does the GNN need to embed them?

Chapter 9

CNNs and Transformers Are GNNs Too

Read an image as a grid graph and a sentence as a complete graph, and find what each one gives up

Treat an image as a graph: each pixel is a node, joined to its 8 neighbours. One layer of a 3 × 3 convolutional network (CNN) then updates pixel v from v and its 8 neighbours. Call the weight for the neighbour at position u Wku: one matrix per position.

Say it aloud

h-v at layer k equals sigma of the sum over u in N of v together with v, of W-k-u times h-u at layer k minus one.

hv(k)
h-v at layer k pixel v's new vector.
σ
sigma the nonlinearity.
Σu∈N(v)∪{v}
the sum over u in N of v together with v the 9 pixels of the 3 × 3 window.
Wku
W-k-u a weight for each position (up-left, up, ..., down-right): 9 different matrices, the filter.
hu(k−1)
h-u at layer k minus one the pixel at position u.
In plain words

Multiply each of the 9 pixels by the weight for its position, add, apply sigma. A GNN layer instead multiplies the average of all neighbours by one W. The CNN can tell "left" from "right"; the GNN cannot.

With numbers

A vertical-edge filter: left column −1, −2, −1; right column +1, +2, +1. On a patch dark on the left (0) and bright on the right (1), the output is 4. Turn the patch by 90° and the output is 0. The GNN's neighbour average is 0.5 both times.

Turn the patch, then go complete

CNN and GNN read the same 3 × 3 patch. Turn it by 90° and compare their outputs. Then pick Attention: every token joins every other, and edge width is the attention weight.

Illustrative toy. The attention weights are the Code Lab's own: 6 random tokens, dk = 8, NumPy seed 1, softmax of q·k/√8 per row.

A pixel's neighbours have a fixed order, so a CNN can learn one weight per position. A graph node's neighbours have none, so a GNN must use one W for them all. The lecture's verdict: a CNN is a special GNN with a fixed neighbour count and order, and it is not permutation invariant.

A Transformer layer lets every token attend to every other: a GNN on the complete graph. Its edge weights are attention scores, αij = softmax over j of qi·kj/√dk, computed from the tokens' content. The price is the edge count. With 2 million papers, a complete graph has about 4 × 1012 pairs per layer. A sparse graph with 10 neighbours each has 2 × 107 edges, 200,000 times fewer.

Symptom: a Transformer runs out of memory on a large graph.

Measure: its attention scores every pair: N2 numbers per head per layer, 4 × 1012 for 2 million nodes.

Fix: attend along the graph's edges, or keep full attention but add the graph as positional encodings or attention biases. Lecture 8 covers graph Transformers.

What can a CNN on an image do that a GNN on the same grid graph cannot?

Chapter 10

Field Guide

Keep the numbers, the code and the road to a general GNN

A graph neural network computes each node's vector from its neighbours' vectors, layer by layer, with weights every node shares. The average over neighbours ignores node order, so the network gives each node the same answer under any numbering. Kipf and Welling's GCN adds self-loops and weights each edge by both degrees; in matrix form a layer is σ(ÂHW). Training is ordinary backpropagation, and the error flows back along the same edges. With features that new nodes also have, the trained weights embed nodes and graphs the model never saw.

IdeaRuleThis lesson's number
EquivarianceP f(A, X) = f(PAPT, PX)MLP hub 0.036 vs 0.997; GNN 0.495 both
Lecture layerσ(Wk mean hu + Bk hv)hub v5: 0.6 × 0.425 + 0.4 × 0.6 = 0.495
Computation treelevel k = walks of k stepsmember 1, K = 3: 688 slots, 34 members
GCN weight1/√(d̃u d̃v)v1 and v5: 1/√20 = 0.224
Matrix formH(k) = σ(ÂH(k−1)Wk)v5: 0.547; club Â: 190 of 1,156 non-zero
Loss−(1/|VL|) Σ log ŷv,yv0.80 and 0.90: 0.164
Gradient(ÂH)TG and ÂTGWTtoy d-L by d-w = −0.041; v4 gets 0
Karate resulttwo labels, two layers30.2 of 32; no graph 15.7; shuffled 12.0
Inductivesame 4 weights, fresh surveys82% vs 69% for answers alone
ModelGraph it runs onEdge weightsNew nodes?
Shallow embedding (Lecture 2)walks, then a tablenone at run timeno
MLP on [A, X]none; fixed node orderone weight per node slotno
Lecture's GCN layerthe given graph1/|N(v)| plus a self term Byes, with features
Kipf and Welling GCNthe graph plus self-loops1/√(d̃u d̃v)yes, with features
GraphSAGEsampled neighboursmean, LSTM or pooling; self vector concatenatedyes, built for it
CNNa pixel gridone per neighbour positiongrids only
Transformerthe complete graphattention, from contentyes; N2 cost

The whole method in NumPy: the normalized adjacency, two layers, the two gradient rules of Chapter 6, and gradient descent. We ran it.

python
import networkx as nx, numpy as np
G = nx.karate_club_graph(); n = 34
A = nx.to_numpy_array(G, nodelist=range(n), weight=None)
At = A + np.eye(n)                                   # 1. self-loops
d = At.sum(1)
Ahat = At / np.sqrt(np.outer(d, d))                  # 2. D~^-1/2 A~ D~^-1/2
X = np.eye(n)                                        # no features: one-hot
y = np.array([0 if G.nodes[v]["club"] == "Mr. Hi" else 1 for v in range(n)])
lab = [0, 33]                                        # only members 1 and 34
rng = np.random.default_rng(0)
glorot = lambda a, b: rng.uniform(-1, 1, (a, b)) * np.sqrt(6 / (a + b))
W1, W2 = glorot(n, 4), glorot(4, 2)
for step in range(200):                              # 3. full-batch gradient descent
    P1 = Ahat @ X; H1 = np.tanh(P1 @ W1)             # layer 1
    P2 = Ahat @ H1; Z = P2 @ W2                      # layer 2: logits
    Y = np.exp(Z - Z.max(1, keepdims=True)); Y /= Y.sum(1, keepdims=True)
    G2 = np.zeros_like(Y); G2[lab] = Y[lab]; G2[lab, y[lab]] -= 1; G2 /= len(lab)
    dW2 = P2.T @ G2                                  # (A H)^T G
    dH1 = Ahat.T @ G2 @ W2.T                         # A^T G W^T
    dW1 = P1.T @ (dH1 * (1 - H1**2))
    W1 -= 0.5 * dW1; W2 -= 0.5 * dW2
pred = Z.argmax(1)
print(sum(pred[v] == y[v] for v in range(1, 33)), "of 32 right")

It prints 30 of 32 right; seeds 1 to 5 give 31. For real work, PyTorch Geometric ships torch_geometric.nn.GCNConv, which takes x and edge_index and builds  for you.

The road through CS224W, Fall 2026

LecturesTopic
1 and 2Introduction and node embeddings: graphs, tasks, and the lookup table this lesson replaces
3Graph neural networks: this lesson
4 and 5A general perspective on GNNs and augmentation and training: messages, aggregators, GraphSAGE, GAT, depth
6 to 8Theory of GNNs, powerful graph encoders, graph Transformers

Keep going

Read next

The habit. Before you trust a graph model, renumber its nodes and add a node it never saw. A GNN passes both tests by construction; most other models fail one.
In one sentence, what does a GCN layer do?

Now teach it: press Present or Teach. Explain why node order breaks an MLP, what one layer computes, why GCN divides by both degrees, and how the error flows back. Then go back to the club, take the graph away, and say why the score falls to a coin flip before you look.

Graph Neural Networks · Stanford CS224W, Lecture 3
Previous: Node Embeddings · Next: A General Perspective on GNNs · Course site · Back to Gleams