From Notebook to Reproducible Experiment: Using the TGraphX Colab Gallery
Topic: Getting started with TGraphX
A demo notebook shows that a library runs. An experiment is something you can defend: your data, a split that keeps test nodes out of training, a recorded configuration, and a result you can produce again. TGraphX has a notebook gallery for the first part. This guide takes you through the second.
The code on this page was tested with TGraphX 1.5.1 on CPU, outside Colab. New to the library? Start with getting started with tensor-valued nodes.
What the gallery is
The Colab gallery page and the repository's colab_gallery.md list notebooks hosted on Google Drive. Open one and choose Open with → Google Colaboratory, or download it and run it in Jupyter. According to the gallery index, most notebooks cover one concept on synthetic or toy data and run in under two minutes on a modest CPU. The advanced real-data notebooks, 31 to 35, take under five minutes in their fast mode and need a GPU for full mode; the gallery page says their saved outputs were produced with TGraphX 1.3.8.
Some useful starting points:
| Notebook | What it shows |
|---|---|
28: Install and tgraphx doctor |
checking a fresh install |
| 01: Easy Mode node classification | training on [N, C, H, W] node features |
| 06: NeighborLoader seed-node loss | taking the loss on seed-node logits only. It has no split: with one, pass mask=g.train_mask to NeighborLoader, because the notebook does not and the default seeds every node |
| 23: Dashboard artifacts | writing files the dashboard reads |
| 25: Reproducibility and seed control | repeating a run with the same seed |
| 29: End-to-end workflow | data, training, metrics and artifacts |
The code cells of these six ran on TGraphX 1.5.1 on CPU, with the pip lines removed, when this page was revised. That was not a Colab test, and the other notebooks were not checked. The repository index also lists a notebook 30 on limitations, whose Drive link was not publicly accessible at that time.
Separately, the repository has runnable scripts in tutorials/ and examples/. They are not the same files as the notebooks, and the pip package does not include them.
Step 1: confirm the environment
The six notebooks above install the newest release with pip install tgraphx. For an experiment, pin the version:
# in Colab, prefix each line with "!"
pip install -q "tgraphx==1.5.1"
tgraphx-doctor
tgraphx-doctor (or python -m tgraphx doctor) prints versions, CUDA availability and which optional dependencies are installed. It does not test your data or your model. The Examples and Tutorials paths it prints do not exist in a pip install; those folders are in the repository.
Step 2: read what the demo measures
Before reusing a notebook, check what its numbers mean. Several of them use Easy Mode, and tgx.easy.train_node_classifier reports loss and accuracy on the nodes it trained on. With no mask, that is every node. Those are training metrics: useful as a smoke test, not as a result. For an experiment you need held-out nodes, as below.
Step 3: swap in your data
Put the whole configuration in one dictionary first, so that every later step reads the same values. Then replace the notebook's synthetic data with one function that returns three tensors. Everything after it stays the same. Here the stand-in builds 120 nodes, each a [3, 8, 8] tensor, and connects each to similar nodes with knn_graph:
import copy
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx.estimators import EarlyStopping, node_train_val_test_split
CONFIG = {"seed": 42, "split_seed": 0, "layer": "sage", "in_shape": [3, 8, 8],
"hidden_shape": [16, 8, 8], "num_layers": 2, "num_classes": 3,
"lr": 0.01, "max_epochs": 80, "patience": 10}
def load_my_data():
"""Replace with your loader. Return x [N, C, H, W] float,
edge_index [2, E] long and y [N] long."""
gen = torch.Generator().manual_seed(0)
num_nodes, num_classes = 120, 3
y = torch.randint(0, num_classes, (num_nodes,), generator=gen)
offsets = torch.randn(num_classes, 3, 1, 1, generator=gen) # per-class channel shift
x = 0.2 * offsets[y] + torch.randn(num_nodes, 3, 8, 8, generator=gen)
edge_index = tgx.knn_graph(x, k=6) # similarity uses features only, never labels
return x, edge_index, y
def build_graph(split_seed):
x, edge_index, y = load_my_data()
train, val, test = node_train_val_test_split(x.size(0), 0.6, 0.2, 0.2, seed=split_seed)
g = tgx.Graph(node_features=x, edge_index=edge_index, node_labels=y,
train_mask=train, val_mask=val, test_mask=test)
g.validate()
assert tgx.check_leakage(train_mask=train, val_mask=val, test_mask=test)["ok"]
return g
g = build_graph(CONFIG["split_seed"])
print(g.num_nodes, g.num_edges, g.feature_shape)
Two cautions. This is a transductive setup: test node features and edges are visible during training, only their labels are held out. And a random node split is wrong if your nodes come in groups, such as many patches from one image or many records from one patient. Split by group instead.
Step 4: train with validation, test once
Put the whole run in one function that takes the graph and the configuration. split_seed has already been used to build the graph; the function reads the rest. It seeds itself, so random numbers drawn in earlier cells do not change the result for the same graph:
def run_experiment(g, cfg):
with tgx.reproducible(seed=cfg["seed"]):
model = tgx.build_model("node_classification", layer=cfg["layer"],
in_shape=tuple(cfg["in_shape"]),
hidden_shape=tuple(cfg["hidden_shape"]),
num_layers=cfg["num_layers"],
num_classes=cfg["num_classes"])
optimizer = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
stopper = EarlyStopping(patience=cfg["patience"], mode="min")
history, best_state, best_epoch = [], None, -1
for epoch in range(cfg["max_epochs"]):
model.train()
optimizer.zero_grad()
loss = F.cross_entropy(model(g.x, g.edge_index)[g.train_mask], g.y[g.train_mask])
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
val_logits = model(g.x, g.edge_index)[g.val_mask]
val_loss = F.cross_entropy(val_logits, g.y[g.val_mask]).item()
history.append((epoch, loss.item(), val_loss))
stop = stopper.step(val_loss)
if stopper.counter == 0:
best_state, best_epoch = copy.deepcopy(model.state_dict()), epoch
if stop:
break
model.load_state_dict(best_state)
model.eval()
with torch.no_grad():
pred = model(g.x, g.edge_index).argmax(1)
def accuracy(mask):
return (pred[mask] == g.y[mask]).float().mean().item()
metrics = {"val_acc": accuracy(g.val_mask), "test_acc": accuracy(g.test_mask),
"best_epoch": best_epoch, "epochs_run": len(history)}
return model, metrics, history
model, metrics, history = run_experiment(g, CONFIG)
print(metrics)
mode="min" matters: EarlyStopping defaults to "max", which would be wrong for a loss. With only 24 test nodes and one seed, treat the accuracy as a pipeline check; report several seeds for a real comparison.
Step 5: record the run
A seed alone does not describe an experiment. Save the exact input, the configuration, the environment (including the number of PyTorch CPU threads), the metrics, the per-epoch curve and the weights in one folder. Make it a new folder every time: CSVLogger appends to an existing metrics.csv, so a reused folder would collect the curves of several runs while the other files are overwritten.
import os
from itertools import count
from tgraphx.reproducibility import reproducibility_report
runs_root = "runs" # in Colab, a folder on mounted Drive
run_dir = next(path for path in (f"{runs_root}/exp_{i:03d}" for i in count(1))
if not os.path.exists(path)) # first unused: exp_001, exp_002, ...
os.makedirs(run_dir)
tgx.save_tgraphx(g, f"{run_dir}/input_graph.tgx") # features, edges, labels, masks
tgx.write_experiment_config(f"{run_dir}/experiment_config.json", CONFIG)
tgx.write_run_metadata(f"{run_dir}/run_metadata.json",
run_name=os.path.basename(run_dir), status="completed",
seed=CONFIG["seed"], num_threads=torch.get_num_threads(),
tgraphx_version=tgx.__version__,
environment=reproducibility_report(),
source="gallery notebook, adapted")
tgx.write_metrics_summary(f"{run_dir}/metrics_summary.json", **metrics)
tgx.save_checkpoint(model, None, metrics["best_epoch"], f"{run_dir}/model.pt")
with tgx.CSVLogger(run_dir) as log:
for epoch, train_loss, val_loss in history:
log.log(epoch=epoch, train_loss=train_loss, val_loss=val_loss)
Nothing here happens automatically: tgx.reproducible seeds and sets determinism flags but writes no file. In Colab, point runs_root at a mounted Drive folder, or the files disappear with the runtime. The Colab quickstart shows how.
Step 6: replay it
The test of the record is running from it. Load the saved graph, restore the recorded thread count, train again with the saved configuration, and compare:
import json
with open(f"{run_dir}/experiment_config.json") as f:
saved_config = json.load(f)
with open(f"{run_dir}/run_metadata.json") as f:
torch.set_num_threads(json.load(f)["num_threads"])
saved_graph = tgx.load_tgraphx(f"{run_dir}/input_graph.tgx") # trusted files only
replay_model, replay_metrics, _ = run_experiment(saved_graph, saved_config)
assert replay_metrics == metrics
assert all(torch.equal(a, b) for a, b in
zip(model.state_dict().values(), replay_model.state_dict().values()))
print("replay matches")
With the same CPU machine, library versions and number of PyTorch threads, this matched exactly. The thread count matters: when this example was checked, changing only the number of threads left the metrics equal but moved some weights by about 1e-6, enough to fail the torch.equal assertion. Do not expect bit-identical results on another GPU, CUDA or PyTorch version. On CUDA, PyTorch's deterministic mode may also require the CUBLAS_WORKSPACE_CONFIG environment variable. tgx.reproducible leaves deterministic algorithms switched on after the block ends.
Then leave the notebook
Notebooks allow cells to run out of order, which is easy to miss. Once the result matters:
- Move the functions into a script under version control and record the commit in the run metadata.
- Pin versions and keep a
pip freezenext to the results. - Restart and run everything from the top before quoting a number.
- Keep test nodes untouched until the configuration is fixed.
Gallery runtimes and numbers are demonstrations, not benchmarks. For larger graphs, add neighbour sampling and measure on your own hardware. Notebook 06 shows how to take the loss on seed-node logits only, but it has no data split. In this experiment you must pass mask=g.train_mask to NeighborLoader: the notebook does not, and the default (mask=None) uses every node as a seed, so validation and test labels would enter the training loss.