TGraphX › Insights › A Practical GNN Reproducibility Checklist with Code
← Back to Insights

A Practical GNN Reproducibility Checklist with Code

Topic: Reproducibility and research integrity

Making a GNN result reproducible takes more than one torch.manual_seed call. On top of the usual sources of run-to-run variation, graph experiments add neighbourhood sampling, graph construction and split definition, and each of them can change the numbers you report.

This checklist goes through them one by one. Each item says what to do, shows the code, and says what goes wrong if you skip it. The Python blocks share one running example and run in order, so you can paste them into a single script. Examples tested with TGraphX 1.5.1 on CPU; the GPU-specific advice follows PyTorch's documented behaviour and was not run here.


Where GNN experiments pick up extra variation

PyTorch does not promise identical results across releases, platforms, or between CPU and GPU, even with identical seeds. Graph pipelines then add their own sources:

  1. Neighbourhood sampling. Which neighbours are sampled, and which seed nodes share a mini-batch, both affect training.
  2. Graph construction. A k-NN graph built from embeddings can change when distances are tied or nearly tied, so rebuilding it elsewhere may not give the same edges. Save the edge list you trained on.
  3. Duplicate edges. Duplicates change message sums and node degrees. Whether you keep them or merge them (and with which reduction) is part of the experiment definition.
  4. Parallel reductions on GPU. The scatter and index-add operations used for message aggregation can accumulate floating-point values in a varying order.
  5. Shared random state. Any extra random draw before training shifts the global random stream. With num_workers > 0, PyTorch derives each worker's seed from the main process (or from the generator you pass), so seed that, and handle libraries that keep their own random state in a worker_init_fn.

Checklist item 1: Seed all RNG sources

python
import torch
from tgraphx.reproducibility import set_seed

state = set_seed(42)   # Python random, NumPy, torch (CPU and all CUDA devices)
print(state["seed"], state["deterministic"])

set_seed does not set PYTHONHASHSEED, and setting that variable from inside a running interpreter would not change its string hashing anyway. If your pipeline depends on hash order (for example, assigning node ids while iterating over a set of strings), sort before assigning ids, or export PYTHONHASHSEED before starting Python.

TGraphX 1.5.1 has two functions named set_seed, and they differ:

Function With deterministic=True Returns
tgraphx.reproducibility.set_seed cuDNN flags and torch.use_deterministic_algorithms (warn_only=True by default) a state dict
tgraphx.set_seed cuDNN flags only None

There is also a context manager that seeds and configures in one step:

python
import tgraphx as tgx

with tgx.reproducible(seed=42, deterministic=True) as info:
    print(info["seed"], info["deterministic"])

# Nothing is restored on exit: the settings stay active for the rest of the process
assert torch.are_deterministic_algorithms_enabled()

If skipped: weight initialisation, dropout masks and shuffling differ from run to run. Each seeding call is covered in more detail in seeded operations and deterministic flags.


Checklist item 2: Fix the train, validation and test split

Define the split once, with its own seed, independent of the training seed. Otherwise a "five seed" result mixes variation between splits with variation between training runs. This block also builds the small synthetic graph used in the rest of the article.

python
from tgraphx import Graph, check_leakage
from tgraphx.estimators import node_train_val_test_split

DATA_SEED, SPLIT_SEED = 0, 0          # fixed once, never tied to the training seed
N, D, C = 500, 16, 4

gen = torch.Generator().manual_seed(DATA_SEED)
y = torch.randint(0, C, (N,), generator=gen)
x = torch.randn(N, D, generator=gen)
x[torch.arange(N), y] += 1.5          # a class signal in the features
pairs = torch.randint(0, N, (2, 6000), generator=gen)
keep = (y[pairs[0]] == y[pairs[1]]) | (torch.rand(6000, generator=gen) < 0.1)
edge_index = pairs[:, keep]           # toy data only: edges are built from the labels

train_mask, val_mask, test_mask = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=SPLIT_SEED)

# Use keyword arguments: the first positional parameter of check_leakage is `graph`
leakage = check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
assert leakage["ok"]

g = Graph(node_features=x, edge_index=edge_index, node_labels=y,
          train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)

node_train_val_test_split returns three boolean masks and does not stratify by class. Pass seed= explicitly: with seed=None, version 1.5.1 uses a new generator in its default state, so you get the same split whatever you pass to torch.manual_seed. check_leakage compares node masks only; it does not detect leaked edges or duplicated samples. For more on this, see masks, splits and leakage.

