Merged
regbase样例新增多核非对齐场景 #2024
ruanyyAdd on May 9
regbase样例新增多核非对齐场景 #2024
Merged
ruanyyAdd on May 9
Total: 37 files changed+444-186
@@ -8,4 +8,4 @@
8 8 
9| 目录名称 | 功能描述 |9| 目录名称 | 功能描述 |
10| ------------------------------------------------------------ | ---------------------------------------------------- |10| ------------------------------------------------------------ | ---------------------------------------------------- |
11-| [vector_add](./vector_add) | 基于RegBase编程范式的Add样例 |11+| [vector_add](./vector_add) | 基于Reg编程接口的Add样例 |
@@ -1,7 +1,7 @@
1# 基于RegBase编程add样例1# 基于RegBase编程add样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Add计算,采用4核并行模式处理数据。4+本样例基于Reg编程接口实现Add计算,采用4核并行模式处理数据。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -15,9 +15,9 @@
15| [data_copy_l0c2gm](./data_copy_l0c2gm)          | 本样例在卷积场景下,基于DataCopy实现数据随路量化激活搬运                                                                         |15| [data_copy_l0c2gm](./data_copy_l0c2gm)          | 本样例在卷积场景下,基于DataCopy实现数据随路量化激活搬运                                                                         |
16| [data_copy_pad_gm2ub_ub2gm](./data_copy_pad_gm2ub_ub2gm) | 本样例基于DataCopyPad实现数据非32字节对齐数据的搬运,并进行数据填充                                                                    |16| [data_copy_pad_gm2ub_ub2gm](./data_copy_pad_gm2ub_ub2gm) | 本样例基于DataCopyPad实现数据非32字节对齐数据的搬运,并进行数据填充                                                                    |
17| [data_copy_ub2l1](./data_copy_ub2l1)           | 本样例在Mmad矩阵乘场景下,基于DataCopy实现UB(Unified Buffer)到L1(L1 Buffer)的数据搬运                                                         |17| [data_copy_ub2l1](./data_copy_ub2l1)           | 本样例在Mmad矩阵乘场景下,基于DataCopy实现UB(Unified Buffer)到L1(L1 Buffer)的数据搬运                                                         |
18-| [ld_st_reg_mask](./ld_st_reg_mask)            | 本样例基于RegBase编程范式实现UB(Unified Buffer)对MaskReg(掩码寄存器)的搬入搬出,以及使用mask进行掩码搬出的操作                                              |18+| [ld_st_reg_mask](./ld_st_reg_mask)            | 本样例基于Reg编程接口实现UB(Unified Buffer)对MaskReg(掩码寄存器)的搬入搬出,以及使用mask进行掩码搬出的操作                                              |
19-| [ld_st_reg_align](./ld_st_reg_align)           | 本样例基于RegBase编程范式实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的连续和非连续的对齐数据搬运操作                                              |19+| [ld_st_reg_align](./ld_st_reg_align)           | 本样例基于Reg编程接口实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的连续和非连续的对齐数据搬运操作                                              |
20-| [ld_st_reg_unalign](./ld_st_reg_unalign)         | 本样例基于RegBase编程范式实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的非对齐数据搬运操作                                                    |20+| [ld_st_reg_unalign](./ld_st_reg_unalign)         | 本样例基于Reg编程接口实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的非对齐数据搬运操作                                                    |
21| [gather_ld_reg](./gather_ld_reg)             | 本样例演示使用Gather接口实现离散数据搬入,包含高维Gather(源为LocalTensor)和Reg::GatherB(按DataBlock收集)两种场景                                           |21| [gather_ld_reg](./gather_ld_reg)             | 本样例演示使用Gather接口实现离散数据搬入,包含高维Gather(源为LocalTensor)和Reg::GatherB(按DataBlock收集)两种场景                                           |
22| [scatter_st_reg](./scatter_st_reg)            | 本样例演示使用Reg::Scatter接口实现离散数据搬出(按元素分散到UB)                                                                     |22| [scatter_st_reg](./scatter_st_reg)            | 本样例演示使用Reg::Scatter接口实现离散数据搬出(按元素分散到UB)                                                                     |
23| [auxscalar_reg](./auxscalar_reg)                 | 本样例演示使用AuxScalar方式从UB读取多个标量数据参与计算|23| [auxscalar_reg](./auxscalar_reg)                 | 本样例演示使用AuxScalar方式从UB读取多个标量数据参与计算|
@@ -1,7 +1,7 @@
1# auxscalar_reg样例1# auxscalar_reg样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现AuxScalar方式从UB(Unified Buffer)读取多个标量数据,结合Adds进行向量与标量加法计算。4+本样例基于Reg编程接口实现AuxScalar方式从UB(Unified Buffer)读取多个标量数据,结合Adds进行向量与标量加法计算。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# gather_ld_reg样例1# gather_ld_reg样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现将离散数据从UB(Unified Buffer)搬入到RegTensor(Reg矢量计算基本单元)的功能,支持两种场景,通过编译时宏选择场景。4+本样例基于Reg编程接口实现将离散数据从UB(Unified Buffer)搬入到RegTensor(Reg矢量计算基本单元)的功能,支持两种场景,通过编译时宏选择场景。
5 <table>5 <table>
6 <tr>6 <tr>
7 <td>scenarioNum</td>7 <td>scenarioNum</td>
@@ -1,7 +1,7 @@
1# ld_st_reg_align样例1# ld_st_reg_align样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的连续和非连续的对齐数据搬运操作,该样例使用LoadAlign,StoreAlign接口,以及POST_MODE_UPDATE、DATA_BLOCK_COPY等模式的使能。本样例支持6种搬运场景,通过环境变量选择场景。4+本样例基于Reg编程接口实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的连续和非连续的对齐数据搬运操作,该样例使用LoadAlign,StoreAlign接口,以及POST_MODE_UPDATE、DATA_BLOCK_COPY等模式的使能。本样例支持6种搬运场景,通过环境变量选择场景。
5 <table>5 <table>
6 <tr>6 <tr>
7 <td>scenarioNum</td>7 <td>scenarioNum</td>
@@ -1,7 +1,7 @@
1# ld_st_reg_mask样例1# ld_st_reg_mask样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现UB(Unified Buffer)对MaskReg(掩码寄存器)的搬入搬出,以及使用mask进行掩码搬出的操作。样例使用LoadAlign,StoreAlign,CreateMask,Duplicate接口。4+本样例基于Reg编程接口实现UB(Unified Buffer)对MaskReg(掩码寄存器)的搬入搬出,以及使用mask进行掩码搬出的操作。样例使用LoadAlign,StoreAlign,CreateMask,Duplicate接口。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -18,10 +18,24 @@ find_package(ASC REQUIRED)
18 18 
19project(kernel_samples LANGUAGES ASC CXX)19project(kernel_samples LANGUAGES ASC CXX)
20 20 
21+set(SCENARIO_NUM "1" CACHE STRING "Scene number (1-2)")
22+ 
23+message(STATUS "[INFO] SCENARIO_NUM is ${SCENARIO_NUM}")
24+ 
25+if(NOT DEFINED SCENARIO_NUM)
26+ message(FATAL_ERROR "SCENARIO_NUM is not set. Please specify -DSCENARIO_NUM=1 or -DSCENARIO_NUM=2")
27+endif()
28+ 
29+if(NOT SCENARIO_NUM EQUAL 1 AND NOT SCENARIO_NUM EQUAL 2)
30+ message(FATAL_ERROR "SCENARIO_NUM must be 1 or 2, got: ${SCENARIO_NUM}")
31+endif()
32+ 
21add_executable(demo33add_executable(demo
22 ld_st_reg_unalign.asc34 ld_st_reg_unalign.asc
23)35)
24 36 
37+target_compile_definitions(demo PRIVATE SCENARIO_NUM=${SCENARIO_NUM})
38+ 
25target_link_libraries(demo PRIVATE39target_link_libraries(demo PRIVATE
26 tiling_api40 tiling_api
27 register41 register
@@ -31,4 +45,4 @@ target_link_libraries(demo PRIVATE
31 45 
32target_compile_options(demo PRIVATE46target_compile_options(demo PRIVATE
33 $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>47 $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>
34-)48+)
@@ -1,7 +1,22 @@
1# ld_st_reg_unalign样例1# ld_st_reg_unalign样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的非对齐数据搬运操作,该样例使用LoadUnAlign,StoreUnAlign,LoadUnAlignPre,StoreUnAlignPost接口。4+本样例基于Reg编程接口实现UB(Unified Buffer)对RegTensor(Reg矢量计算基本单元)的非对齐数据搬运操作,支持多种场景,通过环境变量选择场景。
5+ <table>
6+ <tr>
7+ <td>scenarioNum</td>
8+ <td>场景类型</td>
9+ </tr>
10+ <tr>
11+ <td>1</td>
12+ <td>单核非对齐数据搬运:使用LoadUnAlign和StoreUnAlign进行非对齐地址的数据搬运</td>
13+ </tr>
14+ <tr>
15+ <td>2</td>
16+ <td>多核非对齐场景计算及搬运:使用LoadUnAlign处理非对齐输入(uint16_t),ReduceDataBlock(MAX)进行块内求最大值</td>
17+ </tr>
18+ </table>
19+ 
5 20 
6## 支持的产品21## 支持的产品
7- Ascend 950PR/Ascend 950DT22- Ascend 950PR/Ascend 950DT
@@ -18,8 +33,10 @@
18```33```
19 34 
20## 样例描述35## 样例描述
36+ 
37+### 场景1:单核地址非对齐数据搬运
21- 样例功能: 38- 样例功能:
22- 输入一个数据类型为float,数据量为1024的向量,在源操作数和目的操作数地址均非32B对齐的情况下,搬运128个数据。39+ 输入shape为[1, 1024]的float类型矩阵,在源操作数和目的操作数地址均非32B对齐的情况下,搬运128个数据。
changxianyu

分核逻辑,可以用AI生成一个Markdown的图示简单说明一下,包括尾块的部分

likedislike
23- 样例规格:40- 样例规格:
24 <table>41 <table>
25 <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="3" align="center">AIV样例</td></tr>42 <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="3" align="center">AIV样例</td></tr>
@@ -31,13 +48,54 @@
31 <tr><td rowspan="1" align="center">样例输出</td><td align="center">y</td><td align="center">[1, 128]</td><td align="center">float</td></tr>48 <tr><td rowspan="1" align="center">样例输出</td><td align="center">y</td><td align="center">[1, 128]</td><td align="center">float</td></tr>
32 </tr>49 </tr>
33 <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">ld_st_reg_unalign_kernel</td></tr>50 <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">ld_st_reg_unalign_kernel</td></tr>
51+ <tr><td rowspan="1" align="center">核数</td><td colspan="4" align="center">1</td></tr>
34 </table>52 </table>
35- 样例实现: 53- 样例实现:
36- 将UB上源操作数和目的操作数地址偏移一个元素(4 Btype)长度,使得起始地址非32B对齐,调用CopyVF从该地址开始搬运128个float数,写回UB(Unified Buffer)。54+ 将UB上源操作数和目的操作数地址偏移一个元素(4 Byte)长度,使得起始地址非32B对齐,调用CopyVF从该地址开始搬运128个float数,写回UB(Unified Buffer)。
37- 55+ 
38- - 调用实现 56+### 场景2:多核地址非对齐、数据量不对齐场景搬运
39- 使用内核调用符<<<>>>调用核函数。57+- 样例功能:
40- 58+ 输入shape为[14, 255]的uint16_t类型矩阵,展示LoadUnAlign处理非对齐输入的自然使用场景。使用ReduceDataBlock对每个DataBlock(16个uint16_t元素)求最大值,4核并行处理,StoreUnAlign连续存储结果。
59+- 样例规格:
60+ <table>
61+ <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="3" align="center">AIV样例</td></tr>
62+ </tr>
63+ <tr><td rowspan="2" align="center">样例输入</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td></tr>
64+ <tr><td align="center">x</td><td align="center">[14, 255]</td><td align="center">uint16_t</td></tr>
65+ </tr>
66+ </tr>
67+ <tr><td rowspan="1" align="center">样例输出</td><td align="center">y</td><td align="center">[14, 16]</td><td align="center">uint16_t</td></tr>
68+ </tr>
69+ <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">ld_st_reg_unalign_kernel</td></tr>
70+ <tr><td rowspan="1" align="center">核数</td><td colspan="4" align="center">4</td></tr>
71+ </table>
72+- 样例实现:
73+ 1. **数据搬入**:
74+ - 0、1、2核搬运4×255=1020个元素,3核搬运2×255=510个元素,连续整块搬入UB
75+ - UB紧密排列,每行间隔255个元素
76+ - 行1-3起始地址非32B对齐(510字节、1020字节、1530字节)
77+ 
78+ 2. **LoadUnAlign自然使用**:
79+ - 所有行统一使用LoadUnAlignPre + LoadUnAlign处理对齐地址(行0)和非对齐地址(行1-3)
80+ - 对齐地址也可使用StoreAlign接口,当前仅为保证代码格式统一,用作样例演示,不作为极致性能参考
81+ 
82+ 3. **ReduceDataBlock计算**:
83+ - 每行255元素分2个VL块处理(128 + 127)
84+ - 每个VL块产生8个结果(每DataBlock求最大值)
85+ 
86+ 4. **StoreUnAlign连续存储**:
87+ - 使用带postUpdateStride的StoreUnAlign版本
88+ - 每次存储偏移8个元素(resultsPerRepeat=8)
89+ - 循环2次后自动偏移到dstAddr+16
90+ - StoreUnAlignPost处理最后的边界数据
91+ 
92+ 5. **输出布局**:
93+ - 每行16个结果,数据连续排列
94+ - 核0、核1、核2输出64个数(GM[0-63]、GM[64-127]、GM[128-191]),核3输出32个数(GM[192-223])
95+
96+- 调用实现
97+ 使用内核调用符<<<>>>调用核函数,启动4个核。
98+ 
41## 编译运行99## 编译运行
42在本样例根目录下执行如下步骤,编译并执行样例。100在本样例根目录下执行如下步骤,编译并执行样例。
43- 配置环境变量 101- 配置环境变量
@@ -59,28 +117,31 @@
59 117
60- 样例执行118- 样例执行
61 ```bash119 ```bash
62- python3 ../scripts/gen_data.py # 生成测试输入数据120+ SCENARIO=1 # 设置场景编号
63- mkdir -p build && cd build; # 创建并进入build目录121+ mkdir -p build && cd build; # 创建并进入build目录
64- cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # 编译工程(默认npu模式)122+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DSCENARIO_NUM=$SCENARIO ..;make -j; # 编译工程(默认npu模式)
65- ./demo # 执行编译生成的可执行程序,执行样例123+ python3 ../scripts/gen_data.py -scenarioNum=$SCENARIO # 生成测试输入数据
124+ ./demo # 执行编译生成的可执行程序,执行样例
66 ```125 ```
67 126 
68 使用 CPU调试 或 NPU仿真 模式时,添加 `-DCMAKE_ASC_RUN_MODE=cpu` 或 `-DCMAKE_ASC_RUN_MODE=sim` 参数即可。127 使用 CPU调试 或 NPU仿真 模式时,添加 `-DCMAKE_ASC_RUN_MODE=cpu` 或 `-DCMAKE_ASC_RUN_MODE=sim` 参数即可。
69 128 
70 示例如下:129 示例如下:
71 ```bash130 ```bash
72- cmake -DCMAKE_ASC_RUN_MODE=cpu -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # cpu调试模式131+ SCENARIO=1
73- cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU仿真模式132+ cmake -DCMAKE_ASC_RUN_MODE=cpu -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DSCENARIO_NUM=$SCENARIO ..;make -j; # cpu调试模式
133+ cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DSCENARIO_NUM=$SCENARIO ..;make -j; # NPU仿真模式
74 ```134 ```
75 135 
76 > **注意:** 切换编译模式或场景前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。136 > **注意:** 切换编译模式或场景前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
77 137 
78- 编译选项说明138- 编译选项说明
79 139 
80-| 选项    | 可选值           | 说明                       |140+| 选项      | 可选值           | 说明                       |
81-| ------------| -----------------------------| ---------------------------------------------------|141+| ----------------| -----------------------------| ---------------------------------------------------|
82| `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真       |142| `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真       |
83| `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |143| `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
144+| `SCENARIO_NUM` | `1`、`2` | 场景编号:1=单核地址非对齐数据搬运,2=多核地址非对齐、数据量非对齐数据搬运 |
84 145 
85- 执行结果 146- 执行结果
86 执行结果如下,说明精度对比成功。147 执行结果如下,说明精度对比成功。
@@ -1,13 +1,19 @@
1/**1/**
2-* Copyright (c) 2025 Huawei Technologies Co., Ltd.2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3-* This program is free software, you can redistribute it and/or modify it under the terms and conditions of3+ * 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").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.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,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.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.8+ * See LICENSE in the root of the software repository for the full text of the License.
9-*/9+ */
10 10 
11+/* !
12+ * \file ld_st_reg_unalign.asc
13+ * \brief 演示LoadUnAlign和StoreUnAlign接口在多场景下的使用方法
14+ * 场景1:单核地址非对齐数据搬运
15+ * 场景2:多核地址非对齐、数据量非对齐数据搬运
16+ */
11 17 
12#include "acl/acl.h"18#include "acl/acl.h"
13#include "kernel_operator.h"19#include "kernel_operator.h"
@@ -17,37 +23,16 @@
17#include "cpu_debug_launch.h"23#include "cpu_debug_launch.h"
18#endif24#endif
19 25 
20-template <typename T>26+constexpr uint32_t scenarioNum = SCENARIO_NUM;
21-__simd_vf__ inline void CopyVF(__ubuf__ T* zAddr, __ubuf__ T* xAddr, __ubuf__ T* yAddr,
22- uint32_t repeatTimes, uint16_t oneRepeatSize)
23-{
24- AscendC::Reg::RegTensor<T> xReg;
25- AscendC::Reg::RegTensor<T> yReg;
26- AscendC::Reg::RegTensor<T> zReg;
27- AscendC::Reg::UnalignRegForLoad ureg0;
28- AscendC::Reg::UnalignRegForLoad ureg1;
29- AscendC::Reg::UnalignRegForStore ureg2;
30- AscendC::Reg::MaskReg mask = AscendC::Reg::CreateMask<T>();
31- AscendC::Reg::LoadUnAlignPre(ureg0, xAddr);
32- AscendC::Reg::LoadUnAlignPre(ureg1, yAddr);
33- for (uint16_t i = 0; i < repeatTimes; ++i) {
34- AscendC::Reg::LoadUnAlign(xReg, ureg0, xAddr + i * oneRepeatSize);
35- AscendC::Reg::LoadUnAlign(yReg, ureg1, yAddr + i * oneRepeatSize);
36- AscendC::Reg::Add(zReg, xReg, yReg, mask);
37- AscendC::Reg::StoreUnAlign(zAddr, zReg, ureg2, oneRepeatSize);
38- }
39- AscendC::Reg::StoreUnAlignPost(zAddr, ureg2, 0);
40-}
41 27 
42-template<typename T>28+// 场景1:单核Kernel
43-class Kernel {29+template<typename T, uint32_t count>
30+class KernelScenario1 {
44public:31public:
45- __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, uint32_t count)32+ __aicore__ inline void Init(GM_ADDR x, GM_ADDR y)
46 {33 {
47- this->count = count;
48 this->xGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(x));34 this->xGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(x));
49 this->yGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(y));35 this->yGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(y));
50- this->zGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(z));
51 }36 }
52 37 
53 __aicore__ inline void Process()38 __aicore__ inline void Process()
@@ -55,122 +40,275 @@ public:
55 AscendC::LocalMemAllocator<AscendC::Hardware::UB> ubAllocator;40 AscendC::LocalMemAllocator<AscendC::Hardware::UB> ubAllocator;
56 AscendC::LocalTensor<T> xLocal = ubAllocator.Alloc<T>(count);41 AscendC::LocalTensor<T> xLocal = ubAllocator.Alloc<T>(count);
57 AscendC::LocalTensor<T> yLocal = ubAllocator.Alloc<T>(count);42 AscendC::LocalTensor<T> yLocal = ubAllocator.Alloc<T>(count);
58- AscendC::LocalTensor<T> zLocal = ubAllocator.Alloc<T>(count);
59 43 
60 AscendC::DataCopy(xLocal, xGm, count);44 AscendC::DataCopy(xLocal, xGm, count);
61- AscendC::DataCopy(yLocal, yGm, count);
62- 
63 AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);45 AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
64 AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);46 AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
65 47 
66- AscendC::Duplicate<T>(zLocal, 0, count);48+ AscendC::Duplicate<T>(yLocal, 0, count);
67 49 
68- __ubuf__ T* xAddr = reinterpret_cast<__ubuf__ T*>(xLocal.GetPhyAddr());50+ __ubuf__ T* srcAddr = reinterpret_cast<__ubuf__ T*>(xLocal.GetPhyAddr());
69- __ubuf__ T* yAddr = reinterpret_cast<__ubuf__ T*>(yLocal.GetPhyAddr());51+ __ubuf__ T* dstAddr = reinterpret_cast<__ubuf__ T*>(yLocal.GetPhyAddr());
70- __ubuf__ T* zAddr = reinterpret_cast<__ubuf__ T*>(zLocal.GetPhyAddr());
71 constexpr uint32_t oneRepeatSize = AscendC::GetVecLen() / sizeof(T);52 constexpr uint32_t oneRepeatSize = AscendC::GetVecLen() / sizeof(T);
72- uint16_t repeatTimes = 2;53+ asc_vf_call<CopyVF>(dstAddr + 1, srcAddr + 1, oneRepeatSize);
73- asc_vf_call<CopyVF<T>>(zAddr + 3, xAddr + 1, yAddr + 2, repeatTimes, oneRepeatSize);
74 54 
75 AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);55 AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
76 AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);56 AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
77 57 
78- AscendC::DataCopy(zGm, zLocal, count);58+ AscendC::DataCopy(yGm, yLocal, count);
59+ }
60+ 
61+ __simd_vf__ static inline void CopyVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr, uint16_t oneRepeatSize)
62+ {
63+ AscendC::Reg::RegTensor<T> srcReg, dstReg;
64+ AscendC::Reg::UnalignRegForLoad ureg0;
65+ AscendC::Reg::UnalignRegForStore ureg1;
66+ 
67+ AscendC::Reg::LoadUnAlignPre(ureg0, srcAddr);
68+ for (uint16_t i = 0; i < 2; ++i) {
69+ AscendC::Reg::LoadUnAlign(srcReg, ureg0, srcAddr, oneRepeatSize);
70+ AscendC::Reg::StoreUnAlign(dstAddr, srcReg, ureg1, oneRepeatSize);
71+ }
72+ AscendC::Reg::StoreUnAlignPost(dstAddr, ureg1, 0);
79 }73 }
80 74 
81private:75private:
82- uint32_t count;
83 AscendC::GlobalTensor<T> xGm;76 AscendC::GlobalTensor<T> xGm;
84 AscendC::GlobalTensor<T> yGm;77 AscendC::GlobalTensor<T> yGm;
85- AscendC::GlobalTensor<T> zGm;
86};78};
87 79 
88-__global__ __vector__ void ld_st_reg_unalign_kernel(GM_ADDR x, GM_ADDR y, GM_ADDR z)80+// 场景2:多核Kernel
81+template<typename T, uint32_t totalM, uint32_t singleCoreM, uint32_t inputN, uint32_t outputN>
82+class KernelScenario2 {
83+public:
84+ __aicore__ inline void Init(GM_ADDR x, GM_ADDR y)
85+ {
86+ AscendC::InitSocState();
87+ xGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(x));
88+ yGm.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(y));
89+ 
90+ constexpr uint32_t mIndex = (totalM + singleCoreM - 1) / singleCoreM;
91+ constexpr uint32_t tailSingleCoreM = totalM - (mIndex - 1) * singleCoreM;
92+ 
93+ uint32_t blockIdx = AscendC::GetBlockIdx();
94+ if (blockIdx >= mIndex) {
95+ return;
96+ }
97+ 
98+ actualSingleCoreM = (blockIdx == (mIndex - 1)) ? tailSingleCoreM : singleCoreM;
99+ xGm = xGm[blockIdx * singleCoreM * inputN];
100+ yGm = yGm[blockIdx * singleCoreM * outputN];
101+ 
102+ // ub 要求32B对齐
103+ constexpr uint32_t alignSize = 32 / sizeof(T);
104+ inputSize = actualSingleCoreM * inputN;
105+ alignInputSize = AscendC::AlignUp(inputSize, alignSize);
106+ outputSize = actualSingleCoreM * outputN;
107+ alignOutputSize = AscendC::AlignUp(outputSize, alignSize);
108+ }
109+ 
110+ __aicore__ inline void Process()
111+ {
112+ AscendC::LocalMemAllocator<AscendC::Hardware::UB> ubAllocator;
113+ AscendC::LocalTensor<T> xLocal = ubAllocator.Alloc<T>(alignInputSize);
114+ AscendC::LocalTensor<T> yLocal = ubAllocator.Alloc<T>(alignOutputSize);
115+ 
116+ uint32_t blockLen = inputSize * sizeof(T);
117+ AscendC::DataCopyExtParams copyParams = {1, blockLen, 0, 0, 0};
118+ uint8_t rpad = alignInputSize - inputSize;
119+ AscendC::DataCopyPadExtParams<T> padParams = {false, 0, rpad, 0};
120+ AscendC::DataCopyPad<T>(xLocal, xGm, copyParams, padParams);
121+ 
122+ AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
123+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
124+ 
125+ __ubuf__ T* srcAddr = reinterpret_cast<__ubuf__ T*>(xLocal.GetPhyAddr());
126+ __ubuf__ T* dstAddr = reinterpret_cast<__ubuf__ T*>(yLocal.GetPhyAddr());
127+ 
128+ constexpr uint32_t oneRepeatInputSize = AscendC::GetVecLen() / sizeof(T);
129+ // 每个DataBlock大小为32B
130+ constexpr uint32_t oneRepeatOutputSize = AscendC::GetVecLen() / 32;
131+ uint16_t repeatTimes = AscendC::CeilDivision(inputN, oneRepeatInputSize);
132+ 
133+ for (uint32_t m = 0; m < actualSingleCoreM; ++m) {
134+ asc_vf_call<ReduceDataBlockVF>(dstAddr + m * outputN, srcAddr + m * inputN,
135+ inputN, oneRepeatInputSize, oneRepeatOutputSize, repeatTimes);
136+ }
137+ 
138+ AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
139+ AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
140+ 
141+ AscendC::DataCopy(yGm, yLocal, outputSize);
142+ }
143+ 
144+ __simd_vf__ static inline void ReduceDataBlockVF(__ubuf__ T* dstAddr, __ubuf__ T* srcAddr,
145+ uint32_t inputSize, uint32_t oneRepeatInputSize, uint32_t oneRepeatOutputSize, uint32_t repeatTimes)
146+ {
147+ AscendC::Reg::RegTensor<T> srcReg;
148+ AscendC::Reg::RegTensor<T> dstReg;
149+ AscendC::Reg::UnalignRegForLoad uregLoad;
150+ AscendC::Reg::UnalignRegForStore uregStore;
151+ AscendC::Reg::MaskReg mask;
152+ 
153+ AscendC::Reg::LoadUnAlignPre(uregLoad, srcAddr);
154+ for (uint16_t i = 0; i < repeatTimes; ++i) {
155+ mask = AscendC::Reg::UpdateMask<T>(inputSize);
156+ AscendC::Reg::LoadUnAlign(srcReg, uregLoad, srcAddr, oneRepeatInputSize);
157+ AscendC::Reg::ReduceDataBlock<AscendC::Reg::ReduceType::MAX>(dstReg, srcReg, mask);
158+ AscendC::Reg::StoreUnAlign(dstAddr, dstReg, uregStore, oneRepeatOutputSize);
159+ }
160+ AscendC::Reg::StoreUnAlignPost(dstAddr, uregStore, 0);
161+ }
162+ 
163+private:
164+ AscendC::GlobalTensor<T> xGm;
165+ AscendC::GlobalTensor<T> yGm;
166+ uint32_t actualSingleCoreM;
167+ uint32_t inputSize;
168+ uint32_t alignInputSize;
169+ uint32_t outputSize;
170+ uint32_t alignOutputSize;
171+};
172+ 
173+// 输入shape为[M, N],M方向分核处理,N方向每DataBlock(即16个元素)ReduceMax为1个元素
174+template<typename T, uint32_t totalM, uint32_t singleCoreM, uint32_t inputN, uint32_t outputN>
175+__global__ __vector__ void ld_st_reg_unalign_kernel(GM_ADDR x, GM_ADDR y)
89{176{
90 AscendC::InitSocState();177 AscendC::InitSocState();
91- Kernel<float> kernel;178+ if constexpr (scenarioNum == 1) {
92- kernel.Init(x, y, z, 1024);179+ KernelScenario1<T, inputN> kernel;
93- kernel.Process();180+ kernel.Init(x, y);
181+ kernel.Process();
182+ } else if constexpr (scenarioNum == 2) {
183+ KernelScenario2<T, totalM, singleCoreM, inputN, outputN> kernel;
184+ kernel.Init(x, y);
185+ kernel.Process();
186+ }
94 AscendC::PipeBarrier<PIPE_ALL>();187 AscendC::PipeBarrier<PIPE_ALL>();
95}188}
96 189 
97-static bool CompareResult(const void* outputData, uint32_t outSize)190+bool CompareResult(const void* outputData, uint32_t outSize)
98{191{
99 void* goldenData;192 void* goldenData;
100 aclrtMallocHost((void**)(&goldenData), outSize);193 aclrtMallocHost((void**)(&goldenData), outSize);
101 size_t goldenSize = outSize;194 size_t goldenSize = outSize;
102 bool ret = ReadFile("./output/golden.bin", goldenSize, goldenData, goldenSize);195 bool ret = ReadFile("./output/golden.bin", goldenSize, goldenData, goldenSize);
103- if (ret) {196+ if (!ret) {
104- printf("ReadFile golden.bin success!\n");197+ printf("ReadFile golden.bin failed!\n");
105- } else {
106- printf("test failed!\n");
107 aclrtFreeHost(goldenData);198 aclrtFreeHost(goldenData);
108 return false;199 return false;
109 }200 }
110- constexpr float EPS = 1e-5;201+ 
202+ constexpr float EPS = 1e-3;
111 int64_t wrongNum = 0;203 int64_t wrongNum = 0;
112 204 
113- for (size_t i = 0; i < outSize / sizeof(float); i++) {205+ if constexpr (scenarioNum == 1) {
114- float a = (reinterpret_cast<const float*>(outputData))[i];206+ const float* output = reinterpret_cast<const float*>(outputData);
115- float b = (reinterpret_cast<const float*>(goldenData))[i];207+ const float* golden = reinterpret_cast<const float*>(goldenData);
116- float ae = std::abs(a - b);208+ uint32_t totalSize = outSize / sizeof(float);
117- float re = ae / std::abs(b);209+
118- if (ae > EPS && re > EPS) {210+ for (uint32_t i = 0; i < totalSize; ++i) {
119- printf("CompareResult golden.bin failed output is %lf, golden is %lf\n", a, b);211+ float a = output[i];
120- wrongNum++;212+ float b = golden[i];
213+ if (std::abs(a - b) > EPS) {
214+ if (wrongNum < 5) {
215+ printf("Mismatch at index %u: output=%f, golden=%f\n", i, a, b);
216+ }
217+ wrongNum++;
218+ }
219+ }
220+ } else if constexpr (scenarioNum == 2) {
221+ const uint16_t* output = reinterpret_cast<const uint16_t*>(outputData);
222+ const uint16_t* golden = reinterpret_cast<const uint16_t*>(goldenData);
223+ uint32_t totalSize = outSize / sizeof(uint16_t);
224+
225+ for (uint32_t i = 0; i < totalSize; ++i) {
226+ if (output[i] != golden[i]) {
227+ if (wrongNum < 5) {
228+ printf("Mismatch at index %u: output=%u, golden=%u\n", i, (uint32_t)output[i], (uint32_t)golden[i]);
229+ }
230+ wrongNum++;
231+ }
121 }232 }
122 }233 }
234+ 
123 aclrtFreeHost(goldenData);235 aclrtFreeHost(goldenData);
124- if (wrongNum != 0) {236+ if (wrongNum == 0) {
125- return false;237+ printf("test pass!\n");
126- } else {
127- printf("CompareResult golden.bin success!\n");
128 return true;238 return true;
239+ } else {
240+ printf("test fail! wrong count: %ld\n", wrongNum);
241+ return false;
129 }242 }
130}243}
131 244 
132int32_t main(int32_t argc, char* argv[])245int32_t main(int32_t argc, char* argv[])
133{246{
134- uint32_t numBlocks = 1;
135 aclInit(nullptr);247 aclInit(nullptr);
136 int32_t deviceId = 0;248 int32_t deviceId = 0;
137 aclrtSetDevice(deviceId);249 aclrtSetDevice(deviceId);
138 aclrtStream stream = nullptr;250 aclrtStream stream = nullptr;
139 aclrtCreateStream(&stream);251 aclrtCreateStream(&stream);
140- uint32_t totalLength = 1024;252+ 
141- size_t inputByteSize = static_cast<size_t>(1) * totalLength * sizeof(float);253+ uint32_t numBlocks;
142- size_t outputByteSize = static_cast<size_t>(1) * totalLength * sizeof(float);254+ size_t inputByteSize;
143- uint8_t *xHost, *yHost, *zHost;255+ size_t outputByteSize;
144- uint8_t *xDevice, *yDevice, *zDevice;256+ if constexpr (scenarioNum == 1) {
145- aclrtMallocHost((void**)(&xHost), inputByteSize);257+ using DataType = float;
146- aclrtMallocHost((void**)(&yHost), inputByteSize);258+ constexpr uint32_t totalM = 1;
147- aclrtMallocHost((void**)(&zHost), outputByteSize);259+ constexpr uint32_t singleCoreM = 1;
148- aclrtMalloc((void**)&xDevice, inputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);260+ constexpr uint32_t inputN = 1024;
149- aclrtMalloc((void**)&yDevice, inputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);261+ constexpr uint32_t outputN = 1024;
150- aclrtMalloc((void**)&zDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);262+ 
151- ReadFile("./input/input_x.bin", inputByteSize, xHost, inputByteSize);263+ numBlocks = (totalM + singleCoreM - 1) / singleCoreM;
152- ReadFile("./input/input_y.bin", inputByteSize, yHost, inputByteSize);264+ inputByteSize = static_cast<size_t>(1) * totalM * inputN * sizeof(DataType);
153- aclrtMemcpy(xDevice, inputByteSize, xHost, inputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);265+ outputByteSize = static_cast<size_t>(1) * totalM * outputN * sizeof(DataType);
154- aclrtMemcpy(yDevice, inputByteSize, yHost, inputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
155- ld_st_reg_unalign_kernel<<<numBlocks, nullptr, stream>>>(xDevice, yDevice, zDevice);
156- aclrtSynchronizeStream(stream);
157- aclrtMemcpy(zHost, outputByteSize, zDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);
158- WriteFile("./output/output.bin", zHost, outputByteSize);
159- bool goldenResult = true;
160- goldenResult = CompareResult(zHost, outputByteSize);
161- if (goldenResult) {
162- printf("test pass!\n");
163 } else {266 } else {
164- printf("test failed!\n");267+ using DataType = uint16_t;
268+ constexpr uint32_t totalM = 14;
269+ constexpr uint32_t singleCoreM = 4;
270+ constexpr uint32_t inputN = 255;
271+ constexpr uint32_t outputN = 16;
272+ 
273+ numBlocks = (totalM + singleCoreM - 1) / singleCoreM;
274+ inputByteSize = static_cast<size_t>(1) * totalM * inputN * sizeof(DataType);
275+ outputByteSize = static_cast<size_t>(1) * totalM * outputN * sizeof(DataType);
165 }276 }
277+ 
278+ uint8_t* xHost;
279+ uint8_t* yHost;
280+ uint8_t* xDevice;
281+ uint8_t* yDevice;
282+ 
283+ aclrtMallocHost((void**)(&xHost), inputByteSize);
284+ aclrtMallocHost((void**)(&yHost), outputByteSize);
285+ aclrtMalloc((void**)&xDevice, inputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
286+ aclrtMalloc((void**)&yDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
287+ 
288+ ReadFile("./input/input_x.bin", inputByteSize, xHost, inputByteSize);
289+ aclrtMemcpy(xDevice, inputByteSize, xHost, inputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
290+ 
291+ if constexpr (scenarioNum == 1) {
292+ ld_st_reg_unalign_kernel<float, 1, 1, 1024, 1024>
293+ <<<numBlocks, nullptr, stream>>>(xDevice, yDevice);
294+ } else {
295+ ld_st_reg_unalign_kernel<uint16_t, 14, 4, 255, 16>
296+ <<<numBlocks, nullptr, stream>>>(xDevice, yDevice);
297+ }
298+ 
299+ aclrtSynchronizeStream(stream);
300+ aclrtMemcpy(yHost, outputByteSize, yDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);
301+ WriteFile("./output/output.bin", yHost, outputByteSize);
302+
303+ bool result = CompareResult(yHost, outputByteSize);
304+
166 aclrtFree(xDevice);305 aclrtFree(xDevice);
167 aclrtFree(yDevice);306 aclrtFree(yDevice);
168- aclrtFree(zDevice);
169 aclrtFreeHost(xHost);307 aclrtFreeHost(xHost);
170 aclrtFreeHost(yHost);308 aclrtFreeHost(yHost);
171- aclrtFreeHost(zHost);
172 aclrtDestroyStream(stream);309 aclrtDestroyStream(stream);
173 aclrtResetDevice(deviceId);310 aclrtResetDevice(deviceId);
174 aclFinalize();311 aclFinalize();
175- return 0;312+
313+ return result ? 0 : 1;
176}314}
@@ -2,10 +2,10 @@
2# coding=utf-82# coding=utf-8
3 3 
4# ----------------------------------------------------------------------------------------------------------4# ----------------------------------------------------------------------------------------------------------
5-# Copyright (c) 2026 Huawei Technologies Co., Ltd.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 of6+# 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").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.8+# 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,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.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.11# See LICENSE in the root of the software repository for the full text of the License.
@@ -13,31 +13,76 @@
13 13 
14 14 
15import os15import os
16-import sys16+import argparse
17import numpy as np17import numpy as np
18 18 
19-def gen_golden_data():19+ 
20- total_length = 102420+def gen_golden_data_scenario1():
21- data_type = np.float3221+ """
22+ Scenario 1: Single-core non-aligned data copy
23+ Input: 1024 float32 numbers
24+ Output: 1024 float32 numbers
25+ - Kernel: CopyVF copies from xLocal[1] to yLocal[1], 128 floats in 2 iterations
26+ - Iteration 0: Load 64 floats from xLocal[1:65], Store to yLocal[1:65]
27+ - Iteration 1: Load 64 floats from xLocal[65:129], Store to yLocal[65:129]
28+ - Result: yLocal[1:129] = xLocal[1:129], yLocal[0] and yLocal[129:] are zeros
29+ """
30+ count = 1024
31+ x = np.random.randn(count).astype(np.float32)
32+ x.tofile("./input/input_x.bin")
22 33
23- input_x = np.zeros(total_length, dtype=data_type)34+ # Golden: 1024 floats, with copied data at indices 1-128
24- input_x[1:129] = 1.035+ golden = np.zeros(count, dtype=np.float32)
25- input_x = input_x.reshape(1, total_length)36+ golden[1:129] = x[1:129].copy() # indices 1-128 inclusive
37+ golden.tofile("./output/golden.bin")
38+ print(f"Scenario 1: Generated input_x.bin ({count} floats) and golden.bin ({count} floats)")
39+ 
40+ 
41+def gen_golden_data_scenario2():
42+ """
43+ Scenario 2: Multi-core ReduceDataBlock MAX
44+ Input: 14x255 = 3570 uint16 numbers
45+ Output: 14x16 = 224 uint16 numbers (max of each DataBlock)
46+ Each row has 255 elements, split into DataBlocks of 16 elements each.
47+ The last DataBlock has 15 elements (255 = 15*16 + 15)
48+ """
49+ total_rows = 14
50+ row_length = 255
51+ data_block_size = 16
52+ results_per_row = 16
26 53
27- input_y = np.zeros(total_length, dtype=data_type)54+ # Generate random input data
28- input_y[2:130] = 1.055+ total_elements = total_rows * row_length
29- input_y = input_y.reshape(1, total_length)56+ x = np.random.randint(0, 1000, size=total_elements, dtype=np.uint16)
57+ x.tofile("./input/input_x.bin")
58+
59+ # Compute golden output
60+ golden = np.zeros(total_rows * results_per_row, dtype=np.uint16)
61+
62+ for row in range(total_rows):
63+ row_start = row * row_length
64+ for block_idx in range(results_per_row):
65+ block_start = row_start + block_idx * data_block_size
66+ block_end = min(block_start + data_block_size, row_start + row_length)
67+
68+ # Max of all elements in this DataBlock
69+ block_max = np.max(x[block_start:block_end]).astype(np.uint16)
70+ golden[row * results_per_row + block_idx] = block_max
71+
72+ golden.tofile("./output/golden.bin")
73+ print(f"Scenario 2: Generated input_x.bin ({total_elements} uint16) and golden.bin ({len(golden)} uint16)")
74+ 
75+ 
76+if __name__ == "__main__":
77+ parser = argparse.ArgumentParser()
78+ parser.add_argument('-scenarioNum', type=int, default=1, choices=[1, 2],
79+ help='Scenario number: 1=Single-core copy, 2=Multi-core ReduceDataBlock')
80+ args = parser.parse_args()
30 81
31 os.makedirs("input", exist_ok=True)82 os.makedirs("input", exist_ok=True)
32 os.makedirs("output", exist_ok=True)83 os.makedirs("output", exist_ok=True)
33 84
34- input_x.tofile('./input/input_x.bin')85+ if args.scenarioNum == 1:
35- input_y.tofile('./input/input_y.bin')86+ gen_golden_data_scenario1()
36- 87+ elif args.scenarioNum == 2:
37- golden = np.zeros(total_length, dtype=data_type).reshape(1, total_length)88+ gen_golden_data_scenario2()
38- golden[0, 3:131] = input_x[0, 1:129] + input_y[0, 2:130]
39-
40- golden.tofile('./output/golden.bin')
41- 
42-if __name__ == "__main__":
43- gen_golden_data()
@@ -1,7 +1,7 @@
1# move_reg样例1# move_reg样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式演示验证从RegTensor(Reg矢量计算基本单元)中搬运数据到MaskReg(掩码寄存器),使用MaskGenWithRegTensor接口。4+本样例基于Reg编程接口演示验证从RegTensor(Reg矢量计算基本单元)中搬运数据到MaskReg(掩码寄存器),使用MaskGenWithRegTensor接口。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# scatter_st_reg样例1# scatter_st_reg样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现离散数据搬出功能(按元素分散到UB(Unified Buffer)),使用Scatter接口。4+本样例基于Reg编程接口实现离散数据搬出功能(按元素分散到UB(Unified Buffer)),使用Scatter接口。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -8,19 +8,19 @@
8 8 
9| 目录名称 | 功能描述 |9| 目录名称 | 功能描述 |
10| -------------------------------- | ---------------------------------------------------------------------------------------------|10| -------------------------------- | ---------------------------------------------------------------------------------------------|
11-| [abs](./abs) | 本样例基于RegBase编程范式实现Abs运算,Relu/Exp/Sqrt/Ln/Log/Log2/Log10/Neg接口皆可参考该样例 |11+| [abs](./abs) | 本样例基于Reg编程接口实现Abs运算,Relu/Exp/Sqrt/Ln/Log/Log2/Log10/Neg接口皆可参考该样例 |
12-| [mul](./mul) | 本样例基于RegBase编程范式实现Mul运算,Add/Sub/Div/Max/Min/Prelu接口皆可参考该样例 |12+| [arange](./arange)       | 本样例基于Reg编程接口实现Arange运算,以标量值为起始生成递增/递减索引序列        |
13-| [muls](./muls) | 本样例基于RegBase编程范式实现Muls运算,Adds/Maxs/Mins/LeakyRelu接口皆可参考该样例 |13+| [cast](./cast)         | 本样例基于Reg编程接口实现Cast运算,用于RegTensor数据类型转换(位宽大转小/小转大)    |
14-| [reduce](./reduce) | 本样例基于RegBase编程范式实现Reduce运算(SUM模式),Reduce接口支持SUM/MAX/MIN归约模式 |14+| [compare](./compare)       | 本样例基于Reg编程接口实现Compare运算,用于比较两个向量或向量与标量的大小关系    |
15-| [reduce_pair](./reduce_pair) | 本样例基于RegBase编程范式实现PairReduceElem运算(SUM模式),对相邻奇偶元素对进行归约求和 |15+| [data_relayout](./data_relayout) | 本样例基于Reg编程接口演示Interleave和Pack接口实现数据重排(Interleave交织 + Pack低位提取) |
16-| [reduce_block](./reduce_block) | 本样例基于RegBase编程范式实现ReduceDataBlock运算(SUM模式),对每个DataBlock(32B)内元素归约 |16+| [duplicate](./duplicate)    | 本样例基于Reg编程接口实现Duplicate运算(标量填充),将标量值填充到向量的每个位置    |
17-| [cast](./cast)         | 本样例基于RegBase编程范式实现Cast运算,用于RegTensor数据类型转换(位宽大转小/小转大)    |17+| [gather](./gather) | 本样例基于Reg编程接口演示Gather接口(源操作数为寄存器)按索引收集元素,使用LoadAlign/StoreAlign的postUpdate模式 |
18-| [truncate](./truncate)     | 本样例基于RegBase编程范式实现Truncate运算,将浮点数截断到整数位               |18+| [mergemode](./mergemode) | 本样例基于Reg编程接口综合演示MaskMergeMode::MERGING + postUpdate + UpdateMask + ReduceMax |
19-| [arange](./arange)       | 本样例基于RegBase编程范式实现Arange运算,以标量值为起始生成递增/递减索引序列        |19+| [mul](./mul) | 本样例基于Reg编程接口实现Mul运算,Add/Sub/Div/Max/Min/Prelu接口皆可参考该样例 |
20-| [duplicate](./duplicate)    | 本样例基于RegBase编程范式实现Duplicate运算(标量填充),将标量值填充到向量的每个位置    |20+| [muls](./muls) | 本样例基于Reg编程接口实现Muls运算,Adds/Maxs/Mins/LeakyRelu接口皆可参考该样例 |
21-| [compare](./compare)       | 本样例基于RegBase编程范式实现Compare运算,用于比较两个向量或向量与标量的大小关系    |21+| [reduce](./reduce) | 本样例基于Reg编程接口实现Reduce运算(SUM模式),Reduce接口支持SUM/MAX/MIN归约模式 |
22-| [select](./select)       | 本样例基于RegBase编程范式实现Select运算,根据掩码在两个向量之间选取元素    |22+| [reduce_block](./reduce_block) | 本样例基于Reg编程接口实现ReduceDataBlock运算(SUM模式),对每个DataBlock(32B)内元素归约 |
23-| [squeeze](./squeeze)       | 本样例基于RegBase编程范式实现Squeeze运算,将向量压缩为标量    |23+| [reduce_pair](./reduce_pair) | 本样例基于Reg编程接口实现PairReduceElem运算(SUM模式),对相邻奇偶元素对进行归约求和 |
24-| [mergemode](./mergemode) | 本样例基于RegBase编程范式综合演示MaskMergeMode::MERGING + postUpdate + UpdateMask + ReduceMax |24+| [select](./select)       | 本样例基于Reg编程接口实现Select运算,根据掩码在两个向量之间选取元素    |
25-| [data_relayout](./data_relayout) | 本样例基于RegBase编程范式演示Interleave和Pack接口实现数据重排(Interleave交织 + Pack低位提取) |25+| [squeeze](./squeeze)       | 本样例基于Reg编程接口实现Squeeze运算,将向量压缩为标量    |
26-| [gather](./gather) | 本样例基于RegBase编程范式演示Gather接口(源操作数为寄存器)按索引收集元素,使用LoadAlign/StoreAlign的postUpdate模式 |26+| [truncate](./truncate)     | 本样例基于Reg编程接口实现Truncate运算,将浮点数截断到整数位               |
@@ -1,7 +1,7 @@
1# abs样例1# abs样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Abs运算,主要调用Abs接口。4+本样例基于Reg编程接口实现Abs运算,主要调用Abs接口。
5- Relu/Exp/Sqrt/Ln/Log/Log2/Log10/Neg接口皆可参考该样例5- Relu/Exp/Sqrt/Ln/Log/Log2/Log10/Neg接口皆可参考该样例
6 6 
7## 支持的产品7## 支持的产品
@@ -1,7 +1,7 @@
1# arange样例1# arange样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Arange运算,主要调用Arange接口。4+本样例基于Reg编程接口实现Arange运算,主要调用Arange接口。
5- Arange接口以传入的标量值为起始值,生成递增/递减的索引序列5- Arange接口以传入的标量值为起始值,生成递增/递减的索引序列
6- 本样例以递增模式为例,起始值为06- 本样例以递增模式为例,起始值为0
7 7 
@@ -1,7 +1,7 @@
1# cast样例1# cast样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Cast运算,主要调用Cast接口实现数据类型转换。 4+本样例基于Reg编程接口实现Cast运算,主要调用Cast接口实现数据类型转换。
5本样例支持两种数据类型转换场景,通过环境变量SCENARIO_NUM选择场景。5本样例支持两种数据类型转换场景,通过环境变量SCENARIO_NUM选择场景。
6 <table>6 <table>
7 <tr>7 <tr>
@@ -1,7 +1,7 @@
1# compare样例1# compare样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Compare、Compares接口完成多场景下的数据比较功能。 4+本样例基于Reg编程接口实现Compare、Compares接口完成多场景下的数据比较功能。
5本样例支持两种比较场景,通过环境变量SCENARIO_NUM选择场景。5本样例支持两种比较场景,通过环境变量SCENARIO_NUM选择场景。
6 <table>6 <table>
7 <tr>7 <tr>
@@ -1,7 +1,7 @@
1# data_relayout样例1# data_relayout样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现数据重排功能,支持多种场景,通过环境变量选择场景。4+本样例基于Reg编程接口实现数据重排功能,支持多种场景,通过环境变量选择场景。
5 <table>5 <table>
6 <tr>6 <tr>
7 <td>scenarioNum</td>7 <td>scenarioNum</td>
@@ -1,7 +1,7 @@
1# duplicate样例1# duplicate样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Duplicate运算(标量填充模式),主要调用Duplicate接口。4+本样例基于Reg编程接口实现Duplicate运算(标量填充模式),主要调用Duplicate接口。
5- `Duplicate(dstReg, scalarValue, mask)` 接口将一个标量值复制多次并填充到向量中5- `Duplicate(dstReg, scalarValue, mask)` 接口将一个标量值复制多次并填充到向量中
6- `Duplicate(dstReg, srcReg, mask)` 接口将源RegTensor的第一个元素复制多次并填充到向量中6- `Duplicate(dstReg, srcReg, mask)` 接口将源RegTensor的第一个元素复制多次并填充到向量中
7 7 
@@ -1,7 +1,7 @@
1# gather样例1# gather样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现按索引从RegTensor(Reg矢量计算基本单元)收集元素功能。4+本样例基于Reg编程接口实现按索引从RegTensor(Reg矢量计算基本单元)收集元素功能。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# histogram样例1# histogram样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现直方图统计功能,使用了Histograms接口。4+本样例基于Reg编程接口实现直方图统计功能,使用了Histograms接口。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# mergemode样例1# mergemode样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式验证MaskMergeMode::MERGING模式的行为特性,演示未激活mask位保留dstReg原值的机制,使用Max接口进行验证。4+本样例基于Reg编程接口验证MaskMergeMode::MERGING模式的行为特性,演示未激活mask位保留dstReg原值的机制,使用Max接口进行验证。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# mul样例1# mul样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现逐元素乘法运算,采用4核并行模式处理数据。4+本样例基于Reg编程接口实现逐元素乘法运算,采用4核并行模式处理数据。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# muls样例1# muls样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Muls运算,主要调用Muls接口。4+本样例基于Reg编程接口实现Muls运算,主要调用Muls接口。
5- Adds/Maxs/Mins/LeakyRelu接口皆可参考该样例5- Adds/Maxs/Mins/LeakyRelu接口皆可参考该样例
6 6 
7## 支持的产品7## 支持的产品
@@ -1,7 +1,7 @@
1# reduce样例1# reduce样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Reduce运算,主要调用Reduce接口(SUM模式)。4+本样例基于Reg编程接口实现Reduce运算,主要调用Reduce接口(SUM模式)。
5- Reduce接口支持SUM/MAX/MIN归约模式,本样例以SUM模式为例5- Reduce接口支持SUM/MAX/MIN归约模式,本样例以SUM模式为例
6 6 
7## 支持的产品7## 支持的产品
@@ -1,7 +1,7 @@
1# reduce_block样例1# reduce_block样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现ReduceDataBlock运算,主要调用ReduceDataBlock接口(SUM模式)。4+本样例基于Reg编程接口实现ReduceDataBlock运算,主要调用ReduceDataBlock接口(SUM模式)。
5- ReduceDataBlock接口支持SUM/MAX/MIN归约模式,本样例以SUM模式为例5- ReduceDataBlock接口支持SUM/MAX/MIN归约模式,本样例以SUM模式为例
6 6 
7## 支持的产品7## 支持的产品
@@ -1,7 +1,7 @@
1# reduce_pair样例1# reduce_pair样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现PairReduceElem运算,主要调用PairReduceElem接口(SUM模式)。4+本样例基于Reg编程接口实现PairReduceElem运算,主要调用PairReduceElem接口(SUM模式)。
5- PairReduceElem接口对相邻的奇偶元素对进行归约求和,当前仅支持SUM归约模式5- PairReduceElem接口对相邻的奇偶元素对进行归约求和,当前仅支持SUM归约模式
6 6 
7 7 
@@ -1,7 +1,7 @@
1# select样例1# select样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Select运算,主要调用Select接口。4+本样例基于Reg编程接口实现Select运算,主要调用Select接口。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# squeeze样例1# squeeze样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Squeeze运算,主要调用Squeeze接口和StoreUnAlign/StoreUnAlignPost接口。4+本样例基于Reg编程接口实现Squeeze运算,主要调用Squeeze接口和StoreUnAlign/StoreUnAlignPost接口。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# truncate样例1# truncate样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现Truncate运算,用于将RegTensor(Reg矢量计算基本单元)的浮点数截断到整数位,主要调用Truncate接口。4+本样例基于Reg编程接口实现Truncate运算,用于将RegTensor(Reg矢量计算基本单元)的浮点数截断到整数位,主要调用Truncate接口。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -36,4 +36,4 @@
36 36 
37| 目录名称 | 功能描述 |37| 目录名称 | 功能描述 |
38|----------|----------|38|----------|----------|
39-| [reg_sync](./reg_sync) | 演示RegBase编程范式下UB读写操作的同步,包括寄存器保序特性(优化读写之间的同步指令)和LocalMemBar接口保序两种场景 |39+| [reg_sync](./reg_sync) | 演示Reg编程接口下UB读写操作的同步,包括寄存器保序特性(优化读写之间的同步指令)和LocalMemBar接口保序两种场景 |
@@ -1,7 +1,7 @@
1# reg_sync样例1# reg_sync样例
2 2 
3## 概述3## 概述
4-本样例基于RegBase编程范式实现UB(Unified Buffer)读或写操作的同步机制,支持多种场景,通过环境变量选择场景。4+本样例基于Reg编程接口实现UB(Unified Buffer)读或写操作的同步机制,支持多种场景,通过环境变量选择场景。
5 <table>5 <table>
6 <tr>6 <tr>
7 <td>scenarioNum</td>7 <td>scenarioNum</td>
@@ -11,7 +11,7 @@
11| [00_data_movement](./00_data_movement/) | 本路径下包含了与数据搬运相关的多个API的样例,展示了数据搬运接口的使用。|11| [00_data_movement](./00_data_movement/) | 本路径下包含了与数据搬运相关的多个API的样例,展示了数据搬运接口的使用。|
12| [01_matrix_compute](./01_matrix_compute/) | 本样例路径以batch_mmad、fixpipe_co12c1_quantization等算子为示例,展示了矩阵计算接口的使用。|12| [01_matrix_compute](./01_matrix_compute/) | 本样例路径以batch_mmad、fixpipe_co12c1_quantization等算子为示例,展示了矩阵计算接口的使用。|
13| [02_memory_vector_compute](./02_memory_vector_compute/) | 本样例路径以reduce、sort、transpose等算子为示例,展示了内存向量计算接口的使用。|13| [02_memory_vector_compute](./02_memory_vector_compute/) | 本样例路径以reduce、sort、transpose等算子为示例,展示了内存向量计算接口的使用。|
14-| [03_reg_vector_compute](./03_reg_vector_compute/) | 本路径下包含了与向量计算相关的多个API的样例,基于RegBase编程范式实现。|14+| [03_reg_vector_compute](./03_reg_vector_compute/) | 本路径下包含了与向量计算相关的多个API的样例,基于Reg编程接口实现。|
15| [04_resource_management](./04_resource_management/) | 本路径下包含了与资源管理相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 |15| [04_resource_management](./04_resource_management/) | 本路径下包含了与资源管理相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 |
16| [06_sync_control](./06_sync_control/) | 本路径下包含了与同步控制相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 |16| [06_sync_control](./06_sync_control/) | 本路径下包含了与同步控制相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 |
17| [07_system_access](./07_system_access/) | 本路径下包含了与系统变量访问相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 |17| [07_system_access](./07_system_access/) | 本路径下包含了与系统变量访问相关的多个API的样例。每个样例均基于Ascend C的<<<>>>直调方法,支持main函数和kernel函数在同一个cpp文件中实现。 |
@@ -8,7 +8,7 @@
8| 目录名称 | 功能描述 |8| 目录名称 | 功能描述 |
9| -------------------------------------------------- | ---------------------------------------------------- |9| -------------------------------------------------- | ---------------------------------------------------- |
10| [optimize_vf_continious_align](./optimize_vf_continious_align) | 本样例演示了SIMD场景下,基于连续非对齐搬运接口LoadUnAlign/StoreUnAlign进行搬运优化的算子实现。 |10| [optimize_vf_continious_align](./optimize_vf_continious_align) | 本样例演示了SIMD场景下,基于连续非对齐搬运接口LoadUnAlign/StoreUnAlign进行搬运优化的算子实现。 |
11-| [optimize_vf_dual_instr](./optimize_vf_dual_instr) | 本样例演示了SIMD场景下,基于RegBase编程范式下VF指令双发优化的样例,通过合理拆分VF循环,适当搬出中间结果到UB,减少数据依赖。 |11+| [optimize_vf_dual_instr](./optimize_vf_dual_instr) | 本样例演示了SIMD场景下,基于Reg编程接口下VF指令双发优化的样例,通过合理拆分VF循环,适当搬出中间结果到UB,减少数据依赖。 |
12-| [optimize_vf_fusion](./optimize_vf_fusion) | 本样例演示了SIMD场景下,基于RegBase编程范式,通过VF融合优化算子代码实现。 |12+| [optimize_vf_fusion](./optimize_vf_fusion) | 本样例演示了SIMD场景下,基于Reg编程接口,通过VF融合优化算子代码实现。 |
13| [optimize_vf_loop](./optimize_vf_loop) | 通过循环内成员变量访问优化、循环内指令分布优化、循环内地址管理优化等手段优化VF循环。 |13| [optimize_vf_loop](./optimize_vf_loop) | 通过循环内成员变量访问优化、循环内指令分布优化、循环内地址管理优化等手段优化VF循环。 |
14| [gelu_high_performance](./gelu_high_performance) | 本样例以Gelu计算为例,介绍RegBase的向量性能调优方法,样例展示使能VF融合之后的性能收益情况。 |14| [gelu_high_performance](./gelu_high_performance) | 本样例以Gelu计算为例,介绍RegBase的向量性能调优方法,样例展示使能VF融合之后的性能收益情况。 |
@@ -1,7 +1,7 @@
1# optimize_vf_dual_instr样例1# optimize_vf_dual_instr样例
2 2 
3## 概述3## 概述
4-本样例演示了SIMD场景下,基于RegBase编程范式下vf指令双发优化的样例,通过合理拆分VF循环,适当搬出中间结果到UB,减少数据依赖。4+本样例演示了SIMD场景下,基于Reg编程接口下vf指令双发优化的样例,通过合理拆分VF循环,适当搬出中间结果到UB,减少数据依赖。
5 5 
6## 支持的产品6## 支持的产品
7- Ascend 950PR/Ascend 950DT7- Ascend 950PR/Ascend 950DT
@@ -1,7 +1,7 @@
1# optimize_vf_fusion样例1# optimize_vf_fusion样例
2 2 
3## 概述3## 概述
4-本样例演示了SIMD场景下,基于RegBase编程范式,通过VF融合优化算子代码实现。样例中定义了两个vf函数,其中,4+本样例演示了SIMD场景下,基于Reg编程接口,通过VF融合优化算子代码实现。样例中定义了两个vf函数,其中,
5DivVF函数实现对输入向量中的每个数取倒数操作,AddVF函数实现对输入向量的加一操作,5DivVF函数实现对输入向量中的每个数取倒数操作,AddVF函数实现对输入向量的加一操作,
6DivVF和AddVF会被编译器融合为一个VF函数。6DivVF和AddVF会被编译器融合为一个VF函数。
7 7