TGraphX › Insights › Different Node Types, Different Modalities: HeteroGraph or One Projected Graph
← Back to Insights

Different Node Types, Different Modalities: HeteroGraph or One Projected Graph

Topic: Vision, multimodal and domain applications

A multi-modal graph has nodes whose features come from different kinds of data. Consider a healthcare graph: patient nodes have demographic vectors [64], imaging nodes have image tensors [C, H, W], lab-result nodes have time series [T, D], and clinical-note nodes have text embeddings. Shapes and meanings differ from type to type.

The usual [N, D] node feature matrix cannot hold this. This article shows what TGraphX offers instead, with two runnable ways of training on such a graph, and states the limits. Examples tested with TGraphX 1.5.1 on CPU.

The core challenge

In a homogeneous graph every node has the same feature shape, and message passing combines neighbour features of that shape. With mixed modalities:

  • A patient node should aggregate from an imaging node (a 3-D tensor per node) and from lab nodes (a 2-D tensor per node). What shape does that sum have?
  • A layer built for [N, C, H, W] cannot read [N, T, D], and no TGraphX message-passing layer is designed for [N, T, D].
  • The output shape of the patient node has to be decided by you.

The common answer is to encode each modality into a shared embedding space before messages are exchanged. The choice is where that happens.

For a time series this means encoding it to one vector per node first, with your own module (as below) or the Experimental tgraphx.mining.GraphSequenceEncoder, an LSTM that maps [N, T, D] to [N, hidden_dim]. 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 is a temporal model (the first processes each time step on its own).

What TGraphX provides

  1. Single-type tensor-valued graphs. All nodes share one feature shape, which can be [C, H, W] rather than [D]. Graph and the tensor message-passing layers are labelled Stable.
  2. HeteroGraph and heterogeneous layers (Experimental). Each node type keeps its own tensor shape. The ready-made models (HeteroNodeClassifier, HeteroGraphClassifier) accept vectors per type, so images and sequences need an encoder first.
  3. Multi-modal knowledge graph entities (Experimental). MultimodalKGModel with entity projectors, covered at the end.

Single-modality tensor-valued graphs

If all nodes are of one kind, for example image patches, there is nothing special to do:

python
import torch
import tgraphx as tgx
from tgraphx.estimators import node_train_val_test_split

torch.manual_seed(0)
x = torch.randn(200, 3, 8, 8)                      # 200 image patches, each [3, 8, 8]
edge_index = tgx.knn_graph(x, k=8)                 # distances use the flattened patches
labels = torch.randint(0, 10, (200,))              # random labels: this only shows the calls
train, val, test = node_train_val_test_split(200, 0.6, 0.2, 0.2, seed=0)

g = tgx.Graph(node_features=x, edge_index=edge_index, node_labels=labels)
print(g.feature_shape, g.num_edges)                # (3, 8, 8) 1904

result = tgx.classify_nodes(x, edge_index, labels, train_mask=train, val_mask=val,
                            test_mask=test, seed=42, device="cpu")
print(sorted(result.metrics))
# ['epochs', 'num_classes', 'num_nodes', 'test_accuracy', 'val_accuracy']

Pass all three masks to classify_nodes; by default it also runs only a few epochs. See why shape matters for tensor-valued nodes and MNIST as a graph for this single-type case in detail.

Mixed node types with HeteroGraph (Experimental)

HeteroGraph takes node_stores (a tensor per node type) and edge_stores (an edge_index per (source type, relation, target type)). Messages flow from source to target, so you need relations that point at the node type you predict.

The data below is synthetic: 200 patients, one imaging study each, and 300 lab series. The label can only be read from the image.

python
from tgraphx import HeteroGraph

num_patients, num_labs = 200, 300
gen = torch.Generator().manual_seed(0)
diagnosis = torch.randint(0, 2, (num_patients,), generator=gen)       # label to predict

patient_x = torch.randn(num_patients, 64, generator=gen)             # [64] per patient
image_x = torch.randn(num_patients, 3, 16, 16, generator=gen)        # [3, 16, 16] per study
image_x += 0.5 * (2 * diagnosis - 1).view(-1, 1, 1, 1)               # the signal is in the image
lab_x = torch.randn(num_labs, 24, 8, generator=gen)                  # [24, 8] time series

