TGraphX › Insights › Heterogeneous Graph Learning with TGraphX: RGCN, HAN, and HGT
← Back to Insights

Heterogeneous Graph Learning with TGraphX: RGCN, HAN, and HGT

Topic: GNN architectures and learning tasks

Many introductory graph learning examples use homogeneous graphs: one node type and one edge type. A lot of real data is heterogeneous instead. A publication graph has papers, authors and venues, connected by "writes", "cites" and "published at" relations, and each node type can have its own features. A model that keeps these types apart can give each relation its own parameters. Whether that improves your task is something to measure against a homogeneous baseline.

TGraphX provides a HeteroGraph container, a generic HeteroConv wrapper, RGCNConv, HANConv and HGTConv layers, a batch class and a typed neighbour sampler. The heterogeneous subsystem is Experimental, so pin the version you use. The examples were tested with TGraphX 1.5.1 on CPU and are meant to run in order. All data is random, so the losses and predictions carry no meaning. The point is the shapes, the wiring and the pitfalls.

Understanding heterogeneous graphs

A heterogeneous graph is a graph G = (V, E) with a node-type function τ(v) ∈ A and an edge-type (relation) function φ(e) ∈ R, where |A| + |R| > 2. In TGraphX a relation is written as a triple (source type, relation name, destination type):

  • ("author", "writes", "paper")
  • ("paper", "cites", "paper")
  • ("paper", "published_at", "venue")

Two conventions matter in everything below.

  • Each node type has its own index space. Paper 0 and author 0 are different nodes. Row 0 of an edge index refers to the source type and row 1 to the destination type.
  • Messages flow from source to destination. With only the three relations above, papers never receive anything from venues, and authors receive nothing at all. If information should flow both ways, add reverse relations such as ("paper", "written_by", "author").

The HeteroGraph container

HeteroGraph takes a dictionary of node feature tensors (node_stores) and a dictionary of edge indices (edge_stores). Labels per node type are optional (node_label_stores).

python
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import HeteroGraph

torch.manual_seed(0)                              # node features and model weights
gen = torch.Generator().manual_seed(1_000_003)    # edges and labels: an unrelated seed
n_paper, n_author, n_venue = 40, 20, 5

x_dict = {
    "paper": torch.randn(n_paper, 16),
    "author": torch.randn(n_author, 8),
    "venue": torch.randn(n_venue, 4),
}

# Row 0 indexes the source type, row 1 the destination type.
writes = torch.unique(torch.stack([
    torch.randint(0, n_author, (80,), generator=gen),
    torch.arange(n_paper).repeat(2),
]), dim=1)
cites = torch.randint(0, n_paper, (2, 100), generator=gen)
cites = torch.unique(cites[:, cites[0] != cites[1]], dim=1)
published = torch.stack([
    torch.arange(n_paper),
    torch.randint(0, n_venue, (n_paper,), generator=gen),
])

edge_dict = {
    ("author", "writes", "paper"): writes,
    ("paper", "written_by", "author"): writes.flip(0),
    ("paper", "cites", "paper"): cites,
    ("paper", "cited_by", "paper"): cites.flip(0),
    ("paper", "published_at", "venue"): published,
    ("venue", "publishes", "paper"): published.flip(0),
}
paper_y = torch.randint(0, 3, (n_paper,), generator=gen)

hg = HeteroGraph(
    node_stores=x_dict,
    edge_stores=edge_dict,
    node_label_stores={"paper": paper_y},
)

print(hg.node_types)                    # ['paper', 'author', 'venue']
print(len(hg.edge_types))               # 6
print(hg.num_nodes("paper"))            # 40
print(hg.num_edges(("paper", "published_at", "venue")))  # 40

Note that num_edges takes the whole edge-type triple.

HeteroGraph does not range-check edge indices. The constructor checks shapes, dtypes and type names, but accepts an index that is negative or too large for its node type. Depending on the layer, such an index raises an error later or silently reads the wrong row. Check it yourself:

python
def check_indices(graph):
    for etype in graph.edge_types:
        src_type, _, dst_type = etype
        ei = graph.edge_index(etype)
        if ei.numel() == 0:
            continue
        if (ei.min() < 0 or ei[0].max() >= graph.num_nodes(src_type)
                or ei[1].max() >= graph.num_nodes(dst_type)):
            raise ValueError(f"edge index out of range for {etype}")

check_indices(hg)

A baseline with HeteroNodeClassifier

HeteroNodeClassifier is the shortest way to classify one node type. It projects every type to a common width, then stacks HeteroConv blocks with one LinearMessagePassing layer per relation. Each message is a linear function of the concatenated source and destination features. Messages are aggregated per relation and then summed across relations.

