A transformer on a graph
Message-passing networks only let a node hear from its neighbours, one hop per layer. A graph transformer lets every node attend to every other node of the graph in every layer, as tokens do in a sentence. Nothing then limits how far information travels, but the attention no longer knows the graph either: full self-attention treats its inputs as an unordered set. Whatever the model should know about the structure has to be added to the node features, as positional encodings.
This page trains such a model on molecules from ZINC, in the 12,000-molecule subset of the benchmark of Dwivedi et al.: atoms are nodes, bonds are edges, and the target is a molecular property, constrained solubility (logP minus the synthetic-accessibility score minus the number of long cycles), scored by mean absolute error (MAE). The transformer is small: 4 pre-norm layers of width 64 with 4 heads, an embedding of the atom type plus a linear map of 8 Laplacian eigenvectors, and mean pooling into one prediction, 138,497 weights. As in the full-graph variant of Dwivedi and Bresson (2020), every atom attends to every atom of its molecule; neither this model nor the baseline reads the bond types.
Laplacian eigenvectors as positions
Words have positions 1, 2, 3; a graph has no first node. The natural replacement comes from spectral graph theory. The normalized Laplacian
has eigenvalues between 0 and 2, and its eigenvectors are the graph's vibration modes: those with small eigenvalues vary slowly across the graph, so atoms close together get similar values, and those with large eigenvalues alternate between neighbours. Dwivedi et al. use the eigenvectors of the smallest nontrivial eigenvalues as each node's position; here , so every atom gets 8 numbers. The Laplacian positions panel colours the atoms of one training molecule, ZINC molecule 72097 with 21 atoms, by the eigenvector chosen in the toolbar. The first, with , splits the molecule into its two halves; later ones cut it into more and more pieces. The strip under the drawing places all 21 eigenvalues on the axis from 0 to 2.
Signs and symmetry
An eigenvector is defined only up to its sign: if then , and the solver returns either. A model fed one sign would learn features tied to an arbitrary choice and would see a different molecule when the other is returned. Dwivedi et al. therefore flip the sign of each eigenvector at random during training, one coin toss per eigenvector per batch, so the model has to cope with both. The row of red and blue ticks under the drawing, and the strip at the bottom of the page, are the signs molecule 72097's batch actually received in each of the 100 epochs (its first eigenvector was flipped in 54 of them); clicking a tick shows the molecule as the model saw it then.
Repeated eigenvalues make it worse: then any rotation within their eigenspace is as valid as the vectors the solver returns. In this dataset 25 % of the training molecules have a repeated value among ; random flips do nothing for them. Sign- and basis-invariant networks such as SignNet and BasisNet (Lim et al., 2023) build the invariance into the model instead of training for it.
Whether the training worked can be measured directly. The All 256 sign patterns panel runs molecule 72097 through the trained transformer with every combination of the 8 signs: with random flips in training its prediction moves over 0.50 of the target's units; a second transformer, identical but always trained on the solver's signs, moves over 1.78. Over the test set, 16 random sign patterns per molecule move a prediction by 0.21 on average for the first model and 1.13 for the second.
Full attention against the bonds
The Full attention vs the bonds panel puts the molecule's adjacency matrix next to the attention map of the chosen layer and head, with the bonded pairs circled. Every atom spreads its attention over the whole molecule, bonded or not. The chart below it averages over all 1,000 test molecules: the share of attention that goes to atoms 0, 1, 2, … bonds away, against the share uniform attention would give (the fraction of atoms at that distance). The curves follow the uniform ones closely; bonded neighbours receive about 9 % of the attention, as they would at random, and an atom's attention to itself ranges from 1 % to 6 % across heads, around the 4.3 % of uniform attention. The eigenvectors tell the model where atoms are, but it does not use that to look at its neighbours more.
Against a GCN
The Error over training chart compares three models trained for 100 epochs on identical batches with Adam, learning rate decaying to on a cosine: the transformer with random signs, the transformer with fixed signs, and a GCN of 4 residual graph convolutions of width 172 (140,181 weights) that sees the bonds through its normalized adjacency matrix. Test MAE after the last epoch: 0.673 for the transformer with random signs, 0.718 with fixed signs, 0.525 for the GCN. The fixed-sign transformer fits its training molecules best (training MAE 0.400 against 0.577) and generalizes worst, the signature of features that depend on the solver's sign choice.
So on this small run the plain GCN wins clearly. Dwivedi and Bresson found the same direction in their experiments: on molecules, attention restricted to the graph's edges beat full attention. Later graph transformers put the graph back in: SAN (Kreuzer et al., 2021) uses separate attention for real and virtual edges and learned spectral encodings, Graphormer (Ying et al., 2021) adds attention biases from shortest-path distances and edge types, and GPS (Rampášek et al., 2022) runs a message-passing layer next to global attention in every block. The GAT tab shows the other end: attention kept strictly to the edges.
How it was recorded
All three models were trained here on a CPU with one thread and the same seed, in about 15, 9 and 4 minutes. The layers are written in plain PyTorch (the </> chips) and checked against nn.MultiheadAttention, nn.TransformerEncoderLayer and PyTorch Geometric's AddLaplacianEigenvectorPE and GCNConv; the check also reproduces the recorded attention maps and test predictions from the recorded weights and retrains the first epoch exactly.
Papers
- A Generalization of Transformer Networks to Graphs The graph transformer with Laplacian positional encodings and random sign flips, and its full-graph variant.
- Benchmarking Graph Neural Networks The ZINC 12k subset and its split, Laplacian eigenvector positions, and the GCN baseline's design.
- Sign and Basis Invariant Networks for Spectral Graph Representation Learning SignNet and BasisNet: the sign and basis ambiguity of eigenvectors handled by the architecture.
- Rethinking Graph Transformers with Spectral Attention SAN: full attention with separate weights for real edges, and learned spectral positional encodings.
- Do Transformers Really Perform Bad for Graph Representation? Graphormer: attention biased by shortest-path distance and edge features.
- Recipe for a General, Powerful, Scalable Graph Transformer GPS: message passing and global attention side by side in every layer.
- Junction Tree Variational Autoencoder for Molecular Graph Generation The ZINC molecule set the benchmark draws from, and the penalized logP target it predicts.