# onnxruntime-cann-guide **Repository Path**: chenliang267/onnxruntime-cann-guide ## Basic Information - **Project Name**: onnxruntime-cann-guide - **Description**: 介绍onnxruntime-cann的安装和使用方式。 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 4 - **Forks**: 1 - **Created**: 2023-01-17 - **Last Updated**: 2025-10-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 构建、安装 - 2023-1-17: 目前官方的主线无法编译支持cann的版本,所以要从维护者的分支构建,请跟踪这个PR:https://github.com/microsoft/onnxruntime/pull/14058 - 2023-2-11: 更新了分支 - 2023-2-17: 更新了分支,内存释放问题已解决 - 2023-2-20: 更新了分支,优化了调度,性能有提升 - 2023-2-21: 更新了分支,添加了一些atc参数支持 ## 环境要求: - CMake >= 3.24 - GCC (G++) >= 7.5.0 获取源码 ```bash git clone -b multi_stream https://github.com/learningbackup/onnxruntime.git cd onnxruntime ``` 然后构建whl包 ```bash # 初始化CANN环境 source /usr/local/Ascend/ascend-toolkit/set_env.sh # 执行build脚本 ./build.sh --config RelWithDebInfo --build_shared_lib --parallel --use_cann --build_wheel ``` 可能遇到的问题: - 构建可能会因为网络问题而出错,多重试几次。 - 如果在```git submodule update```的步骤无法成功下载第三方子模组,可以参照```.gitmodules```文件手动下载并放到对应目录,然后在执行build脚本时再添加一个参数```--skip_submodule_sync```,以跳过该步骤。 - 如果构建时遇到SSL认证错误,修改文件```tools/ci_build/build.py```的981行(或搜索CMAKE_TLS_VERIFY),如下将ON改为OFF,关闭SSL认证(如果设置不生效,请更新CMake)。 ```cmake add_default_definition(cmake_extra_defines, "CMAKE_TLS_VERIFY", "OFF") ``` - 如果提示numpy相关的错误,请先通过pip安装numpy,再进行构建。 ```bash pip3 install numpy ``` 构建成功后,whl包会生成在```build/Linux/RelWithDebInfo/dist/```路径下。 如果已经安装了非CANN版本的onnxruntime,需要先卸载它。 安装onnxruntime-cann ```bash pip3 install build/Linux/RelWithDebInfo/dist/onnxruntime_cann-x.xx.x-xxxx-xxxxx-xxxxx_xxx_xx.whl ``` # 推理示例 ```python import numpy as np import onnxruntime as ort # 模型路径 model_path = 'resnet.onnx' options = ort.SessionOptions() #以CANN作为EP的配置,参数说明可见:https://github.com/microsoft/onnxruntime/blob/gh-pages/docs/execution-providers/community-maintained/CANN-ExecutionProvider.md providers = [ ( "CANNExecutionProvider", { "device_id": 0, "arena_extend_strategy": "kNextPowerOfTwo", "npu_mem_limit": 4 * 1024 * 1024 * 1024, "enable_cann_graph": True }, ), "CPUExecutionProvider", ] session = ort.InferenceSession(model_path, sess_options=options, providers=providers) # 构造纯推理数据 ndata = np.zeros([1, 3, 224, 224], dtype=np.float32) # 执行推理 output = session.run([], {"image": ndata}) ```