0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

自定义算子开发

地瓜机器人 2022-04-07 16:11 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

地平线工具链中已经支持了丰富的算子,在大多数情况下,您的模型应该可以通过使用hb_mapper工具完成转换并顺利部署到地平线芯片上。 少部分算子不支持情况下,我们建议您先尝试下替换算子的可能性,这样有利于将地平线芯片能力充分发挥出来。

自定义算子目前只提供CPU算子开发能力,可自定义onnx算子以及caffe算子。一个完整的自定义算子应用过程包括注册算子、算子实现、含自定义算子模型转换和运行含自定义op模型四个阶段。

1 自定义onnx算子

1.1 将含有自定义算子的pytorch模型导出ONNX

使用torch.onnx.register_custom_op_symbolic注册自定义算子,再导出onnx模型。有以下几处配置参数需要注意:

1. register_custom_op_symbolic函数的第一个参数'::adaptive_avg_pool2d'为pytorch对应操作符名称,若填写错误,则会导致自定义算子注册失败

2. 操作域必须设置为horizon.custom,算子类型为PyOp

3. class_name_s需要与算子实现文件中的类名相对应

4. module_s与算子实现文件名相同,若算子实现文件在当前目录的子目录(custom_op)中,要将相对路径包含进去:"custom_op/sample_custom"

5. 必须指定input_types_i、output_types_i、output_shape_s三个参数

6. 注意指定opset_version为10或11

参考代码:

import torch

from horizon_nn.horizon_onnx.onnx_pb import TensorProto

from torch.onnx.utils import register_custom_op_symbolic

#prepare your model and input_data

def horizon_pool(g, input, output_size):

return g.op(

'horizon.custom::PyOp', #required, ! must be 'horizon.custom' domain !

input,

class_name_s="GlobalAveragePool", #required ! must match the class def name in sample_custom python file !

compute_s="compute", #optional, 'compute' by default

module_s="sample_custom",#required ! must match the file name of the "op_register_files" !

input_types_i=[TensorProto.FLOAT], #required

output_types_i=[TensorProto.FLOAT],#required

output_shape_s=["1, 1024, 1, 1"]) #required

register_custom_op_symbolic('::adaptive_avg_pool2d',

horizon_pool,

opset_version=11)

torch.onnx.export(model, input_data, "custom_op.onnx", opset_version=11)

1.2 算子实现

对应上一节注册自定义算子时配置的算子实现文件(class_name需要保持一致)。

#sample_custom.py

import numpy as np

from horizon_nn.custom import op_implement_register

@op_implement_register("CustomIdentity")

class CustomIdentity(object):

def __init__(self, kernel_size, threshold):

self._kernel_size = kernel_size

self._default_threshold = threshold

def compute(self, X):

return X

@op_implement_register("GlobalAveragePool")

class GlobalAveragePool(object):

def __init__(self):

pass

def compute(self, X):

return np.nanmean(X, axis=(2, 3)).reshape(-1, 1024, 1, 1)

2 自定义caffe算子

2.1 修改prototxt

在原始模型文件中,将自定义算子对应的类型标记为"Custom" ,并设置custom_param。params 是算子的传入参数,指定方式为‘param_name’:param_value, 多个参数之间使用 \n 分隔。

layer {

name: "hr_op"

type: "Custom"

bottom: "res3d_in"

top: "res3d"

custom_param {

kind: "CustomIdentity"

shape {

dim: 1

dim: 512

dim: 28

dim: 28

}

params: "'kernel_size': 10 \n'threshold': 0.5"

}

}

2.2 算子实现

相比于onnx模型,caffe模型的自定义算子实现还需要提供该算子的输出尺寸。

#sample_custom.py

from horizon_nn.custom.op_registration import op_implement_register, op_shape_infer_register

@op_implement_register("CustomIdentity")

class CustomIdentity(object):

def __init__(self, kernel_size, threshold):

self._kernel_size = kernel_size

self._default_threshold = threshold

def compute(self, X):

return X

@op_shape_infer_register("CustomIdentity")

def infer_shape(inputs_shape):

"""Infer the output shapes of the custom operator.

Arguments:

input_shapes: A list of input shapes.

Returns:

Return a list of custom operator's output shapes.

"""

outputs_shape = inputs_shape

return outputs_shape

3 含自定义算子的模型转换

