TGraphX › Insights › Interoperating with PyTorch Geometric, OGB, and DGL Datasets in TGraphX
← Back to Insights

Interoperating with PyTorch Geometric, OGB, and DGL Datasets in TGraphX

Topic: Framework comparisons and interoperability

You probably already have data in PyTorch Geometric (PyG), OGB, DGL or torchvision. TGraphX can read it through converter functions in tgraphx.interop and dataset adapters in tgraphx.datasets. These are data-format converters: they hand the source tensors to a tgraphx.Graph (without cloning them, so in-place edits affect both), and they do not make one library's layers or loaders work like another's.

The most important thing to know up front: the converters do not carry train, validation and test masks across as mask fields. This guide shows what is and is not carried over, and how to fix the gaps. It complements TGraphX vs PyTorch Geometric and TGraphX vs DGL.

The runnable examples were tested with TGraphX 1.5.1 and PyG 2.8.1 on CPU. DGL and OGB were not installed, and nothing was downloaded, so those examples are marked as untested against the real libraries.

What to install

A plain pip install tgraphx brings torch, torchvision and pyyaml. The bridges are optional:

Source Install Note
PyG pip install "tgraphx[pyg]" installs torch-geometric
OGB pip install "tgraphx[ogb]" torch-geometric the ogb extra does not pull in torch-geometric, which the PyG-format OGB loaders need
DGL install DGL following its repository; avoid *.dgl.ai for now (see the DGL section) there is no dgl extra
torchvision included

The converters and adapters import these libraries only when you call them, so a missing package shows up at that moment as an ImportError with an install hint.

Convert a PyG Data object

This example builds a small Data object in memory, so nothing is downloaded:

python
import torch
from torch_geometric.data import Data

import tgraphx as tgx
from tgraphx import Graph
from tgraphx.interop import from_pyg_data, to_pyg_data

torch.manual_seed(0)
n = 100
data = Data(
    x=torch.randn(n, 16),
    edge_index=torch.randint(0, n, (2, 400)),
    y=torch.randint(0, 3, (n,)),
    train_mask=torch.arange(n) < 60,
    val_mask=(torch.arange(n) >= 60) & (torch.arange(n) < 80),
    test_mask=torch.arange(n) >= 80,
)

g = from_pyg_data(data)
print(g)
print(g.train_mask, g.val_mask, g.test_mask)     # None None None

from_pyg_data copies exactly these fields:

PyG field TGraphX field
x (required) node_features
edge_index edge_index
edge_weight edge_weight
edge_attr edge_features
y with one row per node node_labels
any other y graph_label

Everything else is dropped without a warning: split masks, positions, timestamps and custom attributes. from_dgl_graph has the same limitation for masks.

Keep the split masks

Reattach the masks when you build the graph, then check that they do not overlap:

python
def with_masks(graph, train, val, test):
    """Rebuild a converted Graph with split masks attached."""
    return Graph(node_features=graph.node_features, edge_index=graph.edge_index,
                 edge_weight=graph.edge_weight, edge_features=graph.edge_features,
                 node_labels=graph.node_labels, graph_label=graph.graph_label,
                 train_mask=train, val_mask=val, test_mask=test)


g = with_masks(from_pyg_data(data), data.train_mask, data.val_mask, data.test_mask)
g.validate()                                      # raises if the graph is malformed
leak = tgx.check_leakage(train_mask=g.train_mask, val_mask=g.val_mask, test_mask=g.test_mask)
print(leak["ok"], leak["counts"])

Remember that tgx.fit ignores node masks, so for transductive node classification write a loop that computes the loss on g.train_mask only.

The reverse direction also needs a step. to_pyg_data does not create data.train_mask, data.val_mask or data.test_mask. It does copy graph.metadata, so the masks travel only nested inside data.metadata, not where PyG code expects them. Set the three fields yourself:

python
back = to_pyg_data(g)
print("train_mask" in back)                       # False
print(list(back.metadata["masks"]))               # ['train', 'val', 'test']
back.train_mask, back.val_mask, back.test_mask = g.train_mask, g.val_mask, g.test_mask

Shapes to check after conversion

Three source formats need a small fix:

python
from torch_geometric.transforms import Constant

# 1. Labels stored as [N, 1] stay [N, 1]; CrossEntropyLoss wants [N]
column = Data(x=torch.randn(3, 4), edge_index=torch.tensor([[0, 1], [1, 2]]),
              y=torch.tensor([[0], [2], [1]]))
h = from_pyg_data(column)
h.node_labels = h.node_labels.view(-1)

# 2. Edge weights stored as [E, 1] are rejected; flatten them first
weighted = Data(x=torch.randn(3, 4), edge_index=torch.tensor([[0, 1], [1, 2]]),
                edge_weight=torch.ones(2, 1))
