Module contents
Lesson 11 of 30Core 110 min

GraphSAGE and GNNs at scale: induction and sampling

Study inductive GraphSAGE, neighbor and subgraph sampling, neighborhood explosion, historical embeddings and practical memory-aware training.

After this lesson you can

  • Implement GraphSAGE aggregators and explain the own-state branch.
  • Estimate computation-tree sizes and analyze sampled-mean bias and variance.
  • Build bipartite sampled blocks from CSR neighborhoods.
  • Compare node-wise, layer-wise and subgraph sampling.
  • Evaluate scalable training on ogbn-products with an explicit memory budget.

Before you start

Learning a function for new nodes

A purchasing or payment network receives entities and relationships after training. A table assigning a free vector to each identifier has no learned row for the new node. GraphSAGE learns a shared function transforming a node’s features and its neighborhood’s features; it can apply this to an unseen node if compatible attributes and relations are available. This inductive capacity does not guarantee accuracy under arbitrary distribution shift or infer an unobserved attribute.

A GraphSAGE layer separates the node’s own state from its neighbors:

mv(ℓ)=AGG⁡ℓ{hu(ℓ−1):u∈N(v)},hv(ℓ)=σ ⁣(Wℓ[hv(ℓ−1)∥mv(ℓ)]+bℓ).m_v^{(\ell)}=\operatorname{AGG}_\ell\{h_u^{(\ell-1)}:u\in N(v)\},\qquad h_v^{(\ell)}=\sigma\!\left(W_\ell[h_v^{(\ell-1)}\Vert m_v^{(\ell)}]+b_\ell\right).

Concatenation allows different coefficients for own and aggregated information. It can be written as two matrices Wselfhv+WneighmvW_{\rm self}h_v+W_{\rm neigh}m_v; summing the two signals first and using one matrix imposes another constraint. The original algorithm normalizes each representation by its L2L^2 norm after updating. Some implementations make normalization optional: for a zero vector, define the result without dividing by zero.

Mean aggregation is symmetric and retains a first-order statistic, but can confuse distinct multisets. Pooling applies a shared network to each neighbor and takes a channelwise maximum; different neighbors can win different channels. An LSTM processes a sequence: changing order can change output. Shuffling order during training makes the input distribution more symmetric but does not make every LSTM execution exactly invariant. Code must choose a convention for an empty list; here the empty aggregate is zero and the own-state branch remains available.

InteractiveGraphSAGE aggregators

Neighbor feature sequence:

−1.00
−0.25
0.20
0.80
1.20

Mean is symmetric. Pooling applies the same tanh function to each neighbor and takes the maximum, so it is symmetric too. An LSTM updates sequential memory and its output can change under reordering.

Shuffling neighbors during training can reduce statistical sensitivity, but does not make the LSTM exactly invariant for every permutation.

Mean0.1900
Max pooling0.8764
LSTM0.3612
Five scalar values and a fixed-weight LSTM are actually processed in the stated order. Mean and pooling are symmetric; reversing or rotating the sequence can change LSTM state.

The figure uses tanh⁡(1.3x−0.2)\tanh(1.3x-0.2) before the maximum and a scalar LSTM with zero initial state. These are instructional parameters, not weights of a trained model. The full layer must also combine the aggregate with the node’s own feature and may apply a nonlinearity and normalization. In specific libraries, check operation order and whether the node itself is included in its neighbor list.

Consider a new product purchased alongside other items. An aggregator can combine its description with neighboring descriptions without reserving a parameter for its identifier. If it arrives without relationships, the own-state branch still produces a representation; the empty-aggregate convention determines the other half of the input. If relationships appear after the first prediction, the representation can change. To measure inductive generalization, separate new nodes or graphs before fitting and avoid using their labels for model selection. A transductive evaluation on the full graph answers another question even with the same architecture.

Mean loses absolute multiplicity: {1,3}\{1,3\} and {1,1,3,3}\{1,1,3,3\} have the same mean. Max pooling can ignore neighbors that win no channel. These observations describe what information a task might need and why adding degree, sum or other features can change what is learned. With LSTM, the ordering seed also affects reproducible comparison; report whether you average several permutations or use one.

Neighborhood explosion

A batch of BB output nodes needs its neighbors; a second layer needs neighbors of those neighbors. If all had degree dd, the unrolled KK-hop tree would have at most B∑j=0KdjB\sum_{j=0}^K d^j occurrences under that uniform assumption. Neighborhood growth counts tree positions: one node may appear on several branches, and deduplicating a real block reduces unique-node count. A graph’s mean degree is not an upper bound for every node; hubs can have much higher degree.

With fan-outs s1,…,sKs_1,\ldots,s_K per hop, the corresponding count is B(1+s1+s1s2+⋯+∏j=1Ksj)B(1+s_1+s_1s_2+\cdots+\prod_{j=1}^Ks_j). Fan-outs limit samples per destination, but not every node has that many neighbors; without replacement, all are taken when degree is lower. For 1024 seeds and [15,10,5][15,10,5] there are at most 937 984 occurrences. Storing 100 float32 values per occurrence would take 375 193 600 bytes, or 0.375 decimal GB. This excludes index matrices, hidden states, gradients, optimizer and copies, and does not deduct overlaps.

InteractiveNeighborhood explosion

For each seed the tree retains its root and expands each hop. Degree is a uniform reference, not a bound if a real node has more neighbors. The calculator caps each fan-out at reference degree when sampling without replacement.

