TGraphX › Insights › TGraphX FAQ for PyTorch Users
← Back to Insights

TGraphX FAQ for PyTorch Users

Topic: Getting started with TGraphX

If you already know PyTorch and want to understand TGraphX quickly, this FAQ covers what carries over unchanged and where behaviour differs from what you might assume. For error messages and troubleshooting, see the troubleshooting FAQ.

Examples tested with TGraphX 1.5.1 on CPU. Run the Python blocks in order.


How do I install TGraphX?

bash
pip install tgraphx

TGraphX 1.5.1 requires Python 3.10 or later, torch>=1.13, torchvision>=0.14 and pyyaml>=5.4. If you need GPU support, install the CUDA build of PyTorch you want first. Because TGraphX is Beta, pin the version in requirements.txt:

tgraphx==1.5.1

python -m tgraphx doctor prints the installed versions, CUDA availability and optional dependencies.


What is the Graph object, and why does it exist?

Graph is a validated container for node features, an edge list and optional edge data, labels and masks. It is not a tensor subclass.

python
import torch
from tgraphx import Graph

torch.manual_seed(0)
N, E, d, de, C = 32, 100, 16, 4, 3

g = Graph(
    node_features=torch.randn(N, d),          # [N, ...], alias x
    edge_index=torch.randint(0, N, (2, E)),   # [2, E], dtype long
    edge_features=torch.randn(E, de),         # [E, ...], alias edge_attr
    node_labels=torch.randint(0, C, (N,)),    # [N, ...], alias y
)

print(g.num_nodes, g.num_edges)   # 32 100
print(g.node_features.device)     # cpu

It exists because graph code has a recognisable family of mistakes (wrong edge-index orientation, count mismatches, tensors on different devices) that a validated container reports when the graph is built rather than somewhere inside a forward pass.

For a side-by-side view, see what the Graph object adds over raw tensors.


What does validation check at construction?

The constructor checks, among other things, that:

  • node features have at least two dimensions, [N, ...];
  • edge_index is [2, E] with dtype torch.long, not [E, 2];
  • every index lies in [0, N);
  • edge features, edge weights and edge labels have E rows;
  • node labels and masks have N entries;
  • the tensors are on the same device.
python
try:
    Graph(node_features=torch.randn(4, 8), edge_index=torch.tensor([[0, 4], [1, 2]]))
    raise AssertionError("expected the constructor to reject node 4")
except ValueError as err:
    print(err)   # edge_index contains out-of-range indices for 4 nodes ...

It does not look for NaNs, duplicate edges, self-loops, isolated nodes or overlapping masks.


Are TGraphX layers ordinary nn.Modules?

Yes, with one exception noted below. They have parameters and a state_dict, work with any torch.optim optimizer and with autograd, and move with .to(device). The difference from an MLP is the call signature: layers take tensors, usually layer(x, edge_index), not a Graph object.

python
from tgraphx import GCNConv, count_parameters

layer = GCNConv(d, C)
out = layer(g.node_features, g.edge_index)
out.sum().backward()

print(out.shape, count_parameters(layer))   # torch.Size([32, 3]) 51
print(list(layer.state_dict()))             # ['lin.weight', 'lin.bias']

The exception is HANConv (experimental, imported from tgraphx.layers.han), which creates the weights for each metapath on the first forward pass that sees that name. Run one forward pass with every metapath name before you build the optimizer or call load_state_dict. Otherwise those weights are never updated, and a trained state_dict fails to load with Unexpected key(s).


What does "tensor-valued" mean, and which layers accept which shapes?

Node features can have any shape after the node dimension: a vector [D], an image patch [3, 16, 16], a volume [C, D, H, W].

python
g_patches = Graph(
    node_features=torch.randn(32, 3, 16, 16),   # [N, C, H, W]
    edge_index=torch.randint(0, 32, (2, 100)),
)
print(g_patches.feature_shape)                  # (3, 16, 16)

Storing a shape is not the same as having a layer for it:

