pyinstaller打包python进行onnx的gpu推理

对于没有python的电脑环境,直接使用打包好的exe程序进行GPU推理能省掉很多麻烦。
配置打包环境:

conda create -n onnx python=3.9
conda activate onnx

#用conda确保环境兼容。发现pip安装后打包出来的exe各种报错,避免踩坑
conda install pillow numpy fastapi uvicorn 

pip install onnxruntime-gpu
pip install pyinstaller

根据自己的需求写好推理及调用的相关逻辑(比如配合fastapi使用)并运行如下代码自动进行pyinstaller打包:

import os
import subprocess

def get_onnxruntime_dll_paths():
    """
    获取 onnxruntime 的 DLL 文件路径。
    """
    import onnxruntime as ort
    ort_path = os.path.dirname(ort.__file__)
    capi_path = os.path.join(ort_path, 'capi')
    return [
        os.path.join(capi_path, 'onnxruntime_providers_cuda.dll'),
        os.path.join(capi_path, 'onnxruntime_providers_shared.dll')
    ]

def generate_pyinstaller_command(script_name):
    """
    生成包含所有依赖项的 PyInstaller 命令。
    """
    onnxruntime_dll_paths = get_onnxruntime_dll_paths()
    dll_commands = [
        f'--add-binary "{dll};./onnxruntime/capi"' for dll in onnxruntime_dll_paths
    ]
    dll_commands_str = ' '.join(dll_commands)
    
    command = f'pyinstaller {dll_commands_str} --onefile {script_name}'
    return command


if __name__ == '__main__':
    command = generate_pyinstaller_command("main.py")
    subprocess.run(command, shell=True, check=True)

得到的命令运行即可自动打包脚本为单独的exe,将这个exe发到任意一台安装了cuda11.2 cudnn8.1的电脑都可以执行推理了(cuda版本非固定,与onnxruntime-gpu支持的版本兼容即可)

特别注意:如果目标电脑打开打包的exe出现闪退的情况,请将显卡驱动更新到新版本试试。测试目标电脑驱动版本460.89闪退,更新为537.13后正常运行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容