Getting Started with Tensor-Valued Nodes in TGraphX
Topic: Getting started with TGraphX
This tutorial walks through the basics of representing graph data with tensor-valued node features in TGraphX. By the end, you should be able to construct a graph where each node carries a multi-dimensional tensor, validate it, train a node classifier with a held-out split, and save the graph.
Examples tested with TGraphX 1.5.1 on CPU. The Python blocks build on one another, so run them in order.
New to the library? The quickstart goes from installation to a first experiment, and What is a TGX graph? explains the data object used here.
Prerequisites
pip install tgraphx
TGraphX 1.5.1 requires Python ≥ 3.10 and PyTorch ≥ 1.13. No GPU and no optional extras are needed for this tutorial.
Part 1: Understanding Why Tensor-Valued Nodes Exist
Most GNN layers, including most of the built-in convolutions in PyTorch Geometric, expect each node to be a flat vector. If your graph has 100 nodes and each node has 32 features, the node feature matrix has shape [100, 32]. This is efficient and well supported.
The challenge arises when node features are not naturally flat:
| Node type | Per-node shape | Size if flattened | Layers in TGraphX 1.5.1 |
|---|---|---|---|
| Embedding or tabular row | [D] |
already flat | GCNConv, GATv2Conv, LinearMessagePassing |
| Image patch | [3, 8, 8] (C, H, W) |
192 | ConvMessagePassing, TensorGraphSAGELayer, TensorGATLayer, TensorGINLayer |
| Volumetric block | [1, 4, 4, 4] (C, D, H, W) |
64 | the same four layers (spatial_rank=3 for the last three) |
| Sequence | [32, 16] (T, D) |
512 | none designed for it: Graph stores it; reshape or encode it before a layer |
Flattening does not lose values, but it discards the layout, so a layer can no longer treat neighbouring pixels as neighbours. The tensor layers keep the layout. They differ in how they use it: the tensor GraphSAGE, GAT and GIN layers transform features with 1×1 convolutions, which do not combine neighbouring pixels, while ConvMessagePassing follows its 1×1 message convolution with 3×3 convolutions that do.
Part 2: Constructing a Graph
Minimal graph with flat vector features
import torch
import tgraphx as tgx
torch.manual_seed(0)
# 50 nodes, each with a 16-dimensional feature vector
x_flat = torch.randn(50, 16)
# edge_index has shape [2, E]: row 0 holds sources, row 1 destinations (here, a ring)
nodes = torch.arange(50)
ring = torch.stack([nodes, (nodes + 1) % 50])
labels = torch.randint(0, 3, (50,)) # one class per node
g_flat = tgx.Graph(x=x_flat, edge_index=ring, y=labels)
print(g_flat)
# Graph(num_nodes=50, num_edges=50, node_features_shape=(50, 16), y_shape=(50,), device=cpu)
Graph with tensor-valued nodes
# 50 nodes, each an 8×8 RGB patch
x_spatial = torch.randn(50, 3, 8, 8)
g_spatial = tgx.Graph(x=x_spatial, edge_index=ring, y=labels)
print(g_spatial.feature_shape) # (3, 8, 8)
The constructor takes the same arguments for any feature rank. x is an alias for node_features, and y (or labels) is an alias for node_labels. Messages flow from the source row of edge_index to the destination row.
Part 3: Validating Your Graph
The Graph constructor already checks its inputs: it raises ValueError for an edge_index of the wrong shape or with out-of-range indices, and for per-node or per-edge tensors of the wrong length.
try:
tgx.Graph(x=torch.randn(4, 8), edge_index=torch.tensor([[0], [9]]))
except ValueError as err:
print("rejected:", err)
else:
raise AssertionError("expected the constructor to reject node 9")
The constructor runs only once. If you later modify a graph's tensors, check it again with two calls, because neither one covers the other:
graph.validate()re-runs the constructor's checks onedge_index, edge weights, edge features and node and edge labels, and raises on the first problem. It does not check masks or NaN values.tgx.validate_graph(graph)returns a dictionary withok,issuesandinfo(strict=Trueraises instead). It checks mask lengths, and checks NaN/Inf only withcheck_finite=True.
| Problem introduced after construction | graph.validate() |
validate_graph(graph, check_finite=True) |
|---|---|---|
Edge index of num_nodes or higher |
caught | caught |
Negative edge index, or edge_index that is not long |
caught | missed |
Wrong length: node labels (y), edge labels, edge weights |
caught | missed |
| Wrong length: edge features | caught | caught |
| Wrong length: train, validation or test mask | missed | caught |
| NaN/Inf in node or edge features | missed | caught |
| NaN/Inf in edge weights | missed | missed |
A small helper runs both and covers the edge weights as well:
def check_after_edit(graph):
graph.validate() # indices and lengths
tgx.validate_graph(graph, strict=True, check_finite=True) # mask lengths, NaN/Inf
if graph.edge_weight is not None and not torch.isfinite(graph.edge_weight).all():
raise ValueError("edge_weight contains NaN/Inf")
check_after_edit(g_spatial) # passes
damaged = g_spatial.clone()
damaged.y = damaged.y[:10] # 10 labels for 50 nodes
print(tgx.validate_graph(damaged, check_finite=True)["ok"]) # True: not checked
try:
check_after_edit(damaged)
except ValueError as err:
print(err) # node_labels has 10 entries but expected 50
else:
raise AssertionError("expected the short labels to be rejected")
damaged = g_spatial.clone()
damaged.node_features[0, 0, 0, 0] = float("nan")
damaged.validate() # passes: NaN is not checked
print(tgx.validate_graph(damaged)["ok"]) # True: off by default
print(tgx.validate_graph(damaged, check_finite=True)["issues"])
# ['node_features contains NaN/Inf values.']
# Assert that the node features are tensors (rank >= 3), not flat vectors
tgx.assert_tensor_native(g_spatial, min_rank=3)
check_graph_invariants is an alias of validate_graph. Neither call looks for duplicate edges, isolated nodes or overlapping masks (Part 5 checks overlap with check_leakage).
Neither one knows which layer you will use. Layer compatibility shows up when you call the layer, so one forward pass is a cheap test:
layer = tgx.TensorGraphSAGELayer(3, 16)
print(layer(g_spatial.x, g_spatial.edge_index).shape) # torch.Size([50, 16, 8, 8])
Part 4: Building a Graph from Image Patches
A common use case for tensor-valued nodes is converting images to patch graphs:
# One RGB image of 32×32 pixels (random values stand in for real data)
image = torch.randn(3, 32, 32)
patches, grid_edges = tgx.image_to_patch_graph(image, patch_size=8)
print(patches.shape) # torch.Size([16, 3, 8, 8])
g_patch = tgx.Graph(x=patches, edge_index=grid_edges)
print(g_patch.num_nodes, g_patch.num_edges) # 16 64
The function returns a tuple, not a Graph. It connects each patch to its horizontal and vertical neighbours in both directions (48 edges here) and adds a self-loop per patch (16 more); pass self_loops=False to leave those out. The image height and width must be divisible by patch_size.
Part 5: A First Training Run
All three approaches below use the same small dataset. The target is a toy: which of the three channels has the largest mean in the node's own patch. The accuracies are only there to show where each number comes from.
import torch.nn.functional as F
from tgraphx.estimators import node_train_val_test_split
num_nodes = 120
x = torch.randn(num_nodes, 3, 8, 8) # [N, C, H, W]
y = x.mean(dim=(2, 3)).argmax(dim=1) # 3 classes
edge_index = tgx.knn_graph(x, k=5, metric="cosine") # flattens only to compare nodes
train_mask, val_mask, test_mask = node_train_val_test_split(num_nodes, 0.6, 0.2, 0.2, seed=42)
g = tgx.Graph(x=x, edge_index=edge_index, y=y,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
# Keyword arguments matter: this checks that the three node masks do not overlap
print(tgx.check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)["ok"])
The split is transductive: the model sees every node's features and edges, but learns only from training labels.
Using the one-call API
The shortest route, if you only need the scores (see what the one-call API does for you):
result = tgx.classify_nodes(
x, edge_index, y,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
seed=42, device="cpu",
)
print(result.metrics["val_accuracy"], result.metrics["test_accuracy"])
With rank-4 features and the default model, classify_nodes trains one ConvMessagePassing layer plus a linear head on neighbor-sampled mini-batches, for 3 epochs by default (15 with fast_mode=False). It returns metrics, not the trained model. Pass all three masks. Without train_mask it makes its own random 70/15/15 split and replaces any other masks you passed. With train_mask but no val_mask, val_accuracy is measured on all nodes, training nodes included. Without test_mask, test_accuracy is NaN.
Using the easy mode
The easy namespace takes a Graph and hands back the trained model:
easy_result = tgx.easy.train_node_classifier(
g, model="tensor_gcn", epochs=2,
mask=g.train_mask, # seed nodes; without it, all nodes are seeds
seed=42, device="cpu", verbose=False,
)
print(easy_result.metrics) # loss and accuracy on the TRAINING nodes
easy_result.model.eval()
with torch.no_grad():
pred = easy_result.model(g.x, g.edge_index).argmax(dim=1)
print("validation accuracy:", (pred[val_mask] == y[val_mask]).float().mean().item())
Easy mode makes no validation split and does not read graph.train_mask unless you pass it as mask=. Passing mask= works with the default sampler="neighbor" only: with sampler="full", 1.5.1 ignores it and trains on the labels of every node, validation and test included. The reported accuracy is training accuracy, so evaluate on held-out nodes yourself.
Writing the training loop
For explicit control, build the model, sample mini-batches around the training nodes, select the best epoch on validation loss, and touch the test nodes once:
from tgraphx import NeighborLoader
tgx.set_seed(42)
model = tgx.build_model(
"node_classification",
layer="conv", # ConvMessagePassing; you choose the layer
in_shape=(3, 8, 8),
hidden_shape=(16, 8, 8),
num_layers=2,
num_classes=3,
dropout=0.0, # omitting it emits a DropoutDefaultChangeWarning
)
loader = NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask, batch_size=32, seed=42)
optimizer = torch.optim.Adam(model.parameters(), lr=5e-3)
best_val, best_state = float("inf"), None
for epoch in range(8):
model.train()
for batch in loader:
logits = model(batch.node_features, batch.edge_index)
loss = F.cross_entropy(batch.seed_logits(logits), batch.seed_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
val_loss = F.cross_entropy(model(g.x, g.edge_index)[g.val_mask], g.y[g.val_mask]).item()
if val_loss < best_val:
best_val = val_loss
best_state = {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
model.eval()
with torch.no_grad():
pred = model(g.x, g.edge_index).argmax(dim=1)
print("test accuracy:", (pred[g.test_mask] == g.y[g.test_mask]).float().mean().item())
fanouts=[10, 5] samples two hops, matching the two layers. batch.seed_logits picks out the rows of the seed nodes, which are the only ones that contribute to the loss.
TGraphX also has a fit() function, but it is not suited to this task: it ignores node masks, so it would train on validation and test labels, and it does not accept NeighborLoader batches.
Part 6: Saving and Loading Graphs
The .tgx format keeps feature tensors of any rank, along with labels, masks and metadata:
g.save("my_patch_graph.tgx")
g_loaded = tgx.Graph.load("my_patch_graph.tgx")
print(g_loaded.node_features.shape) # torch.Size([120, 3, 8, 8])
print(torch.equal(g_loaded.train_mask, g.train_mask)) # True
This is useful for pre-computed patch graphs, or any workflow where re-creating the graph is expensive. Loading a .tgx file unpickles data, so only load files you trust. By contrast, the GraphML writer in tgraphx.io omits node features by default and cannot store features of rank 3 or higher.
Part 7: Reproducibility
Set seeds before any randomized operation. tgx.set_seed(42) seeds Python's random, NumPy and PyTorch. The reproducible context also requests deterministic algorithms:
def run_once():
with tgx.reproducible(seed=42, deterministic=True):
return tgx.classify_nodes(
x, edge_index, y,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
seed=42, device="cpu",
).metrics
print(run_once() == run_once()) # True: same machine, CPU
torch.use_deterministic_algorithms(False) # the context does not restore this flag
Three details matter. classify_nodes reseeds with its own seed= argument (default 42), so set the seed there. The context uses warn_only=True, so an operation without a deterministic implementation warns instead of failing. And tgx.set_seed(42, deterministic=True) only sets the cuDNN flags; it does not switch deterministic algorithms on. None of this guarantees identical results across different hardware or library versions.
Common Mistakes
1. Relying on one validation call after editing a graph
The constructor checks a graph only when it is built. After you modify tensors, validate_graph alone misses negative indices and wrong label or edge-weight lengths, and graph.validate() alone misses wrong mask lengths and NaN values, so run both (Part 3). Neither checks edge weights for NaN, or whether the features fit your layer's channel count and input rank.
2. Using tensor features with vector-only layers
GCNConv, GATv2Conv and APPNP expect [N, D] vectors. For [N, C, H, W] inputs use ConvMessagePassing, TensorGATLayer, TensorGraphSAGELayer or TensorGINLayer. build_model() does not choose for you: layer= is required ("conv", "sage", "gat" or "gin" for tensors, "linear" for vectors). Layers expect channels first; a channels-last [N, H, W, C] tensor is not detected as such.
3. kNN on many large tensors
tgx.knn_graph compares every pair of nodes. It works through the queries in chunks, but the running time still grows with N² (and with the flattened feature size). For large N, use a graph that follows from your data, such as a grid, or an approximate nearest-neighbour library.
4. Assuming tensor nodes improve accuracy automatically
Tensor-valued nodes preserve spatial structure. Whether that structure is useful depends on whether spatial correlation in your features is informative for the task. Compare against a flattened baseline on your own data.
Summary
The key steps for a tensor-node workflow are:
- Construct:
tgx.Graph(x=..., edge_index=..., y=..., train_mask=..., val_mask=..., test_mask=...) - Validate after any change:
g.validate()andtgx.validate_graph(g, strict=True, check_finite=True), plus your own finiteness check if the graph has edge weights - Build:
tgx.build_model("node_classification", layer="conv", in_shape=..., hidden_shape=..., num_layers=..., num_classes=...) - Train: your own loop over
NeighborLoader(..., mask=g.train_mask), ortgx.classify_nodes(...)when scores are enough - Save:
g.save("file.tgx")
Neither classify_nodes nor easy mode calls validate_graph for you. For the next step, see the hand-written mini-batch training loop.
FAQ
Q: When should I use tensor-valued nodes instead of flat vectors?
A: When your features have a layout you want to keep across message-passing steps, such as image patches or volumetric blocks. If they are already embeddings or a list of scalars, flat vectors are simpler and sufficient.
Q: Does classify_nodes work with flat [N, D] features too?
A: Yes. For rank-2 input it trains a two-layer GCNConv network. The model= argument is not validated for vector input, so model="gat" still trains that GCN.
Q: How do I handle edge features?
A: tgx.Graph accepts edge_features whose first dimension is the number of edges. A layer uses them only if it was built with use_edge_features=True, and each layer expects particular shapes. classify_nodes and easy mode do not use them. The tensor-valued edge features guide shows the supported modes.
Q: Is there a way to visualize the patch graph?
A: tgraphx.plotting.plot_graph(edge_index, num_nodes) draws the topology (it needs matplotlib). You can also call g.to_networkx() and use NetworkX; that conversion keeps the topology only, not the features.
Q: Can I use TGraphX graphs with standard PyTorch modules?
A: Yes. g.node_features is a regular torch.Tensor, so you can pass it to any PyTorch module that accepts its shape.