TGraphX › Insights › Designing a Graph Experiment Report That Future You Can Understand
← Back to Insights

Designing a Graph Experiment Report That Future You Can Understand

Topic: Reproducibility and research integrity

Six months after an experiment, "future you" is effectively a new person. The context that seemed obvious (why you chose k=5 for the k-NN graph, which split you used, what hardware the numbers came from) has evaporated. A well-designed experiment report makes the experiment legible without access to your working memory.

This tutorial gives one report template for graph learning experiments, then collects most of its factual fields from code on a small synthetic example: TGraphX's writer functions save the machine-readable files, and the script writes a short summary README. The Python blocks run in order. Examples tested with TGraphX 1.5.1 on CPU.

What a graph experiment report needs to contain

On top of what any machine learning report records, a graph experiment has to describe the graph itself and how it was split:

Category What to include
Graph schema Node and edge feature shapes, edge direction, edge construction
Topology summary Node and edge counts, degrees, self-loops, duplicates, components
Evaluation protocol Transductive or inductive, split source and seed, selection metric
Model Layers, dimensions, activations, regularisation, parameter count
Training Optimizer, learning rate, epochs, batching, loss, seeds
Environment Python, PyTorch, TGraphX versions, CUDA build, hardware
Results Train, validation and test metrics, number of runs, uncertainty
Caveats Known limitations, hardware dependencies, assumptions

A missing category is a question you will have to answer later from memory.

The report template

Use this as the outline of the finished README.md in each run directory. A field that does not apply gets "not applicable", not silence.

markdown
# Experiment report: <short name>

## 0. Question
- What was tested, and what result would have changed your mind:

## 1. Data and graph
- Dataset, source and version:
- Node feature shape:              [N, ...]
- Edge index:                      [2, E], directed or symmetrised
- Edge construction rule:          (given by the dataset / grid / k-NN with k=...)
- Edge features or weights:
- Node, edge and graph counts:
- Graph-level datasets: graphs per split, nodes per graph (min, mean, max):
- Degrees (average, min, max), self-loops, duplicates, isolated nodes, components:
- Labels and class counts:
- Preprocessing (and which data each step was fitted on):

## 2. Evaluation protocol
- Transductive or inductive:
- Split sizes, how the split was made, split seed:
- Metric used to select the checkpoint, and on which split:

## 3. Model
- Layers, dimensions, activation, dropout, normalisation:
- Tensor shapes through the pipeline (input, after each layer, output):
- Parameter count:

## 4. Training
- Optimizer, learning rate, weight decay, schedule:
- Maximum epochs, early stopping rule, epoch of the selected checkpoint:
- Batch size or sampler settings, loss:
- Seeds (data, split, training):

## 5. Environment
- Python, PyTorch, TGraphX versions, git commit:
- CUDA build, GPU model, CPU:
- Deterministic mode on or off:

## 6. Results
| Metric | Train | Validation | Test |
|---|---|---|---|
| Accuracy | | | |
| Loss | | | |

- Number of runs, and what any "±" means:
- Training time, and the device it was measured on:

## 7. Caveats and limitations
- Was anything tuned on the test set?
- Is the split standard or custom?
- One seed or several?
- Known preprocessing issues, hardware dependence, assumptions:

Fields typed by hand drift away from the code. The next sections record most of the factual ones from the run itself.

Collecting the facts from code

Data and graph

python
import json
import os

import torch
import torch.nn as nn
import torch.nn.functional as F

import tgraphx
from tgraphx import GCNConv, Graph, algorithms, write_dataset_metadata, write_graph_stats
from tgraphx.estimators import node_train_val_test_split

RUN_DIR = "runs/exp_001"
os.makedirs(RUN_DIR, exist_ok=False)     # refuse to overwrite an earlier run

DATA_SEED, SPLIT_SEED, TRAIN_SEED = 0, 0, 42
N, D, C = 300, 16, 3

# Synthetic stand-in for your data
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] += 0.8
pairs = torch.randint(0, N, (2, 2000), generator=gen)
same_class = y[pairs[0]] == y[pairs[1]]
keep = (pairs[0] != pairs[1]) & (same_class | (torch.rand(2000, generator=gen) < 0.1))

