TGraphX › Insights › Shape-Aware Validation in TGraphX: Catching Bugs Before They Matter
← Back to Insights

Shape-Aware Validation in TGraphX: Catching Bugs Before They Matter

Topic: Shape validation, testing and debugging

PyTorch GNN code can fail with a message like this:

RuntimeError: shape '[64, 128]' is invalid for input of size 12544

It tells you that a size is wrong, not where the data went wrong: an edge list that points at a missing node, a feature tensor that lost a dimension, labels that no longer line up.

TGraphX moves part of this checking to the data container. This article shows what is checked automatically, what you have to ask for, and what nothing checks. Examples tested with TGraphX 1.5.1 on CPU.

The constructor validates first

tgx.Graph validates its inputs when you build it. You do not need a separate call:

python
import torch
import tgraphx as tgx

N = 100
x = torch.randn(N, 3, 8, 8)            # [N, C, H, W]
y = torch.randint(0, 5, (N,))          # [N]

bad_edge_index = torch.tensor([[0, 1, 99, 100],     # node 100 does not exist
                               [1, 2, 0, 3]])
try:
    tgx.Graph(node_features=x, edge_index=bad_edge_index, node_labels=y)
except ValueError as err:
    print(err)
    # edge_index contains out-of-range indices for 100 nodes
    # (found min=0, max=100; valid range [0, 99])
else:
    raise AssertionError("the constructor should reject node id 100")

edge_index = torch.tensor([[0, 1, 99, 50],
                           [1, 2, 0, 3]])
g = tgx.Graph(node_features=x, edge_index=edge_index, node_labels=y)
print(g.num_nodes, g.num_edges, g.feature_shape)     # 100 4 (3, 8, 8)

The constructor rejects:

  • node_features with fewer than two dimensions;
  • an edge_index that is not a [2, E] tensor of dtype long (a transposed [E, 2] tensor fails here, unless E happens to be 2);
  • node ids below 0 or at least N;
  • node_labels whose first dimension is not N;
  • edge_features with fewer than two dimensions (give one scalar per edge the shape [E, 1]);
  • edge_features or edge_labels whose first dimension is not E, and an edge_weight that is not a 1-D tensor of length E;
  • train, validation or test masks whose length is not N;
  • tensors on a different device from the node features (masks are moved there instead of rejected).

It accepts, without a word, NaN or Inf values, duplicate edges, self-loops, isolated nodes, an integer tensor of length N passed as a mask, and features in the wrong axis order.

validate_graph re-checks after mutation

Graph attributes are ordinary attributes. If you reassign or modify them, the constructor does not run again. tgx.validate_graph returns a dictionary with ok, issues and info; with strict=True it raises GraphValidationError, a subclass of ValueError:

python
from tgraphx.ux.validation import GraphValidationError


def fresh():
    return tgx.Graph(node_features=x.clone(), edge_index=edge_index.clone(),
                     node_labels=y.clone())


report = tgx.validate_graph(g)
print(report["ok"], report["issues"])                # True []

h = fresh()
h.edge_index[0, 0] = 100                             # changed after construction
print(tgx.validate_graph(h)["issues"])
# ['edge_index references node 100 but graph has only 100 nodes.']
try:
    tgx.validate_graph(h, strict=True)
except GraphValidationError as err:
    print("strict mode raised:", err)
else:
    raise AssertionError("strict mode should raise")

validate_graph checks less than the constructor. A negative id or a truncated label vector passes it. To re-run the constructor-style checks, call the graph's own validate() method:

python
h = fresh()
h.edge_index[0, 0] = -1                              # negative node id
h.node_labels = y[:50]                               # wrong label length
assert tgx.validate_graph(h, strict=True)["ok"]      # passes anyway
try:
    h.validate()
except ValueError as err:
    print(err)
else:
    raise AssertionError("Graph.validate() should reject this graph")

h = fresh()
h.node_features[0] = float("nan")
h.validate()                                         # values are not checked
assert tgx.validate_graph(h)["ok"]                   # off by default
assert not tgx.validate_graph(h, check_finite=True)["ok"]

