Contents
Figure 1: Scaling GNNs to Large Graphs: Neighbor Sampling and Mini-Batching Explained — capping fan-out turns exponential neighbor explosion into tractable mini-batches
Cora has 2,708 nodes, so you can push the whole graph through your GNN every step. Then your real graph shows up: 100 million nodes, billions of edges, features that don't fit on one GPU. You reach for the usual deep learning trick, which is to train on mini-batches. And it breaks, because a node's embedding depends on its neighbors' embeddings, which depend on their neighbors', and so on. Slice out a batch, and you've accidentally pulled in half the graph.
I can't claim I've trained GNNs on billion-edge graphs, and I haven't run the code below in this conversation, so test it yourself. As you asked, I put the sources after the article, not inside it. IMO, scaling GNNs mostly comes down to one idea (cap the neighborhood you pull in) and a handful of practical details about where the time actually goes. Ready to dig in?
Why Mini-Batching Is Hard for GNNs
Ordinary neural networks split the loss across independent samples, so a mini-batch gives a good stochastic estimate of the gradient. PyG's documentation explains why GNNs differ: a node's embedding depends recursively on all its neighbors' embeddings, which creates inter-dependency between nodes that grows exponentially with the number of layers. The usual name is neighbor explosion.
The simple workaround is full-batch training, where the GNN sees all hidden node representations in all layers at once. The documentation notes that this isn't feasible for large graphs because of memory limits and slow convergence.
The Arithmetic of Explosion
Say each node has about 50 neighbors on average and you use a 3-layer GNN. To compute one seed node's output, you need:
- 1 seed node
- 50 first-hop neighbors
- 50 × 50 = 2,500 second-hop nodes
- 50 × 50 × 50 = 125,000 third-hop nodes
That's roughly 127,000 nodes to score a single node, ignoring overlaps. Real graphs make it worse, because hubs can have millions of neighbors. One systems paper states the effect directly: training a batch for an L-layer GNN accesses the entire L-hop neighborhood of the batch, which is prohibitively expensive for many real-world graphs.
Neighbor Sampling: Cap the Fan-Out
The most common fix comes from the GraphSAGE paper. PyG's tutorial describes it: recursively sample at most k neighbors for each node, which bounds the overall number of nodes in each batch's computation graph. You pick a fanout per layer.
With fanouts of 15, 10, and 5 for a 3-layer model (a configuration one paper uses on the huge ogbn-papers100M dataset):
- 1 seed
- 15 first-hop nodes
- 15 × 10 = 150 second-hop nodes
- 150 × 5 = 750 third-hop nodes
- Total: at most 916 nodes per seed, versus about 127,000 without sampling
That's a reduction of over 100 times. But don't get carried away: the same documentation cautions that sampling only mitigates the problem to some extent, because the overall neighborhood size still grows exponentially with the number of layers. Deeper models stay expensive.
Three Families of Scalable Training
Surveys and papers group the main strategies like this:
Node-wise sampling: sample neighbors for each node, as in GraphSAGE and PyG's NeighborLoader
Layer-wise sampling: sample a fixed number of nodes per layer, as in FastGCN and AS-GCN. This avoids explosion, but one paper notes FastGCN's independent per-layer sampling can degrade accuracy, because many nodes sampled in one layer may not connect to the nodes sampled in the next.
Subgraph-wise sampling: train on sampled subgraphs, as in Cluster-GCN and GraphSAINT. PyG ships ClusterLoader, GraphSAINTSampler, and ShaDowKHopSampler for these. From my background knowledge, Cluster-GCN partitions the graph into clusters and trains on one cluster at a time, and GraphSAINT samples subgraphs with corrections that reduce bias and variance (a description one source supports for the bias and variance part). Verify the details in the original papers.
There's also a fourth approach: decouple propagation from learning, so you precompute neighbor averages once and train a simple model on top. PyG's documentation mentions decoupling among scalability techniques. I won't cover it in depth, but it's worth knowing when you want the cheapest possible pipeline.
Hands-On: Training With NeighborLoader
NeighborLoader builds the sampled subgraph for each batch of seed nodes. The PyG docs describe the key arguments: input_nodes sets which nodes seed the sampling, and shuffle controls whether seeds shuffle each epoch. Here's a training sketch. I haven't run it, and APIs change, so check the current docs. I use Cora so it runs anywhere, but the code is identical for large graphs:
import torch, torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.loader import NeighborLoader
from torch_geometric.nn import GraphSAGE
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dataset = Planetoid("data/Cora", "Cora")
data = dataset[0] # keep on CPU: features can be huge
train_loader = NeighborLoader(
data,
num_neighbors=[15, 10], # fanout per layer; length must equal the number of GNN layers
batch_size=64, # number of SEED nodes per batch
input_nodes=data.train_mask,
shuffle=True,
)
model = GraphSAGE(in_channels=dataset.num_features, hidden_channels=64,
num_layers=2, out_channels=dataset.num_classes).to(device)
opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
def train_epoch():
model.train()
total = 0.0
for batch in train_loader:
batch = batch.to(device)
opt.zero_grad()
out = model(batch.x, batch.edge_index)[: batch.batch_size] # seeds only
loss = F.cross_entropy(out, batch.y[: batch.batch_size])
loss.backward(); opt.step()
total += float(loss) * batch.batch_size
return total / int(data.train_mask.sum())
The Details That Matter
PyG's documentation highlights several behaviors:
Seeds come first. The first batch_size nodes in the batch are exactly the seed nodes, so you slice [: batch.batch_size] for the output and labels.
Compute the loss on seeds only. Non-seed nodes in the batch are neighbors, and some may belong to your validation or test sets. Training on their labels would leak. This is the most common mistake I see.
Sampled subgraphs are directed by default, with edges pointing toward the seed nodes. That restricts use to GNNs whose depth equals the number of sampling hops. So num_neighbors needs one entry per layer.
Original IDs live in batch.n_id, which you can use to map back to the full graph.
A small inefficiency: nodes sampled in later hops no longer contribute to the seeds' representations in the later layers, yet the model still computes embeddings for them. PyG's tutorial notes the standard loader is marginally slower for this reason, and points to its hierarchical neighborhood sampling tutorial for eliminating the overhead.
Heterogeneous graphs work too: you can initialize the loader with HeteroData, and the docs say it allows fine-grained control over sampling parameters per edge type.
Evaluation: Don't Sample the Same Way
Training with sampling gives noisy but useful gradients. At evaluation time, you want predictions that don't depend on random sampling, so you have two choices.
Option 1: full neighborhoods in batches. Use -1 to mean "all neighbors" (check the docs for your version):
val_loader = NeighborLoader(data, num_neighbors=[-1, -1], batch_size=256,
input_nodes=data.val_mask)
@torch.no_grad()
def evaluate(loader):
model.eval()
correct = total = 0
for batch in loader:
batch = batch.to(device)
pred = model(batch.x, batch.edge_index)[: batch.batch_size].argmax(1)
correct += int((pred == batch.y[: batch.batch_size]).sum())
total += batch.batch_size
return correct / total
On graphs with hubs, full two-hop neighborhoods can run out of memory, so you may need smaller batches.
Option 2: sampled inference. The SALIENT paper reports an analysis suggesting that neighborhood sampling during inference sacrifices prediction accuracy only marginally, making mini-batch inference with sampling a viable alternative to layer-wise inference over full neighborhoods. That's one group's result, so verify it on your own graph by comparing sampled and full inference.
Option 3: layer-wise inference. From my background knowledge, you can compute each layer's embeddings for all nodes in chunks, then feed them to the next layer. This is exact and avoids recomputing overlapping neighborhoods, but it needs more memory for the intermediate embeddings. Check whether your PyG version offers a built-in helper for it.
Choosing Fanouts and Batch Size
These settings control the tradeoff between accuracy, speed, and memory:
- Larger fanouts give lower-variance gradients and closer-to-full-graph behavior, but cost more
- Smaller fanouts run fast but add noise, which can hurt accuracy
- Decreasing fanouts outward (for example, 15, 10, 5) is a common pattern, since later hops explode fastest
- Batch size sets the number of seed nodes. Larger batches share more neighbors, so per-seed cost can drop, but memory grows.
- Number of layers is the biggest lever, since cost grows exponentially. Remember the over-smoothing article: you often don't need depth anyway.
Tune on validation accuracy and measure throughput. A tiny fanout that runs five times faster but loses two points of accuracy may or may not be a good deal.
Where the Time Actually Goes
Beginners assume the GNN forward and backward passes dominate. Papers I found say otherwise:
- Batch preparation and data transfer are major bottlenecks in common frameworks, per the SALIENT paper, which also reports that optimizing them gave a 3× training speedup over a standard PyG implementation on a single GPU for ogbn-papers100M, and a further 8× with 16 GPUs
- Sampling is frequently the bottleneck, according to a distributed-sampling paper, which notes that DGL and PyG run sampling on the CPU, a weaker processor than the GPU
- Sampling costs can erase the benefits of fancier training, as another recent paper puts it, and its authors argue for overlapping sampling with training
Practical consequences, from this evidence plus my background knowledge:
- Profile before optimizing. Time sampling, transfer, and compute separately.
- Use multiple loader workers so sampling overlaps with training (check the loader's arguments)
- Keep big feature matrices on the CPU and transfer only each batch's features
- Consider feature caching for frequently sampled nodes
- Use mixed precision where it fits, and test the effect on accuracy
Subgraph Sampling as an Alternative
If neighbor sampling still feels wasteful, subgraph methods train on a whole sampled subgraph per step. Cluster-style methods keep nodes that are densely connected together in the same batch, so most of the neighbors you need are already there. GraphSAINT tries to correct the statistical bias that subgraph sampling introduces, according to one source. The tradeoffs, from my background knowledge: subgraph methods can be very efficient, but their quality depends on how well the sampled subgraphs represent the whole graph, and they can struggle on graphs with weak cluster structure. Test them against neighbor sampling on your data.
Full-Batch vs. Mini-Batch: A Fair Comparison
When your graph fits in memory, compare both. One paper I found cites recent studies claiming that mini-batch training can converge faster and reach higher accuracy than full-graph training. That's a claim from other work, quoted in a systems paper, so check it yourself. Run both on the same splits with several seeds, and compare:
- Accuracy (mean and spread)
- Time per epoch and time to reach target accuracy
- Peak memory
- Sensitivity to fanout
Report what you find, even when sampling hurts.
Scaling Beyond One GPU
When one GPU isn't enough, the evidence points to a few directions: distributed sampling, graph partitioning across GPUs, and highly optimized pipelines. One 2026 paper reports scaling to 2,048 GPUs and a 3.5× end-to-end speedup over a state-of-the-art baseline on ogbn-products. Those are specialized systems, and most teams never need them. Start with a single-machine pipeline, measure, and scale only when the numbers demand it.
Common Mistakes to Avoid
- Computing the loss on all batch nodes. Use seeds only, or you'll train on validation and test labels.
- Mismatching
num_neighborsand the number of layers - Using tiny fanouts at evaluation time. Use full neighborhoods or compare sampled inference carefully.
- Ignoring hubs. One high-degree node can blow up memory when you sample all its neighbors.
- Optimizing the model before profiling the loader
- Moving the entire feature matrix to the GPU when only a batch is needed
- Skipping the full-batch baseline on a graph that fits
- Using one seed. Sampling adds variance, so report spread.
- Forgetting the depth cost. Each added layer multiplies the sampled neighborhood.
- Leaking edges in link prediction. Use the right link-level sampler and splits (check the PyG docs for the link-prediction loader).
Did you notice that most mistakes involve not looking at where the cost or the leak actually is? :/
Wrapping This Up
GNNs resist mini-batching because each node's embedding depends on its neighbors, and the dependency grows exponentially with depth. Neighbor sampling cuts that growth with a fanout cap, subgraph methods trade neighborhoods for clusters, and decoupled methods precompute propagation. In practice, tuning fanouts, evaluating without randomness, and fixing loader bottlenecks matter as much as the model.
So run the NeighborLoader example this week, then print the number of nodes in a few batches under different fanouts, like [15, 10] versus [5, 5]. If the node counts surprise you, you just measured neighbor explosion on your own data. If a small fanout matches the large one in accuracy, congratulations: you found a cheaper pipeline, and your GPU bill will thank you. :)
Best Book to Read
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Deep Learning on Graphs: Methods and Applications — covers scalable GNN training, neighbor sampling, subgraph methods, and production deployment patterns for large graphs. Search on Amazon
Frequently Asked Questions
Why does mini-batching break for GNNs?
A node's embedding depends recursively on all its neighbors' embeddings, which depend on their neighbors', creating exponential neighbor explosion. Computing one seed node's output in a 3-layer GNN with 50 average neighbors pulls in roughly 127,000 nodes.
What is neighbor sampling and how does it help?
Neighbor sampling (from GraphSAGE) caps the number of neighbors sampled per node per layer (fanout). With fanouts of 15, 10, 5 for a 3-layer model, you bound computation to ~916 nodes per seed instead of ~127,000 — a 100× reduction.
Which PyG loader should I use for large graphs?
NeighborLoader for node-wise sampling (GraphSAGE-style), ClusterLoader for Cluster-GCN (subgraph partitions), GraphSAINTSampler for GraphSAINT (bias-corrected subgraph sampling), or ShaDowKHopSampler for ShaDow-KHop. Choose based on your graph's cluster structure and accuracy needs.
How should I evaluate a GNN trained with sampling?
Use full neighborhoods at evaluation (num_neighbors=[-1, -1]) to get deterministic predictions, or compare sampled inference against full inference on your graph. Training with sampling gives noisy gradients; evaluation needs stable outputs.
What are the biggest bottlenecks in scalable GNN training?
Sampling (often on CPU), data transfer (CPU→GPU), and batch preparation dominate time — not the GNN forward/backward passes. Use multiple loader workers, keep features on CPU, and profile before optimizing the model.
Sources
[1] GraphSAGE (Hamilton et al.) — introduces neighbor sampling with fanout to bound computation; foundation for PyG's NeighborLoader.
[2] FastGCN (Chen et al.) — layer-wise sampling to avoid explosion; independent per-layer sampling can degrade accuracy.
[3] Cluster-GCN (Chiang et al.) and GraphSAINT (Zeng et al.) — subgraph-wise sampling; GraphSAINT adds bias and variance corrections.
[4] SALIENT (2023/2024) — systems analysis showing sampling, transfer, and batch prep dominate GNN training time; 3× speedup from loader optimization on ogbn-papers100M.
[5] Distributed sampling and billion-scale GNN training (2026) — scaling to 2,048 GPUs with 3.5× end-to-end speedup on ogbn-products; overlapping sampling with compute.
Related Articles
- Over-Smoothing in GNNs: Why Deeper Isn't Better and What to Do About It
- Graph Neural Networks: Message Passing Explained
- GCN vs GraphSAGE vs GAT: Which Graph Neural Network Architecture Wins
- Detecting Suspicious Networks: Graph Neural Networks for Fraud Rings