Without sampling: 52.245 GB of features
With sampling: 0.375 GB of features
Bar saturates at 8 GB; this is a comparison budget, not measured available memory.

Two branches can visit the same node and blocks deduplicate nodes. This counts maximum occurrences in the assumed tree; it does not measure unique nodes or guarantee training fits.

1024
50
3
15
10
5
Occurrences without sampling130,612,224
Sampled occurrences937,984
Features without sampling52.245 GB
Sampled features0.375 GB
Occurrence calculator, not unique-node count. Compare the reference uniform-degree tree with chosen fan-outs; bars show only hypothetical feature memory against 8 decimal GB.

For d=50d=50, K=3K=3 and 1024 seeds, the unsampled tree has 130 612 224 occurrences and those features would occupy approximately 52.245 GB. This does not establish that a particular graph has exactly that cost: repetitions, variable degrees and storage strategies differ. Conversely, feature memory under 8 GB does not prove the model and all activations fit.

The [15,10,5] fan-out count starts with 1024 roots, adds up to 15 360 occurrences at the first hop, 153 600 at the second and 768 000 at the third. These figures depend on ordering from output outward; a loader listing fan-outs in layer-execution order may use the reverse convention. State the convention with the experiment. A repeated node can be shared once inside a block, but appearances at different layers correspond to different states and dependencies.

Activation memory also depends on hidden channels and the number of layers retained for backward. A useful estimate separately sums fetched features, source and destination indices, weights, intermediate states, gradients and optimizer state. Temporary buffers and fragmentation can increase the peak. Measuring only feature-vector size gives a partial bound, not a full memory forecast.

Sampled mean, variance and nonlinearity

Neighbor sampling replaces each full aggregate with one computed from a sample. For d>0d>0 neighbors with values x1,…,xdx_1,\ldots,x_d, a uniform sample without replacement of size s≤ds\le d gives μ^=s−1∑j∈Sxj\hat\mu=s^{-1}\sum_{j\in S}x_j. Each neighbor is included with probability s/ds/d, so E[μ^]=d−1∑jxj\mathbb E[\hat\mu]=d^{-1}\sum_jx_j. If Sx2=(d−1)−1∑j(xj−μ)2S_x^2=(d-1)^{-1}\sum_j(x_j-\mu)^2 and d>1d>1,

Var⁡(μ^)=(1−sd)Sx2s.\operatorname{Var}(\hat\mu)=\left(1-\frac{s}{d}\right)\frac{S_x^2}{s}.

The finite-population correction makes variance zero when all neighbors are used. Equal expectations apply to one linear layer and a particular sample. Applying a nonlinearity afterward generally does not preserve expectation: with neighbors −1-1 and 11, sampling one has unbiased mean zero, but E[ReLU⁡(μ^)]=0.5\mathbb E[\operatorname{ReLU}(\hat\mu)]=0.5 whereas ReLU⁡(μ)=0\operatorname{ReLU}(\mu)=0. Across layers, errors, shared neighborhoods and nonlinearities combine; proving the first mean unbiased is insufficient.

A bipartite block stores required source nodes and destination nodes whose outputs are computed, along with local edge indices. Output seeds expand backward by layer; computation then proceeds in reverse order. Each destination must also retain its own feature. Deduplicating within a block does not necessarily remove repetition between blocks or prevent all expansion.

For example, if final destinations are [v,w][v,w], first choose their neighbors. Those two destinations and selected neighbors form the last block’s sources. To calculate their states in the preceding layer they are expanded again: destinations of that earlier block are exactly sources of the next. The edge matrix uses local indices to save space, but the result must retain an unambiguous mapping to global identifiers. The own-state branch needs no artificial edge if the block keeps destinations at the start of sources, as the lab does.

Sampling with replacement changes variance and can repeat a neighbor; this lesson samples without replacement. If degree is below ss, taking all neighbors has zero variance for that mean. The isolate case is separate because its mean is undefined by formula 1/d1/d; assigning zero to the empty aggregate is an implementation convention, not a deduction from that formula.

Three sampling perspectives

InteractiveThree ways to sample
123456789101112

Green: seeds 1, 5 and 9. Blue: nodes used. Orange: edges used to calculate the aggregate. Values per node: 1: 0.1 · 2: 0.2 · 3: 0.4 · 4: 0.6 · 5: 0.3 · 6: 0.5 · 7: 0.8 · 8: 0.9 · 9: −0.2 · 10: 0.1 · 11: 0.7 · 12: 1.1.

Each seed chooses two neighbors without replacement and averages their values. Statistics use 1500 samples with a fixed seed.

Sampling
Exact aggregate0.4483
This sample0.4167
Empirical bias−0.0004
Empirical variance0.0137
Fixed synthetic graph with 12 nodes and three seeds. Each strategy computes a particular estimator of mean aggregates; 1500 reproducible samples are compared, not invented results from complete methods.

The figure’s node sampling selects two neighbors per destination and averages them. Global layer sampling chooses four of twelve nodes, multiplies each selected contribution by 12/412/4 and divides by each destination’s actual degree: this estimates a linear aggregate using uniform inclusion. It can sample nodes that are not neighbors of a destination and increase variance. The third scheme induces a subgraph from seeds and four more nodes; averaging only visible edges without correction can give a biased estimator. The plot illustrates these rules, not full implementations of FastGCN, LADIES or GraphSAINT.

FastGCN layer-wise sampling interprets convolution as an integral and uses importance sampling. LADIES conditions the distribution on nodes in the next layer to reduce disconnected samples. Chosen probabilities, weights and normalization matter: not every global subset reproduces those algorithms.

