TGraphX › Insights › Reading the TGraphX Source: How a Tensor-Valued Graph Is Represented
← Back to Insights

Reading the TGraphX Source: How a Tensor-Valued Graph Is Represented

Topic: Tensor-valued nodes, edges and message passing

Graph learning examples usually store node features as a 2D matrix, one row per node and one column per feature. TGraphX allows node features to be tensors of higher rank, so a node can carry an image patch or a multi-channel feature map. This article reads the TGraphX 1.5.1 source to see what a graph actually stores, what is checked when you build one, and what is not.

Three files cover it, linked here at the v1.5.1 tag:

You can also print any of it from your own installation with inspect.getsource. The examples were tested with TGraphX 1.5.1 on CPU.

What a Graph Holds

Four fields carry most graphs:

Field Shape Meaning
node_features [N, ...] One tensor per node; at least 2-D, trailing dims can be anything
edge_index [2, E] Row 0: source nodes, row 1: destination nodes (int64)
edge_features [E, ...] One tensor per edge, at least 2-D
node_labels [N, ...] Per-node targets

Only node_features is required. The constructor also accepts edge_weight ([E]), edge_labels, graph_label (a graph-level target), graph_features (a graph-level input), train_mask / val_mask / test_mask (stored in metadata["masks"]) and a free metadata dictionary. PyG-style aliases x, y and edge_attr work too.

N is the number of nodes and E the number of edges. All nodes share one trailing shape because they are rows of a single tensor.

Why Tensor-Valued Nodes Matter

Consider a graph where each node is an image patch. With vector-input layers you would flatten a 3×16×16 patch into a 768-dimensional vector. No values are lost, but the layer no longer knows which values were neighbouring pixels.

In TGraphX the node feature can stay [3, 16, 16], so node_features is [N, 3, 16, 16], and convolution-based layers can work on the trailing dimensions during message passing. (PyG and DGL can store such tensors too; the difference lies in which built-in layers consume them.)

Tensor Layout

  Graph object
  ┌───────────────────────────────────────────────────────────┐
  │                                                           │
  │  node_features  [N, C, H, W] = [8, 3, 16, 16]             │
  │  ┌────┬────┬────┬────┬────┬────┬────┬────┐                │
  │  │ n0 │ n1 │ n2 │ n3 │ n4 │ n5 │ n6 │ n7 │  N = 8 nodes   │
  │  └────┴────┴────┴────┴────┴────┴────┴────┘                │
  │    each slot holds a [C, H, W] tensor                     │
  │                                                           │
  │  edge_index  [2, E] = [2, 12]                             │
  │  ┌──────────────────────────────────────────────────┐     │
  │  │ src: [0, 1, 1, 2, 3, 4, 4, 5, 6, 7, 0, 3]        │     │
  │  │ dst: [1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 4, 6]        │     │
  │  └──────────────────────────────────────────────────┘     │
  │    row 0 = source nodes, row 1 = destination nodes        │
  │                                                           │
  │  edge_features  [E, d] = [12, 64]                         │
  │  ┌────┬────┬────┬────┬─────┬─────┐                        │
  │  │ e0 │ e1 │ e2 │ e3 │ ... │ e11 │                        │
  │  └────┴────┴────┴────┴─────┴─────┘                        │
  │    row k belongs to the edge in column k of edge_index    │
  │                                                           │
  │  node_labels  [N] = [8]                                   │
  │  ┌────┬────┬────┬────┬────┬────┬────┬────┐                │
  │  │ 0  │ 2  │ 1  │ 3  │ 1  │ 0  │ 2  │ 3  │                │
  │  └────┴────┴────┴────┴────┴────┴────┴────┘                │
  └───────────────────────────────────────────────────────────┘

Here is the same graph in code:

python
import torch
from tgraphx import Graph

torch.manual_seed(0)
N, E, C, H, W = 8, 12, 3, 16, 16

node_features = torch.randn(N, C, H, W)                      # [8, 3, 16, 16]
edge_index = torch.tensor([[0, 1, 1, 2, 3, 4, 4, 5, 6, 7, 0, 3],
                           [1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 4, 6]])  # [2, 12]