train_mask, val_mask, test_mask = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=SPLIT_SEED)
g = Graph(node_features=x, edge_index=pairs[:, keep], node_labels=y,
          train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
g.make_undirected()      # adds reverse edges and merges duplicates, in place

src, dst = g.edge_index
keys = src * g.num_nodes + dst
in_degree = torch.bincount(dst, minlength=g.num_nodes)
out_degree = torch.bincount(src, minlength=g.num_nodes)
graph_stats = {
    "num_nodes": g.num_nodes,
    "num_edges": g.num_edges,
    "node_feature_shape": list(g.feature_shape),
    "directed": not bool(torch.isin(dst * g.num_nodes + src, keys).all()),
    "self_loops": bool((src == dst).any()),
    "duplicate_edges": g.num_edges - keys.unique().numel(),
    # in-degree; on a symmetrised graph it equals out-degree (report both if directed)
    "avg_degree": round(in_degree.float().mean().item(), 2),
    "min_degree": int(in_degree.min()),
    "max_degree": int(in_degree.max()),
    "isolated_nodes": int(((in_degree + out_degree) == 0).sum()),   # no edge either way
    "connected_components": algorithms.connected_components(
        g.edge_index, g.num_nodes).unique().numel(),
}
write_graph_stats(graph_stats, f"{RUN_DIR}/graph_stats.json")

write_dataset_metadata(
    f"{RUN_DIR}/dataset_metadata.json",
    name="synthetic homophilous graph",
    source=f"generated by this script, data seed {DATA_SEED}",
    task="node classification, transductive",
    edge_construction="random pairs, self-pairs dropped; same-class kept, others with p=0.1; symmetrised",
    class_counts=torch.bincount(g.y, minlength=C).tolist(),
    split={"train": int(train_mask.sum()), "val": int(val_mask.sum()),
           "test": int(test_mask.sum()), "seed": SPLIT_SEED,
           "method": "node_train_val_test_split, not stratified"},
    preprocessing="none",
)
print(graph_stats)

Pass write_graph_stats a dictionary. If you hand it a Graph instead, it records only num_nodes and num_edges, which leaves out most of the schema above. Its first parameter (named graph_obj) takes the dictionary and the path is second; the other writers in this article take the path first.

Environment and seeds

python
import platform
import subprocess

from tgraphx import env_report, write_hardware_report
from tgraphx.reproducibility import reproducibility_report, set_seed

seed_state = set_seed(TRAIN_SEED, deterministic=True)     # warn_only=True by default

git = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=False)
git_commit = git.stdout.strip() if git.returncode == 0 else None

env = env_report(include_hardware=True)
env["torch_cuda_build"] = torch.version.cuda              # env_report has no CUDA version field
write_hardware_report(f"{RUN_DIR}/hardware_report.json", **env)

with open(f"{RUN_DIR}/reproducibility_report.json", "w") as f:
    json.dump(reproducibility_report(), f, indent=2)

write_hardware_report writes exactly the fields you pass. Called with only a path, it produces an empty JSON object, so unpack the env_report dictionary into it. env_report gives the Python, PyTorch and TGraphX versions, the operating system, and CUDA availability and device name; with include_hardware=True it adds CPU count and memory figures (the RAM figures need psutil). Neither report records your git commit or installed packages. The script reads the commit with git and saves it in run_metadata.json further down; a commit hash does not capture uncommitted changes, and the package list is still yours to save (for example the output of pip freeze).

Use tgraphx.reproducibility.set_seed here. The top-level tgraphx.set_seed is a different function: with deterministic=True it sets the cuDNN flags but does not enable PyTorch's deterministic algorithms. Neither one guarantees identical results across hardware or PyTorch versions.

Model and training configuration

python
from tgraphx import count_parameters, write_experiment_config

class GCN(nn.Module):
    def __init__(self, in_dim, hidden_dim, num_classes, dropout):
        super().__init__()
        self.conv1 = GCNConv(in_dim, hidden_dim)   # self-loops and symmetric normalisation
        self.conv2 = GCNConv(hidden_dim, num_classes)
        self.dropout = nn.Dropout(dropout)

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

