Module contents
Stage 3 of 8Advanced 110 min

GraphSAGE, GAT and large graphs

Implement GraphSAGE with neighbor sampling and GAT with neighborhood softmax, and train them on ogbn-arxiv, a graph of about 170,000 nodes, within an 8 GB budget. Compare full-batch, neighbor-sampling, and cluster-partition training in memory, time, and accuracy using the official OGB evaluator.

After this lesson you can

  • Implement layer-wise neighbor sampling and node minibatch training.
  • Implement GAT with stable neighborhood softmax and multiple heads.
  • Budget memory for each strategy and choose one suitable for 8 GB.
  • Evaluate on ogbn-arxiv with the official evaluator and multiple seeds.

Before you start

The cost of seeing farther

To calculate a two-hop representation, reading the target node’s neighbors is insufficient: their neighbors are needed too. The number of occurrences can grow quickly even when overlap makes the number of distinct nodes smaller. Neighbor sampling limits how many relations are queried at each hop. Move the controls to see expansion of an idealized tree and its partial cost.

InteractiveThe dependency tree
One root · branches may share actual nodes
2
3
64
Maximum occurrences832
float32 features, 64 channels0.21 MB
The drawing shows one root and uniform fan-out. The counter multiplies occurrences by batch size; repeated nodes and lower degrees reduce the number of unique nodes.

For a batch of BB seeds and fan-outs s1,…,sKs_1,\ldots,s_K counted outward from the output, the occurrence bound is B(1+s1+s1s2+⋯+∏j=1Ksj)B(1+s_1+s_1s_2+\cdots+\prod_{j=1}^Ks_j). This is not a byte bound for complete training: indices, activations, parameters, gradients, and temporaries are omitted. If two branches reach the same node, their occurrences may share storage within a block; states at different layers remain different objects.

GraphSAGE learns a shared function of features and neighborhood instead of a free table by identifier. This permits applying the model to unseen nodes if compatible attributes and edges are known. It does not by itself make evaluation inductive when the full test graph is used during training. ogbn-arxiv has a temporal label split, but keeping the full graph visible is a transductive protocol.

Blocks, estimation, and variance

A bipartite block stores destination nodes, source nodes, and local edges. Start with final destinations and expand backward by layer; computation then proceeds in reverse. Destinations are stored at the start of sources to preserve the self branch. An empty aggregate is defined as zero. The mean layer calculates

hi′=Wselfhi+Wneigh1∣N(i)∣∑j∈N(i)hj+b.\begin{aligned} \vb{h}'_i={}&\mat{W}_{\rm self}\vb{h}_i\\ &+\mat{W}_{\rm neigh}\frac{1}{|N(i)|}\sum_{j\in N(i)}\vb{h}_j+\vb{b}. \end{aligned}

If ss of dd neighbors are selected uniformly without replacement, the sample mean is unbiased for a linear layer’s mean. Its variance in one coordinate is (1−s/d)S2/s(1-s/d)S^2/s, with S2S^2 the sample variance of the neighbor population, d>1d>1, and s≤ds\le d. If s=ds=d it is zero. A subsequent nonlinearity does not generally commute with expectation: sampling one of {−1,1}\{-1,1\} has mean zero, but mean ReLU is 0.5. Repeated layers do not automatically make the full network an unbiased estimator either.

The first result follows because each of the dd neighbors has probability s/ds/d of inclusion. If IjI_j indicates inclusion, μ^=s−1∑jIjhj\widehat\mu=s^{-1}\sum_j I_j h_j has expectation s−1∑j(s/d)hj=d−1∑jhjs^{-1}\sum_j(s/d)h_j=d^{-1}\sum_jh_j. The variance correction 1−s/d1-s/d appears because inclusion without replacement is not independent. Sampling with replacement can repeat an edge and changes that formula; if degree is below fan-out, document whether all neighbors are used or repeated.

To check units, take values 1,2,3,41,2,3,4 and samples of two neighbors. Population mean is 2.52.5 and S2=5/3S^2=5/3. The formula gives (1−2/4)(5/3)/2=5/12(1-2/4)(5/3)/2=5/12. The six possible pairs have means 1.5,2,2.5,2.5,3,3.51.5,2,2.5,2.5,3,3.5; their mean is also 2.52.5 and the mean of squared deviations is 5/125/12. The finite correction is not a regularization heuristic: it exactly describes this sample distribution under the stated assumptions.