# edge_index rows: [source ids, target ids], each in its own type's numbering
has_imaging = torch.stack([torch.arange(num_patients), torch.arange(num_patients)])
has_lab = torch.stack([torch.arange(num_labs) % num_patients, torch.arange(num_labs)])

edges = {
    ("patient", "has_imaging", "imaging"): has_imaging,
    ("patient", "has_lab", "lab"): has_lab,
    # Reverse relations: without them a patient receives nothing.
    ("imaging", "image_of", "patient"): has_imaging.flip(0),
    ("lab", "lab_of", "patient"): has_lab.flip(0),
}
hg = HeteroGraph(node_stores={"patient": patient_x, "imaging": image_x, "lab": lab_x},
                 edge_stores=edges, node_label_stores={"patient": diagnosis})
for node_type in hg.node_types:
    print(node_type, tuple(hg.node_features(node_type).shape))
# patient (200, 64)
# imaging (200, 3, 16, 16)
# lab (300, 24, 8)

HeteroGraph does not check that edge indices are in range in 1.5.1, so check them yourself.

Training end to end

Put one encoder per modality in front of the heterogeneous GNN. Because they are part of the same module, gradients reach them. The last lines compare the full edge set with one that has no relation pointing at patients:

python
import torch.nn as nn
import torch.nn.functional as F
from tgraphx.estimators import EarlyStopping
from tgraphx.models.hetero_models import HeteroNodeClassifier

class Encoders(nn.Module):
    """One encoder per modality, all ending in vectors of the same width."""
    def __init__(self, dim=32):
        super().__init__()
        self.patient = nn.Linear(64, dim)
        self.imaging = nn.Sequential(nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(),
                                     nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(8, dim))
        self.lab_conv = nn.Conv1d(8, 16, 3, padding=1)
        self.lab_out = nn.Linear(16, dim)

    def forward(self, x):
        lab = F.relu(self.lab_conv(x["lab"].transpose(1, 2))).mean(dim=2)    # [N, T, D] -> [N, 16]
        return {"patient": self.patient(x["patient"]),
                "imaging": self.imaging(x["imaging"]),
                "lab": self.lab_out(lab)}

class HeteroModel(nn.Module):
    def __init__(self, edge_types, dim=32):
        super().__init__()
        self.encoders = Encoders(dim)
        self.gnn = HeteroNodeClassifier({"patient": dim, "imaging": dim, "lab": dim}, edge_types,
                                        hidden_dim=dim, num_layers=2, num_classes=2,
                                        target_type="patient")

    def forward(self, x_dict, edge_index_dict):
        return self.gnn(self.encoders(x_dict), edge_index_dict)

train, val, test = node_train_val_test_split(num_patients, 0.6, 0.2, 0.2, seed=0)

