TGraphX › Insights › Reproducibility Checklists for Tensor-Valued GNN Experiments
← Back to Insights

Reproducibility Checklists for Tensor-Valued GNN Experiments

Topic: Reproducibility and research integrity

Reproducibility has two levels: exact reproduction (the same numbers on the same machine) and close reproduction (the same conclusions with comparable numbers). Exact reproduction across machines is often out of reach. Close reproduction is a realistic goal if the experiment records its choices.

Tensor-valued GNNs, where each node holds a [C, H, W] patch or a [C, D, H, W] volume, have more of those choices than vector-feature models. This checklist concentrates on them and shows code that writes each record to disk. For the general items (neighbour sampling, determinism flags, multi-seed reporting) see the code-per-item reproducibility checklist. For why runs drift and what the TGraphX seeding helpers control, see research reproducibility in GNN projects.

The Python blocks run in order as one script and write into experiment_v1/. Examples tested with TGraphX 1.5.1 on CPU. The GPU notes follow PyTorch's documentation and the TGraphX source and were not run on a GPU.

Why tensor-valued GNNs need extra records

  • Layout. [N, C, H, W] is channels-first. TGraphX layers do not detect channels-last input: you get a channel-count error from PyTorch, or, if the sizes happen to match, a model that runs on the wrong axes.
  • Graph construction. Patch size, stride and padding define the nodes. The edge rule (grid, k-NN, fully connected) defines who exchanges messages.
  • Preprocessing. Mean and standard deviation can be computed over different axes and different sample sets.
  • Layer internals. Aggregation, dropout and batch normalisation inside a tensor layer change what is trained.

The checklist

1. Environment

  • [ ] Python, PyTorch and TGraphX versions
  • [ ] CUDA and cuDNN versions (not part of env_report)
  • [ ] GPU name, and CPU model (env_report only reports the CPU count)
  • [ ] Pinned package list
python
import json
import os
import platform
from pathlib import Path

import torch
import tgraphx as tgx
from tgraphx.performance import env_report

# PyTorch needs this for deterministic cuBLAS; set it before the first CUDA call.
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")

def linux_cpu_model():
    """The first 'model name' line of /proc/cpuinfo, or None if there is none."""
    cpuinfo = Path("/proc/cpuinfo")
    if cpuinfo.is_file():
        for line in cpuinfo.read_text().splitlines():
            if line.startswith("model name"):
                return line.split(":", 1)[1].strip()
    return None

run = Path("experiment_v1")
info = env_report(include_hardware=True)
info["cuda_version"] = torch.version.cuda              # None on CPU-only builds
info["cudnn_version"] = torch.backends.cudnn.version()
info["cpu_model"] = linux_cpu_model() or "unknown"
info["cpu_processor"] = platform.processor() or "unknown"   # content depends on the OS
info["cpu_arch"] = platform.machine()                       # architecture, not a model
info["cublas_workspace_config"] = os.environ["CUBLAS_WORKSPACE_CONFIG"]

tgx.write_hardware_report(run / "env" / "hardware.json", **info)
assert json.loads((run / "env" / "hardware.json").read_text())["tgraphx"] == tgx.__version__

write_hardware_report(path, **fields) writes exactly the fields you pass. Calling it with only a path produces an empty {} file. The CPU model is read from /proc/cpuinfo on Linux, because platform.processor() is often empty there and platform.machine() only names the architecture. If cpu_model is unknown, fill it in from your system's hardware information (lscpu on Linux). Save the package list next to it:

bash
python -m pip freeze > experiment_v1/env/requirements.txt

2. Randomness and determinism

  • [ ] Seed, and which function set it
  • [ ] Deterministic-algorithm setting, and whether it only warns
  • [ ] Generator seed for the data loader; seed= for samplers and splits
  • [ ] The seeds used across repeated runs
python
from tgraphx.reproducibility import set_seed, reproducibility_report

SEED = 42
seed_state = set_seed(SEED, deterministic=True)       # warn_only=True by default
loader_generator = torch.Generator().manual_seed(SEED)

assert torch.are_deterministic_algorithms_enabled()

Use tgraphx.reproducibility.set_seed. The function with the same name at the top level, tgx.set_seed(seed, deterministic=True), sets the cuDNN flags but does not call torch.use_deterministic_algorithms. With warn_only=True, an operation without a deterministic implementation warns and runs anyway, so keep the warnings in your log.

