TGraphX › Insights › Reproducibility by Construction: The reproducible() Context and Run Metadata
← Back to Insights

Reproducibility by Construction: The reproducible() Context and Run Metadata

Topic: Reproducibility and research integrity

Seeds and environment details are easiest to capture when a run starts. tgx.reproducible() is the TGraphX context manager for that first step. It seeds the global random generators, switches on PyTorch's determinism settings and hands you a snapshot of the environment. It does not write files, restore settings, or seed samplers that own their generators. This tutorial shows the call, then builds a run folder around it and replays the run.

Examples tested with TGraphX 1.5.1 on CPU. What each determinism flag does is covered in seeds and deterministic flags.

What happens on entry and exit

The signature is tgx.reproducible(seed=42, deterministic=True, warn_only=True).

On entry it calls tgraphx.reproducibility.set_seed, which seeds Python's random, NumPy's global generator and PyTorch on CPU and CUDA. With deterministic=True it also sets cudnn.deterministic = True and cudnn.benchmark = False, and calls torch.use_deterministic_algorithms(True, warn_only=warn_only). It then yields a dictionary.

On exit it does nothing. The source comment says that not restoring the previous flags is intentional.

python
import torch
import tgraphx as tgx

with tgx.reproducible(seed=42) as state:
    print(sorted(state))
    print(state["seed"], state["cudnn_deterministic"], state["cudnn_benchmark"],
          torch.are_deterministic_algorithms_enabled())

Output:

text
['cuda_available', 'cudnn_benchmark', 'cudnn_deterministic', 'deterministic', 'device_count', 'platform', 'python_version', 'seed', 'torch_version', 'warn_only']
42 True False True

So the dictionary holds the three arguments (seed, deterministic, warn_only), the PyTorch and Python versions, the platform string, CUDA availability and device count, and the two cuDNN flags. It does not hold:

  • the NumPy or TGraphX version,
  • the CUDA or cuDNN version, or the GPU name,
  • whether deterministic algorithms are on (reproducibility_report() has that),
  • installed packages or a git commit.

tgx.reproducibility_state() returns the environment fields at any later point.

tgx.seeded(seed) is reproducible(seed, deterministic=False). It seeds the generators and leaves the backend flags as they are, so it does not switch off determinism that was already on.

It writes nothing, so write the run folder yourself

A run you can replay needs the inputs and settings on disk. These calls each write one file:

File Written by Holds
run_metadata.json tgx.write_run_metadata(path, **fields) seed, epoch count, model and optimiser settings, versions, device
reproducibility_report.json json.dump of reproducibility_report() versions and backend flags
graph.tgx graph.save(path) the input graph, including labels and masks
model.pt tgx.save_checkpoint(...) model and optimizer state
metrics_summary.json tgx.write_metrics_summary(path, **fields) results

First define the data, the settings and the training function. The model arguments and learning rate sit in one dictionary that train reads, so the same dictionary can be written to disk. The graph builder uses its own seeded generator, and training uses only the training mask.

python
import json
import os
import numpy as np
import torch.nn.functional as F
from tgraphx import Graph
from tgraphx.estimators import node_train_val_test_split
from tgraphx.reproducibility import reproducibility_report

def make_graph(seed):
    gen = torch.Generator().manual_seed(seed)
    x = torch.randn(60, 3, 8, 8, generator=gen)          # [N, C, H, W]
    edge_index = torch.randint(0, 60, (2, 240), generator=gen)
    y = torch.arange(60) % 3
    train_mask, val_mask, test_mask = node_train_val_test_split(60, 0.6, 0.2, 0.2, seed=seed)
    return Graph(node_features=x, edge_index=edge_index, y=y,
                 train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)

CONFIG = {
    "model": {"task": "node_classification", "layer": "sage", "in_shape": [3, 8, 8],
              "hidden_shape": [8, 8, 8], "num_layers": 2, "num_classes": 3},
    "lr": 1e-2,
}

def train(graph, epochs, config):
    model = tgx.build_model(**config["model"])
    opt = torch.optim.Adam(model.parameters(), lr=config["lr"])
    for _ in range(epochs):
        model.train()
        logits = model(graph.x, graph.edge_index)
        loss = F.cross_entropy(logits[graph.train_mask], graph.y[graph.train_mask])
        opt.zero_grad()
        loss.backward()
        opt.step()
    model.eval()
    with torch.no_grad():
        pred = model(graph.x, graph.edge_index).argmax(dim=1)
    val_acc = (pred[graph.val_mask] == graph.y[graph.val_mask]).float().mean().item()
    return model, opt, loss.item(), val_acc

Then run it inside the context and save each record. The data here is random, so the accuracy means nothing; the point is the files.

python
SEED, EPOCHS = 42, 3
run_dir = "runs/seed42"
os.makedirs(run_dir, exist_ok=True)

