Testing Graph Learning Code: Unit Tests That Catch Real Mistakes
It is easy to leave research code untested. Experiments run, results look plausible, and nothing reports that a change broke something that used to be correct. This tutorial builds a test file for the mistakes that are specific to graph learning code: invalid graphs, wrong message-passing behaviour, batching errors and non-determinism.
All Python blocks below form one file, for example tests/test_graph_code.py;
they build on each other, so keep them in order. The tests are plain functions
with assert statements, which pytest collects as they are. Examples tested
with TGraphX 1.5.1 on CPU.
Why GNN Code Needs Its Own Test Patterns
Standard testing advice applies, but graph code has extra failure modes:
- Shape convention errors: a reshaped or reversed
edge_indexcan have a valid shape and describe a different graph. - Device splits: model on the GPU and data on the CPU fails only in the forward pass.
- Aggregation errors: a wrong axis or direction produces the right shape with wrong values.
- Batching errors: a custom collate function that forgets to offset
edge_indexconnects the wrong nodes. - Non-determinism: results that change between runs hide real regressions.
Shape checks alone catch little of items 3 and 4, so several tests below check behaviour instead.
Shared Helpers
import unittest
import torch
import torch.nn as nn
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import GCNConv, Graph, GraphBatch, TensorGraphSAGELayer
from tgraphx.reproducibility import set_seed
def graph_kwargs():
return dict(
node_features=torch.randn(10, 8),
edge_index=torch.randint(0, 10, (2, 20)),
edge_features=torch.randn(20, 4),
node_labels=torch.randint(0, 3, (10,)),
)
def make_graph(N=10, E=20, d=8, seed=0):
gen = torch.Generator().manual_seed(seed)
return Graph(
node_features=torch.randn(N, d, generator=gen),
edge_index=torch.randint(0, N, (2, E), generator=gen),
edge_features=torch.randn(E, 4, generator=gen),
node_labels=torch.randint(0, 3, (N,), generator=gen),
)
def expect_error(error_type, text, fn):
"""Fail unless fn() raises error_type with `text` in the message."""
try:
fn()
except error_type as err:
assert text in str(err), f"unexpected message: {err}"
else:
raise AssertionError(f"expected {error_type.__name__}")
expect_error keeps the file runnable without pytest. In a pytest-only project,
pytest.raises(ValueError, match=re.escape("[2, E]")) does the same job;
match is a regular expression, so escape literal brackets. Checking the message
matters: it proves that the test failed for the reason you meant.
Test 1: Construction Validation
Invalid graphs must raise, and valid ones must not:
def test_valid_construction():
g = Graph(**graph_kwargs())
assert g.node_features.shape == (10, 8)
assert g.edge_index.shape == (2, 20)
def test_wrong_edge_index_orientation():
kwargs = graph_kwargs()
kwargs["edge_index"] = kwargs["edge_index"].t() # [E, 2]
expect_error(ValueError, "[2, E]", lambda: Graph(**kwargs))
def test_edge_feature_count_mismatch():
kwargs = graph_kwargs()
kwargs["edge_features"] = torch.randn(25, 4) # 25 rows, 20 edges
expect_error(ValueError, "edge_features", lambda: Graph(**kwargs))
def test_node_label_count_mismatch():
kwargs = graph_kwargs()
kwargs["node_labels"] = torch.randint(0, 3, (15,)) # 15 labels, 10 nodes
expect_error(ValueError, "node_labels", lambda: Graph(**kwargs))
def test_out_of_range_and_negative_indices():
for bad_id in (10, -1):
kwargs = graph_kwargs()
kwargs["edge_index"][0, 0] = bad_id
expect_error(ValueError, "out-of-range", lambda: Graph(**kwargs))
These tests document the constructor behaviour your code relies on, and they fail if an upgrade changes it.
Test 2: Device Handling
A CPU-only CI machine can still check that .to() moves every tensor: the
meta device holds shapes without data.
def test_to_moves_every_tensor():
g = Graph(**graph_kwargs(), train_mask=torch.arange(10) < 6)
moved = g.to("meta")
assert moved is g # Graph.to() works in place
for tensor in (g.node_features, g.edge_index, g.edge_features,
g.node_labels, g.train_mask):
assert tensor.device.type == "meta"
def test_gpu_if_available():
if not torch.cuda.is_available():
raise unittest.SkipTest("CUDA not available") # pytest reports a skip
g = Graph(**graph_kwargs()).to("cuda")
assert g.node_features.is_cuda and g.edge_index.is_cuda
Note the first assertion: Graph.to() changes the graph itself. Use
g.clone() first if a test needs the original.
Test 3: Output Shapes
Layers are called as layer(x, edge_index), not layer(graph). Spatial layers
need [N, C, H, W] features; vector features go to layers such as GCNConv.
def test_sage_output_shape():
x = torch.randn(15, 8, 4, 4)
edge_index = torch.randint(0, 15, (2, 30))
out = TensorGraphSAGELayer(8, 16)(x, edge_index)
assert out.shape == (15, 16, 4, 4)
def test_gcn_output_shape():
g = make_graph(N=15, E=30, d=32)
assert GCNConv(32, 64)(g.x, g.edge_index).shape == (15, 64)
def test_spatial_layer_rejects_vector_features():
g = make_graph()
expect_error(ValueError, "[N, C, H, W]",
lambda: TensorGraphSAGELayer(8, 16)(g.x, g.edge_index))
Write one of these for each layer you use.
Test 4: Message-Passing Behaviour
A layer can return the right shape and still aggregate the wrong things. Two
properties are cheap to test. Permutation equivariance: renumbering the
nodes must renumber the output the same way. Direction: information flows
from edge_index[0] to edge_index[1] and not back.
def test_permutation_equivariance():
set_seed(0)
layer = TensorGraphSAGELayer(8, 16).eval()
x = torch.randn(12, 8, 4, 4)
edge_index = torch.randint(0, 12, (2, 40))
perm = torch.randperm(12) # new row i holds old node perm[i]
new_id = torch.argsort(perm) # old id -> new id
with torch.no_grad():
out = layer(x, edge_index)
out_permuted = layer(x[perm], new_id[edge_index])
assert torch.allclose(out_permuted, out[perm], atol=1e-5)
def test_messages_follow_edge_direction():
set_seed(0)
layer = GCNConv(8, 8).eval() # adds self-loops
x = torch.randn(4, 8)
edge_index = torch.tensor([[0], [1]]) # 0 -> 1
def rows_changed_by(node):
x2 = x.clone()
x2[node] += 1.0
with torch.no_grad():
diff = (layer(x2, edge_index) - layer(x, edge_index)).abs().sum(1)
return (diff > 1e-6).nonzero().flatten().tolist()
assert rows_changed_by(0) == [0, 1] # node 0 reaches node 1
assert rows_changed_by(1) == [1] # nothing flows back
def test_mean_pooling_matches_hand_computation():
x = torch.tensor([[1.0], [3.0], [10.0]])
batch = torch.tensor([0, 0, 1])
assert torch.equal(tgx.global_mean_pool(x, batch), torch.tensor([[2.0], [10.0]]))
Permutation equivariance catches code that depends on node order, such as
reading "the first k rows". Layers that use dropout or batch statistics need
.eval() for these comparisons.
Test 5: GraphBatch Correctness
GraphBatch takes a list of graphs. It concatenates node tensors, offsets edge
indices and builds the batch vector. Test the properties you depend on:
def three_graphs():
return [make_graph(N=5, E=8, seed=1), make_graph(N=7, E=12, seed=2),
make_graph(N=4, E=6, seed=3)]
def test_batch_concatenates_nodes_and_labels():
graphs = three_graphs()
batch = GraphBatch(graphs)
assert torch.equal(batch.node_features, torch.cat([g.node_features for g in graphs]))
assert torch.equal(batch.node_labels, torch.cat([g.node_labels for g in graphs]))
assert batch.batch.tolist() == [0] * 5 + [1] * 7 + [2] * 4
def test_batch_offsets_edge_indices():
graphs = three_graphs()
batch = GraphBatch(graphs)
src, dst = batch.edge_index
assert torch.equal(batch.batch[src], batch.batch[dst]) # no cross-graph edges
offset = 0
for i, g in enumerate(graphs):
own = batch.edge_index[:, batch.batch[src] == i]
assert torch.equal(own - offset, g.edge_index)
offset += g.num_nodes
def test_output_does_not_depend_on_other_graphs():
set_seed(0)
layer = GCNConv(8, 16).eval()
graphs = three_graphs()
batch = GraphBatch(graphs)
with torch.no_grad():
alone = layer(graphs[0].x, graphs[0].edge_index)
together = layer(batch.node_features, batch.edge_index)[: graphs[0].num_nodes]
assert torch.allclose(alone, together, atol=1e-5)
The last test is the one to copy for your own models: it fails if the other
graphs in the batch change the first graph's output at inference. Because it runs
in .eval(), it does not see BatchNorm computing statistics across graphs during
training. To check the training path, run the same comparison in train mode with
dropout disabled.
Test 6: Determinism
def forward_with_seed(seed, x, edge_index):
set_seed(seed) # seeds Python, NumPy and PyTorch
layer = GCNConv(8, 16)
with torch.no_grad():
return layer(x, edge_index)
def test_same_seed_same_output():
g = make_graph()
assert torch.equal(forward_with_seed(42, g.x, g.edge_index),
forward_with_seed(42, g.x, g.edge_index))
def test_different_seed_different_output():
g = make_graph()
assert not torch.allclose(forward_with_seed(42, g.x, g.edge_index),
forward_with_seed(99, g.x, g.edge_index))
Exact equality is reasonable for this repeated CPU computation. On GPUs, or across machines, compare with a tolerance. See seeded deterministic experiments for what a seed does and does not guarantee.
Test 7: Builder Defaults
build_grid_graph and build_knn_graph return edge_index tensors, and by
default both add reverse edges and self-loops. Other builders differ:
tgx.knn_graph and build_fully_connected_graph add no self-loops, and
build_random_graph is directed with no self-loops by default. Pin down what you
expect:
def test_directed_knn_has_k_edges_per_query():
ei = tgx.build_knn_graph(torch.randn(20, 32), k=4, directed=True, self_loops=False)
assert ei.shape == (2, 80)
assert torch.equal(torch.bincount(ei[0], minlength=20), torch.full((20,), 4))
assert (ei[0] != ei[1]).all()
def test_default_knn_is_symmetric_with_self_loops():
ei = tgx.build_knn_graph(torch.randn(20, 32), k=4)
pairs = set(map(tuple, ei.t().tolist()))
assert all((j, i) in pairs for i, j in pairs)
assert all((i, i) in pairs for i in range(20))
def test_grid_graph_edge_count():
ei = tgx.build_grid_graph(4, 5)
neighbour_pairs = 4 * 4 + 3 * 5 # horizontal + vertical
assert ei.shape == (2, 2 * neighbour_pairs + 4 * 5) # both ways + self-loops
Test 8: Overfit a Small Batch
An integration test for the training path: a small model should memorise 40 random labels. If it cannot, look for a disconnected layer, parameters missing from the optimizer, or a learning rate or step count that is too small.
class TinyGNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = GCNConv(16, 32)
self.conv2 = GCNConv(32, 3)
def forward(self, x, edge_index):
return self.conv2(F.relu(self.conv1(x, edge_index)), edge_index)
def test_every_parameter_gets_a_gradient():
set_seed(0)
model, g = TinyGNN(), make_graph(d=16)
F.cross_entropy(model(g.x, g.edge_index), g.y).backward()
for name, p in model.named_parameters():
assert p.grad is not None and p.grad.abs().sum() > 0, name
def test_model_can_overfit_small_batch():
set_seed(0)
batch = GraphBatch([make_graph(N=8, E=15, d=16, seed=i) for i in range(5)])
model = TinyGNN()
opt = torch.optim.Adam(model.parameters(), lr=0.02)
for _ in range(300):
opt.zero_grad()
out = model(batch.node_features, batch.edge_index)
loss = F.cross_entropy(out, batch.node_labels)
loss.backward()
opt.step()
assert loss.item() < 0.1, f"failed to overfit: loss={loss.item():.4f}"
Passing this says the pipeline can learn. It says nothing about generalisation, and it can pass with either of these bugs present:
- Misaligned labels. This test does not detect them. The labels are random, so shuffled labels, or labels rolled by one row, are memorised just as well. Row alignment needs its own assertion. Test 5's concatenation check covers batching. If features and labels are loaded separately, also assert that their node ids match, in order, before you build the graph.
- A layer left out of the optimizer. With only
conv1in the optimizer, so that the output layerconv2is never updated, the loss in this setup still ends below 0.1. (Leaving outconv1instead does make it fail, so whether the loss notices depends on which layer is missing.)
To catch the second one, take one optimizer step and assert that every named parameter changed. Create the optimizer with the same function your training code uses; an optimizer written separately inside the test would not show the mistake.
def make_optimizer(model): # in a project, import the one you train with
return torch.optim.Adam(model.parameters(), lr=0.02)
def test_optimizer_step_changes_every_parameter():
set_seed(0)
model, g = TinyGNN(), make_graph(d=16)
opt = make_optimizer(model)
before = {name: p.detach().clone() for name, p in model.named_parameters()}
F.cross_entropy(model(g.x, g.edge_index), g.y).backward()
opt.step()
for name, p in model.named_parameters():
assert not torch.equal(p.detach(), before[name]), f"{name} did not change"
Running the Tests
Add this block at the end of the file if you also want to run it directly with
python:
if __name__ == "__main__":
passed = skipped = 0
for name, test in list(globals().items()):
if name.startswith("test_") and callable(test):
try:
test()
passed += 1
except unittest.SkipTest as reason:
print("skipped", name, "-", reason)
skipped += 1
print(passed, "passed,", skipped, "skipped")
On a machine without a GPU it reports one skipped test (the CUDA one). Any failing test stops the script with a traceback.
With pytest:
pip install pytest
python -m pytest tests/ -v
As the suite grows, split it by topic and move the helpers into a shared module:
project/
├── model.py
├── data.py
└── tests/
├── helpers.py
├── test_graph_construction.py
├── test_layers.py
├── test_batching.py
└── test_training.py
These tests use tiny CPU graphs, so run them after every code change, before a training job and after upgrading TGraphX or PyTorch. Related reading: silent GNN failures for more bugs worth a test, and debugging graph neural networks for what to do when one fails.