In a sum ∑jaj\sum_j a_j, if index JJ is drawn with positive probability qjq_j, ratio aJ/qJa_J/q_J has expectation equal to the sum. The price is variance: an important term with tiny probability receives enormous weight when drawn. Sampling without replacement uses appropriate inclusion probabilities, which need not equal probabilities of a single draw. The figure uses known uniform inclusion; practical methods use more elaborate rules to balance connectivity and cost.

Subgraph sampling first constructs a batch of nodes and edges and runs layers on that subgraph. Cluster-GCN groups graph partitions; mixing several partitions in a batch can recover some intergroup edges. One homogeneous partition can yield unrepresentative gradients. GraphSAINT uses specific inclusion probabilities and normalizations; correcting a linear sum does not automatically make a deep nonlinear network’s gradient unbiased in every configuration.

Memory and changing data

Historical embeddings store previously calculated node states to reduce repeated work. These can be stale relative to current parameters and use additional memory; refresh timing is part of the method. GNNAutoScale studies this family of approximations. SIGN precomputed propagation stores several graph transformations applied to XX and trains a network on them. It saves propagation during epochs but costs storage and must be recalculated or updated when edges or features change.

Serving new nodes requires obtaining their features and neighbors, applying the same transformations and controlling latency and graph version. To evaluate a sampling-trained model, full layer-wise inference avoids additional test-sampling variation; on a large graph it can run in batches, writing all states of one layer before the next. If only a sample of nodes or neighbors is evaluated, name the estimate and distinguish it from full-test accuracy.

A historical cache and SIGN solve different problems. The former can reuse hidden representations depending on changing weights; staleness introduces discrepancy that must be measured or controlled. SIGN precomputes input-feature propagation independently of those weights and then trains a network on the results. Its cost moves to storage and data updates. Neither technique makes a massive graph change free or removes the need to coordinate versions between training and inference.

On an 8 GB GPU, first calculate memory for features, indices, parameters, activations and gradients. Keep graph and features on CPU if they do not fit; transfer only the minibatch. Pinned memory can facilitate asynchronous transfers if supported, but uses RAM; multiple workers can improve throughput or duplicate memory and overload the processor. Measure process peak and preparation time, not only kernel time. Actual availability on a shared GPU can be below nominal capacity.

In a particular pipeline, separate structure loading and ordering, CPU sampling, transfer, and GPU forward/backward times. An idle GPU may indicate the sampler is not delivering batches fast enough, although other processes can also contend. Increasing batch size reduces some overhead and increases activations; it guarantees neither better throughput nor the same optimization dynamics. Fix a seed, document processed nodes and measure both CPU resident memory and process-allocated GPU memory.

Lab: blocks and aggregators from scratch

The following CSR uses each destination row to list source neighbors. The sampler builds blocks backward, keeps destinations first among sources and returns computation order. Layers implement an own-state branch and a mean or pooling branch, with ReLU; pooling transforms each source before the maximum. Loop-free graphs ensure the own branch is not also counted as a neighbor. This code illustrates the mechanism and does not implement a library’s trainable LSTM.

[ ]CSR sampling and SAGE layersBrowser
import numpy as np
from scipy import sparse

def sample_blocks(csr,seeds,fanouts,rng):
    csr=sparse.csr_matrix(csr).copy(); csr.sum_duplicates(); csr.eliminate_zeros(); csr.sort_indices()
    dst=list(dict.fromkeys(map(int,seeds))); blocks=[]
    for count in fanouts:
        src=dst.copy(); position={v:i for i,v in enumerate(src)}; edge_src=[]; edge_dst=[]
        for di,node in enumerate(dst):
            neighbors=csr.indices[csr.indptr[node]:csr.indptr[node+1]]
            pick=rng.choice(neighbors,size=min(count,len(neighbors)),replace=False)
            for v in pick:
                v=int(v)
                if v not in position: position[v]=len(src); src.append(v)
                edge_src.append(position[v]); edge_dst.append(di)
        edge_index=np.array([edge_src,edge_dst],dtype=np.int64).reshape(2,-1)
        blocks.append({'src':np.array(src),'dst':np.array(dst),'edge_index':edge_index}); dst=src
    return blocks[::-1]

def sage_mean(block,features,W_self,W_neigh):
    edge=block['edge_index']; n_dst=len(block['dst']); sums=np.zeros((n_dst,features.shape[1])); deg=np.zeros(n_dst)
    np.add.at(sums,edge[1],features[edge[0]]); np.add.at(deg,edge[1],1)
    mean=sums/np.maximum(deg[:,None],1)
    return np.maximum(features[:n_dst]@W_self+mean@W_neigh,0)

def sage_pool(block,features,W_pool,b_pool,W_self,W_neigh):
    edge=block['edge_index']; n_dst=len(block['dst']); transformed=np.maximum(features@W_pool+b_pool,0); pooled=np.zeros((n_dst,transformed.shape[1]))
    for i in range(n_dst):
        source=edge[0,edge[1]==i]
        if len(source): pooled[i]=transformed[source].max(axis=0)
    return np.maximum(features[:n_dst]@W_self+pooled@W_neigh,0)
[ ]Build and check blocksBrowser
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]])
blocks=sample_blocks(A,[0,3],[2,3],np.random.default_rng(9))
for i,b in enumerate(blocks):
 src,dst,e=b['src'],b['dst'],b['edge_index'];print('capa',i,'src',src.tolist(),'dst',dst.tolist(),'aristas',e.shape[1]);assert np.array_equal(src[:len(dst)],dst)
 for a,c in e.T: assert A[dst[c],src[a]]==1