An unbiased estimate does not mean each optimization step is identical to full batch. Loss and its gradient are calculated after aggregation and nonlinear functions, and sampling noise interacts with noise from nodes selected for supervision. Increasing fan-out often reduces part of neighborhood variance, but also increases compute and memory. A relevant comparison measures quality, time, and peak under the same validation criterion, rather than choosing the largest fan-out by intuition.

In a block implementation distinguish local indices from global identifiers. Local destination 0 may correspond to global node 812, and the same global node can reappear in blocks of different layers. The layer uses local indices to gather and sum messages; training labels correspond only to supervised seeds. Training on every auxiliary node in the block without a mask changes the example distribution and can include labels the protocol does not permit.

Index orientation is equally important. Here an edge u→vu\to v carries the message from uu to vv: index zero of edge_index is source and one is destination. CSR used for sampling stores possible sources uu in row vv. If the matrix is built under the opposite convention and queried without transposing, the program can run without error but aggregate outgoing neighbors where incoming ones were expected. In a symmetrized graph the difference is hidden; a small test with one directed edge can detect it.

The following implementation accepts fan-out -1 as all neighbors. csr indexes source neighbors by destination row. The example uses a fixed small graph and compares block outputs with full inference and NeighborLoader, both with all neighbors. That equality tests the contract; for finite fan-out samples may differ and pointwise equality is not required.

[ ]Custom blocks and NeighborLoaderLocal GPU
import numpy as np
from scipy import sparse
import torch
from torch_geometric.data import Data
from torch_geometric.loader import NeighborLoader
from torch_geometric.nn import SAGEConv, GATConv

def sample_blocks(csr, seeds, fanouts, rng):
    targets = list(dict.fromkeys(map(int, seeds))); blocks = []
    for fan in fanouts:
        sources = targets.copy(); lookup = {v:i for i,v in enumerate(sources)}; es = []; et = []
        for t,node in enumerate(targets):
            candidates = csr.indices[csr.indptr[node]:csr.indptr[node+1]]
            take = len(candidates) if fan < 0 else min(fan,len(candidates))
            for v in rng.choice(candidates, size=take, replace=False):
                v = int(v)
                if v not in lookup: lookup[v] = len(sources); sources.append(v)
                es.append(lookup[v]); et.append(t)
        blocks.append((np.asarray(sources), np.asarray(targets), np.asarray([es,et],dtype=np.int64).reshape(2,-1)))
        targets = sources
    return blocks[::-1]

def sage_block(features, block, conv):
    source, target, edge = block; index = torch.from_numpy(edge)
    msg = features[index[0]]; n = len(target)
    aggregate = features.new_zeros((n,features.shape[1])); aggregate.index_add_(0,index[1],msg)
    degree = torch.bincount(index[1],minlength=n).clamp_min(1).to(features.dtype)
    return conv.lin_l(aggregate/degree[:,None]) + conv.lin_r(features[:n])

torch.manual_seed(14)
A = sparse.csr_matrix([[0,1,1,0,0],[1,0,1,1,0],[1,1,0,1,1],[0,1,1,0,1],[0,0,1,1,0]])
dst,src = A.nonzero(); edge = torch.tensor(np.stack([src,dst]),dtype=torch.long)
x = torch.randn(5,4); graph = Data(x=x,edge_index=edge)
layers = [SAGEConv(4,3),SAGEConv(3,2)]
blocks = sample_blocks(A,[0,3],[-1,-1],np.random.default_rng(14))
z = x[blocks[0][0]]
for block,conv in zip(blocks,layers): z = sage_block(z,block,conv)
full = layers[1](layers[0](x,edge),edge)[torch.tensor([0,3])]
batch = next(iter(NeighborLoader(graph,num_neighbors=[-1,-1],input_nodes=torch.tensor([0,3]),batch_size=2,shuffle=False)))
pyg = layers[1](layers[0](batch.x,batch.edge_index),batch.edge_index)[:batch.batch_size]
print('error propio',float((z-full).detach().abs().max()),'error NeighborLoader',float((pyg-full).detach().abs().max()))
assert torch.allclose(z,full,atol=1e-6) and torch.allclose(pyg,full,atol=1e-6)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Attention by destination

Graph attention calculates a score for each edge and head. In original GAT, with projected representation zi\vb{z}_i,