If skipped: different runs are scored on different test nodes, and overlapping masks put training nodes into the test score.


Checklist item 3: Seed the NeighborLoader and restrict it to training nodes

python
from tgraphx import NeighborLoader

loader = NeighborLoader(
    g,
    fanouts=[15, 10],
    mask=g.train_mask,   # required: with mask=None every node becomes a seed
    batch_size=64,
    seed=42,             # fixes batch shuffling and neighbour sampling
)

NeighborLoader does not pick up g.train_mask by itself. Without mask=, validation and test labels go into the training loss, which is a worse problem than any seed.

Check the behaviour you rely on instead of assuming it:

python
def epoch_signature(seed):
    """Seed nodes and sampled node ids of every batch in one epoch."""
    loader = NeighborLoader(g, fanouts=[2, 2], mask=g.train_mask, batch_size=64, seed=seed)
    return [(b.seed_node_ids.tolist(), b.graph.metadata["sampling"]["original_node_ids"].tolist())
            for b in loader]

torch.manual_seed(0)
first = epoch_signature(42)
torch.manual_seed(999)                      # change the unrelated global RNG state
assert epoch_signature(42) == first         # same loader seed, same batches
assert epoch_signature(43) != first         # different loader seed, different batches

seed_nodes = sorted(n for seeds, _ in first for n in seeds)
assert seed_nodes == g.train_mask.nonzero().flatten().tolist()   # training nodes only

How seeding works in TGraphX 1.5.1:

  • With seed=, the loader has its own shuffle generator and neighbour sampling is seeded with the same value.
  • Without seed=, the shuffle order follows the global torch RNG, so seeding globally does make it repeatable. Neighbour picks come from a new generator in its default state for each batch, so your global seed does not change that random stream.
  • In both cases sampling restarts from the same state for every batch. A batch with the same seed nodes in the same order gets the same neighbours in every epoch; variation between epochs comes from batch composition. If you want fresh neighbourhoods each epoch, build the loader inside the epoch loop with a seed derived from the run seed and the epoch number, and record that rule.

If skipped: without mask you leak labels. Without seed, the batch order depends on everything else that consumed the global RNG before the loop.


Checklist item 4: Record exact versions

python
import platform
import tgraphx

versions = {
    "tgraphx": tgraphx.__version__,
    "torch": torch.__version__,
    "cuda_build": torch.version.cuda,        # None for a CPU-only build
    "python": platform.python_version(),
    "os": f"{platform.system()} {platform.release()}",
}
print(versions)

Also record the git commit of your code and the installed packages; item 9 writes both into the record. Library updates can change behaviour: TGraphX 1.5.0 changed the default dropout of CNNEncoder and of the CNN aggregator used by ConvMessagePassing from 0.3 to 0.0.

If skipped: "it worked before" cannot be investigated, because nobody knows what "before" was.


Checklist item 5: Turn on deterministic algorithms

python
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)   # raises on ops that have no deterministic version

Some environment variables have to be set before the process starts:

bash
export CUBLAS_WORKSPACE_CONFIG=:4096:8   # needed for cuBLAS ops on CUDA 10.2 or later
export PYTHONHASHSEED=0                  # only matters if you depend on hash order
python train.py

In this mode PyTorch switches to deterministic implementations where it has them and raises a RuntimeError where it only has non-deterministic ones. Passing warn_only=True turns that error into a warning. Without CUBLAS_WORKSPACE_CONFIG, operations that go through cuBLAS (such as matrix multiplication) raise the same kind of error on CUDA 10.2 or later. Deterministic kernels can be slower; measure on your own model, and state in your report whether the mode was on.

tgx.reproducible(seed, deterministic=True) sets the three flags above with warn_only=True. Your run continues past a non-deterministic operation with only a warning, so read the warnings. It does not set CUBLAS_WORKSPACE_CONFIG. Also note that the docstring of tgraphx.set_seed warns that max-style scatter reductions used in some attention and pooling code may lack deterministic CUDA kernels.

If skipped: GPU runs with the same seed can drift apart.


Checklist item 6: Validate graph construction

python
from tgraphx import validate_graph

validate_graph(g, strict=True, check_finite=True)   # raises if a check fails
g.validate()                                       # re-checks tensors and labels, not masks

edge_keys = g.edge_index[0] * g.num_nodes + g.edge_index[1]
num_duplicates = g.num_edges - edge_keys.unique().numel()
print("duplicate directed edges:", num_duplicates)