edge_features = torch.randn(E, 64)                           # [12, 64]
node_labels = torch.tensor([0, 2, 1, 3, 1, 0, 2, 3])         # [8]

g = Graph(
    node_features=node_features,
    edge_index=edge_index,
    edge_features=edge_features,
    node_labels=node_labels,
)
print(g.feature_shape, g.edge_feature_shape)  # (3, 16, 16) (64,)

What the Constructor Checks

The edge index validator is short enough to read in full:

python
import inspect
from tgraphx.core import graph_utils

print(inspect.getsource(graph_utils.validate_edge_index))

The checks it runs, excerpted from that output:

    if edge_index.dim() != 2 or edge_index.size(0) != 2:
    ...
    if edge_index.dtype != torch.long:
    ...
    if device is not None and edge_index.device != device:
    ...
        if lo < 0 or hi >= num_nodes:

So shape, dtype, device and index range are all verified: an index below 0 or at or above N is rejected. Matching validators check that edge_weight is [E] and that edge_features is at least 2-D with E rows. Labels must have N (or E) rows and masks must have length N. Tensors must be on the same device as node_features (masks are the exception: they are moved there for you). Each of these calls raises:

python
def expect_rejection(**overrides):
    kwargs = dict(node_features=node_features, edge_index=edge_index)
    kwargs.update(overrides)
    try:
        Graph(**kwargs)
    except (TypeError, ValueError) as err:
        print(f"{type(err).__name__}: {err}")
    else:
        raise AssertionError("the constructor accepted this input")

expect_rejection(edge_index=edge_index.t())              # [E, 2] instead of [2, E]
expect_rejection(edge_index=torch.tensor([[0], [8]]))    # node 8 does not exist
expect_rejection(edge_index=torch.tensor([[-1], [0]]))   # negative index
expect_rejection(edge_index=edge_index.int())            # int32 instead of int64
expect_rejection(edge_features=torch.randn(E - 1, 64))   # one row short
expect_rejection(node_labels=torch.zeros(N + 1))         # one label too many

One gap follows from the shape test: a transposed edge list is caught only because E is not 2. With exactly two edges, [E, 2] and [2, E] look the same to the validator.

Checks Run at Construction, Not Afterwards

The fields are ordinary attributes, so later assignments are not checked. g.validate() re-runs the constructor's checks on features, edge_index, edge weights, labels and their devices, but it does not re-check the masks. The helper tgx.validate_graph() is a different, lighter report: it does check mask lengths, but it does not notice negative indices, a wrong index dtype such as int32, or a wrong-length edge_weight, node_labels or edge_labels:

python
import tgraphx as tgx

broken = g.clone()
broken.edge_index[0, 0] = -1
print(tgx.validate_graph(broken)["ok"])  # True: the negative index is not noticed

try:
    broken.validate()
except ValueError as err:
    print(err)
else:
    raise AssertionError("expected validate() to reject the graph")

assert g.edge_index[0, 0] == 0  # clone() copied the tensors; g is untouched

What Validation Does Not Cover

Construction succeeds regardless of:

  • NaN or Inf values (tgx.validate_graph(g, check_finite=True) looks for them in node and edge features, not in edge weights or labels)
  • duplicate edges, self-loops, connectivity, or whether the graph is directed
  • whether label values and dtype suit your loss function
  • whether masks are boolean or disjoint; only their length is checked (use tgx.check_leakage with keyword arguments and boolean masks)
  • whether any layer can read the feature layout. [N, T, D] sequences construct fine, and no shipped message-passing layer is designed for them. The tensor layers, GCNConv and GATv2Conv reject them, but LinearMessagePassing and the legacy AttentionMessagePassing, built with in_shape=(D,), do not check the input rank and run silently: the first works on each time step separately, the second also sums its attention scores over T

These are application-level concerns that stay with you.

Device Moves

g.to(device) moves every tensor field of the graph, including the masks in metadata. It modifies the graph in place and returns the same object. A dtype argument converts floating-point features and weights only; indices, masks and all label tensors (including float regression targets) keep their type:

python
from tgraphx.performance import recommended_device