Pass the generator to the data loader: it fixes the shuffle order and the base seed from which PyTorch seeds each worker. PyTorch's reproducibility notes also show a worker_init_fn for re-seeding NumPy and random; tgraphx.reproducibility.seed_worker provides one. Seeded and deterministic GNN experiments covers which TGraphX samplers ignore the global seed.

3. Tensor schema and graph construction

  • [ ] Node feature shape, axis order, dtype and value range
  • [ ] Edge feature shape ([E, ...]), if the graph has edge features
  • [ ] Label shape and class distribution
  • [ ] Patch size, stride, padding and patch order
  • [ ] Edge rule with its parameters (k, metric), self-loops, direction
  • [ ] The edge list itself, when it cannot be rebuilt exactly

The running example treats each image as a graph of patch nodes on a grid.

python
generator = torch.Generator().manual_seed(0)
images = torch.rand(30, 3, 32, 32, generator=generator)    # stand-in for real data
labels = torch.arange(30) % 2
images[labels == 1, 0] += 0.5                              # a signal to learn

patches = tgx.image_to_patches(images, patch_size=8)       # [30, 16, 3, 8, 8], row-major
edge_index = tgx.build_grid_graph(4, 4, directed=False, self_loops=True)

schema = {
    "num_graphs": patches.size(0),
    "nodes_per_graph": patches.size(1),
    "node_feature_shape": list(patches.shape[2:]),
    "layout": "[N, C, H, W], channels first",
    "dtype": str(patches.dtype),
    "value_range": [images.min().item(), images.max().item()],
    "value_range_of": "raw images, before standardisation",
    "edge_features": "none",
    "labels": {"shape": list(labels.shape),
               "class_counts": torch.bincount(labels).tolist()},
    "patching": {"patch_size": 8, "stride": 8, "padding": "none", "order": "row-major"},
    "edges": {"rule": "4x4 grid, horizontal and vertical neighbours",
              "symmetrised": True, "self_loops": True,
              "edges_per_graph": edge_index.size(1)},
}
tgx.write_graph_stats(schema, run / "data" / "graph_stats.json")   # object first, then path

If you pass a Graph object to write_graph_stats instead of a dict, only num_nodes and num_edges are written. Shapes, dtype and construction parameters have to come from you.

For k-NN graphs built from learned embeddings, save edge_index: tied or nearly tied distances can resolve differently on another machine.

4. Data split

  • [ ] The unit of splitting (image, patient, scene, subgraph)
  • [ ] Method, sizes, seed and whether it is stratified
  • [ ] The indices themselves

Patches from one image share content, so split by image, not by patch.

python
order = torch.randperm(30, generator=torch.Generator().manual_seed(SEED))
split = {"train": order[:18], "val": order[18:24], "test": order[24:]}

masks = {name: torch.zeros(30, dtype=torch.bool) for name in split}
for name, index in split.items():
    masks[name][index] = True

# Keyword arguments matter; this raises if any two masks overlap.
tgx.check_leakage(train_mask=masks["train"], val_mask=masks["val"],
                  test_mask=masks["test"])

tgx.write_run_metadata(run / "data" / "split_info.json",
                       unit="image", method="seeded random permutation", seed=SEED,
                       **{name: sorted(index.tolist()) for name, index in split.items()})

check_leakage compares masks only. It cannot tell that two different indices are the same photograph or the same patient. See masks, splits and leakage.

5. Preprocessing

  • [ ] Which axes and which samples the statistics were computed over
  • [ ] The statistic values
  • [ ] Augmentations on the trailing dimensions, with parameters
  • [ ] Graph augmentations (edge dropout, feature masking), with rates and when they are active
  • [ ] Order relative to splitting and patching
python
train_images = images[split["train"]]
mean = train_images.mean(dim=(0, 2, 3), keepdim=True)    # one value per channel
std = train_images.std(dim=(0, 2, 3), keepdim=True)
patches = tgx.image_to_patches((images - mean) / std, patch_size=8)

tgx.write_transform_metadata(run / "data" / "transform_metadata.json",
                             ["per-channel standardisation", "patching"],
                             fit_on="training images only", axes=[0, 2, 3],
                             augmentations="none",
                             mean=mean.flatten().tolist(),
                             std=std.flatten().tolist())

