Module contents
Lesson 12 of 30Core 105 min

Graph Attention Networks: attention over neighborhoods

Graph attention replaces degree-based weights with learned neighborhood-normalized coefficients. Implement segment softmax and its backward pass, compare static and dynamic attention, incorporate edge features, and situate graph layers in a common framework.

After this lesson you can

  • Write a multi-head GAT layer using neighborhood softmax, concatenation or averaging.
  • Implement numerically stable segment softmax over edge_index and its backward pass.
  • Prove that GAT attention is static and construct a task GATv2 can solve but GAT cannot.
  • Incorporate edge features into attention and messages.
  • Classify GNN layers and reason about their expressivity and cost.

Before you start

Attention within a neighborhood

A transaction with a familiar account can convey different information from one with an unknown account. Structure determines which messages are available; attention learns coefficients from their features. This does not prove a particular relation is causal or guarantee learned coefficients remain stable under data changes.

In Graph Attention Networks, each head projects hih_i to zi=Whiz_i=Wh_i and computes, for each directed edge j→ij\to i,

eij=LeakyReLU⁡ ⁣(aT[zi∥zj]),αij=exp⁡(eij)∑k∈N(i)exp⁡(eik),hi′=σ ⁣(∑j∈N(i)αijzj).e_{ij}=\operatorname{LeakyReLU}\!\left(a^{\mathsf T}[z_i\Vert z_j]\right),\quad \alpha_{ij}=\frac{\exp(e_{ij})}{\sum_{k\in N(i)}\exp(e_{ik})},\quad h'_i=\sigma\!\left(\sum_{j\in N(i)}\alpha_{ij}z_j\right).

The graph attention layer shares its parameters between nodes. Softmax is computed over incoming edges per destination, not the entire graph. Adding ii to its own neighborhood retains its own state and gives an isolate a nonempty group. Without a self-loop, an implementation must define what an empty neighborhood returns; the lab uses zero.

With HH independent heads, an intermediate layer commonly concatenates hi′=[hi,1′∥⋯∥hi,H′]h'_i=[h'_{i,1}\Vert\cdots\Vert h'_{i,H}]. A final layer can average them to retain one head’s dimension. Concatenating heads of dimension dd gives HdHd channels; averaging gives dd. During training, dropout applied to coefficients after softmax removes and rescales contributions: sums need not equal one in a realization. It is disabled for evaluation.

Normalization makes two neighbors compete within a head. Adding a third with a very high score lowers the previous coefficients even if their scores do not change. A coefficient is therefore relative to the available neighbors and head; it does not measure an absolute edge property. In a directed graph, reversing an edge changes the normalization group and message direction. An implementation storing edge_index[0] as source and edge_index[1] as destination must group by the second row.

With one neighbor, its coefficient is one regardless of score. That head cannot distinguish relative importance through softmax, though its transformed message can still change. Adding a self-loop creates two candidates and changes the denominator. Loop handling must be consistent between training and inference. A library may add loops, replace existing ones or derive edge attributes by a specific rule; inspect it before comparing results.

Heads need not be identical replicas. Each has its own projection and scoring vector and can respond to a different neighborhood property. Concatenation keeps outputs separate for the next layer to combine; averaging mixes them. Neither operation alone guarantees head specialization. State total dimension, parameter count and subsequent classifier width when comparing configurations.

One softmax per destination

For each nonempty segment SiS_i, subtract its maximum mim_i before exponentiating. This does not change the distribution and prevents overflow for large scores. A destination without edges has no maximum or denominator: no probability is created for it.

InteractiveA softmax for each neighborhood
1000.001001.00999.00−1000.00−999.00500.00d0d1d2

Flat destinations: [0, 0, 0, 1, 1, 2]. Values: [1000.000, 1001.000, 999.000, −1000.000, −999.000, 500.000]. Each edge goes from a source to its destination; group 2 contains a single edge.

Step
Highlighted destination
0
Group maximum1001
Group α sum1.000
Six directed edges are grouped by destination. The visualization computes maxima, exponentials and normalization and shows the flat array at each step.

Segment softmax has a compact backward pass. If gij=∂L/∂αijg_{ij}=\partial L/\partial\alpha_{ij}, then for the same destination

∂L∂eij=αij(gij−∑k∈N(i)gikαik).\frac{\partial L}{\partial e_{ij}}=\alpha_{ij}\left(g_{ij}-\sum_{k\in N(i)}g_{ik}\alpha_{ik}\right).

The sum in parentheses is also computed per destination and head. The Jacobian is diag⁡(α)−ααT\operatorname{diag}(\alpha)-\alpha\alpha^{\mathsf T}, without constructing a matrix for each segment. Subtracting the maximum can be treated as a common translation: its contribution cancels because score gradients sum to zero in each segment. In finite precision, evaluate exponentials on shifted values and preserve source and destination indices without swapping them.