There is one trap. This layer has no separate self-connection. In a node type that receives messages, a node without any incoming edge gets a zero vector and loses its own features. Adding an explicit self relation for each node type avoids that.

The labels belong to papers, so split the paper nodes. Train on the training mask, select the model on the validation mask and look at the test mask once.

python
from tgraphx.estimators import EarlyStopping, node_train_val_test_split
from tgraphx.models.hetero_models import HeteroNodeClassifier

edges_with_self = dict(hg.edge_index_dict)
for ntype in hg.node_types:
    idx = torch.arange(hg.num_nodes(ntype))
    edges_with_self[(ntype, "self", ntype)] = torch.stack([idx, idx])
full = HeteroGraph(hg.x_dict, edges_with_self, node_label_stores={"paper": paper_y})
check_indices(full)

train_mask, val_mask, test_mask = node_train_val_test_split(n_paper, 0.6, 0.2, 0.2, seed=0)

in_dims = {t: full.node_features(t).size(1) for t in full.node_types}
model = HeteroNodeClassifier(
    node_in_dims=in_dims,
    edge_types=full.edge_types,
    hidden_dim=32,
    num_layers=2,
    num_classes=3,
    target_type="paper",
    aggr="mean",
)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
stopper = EarlyStopping(patience=5, mode="min")   # the default mode is "max"
best_state = None

for epoch in range(30):
    model.train()
    optimizer.zero_grad()
    logits = model(full.x_dict, full.edge_index_dict)      # [40, 3]
    loss = F.cross_entropy(logits[train_mask], paper_y[train_mask])
    loss.backward()
    optimizer.step()

    model.eval()
    with torch.no_grad():
        val_logits = model(full.x_dict, full.edge_index_dict)
        val_loss = F.cross_entropy(val_logits[val_mask], paper_y[val_mask]).item()
    stop = stopper.step(val_loss)
    if stopper.counter == 0:
        best_state = {k: v.clone() for k, v in model.state_dict().items()}
    if stop:
        break

model.load_state_dict(best_state)
model.eval()
with torch.no_grad():
    test_logits = model(full.x_dict, full.edge_index_dict)
    test_acc = (test_logits[test_mask].argmax(1) == paper_y[test_mask]).float().mean().item()
print(test_logits.shape)   # torch.Size([40, 3])
print(test_acc)            # the labels are random, so this number means nothing

This is a transductive setup: all nodes and edges are visible during training, only the labels are held out. If your relations encode the label (for example a "belongs to category" edge when you predict the category), remove them.

HeteroConv: choose a layer per relation

HeteroConv({edge_type: module}, aggr="sum") applies your own module to each relation and combines the results per destination type ("sum", "mean" or "max"). Keep in mind:

  • For a relation between two different types, source and destination features must have the same shape, because the wrapper concatenates them before calling the layer. Project types to a common width first.
  • Every relation that has a module must be present in the edge-index dictionary you pass in.
  • A node type that is the destination of no relation is passed through unchanged.

Because the wrapper only dispatches, node features do not have to be vectors. With layers that accept spatial features, for example TensorGraphSAGELayer, nodes can keep [C, H, W] feature maps, provided connected types share the same shape:

python
from tgraphx import TensorGraphSAGELayer
from tgraphx.layers.hetero import HeteroConv

maps = {"image": torch.randn(6, 8, 4, 4), "region": torch.randn(4, 8, 4, 4)}
contains = torch.tensor([[0, 0, 1, 2], [0, 1, 2, 3]])   # image -> region
map_edges = {
    ("image", "contains", "region"): contains,
    ("region", "part_of", "image"): contains.flip(0),
}
conv = HeteroConv({etype: TensorGraphSAGELayer(8, 16) for etype in map_edges})
out = conv(maps, map_edges)
print(out["image"].shape, out["region"].shape)
# torch.Size([6, 16, 4, 4]) torch.Size([4, 16, 4, 4])

RGCNConv, HANConv, HGTConv, HeteroNodeClassifier and HeteroGraphClassifier are written for vector features [N, D].

Relational GCN (RGCN)

RGCN (Schlichtkrull et al., "Modeling Relational Data with Graph Convolutional Networks", ESWC 2018) learns a weight matrix for each relation:

h_i' = W_0 h_i + Σ_{r ∈ R} Σ_{j ∈ N_r(i)} (1 / |N_r(i)|) W_r h_j

