Graph transformer

On this page 7

A graph transformer is a neural network architecture that applies transformer-style self-attention to the nodes of a graph, injecting the graph structure through positional encodings, structural encodings or attention biases rather than relying only on edges for communication. In graph learning, it extends or replaces message passing so that any node can exchange information with any other node in a single layer.

Graph transformers emerged around 2020 to address weaknesses of classical graph neural networks, notably over-squashing, over-smoothing and limited expressive power. Well-known designs include the Graph Transformer of Dwivedi and Bresson, SAN, Graphormer and the hybrid GraphGPS framework.

How a graph transformer processes a graph

A standard transformer treats its input as an unordered set of tokens and computes attention scores between every pair. Applied naively to graph nodes, it would ignore the edges entirely, because plain self-attention is permutation-invariant and structure-blind. A graph transformer therefore adds information about topology in one or more of three ways.

  • Node-level encodings are added to the input features, such as Laplacian eigenvectors or random-walk landing probabilities, so each node carries a signature of its position.
  • Attention biases add a learned term to each attention score based on the pairwise relation, for example the shortest-path distance or the edge features along the path.
  • Attention masking or sparsification restricts attention to neighbors, sampled nodes or an expander graph, trading global reach for lower cost.

Each layer then computes queries, keys and values for all nodes, mixes values by the biased attention weights and passes the result through a feed-forward block with residual connections and normalization. A readout function or a special graph token aggregates node states when a graph-level prediction is required.

Formally, the attention score between nodes i and j becomes the scaled dot product of their query and key vectors plus a structural bias term b(i, j). In Graphormer, this bias is a learned scalar indexed by the shortest-path distance, and disconnected pairs receive a dedicated value. Because the bias is shared across all graphs, the model learns general rules about distance, for example that nearby atoms usually matter more, while still allowing distant nodes to receive high weight when the data supports it.

Some designs also add a virtual graph token connected to every node. It acts as a global memory, collecting a summary of the whole graph in each layer and broadcasting it back, which gives even sparse-attention variants a short path between any two nodes. Edge features, when present, enter either through the bias term or through separate edge channels updated alongside node states.

Positional and structural encodings

Encodings are the decisive design choice in a graph transformer, because graphs have no natural ordering of nodes. The table summarizes the most common families and what they capture.

EncodingWhat it capturesMain caveat
Laplacian eigenvectors (LapPE)Global position in the spectral domainSign and basis ambiguity
Random-walk encoding (RWSE)Local structure such as cycles and degreeWeaker global position signal
Shortest-path distanceHop distance between node pairsQuadratic preprocessing on large graphs
Centrality encodingNode degree or importanceLittle information about position
Edge-path encodingEdge features along shortest pathsCostly for long paths
Common encodings in graph transformers

Laplacian eigenvectors are defined only up to sign and rotation within repeated eigenvalues, so models either randomly flip signs during training or use invariant networks such as SignNet and BasisNet. Well-chosen encodings let a graph transformer distinguish graphs that the 1-Weisfeiler-Lehman test cannot separate, which is a formal gain in expressiveness.

Graph transformers compared with message passing networks

The core difference is the communication pattern: message passing neural networks exchange information only along edges, while graph transformers allow all-pairs interaction. The comparison below shows the practical consequences.

PropertyMessage passing networksGraph transformers
Receptive field per layerOne hopEntire graph
Time complexity per layerLinear in edgesQuadratic in nodes for full attention
Over-squashingSevere on long-range dependenciesLargely avoided
Inductive biasStrong localityWeak; relies on encodings
Data efficiencyGood on small datasetsNeeds more data or regularization
Typical scaleMillions of nodesHundreds to thousands of nodes
Message passing versus graph transformers

Hybrid architectures such as GraphGPS combine both in each layer: a local message passing module runs in parallel with global attention, and their outputs are summed. This design keeps the locality bias of GNNs while adding long-range reach, and it became a strong default on molecular benchmarks.

Variants and scaling strategies

Because full attention costs O(N squared) in memory and time, much research targets scalability. Each family below makes a different trade-off between expressiveness and cost.

DesignKey ideaTypical use
Graph Transformer (2020)Attention restricted to neighbors plus LapPESmall graphs, baseline studies
SANLearned spectral attention over full graphMolecular property prediction
GraphormerCentrality, distance and edge biasesQuantum chemistry benchmarks
GraphGPSMPNN plus global attention per layerGeneral-purpose graph tasks
ExphormerSparse attention over expander edgesLarger graphs at linear cost
NodeFormer and SGFormerKernelized or simplified linear attentionNode classification on large graphs
Representative graph transformer designs

For very large graphs, practitioners also apply neighbor sampling or subgraph tokenization, treating each node’s local neighborhood as a short sequence. This makes training feasible but reintroduces locality limits similar to those of message passing.

Limitations and practical guidance

Graph transformers are not universally superior. Several re-evaluations on long-range benchmarks found that carefully tuned message passing networks close much of the reported gap, so claims of superiority should be checked against well-tuned GNN baselines.

  • Use them for small to medium graphs where long-range interactions matter, such as molecules, proteins and circuit graphs.
  • Prefer message passing for very large, sparse graphs with strong homophily, such as social or citation networks.
  • Regularize heavily on small datasets, because weak inductive bias leads to overfitting.
  • Budget for preprocessing, since eigendecomposition and shortest-path computation can dominate total cost.
  • Validate encodings separately, because a poor encoding can make attention effectively structure-blind.

Explained without jargon

Many things can be drawn as dots connected by lines: atoms in a molecule, people in a network, parts in a machine. A graph transformer is a model that lets every dot look at every other dot directly, instead of only passing notes to its neighbors.

To keep track of the map, each dot also gets a label describing where it sits. The model then learns which distant dots matter. This helps when an important effect depends on two parts that are far apart.

A typical use case

A pharmaceutical research team wants to predict the solubility of candidate molecules before synthesizing them. Each molecule becomes a graph of 20 to 60 atoms, with bond types as edge features. A standard graph convolutional network struggles when two functional groups on opposite ends of the molecule interact.

The team trains a GraphGPS-style model with random-walk structural encodings and Laplacian positional encodings, combining local message passing with global attention. On a held-out scaffold split, the mean absolute error falls by roughly 15 percent compared with the message passing baseline. The chemists use the model to rank several thousand candidates and send only the top few hundred to the laboratory.