Merged
add abs and muls example #1459
add abs and muls example #1459
Merged
wang-zijiuAdd on Apr 7
Total: 23 files changed+994-27
@@ -11,6 +11,14 @@
11 11 
12cmake_minimum_required(VERSION 3.16)12cmake_minimum_required(VERSION 3.16)
13 13 
14+if(DEFINED RUN_MODE)
15+ set(CMAKE_ASC_RUN_MODE ${RUN_MODE} CACHE STRING "Alias of RUN_MODE")
16+endif()
17+ 
18+if(DEFINED NPU_ARCH)
19+ set(CMAKE_ASC_ARCHITECTURES ${NPU_ARCH} CACHE STRING "Alias of NPU_ARCH")
20+endif()
21+ 
14find_package(ASC REQUIRED)22find_package(ASC REQUIRED)
15 23 
16project(kernel_samples LANGUAGES ASC CXX)24project(kernel_samples LANGUAGES ASC CXX)
@@ -32,6 +40,7 @@ target_link_libraries(demo PRIVATE
32# 说明:40# 说明:
33# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。41# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。
34# ======================================================================================42# ======================================================================================
43+set(NPU_ARCH "dav-3510" CACHE STRING "NPU ARCH, e.g. dav-3510")
35target_compile_options(demo PRIVATE44target_compile_options(demo PRIVATE
36- $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=dav-3510>45+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${NPU_ARCH}>
37)46)
@@ -91,9 +91,29 @@
91- 样例执行91- 样例执行
92 ```bash92 ```bash
93 mkdir -p build && cd build; # 创建并进入build目录93 mkdir -p build && cd build; # 创建并进入build目录
94- cmake ..;make -j; # 编译工程94+ cmake -DNPU_ARCH=dav-3510 ..;make -j; # 编译工程
95 ./demo # 执行编译生成的可执行程序,执行样例95 ./demo # 执行编译生成的可执行程序,执行样例
96 ```96 ```
97+ 
98+ 使用 CPU调试 或 NPU仿真 模式时,添加 `-DRUN_MODE=cpu` 或 `-DRUN_MODE=sim` 参数即可。
99+ 
100+ 示例如下:
101+ ```bash
102+ cmake -DRUN_MODE=cpu -DNPU_ARCH=dav-3510 ..;make -j; # cpu调试模式
103+ cmake -DRUN_MODE=sim -DNPU_ARCH=dav-3510 ..;make -j; # NPU仿真模式
104+ ```
105+ 
106+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
107+ 
108+- 编译选项说明
109+ 
110+ | 选项 | 可选值 | 说明 |
111+ |------|--------|------|
112+ | `RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真 |
113+ | `NPU_ARCH` | `dav-3510`(默认) | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
114+ 
115+- 执行结果
116+ 
97 执行结果如下,说明精度对比成功。117 执行结果如下,说明精度对比成功。
98 ```bash118 ```bash
99 test pass!119 test pass!
@@ -15,6 +15,10 @@
15#include "acl/acl.h"15#include "acl/acl.h"
16#include "kernel_operator.h"16#include "kernel_operator.h"
17 17 
18+#ifdef ASCENDC_CPU_DEBUG
19+#include "cpu_debug_launch.h"
20+#endif
21+ 
18template <typename T>22template <typename T>
19__simd_vf__ inline void CopySucceVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr, uint16_t oneRepeatSize, uint32_t repeatTimes,23__simd_vf__ inline void CopySucceVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr, uint16_t oneRepeatSize, uint32_t repeatTimes,
20 uint32_t count)24 uint32_t count)
@@ -163,21 +167,18 @@ std::vector<float> ld_st_reg_align(std::vector<float>& input)
163 aclrtCreateStream(&stream);167 aclrtCreateStream(&stream);
164 size_t aInputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);168 size_t aInputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);
165 size_t outputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);169 size_t outputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);
166- uint8_t *xHost, *yHost;170+ uint8_t *yHost;
167 uint8_t *xDevice, *yDevice;171 uint8_t *xDevice, *yDevice;
168- aclrtMallocHost((void**)(&xHost), aInputByteSize);
169 aclrtMallocHost((void**)(&yHost), outputByteSize);172 aclrtMallocHost((void**)(&yHost), outputByteSize);
170 aclrtMalloc((void**)&xDevice, aInputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);173 aclrtMalloc((void**)&xDevice, aInputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
171 aclrtMalloc((void**)&yDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);174 aclrtMalloc((void**)&yDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
172- xHost = reinterpret_cast<uint8_t *>(input.data());175+ aclrtMemcpy(xDevice, aInputByteSize, input.data(), aInputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
173- aclrtMemcpy(xDevice, aInputByteSize, xHost, aInputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
174 ld_st_reg_align_kernel<<<numBlocks, nullptr, stream>>>(xDevice, yDevice);176 ld_st_reg_align_kernel<<<numBlocks, nullptr, stream>>>(xDevice, yDevice);
175 aclrtSynchronizeStream(stream);177 aclrtSynchronizeStream(stream);
176 aclrtMemcpy(yHost, outputByteSize, yDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);178 aclrtMemcpy(yHost, outputByteSize, yDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);
177 std::vector<float> output((float*)yHost, (float*)(yHost + outputByteSize));179 std::vector<float> output((float*)yHost, (float*)(yHost + outputByteSize));
178 aclrtFree(xDevice);180 aclrtFree(xDevice);
179 aclrtFree(yDevice);181 aclrtFree(yDevice);
180- aclrtFreeHost(xHost);
181 aclrtFreeHost(yHost);182 aclrtFreeHost(yHost);
182 aclrtDestroyStream(stream);183 aclrtDestroyStream(stream);
183 aclrtResetDevice(deviceId);184 aclrtResetDevice(deviceId);
@@ -206,7 +207,6 @@ uint32_t verify_result(std::vector<float>& output, std::vector<float>& golden)
206 std::cout << "test fail!" << std::endl;207 std::cout << "test fail!" << std::endl;
207 return 1;208 return 1;
208 }209 }
209- return 0;
210}210}
211 211 
212int32_t main(int32_t argc, char* argv[])212int32_t main(int32_t argc, char* argv[])
@@ -11,6 +11,14 @@
11 11 
12cmake_minimum_required(VERSION 3.16)12cmake_minimum_required(VERSION 3.16)
13 13 
14+if(DEFINED RUN_MODE)
15+ set(CMAKE_ASC_RUN_MODE ${RUN_MODE} CACHE STRING "Alias of RUN_MODE")
16+endif()
17+ 
18+if(DEFINED NPU_ARCH)
19+ set(CMAKE_ASC_ARCHITECTURES ${NPU_ARCH} CACHE STRING "Alias of NPU_ARCH")
20+endif()
21+ 
14find_package(ASC REQUIRED)22find_package(ASC REQUIRED)
15 23 
16project(kernel_samples LANGUAGES ASC CXX)24project(kernel_samples LANGUAGES ASC CXX)
@@ -25,6 +33,7 @@ add_executable(demo
25# 说明:33# 说明:
26# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。34# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。
27# ======================================================================================35# ======================================================================================
36+set(NPU_ARCH "dav-3510" CACHE STRING "NPU ARCH, e.g. dav-3510")
28target_compile_options(demo PRIVATE37target_compile_options(demo PRIVATE
29- $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=dav-3510>38+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${NPU_ARCH}>
30)39)
@@ -67,10 +67,30 @@
67- 样例执行67- 样例执行
68 ```bash68 ```bash
69 mkdir -p build && cd build; # 创建并进入build目录69 mkdir -p build && cd build; # 创建并进入build目录
70- cmake ..;make -j; # 编译工程70+ cmake -DNPU_ARCH=dav-3510 ..;make -j; # 编译工程(默认npu模式)
71 python3 ../scripts/gen_data.py # 生成测试输入数据71 python3 ../scripts/gen_data.py # 生成测试输入数据
72 ./demo # 执行编译生成的可执行程序,执行样例72 ./demo # 执行编译生成的可执行程序,执行样例
73 ```73 ```
74+ 
75+ 使用 CPU调试 或 NPU仿真 模式时,添加 `-DRUN_MODE=cpu` 或 `-DRUN_MODE=sim` 参数即可。
76+ 
77+ 示例如下:
78+ ```bash
79+ cmake -DRUN_MODE=cpu -DNPU_ARCH=dav-3510 ..;make -j; # cpu调试模式
80+ cmake -DRUN_MODE=sim -DNPU_ARCH=dav-3510 ..;make -j; # NPU仿真模式
81+ ```
82+ 
83+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
84+ 
85+- 编译选项说明
86+ 
87+ | 选项 | 可选值 | 说明 |
88+ |------|--------|------|
89+ | `RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真 |
90+ | `NPU_ARCH` | `dav-3510`(默认) | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
91+ 
92+- 执行结果
93+ 
74 执行结果如下,说明精度对比成功。94 执行结果如下,说明精度对比成功。
75 ```bash95 ```bash
76 test pass!96 test pass!
@@ -13,6 +13,10 @@
13#include "kernel_operator.h"13#include "kernel_operator.h"
14#include "data_utils.h"14#include "data_utils.h"
15 15 
16+#ifdef ASCENDC_CPU_DEBUG
17+#include "cpu_debug_launch.h"
18+#endif
19+ 
16template <typename T>20template <typename T>
17__simd_vf__ inline void CopyVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr, uint16_t oneRepeatSize)21__simd_vf__ inline void CopyVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr, uint16_t oneRepeatSize)
18{22{
@@ -11,6 +11,14 @@
11 11 
12cmake_minimum_required(VERSION 3.16)12cmake_minimum_required(VERSION 3.16)
13 13 
14+if(DEFINED RUN_MODE)
15+ set(CMAKE_ASC_RUN_MODE ${RUN_MODE} CACHE STRING "Alias of RUN_MODE")
16+endif()
17+ 
18+if(DEFINED NPU_ARCH)
19+ set(CMAKE_ASC_ARCHITECTURES ${NPU_ARCH} CACHE STRING "Alias of NPU_ARCH")
20+endif()
21+ 
14find_package(ASC REQUIRED)22find_package(ASC REQUIRED)
15 23 
16project(kernel_samples LANGUAGES ASC CXX)24project(kernel_samples LANGUAGES ASC CXX)
@@ -32,6 +40,7 @@ target_link_libraries(demo PRIVATE
32# 说明:40# 说明:
33# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。41# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。
34# ======================================================================================42# ======================================================================================
43+set(NPU_ARCH "dav-3510" CACHE STRING "NPU ARCH, e.g. dav-3510")
35target_compile_options(demo PRIVATE44target_compile_options(demo PRIVATE
36- $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=dav-3510>45+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${NPU_ARCH}>
37)46)
@@ -57,9 +57,29 @@
57- 样例执行57- 样例执行
58 ```bash58 ```bash
59 mkdir -p build && cd build; # 创建并进入build目录59 mkdir -p build && cd build; # 创建并进入build目录
60- cmake ..;make -j; # 编译工程60+ cmake -DNPU_ARCH=dav-3510 ..;make -j; # 编译工程
61 ./demo # 执行编译生成的可执行程序,执行样例61 ./demo # 执行编译生成的可执行程序,执行样例
62 ```62 ```
63+ 
64+ 使用 CPU调试 或 NPU仿真 模式时,添加 `-DRUN_MODE=cpu` 或 `-DRUN_MODE=sim` 参数即可。
65+ 
66+ 示例如下:
67+ ```bash
68+ cmake -DRUN_MODE=cpu -DNPU_ARCH=dav-3510 ..;make -j; # cpu调试模式
69+ cmake -DRUN_MODE=sim -DNPU_ARCH=dav-3510 ..;make -j; # NPU仿真模式
70+ ```
71+ 
72+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
73+ 
74+- 编译选项说明
75+ 
76+ | 选项 | 可选值 | 说明 |
77+ |------|--------|------|
78+ | `RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真 |
79+ | `NPU_ARCH` | `dav-3510`(默认) | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
80+ 
81+- 执行结果
82+ 
63 执行结果如下,说明精度对比成功。83 执行结果如下,说明精度对比成功。
64 ```bash84 ```bash
65 test pass!85 test pass!
@@ -15,6 +15,10 @@
15#include "acl/acl.h"15#include "acl/acl.h"
16#include "kernel_operator.h"16#include "kernel_operator.h"
17 17 
18+#ifdef ASCENDC_CPU_DEBUG
19+#include "cpu_debug_launch.h"
20+#endif
21+ 
18template <typename T>22template <typename T>
19__simd_vf__ inline void CopyVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr, uint16_t oneRepeatSize)23__simd_vf__ inline void CopyVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr, uint16_t oneRepeatSize)
20{24{
@@ -95,21 +99,18 @@ std::vector<float> ld_st_reg_unalign(std::vector<float>& input)
95 aclrtCreateStream(&stream);99 aclrtCreateStream(&stream);
96 size_t aInputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);100 size_t aInputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);
97 size_t outputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);101 size_t outputByteSize = static_cast<size_t>(1) * input_length * sizeof(float);
98- uint8_t *xHost, *yHost;102+ uint8_t *yHost;
99 uint8_t *xDevice, *yDevice;103 uint8_t *xDevice, *yDevice;
100- aclrtMallocHost((void**)(&xHost), aInputByteSize);
101 aclrtMallocHost((void**)(&yHost), outputByteSize);104 aclrtMallocHost((void**)(&yHost), outputByteSize);
102 aclrtMalloc((void**)&xDevice, aInputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);105 aclrtMalloc((void**)&xDevice, aInputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
103 aclrtMalloc((void**)&yDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);106 aclrtMalloc((void**)&yDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
104- xHost = reinterpret_cast<uint8_t *>(input.data());107+ aclrtMemcpy(xDevice, aInputByteSize, input.data(), aInputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
105- aclrtMemcpy(xDevice, aInputByteSize, xHost, aInputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
106 ld_st_reg_unalign_kernel<<<numBlocks, nullptr, stream>>>(xDevice, yDevice);108 ld_st_reg_unalign_kernel<<<numBlocks, nullptr, stream>>>(xDevice, yDevice);
107 aclrtSynchronizeStream(stream);109 aclrtSynchronizeStream(stream);
108 aclrtMemcpy(yHost, outputByteSize, yDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);110 aclrtMemcpy(yHost, outputByteSize, yDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);
109 std::vector<float> output((float*)yHost, (float*)(yHost + outputByteSize));111 std::vector<float> output((float*)yHost, (float*)(yHost + outputByteSize));
110 aclrtFree(xDevice);112 aclrtFree(xDevice);
111 aclrtFree(yDevice);113 aclrtFree(yDevice);
112- aclrtFreeHost(xHost);
113 aclrtFreeHost(yHost);114 aclrtFreeHost(yHost);
114 aclrtDestroyStream(stream);115 aclrtDestroyStream(stream);
115 aclrtResetDevice(deviceId);116 aclrtResetDevice(deviceId);
@@ -138,7 +139,6 @@ uint32_t verify_result(std::vector<float>& output, std::vector<float>& golden)
138 std::cout << "test fail!" << std::endl;139 std::cout << "test fail!" << std::endl;
139 return 1;140 return 1;
140 }141 }
141- return 0;
142}142}
143 143 
144int32_t main(int32_t argc, char* argv[])144int32_t main(int32_t argc, char* argv[])
@@ -0,0 +1,48 @@
1+# ----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# ----------------------------------------------------------------------------------------------------------
10+ 
11+ 
12+cmake_minimum_required(VERSION 3.16)
13+ 
14+if(DEFINED RUN_MODE)
15+ set(CMAKE_ASC_RUN_MODE ${RUN_MODE} CACHE STRING "Alias of RUN_MODE")
16+endif()
17+ 
18+if(DEFINED NPU_ARCH)
19+ set(CMAKE_ASC_ARCHITECTURES ${NPU_ARCH} CACHE STRING "Alias of NPU_ARCH")
20+endif()
21+ 
22+find_package(ASC REQUIRED)
23+ 
24+project(kernel_samples LANGUAGES ASC CXX)
25+ 
26+add_executable(demo
27+ abs.asc
28+)
29+ 
30+target_link_libraries(demo PRIVATE
31+ tiling_api
32+ register
33+ platform
34+ m
35+)
36+ 
37+# ======================================================================================
38+# NPU 编译选项配置
39+#
40+# 说明:
41+# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。
42+# ======================================================================================
43+set(NPU_ARCH "dav-2201" CACHE STRING "NPU ARCH, e.g. dav-3510")
44+target_compile_options(demo PRIVATE
45+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${NPU_ARCH}>
46+ $<$<COMPILE_LANGUAGE:ASC>:--cce-simd-vf-fusion=false>
47+)
48+ 
@@ -0,0 +1,90 @@
1+# abs样例
2+ 
3+## 概述
4+本样例基于RegBase编程范式实现Abs运算,主要调用Abs接口。
5+- Relu/Exp/Sqrt/Ln/Log/Log2/Log10/Neg接口皆可参考该样例
6+ 
7+## 支持的产品
8+- Ascend 950PR/Ascend 950DT
9+ 
10+## 目录结构介绍
11+```
12+├── abs
13+│ ├── scripts
14+│ │ ├── gen_data.py // 输入数据和真值数据生成脚本
15+│ ├── CMakeLists.txt // 编译工程文件
16+│ ├── data_utils.h // 数据读入写出函数
17+│ ├── abs.asc // AscendC样例实现 & 调用样例
18+│ └── README.md // 样例介绍
19+```
20+ 
21+## 样例描述
22+- 样例功能:
23+ 计算向量中每个元素的绝对值,向量数据量为256,数据类型为float。
24+- 样例规格:
25+ <table>
26+ <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="3" align="center">AIV样例</td></tr>
27+ </tr>
28+ <tr><td rowspan="2" align="center">样例输入</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td></tr>
29+ <tr><td align="center">x</td><td align="center">[1, 256]</td><td align="center">float</td></tr>
30+ </tr>
31+ </tr>
32+ <tr><td rowspan="1" align="center">样例输出</td><td align="center">y</td><td align="center">[1, 256]</td><td align="center">float</td></tr>
33+ </tr>
34+ <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">abs</td></tr>
35+ </table>
36+- 样例实现:
37+ AbsVF函数内调用Abs接口进行计算,结果写回UB
38+ - 调用实现
39+ 使用内核调用符<<<>>>调用核函数。
40+ 
41+## 编译运行
42+在本样例根目录下执行如下步骤,编译并执行样例。
43+- 配置环境变量
44+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../../../docs/quick_start.md#prepare&install),选择对应配置环境变量的命令。
45+ - 默认路径,root用户安装CANN软件包
46+ ```bash
47+ source /usr/local/Ascend/cann/set_env.sh
48+ ```
49+ 
50+ - 默认路径,非root用户安装CANN软件包
51+ ```bash
52+ source $HOME/Ascend/cann/set_env.sh
53+ ```
54+ 
55+ - 指定路径install_path,安装CANN软件包
56+ ```bash
57+ source ${install_path}/cann/set_env.sh
58+ ```
59+ 
60+- 样例执行
61+ ```bash
62+ mkdir -p build && cd build; # 创建并进入build目录
63+ cmake -DNPU_ARCH=dav-3510 ..;make -j; # 编译工程(默认npu模式)
64+ python3 ../scripts/gen_data.py # 生成测试输入数据
65+ ./demo # 执行编译生成的可执行程序,执行样例
66+ ```
67+ 
68+ 使用 CPU调试 或 NPU仿真 模式时,添加 `-DRUN_MODE=cpu` 或 `-DRUN_MODE=sim` 参数即可。
69+ 
70+ 示例如下:
71+ ```bash
72+ cmake -DRUN_MODE=cpu -DNPU_ARCH=dav-3510 ..;make -j; # cpu调试模式
73+ cmake -DRUN_MODE=sim -DNPU_ARCH=dav-3510 ..;make -j; # NPU仿真模式
74+ ```
75+ 
76+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
77+ 
78+- 编译选项说明
79+ 
80+ | 选项 | 可选值 | 说明 |
81+ |------|--------|------|
82+ | `RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真 |
83+ | `NPU_ARCH` | `dav-3510`(默认) | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
84+ 
85+- 执行结果
86+ 
87+ 执行结果如下,说明精度对比成功。
88+ ```bash
89+ test pass!
90+ ```
@@ -0,0 +1,156 @@
1+/**
2+* Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+* CANN Open Software License Agreement Version 2.0 (the "License").
5+* Please refer to the License for details. You may not use this file except in compliance with the License.
6+* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+* See LICENSE in the root of the software repository for the full text of the License.
9+*/
10+ 
11+ 
12+#include "acl/acl.h"
13+#include "kernel_operator.h"
14+#include "data_utils.h"
15+ 
16+#ifdef ASCENDC_CPU_DEBUG
17+#include "cpu_debug_launch.h"
18+#endif
19+ 
20+template <typename T>
21+__simd_vf__ inline void AbsVF(__ubuf__ T* xAddr, __ubuf__ T* yAddr, uint32_t totalCount,
22+ uint32_t repeatTimes, uint32_t oneRepeatSize)
23+{
24+ AscendC::Reg::MaskReg mask = AscendC::Reg::CreateMask<T, AscendC::Reg::MaskPattern::ALL>();
25+ AscendC::Reg::RegTensor<T> xReg;
26+ AscendC::Reg::RegTensor<T> yReg;
27+ for (uint16_t i = 0; i < repeatTimes; ++i) {
28+ AscendC::Reg::LoadAlign(xReg, xAddr + i * oneRepeatSize);
29+ AscendC::Reg::Abs(yReg, xReg, mask);
30+ AscendC::Reg::StoreAlign(yAddr + i * oneRepeatSize, yReg, mask);
31+ }
32+}
33+ 
34+template <typename T>
35+class Kernel {
36+public:
37+ __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, uint32_t totalLength)
38+ {
39+ this->totalLength = totalLength;
40+ this->xGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(x));
41+ this->yGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(y));
42+ }
43+ __aicore__ inline void Process()
44+ {
45+ AscendC::LocalMemAllocator<AscendC::Hardware::UB> ubAllocator;
46+ AscendC::LocalTensor<T> xLocal = ubAllocator.Alloc<T, 256>();
47+ AscendC::LocalTensor<T> yLocal = ubAllocator.Alloc<T, 256>();
48+ 
49+ // CopyIn: GM -> UB
50+ AscendC::DataCopy(xLocal, xGm, totalLength);
51+ AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
52+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
53+ 
54+ // Compute: RegBase AbsVF y = |x|
55+ __ubuf__ T* xAddr = reinterpret_cast<__ubuf__ T*>(xLocal.GetPhyAddr());
56+ __ubuf__ T* yAddr = reinterpret_cast<__ubuf__ T*>(yLocal.GetPhyAddr());
57+ // 一次repeat计算的数据个数
58+ constexpr uint32_t oneRepeatSize = AscendC::GetVecLen() / sizeof(T);
59+ // 总迭代次数
60+ uint16_t repeatTimes = AscendC::CeilDivision(totalLength, oneRepeatSize);
61+ AbsVF(xAddr, yAddr, totalLength, repeatTimes, oneRepeatSize);
62+ 
63+ AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
64+ AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
65+ 
66+ // CopyOut: UB -> GM
67+ AscendC::DataCopy(yGm, yLocal, totalLength);
68+ }
69+ 
70+private:
71+ uint32_t totalLength;
72+ AscendC::GlobalTensor<T> xGm;
73+ AscendC::GlobalTensor<T> yGm;
74+};
75+ 
76+__global__ __vector__ void abs(GM_ADDR x, GM_ADDR y)
77+{
78+ uint32_t totalLength = 256;
79+ Kernel<float> kernel;
80+ kernel.Init(x, y, totalLength);
81+ kernel.Process();
82+}
83+ 
84+static bool CompareResult(const void* outputData, uint32_t outSize)
85+{
86+ void* goldenData;
87+ aclrtMallocHost((void**)(&goldenData), outSize);
88+ size_t goldenSize = outSize;
89+ bool ret = ReadFile("./output/golden.bin", goldenSize, goldenData, goldenSize);
90+ if (ret) {
91+ printf("ReadFile golden.bin success!\n");
92+ } else {
93+ printf("test failed!\n");
94+ return false;
95+ }
96+ constexpr float EPS = 1e-4;
97+ int64_t wrongNum = 0;
98+ 
99+ for (size_t i = 0; i < outSize / sizeof(float); i++) {
100+ float a = (reinterpret_cast<const float*>(outputData))[i];
101+ float b = (reinterpret_cast<const float*>(goldenData))[i];
102+ float ae = std::abs(a - b);
103+ float re = ae / std::abs(b);
104+ if (ae > EPS && re > EPS) {
105+ printf("CompareResult golden.bin failed output is %lf, golden is %lf\n", a, b);
106+ wrongNum++;
107+ }
108+ }
109+ aclrtFreeHost(goldenData);
110+ if (wrongNum != 0) {
111+ return false;
112+ } else {
113+ printf("CompareResult golden.bin success!\n");
114+ return true;
115+ }
116+}
117+ 
118+int32_t main(int32_t argc, char* argv[])
119+{
120+ uint32_t numBlocks = 1;
121+ aclInit(nullptr);
122+ int32_t deviceId = 0;
123+ aclrtSetDevice(deviceId);
124+ aclrtStream stream = nullptr;
125+ aclrtCreateStream(&stream);
126+ uint32_t totalLength = 256;
127+ size_t inputByteSize = static_cast<size_t>(1) * totalLength * sizeof(float);
128+ size_t outputByteSize = static_cast<size_t>(1) * totalLength * sizeof(float);
129+ uint8_t *xHost, *yHost;
130+ uint8_t *xDevice, *yDevice;
131+ aclrtMallocHost((void**)(&xHost), inputByteSize);
132+ aclrtMallocHost((void**)(&yHost), outputByteSize);
133+ aclrtMalloc((void**)&xDevice, inputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
134+ aclrtMalloc((void**)&yDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
135+ ReadFile("./input/input_x.bin", inputByteSize, xHost, inputByteSize);
136+ aclrtMemcpy(xDevice, inputByteSize, xHost, inputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
137+ abs<<<numBlocks, nullptr, stream>>>(xDevice, yDevice);
138+ aclrtSynchronizeStream(stream);
139+ aclrtMemcpy(yHost, outputByteSize, yDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);
140+ WriteFile("./output/output.bin", yHost, outputByteSize);
141+ bool goldenResult = true;
142+ goldenResult = CompareResult(yHost, outputByteSize);
143+ if (goldenResult) {
144+ printf("test pass!\n");
145+ } else {
146+ printf("test failed!\n");
147+ }
148+ aclrtFree(xDevice);
149+ aclrtFree(yDevice);
150+ aclrtFreeHost(xHost);
151+ aclrtFreeHost(yHost);
152+ aclrtDestroyStream(stream);
153+ aclrtResetDevice(deviceId);
154+ aclFinalize();
155+ return 0;
156+}
@@ -0,0 +1,94 @@
1+/**
2+* Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+* CANN Open Software License Agreement Version 2.0 (the "License").
5+* Please refer to the License for details. You may not use this file except in compliance with the License.
6+* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+* See LICENSE in the root of the software repository for the full text of the License.
9+*/
10+ 
11+ 
12+/* !
13+ * \file data_utils.h
14+ * \brief
15+ */
16+ 
17+#ifndef DATA_UTILS_H
18+#define DATA_UTILS_H
19+#include <fcntl.h>
20+#include <sys/stat.h>
21+#include <unistd.h>
22+#include <fstream>
23+ 
24+#define ERROR_LOG(fmt, args...) fprintf(stdout, "[ERROR] " fmt "\n", ##args)
25+ 
26+bool ReadFile(const std::string &filePath, size_t &fileSize, void *buffer, size_t bufferSize)
27+{
28+ struct stat sBuf;
29+ int fileStatus = stat(filePath.data(), &sBuf);
30+ if (fileStatus == -1) {
31+ ERROR_LOG("failed to get file");
32+ return false;
33+ }
34+ if (S_ISREG(sBuf.st_mode) == 0) {
35+ ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
36+ return false;
37+ }
38+ 
39+ std::ifstream file;
40+ file.open(filePath, std::ios::binary);
41+ if (!file.is_open()) {
42+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
43+ return false;
44+ }
45+ 
46+ std::filebuf *buf = file.rdbuf();
47+ size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
48+ if (size == 0) {
49+ ERROR_LOG("file size is 0");
50+ file.close();
51+ return false;
52+ }
53+ if (size > bufferSize) {
54+ ERROR_LOG("file size is larger than buffer size");
55+ file.close();
56+ return false;
57+ }
58+ buf->pubseekpos(0, std::ios::in);
59+ buf->sgetn(static_cast<char *>(buffer), size);
60+ fileSize = size;
61+ file.close();
62+ return true;
63+}
64+ 
65+/**
66+ * @brief Write data to file
67+ * @param [in] filePath: file path
68+ * @param [in] buffer: data to write to file
69+ * @param [in] size: size to write
70+ * @return write result
71+ */
72+bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
73+{
74+ if (buffer == nullptr) {
75+ ERROR_LOG("Write file failed. buffer is nullptr");
76+ return false;
77+ }
78+ 
79+ int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
80+ if (fd < 0) {
81+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
82+ return false;
83+ }
84+ 
85+ size_t writeSize = write(fd, buffer, size);
86+ (void)close(fd);
87+ if (writeSize != size) {
88+ ERROR_LOG("Write file Failed.");
89+ return false;
90+ }
91+ 
92+ return true;
93+}
94+#endif // DATA_UTILS_H
@@ -0,0 +1,31 @@
1+#!/usr/bin/python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
6+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
7+# CANN Open Software License Agreement Version 2.0 (the "License").
8+# Please refer to the License for details. You may not use this file except in compliance with the License.
9+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
10+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
11+# See LICENSE in the root of the software repository for the full text of the License.
12+# ----------------------------------------------------------------------------------------------------------
13+ 
14+ 
15+import os
16+import numpy as np
17+ 
18+def gen_golden_data_simple():
19+ total_length = 256
20+ data_type = np.float32
21+ # 生成一个 [1, 256] 向量,包含正负值
22+ x = np.random.uniform(-2, 2, [1, total_length]).astype(data_type)
23+ # 计算绝对值 y = |x|
24+ golden = np.abs(x)
25+ os.makedirs("input", exist_ok=True)
26+ os.makedirs("output", exist_ok=True)
27+ x.tofile('./input/input_x.bin')
28+ golden.tofile('./output/golden.bin')
29+ 
30+if __name__ == "__main__":
31+ gen_golden_data_simple()
@@ -11,6 +11,14 @@
11 11 
12cmake_minimum_required(VERSION 3.16)12cmake_minimum_required(VERSION 3.16)
13 13 
14+if(DEFINED RUN_MODE)
15+ set(CMAKE_ASC_RUN_MODE ${RUN_MODE} CACHE STRING "Alias of RUN_MODE")
16+endif()
17+ 
18+if(DEFINED NPU_ARCH)
19+ set(CMAKE_ASC_ARCHITECTURES ${NPU_ARCH} CACHE STRING "Alias of NPU_ARCH")
20+endif()
21+ 
14find_package(ASC REQUIRED)22find_package(ASC REQUIRED)
15 23 
16project(kernel_samples LANGUAGES ASC CXX)24project(kernel_samples LANGUAGES ASC CXX)
@@ -32,7 +40,8 @@ target_link_libraries(demo PRIVATE
32# 说明:40# 说明:
33# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。41# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。
34# ======================================================================================42# ======================================================================================
43+set(NPU_ARCH "dav-2201" CACHE STRING "NPU ARCH, e.g. dav-3510")
35target_compile_options(demo PRIVATE44target_compile_options(demo PRIVATE
36- $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=dav-3510>45+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${NPU_ARCH}>
37 $<$<COMPILE_LANGUAGE:ASC>:--cce-simd-vf-fusion=false>46 $<$<COMPILE_LANGUAGE:ASC>:--cce-simd-vf-fusion=false>
38)47)
@@ -2,7 +2,7 @@
2 2 
3## 概述3## 概述
4本样例基于RegBase编程范式实现Mul运算,主要调用Mul接口。4本样例基于RegBase编程范式实现Mul运算,主要调用Mul接口。
5-- Add/Exp/Sqrt/Ln/Log/Log2/Log10/Neg接口皆可参考该样例5+- Add/Sub/Div/Max/Min/Prelu接口皆可参考该样例
6 6 
7## 支持的产品7## 支持的产品
8- Ascend 950PR/Ascend 950DT8- Ascend 950PR/Ascend 950DT
@@ -14,7 +14,8 @@
14│ │ ├── gen_data.py // 输入数据和真值数据生成脚本14│ │ ├── gen_data.py // 输入数据和真值数据生成脚本
15│ ├── CMakeLists.txt // 编译工程文件15│ ├── CMakeLists.txt // 编译工程文件
16│ ├── data_utils.h // 数据读入写出函数16│ ├── data_utils.h // 数据读入写出函数
17-│ └── mul.asc // AscendC样例实现 & 调用样例17+│ ├── mul.asc // AscendC样例实现 & 调用样例
18+│ └── README.md // 样例介绍
18```19```
19 20 
20## 样例描述21## 样例描述
@@ -41,7 +42,7 @@
41## 编译运行42## 编译运行
42在本样例根目录下执行如下步骤,编译并执行样例。43在本样例根目录下执行如下步骤,编译并执行样例。
43- 配置环境变量44- 配置环境变量
44- 请根据当前环境上CANN开发套件包的[安装方式](../../../../docs/quick_start.md#prepare&install),选择对应配置环境变量的命令。45+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../../../docs/quick_start.md#prepare&install),选择对应配置环境变量的命令。
45 - 默认路径,root用户安装CANN软件包46 - 默认路径,root用户安装CANN软件包
46 ```bash47 ```bash
47 source /usr/local/Ascend/cann/set_env.sh48 source /usr/local/Ascend/cann/set_env.sh
@@ -60,11 +61,31 @@
60- 样例执行61- 样例执行
61 ```bash62 ```bash
62 mkdir -p build && cd build; # 创建并进入build目录63 mkdir -p build && cd build; # 创建并进入build目录
63- cmake ..;make -j; # 编译工程64+ cmake -DNPU_ARCH=dav-3510 ..;make -j; # 编译工程(默认npu模式)
64 python3 ../scripts/gen_data.py # 生成测试输入数据65 python3 ../scripts/gen_data.py # 生成测试输入数据
65 ./demo # 执行编译生成的可执行程序,执行样例66 ./demo # 执行编译生成的可执行程序,执行样例
66 ```67 ```
68+ 
69+ 使用 CPU调试 或 NPU仿真 模式时,添加 `-DRUN_MODE=cpu` 或 `-DRUN_MODE=sim` 参数即可。
70+ 
71+ 示例如下:
72+ ```bash
73+ cmake -DRUN_MODE=cpu -DNPU_ARCH=dav-3510 ..;make -j; # cpu调试模式
74+ cmake -DRUN_MODE=sim -DNPU_ARCH=dav-3510 ..;make -j; # NPU仿真模式
75+ ```
76+ 
77+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
78+ 
79+- 编译选项说明
80+ 
81+ | 选项 | 可选值 | 说明 |
82+ |------|--------|------|
83+ | `RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真 |
84+ | `NPU_ARCH` | `dav-3510`(默认) | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
85+ 
86+- 执行结果
87+ 
67 执行结果如下,说明精度对比成功。88 执行结果如下,说明精度对比成功。
68 ```bash89 ```bash
69 test pass!90 test pass!
70- ```91+ ```
@@ -13,6 +13,10 @@
13#include "kernel_operator.h"13#include "kernel_operator.h"
14#include "data_utils.h"14#include "data_utils.h"
15 15 
16+#ifdef ASCENDC_CPU_DEBUG
17+#include "cpu_debug_launch.h"
18+#endif
19+ 
16template <typename T>20template <typename T>
17__simd_vf__ inline void MulVF(__ubuf__ T* xAddr, __ubuf__ T* yAddr, __ubuf__ T* zAddr, uint32_t totalCount,21__simd_vf__ inline void MulVF(__ubuf__ T* xAddr, __ubuf__ T* yAddr, __ubuf__ T* zAddr, uint32_t totalCount,
18 uint32_t repeatTimes, uint32_t oneRepeatSize)22 uint32_t repeatTimes, uint32_t oneRepeatSize)
@@ -16,11 +16,11 @@ import os
16import numpy as np16import numpy as np
17 17 
18def gen_golden_data_simple():18def gen_golden_data_simple():
19- totalLength = 25619+ total_length = 256
20 data_type = np.float3220 data_type = np.float32
21 # 生成两个 [1, 256] 矩阵21 # 生成两个 [1, 256] 矩阵
22- x = np.random.uniform(1, 2, [1, totalLength]).astype(data_type)22+ x = np.random.uniform(1, 2, [1, total_length]).astype(data_type)
23- y = np.random.uniform(1, 2, [1, totalLength]).astype(data_type)23+ y = np.random.uniform(1, 2, [1, total_length]).astype(data_type)
24 # 计算逐元素乘法 z = x * y24 # 计算逐元素乘法 z = x * y
25 golden = x * y25 golden = x * y
26 os.makedirs("input", exist_ok=True)26 os.makedirs("input", exist_ok=True)
@@ -0,0 +1,47 @@
1+# ----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# ----------------------------------------------------------------------------------------------------------
10+ 
11+ 
12+cmake_minimum_required(VERSION 3.16)
13+ 
14+if(DEFINED RUN_MODE)
15+ set(CMAKE_ASC_RUN_MODE ${RUN_MODE} CACHE STRING "Alias of RUN_MODE")
16+endif()
17+ 
18+if(DEFINED NPU_ARCH)
19+ set(CMAKE_ASC_ARCHITECTURES ${NPU_ARCH} CACHE STRING "Alias of NPU_ARCH")
20+endif()
21+ 
22+find_package(ASC REQUIRED)
23+ 
24+project(kernel_samples LANGUAGES ASC CXX)
25+ 
26+add_executable(demo
27+ muls.asc
28+)
29+ 
30+target_link_libraries(demo PRIVATE
31+ tiling_api
32+ register
33+ platform
34+ m
35+)
36+ 
37+# ======================================================================================
38+# NPU 编译选项配置
39+#
40+# 说明:
41+# - 需根据实际部署的 NPU 硬件架构选择对应的 `npu-arch` 参数。
42+# ======================================================================================
43+set(NPU_ARCH "dav-2201" CACHE STRING "NPU ARCH, e.g. dav-3510")
44+target_compile_options(demo PRIVATE
45+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${NPU_ARCH}>
46+ $<$<COMPILE_LANGUAGE:ASC>:--cce-simd-vf-fusion=false>
47+)
@@ -0,0 +1,91 @@
1+# muls样例
2+ 
3+## 概述
4+本样例基于RegBase编程范式实现Muls运算,主要调用Muls接口。
5+- Adds/Maxs/Mins/LeakyRelu接口皆可参考该样例
6+ 
7+## 支持的产品
8+- Ascend 950PR/Ascend 950DT
9+ 
10+## 目录结构介绍
11+```
12+├── muls
13+│ ├── scripts
14+│ │ ├── gen_data.py // 输入数据和真值数据生成脚本
15+│ ├── CMakeLists.txt // 编译工程文件
16+│ ├── data_utils.h // 数据读入写出函数
17+│ ├── muls.asc // AscendC样例实现 & 调用样例
18+│ └── README.md // 样例介绍
19+```
20+ 
21+## 样例描述
22+- 样例功能:
23+ 对向量做标量乘法,向量数据量为256,数据类型为float,标量值为2.0。
24+- 样例规格:
25+ <table>
26+ <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="3" align="center">AIV样例</td></tr>
27+ </tr>
28+ <tr><td rowspan="3" align="center">样例输入</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td></tr>
29+ <tr><td align="center">x</td><td align="center">[1, 256]</td><td align="center">float</td></tr>
30+ <tr><td align="center">scalar</td><td align="center">[1]</td><td align="center">float</td></tr>
31+ </tr>
32+ </tr>
33+ <tr><td rowspan="1" align="center">样例输出</td><td align="center">z</td><td align="center">[1, 256]</td><td align="center">float</td></tr>
34+ </tr>
35+ <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">muls</td></tr>
36+ </table>
37+- 样例实现:
38+ MulsVF函数内调用Muls接口进行计算,结果写回UB
39+ - 调用实现
40+ 使用内核调用符<<<>>>调用核函数。
41+ 
42+## 编译运行
43+在本样例根目录下执行如下步骤,编译并执行样例。
44+- 配置环境变量
45+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../../../docs/quick_start.md#prepare&install),选择对应配置环境变量的命令。
46+ - 默认路径,root用户安装CANN软件包
47+ ```bash
48+ source /usr/local/Ascend/cann/set_env.sh
49+ ```
50+ 
51+ - 默认路径,非root用户安装CANN软件包
52+ ```bash
53+ source $HOME/Ascend/cann/set_env.sh
54+ ```
55+ 
56+ - 指定路径install_path,安装CANN软件包
57+ ```bash
58+ source ${install_path}/cann/set_env.sh
59+ ```
60+ 
61+- 样例执行
62+ ```bash
63+ mkdir -p build && cd build; # 创建并进入build目录
64+ cmake -DNPU_ARCH=dav-3510 ..;make -j; # 编译工程(默认npu模式)
65+ python3 ../scripts/gen_data.py # 生成测试输入数据
66+ ./demo # 执行编译生成的可执行程序,执行样例
67+ ```
68+ 
69+ 使用 CPU调试 或 NPU仿真 模式时,添加 `-DRUN_MODE=cpu` 或 `-DRUN_MODE=sim` 参数即可。
70+ 
71+ 示例如下:
72+ ```bash
73+ cmake -DRUN_MODE=cpu -DNPU_ARCH=dav-3510 ..;make -j; # cpu调试模式
74+ cmake -DRUN_MODE=sim -DNPU_ARCH=dav-3510 ..;make -j; # NPU仿真模式
75+ ```
76+ 
77+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
78+ 
79+- 编译选项说明
80+ 
81+ | 选项 | 可选值 | 说明 |
82+ |------|--------|------|
83+ | `RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真 |
84+ | `NPU_ARCH` | `dav-3510`(默认) | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
85+ 
86+- 执行结果
87+ 
88+ 执行结果如下,说明精度对比成功。
89+ ```bash
90+ test pass!
91+ ```
@@ -0,0 +1,94 @@
1+/**
2+* Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+* CANN Open Software License Agreement Version 2.0 (the "License").
5+* Please refer to the License for details. You may not use this file except in compliance with the License.
6+* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+* See LICENSE in the root of the software repository for the full text of the License.
9+*/
10+ 
11+ 
12+/* !
13+ * \file data_utils.h
14+ * \brief
15+ */
16+ 
17+#ifndef DATA_UTILS_H
18+#define DATA_UTILS_H
19+#include <fcntl.h>
20+#include <sys/stat.h>
21+#include <unistd.h>
22+#include <fstream>
23+ 
24+#define ERROR_LOG(fmt, args...) fprintf(stdout, "[ERROR] " fmt "\n", ##args)
25+ 
26+bool ReadFile(const std::string &filePath, size_t &fileSize, void *buffer, size_t bufferSize)
27+{
28+ struct stat sBuf;
29+ int fileStatus = stat(filePath.data(), &sBuf);
30+ if (fileStatus == -1) {
31+ ERROR_LOG("failed to get file");
32+ return false;
33+ }
34+ if (S_ISREG(sBuf.st_mode) == 0) {
35+ ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
36+ return false;
37+ }
38+ 
39+ std::ifstream file;
40+ file.open(filePath, std::ios::binary);
41+ if (!file.is_open()) {
42+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
43+ return false;
44+ }
45+ 
46+ std::filebuf *buf = file.rdbuf();
47+ size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
48+ if (size == 0) {
49+ ERROR_LOG("file size is 0");
50+ file.close();
51+ return false;
52+ }
53+ if (size > bufferSize) {
54+ ERROR_LOG("file size is larger than buffer size");
55+ file.close();
56+ return false;
57+ }
58+ buf->pubseekpos(0, std::ios::in);
59+ buf->sgetn(static_cast<char *>(buffer), size);
60+ fileSize = size;
61+ file.close();
62+ return true;
63+}
64+ 
65+/**
66+ * @brief Write data to file
67+ * @param [in] filePath: file path
68+ * @param [in] buffer: data to write to file
69+ * @param [in] size: size to write
70+ * @return write result
71+ */
72+bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
73+{
74+ if (buffer == nullptr) {
75+ ERROR_LOG("Write file failed. buffer is nullptr");
76+ return false;
77+ }
78+ 
79+ int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
80+ if (fd < 0) {
81+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
82+ return false;
83+ }
84+ 
85+ size_t writeSize = write(fd, buffer, size);
86+ (void)close(fd);
87+ if (writeSize != size) {
88+ ERROR_LOG("Write file Failed.");
89+ return false;
90+ }
91+ 
92+ return true;
93+}
94+#endif // DATA_UTILS_H
@@ -0,0 +1,159 @@
1+/**
2+* Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+* CANN Open Software License Agreement Version 2.0 (the "License").
5+* Please refer to the License for details. You may not use this file except in compliance with the License.
6+* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+* See LICENSE in the root of the software repository for the full text of the License.
9+*/
10+ 
11+ 
12+#include "acl/acl.h"
13+#include "kernel_operator.h"
14+#include "data_utils.h"
15+ 
16+#ifdef ASCENDC_CPU_DEBUG
17+#include "cpu_debug_launch.h"
18+#endif
19+ 
20+template <typename T>
21+__simd_vf__ inline void MulsVF(__ubuf__ T* xAddr, __ubuf__ T* zAddr, T scalar, uint32_t totalCount,
22+ uint32_t repeatTimes, uint32_t oneRepeatSize)
23+{
24+ AscendC::Reg::MaskReg mask = AscendC::Reg::CreateMask<T, AscendC::Reg::MaskPattern::ALL>();
25+ AscendC::Reg::RegTensor<T> xReg;
26+ AscendC::Reg::RegTensor<T> zReg;
27+ for (uint16_t i = 0; i < repeatTimes; ++i) {
28+ AscendC::Reg::LoadAlign(xReg, xAddr + i * oneRepeatSize);
29+ AscendC::Reg::Muls(zReg, xReg, scalar, mask);
30+ AscendC::Reg::StoreAlign(zAddr + i * oneRepeatSize, zReg, mask);
31+ }
32+}
33+ 
34+template <typename T>
35+class Kernel {
36+public:
37+ __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, uint32_t totalLength, T scalar)
38+ {
39+ this->totalLength = totalLength;
40+ this->scalar = scalar;
41+ this->xGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(x));
42+ this->zGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(z));
43+ }
44+ __aicore__ inline void Process()
45+ {
46+ AscendC::LocalMemAllocator<AscendC::Hardware::UB> ubAllocator;
47+ AscendC::LocalTensor<T> xLocal = ubAllocator.Alloc<T, 256>();
48+ AscendC::LocalTensor<T> zLocal = ubAllocator.Alloc<T, 256>();
49+ 
50+ // CopyIn: GM -> UB
51+ AscendC::DataCopy(xLocal, xGm, totalLength);
52+ AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
53+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
54+ 
55+ // Compute: RegBase MulsVF z = x * scalar
56+ __ubuf__ T* xAddr = reinterpret_cast<__ubuf__ T*>(xLocal.GetPhyAddr());
57+ __ubuf__ T* zAddr = reinterpret_cast<__ubuf__ T*>(zLocal.GetPhyAddr());
58+ // 一次repeat计算的数据个数
59+ constexpr uint32_t oneRepeatSize = AscendC::GetVecLen() / sizeof(T);
60+ // 总迭代次数
61+ uint16_t repeatTimes = AscendC::CeilDivision(totalLength, oneRepeatSize);
62+ MulsVF(xAddr, zAddr, scalar, totalLength, repeatTimes, oneRepeatSize);
63+ 
64+ AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
65+ AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
66+ 
67+ // CopyOut: UB -> GM
68+ AscendC::DataCopy(zGm, zLocal, totalLength);
69+ }
70+ 
71+private:
72+ uint32_t totalLength;
73+ T scalar;
74+ AscendC::GlobalTensor<T> xGm;
75+ AscendC::GlobalTensor<T> zGm;
76+};
77+ 
78+__global__ __vector__ void muls(GM_ADDR x, GM_ADDR z)
79+{
80+ uint32_t totalLength = 256;
81+ float scalar = 2.0f;
82+ Kernel<float> kernel;
83+ kernel.Init(x, z, totalLength, scalar);
84+ kernel.Process();
85+}
86+ 
87+static bool CompareResult(const void* outputData, uint32_t outSize)
88+{
89+ void* goldenData;
90+ aclrtMallocHost((void**)(&goldenData), outSize);
91+ size_t goldenSize = outSize;
92+ bool ret = ReadFile("./output/golden.bin", goldenSize, goldenData, goldenSize);
93+ if (ret) {
94+ printf("ReadFile golden.bin success!\n");
95+ } else {
96+ printf("test failed!\n");
97+ return false;
98+ }
99+ constexpr float EPS = 1e-4;
100+ int64_t wrongNum = 0;
101+ 
102+ for (size_t i = 0; i < outSize / sizeof(float); i++) {
103+ float a = (reinterpret_cast<const float*>(outputData))[i];
104+ float b = (reinterpret_cast<const float*>(goldenData))[i];
105+ float ae = std::abs(a - b);
106+ float re = ae / std::abs(b);
107+ if (ae > EPS && re > EPS) {
108+ printf("CompareResult golden.bin failed output is %lf, golden is %lf\n", a, b);
109+ wrongNum++;
110+ }
111+ }
112+ aclrtFreeHost(goldenData);
113+ if (wrongNum != 0) {
114+ return false;
115+ } else {
116+ printf("CompareResult golden.bin success!\n");
117+ return true;
118+ }
119+}
120+ 
121+int32_t main(int32_t argc, char* argv[])
122+{
123+ uint32_t numBlocks = 1;
124+ aclInit(nullptr);
125+ int32_t deviceId = 0;
126+ aclrtSetDevice(deviceId);
127+ aclrtStream stream = nullptr;
128+ aclrtCreateStream(&stream);
129+ uint32_t totalLength = 256;
130+ size_t inputByteSize = static_cast<size_t>(1) * totalLength * sizeof(float);
131+ size_t outputByteSize = static_cast<size_t>(1) * totalLength * sizeof(float);
132+ uint8_t *xHost, *zHost;
133+ uint8_t *xDevice, *zDevice;
134+ aclrtMallocHost((void**)(&xHost), inputByteSize);
135+ aclrtMallocHost((void**)(&zHost), outputByteSize);
136+ aclrtMalloc((void**)&xDevice, inputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
137+ aclrtMalloc((void**)&zDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
138+ ReadFile("./input/input_x.bin", inputByteSize, xHost, inputByteSize);
139+ aclrtMemcpy(xDevice, inputByteSize, xHost, inputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
140+ muls<<<numBlocks, nullptr, stream>>>(xDevice, zDevice);
141+ aclrtSynchronizeStream(stream);
142+ aclrtMemcpy(zHost, outputByteSize, zDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);
143+ WriteFile("./output/output.bin", zHost, outputByteSize);
144+ bool goldenResult = true;
145+ goldenResult = CompareResult(zHost, outputByteSize);
146+ if (goldenResult) {
147+ printf("test pass!\n");
148+ } else {
149+ printf("test failed!\n");
150+ }
151+ aclrtFree(xDevice);
152+ aclrtFree(zDevice);
153+ aclrtFreeHost(xHost);
154+ aclrtFreeHost(zHost);
155+ aclrtDestroyStream(stream);
156+ aclrtResetDevice(deviceId);
157+ aclFinalize();
158+ return 0;
159+}
@@ -0,0 +1,32 @@
1+#!/usr/bin/python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
6+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
7+# CANN Open Software License Agreement Version 2.0 (the "License").
8+# Please refer to the License for details. You may not use this file except in compliance with the License.
9+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
10+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
11+# See LICENSE in the root of the software repository for the full text of the License.
12+# ----------------------------------------------------------------------------------------------------------
13+ 
14+ 
15+import os
16+import numpy as np
17+ 
18+def gen_golden_data_simple():
19+ total_length = 256
20+ data_type = np.float32
21+ scalar = 2.0
22+ # 生成一个 [1, 256] 向量
23+ x = np.random.uniform(1, 2, [1, total_length]).astype(data_type)
24+ # 计算标量乘法 z = x * scalar
25+ golden = x * scalar
26+ os.makedirs("input", exist_ok=True)
27+ os.makedirs("output", exist_ok=True)
28+ x.tofile('./input/input_x.bin')
29+ golden.tofile('./output/golden.bin')
30+ 
31+if __name__ == "__main__":
32+ gen_golden_data_simple()