Foundations to Frontier
Tests
E. Deep Learning › E14 Graph Neural Networks

Graph Transformers

Graph Transformers apply self-attention across all nodes of a graph, so information can travel between any two nodes in one layer. This avoids message passing's limited reach and its oversquashing. Attention alone ignores the graph, so structure must be injected through positional and structural encodings: Laplacian eigenvectors (Dwivedi and Bresson, 2020), shortest-path and centrality encodings (Graphormer, 2021), or a hybrid with message passing (GraphGPS, 2022). This page covers full attention on graphs, positional encodings and their sign ambiguity, and the trade-off between global reach and n² cost. In the exercises you implement Laplacian positional encodings and global attention, then train three models on a 16-node path to say whether each node is within 5 hops of a marked node. A 2-layer MPNN reached 0.72, a Transformer without positions 0.57 (chance level), and a Transformer with Laplacian positions 1.00.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Everyone talks to everyone, but knows where they are

Message passing only lets information hop one edge per layer, so far-apart nodes need many layers to communicate. A graph Transformer lets every node look at every other node directly through attention. The catch is that attention by itself treats nodes as an unordered crowd and has no idea who is connected to whom. Graph Transformers therefore give each node “coordinates” computed from the graph, such as the eigenvectors of its Laplacian. The demo shows how far plain message passing reaches in k layers.

Graph neural network lab
01234567891011
After 2 rounds, node 0 has received information from 6 of 12 nodes: its 2-hop neighbourhood. A GNN with k layers cannot see further.
Why engineers care

Long-range interactions matter in molecules (charges across a protein), circuits and infrastructure networks. Graph Transformers capture them, and they top many molecular property benchmarks.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In a graph Transformer, each node can attend to…
  2. 2. Without positional encodings, attention…
  3. 3. A common positional encoding uses…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Global attention: α_ij = softmax_j(q_iᵀ k_j / √d) over all n nodes, costing n² pairs (256 for 16 nodes, 10⁶ for 1000).
  • Laplacian positional encodings:
    • use the eigenvectors u₂, …, u_(k+1) of the normalised Laplacian as each node’s coordinates;
    • they are smooth over the graph, like Fourier modes, so nearby nodes get similar encodings;
    • each eigenvector is defined only up to sign, so k of them have 2^k equivalent sign choices (256 for k = 8). Flip signs randomly in training, or use sign-invariant networks.
  • Graphormer’s encodings:
    • centrality (degree) embeddings added to node features;
    • a learned bias per shortest-path distance added to attention scores;
    • edge encodings along shortest paths.
  • Reach: a 16-node path has diameter 15, so an MPNN needs 15 layers to link its ends; one attention layer suffices.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Attention pairs for 16 nodes:
  2. 2. Sign choices for 8 eigenvectors:
  3. 3. Graphormer adds a bias based on…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Graph Transformers in code

Exercise 1.

  • Laplacian encodings of a 6-node path were orthonormal, and the first was antisymmetric.
  • Global attention produced proper weight distributions.
  • Random sign flipping preserved magnitudes.

Practice.

  • In PyTorch Geometric, use AddLaplacianEigenvectorPE / AddRandomWalkPE transforms and GPSConv, which combines a local MPNN with global attention.
  • For large graphs, use linear or sparse attention (Performer, BigBird-style) or attention restricted to sampled nodes.
  • Random-walk encodings (landing probabilities after 1..k steps) avoid sign ambiguity.
import torch_geometric.transforms as T
from torch_geometric.nn import GPSConv, GINEConv
data = T.AddLaplacianEigenvectorPE(k=8, attr_name="pe")(data)
x = torch.cat([data.x, pe_encoder(data.pe * random_sign)], -1)        # random sign flips in training
conv = GPSConv(d, GINEConv(mlp), heads=4)                              # local MPNN + global attention
🐍 Exercise 1: positions and global attention
Compute Laplacian positional encodings, global attention and random sign flips.
📝 Quick check (Level 2)
0/3 answered
  1. 1. PyG layer combining MPNN and global attention:
  2. 2. An encoding without sign ambiguity:
  3. 3. For large graphs, use…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Reach and oversquashing.

  • An L-layer MPNN sees only L hops. Even within reach, information from exponentially many nodes must squeeze through a few edges and fixed-size vectors (oversquashing; Alon and Yahav, 2021).
  • Global attention gives every pair a direct path of length one.

