TGraphX › Insights › Tensor-Valued Graphs for Multimodal Research Workflows
← Back to Insights

Tensor-Valued Graphs for Multimodal Research Workflows

Topic: Vision, multimodal and domain applications

Many research datasets describe each sample with several modalities: a scan and a table of measurements, a video frame and a sensor trace. A graph over the samples lets similar ones exchange information, and tensor-valued node features let each modality keep its layout until you decide to compress it.

This page walks through that workflow for the case where every node carries the same set of modalities: shapes, edges, fusion, baselines, and where TGraphX stops. If different node types carry different modalities, see mixing modalities across node types. Examples tested with TGraphX 1.5.1 on CPU.

Choosing a representation

Situation Representation
All nodes hold one tensor of the same shape one Graph with node_features [N, ...]
Every node has several modalities one encoder per modality, fused per node, inside the model
Different node types have different modalities HeteroGraph (Experimental), or projection to a common width

A Graph holds a single node feature tensor of any rank from 2 up, with the same trailing shape for all nodes. A second modality can be kept next to it as an ordinary tensor and passed to your model, as below.

text
  one node = one sample

  sample i: image [3, H, W] + table row [8]      sample j: image [3, H, W] + table row [8]
            |  encoders                                     |  encoders
            v                                               v
        z_i [2 * dim]  ------------- edge i-j -------------  z_j [2 * dim]

Data, edges and splits

The synthetic task below is built so that neither modality is enough: the label combines one bit that is only in the image with one bit that is only in the table.

python
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import Graph, GCNConv
from tgraphx.graph_builders import build_knn_graph
from tgraphx.estimators import EarlyStopping, node_train_val_test_split

N = 300
gen = torch.Generator().manual_seed(0)
shape_class = torch.randint(0, 2, (N,), generator=gen)        # visible in the image only
group = torch.randint(0, 2, (N,), generator=gen)              # visible in the table only
labels = 2 * shape_class + group                              # four classes: both are needed

images = torch.randn(N, 3, 8, 8, generator=gen) + 0.25 * (2 * shape_class - 1).view(N, 1, 1, 1)
table = torch.randn(N, 8, generator=gen) + 0.5 * (2 * group - 1).view(N, 1)
train, val, test = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=0)

# Standardise with training rows only, then link similar rows of the table.
table = (table - table[train].mean(0)) / table[train].std(0)
edge_index = build_knn_graph(table, k=5, self_loops=False)    # symmetric kNN edges
g = Graph(node_features=images, edge_index=edge_index, node_labels=labels)
print(g.feature_shape, tuple(edge_index.shape))     # (3, 8, 8) (2, 2190)

Self-loops are switched off on purpose. build_knn_graph adds them by default, and so does GCNConv, which does not check for existing ones, so with both defaults every node's self-loop would count twice.

Three decisions are visible here, and each one belongs in your write-up:

  • Which modality defines the edges. Here rows with similar measurements are connected. This choice decides what message passing mixes together.
  • What the edges were computed from. Features only, never labels. Building a k-nearest-neighbour graph over all samples lets test inputs take part, which is acceptable in a transductive study and not in an inductive one.
  • What was fitted on training rows. The standardisation uses training statistics only.

build_knn_graph expects [N, D] coordinates, so flatten or embed a tensor modality before using it for distances. The node features themselves stay as they are. (build_fully_connected_graph and build_grid_graph do not look at features at all.)

Fusion, with baselines

The model encodes each modality, concatenates the codes and then either classifies each node alone or passes messages first. Running the single-modality and no-graph variants is what makes the result interpretable.

python
class FusionNet(nn.Module):
    """Encode each modality, concatenate, then classify with or without message passing."""
    def __init__(self, use_image=True, use_table=True, graph=None, dim=16):
        super().__init__()
        self.graph = graph                                   # None, "gcn" or "gcn+skip"
        self.image_encoder = nn.Sequential(
            nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1),
            nn.Flatten(), nn.Linear(8, dim)) if use_image else None
        self.table_encoder = nn.Linear(8, dim) if use_table else None
        width = dim * (int(use_image) + int(use_table))
        if graph is None:
            self.mix = nn.Linear(width, 32)
        else:
            self.mix = GCNConv(width, 32)
        self.head = nn.Linear(32 + (width if graph == "gcn+skip" else 0), 4)

    def forward(self, images, table, edge_index):
        parts = []
        if self.image_encoder is not None:
            parts.append(self.image_encoder(images))
        if self.table_encoder is not None:
            parts.append(self.table_encoder(table))
        z = F.relu(torch.cat(parts, dim=1))                  # fusion by concatenation
        h = self.mix(z) if self.graph is None else self.mix(z, edge_index)
        h = F.relu(h)
        if self.graph == "gcn+skip":
            h = torch.cat([z, h], dim=1)                     # keep the node's own features
        return self.head(h)

