TGraphX › Insights › TGraphX Quickstart: From Install to First Working Experiment
← Back to Insights

TGraphX Quickstart: From Install to First Working Experiment

Topic: Getting started with TGraphX

This tutorial goes from installation to a small experiment that trains on one set of nodes and reports accuracy on nodes it never trained on. It is for researchers and engineers who are new to TGraphX and want something running before reading deeper material.

By the end you will have:

  1. TGraphX installed and checked
  2. A synthetic graph with tensor-valued node features
  3. A message-passing layer applied, with shapes confirmed
  4. A seeded training loop with train, validation and test masks
  5. A saved graph and a short list of what to read next

Examples tested with TGraphX 1.5.1 on CPU. Run the Python blocks in order, because later steps reuse variables from earlier ones.


Prerequisites

  • Python 3.10 or later
  • PyTorch 1.13 or later (torchvision 0.14+ and PyYAML 5.4+ are also required dependencies)
  • No PyG, DGL or other GNN library

Step 1: Install TGraphX

bash
pip install tgraphx

TGraphX is a Beta package, so pin the version you tested (for example tgraphx==1.5.1) in your requirements file.

If you want CPU-only PyTorch wheels (common on laptops and CI runners), install PyTorch first from the CPU index:

bash
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
pip install tgraphx

Then look at your environment:

bash
python -m tgraphx doctor

doctor prints the TGraphX, Python and PyTorch versions, whether CUDA is available, and which optional dependencies are installed. It does not run a forward pass or test your data, so treat Steps 2 to 4 as the real installation check. The example and tutorial paths it prints are not part of the PyPI wheel; those files live in the GitHub repository.

No local environment? You can run TGraphX on Colab instead.


Step 2: Verify the Installation in Python

python
import tgraphx as tgx

print(tgx.__version__)
print(tgx.api_status("Graph"))     # stable
print(tgx.api_status("workflow"))  # beta

api_status reports the stability label of one public name. It covers a curated list and raises KeyError for names that are not in it.


Step 3: Create Your First Graph

A TGraphX Graph holds node features of shape [N, ...] and an edge list of shape [2, E]. Row 0 of edge_index is the source node, row 1 the destination, and messages flow from source to destination.

The simplest case has vector features [N, D]:

python
import torch
from tgraphx import Graph

torch.manual_seed(0)

# 50 nodes, each with a 32-dimensional feature vector
x = torch.randn(50, 32)
edge_index = torch.randint(0, 50, (2, 150), dtype=torch.long)  # [2, E]
labels = torch.randint(0, 4, (50,))                            # 4 classes

g = Graph(node_features=x, edge_index=edge_index, node_labels=labels)

print(g.num_nodes)            # 50
print(g.node_features.shape)  # torch.Size([50, 32])
print(g.edge_index.shape)     # torch.Size([2, 150])

For image-like features [N, C, H, W], the same constructor applies:

python
N, C, H, W = 50, 16, 8, 8
g_spatial = Graph(
    node_features=torch.randn(N, C, H, W),
    edge_index=edge_index,
    node_labels=labels,
)
print(g_spatial.node_features.shape)  # torch.Size([50, 16, 8, 8])

The constructor checks shapes, index range, dtypes and devices, and raises TypeError or ValueError if something does not match.


Step 4: Apply a Message-Passing Layer

Layers take tensors, not the Graph object. For vector features, use LinearMessagePassing (or GCNConv):

python
from tgraphx import LinearMessagePassing

layer = LinearMessagePassing(in_shape=(32,), out_shape=(64,))
out = layer(g.node_features, g.edge_index)
print(out.shape)       # torch.Size([50, 64])
out.sum().backward()   # gradients flow

For spatial [C, H, W] features, use ConvMessagePassing. Pass dropout_prob explicitly: its default changed to 0.0 in TGraphX 1.5.0, and leaving it out raises a warning that says so.

python
from tgraphx import ConvMessagePassing

layer_conv = ConvMessagePassing(
    in_shape=(C, H, W), out_shape=(32, H, W), dropout_prob=0.0
)
out_spatial = layer_conv(g_spatial.node_features, g_spatial.edge_index)
print(out_spatial.shape)  # torch.Size([50, 32, 8, 8]), spatial size preserved
out_spatial.sum().backward()