eji=LeakyReLU⁡(adst⊤zi+asrc⊤zj),αji=eeji−mi∑k→ieeki−mi,mi=max⁡k→ieki.\begin{aligned} e_{ji}&=\operatorname{LeakyReLU}\bigl(\vb{a}_{\rm dst}\T\vb{z}_i\\ &\qquad+\vb{a}_{\rm src}\T\vb{z}_j\bigr),\\ \alpha_{ji}&=\frac{e^{e_{ji}-m_i}}{\sum_{k\to i}e^{e_{ki}-m_i}},\\ m_i&=\max_{k\to i}e_{ki}. \end{aligned}

Subtracting the maximum does not change the ratio but prevents overflow. One maximum and sum are calculated per destination and head; normalizing across all edges would mix different neighborhoods. A head’s output is ∑j→iαjizj\sum_{j\to i}\alpha_{ji}\vb{z}_j. A node without edges receives zero in this implementation; to preserve it, explicitly add its loops or a self branch. Concatenating heads multiplies output width; averaging gives another shape.

The score separates a destination-dependent term from a source-dependent one. If two neighbors are shared by two queries, adding the same query term and applying a strictly increasing LeakyReLU preserves their score order. That is why GATv2 calls the ordering static; this does not mean numerical attention values or neighbor sets are equal. The variant changes operation order so the query can alter ranking.

Sampling neighbors before attention also changes the denominator. If two neighbors have logits 00 and log⁡3\log 3 and scalar messages 00 and 11, full attention returns 3/43/4. If one is chosen uniformly and softmax applied only to that neighbor, the result is 0 or 1 with equal probability, expectation 1/21/2. Random normalization prevents directly transferring linear mean unbiasedness to this attention. Another sampling distribution or importance correction defines a different estimator and must be described.

A high attention coefficient is a weight within one neighborhood and head. It does not by itself prove that edge causes the prediction: the message also depends on its representation and later layers, and removing an edge renormalizes the rest. To study sensitivity, compare controlled interventions while making clear what information changes and whether the resulting graph remains a valid task input.

Softmax is normalized per destination node and head, not over all graph edges. Subtracting each segment’s maximum before exponentiating prevents overflow without changing the ratio. A destination without edges has no denominator to calculate; its aggregate is defined as zero or a self-loop is added, depending on the layer contract. If loops are added, they must be added consistently in the custom and reference versions before comparing outputs.

Heads can be concatenated in intermediate layers or averaged at the end. Concatenating four heads of 32 channels produces 128 channels per node, not 32 total. Per-edge message representation often dominates memory cost on a large graph: multiplying heads can double or quadruple activations even if output vector dimension is fixed. Speed comparison should therefore include head count and peak memory as well as accuracy.

This laboratory’s symmetrized ogbn-arxiv copy has 2,315,598 directed edges. If GAT adds at most one loop for each of its 169,343 nodes, a materialized message tensor with four heads, 32 channels, and float32 can reach about 1,272,289,792 bytes, approximately 1.185 GiB. Existing loops are replaced and reduce that count slightly. This is one hypothetical matrix, not the actual peak: layers, temporaries, gradients, and optimizer also occupy memory, and a kernel may avoid materializing it.

[ ]Segment softmax and multi-head GATLocal GPU
def segment_softmax(scores,index,n):
    expanded = index[:,None].expand_as(scores)
    maxima = scores.new_full((n,scores.shape[1]),-torch.inf)
    maxima.scatter_reduce_(0,expanded,scores,reduce='amax',include_self=True)
    ex = (scores-maxima[index]).exp()
    denom = scores.new_zeros((n,scores.shape[1])); denom.index_add_(0,index,ex)
    return ex/denom[index]

def gat(x,edge,linear,att_src,att_dst,heads,channels):
    src,dst = edge; h = linear(x).reshape(len(x),heads,channels)
    score = torch.nn.functional.leaky_relu((h[src]*att_src).sum(-1)+(h[dst]*att_dst).sum(-1),negative_slope=.2)
    alpha = segment_softmax(score,dst,len(x))
    out = h.new_zeros(h.shape); out.index_add_(0,dst,h[src]*alpha[...,None])
    return out.reshape(len(x),heads*channels),alpha