For example, scores [1000,1001,999][1000,1001,999] of the first destination shift to [−1,0,−2][-1,0,-2]. Their exponentials are finite and resulting probabilities sum to one. Subtracting one global maximum across destinations is not a safe replacement: a group with much smaller scores can underflow all exponentials and divide zero by zero. Segments permit shifting each group separately without changing its distribution.

Backward also respects isolation between groups. Changing one destination’s loss does not propagate gradients to another destination’s scores through this softmax. Parameters or features participating in several edges can have shared dependencies, and those contributions are summed later. With multiple heads, normalization is independent per destination and head; normalizing heads jointly would change the model.

Can the preferred neighbor change?

Write a=[aL∥aR]a=[a_L\Vert a_R], qi=aLTziq_i=a_L^{\mathsf T}z_i and kj=aRTzjk_j=a_R^{\mathsf T}z_j. The original score is eij=LeakyReLU⁡(qi+kj)e_{ij}=\operatorname{LeakyReLU}(q_i+k_j). Because LeakyReLU with positive negative-side slope is strictly increasing, kj>kℓk_j>k_\ell implies eij>eiℓe_{ij}>e_{i\ell} for any query ii. Softmax preserves ordering. For the same set of keys, the top key is the same for every query, although probabilities and their differences may change. With different available neighborhoods the best available neighbor can vary; edge attributes in scores also change this proof.

GATv2 dynamic attention applies the nonlinearity before scalar projection:

eij=aTLeakyReLU⁡(WLhi+WRhj).e_{ij}=a^{\mathsf T}\operatorname{LeakyReLU}(W_Lh_i+W_Rh_j).

Different channels can now activate depending on the pair and change ordering. For example, with negative-side slope 0.20.2, two channels q−kq-k and k−qk-q and vector (−1/0.8,−1/0.8)(-1/0.8,-1/0.8) give exactly −∣q−k∣-|q-k|. The key closest to the query changes between q=−1q=-1 and q=1q=1. An original GAT score with common keys cannot simultaneously rank both distinct keys first. This limits one head’s score, not every architecture containing GAT on every related problem.

The proof does not require identical probabilities. For example, if the query term shifts some scores across the LeakyReLU kink, score differences and therefore softmax concentration change. The ordering of common keys remains. If negative-side slope were zero, the function would only be nondecreasing and could create new ties; with strictly positive slope it also preserves strict inequalities.

The dynamic counterexample uses distinct query and key projections. For queries −1-1 and 11 and keys with those same values, the first row prefers the first key and the second row the second. The experiment below learns scores for that selection; it uses no real-dataset labels and does not prove GATv2 wins every task. In real applications evaluate the architecture using an appropriate split, budget and seed count.

InteractiveAttention that cannot tell who is asking
k1k2k3q1q2Squares: keysCircles: queriesGAT0.210.320.470.020.120.87GATv20.870.120.020.020.120.87

Rows: queries 1 and 2. Columns: keys k1, k2 and k3. Values are calculated probabilities, not weights of a trained network. In GAT values can vary by query, but their order does not change.

-1.0
-1.0
1.0
1.0
Keys(−1,−1), (0,0), (1,1)
Negative slope0,2
Two queries move in a plane with three common keys. Matrices use additive GAT and GATv2 with four channels representing L1 distance.

The figure extends the example to two coordinates: GAT uses LeakyReLU⁡(qx+qy+kx+ky)\operatorname{LeakyReLU}(q_x+q_y+k_x+k_y) and GATv2 sums the two absolute-distance terms, −∣qx−kx∣−∣qy−ky∣-|q_x-k_x|-|q_y-k_y|. Each distance requires two channels as in the scalar construction. Controls move each query in the plane and recalculate both matrices; keys stay fixed.

Edges, messages and costs

Edge-featured attention can add a projection of ejie_{ji} to the score, message or both. These are different choices: changing the score changes a neighbor’s weight; changing the message changes the information carried. In a molecule, bond category is not an ordinal continuous quantity: it can be encoded with a learned table. TransformerConv uses query-key dot product and can include projected edge attributes in both key and value; check options and self-loop handling in the version used.

Layer families help comparisons: GCN uses degree-determined weights; GAT learns feature-dependent scalar weights; a general MPNN can construct a different message vector per edge. These overlap: attention is a case of message passing. A dot-product transformer over a complete graph must also specify positions, masks and updates to be fully defined.

InteractiveConvolution, attention or message
v1: 1.0v2: 0.4v3: −0.2v4: 0.8v5: 1.3Orange: GCN · Blue: GAT