assert np.array_equal(blocks[0]['dst'],blocks[1]['src'])
X=np.arange(10,dtype=float).reshape(5,2)/10
b=blocks[0]; values=X[b['src']]; W=np.eye(2)
print('media',sage_mean(b,values,W,W).round(4).tolist());print('pool',sage_pool(b,values,W,np.zeros(2),W,W).round(4).tolist())
# Un ejemplo completo con toda la vecindad debe coincidir con la agregación densa.
full=sample_blocks(A,[0,3],[10],np.random.default_rng(2))[0]; actual=sage_mean(full,X[full['src']],W,W); expected=np.maximum(X[[0,3]]+np.asarray(A[[0,3]]@X)/np.asarray(A[[0,3]].sum(axis=1)),0); assert np.allclose(actual,expected)
[ ]Empirical bias and varianceBrowser
import numpy as np
rng=np.random.default_rng(22); values=np.array([-2.,-1.,0.,2.,3.,4.]); d=len(values); exact=values.mean()
for size in (1,2,3,6):
    order=rng.random((5000,d)).argsort(axis=1)[:,:size]; estimate=values[order].mean(axis=1)
    theory=(1-size/d)*values.var(ddof=1)/size
    print('s',size,'media',round(float(estimate.mean()),4),'sesgo',round(float(estimate.mean()-exact),4),'varianza',round(float(estimate.var()),4),'teórica',round(float(theory),4))
# Primer estimador insesgado y ReLU no conmutan.
values=np.array([-1.,1.]); sampled=values[rng.integers(0,2,size=10000)]
print('ReLU de media exacta',max(0,float(values.mean())),'media de ReLU muestreada',round(float(np.maximum(sampled,0).mean()),4))

In the synthetic execution, full mean aggregation matches the dense computation. Sampling one neighbor from population [−2,−1,0,2,3,4][-2,-1,0,2,3,4] produced mean 1.0108 versus exact mean 1 and variance 4.6399 versus formula 4.6667. Taking all six neighbors gave zero variance. In the ReLU example, empirical mean was 0.5012 versus zero when applying ReLU after the exact mean. Small differences are finite-sample fluctuations.

Local comparison with NeighborLoader

The local runtime is independent of the browser: hidden setup redefines the sampler. To check equivalence without depending on two different random generators, both methods use all neighbors. NeighborLoader requires PyTorch Geometric and a compatible sampling backend such as pyg-lib.

[ ]Compare blocks with NeighborLoaderLocal GPU
import torch
from torch_geometric.data import Data
from torch_geometric.loader import NeighborLoader
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]])
seeds=np.array([0,3]); blocks=sample_blocks(A,seeds,[10,10],np.random.default_rng(7))
# A es simétrica; fuente vecina -> destino de fila.
r,c=A.nonzero(); edge_index=torch.tensor(np.stack([c,r]),dtype=torch.long)
data=Data(x=torch.arange(10,dtype=torch.float32).reshape(5,2),edge_index=edge_index,num_nodes=5)
loader=NeighborLoader(data,num_neighbors=[-1,-1],input_nodes=torch.tensor(seeds),batch_size=2,shuffle=False,num_workers=0)
batch=next(iter(loader)); found={(int(batch.n_id[u]),int(batch.n_id[v])) for u,v in batch.edge_index.T.tolist()}
expected={(int(b['src'][u]),int(b['dst'][v])) for b in blocks for u,v in b['edge_index'].T}
print('semillas',batch.n_id[:batch.batch_size].tolist(),'nodos',len(batch.n_id),'aristas PyG/manual',len(found),len(expected))
assert set(batch.n_id.tolist())==set(blocks[0]['src'].tolist()) and found==expected
print('NeighborLoader coincide con bloques manuales de vecindad completa')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: ogbn-products

The official ogbn-products dataset contains 2 449 029 products, 100-dimensional features and 47 categories. Its official split depends on popularity: training products have the highest sales rank. Graph and features are visible in the transductive protocol; this is not an inductive test on future products. This machine’s available GPU is an RTX 3060, with a stated budget of 8 GB of process-allocated memory.

Cells require PyTorch, PyTorch Geometric with a sampling backend, OGB, NumPy, SciPy and psutil. The first official download exceeds 1 GB: prepare the dataset with OGB in a terminal that accepts its confirmation and set ORYON_PRODUCTS_ROOT to the cache folder. The installed OGB loader uses serialized PyG objects; cells allow only necessary classes during loading. Use data obtained from a trusted source. This execution’s loader produced 123 718 280 directed entries after adding reverses; it retains repeated edges as messages and does not move the full graph to GPU.

On Windows, the METIS kernel of pyg-lib in this environment advertises availability but does not implement partitioning. The reproducible preparer downloads Apache-2.0-licensed METIS 5.1.0 from conda-forge, checks hashes and creates a copy of gpmetis.exe with a 64 MiB stack to avoid the overflow observed with the original executable. From topology without loops or duplicates it generates 1500 parts and verifies the cut. Original and license are retained; the Python installation is not modified. Run the preparer after processing the dataset and set ORYON_PRODUCTS_PARTITION to the resulting .part.1500 file. PyG then constructs blocks from that assignment. Partitioning uses topology, not labels; since products is split by popularity rather than date, this does not prove absence of future information in a temporal scenario.

