本文分享自华为云社区《Ascend C 自定义算子 Kernel Launch调用入门》,作者: jackwangcumt。

1 Kernel Launch概述

根据官方说明文档的介绍,Ascend C对外开放核函数的基础调用(Kernel Launch)方式,是为了简化Ascend C 自定义算子的开发流程,提供更易用的调试调优功能。当开发者完成算子核函数的开发和Tiling实现后,即可通过AscendCL运行时接口,完成算子的调用并实现自己的推理应用;同时提供简易的kernel开发工程,开发者仅需提供kernel侧实现,基于工程框架可以快速实现Kernel Launch。本文实验前提是完成了《Ascend C 自定义PRelu算子》博文的相关算子开发工程。网址为:https://bbs.huaweicloud.com/blogs/425244 。请注意:

  • 8.0.RC1.alpha002 当前版本,Kernel Launch开放式编程为试用特性,不支持应用于商用产品中。
  • 8.0.RC1.alpha002当前版本暂不支持获取用户workspace特性。

2 Kernel Launch调用方式

ACLRT_LAUNCH_KERNEL调用方式对内核调用符方式进行了功能加强,核函数的调用是异步的,调用接口的使用方法如下:

ACLRT_LAUNCH_KERNEL(kernel_name)(blockDim, stream, argument list);
  • kernel_name:算子核函数的名称。
  • blockDim:规定了核函数将会在几个核上执行。每个执行该核函数的核会被分配一个逻辑ID,即block_idx,可以在核函数的实现中调用GetBlockIdx来获取block_idx。
  • stream,类型为aclrtStream,stream用于维护一些异步操作的执行顺序,确保按照应用程序中的代码调用顺序在Device上执行。
  • argument list:参数列表,与核函数的参数列表保持一致。

为帮助开发者快速的完成算子的Kernel Launch调试,官方提供了简易的算子工程,我们可以基于该算子工程中的样例代码和工程框架进行算子开发。算子工程支持的如下:

  • 该工程支持调试功能,如PRINTF功能、DumpTensor
  • 工程编译生成的应用程序,可通过msprof命令行方式采集和解析性能数据。

可以参考工程样例:https://gitee.com/ascend/samples/blob/master/operator/AddCustomSample/KernelLaunch/AddKernelInvocationTilingNeo ,其目录结构如下所示:

AddKernelInvocationNeo
|-- cmake // CMake编译文件
|-- scripts
| ├── gen_data.py // 输入数据和真值数据生成脚本文件
| ├── verify_result.py // 验证输出数据和真值数据是否一致的验证脚本
|-- CMakeLists.txt // CMake编译配置文件
|-- add_custom.cpp // 矢量算子kernel实现
|-- data_utils.h // 数据读入写出函数
|-- main.cpp // 主函数,调用算子的应用程序,含CPU域及NPU域调用
|-- run.sh // 编译运行算子的脚本

基于该算子工程,开发者进行算子开发的步骤如下:

  • 完成算子kernel侧实现。
  • 编写算子调用应用程序main.cpp。
  • 编写CMake编译配置文件CMakeLists.txt。

  • 根据实际需要修改输入数据和真值数据生成脚本文件gen_data.py和验证输出数据和真值数据是否一致的验证脚本verify_result.py。
  • 根据实际需要修改编译运行算子的脚本run.sh并执行该脚本,完成算子的编译运行和结果验证。

3 Kernel Launch实现

在PReluSample目录下新建一个目录KernelLaunch,用于存放Kernel Launch调用方式的工程代码,我这里参考官方的https://gitee.com/ascend/samples/tree/master/operator/LeakyReluCustomSample/KernelLaunch/

LeakyReluKernelInvocation样例工程,并修改了相关参数,p_relu_custom.cpp 代码如下所示:

