pytorch_geometric

pyg-teamMIT活跃维护

基于 PyTorch 的图神经网络库,提供图卷积等 GNN 模型的构建与训练组件,省去自己实现图数据结构和消息传递的麻烦。

Graph Neural Network Library for PyTorch

2.8.1发布于 2026-10-06 01:41 UTC24,139star +1 / 7 天4,094fork同步于 2026-11-10 11:23 UTC

怎么上手

由 README 提炼,执行前请确认
pip install torch_geometric
硬件要求按 README 说明

README 未说明显存要求;额外扩展库提供 CPU 与 GPU(CUDA/ROCm)内核,官方 wheel 覆盖 cpu、cu126、cu128、cu130、cu132 等组合,Linux、Windows、macOS 均有 CPU 版本。

需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

基于 PyTorch 的图神经网络库,让你用十几行代码就能训练 GNN 模型

基于 PyTorch 的图神经网络库,提供图卷积等 GNN 模型的构建与训练组件,省去自己实现图数据结构和消息传递的麻烦。

核心能力

  • 提供 GCNConv 等大量已实现的 SOTA GNN 层
  • 用 MessagePassing 接口自定义消息传递层
  • 内置 Planetoid 等常用基准数据集接口
  • 支持小图批量加载与单张巨型图上的训练
  • 支持多 GPU 训练与 torch.compile

容易踩的坑