conv = GATConv(4,3,heads=2,add_self_loops=False,bias=False,dropout=0)
own,alpha = gat(x,edge,conv.lin,conv.att_src,conv.att_dst,2,3)
ref = conv(x,edge)
print('error GAT frente a PyG',float((own-ref).detach().abs().max()))
assert torch.allclose(own,ref,atol=1e-6)
large = torch.tensor([[1000.,-1000.],[1001.,-999.],[3.,4.]],requires_grad=True)
i = torch.tensor([0,0,2]); a = segment_softmax(large,i,4)
print('softmax estable',a.detach().tolist()); assert torch.isfinite(a).all()

# Contraste también del backward en un grafo dirigido con duplicados y aislados.
torch.manual_seed(31)
xd = torch.randn(6,4,dtype=torch.float64,requires_grad=True)
ed = torch.tensor([[0,2,2,3,0,4,2],[1,1,1,2,2,3,2]])
cd = GATConv(4,3,heads=2,add_self_loops=False,bias=False,dropout=0).double()
own_d,ad = gat(xd,ed,cd.lin,cd.att_src,cd.att_dst,2,3); ref_d = cd(xd,ed)
upstream = torch.randn_like(ref_d); inputs = [xd,cd.lin.weight,cd.att_src,cd.att_dst]
g_own = torch.autograd.grad((own_d*upstream).sum(),inputs,retain_graph=True)
g_ref = torch.autograd.grad((ref_d*upstream).sum(),inputs)
grad_error = max(float((u-v).abs().max()) for u,v in zip(g_own,g_ref))
assert torch.allclose(own_d,ref_d,atol=1e-10,rtol=1e-10) and grad_error < 1e-10
assert torch.equal(own_d[[0,4,5]],torch.zeros_like(own_d[[0,4,5]]))
print('error backward GAT',grad_error)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The final test includes a loop, repeated edge, and destinations without input. It compares output and feature and parameter gradients with the same PyG weights; it does not prove equality for every input or compare trained networks.

Memory budget and evaluation

Large-graph training requires deciding where data live and which activations backward stores. Full batch loads all features and edges and calculates all states each epoch. Neighbor sampling loads blocks and may repeat work across batches. Cluster-GCN groups nodes and trains on subgraphs, sacrificing cross-partition edges when they are not in the same batch. Grouping several partitions recovers some edges without turning every batch into the full graph.

To make the tradeoff concrete, imagine 128 partitions placed uniformly in groups of eight during an epoch. An edge whose endpoints are in the same partition always appears when that partition loads. For endpoints in different partitions, given the first, the second shares a group with probability 7/1277/127: there are seven places among the other 127 partitions. The figure depends on that random grouping and does not assume the METIS cut distributes edges uniformly. Changing partition order across epochs can expose some boundary edges, but each batch still sees only a subgraph.

Sampling and partitioning affect both signal and work. If a high-degree node appears in several batches, its features or messages may be transferred repeatedly; a small batch does not guarantee less total time than one full pass. In Cluster-GCN, partition construction cost is paid before training and can be amortized over epochs, but also uses memory and depends on partitioner version. Comparing only first-epoch time without separating preparation mixes two different costs.

A structural partition with few cuts does not guarantee each batch has the same number of training labels or balanced classes. The program calculates loss only on training nodes and skips a batch without any; remaining nodes can contribute messages without labels. Recording these choices helps distinguish information used to propagate states from information used to supervise loss.

Peak torch.cuda.max_memory_allocated() counts memory allocated by PyTorch to the process; it is not total GPU memory and does not necessarily include all CPU cost. Synchronize before measuring CUDA time and record data loading and partitioning separately. Full layer-wise inference avoids test sampling noise. With multiple seeds, select each checkpoint using validation and report test mean and deviation, not the best seed.

Layer-wise inference requires a precise order: first calculate layer one for all nodes with all their neighbors and save results, then calculate layer two from that complete vector. If both layers are calculated in isolation for each batch, a seed’s neighbors may need states not calculated with their own full neighborhood. Storing an intermediate matrix on CPU reduces GPU memory at the cost of transfers and time; that choice must be counted in evaluation even if the training table separates its cost.

With weights from a short neighbor-SAGE test, both paths were compared on CPU over the 169,343 nodes of symmetrized ogbn-arxiv. Maximum logit discrepancy was 2.39×10−72.39\times10^{-7} and predictions matched at every node. This is an equivalence check for those weights and graph, not a convergence measure or guarantee of exact agreement on every device.

