TGraphX › Insights › When Flat Vector Node Features Are Insufficient for Your GNN Task
← Back to Insights

When Flat Vector Node Features Are Insufficient for Your GNN Task

Topic: Tensor-valued nodes, edges and message passing

Tensor-valued nodes let each node keep a shape such as [C, H, W] instead of a single vector of length D. This is a decision guide: does your task need a model that uses the structure inside a node feature, or are flat vectors enough?

Keep two questions apart. The first is about the data container: can the library store a tensor per node? TGraphX's Graph can, and so can PyTorch Geometric's Data. The second is about the model: does any part of it use the axes, for example to treat neighbouring pixels differently from distant ones? Only the second question affects what the network can learn efficiently.

Examples tested with TGraphX 1.5.1.

When flat vectors are sufficient

Flat node feature vectors [N, D] are the natural representation for:

  • Citation networks. Nodes are papers; features are bag-of-words or learned embeddings. The natural representation is vector. (For a worked vector-feature example, see applying TGraphX to a citation network.)
  • Social networks. Nodes are users; features are demographic or behavioral attributes.
  • Molecular property prediction with standard atom descriptors. Element type, degree, charge and similar fields form a vector.
  • Recommendation graphs. Nodes are users and items; features are learned embeddings or content vectors.
  • Knowledge graphs. Entities usually have learned embeddings, sometimes joined with text features that are already encoded as vectors.

For these, use vector models: a vector GNN from PyTorch Geometric, DGL or TGraphX (GCNConv, GATv2Conv), or a knowledge-graph embedding model for knowledge graphs. Tensor-shaped hidden states would add cost without giving the model anything new to use.

What flattening does, and what it does not

Flattening is a reshape. It is reversible and removes no values. In row-major order, entry (c, row, col) of a [C, H, W] patch moves to position c·H·W + row·W + col. Horizontal neighbours such as pixels (3, 4) and (3, 5) stay next to each other; vertical neighbours such as (3, 4) and (4, 4) end up W positions apart.

python
import torch

x = torch.randn(10, 3, 8, 8)             # 10 nodes, each a 3x8x8 patch
x_flat = x.flatten(1)                    # [10, 192]
assert torch.equal(x_flat.reshape(10, 3, 8, 8), x)    # nothing was lost

C, H, W = 3, 8, 8
pos = lambda c, row, col: c * H * W + row * W + col
print(pos(0, 3, 5) - pos(0, 3, 4))       # horizontal neighbour
print(pos(0, 4, 4) - pos(0, 3, 4))       # vertical neighbour
assert x_flat[7, pos(2, 3, 4)] == x[7, 2, 3, 4]

Output:

text
1
8

What changes is what the next layer assumes. A dense layer, including the weight matrix inside a GCN layer, has separate weights for every input position and no concept of which positions are neighbours. If you reorder the 192 inputs the same way for every node, reordering the weights to match gives exactly the same function. A GCN shares its weights across nodes, not across positions inside a node, so any pattern based on locality has to be learned position by position.

The same reasoning applies to other kinds of internal structure:

  • Spatial. A convolution looks at a small neighbourhood and reuses the same kernel everywhere. A dense layer on the flattened patch does neither.
  • Temporal. For a window [T, D] per node, a dense layer on [T·D] can learn position-specific weights, but it does not share them across time steps. A 1-D convolution or a recurrent encoder does.
  • Volumetric. For [C, D, H, W] blocks the same argument applies on three axes, and the number of weights in a dense first layer grows with the number of voxels.
  • Multiple channels. A dense layer mixes channels anyway. Keeping the channel axis lets you share that channel mixing across positions, which is what a 1×1 convolution does.

Keeping the tensor shape is not enough

A tensor-shaped layer does not automatically use the layout. In TGraphX 1.5.1, TensorGraphSAGELayer, TensorGATLayer and TensorGINLayer with their default settings use only 1×1 convolutions on the maps, so they never look at which pixels are neighbours. If you shuffle pixel positions in the same way for every node and then average over H and W, a stack of these layers returns the same result. ConvMessagePassing is different: after aggregating messages it applies 3×3 convolutions.

python
import torch
import tgraphx as tgx

torch.manual_seed(0)
x = torch.randn(10, 3, 8, 8)
edge_index = torch.randint(0, 10, (2, 30))
perm = torch.randperm(64)
x_shuffled = x.flatten(2)[:, :, perm].reshape_as(x)     # same shuffle for all nodes

