TGraphX › Insights › Distributed GNN Training with TGraphX Helpers
← Back to Insights

Distributed GNN Training with TGraphX Helpers

Topic: Sampling, feature stores and performance

Training a GNN on a single GPU works until memory runs out or training becomes too slow for iterative research. The natural next step is to distribute training across several GPUs or machines. This is harder for GNNs than for most deep learning tasks, because the graph creates dependencies between training examples. This article explains the difficulty, shows a complete PyTorch DistributedDataParallel (DDP) script for mini-batch GNN training, and states exactly which parts TGraphX's experimental tgraphx.distributed module helps with and which parts remain your job.

Examples tested with TGraphX 1.5.1 on CPU with the gloo backend (1, 2 and 4 processes on one machine). The GPU (nccl) and multi-node paths were not run.


What This Builds On

This article assumes familiarity with PyTorch's basic training loop and with subgraph-based GNN training. The neighbor sampling article is essential background, because distributed training here builds directly on mini-batch subgraphs. The feature store guide is relevant if your node features are large enough to need disk-backed storage.


Why Distributed GNN Training Is Hard

In standard image classification, training samples are independent. A batch of 256 images can be split across 4 GPUs with 64 images each, each GPU computes its gradient on its own, and the gradients are averaged.

Graph data is different. The representation of node v after two message-passing layers depends on the first-layer representations of its neighbors, which in turn depend on the input features of their neighbors. Those dependencies cross whatever boundary you draw between devices.

The problem has two faces:

Graph partitioning: if you assign different nodes to different devices, every edge that crosses a partition boundary needs communication (or replicated data) before message passing can complete. The number of such edges, the edge cut, depends on the partitioning method and the graph.

Neighborhood growth: a k-layer GNN needs features from k-hop neighborhoods. With 10 neighbors per node, one seed node can pull in up to 10 + 100 = 110 other nodes at two hops, and far more around high-degree nodes. Neighbor sampling caps this growth.

There is no free solution. Every approach trades communication against redundant memory or computation and implementation effort.


Data Parallelism for GNNs: The Mini-Batch Approach

The most common starting point is data parallelism over mini-batches of seed nodes:

  • Each rank (process) takes its own disjoint set of training seed nodes.
  • It samples their k-hop neighborhoods, runs the forward pass and computes the loss on the seeds only.
  • DDP averages the gradients across ranks (an all-reduce), so every rank applies the same update.

One step then behaves much like a single-process step with a batch world_size times larger, apart from sampling and dropout randomness. Sampled neighborhoods overlap between ranks; that is redundant work, not an error.

The simplest layout keeps a full copy of the graph in the CPU memory of every process, as the script below does, and moves only the sampled subgraph to the GPU. It works as long as those copies fit in host memory. Beyond that, the graph has to be shared between processes or partitioned.


Model Parallelism: When Weights Don't Fit

Data parallelism requires the full model on every device. Model parallelism places different layers on different devices and is meant for models that do not fit on one. GNNs usually have comparatively few parameters; their memory pressure comes from node features, per-edge messages and activations. Model parallelism is therefore rarely the first tool to reach for.


What TGraphX Provides, and What It Does Not

tgraphx.distributed is a small set of helpers. The project's README labels them Experimental.

Helper What it does
detect_distributed_environment() Reads RANK, LOCAL_RANK, WORLD_SIZE, MASTER_ADDR and similar (including SLURM fallbacks)
distributed_device(local_rank) Returns cuda:<local_rank> if CUDA is available, else CPU
get_rank, get_world_size, is_rank_zero, barrier Safe to call with or without a process group
rank_zero_print, rank_zero_only Print or run a function on rank 0 only
rank_seed(base_seed, rank) A different, reproducible seed per rank
shard_indices(indices, rank, world_size, drop_last) The contiguous slice of an index tensor owned by one rank
maybe_wrap_ddp(model, device_ids) Wraps in DDP if a process group is initialised, otherwise returns the model unchanged
write_distributed_run_summary(path, **fields) Writes a small JSON record from rank 0

It does not call torch.distributed.init_process_group, and it provides no distributed sampler, partitioned graph store or cross-rank feature fetching. The module's own documentation says TGraphX does not ship a distributed training framework.


A Complete DDP Training Script

Save this as train_ddp.py. It runs as a single process with python train_ddp.py, or in several with torchrun. The graph is synthetic so that you can run it as it is.

