TGraphX vs Hand-Rolled Graph Code: Maintainability Trade-Offs
Every research project asks it at some point: use a library, or write the GNN layer yourself? Hand-rolled code gives you full control and no extra dependency. A library gives you ready building blocks, input checks and conventions you do not have to invent. Neither is always right.
This page is about layer code: writing it, checking it, extending it and keeping it working. Examples tested with TGraphX 1.5.1 on CPU.
What Hand-Rolled Code Looks Like
A GraphSAGE-style layer with mean aggregation takes a few lines of PyTorch:
import torch
import torch.nn as nn
class HandRolledSAGE(nn.Module):
"""h'_v = W [h_v || mean of h_u over incoming edges u -> v] + b"""
def __init__(self, in_dim, out_dim):
super().__init__()
self.W = nn.Linear(2 * in_dim, out_dim)
def forward(self, x, edge_index):
src, dst = edge_index
total = torch.zeros_like(x).index_add_(0, dst, x[src]) # [N, d]
degree = x.new_zeros(x.size(0)).index_add_(0, dst, x.new_ones(dst.numel()))
mean = total / degree.clamp(min=1).unsqueeze(1)
return self.W(torch.cat([x, mean], dim=1)) # [N, out]
torch.manual_seed(0)
x = torch.randn(6, 8)
edge_index = torch.tensor([[0, 1, 2, 3, 4], # source
[2, 2, 3, 4, 0]]) # target
hand = HandRolledSAGE(8, 16)
print(tuple(hand(x, edge_index).shape)) # (6, 16)
It depends only on PyTorch and runs on a GPU once the module and tensors are moved there. It also checks nothing.
The Library Layer, and Checking One Against the Other
TGraphX's TensorGraphSAGELayer is written for image-like [N, C, H, W] or
volumetric node features, using 1x1 convolutions. Vectors can be passed as
[N, d, 1, 1]. Its formula is W_self h_v + W_neigh mean(h_u) + b, which is
the same function as one linear map on the concatenation above. Copy the weights
across and the two must agree:
from tgraphx import TensorGraphSAGELayer
lib = TensorGraphSAGELayer(8, 16) # aggr="mean" is the default
with torch.no_grad():
hand.W.weight.copy_(torch.cat([lib.W_self.weight[:, :, 0, 0],
lib.W_neigh.weight[:, :, 0, 0]], dim=1))
hand.W.bias.copy_(lib.W_self.bias)
out_lib = lib(x[:, :, None, None], edge_index).flatten(1)
assert torch.allclose(hand(x, edge_index), out_lib, atol=1e-6)
print("hand-rolled and library layer agree")
This reference test is useful whichever side you ship: it catches a wrong
aggregation axis, swapped source and target, or sum where you meant mean. Note
the call: layers take layer(x, edge_index), not a Graph object.
The library version also handles spatial features, which you would otherwise have to write with convolutions and a four-dimensional scatter:
patches = torch.randn(6, 3, 8, 8) # 6 nodes, each a 3x8x8 patch
print(tuple(TensorGraphSAGELayer(3, 16)(patches, edge_index).shape)) # (6, 16, 8, 8)
Where the Graph Object Fits
Graph is the input check. It rejects a wrongly shaped edge_index, node IDs
out of range and mismatched row counts when the object is built:
from tgraphx import Graph
g = Graph(node_features=x, edge_index=edge_index)
try:
Graph(node_features=x, edge_index=torch.tensor([[0], [6]]))
except ValueError as err:
print("rejected:", err)
else:
raise AssertionError("expected a ValueError")
Graph is mutable, so the check applies at construction. Call g.validate()
again if code reassigns fields. It does not re-check train, validation or test
masks, so compare their length with g.num_nodes yourself if the node set
changes.
Trade-Off Table
| Dimension | Hand-rolled | TGraphX |
|---|---|---|
| Code for a first vector layer | Short | One line to construct |
| Spatial or volumetric node features | You write it | Built-in layers |
| Dependency risk | PyTorch only | A Beta library (plus torchvision, pyyaml) |
| Input checks | You add them | Graph checks at construction |
| Device moves | Tensor by tensor | g.to(device) moves the graph's tensor fields and masks |
| Correctness of aggregation | Your tests | Maintained upstream; still test what you rely on |
| Custom aggregation | Full control | Subclass TensorMessagePassingLayer, or any nn.Module |
| Batching graphs | You write the index offsets | GraphBatch([g1, g2]) |
| Logging and run records | You write them | CSVLogger, MLflowLogger, write_* functions |
| Reading the internals | All in your repository | In the dependency, as readable Python |
| Long-term maintenance | You own it | Upgrades may change behaviour |
The narrower question of what the Graph container alone buys you is treated in TGraphX versus plain PyTorch tensors.
When Hand-Rolled Code Is Better
The operation is the research. If you are inventing an aggregation scheme, plain PyTorch keeps every step visible. You can still start from the library's base class, shown below.
The structure does not fit. TGraphX has separate containers for
heterogeneous graphs (HeteroGraph) and snapshot sequences
(TemporalGraphSequence), both Experimental, and a Hypergraph class without a
hypergraph convolution layer. If none matches your problem, write the
representation that does. For hypergraphs specifically, see incidence matrices and clique expansion.
Dependencies are restricted. A short scatter-based layer in pure PyTorch can go wherever PyTorch goes.
The code is disposable. For a one-off notebook, an extra abstraction may not pay for itself.
When TGraphX Is Better
Node features are tensors. The spatial layers already exist and keep the
[C, H, W] layout.
Graph data crosses many modules. Constructing a Graph at each pipeline
boundary turns a silent convention mistake into an early error.
You need sampling or batching. Neighbour, GraphSAINT and Cluster-GCN loaders
(Beta) and GraphBatch are code you would otherwise maintain.
Several people share the code. A named type with documented fields is easier to agree on than a loose group of tensors.
The Hybrid Approach: Custom Layers on a Library Base
A practical middle ground is to keep the library's data handling and
message-passing loop, and write only the part that is new.
TensorMessagePassingLayer calls your message(), aggregates by target node
(sum, mean or max), then calls update():
from tgraphx import TensorMessagePassingLayer
class GatedMeanLayer(TensorMessagePassingLayer):
"""message = sigmoid(a . [h_u || h_v]) * W h_u; h'_v = relu(U h_v + mean)"""
def __init__(self, in_dim, out_dim):
super().__init__(in_shape=(in_dim,), out_shape=(out_dim,), aggr="mean")
self.gate = nn.Linear(2 * in_dim, 1)
self.msg = nn.Linear(in_dim, out_dim)
self.own = nn.Linear(in_dim, out_dim)
def message(self, src, dest, edge_attr):
return torch.sigmoid(self.gate(torch.cat([src, dest], dim=1))) * self.msg(src)
def update(self, node_feature, aggregated_message):
return torch.relu(self.own(node_feature) + aggregated_message)
layer = GatedMeanLayer(8, 16)
print(tuple(layer(g.node_features, g.edge_index).shape)) # (6, 16)
weights = torch.tensor([1.0, 0.5, 1.0, 0.0, 1.0]) # one per edge, [E]
print(tuple(layer(g.node_features, g.edge_index, edge_weight=weights).shape))
The base class multiplies each message by edge_weight; with aggr="mean" it
still divides by the number of incoming edges, not by the sum of weights.
Overriding update() also replaces the base class's residual, batch-norm and
dropout handling.
Spell aggr exactly. In 1.5.1 the base class treats any value other than
"mean" or "max" as a sum, so aggr="min" or a misspelt "Mean" returns sums
without an error. For a different reduction, override aggregate().
Watch for placeholder tensors. Multiplying messages by an all-zero "edge feature" silently turns message passing off, and a model with a self term still trains, which hides the problem.
Test Custom Layers, Whatever They Are Built On
Two cheap tests catch most wiring mistakes. First, renumbering the nodes must renumber the output in the same way (permutation equivariance). Second, changing a neighbour must change the target's output:
def check_permutation(model, x, edge_index):
perm = torch.randperm(x.size(0)) # new row i holds old node perm[i]
new_id = torch.argsort(perm) # old node id -> new id
torch.testing.assert_close(model(x[perm], new_id[edge_index]),
model(x, edge_index)[perm])
def check_neighbour_matters(model, x, edge_index, source=0, target=2):
changed = x.clone()
changed[source] += 1.0 # edge source -> target exists
assert not torch.allclose(model(x, edge_index)[target],
model(changed, edge_index)[target])
for model in (hand, layer):
check_permutation(model, x, edge_index)
check_neighbour_matters(model, x, edge_index)
print("both layers pass")
Test library behaviour you rely on, too. In 1.5.1, GCNConv adds a self-loop to
every node even when the edge index already has one, so a graph builder that
adds self-loops leads to double counting.
Stacking Layers
Layers return tensors, and topology does not change between them, so there is no
need to rebuild a Graph after every layer:
first, second = GatedMeanLayer(8, 16), GatedMeanLayer(16, 4)
h = first(g.node_features, g.edge_index)
out = second(h, g.edge_index)
print(tuple(out.shape)) # (6, 4)
Build and validate the graph where data enters the pipeline or where its structure changes (sampling, augmentation), and pass tensors in between.
The Maintenance Horizon
For a short-lived experiment, hand-rolled code is often fine. For code that several people will change over months, shared types, reference tests and a maintained base can save work.
A Beta dependency has its own cost: behaviour can change between releases. For
example, ConvMessagePassing and CNNEncoder applied a dropout of 0.3 by
default up to 1.4.2 and use 0.0 since 1.5.0. Pin the version
(tgraphx==1.5.1), pass important hyperparameters explicitly, read the changelog
before upgrading, and keep tests like the ones above in your own repository.