TGraphX › Insights › Porting a [C, H, W] Node Classifier Between DGL and TGraphX
← Back to Insights

Porting a [C, H, W] Node Classifier Between DGL and TGraphX

Topic: Framework comparisons and interoperability

DGL (Deep Graph Library) and TGraphX both build graph neural networks on PyTorch, but they put effort in different places. This page follows one workflow in both: node classification where every node carries a [C, H, W] tensor, with neighbour sampling, so you can see what changes when you port it in either direction. For a feature-by-feature and API comparison, including installation details and graph conversion, see TGraphX vs DGL: a practical comparison.

What was checked. The TGraphX blocks were run with TGraphX 1.5.1 on CPU, in order. The DGL blocks follow the DGL 2.4.0 source code but were not executed: DGL was not installed in the test environment.

Before you install DGL. As of 26 November 2026 the dgl.ai domain showed as expired, so do not install or download anything from *.dgl.ai addresses, including through dgl.data downloads (details on the comparison page).

High-Level Positioning

Dimension TGraphX 1.5.1 DGL 2.4.0
Maturity Beta Newest release tag is v2.4.0, September 2024 (checked 26 November 2026)
Tensor-valued node features Stored, with spatial layers for [N, C, H, W] and [N, C, D, H, W] Stored in ndata; no spatial convolutions in dgl.nn
Built-in vector layers Small set Large collection
Validation At Graph construction When data is assigned to ndata / edata
Neighbourhood sampling NeighborLoader, GraphSAINT, Cluster-GCN loaders (Beta) NeighborSampler, SAINTSampler, ClusterGCNSampler; GraphBolt
Many small graphs GraphBatch, GraphDataLoader dgl.batch, dgl.dataloading.GraphDataLoader
Multi-machine training No distributed graph store dgl.distributed
Dependency Pure-Python package; requires torch, torchvision and pyyaml Compiled libraries tied to PyTorch and CUDA versions

Neither library forces you to flatten tensor features. The practical difference is which layers exist to consume them.

Step 1: Build the Graph

TGraphX. Features, labels and masks go into one object, which validates shapes, index ranges and devices when it is built:

python
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph, NeighborLoader
from tgraphx.estimators import node_train_val_test_split
from tgraphx.reproducibility import set_seed

set_seed(0)
N = 120
x = torch.randn(N, 3, 8, 8)                    # one [C, H, W] map per node
edge_index = torch.randint(0, N, (2, 600))     # [source, destination]
y = torch.randint(0, 4, (N,))                  # random labels: workflow only, no accuracy claim
train, val, test = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=0)

g = Graph(node_features=x, edge_index=edge_index, y=y,
          train_mask=train, val_mask=val, test_mask=test)
assert tgx.check_leakage(train_mask=train, val_mask=val, test_mask=test)["ok"]

DGL. The graph is created from the edge endpoints, and tensors are attached by name. DGL raises if a node tensor's first dimension does not match the number of nodes, if it lives on another device than the graph, or if num_nodes is too small for the edge ids:

python
import dgl

src, dst = edge_index
g_dgl = dgl.graph((src, dst), num_nodes=N)
g_dgl.ndata["feat"] = x                        # [N, 3, 8, 8] is stored as is
g_dgl.ndata["label"] = y

One difference to remember: TGraphX validates in the constructor. If you reassign an attribute afterwards, call g.validate() yourself.

Step 2: Define a Model over Feature Maps

TGraphX ships the layer. This builds two spatial GraphSAGE layers, averages over the spatial axes and classifies each node:

python
model = tgx.build_model("node_classification", layer="sage", in_shape=(3, 8, 8),
                        hidden_shape=(16, 8, 8), num_layers=2, num_classes=4)
print(model(g.node_features, g.edge_index).shape)      # torch.Size([120, 4])

DGL has no built-in spatial convolution over node maps, so you write the layer from message and reduce functions. This one mirrors the TGraphX layer (1x1 convolutions, mean over neighbours):

python
import dgl.function as fn
import torch.nn as nn

class SpatialSAGE(nn.Module):
    def __init__(self, c_in, c_out):
        super().__init__()
        self.lin_self = nn.Conv2d(c_in, c_out, 1)
        self.lin_neigh = nn.Conv2d(c_in, c_out, 1, bias=False)

    def forward(self, block, h):
        h_dst = h[: block.num_dst_nodes()]     # destination nodes come first in a block
        with block.local_scope():
            block.srcdata["h"] = h
            block.update_all(fn.copy_u("h", "m"), fn.mean("m", "agg"))
            return self.lin_self(h_dst) + self.lin_neigh(block.dstdata["agg"])

class DGLModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer1 = SpatialSAGE(3, 16)
        self.layer2 = SpatialSAGE(16, 16)
        self.head = nn.Linear(16, 4)

    def forward(self, blocks, x):
        h = F.relu(self.layer1(blocks[0], x))
        h = F.relu(self.layer2(blocks[1], h))
        return self.head(h.mean(dim=(2, 3)))

Step 3: Mini-Batch Training with Neighbour Sampling

TGraphX. Pass the training mask as seeds. Each batch is an ordinary subgraph, so the same model runs on it; the loss is taken on the seed rows:

python
loader = NeighborLoader(g, fanouts=[5, 3], mask=g.train_mask, batch_size=24, seed=0)
opt = torch.optim.Adam(model.parameters(), lr=1e-2)

for epoch in range(2):
    model.train()
    for batch in loader:
        opt.zero_grad()
        out = model(batch.node_features, batch.edge_index)
        loss = F.cross_entropy(batch.seed_logits(out), batch.seed_y)
        loss.backward()
        opt.step()

