DGL vs PyTorch Geometric: API, Sampling and Project Status
DGL (Deep Graph Library) and PyTorch Geometric (PyG) both build graph neural networks on PyTorch, and for the common layers they can compute the same numbers. The choice today turns less on the API than on maintenance and installability. As checked on 27 November 2026, PyG is the safer default for a new project: it had a release in October 2026 and states support for PyTorch 2.9 to 2.12, while the newest DGL release dates from September 2024 and its prebuilt packages stop at PyTorch 2.4. DGL remains a reasonable choice to keep running an existing DGL codebase in a pinned environment.
That is a judgement about release activity and compatibility. It says nothing about speed or accuracy: neither was measured here.
What was checked. Code ran on CPU with DGL 2.1.0 (the newest Linux x86-64 wheel on PyPI) on PyTorch 2.2.1, where the side-by-side parity blocks also loaded PyG 2.8.1. The PyG blocks, including neighbour sampling, were run on PyTorch 2.12.0 as well. Release dates and package listings come from GitHub, PyPI and the anaconda.org API on 27 November 2026. DGL 2.4.0 was not executed.
Project status
| DGL | PyG | |
|---|---|---|
| Newest GitHub release | v2.4.0, 3 September 2024 | 2.8.1, 6 October 2026 |
| Last commit on the default branch | 31 July 2025 | 6 November 2026 |
| Repository archived | No | No |
| License | Apache-2.0 | MIT |
Three further observations matter for DGL.
The project's domain. On 27 November 2026, www.dgl.ai showed a registrar page reading "Domain registration has expired", and docs.dgl.ai did not complete an HTTPS connection. That domain hosted the documentation, the wheel index and the downloadable datasets, and DGL's dataset loaders (checked in the 2.1.0 source) download from data.dgl.ai unless you override the repository address. Until you can confirm that the DGL project controls the domain again, do not install packages or download data from any dgl.ai address, including through a library call that does so for you. Search results and old tutorials still link there.
Open questions in the tracker. An issue titled Is new release planned?, opened in May 2026, had comments from users but no visible reply from a maintainer. A second issue contains user reports about the expired domain and failing downloads.
What this does not establish. No announcement ending the project was found, and the repository is not archived. "No recent release" is an observation with a date on it; check the DGL repository again before you rely on it.
Installation and compatibility
DGL ships compiled libraries built for specific PyTorch versions, so the PyTorch version is chosen by DGL, not by you:
| Package | PyTorch it was built for | Python |
|---|---|---|
| DGL 2.1.0 wheel on PyPI (Linux x86-64) | 2.0.0 to 2.2.1 | 3.8 to 3.12 |
DGL 2.4.0 builds on the dglteam conda channel (Linux) |
2.1 to 2.4 | 3.8 to 3.12 |
| PyG 2.8.1 (supported range stated for 2.8) | 2.9 to 2.12 | 3.10 to 3.14 |
The first row was read from the wheel itself, which contains one compiled library per supported PyTorch version. Importing it next to PyTorch 2.15 failed with a FileNotFoundError for a missing libgraphbolt_pytorch_2.15.0.so. The newer PyPI uploads, 2.2.0 and 2.2.1, have no Linux x86-64 wheel (they cover macOS and Windows respectively). Note also that the DGL and PyG ranges above do not overlap, so a single environment holding both runs at least one of them outside its stated range. For the runs below, DGL had its own environment: dgl==2.1.0 from PyPI with torch==2.2.1, numpy<2 and torchdata==0.7.1.
PyG's core is pure Python and installs with pip install torch_geometric. Some features need compiled extensions that match your PyTorch build. Neighbour sampling is the one most people meet: it needs pyg-lib or torch-sparse.
The data model
A PyG graph is a Data object with attributes: data.x, data.edge_index (a [2, E] tensor of source and destination rows), data.edge_attr, data.y, and anything else you assign. A DGL graph is a DGLGraph built from a source tensor and a destination tensor; features live in the dictionaries g.ndata and g.edata. Both store directed edges, so an undirected graph needs both directions.
One difference bites immediately. DGL infers the number of nodes from the largest id unless you pass num_nodes, so isolated nodes at the end disappear. PyG infers num_nodes from the feature matrix when there is one, and otherwise also guesses from the ids. State the count in both.
For ids that are not 0..N-1, build an explicit mapping before either library sees the data; node order and id mapping from NetworkX shows how to keep it reversible.
The same GraphSAGE layer in both
The mean-aggregator GraphSAGE layer computes, for each destination node j,
h'_j = W_self x_j + W_neigh · mean_{i : i -> j} x_i + b
with a zero mean when j has no incoming edge. Here it is in PyG:
import torch
from torch_geometric.nn import SAGEConv
# 5 nodes; column k is the edge src[k] -> dst[k]. Node 4 receives nothing.
src = torch.tensor([0, 1, 2, 3, 3])
dst = torch.tensor([2, 2, 3, 0, 1])
num_nodes = 5
torch.manual_seed(0)
x = torch.randn(num_nodes, 4)
torch.manual_seed(1)
pyg_layer = SAGEConv(4, 3) # aggr="mean" is the default
with torch.no_grad():
pyg_out = pyg_layer(x, torch.stack([src, dst]))
print(pyg_out.shape)
The formula written with plain tensor operations gives a reference that does not depend on either library:
# h'_j = W_self x_j + W_neigh mean_{i -> j} x_i + b, written out by hand
with torch.no_grad():
total = torch.zeros(num_nodes, 4).index_add(0, dst, x[src])
count = torch.bincount(dst, minlength=num_nodes).clamp(min=1).unsqueeze(1)
reference = (x @ pyg_layer.lin_r.weight.T
+ (total / count) @ pyg_layer.lin_l.weight.T
+ pyg_layer.lin_l.bias)
assert torch.allclose(pyg_out, reference, atol=1e-6)
print("PyG matches the formula")
Now DGL, with the weights copied across. The two libraries use different parameter names, and they attach the bias to different linear maps (PyG to the neighbour map, DGL to the self map), which is harmless because the two terms are added:
import dgl
from dgl.nn import SAGEConv as DGLSAGEConv
g = dgl.graph((src, dst), num_nodes=num_nodes) # without num_nodes: 4 nodes
dgl_layer = DGLSAGEConv(4, 3, aggregator_type="mean")
with torch.no_grad():
dgl_layer.fc_self.weight.copy_(pyg_layer.lin_r.weight)
dgl_layer.fc_self.bias.copy_(pyg_layer.lin_l.bias) # the bias moves sides
dgl_layer.fc_neigh.weight.copy_(pyg_layer.lin_l.weight)
dgl_out = dgl_layer(g, x)
assert torch.allclose(dgl_out, reference, atol=1e-6)
print("DGL matches the formula; nodes:", g.num_nodes())
DGL matches the formula; nodes: 5
The aggregator_type argument is required in DGL, while PyG's SAGEConv defaults to aggr="mean". Parity of this one layer is a property of this one layer: other convolutions differ in defaults, so test each one you rely on. Two DGL defaults change behaviour on this very graph: the inferred node count and GraphConv's zero-in-degree check.
inferred = dgl.graph((src, dst))
print("inferred node count:", inferred.num_nodes())
try:
dgl.nn.GraphConv(4, 3)(g, x)
except dgl.DGLError as err:
print("GraphConv:", str(err).split(",")[0])
inferred node count: 4
GraphConv: There are 0-in-degree nodes in the graph
DGL's GraphConv refuses a graph with a node that has no incoming edge unless you add self-loops or pass allow_zero_in_degree=True. PyG's GCNConv adds self-loops by default and returns a row for every node. The GCN reference shows what those self-loops do to the weights.
The two layers also normalise differently on directed graphs. DGL's GraphConv with norm="both" divides by the sender's out-degree and the receiver's in-degree. PyG's GCNConv counts incoming edges for both ends. With self-loops added by hand for DGL and the same weights:
from torch_geometric.nn import GCNConv
# directed edges; DGL needs the self-loops added by hand
d_src, d_dst = torch.tensor([0, 0, 0, 1]), torch.tensor([1, 2, 3, 2])
loops = torch.arange(4)
feats4 = torch.randn(4, 3, generator=torch.Generator().manual_seed(0))
pyg_gcn = GCNConv(3, 2)
dgl_gcn = dgl.nn.GraphConv(3, 2, norm="both")
with torch.no_grad():
dgl_gcn.weight.copy_(pyg_gcn.lin.weight.T) # DGL stores [in, out]
dgl_gcn.bias.copy_(pyg_gcn.bias)
for name, s, d in [("directed", d_src, d_dst),
("both directions", torch.cat([d_src, d_dst]), torch.cat([d_dst, d_src]))]:
a = pyg_gcn(feats4, torch.stack([s, d]))
h = dgl.graph((torch.cat([s, loops]), torch.cat([d, loops])), num_nodes=4)
gap = (a - dgl_gcn(h, feats4)).abs().max().item()
print(f"{name:16s} largest difference {gap:.1e}")
directed largest difference 1.4e+00
both directions largest difference 2.4e-07
They agree when every edge is present in both directions, so a parity test on an undirected graph will not reveal the difference.
Custom message passing
Both let you write the message and the aggregation yourself, in different styles.
- DGL works on the graph object. You write intermediate tensors into
g.srcdata,g.dstdataorg.edata, usually insidewith g.local_scope():, and callg.update_all(message_func, reduce_func)org.apply_edges. Built-ins such asfn.copy_uandfn.meanlet DGL fuse the two steps. A user-defined reduce function receives a "mailbox" holding the incoming messages of nodes with the same in-degree. - PyG works through a class. You subclass
MessagePassing, callself.propagate(edge_index, x=x), and definemessage()with arguments such asx_i(destination) andx_j(source) that are gathered for you. Aggregation is selected withaggr=, including learnable aggregation modules.
The practical difference when debugging: in DGL you can inspect every intermediate in the graph's data dictionaries; in PyG you inspect the arguments inside message(). Neither is more expressive for ordinary sum, mean and max layers.
Heterogeneous graphs
Both treat typed graphs as first-class. PyG uses HeteroData, keyed by node type and by (source type, relation, destination type). DGL uses dgl.heterograph with the same triples. Here is one relation-wise update in each, on authors who write papers and papers that cite papers. In PyG:
from torch_geometric.data import HeteroData
from torch_geometric.nn import HeteroConv
writes = ("author", "writes", "paper")
cites = ("paper", "cites", "paper")
torch.manual_seed(2)
feats = {"author": torch.randn(3, 5), "paper": torch.randn(4, 6)}
edges = {writes: (torch.tensor([0, 1, 1, 2]), torch.tensor([0, 0, 1, 2])),
cites: (torch.tensor([1, 2, 3]), torch.tensor([0, 0, 2]))}
data = HeteroData()
for node_type, h in feats.items():
data[node_type].x = h
for edge_type, (s, d) in edges.items():
data[edge_type].edge_index = torch.stack([s, d])
data.validate(raise_on_error=True)
torch.manual_seed(3)
pyg_hetero = HeteroConv({writes: SAGEConv((5, 6), 3), cites: SAGEConv(6, 3)}, aggr="sum")
with torch.no_grad():
pyg_paper = pyg_hetero(data.x_dict, data.edge_index_dict)["paper"]
print(pyg_paper.shape)
PyG warns that author nodes are not updated, since no relation points to them. In DGL, with the same weights:
from dgl.nn import HeteroGraphConv
hg = dgl.heterograph(edges, num_nodes_dict={"author": 3, "paper": 4})
dgl_hetero = HeteroGraphConv({"writes": DGLSAGEConv((5, 6), 3, "mean"),
"cites": DGLSAGEConv((6, 6), 3, "mean")}, aggregate="sum")
with torch.no_grad():
for edge_type, rel in ((writes, "writes"), (cites, "cites")):
p, d = pyg_hetero.convs[edge_type], dgl_hetero.mods[rel]
d.fc_self.weight.copy_(p.lin_r.weight)
d.fc_self.bias.copy_(p.lin_l.bias)
d.fc_neigh.weight.copy_(p.lin_l.weight)
dgl_paper = dgl_hetero(hg, feats)["paper"]
assert torch.allclose(dgl_paper, pyg_paper, atol=1e-6)
print("heterogeneous layer matches:", tuple(dgl_paper.shape))
heterogeneous layer matches: (4, 3)
HeteroGraphConv and HeteroConv play the same role: one convolution per relation, then a reduction over relations (aggregate="sum" and aggr="sum"). Differences to check when porting are the keys (DGL accepts relation names such as "writes"; PyG's dictionary uses the full triple) and what happens to node types that receive nothing. PyG also offers to_hetero, which converts a homogeneous model into a typed one; DGL ships relational layers such as RelGraphConv and HGTConv.
Mini-batch sampling: the fanout lists run in opposite order
This is the difference most likely to change results silently.
- In DGL,
NeighborSampler(fanouts)takes one entry per GNN layer, first layer first. The last entry applies to the seeds' own neighbours. - In PyG,
num_neighborstakes one entry per hop, starting from the seeds. The first entry applies to the seeds' own neighbours.
On a random graph with 200 nodes, 4,000 edges and 10 seeds, in DGL:
torch.manual_seed(0)
big_src, big_dst = torch.randint(0, 200, (4000,)), torch.randint(0, 200, (4000,))
seeds = torch.arange(10)
big = dgl.graph((big_src, big_dst), num_nodes=200)
for fanouts in ([1, 5], [5, 1]):
sampler = dgl.dataloading.NeighborSampler(fanouts)
input_nodes, output_nodes, blocks = sampler.sample(big, seeds)
into_seeds = int(blocks[-1].in_degrees().max())
farther = int(blocks[0].in_degrees().max())
print(f"DGL {fanouts}: max incoming per seed {into_seeds}, one hop farther {farther}")
DGL [1, 5]: max incoming per seed 5, one hop farther 1
DGL [5, 1]: max incoming per seed 1, one hop farther 5
The same graph in PyG (on PyTorch 2.12.0 with pyg-lib):
from torch_geometric.data import Data
from torch_geometric.loader import NeighborLoader
big_data = Data(edge_index=torch.stack([big_src, big_dst]), num_nodes=200)
for num_neighbors in ([1, 5], [5, 1]):
batch = next(iter(NeighborLoader(big_data, num_neighbors=num_neighbors,
input_nodes=seeds, batch_size=10)))
first_hop = batch.num_sampled_edges[0]
second_hop = batch.num_sampled_edges[1]
indeg = torch.bincount(batch.edge_index[1], minlength=batch.num_nodes)
print(f"PyG {num_neighbors}: max incoming per seed {int(indeg[:10].max())}, "
f"edges at hop 1 and 2: {first_hop}, {second_hop}")
PyG [1, 5]: max incoming per seed 1, edges at hop 1 and 2: 10, 50
PyG [5, 1]: max incoming per seed 5, edges at hop 1 and 2: 50, 44
So DGL's [10, 25] corresponds to PyG's [25, 10]. Reverse the list when you port, and verify it with the in-degrees as above.
The batch objects differ too. DGL returns (input_nodes, output_nodes, blocks): one bipartite message-flow graph per layer, and the model's forward applies layer l to blocks[l]. PyG returns one subgraph as a Data object in which the seed nodes come first, and by default the same edge list is used by every layer. A DGL model written for blocks therefore needs a different forward in PyG, not only a different loader.
Both include cluster-based and GraphSAINT-style samplers. DGL 2.x also has GraphBolt, a separate data-loading pipeline in dgl.graphbolt; it was not run here.
Large graphs and multiple machines
DGL has dgl.distributed: it partitions a graph across machines and samples from the partitions. It is the clearest functional reason to stay with DGL today, subject to the compatibility limits above.
PyG's own torch_geometric.distributed has been deprecated since 2.7.0. PyG's current guidance for scalable GPU workflows points to NVIDIA's PyG container and the cuGraph examples. None of these distributed paths was run for this page.
Other components
Both include explainability tools (DGL: GNNExplainer, PGExplainer, SubgraphX in dgl.nn; PyG: torch_geometric.explain with GNNExplainer, PGExplainer, CaptumExplainer and others) and knowledge-graph scoring (DGL: TransE and TransR modules; PyG: torch_geometric.nn.kge with TransE, DistMult, ComplEx and RotatE).
Criteria matrix
| Criterion | DGL | PyG |
|---|---|---|
| Release activity (27 Nov 2026) | Last release September 2024 | Releases in June and October 2026 |
| PyTorch versions | Prebuilt up to 2.4 | 2.9 to 2.12 stated for 2.8 |
| Compiled code needed for basic layers | Yes, the library itself | No |
| Graph object | DGLGraph, ndata / edata |
Data / HeteroData attributes |
| Custom layers | update_all, apply_edges |
MessagePassing.propagate |
| Sampled batch | one block per layer | one subgraph |
| Fanout order | first GNN layer first | seed hop first |
| Zero in-degree in the GCN layer | error by default | self-loops added by default |
| Heterogeneous graphs | heterograph, HeteroGraphConv |
HeteroData, HeteroConv, to_hetero |
| Multi-machine partitioned training | dgl.distributed |
own module deprecated; external options |
| Documentation | project site unreachable or expired; docs/ in the repository |
hosted on Read the Docs |
How to decide
- Starting something new? Choose PyG, unless a hard requirement points elsewhere. You get a newer PyTorch and a maintained release line.
- Maintaining a DGL codebase that works? Pin Python, PyTorch, CUDA and DGL together, keep a private copy of the packages and datasets you depend on from sources you trust, and add numeric regression tests. Plan a migration if you need a newer PyTorch or GPU generation.
- Need
dgl.distributed? Check first that a DGL build exists for your PyTorch and CUDA. Then compare it with the cuGraph route on your own cluster. - Reproducing a paper whose code is in DGL? Use the paper's versions in an isolated environment. Porting is a separate project with its own validation.
- Choosing for a course or tutorial? A library your students can install on current Python and PyTorch avoids most support requests.
If you migrate, do not translate by name. Copy weights, compare outputs layer by layer, reverse fanout lists, and make node counts explicit.
For questions that involve more tools than these two, including graph analytics in NetworkX, see the tool selection matrix and the comparison hub.
Limitations
- No speed, memory or accuracy measurements. A library that is faster for one model and graph can be slower for another.
- DGL was run as 2.1.0 on CPU, not 2.4.0. Behaviour may differ between those versions.
- GPU installation was not tested for either library.
- Status facts age. Re-check the dates above before citing them.
Disclosure: this page is published on the website of TGraphX, a third graph library whose author runs the site. TGraphX is not part of this comparison; separate pages compare it with DGL and with PyG.
References
- Minjie Wang et al. Deep Graph Library: A Graph-Centric, Highly-Performant Package for Graph Neural Networks. 2019.
- Matthias Fey and Jan Eric Lenssen. Fast Graph Representation Learning with PyTorch Geometric. 2019.
- DGL user guide sources at tag v2.4.0: message passing, stochastic training, heterogeneous graphs, distributed training.
- DGL releases and DGL on PyPI.
- PyG documentation: Creating message passing networks.
- PyG release notes: 2.7.0 and 2.8.0.