从 PyG 2.3 起基础安装只需 PyTorch,但 pyg-lib、torch-scatter、torch-sparse 等加速库需按 PyTorch 与 CUDA 版本单独从 data.pyg.org 安装;这些扩展库的 wheel 需把 ${CUDA} 替换为与本地 PyTorch 匹配的 cpu/cu126 等标识,否则装不上;旧版 PyTorch 可能需要显式指定最新支持的版本号或用 --no-index 安装以避免源码编译。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本2.8.1
  1. 2.8.1PyG 2.8.1: Bug Fixes最新正式版2026-10-06 · 2026-10-06 01:41 UTC

    What's Changed

    Full Changelog: https://github.com/pyg-team/pytorch_geometric/compare/2.8.0...2.8.1

  2. 2.8.0PyG 2.8.02026-06-05 · 2026-06-05 21:20 UTC
    查看更新说明

    We are excited to announce the release of PyG 2.8 🎉🎉🎉

    PyG 2.8 includes 82 commits since torch-geometric==2.7.0, with feature and bug-fix work from 16 contributors.

    Highlights

    Support for PyTorch 2.9-2.12

    PyG 2.8 supports PyTorch 2.9, 2.10, 2.11, and 2.12, along with Python 3.10-3.14. Prebuilt wheels are available for CUDA 12.6, 12.8, 13.0, and 13.2, depending on the PyTorch version (see the table below).

    PyTorchSupported wheels
    2.12.*cpu, cu126, cu130, cu132
    2.11.*cpu, cu126, cu128, cu130
    2.10.*cpu, cu126, cu128, cu130
    2.9.*cpu, cu126, cu128, cu130

    For a typical installation, PyG remains installable directly from PyPI:

    pip install torch-geometric
    
    # Optional accelerated dependencies, matching your PyTorch install:
    pip install pyg-lib torch-scatter torch-sparse -f https://data.pyg.org/whl/torch-${TORCH}+${CUDA}.html
    

    For example, use TORCH=2.12.0 and CUDA=cu132 for PyTorch 2.12.* with CUDA 13.2.

    Consolidated Acceleration on pyg-lib

    PyG 2.8 trims its optional accelerated dependencies: torch-cluster and torch-spline-conv are now deprecated and ignored, with their functionality provided by pyg-lib==0.7.0. The installation and cuGraph documentation now point users toward the NVIDIA PyG container, the rapidsai/cugraph-gnn examples, and RAPIDS guidance for scalable GPU workflows (#10489, #10603, #10639, #10640).

    Synthetic QA Generation for Graph RAG

    The new examples/llm/txt2qa.py workflow introduces a synthetic multi-hop question-answer generation pipeline for text documents (#10559). It supports local vLLM and NVIDIA NIM API backends and is designed for creating training and evaluation data for retrieval-augmented generation systems.

    Breaking Changes

    • Dropped support for PyTorch 2.8. Use PyG 2.8 with PyTorch 2.9 through 2.12, or pin torch-geometric==2.7.* if you need to stay on PyTorch 2.8. Older PyTorch 2.8 wheel links remain available for existing installs (#10708).
    • Removed dependencies on torch-cluster and torch-spline-conv in favor of pyg-lib==0.7.0. These packages are now deprecated and ignored if installed; the operators they previously provided now require pyg-lib==0.7.0 (#10682, #10622).

    Features

    Examples
    • Added examples/llm/txt2qa.py for synthetic multi-hop QA generation from text documents with vLLM and NVIDIA NIM backends (#10559).
    • Added examples/llm/relbench_gretriever.py, showing how to convert a RelBench database into a PyG graph and run GRetriever on it (#10681).
    • Added examples/relbench_example.py for the new RelBench conversion utility (#10628).
    • Added examples/graphland.py for the GraphLand benchmark (#10458).
    • Improved the txt2kg model and its example indexing flow (#10623, [#10546](https://
  3. 2.7.0PyG 2.7.02025-10-14 · 2025-10-14 22:05 UTC
    查看更新说明

    We are excited to announce the release of PyG 2.7 🎉🎉🎉

    PyG 2.7 is the culmination of work from 53 contributors who have worked on features and bug-fixes for a total of over 282 commits since torch-geometric==2.6.0.

    Highlights

    PyTorch 2.8 Support

    PyG 2.7 is fully compatible with PyTorch 2.8 and supports the following combinations:

    PyTorch 2.8cpucu126cu128cu129
    Linux✅✅✅✅
    Windows✅✅✅✅
    macOS✅

    In addition, PyG 2.7 supports two previous PyTorch minor releases, PyTorch 2.7 and 2.6:

    PyTorch 2.7cpucu118cu126cu128
    Linux✅✅✅✅
    Windows✅✅✅✅
    macOS✅
    PyTorch 2.6cpucu118cu124cu126
    Linux✅✅✅✅
    Windows✅✅✅✅
    macOS✅

    Breaking Changes

    Deprecation

    • Deprecated torch_geometric.distributed (#10411)

    Bugfixes

    • Fixed ogbn_train_cugraph example for distributed cuGraph (#10439)
    • Added safe_onnx_export function with workarounds for onnx_ir.serde.SerdeError issues in ONNX export (#10422)
    • Fixed importing PyTorch Lightning in torch_geometric.graphgym and torch_geometric.data.lightning when using lightning instead of pytorch-lightning (#10404, #10417))
    • Fixed detach() warnings in example scripts involving tensor conversions (#10357)
    • Fixed non-tuple indexing to resolve PyTorch deprecation warning (#10389)
    • Fixed conversion to/from cuGraph graph objects by ensuring cudf column names are correctly specified (#10343)
    • Fixed _recursive_config() for torch.nn.ModuleList and torch.nn.ModuleDict (#10124, #10129)
    • Fixed the k_hop_subgraph() method for directed graphs (#9756)
    • Fixed utils.group_cat concatenating dimension (#9766)
    • Fixed WebQSDataset.process raising exceptions (#9665)
    • Fixed is_node_attr() and is_edge_attr() errors when cat_dim is a tuple (#9895)
    • Avoid GRetriever instantiation when num_gnn_layers == 0 (#10156)

    Features

    • Added llm generated explanations to TAGDataset ([#9918](https://github
  4. 2.6.1 PyG 2.6.1: Bugfixes2024-09-26 · 2024-09-26 07:09 UTC
    查看更新说明

    PyG 2.6.1 includes a bugfix in the WebQSDataset.

    Bug Fixes

    • Fixed a bug in the WebQSDataset dataset where empty edges were not treated gracefully (#9665)

    Full Changelog: https://github.com/pyg-team/pytorch_geometric/compare/2.6.0...2.6.1

  5. 2.6.0PyG 2.6.02024-09-13 · 2024-09-13 06:49 UTC
    查看更新说明

    We are excited to announce the release of PyG 2.6 🎉🎉🎉

    PyG 2.6 is the culmination of work from 59 contributors who have worked on features and bug-fixes for a total of over 238 commits since torch-geometric==2.5.0.

    Highlights

    PyTorch 2.4 Support

    PyG 2.6 is fully compatible with PyTorch 2.4, and supports the following combinations:

    PyTorch 2.2cpucu118cu121cu124
    Linux✅✅✅✅
    macOS✅
    Windows✅✅✅✅

    You can still install PyG 2.6 with an older PyTorch release up to PyTorch 1.13 in case you are not eager to update your PyTorch version.

    GNNs+LLMs

    In order to facilitate further research on combining GNNs with LLMs, PyG 2.6 introduces

    Index Tensor Representation

    Similar to the EdgeIndex class introduced in PyG 2.5, torch-geometric==2.6.0 introduces the Index class for efficient storage of 1D indices. While Index sub-classes a general torch.Tensor, it can hold additional (meta)data, i.e.:

    • dim_size: The size of the underlying sparse vector, i.e. the size of a dimension that can be indexed via Index. By default, it is inferred as dim_size=index.max() + 1
    • is_sorted: Whether indices are sorted in ascending order.

    Additionally, Index caches data via indptr for fast CSR conversion in case its representation is sorted. Caches are filled based on demand (e.g., when calling Index.get_indptr() or when explicitly requested via Index.fill_cache_(), and are maintained and adjusted over its lifespan.

     from torch_geometric import Index
    
    index = Index([0, 1, 1, 2], dim_size=3, is_sorted=True)
    assert index.dim_size == 3
    assert index.is_sorted
    
    # Flipping order:
    index.flip(0)
    assert not index.is_sorted
    
    # Filtering:
    mask = torch.tensor([True, True, True, False])
    index[:, mask]
    assert index.is_sorted
    

    [EdgeIndex](https://pytor

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    [![PyPI Version][pypi-image]][pypi-url] [![PyPI Download][pypi-download-image]][pypi-download-url] [![Slack][slack-image]][slack-url] [Contributing][contributing-url]

    Documentation | PyG 1.0 Paper | PyG 2.0 Paper | Colab Notebooks | External Resources | OGB Examples

    PyG (PyTorch Geometric) is a library built upon PyTorch to easily write and train Graph Neural Networks (GNNs) for a wide range of applications related to structured data.

    It consists of various methods for deep learning on graphs and other irregular structures, also known as geometric deep learning, from a variety of published papers. In addition, it consists of easy-to-use mini-batch loaders for operating on many small and single giant graphs, multi GPU-support, torch.compile support, DataPipe support, a large number of common benchmark datasets (based on simple interfaces to create your own), and helpful transforms, both for learning on arbitrary graphs as well as on 3D meshes or point clouds.

    [Click here to join our Slack community!][slack-url]


    Library Highlights

    Whether you are a machine learning researcher or first-time user of machine learning toolkits, here are some reasons to try out PyG for machine learning on graph-structured data.

    • Easy-to-use and unified API: All it takes is 10-20 lines of code to get started with training a GNN model (see the next section for a quick tour). PyG is PyTorch-on-the-rocks: It utilizes a tensor-centric API and keeps design principles close to vanilla PyTorch. If you are already familiar with PyTorch, utilizing PyG is straightforward.
    • Comprehensive and well-maintained GNN models: Most of the state-of-the-art Graph Neural Network architectures have been implemented by library developers or authors of research papers and are ready to be applied.
    • Great flexibility: Existing PyG models can easily be extended for conducting your own research with GNNs. Making modifications to existing models or creating new architectures is simple, thanks to its easy-to-use message passing API, and a variety of operators and utility functions.
    • Large-scale real-world GNN models: We focus on the need of GNN applications in challenging real-world scenarios, and support learning on diverse types of graphs, including but not limited to: scalable GNNs for graphs with millions of nodes; dynamic GNNs for node predictions over time; heterogeneous GNNs with multiple node types and edge types.

    Quick Tour for New Users

    In this quick tour, we highlight the ease of creating and training a GNN model with only a few lines of code.

    Train your own GNN model

    In the first glimpse of PyG, we implement the training of a GNN for classifying papers in a citation graph. For this, we load the Cora dataset, and create a simple 2-layer GCN model using the pre-defined GCNConv:

    import torch
    from torch import Tensor
    from torch_geometric.nn import GCNConv
    from torch_geometric.datasets import Planetoid
    
    dataset = Planetoid(root='.', name='Cora')
    
    class GCN(torch.nn.Module):
        def __init__(self, in_channels, hidden_channels, out_channels):
            super().__init__()
            self.conv1 = GCNConv(in_channels, hidden_channels)
            self.conv2 = GCNConv(hidden_channels, out_channels)
    
        def forward(self, x: Tensor, edge_index: Tensor) -> Tensor:
            # x: Node feature matrix of shape [num_nodes, in_channels]
            # edge_index: Graph connectivity matrix of shape [2, num_edges]
            x = self.conv1(x, edge_index).relu()
            x = self.conv2(x, edge_index)
            return x
    
    model = GCN(dataset.num_features, 16, dataset.num_classes)
    
    import torch.nn.functional as F
    
    data = dataset[0]
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    
    for epoch in range(200):
        pred = model(data.x, data.edge_index)
        loss = F.cross_entropy(pred[data.train_mask], data.y[data.train_mask])
    
        # Backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    

    More information about evaluating final model performance can be found in the corresponding example.

    Create your own GNN layer

    In addition to the easy application of existing GNNs, PyG makes it simple to implement custom Graph Neural Networks (see here for the accompanying tutorial). For example, this is all it takes to implement the edge convolutional layer from Wang et al.:

    $$x_i^{\prime} ~ = ~ \max_{j \in \mathcal{N}(i)} ~ \textrm{MLP}_{\theta} \left( [ ~ x_i, ~ x_j - x_i ~ ] \right)$$

    import torch
    from torch import Tensor
    from torch.nn import Sequential, Linear, ReLU
    from torch_geometric.nn import MessagePassing
    
    class EdgeConv(MessagePassing):
        def __init__(self, in_channels, out_channels):
            super().__init__(aggr="max")  # "Max" aggregation.
            self.mlp = Sequential(
                Linear(2 * in_channels, out_channels),
                ReLU(),
                Linear(out_channels, out_channels),
            )
    
        def forward(self, x: Tensor, edge_index: Tensor) -> Tensor:
            # x: Node feature matrix of shape [num_nodes, in_channels]
            # edge_index: Graph connectivity matrix of shape [2, num_edges]
            return self.propagate(edge_index, x=x)  # shape [num_nodes, out_channels]
    
        def message(self, x_j: Tensor, x_i: Tensor) -> Tensor:
            # x_j: Source node features of shape [num_edges, in_channels]
            # x_i: Target node features of shape [num_edges, in_channels]
            edge_features = torch.cat([x_i, x_j - x_i], dim=-1)
            return self.mlp(edge_features)  # shape [num_edges, out_channels]
    

    Architecture Overview

    PyG provides a multi-layer framework that enables users to build Graph Neural Network solutions on both low and high levels. It comprises of the following components:

    • The PyG engine utilizes the powerful PyTorch deep learning framework with full torch.compile and TorchScript support, as well as additions of efficient CPU/CUDA libraries for operating on sparse data, e.g., pyg-lib.
    • The PyG storage handles data processing, transformation and loading pipelines. It is capable of handling and processing large-scale graph datasets, and provides effective solutions for heterogeneous graphs. It further provides a variety of sampling solutions, which enable training of GNNs on large-scale graphs.
    • The PyG operators bundle essential functionalities for implementing Graph Neural Networks. PyG supports important GNN building blocks that can be combined and applied to various parts of a GNN model, ensuring rich flexibility of GNN design.
    • Finally, PyG provides an abundant set of GNN models, and examples that showcase GNN models on standard graph benchmarks. Thanks to its flexibility, users can easily build and modify custom GNN models to fit their specific needs.

    Implemented GNN Models

    We list currently supported PyG models, layers and operators according to category:

    GNN layers: All Graph Neural Network layers are implemented via the nn.MessagePassing interface. A GNN layer specifies how to perform message passing, i.e. by designing different message, aggregation and update functions as defined here. These GNN layers can be stacked together to create Graph Neural Network models.

    Pooling layers: Graph pooling layers combine the vectorial representations of a set of nodes in a graph (or a subgraph) into a single vector representation that summarizes its properties of nodes. It is commonly applied to graph-level tasks, which require combining node features into a single graph representation.

    GNN models: Our supported GNN models incorporate multiple message passing layers, and users can directly use these pre-defined models to make predictions on graphs. Unlike simple stacking of GNN layers, these models could involve pre-processing, additional learnable parameters, skip connections, graph coarsening, etc.

    GNN operators and utilities: PyG comes with a rich set of neural network operators that are commonly used in many GNN models. They follow an extensible design: It is easy to apply these operators and graph utilities to existing GNN layers and models to further enhance model performance.

    Scalable GNNs: PyG supports the implementation of Graph Neural Networks that can scale to large-scale graphs. Such application is challenging since the entire graph, its associated features and the GNN parameters cannot fit into GPU memory. Many state-of-the-art scalability approaches tackle this challenge by sampling neighborhoods for mini-batch training, graph clustering and partitioning, or by using simplified GNN models. These approaches have been implemented in PyG, and can benefit from the above GNN layers, operators and models.

    Installation

    PyG is available for Python 3.10 to Python 3.14.

    From PyG 2.3 onwards, you can install and use PyG without any external library required except for PyTorch. For this, simply run

    pip install torch_geometric
    

    Additional Libraries

    If you want to utilize the full set of features from PyG, there exists several additional libraries you may want to install:

    These packages come with their own CPU and GPU kernel implementations based on the PyTorch C++/CUDA/hip(ROCm) extension interface. For a basic usage of PyG, these dependencies are fully optional. We recommend to start with a minimal installation, and install additional dependencies once you start to actually need them.

    For ease of installation of these extensions, we provide pip wheels for all major OS/PyTorch/CUDA combinations, see here.

    PyTorch 2.12

    To install the binaries for PyTorch 2.12, simply run

    pip install pyg_lib torch_scatter torch_sparse -f https://data.pyg.org/whl/torch-2.12.0+${CUDA}.html
    

    where ${CUDA} should be replaced by either cpu, cu126, cu130, or cu132 depending on your PyTorch installation.

    cpucu126cu128cu130cu132
    Linux✅✅✅✅
    Windows✅✅✅✅
    macOS✅
    PyTorch 2.11

    To install the binaries for PyTorch 2.11, simply run

    pip install pyg_lib torch_scatter torch_sparse -f https://data.pyg.org/whl/torch-2.11.0+${CUDA}.html
    

    where ${CUDA} should be replaced by either cpu, cu126, cu128, or cu130 depending on your PyTorch installation.

    cpucu126cu128cu130
    Linux✅✅✅✅
    Windows✅✅✅✅
    macOS✅
    PyTorch 2.10

    To install the binaries for PyTorch 2.10, simply run

    pip install pyg_lib torch_scatter torch_sparse -f https://data.pyg.org/whl/torch-2.10.0+${CUDA}.html
    

    where ${CUDA} should be replaced by either cpu, cu126, cu128, or cu130 depending on your PyTorch installation.

    cpucu126cu128cu130
    Linux✅✅✅✅
    Windows✅✅✅✅
    macOS✅
    PyTorch 2.9

    To install the binaries for PyTorch 2.9, simply run

    pip install pyg_lib torch_scatter torch_sparse -f https://data.pyg.org/whl/torch-2.9.0+${CUDA}.html
    

    where ${CUDA} should be replaced by either cpu, cu126, cu128, or cu130 depending on your PyTorch installation.

    cpucu126cu128cu130
    Linux✅✅✅✅
    Windows✅✅✅✅
    macOS✅

    Note: Binaries of older versions are also provided for PyTorch 1.4.0, PyTorch 1.5.0, PyTorch 1.6.0, PyTorch 1.7.0/1.7.1, PyTorch 1.8.0/1.8.1, PyTorch 1.9.0, PyTorch 1.10.0/1.10.1/1.10.2, PyTorch 1.11.0, PyTorch 1.12.0/1.12.1, PyTorch 1.13.0/1.13.1, PyTorch 2.0.0/2.0.1, PyTorch 2.1.0/2.1.1/2.1.2, PyTorch 2.2.0/2.2.1/2.2.2, PyTorch 2.3.0/2.3.1, PyTorch 2.4.0/2.4.1, PyTorch 2.5.0/2.5.1, PyTorch 2.6.0, PyTorch 2.7.0/2.7.1, and PyTorch 2.8.0 (following the same procedure). For older versions, you might need to explicitly specify the latest supported version number or install via pip install --no-index in order to prevent a manual installation from source. You can look up the latest supported version number here.

    NVIDIA PyG Container

    NVIDIA provides a PyG docker container for effortlessly training and deploying GPU accelerated GNNs with PyG, see here.

    Nightly and Master

    In case you want to experiment with the latest PyG features which are not fully released yet, either install the nightly version of PyG via

    pip install pyg-nightly
    

    or install PyG from master via

    pip install git+https://github.com/pyg-team/pytorch_geometric.git
    

    ROCm Wheels

    The external pyg-rocm-build repository provides wheels and detailed instructions on how to install PyG for ROCm. If you have any questions about it, please open an issue here.

    Cite

    Please cite our PyG 1.0 and PyG 2.0 papers if you use this code in your own work:

    @inproceedings{Fey/Lenssen/2019,
      title={Fast Graph Representation Learning with {PyTorch Geometric}},
      author={Fey, Matthias and Lenssen, Jan E.},
      booktitle={ICLR Workshop on Representation Learning on Graphs and Manifolds},
      year={2019},
    }
    
    @inproceedings{Fey/etal/2025,
      title={{PyG} 2.0: Scalable Learning on Real World Graphs},
      author={Fey, Matthias and Sunil, Jinu and Nitta, Akihiro and Puri, Rishi and Shah, Manan, and Stojanovi{\v{c}, Bla{\v{z} and Bendias, Ramona and Alexandria, Barghi and Kocijan, Vid and Zhang, Zecheng and He, Xinwei and Lenssen, Jan E. and Leskovec, Jure},
      booktitle={Temporal Graph Learning Workshop @ KDD},
      year={2025},
    }
    

    Feel free to email us if you wish your work to be listed in the external resources. If you notice anything unexpected, please open an issue and let us know. If you have any questions or are missing a specific feature, feel free to discuss them with us. We are motivated to constantly make PyG even better.