TGraphX › Insights › TGraphX Architecture Reference: Paper vs Released Package
← Back to Insights

TGraphX Architecture Reference: Paper vs Released Package

Topic: Tensor-valued nodes, edges and message passing

TGraphX is a name for two related things. One is the architecture in the preprint TGraphX: Tensor-Aware Graph Neural Network for Multi-Dimensional Feature Learning (Sajjadi and Eramian, 2025): a CNN turns image patches into feature maps, those maps become graph nodes, and convolutional message passing refines them without flattening. The other is the tgraphx Python package, version 1.5.1, which implements that pipeline and also ships a good deal that the paper never discusses.

If you only want the data container, start with what a TGX graph is. This page maps one onto the other. It follows the data from image to class score, gives the tensor shape at each stage, names the released symbol, and says where the package departs from the equations. In short:

Question Short answer
What is a node? A tensor, for the paper a feature map [C, H, W]; the package also takes volumes [C, D, H, W] and vectors [d] with matching layers
What is a message? A 1×1 convolution over the concatenated source and destination maps
What is the update? A stack of 3×3 convolutions applied to the summed messages, with an optional skip connection (off by default in the package)
What is the output? Spatial average pooling to a vector, then a linear classifier
Who builds the graph? You do. No model in the pipeline infers edges from the images

Statements about the paper refer to arXiv version 1. Statements about code refer to tgraphx 1.5.1 and were checked against its source or by running it on CPU. The code blocks run in order.

Notation

A directed graph is G = (V, E) with N nodes and E edges (the set and its size share a letter, as in the paper). An edge goes from source i to destination j, and edge_index stores sources in row 0 and destinations in row 1. N(j) is the set of sources of edges that end at j.

All tensors are channels-first. Node features are [N, C, H, W], one node is x_j with shape [C, H, W], and the number of spatial positions is S = H·W. One message-passing layer then reads:

text
m_ij = phi(x_i, x_j)                  [C', H, W]   one per edge
a_j  = sum over i in N(j) of m_ij     [C', H, W]   one per node
x'_j = psi(x_j, a_j)                  [C', H, W]

This is the generic message-passing template of Gilmer and co-authors and of the graph-network framework of Battaglia and co-authors. Nothing in the template requires x_j to be a vector. What changes with tensor nodes is the choice of phi and psi: they can be convolutions, because the grid inside each node still exists.

The pipeline stage by stage

TGraphX data flow with shapes for the example on this page

1. Patch extraction2. CNN encoder3. Graph and batch4. Message and sum5. Update6. Pool and classify
Inputs and outputs of every stage
stageinputoutputwhat happens
1. Patch extractionimages [2, 3, 32, 32]patches [32, 3, 8, 8]image_to_patches returns [B, P, C, ph, pw] in row-major order; flatten the first two axes to get one row per node.
2. CNN encoderpatches [32, 3, 8, 8]node maps [32, 16, 4, 4]CNNEncoder with return_feature_map=True keeps a spatial grid per patch instead of returning a vector.
3. Graph and batch16 node maps per imageedge_index [2, 128]You supply edges, here a 4 by 4 grid with self-loops per image; GraphBatch offsets the node ids.
4. Message and sumnode maps and edge_indexper node [32, 32, 4, 4]A 1x1 convolution on concatenated source and destination maps, then a sum over incoming edges.
5. Updatesummed messagesnode maps [32, 32, 4, 4]Four 3x3 convolutions by default; a skip connection only if residual=True and the shapes match.
6. Pool and classifynode maps [32, 32, 4, 4]node [32, 3], graph [2, 3]Mean over spatial positions, then a linear layer, with an optional mean over the nodes of each graph.

Stage 1 of 6, Patch extraction. Input: images [2, 3, 32, 32]. Output: patches [32, 3, 8, 8].

Two 32 by 32 images, 8 by 8 patches, a 4 by 4 grid of nodes per image. Shapes match the runnable code; the figure computes nothing. A schematic of the stages as described by the author; nothing is executed.

Patch extraction

The paper splits an image into N patches (Eq. 3 and 4). The package function tgx.image_to_patches(images, patch_size) takes [B, C, H, W] and returns [B, P, C, ph, pw], with patches in row-major order, the same order tgx.build_grid_graph uses for node ids. By default the image size must divide exactly; padding="auto" pads the right and bottom edges instead.

Encoding patches into node tensors

The paper allows an optional pre-encoder (Eq. 5) before a CNN encoder (Eq. 6). The encoder uses blocks of 3×3 convolution, batch normalisation and ReLU, with max pooling applied only when the map is large enough, plus residual blocks.

The package equivalents are PreEncoder and CNNEncoder in tgraphx.models. One argument matters more than the rest: return_feature_map defaults to False, and then the encoder pools globally and returns a vector [N, out_features]. For spatial nodes you need return_feature_map=True.

Set the pooling depth too. With the default use_residual=True and pool_layers=2, the forward pass raises a size-mismatch RuntimeError for patches of 8 pixels or more, because the skip path is not downsampled along with the second pooling block. Pass pool_layers=1 or use_residual=False; the same applies to the cnn_params of CNN_GNN_Model.

The paper does not report the layer counts, channel widths or pooling depth used in its experiment, so no configuration of this class can be called "the paper's encoder".

Graph construction and batching

The paper defines neighbourhoods by patch proximity, N(j) = {i : d(P_i, P_j) ≤ τ} (Eq. 9), without fixing the distance d or the threshold τ. Its car-detection experiment uses a different graph altogether, built from detector boxes and their union.

In the package, topology is an input. tgraphx.Graph stores node_features and edge_index (plus optional edge weights, edge features, labels and masks), and tgraphx.graph_builders offers grid, k-nearest-neighbour, radius, fully connected and IoU builders. build_grid_graph adds self-loops unless you pass self_loops=False. The container is described field by field in Reading the TGraphX Source, and the difference between graph distance and pixel distance in topology versus feature geometry.

GraphBatch concatenates the node tensors and adds the node count of all earlier graphs to each graph's edge ids, which is the offset rule the paper states in section 3.2.1. All nodes in a batch need the same shape, and node masks are not concatenated; see Graph and GraphBatch internals.

Message and aggregation

The paper's message (Eq. 10) and aggregation (Eq. 11) are

text
m_ij = Conv1x1( concat(x_i, x_j, e_ij) )
a_j  = sum over i in N(j) of m_ij

tgx.ConvMessagePassing implements this directly. The 1×1 convolution mixes channels at each position independently, so position (h, w) of a message depends only on position (h, w) of its two endpoint maps. Optional edge features must have the same channel count and spatial rank as the node features. The package also offers aggr="mean" and aggr="max".

Update

The paper's update (Eq. 12) is x'_j = x_j + A(a_j), where A is a deep CNN aggregator. The released layer computes

text
u_j  = Pool( A(a_j) )
x'_j = x_j + u_j    if residual=True and the shapes are equal, else u_j

A is DeepCNNAggregator: by default four 3×3 convolutions, each followed by batch normalisation and ReLU, with dropout probability 0.0 unless you ask for more. Pool is the identity unless the spatial size in out_shape differs from in_shape. Two consequences follow. First, residual is False by default, and with True it is skipped without any message when channels or spatial size change. Second, one default layer sees one graph hop but a 9×9 window of feature positions, because four 3×3 convolutions give a receptive field of 1 + 4·2 = 9. The message-passing walkthrough measures that window.

Readout and classifier

The paper pools each node map over space (Eq. 13) and applies a linear map (Eq. 14):

text
z_j = (1 / (H*W)) * sum over h, w of x_j[:, h, w]      [C]
y_j = W_out z_j + b                                    [Q]

with Q classes. The printed paper gives the weight matrix the shape C×Q; for the product as written to exist it must be Q×C, which is what torch.nn.Linear(C, Q) stores. For graph-level tasks the paper says node pooling (mean or sum) can be added.

There is no readout class to look for in the package. The spatial mean is a line inside the model classes, and the node-level pooling is done by global_mean_pool, global_sum_pool and global_max_pool, which reduce over nodes only and keep every trailing axis. See pooling and readout.

One runnable pipeline, with shapes

The following builds the whole path from two random images to class scores. Random data means the scores are meaningless; the point is the shapes and the wiring.

python
import torch
import torch.nn as nn
import tgraphx as tgx
from tgraphx.models import CNNEncoder

torch.manual_seed(0)
images = torch.rand(2, 3, 32, 32)                       # [B, C, H, W]
patches = tgx.image_to_patches(images, patch_size=8)
print("patches", tuple(patches.shape))

encoder = CNNEncoder(in_channels=3, out_features=16, num_layers=3, hidden_channels=32,
                     dropout_prob=0.0, pool_layers=1, return_feature_map=True).eval()
feats = encoder(patches.flatten(0, 1))                  # one row per patch
print("encoded", tuple(feats.shape))

grid = tgx.build_grid_graph(4, 4)                       # self-loops included
graphs = [tgx.Graph(node_features=f, edge_index=grid)
          for f in feats.view(2, 16, 16, 4, 4)]
batch = tgx.GraphBatch(graphs)
print("batched", tuple(batch.node_features.shape), tuple(batch.edge_index.shape))

conv1 = tgx.ConvMessagePassing((16, 4, 4), (32, 4, 4), dropout_prob=0.0).eval()
conv2 = tgx.ConvMessagePassing((32, 4, 4), (32, 4, 4), dropout_prob=0.0,
                               residual=True).eval()
h = torch.relu(conv1(batch.node_features, batch.edge_index))
h = conv2(h, batch.edge_index)
print("message passing", tuple(h.shape))

head = nn.Linear(32, 3)
z = h.mean(dim=(2, 3))                                  # spatial mean per node
node_logits = head(z)
graph_logits = head(tgx.global_mean_pool(z, batch.batch))
print("z", tuple(z.shape), "node", tuple(node_logits.shape),
      "graph", tuple(graph_logits.shape))

for name, module in [("encoder", encoder), ("conv1", conv1),
                     ("conv2", conv2), ("head", head)]:
    print(f"{name:8s}{sum(p.numel() for p in module.parameters()):>7d} parameters")

Output:

text
patches (2, 16, 3, 8, 8)
encoded (32, 16, 4, 4)
batched (32, 16, 4, 4) (2, 128)
message passing (32, 32, 4, 4)
z (32, 32) node (32, 3) graph (2, 3)
encoder   22224 parameters
conv1     38304 parameters
conv2     39328 parameters
head         99 parameters

The 128 edges are 64 per image: 48 directed links between 4-neighbours and 16 self-loops. In conv1, only 1,056 of the 38,304 parameters belong to the 1×1 message convolution; the other 37,248 sit in the aggregator. If you describe the layer as "1×1 message passing", you are describing the smaller part of it.

Parameter counts do not depend on H or W, but memory does. The message buffer holds E·C'·S numbers:

python
estimate = tgx.estimate_message_memory(num_edges=batch.edge_index.size(1),
                                       out_shape=(32, 4, 4))
print(estimate["total_bytes"])      # 128 edges * 32 channels * 16 positions * 4 bytes
assert estimate["total_bytes"] == 128 * 32 * 16 * 4

That figure is the message tensor alone. The concatenated source and destination tensor and the activations kept for the backward pass come on top.

The packaged models compose the stages differently

You rarely need to write the loop above. The package has model classes, but they do not all wire the stages the same way.

CNN_GNN_Model is the closest to the paper's figure: encoder, a stack of ConvMessagePassing layers, spatial mean, optional mean over the nodes of each graph, linear classifier. The optional direct skip from the CNN to the classifier in the caption of the paper's Figure 1 is skip_cnn_to_classifier (default False): it adds the encoder maps to the output of the last graph layer before spatial pooling, and does nothing, without an error, if the two shapes differ, as with the 16 and 32 channels used here. The following confirms the default path by recomputing its output by hand:

python
from tgraphx.models import CNN_GNN_Model

torch.manual_seed(0)
model = CNN_GNN_Model(
    cnn_params=dict(in_channels=3, out_features=16, num_layers=3, hidden_channels=32,
                    dropout_prob=0.0, pool_layers=1, return_feature_map=True),
    gnn_in_dim=(16, 4, 4), gnn_hidden_dim=(32, 4, 4), num_classes=3,
    num_gnn_layers=2, residual=True).eval()
raw = patches.flatten(0, 1)

with torch.no_grad():
    out = model(raw, batch.edge_index, batch=batch.batch)
    x = model.encoder(raw)
    for layer in model.gnn_layers:
        x = torch.relu(layer(x, batch.edge_index))      # ReLU after every layer
    pooled = tgx.global_mean_pool(x.mean(dim=(2, 3)), batch.batch)
    assert torch.allclose(out, model.classifier(pooled))

    edge_maps = torch.randn(batch.edge_index.size(1), 16, 4, 4)
    with_edges = model(raw, batch.edge_index, edge_features=edge_maps, batch=batch.batch)
    assert torch.equal(with_edges, out)                 # edge features have no effect
print(tuple(out.shape), tuple(model.classifier.weight.shape))   # (2, 3) (3, 32)

Two behaviours in that block are not visible in the equations. A ReLU follows every graph layer. And forward accepts edge_features but the model builds its layers with use_edge_features=False, so they are ignored without an error. In this configuration the residual=True flag also applies to the second layer only, because the first changes the channel count from 16 to 32.

Class or function Node input Activation after graph layers Order of reductions Output
CNN_GNN_Model raw patches [N, C, h, w] ReLU after each spatial mean, then node mean if batch is given graph or node logits
GraphClassifier spatial [N, C, H, W] or volume ReLU after each node pooling (mean, sum, max), then spatial mean graph logits; batch is required
build_model(task, layer=...) depends on the layer ReLU after each spatial mean, then node pooling for graph tasks linear head
NodeClassifier vectors [N, d] ReLU after each, including the last none non-negative scores

GraphClassifier and NodeClassifier have no residual argument, so the residual update of Eq. 12 cannot be requested through them; CNN_GNN_Model(residual=True) and build_model(..., layer="conv", residual=True) pass it to their layers.

Mean and sum pooling give the same result in either order; max pooling does not. build_model accepts layer="conv", "gat", "sage", "gin" or "linear" among others, and silently ignores keyword arguments it does not know.

What the package contains beyond the paper

The paper describes one operator family for spatial nodes. Version 1.5.1 ships considerably more. None of the following was evaluated in the preprint.

  • Other tensor layers. TensorGATLayer attends by default with one score per edge and head, computed from spatially pooled maps. TensorGraphSAGELayer and TensorGINLayer use 1×1 convolutions only, so they never mix feature positions.
  • Vector layers. GCNConv, GATv2Conv, APPNP and LinearMessagePassing work on [N, d] features.
  • Edge tensors. The layers accept edge information in different forms; see tensor-valued edge features.
  • Set attention. TGraphXSetAttention ignores edge_index and relates all nodes of a graph to each other.
  • Scale. Neighbour, GraphSAINT and Cluster-GCN sampling.
  • Other subsystems. Heterogeneous and temporal graphs, knowledge-graph embeddings, generation, evolutionary search, reinforcement learning and mining. Most are labelled Beta or Experimental, and several behave in ways worth testing before you rely on them. The capability map routes each task to its module.

The paper's composite loss (cross-entropy with a ranking term or an IoU term, Eq. 15 and 17 to 19) and its detector pipeline are not part of the installed package, so the reported experiment cannot be rerun from pip install tgraphx alone.

Stability labels

Three sources label the API, and they cover different names. The registry behind tgx.api_status(name) can be queried from code:

python
for name in ["Graph", "GraphBatch", "ConvMessagePassing", "TensorGATLayer",
             "build_grid_graph", "NeighborLoader", "HeteroGraph",
             "build_model", "CNNEncoder"]:
    try:
        print(f"{name:20s}{tgx.api_status(name)}")
    except KeyError:
        print(f"{name:20s}not in the registry")

Output:

text
Graph               stable
GraphBatch          stable
ConvMessagePassing  stable
TensorGATLayer      stable
build_grid_graph    stable
NeighborLoader      beta
HeteroGraph         experimental
build_model         not in the registry
CNNEncoder          not in the registry

The repository's API stability document additionally lists build_model, GraphClassifier, NodeClassifier, fit and all graph builders as Stable. As of 1.5.1 it does not list CNNEncoder, PreEncoder, DeepCNNAggregator or CNN_GNN_Model, the classes closest to the paper's pipeline.

The third source is the README at the same tag. Its "Stable core APIs" table lists CNNEncoder as the CNN patch encoder, so the README presents it as stable while the registry and the stability document do not list it. For PreEncoder, DeepCNNAggregator and CNN_GNN_Model, no stability promise is written down in any of the three. A missing entry is not a statement that something is unstable. The package as a whole is classified Beta.

Three reductions that are easy to confuse

A tensor graph has more axes than a vector graph, so "mean" alone does not identify an operation. The pipeline reduces over three different things:

Reduction Axis Where it happens Result shape
Neighbour aggregation edges, grouped by destination node inside each layer [N, C', H, W]
Spatial pooling H and W of every node after the last layer [N, C']
Graph readout nodes, grouped by graph id graph-level tasks only [B, ...]

Here B is the number of graphs. Neighbour aggregation keeps the grid: it adds feature maps position by position, so ten neighbours give one map, not ten and not a vector. Spatial pooling is the step that gives up the grid, and everything the classifier knows about where something was inside a patch has to be encoded in the channels by then. Graph readout is optional and independent of the other two.

This also explains what "keeping spatial structure" can mean for the output. In the paper's pipeline the structure survives until Eq. 13 and no further: the logits are computed from a per-node vector. If your task needs a map as output, for example a mask per node, stop before the spatial mean and attach a convolutional head; none of the packaged classifier classes does that for you.

Volumes and vectors use the same template

For volumetric nodes [C, D, H, W], ConvMessagePassing switches to 1×1×1 and 3×3×3 convolutions when in_shape has four entries, and the other tensor layers take spatial_rank=3. The number of positions S becomes D·H·W, which multiplies both the message buffer and the convolution cost. For vector nodes [N, d] there is no grid to convolve over, so the package provides separate linear layers; ConvMessagePassing rejects a one-entry in_shape. A time axis [N, T, d] can be stored in a Graph, but no shipped layer models it.

Component provenance table

Stage Paper Released symbol (1.5.1) Difference to remember Stability listing
Patches Eq. 3–4 image_to_patches channels-first [B, P, C, ph, pw] stability doc: Stable
Pre-encoder Eq. 5 PreEncoder pretrained ResNet-18 option downloads weights not listed
Encoder Eq. 6–7 CNNEncoder spatial output only with return_feature_map=True; default pool_layers=2 with residuals raises for patches of 8 pixels or more README: stable core; stability doc: not listed
Container §3.2.1 Graph also volumes, vectors, masks, weights Stable
Batching §3.2.1 GraphBatch equal node shapes; masks not merged Stable
Topology Eq. 8–9 build_grid_graph and other builders you choose and build the edges Stable
Message Eq. 10 ConvMessagePassing.message edge channels must equal node channels Stable
Aggregation Eq. 11 aggregate sum default; mean and max added Stable
Update Eq. 12 DeepCNNAggregator, residual residual off by default, skipped on shape mismatch aggregator not listed
Spatial pooling Eq. 13 inside the model classes order relative to node pooling varies no separate symbol
Classifier Eq. 14 nn.Linear head weight shape is Q×C part of each model
Whole pipeline Fig. 1 CNN_GNN_Model ReLU between layers; edge features ignored not listed
CNN-to-classifier skip Fig. 1 (optional) CNN_GNN_Model(skip_cnn_to_classifier=True) default False; ignored if shapes differ not listed
Loss Eq. 15–19 none write it yourself not shipped

What the architecture does and does not guarantee

Spatial layout is preserved as a shape. A [C, H, W] node stays a grid through the layers. That is a property of the operators, not evidence that predictions are better. The paper reports one detection-refinement run, without repeated seeds or ablations.

Node order does not matter, in evaluation mode. Messages are computed edge by edge and aggregated with a symmetric function, so relabelling nodes relabels the outputs. The conditions are listed in permutation equivariance in tensor GNNs. This says nothing about rotating or shifting the pixels inside a node.

Messages assume alignment. The 1×1 message combines position (h, w) of the source with position (h, w) of the destination. If the two patches have no meaningful common coordinate frame, that pairing is arbitrary, and only the later 3×3 convolutions mix positions.

Training mode couples nodes. The default aggregator contains batch normalisation, whose statistics are taken over all nodes of the batch. In training mode a graph's output depends on what else is batched with it.

Receptive field has two meanings. L layers reach L hops in the graph. With the default aggregator they also reach 1 + 8L positions per axis inside the feature maps. On the 4×4 maps above, one layer already covers a whole node map.

Choosing an entry point

  • You have images and a graph over their regions, and want a baseline quickly: CNN_GNN_Model, remembering the ignored edge features.
  • You already have node tensors: ConvMessagePassing or one of the other tensor layers, with your own head.
  • You want to compare operators under one wiring: build_model with different layer= values, same seed and split.
  • You have vector features: the vector layers; nothing on this page about spatial mixing applies.
  • You have no meaningful edges: consider whether set attention, or no graph at all, answers your question better.

To report what you ran, record the package version and the layer arguments, and follow citing and describing TGraphX.

Going deeper

References