PyTorch Geometric: Strengths, Weaknesses, and What It Doesn't Cover
PyTorch Geometric (PyG) is one of the most widely used libraries for graph neural networks, and for most GNN work it is a sound choice. This page assesses it for a researcher deciding whether it covers a project: what it does well, where you will need extra work, and what it leaves to other tools.
Statements about PyG refer to version 2.8.1, checked on 26 November 2026. The code on this page runs with it; other points come from reading its installed source. Libraries change, so recheck the points that matter to you. The few comparisons with TGraphX use version 1.5.1.
What PyG Does Well
- Datasets.
torch_geometric.datasetsoffers more than 100 dataset classes, including the Planetoid citation graphs, the TU collections, ZINC and QM9. OGB publishes PyG-format loaders in its ownogbpackage. - Layers.
torch_geometric.nn.convexports more than 60 classes, among themGCNConv,GATv2Conv,SAGEConv,GINConv,PNAConv,GCN2Conv,TransformerConv,RGCNConvandHGTConv. - Message passing. The
MessagePassingbase class separatesmessage,aggregateandupdate, so a new layer is a small class. - Mini-batching.
NeighborLoader,LinkNeighborLoader, Cluster-GCN (ClusterData,ClusterLoader) and GraphSAINT samplers. - Heterogeneous graphs.
HeteroData,to_heteroand relation-specific convolutions. - Beyond convolutions.
torch_geometric.explain(Explainer,GNNExplainer,PGExplainer),Node2Vec,MetaPath2Vec,GAEandVGAE, and knowledge graph embeddings intorch_geometric.nn.kge(TransE, ComplEx, DistMult, RotatE). - Community. A large user base, extensive documentation and active releases.
A quick way to confirm what your installation provides:
import torch
import torch_geometric
from torch_geometric.data import Data
from torch_geometric.explain import Explainer, GNNExplainer, PGExplainer
from torch_geometric.nn import GAE, VGAE, MetaPath2Vec, Node2Vec, WLConv, conv
from torch_geometric.nn.kge import ComplEx, DistMult, RotatE, TransE
from torch_geometric.utils import (barabasi_albert_graph, erdos_renyi_graph,
get_ppr, stochastic_blockmodel_graph)
print(torch_geometric.__version__)
print(len(conv.__all__) - 1) # classes listed in torch_geometric.nn.conv, minus the base class
2.8.1
66
Where You Will Need Extra Work
Most built-in layers assume vector node features
Data is a general container: it holds x with any trailing shape. The constraint is in the layers. Most built-in convolutions apply linear maps to the last dimension and expect [N, D], so image-like [N, C, H, W] features either get flattened or need a layer that handles them.
import torch.nn as nn
from torch_geometric.nn import GCNConv, GINConv
torch_geometric.seed_everything(0)
x = torch.randn(6, 3, 8, 8) # 6 nodes, each a 3x8x8 tensor
edge_index = torch.tensor([[0, 1, 2, 3, 4], [1, 2, 3, 4, 5]])
data = Data(x=x, edge_index=edge_index)
print(data, data.num_node_features) # the container keeps the 4-D x
try:
GCNConv(3, 16)(data.x, data.edge_index)
except RuntimeError as err:
print("GCNConv:", err)
def conv_net():
return nn.Sequential(nn.Conv2d(3, 16, 1), nn.ReLU(), nn.Conv2d(16, 16, 1))
summed = torch.zeros_like(x).index_add_(0, edge_index[1], x[edge_index[0]])
right = GINConv(conv_net(), node_dim=0) # nodes are dimension 0
print(torch.allclose(right(x, edge_index), right.nn(x + summed)))
wrong = GINConv(conv_net()) # default node_dim=-2
out = wrong(x, edge_index) # no error ...
print(tuple(out.shape), torch.allclose(out, wrong.nn(x + summed))) # ... wrong values
Data(x=[6, 3, 8, 8], edge_index=[2, 5]) 8
GCNConv: mm: mat1 and mat2 shapes cannot be multiplied (144x8 and 3x16)
True
(6, 16, 8, 8) False
Two points are worth knowing:
data.num_node_featuresreports the last dimension (8), not the channel count.GINConvworks on tensor features when you give it a convolutional network andnode_dim=0. With the defaultnode_dim=-2, PyG treats the height axis as the node axis. Here it ran without an error and returned wrong values; if an edge index reaches the image height (8 here), the same mistake raises an error instead. Test a new tensor setup against a hand-computed sum, as above.
You can also write your own MessagePassing layer with node_dim=0 and any tensor operations, including spatial convolutions; TGraphX vs PyTorch Geometric shows one. Edge attributes are similar: Data can hold any shape, but check what each layer expects before passing anything other than one vector per edge.
Flattening has a cost
If you flatten [16, 32, 32] feature maps to use vector layers, each node has 16,384 features:
import tgraphx as tgx
def n_params(module):
return sum(p.numel() for p in module.parameters())
flat_dim = 16 * 32 * 32
print(flat_dim, n_params(GCNConv(flat_dim, 256)))
print(n_params(tgx.TensorGINLayer(16, 256))) # two 1x1 convolutions
16384 4194560
70144
One GCNConv(16384, 256) layer has about 4.2 million parameters: a separate weight for every input value and output unit, with no weight sharing across positions and no notion of which pixels are neighbours. A layer built from 1×1 convolutions has far fewer because it shares weights across positions. The two layers are not equivalent: the convolutional one outputs 256×32×32 values per node rather than 256, and it never mixes pixel positions. Which trade-off suits your task is something to measure on held-out data.
Flattening itself is reversible, and a message or update function can reshape back to [C, H, W]. The cost lies in using vector layers on the flattened values.
Check the knowledge graph evaluation protocol
In 2.8.1, KGEModel.test ranks each test triple against every entity as the tail only. It takes no list of known triples, so ranks are unfiltered, and its mean rank is zero-based (the best possible value is 0). Knowledge graph results are commonly reported as filtered ranks averaged over head and tail prediction, so check the protocol before comparing numbers.
model = DistMult(num_nodes=5, num_relations=1, hidden_channels=2)
with torch.no_grad(): # hand-set weights so the ranking is known
model.node_emb.weight.copy_(
torch.tensor([[1., 0.], [3., 0.], [2., 0.], [1., 0.], [0.5, 0.]]))
model.rel_emb.weight.copy_(torch.tensor([[1., 0.]]))
# Test triple (0, 0, 1): entity 1 is the highest-scoring tail
mean_rank, mrr, hits = model.test(torch.tensor([0]), torch.tensor([0]), torch.tensor([1]),
batch_size=10, k=1, log=False)
print(mean_rank, mrr, hits)
0.0 1.0 1.0
For filtered head-and-tail ranking, write the evaluation yourself or use a library that provides it, such as PyKEEN or tgraphx.kg.KGEvaluator. See TGraphX vs PyKEEN.
Some samplers need compiled extensions
pyg-lib and torch-sparse are separate compiled packages whose builds are tied to your PyTorch and CUDA versions. In an environment with only torch-geometric, NeighborLoader raises 'NeighborSampler' requires either 'pyg-lib' or 'torch-sparse' on its first batch, and ClusterData fails too without one of them. The GraphSAINT samplers need torch-sparse specifically: without it they raise 'SparseTensor' requires 'torch-sparse', and pyg-lib does not replace it. In 2.8.1, Node2Vec also requires pyg-lib>=0.6.0: without it the constructor raises 'Node2Vec' requires 'pyg-lib>=0.6.0', even though the import at the top of this page succeeds. Plan the installation for your cluster before depending on these.
Graph analysis is not its focus
PyG has some structural tools: WLConv for Weisfeiler-Lehman colouring, get_ppr for personalized PageRank (it needs numba; the import succeeds without it), positional-encoding transforms and Data.connected_components(). A search of the 2.8.1 source finds no betweenness or closeness centrality, motif counting or Louvain community detection. Use a graph analysis library such as NetworkX for those (TGraphX vs NetworkX).
No evolutionary search or graph RL module
PyG can generate random topologies (erdos_renyi_graph, barabasi_albert_graph and stochastic_blockmodel_graph in torch_geometric.utils, plus generator classes in torch_geometric.datasets.graph_generator) and has autoencoders for link reconstruction. It has no module for evolutionary search over graph structures or for reinforcement learning on graphs, so combine it with an RL or optimization library, or write your own.
Seeding is not determinism
torch_geometric.seed_everything(seed) seeds Python's random, NumPy and PyTorch (CPU and CUDA). It does not switch on deterministic algorithms; call torch.use_deterministic_algorithms(True) yourself if you need that, and record library versions and hardware. GraphGym offers configuration-driven experiments and has extra dependencies. See GNN research reproducibility.
Distributed sampling
In 2.8.1, classes in torch_geometric.distributed warn that the module has been deprecated since 2.7.0. Check the current documentation for the recommended multi-node approach before planning around it.
Gap Summary
| Need | PyG 2.8.1 | If it matters |
|---|---|---|
| Vector features, standard layers | Broad support | Use PyG |
[C, H, W] or [C, D, H, W] node features |
Container yes; most layers no | Custom MessagePassing, GINConv with node_dim=0, or ready-made layers such as TGraphX's |
| Filtered knowledge graph ranking | Not in KGEModel.test |
Your own evaluation, PyKEEN or tgraphx.kg |
| Neighbor, cluster and GraphSAINT sampling | Yes, with compiled extensions | Install pyg-lib or torch-sparse (GraphSAINT needs torch-sparse), or use loaders written in plain PyTorch such as TGraphX's (Beta; for GraphSAINT, read the porting notes below) |
| Centrality, motifs, communities | Limited | NetworkX |
| Explainability | torch_geometric.explain |
Use PyG |
| Heterogeneous graphs | Well developed | Use PyG |
| Graph RL, evolutionary search | Not included | External library, your own code, or TGraphX's graph RL (Experimental) or evolutionary modules (Beta in the README, partly experimental in the registry) |
Porting GraphSAINT code to TGraphX
If you move GraphSAINT code from PyG to TGraphX, rewrite the weighting. With sample_coverage > 0, PyG attaches node_norm and edge_norm as weights that you multiply by. For each subgraph sub that its GraphSAINTLoader yields, TGraphX 1.5.1 stores estimated inclusion probabilities under the same two names, in sub.metadata["graphsaint"], and applies neither. Code that still multiplies by them runs without any error and weights wrongly. Do not multiply by them. Build the weights from them:
- Node loss weight:
1 / (node_norm * N), withNthe node count of the full graph. This plays the role of PyG'snode_norm. - Edge weight in PyG's convention:
node_norm[sub.edge_index[0]] / edge_norm. It is a ratio of two probabilities, so never use1 / edge_normalone, which leaves out the node probability.
The aggregator correction in the GraphSAINT paper uses the receiving node, node_norm[sub.edge_index[1]] / edge_norm, while PyG 2.8.1 uses the source node. The two differ when the end nodes of an edge have different inclusion probabilities, so use the PyG form to match PyG's weighting and the receiving-node form to follow the paper.
Check the sampling itself as well:
- Pass an integer
seedto the sampler. PyG's GraphSAINT samplers take noseedargument, so a straight port tends to leave it atNone. TGraphX 1.5.1 then draws the same subgraph at every step, the estimated probabilities of its nodes and edges all come out as 1.0, and nodes outside it are never visited. - Move the seed between epochs. With a fixed seed, every pass over the loader repeats the same sequence. Set
sampler.seed = base_seed + epoch * sampler.num_stepsbefore each pass, and keep thebase_seedvalues of repeated runs at leastepochs * sampler.num_stepsapart. - Clamp both probabilities before dividing, for example with
clamp_min(1 / num_norm_samples). A node or edge that the estimating draws never saw is stored as 1e-6, which can produce an enormous weight. Clamping limits the weight but adds bias, so also raisenum_norm_samples, an argument ofGraphSAINTLoader(default 50), when each draw covers only a small share of the graph.
The sampling math note derives the receiving-node form, lists where the TGraphX samplers differ from the paper's, and has a training loop with an integer seed, per-epoch seed changes and clamped probabilities.
When PyG Is the Right Choice
- You are reproducing a published PyG baseline.
- Your node features are naturally vectors.
- You need a layer that PyG already implements.
- You want its built-in datasets, or OGB's PyG data loaders.
- You need heterogeneous graph support or its explainability tools.
See TGraphX vs PyTorch Geometric for a side-by-side comparison, and the decision guide for a quick way to test the fit on your own data.
Common Misconceptions
"PyG is faster than everything else." Speed depends on graph size, batch size, hardware, layer type and the installed extensions. This page reports no benchmarks; for your own measurements, see what to record with a benchmark number.
"A PyG layer is the paper's code." A library implementation can differ from the original in normalization, initialization or default hyperparameters. When reproducing a paper, read the layer's documentation and compare the settings.
"If PyG lacks it, you must start over." PyG works on ordinary PyTorch tensors, so you can combine it with other libraries in one pipeline. The TGraphX and PyG workflow article shows one way.
Summary
PyG is a mature, broad library and the natural starting point for GNN research on vector features. The points to check before committing are specific: how its layers treat tensor-valued features, what its knowledge graph test method measures, whether your environment can install the compiled sampling extensions, and which analysis or search tools you need from elsewhere.
Further Reading
- Shape-aware validation in TGraphX: why shape errors are subtle and how to catch them
- When flat vector node features are insufficient: the spatial structure question in depth
- GNN research reproducibility: more than a random seed
- Recording benchmark context: what to record with a benchmark number
- Research integrity in graph learning: the broader context of GNN evaluation