python
import os
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F

import tgraphx as tgx
from tgraphx import Graph, NeighborLoader
from tgraphx.distributed import (
    detect_distributed_environment, distributed_device, maybe_wrap_ddp,
    rank_seed, rank_zero_print, shard_indices,
)
from tgraphx.estimators import node_train_val_test_split


def make_graph(num_nodes=2000, num_classes=4, dim=16, seed=0):
    """Synthetic graph; the fixed seed makes every rank build the same one."""
    gen = torch.Generator().manual_seed(seed)
    y = torch.randint(0, num_classes, (num_nodes,), generator=gen)
    x = torch.randn(num_nodes, dim, generator=gen) + 0.7 * F.one_hot(y, dim).float()
    src = torch.randint(0, num_nodes, (24000,), generator=gen)
    dst = torch.randint(0, num_nodes, (24000,), generator=gen)
    keep = (y[src] == y[dst]) | (torch.rand(24000, generator=gen) < 0.05)
    edge_index = torch.stack([src[keep], dst[keep]])
    edge_index = torch.cat([edge_index, edge_index.flip(0)], dim=1)
    train, val, test = node_train_val_test_split(num_nodes, 0.6, 0.2, 0.2, seed=seed)
    return Graph(node_features=x, edge_index=edge_index, y=y,
                 train_mask=train, val_mask=val, test_mask=test)


class GCN(nn.Module):
    def __init__(self, in_dim, hidden, num_classes):
        super().__init__()
        self.conv1 = tgx.GCNConv(in_dim, hidden)
        self.conv2 = tgx.GCNConv(hidden, num_classes)

    def forward(self, x, edge_index):      # the whole computation lives in forward
        h = F.relu(self.conv1(x, edge_index))
        h = F.dropout(h, p=0.3, training=self.training)
        return self.conv2(h, edge_index)


def main(epochs=3, batch_size=64, base_seed=1234):
    env = detect_distributed_environment()          # reads RANK, WORLD_SIZE, ...
    rank, local_rank, world_size = env["rank"], env["local_rank"], env["world_size"]
    device = distributed_device(local_rank)         # cuda:<local_rank> or cpu

    # TGraphX never initialises the process group: that is your job.
    os.environ.setdefault("MASTER_ADDR", "127.0.0.1")   # torchrun sets these;
    os.environ.setdefault("MASTER_PORT", "29517")       # defaults for 1 process
    if device.type == "cuda":
        torch.cuda.set_device(device)
    dist.init_process_group("nccl" if device.type == "cuda" else "gloo",
                            rank=rank, world_size=world_size)

    graph = make_graph()                            # kept in CPU memory
    train_ids = graph.train_mask.nonzero().flatten()

    tgx.set_seed(base_seed)                         # DDP also copies rank 0's weights
    model = GCN(16, 32, 4).to(device)
    model = maybe_wrap_ddp(model, device_ids=[device.index] if device.type == "cuda" else None)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
    tgx.set_seed(rank_seed(base_seed, rank))        # per-rank dropout stream

    for epoch in range(epochs):
        # Same permutation on every rank, then a disjoint slice for this rank.
        shared = torch.Generator().manual_seed(base_seed + epoch)
        perm = train_ids[torch.randperm(train_ids.numel(), generator=shared)]
        mine = shard_indices(perm, rank=rank, world_size=world_size, drop_last=True)
        seed_mask = torch.zeros(graph.num_nodes, dtype=torch.bool)
        seed_mask[mine] = True
        loader = NeighborLoader(graph, fanouts=[10, 5], mask=seed_mask,
                                batch_size=batch_size,        # new seed each epoch:
                                seed=rank_seed(base_seed + epoch, rank))

        model.train()
        for batch in loader:
            batch = batch.to(device)
            logits = model(batch.node_features, batch.edge_index)   # not model.module
            loss = F.cross_entropy(batch.seed_logits(logits), batch.seed_y)
            optimizer.zero_grad()
            loss.backward()                         # DDP all-reduces gradients here
            optimizer.step()

        if rank == 0:                               # rank-0-only evaluation
            bare = getattr(model, "module", model)  # unwrapped: only rank 0 runs this
            bare.eval()
            with torch.no_grad():
                logits = bare(graph.node_features.to(device), graph.edge_index.to(device))
                pred = logits.argmax(1).cpu()
            val_acc = (pred[graph.val_mask] == graph.y[graph.val_mask]).float().mean().item()
            rank_zero_print(f"epoch {epoch}: {len(loader)} batches/rank, "
                            f"{mine.numel()} seeds/rank, val acc {val_acc:.3f}")
        dist.barrier()

    # Self-test: all replicas must hold identical weights.
    flat = torch.cat([p.detach().flatten() for p in model.parameters()])
    copies = [torch.empty_like(flat) for _ in range(world_size)]
    dist.all_gather(copies, flat)
    assert all(torch.allclose(c, copies[0]) for c in copies), "replicas diverged"
    rank_zero_print(f"replicas in sync across {world_size} process(es); "
                    f"{flat.numel()} parameters")

    dist.destroy_process_group()