def unchanged_by_shuffle(first, second):
    first.eval()
    second.eval()
    def f(inp):
        h = torch.relu(first(inp, edge_index))
        return second(h, edge_index).mean(dim=(-2, -1))
    with torch.no_grad():
        return torch.allclose(f(x), f(x_shuffled), atol=1e-5)

for name, layer in [("SAGE", tgx.TensorGraphSAGELayer),
                    ("GAT", tgx.TensorGATLayer),
                    ("GIN", tgx.TensorGINLayer)]:
    print(name, unchanged_by_shuffle(layer(3, 8), layer(8, 8)))

print("ConvMessagePassing", unchanged_by_shuffle(
    tgx.ConvMessagePassing((3, 8, 8), (8, 8, 8), dropout_prob=0.0),
    tgx.ConvMessagePassing((8, 8, 8), (8, 8, 8), dropout_prob=0.0)))

Output:

text
SAGE True
GAT True
GIN True
ConvMessagePassing False

That invariance depends on a position-blind readout, such as the spatial mean here. A readout that keeps positions, for example flattening the final maps into a linear layer, can tell the shuffled input apart, but only through position-specific weights, as in the dense case. To exploit neighbourhoods with weights shared across positions, some part of the model needs a receptive field larger than one pixel: a CNN encoder before the GNN, or a message-passing layer with spatial convolutions.

What tensor features cost

Storing [N, C, H, W] takes the same memory as storing [N, C·H·W]. The cost appears when hidden states stay as feature maps, because every edge then carries a map-sized message:

python
import tgraphx as tgx

maps = tgx.estimate_message_memory(num_edges=10_000, out_shape=(64, 8, 8))
vectors = tgx.estimate_message_memory(num_edges=10_000, out_shape=(64,))
print(maps["total_bytes"], vectors["total_bytes"])

Output:

text
163840000 2560000

This counts only the float32 message buffer. Activations, gradients and the convolutions themselves come on top.

A test that isolates the question

A tempting comparison is "a vector GNN on flattened patches against a tensor GNN on the patches". If the two models differ in depth, width, operations and training schedule, a gap cannot be attributed to the feature shape. This also rules out the one-call classify_nodes helper for the comparison: it builds different architectures for vector and image features.

Change one thing at a time instead:

  • Same graph, same split, same GNN layers, same optimizer, epochs and model-selection rule.
  • Only the node encoder differs: an MLP on the flattened patch, or a small CNN on the patch.
  • Similar parameter counts (compute will still differ).
  • A control: apply one fixed pixel shuffle to every node. All values are kept and the layout is destroyed. An advantage that comes from layout should largely disappear.

The data below is synthetic and built so that layout matters. Each node is a noisy 8×8 patch holding a short bar, and the class is the bar's orientation. The purpose is to show the procedure and to check that it detects the effect when the effect exists. It says nothing about your data.

The graph is synthetic too: its edges are generated from the labels of all nodes, validation and test nodes included, in the style of a stochastic block model. That is acceptable only inside a data generator, where it defines the toy problem. Never build the edges of a real graph from validation or test labels. The graph also affects the accuracies, so read them only as a comparison between arms that share it.

python
import statistics
import torch
import torch.nn as nn
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx.estimators import node_train_val_test_split

def make_data(n=600, seed=0):
    gen = torch.Generator().manual_seed(seed)
    y = torch.randint(0, 3, (n,), generator=gen)
    x = 0.5 * torch.randn(n, 1, 8, 8, generator=gen)
    steps = [(0, 1), (1, 0), (1, 1)]            # horizontal, vertical, diagonal
    for i, c in enumerate(y.tolist()):
        row, col = torch.randint(0, 6, (2,), generator=gen).tolist()
        for t in range(3):
            x[i, 0, row + t * steps[c][0], col + t * steps[c][1]] += 2.0

    # Link each node to two others: same class with probability 0.6.
    members = [(y == c).nonzero().flatten() for c in range(3)]
    pairs = []
    for i, c in enumerate(y.tolist()):
        for _ in range(2):
            same = torch.rand((), generator=gen).item() < 0.6
            other = (c + 1 + torch.randint(0, 2, (), generator=gen).item()) % 3
            pool = members[c if same else other]
            j = pool[torch.randint(0, len(pool), (), generator=gen)].item()
            if i != j:
                pairs += [(j, i), (i, j)]
    edge_index = torch.unique(torch.tensor(pairs).t(), dim=1)
    return x, edge_index, y