Layer [N, D] [N, C, H, W] [N, C, D, H, W]
GCNConv, GATv2Conv, APPNP, LinearMessagePassing yes no no
ConvMessagePassing no yes yes
TensorGraphSAGELayer, TensorGATLayer, TensorGINLayer no yes with spatial_rank=3

No shipped message-passing layer models a time axis inside a node feature. GCNConv, GATv2Conv and the tensor layers reject [N, T, D], but LinearMessagePassing and the legacy AttentionMessagePassing built with in_shape=(D,) run on it silently, which is not sequence support: check x.dim() == 2 or encode the sequence first. All of the layers in the table import from the top-level package:

python
from tgraphx import (
    APPNP, ConvMessagePassing, GATv2Conv, GCNConv, LinearMessagePassing,
    TensorGATLayer, TensorGINLayer, TensorGraphSAGELayer,
)

sage = TensorGraphSAGELayer(3, 8)     # channel counts, not full shapes
print(sage(g_patches.node_features, g_patches.edge_index).shape)  # [32, 8, 16, 16]

How do I move a graph to GPU?

python
from tgraphx.performance import recommended_device

device = recommended_device()        # a torch.device: cuda, mps or cpu
g_device = g.clone().to(device)      # clone first if you want to keep the original
model = GCNConv(d, C).to(device)
print(model(g_device.x, g_device.edge_index).device)
print(g_device.device.type)          # "cuda" if the graph is on a GPU

One difference from tensors matters here: Graph.to() modifies the graph in place and returns the same object. tensor.to() returns a new tensor and leaves the old one alone. add_self_loops(), remove_self_loops(), make_undirected() and coalesce() are in place too.


How do I batch multiple graphs?

Pass a list to GraphBatch. It concatenates node features, shifts each graph's edge indices, and records which graph every node came from in batch.

python
from tgraphx import GraphBatch, GraphDataLoader, GraphDataset, global_mean_pool

def small_graph(label):
    return Graph(
        node_features=torch.randn(5, 8),
        edge_index=torch.tensor([[0, 1, 2], [1, 2, 3]]),
        graph_label=torch.tensor(label),
    )

graphs = [small_graph(i % 2) for i in range(6)]
batch = GraphBatch(graphs[:3])
print(batch.node_features.shape)    # torch.Size([15, 8])
print(batch.batch.shape, batch.graph_labels)
print(global_mean_pool(batch.node_features, batch.batch).shape)   # [3, 8]

loader = GraphDataLoader(GraphDataset(graphs), batch_size=2, shuffle=True, num_workers=0)
for b in loader:
    print(b.num_graphs, b.node_features.shape)

GraphDataLoader is a subclass of torch.utils.data.DataLoader, so options such as num_workers and generator are passed through. pin_memory=True is accepted but does nothing for graph batches in 1.5.1: GraphBatch has no pin_memory() method, so PyTorch hands the batch back unpinned. Masks are not concatenated into batch attributes, and graph_features is not carried into the batch.


Can I write my own training loop?

Yes, and for node classification with masks you should. tgraphx.fit exists for loaders that yield GraphBatch or (x, y) pairs, but it does not look at node masks: given labelled nodes, it computes the loss on all of them. A transductive loop is ordinary PyTorch:

python
import torch.nn.functional as F

train_mask = torch.zeros(N, dtype=torch.bool)
train_mask[:20] = True

net = GCNConv(d, C)
optimizer = torch.optim.Adam(net.parameters(), lr=1e-2)
for step in range(5):
    optimizer.zero_grad()
    logits = net(g.node_features, g.edge_index)
    loss = F.cross_entropy(logits[train_mask], g.node_labels[train_mask])
    loss.backward()
    optimizer.step()
print(f"training loss: {loss.item():.3f}")

For large graphs, NeighborLoader yields sampled subgraphs, and the loop needs both of these changes:

  1. pass mask=train_mask, so that only training nodes are chosen as seeds;
  2. compute the loss from batch.seed_logits(logits) and batch.seed_y.

