TGraphX › Insights › Why Graph Learning Libraries Need Honest Failure Modes
← Back to Insights

Why Graph Learning Libraries Need Honest Failure Modes

Topic: Shape validation, testing and debugging

Software fails. The question is whether it fails loudly, with useful information, or silently, wasting the user's time and trust. Graph learning libraries face this question acutely because a wrong edge list, mask or aggregation usually still produces tensors of the right shape.

This article examines what good failure behaviour looks like in a GNN library, using TGraphX as a concrete example, including the places where it does not yet meet the standard. Examples tested with TGraphX 1.5.1 on CPU; the blocks build on each other, so run them in order.

The Cost of Silent Failures

A failure that stays hidden creates three problems:

  1. Silent corruption: the computation continues with wrong results.
  2. Misdirected debugging: the user looks for bugs in their own code rather than in library assumptions, or the reverse.
  3. Eroded trust: once a hidden failure surfaces, every earlier result is in doubt.

All three are expensive in research, where a wrong number can end up in a paper or an ablation table.

Types of Failure Modes in GNN Libraries

Failure type Example Loud or silent?
Shape mismatch edge_index given as [E, 2] Depends on who checks
Device mismatch features on CPU, edge_index on GPU Usually loud
Low-precision arithmetic hand-written softmax in float16 Silent: produces NaN
Ignored option misspelled keyword accepted through **kwargs Silent
Ignored data train mask that the training loop never reads Silent
Changed default a hidden default differs after an upgrade Silent unless the library warns
Missing capability no distributed training Fine if documented

The dangerous rows are the silent ones: the program finishes, and nothing tells you that the number it printed means something else than you think.

Loud at Construction: What Graph Checks

The Graph constructor validates shapes, index ranges and devices. The messages below are the ones TGraphX 1.5.1 raises. The meta device is used as a second device so that the mismatch can be shown on a machine without a GPU.

python
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph

torch.manual_seed(0)

def show_error(make):
    try:
        make()
    except (ValueError, TypeError) as err:
        print(f"{type(err).__name__}: {err}")
    else:
        raise AssertionError("expected an error")

x = torch.randn(10, 64)
show_error(lambda: Graph(node_features=x, edge_index=torch.randint(0, 10, (20, 2))))
# ValueError: edge_index must have shape [2, E], got (20, 2)

show_error(lambda: Graph(node_features=x, edge_index=torch.randint(0, 10, (2, 20)),
                         edge_features=torch.randn(25, 16)))
# ValueError: edge_features has 25 entries but edge_index has 20 edges

show_error(lambda: Graph(node_features=x, edge_index=torch.tensor([[0], [10]])))
# ValueError: edge_index contains out-of-range indices for 10 nodes
#             (found min=0, max=10; valid range [0, 9])

show_error(lambda: Graph(node_features=x,
                         edge_index=torch.zeros((2, 3), dtype=torch.long, device="meta")))
# ValueError: edge_index device (meta) must match node_features device (cpu)

Each message names the argument and says what was expected, at the line that built the bad object. One device mismatch raises nothing: train_mask, val_mask and test_mask are moved to the device of node_features without a message. And a constructor cannot read intent: an [E, 2] array with exactly two edges has shape [2, 2] and is accepted.

Where TGraphX Stays Silent

An article about honesty has to include these. All were checked against 1.5.1.

Layers check less than Graph. The constructor checks do not run when raw tensors go straight into a layer. These two calls are wrong, and both return an output:

python
features = torch.randn(8, 4)
transposed = torch.randint(0, 8, (20, 2))                         # [E, 2]
print(tgx.LinearMessagePassing((4,), (3,))(features, transposed).shape)   # torch.Size([8, 3])

negative = torch.tensor([[-1], [0]])                              # node id -1
print(tgx.GCNConv(4, 3)(features, negative).shape)                # torch.Size([8, 3])

Other layers do reject some of these, so do not rely on a layer to validate your input. Build a Graph, or check the tensor yourself.