Destination degree: 6; neighbor degrees: 2, 3, 4, 2, 5. Only neighbor contributions are shown, excluding the self contribution. General message per edge: (x·e, x²).

Neighbor
1.0
1.0
GCN sum0.810
GAT sum0.850
General message(3.00, 3.53)
Five synthetic neighbors. Bars and sums use explicit formulas rather than trained weights; the general message has two channels.

For EE edges and HH heads, storing float32 coefficients costs 4EH4EH bytes. Materializing an dd-channel message per head and edge costs an additional 4EHd4EHd bytes. With 20 million edges, eight heads and 64 channels these are 0.64 GB and 40.96 decimal GB respectively. Fused kernels can avoid materializing every message; indices, activations, gradients and optimizer add other costs. Attention summing to one does not make a coefficient a causal effect: alternatives, correlation, downstream parameters and input distribution matter.

The figure separates the GCN weight from the value carried. Symmetric normalization 1/didj1/\sqrt{d_i d_j} need not sum to one per destination: it is not a softmax. GAT transforms the same neighbor value and multiplies it by a normalized coefficient, while the general message has two channels. A more expressive message network can also cost more memory or overfit; flexibility does not replace evaluation.

A practical interpretation starts by checking whether controlled removal or alteration of an edge changes output, while stating which other variables change. Even that model intervention does not automatically equal a causal effect in the real system: removing a relation can produce out-of-distribution inputs. Attention can help inspect computation, generate hypotheses and detect errors, but those hypotheses need further tests. Comparing heads, repeating training with different seeds and checking perturbation sensitivity help distinguish stable patterns from artifacts.

On a large graph measure the steps omitted by the memory count. Integer indices, node projections, pre-softmax scores, dropout masks and backward states can coexist. Time also depends on degree distribution and memory access: graphs with equal edge counts need not have equal performance. Neighbor sampling can reduce work, but changes the set over which attention is normalized and requires an explicit inference protocol.

Lab: segments and gradients

The first cell is self-contained and uses NumPy. index identifies each edge’s destination. Rows of scores are edges and columns are heads; jointly permuting rows and indices preserves results up to the same reordering. The dropout mask must be fixed during finite-difference checking.

[ ]Stable softmax and backward per destinationBrowser
import numpy as np

def segment_softmax(scores, index, num_nodes):
    scores=np.asarray(scores, dtype=float); index=np.asarray(index, dtype=int)
    maximum=np.full((num_nodes, scores.shape[1]), -np.inf)
    np.maximum.at(maximum, index, scores)
    exp=np.exp(scores-maximum[index]); total=np.zeros_like(maximum)
    np.add.at(total,index,exp)
    return exp/total[index]

def segment_backward(alpha, grad, index, num_nodes):
    dot=np.zeros((num_nodes,alpha.shape[1]))
    np.add.at(dot,index,alpha*grad)
    return alpha*(grad-dot[index])

scores=np.array([[1000.,-3.],[1001.,1.],[-1000.,4.],[-999.,5.],[999.,2.]])
index=np.array([0,0,1,1,0]); alpha=segment_softmax(scores,index,3)
grad=np.arange(10,dtype=float).reshape(5,2)/10
analytic=segment_backward(alpha,grad,index,3); numeric=np.zeros_like(scores); eps=1e-5
for e in range(len(scores)):
    for h in range(scores.shape[1]):
        delta=np.zeros_like(scores); delta[e,h]=eps
        numeric[e,h]=np.sum((segment_softmax(scores+delta,index,3)-segment_softmax(scores-delta,index,3))*grad)/(2*eps)
print('sumas',np.array([alpha[index==i].sum(axis=0) for i in range(3)]).round(6))
print('error gradiente',float(np.max(np.abs(analytic-numeric))))
assert np.allclose(analytic,numeric,atol=1e-8)

The next implementation uses the same projection for source and destination, two heads and an explicit dropout mask. Weights are instructional. Backward propagates through both the message and coefficient computation. It does not automatically add loops: the caller chooses edges.

[ ]Multi-head GAT and GATv2 from scratchBrowser
def layer(x, edge, W, a, version='gat', mask=None):
    src,dst=edge; n=len(x); h=W.shape[1]; d=W.shape[2]
    z=np.einsum('ni,ihd->nhd',x,W)
    if version=='gat':
        pre=(z[dst]*a[0]+z[src]*a[1]).sum(axis=2)
        score=np.where(pre>=0,pre,.2*pre)
    else:
        pre=z[dst]+z[src]
        score=(np.where(pre>=0,pre,.2*pre)*a[0]).sum(axis=2)
    alpha=segment_softmax(score,dst,n)
    if mask is None: mask=np.ones_like(alpha)
    coeff=alpha*mask
    out=np.zeros((n,h,d)); np.add.at(out,dst,coeff[:,:,None]*z[src])
    return out,(x,edge,W,a,version,z,pre,alpha,mask)

