目录

ONNX Framework

Plugin Development

You can refer to this section to develop an operator plugin and map the operators of the ONNX framework to the operators that adapt to the Kirin AI processors (AscendC operators for short). In this way, Ascend C custom operators can be called from the ONNX framework. The following example shows a basic development process:

#include "register/register.h"
#include "nlohmann/json.hpp"
namespace domi {
    Status ParseParamByOpFunc(const ge::Operator& op_src, ge::Operator& op_dest) {
        // ...
    }
    REGISTER_CUSTOM_OP("OpType") // Type of the mapped custom operator
        .FrameworkType(ONNX)
        .OriginOpType("OriginOpType") // Operator type in the ONNX model
        .ParseParamsByOperatorFn(ParseParamByOpFunc); // Registers a function for parsing operator attributes.
   }
  1. Include required header files.

    • register.h is stored in the ddk/ai_ddk_lib/include/register directory after the DDK software is installed. You can use the operator registration class to call operator registration APIs after this header file is included.
    • json.hpp is used to parse ONNX parameter definitions of the string type into the JSON format. If the json.hpp file is not provided in the sample project, you can download it and place it in any path that can be found in the project. Then, include this header file. It is recommended that you place the file in the tools/tools_ascendc/json-develop directory under the DDK installation directory. The following is an example. For details about the download path, see json.hpp.
      json-develop
      ├── include
      │   └── nlohmann
      │       └── json.hpp
      └── README.md
  2. Use the REGISTER_CUSTOM_OP macro to register the mapping between the DDK operators and the ONNX operators. The method is as follows:

    • REGISTER_CUSTOM_OP: Registers a custom operator. OpType indicates the operator type name, which must be the same as that in Operator Prototype Definition and Implementation.
    • FrameworkType: ONNX indicates that the original framework is ONNX.
    • OriginOpType: indicates the type of an operator in the original framework. For example, the custom operator OpTypeA corresponds to the ONNX operator package version opset_version=11, and **ai.onnx::11::**OpTypeA is passed. The supported ONNX versions range from 9 to 15.
    • ParseParamsByOperatorFn (ParseParamByOpFunc): parses the operator parameter to implement mapping. You need to implement ParseParamsByOperatorFn. For details about the implementation, see Step 3.
  3. Implement the ParseParamByOpFunc callback function. The function declaration is as follows:

    Status ParseParamByOpFunc(const ge::Operator& op_src, ge::Operator& op_dest)
    • ParseParamByOpFunc: function name, which is user-defined.
    • op_src: an Operator class object defined by the ONNX framework, including attributes of the operator in the ONNX model. The definition is obtained from the original ONNX model file.
    • op_dest: DDK operator data structure, which stores operator information. For details about the Operator class, see Operator.

    You need to implement attribute parsing and mapping in the callback function as follows:

    In the original ONNX model, for parameters of the repeated message type, you can obtain attribute values using the GetAttr(const char *name, ge::AscendString &attr_value) API, cast the attribute values of type AscendString to String, and then convert the attribute values to the JSON format for attribute field parsing.

    The implementation is as follows.

    Status ParseParamAddCustom(const ge::Operator& op_src, ge::Operator& op_dest) {
    ge::AscendString attrs_string;
    // Obtain the attributes of an ONNX operator using the specified attribute name attribute and assign a value to the object of the AscendString type.
        if (ge::GRAPH_SUCCESS == op_src.GetAttr("attribute", attrs_string)) {
            nlohmann::json attrs = nlohmann::json::parse(attrs_string.GetString());
            for (nlohmann::json attr : attrs["attribute"]) {
                if (attr["name"] == "bias") {
                    int64_t bias  = attr["i"];
                    op_dest.SetAttr("bias", bias);
                }
            }
        }
        return SUCCESS;
    }

    You can also use automatic parsing and the mapped callback function AutoMappingByOpFn. The usage is as follows:

    #include "register/register.h"
    namespace domi {
        REGISTER_CUSTOM_OP("OpType")
            .FrameworkType(ONNX)
            .OriginOpType("OriginOpType")
            .ParseParamsByOperatorFn(AutoMappingByOpFn); // Registers a function for parsing operator attributes.
    }
    • The GetAttr and SetAttr APIs of the current version cannot parse fields of type double or uint64 in the source file.

    • During model conversion using the omg tool, strong verification is not performed on obtaining attributes. When implementing an operator plugin, it is advisable to add the corresponding processing logic for possible GetAttr call failures. For example, return a failure message for a required attribute or prompt the developer to set a default value for an optional attribute.

    • For non-constant float32 inputs, if the operator registration supports only float16, the framework automatically inserts a cast operator to convert the float32 input to float16. After the computation is complete, the cast operator converts the output back to float32. For constant float32 inputs, the framework does not automatically convert them. You need to modify the weight format and type to match the operator input.