The quick configuration performs eight training batches and evaluates the same 128 test nodes selected randomly with seed 93. GraphSAGE and Cluster-GCN use all two-hop neighbors for those nodes; SIGN uses precomputed full propagations. This is a test sample, not the full test, and models have not converged. Training seeds are not identical: Cluster-GCN processes labels appearing in four partitions per batch. Training times exclude initial loading, METIS time and SIGN precomputation; these are printed separately. To process a full epoch use ORYON_PRODUCTS_STEPS=0; to evaluate all test nodes use ORYON_PRODUCTS_EVAL=0. SAGE and Cluster-GCN then perform complete layer-wise inference in batches, and SIGN evaluates precomputed features in batches. That run needs more time and RAM than the quick configuration.

[ ]GraphSAGE with NeighborLoaderLocal GPU
import os,time,tempfile,gc
from pathlib import Path
import numpy as np
import psutil
import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.data import Data
from torch_geometric.data.data import DataEdgeAttr,DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.loader import NeighborLoader
from torch_geometric.nn import SAGEConv
from ogb.nodeproppred import PygNodePropPredDataset

root=Path(os.environ.get('ORYON_PRODUCTS_ROOT',str(Path(tempfile.gettempdir())/'oryon-graph-datasets')))
steps=int(os.environ.get('ORYON_PRODUCTS_STEPS','8')); eval_count=int(os.environ.get('ORYON_PRODUCTS_EVAL','128'))
if steps<0 or eval_count<0:raise ValueError('Usa 0 para una época o test completos')
torch.set_num_threads(4); torch.manual_seed(42); device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type=='cuda':
    fraction=min(.99,8e9/torch.cuda.get_device_properties(0).total_memory); torch.cuda.set_per_process_memory_fraction(fraction)
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    dataset=PygNodePropPredDataset(name='ogbn-products',root=str(root)); graph=dataset[0]; split=dataset.get_idx_split()
graph.y=graph.y.view(-1); process=psutil.Process(); print('datos',graph.num_nodes,graph.num_edges,graph.num_features,'clases',dataset.num_classes,'train/val/test',*(len(split[k]) for k in ('train','valid','test')),'dispositivo',device,flush=True)

class Sage(nn.Module):
    def __init__(self):
        super().__init__(); self.a=SAGEConv(graph.num_features,64); self.b=SAGEConv(64,dataset.num_classes)
    def forward(self,x,edges):
        edges=edges[:,edges[0]!=edges[1]]
        return self.b(F.relu(self.a(x,edges)),edges)

def evaluate_full_neighborhood(model,graph,test,kind):
    # Se usan todos los vecinos de dos saltos de cada nodo evaluado; solo se evalúa la muestra indicada.
    loader=NeighborLoader(graph,input_nodes=test,num_neighbors=[-1,-1],batch_size=1,shuffle=False,num_workers=0)
    correct=0; count=0; model.eval()
    with torch.no_grad():
        for batch in loader:
            batch=batch.to(device); out=model(batch.x,batch.edge_index)[:batch.batch_size]; correct+=int((out.argmax(-1)==batch.y[:batch.batch_size]).sum());count+=batch.batch_size
    return correct/count

def evaluate_all_layerwise(model,graph,test):
    # Cada pasada escribe todas las salidas de la capa antes de comenzar la siguiente.
    x_all=graph.x;model.eval()
    with torch.no_grad():
        for level,conv in enumerate((model.a,model.b)):
            graph.x=x_all; loader=NeighborLoader(graph,num_neighbors=[-1],batch_size=4096,shuffle=False,num_workers=0)
            out_all=torch.empty((graph.num_nodes,conv.out_channels),dtype=torch.float32)
            for batch in loader:
                ids=batch.n_id[:batch.batch_size];batch=batch.to(device);edge=batch.edge_index;edge=edge[:,edge[0]!=edge[1]]
                z=conv((batch.x,batch.x[:batch.batch_size]),edge)
                if level==0:z=F.relu(z)
                out_all[ids]=z.cpu()
            x_all=out_all;del loader,batch,z;gc.collect()
    return float((x_all[test].argmax(1)==graph.y[test]).float().mean())

choice=torch.randperm(len(split['test']),generator=torch.Generator().manual_seed(93))[:eval_count] if eval_count else torch.arange(len(split['test'])); test_nodes=split['test'][choice]
model=Sage().to(device); optimizer=torch.optim.Adam(model.parameters(),lr=.003)
loader=NeighborLoader(graph,input_nodes=split['train'],num_neighbors=[15,10],batch_size=512,shuffle=True,num_workers=0,pin_memory=device.type=='cuda')
if device.type=='cuda': torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize()
process.cpu_percent(None); start=time.perf_counter(); batches=0; n_train=0
for batch in loader:
    batch=batch.to(device); optimizer.zero_grad(); logits=model(batch.x,batch.edge_index)[:batch.batch_size]; loss=F.cross_entropy(logits,batch.y[:batch.batch_size]); loss.backward(); optimizer.step();batches+=1;n_train+=batch.batch_size
    if steps and batches>=steps: break