The constructor, g.validate() and validate_graph overlap but are not the same:

Problem Graph(...) g.validate() validate_graph
wrong edge_index shape, node index too large yes yes yes
negative node index, non-long edge_index yes yes no
wrong edge-feature length yes yes yes
wrong edge_weight length yes yes no
wrong node-label or edge-label length yes yes no
wrong mask length yes no yes
edge_index, edge features or node labels on another device yes yes yes
edge_weight, edge labels or graph label on another device yes yes no
mask on another device no (the mask is moved) no no
NaN or Inf in node features no no only with check_finite=True
duplicate edges, self-loops, isolated nodes no no no
overlapping split masks no no no (use check_leakage)

Run g.validate() after any code that assigns to graph attributes directly. It does not look at masks, so if you changed a mask, run validate_graph too: it checks the length of g.train_mask, g.val_mask and g.test_mask.

If duplicates are unintended, g.coalesce() merges them in place, averaging edge weights and edge features by default (reduce="sum" is the alternative). In 1.5.1 it does not reorder or merge edge_labels, although it re-sorts the edges even when there is nothing to merge. So do not call it on a graph that has edge labels. If you must, set g.edge_labels = None first and rebuild the labels for the new edge order yourself.

If skipped: a construction bug surfaces as a bad score or a confusing error deep inside a layer, if it surfaces at all. See shape-aware validation in TGraphX.


Checklist item 7: Save the inputs and the selected checkpoint

Save the graph you trained on, choose the checkpoint on validation data, and evaluate the test nodes with that checkpoint only.

python
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import GCNConv, load_checkpoint, save_checkpoint

g.save("runs/exp01/graph.tgx")      # features, edges, labels and masks

class TwoLayerGCN(nn.Module):
    def __init__(self, in_dim, hidden_dim, num_classes):
        super().__init__()
        self.conv1 = GCNConv(in_dim, hidden_dim)
        self.conv2 = GCNConv(hidden_dim, num_classes)

    def forward(self, x, edge_index):
        return self.conv2(F.relu(self.conv1(x, edge_index)), edge_index)

MODEL_CLASS = TwoLayerGCN        # change the model here, so the record follows it

CONFIG = {                       # train_one_seed uses these; item 9 saves them
    "model": MODEL_CLASS.__name__,
    "hidden_dim": 32,
    "optimizer": "Adam",
    "lr": 1e-2,
    "epochs": 20,
    "fanouts": [15, 10],
    "batch_size": 64,
}

def accuracy(model, mask):
    model.eval()
    with torch.no_grad():
        pred = model(g.x, g.edge_index).argmax(dim=1)   # full graph, transductive
    return (pred[mask] == g.y[mask]).float().mean().item()

def train_one_seed(seed, ckpt_path):
    set_seed(seed)                                      # before the model is built
    model = MODEL_CLASS(D, CONFIG["hidden_dim"], C)     # CONFIG["model"] is its name
    optimizer_class = getattr(torch.optim, CONFIG["optimizer"])
    optimizer = optimizer_class(model.parameters(), lr=CONFIG["lr"])
    loader = NeighborLoader(g, fanouts=CONFIG["fanouts"], mask=g.train_mask,
                            batch_size=CONFIG["batch_size"], seed=seed)

    best_val, best_epoch = -1.0, -1
    for epoch in range(CONFIG["epochs"]):
        model.train()
        for batch in loader:
            optimizer.zero_grad()
            logits = model(batch.node_features, batch.edge_index)
            F.cross_entropy(batch.seed_logits(logits), batch.seed_y).backward()
            optimizer.step()

        val_acc = accuracy(model, g.val_mask)
        if val_acc > best_val:
            best_val, best_epoch = val_acc, epoch
            save_checkpoint(model, optimizer, epoch, ckpt_path, seed=seed, val_acc=val_acc)

    load_checkpoint(model, None, ckpt_path)             # restore the best-validation weights
    result = {"seed": seed, "best_epoch": best_epoch, "val_acc": best_val,
              "test_acc": accuracy(model, g.test_mask)}
    return result, model

This setup is transductive: test node features take part in message passing, and the training loss never sees test labels. The toy edges, however, were generated from the labels of all nodes, so the accuracy of this example says nothing about real data. .tgx files are loaded with Python's pickle machinery, so open only files you trust.

If skipped: you cannot re-evaluate the reported model or check later which data it saw.