def layer_backward(grad, cache):
    x,edge,W,a,version,z,pre,alpha,mask=cache; src,dst=edge
    dz=np.zeros_like(z); da=np.zeros_like(a)
    np.add.at(dz,src,grad[dst]*(alpha*mask)[:,:,None])
    ga=(grad[dst]*z[src]).sum(axis=2)*mask
    gs=segment_backward(alpha,ga,dst,len(x))
    slope=np.where(pre>=0,1.,.2)
    if version=='gat':
        gp=gs*slope
        da[0]=np.sum(gp[:,:,None]*z[dst],axis=0); da[1]=np.sum(gp[:,:,None]*z[src],axis=0)
        np.add.at(dz,dst,gp[:,:,None]*a[0]); np.add.at(dz,src,gp[:,:,None]*a[1])
    else:
        activated=np.where(pre>=0,pre,.2*pre)
        da[0]=np.sum(gs[:,:,None]*activated,axis=0)
        gp=gs[:,:,None]*a[0]*slope
        np.add.at(dz,dst,gp); np.add.at(dz,src,gp)
    return np.einsum('ni,nhd->ihd',x,dz),da,np.einsum('nhd,ihd->ni',dz,W)

rng=np.random.default_rng(21); x=rng.normal(size=(4,3)); W=rng.normal(size=(3,2,2)); a=rng.normal(size=(2,2,2))
edge=np.array([[0,1,2,3,0,2],[0,0,0,1,1,3]])
mask=np.array([[1,0],[1,1],[0,1],[1,1],[1,0],[1,1]],float)/.8
upstream=rng.normal(size=(4,2,2)); eps=1e-6
for version in ('gat','gatv2'):
    out,cache=layer(x,edge,W,a,version,mask); dw,da,dx=layer_backward(upstream,cache)
    errors=[]
    for arg,analytic in ((W,dw),(a,da),(x,dx)):
        numerical=np.zeros_like(arg)
        for idx in np.ndindex(arg.shape):
            arg[idx]+=eps; plus=np.sum(layer(x,edge,W,a,version,mask)[0]*upstream)
            arg[idx]-=2*eps; minus=np.sum(layer(x,edge,W,a,version,mask)[0]*upstream)
            arg[idx]+=eps; numerical[idx]=(plus-minus)/(2*eps)
        errors.append(float(np.max(np.abs(analytic-numerical))))
    print(version,'errores W, a, X',errors,'salida',out.shape)
    assert max(errors)<1e-7

Conventional attention dropout generates a Bernoulli mask and multiplies by 1/(1−p)1/(1-p) during training. The example fixes that mask so the function is deterministic for gradient estimation. Duplicate edges count as separate messages: deduplication changes the distribution when repetitions exist. Sum reduction is invariant to edge order, but floating-point results can vary slightly with accumulation order.

Now directly train scoring parameters on a minimal dictionary. Two queries share two keys and must select the key with the same sign. Loss is attention cross-entropy, so this measures the score’s selection capacity rather than full-classifier performance. Seed and step count are fixed.

[ ]Train the dictionaryBrowser
import numpy as np
q=np.array([-1.,-1.,1.,1.]); k=np.array([-1.,1.,-1.,1.]); dest=np.array([0,0,1,1]); target=np.array([1.,0.,0.,1.])
def train_dictionary(dynamic):
    rng=np.random.default_rng(17)
    if dynamic:
        wq=rng.normal(size=4); wk=rng.normal(size=4); a=rng.normal(size=4)
    else:
        wq=rng.normal(size=1); wk=rng.normal(size=1); a=None
    for step in range(800):
        pre=q[:,None]*wq+k[:,None]*wk
        activated=np.where(pre>=0,pre,.2*pre); slope=np.where(pre>=0,1.,.2)
        score=activated@a if dynamic else activated[:,0]
        alpha=segment_softmax(score[:,None],dest,2)[:,0]
        gs=(alpha-target)/2
        gp=gs[:,None]*slope*(a if dynamic else 1)
        dwq=(gp*q[:,None]).sum(axis=0); dwk=(gp*k[:,None]).sum(axis=0)
        if dynamic:
            da=(gs[:,None]*activated).sum(axis=0); a-=.1*da
        wq-=.1*dwq; wk-=.1*dwk
    accuracy=np.mean(np.argmax(alpha.reshape(2,2),axis=1)==[0,1])
    loss=-np.log(alpha[target==1]).mean()
    return alpha.reshape(2,2),float(loss),float(accuracy)
