Neighbor Sampling in TGraphX: Scaling GNNs to Large Graphs
Full-batch GNN training is straightforward: feed the entire graph through the model in one forward pass. It works until the activations of every node no longer fit on your device. Then you need mini-batch training, and mini-batching a graph means sampling.
For node-level mini-batch training, TGraphX ships three families of samplers, all marked Beta: NeighborLoader, GraphSAINT subgraph samplers (with GraphSAINTLoader), and Cluster-GCN partitioners (with ClusterLoader). All of them work on a Graph that is already in memory. They bound what each training step processes; they do not by themselves let you hold a graph that does not fit in RAM, although node features can be moved to a feature store.
This tutorial shows a complete loop for NeighborLoader, short usage of the other two, and the behaviour that matters when you use them. Examples tested with TGraphX 1.5.1 on CPU.
Why graph sampling is non-trivial
For independent images, mini-batching is simple: pick some images at random. For graphs, picking nodes at random is not enough, because a message-passing layer needs each node's neighbors.
The three standard approaches:
- Neighbor sampling (GraphSAGE; Hamilton et al., NeurIPS 2017). Pick seed nodes and sample a few neighbors per hop around them.
- Subgraph sampling (GraphSAINT; Zeng et al., ICLR 2020). Sample a subgraph, train on all of it, and correct for the unequal sampling probabilities.
- Cluster sampling (Cluster-GCN; Chiang et al., KDD 2019). Partition the graph once and train on one or a few partitions at a time.
NeighborLoader: seeds and fanouts
The first block builds a small synthetic graph with community structure, boolean train, validation and test masks, and a loader. The arguments are fanouts (neighbors per hop) and mask (which nodes may be seeds).
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph, NeighborLoader, TensorGraphSAGELayer
from tgraphx.estimators import node_train_val_test_split
torch.manual_seed(0)
NUM_NODES, NUM_CLASSES = 1200, 4
community = torch.arange(NUM_NODES) // 50 # 24 communities of 50 nodes
labels = community % NUM_CLASSES
# Random edges, 90% of them inside a community, stored in both directions.
src = torch.randint(0, NUM_NODES, (3600,))
inside = community[src] * 50 + torch.randint(0, 50, (3600,))
dst = torch.where(torch.rand(3600) < 0.9, inside, torch.randint(0, NUM_NODES, (3600,)))
edge_index = torch.cat([torch.stack([src, dst]), torch.stack([dst, src])], dim=1)
x = F.one_hot(labels, NUM_CLASSES).float() + 2.0 * torch.randn(NUM_NODES, NUM_CLASSES)
train_mask, val_mask, test_mask = node_train_val_test_split(NUM_NODES, 0.6, 0.2, 0.2, seed=0)
g = Graph(node_features=x, edge_index=edge_index, y=labels,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
tgx.validate_graph(g, strict=True)
loader = NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask, batch_size=64, seed=0)
batch = next(iter(loader))
print(batch.batch_size, batch.num_nodes, batch.num_edges)
print(batch.node_features.shape, batch.edge_index.shape, batch.seed_y.shape)
What a GraphMiniBatch gives you:
batch.node_features(aliasbatch.x) andbatch.edge_index: the sampled subgraph, with local node ids.batch.seed_node_ids: the global ids of the seeds.batch.input_nodesholds the global ids of all nodes in the subgraph.batch.seed_yandbatch.seed_logits(out): labels and outputs for the seed rows only. Seeds are not necessarily the first rows, so use these helpers instead of slicing.
Always pass mask. With the default mask=None every node becomes a seed, including validation and test nodes, and graph.train_mask is not picked up on its own.
A complete training loop
The model below uses TensorGraphSAGELayer, which expects [N, C, H, W] node tensors, so vector features get two unit axes. For image-like node features, drop the reshaping.
Two details in the loop are important. A new loader is built every epoch with a different seed (the next section explains why). Validation and test use fanouts=[-1, -1], meaning all neighbors for both hops; for this two-layer mean-aggregation model that reproduces the full-graph outputs for the seed nodes.
class SAGE(torch.nn.Module):
def __init__(self, in_dim, hidden_dim, num_classes):
super().__init__()
self.conv1 = TensorGraphSAGELayer(in_dim, hidden_dim)
self.conv2 = TensorGraphSAGELayer(hidden_dim, num_classes)
def forward(self, x, edge_index):
h = x[:, :, None, None] # [N, D] -> [N, D, 1, 1]
h = F.relu(self.conv1(h, edge_index))
return self.conv2(h, edge_index).flatten(1) # [N, num_classes]
@torch.no_grad()
def accuracy(model, graph, mask):
model.eval()
correct = total = 0
for batch in NeighborLoader(graph, fanouts=[-1, -1], mask=mask,
batch_size=128, shuffle=False):
pred = batch.seed_logits(model(batch.node_features, batch.edge_index)).argmax(1)
correct += int((pred == batch.seed_y).sum())
total += batch.batch_size
return correct / total
torch.manual_seed(0)
model = SAGE(NUM_CLASSES, 32, NUM_CLASSES)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
best_val, best_state = -1.0, None
for epoch in range(5):
model.train()
for batch in NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask,
batch_size=64, seed=epoch):
optimizer.zero_grad()
out = model(batch.node_features, batch.edge_index)
loss = F.cross_entropy(batch.seed_logits(out), batch.seed_y) # seeds only
loss.backward()
optimizer.step()
val = accuracy(model, g, g.val_mask)
if val > best_val:
best_val = val
best_state = {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
print(f"best val accuracy {best_val:.3f}, test accuracy {accuracy(model, g, g.test_mask):.3f}")
The test nodes are used once, after model selection. The numbers come from synthetic data and say nothing about real datasets. Note that tgraphx.fit() does not accept NeighborLoader batches, so a hand-written loop like this one is the way to train with it.
The batch is an induced subgraph
TGraphX picks up to fanouts[hop] incoming neighbors per frontier node, collects all visited nodes, and then returns the subgraph induced on them: every edge whose two endpoints were visited is included, sampled or not. A seed can therefore receive far more messages than the first fanout suggests.
torch.manual_seed(0)
dense_ei = torch.randint(0, 1000, (2, 20000))
dense = Graph(node_features=torch.randn(1000, 4), edge_index=dense_ei)
b = next(iter(NeighborLoader(dense, fanouts=[2, 2], batch_size=128, seed=0)))
in_degree = torch.bincount(b.edge_index[1], minlength=b.num_nodes)
seed_in_degree = in_degree[b.seed_local_indices]
print(b.num_nodes, b.num_edges)
print("messages into a seed: mean", round(seed_in_degree.float().mean().item(), 1),
"max", int(seed_in_degree.max()), "(fanout was 2)")
In this run the seeds receive about 11 messages on average and up to 23. Practical consequences:
- The node count is bounded by the fanouts (at most
batch_size * (1 + s1 + s1*s2)for two hops), but the edge count is not bounded by them. Watchbatch.num_edges. - Libraries differ here. PyTorch Geometric's
NeighborLoader, for example, defaults tosubgraph_type="directional", which keeps the sampled edges only. Do not expect the two to behave identically with the same fanouts.
Resample every epoch
In TGraphX 1.5.1, the loader passes its seed to the neighbor sampler for every batch, and the sampler creates a fresh torch.Generator each time. With seed=None that generator starts from PyTorch's fixed default seed, not from the global RNG. The neighbor picks therefore follow from the batch itself: an identical batch of seed nodes, in the identical order, is expanded identically every time. Regroup or reorder the seeds and the picks change.
from tgraphx import neighbor_sample
def one_pass(loader):
return [(b.seed_node_ids.tolist(), b.input_nodes.tolist()) for b in loader]
for shuffle in (False, True):
loader = NeighborLoader(g, fanouts=[2, 2], mask=g.train_mask,
batch_size=64, shuffle=shuffle, seed=0)
first, second = one_pass(loader), one_pass(loader) # one loader object, two passes
print(f"shuffle={shuffle}: second pass identical: {first == second}")
def sampled_nodes(seeds):
sub = neighbor_sample(g, seeds, [2, 2], seed=0)
return sub.metadata["sampling"]["original_node_ids"].tolist()
seeds = torch.arange(64)
print("same seeds, same order: ", sampled_nodes(seeds) == sampled_nodes(seeds))
print("same seeds, reversed order:", sampled_nodes(seeds) == sampled_nodes(seeds.flip(0)))
So for a loader object that you reuse across epochs:
- With
shuffle=False(a typical evaluation loop), or withbatch_size=1, batch composition and order repeat, so every pass gets exactly the same neighborhoods. - With
shuffle=Trueand larger batches, the picks do change between passes, but only because the batches change. It is a side effect of reshuffling, not a sampling seed that you set.
To resample in an explicit, controlled way, create the loader inside the epoch loop with seed=base_seed + epoch, as in the training loop above (where base_seed is 0; for repeated runs, see the reproducibility section below).
Node features outside the graph
When tensor-valued node features dominate memory, NeighborLoader can read them from a feature store for the sampled nodes only. The Graph then needs just the topology, the labels and a small placeholder for node_features.
import tempfile
from tgraphx import MemmapFeatureStore
patches = torch.randn(NUM_NODES, 3, 8, 8) # stand-in for large tensor features
store = MemmapFeatureStore(tempfile.mkdtemp())
store.put("x", patches) # the first put takes the full tensor
topology = Graph(node_features=torch.zeros(NUM_NODES, 1), edge_index=edge_index, y=labels)
loader = NeighborLoader(topology, fanouts=[5, 5], mask=train_mask, batch_size=16,
seed=0, feature_store=store, feature_name="x")
batch = next(iter(loader))
print(batch.node_features.shape) # [num_sampled_nodes, 3, 8, 8]
assert torch.equal(batch.node_features, patches[batch.input_nodes])
The first put of a name needs the whole block in one call, but the tensor you pass may be memory-mapped, so you do not need to load the whole block into memory first. The memory-mapped feature store guide fills a staging file chunk by chunk and hands it to put; the feature store for tensor node features article compares the two store classes.
GraphSAINT and Cluster-GCN: the short version
The other two families train on a whole subgraph per step instead of expanding around seed nodes. Their complete training loops are in the GraphSAINT and Cluster-GCN comparison.
GraphSAINT. A sampler (GraphSAINTNodeSampler, GraphSAINTEdgeSampler or GraphSAINTRandomWalkSampler) draws subgraphs, and GraphSAINTLoader yields them as Graph objects.
from tgraphx import GraphSAINTLoader, GraphSAINTRandomWalkSampler
sampler = GraphSAINTRandomWalkSampler(g, num_roots=60, walk_length=3,
num_steps=8, seed=0)
sub = next(iter(GraphSAINTLoader(sampler, num_norm_samples=200)))
ids = sub.metadata["sampling"]["original_node_ids"]
p = sub.metadata["graphsaint"]["node_norm"] # estimated inclusion probabilities
print(sub.num_nodes, int(g.train_mask[ids].sum()), tuple(p.shape))
- The loader does not correct anything for you: divide each training node's loss by its probability.
- Pass an integer
seedto the sampler and changesampler.seedevery epoch. Withseed=None, 1.5.1 returns the same subgraph at every step; with a fixed seed, every pass repeats the same sequence. - A subgraph keeps the full-length masks of the source graph, so index them with the original node ids.
Cluster-GCN. A partitioner's .fit(graph) returns a PartitionResult, and ClusterLoader yields (subgraph, cluster_ids) tuples.
from tgraphx import BFSPartitioner, ClusterLoader
partition = BFSPartitioner(num_partitions=24, seed=0).fit(g)
print("cut edges:", partition.cut_edges, "of", g.num_edges)
sub, cluster_ids = next(iter(ClusterLoader(g, partition, num_clusters_per_batch=4, seed=0)))
print(sub.num_nodes, len(cluster_ids))
- Create the
ClusterLoaderinside the epoch loop with a newseed. One loader object repeats the same cluster groupings every time you iterate it. - TGraphX has
RandomBalancedPartitioner,BFSPartitioner,ConnectedComponentPartitionerandSpectralPartitioner(up to 4,096 nodes by default), and no METIS partitioner. Checkcut_edgesbefore training: edges to clusters outside the batch are dropped.
Choosing between the three
| Approach | A reasonable first choice when | Main limitation |
|---|---|---|
NeighborLoader |
node-level task, a few layers | batch size grows quickly with depth and fanout |
| GraphSAINT | deeper models, no clear community structure | you apply the normalization yourself |
ClusterLoader |
the graph has community structure a partitioner can find | edges to unselected clusters are dropped |
These are starting points. Compare validation accuracy, step time and peak memory on your own graph. The two alternatives to neighbor sampling are examined in the GraphSAINT and Cluster-GCN comparison.
For what each sampler estimates, and where its bias comes from, see the mathematics of the three samplers.
Building the graph: all-pairs kNN is O(N²)
If you construct your graph with tgx.knn_graph(x, k=10), every node is compared with every other node, so time grows quadratically. It processes queries in chunks (chunk_size=1024) but emits no warning for large inputs. With metric="euclidean" each chunk also materializes a [chunk_size, N, features] difference tensor, which gets large quickly. tgx.build_knn_graph(coords, k), which takes an [N, D] coordinate matrix, is quadratic too; it warns above 10,000 nodes when you do not pass chunk_size.
For large inputs, use a precomputed edge index or an approximate nearest-neighbor library.
Memory tips
- Reduce
batch_sizefirst, then the fanouts, and checkbatch.num_nodesandbatch.num_edgesto see the effect (remember the induced edges). - Keep large features in a feature store so that only the sampled rows are read.
- If you store features in
float16to save space, cast each batch back (batch.node_features.float()) unless you run the model under mixed precision. NeighborLoaderacceptsnum_workersfor background sampling. It has nopin_memoryargument. Its sampler loops over frontier nodes in Python, so measure sampling time separately from model time.
Reproducibility for samplers
NeighborLoader and ClusterLoader take a seed; for GraphSAINT the seed belongs to the sampler, not to GraphSAINTLoader. The neighbor, subgraph and partition samplers draw from their own generators, so torch.manual_seed does not feed those draws. It does control model initialization, and the shuffle order of a NeighborLoader created with seed=None. In that case a different torch.manual_seed puts different seed nodes into a batch together, so with shuffling and batches larger than one it also changes which neighbors are drawn.
def seed_batches(seed):
loader = NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask,
batch_size=64, seed=seed)
return [(b.seed_node_ids.tolist(), b.input_nodes.tolist()) for b in loader]
assert seed_batches(7) == seed_batches(7)
assert seed_batches(7) != seed_batches(8)
Record the sampler seeds together with the model seed. When you repeat training with several run seeds, keep their sampler seeds apart: base_seed + epoch with base seeds 0, 1 and 2 reuses the same epoch seeds, shifted by one. For NeighborLoader and ClusterLoader, a rule such as run_seed * 1_000 + epoch avoids that (below 1,000 epochs). A GraphSAINT sampler uses seed + k for draw k, so use for example run_seed * 100_000 + epoch * sampler.num_steps (while epochs × num_steps stays below 100,000). Identical batches do not guarantee bit-identical training across hardware or library versions.
On benchmark numbers
This article makes no speed or memory comparison between TGraphX and other libraries. The samplers follow the published algorithms but differ in details, such as the induced edges above, so per-epoch behavior can differ too. If sampler speed is critical to your project, profile both frameworks on your actual data before drawing conclusions.
FAQ
Q: What does fanouts=[15, 10] mean exactly?
A: Up to 15 incoming neighbors are sampled for each seed, then up to 10 incoming neighbors for each newly reached node. That is at most batch_size * (1 + 15 + 15*10) nodes, usually fewer because neighborhoods overlap. The returned edges are the induced ones, so there can be more of them than were sampled.
Q: How many entries should fanouts have?
A: One per message-passing layer. fanouts=[20] is a 1-hop sample for a 1-layer model. -1 means all neighbors at that hop.
Q: Does GraphSAINT need a normalization step in the loss?
A: Yes, and you write it. attach_norm=True (the default) only attaches the estimated probabilities to each subgraph.
Q: How does ClusterLoader handle edges between clusters?
A: With num_clusters_per_batch > 1, edges between the selected clusters are included. Edges to clusters outside the batch are dropped.
Q: What about heterogeneous graphs?
A: Heterogeneous support is Experimental, and NeighborLoader does not handle multiple node types. There is no hetero loader class; use the hetero_neighbor_sample function, which takes seed ids per node type and a fanout per relation for each hop. The typed-graph setting is covered in heterogeneous graph learning with RGCN, HAN, and HGT.
from tgraphx import HeteroGraph, hetero_neighbor_sample
writes, cites = ("author", "writes", "paper"), ("paper", "cites", "paper")
hg = HeteroGraph(
node_stores={"author": torch.randn(30, 8), "paper": torch.randn(50, 16)},
edge_stores={writes: torch.stack([torch.randint(0, 30, (120,)), torch.randint(0, 50, (120,))]),
cites: torch.randint(0, 50, (2, 150))},
)
sub = hetero_neighbor_sample(hg, {"paper": torch.tensor([0, 1])},
[{writes: 3, cites: 3}, {cites: 2}], seed=0)
print({t: sub.num_nodes(t) for t in sub.node_types})
print(sub.metadata["sampling"]["original_node_ids"]["paper"][:5]) # global paper ids