TL;DR
Graphormer shows that a standard Transformer can lead graph benchmarks if it is given the graph's structure. The paper adds three signals to the attention computation: each node's degree, the shortest-path distance between every pair of nodes, and the edge features along that path. The model won first place in the graph-level track of the Open Graph Benchmark Large-Scale Challenge and beat the strongest graph neural networks on the paper's molecular benchmarks.
Builds on: Transformer, Graph Neural Network · Leads to: Shortest-Path Distance, Degree Centrality
Why it mattered
Until this paper, Transformers were the default for text, images and code, but they were not the default for graphs. The paper gave a clear answer to why: the attention score between two nodes depends only on their features, so the model does not know how the nodes are connected. Graphormer fixes that with inputs and biases built from the graph itself. After it, graph transformers became a serious alternative to message passing for molecules and other graph-level prediction tasks.
The numbers show the scale of the claim. The main experiment uses PCQM4M-LSC, a quantum chemistry dataset with more than 3.8 million molecular graphs, where the task is to predict each molecule's HOMO-LUMO energy gap. The full model has 47.1 million parameters. Its ensemble placed first in the graph-level track of the challenge, with a test mean absolute error of 0.1200.
The problem
Three things were true before Graphormer.
First, a Transformer layer lets every node attend to every other node, which is a global receptive field. Graph neural networks, by contrast, only see neighbours, and a node has to be reached through several stacked layers to pass information far across a graph. The Transformer's global reach is attractive, but it has no sense of which nodes are close.
Second, sequence Transformers handle position with a positional encoding: a vector added to each token that says where it sits in a line. A graph has no such line. Nodes sit in a space defined by their connections, so a single index per node is the wrong kind of information.
Third, earlier Transformer-based graph models took one of two routes. Some restricted attention to neighbours, which keeps the graph sparse but gives up the global reach. Others, such as the Graph Transformer (GT), kept global attention and added Laplacian eigenvector positions, which are features computed from the Graph Laplacian. The authors argue that neither route makes full use of the graph's structure inside the attention itself.
How it works
The walkthrough traces one tiny graph through one attention layer. The graph has three nodes in a line, A – B – C, with A and C not connected. The numbers are chosen to be easy to follow; the bias values are illustrative, not trained.
flowchart LR F["Node features x_i"] --> D["Add degree embeddings"] D --> L["Transformer layers with structural attention bias"] L --> V["Virtual node state"] V --> G["Graph vector h_G"]
-
Start with features and degrees. Node A has degree 1, node B has degree 2 and node C has degree 1. The model looks up a learned vector for each node's degree and adds it to the node's feature vector. Two nodes with identical features but different degrees now enter the network differently. This is the centrality encoding, and it lets attention see how well connected a node is.
-
Measure the distances. The shortest-path distances are A to B 1, B to C 1, A to C 2, and each node to itself 0. The spatial encoding maps each distance to a learned scalar bias, here , and . A pair that is far apart gets the lowest bias. Check: the bias depends only on the pair's distance, so A and C get the same bias as any other pair two steps apart.
-
Score the pairs for A's query. After the usual query and key projections and scaling, the content scores for A's query are 0.9 for A itself, 0.5 for B and 0.6 for C. These scores already include the degree information from step 1. Now add the bias for each distance: 0.9 + 0.5 = 1.4 for A, 0.5 + 0.2 = 0.7 for B, and 0.6 + (-0.4) = 0.2 for C. Check: only the bias changed, so C's score dropped relative to the content alone.
-
Turn the scores into weights. Softmax exponentiates each score and divides by the total. The exponentials are about 4.055, 2.014 and 1.221, which sum to about 7.290. The weights are about 0.556 for A, 0.276 for B and 0.168 for C. Check: the three weights add to 1. Without the distance bias, C would receive about 0.31 of A's attention, so the bias pulls attention away from the distant node.
-
Mix the values. Give each node a value of 1 (A), 2 (B) and 4 (C), for illustration. A's new representation is the weighted sum: 0.556 times 1, plus 0.276 times 2, plus 0.168 times 4, which is about 1.78. Check: the weights sum to 1, so the result must lie between the smallest and largest values, 1 and 4. Every node does the same computation in parallel.
-
Read out the graph. The paper adds a virtual node connected to every real node. Its feature is passed through the layers like any other node's, and after the last layer its vector is the graph vector h_G. Check: the virtual node attends to all nodes in one step, so it can gather information from the whole graph, and the prediction is read from that single vector.
The math
The model has three structural encodings and a Transformer layer that uses them. Here is the representation of node at layer , is its input feature, is the hidden dimension, and is the number of layers.
For nodes and with query and key projections and , the score that node gives node is the scaled dot product of their projections, plus a bias for their shortest-path distance, plus an edge term. Softmax over turns these scores into the attention weights.
Step 1 in symbols: the centrality encoding
Each node adds two learned vectors, one chosen by its in-degree and one by its out-degree. For undirected graphs the two are merged into one vector chosen by degree.
Here and are learnable vectors in , indexed by in-degree and out-degree. They are full vectors learned during training, not single numbers as in the walkthrough.
Step 2 in symbols: the spatial encoding
The function returns the shortest-path distance between two nodes, or the special value -1 when there is no path. Each possible output gets its own learnable scalar , shared across all layers. The score becomes
Because the bias is a function of the distance, a learned decreasing bias makes each node attend more to nearby nodes. This is the step that gives the walkthrough its pull away from C.
Step 3 in symbols: the edge encoding
When edges have features, such as the bond type between two atoms, the model takes one shortest path from to . For each edge on the path it takes the dot product of the edge's feature vector with a learnable weight vector , and averages over the path:
The result is a bias on the attention score, so edge information reaches the attention directly rather than only through the two endpoint nodes.
Step 4 in symbols: the layer
Layer normalization is applied before the attention and the feed-forward block, rather than after, which the authors note has become the standard choice for better optimisation. Each layer adds its outputs back to its inputs as residuals:
Here MHA is multi-head attention with the biased scores above, LN is layer normalization and FFN is a position-wise feed-forward network whose inner width equals .
Step 5 in symbols: the readout
The graph vector is the state of the virtual node after the final layer:
The virtual node is connected to every real node, but its connections are not physical. The paper gives them a separate learnable bias so the model can tell virtual connections from real ones.
Expressiveness
The authors prove two facts. With suitable weights and distance function, a Graphormer layer can represent the aggregate and combine steps of GCN, GIN and GraphSAGE. Without any extra encoding, a Graphormer layer can represent the mean readout over all nodes. The proofs are in Appendix A and use the universal approximation property of the feed-forward block.
Results
- Quantum chemistry (PCQM4M-LSC, validation MAE, lower is better). GIN with a virtual node reached 0.1395 with 6.7 million parameters, the previous best. GT reached 0.1400 with 0.6 million. Graphormer-Small reached 0.1264 with 12.5 million parameters. The full Graphormer reached 0.1234 with 47.1 million, an 11.5 percent relative drop from GIN with a virtual node. Ensembling with ExpC gave 0.1200 on the full test set and first place in the graph-level track.
- Molecular property benchmark (MolPCBA, average precision in percent). The Graphormer model fine-tuned with FLAG augmentation reached 31.39 ± 0.32, against 29.79 ± 0.30 for the best other row, GINE-APPNP.
- Graph regression benchmark (ZINC, test MAE, lower is better). The slim Graphormer, with 489,321 parameters, reached 0.122 ± 0.006. The compared models include SAN at 0.139, PNA at 0.142, and GIN at 0.526 with about 510,000 parameters.
- Ablation (PCQM4M-LSC, validation MAE after 100,000 steps on a 12-layer model). With none of the structural encodings the error is 0.2276. With all three encodings it is 0.1304. The attention-bias form of edge encoding does better than the two common alternatives, which differ from each other only slightly.
Limits, in the authors' own words and in the numbers. The model is large and needs pre-training on a big dataset: the molecular results start from a model pre-trained on PCQM4M-LSC. Self-attention costs grow quadratically with the number of nodes, which restricts the model on large graphs. The authors also note that a naive virtual node can over-smooth features, while Graphormer did not show this problem in their experiments; that observation is empirical, not a proof. The ablation runs are shorter than the main runs, so their numbers are for comparing designs, not for reporting the best achievable score.
Reading guide
- Introduction (Section 1). Read after Transformer and Graph Neural Network. The three encodings are previewed here and developed in Section 3.
- Preliminaries (Section 2). The AGGREGATE, COMBINE and READOUT steps are the Graph Neural Network pattern from Graph Readout. The attention formula is Attention Mechanism with Softmax.
- Structural encodings (Section 3.1). Needs Degree Centrality and Shortest-Path Distance. The contrast with Positional Encoding is the paper's central argument for structure-aware attention.
- Implementation (Section 3.2). Needs Layer Normalization, Multi-Head Attention and Feedforward Neural Network. The virtual node is the graph-level readout idea from Graph Readout.
- Expressiveness (Section 3.3 and Appendix A). Needs Weisfeiler-Lehman Test for the claim that the model goes beyond 1-WL, How Powerful are Graph Neural Networks? and Graph Convolutional Network for the GNN layers it covers, and Universal Approximation Theorem for the proofs.
- Experiments (Section 4 and Appendix B). The optimiser is AdamW Optimizer with a Learning Rate Warmup stage. The baselines are GNNs from earlier sections.
Check yourself
QuestionRecall: what does the centrality encoding add to a node, and what does it let attention see?Show answer
It adds two learned vectors to the node's input feature, one chosen by its in-degree and one by its out-degree (merged into one vector for undirected graphs). Attention can then take the node's connectivity into account, not only its content.
QuestionComputation: in the walkthrough, suppose the bias for distance 2 were -1.0 instead of -0.4. What weight does C receive in A's row?Show answer
The scores for A's row become 0.9 + 0.5 = 1.4 for A, 0.5 + 0.2 = 0.7 for B, and 0.6 + (-1.0) = -0.4 for C. The exponentials are about 4.055, 2.014 and 0.670, summing to about 6.739. C's weight is 0.670 divided by 6.739, which is about 0.10.
QuestionWhy: why is the distance term a bias on the attention score rather than a change to each node's input vector?Show answer
Distance is a property of a pair of nodes, not of one node. A per-node input vector cannot express that A and C are two steps apart. A scalar bias on the score for each pair gives every pair its own adjustment, and it is shared across all layers.
QuestionApplied: a chemist models a molecule in which two atoms share a double bond. Which encoding carries that bond, and how?Show answer
The edge encoding. The bond's feature vector is dotted with a learnable weight vector for each position along the shortest path between the two atoms, the results are averaged, and the average is added to the attention score for that pair.
Sources
- Ying, C., Cai, T., Luo, S., Zheng, S., Ke, G., He, D., Shen, Y., Liu, T.-Y. (2021). Do Transformers Really Perform Bad for Graph Representation? arXiv: 2106.05234
- DOI: 10.48550/arXiv.2106.05234