TGraphX › Insights › TGraphX and PyTorch Geometric: A Complementary Workflow
← Back to Insights

TGraphX and PyTorch Geometric: A Complementary Workflow

Topic: Framework comparisons and interoperability

Most "X vs Y" articles end with a winner. This one is about using both. PyTorch Geometric (PyG) and TGraphX work on ordinary PyTorch tensors, and both use a [2, E] edge_index whose messages flow from row 0 to row 1. So you can mix them in one program, as long as you know what a conversion drops.

This page covers the modelling side: PyG layers on TGraphX data, TGraphX loaders and layers on PyG data, and a training loop that keeps test nodes out of training. For field-by-field dataset conversion, including OGB and DGL, see interoperating with PyG, OGB and DGL datasets. Examples tested with TGraphX 1.5.1 and PyG 2.8.1 on CPU.

Who does what

Take from PyG Take from TGraphX
Layers TGraphX lacks, such as TransformerConv or PNA, and a dedicated vector SAGEConv Ready-made layers for [C, H, W] and [C, D, H, W] node features
Benchmark datasets A NeighborLoader that needs no compiled extensions
Heterogeneous graph and explainability tooling check_leakage, .tgx files, run-record writers, a local dashboard

Neither replaces the other. If you need nothing from the second column, plain PyG is simpler.

Install

bash
pip install "tgraphx[pyg]"

The pyg extra installs torch-geometric, so one command is enough. PyG's own neighbor and cluster samplers also need pyg-lib or torch-sparse; follow PyG's installation guide for those.

Bring PyG data across and keep the masks

The converters live in tgraphx.interop. The Data object below stands in for a Planetoid-style citation graph, so nothing is downloaded:

python
import torch
from torch_geometric.data import Data

import tgraphx as tgx
from tgraphx.interop import from_pyg_data

torch.manual_seed(0)
n = 120
pyg_data = Data(
    x=torch.randn(n, 32),
    edge_index=torch.randint(0, n, (2, 600)),
    y=torch.randint(0, 4, (n,)),
    train_mask=torch.arange(n) < 70,
    val_mask=(torch.arange(n) >= 70) & (torch.arange(n) < 95),
    test_mask=torch.arange(n) >= 95,
)

converted = from_pyg_data(pyg_data)
print(converted.train_mask)                        # None: masks are not copied

def with_masks(data):
    """Convert a PyG Data object and reattach its split masks."""
    c = from_pyg_data(data)
    return tgx.Graph(x=c.x, edge_index=c.edge_index, y=c.y,
                     edge_weight=c.edge_weight, edge_features=c.edge_features,
                     train_mask=data.train_mask, val_mask=data.val_mask,
                     test_mask=data.test_mask)

g = with_masks(pyg_data)
report = tgx.check_leakage(train_mask=g.train_mask, val_mask=g.val_mask,
                           test_mask=g.test_mask)
print(report["ok"], report["counts"])
text
None
True {'train': 70, 'val': 25, 'test': 25}

from_pyg_data copies x, edge_index, edge_weight, edge_attr and y. Split masks and other attributes are dropped without a warning, so reattach them. A new tgx.Graph keeps only what you pass to it, which is why with_masks hands over edge_weight and edge_features as well as the masks. The PyG-backed adapters in tgraphx.datasets, such as PyGPlanetoidDataset, use the same converter. In the other direction, to_pyg_data does not set train_mask on its result either.

With a real dataset only the first step changes: pass it to with_masks and keep the name g. The hybrid model below reads its input width and class count from g. This block downloads Cora, so it was not run for this page:

python
from torch_geometric.datasets import Planetoid

g = with_masks(Planetoid(root="data/Planetoid", name="Cora")[0])

Do not use NetworkX as a bridge between the two libraries. Graph.to_networkx() exports topology only, so every node feature and label is lost, including plain vectors.

A hybrid model: PyG and TGraphX layers together

Convolution layers from both libraries are torch.nn.Modules that accept (x, edge_index), so you can stack them. TGraphX 1.5.1 has no dedicated vector GraphSAGE class (its TensorGraphSAGELayer wants spatial axes), so this model takes SAGEConv from PyG. The training loop is plain PyTorch: the loss uses training nodes, early stopping watches the validation loss, and the test nodes are read once at the end.

python
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import SAGEConv
from tgraphx.estimators import EarlyStopping

class HybridGNN(nn.Module):
    """A PyG GraphSAGE layer followed by a TGraphX GCN layer."""
    def __init__(self, in_dim, hidden_dim, num_classes):
        super().__init__()
        self.sage = SAGEConv(in_dim, hidden_dim)          # PyG
        self.gcn = tgx.GCNConv(hidden_dim, num_classes)   # TGraphX

    def forward(self, x, edge_index):
        return self.gcn(F.relu(self.sage(x, edge_index)), edge_index)

