TGraphX › Insights › Tensor-Valued Nodes in Graph Neural Networks: Why Shape Matters
← Back to Insights

Tensor-Valued Nodes in Graph Neural Networks: Why Shape Matters

Topic: Tensor-valued nodes, edges and message passing

Most built-in layers in graph neural network (GNN) libraries assume that every node is described by a flat feature vector. You get a node feature matrix of shape [N, D], message passing operates on that matrix, and everything is comfortably linear-algebra friendly. This works very well for citation networks, social graphs and most molecular graphs.

It fits less well when your nodes have real structure. An image patch is [C, H, W]. A volumetric block from a medical scan is [C, D, H, W]. Flattening these into vectors is easy and loses no values, but the layer no longer knows which values were neighbouring pixels or voxels.

TGraphX (pip install tgraphx) lets node features keep their tensor shape, and ships layers that read [C, H, W] and [C, D, H, W] node features. This article explains what that means in practice and where the design helps. The examples were tested with TGraphX 1.5.1 on CPU.

The flat-vector assumption

A typical PyG or DGL pipeline starts like this:

python
import torch

x = torch.randn(100, 32)                 # 100 nodes, 32 features each
edge_index = torch.randint(0, 100, (2, 300))

Most built-in PyG and DGL convolution layers expect x to be [N, D]. Their data containers can hold higher-rank tensors, and you can write custom message functions that operate on them, but then you are writing the layer yourself.

This is fine when the features are genuinely vector-shaped. A bag-of-words representation of a paper, a one-hot encoding of an atom type, a learned user embedding: these are all naturally vectors. The assumption matches the data.

Where the assumption gets in the way

Consider a graph of image regions. Each node is a cropped patch, and edges link adjacent or visually similar patches. The natural node feature is [3, 8, 8]: three colour channels over a small grid.

Two options exist:

  1. Flatten it. Reshape every patch to a [192] vector. The reshape is reversible, but a plain linear layer treats the 192 entries as unrelated positions. To exploit locality, a model would have to reshape them back or relearn the structure from data.

  2. Preserve the shape. Keep x as [N, 3, 8, 8] and use message passing layers that apply convolutions.

TGraphX is built around the second option.

How TGraphX preserves shape

The Graph container accepts node features of any rank from 2 up:

python
import torch
import tgraphx as tgx

torch.manual_seed(0)

# 100 nodes, each an 8x8 RGB patch
x = torch.randn(100, 3, 8, 8)
edge_index = torch.randint(0, 100, (2, 300))
labels = torch.randint(0, 5, (100,))

g = tgx.Graph(x=x, edge_index=edge_index, labels=labels)
tgx.validate_graph(g, strict=True)

layer = tgx.TensorGraphSAGELayer(in_channels=3, out_channels=16)
print(layer(g.x, g.edge_index).shape)  # torch.Size([100, 16, 8, 8])

# A vector layer does not accept the same tensor
try:
    tgx.GCNConv(3, 16)(g.x, g.edge_index)
except ValueError as err:
    print(err)
else:
    raise AssertionError("expected GCNConv to reject 4-D features")

The constructor checks shapes and that edge indices are in range. The shipped tensor layers are ConvMessagePassing, TensorGATLayer, TensorGraphSAGELayer and TensorGINLayer, for [C, H, W] and [C, D, H, W] features.

Sequences of shape [T, D] can be stored in a Graph, but no shipped message-passing layer is designed for them. The four tensor layers, GCNConv and GATv2Conv reject [N, T, D]. LinearMessagePassing and the legacy AttentionMessagePassing, built with in_shape=(D,), accept it silently without modelling the time axis properly: the first processes each time step on its own, and the second also sums its attention scores over time. Do not read a successful forward pass as sequence support.

Keeping the shape is not the same as using it. The SAGE, GAT and GIN layers use 1×1 convolutions that never mix pixel positions; ConvMessagePassing also applies 3×3 convolutions, which can pick up local spatial patterns.

For a first end-to-end run there is a one-call helper:

python
from tgraphx.estimators import node_train_val_test_split

train_mask, val_mask, test_mask = node_train_val_test_split(100, 0.6, 0.2, 0.2, seed=42)
result = tgx.classify_nodes(
    x=x, edge_index=edge_index, labels=labels,
    train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
    model="tensor_gcn", seed=42, device="cpu",
)
print(result.metrics["val_accuracy"])

It trains a small fixed tensor model and reports validation and test accuracy. It does not search over models. The labels here are random, so the number only shows that the pipeline runs.

When does this design actually help

Not always. Flat vectors are sufficient for many standard GNN benchmarks. Consider tensor-valued nodes when:

  • Your nodes represent image patches, volumetric regions or other inherently spatial data (scientific cases are discussed in graph learning for biology and materials data)
  • You want convolutions inside message passing
  • You want to keep channel-wise spatial maps through aggregation
  • Your graph combines different tensor modalities that you can encode to a common node shape

If your nodes are user IDs, atom types or text embeddings, you do not need this. Use flat features with the library you already know and skip the complexity. For a way to test the choice on your data, see when flat vector node features are not enough.

Trade-offs to acknowledge

Tensor-valued nodes are not free:

  • Memory. A [N, C, H, W] feature tensor is much larger than a typical [N, D] matrix for the same node count.
  • Compute. Tensor-aware layers do more work per edge.
  • Ecosystem. PyG has many more built-in layers and dataset integrations. TGraphX is a smaller, newer project.
  • Maturity. TGraphX is classified as Beta on PyPI. tgx.api_status(name) reports a label per API: for example, Graph and the tensor layers are stable, NeighborLoader is beta and HeteroGraph is experimental.

Practical guidance

If your node features have spatial structure, write a short prototype: build the graph, run one tensor layer, then train a small model on a subset of your data and compare it with a flattened-feature baseline on a held-out split. If the tensor model does not help, or the shape bookkeeping costs more than it gives, flat vectors are the better choice.

TGraphX is described in a preprint (Sajjadi & Eramian, arXiv:2504.03953, 2025), and the package is on PyPI as tgraphx; version 1.5.1 is the release used here.


If you work in PyTorch Geometric, see what its layers accept in multidimensional node features in PyTorch Geometric.

FAQ

Q: Can I mix tensor-valued and flat-vector nodes in the same graph?
A: Not in one Graph: all nodes share one feature tensor and therefore one shape. HeteroGraph (experimental) can store a different shape per node type, but a relation between two types still needs features the chosen layer can combine; HeteroConv concatenates source and destination features, so their trailing shapes must match. The usual approach is to encode each modality to a common shape first.

Q: Do I need to flatten before any operation?
A: Not inside the tensor-aware layers. ConvMessagePassing or TensorGATLayer take rank-4 inputs directly. You pool or flatten when you hand the result to a vector-only layer such as GCNConv or to a linear classifier.

Q: Are there pre-trained models that use tensor-valued nodes?
A: TGraphX ships no pre-trained graph models. Its optional tgraphx.models.pre_encoder.PreEncoder(..., use_pretrained=True) can load torchvision's ImageNet ResNet-18 weights (a download) to encode image patches.

Q: How do I save and load a graph with tensor features?
A: Use the .tgx format: g.save("file.tgx") and tgx.Graph.load("file.tgx"). GraphML has no tensor attribute type. By default tgraphx.io.write_graphml writes no node or edge features at all: it succeeds and silently drops them. With include_tensor_features=True it writes vector features and raises ValueError for image or volume features. Load .tgx files only from sources you trust, because loading unpickles data. For the explicit training workflow, continue with the deeper tutorial.