A node with no incoming edges receives no message. In LinearMessagePassing and ConvMessagePassing, its own features then do not reach the output. If that matters for your data, call add_self_loops() before training on the graph whose edge_index you pass to the layer: g.add_self_loops() if the vector example uses LinearMessagePassing, g_spatial.add_self_loops() for the spatial one. The call changes only that graph, in place. Do not do this for GCNConv: it adds self-loops itself, and adding them to the graph as well changes its output.


Step 5: Seed Before You Build Anything

Set the seed before creating data, models and loaders:

python
import torch
from tgraphx.reproducibility import set_seed

set_seed(42)
a = torch.randn(3)
set_seed(42)
b = torch.randn(3)
print(torch.equal(a, b))  # True

set_seed(42, deterministic=True) additionally asks PyTorch for deterministic algorithms. tgx.reproducible(seed=42) is also available as a with block, but it does not restore the previous settings when the block ends, so read it as a "seed and configure" call rather than a scoped one. The same seed does not guarantee identical results on different hardware or library versions, or even between runs on one machine: multi-threaded CPU runs can differ, and the easy-mode training in Step 7 does when deterministic algorithms are off. When repeatable numbers matter, pass deterministic=True (to set_seed, or to train_node_classifier as Step 7 does). Even then, changing the number of threads can change the numbers.


Step 6: Train with NeighborLoader and Evaluate on Held-Out Nodes

This step is a complete small experiment. The data is synthetic: each class has a random prototype tensor, and each node is its class prototype plus noise. That gives the model something real to learn. The edges are random, so this tests the pipeline and says nothing about whether graph structure helps.

Two details matter for correctness:

  • NeighborLoader(..., mask=g.train_mask) makes only training nodes the "seeds". The sampled subgraph also contains their neighbors, including validation and test nodes, and batch.y holds all of their labels, so compute the loss from batch.seed_logits(logits) and batch.seed_y only. Without mask, every node is a seed.
  • Validation picks the epoch to keep, and test nodes are used once at the end.
python
import copy

import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import Graph, NeighborLoader, TensorGraphSAGELayer, check_leakage
from tgraphx.estimators import node_train_val_test_split
from tgraphx.reproducibility import set_seed

set_seed(42)

N, C, H, W, K = 200, 8, 6, 6, 4
labels = torch.randint(0, K, (N,))
prototypes = torch.randn(K, C, H, W)
x = prototypes[labels] + 2.0 * torch.randn(N, C, H, W)
edge_index = torch.randint(0, N, (2, 800), dtype=torch.long)

train_mask, val_mask, test_mask = node_train_val_test_split(
    N, 0.6, 0.2, 0.2, seed=42
)
check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)

g = Graph(
    node_features=x,
    edge_index=edge_index,
    node_labels=labels,
    train_mask=train_mask,
    val_mask=val_mask,
    test_mask=test_mask,
)

class TwoLayerGNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = TensorGraphSAGELayer(C, 16)
        self.conv2 = TensorGraphSAGELayer(16, 16)
        self.classifier = nn.Linear(16 * H * W, K)

    def forward(self, x, edge_index):
        h = F.relu(self.conv1(x, edge_index))
        h = F.relu(self.conv2(h, edge_index))
        return self.classifier(h.flatten(1))

def accuracy_on(model, graph, mask):
    model.eval()
    with torch.no_grad():
        pred = model(graph.node_features, graph.edge_index).argmax(dim=1)
    return (pred[mask] == graph.node_labels[mask]).float().mean().item()

model = TwoLayerGNN()
optimizer = torch.optim.Adam(model.parameters(), lr=5e-3)
loader = NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask, batch_size=32, seed=42)

best_val, best_state = -1.0, None
for epoch in range(8):
    model.train()
    total_loss, total_seeds = 0.0, 0
    for batch in loader:
        optimizer.zero_grad()
        logits = model(batch.node_features, batch.edge_index)
        loss = F.cross_entropy(batch.seed_logits(logits), batch.seed_y)
        loss.backward()
        optimizer.step()
        total_loss += loss.item() * batch.batch_size
        total_seeds += batch.batch_size

    val_acc = accuracy_on(model, g, g.val_mask)
    if val_acc > best_val:
        best_val, best_state = val_acc, copy.deepcopy(model.state_dict())
    print(f"epoch {epoch + 1}: train loss {total_loss / total_seeds:.4f}  val acc {val_acc:.3f}")

