TGraphX › Insights › Silent GNN Failures: Shape-Compatible Bugs That Raise No Error
← Back to Insights

Silent GNN Failures: Shape-Compatible Bugs That Raise No Error

Topic: Shape validation, testing and debugging

Graph neural network code fails in two ways. Loud failures, such as a RuntimeError, an IndexError or a CUDA assertion, are unpleasant but informative. Silent failures are worse: the program runs, the loss goes down, the metrics look plausible, and the numbers are wrong.

A genuine shape mismatch usually does raise. The bugs that stay silent are the ones where every shape is right and the meaning is not. This article is a catalogue of such patterns, each with a way to detect it. Where TGraphX checks something for you, it says so; most of these patterns it cannot see. Examples tested with TGraphX 1.5.1 on CPU. Run the first block, then any pattern.

python
import warnings

import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph, GraphBatch, NeighborLoader

torch.manual_seed(0)

Overview

# Pattern Raises? How to detect it
1 Features and labels indexed in different orders No Index everything with one tensor, assert alignment
2 Mini-batch loss on the wrong rows No Use seed_logits / seed_y
3 Edge list reshaped instead of transposed, or reversed No Test the direction on a tiny graph
4 Subgraph edges not relabelled Only if an id is out of range Compare endpoint features before and after
5 Softmax or pooling over the wrong axis No Assert what must sum to one
6 [N, 1] against [N] in a regression loss Warning at most Assert equal shapes
7 Channels-last maps with H == C No Keep one layout, check at the boundary
8 Nodes that receive nothing No Count incoming edges
9 Masks ignored or overlapping No Check masks explicitly
10 Target columns in the wrong order No Select columns by name

1. Features and Labels Indexed in Different Orders

Give node i the feature i and the label 10 * i, so that any mix-up is visible:

python
x_full = torch.arange(50).float().unsqueeze(1)        # [50, 1]
labels = torch.arange(50) * 10                        # [50]
sampled = torch.tensor([5, 12, 23, 7])

