疑难问题(一)——PyTorch 2.3.0 ‘import torch‘ 错误 Error loading“xxx\site-packages\torch\lib\shm.dll“

问题

前置条件

虚拟环境管理:Anaconda
虚拟环境创建命令:conda create -n py311 python=3.11.9
Python版本:3.11.9
PyPorch版本:2.3.0 + cuda 12.1
安装命令:pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121(官网复制

触发条件

进入虚拟环境’py311 '之后输入命令

python

进入python环境之后,输入

import torch

现象描述

导入torch失败,提示OSError:无法加载’shm.dll’或其依赖项。
报错图如下:

Python 3.12.3 (tags/v3.12.3:f6650f9, Apr  9 2024, 14:05:25) [MSC v.1938 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Administrator\AppData\Roaming\Python\Python312\site-packages\torch\__init__.py", line 141, in <module>
    raise err
OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\Administrator\AppData\Roaming\Python\Python312\site-packages\torch\lib\shm.dll" or one of its dependencies.
>>> exit()

解决办法

以"C:\Users\Administrator\AppData\Roaming\Python\Python312\site-packages\torch_init_.py"路径为例。
1.按照错误提示的路径找到"init.py"文件。
2.用VS Code打开用VS Code打开用VS Code打开!(我自己用PyCharm改了几次都没成功)。
3.按照官方示例(Github链接)修改"init.py"文件。
上不去的话,给你们截个图
官方解决
总结一下就是加3行,删一行
69行增加

import sysconfig

73行增加

usebase_path = os.path.join(sysconfig.get_config_var("userbase"), 'Library', 'bin')

原82行代码删除

dll_paths = list(filter(os.path.exists, [th_dll_path, py_dll_path, base_py_dll_path]))

替换为

dll_paths = list(filter(os.path.exists, [th_dll_path, py_dll_path, base_py_dll_path, usebase_path]))

解决原理

直接放原文

Fixes #125109 which is a regression introduced by pytorch/builder#1467 that adds dynamic dependency to mkl, which if installed in the user-dir is placed into sysconfig.sysconfig.get_config_var("userbase") / "Library" / "bin"
Fix this one, but adding userbase folder to the DLL search path

其他

这个问题我按照官方流程已经解决。
在此过程中了解到的信息:
1.有人将PyPorch版本降为2.2就不会有这个问题了,本人未测试;
2.有人说添加环境变量可以解决,本人使用无效;

  • 23
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值