if device.type=='cuda': torch.cuda.synchronize()
elapsed=time.perf_counter()-start; cpu=process.cpu_percent(None); gpu=torch.cuda.max_memory_allocated()/1e9 if device.type=='cuda' else 0.; rss=process.memory_info().rss/1e9
print('SAGE entrenamiento lotes',batches,'semillas',n_train,'segundos',round(elapsed,3),'CPU %',round(cpu,1),'RAM GB',round(rss,3),'pico GPU GB',round(gpu,3),flush=True)
del loader; gc.collect(); start=time.perf_counter(); accuracy=evaluate_full_neighborhood(model,graph,test_nodes,'sage') if eval_count else evaluate_all_layerwise(model,graph,test_nodes)
if device.type=='cuda': torch.cuda.synchronize()
print('SAGE test', 'muestra con vecindario completo' if eval_count else 'total por capas',len(test_nodes),'exactitud',round(accuracy,4),'segundos evaluación',round(time.perf_counter()-start,3),'pico GPU GB',round(torch.cuda.max_memory_allocated()/1e9,3) if device.type=='cuda' else 0.,flush=True)
del batch,model,optimizer,graph,dataset,split;gc.collect()
if device.type=='cuda':torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Cluster-GCN with METIS partitionLocal GPU
import os,time,tempfile,gc,hashlib
from pathlib import Path
import psutil
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.data import Data
from torch_geometric.data.data import DataEdgeAttr,DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.loader import NeighborLoader,ClusterData,ClusterLoader
from torch_geometric.loader.cluster import Partition
from torch_geometric.nn import GCNConv
from ogb.nodeproppred import PygNodePropPredDataset

root=Path(os.environ.get('ORYON_PRODUCTS_ROOT',str(Path(tempfile.gettempdir())/'oryon-graph-datasets')))
steps=int(os.environ.get('ORYON_PRODUCTS_STEPS','8')); eval_count=int(os.environ.get('ORYON_PRODUCTS_EVAL','128'))
if steps<0 or eval_count<0:raise ValueError('Usa 0 para una época o test completos')
torch.set_num_threads(4); torch.manual_seed(42); device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type=='cuda': torch.cuda.set_per_process_memory_fraction(min(.99,8e9/torch.cuda.get_device_properties(0).total_memory))
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    dataset=PygNodePropPredDataset(name='ogbn-products',root=str(root)); graph=dataset[0]; split=dataset.get_idx_split()
graph.y=graph.y.view(-1); graph.n_id=torch.arange(graph.num_nodes);graph.train_mask=torch.zeros(graph.num_nodes,dtype=torch.bool);graph.train_mask[split['train']]=True
# Grados de todas las entradas de arista y un lazo propio adicional, en CPU.
degree=torch.bincount(graph.edge_index[1],minlength=graph.num_nodes).float()+1; inverse=degree.rsqrt(); process=psutil.Process()
print('datos',graph.num_nodes,graph.num_edges,'train/val/test',*(len(split[k]) for k in ('train','valid','test')),'dispositivo',device,flush=True)

class ClusterGCN(nn.Module):
    def __init__(self):
        super().__init__(); self.a=GCNConv(graph.num_features,64,normalize=False,add_self_loops=False);self.b=GCNConv(64,dataset.num_classes,normalize=False,add_self_loops=False)
    @staticmethod
    def layer(conv,x,edge,inv):
        w=inv[edge[0]]*inv[edge[1]];return conv(x,edge,w)+conv.lin(x)*inv.square()[:,None]
    def forward(self,x,edge,inv):
        return self.layer(self.b,F.relu(self.layer(self.a,x,edge,inv)),edge,inv)

class ExternalClusterData(ClusterData):
    def _metis(self,edge_index,num_nodes):
        path=Path(os.environ['ORYON_PRODUCTS_PARTITION']); membership=np.loadtxt(path,dtype=np.int64)
        if membership.shape!=(num_nodes,) or membership.min()<0 or membership.max()>=self.num_parts:raise ValueError('Asignación METIS inválida')
        return torch.from_numpy(membership)

assignment=Path(os.environ['ORYON_PRODUCTS_PARTITION']);digest=hashlib.sha256(assignment.read_bytes()).hexdigest()
start=time.perf_counter()
with torch.serialization.safe_globals([Partition]):
    parts=ExternalClusterData(graph,num_parts=1500,recursive=False,save_dir=str(root/('cluster-products-'+digest)))
print('partición segundos',round(time.perf_counter()-start,3),'RAM GB',round(process.memory_info().rss/1e9,3),flush=True)
loader=ClusterLoader(parts,batch_size=4,shuffle=True,num_workers=0);model=ClusterGCN().to(device);optimizer=torch.optim.Adam(model.parameters(),lr=.003)
if device.type=='cuda':torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize()
process.cpu_percent(None);start=time.perf_counter();batches=0;n_train=0
for batch in loader:
    inv=inverse[batch.n_id].to(device);batch=batch.to(device);mask=batch.train_mask
    if int(mask.sum())==0:continue
    optimizer.zero_grad(); logits=model(batch.x,batch.edge_index,inv);loss=F.cross_entropy(logits[mask],batch.y[mask]);loss.backward();optimizer.step();batches+=1;n_train+=int(mask.sum())
    if steps and batches>=steps:break
