TGraphX › Insights › TGraphX vs PyTorch Tensors Alone: When a Graph Abstraction Helps
← Back to Insights

TGraphX vs PyTorch Tensors Alone: When a Graph Abstraction Helps

Topic: Tensor-valued nodes, edges and message passing

The honest question for any library is: what does this abstraction give me that raw PyTorch tensors do not? Sometimes the answer is substantial. Sometimes the right call is to skip it. This article answers the question for one thing, TGraphX's Graph class. Examples tested with TGraphX 1.5.1 on CPU.

What Raw Tensors Look Like

A common pattern in hand-written GNN code:

python
import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Convention, held only in your head: [N, d], [2, E], [E, d_e], [N]
torch.manual_seed(0)
node_feats = torch.randn(100, 64)
edge_index = torch.randint(0, 100, (2, 300))
edge_feats = torch.randn(300, 32)
labels = torch.randint(0, 5, (100,))

node_feats = node_feats.to(device)
edge_index = edge_index.to(device)
edge_feats = edge_feats.to(device)
labels = labels.to(device)

This works, and for a single experiment it is perfectly fine. Problems appear when the code grows, changes hands or is modified months later.

Where Raw Tensor Code Goes Wrong

Some mistakes raise an error, although often late and far from their cause. Others produce a wrong result with no error at all:

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

x = torch.randn(5, 3)
star = torch.tensor([[0, 0, 0, 0],      # source
                     [1, 2, 3, 4]])     # target

# Silent: the edge list arrives as [E, 2] and is read as two wrong edges
print(torch.allclose(sum_incoming(x, star), sum_incoming(x, star.t())))  # False

# Silent: in x[...] a negative node ID wraps around to the last node
print(torch.equal(x[torch.tensor([-1])], x[4:]))                          # True

# Loud, but only when the index is first used: a source ID past the end,
# or a negative target ID passed to index_add_
for bad_edge in ([[7], [0]], [[0], [-1]]):
    try:
        sum_incoming(x, torch.tensor(bad_edge))
    except (IndexError, RuntimeError) as err:
        print(type(err).__name__, err)
    else:
        raise AssertionError("expected an error")
Mistake Plain PyTorch Graph constructor
Edge list is [E, 2] Can run with wrong edges Rejects it (except when E = 2)
Node ID >= N Errors when first used for indexing Rejects it
Negative node ID x[src] wraps around silently; index_add_ on a negative target raises Rejects it
Edge feature rows differ from E Errors only if an operation needs them to match Rejects it
Label count differs from N Errors if full labels meet full outputs; with integer-index splits, extra labels pass silently Rejects it
Tensors on different devices Usually errors, at the operation that mixes them Rejects it
Labels in the wrong order Silent Not detected

What Graph Catches

The constructor checks that:

  1. node_features has at least two dimensions, [N, ...]
  2. edge_index has shape [2, E], dtype long, and IDs in 0..N-1
  3. edge weights, edge features and edge labels have E rows
  4. node labels and train/validation/test masks have N entries
  5. the tensors are on the same device as node_features (masks are moved there for you instead of rejected)
python
from tgraphx import Graph

g = Graph(
    node_features=node_feats,     # [N, d]
    edge_index=edge_index,        # [2, E]
    edge_features=edge_feats,     # [E, d_e]
    node_labels=labels,           # [N]
)

def expect_rejection(**fields):
    try:
        Graph(**fields)
    except (ValueError, TypeError) as err:
        print("rejected:", err)
        return
    raise AssertionError("Graph accepted this input")

expect_rejection(node_features=x, edge_index=star.t())
expect_rejection(node_features=x, edge_index=torch.tensor([[0], [7]]))
expect_rejection(node_features=x, edge_index=torch.tensor([[-1], [0]]))
expect_rejection(node_features=x, edge_index=star, edge_features=torch.randn(5, 2))
expect_rejection(node_features=x, edge_index=star, node_labels=torch.tensor([0, 1]))

Each error message names the field that is wrong.

What Graph Does Not Catch

Graph is a structural validator, not a semantic one:

Not checked Note
NaN or Inf in features validate_graph(g, check_finite=True) checks this
Duplicate edges, self-loops Accepted
Connectivity, isolated nodes No topology requirements
Meaning or order of labels Cannot be known
A 2 x 2 edge index with the wrong orientation Both layouts have a valid shape
Changes made after construction Fields are plain attributes; see below

The last row matters. Assigning a field does not re-run the checks. Calling validate() re-checks shapes, the index range, label and edge row counts and devices, but not the train, validation or test masks:

python
import tgraphx as tgx

