• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Neural Network Runtime对接AI推理框架开发指导
2
3<!--Kit: Neural Network Runtime Kit-->
4<!--Subsystem: AI-->
5<!--Owner: @GbuzhidaoR-->
6<!--Designer: @GbuzhidaoR-->
7<!--Tester: @GbuzhidaoR-->
8<!--Adviser: @ge-yafang-->
9
10## 场景介绍
11
12Neural Network Runtime作为AI推理引擎和加速芯片的桥梁,为AI推理引擎提供精简的Native接口,满足推理引擎通过加速芯片执行端到端推理的需求。
13
14本文以图1展示的`Add`单算子模型为例,介绍Neural Network Runtime的开发流程。`Add`算子包含两个输入、一个参数和一个输出,其中的`activation`参数用于指定`Add`算子中激活函数的类型。
15
16**图1** Add单算子网络示意图
17!["Add单算子网络示意图"](figures/02.png)
18
19## 环境准备
20
21### 环境要求
22
23Neural Network Runtime部件的环境要求如下:
24
25- 开发环境:Ubuntu 18.04及以上。
26- 接入设备:系统定义的标准设备,系统中内置AI硬件驱动并已接入Neural Network Runtime。
27
28由于Neural Network Runtime通过Native API对外开放,需要下载对应的SDK并通过Native开发套件编译Neural Network Runtime应用。可以使用DevEco Studio来搭建环境和编译代码。
29
30### 环境搭建
31
321. 使用Ubuntu编译服务器的终端。
332. 指定native工具链路径来编译代码,可以使用DevEco Studio来下载对应的SDK来进行编译。
343. DevEco Studio安装目录下的SDK路径可以在DevEco Studio工程界面,点击File > Settings... > 在settings中搜索SDK,下载对应的SDK即可。
35
36## 接口说明
37
38以下为Neural Network Runtime开发流程中的常用接口,具体可见[NeuralNetworkRuntime](../../reference/apis-neural-network-runtime-kit/capi-neuralnetworkruntime.md)。
39
40### 结构体
41
42| 结构体名称 | 描述 |
43| --------- | ---- |
44| typedef struct OH_NNModel OH_NNModel | Neural Network Runtime的模型句柄,用于构造模型。 |
45| typedef struct OH_NNCompilation OH_NNCompilation | Neural Network Runtime的编译器句柄,用于编译AI模型。 |
46| typedef struct OH_NNExecutor OH_NNExecutor | Neural Network Runtime的执行器句柄,用于在指定设备上执行推理计算。 |
47| typedef struct NN_QuantParam NN_QuantParam | Neural Network Runtime的量化参数句柄,用于在构造模型时指定张量的量化参数。 |
48| typedef struct NN_TensorDesc NN_TensorDesc | Neural Network Runtime的张量描述句柄,用于描述张量的各类属性,例如数据布局、数据类型、形状等。 |
49| typedef struct NN_Tensor NN_Tensor | Neural Network Runtime的张量句柄,用于设置执行器的推理输入和输出张量。 |
50
51### 模型构造接口
52
53| 接口名称 | 描述 |
54| ------- | --- |
55| OH_NNModel_Construct() | 创建OH_NNModel类型的模型实例。 |
56| OH_NN_ReturnCode OH_NNModel_AddTensorToModel(OH_NNModel *model, const NN_TensorDesc *tensorDesc) | 向模型实例中添加张量。 |
57| OH_NN_ReturnCode OH_NNModel_SetTensorData(OH_NNModel *model, uint32_t index, const void *dataBuffer, size_t length) | 设置张量的数值。 |
58| OH_NN_ReturnCode OH_NNModel_AddOperation(OH_NNModel *model, OH_NN_OperationType op, const OH_NN_UInt32Array *paramIndices, const OH_NN_UInt32Array *inputIndices, const OH_NN_UInt32Array *outputIndices) | 向模型实例中添加算子。 |
59| OH_NN_ReturnCode OH_NNModel_SpecifyInputsAndOutputs(OH_NNModel *model, const OH_NN_UInt32Array *inputIndices, const OH_NN_UInt32Array *outputIndices) | 指定模型的输入和输出张量的索引值。 |
60| OH_NN_ReturnCode OH_NNModel_Finish(OH_NNModel *model) | 完成模型构图。|
61| void OH_NNModel_Destroy(OH_NNModel **model) | 销毁模型实例。 |
62
63
64### 模型编译接口
65
66| 接口名称 | 描述 |
67| ------- | --- |
68| OH_NNCompilation *OH_NNCompilation_Construct(const OH_NNModel *model) | 基于模型实例创建OH_NNCompilation类型的编译实例。 |
69| OH_NNCompilation *OH_NNCompilation_ConstructWithOfflineModelFile(const char *modelPath) | 基于离线模型文件路径创建OH_NNCompilation类型的编译实例。 |
70| OH_NNCompilation *OH_NNCompilation_ConstructWithOfflineModelBuffer(const void *modelBuffer, size_t modelSize) | 基于离线模型文件内存创建OH_NNCompilation类型的编译实例。 |
71| OH_NNCompilation *OH_NNCompilation_ConstructForCache() | 创建一个空的编译实例,以便稍后从模型缓存中恢复。 |
72| OH_NN_ReturnCode OH_NNCompilation_ExportCacheToBuffer(OH_NNCompilation *compilation, const void *buffer, size_t length, size_t *modelSize) | 将模型缓存写入到指定内存区域。 |
73| OH_NN_ReturnCode OH_NNCompilation_ImportCacheFromBuffer(OH_NNCompilation *compilation, const void *buffer, size_t modelSize) | 从指定内存区域读取模型缓存。 |
74| OH_NN_ReturnCode OH_NNCompilation_AddExtensionConfig(OH_NNCompilation *compilation, const char *configName, const void *configValue, const size_t configValueSize) | 为自定义硬件属性添加扩展配置,具体硬件的扩展属性名称和属性值需要从硬件厂商的文档中获取。 |
75| OH_NN_ReturnCode OH_NNCompilation_SetDevice(OH_NNCompilation *compilation, size_t deviceID) | 指定模型编译和计算的硬件,可通过设备管理接口获取。 |
76| OH_NN_ReturnCode OH_NNCompilation_SetCache(OH_NNCompilation *compilation, const char *cachePath, uint32_t version) | 设置编译模型的缓存目录和版本。 |
77| OH_NN_ReturnCode OH_NNCompilation_SetPerformanceMode(OH_NNCompilation *compilation, OH_NN_PerformanceMode performanceMode) | 设置模型计算的性能模式。 |
78| OH_NN_ReturnCode OH_NNCompilation_SetPriority(OH_NNCompilation *compilation, OH_NN_Priority priority) | 设置模型计算的优先级。 |
79| OH_NN_ReturnCode OH_NNCompilation_EnableFloat16(OH_NNCompilation *compilation, bool enableFloat16) | 是否以float16的浮点数精度计算。 |
80| OH_NN_ReturnCode OH_NNCompilation_Build(OH_NNCompilation *compilation) | 执行模型编译。 |
81| void OH_NNCompilation_Destroy(OH_NNCompilation **compilation) | 销毁编译实例。 |
82
83### 张量描述接口
84
85| 接口名称 | 描述 |
86| ------- | --- |
87| NN_TensorDesc *OH_NNTensorDesc_Create() | 创建一个张量描述实例,用于后续创建张量。 |
88| OH_NN_ReturnCode OH_NNTensorDesc_SetName(NN_TensorDesc *tensorDesc, const char *name) | 设置张量描述的名称。 |
89| OH_NN_ReturnCode OH_NNTensorDesc_GetName(const NN_TensorDesc *tensorDesc, const char **name) | 获取张量描述的名称。 |
90| OH_NN_ReturnCode OH_NNTensorDesc_SetDataType(NN_TensorDesc *tensorDesc, OH_NN_DataType dataType) | 设置张量描述的数据类型。 |
91| OH_NN_ReturnCode OH_NNTensorDesc_GetDataType(const NN_TensorDesc *tensorDesc, OH_NN_DataType *dataType) | 获取张量描述的数据类型。 |
92| OH_NN_ReturnCode OH_NNTensorDesc_SetShape(NN_TensorDesc *tensorDesc, const int32_t *shape, size_t shapeLength) | 设置张量描述的形状。 |
93| OH_NN_ReturnCode OH_NNTensorDesc_GetShape(const NN_TensorDesc *tensorDesc, int32_t **shape, size_t *shapeLength) | 获取张量描述的形状。 |
94| OH_NN_ReturnCode OH_NNTensorDesc_SetFormat(NN_TensorDesc *tensorDesc, OH_NN_Format format) | 设置张量描述的数据布局。 |
95| OH_NN_ReturnCode OH_NNTensorDesc_GetFormat(const NN_TensorDesc *tensorDesc, OH_NN_Format *format) | 获取张量描述的数据布局。 |
96| OH_NN_ReturnCode OH_NNTensorDesc_GetElementCount(const NN_TensorDesc *tensorDesc, size_t *elementCount) | 获取张量描述的元素个数。 |
97| OH_NN_ReturnCode OH_NNTensorDesc_GetByteSize(const NN_TensorDesc *tensorDesc, size_t *byteSize) | 获取基于张量描述的形状和数据类型计算的数据占用字节数。 |
98| OH_NN_ReturnCode OH_NNTensorDesc_Destroy(NN_TensorDesc **tensorDesc) | 销毁张量描述实例。 |
99
100### 张量接口
101
102| 接口名称 | 描述 |
103| ------- | --- |
104| NN_Tensor* OH_NNTensor_Create(size_t deviceID, NN_TensorDesc *tensorDesc) | 从张量描述创建张量实例,会申请设备共享内存。 |
105| NN_Tensor* OH_NNTensor_CreateWithSize(size_t deviceID, NN_TensorDesc *tensorDesc, size_t size) | 按照指定内存大小和张量描述创建张量实例,会申请设备共享内存。 |
106| NN_Tensor* OH_NNTensor_CreateWithFd(size_t deviceID, NN_TensorDesc *tensorDesc, int fd, size_t size, size_t offset) | 按照指定共享内存的文件描述符和张量描述创建张量实例,从而可以复用其他张量的设备共享内存。 |
107| NN_TensorDesc* OH_NNTensor_GetTensorDesc(const NN_Tensor *tensor) | 获取张量内部的张量描述实例指针,从而可读取张量的属性,例如数据类型、形状等。 |
108| void* OH_NNTensor_GetDataBuffer(const NN_Tensor *tensor) | 获取张量数据的内存地址,可以读写张量数据。 |
109| OH_NN_ReturnCode OH_NNTensor_GetFd(const NN_Tensor *tensor, int *fd) | 获取张量数据所在共享内存的文件描述符,文件描述符fd对应了一块设备共享内存。 |
110| OH_NN_ReturnCode OH_NNTensor_GetSize(const NN_Tensor *tensor, size_t *size) | 获取张量数据所在共享内存的大小。 |
111| OH_NN_ReturnCode OH_NNTensor_GetOffset(const NN_Tensor *tensor, size_t *offset) | 获取张量数据所在共享内存上的偏移量,张量数据可使用的大小为所在共享内存的大小减去偏移量。 |
112| OH_NN_ReturnCode OH_NNTensor_Destroy(NN_Tensor **tensor) | 销毁张量实例。 |
113
114### 执行推理接口
115
116| 接口名称 | 描述 |
117| ------- | --- |
118| OH_NNExecutor *OH_NNExecutor_Construct(OH_NNCompilation *compilation) | 创建OH_NNExecutor类型的执行器实例。 |
119| OH_NN_ReturnCode OH_NNExecutor_GetOutputShape(OH_NNExecutor *executor, uint32_t outputIndex, int32_t **shape, uint32_t *shapeLength) | 获取输出张量的维度信息,用于输出张量具有动态形状的情况。 |
120| OH_NN_ReturnCode OH_NNExecutor_GetInputCount(const OH_NNExecutor *executor, size_t *inputCount) | 获取输入张量的数量。 |
121| OH_NN_ReturnCode OH_NNExecutor_GetOutputCount(const OH_NNExecutor *executor, size_t *outputCount) | 获取输出张量的数量。 |
122| NN_TensorDesc* OH_NNExecutor_CreateInputTensorDesc(const OH_NNExecutor *executor, size_t index) | 由指定索引值创建一个输入张量的描述,用于读取张量的属性或创建张量实例。 |
123| NN_TensorDesc* OH_NNExecutor_CreateOutputTensorDesc(const OH_NNExecutor *executor, size_t index) | 由指定索引值创建一个输出张量的描述,用于读取张量的属性或创建张量实例。 |
124| OH_NN_ReturnCode OH_NNExecutor_GetInputDimRange(const OH_NNExecutor *executor, size_t index, size_t **minInputDims, size_t **maxInputDims, size_t *shapeLength) |获取所有输入张量的维度范围。当输入张量具有动态形状时,不同设备可能支持不同的维度范围。 |
125| OH_NN_ReturnCode OH_NNExecutor_SetOnRunDone(OH_NNExecutor *executor, NN_OnRunDone onRunDone) | 设置异步推理结束后的回调处理函数,回调函数定义详见接口文档。 |
126| OH_NN_ReturnCode OH_NNExecutor_SetOnServiceDied(OH_NNExecutor *executor, NN_OnServiceDied onServiceDied) | 设置异步推理执行期间设备驱动服务突然死亡时的回调处理函数,回调函数定义详见接口文档。 |
127| OH_NN_ReturnCode OH_NNExecutor_RunSync(OH_NNExecutor *executor, NN_Tensor *inputTensor[], size_t inputCount, NN_Tensor *outputTensor[], size_t outputCount) | 执行同步推理。 |
128| OH_NN_ReturnCode OH_NNExecutor_RunAsync(OH_NNExecutor *executor, NN_Tensor *inputTensor[], size_t inputCount, NN_Tensor *outputTensor[], size_t outputCount, int32_t timeout, void *userData) | 执行异步推理。 |
129| void OH_NNExecutor_Destroy(OH_NNExecutor **executor) | 销毁执行器实例。 |
130
131### 设备管理接口
132
133| 接口名称 | 描述 |
134| ------- | --- |
135| OH_NN_ReturnCode OH_NNDevice_GetAllDevicesID(const size_t **allDevicesID, uint32_t *deviceCount) | 获取对接到Neural Network Runtime的所有硬件ID。 |
136| OH_NN_ReturnCode OH_NNDevice_GetName(size_t deviceID, const char **name) | 获取指定硬件的名称。 |
137| OH_NN_ReturnCode OH_NNDevice_GetType(size_t deviceID, OH_NN_DeviceType *deviceType) | 获取指定硬件的类别信息。 |
138
139
140## 开发步骤
141
142Neural Network Runtime的开发流程主要包含**模型构造**、**模型编译**和**推理执行**三个阶段。以下开发步骤以`Add`单算子模型为例,介绍调用Neural Network Runtime接口,开发应用的过程。
143
1441. 创建应用样例文件。
145
146    首先,创建Neural Network Runtime应用样例的源文件。在项目目录下执行以下命令,创建`nnrt_example/`目录,并在目录下创建 `nnrt_example.cpp` 源文件。
147
148    ```shell
149    mkdir ~/nnrt_example && cd ~/nnrt_example
150    touch nnrt_example.cpp
151    ```
152
1532. 导入Neural Network Runtime。
154
155    在 `nnrt_example.cpp` 文件的开头添加以下代码,引入Neural Network Runtime。
156
157    ```cpp
158    #include <iostream>
159    #include <cstdarg>
160    #include "neural_network_runtime/neural_network_runtime.h"
161    ```
162
1633. 定义日志打印、设置输入数据、数据打印等辅助函数。
164
165    ```cpp
166    // 返回值检查宏
167    #define CHECKNEQ(realRet, expectRet, retValue, ...) \
168        do { \
169            if ((realRet) != (expectRet)) { \
170                printf(__VA_ARGS__); \
171                return (retValue); \
172            } \
173        } while (0)
174
175    #define CHECKEQ(realRet, expectRet, retValue, ...) \
176        do { \
177            if ((realRet) == (expectRet)) { \
178                printf(__VA_ARGS__); \
179                return (retValue); \
180            } \
181        } while (0)
182
183    // 设置输入数据用于推理
184    OH_NN_ReturnCode SetInputData(NN_Tensor* inputTensor[], size_t inputSize)
185    {
186        OH_NN_DataType dataType(OH_NN_FLOAT32);
187        OH_NN_ReturnCode ret{OH_NN_FAILED};
188        size_t elementCount = 0;
189        for (size_t i = 0; i < inputSize; ++i) {
190            // 获取张量的数据内存
191            auto data = OH_NNTensor_GetDataBuffer(inputTensor[i]);
192            CHECKEQ(data, nullptr, OH_NN_FAILED, "Failed to get data buffer.");
193            // 获取张量的描述
194            auto desc = OH_NNTensor_GetTensorDesc(inputTensor[i]);
195            CHECKEQ(desc, nullptr, OH_NN_FAILED, "Failed to get desc.");
196            // 获取张量的数据类型
197            ret = OH_NNTensorDesc_GetDataType(desc, &dataType);
198            CHECKNEQ(ret, OH_NN_SUCCESS, OH_NN_FAILED, "Failed to get data type.");
199            // 获取张量的元素个数
200            ret = OH_NNTensorDesc_GetElementCount(desc, &elementCount);
201            CHECKNEQ(ret, OH_NN_SUCCESS, OH_NN_FAILED, "Failed to get element count.");
202            switch(dataType) {
203                case OH_NN_FLOAT32: {
204                    float* floatValue = reinterpret_cast<float*>(data);
205                    for (size_t j = 0; j < elementCount; ++j) {
206                        floatValue[j] = static_cast<float>(j);
207                    }
208                    break;
209                }
210                case OH_NN_INT32: {
211                    int* intValue = reinterpret_cast<int*>(data);
212                    for (size_t j = 0; j < elementCount; ++j) {
213                        intValue[j] = static_cast<int>(j);
214                    }
215                    break;
216                }
217                default:
218                    return OH_NN_FAILED;
219            }
220        }
221        return OH_NN_SUCCESS;
222    }
223
224    OH_NN_ReturnCode Print(NN_Tensor* outputTensor[], size_t outputSize)
225    {
226        OH_NN_DataType dataType(OH_NN_FLOAT32);
227        OH_NN_ReturnCode ret{OH_NN_FAILED};
228        size_t elementCount = 0;
229        for (size_t i = 0; i < outputSize; ++i) {
230            auto data = OH_NNTensor_GetDataBuffer(outputTensor[i]);
231            CHECKEQ(data, nullptr, OH_NN_FAILED, "Failed to get data buffer.");
232            auto desc = OH_NNTensor_GetTensorDesc(outputTensor[i]);
233            CHECKEQ(desc, nullptr, OH_NN_FAILED, "Failed to get desc.");
234            ret = OH_NNTensorDesc_GetDataType(desc, &dataType);
235            CHECKNEQ(ret, OH_NN_SUCCESS, OH_NN_FAILED, "Failed to get data type.");
236            ret = OH_NNTensorDesc_GetElementCount(desc, &elementCount);
237            CHECKNEQ(ret, OH_NN_SUCCESS, OH_NN_FAILED, "Failed to get element count.");
238            switch(dataType) {
239                case OH_NN_FLOAT32: {
240                    float* floatValue = reinterpret_cast<float*>(data);
241                    for (size_t j = 0; j < elementCount; ++j) {
242                        std::cout << "Output index: " << j << ", value is: " << floatValue[j] << "." << std::endl;
243                    }
244                    break;
245                }
246                case OH_NN_INT32: {
247                    int* intValue = reinterpret_cast<int*>(data);
248                    for (size_t j = 0; j < elementCount; ++j) {
249                        std::cout << "Output index: " << j << ", value is: " << intValue[j] << "." << std::endl;
250                    }
251                    break;
252                }
253                default:
254                    return OH_NN_FAILED;
255            }
256        }
257
258        return OH_NN_SUCCESS;
259    }
260    ```
261
2624. 构造模型。
263
264    使用Neural Network Runtime的模型构造接口,构造`Add`单算子样例模型。
265
266    ```cpp
267    OH_NN_ReturnCode BuildModel(OH_NNModel** pmodel)
268    {
269        // 创建模型实例model,进行模型构造
270        OH_NNModel* model = OH_NNModel_Construct();
271        CHECKEQ(model, nullptr, OH_NN_FAILED, "Create model failed.");
272
273        // 添加Add算子的第一个输入张量,类型为float32,张量形状为[1, 2, 2, 3]
274        NN_TensorDesc* tensorDesc = OH_NNTensorDesc_Create();
275        CHECKEQ(tensorDesc, nullptr, OH_NN_FAILED, "Create TensorDesc failed.");
276
277        int32_t inputDims[4] = {1, 2, 2, 3};
278        auto returnCode = OH_NNTensorDesc_SetShape(tensorDesc, inputDims, 4);
279        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc shape failed.");
280
281        returnCode = OH_NNTensorDesc_SetDataType(tensorDesc, OH_NN_FLOAT32);
282        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc data type failed.");
283
284        returnCode = OH_NNTensorDesc_SetFormat(tensorDesc, OH_NN_FORMAT_NONE);
285        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc format failed.");
286
287        returnCode = OH_NNModel_AddTensorToModel(model, tensorDesc);
288        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Add first TensorDesc to model failed.");
289
290        returnCode = OH_NNModel_SetTensorType(model, 0, OH_NN_TENSOR);
291        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set model tensor type failed.");
292
293        // 添加Add算子的第二个输入张量,类型为float32,张量形状为[1, 2, 2, 3]
294        tensorDesc = OH_NNTensorDesc_Create();
295        CHECKEQ(tensorDesc, nullptr, OH_NN_FAILED, "Create TensorDesc failed.");
296
297        returnCode = OH_NNTensorDesc_SetShape(tensorDesc, inputDims, 4);
298        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc shape failed.");
299
300        returnCode = OH_NNTensorDesc_SetDataType(tensorDesc, OH_NN_FLOAT32);
301        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc data type failed.");
302
303        returnCode = OH_NNTensorDesc_SetFormat(tensorDesc, OH_NN_FORMAT_NONE);
304        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc format failed.");
305
306        returnCode = OH_NNModel_AddTensorToModel(model, tensorDesc);
307        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Add second TensorDesc to model failed.");
308
309        returnCode = OH_NNModel_SetTensorType(model, 1, OH_NN_TENSOR);
310        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set model tensor type failed.");
311
312        // 添加Add算子的参数张量,该参数张量用于指定激活函数的类型,张量的数据类型为int8。
313        tensorDesc = OH_NNTensorDesc_Create();
314        CHECKEQ(tensorDesc, nullptr, OH_NN_FAILED, "Create TensorDesc failed.");
315
316        int32_t activationDims = 1;
317        returnCode = OH_NNTensorDesc_SetShape(tensorDesc, &activationDims, 1);
318        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc shape failed.");
319
320        returnCode = OH_NNTensorDesc_SetDataType(tensorDesc, OH_NN_INT8);
321        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc data type failed.");
322
323        returnCode = OH_NNTensorDesc_SetFormat(tensorDesc, OH_NN_FORMAT_NONE);
324        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc format failed.");
325
326        returnCode = OH_NNModel_AddTensorToModel(model, tensorDesc);
327        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Add second TensorDesc to model failed.");
328
329        returnCode = OH_NNModel_SetTensorType(model, 2, OH_NN_ADD_ACTIVATIONTYPE);
330        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set model tensor type failed.");
331
332        // 将激活函数类型设置为OH_NN_FUSED_NONE,表示该算子不添加激活函数。
333        int8_t activationValue = OH_NN_FUSED_NONE;
334        returnCode = OH_NNModel_SetTensorData(model, 2, &activationValue, sizeof(int8_t));
335        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set model tensor data failed.");
336
337        // 设置Add算子的输出张量,类型为float32,张量形状为[1, 2, 2, 3]
338        tensorDesc = OH_NNTensorDesc_Create();
339        CHECKEQ(tensorDesc, nullptr, OH_NN_FAILED, "Create TensorDesc failed.");
340
341        returnCode = OH_NNTensorDesc_SetShape(tensorDesc, inputDims, 4);
342        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc shape failed.");
343
344        returnCode = OH_NNTensorDesc_SetDataType(tensorDesc, OH_NN_FLOAT32);
345        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc data type failed.");
346
347        returnCode = OH_NNTensorDesc_SetFormat(tensorDesc, OH_NN_FORMAT_NONE);
348        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set TensorDesc format failed.");
349
350        returnCode = OH_NNModel_AddTensorToModel(model, tensorDesc);
351        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Add forth TensorDesc to model failed.");
352
353        returnCode = OH_NNModel_SetTensorType(model, 3, OH_NN_TENSOR);
354        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Set model tensor type failed.");
355
356        // 指定Add算子的输入张量、参数张量和输出张量的索引
357        uint32_t inputIndicesValues[2] = {0, 1};
358        uint32_t paramIndicesValues = 2;
359        uint32_t outputIndicesValues = 3;
360        OH_NN_UInt32Array paramIndices = {&paramIndicesValues, 1};
361        OH_NN_UInt32Array inputIndices = {inputIndicesValues, 2};
362        OH_NN_UInt32Array outputIndices = {&outputIndicesValues, 1};
363
364        // 向模型实例添加Add算子
365        returnCode = OH_NNModel_AddOperation(model, OH_NN_OPS_ADD, &paramIndices, &inputIndices, &outputIndices);
366        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Add operation to model failed.");
367
368        // 设置模型实例的输入张量、输出张量的索引
369        returnCode = OH_NNModel_SpecifyInputsAndOutputs(model, &inputIndices, &outputIndices);
370        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Specify model inputs and outputs failed.");
371
372        // 完成模型实例的构建
373        returnCode = OH_NNModel_Finish(model);
374        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "Build model failed.");
375
376        // 返回模型实例
377        *pmodel = model;
378        return OH_NN_SUCCESS;
379    }
380    ```
381
3825. 查询Neural Network Runtime已经对接的AI加速芯片。
383
384    Neural Network Runtime支持通过HDI接口,对接多种AI加速芯片。在执行模型编译前,需要查询当前设备下,Neural Network Runtime已经对接的AI加速芯片。每个AI加速芯片对应唯一的ID值,在编译阶段需要通过设备ID,指定模型编译的芯片。
385    ```cpp
386    void GetAvailableDevices(std::vector<size_t>& availableDevice)
387    {
388        availableDevice.clear();
389
390        // 获取可用的硬件ID
391        const size_t* devices = nullptr;
392        uint32_t deviceCount = 0;
393        OH_NN_ReturnCode ret = OH_NNDevice_GetAllDevicesID(&devices, &deviceCount);
394        if (ret != OH_NN_SUCCESS) {
395            std::cout << "GetAllDevicesID failed, get no available device." << std::endl;
396            return;
397        }
398
399        for (uint32_t i = 0; i < deviceCount; i++) {
400            availableDevice.emplace_back(devices[i]);
401        }
402    }
403    ```
404
4056. 在指定的设备上编译模型。
406
407    Neural Network Runtime使用抽象的模型表达描述AI模型的拓扑结构。在AI加速芯片上执行前,需要通过Neural Network Runtime提供的编译模块来创建编译实例,并由编译实例将抽象的模型表达下发至芯片驱动层,转换成可以直接推理计算的格式,即模型编译。
408    ```cpp
409    OH_NN_ReturnCode CreateCompilation(OH_NNModel* model, const std::vector<size_t>& availableDevice,
410                                       OH_NNCompilation** pCompilation)
411    {
412        // 创建编译实例compilation,将构图的模型实例或MSLite传下来的模型实例传入
413        OH_NNCompilation* compilation = OH_NNCompilation_Construct(model);
414        CHECKEQ(compilation, nullptr, OH_NN_FAILED, "OH_NNCore_ConstructCompilationWithNNModel failed.");
415
416        // 设置编译的硬件、缓存路径、性能模式、计算优先级、是否开启float16低精度计算等选项
417        // 选择在第一个设备上编译模型
418        auto returnCode = OH_NNCompilation_SetDevice(compilation, availableDevice[0]);
419        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNCompilation_SetDevice failed.");
420
421        // 将模型编译结果缓存在/data/local/tmp目录下,版本号指定为1
422        returnCode = OH_NNCompilation_SetCache(compilation, "/data/local/tmp", 1);
423        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNCompilation_SetCache failed.");
424
425        // 设置硬件性能模式
426        returnCode = OH_NNCompilation_SetPerformanceMode(compilation, OH_NN_PERFORMANCE_EXTREME);
427        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNCompilation_SetPerformanceMode failed.");
428
429        // 设置推理执行优先级
430        returnCode = OH_NNCompilation_SetPriority(compilation, OH_NN_PRIORITY_HIGH);
431        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNCompilation_SetPriority failed.");
432
433        // 是否开启FP16计算模式
434        returnCode = OH_NNCompilation_EnableFloat16(compilation, false);
435        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNCompilation_EnableFloat16 failed.");
436
437        // 执行模型编译
438        returnCode = OH_NNCompilation_Build(compilation);
439        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNCompilation_Build failed.");
440
441        *pCompilation = compilation;
442        return OH_NN_SUCCESS;
443    }
444    ```
445
4467. 创建执行器。
447
448    完成模型编译后,需要调用Neural Network Runtime的执行模块,通过编译实例创建执行器。模型推理阶段中的设置模型输入、触发推理计算以及获取模型输出等操作均需要围绕执行器完成。
449    ```cpp
450    OH_NNExecutor* CreateExecutor(OH_NNCompilation* compilation)
451    {
452        // 通过编译实例compilation创建执行器executor
453        OH_NNExecutor *executor = OH_NNExecutor_Construct(compilation);
454        CHECKEQ(executor, nullptr, nullptr, "OH_NNExecutor_Construct failed.");
455        return executor;
456    }
457    ```
458
4598. 执行推理计算,并打印推理结果。
460
461    通过执行模块提供的接口,将推理计算所需要的输入数据传递给执行器,触发执行器完成一次推理计算,获取模型的推理结果并打印。
462    ```cpp
463    OH_NN_ReturnCode Run(OH_NNExecutor* executor, const std::vector<size_t>& availableDevice)
464    {
465        // 从executor获取输入输出信息
466        // 获取输入张量的个数
467        size_t inputCount = 0;
468        auto returnCode = OH_NNExecutor_GetInputCount(executor, &inputCount);
469        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNExecutor_GetInputCount failed.");
470        std::vector<NN_TensorDesc*> inputTensorDescs;
471        NN_TensorDesc* tensorDescTmp = nullptr;
472        for (size_t i = 0; i < inputCount; ++i) {
473            // 创建输入张量的描述
474            tensorDescTmp = OH_NNExecutor_CreateInputTensorDesc(executor, i);
475            CHECKEQ(tensorDescTmp, nullptr, OH_NN_FAILED, "OH_NNExecutor_CreateInputTensorDesc failed.");
476            inputTensorDescs.emplace_back(tensorDescTmp);
477        }
478        // 获取输出张量的个数
479        size_t outputCount = 0;
480        returnCode = OH_NNExecutor_GetOutputCount(executor, &outputCount);
481        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNExecutor_GetOutputCount failed.");
482        std::vector<NN_TensorDesc*> outputTensorDescs;
483        for (size_t i = 0; i < outputCount; ++i) {
484            // 创建输出张量的描述
485            tensorDescTmp = OH_NNExecutor_CreateOutputTensorDesc(executor, i);
486            CHECKEQ(tensorDescTmp, nullptr, OH_NN_FAILED, "OH_NNExecutor_CreateOutputTensorDesc failed.");
487            outputTensorDescs.emplace_back(tensorDescTmp);
488        }
489
490        // 创建输入和输出张量
491        NN_Tensor* inputTensors[inputCount];
492        NN_Tensor* tensor = nullptr;
493        for (size_t i = 0; i < inputCount; ++i) {
494            tensor = nullptr;
495            tensor = OH_NNTensor_Create(availableDevice[0], inputTensorDescs[i]);
496            CHECKEQ(tensor, nullptr, OH_NN_FAILED, "OH_NNTensor_Create failed.");
497            inputTensors[i] = tensor;
498        }
499        NN_Tensor* outputTensors[outputCount];
500        for (size_t i = 0; i < outputCount; ++i) {
501            tensor = nullptr;
502            tensor = OH_NNTensor_Create(availableDevice[0], outputTensorDescs[i]);
503            CHECKEQ(tensor, nullptr, OH_NN_FAILED, "OH_NNTensor_Create failed.");
504            outputTensors[i] = tensor;
505        }
506
507        // 设置输入张量的数据
508        returnCode = SetInputData(inputTensors, inputCount);
509        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "SetInputData failed.");
510
511        // 执行推理
512        returnCode = OH_NNExecutor_RunSync(executor, inputTensors, inputCount, outputTensors, outputCount);
513        CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNExecutor_RunSync failed.");
514
515        // 打印输出张量的数据
516        Print(outputTensors, outputCount);
517
518        // 清理输入和输出张量以及张量描述
519        for (size_t i = 0; i < inputCount; ++i) {
520            returnCode = OH_NNTensor_Destroy(&inputTensors[i]);
521            CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNTensor_Destroy failed.");
522            returnCode = OH_NNTensorDesc_Destroy(&inputTensorDescs[i]);
523            CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNTensorDesc_Destroy failed.");
524        }
525        for (size_t i = 0; i < outputCount; ++i) {
526            returnCode = OH_NNTensor_Destroy(&outputTensors[i]);
527            CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNTensor_Destroy failed.");
528            returnCode = OH_NNTensorDesc_Destroy(&outputTensorDescs[i]);
529            CHECKNEQ(returnCode, OH_NN_SUCCESS, OH_NN_FAILED, "OH_NNTensorDesc_Destroy failed.");
530        }
531
532        return OH_NN_SUCCESS;
533    }
534    ```
535
5369. 构建端到端模型构造-编译-执行流程。
537
538    步骤4-步骤8实现了模型的模型构造、编译和执行流程,并封装成多个函数,便于模块化开发。以下示例代码将串联这些函数, 形成一个完整的Neural Network Runtime使用流程。
539    ```cpp
540    int main(int argc, char** argv)
541    {
542        OH_NNModel* model = nullptr;
543        OH_NNCompilation* compilation = nullptr;
544        OH_NNExecutor* executor = nullptr;
545        std::vector<size_t> availableDevices;
546
547        // 模型构造
548        OH_NN_ReturnCode ret = BuildModel(&model);
549        if (ret != OH_NN_SUCCESS) {
550            std::cout << "BuildModel failed." << std::endl;
551            OH_NNModel_Destroy(&model);
552            return -1;
553        }
554
555        // 获取可执行的设备
556        GetAvailableDevices(availableDevices);
557        if (availableDevices.empty()) {
558            std::cout << "No available device." << std::endl;
559            OH_NNModel_Destroy(&model);
560            return -1;
561        }
562
563        // 模型编译
564        ret = CreateCompilation(model, availableDevices, &compilation);
565        if (ret != OH_NN_SUCCESS) {
566            std::cout << "CreateCompilation failed." << std::endl;
567            OH_NNModel_Destroy(&model);
568            OH_NNCompilation_Destroy(&compilation);
569            return -1;
570        }
571
572        // 销毁模型实例
573        OH_NNModel_Destroy(&model);
574
575        // 创建模型的推理执行器
576        executor = CreateExecutor(compilation);
577        if (executor == nullptr) {
578            std::cout << "CreateExecutor failed, no executor is created." << std::endl;
579            OH_NNCompilation_Destroy(&compilation);
580            return -1;
581        }
582
583        // 销毁编译实例
584        OH_NNCompilation_Destroy(&compilation);
585
586        // 使用上一步创建的执行器,执行推理计算
587        ret = Run(executor, availableDevices);
588        if (ret != OH_NN_SUCCESS) {
589            std::cout << "Run failed." << std::endl;
590            OH_NNExecutor_Destroy(&executor);
591            return -1;
592        }
593
594        // 销毁执行器实例
595        OH_NNExecutor_Destroy(&executor);
596
597        return 0;
598    }
599    ```
600
601## 调测验证
602
6031. 准备应用样例的编译配置文件。
604
605    新建一个 `CMakeLists.txt` 文件,为开发步骤中的应用样例文件 `nnrt_example.cpp` 添加编译配置。以下提供简单的 `CMakeLists.txt` 示例:
606    ```text
607    cmake_minimum_required(VERSION 3.16)
608    project(nnrt_example C CXX)
609
610    add_executable(nnrt_example
611        ./nnrt_example.cpp
612    )
613
614    target_link_libraries(nnrt_example
615        neural_network_runtime
616        neural_network_core
617    )
618    ```
619
6202. 编译应用样例。
621
622    执行以下命令,在当前目录下新建build/目录,在build/目录下编译 `nnrt_example.cpp`,得到二进制文件 `nnrt_example`。
623    ```shell
624    mkdir build && cd build
625    cmake -DCMAKE_TOOLCHAIN_FILE={交叉编译工具链的路径}/build/cmake/ohos.toolchain.cmake -DOHOS_ARCH=arm64-v8a -DOHOS_PLATFORM=OHOS -DOHOS_STL=c++_static ..
626    make
627    ```
628
6293. 执行以下代码,将样例推送到设备上执行。
630    ```shell
631    # 将编译得到的 `nnrt_example` 推送到设备上,执行样例。
632    hdc_std file send ./nnrt_example /data/local/tmp/.
633
634    # 给测试用例可执行文件加上权限。
635    hdc_std shell "chmod +x /data/local/tmp/nnrt_example"
636
637    # 执行测试用例
638    hdc_std shell "/data/local/tmp/nnrt_example"
639    ```
640
641    如果样例执行正常,应该得到以下输出。
642    ```text
643    Output index: 0, value is: 0.000000.
644    Output index: 1, value is: 2.000000.
645    Output index: 2, value is: 4.000000.
646    Output index: 3, value is: 6.000000.
647    Output index: 4, value is: 8.000000.
648    Output index: 5, value is: 10.000000.
649    Output index: 6, value is: 12.000000.
650    Output index: 7, value is: 14.000000.
651    Output index: 8, value is: 16.000000.
652    Output index: 9, value is: 18.000000.
653    Output index: 10, value is: 20.000000.
654    Output index: 11, value is: 22.000000.
655    ```
656
6574. 检查模型缓存(可选)。
658
659    如果在调测环境下,Neural Network Runtime对接的HDI服务支持模型缓存功能,执行完 `nnrt_example`, 可以在 `/data/local/tmp` 目录下找到生成的缓存文件。
660
661    > **说明:**
662    >
663    > 模型的IR需要传递到硬件驱动层,由HDI服务将统一的IR图,编译成硬件专用的计算图,编译的过程非常耗时。Neural Network Runtime支持计算图缓存的特性,可以将HDI服务编译生成的计算图,缓存到设备存储中。当下一次在同一个加速芯片上编译同一个模型时,通过指定缓存的路径,Neural Network Runtime可以直接加载缓存文件中的计算图,减少编译消耗的时间。
664
665    检查缓存目录下的缓存文件:
666    ```shell
667    ls /data/local/tmp
668    ```
669
670    以下为打印结果:
671    ```text
672    # 0.nncache 1.nncache 2.nncache cache_info.nncache
673    ```
674
675    如果缓存不再使用,需要手动删除缓存,可以参考以下命令,删除缓存文件。
676    ```shell
677    rm /data/local/tmp/*nncache
678    ```
679