weighted.edge_weight = weighted.edge_weight.view(-1)
from_pyg_data(weighted)

# 3. Data without node features raises ValueError; add features first
featureless = Data(edge_index=torch.tensor([[0, 1], [1, 0]]), num_nodes=2, y=torch.tensor([1]))
fg = from_pyg_data(Constant()(featureless))
print(fg.node_features.shape, fg.graph_label)     # torch.Size([2, 1]) tensor(1)

Some TUDataset collections, such as IMDB-BINARY and REDDIT-BINARY, have no node features, so the third case applies to them. A transform like Constant has to be given to the PyG dataset itself, for example get_dataset("pyg:generic", dataset_cls="TUDataset", dataset_kwargs={"name": "IMDB-BINARY", "transform": Constant()}) (this downloads data and was not run here).

Tensor-valued features pass through

PyG's Data.x can hold tensors of any rank; many of its built-in convolutions expect vectors. The converter keeps the shape, so image-like node tensors arrive ready for TGraphX's tensor layers:

python
images = Data(x=torch.randn(6, 3, 8, 8), edge_index=torch.tensor([[0, 1, 2], [1, 2, 3]]))
print(from_pyg_data(images).feature_shape)        # (3, 8, 8)

A flat dataset stays flat: [N, D] features do not become image-like by converting them.

Dataset adapters and load_dataset

tgx.load_dataset(name) looks up a friendly name and returns a dataset object, not a Graph. Index it to get one. tgx.list_dataset_aliases() lists the short names, and tgraphx.datasets.list_datasets() lists all registry names.

The adapter converts each item on access with the same converter, so the same fields are lost. You can see this offline by giving the generic PyG adapter a local class in place of a downloading one:

python
from tgraphx.datasets import get_dataset


class LocalDataset:                               # stands in for a torch_geometric.datasets class
    def __init__(self, root):
        self.items = [data]

    def __len__(self):
        return len(self.items)

    def __getitem__(self, i):
        return self.items[i]


ds = get_dataset("pyg:generic", dataset_cls=LocalDataset, root="pyg_cache")
print(type(ds).__name__, len(ds), ds[0])
print(ds[0].train_mask)                           # None

For Cora this means the standard public split is not on tgx.load_dataset("cora")[0]. Load it with PyG and attach the masks:

python
from torch_geometric.datasets import Planetoid

ds = tgx.load_dataset("cora")                     # a dataset object; downloads on first use
graph_without_masks = ds[0]

data_cora = Planetoid(root="data", name="Cora")[0]
cora = with_masks(from_pyg_data(data_cora), data_cora.train_mask,
                  data_cora.val_mask, data_cora.test_mask)

What gets downloaded

  • PyG and OGB adapters download on first use. They call the upstream constructors, which fetch missing files. The adapters accept a download argument, but it does not stop this.
  • DGL datasets also fetch missing files on first use; see the warning in the DGL section before you let them.
  • torchvision adapters do not download by default. Without local files they raise; pass download=True to fetch.

The default cache is $TGRAPHX_DATA, or ~/.cache/tgraphx/datasets. With an explicit root, adapters create their own subfolder inside it (for example data/pyg_Planetoid). On a machine that must stay offline, prepare the files beforehand.

OGB

The OGB adapter keeps the official split indices and gives access to the OGB evaluator.

With PyTorch 2.6 or newer, do this first. The latest ogb release on PyPI when this page was checked, 1.3.6, reads its processed file with torch.load without setting weights_only. Since PyTorch 2.6 the default is weights_only=True, which refuses the PyG classes in that file and raises UnpicklingError ("Unsupported global ... DataEdgeAttr"). The problem is reported in ogb issue #497, which was still open. For files you trust, allowlist the classes before you create the dataset:

python
from torch_geometric.data.data import DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage

# trusted files only: allows torch.load to rebuild these three PyG classes
torch.serialization.add_safe_globals([DataEdgeAttr, DataTensorAttr, GlobalStorage])

With PyG 2.8.1 and PyTorch 2.15, this allowlist loaded a file written the way ogb 1.3.6 writes its node-property data. It was not tried on the real dataset, and other OGB datasets may store objects that need more.

Then build masks from the split indices, and note that node labels arrive as [N, 1]:

python
from tgraphx.datasets import get_dataset

ogb_ds = get_dataset("ogb:ogbn-arxiv", root="data/ogb")
arxiv = ogb_ds[0]
arxiv.node_labels = arxiv.node_labels.view(-1)
split = ogb_ds.get_idx_split()


def index_to_mask(index, size):
    mask = torch.zeros(size, dtype=torch.bool)
    mask[index] = True
    return mask


