TGraphX › Insights › Debugging Graph Neural Networks: A Systematic Approach with TGraphX
← Back to Insights

Debugging Graph Neural Networks: A Systematic Approach with TGraphX

Topic: Shape validation, testing and debugging

GNN bugs are hard because the data, the model and the training loop interact in ways that are not obvious from a stack trace. A CUDA assertion deep in an indexing operation may come from an out-of-range node id or an out-of-range class label, and a poor validation score may come from almost anywhere. Without a systematic approach, debugging becomes guesswork.

This article is a method for narrowing a problem down: check one layer at a time, with a small test for each. Examples tested with TGraphX 1.5.1 on CPU; blocks build on each other, so run them in order.

The four-layer model of GNN bugs

GNN problems show up at different layers:

  1. Data layer: wrong shapes, out-of-range edge indices, misaligned labels, leaking splits.
  2. Model layer: wrong layer for the input shape, missing activation, mismatched dimensions.
  3. Training-loop layer: gradient flow problems, optimizer misconfiguration, wrong loss or wrong nodes in the loss.
  4. Reproducibility layer: different results across runs, a baseline that cannot be reproduced.

The order matters: a bug in one layer often shows up as a symptom in the next. A data problem can look like a model problem, because the model is where it raises.

A small setup to run the steps on

The steps below use a synthetic node classification graph and a two-layer model. Swap in your own g and model.

python
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph, NeighborLoader
from tgraphx.estimators import node_train_val_test_split

torch.manual_seed(0)
n, num_classes = 120, 3
train_mask, val_mask, test_mask = node_train_val_test_split(n, 0.6, 0.2, 0.2, seed=0)

g = Graph(
    node_features=torch.randn(n, 16),                 # [N, D]
    edge_index=torch.randint(0, n, (2, 480)),         # [2, E]
    y=torch.randint(0, num_classes, (n,)),
    train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
)
model = tgx.build_model("node_classification", layer="linear", in_shape=(16,),
                        hidden_shape=(32,), num_layers=2, num_classes=num_classes)

Step 1: Validate the data

Start with the data. These checks complement each other:

python
g.validate()                                             # shape, dtype, index range, lengths (not masks), devices
tgx.validate_graph(g, strict=True, check_finite=True)    # NaN/Inf in features, mask lengths
tgx.check_leakage(train_mask=g.train_mask, val_mask=g.val_mask,
                  test_mask=g.test_mask)                 # raises if node masks overlap

assert g.y.dtype == torch.long and 0 <= int(g.y.min()) and int(g.y.max()) < num_classes

What each one catches:

  • g.validate(): edge_index not [2, E] or not torch.long, negative or too large node ids, label length, tensors on different devices. It does not check masks.
  • tgx.validate_graph: edge shape and too large ids, mask lengths, devices, and, with check_finite=True, NaN and Inf in node and edge features (not edge weights or labels). It does not check negative ids, label length or dtype.
  • tgx.check_leakage: overlap between node masks only, not duplicated samples or leaked edges. Pass the masks by keyword. The first parameter is graph, so positional masks bind to the wrong names and a train/test overlap can pass unnoticed.

If your nodes are supposed to carry tensors such as [C, H, W], add tgx.assert_tensor_native(g, min_rank=4) (use 5 for [C, D, H, W]). The rank counts the node axis, so min_rank=3 would also pass [N, H, W], a tensor that has lost an axis. For validation as a topic of its own, see shape-aware validation.

Step 2: Inspect a batch

If the full graph is sound, look at what the loader actually yields.

python
loader = NeighborLoader(g, fanouts=[10, 5], mask=g.train_mask, batch_size=16, seed=42)
batch = next(iter(loader))
print(tgx.batch_summary(batch))

batch_summary returns a dictionary with the batch type, feature shape, device and dtype, the number of edges, subgraph nodes and seed nodes, and a short list of structural issues. Its checks are shallow, so read the numbers: is the seed count what you asked for, and is the subgraph size plausible for these fanouts? Note mask=g.train_mask. Without it, validation and test nodes are used as seeds too.

Step 3: Try a forward pass

python
model.eval()
with torch.no_grad():
    out = model(batch.x, batch.edge_index)

assert out.shape == (batch.num_nodes, num_classes)
print(out.shape, bool(torch.isfinite(out).all()))     # one row per subgraph node

If the output contains NaN or Inf, rule out the inputs first. If they are finite, forward hooks can name the first module whose output is not:

python
import copy

