TGraphX › Insights › Why Explicit Graph APIs Help LLM-Assisted Research Coding
← Back to Insights

Why Explicit Graph APIs Help LLM-Assisted Research Coding

Topic: APIs, tooling and research-engineering workflow

Code drafted with an AI assistant can be syntactically correct and still assume the wrong tensor layout. Graph neural network code is exposed to this because conventions (edge index layout, edge direction, feature axes, batching) differ between libraries and hand-written projects, and are often not visible in the code itself.

An explicit API helps in a limited, concrete way: it gives the assistant and the reviewer a written contract, and it makes some violations fail loudly. It does not make generated code correct. This article shows both sides. Examples tested with TGraphX 1.5.1 on CPU; the blocks build on one another.

The implicit convention problem

Consider this signature from a hand-rolled GNN:

python
def message_pass(node_feats, adj, edge_feats):
    ...  # body left to the assistant

Whoever writes the body has to guess:

  • Is adj an adjacency matrix [N, N] or an edge list?
  • If an edge list, is it [2, E] or [E, 2], and which entry is the source?
  • Is node_feats [N, d] or [d, N]?
  • Is edge_feats indexed by edge or by node pair?

PyTorch Geometric uses an edge_index of shape [2, E], DGL builds graphs from separate source and destination tensors, and hand-written code often uses [E, 2] pairs or dense matrices. An assistant that has seen all of these can mix them in plausible-looking ways.

What an explicit contract gives you

TGraphX's Graph class fixes the layout and checks it when the object is built:

python
import torch
from tgraphx import Graph

torch.manual_seed(0)
N, E = 100, 400
feats = torch.randn(N, 3, 16, 16)           # node_features [N, ...]
edge_index = torch.randint(0, N, (2, E))    # [2, E]: row 0 source, row 1 target
e_feats = torch.randn(E, 3, 16, 16)         # edge_features [E, ...]
labels = torch.randint(0, 5, (N,))          # node_labels [N, ...]

g = Graph(node_features=feats, edge_index=edge_index,
          edge_features=e_feats, node_labels=labels)
print(g.num_nodes, g.num_edges, g.feature_shape)   # 100 400 (3, 16, 16)

The contract lives in the documented attribute shapes and in the constructor's checks, not in the Python type hints, which are plain torch.Tensor. At construction TGraphX 1.5.1 checks that node features have at least two dimensions, that edge_index is [2, E] with dtype long and ids in range, that per-node and per-edge tensors (and masks) have matching lengths, and that devices agree.

Where implicit code goes wrong silently

Suppose the project stores raw tensors as [2, E] and the assistant assumes [E, 2]:

python
node_feats = torch.randn(100, 64)
edge_index_2E = torch.randint(0, 100, (2, 200))   # the project's layout

# generated code that assumed [E, 2]
src = edge_index_2E[:, 0]
dst = edge_index_2E[:, 1]
agg = torch.zeros_like(node_feats)
agg.index_add_(0, dst, node_feats[src])           # no error
print(src.numel(), "edges used instead of", edge_index_2E.shape[1])
# 2 edges used instead of 200

Slicing the wrong axis still gives valid index tensors, so PyTorch runs the code and aggregates over two "edges". With a Graph, the layout has one answer:

python
plain = Graph(node_features=node_feats, edge_index=edge_index_2E)
src, dst = plain.edge_index                       # row 0 sources, row 1 targets
agg = torch.zeros_like(plain.node_features)
agg.index_add_(0, dst, plain.node_features[src])
assert src.numel() == plain.num_edges == 200

What construction catches, and what it does not

A transposed edge list is rejected, with a message that names the shape:

python
try:
    Graph(node_features=node_feats, edge_index=torch.randint(0, 100, (200, 2)))
except ValueError as err:
    print(err)      # edge_index must have shape [2, E], got (200, 2)
else:
    raise AssertionError("the [E, 2] layout should be rejected")

Other mistakes build a perfectly valid Graph:

python
# reversed direction: sources and targets swapped
Graph(node_features=node_feats, edge_index=edge_index_2E.flip(0))
# an [E, 2] list with exactly two edges is also a legal [2, E] list
Graph(node_features=node_feats, edge_index=torch.tensor([[0, 1], [2, 3]]))
# a float mask instead of a boolean one
Graph(node_features=node_feats, edge_index=edge_index_2E, train_mask=torch.zeros(100))
# channels-last images
Graph(node_features=torch.randn(100, 16, 16, 3), edge_index=edge_index_2E)

No check can know which direction you meant. Test it on a graph small enough to verify by hand:

python
def sum_incoming(x, edge_index):
    src, dst = edge_index
    return torch.zeros_like(x).index_add_(0, dst, x[src])

x_small = torch.tensor([[1.0], [10.0], [100.0]])
ei_small = torch.tensor([[0, 1],     # sources
                         [2, 2]])    # targets: 0 -> 2 and 1 -> 2
assert sum_incoming(x_small, ei_small).tolist() == [[0.0], [0.0], [11.0]]

A swapped src and dst fails this assertion at once. It tests this helper only; a model built from layers needs its own direction test, shown below.