RGCNConv(in_channels, out_channels, num_relations, num_bases=0, aggr="mean") computes this plus a bias, with no activation. Its forward signature is (x, edge_index_by_rel, num_nodes):

  • x is one feature matrix, so all nodes live in one index space.
  • edge_index_by_rel is a dictionary from an integer relation id to a [2, E_r] edge index.

For a heterogeneous graph you therefore project each type to a common width, stack the types, and shift every edge index by the offset of its node type. Skipping the offsets is a quiet bug: author 3 would be treated as paper 3.

python
from tgraphx.layers.rgcn import RGCNConv

class RGCNOnHetero(nn.Module):
    def __init__(self, graph, hidden, num_classes, num_bases=0):
        super().__init__()
        self.types = graph.node_types
        self.relations = graph.edge_types
        self.proj = nn.ModuleDict({
            t: nn.Linear(graph.node_features(t).size(1), hidden) for t in self.types
        })
        n_rel = len(self.relations)
        self.conv1 = RGCNConv(hidden, hidden, n_rel, num_bases=num_bases)
        self.conv2 = RGCNConv(hidden, num_classes, n_rel, num_bases=num_bases)

    def forward(self, x_dict, edge_index_dict):
        sizes = [x_dict[t].size(0) for t in self.types]
        offset = {t: sum(sizes[:i]) for i, t in enumerate(self.types)}
        x = torch.cat([self.proj[t](x_dict[t]) for t in self.types])
        by_rel = {}
        for rel_id, (src_type, rel, dst_type) in enumerate(self.relations):
            shift = torch.tensor([[offset[src_type]], [offset[dst_type]]], device=x.device)
            by_rel[rel_id] = edge_index_dict[(src_type, rel, dst_type)] + shift
        h = F.relu(self.conv1(x, by_rel, x.size(0)))
        h = self.conv2(h, by_rel, x.size(0))
        return dict(zip(self.types, h.split(sizes)))

rgcn = RGCNOnHetero(hg, hidden=32, num_classes=3, num_bases=2)
print(rgcn(hg.x_dict, hg.edge_index_dict)["paper"].shape)   # torch.Size([40, 3])

RGCN has a root weight W_0, so this model uses the graph without the extra self relations. Inverse relations are not added for you. The graph above already contains them as separate relation ids.

With many relations, one full matrix per relation grows quickly. num_bases > 0 switches on the paper's basis decomposition, W_r = Σ_b a_{rb} V_b, where the bases V_b are shared and each relation only has its own coefficients. Use num_bases=0, not None, to disable it.

Heterogeneous Attention Network (HAN)

HAN (Wang et al., "Heterogeneous Graph Attention Network", WWW 2019) works on meta-paths, here sequences of relations that start and end at the same node type. Paper - Author - Paper links papers that share an author, and Paper - Venue - Paper links papers from the same venue. HAN applies attention among the meta-path neighbours of each node, then a second, "semantic" attention that weights the meta-paths.

HANConv does not build meta-paths. You pass it the features of one node type and a dictionary {name: edge_index}, one homogeneous edge index per meta-path. Below, a paper-by-author (or paper-by-venue) incidence matrix times its transpose finds the pairs. Every paper node also gets a self-loop, because HAN counts a node among its own meta-path neighbours.

python
from tgraphx.layers.han import HANConv

def metapath_via(mid_to_paper, n_mid, n_paper):
    """Paper pairs that share a neighbour of the middle type, plus self-loops."""
    mid, paper = mid_to_paper
    incidence = torch.zeros(n_paper, n_mid)
    incidence[paper, mid] = 1.0
    shared = (incidence @ incidence.T) > 0          # dense [n_paper, n_paper]
    shared |= torch.eye(n_paper, dtype=torch.bool)
    return shared.nonzero().t()

metapaths = {
    "PAP": metapath_via(hg.edge_index(("author", "writes", "paper")), n_author, n_paper),
    "PVP": metapath_via(hg.edge_index(("venue", "publishes", "paper")), n_venue, n_paper),
}

han = HANConv(in_dim=16, out_dim=32, num_heads=4)
head = nn.Linear(32, 3)
paper_x = hg.node_features("paper")

print(len(list(han.parameters())))     # 3  (semantic attention only)
with torch.no_grad():
    han(paper_x, metapaths)            # creates one attention module per meta-path
print(len(list(han.parameters())))     # 7

# Build the optimizer only now.
optimizer = torch.optim.Adam([*han.parameters(), *head.parameters()], lr=1e-2)
optimizer.zero_grad()
logits = head(F.elu(han(paper_x, metapaths)))
loss = F.cross_entropy(logits[train_mask], paper_y[train_mask])
loss.backward()
optimizer.step()
print(logits.shape)                    # torch.Size([40, 3])