if device.type=='cuda':torch.cuda.synchronize()
elapsed=time.perf_counter()-start;cpu=process.cpu_percent(None);gpu=torch.cuda.max_memory_allocated()/1e9 if device.type=='cuda' else 0.;rss=process.memory_info().rss/1e9
print('Cluster-GCN entrenamiento lotes',batches,'semillas',n_train,'segundos',round(elapsed,3),'CPU %',round(cpu,1),'RAM GB',round(rss,3),'pico GPU GB',round(gpu,3),flush=True)
del loader,parts;gc.collect()
choice=torch.randperm(len(split['test']),generator=torch.Generator().manual_seed(93))[:eval_count] if eval_count else torch.arange(len(split['test']));test=split['test'][choice]
model.eval();correct=0;count=0;start=time.perf_counter()
with torch.no_grad():
    if eval_count:
        loader=NeighborLoader(graph,input_nodes=test,num_neighbors=[-1,-1],batch_size=1,shuffle=False,num_workers=0)
        for batch in loader:
            inv=inverse[batch.n_id].to(device);batch=batch.to(device);out=model(batch.x,batch.edge_index,inv)[:batch.batch_size];correct+=int((out.argmax(-1)==batch.y[:batch.batch_size]).sum());count+=batch.batch_size
    else:
        x_all=graph.x
        for level,conv in enumerate((model.a,model.b)):
            graph.x=x_all;loader=NeighborLoader(graph,num_neighbors=[-1],batch_size=4096,shuffle=False,num_workers=0);out_all=torch.empty((graph.num_nodes,conv.out_channels),dtype=torch.float32)
            for batch in loader:
                ids=batch.n_id[:batch.batch_size];inv=inverse[batch.n_id].to(device);batch=batch.to(device);edge=batch.edge_index;z=conv.lin(batch.x);weight=inv[edge[0]]*inv[edge[1]]
                out=torch.zeros((batch.batch_size,conv.out_channels),device=device);out.index_add_(0,edge[1],z[edge[0]]*weight[:,None]);out+=z[:batch.batch_size]*inv[:batch.batch_size,None].square()+conv.bias
                if level==0:out=F.relu(out)
                out_all[ids]=out.cpu()
            x_all=out_all;del loader;gc.collect()
        correct=int((x_all[test].argmax(1)==graph.y[test]).sum());count=len(test)
if device.type=='cuda':torch.cuda.synchronize()
print('Cluster-GCN test','muestra con vecindario completo' if eval_count else 'total por capas',count,'exactitud',round(correct/count,4),'segundos evaluación',round(time.perf_counter()-start,3),'pico GPU GB',round(torch.cuda.max_memory_allocated()/1e9,3) if device.type=='cuda' else 0.,flush=True)
if eval_count:del loader
else:del x_all,out_all,z,weight,edge
del batch,inv,out,logits,model,optimizer,graph,dataset,inverse,split;gc.collect()
if device.type=='cuda':torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]SIGN with precomputed propagationLocal GPU
import os,time,tempfile,gc
from pathlib import Path
import psutil
import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.data import Data
from torch_geometric.data.data import DataEdgeAttr,DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from ogb.nodeproppred import PygNodePropPredDataset

root=Path(os.environ.get('ORYON_PRODUCTS_ROOT',str(Path(tempfile.gettempdir())/'oryon-graph-datasets')))
steps=int(os.environ.get('ORYON_PRODUCTS_STEPS','8'));eval_count=int(os.environ.get('ORYON_PRODUCTS_EVAL','128'))
if steps<0 or eval_count<0:raise ValueError('Usa 0 para una época o test completos')
torch.set_num_threads(4);torch.manual_seed(42);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type=='cuda':torch.cuda.set_per_process_memory_fraction(min(.99,8e9/torch.cuda.get_device_properties(0).total_memory))
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    dataset=PygNodePropPredDataset(name='ogbn-products',root=str(root));graph=dataset[0];split=dataset.get_idx_split()
graph.y=graph.y.view(-1);process=psutil.Process();print('datos',graph.num_nodes,graph.num_edges,'train/val/test',*(len(split[k]) for k in ('train','valid','test')),'dispositivo',device,flush=True)

# La entrada OGB se hace bidireccional al cargar. Operador simétrico con un lazo adicional.
cache=root/'sign-products-normalized-v1.pt';x0=graph.x;process.cpu_percent(None);start=time.perf_counter()
if cache.exists():
    saved=torch.load(cache,map_location='cpu',weights_only=True);x1,x2=saved['x1'],saved['x2']
    if x1.shape!=x0.shape or x2.shape!=x0.shape:raise ValueError('Caché SIGN incompatible con los datos')
    del saved;source='caché'
else:
    degree=torch.bincount(graph.edge_index[1],minlength=graph.num_nodes).float()+1;inv=degree.rsqrt();weights=inv[graph.edge_index[0]]*inv[graph.edge_index[1]]
    # El conjunto de aristas ya es simétrico, por lo que ambas orientaciones representan la misma matriz.
    adj=torch.sparse_coo_tensor(graph.edge_index,weights,(graph.num_nodes,graph.num_nodes));x1=torch.sparse.mm(adj,x0)+inv.square()[:,None]*x0;x2=torch.sparse.mm(adj,x1)+inv.square()[:,None]*x1
    torch.save({'x1':x1,'x2':x2},cache);del adj,weights,degree,inv;source='calculado'
print('SIGN preparación',source,'segundos',round(time.perf_counter()-start,3),'CPU %',round(process.cpu_percent(None),1),'RAM GB',round(process.memory_info().rss/1e9,3),flush=True)
graph.edge_index=None;gc.collect()

class Sign(nn.Module):
    def __init__(self):
        super().__init__();self.branches=nn.ModuleList([nn.Linear(graph.num_features,64) for _ in range(3)]);self.head=nn.Linear(3*64,dataset.num_classes)
    def forward(self,xs):
        return self.head(torch.cat([F.relu(layer(x)) for layer,x in zip(self.branches,xs)],dim=1))