train, val, test = (index_to_mask(split[k], arxiv.num_nodes)
                    for k in ("train", "valid", "test"))
arxiv = with_masks(arxiv, train, val, test)

evaluator = ogb_ds.get_evaluator()
pred = torch.zeros(arxiv.num_nodes, dtype=torch.long)    # replace with model predictions
print(evaluator.eval({"y_true": arxiv.node_labels[test].view(-1, 1),
                      "y_pred": pred[test].view(-1, 1)}))

The block above was run only against a stand-in for the ogb package, which checks the TGraphX side but not the real data. ogbn-arxiv edges are directed; call arxiv.make_undirected() if your model expects both directions.

DGL

Warning (checked 26 and 27 November 2026): the dgl.ai domain, which also serves DGL's datasets from data.dgl.ai, showed a registrar renewal page. Do not trigger downloads through dgl.data (or through the dgl: dataset names below, which build the same classes) until you can confirm that the DGL project controls the domain again. Some of those downloads are read with pickle, which can run code stored in the file. TGraphX vs DGL has the details.

There is also a catch in 1.5.1. The registry has dgl:cora, dgl:citeseer and dgl:pubmed, but indexing them raises ValueError: the adapter looks for node features under ndata["x"], while DGL's citation datasets store them under ndata["feat"] and labels under ndata["label"]. So convert a DGL graph yourself and name the keys. The example builds a small graph in memory; use the same call for a graph you already have from a source you trust:

python
import dgl
from tgraphx.interop import from_dgl_graph

raw = dgl.graph(([0, 1, 2], [1, 2, 0]))
raw.ndata["feat"] = torch.randn(3, 8)
raw.ndata["label"] = torch.tensor([0, 1, 0])
for name, node in (("train_mask", 0), ("val_mask", 1), ("test_mask", 2)):
    raw.ndata[name] = torch.arange(3) == node
dgl_graph = from_dgl_graph(raw, node_feature_key="feat", node_label_key="label")
dgl_graph = with_masks(dgl_graph, raw.ndata["train_mask"],
                       raw.ndata["val_mask"], raw.ndata["test_mask"])

Both the failure and this workaround were checked against a stand-in that uses DGL's key names, not against DGL itself.

torchvision images as patch graphs

The torchvision adapters turn each image into a graph of patches on a grid, with the class as graph_label, so the task is graph classification. fake_patch uses torchvision's random FakeData and needs no files:

python
fake = tgx.load_dataset("torchvision:fake_patch", patch_size=8, root="tv_cache",
                        upstream_kwargs={"size": 8, "image_size": (3, 32, 32),
                                         "num_classes": 10})
g0 = fake[0]
print(len(fake), g0.num_nodes, g0.feature_shape, g0.graph_label.item())

try:
    tgx.load_dataset("mnist", root="tv_cache_empty")      # download defaults to False
except RuntimeError as err:
    print(err)

If you split patches rather than images into train and test sets, pixels from one image end up on both sides. Split by image.

Cache what you converted

Save the converted graph, masks included, so later runs skip the adapter, and record where it came from:

python
g.metadata["source"] = "synthetic PyG Data from this tutorial"
g.metadata["converted_with"] = f"tgraphx {tgx.__version__}"
g.save("converted/graph.tgx")

loaded = Graph.load("converted/graph.tgx")
assert torch.equal(loaded.train_mask, g.train_mask)

.tgx files are loaded by unpickling, so open only files you trust. Exports to NetworkX or GraphML are not a substitute: they do not carry tensor features by default. See serializing tensor graphs.

Conversion checklist

  1. Install the right packages, including torch-geometric for OGB.
  2. Decide where data is cached and whether downloading is acceptable.
  3. Reattach split masks and run check_leakage with keyword arguments.
  4. Check label, edge-weight and feature shapes.
  5. Run g.validate(), and tgx.validate_graph(g, check_finite=True) for NaN or Inf values.
  6. Save the converted graph with its provenance.

When not to convert

If your data are flat vectors and your existing PyG or DGL pipeline already trains well, there is little to gain from converting. Convert when you want TGraphX's tensor layers or tooling on that data. PyG and DGL have their own mature loaders and layers, and you can keep using them.

Related guides

The repository's examples/ folder has adapter demos (pyg_dataset_adapter_demo.py, ogb_dataset_adapter_demo.py, dgl_dataset_adapter_demo.py). They are not part of the pip package. As tagged for 1.5.1, the DGL demo stores its features in ndata["feat"] but calls from_dgl_graph with the default key "x", so expect a ValueError until you add node_feature_key="feat" to that call (checked against a stand-in module, not DGL itself).