x_batch = x_full[sorted(sampled.tolist())]            # nodes 5, 7, 12, 23
y_batch = labels[sampled]                             # nodes 5, 12, 23, 7
print(x_batch.squeeze(1).long().tolist())             # [5, 7, 12, 23]
print((y_batch // 10).tolist())                       # [5, 12, 23, 7]

Row 0 agrees by coincidence; rows 1 to 3 pair features with another node's label. Both tensors have four rows, so nothing complains. Use one index tensor for everything and assert it while you debug:

python
x_batch, y_batch = x_full[sampled], labels[sampled]
assert torch.equal(x_batch.squeeze(1).long() * 10, y_batch)

The same trap hides in helpers that reorder nodes. tgx.induced_subgraph returns nodes in ascending original-id order, whatever order you pass:

python
g = Graph(node_features=x_full, edge_index=torch.randint(0, 50, (2, 200)),
          node_labels=labels)
sub = tgx.induced_subgraph(g, sampled)
ids = sub.metadata["sampling"]["original_node_ids"]
print(ids.tolist())                                   # [5, 7, 12, 23]
assert torch.equal(sub.node_labels, labels[ids])      # its own tensors stay aligned

Pair the subgraph's rows with ids, not with the list you passed in.


2. Mini-Batch Loss on the Wrong Rows

A sampled mini-batch contains the seed nodes plus their neighbours. Some libraries put the seeds first; TGraphX's NeighborLoader does not, so logits[:batch_size] selects the wrong nodes with exactly the right shape:

python
g = Graph(node_features=torch.randn(50, 16), edge_index=torch.randint(0, 50, (2, 200)),
          y=torch.randint(0, 4, (50,)), train_mask=torch.arange(50) % 2 == 0)
loader = NeighborLoader(g, fanouts=[5, 3], mask=g.train_mask, batch_size=8, seed=0)
batch = next(iter(loader))

conv = tgx.GCNConv(16, 4)
logits = conv(batch.node_features, batch.edge_index)  # one row per subgraph node
print(batch.num_nodes, batch.batch_size)
print(batch.seed_local_indices.tolist())              # where the seeds really are

wrong = logits[:batch.batch_size]
right = batch.seed_logits(logits)
assert wrong.shape == right.shape and not torch.equal(wrong, right)
loss = F.cross_entropy(right, batch.seed_y)           # seed_y is in the same order

Also pass mask=. With mask=None, NeighborLoader uses every node as a seed, validation and test nodes included; it does not read g.train_mask by itself.


3. Edge Lists Reshaped Instead of Transposed

Edges often arrive as [E, 2] pairs. reshape(2, -1) gives the expected shape and a different graph:

python
pairs = torch.tensor([[0, 1], [1, 2], [2, 3]])        # (source, destination) rows
correct = pairs.t()
scrambled = pairs.reshape(2, -1)
print(correct.tolist())                               # [[0, 1, 2], [1, 2, 3]]
print(scrambled.tolist())                             # [[0, 1, 1], [2, 2, 3]]
Graph(node_features=torch.randn(4, 8), edge_index=scrambled)   # accepted

Direction is just as quiet. In TGraphX, as in PyTorch Geometric's default, messages travel from edge_index[0] to edge_index[1]. A perturbation test on a one-edge graph shows what your model actually does:

python
conv = tgx.GCNConv(8, 8)                              # adds self-loops
x = torch.randn(4, 8)
one_edge = torch.tensor([[0], [1]])                   # 0 -> 1

def rows_changed_by(node):
    x2 = x.clone()
    x2[node] += 1.0
    with torch.no_grad():
        diff = (conv(x2, one_edge) - conv(x, one_edge)).abs().sum(1)
    return (diff > 1e-6).nonzero().flatten().tolist()

print(rows_changed_by(0))                             # [0, 1]: node 0 reaches node 1
print(rows_changed_by(1))                             # [1]: nothing flows back to node 0
assert rows_changed_by(0) == [0, 1] and rows_changed_by(1) == [1]

4. Subgraph Edges That Keep the Original Ids

When you slice node features by hand, edge ids must be renumbered too. If an old id is out of range, the Graph constructor raises. If every old id happens to be in range, nothing does:

python
full_x = torch.randn(100, 16)
keep = torch.tensor([3, 0, 2, 1])
sub_x = full_x[keep]                                  # row 0 is now original node 3
old_edges = torch.tensor([[0, 1], [1, 2]])            # 0->1 and 1->2, ORIGINAL ids

Graph(node_features=sub_x, edge_index=old_edges)      # accepted: every id is < 4
assert not torch.equal(sub_x[old_edges], full_x[old_edges])   # wrong endpoints

new_id = torch.full((100,), -1)
new_id[keep] = torch.arange(len(keep))
new_edges = new_id[old_edges]
print(new_edges.tolist())                             # [[1, 3], [3, 2]]
assert torch.equal(sub_x[new_edges], full_x[old_edges])       # the detector

The last assertion works for any relabelling code. tgx.induced_subgraph and tgx.k_hop_subgraph do the renumbering for you.


5. The Wrong Axis

For [N, num_classes] logits, a softmax over dim=0 normalises each class across nodes:

python
logits = torch.randn(6, 3)
wrong = F.softmax(logits, dim=0)
right = F.softmax(logits, dim=1)
print(wrong.sum(dim=1))                               # not ones
assert torch.allclose(right.sum(dim=1), torch.ones(6))
assert not torch.allclose(wrong.sum(dim=1), torch.ones(6))

Pooling has the same problem in a batch of graphs. A mean over dim=0 mixes all graphs into one vector; pass the batch vector instead:

python
node_out = torch.randn(7, 4)
which_graph = torch.tensor([0, 0, 0, 1, 1, 1, 1])
mixed = node_out.mean(dim=0)                          # [4]: both graphs together
per_graph = tgx.global_mean_pool(node_out, which_graph)
print(mixed.shape, per_graph.shape)                   # torch.Size([4]) torch.Size([2, 4])
assert torch.allclose(per_graph[0], node_out[:3].mean(0))

A general detector: change the features of graph 1 and confirm that the output for graph 0 does not move. When a matrix is square (N == D), also check reductions by hand, because dim=0 and dim=1 return the same shape.


6. Broadcasting in a Regression Loss

A model output of shape [N, 1] against a target of shape [N] broadcasts to [N, N]. F.mse_loss warns; a hand-written loss says nothing:

python
pred, target = torch.randn(10, 1), torch.randn(10)

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    F.mse_loss(pred, target)
print(caught[0].category.__name__)                    # UserWarning

by_hand = (pred - target) ** 2
print(by_hand.shape)                                  # torch.Size([10, 10])

loss = F.mse_loss(pred.squeeze(1), target)            # shapes now match

Assert pred.shape == target.shape before every regression loss, or turn warnings into errors in your tests.


7. Channels-Last Feature Maps

TGraphX's spatial layers expect [N, C, H, W] and do not detect another layout. A channels-last [N, H, W, C] tensor is read with H as the channel count, so PyTorch raises a channel-count error only when H differs from C. When H equals C nothing is raised, and if W is equal too even the output shape is correct:

python
maps = torch.randn(10, 8, 8, 8)                       # [N, C, H, W], C = H = W
channels_last = maps.permute(0, 2, 3, 1)              # [N, H, W, C], same shape
layer = tgx.TensorGraphSAGELayer(8, 16)
edges = torch.randint(0, 10, (2, 40))

out_good = layer(maps, edges)
out_bad = layer(channels_last, edges)
assert out_good.shape == out_bad.shape and not torch.allclose(out_good, out_bad)

wide = torch.randn(10, 8, 8, 16)                      # C = H = 8, but W = 16
wide_good = layer(wide, edges)
wide_bad = layer(wide.permute(0, 2, 3, 1), edges)     # [10, 8, 16, 8]: also accepted
print(tuple(wide_good.shape))                         # (10, 16, 8, 16)
print(tuple(wide_bad.shape))                          # (10, 16, 16, 8)
assert wide_good.shape != wide_bad.shape

In the second case, comparing the full per-node shape of the input or the output with the expected one still catches the mistake. In the first, no shape check can. Convert once, where data enters the pipeline, and check the layout there with a case whose C, H and W differ.


8. Nodes That Receive Nothing

A node with no incoming edge receives no message, and what comes out for it depends on the layer. With default settings, LinearMessagePassing returns zeros. TensorGATLayer, whose default is add_self_loops=False, returns only its output bias: zeros in a new layer, other values once the bias has been trained. ConvMessagePassing has no self term either, but its CNN still runs on the all-zero aggregate, so the output is usually not zero. In eval mode with the default residual=False, that output is the same whatever the node's own features are:

python
maps = torch.randn(3, 3, 4, 4)
edges = torch.tensor([[0], [1]])                      # only node 1 receives

out = tgx.TensorGATLayer(3, 8)(maps, edges)           # new layer: bias is zero
print((out.flatten(1) == 0).all(dim=1).tolist())      # [True, False, True]

with_loops = tgx.TensorGATLayer(3, 8, add_self_loops=True)(maps, edges)
assert not (with_loops.flatten(1) == 0).all(dim=1).any()

conv = tgx.ConvMessagePassing((3, 4, 4), (16, 4, 4), dropout_prob=0.0).eval()
changed = maps.clone()
changed[2] += 1.0                                     # node 2: no edges at all
with torch.no_grad():
    before, after = conv(maps, edges)[2], conv(changed, edges)[2]
assert not (before == 0).all()                        # not a zero row
assert torch.allclose(before, after)                  # own features ignored

So do not look for zero rows to find these nodes. Count incoming edges with torch.bincount(edge_index[1], minlength=num_nodes) and decide what isolated nodes should do.


9. Masks That Are Ignored or Overlap

tgx.fit does not read node masks. Given a graph with masks, it computes the loss on every node:

python
N = 40
g = Graph(node_features=torch.randn(N, 8), edge_index=torch.randint(0, N, (2, 160)),
          y=torch.randint(0, 3, (N,)),
          train_mask=torch.arange(N) < 24,
          val_mask=(torch.arange(N) >= 24) & (torch.arange(N) < 32),
          test_mask=torch.arange(N) >= 32)
model = tgx.build_model("node_classification", layer="linear", in_shape=(8,),
                        hidden_shape=(16,), num_layers=2, num_classes=3)
seen = []

def counting_loss(out, target):
    seen.append(len(target))
    return F.cross_entropy(out, target)

tgx.fit(model, [GraphBatch([g])], epochs=1, loss_fn=counting_loss,
        optimizer=torch.optim.Adam(model.parameters()), device="cpu")
print(seen)                                           # [40], not 24
assert seen == [N]

# What you meant
loss = F.cross_entropy(model(g.x, g.edge_index)[g.train_mask], g.y[g.train_mask])

For overlapping masks, TGraphX has check_leakage. Call it with keyword arguments; it compares boolean node masks only:

python
bad_val_mask = torch.arange(N) >= 20                  # overlaps train and test
report = tgx.check_leakage(train_mask=g.train_mask, val_mask=bad_val_mask,
                           test_mask=g.test_mask, strict=False)
print(report["ok"], report["overlaps"])
assert not report["ok"]

for mask in (g.train_mask, g.val_mask, g.test_mask):
    assert mask.dtype == torch.bool and mask.any()    # non-empty: check it yourself

A validation mask that accidentally covers training nodes does not raise either. It makes validation scores look better than they are and can steer early stopping and model selection. Positional calls, index tensors instead of boolean masks, and graphs without readable masks all make check_leakage results meaningless, including a false ok=True; see masks, splits and leakage.


10. Target Columns in the Wrong Order

In multi-task problems, pred and y can both be [N, 3] with different columns. No shape check can find this. Select columns by name:

python
model_outputs = ["toxicity", "solubility", "binding"]
file_columns = ["solubility", "toxicity", "binding"]  # order in the label file
raw = torch.randn(50, 3)

y = raw[:, [file_columns.index(name) for name in model_outputs]]
assert torch.equal(y[:, 0], raw[:, 1])                # toxicity

g = Graph(node_features=torch.randn(50, 16), node_labels=y,
          metadata={"label_names": model_outputs})

Storing the names in metadata documents the order; it does not check it.


What TGraphX Does Reject

These fail loudly, which is what you want:

python
def show_error(make):
    try:
        make()
    except (ValueError, RuntimeError) as err:
        print(f"{type(err).__name__}: {str(err)[:110]}")
    else:
        raise AssertionError("expected an error")

one_edge = torch.tensor([[0], [1]])

# Edge ids out of range
show_error(lambda: Graph(node_features=torch.randn(4, 8), edge_index=torch.tensor([[0], [7]])))

# Different per-node shapes in one batch
show_error(lambda: GraphBatch([Graph(node_features=torch.randn(3, 4, 8, 8), edge_index=one_edge),
                               Graph(node_features=torch.randn(3, 4, 4, 4), edge_index=one_edge)]))

# Vector features given to a spatial layer
show_error(lambda: tgx.TensorGraphSAGELayer(16, 32)(torch.randn(5, 16), one_edge))

# Wrong channel count: this one is PyTorch's own convolution error
show_error(lambda: tgx.TensorGINLayer(16, 64)(torch.randn(5, 32, 8, 8), one_edge))

The first is checked by the Graph constructor, the second by GraphBatch, the third by the layer's rank check. The layer does not check the channel count itself, so the fourth is a RuntimeError from Conv2d. Layers called on raw tensors check less than the constructor (LinearMessagePassing, for example, accepts a transposed [E, 2] edge index), so validate data by building a Graph. tgx.validate_graph is useful after you modify a graph, but it checks less than the constructor; see shape-aware validation.

What the doctor command does

bash
python -m tgraphx doctor

It prints the TGraphX, Python and PyTorch versions, CUDA availability and which optional dependencies are installed. It does not run a forward pass and does not look at your data or your model, so it cannot find any of the bugs above.


Checklist

  1. Index features, labels and masks with the same tensor, and assert it on a case where mix-ups are visible.
  2. In mini-batches, pass mask= to the loader and use batch.seed_logits(out) with batch.seed_y.
  3. Build edge_index with .t(), not reshape, and test message direction once.
  4. After relabelling, assert sub_x[new_edges] == full_x[old_edges].
  5. Check softmax and pooling axes; pool batches with the batch vector.
  6. Require pred.shape == target.shape.
  7. Keep [N, C, H, W] and test with unequal C, H, W.
  8. Count incoming edges per node.
  9. Check that masks are boolean, non-empty and disjoint, and do not use fit() for masked node tasks.
  10. Select target columns by name.

Limitations

This catalogue does not cover numerical problems (exploding gradients, NaN), which need monitoring of values rather than shapes, nor custom layers with their own indexing bugs, nor problems in how a dataset was built, such as duplicated or near-duplicated samples across splits. Passing all the checks does not make a result correct.

Related Articles