with tgx.reproducible(seed=SEED) as state:
    graph = make_graph(SEED)
    graph.save(f"{run_dir}/graph.tgx")
    tgx.write_run_metadata(
        f"{run_dir}/run_metadata.json",
        run_name="seed42", task="node_classification", seed=SEED, total_epochs=EPOCHS,
        config=CONFIG, device="cpu", tgraphx_version=tgx.__version__, numpy_version=np.__version__,
        cuda_version=torch.version.cuda, num_threads=torch.get_num_threads(),
        environment=state,
    )
    with open(f"{run_dir}/reproducibility_report.json", "w") as f:
        json.dump(reproducibility_report(), f, indent=2)
    model, opt, loss, val_acc = train(graph, EPOCHS, CONFIG)
    tgx.save_checkpoint(model, opt, EPOCHS, f"{run_dir}/model.pt")
    tgx.write_metrics_summary(f"{run_dir}/metrics_summary.json",
                              final_train_loss=loss, val_accuracy=val_acc)

print(sorted(os.listdir(run_dir)))

Output:

text
['graph.tgx', 'metrics_summary.json', 'model.pt', 'reproducibility_report.json', 'run_metadata.json']

Pass plain numbers to the writers (.item() on tensors). A tensor is stored as a string such as "tensor(0.5000)" without any error.

Keep the names run_metadata.json and reproducibility_report.json if you want the TGraphX dashboard to read the folder; its source renders the second one as a key/value table in the Graph Mining section. Per-epoch curves come from metrics.csv, which this example does not write (see dashboard offline reports).

Replay the run

Read the seed, epoch count and configuration from run_metadata.json, load the saved graph and train again. No value is carried over from the first run except the folder path.

python
run_dir = "runs/seed42"
with open(f"{run_dir}/run_metadata.json") as f:
    meta = json.load(f)

with tgx.reproducible(seed=meta["seed"]):
    saved = Graph.load(f"{run_dir}/graph.tgx")        # unpickles: trusted files only
    _, _, loss_again, val_again = train(saved, meta["total_epochs"], meta["config"])

with open(f"{run_dir}/metrics_summary.json") as f:
    first = json.load(f)
print(loss_again == first["final_train_loss"], val_again == first["val_accuracy"])

Output:

text
True True

On the same machine and CPU setup the numbers match exactly, because the global PyTorch stream is in the same state when the model is built: neither run draws from it between seeding and build_model. If you add an augmentation or another random step before the model is created, the replay must perform it too.

The folder records settings, not code. The train function, including its choice of Adam and cross-entropy, lives in your script, so also record the git commit or a script version in run_metadata.json.

What the context does not cover

Splits, samplers and one-call helpers have their own seeds

In 1.5.1, negative_sampling, split functions such as node_train_val_test_split and edge_train_val_test_split, neighbor_sample, the GraphSAINT samplers and several others ignore torch.manual_seed: without seed= they behave as if a fixed seed had been given. Pass seed= to them.

The one-call helpers do the opposite. classify_nodes, kg_completion, workflow, generate_graph, optimize_graph and train_graph_rl each have a seed= argument that defaults to 42, and each resets the global PyTorch generator to it, overriding the surrounding context. classify_nodes, kg_completion and workflow also reset NumPy's global generator and Python's random. For example:

python
with tgx.reproducible(seed=123):
    result = tgx.classify_nodes(
        graph.x, graph.edge_index, graph.y,
        train_mask=graph.train_mask, val_mask=graph.val_mask, test_mask=graph.test_mask,
        epochs=1, device="cpu",
    )
print(result.config["seed"], torch.initial_seed())    # 42 42, not 123

Pass seed=123 to classify_nodes as well, and do the same for every other helper you call. Random draws made after a helper call follow the helper's seed.

It is one-way

After the block, the seeds and flags stay in force. If you need the backend flags restored, use deterministic_mode from tgraphx.reproducibility. It does not restore the random state, and a strict warn_only=False setting comes back as warn_only=True.

python
from tgraphx.reproducibility import deterministic_mode

torch.use_deterministic_algorithms(False)
with deterministic_mode(seed=SEED):
    print(torch.are_deterministic_algorithms_enabled())   # True
print(torch.are_deterministic_algorithms_enabled())       # False

GPU determinism is best effort

Some CUDA operations have no deterministic implementation. With warn_only=True they run and warn, and that part of the computation may vary; with warn_only=False they raise. Some matrix operations also need CUBLAS_WORKSPACE_CONFIG=:4096:8 set before CUDA is initialised, and no TGraphX call sets it. See the PyTorch randomness notes. The outputs above come from a CPU run; GPU behaviour was not tested.

Other machines can give other numbers

A matching seed does not promise matching results across hardware, CUDA versions, PyTorch builds or thread counts. The saved records help you see what differed. For a claim that should hold across environments, report the mean and spread over several seeds.

Checklist

  1. Enter tgx.reproducible(seed=SEED) before building data or models.
  2. Pass the run seed, or one derived from it, to every split, sampler, loader and one-call helper. Vary it per epoch for samplers. GraphSAINT draw k uses seed + k, so space its seeds num_steps apart (base_seed + epoch * num_steps); adding 1 only shifts the sequence by one draw (see seeds and deterministic flags).
  3. Save the input graph with graph.save(...).
  4. Write run_metadata.json with the seed, epoch count, model configuration, learning rate, versions, device, thread count and code version.
  5. Dump reproducibility_report() to reproducibility_report.json.
  6. Replay once from the folder's contents and compare the numbers before you rely on it.

Related guides