device = recommended_device()  # a torch.device: CUDA, else Apple MPS, else CPU
moved = g.to(device)
assert moved is g              # moved in place

double = g.clone().to("cpu", dtype=torch.float64)
print(double.node_features.dtype, double.edge_index.dtype, double.node_labels.dtype)
# torch.float64 torch.int64 torch.int64
g.to("cpu")

This keeps the graph's tensors together. Putting the model on the same device as the graph is still your job.

Batching Multiple Graphs

GraphBatch([g1, g2, ...]) joins graphs into one disjoint union. The offset logic is a few lines of the source:

python
from tgraphx import GraphBatch

for line in inspect.getsource(GraphBatch).splitlines():
    if "node_offset" in line:
        print(line.strip())

def ring_graph(num_nodes, label):
    ring = torch.arange(num_nodes)
    return Graph(
        node_features=torch.randn(num_nodes, C, H, W),
        edge_index=torch.stack([ring, (ring + 1) % num_nodes]),
        graph_label=torch.tensor(label),
    )

batch = GraphBatch([ring_graph(3, 0), ring_graph(4, 1), ring_graph(2, 0)])
print(batch.node_features.shape)   # torch.Size([9, 3, 16, 16])
print(batch.edge_index[:, 3:7])    # the second graph's edges, shifted by 3
print(batch.batch.tolist())        # [0, 0, 0, 1, 1, 1, 1, 2, 2]
print(batch.graph_labels)          # tensor([0, 1, 0])

The batch vector records which graph each node came from. All graphs must share the same per-node feature shape, and an optional tensor present on only some of them raises a ValueError. Two things do not carry over: masks are not concatenated (each graph's masks stay in batch.metadata[i]), and graph_features is silently dropped. The batching internals article goes further.

GraphML I/O

tgraphx.io provides read_graphml and write_graphml. Reading the writer's signature in the source matters here: include_tensor_features defaults to False, so node and edge features are not written unless you ask, and the call still succeeds. With the flag, vector features are written and higher ranks are refused.

python
import os
import tempfile
from tgraphx.io import read_graphml, write_graphml

folder = tempfile.mkdtemp()
vec = Graph(
    node_features=torch.randn(4, 3),
    edge_index=torch.tensor([[0, 1, 2], [1, 2, 3]]),
    node_labels=torch.tensor([0, 1, 0, 1]),
)

# Default: structure, labels and any edge weights, but no features
path = os.path.join(folder, "default.graphml")
write_graphml(vec, path)
lossy = read_graphml(path)
print(lossy.node_features.shape)  # torch.Size([4, 1]), a placeholder of zeros
assert lossy.node_features.abs().sum() == 0

# Vector features, written explicitly
path = os.path.join(folder, "full.graphml")
write_graphml(vec, path, include_tensor_features=True)
assert torch.allclose(read_graphml(path).node_features, vec.node_features)

# With the flag, image-shaped features are refused
try:
    write_graphml(g, os.path.join(folder, "patches.graphml"), include_tensor_features=True)
except ValueError as err:
    print(err)
else:
    raise AssertionError("expected a ValueError")

# Without the flag the same graph is written without complaint, minus its features
path = os.path.join(folder, "silent.graphml")
write_graphml(g, path)
silent = read_graphml(path)
print(silent.node_features.shape, silent.edge_features)  # torch.Size([8, 1]) None
assert silent.node_features.abs().sum() == 0 and silent.edge_features is None

# The native format keeps them
g.save(os.path.join(folder, "patches.tgx"))
assert torch.equal(Graph.load(os.path.join(folder, "patches.tgx")).node_features, g.node_features)

GraphML also does not carry graph_label, graph_features or metadata such as masks. Use .tgx for a lossless TGraphX round trip, and load .tgx files only from sources you trust, because loading unpickles data.

Reading source has limits; see what source code can and cannot tell you.

Key Takeaway

Graph is a thin, validated container. The constructor checks shapes, dtypes, devices, lengths and the edge index range once; to() moves its tensors in place; GraphBatch handles the index offsets; and GraphML keeps only part of what a tensor graph holds. Knowing where each of those lines is drawn saves debugging time before the first experiment.