The two re-checks complement each other:

Check after mutation g.validate() validate_graph(g)
edge_index is [2, E] yes yes
ids of at least N yes yes
negative ids, edge_index dtype yes no
edge_features length yes yes
edge_features has at least two dimensions yes no
edge_weight shape yes no
label lengths yes no
mask lengths no yes
NaN or Inf in node or edge features no with check_finite=True

validate_graph also compares the devices of edge_index, edge features and labels with the node features, and allow_vector_features=False makes it require node features of rank 3 or more. check_graph_invariants is simply an alias of validate_graph: it adds no extra checks.

assert_tensor_native catches an accidental flatten

Vector features are legal, so a pipeline that flattens image features by mistake still builds a valid graph. State your expectation explicitly:

python
flat = tgx.Graph(node_features=x.reshape(N, -1), edge_index=edge_index, node_labels=y)
print(flat.feature_shape)                            # (192,)

try:
    tgx.assert_tensor_native(flat, min_rank=4)       # rank counts the node axis
except GraphValidationError as err:
    print(err)
else:
    raise AssertionError("rank 2 features should be rejected")

min_rank is the number of dimensions of the whole node_features tensor, node axis included. For [N, C, H, W] use min_rank=4; the default of 3 would also accept [N, C, L].

Check the layout yourself

Rank says nothing about axis order. Channels-last images pass every check above:

python
channels_last = x.permute(0, 2, 3, 1)                # [N, 8, 8, 3]
accepted = tgx.Graph(node_features=channels_last, edge_index=edge_index)
tgx.assert_tensor_native(accepted, min_rank=4)       # passes


def require_layout(graph, shape):
    if graph.feature_shape != shape:
        raise ValueError(f"expected per-node shape {shape}, got {graph.feature_shape}")


require_layout(g, (3, 8, 8))
try:
    require_layout(accepted, (3, 8, 8))
except ValueError as err:
    print(err)        # expected per-node shape (3, 8, 8), got (8, 8, 3)
else:
    raise AssertionError("the layout check should fail")

A tensor layer built for 3 channels raises a PyTorch channel-count RuntimeError on this input. If the second axis happens to have the expected size, it runs and silently treats the wrong axis as channels.

Topology problems need their own check too:

python
def topology_report(graph):
    src, dst = graph.edge_index
    degree = torch.bincount(torch.cat([src, dst]), minlength=graph.num_nodes)
    return {
        "self_loops": int((src == dst).sum()),
        "duplicate_edges": graph.num_edges - torch.unique(graph.edge_index, dim=1).size(1),
        "isolated_nodes": int((degree == 0).sum()),
    }


print(topology_report(g))
# {'self_loops': 0, 'duplicate_edges': 0, 'isolated_nodes': 94}

Whether any of these is a bug depends on your problem. If the graph must be connected, tgraphx.algorithms.is_connected(edge_index, num_nodes) tests that, ignoring edge direction.

Node-mask leakage checks need keyword arguments

check_leakage reports overlap between node masks and, by default, raises LeakageError (a ValueError):

python
train_mask = torch.zeros(N, dtype=torch.bool)
train_mask[:60] = True
val_mask = torch.zeros(N, dtype=torch.bool)
val_mask[60:80] = True
test_mask = ~(train_mask | val_mask)

result = tgx.check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
print(result["ok"], result["counts"])     # True {'train': 60, 'val': 20, 'test': 20}

leaky_val = val_mask.clone()
leaky_val[50:60] = True                   # ten training nodes
try:
    tgx.check_leakage(train_mask=train_mask, val_mask=leaky_val, test_mask=test_mask)
except ValueError as err:
    print(err)                            # train_mask and val_mask overlap on 10 nodes
else:
    raise AssertionError("the overlap should be reported")

Do not pass the three masks positionally. The signature is check_leakage(graph=None, train_mask=None, val_mask=None, test_mask=None, *, strict=True), so the first positional mask lands in graph and the others shift by one place. An overlapping split can then come back as ok: True.