A misspelled option is accepted. build_model takes **kwargs and ignores names it does not know:

python
tgx.build_model("node_classification", layer="linear", in_shape=(8,), hidden_shape=(16,),
                num_layers=2, num_classes=3, dropuot=0.5)    # no error, and no dropout

fit() trains on every node. Masks stored on the graph are not read, so a transductive node task trains on validation and test labels too:

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)
model = tgx.build_model("node_classification", layer="linear", in_shape=(8,),
                        hidden_shape=(16,), num_layers=2, num_classes=3)
rows_in_loss = []

def counting_loss(out, target):
    rows_in_loss.append(out.shape[0])
    return F.cross_entropy(out, target)

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

For node classification with masks, write the loop and index the loss with g.train_mask.

A leakage check can pass without checking anything. The RandomNodeSplit transform stores its masks under keys that check_leakage(graph) does not read:

python
from tgraphx.transforms import RandomNodeSplit

split = RandomNodeSplit(0.6, 0.2, seed=0)(
    Graph(node_features=torch.randn(N, 8), edge_index=torch.randint(0, N, (2, 160))))
report = tgx.check_leakage(split)
print(report["ok"], report["counts"])              # True {}   <- nothing was compared
assert report["ok"] and not report["counts"]
assert split.train_mask is None

Pass boolean masks by keyword (check_leakage(train_mask=..., val_mask=..., test_mask=...)) and look at counts. Positional arguments bind to the wrong parameters.

validate_graph checks less than the constructor. Attributes can be reassigned after construction, and validate_graph does not look for negative indices. Graph.validate() re-runs the constructor checks:

python
bad = Graph(node_features=torch.randn(3, 2), edge_index=torch.tensor([[0], [1]]))
bad.edge_index = torch.tensor([[-1], [0]])         # changed after construction
print(tgx.validate_graph(bad, strict=True)["ok"])  # True
show_error(bad.validate)                           # ValueError: ... out-of-range indices

A determinism flag does less than its name suggests. There are two functions called set_seed. Only the one in tgraphx.reproducibility turns on torch.use_deterministic_algorithms:

python
from tgraphx.reproducibility import set_seed

torch.use_deterministic_algorithms(False)
tgx.set_seed(0, deterministic=True)
print(torch.are_deterministic_algorithms_enabled())    # False
set_seed(0, deterministic=True)
print(torch.are_deterministic_algorithms_enabled())    # True
torch.use_deterministic_algorithms(False)              # restore

A Loud Version Change

Up to version 1.4.2, ConvMessagePassing applied dropout 0.3 unless you said otherwise. Version 1.5.0 changed the default to 0.0. A silent change of default would alter training results; instead, omitting the argument now emits a dedicated warning that explains both choices:

python
import warnings

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    tgx.ConvMessagePassing((3, 8, 8), (16, 8, 8))
dropout_warnings = [w for w in caught if w.category is tgx.DropoutDefaultChangeWarning]
print(dropout_warnings[0].message)

Pass dropout_prob=0.0 or dropout_prob=0.3 explicitly and the warning goes away. This is the pattern to copy when a default has to change.

The float16 Case: Partly Handled Inside the Library

Attention layers take a softmax over each node's incoming edges. Computed naively in float16, the exponential overflows (the largest finite float16 value is 65504, so exp(x) is infinite above roughly 11.1) and the result is NaN:

python
scores = torch.tensor([20.0, 19.0], dtype=torch.float16)
naive = scores.exp() / scores.exp().sum()
print(naive)                                       # tensor([nan, nan], dtype=torch.float16)

# Private helper, imported here only to inspect its behaviour; it may change
from tgraphx.layers._scatter import edge_softmax

weights = edge_softmax(scores, torch.tensor([0, 0]), num_nodes=1)
print(weights)                                     # about [0.731, 0.269], dtype float16
assert torch.isnan(naive).all() and torch.isfinite(weights).all()
assert weights.dtype == torch.float16