config = {
    "model": {"layers": "2 x GCNConv", "in_dim": D, "hidden_dim": 32, "num_classes": C,
              "activation": "ReLU", "dropout": 0.5},
    "training": {"optimizer": "Adam", "lr": 0.01, "weight_decay": 5e-4, "max_epochs": 100,
                 "batching": "full graph", "loss": "cross-entropy on training nodes",
                 "early_stopping": {"monitor": "val_loss", "mode": "min", "patience": 10}},
    "seeds": {"data": DATA_SEED, "split": SPLIT_SEED, "training": TRAIN_SEED},
}

m = config["model"]
model = GCN(m["in_dim"], m["hidden_dim"], m["num_classes"], m["dropout"])
m["parameters"] = count_parameters(model)
write_experiment_config(f"{RUN_DIR}/experiment_config.json", config)

Build the model from the config rather than typing the numbers twice, so the file cannot drift from the code. The training loop below takes its optimizer and stopping settings from the same dictionary. Descriptive strings such as layers and loss are not checked against anything. GCNConv takes vector node features [N, D]; tensor layers such as TensorGraphSAGELayer expect image-like [N, C, H, W] or volumetric node features instead.

Training with validation-based selection

python
import time

from tgraphx import CSVLogger, load_checkpoint, save_checkpoint
from tgraphx.estimators import EarlyStopping

train_cfg = config["training"]
optimizer_class = getattr(torch.optim, train_cfg["optimizer"])
optimizer = optimizer_class(model.parameters(), lr=train_cfg["lr"],
                            weight_decay=train_cfg["weight_decay"])
stop_cfg = train_cfg["early_stopping"]
stopper = EarlyStopping(patience=stop_cfg["patience"], mode=stop_cfg["mode"])