在模型转换配置文件中,添加自定义算子相关参数,示例如下:

poYBAGJOnKmALm2DAAI_kfFzMYs348.png

custom_op_method固定使用 register

op_register_files自定义算子计算的实现文件,如果有多份实现,使用 ‘;’ 将各个文件分开即可。

4 含自定义算子的模型推理

想将包含自定算子的.bin模型顺利部署到开发板上,还需要提供自定义算子的C++代码实现。 您可以使用下文提供的模板进行修改:

头文件:

// custom_identity.h

#ifndef ADVANCED_SAMPLES_CUSTOM_IDENTITY_H_

#define ADVANCED_SAMPLES_CUSTOM_IDENTITY_H_

#include

#include

#include "dnn/hb_dnn.h"

#include "dnn/plugin/hb_dnn_layer.h"

#include "dnn/plugin/hb_dnn_ndarray.h"

namespace hobot {

namespace dnn {

Layer *CustomIdentity_layer_creator();

class CustomIdentity : public Layer {

public:

CustomIdentity() = default;

~CustomIdentity() override = default;

public:

int32_t Init(const Attribute &attributes) override;

int32_t Forward(const std::vector &bottomBlobs,

std::vector &topBlobs,

const hbDNNInferCtrlParam *inferCtrlParam) override;

std::string GetType() const override { return "CustomIdentity"; }

private:

std::string module_;

};

} // namespace dnn

} // namespace hobot

#endif

cpp文件:

// custom_identity.cpp

#include "custom_identity.h"

namespace hobot {

namespace dnn {

Layer *CustomIdentity_layer_creator() { return new CustomIdentity; }

int32_t CustomIdentity::Init(const Attribute &attributes) {

// unused attribute, just demonstrating

attributes.GetAttributeValue(&module_, "module");

return 0;

}

int32_t CustomIdentity::Forward(const std::vector &bottomBlobs,

std::vector &topBlobs,

const hbDNNInferCtrlParam *inferCtrlParam) {

const NDArray *input = bottomBlobs[0];

NDArray *out = topBlobs[0];

const auto *input_data = input->Dptr();

auto *out_data = out->Dptr();

uint32_t size = input->Size();

for (uint32_t i = 0U; i < size; i++) { 

out_data[i] = input_data[i];

}

return 0;

}

} // namespace dnn

} // namespace hobot

将以上两个文件放在当前工程目录下之后,编写infer代码时仅需要在加载模型之前增加对算子的注册即可,注册可参考以下代码:

//infer.cpp

#include "custom_identity.h"

// register custom layer

hbDNNRegisterLayerCreator("CustomIdentity",

hobot::dnn::CustomIdentity_layer_creator)

本文转载自地平线开发者社区:https://developer.horizon.ai
原作者:颜值即正义
原文链接:https://developer.horizon.ai/forumDetail/71036525692881018

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 算子
    +关注

    关注

    0

    文章

    16

    浏览量

    7398
  • 模型转换
    +关注

    关注

    0

    文章

    4

    浏览量

    5355