def first_nonfinite_module(model, *inputs):
    """'input', or the first submodule whose output has NaN/Inf, or None."""
    if any(torch.is_tensor(t) and not torch.isfinite(t).all() for t in inputs):
        return "input"                       # fix the data first: no layer is to blame
    probe = copy.deepcopy(model)             # keeps the mode, leaves your model untouched
    found = []

    def make_hook(name):
        def hook(module, args, output):
            if not found and torch.is_tensor(output) and not torch.isfinite(output).all():
                found.append(name or type(module).__name__)
        return hook

    for name, module in probe.named_modules():
        module.register_forward_hook(make_hook(name))
    with torch.no_grad():
        probe(*inputs)
    return found[0] if found else None

print(first_nonfinite_module(model, batch.x, batch.edge_index))      # None: nothing non-finite

broken_x = batch.x.clone()
broken_x[0, 0] = float("nan")
print(first_nonfinite_module(model, broken_x, batch.edge_index))     # input

broken_model = copy.deepcopy(model)
with torch.no_grad():
    broken_model.gnn_layers[1].message_linear.weight[0, 0] = float("nan")
print(first_nonfinite_module(broken_model, batch.x, batch.edge_index))
# gnn_layers.1.message_linear

The copy matters. In training mode a forward pass updates BatchNorm running statistics even under torch.no_grad(), so a probe on the real model could write NaN into them, and it would then return NaN in eval mode even after the cause is fixed. build_model(layer="conv") and ConvMessagePassing contain BatchNorm by default; the error catalogue shows the effect and the repair. Hooks see only module outputs, so if plain tensor code between modules creates the NaN, the name you get is the next module whose output carries it.

Probe which nodes influence which

A shape check cannot tell you that edges point the wrong way. A perturbation test can: change the input of one node and see which outputs move. In TGraphX, messages travel from edge_index[0] to edge_index[1].

python
probe = tgx.GCNConv(2, 2)
x0 = torch.zeros(3, 2)
x1 = x0.clone()
x1[0] = 1.0                                           # perturb node 0 only
one_edge = torch.tensor([[0], [1]])                   # a single edge 0 -> 1

with torch.no_grad():
    changed = (probe(x1, one_edge) - probe(x0, one_edge)).abs().sum(dim=1) > 0
print(changed)                                        # tensor([ True,  True, False])

Node 0 changes through its self-loop, node 1 through the edge, node 2 not at all. With L message-passing layers, only nodes within L hops downstream of the perturbed node should change, as long as the model is in eval mode and has no operation that mixes all nodes, such as batch normalisation or global pooling. A layer that propagates several times inside one module counts as several hops: an APPNP module counts as K hops (10 by default).

Step 4: Try a backward pass

python
model.train()
model.zero_grad()
out = model(batch.x, batch.edge_index)
loss = F.cross_entropy(batch.seed_logits(out), batch.seed_y)     # seed nodes only
loss.backward()

for name, param in model.named_parameters():
    if param.grad is None:
        print(f"no gradient: {name}")
    else:
        print(f"{name}: grad norm = {param.grad.norm().item():.4f}")

Read the result like this:

  • No gradient (None): the parameter is frozen, unused in the forward pass, or cut off by a detach().
  • Norm exactly zero: the path is connected but nothing flows, for example because all activations are zero.
  • Very large or non-finite norms: check feature scale and learning rate.

Then try to overfit one fixed batch. A model with enough capacity should drive this loss close to zero. If it cannot, look for a broken gradient path, an optimizer that holds the wrong parameters, a wrongly computed loss, an unsuitable learning rate, or nodes with identical inputs and different labels.

python
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
for step in range(200):
    optimizer.zero_grad()
    loss = F.cross_entropy(batch.seed_logits(model(batch.x, batch.edge_index)), batch.seed_y)
    loss.backward()
    optimizer.step()

print(f"{loss.item():.4f}")
assert loss.item() < 0.05

A pass here says that gradients and updates work. It does not show that the model generalises or that the labels are aligned: the labels in this example are random, and the model memorises them anyway.

With layer="linear", also count the nodes with no incoming edges. The layer adds no self-loop or skip connection, so every such node gets the same output (the bias of the output layer), whatever its features are:

python
no_incoming = torch.bincount(g.edge_index[1], minlength=g.num_nodes) == 0
print(int(no_incoming.sum()))                             # 0 for this synthetic graph

If those nodes matter, add self-loops with g.add_self_loops() (it changes g in place) or add your own skip connection. Setting residual=True is not enough for this model: the built-in skip is applied only where a layer's input and output widths are equal, and the first layer maps 16 to 32.

Step 5: What tgx.explain_error can and cannot do

explain_error is a small lookup, not a diagnosis. In 1.5.1 it searches the message for a handful of keywords (rank, nsga, composite_fitness, vgae, missing optional, edge_index, mask overlap, json, cuda), falls back to a fuzzy match, and otherwise prints generic suggestions. For a transposed edge_index the hint is right:

python
try:
    Graph(node_features=torch.randn(4, 8), edge_index=torch.zeros(4, 2, dtype=torch.long))
except ValueError as err:
    print(tgx.explain_error(err))                     # suggests transposing: correct here
else:
    raise AssertionError("expected a shape error")

The same keyword also matches errors where that advice is wrong:

python
advice = tgx.explain_error(
    "edge_index contains out-of-range indices for 4 nodes (found min=0, max=9; valid range [0, 3])")
assert "transpose" in advice                          # wrong: the problem is the node ids

Likewise, a CUDA out-of-memory message gets "CUDA is not available", a message containing "rank" gets advice about GraphML export, and the mask-overlap hint suggests calling check_leakage with positional masks, which you should not do. Read the original exception first.

Step 6: Bisect by simplification

When the bug is real but you cannot localise it, simplify:

  • Reduce the graph to a few dozen nodes.
  • Reduce the model to one layer.
  • Reduce training to one batch.
  • Reduce the loss to a plain, known-correct formulation.
  • Replace the GNN with an MLP that ignores edges. If the MLP learns and the GNN does not, look at the edges.

If the bug persists in the simplified setup, you can now iterate quickly. If it disappears, add complexity back one piece at a time until it returns. The last piece you added is the first suspect.

Step 7: Record runs, then compare them

You can only compare runs that recorded something. In your own training loop TGraphX writes no reproducibility file for you (the config-driven experiment runner behind tgraphx-train does save run_metadata.json and experiment_config.json). reproducibility_report() returns versions and backend flags but not your seed, package list or git commit. Write the report yourself and add what you need:

python
import json
import os
from tgraphx.reproducibility import reproducibility_report

def record_run(run_dir, **settings):
    os.makedirs(run_dir, exist_ok=True)
    record = {**reproducibility_report(), "tgraphx_version": tgx.__version__, **settings}
    with open(os.path.join(run_dir, "reproducibility_report.json"), "w") as fh:
        json.dump(record, fh, indent=2)

record_run("runs/exp_001", seed=42, lr=1e-3, fanouts=[10, 5])
record_run("runs/exp_002", seed=43, lr=1e-3, fanouts=[10, 5])

reports = []
for run in ("runs/exp_001", "runs/exp_002"):
    with open(os.path.join(run, "reproducibility_report.json")) as fh:
        reports.append(json.load(fh))

first, second = reports
for key in sorted(set(first) | set(second)):
    if first.get(key) != second.get(key):
        print(f"differs on {key}: {first.get(key)} vs {second.get(key)}")
# differs on seed: 42 vs 43

There is also tgx.audit_run_dir, which has a narrower job: it requires run_metadata.json, metrics_summary.json and benchmark_summary.json in a directory, checks that the JSON files there parse as objects, and flags a missing seed or version in run_metadata.json. It does not require or interpret the file written above, and it says nothing about whether results are correct.

python
audit = tgx.audit_run_dir("runs/exp_001")
print(audit["ok"], audit["files_missing"])
# False ['run_metadata.json', 'metrics_summary.json', 'benchmark_summary.json']

TGraphX can write those three files. tgraphx.tracking provides write_run_metadata, write_metrics_summary and write_benchmark_results; each takes the target path first and saves your keyword arguments as JSON:

python
from tgraphx.tracking import (write_benchmark_results, write_metrics_summary,
                              write_run_metadata)

run_dir = "runs/exp_001"
write_run_metadata(f"{run_dir}/run_metadata.json", seed=42, tgraphx_version=tgx.__version__)
write_metrics_summary(f"{run_dir}/metrics_summary.json", overfit_batch_loss=loss.item())
write_benchmark_results(f"{run_dir}/benchmark_summary.json", benchmark="not run")

audit = tgx.audit_run_dir(run_dir)
print(audit["ok"], audit["files_missing"])                # True []

The audit asks for a benchmark file even if you ran no benchmark. Record that fact, as above, rather than filling in numbers.

If everything you recorded matches and the results still differ, something you did not record differs (data or preprocessing, installed packages, hardware, thread count), or an operation is nondeterministic.

Common pitfalls and their signatures

"CUDA error: device-side assert triggered": usually an out-of-range index, either a node id or a class label. Run the same step on CPU to get a readable message, or set CUDA_LAUNCH_BLOCKING=1 so the traceback points at the right line. Check the data with g.validate(), which also rejects negative ids.