model=Sign().to(device);opt=torch.optim.Adam(model.parameters(),lr=.003);order=split['train'][torch.randperm(len(split['train']),generator=torch.Generator().manual_seed(42))];batches=0;n_train=0
if device.type=='cuda':torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize()
process.cpu_percent(None);start=time.perf_counter()
for ids in order.split(512):
    xs=[v[ids].to(device) for v in (x0,x1,x2)]; y=graph.y[ids].to(device);opt.zero_grad();loss=F.cross_entropy(model(xs),y);loss.backward();opt.step();batches+=1;n_train+=len(ids)
    if steps and batches>=steps:break
if device.type=='cuda':torch.cuda.synchronize()
print('SIGN entrenamiento lotes',batches,'semillas',n_train,'segundos',round(time.perf_counter()-start,3),'CPU %',round(process.cpu_percent(None),1),'RAM GB',round(process.memory_info().rss/1e9,3),'pico GPU GB',round(torch.cuda.max_memory_allocated()/1e9,3) if device.type=='cuda' else 0.,flush=True)
choice=torch.randperm(len(split['test']),generator=torch.Generator().manual_seed(93))[:eval_count] if eval_count else torch.arange(len(split['test']));ids=split['test'][choice];start=time.perf_counter();model.eval();correct=0
with torch.no_grad():
    for batch_ids in ids.split(8192):
        pred=model([v[batch_ids].to(device) for v in (x0,x1,x2)]).argmax(1).cpu();correct+=int((pred==graph.y[batch_ids]).sum())
accuracy=correct/len(ids)
if device.type=='cuda':torch.cuda.synchronize()
print('SIGN test','muestra' if eval_count else 'total',len(ids),'exactitud',round(accuracy,4),'segundos evaluación',round(time.perf_counter()-start,3),'pico GPU GB',round(torch.cuda.max_memory_allocated()/1e9,3) if device.type=='cuda' else 0.,flush=True)
del x0,x1,x2,xs,graph,dataset,model,opt,split;gc.collect()
if device.type=='cuda':torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

One execution on this machine gave the following results. Accuracy is the fraction over the same 128 test nodes, not a precise estimate of full performance; eight batches are short training and cannot conclusively rank methods.

MethodLabels processedSample accuracyTrainingGPU peakRAM during training
GraphSAGE40960.42191.648 s0.174 GB6.477 GB
Cluster-GCN40070.21090.840 s0.202 GB8.620 GB
SIGN40960.43750.647 s0.020 GB8.125 GB

In that execution SIGN precomputation without cache writes took 284.642 s and used 8.220 GB RAM at completion. METIS received 61 859 012 undirected edges without loops or duplicates; the 1500 parts had sizes between 1570 and 1681 and cut 21 904 607, checked by an independent traversal. ClusterData took another 18.575 s to prepare its blocks. Inference on the sample took 5.176 s for SAGE, 1.458 s for Cluster-GCN and 0.009 s for SIGN with propagations already available. These are timings from one execution and CPU use can exceed 100% with multiple cores; code prints that measure. Download is excluded, and hardware, cache and shared load change the numbers.

With both environment parameters set to zero, one full epoch of 196 615 labels was also processed and all 2 213 091 test nodes evaluated. Layer-wise SAGE and Cluster-GCN outputs were first checked against full-graph outputs on small graphs; SIGN uses propagations for all nodes. GPU peak includes training and evaluation; RAM is resident memory observed at training completion.

MethodBatches per epochFull-test accuracyEpochEvaluationGPU peakObserved RAM
GraphSAGE3850.714523.650 s105.878 s0.548 GB6.520 GB
Cluster-GCN3750.611820.267 s167.474 s0.745 GB8.651 GB
SIGN3850.68604.423 s1.333 s0.042 GB6.170 GB

These values use one seed, one architecture and one fixed epoch. SIGN evaluation uses the cache while initial preparation costs time and space; the ClusterData time here reuses an already calculated partition. No result implies convergence or compares total costs under equal conditions. Repeat with multiple seeds, more epochs and validation selection to study performance, and report initial cost and any split change.

Exercises

Proof
Prove: Prove unbiasedness of the uniform mean without replacement and explain why ReLU can introduce bias.
0
There are d neighbors and s≤d are chosen; Iⱼ indicates whether j was selected.

Step 1 of 2. What is each neighbor's inclusion probability?

Numeric
What is the maximum occurrence count in the tree of 1024 seeds with fan-outs [15,10,5], including seeds and without deduplication?
Numeric
If each of those 937 984 occurrences stores 100 float32 values, how many bytes do those features alone occupy?
Quiz
New nodes arrive with features and neighbors available. Which strategy starts from an inductive capability?
Quiz
On a graph with strong communities, which precaution is appropriate when training by partitions?
Quiz
You have one billion edges and no GPU. What is a reasonable initial plan?
Quiz
Node features are too large for available GPU memory. Which strategy starts by respecting that limit?
Code
Implement sample_blocks(csr, seeds, fanouts): a destination's CSR row lists source neighbors. Take up to fanout neighbors without replacement per destination, deduplicate sources while keeping destinations first, and return blocks in computation order. Each block has src, dst and local edge_index of shape 2×E.
import numpy as np
from scipy import sparse
def sample_blocks(csr, seeds, fanouts):
  pass
Shift+Enter to run

Key ideas

Key idea
GraphSAGE shares an aggregation function to represent nodes from attributes and neighborhoods; sampling limits per-batch work at the cost of variation and, after nonlinearities, possible bias.

Block structure, evaluation strategy and memory budget are part of the experimental protocol and must be reported when comparing models.