What Can Be Parallelized in a Tensor-Valued Graph Pipeline?
Not all parts of a graph learning pipeline parallelize in the same way. Some work is already parallel inside one tensor operation, some becomes parallel when you batch graphs, some can move to background processes, and some needs several devices. Other parts stay sequential: layers run one after another, and each optimizer step depends on the previous one.
This note maps what TGraphX provides at each level and what you have to do yourself. Examples tested with TGraphX 1.5.1 on CPU; the blocks build on one another. DataLoader workers were run on Linux only. GPU and multi-device behaviour is described from the source and the PyTorch documentation and was not run here.
The four levels
Level 1: operation level inside one forward pass, on one device
Level 2: sample level many graphs in one mini-batch
Level 3: data loading building graphs or subgraphs in worker processes
Level 4: multiple devices several GPUs or machines
TGraphX has direct support for the first three. For the fourth it offers a few helpers; the setup is yours.
Level 1: operations inside a forward pass
A message-passing layer gathers node tensors with edge_index, computes all
messages as one tensor with a leading edge axis, and aggregates them by target
node with index_add_ or scatter_reduce_. This replaces a Python loop over
edges with one operation:
import torch
import tgraphx as tgx
torch.manual_seed(0)
num_nodes, num_edges = 200, 1000
edge_index = torch.randint(0, num_nodes, (2, num_edges))
messages = torch.randn(num_edges, 16, 4, 4) # one tensor per edge
slow = torch.zeros(num_nodes, 16, 4, 4)
for e in range(num_edges): # one edge at a time
slow[edge_index[1, e]] += messages[e]
fast = torch.zeros(num_nodes, 16, 4, 4)
fast.index_add_(0, edge_index[1], messages) # all edges at once
assert torch.allclose(slow, fast, atol=1e-5)
TGraphX's layers contain no Python loop over nodes or edges (heterogeneous
layers do loop over edge types). A forward pass is still several operations
(indexing, convolutions or linear maps, aggregation, the update), each
dispatched to PyTorch. On CPU, many of them use PyTorch's intra-op thread pool
(torch.set_num_threads). On CUDA, PyTorch documents that index_add_ and
scatter_reduce_ can be nondeterministic; see
seeded and deterministic experiments.
The price of handling all edges together is memory. The tensor layers and
ConvMessagePassing accept chunk_size to process edges in groups, which trades
some parallelism for a smaller peak. Before enabling mixed precision for speed,
read the caveat about neighbour counts in the
performance FAQ.
In 1.5.1, chunk_size on ConvMessagePassing (sum or mean) also raises under
autocast with float32 input, and chunked TensorGATLayer can return NaN in
float16; the
source-grounded performance review
shows both.
Level 2: many graphs in one batch
For datasets of small graphs, GraphBatch merges them into one disjoint graph:
it concatenates node and edge tensors, offsets each graph's edge indices and
records a batch vector that maps nodes to graphs. All graphs must share the
same per-node feature shape. Graph-level graph_features are not carried over.
from tgraphx import Graph, GraphBatch
def make_graph(label):
n = int(torch.randint(10, 30, (1,)))
return Graph(node_features=torch.randn(n, 1, 8, 8),
edge_index=torch.randint(0, n, (2, 3 * n)),
graph_label=torch.tensor(label))
graphs = [make_graph(i % 3) for i in range(64)]
batch = GraphBatch(graphs) # the constructor takes a list
print(batch.num_graphs, batch.node_features.shape[1:]) # 64 torch.Size([1, 8, 8])
model = tgx.build_model("graph_classification", layer="sage", in_shape=(1, 8, 8),
hidden_shape=(8, 8, 8), num_layers=2, num_classes=3).eval()
with torch.no_grad():
batched = model(batch.node_features, batch.edge_index, batch=batch.batch)
one_by_one = torch.cat([
model(g.node_features, g.edge_index,
batch=torch.zeros(g.num_nodes, dtype=torch.long))
for g in graphs])
print(batched.shape) # torch.Size([64, 3])
assert torch.allclose(batched, one_by_one, atol=1e-5)
No edges connect different graphs, so in evaluation mode this model gives the
same result batched or one at a time. Layers with BatchNorm, such as
ConvMessagePassing, compute statistics over the whole batch in training mode,
so there the batch composition does matter. Batching usually uses a GPU better
than many tiny forward passes; measure it on your own graphs.
Level 3: building batches in worker processes
If creating a graph is expensive (reading files, cutting patches, building
edges), do it inside a dataset's __getitem__. GraphDataLoader is a subclass
of PyTorch's DataLoader and forwards num_workers, so workers can build and
collate batches while the main process trains.
from torch.utils.data import Dataset
from tgraphx import GraphDataLoader
class PatchGraphs(Dataset):
"""Builds one patch graph per image on demand."""
def __init__(self, images):
self.images = images
def __len__(self):
return len(self.images)
def __getitem__(self, i):
patches, edges = tgx.image_to_patch_graph(self.images[i], patch_size=8)
return Graph(node_features=patches, edge_index=edges,
graph_label=torch.tensor(i % 3))
if __name__ == "__main__": # required under the spawn and forkserver start methods
images = torch.randn(64, 1, 32, 32)
loader = GraphDataLoader(PatchGraphs(images), batch_size=16, num_workers=2)
seen = 0
for batch in loader:
with torch.no_grad():
out = model(batch.node_features, batch.edge_index, batch=batch.batch)
seen += out.shape[0]
assert seen == 64
There is no best num_workers. Start at 0, time an epoch, then try 2 or 4. If
your tensors are already in memory, the cost of passing batches between
processes can outweigh the gain. GraphBatch has no pin_memory() method, so
pin_memory=True does not pin its tensors.
One large graph: sampling
When the difficulty is one large graph rather than many small ones, TGraphX
ships NeighborLoader, LinkNeighborLoader, GraphSAINT samplers with
GraphSAINTLoader, and a Cluster-GCN style ClusterLoader:
from tgraphx import NeighborLoader
big = Graph(node_features=torch.randn(num_nodes, 16),
edge_index=edge_index, y=torch.randint(0, 3, (num_nodes,)))
train_mask = torch.arange(num_nodes) < 120
sampler_loader = NeighborLoader(big, fanouts=[10, 5], mask=train_mask,
batch_size=32, seed=0)
sub = next(iter(sampler_loader))
print(sub.batch_size, sub.num_nodes <= big.num_nodes) # 32 True
In 1.5.1 the neighbour sampler loops over frontier nodes in Python, so sampling
is CPU work that num_workers can move off the main process. In a Linux check
with torch 2.15 and its default sharing strategy, LinkNeighborLoader workers
ran only with the fork start method; use num_workers=0 if they exit under
spawn or forkserver (the Linux default from Python 3.14).
The graph structure itself still has to fit in memory. Large node features can be kept in a feature store, and the neighbour sampling guide covers the loaders.
Level 4: multiple devices
TGraphX does not ship a distributed training framework. tgraphx.distributed
has helpers: environment detection, rank-zero printing, rank_seed,
distributed_device, shard_indices, maybe_wrap_ddp and a run-summary writer.
Launching processes, calling torch.distributed.init_process_group, splitting
the data and handling a graph too large for one machine are your job.
Use PyTorch's DistributedDataParallel (DDP), and give every rank its own data.
For a dataset of graphs that means a DistributedSampler, so each rank batches
whole graphs; for node tasks, give each rank its own seed nodes.
from torch.utils.data.distributed import DistributedSampler
from tgraphx.distributed import maybe_wrap_ddp, shard_indices
dataset = PatchGraphs(torch.randn(64, 1, 32, 32))
sampler = DistributedSampler(dataset, num_replicas=2, rank=0) # rank 0 of 2
rank_loader = GraphDataLoader(dataset, batch_size=16, sampler=sampler)
print(len(sampler), len(rank_loader)) # 32 2
seeds = torch.arange(10)
print(shard_indices(seeds, rank=1, world_size=4, drop_last=True).tolist()) # [2, 3]
assert maybe_wrap_ddp(model) is model # no process group: unchanged
In a real run, take num_replicas and rank from the process group and call
sampler.set_epoch(epoch) each epoch. A complete script is in
distributed GNN training.
Do not use nn.DataParallel for graph inputs. It splits every tensor argument
along dimension 0: node features are cut without regard to edges, and an
edge_index of shape [2, E] is separated into its source row and its target
row.
Pipeline diagram
Worker 0: build graphs, collate batch 0 -> batch 2 -> ...
Worker 1: build graphs, collate batch 1 -> batch 3 -> ...
|
v
Main: receive batch -> .to(device) -> forward -> backward -> step
|
Inside forward (per layer): v
x[source] -> message function -> index_add_ / scatter_reduce_ -> update
Summary
| Level | What TGraphX provides | What you provide |
|---|---|---|
| Operations | vectorised message passing; optional chunk_size |
device and thread settings |
| Many graphs | GraphBatch, GraphDataLoader, GraphLoader |
batch size; one per-node feature shape |
| One large graph | neighbour, GraphSAINT and cluster loaders | fanouts, seed mask, evaluation |
| Data loading | num_workers on the graph, neighbour and link loaders |
worker count; the __main__ guard; for the link loader, a start-method check (see sampling above) |
| Multiple devices | helpers in tgraphx.distributed |
process group, DDP, data split, launch |
Practical guidance
For experiments on one GPU or CPU, batch your graphs first and get the results correct. Then measure whether data loading or the model dominates, for example with the profiling workflow, before adding workers or devices. Move to DDP only when a single device is correct and genuinely too slow or too small.