for name,dynamic in [('GAT',False),('GATv2',True)]:
    weights,loss,accuracy=train_dictionary(dynamic)
    print(name,'atención',weights.round(4).tolist(),'pérdida',round(loss,4),'acierto',accuracy)

With the stated seed, training produced loss 0.5200 and accuracy 0.5 for GAT, versus loss 0.0018 and accuracy 1.0 for GATv2. In the former both rows preferred the second key; in the latter each preferred the same-sign key. This is a small synthetic execution with the same key set for both queries and no edge attributes. It confirms the counterexample for these parameters and does not estimate real-data classification performance.

Cora in the browser

First run the softmax and layer cells above: their functions remain in this page’s Pyodide session. The next first cell downloads a real Cora subgraph from this site, prepared in the previous lesson. It has 380 nodes and 808 directed edges induced from Cora; it contains the original 140 training nodes, 70 validation nodes, 70 test nodes and 100 context nodes. The 16 features are an SVD projection fitted to full-Cora features and standardized on the subgraph, without labels. The procedure and selection are in prepare_cora.py. Access to graph and features is transductive; this test does not replace full-Cora evaluation.

[ ]Load reduced real CoraBrowser
import numpy as np
from pyodide.http import pyfetch
from js import globalThis
try:
    origin=str(globalThis.location.origin)
except (AttributeError,TypeError):
    origin='http://localhost:4321'
response=await pyfetch(origin+'/downloads/m25/l12/cora-subgraph.json')
if not response.ok: raise RuntimeError('No se pudo descargar el subgrafo de Cora')
cora_small=await response.json()
x_cora=np.asarray(cora_small['x'],float); y_cora=np.asarray(cora_small['y'],int)
edge_cora=np.asarray(cora_small['edges'],int).T
loops=np.arange(len(x_cora)); edge_cora=np.concatenate([edge_cora,np.stack([loops,loops])],axis=1)
train_cora=np.asarray(cora_small['train'],int); val_cora=np.asarray(cora_small['val'],int); test_cora=np.asarray(cora_small['test'],int)
print('nodos',len(x_cora),'aristas con bucles',edge_cora.shape[1],'train/valid/test',len(train_cora),len(val_cora),len(test_cora))

Each model has one layer with two four-channel heads and a linear classifier. The layer gradient is implemented above; attention dropout of 0.2 and gradient descent run for twenty epochs. Epoch is selected by validation and test evaluated only afterward. The seed is fixed and reset for each variant; one short execution does not establish superiority or convergence.

[ ]Train NumPy GAT and GATv2 on CoraBrowser
for version in ('gat','gatv2'):
    rng=np.random.default_rng(31)
    W=rng.normal(0,.1,(x_cora.shape[1],2,4)); a=rng.normal(0,.1,(2,2,4))
    C=rng.normal(0,.1,(8,7)); bias=np.zeros(7); best=-1.; chosen=0; state=None
    for epoch in range(1,21):
        mask=(rng.random((edge_cora.shape[1],2))>=.2)/.8
        out,cache=layer(x_cora,edge_cora,W,a,version,mask); hidden=out.reshape(len(x_cora),8); logits=hidden@C+bias
        z=logits[train_cora]-logits[train_cora].max(axis=1,keepdims=True); prob=np.exp(z); prob/=prob.sum(axis=1,keepdims=True)
        grad=prob; grad[np.arange(len(train_cora)),y_cora[train_cora]]-=1; grad/=len(train_cora)
        dlogits=np.zeros_like(logits); dlogits[train_cora]=grad
        dC=hidden.T@dlogits; db=dlogits.sum(axis=0); dW,da,_=layer_backward((dlogits@C.T).reshape(out.shape),cache)
        W-=.05*dW; a-=.05*da; C-=.05*dC; bias-=.05*db
        val_out,_=layer(x_cora,edge_cora,W,a,version,np.ones_like(mask)); pred=(val_out.reshape(len(x_cora),8)@C+bias).argmax(axis=1)
        accuracy=(pred[val_cora]==y_cora[val_cora]).mean()
        if accuracy>best: best=accuracy; chosen=epoch; state=(W.copy(),a.copy(),C.copy(),bias.copy())
    W,a,C,bias=state; final,_=layer(x_cora,edge_cora,W,a,version,np.ones_like(mask)); pred=(final.reshape(len(x_cora),8)@C+bias).argmax(axis=1)
    print(version,'época',chosen,'validación',round(float(best),4),'test',round(float((pred[test_cora]==y_cora[test_cora]).mean()),4))

In the reference execution, both variants selected epoch 19 and obtained validation accuracy 0.1857. Test accuracies were 0.2000 for GAT and 0.2143 for GATv2. These are low results on this subgraph and short budget, not a conclusion about the full dataset or which architecture is better.