#include "kernel_operator.h"
using namespace AscendC; constexpr int32_t BUFFER_NUM = 2;
constexpr int32_t TOTAL_LENGTH = 8 * 200 * 1024;
constexpr int32_t TILE_NUM = 32;
constexpr float alpha = 0.002; class KernelPRelu {
public:
__aicore__ inline KernelPRelu() {}
__aicore__ inline void Init(GM_ADDR x, GM_ADDR y, uint32_t totalLength, uint32_t tileNum, float alpha)
{
PRINTF("[npu debug] >>> GetBlockNum() %d", GetBlockNum());
ASSERT(GetBlockNum() != 0 && "block dim can not be zero!");
this->blockLength = totalLength / GetBlockNum();
this->tileNum = tileNum;
this->alpha = static_cast<float>(alpha);
ASSERT(tileNum != 0 && "tile num can not be zero!");
this->tileLength = this->blockLength / tileNum / BUFFER_NUM; // get start index for current core, core parallel
xGm.SetGlobalBuffer((__gm__ float*)x + this->blockLength * GetBlockIdx(), this->blockLength);
yGm.SetGlobalBuffer((__gm__ float*)y + this->blockLength * GetBlockIdx(), this->blockLength);
// pipe alloc memory to queue, the unit is Bytes
pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileLength * sizeof(float));
pipe.InitBuffer(outQueueY, BUFFER_NUM, this->tileLength * sizeof(float));
pipe.InitBuffer(tmpBuffer1, this->tileLength * sizeof(float));
//pipe.InitBuffer(tmpBuffer2, this->tileLength * sizeof(float));
}
__aicore__ inline void Process()
{
// loop count need to be doubled, due to double buffer
int32_t loopCount = this->tileNum * BUFFER_NUM;
// tiling strategy, pipeline parallel
for (int32_t i = 0; i < loopCount; i++) {
CopyIn(i);
Compute(i);
CopyOut(i);
}
} private:
__aicore__ inline void CopyIn(int32_t progress)
{
// alloc tensor from queue memory
LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
// copy progress_th tile from global tensor to local tensor
DataCopy(xLocal, xGm[progress * this->tileLength], this->tileLength);
// enque input tensors to VECIN queue
inQueueX.EnQue(xLocal);
}
__aicore__ inline void Compute(int32_t progress)
{
// deque input tensors from VECIN queue
LocalTensor<float> xLocal = inQueueX.DeQue<float>();
LocalTensor<float> yLocal = outQueueY.AllocTensor<float>();
LocalTensor<float> tmpTensor1 = tmpBuffer1.Get<float>();
float inputVal = 0.0;
Maxs(tmpTensor1, xLocal, inputVal, this->tileLength); // x >= 0 --> x
// x < 0
Mins(xLocal, xLocal, inputVal, this->tileLength);
Muls(xLocal, xLocal, this->alpha, this->tileLength);
Add(yLocal, xLocal, tmpTensor1, this->tileLength);
outQueueY.EnQue<float>(yLocal);
// free input tensors for reuse
inQueueX.FreeTensor(xLocal);
}
__aicore__ inline void CopyOut(int32_t progress)
{
// deque output tensor from VECOUT queue
LocalTensor<float> yLocal = outQueueY.DeQue<float>();
// copy progress_th tile from local tensor to global tensor
DataCopy(yGm[progress * this->tileLength], yLocal, this->tileLength);
// free output tensor for reuse
outQueueY.FreeTensor(yLocal);
} private:
TPipe pipe;
TBuf<QuePosition::VECCALC> tmpBuffer1;
//TBuf<QuePosition::VECCALC> tmpBuffer1, tmpBuffer2;
// create queues for input, in this case depth is equal to buffer num
TQue<QuePosition::VECIN, BUFFER_NUM> inQueueX;
// create queue for output, in this case depth is equal to buffer num
TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueY;
GlobalTensor<float> xGm, yGm;
uint32_t blockLength;
uint32_t tileNum;
uint32_t tileLength;
float alpha;
};
extern "C" __global__ __aicore__ void p_relu_custom(GM_ADDR x, GM_ADDR y) {
//GET_TILING_DATA(tiling_data, tiling);
// TODO: user kernel impl
KernelPRelu op;
op.Init(x, y, TOTAL_LENGTH, TILE_NUM, alpha);
op.Process();
} #ifndef __CCE_KT_TEST__
// call of kernel function
void p_relu_custom_do(uint32_t blockDim, void* l2ctrl, void* stream, uint8_t* x, uint8_t* y)
{
p_relu_custom<<<blockDim, l2ctrl, stream>>>(x, y);
}
#endif

main.cpp 代码如下所示 :