if __name__ == "__main__":
    main()

Launch it like this:

bash
python train_ddp.py                              # 1 process
torchrun --nproc_per_node=2 train_ddp.py         # 2 processes: one per GPU, or CPU

Output of a two-process CPU run (exact accuracies depend on your hardware and library versions):

text
epoch 0: 10 batches/rank, 600 seeds/rank, val acc 0.745
epoch 1: 10 batches/rank, 600 seeds/rank, val acc 0.860
epoch 2: 10 batches/rank, 600 seeds/rank, val acc 0.887
replicas in sync across 2 process(es); 676 parameters

Training seeds come only from train_mask, the validation labels are used only for reporting, and the test nodes are never scored. This is a transductive setup: message passing can see the features of validation and test nodes, but not their labels.

The script moves batch to the device with batch.to(device); the full graph stays on the CPU except during evaluation. For a graph too large for full-graph evaluation, evaluate with a sampler as well.

The NeighborLoader seed changes every epoch on purpose. In TGraphX 1.5.1 the neighbor sampler restarts its random generator from that seed (or from a fixed default if you pass none) on every call, so every batch reuses the same random stream. A constant value gives the same sampled neighbors whenever the same batch of seed nodes, in the same order, is requested.

Call the DDP wrapper, never model.module, in training

DDP synchronises gradients through its own forward. A common mistake with multi-layer GNNs is to call the layers one by one through the wrapped object, for example model.module.conv1(x, edge_index), because nn.Sequential cannot pass edge_index. This bypasses DDP: no error is raised, each rank trains on its own gradients and the replicas drift apart. In a two-process test with a two-layer GCN, training through model.module(...) left the two ranks with different weights, while model(...) kept them identical. Put the whole computation in one forward, as GCN does, and keep a weight comparison like the one at the end of the script while developing.

Also avoid nn.DataParallel for graph inputs: it splits tensor arguments along dimension 0, which would cut an edge_index of shape [2, E] into its source and destination rows.


Giving Each Rank Its Own Seed Nodes

Drawing seeds independently on every rank, for example with torch.randint, does not give disjoint batches and does not cover each training node once per epoch. Instead, build the same permutation on every rank (a shared generator seed) and slice it:

python
import torch
from tgraphx.distributed import shard_indices

ids = torch.arange(10)
print([shard_indices(ids, rank=r, world_size=4).tolist() for r in range(4)])
print([shard_indices(ids, rank=r, world_size=4, drop_last=True).tolist() for r in range(4)])
text
[[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]]
[[0, 1], [2, 3], [4, 5], [6, 7]]

Use drop_last=True for training. Every rank must run the same number of backward passes; if one rank has an extra batch, the others never join its all-reduce and the job hangs. The dropped seeds change from epoch to epoch because the permutation changes. If ranks cannot be given equal work, DDP's model.join() context manager handles uneven inputs.


Graph Partitioning for Large-Scale Training

When one machine cannot hold the graph, you must split it. TGraphX ships partitioners in its Cluster-GCN module. They compute a cluster id for every node; they do not move data between processes. This example compares them on a 32 x 32 grid:

python
import torch
import tgraphx as tgx
from tgraphx import Graph

edge_index = tgx.build_grid_graph(32, 32, self_loops=False)
grid = Graph(node_features=torch.zeros(32 * 32, 1), edge_index=edge_index)

for partitioner in (tgx.RandomBalancedPartitioner(4, seed=0),
                    tgx.BFSPartitioner(4, seed=0),
                    tgx.SpectralPartitioner(4, seed=0)):
    part = partitioner.fit(grid)
    print(f"{part.algorithm:16s} cut {part.cut_edges:4d} of {grid.num_edges} edges, "
          f"sizes {part.partition_sizes.tolist()}")

