What Is TGX Graph? A Practical Introduction to TGraphX
Topic: Getting started with TGraphX
This article explains what a TGX graph is and how TGraphX's approach to graph data differs from other GNN libraries. Here "TGX graph" means the Graph object of TGraphX, which is conventionally imported as tgx. (A separate Python package also named TGX, installed as py-tgx, analyses and visualises temporal graphs; this page is not about it.)
What Is TGraphX?
TGraphX is an open-source (MIT) Python library for graph learning in PyTorch. It is published on PyPI as tgraphx, and its design is described in a preprint: TGraphX: Tensor-Aware Graph Neural Network for Multi-Dimensional Feature Learning (Sajjadi & Eramian, arXiv:2504.03953, 2025), developed at the University of Saskatchewan.
The project README calls it a "tensor-native graph intelligence framework". In concrete terms, a node (or an edge) can carry a whole tensor, such as an image patch [C, H, W], and several layers pass messages on that tensor without flattening it first.
pip install tgraphx
import tgraphx as tgx
print(tgx.__version__) # 1.5.1
The examples on this page were tested with TGraphX 1.5.1 on CPU. It requires Python 3.10 or newer and PyTorch 1.13 or newer.
What Does "TGX Graph" Mean?
A TGX graph is a tgx.Graph object, the basic data container in TGraphX. It holds:
node_features(aliasx): a tensor[N, ...]with one entry per node, at least 2-D (use[N, 1], not[N], for a single number per node);edge_index: a[2, E]tensor, row 0 holding source nodes and row 1 destination nodes;- optionally edge features, edge weights, node and edge labels, a graph label, boolean train/validation/test masks and a metadata dictionary.
Storage alone is not what sets it apart: a PyTorch Geometric Data object or a DGL graph can also hold higher-rank tensors. The difference is that TGraphX ships layers that read [N, C, H, W] and [N, C, D, H, W] node features directly, and that the Graph constructor checks shapes, devices and the edge index range when you build it.
import torch
import tgraphx as tgx
torch.manual_seed(0)
# 100 nodes, each an 8x8 RGB patch (random stand-in data)
x = torch.randn(100, 3, 8, 8)
edge_index = torch.randint(0, 100, (2, 300))
labels = torch.randint(0, 5, (100,))
g = tgx.Graph(x=x, edge_index=edge_index, labels=labels)
print(g.num_nodes, g.num_edges, g.feature_shape) # 100 300 (3, 8, 8)
# A tensor layer maps [N, 3, 8, 8] to [N, 16, 8, 8]: the spatial layout survives
layer = tgx.TensorGraphSAGELayer(in_channels=3, out_channels=16)
h = layer(g.x, g.edge_index)
print(h.shape) # torch.Size([100, 16, 8, 8])
An edge index that points to a node that does not exist is rejected with a ValueError at construction. After modifying a graph in place, call g.validate() to re-run the constructor checks (mask lengths excepted). tgx.validate_graph(g) is a lighter report that, for example, does not notice a negative edge index.
Why Tensor-Valued Node Features?
The classic assumption in GNN design is one flat vector per node, a matrix [N, D]. Most built-in convolution layers in PyTorch Geometric (PyG) and DGL expect that shape, which suits their typical workloads. Both libraries also let you write custom message-passing layers over higher-rank tensors.
Some research data has more structure:
- Graph-based image analysis: image regions as nodes, each a crop of shape
[C, H, W] - Volumetric medical imaging: 3D tissue regions as nodes, each a block of shape
[C, D, H, W] - Knowledge graph entities: entities that come with images or precomputed text embeddings
- Sequences: a time series
[T, D]per node. AGraphcan store it, but no message-passing layer in TGraphX 1.5.1 is designed for it
Take care with the sequence case. The tensor layers, GCNConv and GATv2Conv reject [N, T, D], but LinearMessagePassing and the legacy AttentionMessagePassing do not check the input rank: built with in_shape=(D,), they run on it without an error. The first treats each time step separately; the second also sums its attention scores over time. A successful forward pass is therefore not sequence support. Encode each series first (the experimental tgraphx.mining.GraphSequenceEncoder turns [N, T, D] into one vector per node), reshape deliberately, or write your own layer.
You can always flatten spatial features into a vector. The reshape loses no values, but a plain linear layer then has no notion of which entries were neighbouring pixels, so it cannot exploit the layout. For a deeper treatment, see Tensor-Valued Nodes in Graph Neural Networks.
TGraphX's tensor-aware layers (ConvMessagePassing, TensorGATLayer, TensorGraphSAGELayer, TensorGINLayer) keep the spatial layout through message passing. Keeping the layout is not the same as using it: the SAGE, GAT and GIN layers use 1×1 convolutions, which never mix neighbouring pixels, while ConvMessagePassing also applies 3×3 convolutions. For vector features, the package has separate layers such as GCNConv and GATv2Conv.
What Does the Core API Look Like?
For a quick first run there is a one-call helper, tgx.classify_nodes(). Pass all three node masks yourself so that you know what is being evaluated:
from tgraphx.estimators import node_train_val_test_split
train_mask, val_mask, test_mask = node_train_val_test_split(100, 0.6, 0.2, 0.2, seed=42)
result = tgx.classify_nodes(
x=x,
edge_index=edge_index,
labels=labels,
train_mask=train_mask,
val_mask=val_mask,
test_mask=test_mask,
model="tensor_gcn",
seed=42,
device="cpu",
)
print(sorted(result.metrics))
# ['epochs', 'num_classes', 'num_nodes', 'test_accuracy', 'val_accuracy']
print(result.metrics["val_accuracy"], result.metrics["test_accuracy"])
The labels here are random, so the accuracies only show that the pipeline runs. For tensor features, model="tensor_gcn" builds a small fixed model (one ConvMessagePassing layer and a linear head) and trains it with neighbor sampling for a few epochs. The call returns a WorkflowResult with metrics, config, artifacts, runtime_s and warnings. It does not return the trained model, graph or optimizer, and it writes files only if you pass out_dir.
A note on image datasets: tgx.load_dataset("cifar10", download=True) gives one patch graph per image with a graph-level label. That is graph classification, not node classification; see CIFAR-10 patch graphs. Downloading is opt-in: with the default download=False and no cached copy of the data, the call raises a RuntimeError.
Easy Mode for Exploration
If you need the trained model afterwards, use the tgx.easy namespace, which also generates synthetic data:
data = tgx.easy.synthetic_tensor_node_classification(
num_nodes=100,
node_shape=(16, 8, 8),
num_classes=10,
seed=42,
)
easy = tgx.easy.train_node_classifier(
data, model="tensor_gcn", sampler="neighbor", epochs=2,
seed=42, device="cpu", verbose=False,
)
print(sorted(easy.metrics)) # ['accuracy', 'loss']
print(type(easy.model).__name__) # the trained torch module
This generates a random graph with [16, 8, 8] node features and trains a tensor model on it. The returned EasyResult keeps model, graph, history and a summary() method. Its accuracy is measured on the training seed nodes (here every node, because no mask= was passed), so it is not a validation or test score. No dataset download required. If you would rather start from installation, follow the TGraphX quickstart.
Where TGraphX Fits
TGraphX is not a replacement for PyG or DGL. Those libraries have much larger ecosystems and user communities, with more dataset and model integrations. For standard node classification on citation graphs, OGB-style link prediction or production-scale graph learning, PyG or DGL is probably the better choice.
TGraphX targets a narrower use case: research where node or edge features are tensors rather than flat vectors, and where you want that shape to be explicit in the API. It also ships research utilities such as seeding helpers, run-artifact writers and a local dashboard. For a side-by-side discussion, see TGraphX vs PyTorch Geometric: Choosing the Right Framework.
Beyond message passing, TGraphX 1.5.1 includes modules for graph mining, knowledge graph embeddings, graph generation, evolutionary optimization and graph reinforcement learning. Maturity differs between them: for example, the package's own registry marks generate_graph, optimize_graph and train_graph_rl as experimental.
To see how the container fits with the encoder, the layers and the readout, follow the end-to-end architecture reference, which also separates what comes from the preprint and what comes from the released package.
Reproducibility Utilities
import json
from tgraphx.reproducibility import reproducibility_report
with tgx.reproducible(seed=42, deterministic=True):
result = tgx.classify_nodes(
x=x, edge_index=edge_index, labels=labels,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
seed=42, device="cpu",
)
# No report is written automatically, and the report holds no seeds: add them
record = {**reproducibility_report(),
"seed": 42, # reproducible() and classify_nodes
"split_seed": 42, # node_train_val_test_split
"data_seed": 0} # torch.manual_seed before the synthetic data
with open("reproducibility.json", "w") as f:
json.dump(record, f, indent=2)
tgx.reproducible() seeds Python's random, NumPy and PyTorch and, with deterministic=True, sets the cuDNN flags and requests deterministic algorithms in warn-only mode. It does not restore the previous settings on exit and it writes no file. classify_nodes also takes its own seed. reproducibility_report() records versions, CUDA information, determinism flags and PYTHONHASHSEED, not the seeds you used, which is why the block adds them. A fixed seed does not guarantee identical results across different hardware or library versions. For a practical checklist, see Research Reproducibility in GNN Projects.
The .tgx Native Format
GraphML has no tensor attribute type. TGraphX's .tgx format is a torch.save() bundle that keeps node and edge tensors of any rank, together with labels, masks and metadata:
g.save("experiment.tgx")
g_loaded = tgx.Graph.load("experiment.tgx")
assert torch.equal(g_loaded.x, g.x)
Loading a .tgx file unpickles it, so only load files you trust. The format covers Graph and KnowledgeGraph objects.
Limitations
TGraphX 1.5.1 is classified as Beta on PyPI. Individual APIs carry their own labels, which you can query:
for name in ("Graph", "TensorGraphSAGELayer", "NeighborLoader", "HeteroGraph"):
print(name, tgx.api_status(name))
# Graph stable
# TensorGraphSAGELayer stable
# NeighborLoader beta
# HeteroGraph experimental
It has fewer pretrained models, dataset integrations and users than PyG or DGL. If community size and ecosystem are your priority, those are better choices.
Summary
TGraphX is a PyTorch graph learning library in which node features can be multi-dimensional tensors rather than flat vectors. A TGX graph is its tgx.Graph container; around it are tensor-aware layers, sampling loaders, one-call helpers for first runs and a few research utilities. It is a specialised tool for tensor-valued graph data, not a universal GNN library.
FAQ
Q: Is TGraphX compatible with PyTorch Geometric?
A: They can coexist. tgraphx.interop provides to_pyg_data and from_pyg_data. Note that from_pyg_data copies x, edge_index, edge_weight, edge_attr and y, but not train/validation/test masks, so reattach those yourself. For vector features, graph.x and graph.edge_index are ordinary tensors that PyG layers accept.
Q: Does TGraphX require a GPU?
A: No. All examples here run on CPU, and CUDA works through normal PyTorch device handling. In the one-call helpers, device="auto" picks CUDA if it is available and otherwise CPU; it does not pick Apple MPS. tgraphx.performance.recommended_device() can return MPS, but MPS was not tested for this article.
Q: Where should I look to verify claims about TGraphX?
A: The source code at github.com/arashsajjadi/TGraphX (tag v1.5.1 matches this article), the README and the preprint (arXiv:2504.03953). The docs/ directory is in the repository, not in the installed package. Where documentation and code disagree, trust the code.
Q: Is TGraphX suitable for production use?
A: It is research-oriented and labelled Beta, with several experimental parts. For production inference at scale, a framework with a larger deployment history is the safer choice.
Q: How does TGraphX handle large graphs?
A: It provides NeighborLoader, GraphSAINT samplers and a Cluster-GCN loader. By default the whole graph stays in host memory; node features can instead be read from a disk-backed feature store. Brute-force kNN and radius builders cost O(N²) time; those in tgraphx.graph_builders warn above 10,000 nodes unless you set chunk_size. The package does not claim billion-node production readiness.
Q: Is TGX Graph the same as PyTorch Geometric's Data object?
A: They play a similar role, as the container you put a graph into, but they are different classes. A tgx.Graph is built around [N, ...] node features of any rank from 2 up and validates shapes and edge indices when it is constructed; PyG's Data can also hold higher-rank tensors, but most PyG layers expect [N, D]. tgx.Graph exposes PyG-style aliases (graph.x, graph.y, graph.edge_attr), and the converters in tgraphx.interop move data between the two. This is not drop-in PyG API compatibility. For a fuller comparison, see TGraphX vs PyTorch Geometric.