TGraphX › Insights › TGraphX Performance FAQ: Speed, GPU Use, Parallelism, and Limits
← Back to Insights

TGraphX Performance FAQ: Speed, GPU Use, Parallelism, and Limits

Topic: Sampling, feature stores and performance

Practical questions about TGraphX performance, answered from the 1.5.1 source code and small checks. These answers describe what the library does and does not implement. They make no claim about how fast it runs on your hardware.

Examples tested with TGraphX 1.5.1 on CPU. The blocks build on one another, so run them in order. GPU behaviour is described from the source and the PyTorch documentation and was not run here.

For a longer walk through the source, see the source-level performance review.


Does TGraphX run on GPU?

Yes. TGraphX layers are ordinary nn.Modules built on PyTorch operations. recommended_device() returns a torch.device: CUDA if available, otherwise MPS, otherwise CPU. Compare device.type == "cuda", not device == "cuda".

python
import torch
import tgraphx as tgx

torch.manual_seed(0)
x = torch.randn(32, 3, 8, 8)                    # 32 nodes, each a [3, 8, 8] tensor
edge_index = torch.randint(0, 32, (2, 128))
g = tgx.Graph(x=x, edge_index=edge_index)
model = tgx.build_model("node_classification", layer="sage", in_shape=(3, 8, 8),
                        hidden_shape=(8, 8, 8), num_layers=2, num_classes=4)

device = tgx.recommended_device()
g.to(device)                                    # moves the graph's tensors in place
model.to(device)
print(model(g.x, g.edge_index).shape)           # torch.Size([32, 4])

Graph.to(device) moves node features, the edge index, edge weights and edge features, labels, graph-level tensors and stored masks. It changes the graph in place and returns the same object, so call g.clone() first if you need to keep a CPU copy.


Does TGraphX use custom CUDA kernels?

No. The 1.5.1 wheel is pure Python (py3-none-any), with no compiled extensions. The message-passing layers aggregate with PyTorch's index_add_ and scatter_reduce_, so installing needs no compilation step and kernel performance is whatever your PyTorch build provides.


Is message passing vectorized, or is there a Python loop per node?

There is no loop over nodes. A layer indexes the node features with edge_index, handles the messages for all edges as one tensor, and aggregates them by destination node with scatter operations.

The cost of that design is memory: some intermediate tensors have one row per edge. TensorGraphSAGELayer, TensorGATLayer, TensorGINLayer and ConvMessagePassing accept chunk_size to process edges in groups instead.

python
layer = tgx.TensorGraphSAGELayer(3, 16).to(device).eval()
with torch.no_grad():
    full = layer(g.x, g.edge_index)
    chunked = layer(g.x, g.edge_index, chunk_size=32)   # 32 edges at a time
print(torch.allclose(full, chunked, atol=1e-5))         # True

Chunking adds a Python loop over the chunks. ConvMessagePassing ignores chunk_size (with a warning) when aggr="max". Pass it to the layer itself: models made by build_model do not forward it. During training, autograd can keep intermediates from every chunk until the backward pass, so the saving may be much smaller than under torch.no_grad(). Measure it.

Under mixed precision, chunking has two problems in 1.5.1. ConvMessagePassing with chunk_size (aggr="sum", the default, or "mean") raises a RuntimeError under torch.autocast with float32 input, and chunked TensorGATLayer can return NaN in float16 for nodes without incoming edges. Omit chunk_size in those cases, or run the call with autocast disabled and a float32 input. The source-grounded performance review demonstrates both on CPU, with the workarounds.

For a level-by-level view, see which parts of the pipeline can be parallelized.


Does TGraphX support AMP (Automatic Mixed Precision)?

Yes, in a limited form. fit() and train_epoch() accept amp=True, which runs the forward pass and the loss under torch.autocast("cuda") when the device is CUDA. On other devices the flag does nothing. No GradScaler is used, so for stable float16 training write the loop yourself:

python
use_amp = device.type == "cuda"
scaler = torch.amp.GradScaler("cuda", enabled=use_amp)   # needs a recent PyTorch
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
target = torch.randint(0, 4, (32,), device=device)
train_mask = (torch.arange(32) < 24).to(device)

