Building a Shape-Checked GNN Experiment Skeleton with TGraphX
An experiment script should fail early. Before it spends any time training, it
should have recorded the environment, seeded the random number generators,
checked the graph, and proved that the model produces output of the right shape.
This tutorial builds that skeleton for node classification with tensor-valued
node features [N, C, H, W]. The Python blocks run in order, so put them one
after another in a file called skeleton.py.
Examples tested with TGraphX 1.5.1 on CPU.
Why a skeleton matters
Ad-hoc scripts tend to have no seed, no record of the library versions, and no check of what the model actually returns. A starting template puts those checks in place once, so every later experiment begins with them.
Step 1: imports, run directory, environment report
Each run gets its own timestamped directory. env_report returns a dictionary
describing the interpreter, PyTorch, TGraphX and the available accelerator.
import json
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
import tgraphx
from tgraphx import (
CSVLogger, Graph, TensorGraphSAGELayer, build_knn_graph, check_leakage,
env_report, recommended_device, validate_graph, write_experiment_config,
write_graph_stats, write_hardware_report, write_metrics_summary,
write_run_metadata,
)
from tgraphx.estimators import EarlyStopping, node_train_val_test_split
from tgraphx.reproducibility import set_seed
RUN_DIR = Path("runs") / "skeleton" / time.strftime("%Y%m%d-%H%M%S")
info = env_report(include_hardware=True)
for key in ("python", "torch", "tgraphx", "cuda_available", "recommended_device"):
print(f"{key}: {info[key]}")
Step 2: seed everything
SEED = 42
state = set_seed(SEED, deterministic=True)
print(state["backend_settings"])
tgraphx.reproducibility.set_seed seeds Python's random, NumPy (if installed)
and PyTorch. With deterministic=True it also asks PyTorch for deterministic
algorithms, warning rather than failing for operations that have none. Note that
the top-level tgraphx.set_seed is a different function: its deterministic=True
does not switch on PyTorch's deterministic algorithms.
Seeding improves repeatability on one machine and software stack. It does not
guarantee identical numbers across hardware or PyTorch versions. On CUDA you may
also need to set CUBLAS_WORKSPACE_CONFIG=:4096:8 before starting Python.
Step 3: select a device
device = recommended_device() # torch.device: CUDA if available, else MPS, else CPU
print("device:", device)
Step 4: build the graph and state its contract
The data here is synthetic: each class shifts the node's feature maps by a class-specific pattern, so there is something to learn. Edges connect each node to its nearest neighbours in feature space. The setting is transductive: all node features take part in message passing, and labels are used only through the split masks.
N, C, H, W, NUM_CLASSES = 120, 3, 8, 8, 4
labels = torch.randint(0, NUM_CLASSES, (N,)) # [N]
patterns = torch.randn(NUM_CLASSES, C, H, W)
x = torch.randn(N, C, H, W) + 0.5 * patterns[labels] # [N, C, H, W]
edge_index = build_knn_graph(x.flatten(1), k=5, self_loops=False) # [2, E], symmetrised
train_mask, val_mask, test_mask = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=SEED)
g = Graph(node_features=x, edge_index=edge_index, node_labels=labels,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
# The contract this experiment relies on
assert g.node_features.shape == (N, C, H, W), g.node_features.shape
assert g.edge_index.shape[0] == 2 and g.edge_index.dtype == torch.long
assert g.node_labels.shape == (N,) and g.node_labels.dtype == torch.long
assert 0 <= int(g.node_labels.min()) and int(g.node_labels.max()) < NUM_CLASSES
report = validate_graph(g, check_finite=True)
assert report["ok"], report["issues"]
check_leakage(train_mask=g.train_mask, val_mask=g.val_mask, test_mask=g.test_mask)
g.to(device) # moves the graph in place
print(f"{g.num_nodes} nodes, {g.num_edges} edges on {device}")
The Graph constructor already rejects out-of-range edge indices and label or
mask tensors of the wrong length. The extra assertions document what this
experiment expects, and check_finite=True adds a NaN/Inf check. Always pass the
masks to check_leakage by keyword: it raises if the masks overlap, but
positional arguments bind to the wrong parameters and can hide an overlap.
Step 5: define the model
TensorGraphSAGELayer takes (in_channels, out_channels) and is called as
layer(x, edge_index). It keeps the [C, H, W] layout, so a small head averages
over the spatial axes before classifying.
class SkeletonGNN(nn.Module):
def __init__(self, in_channels, hidden_channels, num_classes):
super().__init__()
self.conv1 = TensorGraphSAGELayer(in_channels, hidden_channels)
self.conv2 = TensorGraphSAGELayer(hidden_channels, hidden_channels)
self.head = nn.Linear(hidden_channels, num_classes)
def forward(self, x, edge_index):
h = F.relu(self.conv1(x, edge_index)) # [N, hidden, H, W]
h = F.relu(self.conv2(h, edge_index)) # [N, hidden, H, W]
return self.head(h.mean(dim=(-2, -1))) # [N, num_classes]
HIDDEN = 16
model = SkeletonGNN(C, HIDDEN, NUM_CLASSES).to(device)
This layer needs spatial features. For plain vector features [N, D], use
tgraphx.GCNConv(in_dim, out_dim) instead and drop the spatial mean. The SAGE
layer uses 1x1 convolutions, so it does not mix pixel positions; add your own
spatial encoder if your task needs that.
Step 6: shape smoke test
Run the model once before training. Check an intermediate shape, the output shape, and that every parameter receives a gradient. The last check catches a layer that is defined but never called.
model.eval()
with torch.no_grad():
h1 = model.conv1(g.node_features, g.edge_index)
assert h1.shape == (N, HIDDEN, H, W), h1.shape
out = model(g.node_features, g.edge_index)
assert out.shape == (N, NUM_CLASSES), out.shape
assert torch.isfinite(out).all()
model.train()
logits = model(g.node_features, g.edge_index)
F.cross_entropy(logits[g.train_mask], g.node_labels[g.train_mask]).backward()
unused = [name for name, p in model.named_parameters() if p.grad is None]
assert not unused, f"parameters without gradient: {unused}"
model.zero_grad()
# A wrong input rank is rejected with a readable message
try:
model(g.node_features.flatten(1), g.edge_index)
raise AssertionError("vector input should have been rejected")
except ValueError as err:
print("rejected:", err)
Step 7: logging and experiment config
CSVLogger(logdir, filename="metrics.csv") writes one row per log(...) call,
with keyword arguments as columns and a timestamp added. The columns are fixed by
the first row, and an existing file is appended to, which is why the run
directory is new each time. write_experiment_config takes the path first.
config = {
"seed": SEED, "device": str(device), "model": "SkeletonGNN",
"node_shape": [C, H, W], "num_nodes": N, "num_edges": g.num_edges,
"num_classes": NUM_CLASSES, "hidden_channels": HIDDEN,
"lr": 0.01, "max_epochs": 40, "patience": 8,
}
write_experiment_config(str(RUN_DIR / "experiment_config.json"), config)
logger = CSVLogger(str(RUN_DIR))
TGraphX also ships TensorBoardLogger(logdir) (needs tensorboard) and
MLflowLogger(run_name=..., experiment=..., tracking_uri=...) (needs mlflow).
See experiment tracking with MLflow
for the latter.
Step 8: train on the training mask, stop on validation
tgraphx.fit does not apply node masks, so a transductive node task needs its own
loop. Pass mode="min" to EarlyStopping when you monitor a loss (the default is
"max"), and keep the best weights yourself.
optimizer = torch.optim.Adam(model.parameters(), lr=config["lr"])
stopper = EarlyStopping(patience=config["patience"], mode="min")
best_state = None
for epoch in range(config["max_epochs"]):
model.train()
optimizer.zero_grad()
logits = model(g.node_features, g.edge_index)
loss = F.cross_entropy(logits[g.train_mask], g.node_labels[g.train_mask])
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
logits = model(g.node_features, g.edge_index)
val_loss = F.cross_entropy(logits[g.val_mask], g.node_labels[g.val_mask]).item()
logger.log(epoch=epoch, train_loss=loss.item(), val_loss=val_loss)
stop = stopper.step(val_loss)
if stopper.counter == 0: # new best epoch
best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}
if stop:
break
logger.close()
model.load_state_dict(best_state)
model.eval()
with torch.no_grad(): # the test mask is used once
pred = model(g.node_features, g.edge_index).argmax(dim=1)
test_acc = (pred[g.test_mask] == g.node_labels[g.test_mask]).float().mean().item()
print(f"epochs run: {epoch + 1}, test accuracy: {test_acc:.3f}")
Step 9: write the run record
The write_* helpers save only what you pass to them. In particular,
write_hardware_report(path) with no fields writes an empty JSON object, so pass
the environment report in.
write_run_metadata(str(RUN_DIR / "run_metadata.json"), seed=SEED, device=str(device),
tgraphx_version=tgraphx.__version__, deterministic=True)
write_hardware_report(str(RUN_DIR / "hardware_report.json"),
**env_report(include_hardware=True))
write_graph_stats(g, str(RUN_DIR / "graph_stats.json")) # object first, then path
write_metrics_summary(str(RUN_DIR / "metrics_summary.json"), test_accuracy=test_acc,
best_val_loss=stopper.best_score, epochs_run=epoch + 1)
expected = ["experiment_config.json", "run_metadata.json", "hardware_report.json",
"graph_stats.json", "metrics_summary.json"]
for name in expected:
assert json.loads((RUN_DIR / name).read_text()), f"{name} is empty"
assert (RUN_DIR / "metrics.csv").stat().st_size > 0
print(sorted(p.name for p in RUN_DIR.iterdir()))
write_graph_stats records only num_nodes and num_edges from a Graph. Pass
it a dictionary if you want degree or component statistics too.
Convert tensors with .item() (or .tolist()) before calling any writer.
write_graph_stats raises TypeError on a tensor and leaves a partial file that
is not valid JSON, while write_metrics_summary, write_run_metadata,
write_experiment_config and write_hardware_report silently store it as a
string such as "tensor(0.5000)".
The resulting layout
skeleton.py
runs/skeleton/<timestamp>/
experiment_config.json <- write_experiment_config
metrics.csv <- CSVLogger
run_metadata.json <- write_run_metadata
hardware_report.json <- write_hardware_report
graph_stats.json <- write_graph_stats
metrics_summary.json <- write_metrics_summary
Common mistakes this skeleton catches
| Mistake | Check |
|---|---|
| Unseeded run | set_seed before data and model construction |
| Model and data on different devices | one device, used for both |
| Wrong node-feature rank or label length | Graph constructor and explicit assertions |
| NaN or Inf in the inputs | validate_graph(..., check_finite=True) |
| Overlapping splits | check_leakage with keyword masks |
| Wrong output shape, or a layer never called | shape and gradient smoke test |
| Training on validation or test labels | loss restricted to train_mask |
| Empty or missing run record | explicit writers, then read the files back |
These checks do not detect every problem. Duplicate nodes across splits, leaked information in the features, or edges that encode the label need their own tests; see masks, splits and leakage and shape-aware validation.
Version pinning
TGraphX is classified as Beta. Pin the version you tested, and pin PyTorch too:
tgraphx==1.5.1
# add torch==<the version recorded in hardware_report.json>
Read the changelog before upgrading. Defaults can change in a minor release:
1.5.0, for example, changed the default dropout of ConvMessagePassing and
CNNEncoder to 0.0. Per-API labels are available from tgraphx.api_status(name);
stability labels in research software
explains how to read them.