You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch导入报错求助:ImportError: Failed to load PyTorch C extensions

解决PyTorch导入时的ImportError: Failed to load PyTorch C extensions错误

错误信息

ImportError: Failed to load PyTorch C extensions:
It appears that PyTorch has loaded the torch/_C folder
of the PyTorch repository rather than the C extensions which
are expected in the torch._C namespace. This can occur when
using the install workflow. e.g.
$ python setup.py install && python -c "import torch"

This error can generally be solved using the `develop` workflow
     $ python setup.py develop && python -c "import torch" # This should succeed
 or by running Python from a different directory.

Not only with importing torch into your project but also with other libraries using it as a dependency.

环境:Python 3.10.10、Torch 2.0.0,已尝试重装PyTorch但问题未解决。


解决步骤

  • 检查并切换工作目录
    核心原因是Python在当前目录优先找到了PyTorch源码的torch/_C文件夹,而非安装好的C扩展模块。

    • 执行pwd(Linux/macOS)或cd(Windows)确认当前路径,若路径包含PyTorch源码仓库,立即切换到项目所在的独立目录,再尝试导入PyTorch。
  • 清理项目目录中的残留源码文件
    如果你的项目目录下存在torch文件夹(误拷贝的源码目录),直接删除:

    • Linux/macOS:rm -rf torch
    • Windows:rd /s/q torch
  • 重新安装官方编译的PyTorch包
    避免用源码setup.py install的方式,改用pip安装官方预编译包:

    1. 卸载现有PyTorch:
      pip uninstall -y torch torchvision torchaudio
      
    2. 根据你的CUDA版本选择对应命令安装Torch 2.0.0:
      • CUDA 11.7版本:
        pip install torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cu117
        
      • CPU版本:
        pip install torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cpu
        
    3. 验证安装:在非源码目录执行
      python -c "import torch; print(torch.__version__)"
      
  • 排查虚拟环境问题

    • 确认当前激活的虚拟环境正确,且未在该环境中执行过PyTorch源码的setup.py install操作。
    • 若之前用源码安装过,进入PyTorch源码目录执行python setup.py clean清理编译残留,再重新用pip安装。

内容的提问来源于stack exchange,提问作者CorAnna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:57:19