optimizer.zero_grad()
with torch.autocast("cuda", enabled=use_amp):
    out = model(g.x, g.edge_index)
    loss = torch.nn.functional.cross_entropy(out[train_mask], target[train_mask])
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
print(loss.item())

Check high-degree nodes before using low precision

Autocast has failure modes in 1.5.1 beyond speed. Some layers raise a dtype RuntimeError under it. Others run and are wrong: neighbour counts are accumulated in the data dtype, so they stop at 256 in bfloat16 and 2048 in float16, and nodes with more incoming edges can then get wrong averages without an error. On graphs with such hubs, keep the averaging layers in float32 or do not enable mixed precision. The source-grounded performance review lists the affected components and shows the checks, which ran on CPU, and the workaround.


Does TGraphX support multi-GPU or distributed training?

Not as a framework. tgraphx.distributed offers helpers such as rank-zero printing, shard_indices, rank_seed, maybe_wrap_ddp (which returns the model unchanged when no process group exists) and a run-summary writer. The module states that TGraphX does not ship a distributed training framework: launching processes, calling torch.distributed.init_process_group and splitting the graph or the seed nodes across ranks are your job.

Use PyTorch's DistributedDataParallel. Do not use nn.DataParallel for graph models: it splits tensor arguments along dimension 0, which would cut an edge_index of shape [2, E] between its source row and its destination row.


How do I estimate memory usage before running on GPU?

estimate_message_memory computes the size of one per-edge buffer of shape [E, *out_shape] and returns a dictionary:

python
from tgraphx import estimate_message_memory

# 50,000 edges, 16-channel 8×8 messages
out_buf = estimate_message_memory(num_edges=50_000, out_shape=(16, 8, 8), dtype=torch.float32)
print(out_buf["total_bytes"], out_buf["total_mb"])  # 204800000 195.312

# ConvMessagePassing first concatenates source and destination: twice the input channels
cat_buf = estimate_message_memory(num_edges=50_000, out_shape=(32, 8, 8))
print(cat_buf["total_mb"])                          # 390.625

total_mb counts 1 MB as 1024 × 1024 bytes. The figure is a floor, not a budget: it leaves out model weights, optimizer state, other intermediates and what autograd keeps for the backward pass. The function's own note field warns that the actual forward peak can be 2–3 times larger. To measure the real peak on CUDA, call torch.cuda.reset_peak_memory_stats(), run one training step, then read torch.cuda.max_memory_allocated().


How many DataLoader workers should I use?

GraphDataLoader is a subclass of PyTorch's DataLoader and forwards num_workers. NeighborLoader and LinkNeighborLoader take num_workers too. There is no value that suits every machine:

  • Start with num_workers=0 and time one epoch.
  • Try 2 or 4 and keep the change only if the epoch gets faster.
  • Workers help when building a batch is expensive, such as reading or decoding files. When the tensors are already in memory, moving batches between processes can cost more than it saves.
  • Whenever num_workers > 0, put the training entry point under if __name__ == "__main__":. The spawn and forkserver start methods require it, and one of them is the default on Windows, macOS and, from Python 3.14, Linux.

LinkNeighborLoader has a further limitation in 1.5.1. In a CPU check on Linux with torch 2.15, its workers crashed under spawn and forkserver even with the guard (DataLoader worker ... exited unexpectedly), while GraphDataLoader and NeighborLoader worked. Keep num_workers=0 for it there, or first call torch.multiprocessing.set_sharing_strategy("file_system"), which also worked. Windows and macOS were not tested.

GraphBatch defines no pin_memory() method, so pin_memory=True on a GraphDataLoader does not pin its tensors. Profiling a TGraphX workflow shows how to time data loading separately from the model.


Does TGraphX support graph sampling for large graphs?

Yes. TGraphX ships NeighborLoader, LinkNeighborLoader, GraphSAINT samplers with GraphSAINTLoader, and a Cluster-GCN style ClusterLoader. Their source marks them as Beta.

python
from tgraphx import NeighborLoader