Validation accuracy stuck at chance level: misaligned labels are one cause. Others are features that carry no signal, a learning rate that is far off, edges that never reach the model (with default settings, build_model with layer="graph_transformer" ignores edge_index without a warning), many nodes with no incoming edge (see Step 4), or evaluating on the wrong mask. Compare labels against the source records by node id, run the overfitting test above, and compare with a features-only baseline.

Validation accuracy suspiciously high: check that the loss uses only training nodes. tgx.fit ignores node masks, and NeighborLoader without mask= seeds every node.

Training loss falls, validation loss does not: often ordinary overfitting, but a distribution shift between splits or a faulty evaluation path looks the same. Rule those out before adding regularisation.

Loss does not change: the gradients are zero or never applied. Check gradient norms, requires_grad, a stray detach(), and that the optimizer was built from the parameters of the model you are running.

Different results across runs with the same seed: tgx.set_seed, even with deterministic=True, does not enable PyTorch's deterministic algorithms. Use tgraphx.reproducibility.set_seed(seed, deterministic=True) or tgx.reproducible(seed=42, deterministic=True), and pass seed= to loaders and samplers.

Out of memory during neighbour sampling: the sampled subgraph can grow roughly with the product of the fanouts. Reduce the fanouts or batch_size.

For fixes organised by error category, see the catalogue of common GNN errors.

Debug logging during training

For problems that appear late, add checks to the loop and fail loudly. Start from a fresh model and optimizer: the model from Step 4 has just memorised one batch of random labels, so its first loss on other batches would look like a fault.

python
model = tgx.build_model("node_classification", layer="linear", in_shape=(16,),
                        hidden_shape=(32,), num_layers=2, num_classes=num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
num_epochs = 20

for epoch in range(num_epochs):
    model.train()
    for batch_idx, batch in enumerate(loader):
        if not torch.isfinite(batch.x).all():            # before the forward pass
            raise FloatingPointError(f"non-finite input at epoch {epoch}, batch {batch_idx}")
        optimizer.zero_grad()
        out = model(batch.x, batch.edge_index)
        loss = F.cross_entropy(batch.seed_logits(out), batch.seed_y)
        if not torch.isfinite(loss):
            raise FloatingPointError(f"loss={loss.item()} at epoch {epoch}, batch {batch_idx}")
        loss.backward()
        optimizer.step()
        if epoch % 10 == 0 and batch_idx == 0:
            print(f"epoch {epoch}: loss={loss.item():.4f}, output_std={out.std().item():.4f}")

The input check comes first because, in a model with BatchNorm, a forward pass on a non-finite input has already damaged the running statistics by the time the loss check runs. If the loss spikes or the output standard deviation collapses, you have a localised symptom to investigate.

Reproducibility for debugging

When you find a bug, reduce it to a deterministic reproducer and confirm that it gives the same number twice:

python
def reproducer():
    with tgx.reproducible(seed=42, deterministic=True):
        x = torch.randn(20, 16)
        edge_index = torch.randint(0, 20, (2, 60))
        labels = torch.randint(0, 3, (20,))
        net = tgx.build_model("node_classification", "linear", (16,), (32,), 2, num_classes=3)
        return F.cross_entropy(net(x, edge_index), labels).item()

assert reproducer() == reproducer()

tgx.reproducible seeds the generators and sets the deterministic flags on entry. It does not restore them on exit. On GPUs, some operations have no deterministic implementation, and PyTorch's reproducibility notes describe extra settings such as CUBLAS_WORKSPACE_CONFIG. A deterministic reproducer helps when you ask for help, file a bug report or verify a fix.


FAQ

Q: Where is the list of patterns explain_error knows about?
A: It is the _ERROR_MAP dictionary in tgraphx/ux/helpers.py. It is private, and there is no API for extending it.

Q: What about debugging gradient instability?
A: Run the suspect step under torch.autograd.detect_anomaly(). It raises when a backward function returns NaN and prints the traceback of the forward operation that created it. It does not inspect forward outputs, for which you can use the hook function from Step 3, and it slows execution, so remove it afterwards.

Q: How do I debug a custom layer?
A: Run it on a tiny graph, compare the output with a value computed by hand, and apply the perturbation test from Step 3. See also testing graph learning code.

Q: Is there a built-in pdb-style debugger?
A: No. Use Python's pdb or ipdb as usual.

Q: What about debugging heterogeneous GNNs?
A: Heterogeneous support in TGraphX is Experimental, and the checks in Step 1 are written for homogeneous Graph objects. HeteroGraph does not range-check edge indices, so check each relation yourself: row 0 against the number of source-type nodes, row 1 against the number of destination-type nodes. PyTorch Geometric's HeteroData has broader heterogeneous tooling, including its own validate() method.