def evaluate_variant(options, seed):
    torch.manual_seed(seed)
    model = FusionNet(**options)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.02, weight_decay=5e-4)
    stopper, best = EarlyStopping(patience=10, mode="min"), None
    for _ in range(80):
        model.train(); optimizer.zero_grad()
        F.cross_entropy(model(images, table, edge_index)[train], labels[train]).backward()
        optimizer.step()
        model.eval()
        with torch.no_grad():
            val_loss = F.cross_entropy(model(images, table, edge_index)[val], labels[val]).item()
        stop = stopper.step(val_loss)
        if stopper.counter == 0:
            best = {k: v.clone() for k, v in model.state_dict().items()}
        if stop:
            break
    model.load_state_dict(best); model.eval()
    with torch.no_grad():
        predicted = model(images, table, edge_index).argmax(1)
    return torch.tensor([(predicted[m] == labels[m]).float().mean() for m in (val, test)])

variants = {
    "image only": dict(use_table=False),
    "table only": dict(use_image=False),
    "both, no graph": dict(),
    "both, GCN": dict(graph="gcn"),
    "both, GCN with skip": dict(graph="gcn+skip"),
}
for name, options in variants.items():
    v, t = torch.stack([evaluate_variant(options, seed) for seed in range(3)]).mean(0).tolist()
    print(f"{name:20s} val {v:.2f}  test {t:.2f}")
# image only           val 0.53  test 0.44
# table only           val 0.40  test 0.42
# both, no graph       val 0.93  test 0.92
# both, GCN            val 0.47  test 0.41
# both, GCN with skip  val 0.93  test 0.92

What this run shows:

  • Each modality alone stays at about one half or below, as designed, and fusing them solves most of the task without any graph.
  • Plain GCN over the table-based edges does much worse. Neighbours share the table bit, but their image bit is unrelated, so averaging over them washes out the image signal.
  • Keeping a skip path with the node's own encoding recovers the no-graph result. The graph still adds nothing here.

That is a property of this synthetic data, not of graphs in general. The lesson is the comparison itself: an edge set built from one modality can suppress another, and only a no-graph baseline reveals it. Report several seeds, and select variants on validation data before reading the test column.

Other fusion choices follow the same pattern: weighted or gated sums of the codes, or attention between them. For concatenation and for plain or gated sums, TGraphX ships TensorFeatureFusion (Experimental, in tgraphx.generation). It takes one encoder per modality, for example ImageNodeEncoder and VectorNodeProjector:

python
from tgraphx import ImageNodeEncoder, VectorNodeProjector
from tgraphx.generation import TensorFeatureFusion

for mode in ("concat_project", "add", "gated"):
    fusion = TensorFeatureFusion([ImageNodeEncoder(3, 16), VectorNodeProjector(8, 16)],
                                 out_dim=16, mode=mode)
    print(mode, tuple(fusion([images, table]).shape))
# concat_project (300, 16)
# add (300, 16)
# gated (300, 16)

"add" sums the encoder outputs. "gated" sums them after scaling each by one learned sigmoid weight per modality, the same for every node. "concat_project", the default, concatenates them and applies a linear layer and a ReLU.

Give every encoder an output width equal to out_dim. concat_project sizes its linear layer on that assumption. If the concatenated width is not out_dim times the number of encoders, 1.5.1 silently replaces the layer on the first forward pass, and an optimizer created before that pass never updates the new weights. add and gated ignore out_dim and need the encoder widths to match each other.

TGraphX has no cross-modal attention module, so for attention between the codes you would use torch.nn.MultiheadAttention or your own layer.

Keeping spatial structure