Checklist item 8: Run several seeds and report the spread

python
import statistics

SEEDS = [42, 123, 456, 789, 1024]
results = [train_one_seed(s, f"runs/exp01/seed{s}/best.pt")[0] for s in SEEDS]

for key in ("val_acc", "test_acc"):
    values = [r[key] for r in results]
    print(f"{key}: {statistics.mean(values):.3f} +/- {statistics.stdev(values):.3f} "
          f"(sample std, n={len(values)})")

# Same seed twice on the same machine: check it, do not assume it
_, model_a = train_one_seed(42, "runs/check/a.pt")
_, model_b = train_one_seed(42, "runs/check/b.pt")
assert all(torch.equal(p, q) for p, q in zip(model_a.state_dict().values(),
                                             model_b.state_dict().values()))

The split is fixed here, so the spread reflects initialisation, batching and sampling, not the choice of split. Always say how many runs there were and whether "±" means standard deviation, standard error or a confidence interval. Five seeds is a reasonable starting point, not a rule: use more when the differences you care about are small compared with the spread.

If skipped: a single number may be a lucky or unlucky draw.


Checklist item 9: Write a reproducibility record

TGraphX does not write this file for you. reproducibility_report() returns a dictionary with the torch and Python versions, CUDA availability, device count, the determinism flags and PYTHONHASHSEED. It has no seed, git commit, package list, GPU name or the device your run used, so add those around it, together with the CONFIG dictionary the training function read.

python
import json
import subprocess
from importlib import metadata
from tgraphx.reproducibility import reproducibility_report

git = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=False)

record = {
    "versions": versions,
    "git_commit": git.stdout.strip() if git.returncode == 0 else None,
    "packages": {d.metadata["Name"]: d.version for d in metadata.distributions()},
    "device": str(g.device),   # where this script trained (it never moves g or the model)
    "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,  # present, maybe unused
    "config": CONFIG,
    "data_seed": DATA_SEED,
    "split_seed": SPLIT_SEED,
    "training_seeds": SEEDS,
    "runs": results,
    "backend_state": reproducibility_report(),
}
with open("runs/exp01/reproducibility.json", "w") as f:
    json.dump(record, f, indent=2)

git_commit is the HEAD of the repository you start the script in, or None when git rev-parse fails, for example outside a repository. A commit hash does not capture uncommitted edits, so commit before a run you intend to report.

If you use the one-call trainer in tgraphx.easy, pass the model type and the mask explicitly:

python
from tgraphx import easy

easy_result = easy.train_node_classifier(
    g,
    model="vector_gcn",     # the default "tensor_gcn" needs image-like node features
    mask=g.train_mask,      # otherwise every node is a training seed
    epochs=3,
    seed=42,
    device="cpu",
    verbose=False,
)
easy_result.save_report("runs/exp01/easy_result.json")

The saved JSON holds metrics, per-epoch history, the resolved config (including the seed) and elapsed time. Its loss and accuracy are measured on the training seeds, so they are not validation or test results, and the TGraphX version is not stored. Keep the default neighbour sampler here: in 1.5.1, sampler="full" ignores mask and trains on all nodes.

If skipped: months later the weights exist, but not the settings that produced them.


Checklist item 10: Keep code and results apart

The code above leaves this layout for results:

runs/
  exp01/
    graph.tgx               # item 7
    seed42/best.pt          # one folder per seed (items 7 and 8)
    seed123/best.pt
    seed456/best.pt
    seed789/best.pt
    seed1024/best.pt
    reproducibility.json    # item 9
    easy_result.json        # item 9
  check/                    # throwaway checkpoints from the repeat-run test

Keep source code and configuration files in version control, outside runs/, and give each new experiment a new folder. save_checkpoint overwrites an existing file without asking.

If skipped: rerunning a modified script silently replaces the results you already cited.


Limitations

Determinism has a scope. Deterministic settings aim at repeatability on the same software and hardware. PyTorch's reproducibility notes say that completely reproducible results are not guaranteed across releases, commits or platforms, or between CPU and GPU runs. Report the hardware with the numbers.

Checking on CPU says little about GPU. The repeat-run assertion in item 8 holds for this small CPU example. Run the same comparison on the device you report.

This checklist covers single-process training. Distributed training, custom CUDA kernels, or multi-process samplers introduce additional non-determinism sources not covered here. For image-like or volumetric node states, see the extra checks for tensor-valued GNNs.


Related Articles