Four behaviours of HANConv in 1.5.1 are easy to get wrong:

  1. Per-meta-path parameters are created on the first forward pass. An optimizer built before that pass silently never trains them.
  2. Checkpoints need the same warm-up. Loading a saved state_dict into a freshly constructed HANConv fails with "Unexpected key(s)" until you have run one forward pass with the same meta-path names. Do not work around this with strict=False, which discards the trained attention weights.
  3. A misspelled meta-path name is not an error. A name the layer has not seen creates a new, randomly initialised module.
  4. No activation is applied and heads are averaged, so the output width is out_dim for any num_heads. Add your own nonlinearity, as above.

The semantic weights are computed from the mean embedding of each meta-path, which differs slightly from the paper (it averages per-node scores). They are not returned. Meta-path graphs can be far denser than the original relations, so check their edge counts. The dense matrix above is only for small graphs; use sparse matrix products (or PyG's AddMetaPaths transform) for large ones.

Heterogeneous Graph Transformer (HGT)

HGT (Hu et al., "Heterogeneous Graph Transformer", WWW 2020) needs no meta-paths. Queries, keys and values use projections that depend on the node type, and attention depends on the relation.

HGTConv(in_dim, out_dim, node_types, edge_types, num_heads=4) takes one shared input width, so project the node types first. out_dim must be divisible by num_heads. Calling the layer with (x_dict, edge_index_dict) returns a dictionary with every node type.

python
from tgraphx.layers.hgt import HGTConv

class HGTModel(nn.Module):
    def __init__(self, graph, hidden, num_classes, num_layers=2, heads=4):
        super().__init__()
        self.proj = nn.ModuleDict({
            t: nn.Linear(graph.node_features(t).size(1), hidden) for t in graph.node_types
        })
        self.layers = nn.ModuleList([
            HGTConv(hidden, hidden, graph.node_types, graph.edge_types, num_heads=heads)
            for _ in range(num_layers)
        ])
        self.head = nn.Linear(hidden, num_classes)

    def forward(self, x_dict, edge_index_dict):
        h = {t: F.relu(self.proj[t](x)) for t, x in x_dict.items()}
        for layer in self.layers:
            h = {t: F.gelu(v) for t, v in layer(h, edge_index_dict).items()}
        return self.head(h["paper"])

hgt_model = HGTModel(hg, hidden=32, num_classes=3)
print(hgt_model(hg.x_dict, hg.edge_index_dict).shape)   # torch.Size([40, 3])

HGTConv is a compact variant, not a full reproduction of the paper. In 1.5.1:

  • The relation-specific part is one learned scalar per head and edge type, which multiplies the attention logits. The paper's per-relation attention and message matrices are not there.
  • The softmax runs over the incoming edges of each relation separately, and the results are summed. The paper normalises over all incoming neighbours together. A node with a single incoming edge in some relation therefore gives it weight 1.
  • No activation is applied inside the layer, and a gated residual connects input and output.
  • There is no relative temporal encoding, and edge weights and edge features are not used.
  • Edge types in the input dictionary that you did not list in the constructor are ignored without a warning, and listed ones that are missing are skipped.

The parameter count grows additively with the number of node types and edge types. With H heads and d_in = d_out = d, each layer has 4d² + d + 1 parameters per node type (query, key, value, output layer and gate) and H per edge type. If d_in ≠ d_out, the query, key and value matrices are d_in × d_out and each node type also gets a d_in × d_out residual projection.

Batching several heterogeneous graphs

For graph-level tasks over many small graphs, HeteroGraphBatch takes a list of graphs and builds their disjoint union, offsetting indices per node type. All graphs must have the same node types and edge types. HeteroGraphClassifier uses the same per-relation layer as HeteroNodeClassifier, so add self relations if nodes without incoming edges must keep their features.

python
from tgraphx import HeteroGraphBatch
from tgraphx.models.hetero_models import HeteroGraphClassifier

g1 = HeteroGraph(hg.x_dict, hg.edge_index_dict, graph_label=torch.tensor(0))
g2 = HeteroGraph(hg.x_dict, hg.edge_index_dict, graph_label=torch.tensor(1))  # normally different
batch = HeteroGraphBatch([g1, g2])

print(batch.num_graphs)                         # 2
print(batch.num_nodes_dict)                     # {'paper': 80, 'author': 40, 'venue': 10}
print(batch.batch_dict["paper"].bincount())     # tensor([40, 40])

classifier = HeteroGraphClassifier(
    node_in_dims=in_dims, edge_types=batch.edge_types,
    hidden_dim=32, num_layers=2, num_classes=2,
)
graph_logits = classifier(batch.x_dict, batch.edge_index_dict, batch_dict=batch.batch_dict)
print(graph_logits.shape)                       # torch.Size([2, 2])
graph_loss = F.cross_entropy(graph_logits, batch.graph_labels)

One limitation: the pooling step infers the number of graphs from each type's batch vector. If the last graphs of a batch contain no node of some type, that type's pooled tensor has too few rows and HeteroGraphClassifier raises a size-mismatch error.

Typed neighbour sampling

hetero_neighbor_sample expands from typed seed nodes with a fanout per relation and per hop. It is a function that returns a smaller HeteroGraph, not a data loader, and TGraphX 1.5.1 has no heterogeneous mini-batch loader class. The loop is yours to write.

python
from tgraphx import hetero_neighbor_sample

sampled_model = HeteroNodeClassifier(
    node_in_dims=in_dims, edge_types=full.edge_types, hidden_dim=32,
    num_layers=2, num_classes=3, target_type="paper", aggr="mean",
)
optimizer = torch.optim.Adam(sampled_model.parameters(), lr=1e-2)
relation_fanout = {etype: 5 for etype in full.edge_types if etype[1] != "self"}
train_ids = train_mask.nonzero().flatten()
sampled_model.train()

order = train_ids[torch.randperm(train_ids.numel(), generator=gen)]
for step, seeds in enumerate(order.split(8)):
    sub = hetero_neighbor_sample(
        full, {"paper": seeds},
        fanouts=[relation_fanout, relation_fanout],   # two hops for two layers
        seed=step,
    )
    # Node ids are relabelled; map the global seed ids to local rows.
    paper_ids = sub.metadata["sampling"]["original_node_ids"]["paper"]
    local = torch.searchsorted(paper_ids, seeds)
    assert torch.equal(paper_ids[local], seeds)

    optimizer.zero_grad()
    out = sampled_model(sub.x_dict, sub.edge_index_dict)
    loss = F.cross_entropy(out[local], sub.node_labels("paper")[local])
    loss.backward()
    optimizer.step()

What to know about the result:

  • Compute the loss on the seed rows only. The subgraph also contains validation and test papers as neighbours.
  • With the default direction="in", expansion follows edges backwards, from a destination node to its sources.
  • The returned graph is induced on all visited nodes. It keeps every edge between them, so a node can have more incoming edges than the fanout.
  • A relation left out of a hop's dictionary adds no new nodes at that hop.
  • The sampler is implemented in Python with a loop over frontier nodes. Time it on your graph before relying on it at scale.

The loop above shows one epoch of the mechanics. A real run repeats it and selects the model on the validation papers, as in the full-graph example.

Moving data in and out

tgraphx.load_dataset("synthetic:hetero")[0] is a small synthetic paper-author-venue graph for smoke tests. For published benchmarks, load them with another library and convert. tgraphx.interop has converters for PyG HeteroData and DGL heterographs. Every node type needs features, so add them first for types that have none. Node masks are not carried over, so keep them yourself. This example needs torch_geometric:

python
from tgraphx.interop import to_pyg_heterodata, from_pyg_heterodata

data = to_pyg_heterodata(hg)
data["paper"].train_mask = train_mask
restored = from_pyg_heterodata(data)      # features, edges and labels come back
paper_train_mask = data["paper"].train_mask   # the mask does not: keep it from here
print(restored.num_nodes_dict)            # {'paper': 40, 'author': 20, 'venue': 5}

tgraphx.save and the .tgx format do not cover HeteroGraph in 1.5.1. To store one, save its dictionaries with torch.save.

Limitations and when to use it

Heterogeneous support is Experimental: containers, layers and sampler may change between releases, so do not depend on it without pinning the version. There is no meta-path utility, no index range check in HeteroGraph, no heterogeneous mini-batch loader, and no published heterogeneous benchmark (DBLP, IMDB, OGB-MAG and so on) among the built-in dataset names. HeteroGraph is also not API-compatible with PyG's HeteroData or DGL heterographs, so moving between them is an explicit conversion.

TGraphX fits when you already work with it and want to prototype a typed model, or when typed nodes carry feature maps or volumes that should keep their spatial layout through HeteroConv. If your main need is mini-batch training on a large heterogeneous graph, PyTorch Geometric (HeteroData, to_hetero, NeighborLoader) and DGL document dedicated workflows that TGraphX 1.5.1 does not provide.

Related articles