How Optimized Is TGraphX? A Source-Grounded Performance Review
When evaluating a graph learning library, reading the source is a good way to learn where the costs are. Marketing claims and informal benchmarks tell you little about where bottlenecks live. This review looks at the installed TGraphX 1.5.1 package (Beta): which optimizations exist, where they apply, where the costs are, and what is out of scope.
It contains no speed or accuracy benchmarks. Statements about behaviour come from the 1.5.1 source, and the code blocks are small CPU checks that you can run yourself, in order. Nothing here was run on a GPU. Examples tested with TGraphX 1.5.1.
What "Performance" Means Here
Separate three things that people mean by "performance":
- Throughput: how many samples or edges are processed per second?
- Memory: how much CPU or GPU memory does a forward and backward pass need?
- Scalability: what happens when the graph no longer fits, or you have several GPUs?
Aggregation: Vectorized, Plain PyTorch
The central operation in message passing is aggregation: combining messages from neighbors at each target node. TGraphX's layers do this with PyTorch tensor operations such as index_add_, scatter_add_ and scatter_reduce_. The layers' forward passes have no per-node Python loop. Loops that remain are over layers, propagation steps, attention heads, node or edge types, or edge chunks.
The wheel ships no compiled extensions or custom CUDA kernels. So there is nothing to build at install time, GPU support is whatever your PyTorch installation provides, and the speed ceiling is that of PyTorch's own kernels.
tgraphx.sparse offers segment utilities and a select_backend("torch_scatter") switch. In 1.5.1 the GNN layers do not call that module, so selecting a backend there does not change how they run.
Memory: Messages Are Built Per Edge
Most layers materialise one tensor per edge before aggregating, so memory scales with the number of edges times the size of a message. With tensor-valued nodes, a message is a whole feature map:
ConvMessagePassinggathers source and target maps and concatenates them,[E, 2C, H, W], before its convolution.TensorGATLayergathers projected source and target maps,[E, heads, C_head, H, W]each, plus[E, heads]scores.TensorGraphSAGELayerbuilds[E, C_out, H, W]messages.GCNConvbuilds[E + N, D_in]messages.D_inis the input width, because aggregation happens before the linear layer, and theNextra rows are the self-loops it adds by default.
estimate_message_memory gives the size of one such buffer, [E, *out_shape]. Despite the parameter name, for GCNConv pass the input width as out_shape and E + N as num_edges:
import torch
from tgraphx.performance import estimate_message_memory
vector = estimate_message_memory(num_edges=500_000, out_shape=(128,), dtype=torch.float32)
tensor = estimate_message_memory(num_edges=500_000, out_shape=(64, 16, 16), dtype=torch.float32)
print(vector["total_mb"]) # 244.141
print(tensor["total_mb"]) # 31250.0
The same edge count needs 128 times more memory per buffer when each message is a 64 × 16 × 16 map rather than a 128-vector. The estimate excludes weights, optimizer state, gradients and intermediate activations, and the function's own note warns that actual peak use may be 2-3 times higher.
Chunked Forward: Check What It Saves
TensorGraphSAGELayer, TensorGINLayer, TensorGATLayer and ConvMessagePassing accept chunk_size= in forward, which processes edges in blocks. (For ConvMessagePassing with aggr="max" it is ignored with a warning.) Under torch.no_grad(), per-chunk tensors can be released as the loop proceeds. Under autocast it needs care: with float32 input ConvMessagePassing raises, even under no_grad, and in float16 TensorGATLayer can return NaN (see "Float16, bfloat16 and AMP" below).
During training it is different, because autograd keeps what each chunk needs for the backward pass. This block counts the bytes saved for backward with and without chunking:
import tgraphx as tgx
torch.manual_seed(0)
N, E = 100, 2000
x = torch.randn(N, 8, 8, 8)
edge_index = torch.randint(0, N, (2, E))
def bytes_saved_for_backward(fn):
storages = {}
def pack(t):
storages[t.untyped_storage().data_ptr()] = t.untyped_storage().nbytes()
return t
with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
out = fn()
return sum(storages.values()) / 1e6, out
for layer in (tgx.TensorGraphSAGELayer(8, 8), tgx.TensorGATLayer(8, 8)):
full_mb, full = bytes_saved_for_backward(lambda: layer(x, edge_index))
chunk_mb, chunked = bytes_saved_for_backward(
lambda: layer(x, edge_index, chunk_size=200)
)
assert torch.allclose(full, chunked, atol=1e-5)
print(f"{type(layer).__name__}: {full_mb:.1f} MB saved unchunked, {chunk_mb:.1f} MB chunked")
In this check the outputs agree and the saved bytes do not go down. Treat chunk_size as an inference tool unless you measure a training benefit for your model. For training, reduce the edges per step (sampling, below), or look at torch.utils.checkpoint, which the TGraphX layers do not use themselves.
Float16, bfloat16 and AMP
Low precision causes two kinds of problem in 1.5.1: some components raise an error under autocast, and some results are silently wrong.
One thing is handled, and only at the level of the softmax computation: the internal edge_softmax used by TensorGATLayer (unchunked) and GATv2Conv computes in float32 when the scores are float16 or bfloat16. That does not make those layers safe as a whole (GATv2Conv still fails on low-precision input, shown below). The chunked GAT path and the HGT and HAN layers have their own softmax code.
fit(..., amp=True) and train_epoch(..., amp=True) wrap the forward pass in CUDA autocast only. They do nothing on CPU and do not use a GradScaler. If you need gradient scaling for float16, write the training loop yourself.
Some layers raise under autocast
In CPU autocast checks with bfloat16 and float16, each of these stopped with a dtype RuntimeError, also under torch.no_grad():
| Component | Raises when |
|---|---|
GATv2Conv |
its input is already bfloat16 or float16, for example after nn.Linear or GCNConv inside autocast |
ConvMessagePassing with chunk_size (aggr="sum" or "mean", more edges than the chunk size) |
its input is float32 |
RGCNConv, HANConv, TGATConv |
the input is float32 |
HGTConv |
the input is bfloat16 or float16 |
GraphClassifier (pooling="mean", the default, or "sum") |
the input is float32, bfloat16 or float16 |
KGRGCNModel.forward_kg |
called inside autocast |
The block below reproduces each case in bfloat16 and then applies the workaround: disable autocast around the call and cast floating-point inputs with .float().
from tgraphx.kg import KGRGCNModel, KnowledgeGraph
from tgraphx.layers.han import HANConv
from tgraphx.layers.hgt import HGTConv
from tgraphx.layers.rgcn import RGCNConv
from tgraphx.temporal import TGATConv
torch.manual_seed(0)
low_dtype = torch.bfloat16
feats = torch.randn(20, 8) # float32 vectors
maps = torch.randn(20, 3, 4, 4) # float32 feature maps
links = torch.randint(0, 20, (2, 60))
times, now = torch.rand(60), torch.ones(20)
etype = ("n", "to", "n")
one_graph = torch.zeros(20, dtype=torch.long)
triples = torch.stack([links[0], torch.zeros(60, dtype=torch.long), links[1]], dim=1)
kg = KnowledgeGraph(triples, num_entities=20, num_relations=1)
gatv2 = tgx.GATv2Conv(8, 8)
conv_mp = tgx.ConvMessagePassing((3, 4, 4), (6, 4, 4), dropout_prob=0.0)
rgcn, han, tgat = RGCNConv(8, 8, 1), HANConv(8, 8), TGATConv(8, 8)
hgt = HGTConv(8, 8, ["n"], [etype], num_heads=2)
classifier = tgx.GraphClassifier((3, 4, 4), (6, 4, 4), 2, dropout_prob=0.0)
kg_model = KGRGCNModel(20, 1, embedding_dim=8)
cases = { # name: (call, an input that triggers the error)
"GATv2Conv": (lambda t: gatv2(t, links), feats.to(low_dtype)),
"ConvMessagePassing, chunked": (lambda t: conv_mp(t, links, chunk_size=7), maps),
"RGCNConv": (lambda t: rgcn(t, {0: links}, 20), feats),
"HANConv": (lambda t: han(t, {"path": links}), feats),
"TGATConv": (lambda t: tgat(t, links, times, now), feats),
"HGTConv": (lambda t: hgt({"n": t}, {etype: links}), feats.to(low_dtype)),
"GraphClassifier": (lambda t: classifier(t, links, batch=one_graph), maps),
"KGRGCNModel": (lambda t: kg_model.forward_kg(kg, t), triples),
}
for name, (call, inp) in cases.items():
with torch.no_grad(), torch.autocast("cpu", dtype=low_dtype):
try:
call(inp)
except RuntimeError as err:
assert "dtype" in str(err) or "scalar type" in str(err)
print(f"{name}: {err}")
else:
raise AssertionError(f"{name} was expected to raise under autocast")
with torch.autocast("cpu", enabled=False): # workaround
call(inp.float() if inp.is_floating_point() else inp)
This list is what these checks found, not a guarantee about every other module. Run one forward pass of your whole model under autocast before a long job.
HANConv needs one more step, with or without autocast: it creates its per-path weights on first use, with the dtype of that input. Run one float32 forward pass with every metapath name before you build the optimizer and before load_state_dict. An optimizer built earlier never updates those weights, without raising an error, and a trained state_dict fails to load into a fresh layer with Unexpected key(s).
Some results are silently wrong
Running without an error does not mean the result is right. Neighbor counts and degrees are accumulated in the same dtype as the data. A bfloat16 counter stops increasing at 256 and a float16 counter at 2048 (adding 1 no longer changes the value), so nodes with more incoming edges than that can get wrong averages. The affected paths include mean aggregation (the TensorGraphSAGELayer default), the degree normalisation in GCNConv and APPNP, and the mean graph readout of build_model models. Here is a node with 1000 incoming edges under CPU bfloat16 autocast:
torch.manual_seed(0)
degree = 1000
star_x = torch.ones(degree + 1, 2, 1, 1)
star_edges = torch.stack([torch.arange(1, degree + 1),
torch.zeros(degree, dtype=torch.long)])
sage = tgx.TensorGraphSAGELayer(2, 2)
with torch.no_grad():
reference = sage(star_x, star_edges)
self_term = sage.W_self(star_x)[0]
with torch.autocast("cpu", dtype=torch.bfloat16):
low = sage(star_x, star_edges)
ratio = (low[0].float() - self_term) / (reference[0] - self_term)
print(ratio.flatten()) # neighbor term about 3.9 times too large
assert (ratio > 3.5).all()
# Workaround: run the aggregating layer in float32
with torch.no_grad(), torch.autocast("cpu", dtype=torch.bfloat16):
with torch.autocast("cpu", enabled=False):
fixed = sage(star_x.float(), star_edges)
assert torch.allclose(fixed, reference)
For GCNConv, the degree counter takes the dtype of the layer's input. A first layer fed float32 features is therefore not affected, even under autocast, but a stacked second layer that receives the first layer's bfloat16 output is:
torch.manual_seed(0)
vec = torch.ones(degree + 1, 4)
conv1, conv2 = tgx.GCNConv(4, 4), tgx.GCNConv(4, 4)
with torch.no_grad():
ref1 = conv1(vec, star_edges)
ref2 = conv2(ref1, star_edges)
with torch.autocast("cpu", dtype=torch.bfloat16):
h = conv1(vec, star_edges) # float32 in, bfloat16 out
out = conv2(h, star_edges) # bfloat16 in
with torch.autocast("cpu", enabled=False):
fixed = conv2(h.float(), star_edges)
first = h[0].float() / ref1[0]
second = out[0].float() / ref2[0]
print(first) # about 1.0
print(second) # about 2.0
assert torch.allclose(first, torch.ones(4), atol=0.05)
assert (second > 1.8).all()
assert torch.allclose(fixed, ref2, rtol=0.02)
So cast the input with .float() as well as disabling autocast. Disabling autocast alone leaves the input in bfloat16 (here the layer then stops with a dtype-mismatch RuntimeError).
If your graph has hubs, keep the averaging layers in float32 or check your maximum in-degree against the limits above before enabling mixed precision.
Chunking has a silent case of its own. In float16, the default autocast dtype on CUDA, chunked TensorGATLayer with its default add_self_loops=False returned NaN for every node with no incoming edges. The unchunked path did not, and neither did chunked bfloat16:
torch.manual_seed(0)
few_maps = torch.randn(4, 3, 4, 4)
few_edges = torch.tensor([[0, 0, 1, 2], [1, 2, 2, 1]]) # nodes 0 and 3 receive no edge
gat_layer = tgx.TensorGATLayer(3, 8)
def nan_nodes(t):
return torch.isnan(t).flatten(1).any(dim=1).tolist()
with torch.no_grad(), torch.autocast("cpu", dtype=torch.float16):
chunked_out = gat_layer(few_maps, few_edges, chunk_size=2)
unchunked_out = gat_layer(few_maps, few_edges)
with torch.autocast("cpu", enabled=False):
float32_out = gat_layer(few_maps.float(), few_edges, chunk_size=2)
assert nan_nodes(chunked_out) == [True, False, False, True]
assert not any(nan_nodes(unchunked_out)) and not any(nan_nodes(float32_out))
A layer converted with .half() showed the same NaN without autocast. add_self_loops=True avoids it in this example, but it changes the model, and with attn_dropout > 0 in training mode all of a node's attention terms can still be dropped, giving NaN again.
All of these precision checks ran on CPU (torch 2.15). CUDA autocast was not run for this review.
Batching, Sampling and Data Loading
Many small graphs. GraphBatch([g1, g2, ...]) concatenates graphs into one disconnected graph with a batch vector. GraphDataLoader is a subclass of PyTorch's DataLoader, so options such as num_workers work as usual.
One large graph. TGraphX ships sampling: NeighborLoader, LinkNeighborLoader, neighbor_sample, k_hop_subgraph, random-walk sampling, GraphSAINT samplers with GraphSAINTLoader, and Cluster-GCN style partitioners with ClusterLoader (no METIS). MemmapFeatureStore can keep node features on disk and feed them to NeighborLoader. The sampling math article explains the methods.
The sampler has its own cost. neighbor_sample, which NeighborLoader calls for every batch, is written in Python and PyTorch: at each hop it loops over the frontier nodes and, for each one, scans that hop's candidate edges. The work per hop grows with frontier size times candidate edges, so per-batch sampling time can grow much faster than the batch size on large, dense graphs. Time the loader separately from the model before concluding that the model is the slow part:
import time
from tgraphx import Graph, NeighborLoader
torch.manual_seed(0)
g = Graph(node_features=torch.randn(5000, 16),
edge_index=torch.randint(0, 5000, (2, 25000)),
y=torch.randint(0, 3, (5000,)))
train_mask = torch.zeros(5000, dtype=torch.bool)
train_mask[:512] = True
model = tgx.GCNConv(16, 3)
for batch_size in (64, 256):
loader = NeighborLoader(g, fanouts=[10, 5], mask=train_mask,
batch_size=batch_size, seed=0)
start = time.perf_counter()
batches = list(loader) # sampling only
sample_s = time.perf_counter() - start
start = time.perf_counter()
with torch.no_grad():
for b in batches:
model(b.node_features, b.edge_index) # model only
model_s = time.perf_counter() - start
print(f"batch_size={batch_size}: sampling {sample_s:.3f} s, model {model_s:.3f} s")
The timings depend on your machine, so none are quoted. NeighborLoader also accepts num_workers= to move sampling into worker processes. Pass mask= for the training seeds: without it every node is a seed.
Distributed Training: Helpers, Not a Framework
tgraphx.distributed provides rank and world-size queries, rank-zero printing, barrier, rank_seed, shard_indices, maybe_wrap_ddp and a run-summary writer. Its source says plainly that TGraphX does not ship a distributed training framework. It does not initialise the process group, and it does not partition a graph across machines or exchange features between partitions.
For several GPUs, use PyTorch DistributedDataParallel and decide yourself what each rank trains on. Avoid nn.DataParallel: it splits tensor arguments along the first dimension, which would cut edge_index of shape [2, E] apart. See distributed GNN training.
Performance Audit Matrix
| Dimension | What TGraphX 1.5.1 provides | Where |
|---|---|---|
| Aggregation | Vectorized scatter operations, no per-node Python loop in layers | layers/ |
| Compiled or custom CUDA kernels | None | wheel contents |
torch.compile |
Not applied by the library; test it on your model | whole package |
| Device handling | recommended_device(); Graph.to() moves the graph tensors in place |
performance.py, core/graph.py |
| Chunked edge processing | chunk_size= on four tensor layers |
layers/ |
| Mixed precision | float32 upcast in edge_softmax; CUDA-only amp=True without GradScaler; some components raise under autocast |
layers/_scatter.py, training.py |
| Memory estimate | One message buffer | performance.py |
| Sampling | Neighbor, link-neighbor, GraphSAINT, cluster loaders | loaders.py, graphsaint.py, cluster_gcn.py |
| Distributed | DDP helpers only | distributed.py |
| Benchmarks | Timed smoke suite on tiny synthetic data; OGB evaluator wrappers | benchmarks/ |
run_v13_benchmark_suite checks that components run and how long they take on tiny inputs. It is not evidence about speed or accuracy on your problem.
What This Means for Experiment Design
- Estimate message memory before launching, using your real edge count and feature shape.
- If the full graph does not fit, sample; then check whether sampling or the model dominates the step time.
- Before using low precision, run a forward pass of your model under autocast (some layers raise) and check the output for NaN and your maximum in-degree (some results are silently wrong).
- Record the environment next to results:
env_report(include_hardware=True)returns Python, PyTorch and TGraphX versions, device information and basic hardware facts. - Seed with
tgraphx.reproducibility.set_seed(seed, deterministic=True)when you need repeatable runs; deterministic algorithms can cost speed. - If you build large synthetic graphs to stress-test with
generate_graph, checknum_edges: in 1.5.1 theerandbamethods return zero edges above 10,000 nodes without an error, and you would be timing an empty graph.
For the measurement itself, see profiling a TGraphX workflow, and for short answers to common questions, the performance FAQ.
Honest Assessment
TGraphX is optimized at the level of vectorized message passing in plain PyTorch. It is not optimized at the level of custom kernels or compiled graph execution, its neighbor sampler does a noticeable amount of work in Python, and per-edge feature maps make memory the first limit for tensor-valued graphs. It does offer sampling loaders, edge chunking for inference and a memory estimate to work within those limits. Mixed precision needs checking layer by layer.
How fast it is relative to other libraries is not something a source review can tell you. The way to find out is to instrument your actual workload, on your actual hardware, with your actual data.