GATv2Conv and TensorGATLayer (without chunking) use this helper. It subtracts the per-node maximum before exponentiating, and for float16 and bfloat16 inputs it also does the computation in float32 and casts the result back. Inputs in float32 or float64 keep their precision. The module docstring says so: "edge_softmax upcasts to float32 when the input is float16 or bfloat16. The max-shift + exp + sum computation is numerically sensitive; computing it in float32 and casting back avoids overflow/underflow in attention weights."

Not every attention path goes through it. HANConv, HGTConv and TGATConv have their own softmax helpers, which subtract the maximum but do not upcast. TensorGATLayer also normalises on its own when chunk_size is set below the number of edges; in a .half() layer, a node with no incoming edges then comes out as NaN.

This covers the softmax only. It does not make the layer or a whole model safe under mixed precision. Under autocast, GATv2Conv itself still raises a dtype RuntimeError when its input is already float16 or bfloat16; the source-grounded performance review shows the error and the workaround. Still check the loss for NaN and infinity.

What TGraphX Documents as Missing

The tgraphx.distributed module says it plainly in its docstring (background: distributed GNN training):

"TGraphX does not ship a distributed training framework. Multi-GPU and DDP are the user's responsibility."

The module does provide small helpers (rank queries, sharding indices, a DDP wrapper), but you initialise the process group and run DDP yourself. A stated limit is far cheaper for users than a stub that appears to work.

Benchmark Disclaimers

run_v13_benchmark_suite is a smoke test: it runs small tasks on tiny synthetic data and records a status, a runtime and a few sanity metrics for each. It is not an accuracy benchmark, and its own output says what it is not:

python
from tgraphx.benchmarks import run_v13_benchmark_suite

report = run_v13_benchmark_suite(small=True, seed=0)
print(report["limitations"])
for row in report["benchmarks"][:3]:
    print(row["name"], row["status"])

For standard accuracy-type metrics, TGraphX wraps the official OGB evaluators (OGBNodeEvaluator and its link and graph counterparts), which need the ogb package. See TGraphX benchmark disclaimers.

Summary Table (TGraphX 1.5.1)

Situation What happens What you do
edge_index as [E, 2], E not 2 ValueError at construction Transpose with .t()
Edge or label count mismatch ValueError at construction Fix the data
Mixed devices in one graph (masks excepted: they are moved silently) ValueError at construction Move tensors first
Raw tensors passed to a layer Checks differ by layer Validate through Graph
Attribute reassigned after construction Not checked Call g.validate()
Unknown build_model keyword Ignored silently Check the signature
Node masks with fit() Ignored silently Write the training loop
NeighborLoader without mask= Every node becomes a seed Pass mask=g.train_mask
float16 softmax in GATv2Conv / unchunked TensorGATLayer Computed in float32 Still monitor the loss
tgx.set_seed(deterministic=True) Deterministic algorithms stay off Use tgraphx.reproducibility.set_seed
Changed dropout default DropoutDefaultChangeWarning Pass dropout_prob
Distributed training Not provided, documented Use torch.distributed
Large graphs NeighborLoader, GraphSAINT and Cluster-GCN loaders (Beta) Choose a sampler
Beta API changes Possible between versions Pin the version

What Good Failure Documentation Looks Like

For each failure mode, good documentation answers:

  1. When does it fail? At construction, in the forward pass, during training, or never while producing wrong results.
  2. What is the error message or symptom?
  3. How do you fix or work around it?
  4. Is it a library limitation or a user error?

The silent cases above are where a library should either start raising, warn, or say so in the docstring of the function concerned. Until then, a short assertion in your own code is cheap insurance. For tgx.set_seed the docstring part is already done: it states that torch.use_deterministic_algorithms(True) is left off intentionally, because some scatter operations may have no deterministic CUDA kernel and would raise, so what is silent is that nothing is reported at runtime.

Related Articles