基于PyTorch微调Mask R-CNN遇torch/torchvision模块错误求助
解决Mask R-CNN微调时torch与torchvision的模块属性/导入错误
问题场景
跟随PyTorch官方教程微调Mask R-CNN模型时,遇到两类版本兼容问题:
- 运行代码时报错:
---> 16 if torch._running_with_deploy(): AttributeError: module 'torch' has no attribute '_running_with_deploy' - 克隆torchvision仓库后仍出现导入错误:
ImportError: cannot import name '_meta_registrations' from 'torchvision' (C:\Users\anaconda33\lib\site-packages\torchvision\__init__.py)
解决方案
1. 严格匹配torch与torchvision版本
两类错误的核心原因均为torch和torchvision版本不兼容,_running_with_deploy和_meta_registrations是版本绑定的内部属性/模块:
- 先卸载现有冲突包:
pip uninstall torch torchvision -y - 根据本地CUDA版本选择完全匹配的版本安装(以CUDA 11.8为例):
pip install torch==2.0.1 torchvision==0.15.2 --index-url https://download.pytorch.org/whl/cu118 - 版本对应关系可参考PyTorch官方兼容表,确保大版本、CUDA版本完全对齐。
2. 修复克隆torchvision后的导入冲突
手动克隆仓库后需避免路径优先级问题:
- 不要直接在torchvision仓库根目录运行代码(Python会优先加载当前目录未安装的仓库版本,与本地torch版本不兼容)。
- 卸载旧torchvision后,在仓库目录执行本地安装:
cd torchvision pip install -e . - 安装前确认仓库README中的torch依赖要求,确保本地torch版本符合要求。
3. 检查Python模块搜索路径
若环境中存在多份torchvision,可能导致加载错误模块:
- 运行以下代码查看模块搜索优先级:
import sys print(sys.path) - 若非site-packages的路径(如当前工作目录)排在前面,移除该路径或切换到干净目录运行代码。
4. 用隔离环境彻底规避冲突(推荐)
通过conda创建独立环境,隔绝现有依赖:
conda create -n maskrcnn_env python=3.10 conda activate maskrcnn_env # 安装匹配版本的torch和torchvision pip install torch==2.0.1 torchvision==0.15.2 --index-url https://download.pytorch.org/whl/cu118
内容的提问来源于stack exchange,提问作者Lorent
相关产品推荐
相关产品推荐