If the image layout matters during message passing, turn the other modality into extra channels and use a tensor layer:

python
from tgraphx import TensorGraphSAGELayer

maps = table[:, :, None, None].expand(-1, -1, 8, 8)          # every pixel gets the table row
node_maps = torch.cat([images, maps], dim=1)                 # [N, 3 + 8, 8, 8]
layer = TensorGraphSAGELayer(11, 16)
print(tuple(layer(node_maps, edge_index).shape))           # (300, 16, 8, 8)

TensorGraphSAGELayer, TensorGATLayer and TensorGINLayer use 1×1 convolutions: they mix channels, not pixel positions. If the model must learn spatial patterns, put a CNN in front or use ConvMessagePassing, which convolves over the spatial axes.

Time-series nodes

A Graph accepts [N, T, D] features, but no TGraphX message-passing layer is designed for them. A tensor layer rejects the shape; you can reshape for it, or first encode each series to one vector:

python
series = torch.randn(N, 48, 4, generator=gen)                # [N, T, D] sensor windows
print(Graph(node_features=series, edge_index=edge_index).feature_shape)   # (48, 4): stored
try:
    TensorGraphSAGELayer(48, 16)(series, edge_index)
except ValueError as error:
    print(error)       # x must have shape [N, C, H, W] (spatial_rank=2); got (300, 48, 4).
as_maps = series.transpose(1, 2).unsqueeze(2)                # [N, D=4, 1, T=48]
print(tuple(TensorGraphSAGELayer(4, 16)(as_maps, edge_index).shape))      # (300, 16, 1, 48)

from tgraphx.mining import GraphSequenceEncoder              # Experimental: an LSTM

encoder = GraphSequenceEncoder(input_dim=4, hidden_dim=16)
codes = encoder(series)                                      # one vector per node
print(tuple(GCNConv(16, 16)(codes, edge_index).shape))       # (300, 16)

The reshaped version runs, with channels = D and a 1 × T "image". A 1×1 convolution then treats every time step separately, so temporal patterns need their own encoder (1-D convolution, recurrent or attention layers) before message passing, or a custom message-passing layer. GraphSequenceEncoder is a shipped recurrent option: it was written for graph traversal sequences, but it treats each node's series as one sequence in the batch and returns [N, hidden_dim]. Put it inside your model so it trains with the rest.

Do not take a forward pass that runs as sequence support. LinearMessagePassing and the legacy AttentionMessagePassing, built with in_shape=(D,), accept [N, T, D] without error, but neither models the time axis. Images, volumes and sequences as node states works through both routes.

What TGraphX provides here, and what it does not

Provided:

  • Graph and GraphBatch for tensor-valued nodes, with shape validation at construction (Stable)
  • message-passing layers for vector, 2-D and 3-D node features, and TensorMessagePassingLayer to write your own
  • CNNEncoder for images (in 1.5.1 its default settings fail with a size-mismatch error for inputs of 8×8 and larger; use_residual=False works)
  • per-node encoders ImageNodeEncoder, VectorNodeProjector and tgraphx.generation.VolumeNodeEncoder, with tgraphx.generation.TensorFeatureFusion to combine modalities (Experimental)
  • tgraphx.mining.GraphSequenceEncoder, an LSTM from [N, T, D] to [N, hidden_dim] (Experimental)
  • projectors and MultimodalEntityFusion in tgraphx.kg, aimed at knowledge graph entities (Experimental)
  • HeteroGraph and heterogeneous layers for typed nodes (Experimental)

Not provided:

  • a ready-made multimodal model for node tasks outside the knowledge graph module
  • cross-modal attention
  • text tokenisers or language models: text has to arrive as precomputed vectors, or be encoded by your own module
  • message-passing layers for sequence-valued node features

Other libraries can hold tensor-valued features too; PyTorch Geometric's Data.x, for instance, accepts any rank, although most of its convolutions expect vectors. The difference TGraphX offers is in its layers that operate on [C, H, W] and [C, D, H, W] directly.

What to record

For a multimodal graph experiment, write down: the shape and preprocessing of every modality; each encoder; where fusion happens; how edges were built and from which data; the split and what was fitted on which part; the seeds; and the single-modality and no-graph baselines. See reproducibility checklists for tensor-valued GNN experiments.