def train(model, graph, max_epochs=60, patience=10):
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    stopper = EarlyStopping(patience=patience, mode="min")    # "min" because it watches a loss
    best_state = None
    for _ in range(max_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():
            logits = model(graph.x, graph.edge_index)
            val_loss = F.cross_entropy(logits[graph.val_mask], graph.y[graph.val_mask]).item()
        stop = stopper.step(val_loss)
        if stopper.counter == 0:                              # this epoch is the best so far
            best_state = {k: v.clone() for k, v in model.state_dict().items()}
        if stop:
            break
    model.load_state_dict(best_state)
    return model

num_classes = int(g.y.max()) + 1                          # classes numbered from 0

with tgx.reproducible(seed=42):
    model = train(HybridGNN(g.x.size(1), 64, num_classes), g)

model.eval()
with torch.no_grad():
    predicted = model(g.x, g.edge_index).argmax(dim=1)
test_accuracy = (predicted[g.test_mask] == g.y[g.test_mask]).float().mean().item()
print(f"test accuracy {test_accuracy:.3f}")       # meaningless on the random synthetic labels

The point is the wiring, not the score. Some details:

  • tgx.reproducible(seed=42) seeds the random generators and switches on PyTorch's deterministic settings, which stay on after the block. It writes no files; if you want a record, save tgraphx.reproducibility.reproducibility_report() yourself.
  • Write the loop yourself for node classification, because tgx.fit ignores node masks.
  • tgx.build_model builds TGraphX's own layers, so a model containing PyG layers is an ordinary module like the one above.
  • The two GCNConv layers are not interchangeable on every graph. TGraphX 1.5.1 adds a self-loop to every node even if the edge list already contains one, while PyG adds only the missing ones.

The same model on mini-batches

PyG's NeighborLoader needs pyg-lib or torch-sparse. TGraphX's loader runs on plain PyTorch and yields tensors that a PyG layer accepts. Pass mask=, or every node, test nodes included, becomes a seed.

python
loader = tgx.NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask, batch_size=16, seed=0)
batch_model = HybridGNN(g.x.size(1), 64, num_classes)
optimizer = torch.optim.Adam(batch_model.parameters(), lr=0.01)

seeds = 0
for batch in loader:
    logits = batch_model(batch.node_features, batch.edge_index)
    loss = F.cross_entropy(batch.seed_logits(logits), batch.seed_y)   # seed nodes only
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    seeds += batch.batch_size
print(seeds, "training seeds in one epoch")
text
70 training seeds in one epoch

The sampled subgraph can contain validation and test nodes as neighbors. Their features take part in message passing (the usual transductive setting), but their labels stay out of the loss.

Tensor-valued nodes: PyG data, TGraphX layers

If a PyG Data object already holds image-like node features, TGraphX layers take them directly:

python
patch_data = Data(x=torch.randn(16, 3, 8, 8),                    # one 3x8x8 patch per node
                  edge_index=tgx.build_grid_graph(4, 4, self_loops=False))
patch_graph = from_pyg_data(patch_data)
print(patch_graph.feature_shape)

layer = tgx.TensorGraphSAGELayer(3, 16)
out = layer(patch_graph.x, patch_graph.edge_index)               # also accepts patch_data.x
print(tuple(out.shape))

head = nn.Linear(16, 4)
node_logits = head(out.mean(dim=(2, 3)))                         # pool H and W, keep nodes
print(tuple(node_logits.shape))
text
(3, 8, 8)
(16, 16, 8, 8)
(16, 4)

TensorGraphSAGELayer uses 1×1 convolutions, so it mixes channels and neighbors but not pixel positions, and the mean over height and width then discards the layout. Where spatial arrangement matters, use ConvMessagePassing or encode each patch with a CNN first.

Heterogeneous data

tgraphx.interop also converts PyG's HeteroData in both directions:

python
from torch_geometric.data import HeteroData
from tgraphx.interop import from_pyg_heterodata, to_pyg_heterodata

hetero = HeteroData()
hetero["author"].x = torch.randn(4, 8)
hetero["paper"].x = torch.randn(6, 16)
hetero["paper"].y = torch.randint(0, 3, (6,))
hetero["paper"].train_mask = torch.tensor([True, True, True, False, False, False])
hetero["author", "writes", "paper"].edge_index = torch.tensor([[0, 1, 2, 3], [0, 1, 4, 5]])

hg = from_pyg_heterodata(hetero)                                 # a TGraphX HeteroGraph
print(hg.node_types, hg.edge_types)
back = to_pyg_heterodata(hg)
print("y" in back["paper"], "train_mask" in back["paper"])
text
['author', 'paper'] [('author', 'writes', 'paper')]
True False

Per-type features and labels and per-relation edge indices, weights and edge features come across; split masks do not. Every node type needs x, and TGraphX's HeteroGraph is labelled Experimental, so for serious heterogeneous modelling staying in PyG is the safer choice. See heterogeneous graph learning.

The module also has to_dgl_graph and from_dgl_graph for DGL. DGL was not installed for this page, so they are untested here.

When to mix, and when not to

Situation Suggestion
Standard node classification on citation or OGB benchmarks Pure PyG
You need a PyG layer next to TGraphX's tensor layers Hybrid
PyG data with image or volume node features Convert (and reattach masks) to use TGraphX layers, or write a PyG MessagePassing layer
Heterogeneous graphs PyG
Knowledge graph completion tgraphx.kg, torch_geometric.nn.kge or PyKEEN
Graph reinforcement learning TGraphX (Experimental) or an RL library

Limits of the combination

  • The converters move data only. Optimized code paths in one library, such as its compiled kernels, apply to its own layers.
  • Conversion does not clone tensors. An in-place edit to converted.x also changes pyg_data.x; clone first if that matters.
  • Both libraries run on the PyTorch you installed. TGraphX declares torch>=1.13; torch-geometric 2.8.1 does not declare torch as a dependency, so check both against your PyTorch and CUDA versions when you upgrade.

FAQ

Q: Can I use TGraphX's seeding context with a pure PyG model?
A: Yes. reproducible() sets global random state and backend flags, independent of the model. PyG's seed_everything seeds the generators but does not set deterministic flags.

Q: Can I install both side by side?
A: Yes, in one environment.

Q: Is there an example in the TGraphX repository?
A: examples/pyg_dataset_adapter_demo.py converts a small Data object. Repository examples are not part of the installed package.

Related guides