Example

After plugins of the ONNX framework are developed, you can call Ascend C custom operators on ONNX. The following uses an ONNX framework network that contains only the AddCustom operator as an example to describe how to use an inference tool to perform inference, helping you quickly experience the calling process of a custom operator on the network in the inference scenario. (The AddCustom operator on the network is mapped to a custom AddCustom operator through a plugin.)

Before performing the following steps, you need to develop the custom AddCustom operator on the kernel and host, develop the ONNX plugin, and compile and deploy the operator.

For details about the complete example, see AddCustom Operator Implementation and ONNX Framework Calling Example.

  1. Generate the custom operator using the Python code.

    import os
    import numpy as np
    import onnx
    from onnx import helper
    from onnx import TensorProto
    
    
    def create_model():
        AddCustom = helper.make_node(
            "AddCustom",
            inputs = ["input1", "input2"],
            outputs = ["output"],
            name = "add",
            bias = 1
        )
    
        input1_input = helper.make_tensor_value_info("input1", TensorProto.FLOAT, [8, 2048])
        input2_input = helper.make_tensor_value_info("input2", TensorProto.FLOAT, [8, 2048])
        add_output = helper.make_tensor_value_info("output", TensorProto.FLOAT, [8, 2048])
    
        graph = helper.make_graph(
            nodes = [AddCustom],
            name = "custom_graph",
            inputs = [input1_input, input2_input],
            outputs = [add_output]
        )
    
        model = helper.make_model(graph, producer_name="onnx-example")
        model.opset_import[0].version = 11
        model.ir_version = 6
    
        return model
    
    model = create_model()
    print(onnx.helper.printable_graph(model.graph))
    onnx.save(model, "./add_custom.onnx")
  2. Run the following command in %{DDK_INSTALL_PATH}/tools/tools_omg to generate an offline model (the path and file arguments in the command are for reference only):

    ./omg --model ./add_custom.onnx --framework 5 --output out/custom_graph --target=omc --platform kirin9020

    The key parameters are described as follows:

    • --model: path of the ONNX network model file (*.onnx).
    • --framework: source framework type. 5 indicates ONNX.
    • --output: path including the file name of the generated offline model. Note: Record the path for storing the .omc model file, which will be used in subsequent app development.
    • --target: model type after conversion. Only OMC is supported in the custom operator scenario.
    • --platform: chip platform on which the OMC model runs. The OMC model is hardware-related.

      For details about the parameters related to the model conversion command, see Offline Model Conversion.

  3. If the following information is displayed, the custom Ascend C operator compilation process starts and the model conversion is successful.

    // ...
    "the node AddCustom is custom node"
    // ...
    "OMG generate offline model success."

    Find the generated offline model (for example, leaky_relu.om) in the path specified by --output.

  4. Prepare the input data in *.bin format that meets the model input requirements. For details, see Generating Input Data.

  5. Complete model integration by referring to App Integration Code.