当前位置:   article > 正文

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

import torch raise err

问题

前置条件

虚拟环境管理: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
  • 1

进入python环境之后,输入

import torch
  • 1

现象描述

导入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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

解决办法

以"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
  • 1
'
运行

73行增加

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

原82行代码删除

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

替换为

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

解决原理

直接放原文

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.有人说添加环境变量可以解决,本人使用无效;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/1010744
推荐阅读
相关标签
  

闽ICP备14008679号