def flat_encoder():
    return nn.Sequential(nn.Flatten(), nn.Linear(64, 15), nn.ReLU(),
                         nn.Linear(15, 16), nn.ReLU())

def conv_encoder():
    return nn.Sequential(nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(),
                         nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(),
                         nn.AdaptiveMaxPool2d(1), nn.Flatten())

class NodeModel(nn.Module):
    def __init__(self, encoder):
        super().__init__()
        self.encoder = encoder                   # patch -> 16 values per node
        self.gcn1 = tgx.GCNConv(16, 16)
        self.gcn2 = tgx.GCNConv(16, 3)

    def forward(self, x, edge_index):
        h = F.relu(self.gcn1(self.encoder(x), edge_index))
        return self.gcn2(h, edge_index)

def run(make_encoder, x, edge_index, y, seed, epochs=60):
    tgx.set_seed(seed)
    train, val, test = node_train_val_test_split(y.numel(), 0.4, 0.2, 0.4, seed=seed)
    model = NodeModel(make_encoder())
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
    best_val, test_at_best = -1.0, 0.0
    for _ in range(epochs):
        model.train()
        optimizer.zero_grad()
        F.cross_entropy(model(x, edge_index)[train], y[train]).backward()
        optimizer.step()
        model.eval()
        with torch.no_grad():
            correct = model(x, edge_index).argmax(1) == y
        val_acc = correct[val].float().mean().item()
        if val_acc > best_val:                   # choose the epoch on validation only
            best_val, test_at_best = val_acc, correct[test].float().mean().item()
    return test_at_best

x, edge_index, y = make_data()
perm = torch.randperm(64, generator=torch.Generator().manual_seed(123))
x_shuffled = x.flatten(1)[:, perm].reshape_as(x)

arms = [("MLP encoder", flat_encoder), ("CNN encoder", conv_encoder)]
for name, make_encoder in arms:
    print(name, "parameters:", tgx.count_parameters(NodeModel(make_encoder())))

for data_name, data in [("original", x), ("shuffled", x_shuffled)]:
    for name, make_encoder in arms:
        acc = [run(make_encoder, data, edge_index, y, seed) for seed in range(5)]
        print(f"{data_name:9s} {name}: "
              f"{statistics.mean(acc):.3f} +/- {statistics.stdev(acc):.3f}")

Output from one CPU run. The figures are the mean and standard deviation of test accuracy at the best validation epoch over five seeds, each of which changes the split and the initialisation. Chance is about 0.33, and the last digit can differ between machines.

text
MLP encoder parameters: 1554
CNN encoder parameters: 1571
original  MLP encoder: 0.592 +/- 0.025
original  CNN encoder: 0.848 +/- 0.014
shuffled  MLP encoder: 0.620 +/- 0.029
shuffled  CNN encoder: 0.562 +/- 0.014

On the original patches the CNN encoder is well ahead. After the shuffle its advantage is gone, while the MLP stays about where it was. In this constructed task the gap therefore came from spatial layout. If a convolutional arm on your data still wins after the shuffle, something other than layout explains at least part of the difference.

To also ask whether the map has to survive message passing, add a third arm that replaces the encoder-then-GCN design with ConvMessagePassing layers and compare it with the CNN-encoder arm.

For your own task, tune the learning rate and size of each arm on the validation set (this example fixes them), and report the spread over seeds next to the mean. If the arms are within that spread, take the simpler flat version.

Candidates worth testing

These data types have internal axes, so the test above is worth running. They are hypotheses, not results:

  • Image-patch graphs where each patch keeps spatial coherence.
  • Medical imaging graphs with a volume per node.
  • Robotics or sensor graphs where each node carries a grid or a time window.
  • Citation or interaction graphs where each node carries an ordered sequence of embeddings.

Bag-of-words features (as in Cora, CiteSeer and PubMed), categorical atom descriptors and ID embeddings have no internal axis to preserve: the order of their entries is arbitrary.

One limitation matters for the sequence cases: no message-passing layer in TGraphX 1.5.1 models a time axis inside a node feature. GCNConv, GATv2Conv and the convolutional tensor layers (ConvMessagePassing and the SAGE, GAT and GIN layers) reject [N, T, D]. Do not count on an error everywhere, though. LinearMessagePassing, AttentionMessagePassing and NodeClassifier built with in_shape=(D,) accept it, and time order never enters: reordering the steps only reorders the output. LinearMessagePassing, and therefore NodeClassifier, treats each step independently. AttentionMessagePassing links the steps only through an attention score summed over them.