rank = 0
owned_nodes = torch.nonzero(part.partition_id == rank).flatten()
text
random_balanced  cut 3000 of 3968 edges, sizes [256, 256, 256, 256]
bfs              cut  478 of 3968 edges, sizes [256, 256, 256, 256]
spectral         cut  246 of 3968 edges, sizes [272, 256, 256, 240]

Random assignment cuts most edges. BFS growth and spectral bisection keep neighbors together, but a grid is an easy case; results depend on the graph and, for BFS, noticeably on the seed. SpectralPartitioner is meant for small graphs only (by default it refuses graphs above 4096 nodes). There is no METIS integration.

Edges that cross partitions still have to be handled. Your options are to fetch remote neighbor features over the network (you write this, or use a library that provides it), to replicate boundary nodes, or to drop the cross-partition edges as Cluster-GCN does within each cluster batch (Chiang et al., KDD 2019). If ranks draw their seeds from their own partitions, the seed counts usually differ, so apply the equal-batches rule above.


Practical Performance Considerations

Data loading: building sampled subgraphs on the CPU can easily take longer than the GNN forward pass on a GPU. Profile it before adding GPUs. In TGraphX 1.5.1, tgraphx.sampling.neighbor_sample, which NeighborLoader calls, loops over the frontier nodes in Python and scans the candidate edges once for each of them; its source assumes modest graphs ("small graphs are typical"), so measure sampling time on your own data before planning multi-GPU runs on a large graph.

Gradient communication: DDP all-reduces the gradients of all parameters every step. The model above has 676 float32 parameters, under 3 KB per step, so for it the volume is trivial and the cost that remains is synchronisation: every rank waits for the slowest one. Larger models shift this balance.

Node feature transfer: tensor-valued node features (image patches, volumes) make each sampled subgraph large. Reading and copying them can dominate the step; see the feature store guide.


Debugging Hanging Jobs

Distributed jobs usually hang because ranks disagree about how many collective operations to run, or because one rank crashed while the others wait.

  • Compare len(loader) across ranks before training.
  • Set TORCH_DISTRIBUTED_DEBUG=DETAIL for extra DDP checks and, on GPUs, NCCL_DEBUG=INFO for NCCL logs.
  • Pass timeout=datetime.timedelta(...) to init_process_group so a stuck job fails instead of waiting for the default timeout.
  • Never run a collective (barrier, all_gather, a backward pass through the DDP wrapper) on only some ranks.

Limitations and Honest Notes

TGraphX's helpers are scaffolding around PyTorch DDP, not a distributed graph system. According to the README, the project validates a two-process CPU/gloo smoke path, and broader multi-node training is a roadmap item.

For multiple machines, torchrun takes --nnodes, --node_rank, --master_addr and --master_port; you also need network connectivity between nodes and a way for each node to read the data. This was not tested here.

If the graph has to stay partitioned across machines, look at tools built for it. PyTorch Geometric deprecated torch_geometric.distributed in version 2.7.0; its distributed training tutorials and the cuGraph-PyG project are where that deprecation notice points. DGL documents its own stack in dgl.distributed. Check the maintenance status and supported PyTorch versions of whichever you choose.

Before adding hardware, check whether sampling solves the problem on one device: GraphSAINT and Cluster-GCN loaders are available in tgraphx.graphsaint and tgraphx.cluster_gcn.


Frequently Asked Questions

Should I use DDP or model parallelism for GNNs?
Usually DDP. Model parallelism only helps when the model itself does not fit on one device.

Does maybe_wrap_ddp set up distributed training for me?
No. It wraps the model only if you have already initialised a process group; otherwise it silently returns the bare model, which is why the script above initialises the group first and checks the replicas at the end.

Does distributed training change the final accuracy?
It can. With a fixed per-rank batch size, the effective batch grows with world_size and each epoch has fewer optimizer steps (running the script above with 1, 2 and 4 processes gives 19, 10 and 5 batches per rank), so the same number of epochs can end at a lower accuracy. Keeping the effective batch size constant, or scaling the learning rate with a warm-up as in the linear scaling rule (Goyal et al., 2017, "Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour"), are starting points. That rule comes from image classification, so verify it on your task.