The mask only chooses the seeds. A sampled subgraph also holds their neighbors, which can include validation and test nodes, and batch.y has the labels of every sampled node. Adapting the loop above as F.cross_entropy(net(batch.x, batch.edge_index), batch.y) would therefore train on held-out labels.

python
from tgraphx import NeighborLoader

loader = NeighborLoader(g, fanouts=[10], mask=train_mask, batch_size=8, seed=0)
for batch in loader:
    optimizer.zero_grad()
    logits = net(batch.x, batch.edge_index)        # one row per sampled node
    loss = F.cross_entropy(batch.seed_logits(logits), batch.seed_y)   # seeds only
    loss.backward()
    optimizer.step()

    outside = int((~train_mask[batch.input_nodes]).sum())   # input_nodes: global IDs
    assert batch.y.shape[0] == batch.num_nodes             # y covers every sampled node
    print(f"{batch.batch_size} seeds; {outside} of {batch.num_nodes} sampled nodes are not training nodes")

How do I set a random seed?

python
from tgraphx.reproducibility import set_seed

set_seed(42, deterministic=True)
# Seeds Python's random, NumPy and PyTorch.
# deterministic=True also enables PyTorch's deterministic algorithms (warn-only)
# and cuDNN determinism, which can reduce throughput.

There is also a top-level tgx.set_seed(seed, deterministic=True), which is a different function: it does not call torch.use_deterministic_algorithms.

NeighborLoader, LinkNeighborLoader, GraphLoader and ClusterLoader take their own seed=. For GraphSAINT, pass the seed to the sampler, not to GraphSAINTLoader. GraphDataLoader is an ordinary DataLoader subclass with no seed= argument, so give it a generator for a reproducible shuffle:

python
def shuffled_features(seed):
    loader = GraphDataLoader(
        GraphDataset(graphs), batch_size=2, shuffle=True,
        generator=torch.Generator().manual_seed(seed),
    )
    return torch.cat([b.node_features for b in loader])

assert torch.equal(shuffled_features(0), shuffled_features(0))   # same batch order

Neighbor sampling has a trap of its own in 1.5.1. neighbor_sample, which NeighborLoader and LinkNeighborLoader call for every batch, creates a new torch.Generator each time and seeds it only from seed=. So set_seed and torch.manual_seed do not seed the draw. A batch with the same target (seed) nodes in the same order gets the same neighbors on every pass, with or without seed=; they change only with another seed= value or a different set or order of target nodes. In multi-seed runs, vary the loader's seed= along with the model seed.


Does mixed precision work?

Not with every layer. You can write torch.autocast and GradScaler into your own loop as usual, but in 1.5.1 some components raise a dtype RuntimeError under autocast, among them GATv2Conv on bfloat16 or float16 input (for example the output of nn.Linear or GCNConv), the relational and temporal layers, and GraphClassifier. A second problem raises no error: neighbor counts are accumulated in the data dtype, so mean aggregation and degree normalisation can be wrong for nodes with more than 256 (bfloat16) or 2048 (float16) incoming edges.

The workaround is to run the affected call with autocast disabled and to cast its floating-point inputs with .float(). fit(..., amp=True) enables autocast on CUDA only and uses no GradScaler. The source-grounded performance review has the full list, demonstrates the problems on CPU and shows the workarounds.


How do I check my environment?

python
from tgraphx.performance import env_report

info = env_report(include_hardware=True)
for key in ("python", "torch", "tgraphx", "cuda_available", "recommended_device"):
    print(key, info[key])

Save this dictionary with your results.


How do I estimate memory usage for a large graph?

python
from tgraphx.performance import estimate_message_memory

estimate = estimate_message_memory(
    num_edges=500_000,
    out_shape=(64,),
    dtype=torch.float32,
)
print(estimate["total_mb"])   # 122.07

This is the size of one per-edge message buffer. It does not include model weights, optimizer state, gradients or activations.


Does TGraphX support distributed or multi-GPU training?

Not as a framework. The source of tgraphx.distributed explicitly states TGraphX does not ship a distributed training framework. See why distributed GNN training is hard for what you would need to build yourself.