A review loop with shape and direction assertions

  Human:      "Build a 2-layer SAGE node classifier for graphs with
               image-patch nodes [N, 3, 16, 16]"
                 ↓
  Assistant:  reads the contract (node_features [N, C, H, W], edge_index [2, E])
              and drafts the model
                 ↓
  Human:      runs it with shape and direction assertions
                 ↓
  assertion fails → fix        assertion passes → review the logic, then train

Note that TensorGraphSAGELayer keeps the spatial axes. A node classifier needs a pooling step before the shape assertion on class scores can pass:

python
import torch.nn as nn
from tgraphx import TensorGraphSAGELayer

class PatchSAGE(nn.Module):
    def __init__(self, in_channels, hidden, num_classes):
        super().__init__()
        self.conv1 = TensorGraphSAGELayer(in_channels, hidden)
        self.conv2 = TensorGraphSAGELayer(hidden, hidden)
        self.head = nn.Linear(hidden, num_classes)

    def forward(self, x, edge_index):
        h = self.conv1(x, edge_index).relu()     # [N, hidden, H, W]
        h = self.conv2(h, edge_index).relu()     # [N, hidden, H, W]
        return self.head(h.mean(dim=(2, 3)))     # [N, num_classes]

out = PatchSAGE(3, 16, 5)(g.node_features, g.edge_index)
assert out.shape == (N, 5), out.shape

A shape assertion cannot see direction: a model that passes edge_index.flip(0) to its layers returns the same shapes. So test the model itself on two nodes joined by one edge 0 → 1. The target must react to a change in the source, and the source must not react to a change in the target:

python
model = PatchSAGE(3, 16, 5).eval()      # eval(): no dropout or batch statistics
x = torch.randn(2, 3, 16, 16)
one_edge = torch.tensor([[0], [1]])     # 0 -> 1

with torch.no_grad():
    base = model(x, one_edge)
    new_source = x.clone()
    new_source[0] += 1.0
    new_target = x.clone()
    new_target[1] += 1.0
    target_hears_source = not torch.allclose(model(new_source, one_edge)[1], base[1])
    source_ignores_target = torch.allclose(model(new_target, one_edge)[0], base[0])

direction_ok = target_hears_source and source_ignores_target
assert direction_ok, "expected messages from row 0 to row 1 only"

A model that flips, symmetrises or ignores edge_index fails this test. If your design is meant to pass messages both ways, change what you assert.

Readable code for code review

Generated code needs human review. This is correct but makes the reviewer decode every index:

python
def agg(x, ei, ef):
    m = x[ei[0]] + ef
    ones = torch.ones(len(m), device=x.device)
    n = torch.zeros(len(x), device=x.device).index_add_(0, ei[1], ones)
    n = n.clamp(min=1).view(-1, *[1] * (x.dim() - 1))
    return torch.zeros_like(x).index_add_(0, ei[1], m) / n

The same computation, written for review:

python
def mean_incoming_messages(graph: Graph) -> torch.Tensor:
    """Per target node, the mean of x[source] + edge_features over incoming edges."""
    src, dst = graph.edge_index                    # row 0 source, row 1 target
    messages = graph.node_features[src] + graph.edge_features      # [E, ...]

    total = torch.zeros_like(graph.node_features)
    total.index_add_(0, dst, messages)             # dim 0 is the node dimension
    in_degree = torch.zeros(graph.num_nodes, device=graph.device)
    in_degree.index_add_(0, dst, torch.ones(graph.num_edges, device=graph.device))
    in_degree = in_degree.clamp(min=1).view(-1, *[1] * (total.dim() - 1))
    return total / in_degree                       # no incoming edges -> zeros

assert torch.allclose(mean_incoming_messages(g), agg(g.x, g.edge_index, g.edge_attr))

The second version is longer, but the aggregation dimension, the direction and the isolated-node behaviour are all visible.

Record what was reviewed

write_experiment_config(path, config) writes a dictionary to a JSON file. Use it to note how a generated component was checked:

python
import json
from tgraphx import write_experiment_config

write_experiment_config("logs/config.json", {
    "model": "2-layer PatchSAGE, assistant-drafted",
    "node_feature_shape": list(g.feature_shape),
    "edge_index_shape": list(g.edge_index.shape),
    "direction_test_passed": direction_ok,
    "output_shape": list(out.shape),
    "assistant": "<name and version you used>",
    "reviewed_by": "<reviewer>",
})

with open("logs/config.json") as f:
    assert json.load(f)["direction_test_passed"] is True

The path comes first and the dictionary second. The file holds only what you put in it; TGraphX does not verify any of these fields. For what TGraphX's own workflows write automatically, see Explicit, Auditable Graph APIs.

The library-side design choices behind LLM-friendly graph APIs are described separately.

Summary

Explicit graph APIs do not stop an assistant from writing wrong code. A fixed [2, E] layout with eager checks turns some mistakes into immediate errors, and named attributes make others easier to spot in review. Edge direction, mask dtype and channel order pass construction, so cover them with small tests of your own.