Building an Inspectable TGraphX Run Directory: graph.tgx, Configs, and Metrics
Graph experiments produce a lot of context: which graph was used, what its structure was, what hardware ran it, which configuration was chosen and what came out. That context often ends up scattered across terminal output and local files, or is not saved at all.
TGraphX has the pieces for a self-contained run directory. .tgx is its native graph file format (Graph.save and Graph.load), and a set of write_* functions and a CSVLogger cover the records around it. No single call collects all of these for your own training loop: you decide what goes in. For what the .tgx file itself holds, see .tgx files: what they store and what they do not.
The blocks run in order as one script. Examples tested with TGraphX 1.5.1 on CPU.
What goes in the directory
| File | Written by | Contents |
|---|---|---|
graph.tgx |
Graph.save |
features, edges, labels, masks, metadata |
config.json |
write_experiment_config(path, dict) |
the settings you pass |
hardware.json |
write_hardware_report(path, **fields) |
the fields you pass |
graph_stats.json |
write_graph_stats(obj, path) |
the dict you pass |
metrics.csv |
CSVLogger |
one row per epoch |
model.pt |
save_checkpoint |
model and optimiser state |
run_metadata.json |
write_run_metadata(path, **fields) |
seed, version, device |
metrics_summary.json |
write_metrics_summary(path, **fields) |
final numbers |
benchmark_summary.json |
write_benchmark_results(path, **fields) |
what a reader should quote |
Note the argument order: write_graph_stats takes the object first; the others take the path first. There are further helpers (write_dataset_metadata, write_sampling_metadata, write_transform_metadata and more). Apart from reading a few counts off an object you hand to some of them, they record exactly what you pass. From a Graph, write_graph_stats records only num_nodes and num_edges.
Step 1: save the input graph
import json
from pathlib import Path
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx.estimators import EarlyStopping, node_train_val_test_split
from tgraphx.performance import env_report
from tgraphx.reproducibility import set_seed
SEED = 42
set_seed(SEED, deterministic=True)
run_dir = Path("artifacts/run_001")
run_dir.mkdir(parents=True, exist_ok=True)
# Synthetic stand-in: 60 nodes with [3, 8, 8] features and 3 classes
N = 60
y = torch.arange(N) % 3
x = torch.randn(N, 3, 8, 8) + 0.4 * y.view(-1, 1, 1, 1)
edge_index = tgx.knn_graph(x, k=4, metric="euclidean") # flattens only for distances
train_mask, val_mask, test_mask = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=SEED)
g = tgx.Graph(node_features=x, edge_index=edge_index, node_labels=y,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
metadata={"dataset": "synthetic-v1",
"edges": "kNN, k=4, euclidean, symmetrised"})
g.validate()
g.save(run_dir / "graph.tgx")
Because the masks travel inside the file, the split is part of the artifact.
Step 2: record configuration, environment and graph statistics
config = {"model": "2 x TensorGraphSAGELayer, mean over H and W, linear head",
"hidden_channels": 8, "lr": 0.01, "weight_decay": 0.0,
"max_epochs": 30, "patience": 8, "seed": SEED}
tgx.write_experiment_config(run_dir / "config.json", config)
tgx.write_hardware_report(run_dir / "hardware.json",
**env_report(include_hardware=True),
cuda_version=torch.version.cuda)
in_degree = torch.bincount(g.edge_index[1], minlength=g.num_nodes)
tgx.write_graph_stats({
"num_nodes": g.num_nodes,
"num_edges": g.num_edges,
"node_feature_shape": list(g.feature_shape),
"dtype": str(g.node_features.dtype),
"min_in_degree": int(in_degree.min()),
"max_in_degree": int(in_degree.max()),
"split_sizes": [int(train_mask.sum()), int(val_mask.sum()), int(test_mask.sum())],
}, run_dir / "graph_stats.json")
env_report provides Python, OS, PyTorch and TGraphX versions, the GPU name if there is one and, with include_hardware=True, the CPU count and (when psutil is installed) memory figures. It has no CUDA version field, so add it.
Step 3: train, log each epoch and keep the best checkpoint
For node classification with masks, write the loop yourself: tgx.fit does not apply node masks and would train on validation and test nodes too.
class Net(torch.nn.Module):
def __init__(self, hidden):
super().__init__()
self.conv1 = tgx.TensorGraphSAGELayer(3, hidden)
self.conv2 = tgx.TensorGraphSAGELayer(hidden, hidden)
self.head = torch.nn.Linear(hidden, 3)
def forward(self, x, edge_index):
h = F.relu(self.conv1(x, edge_index))
h = F.relu(self.conv2(h, edge_index))
return self.head(h.mean(dim=(2, 3)))
model = Net(config["hidden_channels"])
optimizer = torch.optim.Adam(model.parameters(), lr=config["lr"],
weight_decay=config["weight_decay"])
stopper = EarlyStopping(patience=config["patience"], mode="min")
with tgx.CSVLogger(str(run_dir)) as logger:
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: # best epoch so far
tgx.save_checkpoint(model, optimizer, epoch, str(run_dir / "model.pt"),
val_loss=val_loss)
if stop:
break
CSVLogger fixes its columns from the first row, so log every key from the start, and it appends to an existing metrics.csv, so use a fresh directory per run.
Step 4: write the final records
best_epoch = tgx.load_checkpoint(model, None, str(run_dir / "model.pt"),
map_location="cpu")
model.eval()
with torch.no_grad():
predictions = model(g.node_features, g.edge_index).argmax(1)
test_accuracy = (predictions[g.test_mask] == g.node_labels[g.test_mask]).float().mean().item()
tgx.write_run_metadata(run_dir / "run_metadata.json",
tgraphx_version=tgx.__version__, torch_version=torch.__version__,
seed=SEED, deterministic=True, device="cpu", status="completed")
tgx.write_metrics_summary(run_dir / "metrics_summary.json",
best_epoch=best_epoch, test_accuracy=test_accuracy)
tgx.write_benchmark_results(run_dir / "benchmark_summary.json",
benchmark="synthetic-v1 node classification (illustration)",
seeds=[SEED], test_accuracy=test_accuracy)
audit = tgx.audit_run_dir(run_dir)
assert audit["ok"], audit["issues"]
print(sorted(p.name for p in run_dir.iterdir()))
The directory now holds:
artifacts/run_001/
├── benchmark_summary.json
├── config.json
├── graph.tgx
├── graph_stats.json
├── hardware.json
├── metrics.csv
├── metrics_summary.json
├── model.pt
└── run_metadata.json
audit_run_dir checks that run_metadata.json, metrics_summary.json and benchmark_summary.json exist and parse, and that the metadata has seed and tgraphx_version. It does not judge the science.
Step 5: check that the folder explains the result
An artifact is more convincing if someone can rebuild the reported number from it. This block uses only the files on disk plus the model class:
saved_config = json.loads((run_dir / "config.json").read_text())
saved_graph = tgx.Graph.load(run_dir / "graph.tgx") # unpickles: trusted files only
reloaded = Net(saved_config["hidden_channels"])
tgx.load_checkpoint(reloaded, None, str(run_dir / "model.pt"), map_location="cpu")
reloaded.eval()
with torch.no_grad():
again = reloaded(saved_graph.node_features, saved_graph.edge_index).argmax(1)
mask = saved_graph.test_mask
recomputed = (again[mask] == saved_graph.node_labels[mask]).float().mean().item()
recorded = json.loads((run_dir / "metrics_summary.json").read_text())["test_accuracy"]
assert abs(recomputed - recorded) < 1e-6
The model class lives in your code, not in the folder, so record the commit that produced the run.
For a browsable view, run tgraphx-dashboard --logdir artifacts/run_001; see dashboard and offline reports. In 1.5.1 it shows only part of this folder: curves and the metrics log from metrics.csv, status and the run configuration view from run_metadata.json, and the node and edge counts from graph_stats.json. It does not read config.json, hardware.json, metrics_summary.json or benchmark_summary.json, and its hardware panel describes the machine running the dashboard, not the one recorded in hardware.json.
Config-driven runs: Runner and GridRunner
The tgraphx.experiments module offers a second route. Runner takes a configuration and builds the dataset and model itself; fit() takes no model, loaders or logger. GridRunner is a separate sweep driver (not a subclass of Runner).
from tgraphx.experiments import GridRunner, Runner, load_config
base = {
"seed": 0, "run_name": "patch_demo",
"dataset": {"name": "synthetic:patch_graph", "kwargs": {"num_graphs": 8, "seed": 0}},
"model": {"task": "graph_classification", "layer": "sage", "in_shape": [1, 8, 8],
"hidden_shape": [8, 8, 8], "num_layers": 1, "num_classes": 6},
"training": {"epochs": 2, "lr": 0.005},
}
history = Runner(load_config({**base, "run_dir": "artifacts/runner_001"})).fit()
print(sorted(p.name for p in Path("artifacts/runner_001").iterdir()))
runs = GridRunner(base, grid={"training.lr": [0.001, 0.005]}, seeds=[0],
out_dir="artifacts/grid").run()
assert len(runs) == 2 and Path("artifacts/grid/grid_summary.json").exists()
A Runner directory contains run_metadata.json, experiment_config.json, metrics.csv and experiment_summary.json, plus checkpoints/ if you add the model_checkpoint callback. It does not contain a .tgx graph, and audit_run_dir reports it as incomplete. In 1.5.1 treat Runner as a smoke runner: it trains on one full batch and computes no validation loss, so early stopping on the default val_loss never triggers.
Node-level tasks need extra care. Runner in 1.5.1 ignores the train_mask of a Graph and computes the loss on every node, validation and test nodes included. Graph(train_mask=...) stores the mask as metadata["masks"]["train"], while Runner looks for metadata["masks"]["train_mask"]. Use your own masked loop, as in step 3.
See YAML configuration for experiments.
Logging backends
| Logger | Needs |
|---|---|
CSVLogger(logdir) |
nothing extra |
TensorBoardLogger(logdir) |
tensorboard |
MLflowLogger(run_name=..., experiment=..., tracking_uri=...) |
pip install "tgraphx[mlflow]" |
They can be passed to tgx.fit(..., logger=...) or called directly from your own loop. MLflowLogger must be started first, in both cases: use it as a context manager or call .start() (and then .close()). They are not arguments of Runner. For MLflow, see experiment tracking with MLflow.
What the pattern does not provide
- In the hand-written pattern, nothing is saved unless your code saves it, including weights.
- Only the data you put in
graph.tgxis kept, not raw source files. Large graphs may be too big to copy into every run; store them once and record a hash. - No diff tracking between runs.
- No upload to remote storage. Copy the folder to your artifact store yourself.
Inspectable is not the same as reproducible
With these files a collaborator can see which graph, split, configuration and result belong together, and can re-evaluate the saved checkpoint on the saved graph. Retraining to the same numbers is a stronger requirement: it also depends on the code version, library versions, hardware and which operations are deterministic. Claiming that the files describe what you did is a standard you can meet and check.