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.
} Include required header files.
json-develop ├── include │ └── nlohmann │ └── json.hpp └── README.md
Use the REGISTER_CUSTOM_OP macro to register the mapping between the DDK operators and the ONNX operators. The method is as follows:
Implement the ParseParamByOpFunc callback function. The function declaration is as follows:
Status ParseParamByOpFunc(const ge::Operator& op_src, ge::Operator& op_dest)
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.
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.
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") 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:
For details about the parameters related to the model conversion command, see Offline Model Conversion.
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.
Prepare the input data in *.bin format that meets the model input requirements. For details, see Generating Input Data.
Complete model integration by referring to App Integration Code.