Structure through encodings.

  • Attention is permutation-equivariant and treats input as a set. Without encodings, two nodes with equal features are indistinguishable, whatever their position in the graph.
  • Laplacian eigenvectors embed nodes so that graph distance is reflected in encoding geometry, so the model can compute relations such as “within 5 hops” from the encodings.
  • With suitable encodings, graph Transformers can distinguish graphs that 1-WL cannot.

Costs and risks. Full attention costs O(n²) time and memory. It can also overfit or ignore useful locality, which is why hybrids (GraphGPS) combine local message passing with global attention.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Oversquashing means…
  2. 2. Without encodings, attention treats nodes as…
  3. 3. Hybrid models like GraphGPS combine…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Do positions let attention solve long-range graph tasks?

History.

  • V. P. Dwivedi and X. Bresson, “A generalization of transformer networks to graphs” (2020), introduced Laplacian positional encodings with sign flipping.
  • C. Ying et al., “Do Transformers really perform badly for graph representation?” (Graphormer, NeurIPS 2021), won the 2021 OGB-LSC quantum-chemistry track.
  • L. Rampášek et al., “Recipe for a general, powerful, scalable graph Transformer” (GraphGPS, NeurIPS 2022).

Exercise 2.

  • Task: on a 16-node path, one node is marked. Each node must say whether it lies within 5 hops of the mark; always guessing “no” scores 0.57.
  • Models, each trained for 800 Adam steps:
    • a 2-layer MPNN (features after 1 and 2 rounds of mean aggregation, then an MLP);
    • a one-layer Transformer (single-head attention over all nodes, then an MLP), without positions;
    • the same Transformer with 8 Laplacian eigenvector encodings.
model test accuracy
always “no” 0.570
2-layer MPNN 0.718
Transformer, no positions 0.574
Transformer + Laplacian positions 1.000
  • Attention with positions solves the task exactly: each node attends to the marked node, reads its encoding, and compares it with its own to judge distance.
  • The MPNN is limited by its reach: it knows exactly whether the mark is within 2 hops, but nodes 3–5 hops away look the same as distant ones. 0.718 is the best possible with that information.
  • Attention without positions is blind: every unmarked node sees the same thing (one marked node somewhere), so it cannot tell near from far and stays at the majority rate.
  • Seeds 1 and 2 gave identical results (0.718, 0.574, 1.000).
  • Caveat: all training graphs here are the same path, so eigenvector signs never change. On varied graphs, sign flipping or sign-invariant encodings are needed.
🐍 Exercise 2 (research): do positions let attention solve long-range graph tasks?
Train a 2-layer MPNN and one-layer graph Transformers (with and without Laplacian positions) on a within-5-hops task.

Graph Transformers in AI, robotics and aerospace

  • Molecules and materials: state-of-the-art property prediction, where long-range electrostatics matter.
  • Networks and scenes: reasoning about distant parts of road networks, power grids or robot scene graphs.
  • Design lesson: if the task needs information from far away, check your model’s reach. Global attention with good positional encodings provides it, at quadratic cost.

References

  1. V. P. Dwivedi and X. Bresson (2020). “A generalization of transformer networks to graphs.” AAAI Workshop on Deep Learning on Graphs.
  2. C. Ying et al. (2021). “Do Transformers really perform badly for graph representation?” NeurIPS.
  3. L. Rampášek et al. (2022). “Recipe for a general, powerful, scalable graph Transformer.” NeurIPS.
  4. U. Alon and E. Yahav (2021). “On the bottleneck of graph neural networks and its practical implications.” ICLR.