Search

Search papers and lessons

Do Transformers Really Perform Bad for Graph Representation?

Chengxuan Ying, Tianle Cai, Shengjie Luo et al. · 2021

Graphormer shows that a plain Transformer can lead graph benchmarks once attention is told the graph's structure: node degree, shortest-path distance and edge features.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Architectures
  • Neural network basics
  • Linear algebra
  • Probability
  • ReadReady to readNot yet

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"]
  1. 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.

  2. 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 b0=0.5b_0 = 0.5, b1=0.2b_1 = 0.2 and b2=−0.4b_2 = -0.4. 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.

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

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

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

  6. 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 hi(l)h_i^{(l)} is the representation of node viv_i at layer ll, xix_i is its input feature, dd is the hidden dimension, and LL is the number of layers.

Definition: Graphormer attention score

For nodes viv_i and vjv_j with query and key projections WQW_Q and WKW_K, the score that node ii gives node jj is the scaled dot product of their projections, plus a bias for their shortest-path distance, plus an edge term. Softmax over jj 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.

hi(0)=xi+zdeg⁡−(vi)−+zdeg⁡+(vi)+h_i^{(0)} = x_i + z^-_{\deg^-(v_i)} + z^+_{\deg^+(v_i)}

Here z−z^- and z+z^+ are learnable vectors in Rd\mathbb{R}^d, 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 ϕ(vi,vj)\phi(v_i, v_j) 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 bϕ(vi,vj)b_{\phi(v_i, v_j)}, shared across all layers. The score becomes

Aij=(hiWQ)(hjWK)⊤d+bϕ(vi,vj)A_{ij} = \frac{(h_i W_Q)(h_j W_K)^{\top}}{\sqrt{d}} + b_{\phi(v_i, v_j)}

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 e1,…,eNe_1, \ldots, e_N from viv_i to vjv_j. For each edge on the path it takes the dot product of the edge's feature vector xenx_{e_n} with a learnable weight vector wnEw^E_n, and averages over the path:

cij=1N∑n=1Nxen(wnE)⊤,Aij=(hiWQ)(hjWK)⊤d+bϕ(vi,vj)+cijc_{ij} = \frac{1}{N} \sum_{n=1}^{N} x_{e_n} (w^E_n)^{\top}, \qquad A_{ij} = \frac{(h_i W_Q)(h_j W_K)^{\top}}{\sqrt{d}} + b_{\phi(v_i, v_j)} + c_{ij}

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:

h′(l)=MHA(LN(h(l−1)))+h(l−1),h(l)=FFN(LN(h′(l)))+h′(l)h'^{(l)} = \mathrm{MHA}\big(\mathrm{LN}(h^{(l-1)})\big) + h^{(l-1)}, \qquad h^{(l)} = \mathrm{FFN}\big(\mathrm{LN}(h'^{(l)})\big) + h'^{(l)}

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

Step 5 in symbols: the readout

The graph vector is the state of the virtual node after the final layer:

hG=hVNode(L)h_G = h^{(L)}_{\mathrm{VNode}}

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

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

Read the full paper

Chengxuan Ying, Tianle Cai, Shengjie Luo et al., 2021. arXiv:2106.05234