model.load_state_dict(best_state)
print(f"test accuracy: {accuracy_on(model, g, g.test_mask):.3f}  (chance is {1 / K:.2f})")

The test accuracy should be well above chance. If it is not, check the environment before changing the model.

TensorGraphSAGELayer keeps a separate weight for the node's own features and uses 1x1 convolutions, so the final linear layer is what combines different pixel positions. ConvMessagePassing from Step 4 also mixes neighbouring pixels with 3x3 convolutions and contains batch normalisation.


Step 7: A Shorter Route with Easy Mode

tgx.easy.train_node_classifier writes the training loop for you. Two things are easy to misread:

  • result.metrics holds loss and accuracy measured on the training seeds during the last epoch. There is no validation or test metric.
  • The graph's train_mask is not used automatically. Pass mask=.
python
import torch
import tgraphx as tgx

result = tgx.easy.train_node_classifier(
    g,                      # the graph from Step 6
    model="tensor_gcn",     # spatial features; use "vector_gcn" for [N, D]
    sampler="neighbor",
    mask=g.train_mask,
    batch_size=32,
    epochs=15,
    lr=1e-2,
    seed=42,
    deterministic=True,     # repeatable on one machine with the same thread count
    device="cpu",
    verbose=False,
)
print(result.metrics)       # training loss and accuracy only

# Held-out evaluation is your job
result.model.eval()
with torch.no_grad():
    pred = result.model(g.node_features, g.edge_index).argmax(dim=1)
val_acc = (pred[g.val_mask] == g.node_labels[g.val_mask]).float().mean().item()
print(f"validation accuracy: {val_acc:.3f}")

On this data the training accuracy comes out above the validation accuracy, usually by a wide margin, which is why the number in result.metrics must not be reported as a result. The built-in tensor_gcn is also a different model from Step 6: two ConvMessagePassing layers, global average pooling over the spatial dimensions, then a linear head.

result.model is the trained module, result.history the per-epoch training metrics, and result.summary() prints the resolved configuration.

Keep sampler="neighbor" when you pass a mask. In 1.5.1, sampler="full" computes the loss on every labelled node and ignores mask, which puts validation and test labels into training.


Step 8: Save and Load Your Graph

python
from tgraphx import Graph

g.save("my_first_graph.tgx")
g_loaded = Graph.load("my_first_graph.tgx")

print(g_loaded.node_features.shape)   # torch.Size([200, 8, 6, 6])
print(int(g_loaded.train_mask.sum()))  # masks are kept

.tgx is TGraphX's own format and keeps features of any rank, labels and masks. It is a pickle-based PyTorch file, so load only files you trust.

For other tools: g.to_networkx() exports the topology only (node features, labels and masks are not carried over), and tgraphx.io.write_graphml omits node features by default and cannot store features of rank above 2.


What to Read Next

This quickstart covered the minimal path to a working experiment. Common questions and mistakes are collected in the troubleshooting FAQ. For deeper material:

Topic Article
Why tensor-valued nodes matter Tensor-valued nodes in GNNs
Tensor-valued nodes step by step Getting started with tensor-valued nodes
A hand-written mini-batch loop Mini-batch training loop for image-like node features
Reproducibility in detail GNN research reproducibility
Shape validation Shape-aware validation
Choosing a library TGraphX vs PyTorch Geometric
Knowledge graphs Knowledge graph embedding tutorial
Graph generation Graph generation tutorial

Limitations

CPU only here. To use a GPU, move the graph and the model: g.to("cuda") and model.to("cuda"). Graph.to changes the graph in place (use g.clone() first if you need a CPU copy). No GPU run was part of testing this page.

Synthetic data is not representative. The random edges carry no information about the labels. Real experiments need real data; see tgx.load_dataset() for dataset adapters.

One seed is not a result. For anything you plan to report, run several seeds, report the spread, compare against a baseline that ignores the graph, and see the GNN research reproducibility guide.

Easy mode is for exploration. tgx.easy.train_node_classifier fixes the optimiser (Adam) and the training loop. The string model names such as "tensor_gcn" build predefined architectures (hidden_channels= sets their width), but you can also pass your own nn.Module with forward(x, edge_index) as model=, for example model=TwoLayerGNN() from Step 6. For another optimiser, a scheduler or validation-based selection, write the loop yourself as in Step 6.