The Hidden Cost of Silent Shape Errors in GNN Experiments
A GNN that trains without errors and shows a decreasing loss may still be learning from wrong data. Besides the usual tensor shapes, graph code has index structures (edge_index, the batch vector, masks) that must stay aligned with the features and labels, and many ways of breaking that alignment raise nothing.
This article shows which mistakes are loud and which are silent, what TGraphX checks for you, and what a quick overfit test can and cannot reveal. Examples tested with TGraphX 1.5.1; the code blocks run in order and share variables.
What Makes a Shape Error "Silent"
A loud error raises an exception, for example mat1 and mat2 shapes cannot be multiplied. You fix it and move on.
A silent error produces no exception. The code runs, the loss decreases, and training appears to work. The model is learning something, just not what you intended. You may only notice when results do not match a baseline.
Common Silent Errors in GNN Code
1. Transposed edge index
The convention is edge_index of shape [2, E]: row 0 holds source ids, row 1 destination ids. An [E, 2] tensor is a common mistake. If your aggregation code reads edge_index[0] expecting all source ids, it gets the first row instead, which is the two endpoints of the first edge.
import warnings
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph, GraphBatch
torch.manual_seed(0)
N, E, d = 8, 20, 4
x = torch.randn(N, d)
src = torch.randint(0, N, (E,))
dst = torch.randint(0, N, (E,))
edge_index = torch.stack([src, dst], dim=0) # [2, E] correct
transposed = torch.stack([src, dst], dim=1) # [E, 2] wrong
# Hand-written aggregation that indexes rows
messages = x[transposed[0]]
agg = torch.zeros(N, d).index_add_(0, transposed[1], messages)
assert messages.shape == (2, d) # 2 "edges" used instead of 20
assert agg.shape == (N, d) # output shape looks fine
Unpacking with src, dst = transposed would raise for E other than 2, but row indexing does not. What TGraphX does depends on where the tensor enters:
# The Graph constructor rejects it
try:
Graph(node_features=x, edge_index=transposed)
except ValueError as exc:
print(exc) # edge_index must have shape [2, E], got (20, 2)
else:
raise AssertionError("expected a ValueError")
# A layer called directly may not re-check
layer = tgx.LinearMessagePassing((d,), (3,))
assert layer(x, transposed).shape == (N, 3) # no error
In TGraphX 1.5.1, GCNConv, GATv2Conv and the tensor SAGE, GAT and GIN layers also reject [E, 2]. LinearMessagePassing, ConvMessagePassing and AttentionMessagePassing do not. No check can help when E == 2: a transposed [2, 2] tensor is still a valid [2, 2] edge index.
2. Wrong gather or scatter index
Messages are gathered at the source and summed at the destination. Using the same row for both is an easy slip, and every shape stays correct. A toy graph with a hand-computed answer exposes it:
edges = torch.tensor([[0, 1, 2], # source
[2, 2, 3]]) # destination
h = torch.tensor([[1.0], [10.0], [100.0], [1000.0]])
s, t = edges
right = torch.zeros(4, 1).index_add_(0, t, h[s])
wrong = torch.zeros(4, 1).index_add_(0, s, h[s]) # source index used twice
assert right.flatten().tolist() == [0.0, 0.0, 11.0, 100.0]
assert wrong.flatten().tolist() == [1.0, 10.0, 100.0, 0.0]
assert right.shape == wrong.shape # nothing complains
Not every scatter mistake is silent. Calling index_add_ along dim=1 of an [N, d] buffer with edge indices normally raises (Number of indices (20) should be equal to source.size(dim): (4) for the sizes above), because the index length must equal the size of that dimension.
3. Features, labels and edge ids out of step
Shuffling or filtering node features without doing the same to the labels is the classic case. In a graph there is a third thing to keep in step: edge_index refers to node positions, so reordering nodes means relabelling the edges too.
conv = tgx.GCNConv(d, d).eval()
perm = torch.randperm(N) # new position k holds old node perm[k]
inverse = torch.argsort(perm) # old node id -> new position
out = conv(x, edge_index)
consistent = conv(x[perm], inverse[edge_index]) # features and edge ids moved
broken = conv(x[perm], edge_index) # edges still use old positions
assert torch.allclose(consistent, out[perm], atol=1e-5)
assert not torch.allclose(broken, out[perm], atol=1e-5)
The labels have to move with the same permutation (y[perm]). Nothing in the forward pass looks at labels, so a missed y[perm] produces no error at all.
4. Silent broadcasting in the loss
Node regression is a frequent source: a head returns [N, 1] while the targets are [N].
pred = torch.randn(N, 1) # model head output
target = torch.randn(N) # regression targets
assert (pred - target).shape == (N, N) # broadcast, no warning
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
bad_loss = F.mse_loss(pred, target) # only a UserWarning
good_loss = F.mse_loss(pred.squeeze(-1), target)
assert len(caught) == 1 and not torch.isclose(bad_loss, good_loss)
5. Wrong reshape order
With tensor-valued nodes, a view with the axes in the wrong order succeeds because only the element count is checked.
maps = torch.arange(2 * 3 * 4 * 5).view(2, 3, 4, 5) # [N, C, H, W]
flat = maps.reshape(2, -1)
back_wrong = flat.view(2, 5, 4, 3) # "now it is [N, W, H, C]"
assert not torch.equal(back_wrong.permute(0, 3, 2, 1), maps) # it is not
assert torch.equal(flat.view(2, 3, 4, 5), maps)
To move channels around, use permute; use view or reshape only to merge or split axes whose order you are keeping.
The Bug Flow Diagram
Silent Shape or Alignment Error Flow
─────────────────────────────────────────────────────────
Raw data → preprocessing → [ERROR INTRODUCED HERE]
↓
Tensors are misaligned
↓
Graph constructed → no error
(shapes and counts still match)
↓
Forward pass runs → no error
(output has the right shape)
↓
Loss computed → no error
(model learns from corrupted data)
↓
Loss decreases over epochs
↓
Evaluation: results are poor
↓
"Model needs more capacity" ← possibly the wrong diagnosis
"Learning rate is wrong" ← possibly the wrong diagnosis
─────────────────────────────────────────────────────────
What the TGraphX Graph Constructor Catches
Graph checks the following when you build it:
node_featureshas at least two dimensionsedge_indexis[2, E], of typelong, with ids in[0, N)(negative ids are rejected)edge_weighthas lengthE, andedge_featureshas leading sizeEnode_labelshas leading sizeN,edge_labelsleading sizeE, and masks passed astrain_mask=,val_mask=ortest_mask=have lengthN- the tensors are on the same device as
node_features(masks are the exception: they are moved there instead of being rejected)
It does not catch labels in the wrong order, a wrong gather or scatter index inside your own layer, a wrong reshape, broadcasting in your loss, or a transposed [2, 2] edge index. It also does not run again when you assign to an attribute later. g.validate() re-checks features, edge_index, edge tensors, labels and devices after you modify a graph, but it does not re-check masks. tgx.validate_graph, used in the audit function below, does report a train, validation or test mask of the wrong length.
The range check matters even if your shapes are right: some layers called on raw tensors (including LinearMessagePassing and ConvMessagePassing) accept a negative source id and index from the end, although a negative destination id raises there. For the design argument behind these checks, see tensor shapes as an API contract.
The Five-Graph Overfit Test
Take a handful of training graphs and train on them until the loss stops moving. A model with enough capacity, correctly wired, can usually drive the training loss close to zero.
Note how the batch is built: GraphBatch takes a list in its constructor.
def small_graph(n=8):
random_edges = torch.randint(0, n, (2, 3 * n))
self_loops = torch.arange(n).repeat(2, 1)
features = torch.randn(n, 8)
return Graph(node_features=features,
edge_index=torch.cat([random_edges, self_loops], dim=1),
node_labels=features[:, :3].argmax(dim=1)) # label follows features
train_graphs = [small_graph() for _ in range(5)]
mini_batch = GraphBatch(train_graphs)
def overfit(batch, labels, steps=150):
torch.manual_seed(1)
model = tgx.build_model("node_classification", layer="linear", in_shape=(8,),
hidden_shape=(32,), num_layers=2, num_classes=3)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
model.train()
for _ in range(steps):
optimizer.zero_grad()
out = model(batch.node_features, batch.edge_index)
loss = F.cross_entropy(out, labels)
loss.backward()
optimizer.step()
return loss.item()
aligned = overfit(mini_batch, mini_batch.node_labels)
shuffled = mini_batch.node_labels[torch.randperm(mini_batch.num_nodes)]
misaligned = overfit(mini_batch, shuffled)
print(f"aligned labels: {aligned:.3f}")
print(f"shuffled labels: {misaligned:.3f}")
assert aligned < 0.05 and misaligned < 0.05
Output from one CPU run:
aligned labels: 0.000
shuffled labels: 0.000
The second line is the important limit: an overfit test does not detect misaligned labels. Here each label is determined by the node's features and shuffling breaks that link, yet a model with enough capacity simply memorises the wrong labels. It may need more steps to get there, but a threshold on the final loss does not show that. The test checks that the forward pass, loss and optimiser are connected well enough to fit something; data alignment needs its own checks, such as the permutation test above or spot-checking node ids against the source data.
A failed test is also not proof of a bug. Here every node has the same features and the same kind of neighbourhood but different labels, so message passing cannot tell them apart:
ring = torch.arange(6)
ring_edges = torch.stack([torch.cat([ring, ring]),
torch.cat([(ring + 1) % 6, ring])]) # ring + self-loops
twins = Graph(node_features=torch.ones(6, 8), edge_index=ring_edges,
node_labels=torch.tensor([0, 1, 2, 0, 1, 2]))
stuck = overfit(GraphBatch([twins]), twins.node_labels)
print(f"identical nodes: {stuck:.3f}") # ln(3) = 1.099
assert stuck > 1.0
Treat a failure as a strong hint to check the data and the forward pass, after ruling out the optimiser settings, heavy dropout or regularisation, and limits of what your architecture can distinguish.
Practical Shape Audit Checklist
Before a long training run, audit each graph (or a sample of them):
def audit(g, num_classes):
g.validate() # constructor checks, except masks
report = tgx.validate_graph(g, check_finite=True) # mask lengths, NaN/Inf features
assert report["ok"], report["issues"]
assert g.node_labels.dtype == torch.long
assert 0 <= int(g.node_labels.min()) and int(g.node_labels.max()) < num_classes
no_input = g.num_nodes - torch.unique(g.edge_index[1]).numel()
print(f"node_features {tuple(g.node_features.shape)}, "
f"edge_index {tuple(g.edge_index.shape)}, "
f"nodes without incoming edges: {no_input}")
audit(train_graphs[0], num_classes=3)
If the graph carries splits, also check that the masks do not overlap, passing them by keyword: tgx.check_leakage(train_mask=..., val_mask=..., test_mask=...).
For a pattern-by-pattern catalogue, see silent failure patterns and how to detect them.
The Compound Cost
Silent errors are expensive because they consume experiment cycles. Picture the sequence: a long training run gives poor results, you conclude the model needs more capacity, you add layers, run again, get poor results again, and only much later find that the edge index was transposed from the start.
The cost is not only time. Once you find a silent error, you also have to ask which earlier results it touched.
Construction-time validation, small tests with known answers and the overfit test reduce the chance of this. None of them is complete on its own, but each one moves some failures from silent to loud.