DGL. The sampler returns one bipartite block (message flow graph) per layer, and the model output corresponds to the seed nodes:

python
dgl_model = DGLModel()
dgl_opt = torch.optim.Adam(dgl_model.parameters(), lr=1e-2)
sampler = dgl.dataloading.NeighborSampler([3, 5])      # first entry = first (input) layer
dgl_loader = dgl.dataloading.DataLoader(g_dgl, train.nonzero().squeeze(1), sampler,
                                        batch_size=24, shuffle=True)

for epoch in range(2):
    for input_nodes, output_nodes, blocks in dgl_loader:
        dgl_opt.zero_grad()
        out = dgl_model(blocks, blocks[0].srcdata["feat"])
        loss = F.cross_entropy(out, blocks[-1].dstdata["label"])
        loss.backward()
        dgl_opt.step()

Three things differ when you port code:

  • Fanout order is reversed. In TGraphX (as in PyTorch Geometric) the first entry is the number of direct neighbours of the seeds. In DGL the entries are listed per GNN layer from the input side, so the last one applies to the seeds. TGraphX [5, 3] corresponds to DGL [3, 5].
  • A batch is a different object. TGraphX returns the subgraph induced on all visited nodes, which can contain more edges than were sampled, and the seeds are not necessarily the first rows. DGL blocks hold the sampled edges per layer.
  • Seeds must be given. TGraphX's NeighborLoader with mask=None seeds every node, including validation and test nodes.

The fanout order on the TGraphX side, checked on a small tree:

python
tree = Graph(node_features=torch.zeros(7, 1),
             edge_index=torch.tensor([[1, 2, 3, 4, 5, 6],     # sources
                                      [0, 0, 0, 1, 1, 1]]))   # destinations
sub = tgx.neighbor_sample(tree, torch.tensor([0]), [-1, 1], seed=0)
ids = sub.metadata["sampling"]["original_node_ids"].tolist()
print(ids)                     # all of 1, 2, 3 (hop 1), then one of 4, 5, 6 (hop 2)
assert {0, 1, 2, 3} <= set(ids) and len(ids) == 5

Step 4: Evaluate, Save and Log

TGraphX. The graph is small enough for a full forward pass:

python
model.eval()
with torch.no_grad():
    logits = model(g.node_features, g.edge_index)
val_acc = (logits[g.val_mask].argmax(1) == g.y[g.val_mask]).float().mean().item()

with tgx.CSVLogger("runs/dgl_comparison") as logger:
    logger.log(epoch=2, val_accuracy=val_acc)
tgx.save_checkpoint(model, opt, 2, "runs/dgl_comparison/model.pt")

DGL. Because the model above consumes blocks, evaluate with a full-neighbour sampler. Saving and logging use PyTorch and your tracker of choice:

python
full = dgl.dataloading.MultiLayerFullNeighborSampler(2)
val_loader = dgl.dataloading.DataLoader(g_dgl, val.nonzero().squeeze(1), full, batch_size=24)
correct = total = 0
dgl_model.eval()
with torch.no_grad():
    for _, _, blocks in val_loader:
        pred = dgl_model(blocks, blocks[0].srcdata["feat"]).argmax(1)
        correct += (pred == blocks[-1].dstdata["label"]).sum().item()
        total += pred.numel()
torch.save(dgl_model.state_dict(), "dgl_model.pt")

TGraphX includes CSV, TensorBoard and MLflow loggers, fit / evaluate helpers and a config runner. Check what each does before relying on it: fit does not read node masks, and the config runner is a basic smoke runner without a validation split. For masked node classification, write the loop as above. For seeding, tgraphx.reproducibility.set_seed covers Python, NumPy and PyTorch; DGL's own generator is seeded separately with dgl.seed.

Scaling Beyond One Machine

This is where the two diverge most. DGL provides dgl.distributed, with graph partitioning and a distributed graph store, for training on graphs spread over several machines. TGraphX's tgraphx.distributed states that it "does not ship a distributed training framework"; it offers rank, sharding and DDP helpers, and the graph itself must be available to each process. For large graphs on one machine, TGraphX has the sampling loaders above and memory-mapped feature storage.

A Decision Framework

Use TGraphX when:

  • Your nodes carry image-like or volumetric tensors and you want ready-made spatial message-passing layers
  • Your graph structure fits on one machine
  • You want a package with no compiled extensions of its own (its torch and torchvision requirements are compiled, and their builds must match)
  • Beta status, with possible API changes, is acceptable

Use DGL when:

  • You need multi-machine training on a partitioned graph
  • You need a broad set of established vector-feature layers or heterogeneous graphs as a core feature
  • You want compiled message-passing kernels
  • Your PyTorch, CUDA and Python versions match what DGL publishes builds for (check this first; the comparison page records the state of the packages)

You can also combine them. tgraphx.interop converts graphs in both directions (to_dgl_graph, from_dgl_graph); train, validation and test masks are not carried over, so reattach them. The converter's default keys differ from the ones used on this page, so call from_dgl_graph(g_dgl, node_feature_key="feat", node_label_key="label"). A wrong label key is ignored silently and the result has no labels. to_dgl_graph writes ndata["x"] and ndata["y"].

Note on Benchmarks

No throughput or accuracy comparison is made here. Such results depend on graph size, hardware, batch configuration, layer choice and library versions. If performance decides your choice, measure both on your graphs and hardware.

References and Related Articles