在进行生物分子交互计算、图神经网络相关开发时,torch_geometric是常用的 PyTorch 扩展库,但安装过程中常遇到缺失依赖、编译失败等问题。本文结合实际操作场景,详细记录从环境排查到成功运行的完整解决方案,适用于 PyTorch 2.6.0 + CUDA 12.4 环境,新手也能轻松跟进。
一、核心问题:ModuleNotFoundError: No module named 'torch_geometric'
问题现象
在pytorch环境下运行脚本时,终端抛出如下错误:
(pdb) root@a7fb25e384d4:~# python test.py
Traceback (most recent call last):
File "/root/test.py", line 4, in <module>
from torch_geometric.data import Data, Batch
ModuleNotFoundError: No module named 'torch_geometric'
问题原因
环境中未安装torch_geometric库,且该库依赖torch_scatter、torch_sparse、torch_cluster、torch_spline_conv等扩展组件,无法直接通过简单pip install完成安装。
二、尝试 Conda 安装失败:PackagesNotFoundError
问题现象
直接使用 Conda 安装时,出现通道搜索失败提示:
(pdb) root@a7fb25e384d4:~# conda install torch_geometric
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
PackagesNotFoundError: The following packages are not available from current channels:
torch_geometric
问题原因
Conda 默认通道(repo.anaconda.com)中无torch_geometric包,需通过 PyPI 结合官方 whl 源安装,且需提前解决编译依赖。
三、分步解决方案:从编译环境到完整安装
1. 解决编译依赖:安装 g++ 编译器
核心问题
torch_scatter等扩展库安装需编译 C++ 源码,系统缺失g++编译器会导致编译失败,报错提示 “error: command 'g++' failed: No such file or directory”。
解决方案(Conda 环境推荐)
在终端执行以下命令安装编译器,自动解决依赖关联:
conda install -y gxx_linux-64
安装过程说明
执行后会自动下载并安装binutils、gcc、gxx等相关组件,部分包可能出现版本降级(如ld_impl_linux-64从 2.44 降至 2.40),属于正常兼容调整,无需担心:
The following NEW packages will be INSTALLED:
_sysroot_linux-64~ pkgs/main/noarch::_sysroot_linux-64_curr_repodata_hack-3-haa98f57_16
binutils_impl_linux-64 pkgs/main/linux-64::binutils_impl_linux-64-2.40-h5293946_0
...
The following packages will be DOWNGRADED:
ld_impl_linux-64 2.44-h153f514_2 --> 2.40-h12ee557_0
2. 安装 torch_geometric 依赖组件(适配 PyTorch 2.6.0 + CUDA 12.4)
关键说明
需通过torch_geometric官方 whl 源指定适配版本,同时结合国内 PyPI 镜像加速下载(避免国外源超时)。
分步安装命令
依次执行以下 5 条命令,确保每个组件安装成功:
# 安装torch-scatter
pip install torch-scatter -f https://data.pyg.org/whl/torch-2.6.0+cu124.html -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
# 安装torch-sparse
pip install torch-sparse -f https://data.pyg.org/whl/torch-2.6.0+cu124.html -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
# 安装torch-cluster
pip install torch-cluster -f https://data.pyg.org/whl/torch-2.6.0+cu124.html -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
# 安装torch-spline-conv
pip install torch-spline-conv -f https://data.pyg.org/whl/torch-2.6.0+cu124.html -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
# 安装torch-geometric
pip install torch-geometric -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
安装成功验证
以torch-sparse为例,成功安装会显示如下信息:
Successfully built torch-sparse
Installing collected packages: scipy, torch-sparse
Successfully installed scipy-1.16.3 torch-sparse-0.6.18

6143

被折叠的 条评论
为什么被折叠?



