Graph Learning2021advanced11 min read
Do Transformers Really Perform Bad for Graph Representation?
هل المحوِّلات فعلاً ضعيفة في تمثيل البيانات البيانية؟
Ying, C. · Cai, T. · Luo, S. · Zheng, S. · Ke, G. · He, D. · Shen, Y. · Liu, T.-Y. — NeurIPS
The problem
By 2021 the had become the dominant architecture in NLP and computer vision, yet on graph-level prediction benchmarks it consistently underperformed mainstream variants like GIN, GCN, and GAT. The core challenge was that graphs lack the sequential or grid structure that Transformers naturally exploit. Nodes live in non-Euclidean space, connected by edges with no canonical ordering. Without a way to inject this structural information, the Transformer's treats every pair of nodes identically — ignoring topology, distances, and node importance. The question was: could a standard Transformer match or surpass GNNs if given the right structural encoding?
The contribution
Graphormer — a standard Transformer augmented with three structural encodings: (1) adds learnable vectors based on node degree to the input, telling the model how important each node is. (2) adds a learnable bias based on shortest-path distance to the attention matrix, giving the model a sense of graph topology. (3) aggregates edge features along shortest paths as another attention bias. With these, the authors proved that Graphormer subsumes GIN, GCN, and GraphSAGE as special cases, and can distinguish graphs beyond the 1-WL test. Graphormer won first place in the OGB Large-Scale Challenge and set new state-of-the-art on MolHIV, MolPCBA, and ZINC benchmarks.
The impact
Graphormer proved that Transformers can dominate when given proper structural encodings, ending the assumption that GNNs were inherently superior for graph tasks. Its centrality and spatial encodings became foundational techniques adopted by subsequent graph Transformers. The work directly influenced AlphaFold2, which used similar ideas to encode protein structure. Graphormer launched a wave of research into graph Transformers, positional encodings for graphs, and the application of Transformer architectures to molecular property prediction and drug discovery.
Imagine a room full of people at a conference. A standard GNN is like a telephone game: each person can only whisper to their immediate neighbors, and the message degrades as it passes through many intermediaries.
A Transformer puts everyone in the same room — anyone can speak to anyone directly. But without name badges, seating charts, or hallway signs, the conversation is chaos: you can't tell who's important, who's nearby, or what connects two people.
Graphormer hands out three things: (1) a name badge showing each person's popularity (how many connections they have), (2) a card telling how many handshakes apart any two people are, and (3) labels on every corridor between them describing the relationship. Now the open-room conversation becomes structured — and dramatically outperforms the telephone game.
The gap: why Transformers struggled with graphs
In NLP, words sit in a sequence — position 1, 2, 3 — and the Transformer uses to know where each token is. In computer vision, pixels live on a 2D grid. But in a graph, there is no canonical ordering. Node 5 is not "after" node 4 — it might be three hops away, or directly connected, or in a completely different subgraph.
Standard GNNs solve this by restricting communication: in , each node collects information only from its direct neighbors. After layers, a node has seen its -hop neighborhood. This respects graph structure naturally but limits the — distant nodes need many layers to communicate, and deep GNNs suffer from where all node representations converge.
The Transformer's self-attention gives every node a global receptive field in a single layer. But without structural information, the attention treats all pairs equally — it doesn't know that nodes 3 and 7 are neighbors while nodes 3 and 42 are five hops apart. This is why naive application of Transformers to graphs performed poorly.
Encoding 1: centrality — telling the model who matters
In any graph, some nodes are more important than others. In a social network, a celebrity with millions of followers is structurally different from an ordinary user. In a molecule, an atom bonded to many others plays a different chemical role than a terminal atom. But standard self-attention computes similarity purely from node features — it has no idea how connected a node is.
Graphormer solves this with centrality encoding: for each node, it looks up a learnable vector based on the node's degree (number of connections) and adds it directly to the node features at the input layer. Think of it as pinning a "popularity badge" on each node before the conversation begins.
For directed graphs, two separate embeddings capture indegree and outdegree. For undirected graphs, a single degree embedding suffices. This is surprisingly simple — yet the ablation studies show it provides one of the largest performance improvements.
Encoding 2: spatial — telling the model who is near whom
In sequences, the Transformer knows that token 3 is closer to token 4 than to token 100 via positional encoding. Graphs need an analogous concept, but "position" in a graph means something fundamentally different — it's about topological distance, not index.
Graphormer's spatial encoding uses the (SPD) between any two nodes as the structural measure. For each possible distance value, a learnable scalar bias is added directly to the before . If two nodes are 1 hop apart, they get bias ; if 3 hops apart, they get ; if disconnected, they get a special bias .
The beauty of this design is that it naturally introduces a soft : if the model learns , it will pay more attention to nearby nodes — mimicking the locality that makes GNNs effective. But it can also learn other patterns: perhaps for some heads, capturing long-range dependencies that GNNs miss entirely.
Encoding 3: edges — labeling the hallways
Many real-world graphs have rich edge features. In molecular graphs, edges carry bond types (single, double, aromatic); in knowledge graphs, edges carry relation labels. Previous GNNs encoded edge features in two limited ways: either adding them to the connected nodes' features, or using them during the neighbor step. Both only propagate edge information to directly connected nodes.
Graphormer's edge encoding takes a different approach. For any pair of nodes , it finds the shortest path between them — a sequence of edges . It then computes the average dot product between each edge's feature vector and a learnable weight embedding, and adds this as another bias to the attention score.
This means that even for non-neighboring nodes, the model considers the path connecting them and the features of every edge along that path. It's like reading every sign on the hallways between two conference rooms, not just the sign on the door.
Architecture: the virtual node and Graphormer layers
For graph-level tasks — predicting a property of the entire graph, not individual nodes — the model needs a way to aggregate all node representations into a single graph embedding. Previous GNNs used READOUT functions (sum, mean, or learned pooling). Graphormer borrows an idea from BERT: it adds a special ([VNode]) connected to every node in the graph, analogous to BERT's [CLS] token.
The [VNode] participates in self-attention like any regular node, but its spatial encoding uses a distinct learnable scalar — separating "virtual" connections from physical graph edges. After all Transformer layers, the [VNode]'s final representation becomes the graph-level output.
Each Graphormer layer follows the standard Transformer encoder pattern with pre-: layer norm before , a , layer norm before the feed-forward network, and another residual connection. The FFN uses the same hidden dimension as the model dimension , keeping the architecture clean and standard.
Expressive power: Graphormer subsumes popular GNNs
A natural question is whether adding these encodings actually makes Graphormer more powerful than existing GNNs, or just different. The authors provide a mathematical proof: with appropriate weight choices, a single Graphormer layer can simulate the AGGREGATE-COMBINE step of GIN, GCN, and GraphSAGE.
The key insight is that spatial encoding lets the self-attention distinguish between neighbors () and non-neighbors (). Combined with centrality encoding (which provides degree information), the model can compute sum, mean, or max over the neighbor set — exactly what GNN aggregation functions do.
But Graphormer goes further. Standard message-passing GNNs are provably bounded by the 1- for — they cannot distinguish certain non-isomorphic graphs. The authors show a concrete example where Graphormer, using shortest-path distances, can distinguish graphs that the 1-WL test cannot, because shortest-path distances capture global structural patterns that local message passing misses.
Results: dominating graph benchmarks
Graphormer was evaluated on four major benchmarks. On the OGB Large-Scale Challenge (PCQM4M-LSC), containing 3.8 million molecular graphs, Graphormer achieved 0.1234 MAE — an 11.5% relative improvement over the previous best GIN-VN (0.1395). On OGB-MolHIV it reached 80.51% AUC, on MolPCBA 31.39% AP, and on ZINC it set a new state-of-the-art of 0.122 MAE, surpassing SAN (0.139).
Crucially, the naive (GT) of Dwivedi and Bresson — using Laplacian positional encoding — did not outperform GIN-VN, even when scaled to 83M parameters. This shows that the Transformer alone is insufficient; what matters is how structural information is injected. Graphormer's three encodings are the difference between failure and state-of-the-art.
Ablation: every encoding earns its place
The reveals the contribution of each component. Starting from a bare Transformer (0.2276 MAE), adding spatial encoding drops the error to 0.1427. Adding centrality encoding on top reduces it further to 0.1396. Finally, edge encoding via attention bias brings it down to 0.1304.
An important comparison: Laplacian positional encoding (0.1483) is substantially worse than spatial encoding (0.1427) even though both encode node relationships. This is because spatial encoding provides pairwise information (distance between any two nodes) as a bias in the attention matrix, while Laplacian PE provides per-node information added to the input. The pairwise approach directly modulates which node pairs communicate strongly, giving the model finer structural control.
Code: attention with structural encodings
Simplified to show the idea — not the real implementation.
import torch
import torch.nn as nn
class GraphormerAttention(nn.Module):
def __init__(self, d_model, n_heads, max_dist=20):
super().__init__()
self.n_heads = n_heads
self.d_k = d_model // n_heads
self.W_Q = nn.Linear(d_model, d_model)
self.W_K = nn.Linear(d_model, d_model)
self.W_V = nn.Linear(d_model, d_model)
# Spatial encoding: learnable bias per distance per head
self.spatial_bias = nn.Embedding(max_dist + 2, n_heads)
# Edge encoding: learnable weight per path position
self.edge_proj = nn.Linear(d_edge, n_heads)
def forward(self, x, dist_matrix, edge_encoding):
# x: (batch, n_nodes, d_model)
Q = self.W_Q(x) # Query projection
K = self.W_K(x) # Key projection
V = self.W_V(x) # Value projection
# Standard attention scores
attn = (Q @ K.transpose(-2, -1)) / (self.d_k ** 0.5)
# Add spatial bias from shortest-path distances
spatial = self.spatial_bias(dist_matrix) # (batch, n, n, heads)
attn = attn + spatial.permute(0, 3, 1, 2)
# Add edge encoding bias
attn = attn + edge_encoding
# Softmax and weighted sum
attn = torch.softmax(attn, dim=-1)
return attn @ V
Timeline: the rise of graph Transformers
2017
Transformer (Vaswani et al.)
Introduced self-attention for sequences. Global receptive field in one layer, but designed for sequential data with positional encodings.
2018
GAT — Graph Attention Networks
Applied attention to graphs but restricted to neighbors — attention weights replace fixed aggregation but the receptive field remains local.
2019
GIN — How Powerful are GNNs?
Proved that GNNs are bounded by the 1-WL test. GIN achieves this bound with sum aggregation, establishing the theoretical ceiling for message-passing GNNs.
2021
Graphormer (this paper)
Three structural encodings make a standard Transformer dominate graph benchmarks. Subsumes GIN/GCN/GraphSAGE, goes beyond 1-WL test. Won OGB-LSC challenge.
2021
AlphaFold2
Used pair-wise spatial encoding ideas similar to Graphormer for protein structure prediction. Won CASP14 and transformed structural biology.
2022
Graph Transformer wave
GPS, TokenGT, GraphGPS, and others built on Graphormer's insights. Graph Transformers became a major research direction with specialized positional and structural encodings.
CitationYing, Cai, Luo, Zheng, Ke, He, Shen, Liu. Do Transformers Really Perform Bad for Graph Representation?. NeurIPS, 2021.
Terms in this paper
- Graph Neural Network (GNN)الشبكات العصبية الرسومية (البيانية)
- Self-Attentionالانتباه الذاتي
- Positional Encodingالترميز الموضعي
- Adjacency Matrixمصفوفة التجاور
- Message Passingتمرير الرسائل
- Aggregationالتجميع
- Graph Isomorphismتشابُه البيانات البيانية
- Multi-Head Attentionالانتباه المتعدد المسارات
- Layer Normalizationالتسوية الطبقية
- Residual Connectionالوصلة التجاوزية
- Embeddingالتضمين
- Softmaxسوفت ماكس
- Attention Scoreدرجات الانتباه البينية
- Graph Representation Learningتعلّم تمثيلات الرسوم البيانية
- Inductive Biasالانحياز الاستقرائي المسبق