The masks must be boolean. Index tensors are not rejected up front: they are cast with .bool() and compared position by position. If two of them differ in length (and neither has length 1), the call fails with a shape RuntimeError; with equal lengths, the reported overlaps and counts mean nothing.

You can also pass a graph that carries the masks, but then confirm that all three were actually found, because a check with no masks also reports ok:

python
def require_disjoint_splits(graph):
    result = tgx.check_leakage(graph)     # reads train_mask, val_mask, test_mask
    if set(result["counts"]) != {"train", "val", "test"}:
        raise ValueError(f"only checked: {sorted(result['counts'])}")
    return result


masked = tgx.Graph(node_features=x, edge_index=edge_index, node_labels=y,
                   train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
require_disjoint_splits(masked)

This guard matters if you use the RandomNodeSplit or FixedSplit transforms: in 1.5.1 they store masks under keys that graph.train_mask does not read. The check covers node-mask overlap only, not test edges visible during message passing or duplicated samples; see masks, splits, and leakage. validate_split_policy does not inspect masks at all: it validates the name of the setting you declare (transductive, inductive or semi_supervised) and returns a description.

Inspect batches

tgx.debug_batch returns a dictionary describing a batch (it does not print anything); tgx.batch_summary is the same function:

python
batch = tgx.GraphBatch([g, g])
info = tgx.debug_batch(batch)
print(info["num_nodes"], info["num_edges"], info["node_features_shape"])
# 200 8 [200, 3, 8, 8]

Audit run directories

audit_run_dir looks at one directory. It expects run_metadata.json, metrics_summary.json and benchmark_summary.json there. Every .json file in the directory must hold a JSON object; a file over 5 MB, or a top-level key holding a list of more than 5,000 values, is reported as an issue. It also fails if run_metadata.json has no tgraphx_version or seed key, which is why the example passes both. dashboard_audit is an alias, so loop over several runs yourself:

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    run = Path(tmp) / "exp_001"
    run.mkdir()
    tgx.write_run_metadata(str(run / "run_metadata.json"),
                           seed=0, tgraphx_version=tgx.__version__)
    tgx.write_metrics_summary(str(run / "metrics_summary.json"), epochs=0)
    incomplete = tgx.audit_run_dir(run)
    print(incomplete["ok"], incomplete["files_missing"])   # False ['benchmark_summary.json']

    tgx.write_benchmark_results(str(run / "benchmark_summary.json"), seed=0)
    for run_dir in sorted(Path(tmp).iterdir()):
        audit = tgx.audit_run_dir(run_dir)
        print(run_dir.name, audit["ok"], audit["issues"])  # exp_001 True []

A passing audit means the expected files exist, the JSON passes these form checks and run_metadata.json has both keys. It says nothing about whether the numbers are right. See what TGraphX runs record.

Practical recommendation

Put the checks in one function and call it wherever data enters your pipeline:

python
def check_dataset(graph, node_shape):
    graph.validate()
    tgx.validate_graph(graph, strict=True, check_finite=True)
    require_layout(graph, node_shape)
    require_disjoint_splits(graph)


check_dataset(masked, (3, 8, 8))

The shape-checked experiment skeleton shows validate_graph and keyword check_leakage calls inside a complete script. For mistakes that pass all of these checks and still produce wrong numbers, see silent shape errors.

FAQ

Q: Will TGraphX validate automatically when I construct a graph?
A: Yes. The constructor raises TypeError or ValueError for the problems listed in the first section.

Q: Does validation slow down training?
A: The checks in this article run when you build a graph or call them, so a training loop that reuses one graph does not repeat them. The bounds checks scan edge_index, so their cost grows with the number of edges.

Q: Can I skip validation for very large graphs?
A: validate_graph runs only if you call it. The constructor has no option to turn its checks off.

Q: What does check_graph_invariants add over validate_graph?
A: Nothing. It is an alias.

Q: What about debugging the model, not just the data?
A: Run one forward and backward pass on a small graph and check the output shape and that gradients are finite. debug_batch helps you see what a loader actually delivers.