Tensor Shapes as an API Contract in Graph Learning
Shape mismatches in neural networks fail in one of two ways: loudly, with an error that points you to the right line of code; or silently, producing results that look plausible but are computed from wrong data. Graph neural networks have more moving parts than standard feed-forward networks (node features, edge indices, batching offsets), and the silent failures are correspondingly harder to diagnose. Why this matters for tool design is the subject of libraries that fail honestly.
This article argues that tensor shapes should be treated as an explicit API
contract and enforced when an object is built. TGraphX's Graph class serves
as the concrete example. Examples tested with TGraphX 1.5.1; the code blocks
run in order.
The Silent Failure Problem
Suppose hand-rolled message passing receives an edge index of shape [E, 2]
instead of [2, E]. Code that unpacks src, dst = edge_index raises (unless
E is 2). Code that indexes rows, edge_index[0] and edge_index[1], does
not: it silently reads the two endpoints of the first edge as the source ids and
those of the second edge as the destination ids. The forward pass runs on the
wrong topology, and nothing stops training.
This class of error is insidious because:
- No exception is raised.
- The symptom (weak or unstable accuracy) does not point at the cause.
- It looks like a modelling problem, so it is easy to search in the wrong place.
A shape contract removes the problem at the boundary: the wrong object cannot be built in the first place.
What a Shape Contract Looks Like
A shape contract says: for this object to be valid, its parts must have these
shapes, in this order, with this consistency. For TGraphX's Graph:
node_features: [N, ...] at least 2-D; first dim is the node count
edge_index: [2, E] long; row 0 = source, row 1 = destination; ids in [0, N)
edge_weight: [E]
edge_features: [E, ...] at least 2-D
node_labels: [N, ...]
edge_labels: [E, ...]
train/val/test masks: length N
all of these on one device (masks are moved there for you)
The same contract as a diagram:
Shape Contract for Graph Construction
──────────────────────────────────────
node_features [N, *] ──── N must equal ────► node_labels [N, *]
│
│ N = number of nodes
│
edge_index [2, E] ──── E must equal ────► edge_features [E, *]
│
│ row 0: source node indices ∈ [0, N)
│ row 1: destination node indices ∈ [0, N)
│
All tensors must be on the same device
(masks are moved to it, not rejected).
──────────────────────────────────────
Each violation fails as soon as you construct the object:
import torch
import tgraphx as tgx
from tgraphx import Graph
x = torch.randn(5, 3, 16, 16)
edge_index = torch.tensor([[0, 1, 2, 3],
[1, 2, 3, 4]])
violations = {
"transposed edge_index": dict(node_features=x, edge_index=edge_index.t()),
"node id out of range": dict(node_features=x, edge_index=edge_index + 1),
"float edge_index": dict(node_features=x, edge_index=edge_index.float()),
"edge feature count": dict(node_features=x, edge_index=edge_index,
edge_features=torch.randn(3, 8)),
"label count": dict(node_features=x, node_labels=torch.zeros(4)),
"mask length": dict(node_features=x,
train_mask=torch.ones(4, dtype=torch.bool)),
"1-D node features": dict(node_features=torch.randn(5)),
}
for name, kwargs in violations.items():
try:
Graph(**kwargs)
except (ValueError, TypeError) as exc:
print(f"{name}: {type(exc).__name__}: {exc}")
else:
raise AssertionError(f"{name} was accepted")
Why Enforce at Construction, Not at Forward Pass?
The alternative is to let each layer discover problems during the forward pass.
For plain tensors that is how PyTorch works: shape errors surface when an
operation such as F.linear receives mismatched inputs.
For graph objects this is a poor place to find out. A graph is often built once and reused many times, so with forward-pass checks only:
- the error surfaces late, deep inside a layer;
- it may appear only when a particular batch reaches it;
- the message talks about a low-level tensor operation, not about your graph.
Checking at construction reports the problem where you have the most context: you just assembled the tensors, and the stack trace points at that code.
The Contract Holds Only Where It Is Checked
A layer has a contract of its own, about rank and channels:
sage = tgx.TensorGraphSAGELayer(3, 8)
assert sage(x, edge_index).shape == (5, 8, 16, 16)
try:
sage(torch.randn(5, 3), edge_index) # vectors into a spatial layer
except ValueError as exc:
print(exc)
else:
raise AssertionError("expected a ValueError")
It does not necessarily repeat the graph's checks. Layers take raw tensors, and
some TGraphX 1.5.1 layers, LinearMessagePassing and ConvMessagePassing
among them, do not validate edge_index when called directly. In these two
layers a negative source id indexes from the end without an error (a negative
destination id raises):
linear = tgx.LinearMessagePassing((6,), (4,))
negative = torch.tensor([[-1, 0], # source row holds -1
[1, 2]])
assert linear(torch.randn(5, 6), negative).shape == (5, 4) # no error
try:
linear(torch.randn(5, 6), negative.flip(0)) # now a destination is -1
except RuntimeError as exc:
print(exc)
else:
raise AssertionError("expected a RuntimeError")
So build a Graph before handing tensors to a layer. Assigning to an attribute
later skips the checks; call validate() to run most of them again:
g = Graph(node_features=x, edge_index=edge_index)
g.edge_index = torch.tensor([[0], [42]]) # accepted silently
try:
g.validate() # features, edge_index, edge tensors, labels, devices; not masks
except ValueError as exc:
print(exc)
else:
raise AssertionError("expected a ValueError")
Masks are the gap: validate() never looks at them. A mask left at its old
length after nodes are removed or added goes unnoticed.
tgx.validate_graph compares the lengths of g.train_mask, g.val_mask and
g.test_mask with the node count and, on a mismatch, sets report["ok"] to
False:
stale = Graph(node_features=torch.randn(4, 6),
train_mask=torch.tensor([True, True, False, False]))
stale.node_features = torch.randn(2, 6) # two nodes gone, mask not rebuilt
stale.validate() # passes
report = tgx.validate_graph(stale)
assert not report["ok"]
print(report["issues"])
Device Contracts
Shapes are one dimension of the contract; devices are another. A graph whose
node_features sit on the CPU while edge_index sits on a GPU would fail
somewhere inside message passing. Graph rejects tensor fields on mixed devices
at construction. Masks are the exception: the constructor moves
train_mask, val_mask and test_mask arguments to the node-feature device
instead of rejecting them. (Masks you write into metadata["masks"] yourself
are neither moved nor length-checked.) PyTorch's meta device stands in for a
second device here, so this runs without a GPU:
elsewhere = torch.empty(5, 3, device="meta") # node features on another device
moved_mask = Graph(node_features=elsewhere,
train_mask=torch.ones(5, dtype=torch.bool)).train_mask
assert moved_mask.device.type == "meta" # CPU mask moved, no error
try:
Graph(node_features=elsewhere, edge_index=edge_index) # CPU edge_index
except ValueError as exc:
print(exc)
else:
raise AssertionError("expected a ValueError")
graph.to(device) moves the graph's tensor fields together, masks included. It
modifies the graph in place and returns the same object.
from tgraphx.performance import recommended_device
device = recommended_device()
g = Graph(node_features=x, edge_index=edge_index,
node_labels=torch.zeros(5, dtype=torch.long),
train_mask=torch.tensor([True, True, True, False, False]))
moved = g.to(device)
assert moved is g
assert g.node_features.device == g.edge_index.device == g.train_mask.device
Batches have one exception worth knowing: masks stay inside each graph's
metadata and are not moved by GraphBatch.to(), as described in the
batching internals.
Tensor-Valued Features and Shape Generality
The [N, ...] notation keeps the container contract general: the first
dimension is always nodes, and the trailing dimensions can be images
[N, C, H, W], volumes [N, C, D, H, W], sequences [N, T, D] or plain
vectors [N, d].
Being storable is not the same as being consumable. No TGraphX 1.5.1
message-passing layer models a time axis inside a node feature. GCNConv,
GATv2Conv and the tensor SAGE, GAT and GIN layers reject [N, T, D] with a
ValueError, and ConvMessagePassing normally fails with a channel-count error.
Do not count on an error everywhere, though: LinearMessagePassing and
AttentionMessagePassing built with in_shape=(D,) accept it without complaint,
as does the NodeClassifier model. Their linear projections act on the last axis
only, and the attention layer's score is summed over T rather than over
features. Check x.dim() == 2 before a vector layer, or encode the sequence
first.
x_seq = torch.randn(5, 7, 6) # [N, T, D]
for cls in (tgx.LinearMessagePassing, tgx.AttentionMessagePassing):
assert cls((6,), (4,))(x_seq, edge_index).shape == (5, 7, 4) # no error
try:
tgx.GCNConv(6, 4)(x_seq, edge_index)
except ValueError as exc:
print(exc)
else:
raise AssertionError("expected a ValueError")
The Graph class is responsible for consistent counts and devices, the layer for
the meaning of the trailing axes.
The Cost of Enforcement
The checks are a few shape and length comparisons plus a minimum and maximum
over edge_index. The range check has to read those two values back, which on a
GPU means synchronising with the host. I have not measured the overhead here;
it is paid when a Graph is built, not on each forward pass.
When Shape Contracts Are Not Enough
Shape contracts catch structural inconsistencies. They do not catch meaning:
# All of these are accepted
Graph(node_features=x, node_labels=torch.tensor([0, 99, -5, 1, 1])) # label values
Graph(node_features=torch.full((5, 4), float("nan"))) # NaN features
two_edges = torch.tensor([[0, 1],
[2, 3]])
Graph(node_features=x, edge_index=two_edges.t()) # transposed, but still [2, 2]
nan_graph = Graph(node_features=torch.full((5, 4), float("nan")))
assert not tgx.validate_graph(nan_graph, check_finite=True)["ok"]
The same applies to swapped edge direction, unwanted self-loops, disconnected components and overlapping train and test masks. For these, you need additional validation logic or unit tests. Shape contracts are necessary, not sufficient. For concrete bugs that get past them, see silent shape errors in GNN experiments.
Practical Recommendation
Write the expected shape as a comment next to the code that produces each
tensor, assert what the constructor cannot know (rank, resolution, direction),
and build a Graph so the rest is checked for you.
image = torch.randn(1, 3, 64, 64) # [B, C, H, W]
node_features = tgx.image_to_patches(image, patch_size=16)[0]
assert node_features.shape == (16, 3, 16, 16) # [N, C, ph, pw]
# k-NN on patch grid positions; build_knn_graph needs [N, D] coordinates
rows, cols = torch.meshgrid(torch.arange(4), torch.arange(4), indexing="ij")
coords = torch.stack([rows.flatten(), cols.flatten()], dim=1).float()
edge_index = tgx.build_knn_graph(coords, k=4) # [2, E]
graph = Graph(node_features=node_features, edge_index=edge_index)
assert graph.feature_shape == (3, 16, 16)
By default build_knn_graph returns a symmetrised graph with self-loops, so a
node can have more than k neighbours. This pattern makes your assumptions
explicit, catches violations early and documents them for whoever reads the code
later. For a field-by-field walk through the class itself, see
reading the TGraphX source.