Graph transformers and rigorous evaluation
Add Laplacian and random-walk positional encodings and implement a GPS layer combining local message passing with global attention. Compare with GIN on the ZINC subset under a fixed parameter budget, multiple seeds, component ablations, and significance tests, following benchmark methodology in the field.
After this lesson you can
- Calculate Laplacian encodings with sign ambiguity handling and random-walk encodings.
- Implement a GPS layer with global attention and local message passing.
- Design a comparison with fixed parameter budget and at least 4 seeds.
- Perform ablations and significance tests and report intervals.
Before you start
- P04GIN for molecular classificationWeisfeiler-Leman expressivityGraph attention implementation
- 18Transformer blockSinusoidal positional encodingQuadratic cost of attention
- 25Graph transformer architectureCombinatorial graph LaplacianGraph Fourier transform
- 31Ablation studyStrong baselineStatistical comparison report
- 00Local experiment sweepsExperiment metric tracking
A transformer without a natural sequence
A molecule has no intrinsic position 1, 2, 3 like a sentence. Global attention can communicate two distant atoms in one layer, but without structural information it does not itself know which pairs share a bond. A graph transformer combines structural encoding, local bond messages, and an attention mechanism between nodes. Each piece changes both capacity and cost and should be evaluated separately.
The figure uses a six-node path. Its Laplacian has eigenvectors readable as modes of variation over the graph. Change the index and flip the sign: values change sign but represent the same eigenspace. Figure values are calculated with an exact path formula, not chosen to simulate trained results.
Eigenvectors and walks
Graph positional encodings can be extracted from the combinatorial Laplacian of an undirected graph. If , then too. For a simple eigenvalue, any other unit eigenvector in that eigenspace is or . If the eigenvalue is degenerate, any orthonormal eigenspace basis is obtained by an orthogonal rotation of the original basis: ambiguity exceeds one sign per column.
The figure’s six-node path has, for and ,
The figure’s mathematical node index is 1 to 6; the formula uses to 5. The next cell checks all equations and orthonormality. Eigenvectors with small eigenvalues vary slowly on this path; they are not universal geometric coordinates or a canonical order for every graph.
The relation to smoothness appears in the quadratic form. For a simple unweighted undirected graph, , counting each undirected edge once. A unit eigenvector with a small eigenvalue has a small sum of squared neighbor differences. Eigenvalue zero corresponds to constant values on each connected component; with several components the null space has one dimension per component. The program discards one initial column, not all columns of that null space if the graph is disconnected.
import numpy as np
n=6
A=np.diag(np.ones(n-1),1)+np.diag(np.ones(n-1),-1)
L=np.diag(A.sum(1))-A
V=np.stack([np.ones(n)/np.sqrt(n) if k==0 else np.sqrt(2/n)*np.cos(np.pi*k*(np.arange(n)+.5)/n) for k in range(n)],axis=1)
lam=2-2*np.cos(np.pi*np.arange(n)/n)
print('residuo máximo',np.max(np.abs(L@V-V*lam)))
print('error ortogonalidad',np.max(np.abs([email protected](n))))
assert np.allclose(L@V,V*lam) and np.allclose(V.T@V,np.eye(n))An alternative is random-walk return probabilities: with , node ‘s coordinate at step is . They are invariant to eigenvector sign changes and permute with nodes, though they need not identify every position or distinguish all graphs. For an isolated node we define a zero row here, so later return probabilities are zero; another convention can include a loop and must be declared.
In a three-node path without loops, one-step return is zero for all. In two steps, an endpoint returns with probability ; the center returns with probability . The two-step coordinate thus distinguishes center from endpoints but assigns both endpoints the same value by symmetry. It needs no eigenvector sign choice and does not uniquely identify every node.
Sign augmentation during training exposes the model to both orientations. It does not by itself guarantee exact invariance or resolve arbitrary rotations within a degenerate eigenspace. Disconnected graphs have multiple zero eigenvalues; choosing a particular basis may depend on the numerical algorithm. A robust protocol must document how it handles these ambiguities.
To see the difference between structure and numbering, permute graph node indices with permutation matrix . The Laplacian becomes and a valid transformed basis is . An eigensolver may nevertheless return that basis with different signs or mix columns of a degenerate eigenspace. Column-by-column comparison without aligning bases can produce a large error although both results are correct. An alternative eigenspace check compares projectors , unchanged by rotating the basis within that subspace.
The projector preserves the whole subspace, not a particular column orientation: if is orthogonal, . This comparison is appropriate only when the same eigenspace dimensions are included. Cutting the number of eigenvectors in the middle of a repeated eigenvalue can select an arbitrary part of that space and make even the partial projector depend on the numerical routine’s basis.
Walk returns have another limitation: they summarize local information in a sequence of numbers and structurally different nodes can share it for chosen steps. In a molecule, do not equate “more coordinates” with “better information” without ablation. Dense powers of are convenient on small graphs such as ZINC but may be infeasible for a large one. Preprocessing cost, cache, and isolate definition should accompany model results.
In the program, diagonalizing a molecule’s dense Laplacian with nodes typically costs order and requires a matrix of order . Four walk steps are also calculated with dense matrices. These costs are paid before training and the cache stores coordinates alongside hashes of the three processed files. Reusing the cache avoids repeating work but does not eliminate its initial cost or make that preparation suitable for a huge graph.
Local plus global
A GPS graph transformer layer combines a local step with global attention and a per-node network. This lesson’s program uses a schematic residual sum
Masks prevent one molecule’s attention from seeing another’s nodes. In code the local branch sums messages with bond attributes, the global branch uses dense multi-head attention, and encodings are added to initial embeddings. This implements the modular GraphGPS recipe, not an exact reproduction of all variants. Some versions use linear-cost global mechanisms; the dense attention chosen here still costs quadratically in each graph’s size.
Attention without order encodings can respect node permutation. If becomes , query, key, and value matrices permute likewise; the score matrix becomes . Row softmax and transformed mask permute rows and columns, and output becomes . A symmetric readout can turn those states into an invariant prediction. This requires permuting encodings and mask too: Laplacian basis ambiguity remains separate.
If a permutation is an automorphism preserving structure and input attributes, an equivariant model receives the same input after it. Thus its output states must coincide at nodes swapped by that symmetry. An arbitrarily chosen Laplacian basis can break that numerical equality without providing intrinsic position: repeating with another valid basis is a different check from permuting an already fixed basis.
The implemented variant has three blocks, four global-branch heads, and a per-node network with internal width twice the chosen width. Per-head dimension is total width divided by four. The local branch incorporates bond category before aggregation; the global branch can attend to all valid nodes in the same molecule. All five variants share evaluation protocol, but width is adjusted separately to approximate the budget: comparing times remains necessary to discuss efficiency.
The local branch explicitly transmits bond type; the global branch can relate distant atoms without a shared edge. A residual connection preserves a direct information path and normalization controls scale, but neither proves the model learned the correct chemical dependence. If the global branch helps only when encodings are added, comparison suggests interaction between components; removing one piece at a time does not itself identify all possible interactions. Retain a strong purely local condition too, so attention is not credited for improvement from more training or extra attributes.
For a head materializing all scores, memory cost is proportional to , not the square of total nodes if graphs are processed separately. With 128 graphs of 30 nodes, this is bytes in float32; one 100000-node graph would require bytes, 40 decimal GB. This counts only one head’s scores, not activations, gradients, or buffers. A kernel that does not materialize the full matrix changes actual peak, but does not automatically eliminate all-pairs work.
The program packs each batch into a dense matrix padded to its largest molecule. The mask prevents attention to padding positions, but a dense implementation can perform work and reserve space proportional to rather than . Costs coincide if all batch graphs have 30 nodes, as in the numerical exercise. Grouping by size can reduce padding but changes batch order and must remain reproducible.
In this implementation padding positions are masked as keys and only outputs for real nodes retained. This prevents a valid node receiving information from padding even if the kernel calculates some queries later discarded. The mask fixes which information flows; it does not guarantee padding cost disappears. A memory estimate based only on local edge count also omits the dense global branch.
Protocol and ablations
GNN evaluation methodology fixes split, budget, selection, and metrics before inspecting test. The PyG ZINC subset contains 12000 molecules, with 10000/1000/1000 in training, validation, and test. Its target is penalized logP, a calculated score; it must not be presented as an experimental solubility measurement. We report MAE in target units.
Compare GIN, GIN with encodings, GPS, global attention with encodings, and GPS without encodings. The last two conditions and GIN with encodings are component ablations. The program chooses a width per variant to approach 120000 parameters within 5% and shows counts. Matching parameters does not automatically match compute, time, memory, or effective capacity. Each variant uses four seeds; for each, checkpoint is selected by validation MAE and test calculated afterward.
The four conditions GIN, GIN with encodings, GPS without encodings, and GPS allow examination of whether the difference associated with adding attention changes when encodings are included. For example, compare GPS - GIN con codificaciones (GPS minus GIN with encodings) with GPS sin codificaciones - GIN (GPS without encodings minus GIN). The global-only variant with encodings studies absence of local messages but does not cover every possible combination of branches and encodings. Width adjustment for budget also changes capacity and compute; these differences describe specific configurations and do not isolate one chemical cause.
All variants retain the same split and final sum per molecule. A valid width within 5% is chosen from parameter count before examining test. If two variants have similar MAE, comparing preprocessing and execution cost may also help; a win in MAE does not suffice to claim lower latency or energy consumption. Those quantities require their own measurements and an explicit hardware protocol.
Download the ZINC experiment. It requires PyTorch, PyG, SciPy, and NumPy. It calculates four eigenvectors and four return probabilities per node, stores a cache tied to processed-file hash, and randomizes signs during training. Validation and test use the calculated deterministic basis, so the architecture is not exactly sign-invariant. Target, preparation, and seed are held fixed across models.
python zinc_gps.py --epochs 100 --seeds 4 --output zinc-resultados.json
Each epoch leaves a checkpoint with variant, seed, optimizer, RNG, and processed-file hash. After interruption, repeat the command with --resume and retain configuration; best-state selection still uses validation.
When the sweep finishes, the table generator converts final JSON into two Markdown tables: summary by variant and paired comparisons with intervals and p-values. It rejects partial reports.
python summarize_zinc.py zinc-resultados.json
Device can be fixed with --device cpu or --device cuda, and --threads controls PyTorch threads. The checkpoint retains device and that configuration: do not resume on another device as if it were the same trajectory. The best thread count depends on hardware and load; measure it in the execution environment and record it alongside any timing comparison.
The program reports mean and sample deviation, paired differences by seed, 95% t intervals, and paired t-test p-values. It applies Holm correction to prespecified GPS comparisons with each alternative. With only four pairs, intervals and tests rely on strong assumptions about run differences and have low power; failing to establish a difference does not establish equality. If new variants are selected after looking at test, inference on that same test no longer has its intended interpretation.
Our CPU run of five variants with one thread, up to 100 epochs, and four seeds produced the following test results. The complete JSON retains validation-selected epochs, individual values, and parameter counts. Lower MAE is better.
| Variant | Mean MAE ± deviation |
|---|---|
| GIN | 0.28618 ± 0.01909 |
| GIN with encodings | 0.28434 ± 0.01747 |
| GPS | 0.31688 ± 0.00911 |
| Global only with encodings | 0.58263 ± 0.01008 |
| GPS without encodings | 0.31961 ± 0.00816 |
In the same order, models have 120500, 121044, 121188, 120429, and 120740 parameters.
The paired difference GPS - GIN was 0.03071, with individual 95% t interval [0.01259, 0.04882] and Holm p 0.03745: in this run GIN achieved lower MAE. For GPS - GIN con codificaciones (GPS minus GIN with encodings) the difference was 0.03255 and adjusted p 0.09899; for GPS - solo global (GPS minus global only) it was -0.26574 and 0.00039; for GPS - GPS sin codificaciones (GPS minus GPS without encodings), -0.00273 and 0.76114. This does not establish that GPS is generally worse: it describes these architectures, budget, split, and training. Correction applies to four prespecified comparisons and does not turn individual intervals into simultaneous intervals.
Pairing by seed gives four differences . An interval for their mean accounts for variation in those differences; it is not obtained by separately subtracting both models’ deviations. The same seed does not guarantee two architectures consume the random sequence in the same order; pairing is a design choice, not a promise of identical noise. Holm correction orders p-values and controls familywise error under its conditions, but does not correct undeclared hyperparameter searches or turn four observations into a large sample.
With four differences, the two-sided t interval uses three degrees of freedom: . This is a per-comparison interval without simultaneous adjustment; the program adjusts p-values with Holm, not those intervals. Therefore do not expect every individual interval and adjusted decision to agree as if both used the same correction. Variability reflects seeds for the fixed ZINC split; it does not measure uncertainty about other splits or future molecules outside that distribution.
If all four differences are exactly equal, their estimated deviation is zero and the usual t-test is degenerate. The program leaves interval and p-value undefined in that case rather than interpreting a NaN as evidence for either variant. For other comparisons it retains the prespecified family size when applying Holm. When uncertainty is wide, showing all four pairs and their differences is more useful than summarizing them only with a “significant” label.
Validation checkpoint selection is part of each replicate. If test decides epoch or width, the final result shares information with the decision it evaluates. Reserve test until choices are complete and retain each seed’s selected epoch, validation MAE, test MAE, and effective parameters. Also report time and hardware when conclusions concern efficiency: equal weight budget does not imply equal memory or duration for attention and message branches.
Exercises
Step 1 of 2. If λ's eigenspace is one-dimensional, how are two unit eigenvectors related?
import numpy as np
def random_walk_pe(edge_index,n,k):
...