Pass lists or Python numbers to the writers. The metadata writers turn a tensor into its printed string, "tensor(...)", with long tensors abbreviated. write_graph_stats instead raises TypeError on a tensor value and leaves a partial JSON file behind.

6. Model and layer configuration

  • [ ] Layer types, channel sizes, number of layers, activation
  • [ ] Aggregation, residual connections, normalisation
  • [ ] Dropout, set explicitly
  • [ ] Readout order (nodes first or spatial axes first), parameter count
python
import torch.nn as nn

config = {"layer": "TensorGraphSAGELayer", "in_channels": 3, "hidden_channels": 8,
          "num_layers": 2, "aggr": "mean", "activation": "ReLU", "dropout": 0.1,
          "readout": "global_mean_pool over nodes, then mean over H and W",
          "num_classes": 2}

class PatchGraphNet(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        c, h = cfg["in_channels"], cfg["hidden_channels"]
        self.layers = nn.ModuleList([
            tgx.TensorGraphSAGELayer(c, h, aggr=cfg["aggr"]),
            tgx.TensorGraphSAGELayer(h, h, aggr=cfg["aggr"]),
        ])
        self.dropout = nn.Dropout2d(cfg["dropout"])
        self.head = nn.Linear(h, cfg["num_classes"])

    def forward(self, x, edge_index, batch):
        for layer in self.layers:
            x = self.dropout(torch.relu(layer(x, edge_index)))
        pooled = tgx.global_mean_pool(x, batch)            # [B, C, H, W]
        return self.head(pooled.mean(dim=(2, 3)))

model = PatchGraphNet(config)
tgx.write_experiment_config(run / "config" / "model_config.json",     # path first
                            {**config, "parameters": tgx.count_parameters(model),
                             "repr": repr(model)})

Two details are specific to TGraphX's convolutional layers. ConvMessagePassing changed its default dropout from 0.3 to 0.0 in 1.5.0, so write the value down and pass it explicitly. Its aggregator also uses batch normalisation by default, which makes training depend on how nodes are batched; record batch size and sampling with it.

7. Training configuration

  • [ ] Optimiser and its hyperparameters, learning-rate schedule
  • [ ] Epochs, batch size, how batches were formed
  • [ ] Early-stopping quantity, mode and patience
  • [ ] Per-epoch curves
python
from tgraphx.estimators import EarlyStopping

train_cfg = {"optimizer": "Adam", "lr": 0.03, "weight_decay": 0.0, "epochs": 40,
             "batch_size": 6, "early_stopping": {"monitor": "val_loss",
                                                 "mode": "min", "patience": 5}}
tgx.write_experiment_config(run / "config" / "training_config.json", train_cfg)

def graphs_for(index):
    return [tgx.Graph(node_features=patches[i], edge_index=edge_index,
                      graph_label=labels[i]) for i in index.tolist()]

train_loader = tgx.GraphDataLoader(tgx.GraphDataset(graphs_for(split["train"])),
                                   batch_size=train_cfg["batch_size"], shuffle=True,
                                   generator=loader_generator)
val_batch = tgx.GraphBatch(graphs_for(split["val"]))
test_batch = tgx.GraphBatch(graphs_for(split["test"]))

torch.manual_seed(SEED)
model = PatchGraphNet(config)
optimizer = torch.optim.Adam(model.parameters(), lr=train_cfg["lr"],
                             weight_decay=train_cfg["weight_decay"])
stopper = EarlyStopping(patience=train_cfg["early_stopping"]["patience"],
                        mode="min")                        # the default mode is "max"
loss_fn = nn.CrossEntropyLoss()

(run / "results").mkdir(parents=True, exist_ok=True)
with tgx.CSVLogger(str(run / "results")) as logger:
    for epoch in range(train_cfg["epochs"]):
        model.train()
        total = 0.0
        for batch in train_loader:
            optimizer.zero_grad()
            out = model(batch.node_features, batch.edge_index, batch.batch)
            loss = loss_fn(out, batch.graph_labels)
            loss.backward()
            optimizer.step()
            total += loss.item() * batch.num_graphs
        model.eval()
        with torch.no_grad():
            val_out = model(val_batch.node_features, val_batch.edge_index, val_batch.batch)
            val_loss = loss_fn(val_out, val_batch.graph_labels).item()
        logger.log(epoch=epoch, train_loss=total / len(split["train"]), val_loss=val_loss)
        stop = stopper.step(val_loss)
        if stopper.counter == 0:                           # this epoch is the best so far
            tgx.save_checkpoint(model, optimizer, epoch,
                                str(run / "results" / "best.pt"), val_loss=val_loss)
        if stop:
            break

CSVLogger appends to an existing metrics.csv, so use a new directory per run. Its columns are fixed by the first row.

8. Evaluation

  • [ ] Metric definitions and the implementation used (for OGB datasets, the official evaluator, which tgraphx.benchmarks.OGBNodeEvaluator and its link and graph counterparts wrap)
  • [ ] Which split is reported, and which checkpoint
  • [ ] Number of seeds, and mean with standard deviation
python
best_epoch = tgx.load_checkpoint(model, None, str(run / "results" / "best.pt"),
                                 map_location="cpu")
model.eval()
with torch.no_grad():
    pred = model(test_batch.node_features, test_batch.edge_index, test_batch.batch).argmax(1)
test_accuracy = (pred == test_batch.graph_labels).float().mean().item()   # test used once

tgx.write_metrics_summary(run / "results" / "metrics_summary.json",
                          test_accuracy=test_accuracy, best_epoch=best_epoch,
                          num_test_graphs=len(split["test"]))
tgx.write_run_metadata(run / "results" / "run_metadata.json",
                       tgraphx_version=tgx.__version__, seed=SEED, device="cpu",
                       seed_state=seed_state, reproducibility=reproducibility_report())

The accuracy here comes from six synthetic images and one seed. It shows how the record is produced, not how good the model is.

9. Known limitations of the run

  • [ ] Mixed precision: the edge softmax used by TensorGATLayer and GATv2Conv computes float16/bfloat16 scores in float32 and casts back. This depends on the dtype, not on the device, so record the autocast dtype.
  • [ ] Operations that warned under deterministic mode
  • [ ] GPU runs: reductions can add values in a different order from run to run
  • [ ] Topology choices that may not hold on other data

A checklist block for static documentation

For HTML documentation, a details block keeps the list collapsible. The boxes can be ticked, but without JavaScript the state is not saved.

html
<details open>
<summary><strong>Tensor-valued GNN run checklist</strong></summary>
<ul>
  <li><input type="checkbox"> Versions, CUDA, hardware recorded</li>
  <li><input type="checkbox"> Seed, deterministic settings, loader generator recorded</li>
  <li><input type="checkbox"> Feature shape, layout, dtype recorded</li>
  <li><input type="checkbox"> Edge feature shape, label shape and class distribution recorded</li>
  <li><input type="checkbox"> Patching and edge rule recorded, edge list saved if needed</li>
  <li><input type="checkbox"> Split unit and indices saved</li>
  <li><input type="checkbox"> Normalisation axes, sample set and values saved</li>
  <li><input type="checkbox"> Augmentations, including edge dropout and feature masking, saved</li>
  <li><input type="checkbox"> Layer configuration, including dropout, saved</li>
  <li><input type="checkbox"> Training configuration and curves saved</li>
  <li><input type="checkbox"> Test metric, checkpoint choice and seed count stated</li>
</ul>
</details>

The resulting artifact directory

The script above produces this layout; requirements.txt comes from the pip freeze command.

text
experiment_v1/
├── config/
│   ├── model_config.json
│   └── training_config.json
├── data/
│   ├── graph_stats.json
│   ├── split_info.json
│   └── transform_metadata.json
├── env/
│   ├── hardware.json
│   └── requirements.txt
└── results/
    ├── best.pt
    ├── metrics.csv
    ├── metrics_summary.json
    └── run_metadata.json

Add the code version (a git commit hash) and a short README saying how to run the script. With the data source as well, another person can check shapes and configuration and attempt a rerun.

What a checklist cannot guarantee

  • PyTorch does not promise identical results across releases, platforms, or between CPU and GPU, even with the same seed.
  • Deterministic mode with warn_only=True does not remove every source of variation.
  • TGraphX is classified as Beta, and defaults have changed between releases. Pin the exact version.

State these limits next to the results.

Related guides