So encode each sequence first, or write your own message function. For a recurrent encoder, TGraphX has an experimental LSTM, GraphSequenceEncoder in tgraphx.mining, which takes [N, T, D] and returns one vector per node. The block below puts a minimal Conv1d encoder in front of a vector GNN, repeats the step with the LSTM, and ends with the silent case:

python
import torch
import torch.nn as nn
import tgraphx as tgx

x_seq = torch.randn(50, 5, 8)                    # [N, T, D]
edge_index = torch.randint(0, 50, (2, 200))
temporal = nn.Conv1d(8, 16, kernel_size=3, padding=1)
gnn = tgx.GCNConv(16, 16)

h = torch.relu(temporal(x_seq.transpose(1, 2)))  # [N, 16, T]
out = gnn(h.mean(dim=-1), edge_index)            # [N, 16]
print(list(out.shape))

# Alternative encoder: a recurrent model over the T steps.
lstm = tgx.mining.GraphSequenceEncoder(input_dim=8, hidden_dim=16)
assert gnn(lstm(x_seq), edge_index).shape == (50, 16)

# Trap: a layer built for [N, 8] also runs on [N, 5, 8].
silent_layer = tgx.LinearMessagePassing((8,), (16,))
silent = silent_layer(x_seq, edge_index)         # no error
order = torch.tensor([4, 3, 2, 1, 0])            # reverse time
assert silent.shape == (50, 5, 16)
assert torch.allclose(silent_layer(x_seq[:, order], edge_index),
                      silent[:, order], atol=1e-5)

Output:

text
[50, 16]

Decision rule

If you cannot say which structure inside a node a flat model would ignore, use flat vectors. If you can say it ("which pixels are adjacent", "which time step came first"), build both arms and let a controlled measurement decide.

Using both libraries

Choosing tensor features does not tie you to one library. PyTorch Geometric's Data can hold [N, C, H, W] features, and a custom MessagePassing layer can operate on them (set node_dim=0), although most of its built-in convolutions expect vectors. tgraphx.interop provides to_pyg_data and from_pyg_data, and in 1.5.1 you have to handle train, validation and test masks yourself in both directions. from_pyg_data does not carry them over, so reattach them. to_pyg_data does not set data.train_mask, data.val_mask or data.test_mask: it nests the masks under data.metadata["masks"]. Assign them before any PyG-style code reads them:

python
import torch
import tgraphx as tgx
from tgraphx.interop import to_pyg_data

split = torch.tensor([0, 0, 0, 0, 1, 2])         # 0 train, 1 validation, 2 test
g = tgx.Graph(node_features=torch.randn(6, 4),
              edge_index=torch.tensor([[0, 1], [1, 2]]),
              train_mask=split == 0, val_mask=split == 1, test_mask=split == 2)

data = to_pyg_data(g)
assert getattr(data, "train_mask", None) is None  # not set by the converter
for name in ("train", "val", "test"):
    data[f"{name}_mask"] = data.metadata["masks"][name]
assert torch.equal(data.train_mask, split == 0)

FAQ

Q: Is there a quick way to check whether structure inside a node matters?

A: Ignore the graph and compare two per-node classifiers on the same split: an MLP on the flattened feature and a CNN (or temporal encoder) on the shaped feature. Then add the graph and repeat, because neighbour information can shrink or enlarge the gap.

Q: Does TGraphX work for molecular graphs?

A: It can, with limits. GCNConv and GATv2Conv take vector atom features but no bond features. For bond features, one option is TensorGINLayer with use_edge_features=True and edge_features_kind="vector", giving the atom features two unit axes (x[:, :, None, None]). PyTorch Geometric ships many more molecule-specific layers, so it is usually the more convenient choice unless your atoms carry tensor features.

Q: What about node features that are short sequences (T=5, D=8)?

A: That is 40 values per node, and flattening keeps all of them. Try the dense baseline first, then compare it with a small 1-D convolution or recurrent encoder.

Q: How do I convert between tensor and flat representations safely?

A: tgx.Graph accepts both. Use g.node_features.flatten(1) to flatten (it also works on non-contiguous tensors, where view can fail) and reshape to restore the shape. tgx.assert_tensor_native(g, min_rank=3) raises unless node_features has at least three dimensions, counting the node axis. It does not check what the axes mean.