g.cpu()                                             # sample on CPU, move each batch
loader = NeighborLoader(g, fanouts=[10, 5], mask=train_mask.cpu(), batch_size=8, seed=0)
batch = next(iter(loader))
batch.to(device)
out = model(batch.node_features, batch.edge_index)
print(batch.batch_size, batch.seed_logits(out).shape)   # 8 torch.Size([8, 4])

The argument is fanouts (not num_neighbors). Always pass mask=: with mask=None every node becomes a seed, including validation and test nodes. fit() does not accept these batches, so use your own loop. The neighbor sampling guide compares the three approaches.


Can I use torch.compile with TGraphX?

TGraphX does not call torch.compile itself. You can apply it to a layer or model as with any nn.Module. In a quick CPU check, compiled tensor GraphSAGE, GAT and GIN layers matched eager outputs; GPU compilation was not tested.

python
layer = tgx.TensorGraphSAGELayer(16, 32).eval()
x16 = torch.randn(20, 16, 8, 8)
small_ei = torch.randint(0, 20, (2, 60))
compiled = torch.compile(layer)                     # the CPU backend needs a C++ compiler
with torch.no_grad():
    print(torch.allclose(layer(x16, small_ei), compiled(x16, small_ei), atol=1e-5))  # True

The first compiled call includes compilation time, and graphs of changing size can trigger recompilation. Compare outputs and time both versions on your own model before relying on it.


How do I check my environment before running experiments?

python
info = tgx.env_report(include_hardware=True, include_sensors=True)
for key in ("python", "torch", "tgraphx", "cuda_available", "cuda_device",
            "recommended_device", "ram_total_gb", "gpu_util_pct", "gpu_temp_c"):
    print(key, info.get(key))

Store this output with your results. RAM fields need psutil; the sensor fields need pynvml and are None without it (both come with pip install "tgraphx[monitoring]"). Sensor values are a single reading from the first GPU, so use nvidia-smi dmon for continuous monitoring. cuda_mem_free_mb is computed as total memory minus the tensors allocated by this process; for free memory as the driver sees it, use torch.cuda.mem_get_info().


Does deterministic mode affect performance?

It can: PyTorch documents that deterministic algorithms are often slower. TGraphX has two seeding functions that behave differently:

python
from tgraphx.reproducibility import set_seed as set_seed_full

torch.use_deterministic_algorithms(False)
tgx.set_seed(0, deterministic=True)                 # seeds and cuDNN flags only
print(torch.are_deterministic_algorithms_enabled()) # False
set_seed_full(0, deterministic=True)                # also deterministic algorithms
print(torch.are_deterministic_algorithms_enabled()) # True
torch.use_deterministic_algorithms(False)           # restore for later code

tgraphx.reproducibility.set_seed uses warn_only=True by default, so an operation without a deterministic implementation warns instead of raising. Some CUDA operations also require the environment variable CUBLAS_WORKSPACE_CONFIG=:4096:8 to be set before Python starts. See seeded and deterministic experiments.


Are there built-in benchmarks?

There is a timed smoke suite, not a performance or accuracy benchmark. run_v13_benchmark_suite runs short tasks on tiny synthetic data (easy-mode training, neighbor loading, knowledge-graph scoring, graph generation, reinforcement learning, GraphML round trip and others) and reports a status and runtime for each:

python
from tgraphx.benchmarks import run_v13_benchmark_suite

report = run_v13_benchmark_suite(small=True, device="cpu", seed=0)
for row in report["benchmarks"]:
    print(row["name"], row["status"], row["runtime_s"])
print(report["limitations"])

Use it to confirm that these code paths run in your installation. OGBNodeEvaluator, OGBLinkEvaluator and OGBGraphEvaluator in the same module wrap the official OGB evaluators for scoring predictions; they require the ogb package and do not train or time anything.


Is there a difference between running on CPU and GPU?

The same layer code runs on both. A GPU helps when each operation does a lot of work, such as many edges or large feature maps. For small graphs and small features, transfer and launch overhead can leave the CPU just as fast or faster. Time both on your own data, and call torch.cuda.synchronize() before reading the clock on CUDA.

For installation, layer and shape questions, see all TGraphX FAQs.