def fit(model, forward, epochs=60):
    """Train on train patients, keep the best validation weights, return test accuracy."""
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    stopper, best = EarlyStopping(patience=10, mode="min"), None
    for _ in range(epochs):
        model.train()
        optimizer.zero_grad()
        F.cross_entropy(forward(model)[train], diagnosis[train]).backward()
        optimizer.step()
        model.eval()
        with torch.no_grad():
            val_loss = F.cross_entropy(forward(model)[val], diagnosis[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():
        return (forward(model).argmax(1)[test] == diagnosis[test]).float().mean().item()

one_way = {k: v for k, v in edges.items() if k[2] != "patient"}
for name, used in [("with reverse relations", edges), ("patient -> others only", one_way)]:
    torch.manual_seed(0)
    model = HeteroModel(list(used))
    accuracy = fit(model, lambda m: m(hg.x_dict, used))
    reached = model.encoders.imaging[0].weight.grad is not None
    print(f"{name:24s} test accuracy {accuracy:.2f}   image encoder got gradients: {reached}")
# with reverse relations   test accuracy 0.90   image encoder got gradients: True
# patient -> others only   test accuracy 0.47   image encoder got gradients: False

Without reverse relations the code runs without any warning, the image encoder is never trained, and the result is chance level. Only the patient's own features reach the prediction.

One graph after projection

You do not have to use HeteroGraph. Give all nodes one index space, encode every modality to the same width, and run ordinary layers on one graph. This uses the Stable GCNConv, and the encoders can still be trained jointly:

python
from tgraphx import GCNConv

# Patients first, then imaging studies, then lab series.
imaging_offset, lab_offset = num_patients, 2 * num_patients
to_imaging = has_imaging + torch.tensor([[0], [imaging_offset]])
to_lab = has_lab + torch.tensor([[0], [lab_offset]])
one_direction = torch.cat([to_imaging, to_lab], dim=1)
combined_edges = torch.cat([one_direction, one_direction.flip(0)], dim=1)

class ProjectedModel(nn.Module):
    def __init__(self, dim=32):
        super().__init__()
        self.encoders = Encoders(dim)
        self.conv1 = GCNConv(dim, dim)
        self.conv2 = GCNConv(dim, 2)

    def forward(self, x_dict, edge_index):
        z = self.encoders(x_dict)
        h = torch.cat([z["patient"], z["imaging"], z["lab"]], dim=0)    # [700, dim]
        h = F.relu(self.conv1(h, edge_index))
        return self.conv2(h, edge_index)[:num_patients]

x_dict = {"patient": patient_x, "imaging": image_x, "lab": lab_x}
torch.manual_seed(0)
projected = ProjectedModel()
print(f"{fit(projected, lambda m: m(x_dict, combined_edges)):.2f}")       # 0.88

What you give up compared with the heterogeneous model is type-specific message functions: all relations share the same weights. (Do not read 0.88 against 0.90 as a comparison of the two approaches; it is one synthetic run.)

Precomputed embeddings

If the encoders are frozen, for example pretrained backbones, compute the embeddings once without gradients and treat them as ordinary node features:

python
torch.manual_seed(0)
frozen = Encoders().eval()                   # stand-in for your pretrained encoders
with torch.no_grad():
    z = frozen(x_dict)
all_embeddings = torch.cat([z["patient"], z["imaging"], z["lab"]], dim=0)
num_other = all_embeddings.size(0) - num_patients
all_labels = torch.cat([diagnosis, torch.zeros(num_other, dtype=torch.long)])

def pad(mask):                               # non-patient nodes belong to no split
    return torch.cat([mask, torch.zeros(num_other, dtype=torch.bool)])

result = tgx.classify_nodes(all_embeddings, combined_edges, all_labels, train_mask=pad(train),
                            val_mask=pad(val), test_mask=pad(test), seed=42, device="cpu")
print(tuple(all_embeddings.shape), result.metrics["epochs"])       # (700, 32) 3

Two traps here. Embeddings that still require gradients make a repeated training loop fail with "Trying to backward through the graph a second time", hence the no_grad. And classify_nodes does not validate its model argument, so do not rely on it to choose an architecture.

Image-heavy examples are collected in vision use cases for tensor-valued graphs.

When the heterogeneous model pays off

  • Different relations should transform messages differently.
  • Node types have very different roles or counts, and you want to predict on only one of them.
  • You want typed layers such as HGT, HAN or RGCN.

If the types can reasonably share one message function, the projected graph is simpler and rests on stable parts of the library. Whether end-to-end training of the encoders beats precomputed features is a separate question, which you can answer by running both.

Knowledge graphs with multi-modal entities (Experimental)

For triple data, tgraphx.kg has MultimodalKGModel with VectorEntityProjector, ImageEntityProjector and TextEntityProjector. The text projector expects precomputed embeddings, and the image projector pools spatial dimensions before a linear map, so it is not a CNN. See the multimodal knowledge graph tutorial.

Where to look next


FAQ

Q: Can some nodes in a tgx.Graph have image features and others vector features?
A: No. A Graph holds one feature tensor, so all nodes share a shape. Use HeteroGraph (Experimental) or project to a common shape.

Q: Are the standard message-passing layers type-aware?
A: No. They treat the graph as homogeneous. Type-aware layers are in the Experimental heterogeneous part of the library.

Q: Should I use TGraphX or PyTorch Geometric for multi-modal research?
A: PyG's HeteroData also stores tensors of any shape per node type, and its heterogeneous tooling is broader. Choose TGraphX if its tensor-aware layers and workflow suit your project, bearing in mind that its heterogeneous support is Experimental.

Q: Can knowledge graph entities have multi-modal features?
A: Yes, through MultimodalKGModel, which the package documentation labels Experimental.

Q: How do I turn images into embeddings for the projected approach?
A: Any encoder with a fixed-size output works; the penultimate layer of a frozen pretrained ResNet is a common choice. If you prefer not to wire up backbones yourself, VisionServeX lists local DINOv2 and CLIP embedding models.