ImportError: DLL load failed while importing onnxruntime_pybind11_state:

589 阅读2分钟

ImportError: DLL load failed while importing onnxruntime_pybind11_state: 动态链 接库(DLL)初始化例程失败。问题解决办法

在运行第三方库时的常见报错。ONNX Runtime(ORT)是由微软开发的开源推理引擎,支持跨平台、多硬件加速(CPU/GPU)。它能够高效运行 ONNX 格式的模型,广泛应用于模型部署、边缘计算等场景。

1.反复安装卸载无效

用户在使用 import onnxruntime 时遇到以下错误:
from .onnxruntime_pybind11_state import *  # noqa
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ImportError: DLL load failed while importing onnxruntime_pybind11_state: 动态链接库(DLL)初始化例程失败。
初步尝试:
  • 通过 pip uninstall onnxruntime 彻底卸载库。
  • 重新安装最新版本:pip install onnxruntime
  • 多次重复上述步骤,问题依旧。

2.安装 Visual C++ 2019 可再发行组件包

使用搜索引擎排查错误,得知可能是由DLL 初始化失败可能与系统运行时库缺失有关,尝试安装 Microsoft Visual C++ 2019 Redistributable

  1. 从微软官网下载并安装 VC++ 2019 可再发行组件包
  2. 重启系统再次尝试
  3. pip install onnxruntime python -c "import onnxruntime"

错误依然存在,表明问题并非由 VC++ 运行时库缺失直接导致。

3.查阅官方文档

onnxruntime库官方文档查阅后,怀疑是否与 CUDA 相关依赖缺失有关。尝试安装 GPU 版本

pip install onnxruntime-gpu

安装成功后尝试调用onnxruntime-gpu库,报错消失。

到这里原问题已经解决,但产生了一个新问题——与其他第三方库出现兼容性冲突。

是的,在调用其他三方库时又产生了新报错,例如:

AttributeError: module 'onnxruntime' has no attribute 'set_default_logger_severity'

安装 GPU 版本虽然修复了 DLL 问题,但与第三方库不兼容。

4.Python 虚拟环境与版本降级

问题当然不是出在CUDA上,于是怀疑onnxruntime库的报错问题与python环境版本相关,决定通过 Anaconda 的虚拟环境机制解决问题。这里尝试使用python == 3.9.19版本

  1. 安装 Anaconda(如未安装):
  2. 从 Anaconda 官网 下载并安装适合操作系统的版本。
  3. 创建独立环境: 打开 Anaconda Prompt 或终端,执行以下命令创建指定 Python 版本的环境conda create -n onnxruntime python=3.9.19
  4. 激活环境conda activate onnxruntime
  5. 安装 CPU 版 ONNX Runtimepip install onnxruntime
  6. 验证导入:这时我们再安装第三方库尝试运行,发现程序运行正常。

以上便是遇到ImportError: DLL load failed while importing onnxruntime_pybind11_state: 动态链 接库(DLL)初始化例程失败。问题报错的解决办法。

这是作者第一篇技术博客,如果能够帮助到你点个赞就好