TGraphX › Insights › Image, Volume and Sequence Node Features: Which TGraphX Layers Accept Them
← Back to Insights

Image, Volume and Sequence Node Features: Which TGraphX Layers Accept Them

Topic: Vision, multimodal and domain applications

A node feature does not have to be a vector. An image patch is naturally [C, H, W], a block of a 3-D scan is [C, D, H, W], and a windowed signal is [T, D]. TGraphX can store any of these in a Graph, but storing a shape and processing it are different things: its built-in tensor layers cover image-shaped and volume-shaped nodes, not sequence-shaped ones. This note shows what works out of the box, what needs a reshape or a custom layer, and how to combine modalities in one graph.

Examples tested with TGraphX 1.5.1.

Which shapes have built-in support

A single Graph holds one node-feature tensor, so all of its nodes share one per-node shape.

Per-node shape Typical source How to build nodes Built-in layers
(D,) embeddings, tabular rows any [N, D] tensor GCNConv, GATv2Conv, LinearMessagePassing
(C, H, W) image patches, regions image_to_patches, image_to_patch_graph ConvMessagePassing, TensorGraphSAGELayer, TensorGATLayer, TensorGINLayer
(C, D, H, W) volume blocks volume_to_patches the same four layers
(T, D) or (C, L) signals, token windows your own windowing code none models the time or length axis (two vector layers run on it silently, see below): reshape, write one, or encode to vectors

TensorGraphSAGELayer, TensorGATLayer and TensorGINLayer default to 2-D data; pass spatial_rank=3 for volumes. How these layers form messages is covered in Inside Tensor Message Passing.

Image patches as nodes

image_to_patch_graph takes one [C, H, W] image and returns a tuple (node_features, edge_index), not a Graph. Wrap it yourself:

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

torch.manual_seed(0)
image = torch.randn(3, 32, 32)                      # one synthetic [C, H, W] image

x_img, ei_img = tgx.image_to_patch_graph(image, patch_size=8)
g_img = tgx.Graph(node_features=x_img, edge_index=ei_img)
print(g_img.num_nodes, g_img.feature_shape, g_img.num_edges)   # 16 (3, 8, 8) 64

sage = tgx.TensorGraphSAGELayer(in_channels=3, out_channels=16)
conv = tgx.ConvMessagePassing((3, 8, 8), (16, 8, 8), dropout_prob=0.0)

print(sage(g_img.node_features, g_img.edge_index).shape)       # [16, 16, 8, 8]
print(conv(g_img.node_features, g_img.edge_index).shape)       # [16, 16, 8, 8]

The edges form a 4-neighbour grid over the patch positions, with both directions and one self-loop per node. TensorGraphSAGELayer already has a separate self term, so pass self_loops=False if you do not want a node counted again among its neighbours. image_to_patch_graph requires H and W to be divisible by patch_size. For overlapping or padded patches, call image_to_patches(images, patch_size, stride=..., padding="auto") on a [B, C, H, W] batch; it returns [B, P, C, ph, pw]. patch_grid_shape gives the grid size for build_grid_graph when the patches cover the image exactly (it raises otherwise, so compute it from the padded size in that case).

The layer choice matters for what happens inside a patch. The three Tensor* layers transform features with 1×1 convolutions, but they differ in what can cross pixel positions:

  • With TensorGraphSAGELayer and TensorGINLayer at their default settings (for GIN that includes use_batchnorm=False), an output pixel depends only on the same pixel position in the node and its neighbours.
  • TensorGATLayer keeps its values per position, but it computes each attention weight from patch features averaged over all spatial positions. Changing one pixel of a neighbouring patch can therefore change every position of the output.
  • ConvMessagePassing adds a stack of 3×3 convolutions after aggregation, which also mixes nearby positions within the feature map.

For more on the construction choices, see Image Patches as Graph Nodes.

Volume blocks as nodes

The 3-D path uses volume_to_patches, whose output is [B, P, C, d, h, w], plus a 6-neighbour grid from build_grid_graph_3d:

python
volume = torch.randn(1, 1, 16, 32, 32)              # [B, C, D, H, W]
blocks = tgx.volume_to_patches(volume, patch_size=8)
print(blocks.shape)                                 # [1, 32, 1, 8, 8, 8]

n_d, n_h, n_w = tgx.volume_patch_grid_shape(16, 32, 32, 8)     # (2, 4, 4)
x_vol = blocks[0]                                   # [32, 1, 8, 8, 8]
ei_vol = tgx.build_grid_graph_3d(n_d, n_h, n_w)
g_vol = tgx.Graph(node_features=x_vol, edge_index=ei_vol)

