Graph transformers: global attention and structural encodings
Study graph transformer reach, spectral and random-walk encodings, structural attention biases and hybrid models with measured costs.
After this lesson you can
- Compare local and global graph receptive fields.
- Explain Laplacian sign and basis ambiguity and invariant constructions.
- Compute random-walk return encodings and interpret their limits.
- Describe Graphormer biases and GraphGPS hybrid layers.
- Evaluate graph transformer performance and resource use under comparable protocols.
Before you start
Attention needs structure
A message-passing network with layers receives information only from nodes at distance at most . A full attention head can connect two nodes in one layer even when their graph path is long. This shortens the computational path; it does not guarantee the signal survives normalization, noise or difficult training. Cost also changes: a dense matrix has one entry per node pair.
A graph transformer computes attention among nodes and adds information describing the graph. If it receives only node features, without structural encoding or mask, it is permutation equivariant: reordering nodes reorders outputs. Attention can mix the entire set, like a set architecture, but is not literally equivalent to every DeepSets instance. With identical initial features it cannot distinguish two same-size graphs if it cannot see their edges.
Reach does not prove usefulness. A large graph can have thousands of candidates and dilute attention. The model also needs to recognize which distant node matters. Biases, positions and features can supply that information, but must be calculated using edges available at prediction time.
Imagine a chain where a mark at the right endpoint determines the answer requested at the left endpoint. With local aggregation functions and two layers, the left output cannot depend on a mark three edges away if other inputs are equal. The proof is by induction over layers: each update only queries previous neighbor states, so each layer extends the radius by one edge. A global connection removes this reach barrier, although the model must learn to choose the correct endpoint.
Long-range dependence is not synonymous with large geodesic distance in every task. A molecular label may depend on interactions among several groups, aggregate properties or information available in features. Global pooling combines information from all nodes at the end, but does not always let one node adjust its representation according to another before readout. The prediction objective and readout location are part of the comparison.
Equivariance is an operation property, not a promise to distinguish every graph pair. If features are permuted with nodes, per-node output must permute the same way. For a graph-level task an invariant readout such as sum or mean is added. Introducing the file row index as a feature breaks this guarantee: that number can change when saving the same graph in another order.
Spectral coordinates
For an undirected graph the combinatorial Laplacian is . Its lowest-eigenvalue eigenvectors vary smoothly over the graph and can act as coordinates. Laplacian positional encoding concatenates some columns to node features. The normalized Laplacian is another choice with different properties; state which is used.
If , then also . With a repeated eigenvalue any orthonormal basis of the same eigenspace is valid. A solver need not always return the same orientation. Moreover, selecting only part of a repeated eigenspace can break invariance even if sign is handled.
A SignNet-type construction sums using the same function in both branches. The result is unchanged when is replaced by . Augmenting data with random signs during training may help but does not impose exact invariance. Per-column sums are insufficient when the solver mixes columns of a repeated eigenspace.
For a block of orthonormal columns , projector satisfies for every orthogonal matrix . BasisNet uses basis-invariant constructions; a projector can be dense and expensive. Eigenvectors of different eigenvalues should not be mixed: each block has its own symmetry. A disconnected graph has multiple zero eigenvalues and deciding which columns to discard requires care.
The universality guarantees of SignNet and BasisNet depend on their architecture assumptions; the figure’s small example only demonstrates the stated symmetries. On large graphs a dense by decomposition may be infeasible. For few eigenvectors a sparse solver can save memory, though convergence and degeneracy must be controlled.
On the four-node cycle, the combinatorial Laplacian has eigenvalues . The two eigenvectors for eigenvalue 2 can rotate jointly without changing the original matrix. If one column is read as an absolute position, two programs solving the same spectral problem can assign different values to a node. That block’s projector retains node relationships and transforms rows and columns on renaming, but does not itself assign a canonical orientation to the figure.
A practical issue also arises at selection boundaries. Suppose you request the three smallest eigenvectors and the last eigenvalue matches others not included. The chosen subspace can vary with solver because the cutoff has split a degeneracy. Including the full block or designing special handling are different decisions; setting a tolerance for nearly equal eigenvalues introduces a numerical criterion that must be recorded.
An eigenvector may be stable on one graph and change greatly after a small edge modification when eigenvalues are very close. That sensitivity does not necessarily imply solver failure. In an application with changing graphs, assess representation stability under perturbations occurring in data as well as exact symmetries on the same graph.
Random signs during training present alternative orientations of the same vector. Given enough alternatives the model may learn to ignore sign changes, but a finite network with finitely many examples is not forced to. To check the difference, evaluate the same prediction with every sign combination on a small problem; then rotate a degenerate block and repeat. A test flipping all columns at once does not cover independent flips.
The next lab discards the first combinatorial Laplacian eigenvector of each connected toy graph. A disconnected graph has one constant component per connected component. There is no universal rule of discarding one column that removes all such directions: the choice depends on what component information to retain. Near-zero values due to numerical error must also be considered.
Random walks and structure
Let be random-walk transition on positive-degree nodes. A node’s return structural encoding collects . For isolates a zero transition row can be defined; another convention adds a self-loop, changing results.
If permutes nodes, the transformed transition is . Its power is , so the diagonal reorders with nodes. In a simple undirected graph without self-loops and with positive edge weights, exactly when belongs to a triangle: a closed three-edge walk visits two distinct neighbors connected to each other.
RWSE describes local and multiscale structure without choosing a spectral sign, but does not identify all graphs or replace a full WL expressivity analysis. Powers can become dense even when the initial matrix is sparse. Large graphs can use sampling approximations or procedures tailored to required precision; estimation error is declared.
For example, in a triangle each node has two neighbors. Of eight possible sequences of three neighbor choices, two return to the origin, so third-step return is . On a loopless chain no odd closed walk exists: the corresponding value is zero. The NumPy experiment reproduces both results. It does not detect a four-cycle using that same third step; choose walk lengths that answer the question.
A power’s diagonal counts degree-weighted probabilities, not simply cycle count. In an irregular graph two triangles with the same number of edges can contribute different probabilities if their nodes have different degrees. Adding edges changes both possible paths and transition denominators. Thus an RWSE difference should not automatically be interpreted as a difference in raw triangle count.
Walks can be used as message-network input, attention features or signals for graph readout. Keep those decisions separate: a good encoding does not specify which architecture uses it or how it trains. If two nodes have exactly the same chosen return sequence, this descriptor alone cannot distinguish them, although other features or graph context may.
The coding exercise multiplies matrices represented by dictionaries of nonzero entries. It is sparse in initial representation and avoids allocating a dense matrix, but intermediate entries can grow to quadratic. Calling an algorithm sparse is not enough to guarantee linear memory. For large graphs one would limit reach, change algorithm or estimate returns and validate introduced bias and variance.
Graphormer: pairwise biases
A head’s attention combines a query-key product with structural bias before softmax:
Graphormer incorporates centrality in each node representation and uses structural attention biases to modify pairwise attention with distance and edge information. Parameters are learned; the figure’s coefficients are a synthetic rule for inspecting the mechanism.
A finite distance penalty favors nearby pairs without prohibiting distant ones. A mask of does exclude them. Disconnected graphs need a policy for pairs without a path. If several shortest paths exist, choosing one arbitrarily by index can break equivariance: aggregate across paths or set a rule respecting task symmetries, accounting for its cost.
BFS distances from each node cost in an unweighted graph and the matrix occupies . Sparse attention does not become scalable if it first materializes every distance. Path-edge computation must also avoid future information in temporal tasks or held-out edges in link evaluation.
Softmax acts per row: weights of all destinations for a query sum to one. Increasing one destination’s logit also changes other weights through the shared denominator. An attention value should thus be read relative to available candidates, not as a causal probability that an edge caused the prediction.
Input centrality can include in-degree and out-degree separately in a directed graph. Shortest distance can use a parameter table per distance with a special category for disconnected pairs or distances beyond a limit. Path edges can carry features such as bond type; if equivalent paths exist, one selection dependent on index order may introduce unwanted asymmetry.
The figure keeps content logits equal to expose bias effects. In an application queries and keys are learned from features and can favor a distant pair even if its distance bias is negative. Resulting weight depends on both terms. Changing the distance coefficient is not equivalent to changing local layer count: the first alters a distribution over candidates while the second changes which messages can arrive over actual edges.
Attention can simulate certain local aggregators when bias masks all non-neighbor pairs and values are suitably designed. This is a representational-capacity observation, not a guarantee the optimizer finds that behavior or both models use equal resources. Include the local aggregator directly as a baseline in an experiment.
GraphGPS and scale
A GraphGPS layer combines a local edge-message branch with a global attention branch and structural or positional encodings. The recipe allows different layers, normalizations and attention mechanisms; not all GPS models share biases or complexity. The local branch preserves a useful inductive bias and the global offers direct communication. Ablations should separate their contributions.
With , eight heads and float16, one explicit attention matrix needs bytes, approximately 5.96 GiB. This excludes queries, keys, values, activations, gradients and parameters; it is not guaranteed to fit an 8 GiB GPU. A kernel avoiding materialization of the whole matrix can reduce memory, though full-attention work remains quadratic. For ten directed edges per node, eight fp16 scalars per edge would occupy 3.2 MB, only for those weights.
Exphormer sparse attention combines graph edges with connections designed to propagate information through a sparse network. Linear attention changes how the operation is computed or approximated and has its own restrictions; it is not a universally exact version of full softmax. Compare actually measured memory and time, including preparation of positions, distances and extra edges.
How much does the global branch contribute? LRGB proposed long-range tasks; a reevaluation found some published advantage disappeared on several datasets when MPNNs were better tuned. It does not prove global attention never helps. Select hyperparameters on validation with comparable budgets, report multiple seeds, cost and dispersion, and reserve test for final evaluation.
For example, table 1 of that reevaluation reports Peptides-func test AP of 0.6621 for GINE, 0.6765 for GatedGCN and 0.6534 for GPS after hyperparameter search. Final evaluations average four seeds; search uses one run per configuration and a maximum budget of 500000 parameters. These are published figures for their protocol and configurations, not results from this lesson’s reduced lab. The work also shows tasks where GPS retains an advantage and explains that search is not exhaustive.
A useful comparison starts by fixing splits, features and preprocessing. Hyperparameter search should give each family comparable opportunities: the same number of configurations does not guarantee equal compute cost, so publishing time and resources is also useful. Choosing each architecture’s best test result and then comparing them uses test as validation and gives an optimistic estimate.
ZINC and Peptides-func illustrate different metrics. ZINC predicts a numerical property and mean absolute error decreases as performance improves. Peptides-func has multiple binary labels per graph and average precision summarizes ranking for each label; a very small sample may have no positives for a class. Do not directly compare magnitudes of these metrics or interpret average precision as accuracy at a fixed threshold.
To analyze memory, measure with the same batch size and graph set. Maximum nodes in a batch matter when padding a dense attention representation; two batches with the same total nodes may require different memory. A GPU measurement recording only process-reserved memory is not necessarily identical to active tensor memory or available device memory.
If graph node counts vary greatly, grouping similarly sized graphs can reduce padding. This changes batches and may affect time and training, so comparisons should mention it. Also separate encoding preprocessing cost from each epoch’s cost: a stored encoding is computed once, while a transformation depending on trainable parameters may need recomputation.
Kernel attention can factor a sum over keys and values before evaluating queries. This reduces the quadratic term in node count for fixed feature dimension, but changes the kernel used or introduces an approximation. Normalization, feature count and numerical behavior matter. “Linear” does not imply constant memory or exact agreement with softmax attention.
Lab: symmetries and paths
The first cell includes the lesson 9 framework; the second implements LapPE, RWSE, BFS biases and a NumPy attention layer. The triangle detector is an exact property of the example, not a trained classifier. BFS chooses one path by index order: this simplification can break equivariance when tied paths have different edges.
import numpy as np
from collections import deque
def adjacency(n, edges):
a=np.zeros((n,n))
for u,v in edges:
a[u,v]=a[v,u]=1
return a
def lap_pe(a,k):
# Laplaciano combinatorio simétrico; no se incluye el primer autovector.
values,vectors=np.linalg.eigh(np.diag(a.sum(1))-a)
return values[1:k+1],vectors[:,1:k+1]
def rwse(a,k):
degree=a.sum(1)
p=np.divide(a,degree[:,None],out=np.zeros_like(a),where=degree[:,None]!=0)
power=np.eye(len(a)); result=[]
for _ in range(k):
power=power@p; result.append(np.diag(power).copy())
return np.stack(result,axis=1)
def shortest_paths(a):
n=len(a); dist=np.full((n,n),np.inf)
for source in range(n):
dist[source,source]=0; todo=deque([source])
while todo:
u=todo.popleft()
for v in np.flatnonzero(a[u]):
if np.isinf(dist[source,v]):
dist[source,v]=dist[source,u]+1; todo.append(v)
return dist
def path_bias(a,edge_value):
# BFS con desempate por índice: una ruta mínima seleccionada, no todas.
n=len(a); result=np.zeros((n,n)); distances=np.full((n,n),np.inf)
for source in range(n):
distances[source,source]=0; total=np.zeros(n); todo=deque([source])
while todo:
u=todo.popleft()
for v in np.flatnonzero(a[u]):
if np.isinf(distances[source,v]):
distances[source,v]=distances[source,u]+1
total[v]=total[u]+edge_value[u,v]; todo.append(v)
connected=np.isfinite(distances[source]) & (distances[source]>0)
result[source,connected]=total[connected]/distances[source,connected]
return distances,result
def attention(h,bias):
[email protected]/np.sqrt(h.shape[1])+bias
scores=scores-scores.max(axis=1,keepdims=True)
weights=np.exp(scores); weights/=weights.sum(axis=1,keepdims=True)
return weights@h,weights
triangle=adjacency(3,[(0,1),(1,2),(2,0)])
path=adjacency(3,[(0,1),(1,2)])
eigen,v=lap_pe(triangle,2)
# En entrenamiento se pueden voltear signos de forma aleatoria, pero esto no garantiza invariancia.
sign=np.random.default_rng(4).choice([-1,1],size=v.shape[1]); augmented=v*sign
phi=lambda x:x*x+x
assert np.allclose(phi(v)+phi(-v),phi(augmented)+phi(-augmented))
rotation=np.array([[0.,-1.],[1.,0.]])
assert np.allclose([email protected],(v@rotation)@(v@rotation).T)
for a in (triangle,path):
r=rwse(a,3)
has_triangle=r[:,2]>0
print('RWSE paso 3:',np.round(r[:,2],3),'nodos en triángulo:',has_triangle.tolist())
dist,edge_bias=path_bias(a,a*.3)
assert np.array_equal(dist,shortest_paths(a))
out,weights=attention(np.ones((len(a),2)), -dist+edge_bias)
assert np.allclose(weights.sum(1),1)
assert np.isfinite(out).all()
perm=np.array([2,0,1]); rp=rwse(a[perm][:,perm],3)
assert np.allclose(rp,r[perm])
print('Autovalores no triviales:',np.round(eigen,3),'proyector y signos: OK')
print('El detector anterior solo vale para grafos simples no dirigidos sin autolazos.')
# La ruta local de GPS puede apoyarse en el framework de la lección 9.
x=np.ones((3,2)); edges=np.array([(0,1),(1,0),(1,2),(2,1)]).T
layer=MPLayer(2,4,seed=4)
local=layer.forward(x,edges)
global_out,_=attention(x,-shortest_paths(path))
gps=local+global_out
assert gps.shape==(3,2)
print('Salida híbrida NumPy:',gps.shape)
PyG components
This local cell shows shapes and API on a small chain without training. Laplacian encoding may change sign across runs; network output is not numerically compared across versions either. The GPS layer uses full attention, not linear attention.
import torch
from torch import nn
from torch_geometric.data import Data
from torch_geometric.transforms import AddLaplacianEigenvectorPE, AddRandomWalkPE
from torch_geometric.nn import GINEConv, GPSConv
torch.manual_seed(4)
edges=torch.tensor([[0,1,1,2,2,3,3,4,4,5],[1,0,2,1,3,2,4,3,5,4]])
graph=Data(x=torch.ones(6,1),edge_index=edges)
graph=AddLaplacianEigenvectorPE(k=2,attr_name='lap_pe')(graph)
graph=AddRandomWalkPE(walk_length=4,attr_name='rw_pe')(graph)
features=torch.cat([graph.x,graph.lap_pe,graph.rw_pe],dim=1)
h=nn.Linear(7,8)(features)
edge_attr=torch.ones(edges.size(1),8)
local=GINEConv(nn.Sequential(nn.Linear(8,16),nn.ReLU(),nn.Linear(16,8)))
gps=GPSConv(8,local,heads=2,attn_type='multihead')
output=gps(h,edges,batch=torch.zeros(6,dtype=torch.long),edge_attr=edge_attr)
print('LapPE',tuple(graph.lap_pe.shape),'RWSE',tuple(graph.rw_pe.shape),'GPS',tuple(output.shape))
assert output.shape==(6,8)npm run lab and open the connection link.A distant signal in synthetic chains
The reach figure also shows a trained run: two local GINE layers, two global layers and two GPS layers, each with dimension 16 and the same learning rate. Each chain marks the query and source endpoint; the source binary feature is the label. A known position on the chain is added. Graphs are randomly renumbered, but each distance has only two possible feature patterns; train and test are permutations of them, not structurally independent graphs.
With one seed, 64 train examples, 32 test examples and 30 epochs, all three variants got 32/32 at distance 2. At distances 4 and 6, the two-layer local network got 16/32 and the other two 32/32. This demonstrates the reach limit and that these two configurations learned this simple task; it does not prove global attention solves arbitrary long dependencies. The code generates data and retrains, so results may change with version and hardware.
import json, torch
from pathlib import Path
from torch import nn
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader
from torch_geometric.nn import GINEConv,GPSConv
torch.set_num_threads(2)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def graphs(distance,count,seed):
rng=torch.Generator().manual_seed(seed); out=[]; n=distance+1
for i in range(count):
label=i%2; x=torch.zeros(n,4); x[0,0]=1; x[-1,1]=1; x[-1,2]=label
x[:,3]=torch.arange(n)/distance # posición en la cadena, sintética y conocida
edge=torch.tensor([(j,j+1) for j in range(n-1)]+[(j+1,j) for j in range(n-1)]).T
p=torch.randperm(n,generator=rng); inverse=torch.argsort(p)
out.append(Data(x=x[p],edge_index=inverse[edge],y=torch.tensor([label]),query=torch.tensor([inverse[0]])))
return out
class Net(nn.Module):
def __init__(self,kind):
super().__init__(); self.kind=kind; d=16; self.embed=nn.Linear(4,d)
def gin():return GINEConv(nn.Sequential(nn.Linear(d,d),nn.ReLU(),nn.Linear(d,d)))
self.layers=nn.ModuleList([gin() if kind=='local' else GPSConv(d,None if kind=='global' else gin(),heads=2,norm='layer_norm') for _ in range(2)])
self.head=nn.Linear(d,2)
def forward(self,g):
x=self.embed(g.x); attr=torch.zeros(g.edge_index.size(1),16,device=x.device)
for layer in self.layers:
if self.kind=='local': x=torch.relu(x+layer(x,g.edge_index,edge_attr=attr))
elif self.kind=='global': x=layer(x,g.edge_index,batch=g.batch)
else:x=layer(x,g.edge_index,batch=g.batch,edge_attr=attr)
return self.head(x[g.query+g.ptr[:-1]])
results={}
for d in (2,4,6):
train=DataLoader(graphs(d,64,100+d),batch_size=16,shuffle=True)
test=DataLoader(graphs(d,32,200+d),batch_size=16,shuffle=False)
results[d]={}
for kind in ('local','global','gps'):
torch.manual_seed(30); model=Net(kind).to(device); opt=torch.optim.Adam(model.parameters(),lr=.01)
for epoch in range(30):
model.train()
for g in train:
g=g.to(device); loss=nn.functional.cross_entropy(model(g),g.y)
opt.zero_grad();loss.backward();opt.step()
model.eval(); correct=0
with torch.no_grad():
for g in test:
g=g.to(device); correct+=int((model(g).argmax(1)==g.y).sum())
results[d][kind]=correct/32
print('d',d,kind,'test',correct,'/32',flush=True)
print('device',device,flush=True)
output=Path('dataset/oryon-gps/reach_results.json'); output.parent.mkdir(parents=True,exist_ok=True)
output.write_text(json.dumps(results,indent=2),encoding='utf8')
npm run lab and open the connection link.Reproducible experiment on ZINC and Peptides-func
The following local cell downloads PyG-distributed splits: reduced ZINC has 10000/1000/1000 graphs and Peptides-func 10873/2331/2331. It needs Python, PyTorch, PyG, SciPy and scikit-learn, plus storage and a connection to download files. PyG uses serialized files from its data sources; use trusted distributions only. The program prints SHA-256 of downloaded files and saves results in the local data folder.
In this run, the Peptides-func train file had SHA-256 f79896a52fd153d75925d5975b7298b57bdf72f0250d9e4bddf1f976174f1a6e and the ZINC train file 9c76df5a1ab90aac200df22902893827168aeced3df87aab4b6bee100235d7f2. PyG obtains ZINC and LRGB files from sources configured by their classes. Hashes identify measured files; readers must verify origin before opening serialized data.
The measured run used the first 128/64/64 graphs of each split, two epochs, batch 8 and one seed on an RTX 3060 GPU. Widths 32 and 64 were tried per model and the lowest validation loss selected: MAE for ZINC and binary cross-entropy for Peptides. The prefix can be biased; searching two widths is not exhaustive tuning. GatedGCN is a simplified version with per-edge gates, not the paper implementation. All four variants receive LapPE and RWSE; the linear global branch uses the ELU+1 kernel and is not exactly GPS softmax. Parameters and normalizations are not identical.
| Selected model | ZINC test MAE | Peptides test AP | ZINC train+valid time (s) | ZINC peak (MB) |
|---|---|---|---|---|
| GINE | 1.6393 | 0.2149 | 2.03 | 19.50 |
| Simplified gates | 1.6300 | 0.2482 | 1.62 | 19.53 |
| GPS, full attention | 1.5243 | 0.2540 | 1.59 | 22.19 |
| Hybrid, linear attention | 1.7184 | 0.2132 | 1.50 | 21.24 |
Test-prefix AP averages only nine of ten labels because one has no positives; it is not the official full-test metric. Times include training and validation of the selected configuration but not preprocessing or download, and can vary with device load. Peak counts process-allocated tensor memory, not all occupied GPU memory. Selected widths differ among models. These values illustrate the procedure and do not establish a reliable architecture ranking.
To reproduce the small test run the cell with defaults. Environment variables in the code can change sizes and epochs. Evaluating all test requires raising the evaluation limit, and increasing training or search takes more time; changing those options does not reproduce the table. The code retains the official split and selects each model without looking at test.
import os, time, json, hashlib, copy
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from sklearn.metrics import average_precision_score
from torch_geometric.datasets import ZINC, LRGBDataset
from torch_geometric.transforms import AddLaplacianEigenvectorPE, AddRandomWalkPE
from torch_geometric.loader import DataLoader
from torch_geometric.nn import GINEConv, GPSConv, global_mean_pool
from torch_geometric.utils import to_dense_batch
torch.set_num_threads(2)
torch.manual_seed(31); np.random.seed(31)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
root=Path(os.environ.get('GPS_DATA','dataset/oryon-gps'))
limit=int(os.environ.get('GPS_TRAIN','128')); eval_limit=int(os.environ.get('GPS_EVAL','64'))
epochs=int(os.environ.get('GPS_EPOCHS','2')); batch_size=int(os.environ.get('GPS_BATCH','8'))
names=os.environ.get('GPS_DATASETS','ZINC,Peptides-func').split(',')
class Gate(nn.Module):
# GatedGCN simplificada: puertas por arista, normalizadas por destino.
def __init__(self,d):
super().__init__(); self.gate=nn.Linear(3*d,d); self.msg=nn.Linear(d,d); self.self=nn.Linear(d,d)
def forward(self,x,edge_index,edge_attr):
s,t=edge_index
weight=torch.sigmoid(self.gate(torch.cat((x[s],x[t],edge_attr),dim=1)))
num=torch.zeros_like(x).index_add_(0,t,weight*self.msg(x[s]))
den=torch.zeros_like(x).index_add_(0,t,weight)
return F.relu(self.self(x)+num/(den+1e-6))
class LinearGlobal(nn.Module):
# Atención de kernel ELU+1, no una aproximación exacta de softmax.
def __init__(self,d):
super().__init__(); self.q=nn.Linear(d,d); self.k=nn.Linear(d,d); self.v=nn.Linear(d,d)
def forward(self,x,batch):
dense,mask=to_dense_batch(x,batch)
q=F.elu(self.q(dense))+1; k=(F.elu(self.k(dense))+1)*mask.unsqueeze(-1)
v=self.v(dense)*mask.unsqueeze(-1)
kv=torch.einsum('bnd,bne->bde',k,v); ks=k.sum(1)
out=torch.einsum('bnd,bde->bne',q,kv)/(torch.einsum('bnd,bd->bn',q,ks).unsqueeze(-1)+1e-6)
return out[mask]
class Model(nn.Module):
def __init__(self,dim_in,dim_edge,dim_out,h,kind):
super().__init__(); self.kind=kind
self.node=nn.Linear(dim_in+6,h); self.edge=nn.Linear(dim_edge,h)
def gin(): return GINEConv(nn.Sequential(nn.Linear(h,2*h),nn.ReLU(),nn.Linear(2*h,h)))
self.layers=nn.ModuleList()
for _ in range(2):
self.layers.append(GPSConv(h,gin(),heads=2,attn_type='multihead') if kind=='gps' else Gate(h) if kind=='gated' else gin())
self.linear=nn.ModuleList([LinearGlobal(h) for _ in range(2)]) if kind=='linear' else None
self.head=nn.Linear(h,dim_out)
def forward(self,g):
x=g.x.float().reshape(g.num_nodes,-1)/100
x=self.node(torch.cat([x,g.lap_pe,g.rw_pe],dim=1)); edge=self.edge(g.edge_attr.float().reshape(g.edge_index.size(1),-1)/10)
for i,layer in enumerate(self.layers):
if self.kind=='gps': x=layer(x,g.edge_index,batch=g.batch,edge_attr=edge)
elif self.kind=='linear': x=F.relu(x+layer(x,g.edge_index,edge_attr=edge)+self.linear[i](x,g.batch))
else: x=F.relu(x+layer(x,g.edge_index,edge_attr=edge))
return self.head(global_mean_pool(x,g.batch))
def transform(g):
# Las tres primeras columnas no triviales; no se garantiza invariancia de base.
g=AddLaplacianEigenvectorPE(3,attr_name='lap_pe')(g)
g=AddRandomWalkPE(3,attr_name='rw_pe')(g)
return g
def score(model,loader,kind):
model.eval(); pred=[]; target=[]
with torch.no_grad():
for g in loader:
g=g.to(device); pred.append(model(g).cpu()); target.append(g.y.reshape(g.num_graphs,-1).cpu())
p=torch.cat(pred); y=torch.cat(target)
loss=F.l1_loss(p,y).item() if kind=='ZINC' else F.binary_cross_entropy_with_logits(p,y).item()
if kind=='ZINC': return loss,loss,1
valid=[i for i in range(y.shape[1]) if y[:,i].sum()>0]
ap=float(np.mean([average_precision_score(y[:,i].numpy(),p[:,i].numpy()) for i in valid])) if valid else float('nan')
return loss,ap,len(valid)
def run_dataset(name):
def load(split):
return ZINC(str(root/'ZINC'),subset=True,split=split) if name=='ZINC' else LRGBDataset(str(root/'LRGB'),name='Peptides-func',split=split)
raw=[load(s) for s in ('train','val','test')]
sizes=[min(limit,len(raw[0])),min(eval_limit,len(raw[1])),min(eval_limit,len(raw[2]))]
sets=[[transform(raw[s][i]) for i in range(sizes[s])] for s in range(3)]
loaders=[DataLoader(ds,batch_size=batch_size,shuffle=(s==0)) for s,ds in enumerate(sets)]
xdim=sets[0][0].x.reshape(sets[0][0].num_nodes,-1).shape[1]
edim=sets[0][0].edge_attr.reshape(sets[0][0].edge_index.size(1),-1).shape[1]
output=1 if name=='ZINC' else 10
print(name,'split completo',list(map(len,raw)),'muestra',sizes,'device',device,flush=True)
results={}
for kind in ('gin','gated','gps','linear'):
best=None
for h in (32,64):
torch.manual_seed(31); model=Model(xdim,edim,output,h,kind).to(device)
opt=torch.optim.Adam(model.parameters(),lr=.001)
if device.type=='cuda': torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize()
started=time.perf_counter()
for epoch in range(epochs):
model.train()
for g in loaders[0]:
g=g.to(device); pred=model(g); y=g.y.reshape(g.num_graphs,-1)
loss=F.l1_loss(pred,y) if name=='ZINC' else F.binary_cross_entropy_with_logits(pred,y)
opt.zero_grad(); loss.backward(); opt.step()
val_loss,val_metric,val_tasks=score(model,loaders[1],name)
if device.type=='cuda': torch.cuda.synchronize()
duration=time.perf_counter()-started
record={'hidden':h,'val_loss':val_loss,'val_metric':val_metric,'val_tasks':val_tasks,
'seconds_train_val':round(duration,2),'peak_bytes':torch.cuda.max_memory_allocated() if device.type=='cuda' else None}
print(kind,record,flush=True)
if best is None or val_loss<best[0]: best=(val_loss,{k:v.detach().cpu().clone() for k,v in model.state_dict().items()},record)
model=Model(xdim,edim,output,best[2]['hidden'],kind).to(device); model.load_state_dict(best[1])
test_loss,test_metric,test_tasks=score(model,loaders[2],name)
results[kind]={**best[2],'test_loss':test_loss,'test_metric':test_metric,'test_tasks':test_tasks}
return {'splits':list(map(len,raw)),'sample':sizes,'epochs':epochs,'batch':batch_size,'device':str(device),'models':results}
all_results={name:run_dataset(name) for name in names}
root.mkdir(parents=True,exist_ok=True)
files={}
for f in sorted(root.rglob('*')):
if f.is_file() and 'raw' in f.parts:
files[str(f.relative_to(root))]=hashlib.sha256(f.read_bytes()).hexdigest()
print('SHA-256 archivos raw:',files,flush=True)
print(json.dumps(all_results,indent=2),flush=True)
(root/'gps_results.json').write_text(json.dumps({'raw_sha256':files,'results':all_results},indent=2),encoding='utf8')
npm run lab and open the connection link.Exercises
Step 1 of 3. If Lv = λv, what happens to -v?
Step 1 of 3. What happens to P when nodes are renamed by Π?
def rwse(edge_index, n, K):
pass