According to OGB, ogbn-arxiv contains 169343 nodes, 1166243 directed citations, 128 attributes, and 40 classes. The split trains through 2017, validates in 2018, and tests from 2019. Symmetrizing edges for an undirected GNN changes input and must be declared. The official evaluator receives labels and predictions for the correct split; accuracy calculated on nodes of a sampled batch is not full-test accuracy.

Supervised-label date and structure visibility are separate decisions. This protocol limits which labels enter the loss but allows the full graph to provide features and edges for aggregation. Temporal label evaluation therefore does not itself simulate a system knowing only documents and citations available on a historical date. That question requires temporal graph views and a declaration of how new nodes, attributes, and edges appear; results would not automatically be comparable to the transductive benchmark.

The OGB leaderboard lists test references 0.7174 ± 0.0029 for GCN and 0.7149 ± 0.0027 for GraphSAGE, with 110120 and 218664 parameters respectively. These are published results of specific configurations, not measurements from this lesson’s program; when depth, width, optimizer, or selection criterion changes they provide context, not a controlled comparison.

Campaign results

Five seeds were trained with the official evaluator and splits, up to 100 epochs and patience 15. The test column shows mean and sample deviation after selecting each model on validation. Runs used PyTorch 2.11.0, PyG 2.8.1, and OGB 1.3.6; the GPU was an RTX 3060. Measured data and hashes allow the figures to be checked.

Model and strategyTrainingTest accuracy
GraphSAGE, fullCUDA0.6546 ± 0.0018
GraphSAGE, neighborsCPU0.6647 ± 0.0054
GraphSAGE, clustersCPU0.6389 ± 0.0023
GCN, fullCUDA0.6501 ± 0.0015
GAT, fullBlocked CPU0.6530 ± 0.0035

Best epochs for each seed are in the JSON. For full GraphSAGE, GCN, and GAT many are near the limit: these runs do not prove convergence. For GAT, seed 0’s first epoch used the usual kernel and subsequent epochs the blocked kernel; the other four seeds used blocks from the start. Leaderboard results use other configurations and are higher; the difference must not be attributed solely to aggregation method. Switching CPU to CUDA can change operation order and random numbers, so backend is also part of the protocol.

To compare GPU costs under a common contract, the following table measures seed 0’s first epoch on CUDA, with training and validation separated. For CPU-trained rows it is an independent resumable CUDA profile, not a complete five-seed GPU campaign. Peak is the maximum allocated by PyTorch during those phases; it excludes preparation, partitioning, and final test inference. Times are observations under shared load, not constants of the card.

Model and strategyTrain, sValidate, sPeak, GiB
GraphSAGE, full0.5310.0901.737
GraphSAGE, neighbors3.3622.3500.173
GraphSAGE, clusters0.6112.4060.129
GCN, full0.7840.0882.786
GAT, full0.9030.0775.286

The five measured profiles stay below 8 GiB allocated memory in those phases, but the process also needs CPU memory and other CUDA components; that figure alone does not guarantee it fits every machine. Clusters reused a METIS partition whose generation took 8.00 s in another preparation, plus 0.16 s preparation in the CPU campaign. In both sampled strategies, layer-wise validation uses all neighbors and can cost more than the training epoch. A full epoch makes one parameter update; a batched epoch makes several, so these seconds do not compare equal numbers of steps.

Reproducible campaign

Download the benchmark program. It requires PyTorch, PyTorch Geometric, pyg-lib with sampling and METIS, NumPy, and OGB. The first run downloads ogbn-arxiv to the root you specify. The program retains the official split, symmetrizes citations, sets 100 maximum epochs and patience 15, selects by validation accuracy, and evaluates test only after restoring the checkpoint. It reports accuracy via Evaluator, seconds, and allocated CUDA peak separately for training, validation, and final evaluation. Partitioning time is reported separately. Each run’s JSON results allow seeds, versions, and budget to be audited.