/*
* Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
* This file constains code of cpu debug and npu code.We read data from bin file
* and write result to file.
*/
#include "data_utils.h"
#ifndef __CCE_KT_TEST__
#include "acl/acl.h"
extern void p_relu_custom_do(uint32_t coreDim, void* l2ctrl, void* stream, uint8_t* x, uint8_t* y);
#else
#include "tikicpulib.h"
extern "C" __global__ __aicore__ void p_relu_custom(GM_ADDR x, GM_ADDR y);
#endif int32_t main(int32_t argc, char* argv[])
{
uint32_t blockDim = 8;
size_t inputByteSize = 8 * 200 * 1024 * sizeof(float);
size_t outputByteSize = 8 * 200 * 1024 * sizeof(float); #ifdef __CCE_KT_TEST__
// CPU
uint8_t* x = (uint8_t*)AscendC::GmAlloc(inputByteSize);
uint8_t* y = (uint8_t*)AscendC::GmAlloc(outputByteSize);
printf("[cpu debug]>>> inputByteSize: %d\n", inputByteSize); ReadFile("./input/input_x.bin", inputByteSize, x, inputByteSize);
AscendC::SetKernelMode(KernelMode::AIV_MODE);
ICPU_RUN_KF(p_relu_custom, blockDim, x, y); // use this macro for cpu debug
WriteFile("./output/output_y.bin", y, outputByteSize);
AscendC::GmFree((void *)x);
AscendC::GmFree((void *)y); #else
// NPU
//CHECK_ACL(aclInit(nullptr));
CHECK_ACL(aclInit("./acl.json"));
aclrtContext context;
int32_t deviceId = 0;
CHECK_ACL(aclrtSetDevice(deviceId));
CHECK_ACL(aclrtCreateContext(&context, deviceId));
aclrtStream stream = nullptr;
CHECK_ACL(aclrtCreateStream(&stream)); uint8_t *xHost, *yHost;
uint8_t *xDevice, *yDevice;
CHECK_ACL(aclrtMallocHost((void**)(&xHost), inputByteSize));
CHECK_ACL(aclrtMallocHost((void**)(&yHost), outputByteSize));
CHECK_ACL(aclrtMalloc((void**)&xDevice, inputByteSize, ACL_MEM_MALLOC_HUGE_FIRST));
CHECK_ACL(aclrtMalloc((void**)&yDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST)); ReadFile("./input/input_x.bin", inputByteSize, xHost, inputByteSize);
CHECK_ACL(aclrtMemcpy(xDevice, inputByteSize, xHost, inputByteSize, ACL_MEMCPY_HOST_TO_DEVICE)); p_relu_custom_do(blockDim, nullptr, stream, xDevice, yDevice);
CHECK_ACL(aclrtSynchronizeStream(stream)); CHECK_ACL(aclrtMemcpy(yHost, outputByteSize, yDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST));
WriteFile("./output/output_y.bin", yHost, outputByteSize); CHECK_ACL(aclrtFree(xDevice));
CHECK_ACL(aclrtFree(yDevice));
CHECK_ACL(aclrtFreeHost(xHost));
CHECK_ACL(aclrtFreeHost(yHost)); CHECK_ACL(aclrtDestroyStream(stream));
CHECK_ACL(aclrtDestroyContext(context));
CHECK_ACL(aclrtResetDevice(deviceId));
CHECK_ACL(aclFinalize());
#endif
return 0;
}

执行如下代码进行NPU上板调试和CPU调试:

#npu
bash run.sh Ascend310P1 npu_onboard
# cpu
bash run.sh Ascend310P1 cpu

点击关注,第一时间了解华为云新鲜技术~