What the module does provide are helpers: rank and world-size queries, rank-zero printing, barrier, rank_seed, shard_indices, maybe_wrap_ddp and a run-summary writer. For multiple GPUs, use DistributedDataParallel and initialise the process group yourself. Do not wrap a graph model in nn.DataParallel: it splits tensor arguments along the first dimension, which breaks an edge_index of shape [2, E].


How is TGraphX related to PyG (PyTorch Geometric)?

They are separate projects. TGraphX does not depend on PyG and is not a fork of it. PyG is a much larger and longer-established library with many more layers and datasets. TGraphX is a Beta library focused on tensor-valued node features, with layers that keep feature maps intact during message passing, shape validation and experiment helpers.

You can convert between them with tgraphx.interop (PyG must be installed). from_pyg_data copies x, edge_index, edge_weight, edge_attr and y, but not train, validation or test masks, so reattach them:

python
# Optional: requires torch_geometric
from torch_geometric.data import Data
from tgraphx.interop import from_pyg_data, to_pyg_data

data = Data(
    x=torch.randn(10, 8),
    edge_index=torch.randint(0, 10, (2, 30)),
    y=torch.randint(0, 3, (10,)),
    train_mask=torch.arange(10) < 6,
)

converted = from_pyg_data(data)
print(converted.train_mask)          # None: the mask was not copied

converted = Graph(
    node_features=data.x,
    edge_index=data.edge_index,
    node_labels=data.y,
    train_mask=data.train_mask,
)
print(to_pyg_data(converted).x.shape)   # torch.Size([10, 8])

See TGraphX vs PyTorch Geometric for choosing between them.


How do I add edges to an existing graph?

A Graph is mutable: assign the new tensors, keep every per-edge tensor the same length, and call validate().

python
new_edges = torch.tensor([[0, 1], [1, 0]])        # two edges: 0->1 and 1->0
g_more = g.clone()
g_more.edge_index = torch.cat([g_more.edge_index, new_edges], dim=1)
g_more.edge_features = torch.cat([g_more.edge_features, torch.zeros(2, de)], dim=0)
g_more.validate()                                 # raises if something is inconsistent
print(g.num_edges, g_more.num_edges)              # 100 102

Building a new Graph from only node_features and edge_index would silently leave behind labels, edge features, weights and masks.


How mature is TGraphX?

The package is published with the classifier "Development Status :: 4 - Beta" under the MIT license. Individual names carry their own label, which you can query:

python
import tgraphx as tgx

for name in ("Graph", "NeighborLoader", "HeteroGraph"):
    print(name, tgx.api_status(name))   # stable, beta, experimental

api_status covers a curated list and raises KeyError for names outside it. Pin your version, and read the release notes before upgrading.


What experiment infrastructure is built in?

python
from tgraphx import CSVLogger, TensorBoardLogger, MLflowLogger
from tgraphx import write_graph_stats, write_experiment_config, write_hardware_report
from tgraphx.estimators import EarlyStopping
from tgraphx.experiments import load_config, Runner, GridRunner

stopper = EarlyStopping(patience=3, mode="min")   # the default mode is "max"
print([stopper.step(v) for v in [1.0, 0.8, 0.9, 0.9, 0.9]])   # stops on the last value

CSVLogger needs no extra packages; TensorBoardLogger and MLflowLogger need TensorBoard and MLflow. The write_* functions record only the fields you pass. Runner and GridRunner are config-driven: you do not pass them your own model object or data loaders, and in 1.5.1 Runner computes no validation loss, so it is a smoke-test runner rather than a replacement for your evaluation code. For node tasks it also ignores a mask set with Graph(train_mask=...) (it looks for a different metadata key), so the loss is then computed on every labelled node, validation and test included.


Where can I find examples, and how do I report a bug?

The source is at github.com/arashsajjadi/TGraphX. Example scripts live in the repository; the PyPI wheel contains only the library. Report bugs through GitHub Issues with your Python, PyTorch and TGraphX versions and a small script that reproduces the problem.

Short answers and the other question-and-answer pages are collected under all TGraphX FAQs.