sage3d = tgx.TensorGraphSAGELayer(1, 8, spatial_rank=3)
conv3d = tgx.ConvMessagePassing((1, 8, 8, 8), (8, 8, 8, 8), dropout_prob=0.0)

print(sage3d(g_vol.node_features, g_vol.edge_index).shape)     # [32, 8, 8, 8, 8]
print(conv3d(g_vol.node_features, g_vol.edge_index).shape)     # [32, 8, 8, 8, 8]

Patch order is depth, then row, then column, which matches the node numbering of build_grid_graph_3d. To put several volumes (or images) in one batch, build one Graph per item and wrap the list in GraphBatch, which offsets the edge indices for you.

Sequence nodes: storage works, layers need help

A Graph accepts [N, T, D] features, but no shipped message-passing layer models a time axis inside a node feature. ConvMessagePassing((T, D), ...) and LinearMessagePassing((T, D), ...) raise ValueError at construction, the Tensor* layers raise on a rank-3 input, and GCNConv and GATv2Conv expect [N, D]. The legacy AttentionMessagePassing accepts a two-element shape at construction but does not support it: it treats the edge axis as channels, so it usually raises in the forward pass, and when the number of edges happens to equal the first shape dimension it can run and return meaningless output. Do not use it for sequences. The one-element form is quieter: LinearMessagePassing and AttentionMessagePassing built with in_shape=(D,) run on [N, T, D] without an error. That is not sequence support, so check x.dim() == 2 before a vector layer, or encode the sequence first. There is also no sequence-to-graph builder: you decide what a node is and which nodes are connected.

python
seq = torch.randn(16, 24, 8)                        # 16 nodes, T=24 steps, D=8 channels
ei_seq = tgx.build_knn_graph(seq.flatten(1), k=3, directed=False, self_loops=False)
g_seq = tgx.Graph(node_features=seq, edge_index=ei_seq)
print(g_seq.feature_shape)                          # (24, 8): stored as-is

try:
    tgx.TensorGraphSAGELayer(8, 16)(g_seq.node_features, g_seq.edge_index)
except ValueError as err:
    print(err)                                      # x must have shape [N, C, H, W] ...

Route 1: treat the sequence as a one-row image. Move the feature dimension to the channel axis and add a height of 1, giving [N, D, 1, T]:

python
x_seq = g_seq.node_features.transpose(1, 2).unsqueeze(2)       # [16, 8, 1, 24]
out = tgx.TensorGraphSAGELayer(8, 16)(x_seq, g_seq.edge_index)
print(out.shape)                                               # [16, 16, 1, 24]

Be clear about what this computes. With TensorGraphSAGELayer or TensorGINLayer at their default settings, step t of an output depends only on step t of the node and its neighbours, and the same weights are used at every step. Neither layer mixes time steps. That is reasonable when the sequences are time-aligned (for example sensors sampled on a shared clock) and wrong when they are not.

Two other layers accept the same input and do mix time steps:

  • TensorGATLayer has per-step values, but its attention weights come from features averaged over all time steps, so later steps can influence earlier outputs.
  • ConvMessagePassing with shape (8, 1, 24) mixes steps through its 3×3 stack (effectively width-3 convolutions along time). Those convolutions are centred, not causal. Its aggregator also uses BatchNorm by default, which in training mode pools statistics over all nodes and time steps, so making the convolutions causal would not be enough.

If the output at step t must depend only on data up to t, as in step-by-step forecasting, do not use either of these two unchanged. Build the graph from past data only as well: the k-NN edges above were computed from whole sequences.

Route 2: write a layer with 1-D convolutions. Subclass TensorMessagePassingLayer and define the message and update steps; the base class handles indexing and aggregation:

python
class SequenceConv(tgx.TensorMessagePassingLayer):
    """Mean-aggregating message passing for [N, C, L] node features."""

    def __init__(self, in_channels, out_channels, length):
        super().__init__((in_channels, length), (out_channels, length), aggr="mean")
        self.msg = nn.Conv1d(2 * in_channels, out_channels, kernel_size=3, padding=1)
        self.self_map = nn.Conv1d(in_channels, out_channels, kernel_size=1)

    def message(self, src, dest, edge_attr):
        return self.msg(torch.cat([src, dest], dim=1))

    def update(self, node_feature, aggregated_message):
        return torch.relu(self.self_map(node_feature) + aggregated_message)