start = time.perf_counter()
with CSVLogger(RUN_DIR) as logger:                 # writes RUN_DIR/metrics.csv
    for epoch in range(train_cfg["max_epochs"]):
        model.train()
        optimizer.zero_grad()
        loss = F.cross_entropy(model(g.x, g.edge_index)[g.train_mask], g.y[g.train_mask])
        loss.backward()
        optimizer.step()

        model.eval()
        with torch.no_grad():
            val_loss = F.cross_entropy(model(g.x, g.edge_index)[g.val_mask],
                                       g.y[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:                   # this epoch is the new best
            save_checkpoint(model, optimizer, epoch, f"{RUN_DIR}/best.pt", val_loss=val_loss)
        if stop:
            break

train_seconds = time.perf_counter() - start
epochs_run = epoch + 1
best_epoch = load_checkpoint(model, None, f"{RUN_DIR}/best.pt")

The "mode": "min" entry matters: the default for tgraphx.estimators.EarlyStopping is "max", which is wrong for a loss. The stopper does not keep model weights, so the loop saves them. CSVLogger takes its columns from the first row and appends to an existing file, so log every column from the first epoch and use a fresh run directory.

Results and a summary README

Evaluate the test nodes once, with the selected checkpoint.

python
from tgraphx import write_metrics_summary, write_run_metadata

model.eval()
with torch.no_grad():
    logits = model(g.x, g.edge_index)

metrics = {}
for split, mask in [("train", g.train_mask), ("val", g.val_mask), ("test", g.test_mask)]:
    metrics[f"{split}_accuracy"] = (logits[mask].argmax(1) == g.y[mask]).float().mean().item()
    metrics[f"{split}_loss"] = F.cross_entropy(logits[mask], g.y[mask]).item()

# Pass plain Python numbers: a tensor would be written as the string "tensor(...)"
write_metrics_summary(f"{RUN_DIR}/metrics_summary.json", **metrics,
                      num_runs=1, best_epoch=best_epoch)
write_run_metadata(
    f"{RUN_DIR}/run_metadata.json",
    run_name="exp_001", status="completed", device=str(g.device),
    tgraphx_version=tgraphx.__version__, torch_version=torch.__version__,
    seed=TRAIN_SEED, seed_state=seed_state,
    total_epochs=epochs_run, best_epoch=best_epoch,
    early_stopped=stop, train_seconds=round(train_seconds, 2),
    git_commit=git_commit,
)
g.save(f"{RUN_DIR}/graph.tgx")        # the exact graph, labels and masks

caveats = [
    "One training seed and one split: no estimate of variation.",
    "Synthetic data whose edges were generated from the labels of all nodes, test nodes "
    "included. The topology carries label information, so the accuracy says nothing "
    "about real data.",
    "Hyperparameters were set by hand; no search was run.",
]
rows = "\n".join(
    f"| {s} | {metrics[s + '_accuracy']:.3f} | {metrics[s + '_loss']:.3f} |"
    for s in ("train", "val", "test")
)
report = f"""# Experiment report: exp_001

- Data: synthetic, {graph_stats['num_nodes']} nodes, {graph_stats['num_edges']} directed edges (symmetrised)
- Protocol: transductive node classification, {C} classes
- Split: {int(g.train_mask.sum())}/{int(g.val_mask.sum())}/{int(g.test_mask.sum())} train/validation/test nodes
- Seeds: data {DATA_SEED}, split {SPLIT_SEED}, training {TRAIN_SEED}
- Model: {m['layers']}, {m['parameters']} parameters
- Shapes: input {list(g.x.shape)}, hidden [{g.num_nodes}, {m['hidden_dim']}], logits {list(logits.shape)}
- Training: {train_cfg['optimizer']}, lr {train_cfg['lr']}, weight decay {train_cfg['weight_decay']}, {train_cfg['batching']}
- Selection: lowest validation loss at epoch {best_epoch} (counted from 0); {epochs_run} epochs run
- Software: Python {platform.python_version()}, TGraphX {tgraphx.__version__}, PyTorch {torch.__version__}
- Hardware: trained on {g.device}; CUDA build {torch.version.cuda or 'none'}, GPU {env['cuda_device'] or 'none'}
- Deterministic algorithms: {torch.are_deterministic_algorithms_enabled()} (warn_only={seed_state['backend_settings']['warn_only']})
- Git commit: {git_commit or 'not recorded (no git commit found)'}
- More detail: dataset_metadata.json, graph_stats.json, experiment_config.json,
  hardware_report.json, reproducibility_report.json, run_metadata.json (with training time)

| Split | Accuracy | Loss |
|---|---|---|
{rows}

## Caveats
""" + "".join(f"- {c}\n" for c in caveats)

with open(f"{RUN_DIR}/README.md", "w") as f:
    f.write(report)
print(report)

Output from one CPU run with TGraphX 1.5.1 and PyTorch 2.15, started outside a git repository (numbers and environment lines may differ on your machine):

text
# Experiment report: exp_001

- Data: synthetic, 300 nodes, 1684 directed edges (symmetrised)
- Protocol: transductive node classification, 3 classes
- Split: 180/60/60 train/validation/test nodes
- Seeds: data 0, split 0, training 42
- Model: 2 x GCNConv, 643 parameters
- Shapes: input [300, 16], hidden [300, 32], logits [300, 3]
- Training: Adam, lr 0.01, weight decay 0.0005, full graph
- Selection: lowest validation loss at epoch 42 (counted from 0); 53 epochs run
- Software: Python 3.13.12, TGraphX 1.5.1, PyTorch 2.15.0+cpu
- Hardware: trained on cpu; CUDA build none, GPU none
- Deterministic algorithms: True (warn_only=True)
- Git commit: not recorded (no git commit found)
- More detail: dataset_metadata.json, graph_stats.json, experiment_config.json,
  hardware_report.json, reproducibility_report.json, run_metadata.json (with training time)

| Split | Accuracy | Loss |
|---|---|---|
| train | 0.956 | 0.190 |
| val | 0.867 | 0.380 |
| test | 0.900 | 0.484 |

## Caveats
- One training seed and one split: no estimate of variation.
- Synthetic data whose edges were generated from the labels of all nodes, test nodes included. The topology carries label information, so the accuracy says nothing about real data.
- Hyperparameters were set by hand; no search was run.

This README is a short summary, not the filled template. To finish the report, expand it along the template's headings:

  • Copy from the JSON files: dataset name and source, how the split was made, edge construction rule, class counts and preprocessing (dataset_metadata.json); degrees, self-loops, duplicates, isolated nodes and components (graph_stats.json); activation, dropout, loss, maximum epochs and early-stopping patience (experiment_config.json); number of runs (metrics_summary.json); training time (run_metadata.json).
  • Add by hand: the question you were asking; dataset version; edge features or weights; the number of graphs, and "not applicable" for the graph-level dataset line; normalisation; learning-rate schedule; CPU model; whether anything was tuned on the test set; whether the split is standard or custom; and any hardware dependence.

What ends up in the run directory

runs/exp_001/
  README.md                    <- summary and caveats for humans
  best.pt                      <- selected checkpoint
  dataset_metadata.json        <- source, construction, split, class counts
  experiment_config.json       <- model, training, seeds
  graph.tgx                    <- graph, labels and masks
  graph_stats.json             <- topology summary
  hardware_report.json         <- versions and hardware
  metrics.csv                  <- per-epoch losses
  metrics_summary.json         <- final metrics
  reproducibility_report.json  <- determinism flags
  run_metadata.json            <- status, seed, epochs, git commit, training time

Some of these names are ones the local dashboard looks for: tgraphx-dashboard --logdir runs/exp_001 reads metrics.csv, run_metadata.json, graph_stats.json and reproducibility_report.json. See offline dashboard reports. graph.tgx is loaded with Python's pickle machinery, so only open files you trust.

Caveats: the section not to skip

This is the part most often omitted and most often needed later. Ask:

  • Did you tune hyperparameters on the test set? If so, the test number is no longer an estimate of generalisation.
  • Is the split standard or custom? It decides what the number can be compared with.
  • Did you run only one seed? Small datasets can have large run-to-run variation.
  • Could any edge, feature or preprocessing step carry information from validation or test labels?
  • Which results depend on particular hardware or library versions?

What the experiments Runner records

If your run fits the config-driven tgraphx.experiments module, it writes part of this record for you:

python
from tgraphx.experiments import Runner, load_config

cfg = load_config({                      # a path to a YAML file also works
    "seed": 0, "run_name": "runner_demo", "run_dir": "runs/runner_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": 3, "lr": 0.005},
    "callbacks": [{"name": "model_checkpoint"}],
})
history = Runner(cfg).fit()              # takes no model or data loaders
print(sorted(os.listdir("runs/runner_demo")))

It writes run_metadata.json, experiment_config.json, metrics.csv and experiment_summary.json; the checkpoints/ folder appears because of the model_checkpoint callback. In 1.5.1 it is a smoke runner: it puts the whole dataset into one batch and computes no validation or test metrics, so an early_stopping callback monitoring the default val_loss never triggers.

Several things in the run directory can mislead a later reader:

  • experiment_config.json lists val_ratio (0.2 by default) and test_ratio, but neither is applied, so no 20% was held out.
  • It also lists batch_size (8 by default), which is not applied either: every training step uses the whole dataset.
  • device, in both experiment_config.json and run_metadata.json, is the device you requested, not necessarily the one used. Only cuda or mps, when available, selects an accelerator. Otherwise, including for cuda:0, training runs on the CPU without a warning, so record the actual device yourself.
  • Only checkpoints/latest.pt is written, with no best checkpoint, because there is no val_loss.

Node tasks add a label-leakage trap. The Runner restricts its loss only if graph.metadata["masks"] has a key named train_mask, while Graph(train_mask=...) stores that mask under train. It therefore ignores the masks of a graph like g above: if a registered dataset returns one, and no transform adds a train_mask key, the loss covers every node, validation and test labels included. The pyg:planetoid adapters convert with from_pyg_data, which drops masks, so their graphs give the Runner no mask at all. The built-in synthetic:node_classification does store train_mask, and its loss covers only those nodes. Do not use the Runner for node classification or node regression that you intend to evaluate.

For results you intend to report, use your own training and evaluation loop, as above. For the config format, see building an experiment from YAML.

Related reading

Six months from now, you will thank yourself for writing section 7.