目录

Graph Build and Execution

Single-operator model execution refers to executing operators based on graph IR. First, build operators (for example, use the OMG tool to build the single-operator description file defined by Ascend IR into an operator .omc model file). Then, call the model loading and inference API to execute the single-operator network. The following provides only the example and basic content of single-operator model execution. For more details, see Device-Side Deployment.

Currently, HarmonyOS Next does not support graph build and execution. Custom operators can only be integrated through AI Framework Operator Adaptation. The following steps are for reference only.

Environment Requirements

Preparing the Verification Code Project

When running NPU debugging commands, for example:

ascendebug kernel --backend npu  --chip-version kirin9020 --repo-type customize --json-file ./temp.json --core-type AiCore

For details about the command line parameters, see NPU Debugging Parameters. A verification sample project is generated in ${debug_workspace}/${op_type}/npu/src. The directory structure of the code project is as follows:

src
├── BuildIRGraph.cpp // Generates the source file of the single-operator graph.
├── BuildIRGraph.h // Single-operator graph entry: CreateCustomIRGraph
├── build.sh // OMC model build script
├── CMakeLists.txt
├── custom_graph.omc // OMC model generated after compilation
└── op_proto.h // Header file for operator prototype definition output during operator compilation

Generating a Single-Operator Offline Model File

Run build.sh in the sample project.

./build.sh

After the preceding command is executed, the offline model file custom_graph.omc is generated in the current path.

Generating Input Data

Run the following command in the sample operator project directory:

python3 scripts/gen_data.py

Two data files input_0.bin and input_1.bin with shape (8, 2048) and data type float16 are generated in the input directory for verifying the AddCustom operator.

A code example is as follows:

import numpy as np
a = np.random.randint(100, size=(8, 2048,)).astype(np.float16)
b = np.random.randint(100, size=(8, 2048,)).astype(np.float16)
a.tofile('input_0.bin')
b.tofile('input_1.bin')

App Integration Code

You can compile the code logic for loading and executing a model by referring to the following example. For details about the integration process, see App Development.

The following is a code snippet of key steps only, which is not ready to be built or run. After APIs are called, you need to add exception handling branches and record error logs and info logs.

int RunModel(void* modelData, size_t modelSize)
{
    // 1. Load the OMC model.
    auto modelDescV1 = std::make_shared<hiai::AiModelDescription>("model", 3, 0, 0, 0);
    modelDescV1->SetModelBuffer(modelData, modelSize);

    std::vector<std::shared_ptr<hiai::AiModelDescription>> modelDescVec;
    modelDescVec.push_back(modelDescV1);
    auto clientV1 = std::make_shared<hiai::AiModelMngerClient>();
    if (clientV1->Init(nullptr) != hiai::SUCCESS) {
        LOGE("client Init() failed.");
        return FAILURE;
    }

    if (clientV1->Load(modelDescVec) != hiai::SUCCESS) {
        LOGE("client Load() failed.");
        return FAILURE;
    }
    LOGI("load model success");
    std::vector<hiai::TensorDimension> inDimVecV1;
    std::vector<hiai::TensorDimension> outDimVecV1;
    std::vector<std::shared_ptr<hiai::AiTensor>> inTensorVecV1;
    std::vector<std::shared_ptr<hiai::AiTensor>> outTensorVecV1;

    if (clientV1->GetModelIOTensorDim(modelDescV1->GetName(), inDimVecV1, outDimVecV1) != hiai::SUCCESS) {
        LOGE("client GetModelIOTensorDim() failed.");
        clientV1->UnLoadModel();
        return FAILURE;
    }
    // 2. Set the model input and output.
    for (size_t i = 0; i < INPUT_NUM &&  i < inDimVecV1.size(); ++i) {
        void *data = nullptr;
        size_t size = 0;
        LOGI("open input file  inputFile: %s ", INPUT_LIST[i].c_str());
        if (!ReadData(INPUT_LIST[i], &data, size)) {
            LOGE("open input file failed! inputFile: %s ", INPUT_LIST[i].c_str());
            clientV1->UnLoadModel();
            return FAILURE;
        }

        auto inputV1 = std::make_shared<hiai::AiTensor>();

        inputV1->Init(&inDimVecV1[i], INPUT_TYPE);
        if (inputV1->GetSize() != size) {
            LOGE("inputSize: %d != fileSize: %zu ", inputV1->GetSize(), size);
            clientV1->UnLoadModel();
            free(data);
            data = nullptr;
            return FAILURE;
        }
        memcpy(inputV1->GetBuffer(), data, size);
        inTensorVecV1.push_back(inputV1);
        free(data);
        data = nullptr;
    }
    LOGI("load input success");

    for (size_t i = 0; i < outDimVecV1.size(); i++) {
        auto outputV1 = std::make_shared<hiai::AiTensor>();
        outputV1->Init(&outDimVecV1[i], OUTPUT_TYPE);
        outTensorVecV1.push_back(outputV1);
    }
    LOGI("init output success");

    // 3. Perform model inference.
    hiai::AiContext context;
    context.AddPara("model_name", "model");
    int32_t istamp = 0;

    auto retCode = clientV1->Process(context, inTensorVecV1, outTensorVecV1, 1000, istamp);
    if (retCode != hiai::SUCCESS) {
        LOGE("process failed.");
        clientV1->UnLoadModel();
        return retCode;
    }
    LOGI("process success");

    for (size_t i = 0; i < outTensorVecV1.size(); i++) {
        char* data = reinterpret_cast<char*>(outTensorVecV1[i]->GetBuffer());
        DumpBufferToFile(data, outTensorVecV1[i]->GetSize(), OUTPUT_PATH);
    }
    LOGI("dump output success");

    // 4. Uninstall the model.
    clientV1->UnLoadModel();
    return retCode;
}