x_cl = g_seq.node_features.transpose(1, 2)                     # [16, 8, 24] = [N, C, L]
layer = SequenceConv(8, 16, length=24)
print(layer(x_cl, g_seq.edge_index).shape)                     # [16, 16, 24]

As written, SequenceConv is centred too (kernel_size=3, padding=1), so step t reads step t + 1. For forecasting, pad on the left only (build the convolution with padding=0 and apply torch.nn.functional.pad(z, (2, 0)) to its input z) so that it is causal.

Route 3: encode each sequence to a vector. A 1-D CNN or recurrent network per node, followed by an ordinary vector GNN, is simpler still. TGraphX ships a recurrent encoder that fits, tgraphx.mining.sequence_models.GraphSequenceEncoder (Experimental, an LSTM). It was written for graph traversal sequences, but it accepts [N, T, D] node features and treats each node as one batch item:

python
from tgraphx.mining.sequence_models import GraphSequenceEncoder

encoder = GraphSequenceEncoder(input_dim=8, hidden_dim=32)     # last hidden state per node
h_seq = encoder(g_seq.node_features)                           # [16, 32]
print(tgx.GCNConv(32, 16)(h_seq, g_seq.edge_index).shape)      # [16, 16]

Mixing modalities in one graph

Because one Graph has one node shape, image nodes and signal nodes cannot sit in it side by side in raw form. Encode each modality to a common size first, then concatenate and offset the node indices:

python
n_img, n_sig = 16, 5
patches = x_img                                     # [16, 3, 8, 8] from the image above
signals = torch.randn(n_sig, 8, 24)                 # [5, C=8, L=24]

img_encoder = tgx.CNNEncoder(3, 32, num_layers=2, hidden_channels=16,
                             dropout_prob=0.0, use_residual=False)
sig_encoder = nn.Sequential(nn.Conv1d(8, 32, kernel_size=3, padding=1), nn.ReLU(),
                            nn.AdaptiveAvgPool1d(1), nn.Flatten())

h = torch.cat([img_encoder(patches), sig_encoder(signals)], dim=0)    # [21, 32]

grid = tgx.build_grid_graph(4, 4, self_loops=False)  # GCNConv adds self-loops itself
# Illustrative relation: signal j describes patch j (signal indices offset by n_img).
pairs = torch.stack([torch.arange(n_sig), n_img + torch.arange(n_sig)])
edge_index = torch.cat([grid, pairs, pairs.flip(0)], dim=1)

gcn = tgx.GCNConv(32, 16)
print(gcn(h, edge_index).shape)                     # [21, 16]

The encoders are ordinary PyTorch modules, so they train jointly with the GNN if you give the optimizer all of their parameters. Two details: CNNEncoder returns a pooled vector by default (set return_feature_map=True to keep a spatial map), and in 1.5.1 its default use_residual=True fails with a size-mismatch error together with the default two pooling layers, hence use_residual=False here.

If you want each node type to keep its own raw tensor, HeteroGraph (Experimental) can store a different shape per type. You still need per-type projections before message passing, because relation layers need compatible source and destination shapes. See Different node types, different modalities for the heterogeneous side.

A static sequence is not a temporal graph

Keep two situations apart. A fixed window stored on each node is a tensor-valued feature on an ordinary graph, handled as above. A graph whose edges or snapshots change over time belongs to the Experimental temporal subsystem (TemporalGraphSequence, and TGATConv and TGNMemory in tgraphx.temporal). Note that TGATConv does not drop future edges for you; filter by timestamp yourself.

Why preserve the structure, and what it does not promise

Keeping [C, H, W] lets convolutional messages use pixel locality, which is the motivation of the TGraphX preprint. The graph adds relations between nodes on top of structure within them, the distinction discussed in Topology vs Feature Geometry.

Three limits are worth stating in a paper or report:

  • This is not automatic cross-modal fusion. Aligning modalities, choosing encoders and deciding which nodes connect are modelling decisions you make.
  • Grid adjacency encodes position, not meaning. Compare it with a similarity-based graph and with no edges at all.
  • Whether tensor-valued nodes beat a plain CNN, a recurrent model or a flat-feature GNN on your task is empirical. Preserving structure is an inductive bias, not a guarantee, and it costs memory: every edge carries a full message tensor.

Related guides

Conclusion

Image patches and volume blocks are first-class tensor nodes in TGraphX: build them with the patch helpers and pass them to a layer of the matching spatial rank. Sequences can be stored, but you either reshape them to [N, D, 1, T] with a clear idea of what mixes with what, write a small 1-D message-passing layer, or encode them to vectors. For mixed modalities, project to a shared shape before building one graph.