收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    无图形界面模式下自定义检查工具的应用

    此前文章已介绍 ANSA 中的自定义检查工具。本文将探讨该功能在无图形界面(No-GUI)模式下的应用,旨在满足标准化工作流程的需求,适用于需要高度自动化的前处理场景。通过集成自定义检查,用户可实现工作流程的高效自动化运行。
    的头像 发表于 11-30 14:13 300次阅读
    无图形界面模式下<b class='flag-5'>自定义</b>检查工具的应用

    采用汇编指示符来使用自定义指令

    具体实现 1、采用.word .half .dword等汇编指示符直接插入自定义指令,这种方法需要自己指定寄存器。其中.word为插入一个字的数据即32位,.half为插入半字即16位
    发表于 10-28 06:02

    如何使用SDK进行自定义音频播放功能

    在上一篇文章安信可离线语音模组 VC-01、VC-02 系列教程 【二次开发篇】自定义音频替换失败过程中,简要概述了res_build_tool.py 文件, 其主要的作用就是将音频文件进行转换,从而使编译固件的时候能够将音频文件编译到BIN中,然后在各项事件触发的时候实
    的头像 发表于 09-25 15:52 3011次阅读
    如何使用SDK进行<b class='flag-5'>自定义</b>音频播放功能

    LOTO示波器自定义解码功能—CANFD解码

    LOTO示波器软件更新了自定义解码功能,并在bilibili上传了演示视频,视频链接: https://www.bilibili.com/video/BV1wq3ezjEjQ
    的头像 发表于 07-11 10:34 752次阅读
    LOTO示波器<b class='flag-5'>自定义</b>解码功能—CANFD解码

    大彩讲堂:VisualTFT软件如何自定义圆形进度条

    VisualTFT软件如何自定义圆形进度条
    的头像 发表于 07-07 17:10 1220次阅读
    大彩讲堂:VisualTFT软件如何<b class='flag-5'>自定义</b>圆形进度条

    KiCad 中的自定义规则(KiCon 演讲)

    “  Seth Hillbrand 在 KiCon US 2025 上为大家介绍了 KiCad 的规则系统,并详细讲解了自定义规则的设计与实例。  ”   演讲主要围绕 加强 KiCad 中的自定义
    的头像 发表于 06-16 11:17 1480次阅读
    KiCad 中的<b class='flag-5'>自定义</b>规则(KiCon 演讲)

    HarmonyOS应用自定义键盘解决方案

    自定义键盘是一种替换系统默认键盘的解决方案,可实现键盘个性化交互。允许用户结合业务需求与操作习惯,对按键布局进行可视化重构、设置多功能组合键位,使输入更加便捷和舒适。在安全防护层面,自定义键盘可以
    的头像 发表于 06-05 14:19 1582次阅读

    如何使用自定义设置回调函数?

    你好,我正在尝试编写自己的自定义设置回调函数,并使用 fastEnum=false。 是否有任何代码示例或资料可供我参考? void CyU3PUsbRegisterSetupCallback
    发表于 05-21 06:11

    LabVIEW运动控制(三):EtherCAT运动控制器的高效加工指令自定义封装

    LabVIEW高效加工指令自定义封装
    的头像 发表于 04-08 13:49 3269次阅读
    LabVIEW运动控制(三):EtherCAT运动控制器的高效加工指令<b class='flag-5'>自定义</b>封装

    如何添加自定义单板

    开发过程中,用户有时需要创建自定义板配置。本节将通过一个实例讲解用户如何创建属于自己的machine,下面以g2l-test.conf为例进行说明。
    的头像 发表于 03-12 14:43 1082次阅读

    如何快速创建用户自定义Board和App工程

    可将该文件夹复制到用户自定义的工作目录(workspace)中,基于此模板进行开发。本模板主要牵涉到的用户自定义的文件有:用户板级文件Board用户应用程序App用
    的头像 发表于 02-08 13:38 1001次阅读
    如何快速创建用户<b class='flag-5'>自定义</b>Board和App工程

    Altium Designer 15.0自定义元件设计

    电子发烧友网站提供《Altium Designer 15.0自定义元件设计.pdf》资料免费下载
    发表于 01-21 15:04 0次下载
    Altium Designer 15.0<b class='flag-5'>自定义</b>元件设计

    think-cell:自定义think-cell(四)

    C.5 设置默认议程幻灯片布局 think-cell 议程可以在演示文稿中使用特定的自定义布局来定义议程、位置和议程幻灯片上的其他形状,例如标题或图片。通过将此自定义布局添加到模板,您可以为整个组织
    的头像 发表于 01-13 10:37 881次阅读
    think-cell:<b class='flag-5'>自定义</b>think-cell(四)

    智能语音识别照明解决方案,平台自定义,中英切换

    智能语音识别照明方案引入NRK3502芯片,支持平台自定义,离线控制,中英双语切换。NRK3502具备高性能和灵活自定义能力,可推动智能照明革新,控制其他智能设备,为国际用户提供全方位智能生活体验。
    的头像 发表于 01-10 13:23 801次阅读
    智能语音识别照明解决方案,平台<b class='flag-5'>自定义</b>,中英切换

    think-cell;自定义think-cell(一)

    本章介绍如何自定义 think-cell,即如何更改默认颜色和其他默认属性;这是通过 think-cell 的样式文件完成的,这些文件将在前四个部分中进行讨论。 第五部分 C.5 设置默认议程幻灯片
    的头像 发表于 01-08 11:31 1243次阅读
    think-cell;<b class='flag-5'>自定义</b>think-cell(一)