Local lab: molecules and edge attributes

The next experiment requires PyTorch, PyG and OGB. It downloads ogbg-molhiv if absent from ORYON_MOLHIV_ROOT (default dataset). It uses the official scaffold split but takes only eight training batches to observe execution and memory; it neither compares ROC-AUC nor uses test. Atom and bond categories are projected using official encoders. CUDA peak is reset after creating each model and includes batch and training step, not CPU dataset loading. Without CUDA, GPU peak is reported unavailable. We fix 16 channels per head, so increasing heads also increases dimension and parameter count: this is not a quality comparison at constant budget.

[ ]GAT, GATv2 and TransformerConv on molhivLocal GPU
import os, time, numpy as np, torch
from torch import nn
import torch.nn.functional as F
from torch_geometric.data.data import Data, DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.loader import DataLoader
from torch_geometric.nn import GATConv, GATv2Conv, TransformerConv, global_mean_pool
from ogb.graphproppred import PygGraphPropPredDataset
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder

root=os.environ.get('ORYON_MOLHIV_ROOT','dataset')
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    dataset=PygGraphPropPredDataset(name='ogbg-molhiv',root=root)
split=dataset.get_idx_split(); device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class MoleculeAttention(nn.Module):
    def __init__(self,kind,heads):
        super().__init__(); self.atom=AtomEncoder(16); self.bond=BondEncoder(16)
        layer={'GAT':GATConv,'GATv2':GATv2Conv,'Transformer':TransformerConv}[kind]
        self.conv=layer(16,16,heads=heads,edge_dim=16,dropout=.1)
        self.out=nn.Linear(16*heads,1)
    def forward(self,batch,attention=False):
        x=self.atom(batch.x); edge=self.bond(batch.edge_attr)
        if attention:
            x,(idx,alpha)=self.conv(x,batch.edge_index,edge,return_attention_weights=True)
            return self.out(global_mean_pool(F.elu(x),batch.batch)),idx,alpha
        x=self.conv(x,batch.edge_index,edge)
        return self.out(global_mean_pool(F.elu(x),batch.batch))

def entropy_by_destination(index,alpha,n):
    terms=-(alpha.clamp_min(1e-30).log()*alpha)
    ent=torch.zeros((n,alpha.size(1)),device=alpha.device); ent.index_add_(0,index[1],terms)
    degree=torch.bincount(index[1],minlength=n); return ent[degree>0].mean().item()