For GraphSAGE run all three strategies; for GCN and GAT run full batch. The two layers use 128 hidden channels and dropout 0.5; GAT builds four 32-channel heads. In batched strategies the script uses PyG for scalable sampling or METIS, while the earlier custom sampler exposes the mechanism and is checked against PyG. Batched SAGE inference uses all neighbors of one layer, writes all results, and only then proceeds to the next; it does not sample test. Since topology is fixed, it reuses an edge-only loader and gathers each layer’s states separately. Per-epoch training times include sampling and batch transfer but exclude validation. The validation and test timer covers inference and prediction transfer, not subsequent CPU accuracy calculation.

In this configuration networks have 43,176 parameters for SAGE, 21,672 for GCN, and 22,008 for GAT. These count trainable layer parameters and are lower than the OGB references above. Optimizer steps per epoch also differ: full batch performs one and batched strategies one per labeled batch. Equal epochs therefore do not equal updates or compute; consult time and accuracy together without attributing every difference to partitioning strategy.

To train GAT on CPU with less temporary memory, save the blocked entry point, its kernel, and the benchmark in the same directory. Run python gat_blocked_cpu_fresh.py --checkpoint gat-cpu.pt --output gat-cpu.json; add --resume to continue a checkpoint created by that entry point. Aggregation divides edges into blocks and recomputes messages during backward, maintaining attention normalization across all edges per destination. Some summation order and computational cost change: with real weights and a training-only subgraph of 8192 nodes, maximum difference in float32 logits was 2.99×10−72.99\times10^{-7} and in gradients 3.73×10−93.73\times10^{-9}. Validation uses the usual full implementation. A one-epoch blocked process reached 6.21 GB private CPU memory versus 9.21 GB for one epoch with the usual implementation, in different runs under shared load; these figures are not CUDA peaks or universal limits.

If METIS is unavailable on your platform, download the partition generator and install pymetis==2025.2.2 in a compatible environment. For example, the tested pyg-lib build reported METIS available but its call failed on Windows; preparing the assignment on Linux avoided that limitation. The generator reads original edges, symmetrizes them, and generates 128 groups with seed 14; JSON includes source-file hash and preparation cost. Pass that file with --assignment to the cluster command. The benchmark verifies it matches the dataset and uses the assignment in ClusterData.

python partition_pymetis.py --output arxiv-metis.json
python benchmark.py --model sage --strategy clusters --epochs 100 --seeds 5 --assignment arxiv-metis.json --checkpoint sage-clusters.pt --output sage-clusters.json
python benchmark.py --model sage --strategy full --epochs 100 --seeds 5 --checkpoint sage-full.pt --output sage-full.json
python benchmark.py --model sage --strategy neighbors --epochs 100 --seeds 5 --checkpoint sage-neighbors.pt --output sage-neighbors.json
python benchmark.py --model sage --strategy clusters --epochs 100 --seeds 5 --assignment arxiv-metis.json --checkpoint sage-clusters.pt --output sage-clusters.json
python benchmark.py --model gcn --strategy full --epochs 100 --seeds 5 --checkpoint gcn-full.pt --output gcn-full.json
python benchmark.py --model gat --strategy full --epochs 100 --seeds 5 --checkpoint gat-full.pt --output gat-full.json

Each checkpoint file saves training state at the end of each epoch, including optimizer, RNG, and data and split identity. The program also retains each seed’s best model in a .seed-N.best file and records versions, device, and data and code hashes. After interruption, repeat the same command with --resume; a checkpoint from another configuration, code, device, or dataset is rejected. Use separate paths for each strategy. If you change the program, start another campaign or keep the original file to resume the earlier one.

A patience window can stop before epoch 100; changing it or using fewer epochs or seeds defines another run and must be stated in comparisons. The program separately records training peak and full-inference peak, which may differ. Activation budgets, partitioning cost, and parameters differ across architectures, so the table describes one configuration and does not establish a universal ranking.

Exercises

Numeric
A batch of 1024 seeds uses fan-outs 15 and 10 outward from the output. What is the maximum number of occurrences including seeds?
Quiz
Full-pass activations occupy 12 GB and you have 8 GB for the process. What is a reasonable initial decision?
Quiz
What does it mean for an original GAT head to have static attention?
Code
Implement segment_softmax(scores,index,n) for a floating-point E×H matrix and long destination indices. Use stable normalization by destination and head; destinations may be empty.
import torch
def segment_softmax(scores,index,n):
  ...
Shift+Enter to run
Key idea
Sampling controls neighborhood cost but changes the calculation. GAT normalizes per destination and head; quality and budget must be measured with a reproducible protocol and defined inference.