Research Reproducibility in GNN Projects: Lessons from TGraphX
Rerun a GNN experiment with the same code, data and hyperparameters and the metrics can still move. This note lists where that variation comes from, shows what the TGraphX helpers control (and what they do not), and gives a small recipe for recording a run.
Examples tested with TGraphX 1.5.1 on CPU.
What "reproducible" needs to mean
A reproducible experiment is one where:
- The same code, data and seeds, on the same software and hardware, produce the same numbers, or differ only within a stated tolerance.
- A reader can audit how the experiment was run from the files left behind.
- Variation across runs comes from sources you chose to vary, such as seeds and splits, and not from hidden state.
GNN evaluation is sensitive to choices that are easy to leave unrecorded. Shchur et al. ("Pitfalls of Graph Neural Network Evaluation", 2018, arXiv:1811.05868) showed that changing the train/validation/test split of common node classification datasets can change how architectures rank. Errica et al. ("A Fair Comparison of Graph Neural Networks for Graph Classification", ICLR 2020, arXiv:1912.09893) reported reproducibility and model-selection problems in graph classification comparisons.
Sources of non-determinism
torch.manual_seed(42) covers PyTorch's generators. It is not the whole picture.
- Python
randomand NumPy. Data preparation, augmentation and some sampling code use them. They need their own seeds. - CUDA kernels. Some CUDA operations are non-deterministic by default, including scatter-style reductions of the kind message passing relies on.
torch.use_deterministic_algorithms(True)selects deterministic implementations where they exist, which can be slower. Some CUDA matrix operations additionally require the environment variableCUBLAS_WORKSPACE_CONFIG=:4096:8(or:16:8) to be set before the process starts. - Multi-threaded CPU kernels. It is not only a GPU issue. Some CPU operations accumulate in an order that depends on thread scheduling, including the gradient of advanced indexing such as
x[src], which is how many message passing layers gather source features (measured below). - cuDNN autotuning. With
torch.backends.cudnn.benchmark = True, cuDNN times several convolution algorithms and picks one, and the choice can differ between runs. This matters for tensor-valued GNNs that use convolutions. - Data loaders. With
shuffle=Trueand no dedicated generator, the batch order depends on how much of the global random state was consumed before. Withnum_workers > 0, batches still arrive in sampler order by default, but random operations run inside the workers. Current PyTorch releases (checked with 2.15) seedtorch,randomand NumPy's global generator in each worker from a base seed drawn from the loader's generator; random state that you or another library create separately needsworker_init_fn. - Graph sampling. Random walks, neighbor sampling and negative sampling draw random numbers. The corresponding TGraphX samplers and loaders accept a
seedargument. - Hardware and versions. PyTorch does not guarantee identical results across releases, platforms, or CPU versus GPU, even with identical seeds (PyTorch notes on randomness).
For a paper to be reproducible, all of these need to be controlled or acknowledged in the methodology. The flags themselves are explained in seeded operations and deterministic flags.
What TGraphX provides
TGraphX has several helpers for the seeding part (see reproducible() context and run metadata). They differ in ways that matter. All of them seed Python random, NumPy and PyTorch (including CUDA devices):
| Helper | cuDNN deterministic flags | use_deterministic_algorithms |
Restores flags on exit |
|---|---|---|---|
tgx.set_seed(s, deterministic=True) |
yes | no | not a context manager |
tgraphx.reproducibility.set_seed(s, deterministic=True) |
yes | yes | not a context manager |
with tgx.reproducible(seed=s): |
yes | yes | no |
with tgx.seeded(s): |
no | no | no |
with tgraphx.reproducibility.deterministic_mode(s): |
yes | yes | yes |
Three details are worth knowing. The two set_seed functions are different: the top-level tgx.set_seed never calls torch.use_deterministic_algorithms. tgx.reproducible() leaves the deterministic settings switched on after the block ends. None of the helpers restores the random generator state or sets PYTHONHASHSEED.
Check determinism instead of assuming it. Run the same training twice and compare:
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import GCNConv
from tgraphx.reproducibility import deterministic_mode
def train_once(seed):
with deterministic_mode(seed):
x = torch.randn(200, 16)
edge_index = torch.randint(0, 200, (2, 800))
y = torch.randint(0, 3, (200,))
conv1, conv2, dropout = GCNConv(16, 32), GCNConv(32, 3), nn.Dropout(0.5)
optimizer = torch.optim.Adam([*conv1.parameters(), *conv2.parameters()], lr=0.01)
for _ in range(20):
optimizer.zero_grad()
logits = conv2(dropout(F.relu(conv1(x, edge_index))), edge_index)
F.cross_entropy(logits, y).backward()
optimizer.step()
with torch.no_grad():
return conv2(F.relu(conv1(x, edge_index)), edge_index)
first, second, other_seed = train_once(0), train_once(0), train_once(1)
assert torch.equal(first, second)
assert not torch.equal(first, other_seed)
The model and data are created inside the seeded block. Anything created before it is not covered by the seed. Passing on CPU says nothing about your GPU run, so repeat the check on the hardware you report.
The CPU case is easy to demonstrate. With the same inputs and four threads, repeat one backward pass through x[src]:
threads = torch.get_num_threads()
torch.set_num_threads(4)
torch.manual_seed(0)
features = torch.randn(600, 16)
src = torch.randint(0, 600, (20_000,))
weights = torch.randn(20_000, 16)
def gradient():
leaf = features.clone().requires_grad_(True)
(leaf[src] * weights).sum().backward() # one gathered row per edge
return leaf.grad
reference = gradient()
print(sum(not torch.equal(reference, gradient()) for _ in range(10)), "of 10 repeats differ")
with deterministic_mode(0):
reference = gradient()
assert all(torch.equal(reference, gradient()) for _ in range(10))
torch.set_num_threads(threads)
On the machine used here (PyTorch 2.15), nine or ten of the ten repeats differed from the first without deterministic algorithms, and none differed with them. The differences are at floating-point rounding level, but training can amplify them. The count you see depends on your hardware and PyTorch build. The thread count also matters: changing it can change results even when each setting is repeatable on its own.
Give data loaders their own generator
A dedicated generator keeps the batch order stable when unrelated code starts drawing random numbers:
from tgraphx import Graph, GraphDataset, GraphDataLoader
from tgraphx.reproducibility import set_seed, make_generator
graphs = [Graph(node_features=torch.randn(3, 4), edge_index=torch.tensor([[0, 1], [1, 2]]),
graph_label=torch.tensor(i)) for i in range(10)]
def epoch_order(extra_draw, dedicated_generator):
set_seed(0)
if extra_draw:
torch.rand(1) # e.g. a new random augmentation added later
kwargs = {"generator": make_generator(123)} if dedicated_generator else {}
loader = GraphDataLoader(GraphDataset(graphs), batch_size=4, shuffle=True, **kwargs)
return torch.cat([batch.graph_labels for batch in loader]).tolist()
assert epoch_order(False, False) != epoch_order(True, False) # order silently changed
assert epoch_order(False, True) == epoch_order(True, True) # order unchanged
With worker processes, the same generator also fixes the workers' base seed. tgraphx.reproducibility.seed_worker can be passed as worker_init_fn to seed random and NumPy explicitly, which is useful on older PyTorch versions.
Record what you ran
Do not assume a run has been recorded. tgx.classify_nodes writes files only when you pass out_dir: run_metadata.json, metrics_summary.json and benchmark_summary.json. reproducibility_report() returns a dictionary and writes nothing. Save it yourself, together with the facts it does not contain.
Know what you are recording, too. The defaults of classify_nodes are a smoke run: fast_mode=True trains for only 3 epochs (15 with fast_mode=False; epochs= overrides both). In either mode, training and evaluation use neighbor-sampled mini-batches, not the full graph. For a result you intend to report, set epochs= yourself; the 30 below is a placeholder, not a recommendation. The function also has no early stopping and returns no model, so write your own loop when you need model selection or a checkpoint.
import hashlib
import json
import os
import platform
import tgraphx as tgx
from tgraphx.estimators import node_train_val_test_split
from tgraphx.reproducibility import reproducibility_report
def fingerprint(tensor):
return hashlib.sha256(tensor.cpu().numpy().tobytes()).hexdigest()
SEED = 42
torch.manual_seed(0)
x = torch.randn(200, 16) # random data: the accuracy is meaningless
edge_index = torch.randint(0, 200, (2, 800))
y = torch.randint(0, 3, (200,))
train_mask, val_mask, test_mask = node_train_val_test_split(200, 0.6, 0.2, 0.2, seed=0)
out_dir = "runs/exp_seed42"
with tgx.reproducible(seed=SEED, deterministic=True):
result = tgx.classify_nodes(
x, edge_index, y,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
model="tensor_gcn", seed=SEED, device="cpu", out_dir=out_dir,
fast_mode=False, epochs=30, # the default is a 3-epoch smoke run
)
environment = reproducibility_report()
hardware = tgx.env_report(include_hardware=True)
environment.update(
seed=SEED,
epochs=result.config["epochs"],
tgraphx_version=tgx.__version__,
platform=platform.platform(),
cuda_version=torch.version.cuda, # None for a CPU-only PyTorch build
cudnn_version=torch.backends.cudnn.version(), # None without cuDNN
gpu_name=hardware["cuda_device"], # first GPU; None without CUDA
cpu_count=hardware["cpu_count"],
data_sha256={"x": fingerprint(x), "edge_index": fingerprint(edge_index), "y": fingerprint(y)},
split_sha256={name: fingerprint(m) for name, m in
(("train", train_mask), ("val", val_mask), ("test", test_mask))},
)
with open(os.path.join(out_dir, "environment.json"), "w") as f:
json.dump(environment, f, indent=2)
print(sorted(os.listdir(out_dir)))
print("fast_mode:", result.config["fast_mode"], "epochs:", result.config["epochs"])
print("seed:", environment["seed"], "CUDA:", environment["cuda_version"], "GPU:", environment["gpu_name"])
audit = tgx.audit_run_dir(out_dir)
print(audit["ok"], audit["issues"])
Output on a CPU-only build of PyTorch:
['benchmark_summary.json', 'environment.json', 'metrics_summary.json', 'run_metadata.json']
fast_mode: False epochs: 30
seed: 42 CUDA: None GPU: None
True []
For vector features like these, model="tensor_gcn" trains a two-layer GCN. Pass all three masks: with partial masks the reported metrics can include training nodes or be undefined.
reproducibility_report() contains the PyTorch and Python versions, CUDA availability and device count, the cuDNN flags, whether deterministic algorithms are enabled, and PYTHONHASHSEED. It does not contain the seed, CUDA version, GPU model, package list or git commit, and no single call supplies them all:
| Fact | Where it comes from |
|---|---|
| Seed | you record it (classify_nodes writes the seed it was given to run_metadata.json) |
| CUDA and cuDNN versions | torch.version.cuda, torch.backends.cudnn.version() |
| GPU name | tgx.env_report(include_hardware=True)["cuda_device"], first GPU only |
| OS, Python, PyTorch and TGraphX versions, CPU count, RAM | tgx.env_report(include_hardware=True) (RAM figures need psutil) |
| Installed packages | pip freeze |
| Code version | git rev-parse HEAD (commit your changes first) |
The last two come from the shell. From inside your project repository, with the run's environment active:
pip freeze > runs/exp_seed42/requirements_lock.txt
git rev-parse HEAD > runs/exp_seed42/git_commit.txt
The local dashboard displays a reproducibility_report.json if one is in the log directory, but you have to write it.
audit_run_dir checks that the three expected JSON files exist and parse, and that run_metadata.json has a seed and a TGraphX version. ok=True does not mean the experiment is sound.
The config-driven Runner in tgraphx.experiments writes its own run directory (metadata, the experiment config, a metrics CSV, a summary and, if configured, checkpoints). It records neither a package lock nor data hashes, and in 1.5.1 it computes no validation loss, so treat it as a smoke runner.
What these helpers do not solve
- Bit-identical results across GPU models, CUDA versions or PyTorch releases.
- Operations with no deterministic implementation. With the default
warn_only=Trueyou get a warning and the run continues non-deterministically. - Random state held by external libraries or other processes.
- Anything outside randomness: a changed dataset download, a different preprocessing script or an undocumented hyperparameter.
A practical standard is: same code, same data, same environment gives the same numbers on the same hardware, and a stated tolerance elsewhere.
A practical reproducibility checklist
The checklist is kept in one place, with code for each item: a practical GNN reproducibility checklist with code. For image-like or volumetric node features, add the reproducibility checks for tensor-valued GNN experiments.
The short version: seed every generator you use and pass seeds to loaders and samplers, state the determinism setting, record versions, data and splits, and report several seeds with model selection on validation data only. If you write your own training loop, build these records into it.
On benchmark claims
If you cannot reproduce your own result on your own hardware, do not publish it as a benchmark number. Report the spread across runs, not the best run. This is a general standard of experimental work, not something specific to one library.
FAQ
Q: Does deterministic=True always give deterministic results?
A: No. Some operations have no deterministic implementation. In plain PyTorch, strict mode raises RuntimeError for them; the TGraphX helpers in tgraphx.reproducibility and tgx.reproducible() default to warn_only=True, which only warns. Pass warn_only=False if you want a hard failure.
Q: Why does my run differ across machines?
A: Floating-point addition is not associative, and different hardware, kernels and thread counts can sum in different orders. PyTorch makes no cross-platform guarantee.
Q: How should I report variance?
A: Report mean and standard deviation over several seeds, state how many, and say whether the split also changed.
Q: Where are run records written?
A: tgx.classify_nodes writes files only when you pass out_dir, and writer functions write to the path you give them. Runner is different: it always has a run directory and creates it as soon as you construct it. It uses the run_dir argument if given, else config.run_dir, else runs/<run_name>/<timestamp>/ (UTC time) under the current working directory, and fit() writes its records there.
Q: What if my preprocessing is non-deterministic?
A: Run it once, save the output with a hash and the seed used, and load the saved version in later runs.