# NaN features and a duplicated edge are accepted
odd = Graph(node_features=torch.full((3, 2), float("nan")),
            edge_index=torch.tensor([[0, 0], [1, 1]]))
print(tgx.validate_graph(odd, check_finite=True)["ok"])      # False

changed = g.clone()
changed.edge_index = changed.edge_index.t()                  # no error here
try:
    changed.validate()
except ValueError as err:
    print("validate():", err)
else:
    raise AssertionError("expected a ValueError")

# validate() ignores masks: drop two nodes and the old split survives
split = Graph(node_features=torch.randn(5, 3),
              edge_index=torch.tensor([[0, 1], [1, 2]]),
              train_mask=torch.tensor([True, True, True, False, False]))
split.node_features = split.node_features[:3]
split.validate()                                             # passes
print(split.num_nodes, split.train_mask.size(0))             # 3 5

def stale_masks(graph):
    names = ("train_mask", "val_mask", "test_mask")
    return [name for name in names
            if getattr(graph, name) is not None
            and getattr(graph, name).size(0) != graph.num_nodes]

print(stale_masks(split))                                    # ['train_mask']

So after changing the node set, rebuild the masks and assert their length, for example assert g.train_mask.size(0) == g.num_nodes. A matching length does not show that the entries still refer to the same nodes. tgx.validate_graph also reports a wrong mask length, but it misses other things the constructor checks, such as negative IDs, so it does not replace validate().

The .to(device) Convenience

With raw tensors it is easy to forget one line:

python
node_feats = node_feats.to(device)
edge_index = edge_index.to(device)
# edge_feats forgotten: nothing complains until an op mixes devices
labels = labels.to(device)

With Graph, one call moves all of its tensor fields, including masks:

python
moved = g.to(device)
print(moved is g)      # True: the graph is moved in place

Because to() modifies the object, use g.clone().to(device) when you want to keep a copy where it was. The move covers the graph's tensor fields and its masks; other tensors you put in metadata, and tensors you keep outside the graph, are still your job.

When Raw Tensors Are the Right Choice

Exploratory prototyping. For a quick idea you will throw away, building a Graph adds a step without much benefit.

Other representations. If your method works on a sparse adjacency matrix or a hypergraph and does not map to the [N, ...] / [2, E] / [E, ...] / [N, ...] schema, don't force it. The longer-term cost side of that choice is discussed in maintainability trade-offs of hand-rolled graph code.

Trivial pipelines. One small graph, built once and used in one place, can be fine as tensors.

Needs outside TGraphX. If you need training on a graph partitioned across machines, built-in layers for sequence-shaped node features, or a very large catalogue of published layers, plan on another library or your own code.

When the Abstraction Helps

Several modules. When features, edges and labels travel through many functions, one object keeps them together, and the layout is checked where it is built.

Shared code. "This function takes a Graph" says more than "this function takes x, edge_index and ef".

Generated code. If a coding assistant produces an out-of-range index or a transposed edge list, construction fails immediately instead of later or never.

Batching. GraphDataLoader uses a default collate function that turns a list of Graph objects into a GraphBatch, applying the node offsets for you.

Sampling. Neighbour and subgraph samplers (Beta) take a Graph as input.

Recording. write_graph_stats records num_nodes and num_edges from a Graph, or any dictionary of statistics you pass.

Code Comparison: A Multi-Step Pipeline

With raw tensors, every step repeats the whole argument list and trusts the previous one:

python
import torch.nn.functional as F

def step1_raw(node_feats, edge_index, edge_feats, labels):
    return F.normalize(node_feats, dim=1), edge_index, edge_feats, labels

def step2_raw(node_feats, edge_index, edge_feats, labels):
    return sum_incoming(node_feats, edge_index)    # assumes [2, E]

With Graph, a step takes and returns one object and can check its own output:

python
def step1(graph: Graph) -> Graph:
    out = graph.clone()                            # keeps labels, masks, metadata
    out.node_features = F.normalize(out.node_features, dim=1)   # per node
    out.validate()
    return out

def step2(graph: Graph) -> torch.Tensor:
    return sum_incoming(graph.node_features, graph.edge_index)

print(tuple(step2(step1(g)).shape))                # (100, 64)

Summary Decision Table

Situation Suggestion
Exploratory notebook, one-off script Raw tensors are fine
Graph passes through several modules Use Graph
Team working on a shared codebase Use Graph
You want early shape, index and device checks Use Graph
Neighbour or subgraph sampling TGraphX samplers (Beta), or PyG or DGL
Data does not fit [N, ...] and [2, E] Raw tensors or a specialised structure
Training on a partitioned graph across machines Another library's distributed tooling