print('dataset',len(dataset),'train/valid/test',*[len(split[x]) for x in ('train','valid','test')],'dispositivo',device)
for kind in ('GAT','GATv2','Transformer'):
    for heads in (1,4):
        torch.manual_seed(12); model=MoleculeAttention(kind,heads).to(device)
        loader=DataLoader(dataset[split['train']],batch_size=64,shuffle=True,generator=torch.Generator().manual_seed(12))
        opt=torch.optim.Adam(model.parameters(),lr=.001)
        if device.type=='cuda': torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize()
        start=time.perf_counter(); model.train(); count=0
        for batch in loader:
            batch=batch.to(device); opt.zero_grad(); logits=model(batch)
            loss=F.binary_cross_entropy_with_logits(logits,batch.y.float().view(-1,1)); loss.backward(); opt.step(); count+=1
            if count==8: break
        if device.type=='cuda': torch.cuda.synchronize()
        elapsed=time.perf_counter()-start; peak=torch.cuda.max_memory_allocated()/1e6 if device.type=='cuda' else None
        model.eval()
        with torch.no_grad():
            _,idx,alpha=model(batch,True); entropy=entropy_by_destination(idx,alpha,batch.num_nodes)
        print(kind,'cabezas',heads,'lotes',count,'pérdida último',round(loss.item(),4),'entropía',round(entropy,4),'segundos',round(elapsed,3),'pico MB',None if peak is None else round(peak,1),'parámetros',sum(p.numel() for p in model.parameters()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Entropy is −∑jαijlog⁡αij-\sum_j\alpha_{ij}\log\alpha_{ij}, averaged per destination with edges and per head in the last training batch, with dropout disabled. GAT and GATv2 in this configuration add self-loops; TransformerConv retains a separate root branch and its attention groups only supplied edges. Entropies are not directly comparable without neighborhood sizes. Eight batches and one seed are not evidence of convergence or generalization; memory depends on batch and device.

An RTX 3060 execution with 41 127 molecules and 32 901 training molecules produced entropies 0.9905 and 1.0910 for one- and four-head GAT, 1.0846 and 1.0950 for GATv2, and 0.6767 and 0.6744 for TransformerConv. Training GPU peaks were 20.1 and 27.4 MB, 21.9 and 30.2 MB, and 21.1 and 27.5 MB respectively. These are peaks allocated by PyTorch in this execution; they include model memory already allocated and do not equal total process capacity. The first run can include kernel initialization, so those times are not used as a ranking.

The molecular label is binary and the cell optimizes cross-entropy over training-batch logits. A quality evaluation would require further training, choosing hyperparameters by validation, calculating ROC-AUC on the official split and reserving test for the final protocol. The scaffold split aims to separate structural families, but does not eliminate every possible dependency or justify generalizing the result to any molecular population.

Cora from scratch: transductive classification

The following local block redefines the browser NumPy functions because the runtimes are independent. It trains a single attention layer with two heads and a linear classifier on the full Cora graph. It uses self-loops, attention dropout and manual gradients, with ten epochs and one seed. This is a short CPU test, not a reproduction of the full training from the paper. Selection uses validation and evaluates test only after selecting the epoch; features and the full graph topology are visible, so the protocol is transductive.

[ ]NumPy training on CoraLocal GPU
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    cora=Planetoid(os.environ.get('ORYON_CORA_ROOT','dataset'),'Cora')
data=cora[0]; x=data.x.numpy().astype(float); x/=np.maximum(x.sum(axis=1,keepdims=True),1)
edge=add_remaining_self_loops(data.edge_index,num_nodes=len(x))[0].numpy(); y=data.y.numpy()
train=np.flatnonzero(data.train_mask.numpy()); val=np.flatnonzero(data.val_mask.numpy()); test=np.flatnonzero(data.test_mask.numpy())
for version in ('gat','gatv2'):
    rng=np.random.default_rng(31); W=rng.normal(0,.05,(x.shape[1],2,4)); a=rng.normal(0,.1,(2,2,4)); C=rng.normal(0,.1,(8,cora.num_classes)); bias=np.zeros(cora.num_classes)
    best=-1.; chosen=0; state=None
    for epoch in range(1,11):
        mask=(rng.random((edge.shape[1],2))>=.2)/.8
        out,cache=layer(x,edge,W,a,version,mask); hidden=out.reshape(len(x),-1); logits=hidden@C+bias
        z=logits[train]-logits[train].max(axis=1,keepdims=True); prob=np.exp(z); prob/=prob.sum(axis=1,keepdims=True)
        grad=prob; grad[np.arange(len(train)),y[train]]-=1; grad/=len(train)
        dlogits=np.zeros_like(logits); dlogits[train]=grad; dC=hidden.T@dlogits; db=dlogits.sum(axis=0)
        dW,da=layer_backward((dlogits@C.T).reshape(out.shape),cache)
        W-=.05*dW; a-=.05*da; C-=.05*dC; bias-=.05*db
        eval_out,_=layer(x,edge,W,a,version,np.ones_like(mask)); pred=(eval_out.reshape(len(x),-1)@C+bias).argmax(axis=1)
        accuracy=(pred[val]==y[val]).mean()
        if accuracy>best: best=accuracy; chosen=epoch; state=(W.copy(),a.copy(),C.copy(),bias.copy())
    W,a,C,bias=state; final,_=layer(x,edge,W,a,version,np.ones_like(mask)); pred=(final.reshape(len(x),-1)@C+bias).argmax(axis=1)
    print(version,'época',chosen,'validación',round(best,4),'test',round((pred[test]==y[test]).mean(),4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The update rule is gradient descent, without an external optimizer. The layer uses the same projection for source and destination in both versions; general GATv2 can also use different projections. Ten epochs are insufficient to attribute small accuracy differences to the architecture, and this code prioritizes clarity over speed. Feature-row normalization uses one as the denominator for empty rows.

In the recorded run, both variants selected epoch 10, with validation accuracy 0.246 and test accuracy 0.195. These are low results from a short test from scratch, not measures of convergence. This implementation normalizes features by row and uses one layer, whereas the next uses two PyG layers and features as loaded by Planetoid; their results do not isolate the effect of scoring.

Cora with PyG

This second local experiment trains a two-layer network on Cora using the public Planetoid split. The full graph and features are available during training; only training labels contribute to the loss. The epoch with highest validation accuracy is saved and test is evaluated once for that selection. Thirty epochs and one seed are an executable diagnostic, not a benchmark comparison. The ORYON_CORA_ROOT variable allows reuse of a download; by default dataset is created.

[ ]GAT and GATv2 on CoraLocal GPU
import os, torch
from torch import nn
import torch.nn.functional as F
from torch_geometric.data.data import Data, DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.nn import GATConv, GATv2Conv
from torch_geometric.datasets import Planetoid
import copy
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
cora_root=os.environ.get('ORYON_CORA_ROOT','dataset')
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    cora=Planetoid(cora_root,'Cora')
graph=cora[0].to(device)
class CoraAttention(nn.Module):
    def __init__(self,layer):
        super().__init__()
        self.first=layer(cora.num_features,8,heads=8,dropout=.6)
        self.last=layer(64,cora.num_classes,heads=1,concat=False,dropout=.6)
    def forward(self):
        x=F.dropout(graph.x,p=.6,training=self.training)
        x=F.elu(self.first(x,graph.edge_index))
        x=F.dropout(x,p=.6,training=self.training)
        return self.last(x,graph.edge_index)

for label,layer in [('GAT',GATConv),('GATv2',GATv2Conv)]:
    torch.manual_seed(7); model=CoraAttention(layer).to(device); opt=torch.optim.Adam(model.parameters(),lr=.005,weight_decay=.0005)
    best=-1.; state=None; best_epoch=0
    for epoch in range(1,31):
        model.train(); opt.zero_grad(); logits=model(); loss=F.cross_entropy(logits[graph.train_mask],graph.y[graph.train_mask]); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            pred=model().argmax(1); val=(pred[graph.val_mask]==graph.y[graph.val_mask]).float().mean().item()
        if val>best: best=val; best_epoch=epoch; state=copy.deepcopy(model.state_dict())
    model.load_state_dict(state); model.eval()
    with torch.no_grad():
        pred=model().argmax(1); test=(pred[graph.test_mask]==graph.y[graph.test_mask]).float().mean().item()
    print(label,'época elegida',best_epoch,'validación',round(best,4),'test',round(test,4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In a local run of thirty epochs and seed 7, validation selected epoch 11 for GAT and 14 for GATv2. Validation accuracies were 0.774 and 0.804, and test accuracies 0.787 and 0.790, respectively. These are measured figures from this short configuration, not a claim of superiority: they change with seed, duration, versions and selection. Test does not participate in epoch selection.

As an additional check, PyG normalizes the same edge list by destination. Autograd computes the gradient of the weighted sum; the manual formula should match even with an empty destination and large scores.

[ ]Comparison with PyG softmaxLocal GPU
import numpy as np, torch
from torch_geometric.utils import softmax
s=torch.tensor([[1000.,-1000.],[1001.,-999.],[-7.,4.],[999.,-1001.]],dtype=torch.float64,requires_grad=True)
idx=torch.tensor([0,0,2,0]); upstream=torch.tensor([[.2,1.],[2.,-.4],[.7,3.],[1.2,.8]],dtype=torch.float64)
a=softmax(s,idx,num_nodes=4); (a*upstream).sum().backward()
scores=s.detach().numpy(); index=idx.numpy(); maximum=np.full((4,2),-np.inf)
np.maximum.at(maximum,index,scores); exponent=np.exp(scores-maximum[index]); total=np.zeros_like(maximum); np.add.at(total,index,exponent)
reference=exponent/total[index]; assert np.allclose(reference,a.detach().numpy(),atol=1e-12)
dot=torch.zeros((4,2),dtype=s.dtype); dot.index_add_(0,idx,a.detach()*upstream)
manual=a.detach()*(upstream-dot[idx]); error=(manual-s.grad).abs().max().item()
print('error backward frente a autograd',error,'sumas por destino',torch.stack([a[idx==i].sum(0) for i in range(4)]).detach().numpy().round(6).tolist())
assert error<1e-12
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Show that an original GAT head has a common maximum key for all queries with the same set of keys.
0
Split vector a into two parts and assume a strictly positive negative slope.

Step 1 of 2. How does the score separate?

Numeric
How many bytes do float32 coefficients for 20 million edges and 8 heads occupy?
Numeric
How many bytes would float32 messages for those edges, 8 heads and 64 channels occupy if materialized?
Quiz
A neighbor receives high attention. What conclusion is justified?
Proof
Prove: Show that the GAT layer is equivariant to a permutation of nodes.
0
Simultaneously permute feature rows and both endpoints of every edge; parameters are shared.

Step 1 of 2. What happens to corresponding edge scores?

Code
Implement segment_softmax(scores, index, num_nodes) and backward(alpha, grad, index, num_nodes). scores has shape edges × heads; index indicates the destination. Use per-segment maxima and sums with numerical stability.
import numpy as np
def segment_softmax(scores,index,num_nodes):
  pass
def backward(alpha,grad,index,num_nodes):
  pass
Shift+Enter to run

Key ideas

Key idea
Attention learns weights in each neighborhood; original GAT retains the order of common keys across queries, whereas GATv2 can change it.

Meaning, self-loops, edge cost and data splitting are all part of defining a graph attention experiment.