Before you start: review of the earlier sessions
The thread so far. Sessions 6–8 form the expressiveness arc: the ceiling, encodings that pass it, and the transformer as a GNN with learned global attention. The GNN block is now complete; the next block applies it to richer graphs.
What this session takes from earlier ones
Those sessions in one minute each
Lecture 7 · Designing Powerful Graph Encoders — Breaking the WL Limit
Message passing can only see what its initial features let it see: give nodes structural features (closed walks, cycles, eigenvectors) to go beyond WL on structure, and distances to random anchor sets to make embeddings position-aware.
\((A^k)_{vv}\) = number of closed walks of length \(k\) from \(v\). Since \(\mathrm{tr}(A^k)=\sum_n\lambda_n^k\), these features carry spectral information that constant inputs cannot reach.
Lecture 4 · A General Perspective on GNNs
A GNN layer is "message, then order-free aggregation (including yourself)"; architectures differ in how neighbours are weighted, and depth must be matched to the receptive field you need because too many layers smooth everything into one vector.
GCN is the special case \(\alpha_{vu}=1/|N(v)|\) (fixed); GAT learns \(e_{vu}=a(\mathbf{W}\mathbf{h}_u,\mathbf{W}\mathbf{h}_v)\).
Lecture 6 · Theory of GNNs — How Expressive Are They?
A message-passing GNN is at most as powerful as the 1-WL test; it reaches that bound exactly when every aggregation is injective on multisets — which sum aggregation with MLPs (GIN) achieves and mean/max do not.
GIN layer. For graph classification, GIN reads out with a sum over nodes at every layer and concatenates them (the paper's readout).
Warm-up: answer these before you read on
What makes an encoding "structural" rather than "positional"? from Lecture 7
Structural encodings describe the local structure around a node (cycle counts, degrees) and are the same for structurally identical nodes; positional encodings locate the node in the graph and can differ for identical local structures.
Why add MLP layers before and after message passing? from Lecture 4
Pre-processing encodes rich input features (text, images); post-processing lets the model reason over the embedding, e.g. for graph classification, without adding more hops.
Give a pair of graphs 1-WL cannot tell apart. from Lecture 6
Two disjoint triangles and a six-cycle: all nodes have degree two with degree-two neighbours at every iteration.
Why can a message-passing GNN with constant features not distinguish a node on a triangle from a node on a square? from Lecture 7
Both see a degree-two neighbour at every iteration of colour refinement; the cycle length is never visible to 1-WL.
More questions from every session you have reached, with spaced repetition: the cumulative review.
In short
Transformers map a sequence of token vectors to a sequence of output vectors using self-attention: every token computes a query, key and value; each token's output is a softmax-weighted sum of all values. Written per token, that is message + aggregation — i.e. a GNN — running on the fully connected graph. Restrict the softmax to graph neighbours and you get (roughly) GAT.
Self-attention ignores token order, so transformers need positional encodings. For graphs this is the whole game: if nodes are tokens, the adjacency information has to come back in through (1) the tokens, (2) the positional encodings (relative distances, Laplacian eigenvectors, learned PEs), or (3) a modified attention that adds edge/shortest-path biases to the scores (Graphormer).
Eigenvector PEs have a hidden flaw — the sign (and basis) of an eigenvector is arbitrary, so the model may give \(2^k\) different answers for the same graph — and they cost \(O(n^3)\). The lecture ends with PEARL: run a GNN on random node "IDs", average over samples, and get expressive, nearly linear-time, inductive PEs.
The picture: the graph transformer design space
How to read it (hover a step)
- Tokenisation: usually one token per node (its features). Alternatives: subgraphs, nodes + edges as tokens.
- Positional encoding: tells each token where it sits in the graph — relative distances to anchors, Laplacian eigenvectors, or learned PEs (PEARL).
- Modified attention: add a bias \(c_{ij}\) to the attention score, computed from edge features or the features along the shortest path (Graphormer).
- Without (2) and (3), the transformer sees a bag of nodes on a complete graph — the adjacency is lost entirely.
1 · Transformers and self-attention, from scratch
A transformer maps a 1-D sequence of token vectors to a sequence of outputs. Output options: predict the next token (GPT), or pool outputs (e.g. sum) for a sequence-level prediction. Inside a block: normalisation, feed-forward networks, positional encoding and multi-head self-attention.
Single-head self-attention in three steps
- For each input \(x_i\) compute query, key, value: \(q_i=W^Qx_i,\ k_i=W^Kx_i,\ v_i=W^Vx_i\).
- For token 1, score every token: \(q_1^\top k_j\) (scaled by \(\sqrt{d}\)); softmax into probabilities.
- Output \(z_1=\sum_j \text{softmax}_j(q_1^\top k_j)\,v_j\), e.g. \(z_1=0.88\,v_1+0.12\,v_2\).
Multi-head: run several attentions in parallel with separate parameters, each learning a different notion of "similarity", then combine.
2 · Self-attention is message passing
Look at one token: \(z_1=\sum_{j}\text{softmax}_j(q_1^\top k_j)\,v_j\). Read it as a GNN layer:
- Message from \(j\): \((v_j,k_j)=\text{MSG}(x_j)=(W^Vx_j,W^Kx_j)\).
- Query for 1: \(q_1=W^Qx_1\).
- Aggregate: \(\text{AGG}(q_1,\{\text{MSG}(x_j)\})=\sum_j\text{softmax}_j(q_1^\top k_j)\,v_j\).
Swap tokens 1 and 2 in "The cat sat on the mat". What happens to the outputs, and to a sum-pooled prediction?
Outputs \(z_1,z_2\) swap and are otherwise unchanged — self-attention is permutation equivariant. After sum pooling the prediction is identical: without positional encodings a transformer is a "bag-of-words" model. For language that's a bug (word order matters); for graphs it's a feature (node order shouldn't matter) — but then we must re-inject the graph structure some other way.
3 · A design landscape for graph transformers
A graph has (1) node features, (2) adjacency, (3) edge features. A transformer has (1) tokens, (2) positional encodings, (3) self-attention. Designs differ in how they match the two lists.
Tokens = node features
The sensible default, matching "attention = MP on the complete graph". Problem: the adjacency is completely lost.
Adjacency → positional encoding
- Relative distances to anchors (Lecture 7, P-GNN) or random-walk based encodings: strong for position-aware tasks and for counting cycles, less suited to structure-aware tasks.
- Laplacian eigenvectors (\(L=D-A\)): compute \(k\) eigenvectors, stack into \(n\times k\), row \(i\) is node \(i\)'s PE; add/concatenate to its token. Small-eigenvalue eigenvectors encode global structure; large ones local symmetries. Also helps message-passing GNNs (cycle detection table on slide 54).
Edge features → modified attention (Graphormer)
\(a_{ij}=(QK^\top)_{ij}\) is an \(n\times n\) matrix saying how much token \(j\) contributes to \(i\). Replace it by \(a_{ij}+c_{ij}\):
- if \((i,j)\) is an edge with features \(e_{ij}\): \(c_{ij}=w_1^\top e_{ij}\);
- otherwise, take the shortest path \(e_1,\dots,e_N\) between them: \(c_{ij}=\sum_n w_n^\top e_n\) (learned \(w_1,\dots,w_N\)).
(Graphormer also adds a learned bias per shortest-path distance and a centrality (degree) encoding to the tokens.)
4 · Eigenvector PEs done right: sign & basis invariance
Eigenvectors are not arbitrary vectors. If \(Lv=\lambda v\), then \(L(-v)=\lambda(-v)\): the sign is arbitrary. Pick the other sign and the PE changes, so predictions change. With \(k\) eigenvectors there are \(2^k\) sign choices → up to \(2^k\) different predictions for the same graph. (With repeated eigenvalues, any orthonormal basis of the eigenspace is valid — basis ambiguity.)
- Simple idea: randomly flip signs during training (data augmentation). Issue: exponentially many choices — hard to learn.
- Better: build the invariance into the network. SignNet: \(f(v_1,\dots,v_k)=\rho\big([\phi(v_i)+\phi(-v_i)]_{i=1}^k\big)\) — symmetrising over \(\pm v_i\) makes it sign-invariant, and it's universal among such functions. BasisNet handles eigenspaces (Lim, Robinson et al.).
Remaining problems: eigendecomposition costs \(O(n^3)\) time and \(O(n^2)\) memory.
5 · PEARL: learning efficient PEs with GNNs
Recall from Lecture 7: GIN layers are non-linear functions of the eigenvectors, \(c^{(l+1)}[f]=\sigma\big(\sum_n w[n,f]\,v_n\big)\) with \(w[n,f]=\sum_{i,k}\lambda_n^kW_k[i,f]\langle v_n,C^{(l)}[:,i]\rangle\) — but constant inputs make many \(\langle v_n,\cdot\rangle\) vanish. One-hot IDs fix that but aren't scalable or inductive. PEARL's idea: use random samples as node IDs.
- Sample node IDs from a distribution (e.g. each node gets \(M\) random numbers).
- Run a GNN on each sample independently: \(y^{(m)}=\text{GNN}(A, \text{sample}_m)\).
- Average: \(y=\mathbb{E}[y^{(m)}]\approx\frac1M\sum_m y^{(m)}\) — this restores permutation equivariance / inductiveness.
- Concatenate the PEARL embedding with node features \(X\); pass through the main GNN or transformer; train end-to-end.
Analogy from the slides: to map a country's opinions, sample one person per state, ask everyone the same questions, repeat, and average — each sample is noisy, the average describes the structure.
Theorem (Kanatsoulis et al., ICLR 2025): PEARL is strictly more expressive than the WL test, can count cycles up to 7 nodes, with nearly linear complexity. On molecule solubility it reduced test error by about 60% versus no-PE baselines.
The mathematics, step by step
A transformer and a GNN are the same kind of machine: each element collects a weighted sum of the others. The cards write self-attention out for one token, explain the \(\sqrt d\), show the step that makes it message passing on a complete graph, add the two places where a real graph can be put back in, and end with the symmetry of eigenvectors that positional encodings must respect.
Symbols used in this session
| symbol | meaning | what kind of object |
|---|---|---|
| \(X\) | the input tokens, one row per node (or word): row \(i\) is \(\mathbf x_i^\top\) | \(n\times d\) matrix |
| \(W^Q,\ W^K,\ W^V\) | weights that turn a token into its query, key and value | \(d\times d\) matrices (parameters) |
| \(Q,\ K,\ V\) | queries, keys and values of all tokens: \(Q=XW^Q\), and so on | \(n\times d\) matrices |
| \(\alpha_{ij}\) | attention weight: how much token \(i\) takes from token \(j\) | number in \((0,1)\); row \(i\) sums to 1 |
| \(d\) | dimension of the keys and queries | whole number |
| \(P\) | positional encodings, one row per node (for example Laplacian eigenvectors) | \(n\times d\) matrix |
| \(C\) | attention bias: \(C_{ij}\) is added to the score of the pair \((i,j)\), e.g. a learned number per shortest-path distance | \(n\times n\) matrix |
| \(\mathbf v_i\) | eigenvector of the Laplacian; \(-\mathbf v_i\) is an equally valid choice | unit vector |
1Self-attention
In words. Each token asks a question (its query), every token offers a label (its key) and a content (its value). A token's output is the average of all values, weighted by how well each key matches its query.
Why it has this form. Entry \((i,j)\) of \(QK^\top\) is the dot product \(\mathbf q_i^\top\mathbf k_j\): large when token \(j\)'s key points the same way as token \(i\)'s query. The softmax is applied to each row separately, turning the scores of token \(i\) into positive weights \(\alpha_{i1},\dots,\alpha_{in}\) that sum to one. Multiplying by \(V\) then gives row \(i\) of the output, \(\sum_j\alpha_{ij}\mathbf v_j\). Three separate matrices let a token look for one thing, advertise another and deliver a third.
Watch out. The softmax runs over a row (over \(j\) for a fixed \(i\)), not over the whole matrix. The cost is \(n^2\) scores, which is the price for letting every token see every other.
2Why the scores are divided by √d
In words. A dot product of two random \(d\)-dimensional vectors has a typical size of \(\sqrt d\). Dividing by \(\sqrt d\) brings the scores back to a typical size of 1, whatever the dimension.
Why it has this form. Each product \(q_tk_t\) has mean 0 and variance 1; the variance of a sum of \(d\) independent terms is \(d\), so the standard deviation is \(\sqrt d\). Large scores push the softmax towards a one-hot vector, where its gradient is almost zero and learning stalls. The division keeps the softmax in the range where it still responds to changes.
Watch out. The scaling fixes the size at initialisation only; training can still make the attention as sharp as it needs by growing the weights.
3Attention is message passing on the complete graph
In words. Write the attention output for one token: it is a weighted sum of transformed vectors of all tokens. That is a GNN layer in which every node is a neighbour of every node.
Why it has this form. Compare with GAT (Lecture 4): \(\mathbf h_v=\sum_{u\in N(v)}\alpha_{vu}W\mathbf h_u\). The message is \(W\mathbf x_j\), the aggregation is a weighted sum, the weights come from a softmax over the neighbourhood. The only difference is the neighbourhood: \(N(i)\) is everything. A consequence: a plain transformer has no idea which nodes are linked. The graph has to be supplied separately (next card).
Watch out. Message passing on the complete graph costs \(n^2\) per layer, against the number of edges for a GNN; for large sparse graphs this is the main obstacle.
4Putting the graph back: positions and biases
In words. Two additions tell the transformer about the graph: a position vector \(P\) added to each node's features before attention, and a bias \(C_{ij}\) added to each pair's score before the softmax.
Why it has this form. \(P\) answers 'where is this node?': rows are, for example, the node's entries in the first few Laplacian eigenvectors (Lecture 7), so nearby nodes get similar vectors. \(C\) answers 'how are these two nodes related?': a learned number that depends on the shortest-path distance between \(i\) and \(j\) or on the type of the edge between them. Since \(C\) is added inside the exponent, it multiplies the attention weight by \(e^{C_{ij}}\): setting \(C_{ij}=-\infty\) for non-neighbours removes them and recovers message passing on the real graph.
Watch out. Adding \(P\) to the features and adding \(C\) to the scores are different mechanisms; the second cannot be expressed by the first, because it depends on the pair and not on each node alone.
5The sign ambiguity of eigenvectors
In words. If \(\mathbf v\) is an eigenvector, so is \(-\mathbf v\); a solver returns one of them arbitrarily. A positional encoding must give the same result for both, which the sum \(\phi(\mathbf v)+\phi(-\mathbf v)\) guarantees.
Why it has this form. With \(k\) eigenvectors there are \(2^k\) equally valid sign choices, so the same graph can produce \(2^k\) different inputs; a network trained on one may fail on another. Swapping \(\mathbf v\) for \(-\mathbf v\) only swaps the two terms of the sum, so the sum is unchanged: the encoding is sign-invariant by construction, whatever the network \(\phi\) is (this is SignNet). When an eigenvalue is repeated the ambiguity is larger, any rotation within its eigenspace, and needs basis-invariant functions.
Watch out. Simply taking absolute values is also sign-invariant but throws away more: it cannot tell whether two nodes are on the same side or on opposite sides.
Check yourself
Questions from the lecture, in order. Answer each one in your head (or on paper) before you open it. If one stumps you, follow the link to the walkthrough block it comes from.
Check yourself: why not put adjacency into the tokens directly, e.g. one token per edge? show answer
It is possible (the slides later mention "subgraphs" and "node + edge features" as other tokenisations), but then the number of tokens grows with the number of edges and attention cost grows quadratically in that.
from Graph inputs vs transformer components; nodes as tokens
Check yourself: a graph transformer with no positional encoding and no attention bias — what can it compute about the graph? show answer
Nothing structural: it is a set model on node features (a "bag of nodes").
from The graph transformer design space
Check yourself: why is a plain Laplacian PE no better than no PE in slide 90? show answer
Sign (and basis) ambiguity: the model sees arbitrary sign choices and cannot learn a stable function of them. Making the PE sign-invariant fixes most of the gap; learning it from random samples (PEARL) also avoids the \(O(n^3)\) eigendecomposition.
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.
- Why graph transformers?
- Transformers ingest tokens
- Single-head and multi-head self-attention
- Self-attention is message passing on a complete graph
- Inputting a graph, and the missing piece: order
- Graph inputs vs transformer components; nodes as tokens
- Positional encoding option 1: relative distances
- Positional encoding option 2: Laplacian eigenvectors
- Edge features in self-attention
- The graph transformer design space
- Eigenvector positional encodings: sign ambiguity and cost
- Back to the spectral view: why not just use IDs?
- PEARL: process random samples independently, then average
- PEARL: theory, practice, results, and summary
Why graph transformers? slides 3,4,6-8 ↗
Slide 3 recalls the GNN design space from Lecture 4 (You, Ying, Leskovec, NeurIPS 2020): (1) message, (2) aggregation, (3) layer connectivity, (4) graph augmentation, (5) learning objective. The figure shows an input graph, a two-layer computation graph with message and aggregation boxes, and the objective on top.
Slide 4 asks the lecture's question: we know a lot about the GNN design space — what does the corresponding design space for graph transformers look like? (Left: the GNN design space; right: an empty box with a big question mark.)
Slide 6 shows a chatbot answer to "what is a transformer?": the model from "Attention Is All You Need" (Vaswani et al., 2017) with five ingredients — self-attention (each token attends to all others, so the whole input is processed at once rather than step by step like an LSTM), an encoder–decoder architecture (BERT uses only the encoder, GPT only the decoder), positional encoding (transformers do not know token order by themselves), multi-head attention, and feed-forward networks. Applications: language models (BERT, GPT, T5), vision (ViTs), and graphs. The point: transformers are the backbone of generative AI.
Slide 7 states the goal: bring the power of transformers to graphs. Examples: small molecules (drug structures), knowledge graphs (diseases, drugs, proteins, pathways), code graphs (syntax trees), communication networks. There is a lot of multi-billion node/graph-scale data to learn from.
Slide 8 gives the plan: Part 1 — introduce transformers and relate them to message-passing GNNs; Part 2 — a new design landscape for graph transformers; Part 3 — PEARL, learning efficient positional encodings with GNNs.
Transformers ingest tokens slides 10-13 ↗
Slide 10: a transformer maps a 1D sequence of vectors to a 1D sequence of vectors. The figure feeds the sentence "The cat sat on the mat and sang" as inputs \(x_1,\dots,x_8\) and gets 8 output vectors.
Slide 11: the input vectors are called tokens; a token describes a "piece" of data, e.g. a word. What output sequence do we want?
- Option 1: next token (GPT). Output \(i\) predicts input \(i+1\): above "The" sits "cat", above "cat" sits "sat", and so on.
- Option 2: pool the outputs (e.g. sum-pool, slide 12) into one sequence-level embedding, used for classification. The figure predicts the label "kids story" for the whole sentence.
Slide 13 shows the transformer blueprint (the encoder–decoder diagram from Vaswani et al.: input embedding + positional encoding, then \(N\times\) blocks of multi-head attention and feed-forward layers, each with "Add & Norm"; the decoder adds masked multi-head attention, and a final linear + softmax gives output probabilities). Tokens are processed by many components: normalisation, feed-forward networks, positional encoding (more later), and multi-head self-attention. The key question: what does the self-attention block do?
Compare with GNNs: option 1 is like node-level prediction (one output per token), option 2 is like graph-level prediction with a readout/pooling.
Single-head and multi-head self-attention slides 14-19 ↗
Slides 14–17 follow the Illustrated Transformer tutorial (Jay Alammar) with two input words, "Thinking" (\(x_1\)) and "Machines" (\(x_2\)).
- Step 1 (slide 15): for each input compute a query, key and value with three learned matrices (the model parameters): \[ \mathbf{q}_i=W^Q\mathbf{x}_i,\qquad \mathbf{k}_i=W^K\mathbf{x}_i,\qquad \mathbf{v}_i=W^V\mathbf{x}_i. \]
- Step 2 (slide 16, just for \(x_1\)): compute a score between pairs, then turn scores into probabilities. Scores: \(\mathbf{q}_1\cdot\mathbf{k}_1=112\), \(\mathbf{q}_1\cdot\mathbf{k}_2=96\). Divide by \(\sqrt{d_k}=8\) (key dimension 64): 14 and 12. Softmax: 0.88 and 0.12. (Same for \(x_2\).)
- Step 3 (slide 17): the new embedding is the probability-weighted sum of values: \(\mathbf{z}_1=0.88\,\mathbf{v}_1+0.12\,\mathbf{v}_2\).
Slide 18 does the same in matrix form. Stack inputs as rows of \(X\). Step 1: \(Q=XW^Q\), \(K=XW^K\), \(V=XW^V\). Steps 2–3 together:
\[ Z=\mathrm{softmax}\!\Big(\frac{QK^\top}{\sqrt{d_k}}\Big)V, \]with the softmax applied row by row.
Slide 19: multi-head self-attention. Do many self-attentions in parallel and combine them. Each head has its own parameters \(W_h^Q,W_h^K,W_h^V\), so different heads can learn different "similarities" between inputs. The figure uses 8 heads (0–7), producing \(Z_0,\dots,Z_7\); these are concatenated and multiplied by an output matrix \(W^O\) to give the final \(Z\). (In every encoder layer after the first, the input is the output \(R\) of the layer below rather than the word embeddings.)
Check yourself: with 112 and 96 before scaling, the softmax would give \(1/(1+e^{-16})\approx 1\) — almost all weight on \(\mathbf{v}_1\). Dividing by \(\sqrt{d_k}\) keeps the scores in a range where softmax is not saturated and gradients still flow.
Self-attention is message passing on a complete graph slides 20,21,23-28 ↗
Slide 20 compares transformers and GNNs. Similarity: GNNs also take a set of vectors (node features \(x_1,x_2,x_3\), in no particular order) and output a set of embeddings (\(z_1,z_2,z_3\)). Difference: GNNs use message passing; transformers use self-attention. Slide 21 asks: are these really different? (Left: a message-passing computation tree; right: the attention matrix computation.)
Slides 23–25 recall the attention formula with inputs stored row-wise in \(X\):
\[ \mathrm{Att}(X)=\mathrm{softmax}(QK^\top)\,V,\qquad Q=XW^Q,\ K=XW^K,\ V=XW^V \](the \(\sqrt{d_k}\) scaling is dropped for simplicity). This gives all tokens' outputs at once. Look at one token, \(x_1\):
\[ \mathbf{z}_1=\sum_{j=1}^{n}\mathrm{softmax}_j\big(\mathbf{q}_1^\top\mathbf{k}_j\big)\,\mathbf{v}_j. \]Slide 26 rewrites this as the three steps of a GNN layer:
- Message from \(j\): \((\mathbf{v}_j,\mathbf{k}_j)=\mathrm{MSG}(\mathbf{x}_j)=(W^V\mathbf{x}_j,\,W^K\mathbf{x}_j)\).
- Query for 1: \(\mathbf{q}_1=W^Q\mathbf{x}_1\).
- Aggregate all messages: \(\mathrm{Agg}\big(\mathbf{q}_1,\{\mathrm{MSG}(\mathbf{x}_j):j\}\big)=\sum_{j=1}^n\mathrm{softmax}_j(\mathbf{q}_1^\top\mathbf{k}_j)\,\mathbf{v}_j\).
Slide 27: so self-attention is a GNN. But which graph? Tokens are nodes; since token 1 receives messages from all other tokens, the graph is fully connected (the figure draws a complete graph on 5 nodes). If instead we only sum over \(j\in N(i)\), we get roughly GAT.
Slide 28 lists the takeaways:
- Takeaway 1: self-attention is a special case of message passing.
- Takeaway 2: it is message passing on the fully connected graph.
- Takeaway 3: given a graph \(G\), restricting the softmax to \(j\) adjacent to \(i\) gives ~GAT.
So what is gained by going "full"? Every pair of nodes can talk in one layer, so there is no over-squashing through bottleneck edges and long-range dependencies are one hop away. The cost: \(O(n^2)\) attention, and the graph structure disappears unless we put it back — the topic of Part 2.
Inputting a graph, and the missing piece: order slides 31-39 ↗
Slide 31 repeats the question about the graph-transformer design space. Slide 32: we start with a graph (nodes with feature vectors). How do we input it into a transformer, which expects a sequence \(x_1,\dots,x_5\)?
Slide 33: to answer that, understand the key components of the transformer and make graph versions of each. Seen so far: (1) tokenising (input tokens) and (2) self-attention (the attention module).
Slides 34–36: one key piece is still missing. Recall \(\mathbf{z}_1=\sum_j\mathrm{softmax}_j(\mathbf{q}_1^\top\mathbf{k}_j)\mathbf{v}_j\). Key observation: the order of the tokens does not matter. The figure swaps tokens 1 and 2 ("cat The sat on …"): the outputs \(z_1,z_2\) swap places but otherwise do not change. In other words, self-attention is permutation equivariant.
Slide 37: this is a problem. After sum-pooling, both orders give identical outputs: the model makes the same prediction whatever the word order — it is a "bag of words" model. "The cat sat" and "sat cat The" look the same.
Slide 38: the fix is positional encoding. The transformer does not know the order of the inputs, so we add extra positional features telling it that "Je" is word 1, "suis" is word 2, and so on. The figure: each word embedding \(x_i\) gets a positional vector \(t_i\) added, giving the "embedding with time signal" that enters encoder #0. For NLP, positional encoding vectors are often learnable parameters.
Slide 39 updates the list of key components: (1) tokenising, (2) positional encoding, (3) self-attention. The figure shows tokens \(x_i\) plus positional encodings feeding into the self-attention transformer. Key question: what should these three be for a graph input?
For graphs, permutation equivariance is exactly what we want for the node order — node IDs are arbitrary. The real problem is different: with nodes as tokens, attention also ignores which nodes are connected. Positional encodings for graphs must carry structure, not a sequence index.
Graph inputs vs transformer components; nodes as tokens slides 40-46 ↗
Slide 40: a graph transformer must take three kinds of input: (1) node features, (2) adjacency information, (3) edge features. The transformer has three components: (1) tokenising, (2) positional encoding, (3) self-attention.
Slide 41: there are many ways to do this; different approaches correspond to different "matchings" between graph inputs (1)(2)(3) and transformer components (1)(2)(3). Slide 42 shows today's matching with arrows: node features → tokens, adjacency information → positional encoding, edge features → self-attention.
Slide 43, Q1: what should the tokens be? The sensible idea: node features = input tokens. This matches the "attention is message passing on the fully connected graph" view — each node is a token.
Slide 44: problem — we completely lose adjacency information. The transformer sees a set of node feature vectors and nothing about edges. How do we inject adjacency?
Slides 45–46: idea — encode adjacency in the positional encoding of each node. The positional encoding describes where a node is in the graph; it is added to the node feature token (the figure shows a PE vector "+" each red token). Q2: how do we design a good positional encoding?
Check yourself: why not put adjacency into the tokens directly, e.g. one token per edge? show answer
It is possible (the slides later mention "subgraphs" and "node + edge features" as other tokenisations), but then the number of tokens grows with the number of edges and attention cost grows quadratically in that.
Positional encoding option 1: relative distances slides 47-49 ↗
Slide 47 recalls last lecture's position encoding based on relative distances to anchors and anchor-sets. In the figure (two triangles joined by an edge), node \(v_1\) gets the encoding \((1,2,1)\) from its distances to anchors \(s_1,s_2\) and the size-2 anchor-set \(s_3\); \(v_3\) gets \((1,2,0)\). Anchors \(s_1,s_2\) alone cannot separate \(v_1\) and \(v_3\), but the anchor-set \(s_3\) can. Similar methods use random walks instead of shortest-path distances.
- This is a good idea; it works well in many cases.
- It is especially strong for tasks that require counting cycles.
Slide 48 adds a caveat: relative distances are useful for position-aware tasks, but not suited to structure-aware tasks. The figures show the barbell graph (two triangles joined by an edge) labelled two ways: by position (left triangle A, right triangle B) and by structural role (degree-2 nodes A, bridge nodes B on both sides). Distances to random anchors capture the first labelling, but mirror-image nodes with the same role get different distances, so the encoding does not reflect role.
Slide 49 asks: what other ways are there to build a positional encoding?
Positional encoding option 2: Laplacian eigenvectors slides 50-54 ↗
Slide 50: draw on graph theory. Key object: the Laplacian matrix \(L = D - A\) (degrees minus adjacency). Each graph has its own Laplacian; it encodes the graph's structure; several variants add degree information differently. Example, the 4-node path \(v_1-v_2-v_3-v_4\):
\[ L=\mathrm{diag}(1,2,2,1)-\begin{pmatrix}0&1&0&0\\1&0&1&0\\0&1&0&1\\0&0&1&0\end{pmatrix}. \]Slide 51: the Laplacian captures graph structure, and its eigenvectors inherit this structure. This matters because eigenvectors are vectors, so they can be fed into a transformer. Eigenvectors with small eigenvalues describe global structure; large eigenvalues describe local symmetries. (Refresher: \(L\mathbf{v}=\lambda\mathbf{v}\), \(L\) is \(n\times n\), \(\mathbf{v}\in\mathbb{R}^n\), \(\lambda\) a scalar. The figure, from Kreuzer, Beaini et al. 2021, colours a molecule-like graph by eigenvector entries: \(\lambda_1=0.037\) and \(\lambda_2=0.1\) vary smoothly across the whole graph; \(\lambda_{10}=\lambda_{11}=1.0\) vary locally.)
Slide 52, positional encoding steps:
- Compute \(k\) eigenvectors (figure: \(k=3\)).
- Stack them into an \(n\times k\) matrix.
- Row \(i\) is the positional encoding of node \(i\); add it to node \(i\)'s feature token.
Slide 53 summarises and adds: Laplacian eigenvector PEs can also be used with message-passing GNNs, where they help for the same reasons as the structural and relative-distance encodings of the previous lecture.
Slide 54 repeats the cycle-detection experiment (predict YES if the graph has a cycle). With 5000 training samples: GIN 86.130±1.140 vs GIN-PE 99.570±0.089; GatedGCN 50.000±0.000 (chance, at every training size) vs GatedGCN-PE 99.725±0.027. With only 200 samples, GIN-PE reaches 86.720±3.376 and GatedGCN-PE 95.082±0.346.
Why do Laplacian eigenvectors help with cycles? They are global "coordinates" of the graph. In a tree, nodes far apart along the tree get very different coordinates; a cycle ties distant parts together and changes the eigenvectors in a way the model can see. And unlike constant features (Lecture 7), eigenvectors are not orthogonal to the hidden spectral components — they are those components.
Edge features in self-attention slides 55-59 ↗
Slide 55: so far, node features → tokens and adjacency → positional encoding. Slide 56: left to do — (3) edge features.
Slide 57: it is not clear how to put edge features into the tokens or the positional encoding. How about in the attention? In \(\mathrm{Att}(X)=\mathrm{softmax}(QK^\top)V\), the matrix \([a_{ij}]=QK^\top\) is \(n\times n\). Entry \(a_{ij}\) says how much token \(j\) contributes to the update of token \(i\). It is the only place where pairs of nodes appear — the natural place for pairwise (edge) information.
Slide 58, idea: adjust \(a_{ij}\) based on edge features. Replace
\[ a_{ij}\ \longrightarrow\ a_{ij}+c_{ij},\qquad c_{ij}\ \text{depends on the edge features.} \]Slide 59, implementation (Graphormer: Ying et al., "Do Transformers Really Perform Bad for Graph Representation?", NeurIPS 2021):
- If there is an edge between \(i\) and \(j\) with features \(\mathbf{e}_{ij}\): \(c_{ij}=\mathbf{w}_1^\top\mathbf{e}_{ij}\), with learned \(\mathbf{w}_1\).
- If there is no edge: find the shortest path between \(i\) and \(j\), with edges \(\mathbf{e}^1,\mathbf{e}^2,\dots,\mathbf{e}^N\), and set \(c_{ij}=\sum_n\mathbf{w}_n^\top\mathbf{e}^n\), with learned \(\mathbf{w}_1,\dots,\mathbf{w}_N\) (one per position along the path).
Intuition: \(c_{ij}\) is a learned bias that says "these two nodes are connected through edges of this kind", so attention can prefer (or avoid) them. Because the bias is added before the softmax, it reshapes the attention distribution instead of overriding it.
In the Graphormer paper the path sum is averaged over the path length, and two more biases are used: a degree-based "centrality encoding" added to the node tokens and a learned bias per shortest-path distance ("spatial encoding"). The slides show only the edge part.
The graph transformer design space slides 60,61 ↗
Slide 60 summarises the design space:
- Tokenisation: usually node features. Other options exist, such as subgraphs, or node + edge features (not discussed today).
- Positional encoding: relative distances or Laplacian eigenvectors. This gives the transformer the adjacency structure of the graph.
- Modified attention: reweight attention using edge features.
Slide 61 places it next to the GNN design space. GNN: message, aggregation, layer connectivity, graph augmentation, learning objective. Graph transformer: input tokens, positional encoding, modified attention. Read the correspondence: tokens ↔ node features; positional encoding plays the role that the graph structure plays in message passing; modified attention ↔ message + aggregation with edge-aware weights.
Check yourself: a graph transformer with no positional encoding and no attention bias — what can it compute about the graph? show answer
Nothing structural: it is a set model on node features (a "bag of nodes").
Eigenvector positional encodings: sign ambiguity and cost slides 64-72 ↗
Slide 64 recalls Laplacian eigenvector PEs: compute \(L=D-A\), take \(k\) eigenvectors, row \(i\) is the PE of node \(i\). Slide 65: they work — but is this the best we can do? (Hint: no.) The problem: eigenvectors are not arbitrary vectors. They have special structure that we have ignored, and we must account for it in our models.
Slide 66, sign ambiguity: if \(L\mathbf{v}=\lambda\mathbf{v}\), then also \(L(-\mathbf{v})=\lambda(-\mathbf{v})\). So \(-\mathbf{v}\) is an equally valid eigenvector (the figure draws \(\mathbf{v}_i\) and \(-\mathbf{v}_i\) as opposite arrows). The choice of sign is arbitrary.
Slides 67–69: when we use eigenvectors as PEs, we pick one sign arbitrarily (the eigensolver decides). Why does this matter? If we had picked the other sign, the input PE changes, so the model's predictions change. With \(k\) eigenvectors there are \(2^k\) sign choices, so potentially \(2^k\) different predictions for the same input graph.
Slide 70, simple idea: randomly flip the signs during training (data augmentation), so the model learns not to use sign information. Issue: there are exponentially many sign choices, which is very hard to learn.
Slide 71, better idea: build a network that is invariant to sign choices (SignNet; Lim, Robinson et al., "Sign and Basis Invariant Networks for Spectral Graph Representation Learning"). Because it is invariant, predictions no longer depend on the sign choice.
Slide 72: there is still a problem with eigenvector PEs. (A1) computing eigenvectors has cubic complexity, \(O(n^3)\); (A2) storing them needs quadratic space. Can we do better? This motivates Part 3.
Sign is only the simplest ambiguity. When an eigenvalue is repeated (e.g. \(\lambda_{10}=\lambda_{11}=1.0\) in the figure of slide 51), any rotation of the eigenvectors inside that eigenspace is also valid — a "basis ambiguity" that BasisNet, in the same paper, addresses.
Back to the spectral view: why not just use IDs? slides 74-80 ↗
Slides 74–75 recall from Lecture 7 that GNNs are nonlinear functions of eigenvectors. With a single-layer MLP, the GIN update in matrix form is \(C^{(l+1)}=\sigma\big(\sum_{k=0}^1A^kC^{(l)}W_k^{(l)}\big)=\sigma\big(\sum_k V\Lambda^kV^\top C^{(l)}W_k^{(l)}\big)\) with \(A=V\Lambda V^\top\). Per node \(v\) and output feature \(f\):
\[ \mathbf{c}_v^{(l+1)}[f]=\sigma\Big(\sum_{n=1}^{N}w[n,f]\,\mathbf{v}_n\Big)[v],\qquad w[n,f]=\sum_{i=1}^{d}\sum_{k=0}^{1}\lambda_n^k\,W_k[i,f]\,\big\langle\mathbf{v}_n,C^{(l)}[:,i]\big\rangle. \]So a GNN already builds combinations of eigenvectors — it could produce eigenvector-like positional encodings itself, without an eigendecomposition. But the weights depend on \(\langle\mathbf{v}_n,C^{(l)}[:,i]\rangle\).
Slide 76 recalls the catch: the WL colours inherit the graph symmetries (the hexagon pair \(\mathcal{G}\) vs pentagon pair \(\hat{\mathcal{G}}\) from Lecture 7), and symmetric colours hide parts of the spectrum.
Slide 77: can we break these symmetries? Standard approach: assign unique IDs to nodes and convert them to one-hot vectors. The figure: a 6-node graph with IDs 1–6; the node with ID 5 gets \([0,0,0,0,1,0]\) (total number of IDs = 6).
Slides 78–79 recall that one-hot IDs make computation graphs clearly different, but they are not scalable (\(O(N)\) feature dimensions) and not inductive (cannot generalise to new nodes/graphs).
Slide 80 (Kanatsoulis, Choi et al., "Learning Efficient Positional Encodings with Graph Neural Networks", ICLR 2025): can we learn powerful PEs with GNNs only? Still assign unique IDs, but represent them by random samples: each node gets a different set of random numbers. Example: node 3 gets \([0.2, 1.5, -2.3, -10.1]\); total number of random samples = 4.
Why random numbers instead of one-hot? A random vector is almost surely different for every node (so symmetry is broken), its dimension does not depend on \(N\) (scalable), and a new graph can be given new random values from the same distribution (inductive).
PEARL: process random samples independently, then average slides 81-87 ↗
Slide 81 lists the random samples for the 6-node graph (A–F; edges A–B, A–C, B–C, A–D, C–E, C–F, E–F): A \([3.3,-1.7,-1.2,-0.1]\), B \([-0.1,-5.4,3.0,-9.8]\), C \([0.2,1.5,-2.3,-10.1]\), D \([0.5,1.9,-12.7,11.1]\), E \([5.1,-0.7,-2.9,-13.5]\), F \([-1.2,7.5,-0.3,-7.9]\).
Slides 82–84, independent processing of samples. Sample \(m\) uses the \(m\)-th number of every node as a 1-dimensional node feature:
- Sample 1 (slide 82): A=3.3, B=−0.1, C=0.2, D=0.5, E=5.1, F=−1.2 → GNN → \(\mathbf{y}^{(1)}\).
- Sample 2 (slide 83): A=−1.7, B=−5.4, C=1.5, D=1.9, E=−0.7, F=7.5 → the same GNN → \(\mathbf{y}^{(2)}\).
- … up to sample 4 (slide 84): A=−0.1, B=−9.8, C=−10.1, D=11.1, E=−13.5, F=−7.9 → \(\mathbf{y}^{(4)}\).
Each run is an ordinary message-passing GNN, but on inputs that break all symmetries, so each output \(\mathbf{y}^{(m)}\) can depend on the full structure.
Slides 85–86 give an approximate analogy: a survey. Sample one person per state (the US map as the "input graph") and ask them the same set of questions → answers \(\mathbf{y}^{(1)}\); repeat with other random people → \(\mathbf{y}^{(4)}\). Any single respondent is random, but the statistics over many samples describe each state stably. Slide 86 shows such a summary: a bar map with three bars (PW 1, PW 2, PW 3) in each state. Slide 87 repeats the processing picture.
Why averaging extracts structure — a short derivation (ours, connecting to Lecture 7). Let \(\mathbf{x}\) have i.i.d. zero-mean entries with variance \(s^2\). Then \(\mathbb{E}\big[x_v\,(A^k\mathbf{x})_v\big]=s^2\,(A^k)_{vv}\): the expectation of a product a GNN can form turns random inputs into closed-walk counts, the same structural features as \(\mathrm{diag}(A^k)\) in Lecture 7. A single sample is noisy; the average is not.
PEARL: theory, practice, results, and summary slides 88-92 ↗
Slide 88: to keep the model inductive (and permutation equivariant), the final output is an expectation over the random samples,
\[ \mathbf{y}=\mathbb{E}\big[\mathbf{y}^{(m)}\big],\qquad\text{computed in practice as}\qquad \mathbf{y}=\frac{1}{M}\sum_{m=1}^{M}\mathbf{y}^{(m)}. \]Theorem: PEARL is strictly more expressive than the WL test. PEARL can count 7-node cycles with near-linear complexity. So a GNN can break the limits of the WL kernel and count important substructures — with no eigendecomposition.
Slide 89, PEARL in practice:
- Sample node IDs from a probability distribution.
- Process each set of node samples independently with a GNN.
- Summarise the outputs by the empirical expectation (a pooling \(\rho[\cdot]\) giving the PE matrix \(P\)).
- Concatenate the PEARL embeddings with the node features \(X\).
- Pass through the main GNN or transformer as usual.
- Backpropagate to train PEARL and the prediction model jointly.
The figure: the input graph's attributes (people, text) go straight to the main model; a copy with node attributes removed goes to the PEARL GNN (red box), whose output \(P\) is fed in alongside.
Slide 90: small-molecule property prediction — given a molecule (e.g. MBX-2982), predict its solubility. The bar chart shows mean absolute error for four positional encodings: No PE and Laplacian PE are the worst (Laplacian PE is no better than none), sign-invariant Laplacian PE roughly halves the error, and PEARL is the lowest — the slide reports a 60% reduction in test error (the arrow runs from the PEARL bar to the No PE / Laplacian PE bars).
Slide 91 summarises the lecture. Part 1: transformers = message passing on a fully connected graph. Part 2: new design landscape for graph transformers — tokenisation, positional encoding, modified self-attention. Part 3: PEARL, positional encodings for graph transformers. Slide 92 shows the final picture: the GNN design space next to the graph-transformer design space (input tokens, positional encoding, modified attention).
Check yourself: why is a plain Laplacian PE no better than no PE in slide 90? show answer
Sign (and basis) ambiguity: the model sees arbitrary sign choices and cannot learn a stable function of them. Making the PE sign-invariant fixes most of the gap; learning it from random samples (PEARL) also avoids the \(O(n^3)\) eigendecomposition.
Not shown (no new content): slides 1,2,5,9,22,29,30,62,63,73 — title page, announcements, section-divider pages, and repeated 'plan for today' outline slides.
Review: what to keep from this session
Carried forward. Lecture 13's relational graph transformer and Lecture 15's foundation models both use the token + positional-encoding view; Lecture 16 compares transformers (LLMs) and GNNs as complementary.
Quick self-check
In what sense is a transformer a GNN?
Each token aggregates messages (values) from all other tokens with attention weights; that is message passing on the complete graph with attention as the aggregation weights.
Why do graph transformers need positional encodings more urgently than text transformers?
In text a simple index encodes position; a graph has no canonical order, so without encodings the model sees only a bag of node features and cannot tell the graph structure at all.
Name two ways to inject edges into a graph transformer.
As an attention bias (e.g. shortest-path distance or edge features added to the attention logits) or by restricting attention to neighbours; a third is to use edges as tokens.
Key idea
A transformer is a GNN on the complete graph; a graph transformer re-injects the real graph via tokens, positional encodings, and attention biases — and the positional encodings must respect the symmetries (sign/basis) of whatever spectral object they come from.
\(P\): positional encodings (one row per node); \(C\): edge / shortest-path biases \(c_{ij}\). Setting \(C_{ij}=-\infty\) for non-edges recovers neighbourhood-restricted attention (GAT-like).
Worked example: one attention step by hand
Two tokens, \(d=64\) (so \(\sqrt d=8\)). Suppose \(q_1^\top k_1=112\) and \(q_1^\top k_2=96\) (the Illustrated Transformer example the slides use).
- Scale: \(112/8=14,\ 96/8=12\).
- Softmax: \(e^{14}/(e^{14}+e^{12})=1/(1+e^{-2})\approx0.88\); the other is 0.12.
- Output: \(z_1=0.88\,v_1+0.12\,v_2\).
- Now treat it as a graph with no edge between 1 and 2 and Graphormer-style bias \(c_{12}=-2\) (far apart): scores become \(14\) and \(10\) → weights \(0.98, 0.02\). Structure has re-entered the attention.
Strictly speaking: full attention costs \(O(n^2)\) — fine for molecules (tens of atoms), prohibitive for million-node social graphs. Practical graph transformers (GPS, Exphormer, NodeFormer) mix local message passing with sparse or linearised global attention.
In code (PyG)
from torch_geometric.nn import GPSConv, GINEConv
import torch_geometric.transforms as T
data = T.AddLaplacianEigenvectorPE(k=8, attr_name='pe')(data)
x = torch.cat([data.x, sign_flip(data.pe)], dim=-1) # random sign flips while training
local = GINEConv(torch.nn.Sequential(torch.nn.Linear(64, 64), torch.nn.ReLU()))
gps = GPSConv(channels=64, conv=local, heads=4) # local MPNN + global attention
h = gps(h, edge_index, batch)
Proof workshop: Eigenvector positional encodings have a symmetry you must quotient out
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. Let \(L\) be a graph Laplacian with eigenvectors \(u_1,\dots,u_k\). (a) Show that if \(u\) is a unit eigenvector, so is \(-u\); if all \(k\) eigenvalues are simple, there are exactly \(2^k\) equally valid choices of \((u_1,\dots,u_k)\). (b) Show that \(h(u)=\phi(u)+\phi(-u)\) is sign-invariant for every \(\phi\), and that every sign-invariant \(h\) has this form. (c) If \(\lambda\) has multiplicity 2, describe the full set of valid orthonormal bases of its eigenspace.
Hint 1
Hint 2
Solution
Why it matters. A model fed raw eigenvectors sees an arbitrary sign per eigenvector at training time and possibly a different one at test time: that is the notebook's "Laplacian PE fits ring A, fails on ring B". SignNet is (b) turned into an architecture, \(\rho\big([\phi(u_i)+\phi(-u_i)]_i\big)\), and BasisNet handles (c). PEARL avoids the question by replacing eigenvectors with GNN outputs on random inputs.
Sharper lens: what attention sees, rung by rung
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.
Softmax attention is a weighted mean, so a bare transformer cannot count
Attention weights sum to 1, so by Lecture 6 a transformer layer on node tokens is a mean-type aggregator: with identical features on every node, the output is the same for a graph of 5 nodes and of 500, and no stack of such layers can recover a node's degree. Two consequences that look like implementation details and are not. Graphormer's centrality encoding (add an embedding of the degree to each token) is there to put back the counting that softmax removes. And graph-level readouts in graph transformers use sum or a special token for the same reason.
At the other end, give the transformer the right tokens and it is strong: TokenGT (Kim et al., NeurIPS 2022) feeds nodes and edges as tokens, each tagged with orthonormal node identifiers, and proves that plain self-attention is then at least as expressive as second-order invariant networks, hence beyond 1-WL. The expressive power is in the tokenisation, as the Key idea says.
Distance-biased attention has its own WL test
Zhang et al. (ICLR 2023, outstanding paper) characterise what Graphormer-style models can separate by a generalised-distance WL test: refine each node's colour by the multiset \(\{\!\{(d(v,u),\text{colour}(u)):u\in V\}\!\}\) over all nodes \(u\). With shortest-path distance this test finds every cut edge, which 1-WL cannot; with resistance distance it also finds every cut vertex. So "attention plus a distance bias" provably sees biconnectivity, a property of bridges and brokers that matters in social graphs. It is bounded above by 3-WL. That places the lecture's design landscape on the ladder of Lecture 6: a plain MPNN at 1-WL, shortest-path attention above it, and the choice of distance (shortest path, resistance, random-walk) is a choice of what structure becomes visible.
Sign flips are the easy half: eigenvectors are unstable
Sign and basis ambiguity are exact symmetries. The harder problem is continuity. By the Davis–Kahan theorem, a perturbation of size \(\lVert E\rVert\) can rotate an eigenvector by an angle of order \(\lVert E\rVert/\text{gap}\), where gap is the distance to the nearest other eigenvalue. When two eigenvalues are close, adding one edge can swap or mix their eigenvectors completely. A model that is sign- and basis-invariant can still change its output drastically between two almost identical graphs, which hurts on exactly the out-of-distribution test the notebook runs.
The stable object is the projector onto an eigenspace, \(V_\lambda V_\lambda^\top\): it has no sign or basis freedom. Stable and Expressive PEs (Huang et al., ICLR 2024) feed the network \(V\,\mathrm{diag}(\phi(\boldsymbol\lambda))\,V^\top\) with smooth \(\phi\), so nearby eigenvalues are treated nearly alike, and prove a Lipschitz bound. Random-walk encodings are of this type too (a polynomial in \(P\) is a smooth function of the spectrum), which is the deeper reason they are robust in practice.
Lab: hands-on and practical tips
Try it live. In the Graph Explorer: flip the sign of an eigenvector and see that nothing distinguishes the two. Each lesson has predict-then-check questions.
notebook · L08 graph transformers computes self-attention by hand, shows that a transformer without graph input is a set model, compares positional encodings and a Graphormer bias on a long-range distance task, implements PEARL and runs GPS on Cora.
nn.TransformerEncoder on node features alone is a set model: its output does not depend on the edges, and on Cora it scored like an MLP. Give it structure explicitly: an attention bias or mask from shortest paths, PEs that match the task, or a local message-passing branch (GPS).Readings & lookup guide
lecture notes CS224W course notes (Leni Aniva, Autumn 2024 — in your course folder)
- Ch. 8 — Graph transformers (pp. 43–49)
Reading order: Müller et al. (survey, to get the map) → Graphormer (attention bias) → SignNet/BasisNet (symmetry) → PEARL (efficiency).
start here Müller, Galkin, Morris, Rampášek — Attending to Graph Transformers (TMLR 2024)
- Read: the taxonomy (§3: encodings, input features, tokenisation, propagation) — a richer version of this lecture's 3-way design space. §4 on expressivity: attention alone is no more expressive than WL without PEs.
- Lookup: Table 1 as a reference when choosing an architecture.
core Ying et al. — Do Transformers Really Perform Bad for Graph Representation? (Graphormer, NeurIPS 2021)
- Read: §3.1 (centrality encoding, spatial encoding via shortest-path distance bias, edge encoding along the path — slides 57–59), §3.3 (Graphormer can express GIN/GCN, so it's at least as powerful as MPNNs).
symmetry Lim, Robinson et al. — Sign and Basis Invariant Networks for Spectral Graph Representation Learning (SignNet/BasisNet)
- Read: §2 (the ambiguities), §3 (SignNet: \(\rho([\phi(v_i)+\phi(-v_i)])\); universality theorem), Fig. 1. Skim BasisNet unless you need repeated eigenvalues.
- Olympiad corner: prove that \(\phi(v)+\phi(-v)\) is sign-invariant and that any continuous sign-invariant function of one vector has this form (with \(\phi\) chosen as half the function). That's the 1-vector version of their theorem.
efficiency Kanatsoulis, Choi et al. — Learning Efficient Positional Encodings with Graph Neural Networks (PEARL, ICLR 2025)
- Read: the random-sample / basis-vector variants of PEARL, the expressivity theorem, and complexity analysis. Compare with RWPE (random-walk PEs) — both avoid eigendecomposition.
Homework & deadlines
Homework 2 out Thu 10/15 · due Thu 10/29
Likely coverage: Lectures 5–9 — GNN training/augmentation, expressiveness beyond WL, graph transformers and positional encodings, heterogeneous graphs. Use the self-checks on those pages as warm-ups.
Colab 2 due Thu 10/22 · Project proposal due Tue 10/20
A graph-transformer comparison (GCN vs GIN vs GPS with LapPE) on an OGB molecule dataset is a solid, well-scoped project idea.
Self-check
Self-attention without positional encodings, viewed as a GNN, runs on …
- a path graph
- the input graph
- the complete graph
- a tree
Every token receives messages from every other token.
Restricting the attention softmax to \(j\in N(i)\) gives approximately …
- GCN
- GAT
- GIN
- DeepWalk
Learned, normalised neighbour weights — the GAT layer.
Graphormer injects edge features by …
- concatenating them to tokens
- using them as PEs
- deleting non-edges
- adding a learned bias \(c_{ij}\) to attention scores
\(a_{ij}+c_{ij}\) with \(c_{ij}\) from the edge or the shortest path's edges.
With k Laplacian eigenvectors as PEs and no sign handling, how many different PEs can the same graph produce?
- \(2^k\)
- \(k\)
- \(k!\)
- 1
Each eigenvector's sign can flip independently.
Why does PEARL average the GNN outputs over random samples?
- To reduce memory
- To recover equivariance/inductiveness while keeping the symmetry-breaking power of random IDs
- To compute eigenvectors exactly
- Because GNNs are stochastic
A single random ID assignment breaks permutation equivariance; the expectation restores it.
Flashcards (click to flip)
History & the bigger picture
- 2017 — "Attention is all you need" (Vaswani et al.); sinusoidal positional encodings for sequences.
- 2020 — Dwivedi & Bresson, "A generalization of transformer networks to graphs": Laplacian eigenvector PEs.
- 2021 — Graphormer wins OGB-LSC; SAN (spectral attention). 2022 — GraphGPS (Rampášek et al.): the "local MPNN + global attention + PE" recipe; SignNet/BasisNet.
- 2023–2025 — scaling and efficiency: Exphormer (expander-graph sparse attention), PEARL, and graph foundation models built on transformers (Lectures 14–15).
Part of the transformer's dominance is technical (parallel, expressive) and part is economic: hardware, compilers and talent are optimised for one architecture, so every field pulls its data toward it. Graph transformers are partly "make graphs look like sequences so they ride the same infrastructure". Whether that's the best inductive bias for relational data — or path dependence — is a live question worth keeping in mind.
Classic SNA bridge
| In this lecture | Classic SNA counterpart | What carried over, what changed |
|---|---|---|
| Self-attention = message passing on the complete graph | Complete-network assumptions: everyone can reach everyone; "global" vs "local" influence models | A transformer assumes a complete social world and learns who to listen to. Classical influence models (Friedkin) fixed the influence network; attention learns it per task from content. |
| Positional encodings restore structure | Position in a network as the explanatory variable (Burt's structural holes, Freeman's centralities) | Where SNA computed one position measure and regressed on it, a graph transformer feeds several (eigenvectors, distances, walks) and lets attention combine them. |
| Shortest-path attention bias (Graphormer) | Distance decay of influence; the "horizon of observability" (Friedkin 1983: people see at most two steps) | A learned bias per distance is a learned horizon of observability. Friedkin's empirical finding that influence fades after two steps predicts what the learned biases should look like. |
| Sign ambiguity of eigenvectors | Reading a spectral partition: only the sign pattern matters | SNA never hit the problem because it used the eigenvector qualitatively. Feeding it to a network makes an arbitrary convention into a feature, hence SignNet. |
| PEARL: average over random node IDs | Monte-Carlo null models and permutation tests | Averaging a model's output over random labellings is the same move as a permutation test: it removes the dependence on an arbitrary choice. |
A retweet cascade is both a time-ordered sequence and a tree. Encode it with a transformer whose attention bias combines time difference and tree distance, then inspect the learned bias per distance. If it decays after two hops you have recovered Friedkin's horizon of observability from data, in a model that also predicts virality.
Go deeper in the SNA course. The twelve-unit course on social network analysis in this repository gives the classic side of this lecture in full, with labs and real-data analyses: Unit 4 · Random graphs & small worlds (graph transformers: attention over all pairs, the complete-graph limit of rewiring).
Connecting to your research
- Scale reality check: full attention over millions of Twitter users is impossible; use transformers over sampled ego-networks or cascade subgraphs (hundreds of nodes), where they shine.
- Cascades as sequences + graphs: a retweet cascade is both a time-ordered sequence and a tree — a natural fit for a graph transformer with temporal PEs and structural attention biases.
- Symmetry as a design principle (SignNet) is the same mathematical move as building invariances into symbolic representations — a natural theme for a math-oriented proposal: which symmetries of the data should a social-network model respect, and which should it deliberately break?
Frontier 2025–26: what changed since the slides
Frontiers · a graph transformer is only as expressive as its encodings · tuned GNNs match transformers
Words & phrases
| Term | Simple meaning | Persian | In context |
|---|---|---|---|
| re-injectv. | to put something back in after it was removed | دوباره وارد کردن، تزریق مجدد | "a graph transformer re-injects the real graph" |
| path dependencen. | when past choices lock in future choices, even if better options exist | وابستگی به مسیر | "or path dependence" |
| self-attentionn. | every token attends to every other token with weights computed from their vectors | خودتوجهی | "self-attention is message passing on a complete graph" |
| tokenn. | one input unit of a transformer (a word piece, a node, a cell) | توکن | "one token per node" |
| quadraticadj. | growing with the square of the input size | درجهدوم | "full attention is quadratic in the number of nodes" |
| long-rangeadj. | depending on nodes far apart in the graph | دوربرد | "long-range benchmarks need many hops" |
Go deeper
- Next: Lecture 9 — heterogeneous graphs: what changes when nodes and edges have types.
- Recipe paper: Rampášek et al. (NeurIPS 2022), "Recipe for a General, Powerful, Scalable Graph Transformer" (GraphGPS).
- Open question: do graph transformers win because of global attention or because of better PEs? Ablations often show PEs + MPNN close most of the gap.