TGraphX vs PyTorch Geometric: Choosing the Right Framework
PyTorch Geometric (PyG) is one of the most widely used libraries for graph neural networks. TGraphX is a newer, smaller research-engineering library built around tensor-valued node features. (New to TGraphX? Start with What Is TGX Graph?.)
This article is meant to help you make a practical choice. It does not claim that TGraphX is better than PyG. The honest answer is that for most tasks, PyG is the better choice. Below are the specific cases where TGraphX's design may be useful.
Examples tested with TGraphX 1.5.1 and PyTorch Geometric 2.8.
Quick summary
| PyTorch Geometric (PyG) | TGraphX | |
|---|---|---|
| Primary focus | General-purpose graph learning | Tensor-valued node features plus research tooling |
| Node features | Data holds tensors of any shape; most built-in convolutions expect [N, D] |
Vector layers for [N, D]; spatial layers for [N, C, H, W] and [N, C, D, H, W] |
| Ecosystem | Large and long established | Small |
| Maturity | 2.x release line | Beta; several subsystems Experimental |
| Version used here | 2.8 | 1.5.1 (Python 3.10 or newer) |
| License | MIT | MIT |
| Install | pip install torch-geometric |
pip install tgraphx |
| Paper | Fey and Lenssen, 2019 (arXiv:1903.02428) | Sajjadi and Eramian, 2025 (arXiv:2504.03953) |
What PyTorch Geometric does well
PyG should be your default for:
- Standard benchmark tasks. It has dataset classes for common node, link and graph benchmarks, such as the Planetoid citation graphs and the TU datasets. OGB provides PyG data loaders as well.
- Layer selection. GCN, GAT, GATv2, GraphSAGE, GIN, PNA, GCNII (
GCN2Conv) and many more. - Heterogeneous graphs.
HeteroData,to_heteroand heterogeneous convolutions are well developed. TGraphX's heterogeneous support is labelled Experimental. - Adjacent tasks. PyG itself includes knowledge graph embedding models (
torch_geometric.nn.kge) and an explainability framework (torch_geometric.explain). - Community. Far more users, tutorials, published implementations and answered questions.
If your work fits standard GNN benchmarks, or you are building something that others must maintain, start with PyG.
What TGraphX offers differently
Ready-made layers for tensor-valued nodes
The simplest way to use image patches as nodes in PyG is to flatten them to [N, C*H*W], which works with every built-in layer but gives up the spatial layout. Flattening is not forced: Data stores x with any trailing shape, and a custom MessagePassing layer with node_dim=0 can keep [C, H, W]. TGraphX ships such layers.
import torch
from torch_geometric.data import Data
from torch_geometric.nn import MessagePassing
import tgraphx as tgx
torch.manual_seed(0)
patches = torch.randn(16, 3, 8, 8) # one 3x8x8 patch per node
grid = tgx.build_grid_graph(4, 4, self_loops=False) # [2, E]
class PatchConv(MessagePassing):
"""A PyG layer that keeps the spatial layout: the message is a 3x3 convolution."""
# Declares what propagate() receives, so PyG need not parse it from the source file.
propagate_type = {"x": torch.Tensor}
def __init__(self, in_channels, out_channels):
super().__init__(aggr="mean", node_dim=0) # nodes are indexed along dim 0
self.conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
def forward(self, x, edge_index):
return self.propagate(edge_index, x=x)
def message(self, x_j): # x_j: [E, C, H, W]
return self.conv(x_j)
data = Data(x=patches, edge_index=grid) # PyG keeps the 4-D tensor
pyg_out = PatchConv(3, 16)(data.x, data.edge_index)
tgx_out = tgx.TensorGraphSAGELayer(3, 16)(patches, grid)
assert pyg_out.shape == tgx_out.shape == (16, 16, 8, 8)
The two layers are not the same operator: the point is only that both libraries can keep the shape, and that TGraphX saves you writing the layer.
The ready-made layers differ in what they mix. With their default settings, TensorGraphSAGELayer and TensorGINLayer use 1x1 convolutions, so they mix channels and neighbours but never pixel positions. TensorGATLayer also computes its values with a 1x1 convolution, but it derives each attention weight from the spatial average of the whole feature maps at both ends of the edge, so a change in any pixel can change the weight applied to every position. ConvMessagePassing adds 3x3 convolutions in its aggregator. Some PyG utilities assume vector features; for the data object above, data.num_node_features reports 8 (the last dimension), not 3.
Whether keeping the shape helps depends on the task. Compare against a flattened baseline before assuming it does.
The .tgx file format
GraphML and GEXF have no tensor value type. A PyG Data object can be saved with torch.save; TGraphX's .tgx file is also a torch.save bundle, with a format tag and version added.
graph = tgx.Graph(x=patches, edge_index=grid)
graph.save("experiment.tgx")
loaded = tgx.Graph.load("experiment.tgx")
assert loaded.node_features.shape == (16, 3, 8, 8)
Loading unpickles the file, so open only files you trust.
One-call baselines, run files and a local dashboard
tgx.classify_nodes trains a small built-in model in one call (by default for only 3 epochs, a smoke run) and, if you pass out_dir=, writes JSON files describing the run. tgraphx-dashboard is a separate local, read-only viewer that needs no account or cloud service. The two do not connect by themselves: in 1.5.1 the dashboard plots metrics.csv, which classify_nodes does not write, and it does not read the metrics_summary.json or benchmark_summary.json where the scores are saved. To see curves, log your own training loop, as shown under "Logging to the dashboard" below. These are conveniences, not reasons to switch on their own.
Seeding exists on both sides: PyG has torch_geometric.seed_everything, and TGraphX's tgx.reproducible() context also switches on PyTorch's deterministic settings (and leaves them on afterwards). Neither guarantees identical results across hardware or library versions, and TGraphX writes no reproducibility report by itself.
Other bundled modules
TGraphX also includes knowledge graph embedding, graph generation, graph mining, gradient-based attribution, graph reinforcement learning and evolutionary optimization in one install. PyG covers some of this too, as noted above. PyG 2.8 has no module for graph reinforcement learning or evolutionary graph search. In TGraphX the labels for these parts differ by source: the README lists classical generation and evolutionary optimization as Beta although parts of them are experimental in the registry, while neural generation and the graph RL learning algorithms are Experimental.
Side-by-side: node classification
The same two-layer GCN
Both libraries give a GCNConv(in, out) that takes (x, edge_index), so one model class can use either. With copied weights and no self-loops in the edge list, the outputs agree.
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
from tgraphx.estimators import node_train_val_test_split
torch.manual_seed(0)
x = torch.randn(100, 32) # flat vectors
edge_index = torch.randint(0, 100, (2, 300))
edge_index = edge_index[:, edge_index[0] != edge_index[1]] # drop self-loops (see below)
y = torch.randint(0, 5, (100,))
train_mask, val_mask, test_mask = node_train_val_test_split(100, 0.6, 0.2, 0.2, seed=0)
class GCN(torch.nn.Module):
def __init__(self, conv):
super().__init__()
self.conv1 = conv(32, 64)
self.conv2 = conv(64, 5)
def forward(self, x, edge_index):
return self.conv2(F.relu(self.conv1(x, edge_index)), edge_index)
pyg_model = GCN(GCNConv)
tgx_model = GCN(tgx.GCNConv)
with torch.no_grad():
for p, t in [(pyg_model.conv1, tgx_model.conv1), (pyg_model.conv2, tgx_model.conv2)]:
t.lin.weight.copy_(p.lin.weight)
t.lin.bias.copy_(p.bias)
assert torch.allclose(pyg_model(x, edge_index), tgx_model(x, edge_index), atol=1e-5)
Two differences to watch. TGraphX 1.5.1's GCNConv appends a self-loop to every node even if the edge list already contains one, while PyG adds only the missing ones, so call graph.remove_self_loops() first if your graph has them. And keep the default add_self_loops=True: with it switched off, 1.5.1 multiplies messages from nodes that have no incoming edges by a huge factor instead of dropping them.
The training loop is plain PyTorch in both cases. The loss uses training nodes only, and the validation score uses validation nodes:
masks = dict(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
pyg_data = Data(x=x, edge_index=edge_index, y=y, **masks)
g = tgx.Graph(x=x, edge_index=edge_index, y=y, **masks)
def train_full_batch(model, graph, epochs=20):
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
for _ in range(epochs):
model.train()
optimizer.zero_grad()
logits = model(graph.x, graph.edge_index)
F.cross_entropy(logits[graph.train_mask], graph.y[graph.train_mask]).backward()
optimizer.step()
model.eval()
with torch.no_grad():
predicted = model(graph.x, graph.edge_index).argmax(dim=1)
return (predicted[graph.val_mask] == graph.y[graph.val_mask]).float().mean().item()
pyg_val = train_full_batch(pyg_model, pyg_data)
tgx_val = train_full_batch(tgx_model, g)
The labels here are random, so the scores carry no information. Keep test_mask untouched until you have finished choosing settings.
Mini-batches with neighbor sampling
TGraphX's NeighborLoader takes fanouts and mask, where PyG's takes num_neighbors and input_nodes. Pass the training mask: without it every node is used as a seed. The model is called on the sampled subgraph, and the loss only on the seed nodes.
loader = tgx.NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask, batch_size=32, seed=0)
model = GCN(tgx.GCNConv)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
for batch in loader:
out = model(batch.node_features, batch.edge_index)
loss = F.cross_entropy(batch.seed_logits(out), batch.seed_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
tgx.fit does not apply to this loader, and it ignores node masks on full graphs, so write the loop for node classification.
The one-call version
import json
from pathlib import Path
from tgraphx.reproducibility import reproducibility_report
with tgx.reproducible(seed=42, deterministic=True):
result = tgx.classify_nodes(
x=x, edge_index=edge_index, labels=y,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
seed=42, device="cpu", out_dir="runs/baseline",
fast_mode=False, # the default, True, trains for only 3 epochs
)
# TGraphX does not write this file for you. The dashboard looks for this name.
report_path = Path("runs/baseline/reproducibility_report.json")
report_path.write_text(json.dumps(reproducibility_report(), indent=2))
print(result.metrics["epochs"]) # 15
print(sorted(p.name for p in Path("runs/baseline").iterdir()))
Do not treat the scores of a default call as a baseline: fast_mode=True is a 3-epoch smoke run. fast_mode=False, used above, trains for 15 epochs, which may still be too few for your data. Set epochs= to choose the number yourself, and choose it on the validation score.
For vector features classify_nodes trains its own two-layer GCN, whatever model= string you pass; for image or volume features, model="tensor_gcn" trains one ConvMessagePassing layer with a linear head. It returns metrics, not the trained model. Pass all three masks: with some missing, the reported scores can be computed on the wrong nodes. It also reseeds with its own seed= argument, so set that, not only the seed of the context.
Logging to the dashboard
The dashboard will not show the scores from the call above. Pointed at runs/baseline, it reads the run metadata and the reproducibility report saved there, but it has no metrics to plot. To plot a run, write metrics.csv with CSVLogger from your own loop:
from tgraphx.tracking import CSVLogger
torch.manual_seed(0)
model = GCN(tgx.GCNConv)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
with CSVLogger("runs/gcn") as logger: # writes runs/gcn/metrics.csv
for epoch in range(20):
model.train()
optimizer.zero_grad()
logits = model(g.node_features, g.edge_index)
loss = F.cross_entropy(logits[g.train_mask], g.node_labels[g.train_mask])
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
logits = model(g.node_features, g.edge_index)
val_loss = F.cross_entropy(logits[g.val_mask], g.node_labels[g.val_mask])
val_acc = (logits[g.val_mask].argmax(1) == g.node_labels[g.val_mask]).float().mean()
logger.log(epoch=epoch, train_loss=loss.item(),
val_loss=val_loss.item(), val_accuracy=val_acc.item())
print(sorted(p.parent.name for p in Path("runs").glob("*/metrics.csv"))) # ['gcn']
Then run tgraphx-dashboard --logdir runs/. With --logdir set to a parent folder, only subfolders that contain metrics.csv are listed as runs, so you get gcn and not baseline. CSVLogger appends to an existing file, so use a new folder for each run. It records whatever numbers you pass, so a PyG training loop can be logged the same way.
Using PyG and TGraphX together
Both use a [2, E] edge_index with messages flowing from row 0 to row 1, so a PyG layer can be called on the tensors of a TGraphX graph. Converters live in tgraphx.interop (they need PyG: pip install "tgraphx[pyg]"), but they do not carry masks across.
from tgraphx.interop import from_pyg_data, to_pyg_data
assert GCNConv(32, 5)(g.node_features, g.edge_index).shape == (100, 5)
assert getattr(to_pyg_data(g), "train_mask", None) is None # lost going out
assert from_pyg_data(pyg_data).train_mask is None # and coming in
converted = tgx.Graph(x=pyg_data.x, edge_index=pyg_data.edge_index, y=pyg_data.y,
train_mask=pyg_data.train_mask, val_mask=pyg_data.val_mask,
test_mask=pyg_data.test_mask)
assert torch.equal(converted.train_mask, train_mask)
See a complementary TGraphX and PyTorch Geometric workflow for more on combining them.
How to decide
- Is there a PyG layer, dataset class or published implementation for your task? Start with PyG.
- Do your node features have a spatial layout the model should keep? If not, PyG is the simpler choice.
- If they do, would you rather write the
MessagePassinglayer yourself, as above, or take a ready-made one? - Before committing, build the smallest version of your problem, including a flattened baseline, and compare on held-out data.
For image-patch or volume nodes, the half-day fit test against PyG gives a decision tree and a script for step 4.
When to choose each
Choose PyTorch Geometric if:
- Your task appears in standard GNN benchmarks
- You need a wide choice of layer architectures
- Others have to maintain or deploy what you build
- You need extensive community support and existing solutions
- Your node features are flat vectors
- You need heterogeneous graph support
Consider TGraphX if:
- Your nodes are images, patches or volumes, and the model should keep that layout
- You want ready-made message passing layers for those shapes
- You want graph RL or evolutionary graph search next to your GNN code and accept their Beta or Experimental status
- You want a local viewer for metrics you log yourself, without an account or service
- You are in a research setting where ecosystem breadth matters less
Honest limitations of TGraphX
- The package is classified as Beta. In the 1.5.1 registry (
tgx.api_status),Graph,GraphBatch,fit,GCNConvand the tensor layers are "stable",NeighborLoaderandclassify_nodesare "beta", and heterogeneous graphs, graph generation, evolutionary optimization and graph RL training are "experimental". - No shipped message-passing layer models a time axis inside a node feature.
GCNConv,GATv2Convand the tensor layers reject[N, T, D], butLinearMessagePassingand the legacyAttentionMessagePassingbuilt within_shape=(D,)run on it silently, which is not sequence support: checkx.dim() == 2or encode the sequence first. - There are no published benchmarks on billion-edge graphs.
- The kNN and radius graph builders compare all pairs of points, which takes O(N²) time.
- The spectral partitioner refuses graphs above 4,096 nodes by default.
- No production deployments are documented.
TGraphX does not claim to be faster, more accurate or more mature than PyG. Those claims would be unsupported.
Conclusion
PyTorch Geometric is the right choice for most GNN tasks. It has a larger ecosystem, broader layer selection and more community resources. A fuller account is in where PyTorch Geometric is strong and what it does not cover.
TGraphX is a specialized library for cases where node features are multi-dimensional and keeping their shape through message passing is useful. Choosing between them is not all or nothing: learn PyG for the standard GNN toolkit, and consider TGraphX when your research problem involves tensor-valued nodes. If DGL is the other library you are weighing, read the TGraphX vs DGL comparison.
FAQ
Q: Can I use PyG layers with TGraphX data?
A: Yes: call the layer on g.node_features and g.edge_index, inside an ordinary PyTorch module.
Q: Does TGraphX replicate all PyG functionality?
A: No. PyG has a much broader selection of layers and datasets and a much larger ecosystem. TGraphX targets a narrower design space.
Q: Is TGraphX slower than PyG?
A: This article has no measurement either way. A fair comparison needs the same operator, data, hardware and sampling settings; run it on your own workload.
Q: Should I switch from PyG to TGraphX?
A: Probably not, unless your use case is tensor-valued nodes and the ready-made layers save you real work. For standard GNN research, stay with PyG.
Q: Is TGraphX production-ready?
A: Not in the sense PyG is used. It is classified as Beta, with several subsystems Experimental. Treat it as a research library.