Ascend C 自定义算子 Kernel Launch调用入门的更多相关文章

  1. Sqlserver如何递归查询层级数据将父级字段和本级某个字段合并?如何自定义用户函数并调用?

    开门见山,首先说下遇到的问题:前期系统地区字典表中,每个省市县只存了本级名称,没存完整的字段.如:肥西县隶属安徽省合肥市,表中就存了一个肥西县.现有需求需要将完整字段显示,由于系统已在线上运营,无法做 ...

  2. Dynamics 365 CE的插件/自定义工作流活动中调用Web API示例代码

    微软动态CRM专家罗勇 ,回复325或者20190428可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! 现在Web API越来越流行,有时候为了程序更加健壮,需要在插件 ...

  3. 腾讯地图 API 调用入门

    本文仅为腾讯地图 API 调用入门,如需进阶学习,请在腾讯位置服务网站上进行学习. 登陆网址 https://lbs.qq.com/ 点击右上角的登陆按钮,需要进行注册按照流程进行就好. 完成之后,选 ...

  4. advancedsearch.php织梦高级自定义模型字段无法调用解决方案

    advancedsearch.php织梦dedecms 高级自定义模型字段无法调用解决方案 ,具体步骤如下: 1  打开修改puls/advancedsearch.php文件,找到复制代码(不同版本可 ...

  5. 利用jQuery扩展接口为jQuery框架定义了两个自定义函数,然后调用这两个函数

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. Part 7:自定义admin站点--Django从入门到精通系列教程

    该系列教程系个人原创,并完整发布在个人官网刘江的博客和教程 所有转载本文者,需在顶部显著位置注明原作者及www.liujiangblog.com官网地址. Python及Django学习QQ群:453 ...

  7. JSP自定义标签之简单标签入门

    在sun官方文档上有下面这样一段话. 官方文档声明 public interface SimpleTag extends JspTag Interface for defining Simple Ta ...

  8. PowerShell自定义函数定义及调用

    PowerShell是一种命令集,也有自己的语法定义及函数.本文主要介绍如何自定义powershell函数及如何调用,当初在写PowerShell自定义函数的时候查阅了很多资料都没找到如何调用自定义函 ...

  9. Jmeter自定义编写Java代码调用socket通信

    一.前言 最近需要测试一款手机游戏的性能,找不到啥录制脚本的工具,然后,另外想办法.性能测试实际上就是对服务器的承载能力的测试,和各种类型的手机客户端没有啥多大关系,手机再好,服务器负载不了,也不能够 ...

  10. Django——自定义分页(可调用)

    1.view from django.shortcuts import render,HttpResponse # Create your views here. from app01.models ...

随机推荐

  1. 深入理解String

    深入理解String String是Java中的一个类,是一个引用类型,用于表示字符串.它是不可变的(immutable),即一旦创建,其值就不能被修改.任何对String对象的修改操作都会创建一个新 ...

  2. 第一百一十三篇: JS数组Array(二)数组方法 栈、队列、排序

    好家伙,    在上一篇中,我们知道了, JS的数组中每个槽位可以存储任意类型的数据 那么,我们能通过数组去模仿某些数据结构吗? 答案是肯定的 1.栈方法 ECMAScript 给数组提供几个方法,让 ...

  3. 【Azure 服务总线】向服务总线发送消息时,返回错误代码Error code : 50009

    问题描述 使用Java SDK向服务总线(Service Bus)发送消息时,返回这个错误: org.springframework.jms.UncategorizedJmsException: Un ...

  4. 【Azure 应用服务】App Service与Application Gateway组合使用时发生的域名跳转问题如何解决呢?

    问题描述 为App Service配置了应用服务网关(Application Gateway),并且为Application Gateway配置了自定义域名,通过浏览器访问时,出现域名跳转问题,由自定 ...

  5. 基于 Nebula Graph 构建图学习能力

    本文首发于 Nebula Graph Community 公众号 经常看技术文章的小伙伴可能会留意到除了正在阅读的那篇文章,在文章页面的正文下方或者右侧区域会有若干同主题.同作者的文章等你阅读:经常逛 ...

  6. 四: Mysql用户管理

    # 用户与权限管理 MySQL用户可以分为普通用户和root用户, root用户是超级管理员,拥有所有权限,包括创建用户.删除用户和修改用户的密码等管理权限:普通用户只拥有被授予的各种权限. MySQ ...

  7. 10、mysql的锁

    锁概述 锁是计算机协调多个进程或线程并发访问某一资源的机制(避免争抢). 在数据库中,除传统的计算资源(如 CPU.RAM.I/O 等)的争用以外,数据也是一种供许多用户共享的资源.如何保证数据并发访 ...

  8. Abp.Zero 手机号免密登录验证与号码绑定功能的实现(二):改造Abp默认实现

    接下来我们重写原Abp的部分实现,来驳接手机号相关业务. 改造User类 重写PhoneNumber使得电话号码为必填项,和中国大陆手机号11位长度 public new const int MaxP ...

  9. SourceTree 摘樱桃 === 遴选 [不要使用这个功能!!不要使用!不要使用!]

    SourceTree 摘樱桃 === 遴选 不要使用摘樱桃!!不要使用!不要使用! 我找了一个文本的git,进行的测试,发现很不好用,文档我又恢复过来了,因为就改了几个字,代码的话,会造成 不可挽回的 ...

  10. pod的拉取和重启策略

    在Kubernetes中,Pod的拉取策略和重启策略可以通过YAML配置文件来定义. Pod的拉取策略 Pod的拉取策略指的是Kubernetes在创建或重启Pod时,如何获取Pod所需的容器镜像.这 ...