Merged
add tensor api examples #6163
li-yuanjie-daAdd on Sep 17
add tensor api examples #6163
Merged
li-yuanjie-daAdd on Sep 17
Total: 42 files changed+2768-34
@@ -0,0 +1,35 @@
1+# ----------------------------------------------------------------------------------------------------------
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 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+cmake_minimum_required(VERSION 3.16)
12+ 
13+set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu or sim")
14+set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture")
15+set(SCENARIO_NUM "1" CACHE STRING "Bank conflict scenario (1=compact stride, 2=bank-offset stride)")
16+ 
17+if(NOT CMAKE_ASC_RUN_MODE STREQUAL "npu" AND NOT CMAKE_ASC_RUN_MODE STREQUAL "sim")
18+ message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be 'npu' or 'sim'")
19+endif()
20+if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510")
21+ message(FATAL_ERROR "bank_conflict only supports dav-3510")
22+endif()
23+if(NOT SCENARIO_NUM MATCHES "^[12]$")
24+ message(FATAL_ERROR "SCENARIO_NUM must be 1 or 2")
25+endif()
26+find_package(ASC REQUIRED)
27+project(bank_conflict LANGUAGES ASC CXX)
28+ 
29+add_executable(demo bank_conflict.asc)
30+target_compile_definitions(demo PRIVATE
31+ SCENARIO_NUM=${SCENARIO_NUM}
32+)
33+target_compile_options(demo PRIVATE
34+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>
35+)
@@ -0,0 +1,246 @@
1+# 基于Tensor API实现的ND2NZ Bank冲突调优样例
2+ 
3+## 概述
4+ 
5+本样例基于静态Tensor API编程范式,实现`8192 × 8192` half矩阵从ND布局到NZ布局的转换,并通过两个场景对比UB Vector写阶段的bank冲突及规避方式。
6+ 
7+GM和UB之间的数据搬运使用Tensor API的`copy`接口,ND到NZ重排的寄存器访问使用C API的`asc_loadalign`和`asc_storealign`。`asc_storealign`一次写入8个DataBlock,通过`block_stride`控制相邻DataBlock之间的间距,从而可以直接对比bank冲突的向量写行为。
8+ 
9+## 本样例支持的产品及CANN软件版本
10+ 
11+| 产品 | CANN软件版本 |
12+|------|-------------|
13+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
14+ 
15+## 目录结构介绍
16+ 
17+```text
18+├── bank_conflict
19+│ ├── scripts
20+│ │ ├── gen_data.py // 输入数据和真值数据生成脚本文件
21+│ │ └── verify_result.py // 真值对比文件
22+│ ├── figures // 图示
23+│ ├── CMakeLists.txt // 编译工程文件
24+│ ├── data_utils.h // 数据读入写出函数
25+│ ├── bank_conflict.asc // Ascend C样例实现
26+│ └── README.md // 样例说明文档
27+```
28+ 
29+## 样例描述
30+ 
31+- 样例功能:
32+ 
33+ 本样例将输入矩阵`x`的ND布局转换为输出矩阵`z`的NZ布局。
34+ 
35+ NZ布局的小分形为16 × C0,小分形中的一个C0块包含16个half,即一个32B DataBlock。每个`144 × 128` tile的一行包含8个C0块,向量写阶段将这8个DataBlock写入NZ区域中对应的8个C0列。
36+ 
37+ - `x`:输入,逻辑shape为`[M, N]`,half,ND布局
38+ - `z`:输出,逻辑shape为`[M, N]`,half,NZ布局
39+ 
40+- 样例规格:
41+ 
42+ 本样例固定`M=8192`、`N=8192`,启动64个Vector block。每个block负责一个行切分和列切分区域,内部按`144 × 128` tile处理;最后一个行tile的有效高度通过`actualTileH`传入。
43+ 
44+ <table>
45+ <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="4" align="center">ND2NZ</td></tr>
46+ <tr><td rowspan="2" align="center">样例输入</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td><td align="center">format</td></tr>
47+ <tr><td align="center">x</td><td align="center">[M, N]</td><td align="center">float16</td><td align="center">ND</td></tr>
48+ <tr><td rowspan="1" align="center">样例输出</td><td align="center">z</td><td align="center">[M, N]</td><td align="center">float16</td><td align="center">NZ</td></tr>
49+ <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">bank_conflict_kernel</td></tr>
50+ </table>
51+ 
52+ 编译期参数如下:
53+ 
54+ | 参数 | 值 | 说明 |
55+ | :--- | :---: | :--- |
56+ | `TOTAL_M` | 8192 | 输入矩阵行数 |
57+ | `TOTAL_N` | 8192 | 输入矩阵列数 |
58+ | `ROW_SPLITS` | 8 | 行方向切分数 |
59+ | `COL_SPLITS` | 8 | 列方向切分数 |
60+ | `TOTAL_BLOCKS` | 64 | 启动block数 |
61+ | `TILE_H` | 144 | tile最大行数 |
62+ | `TILE_W` | 128 | tile列数 |
63+ | `C0_ELEMS` | 16 | 一个C0块中的half元素数 |
64+ | `TILE_C0_COLS` | 8 | 一个tile中的C0列数 |
65+ | `SCENARIO_NUM` | 1、2 | bank冲突对照场景 |
66+ | `dstNzC0Stride` | S1=144、S2=145 | 相邻C0列起始位置的间距,单位为DataBlock |
67+ 
68+ > **术语说明:** DataBlock是向量指令处理的数据单元,大小为32B;half类型下1个DataBlock包含16个half。
69+ 
70+ **图:ND与NZ数据排布示意图**
71+ 
72+ <img src="figures/nd2nz.png" width="80%">
73+ 
74+- 样例实现:
75+ 
76+ - 实现流程:
77+ 
78+ <table>
79+ <tr><th align="left">步骤</th><th align="left">Tensor API/C API操作</th><th align="left">功能</th><th align="left">布局或执行单元</th></tr>
80+ <tr><td align="left">1</td><td align="left">编译期常量</td><td align="left">定义矩阵、tile、分块和场景参数</td><td align="left">不涉及</td></tr>
81+ <tr><td align="left">2</td><td align="left">make_tensor + layout</td><td align="left">创建GM、UB源和UB目标Tensor视图</td><td align="left">GM为ND;NZ写入步长由Vector接口和MTE3 layout分别表达</td></tr>
82+ <tr><td align="left">3</td><td align="left">copy(copy_gm_to_ub)</td><td align="left">将当前有效高度的ND tile从GM搬到UB</td><td align="left">ND到ND</td></tr>
83+ <tr><td align="left">4</td><td align="left">slice + asc_loadalign</td><td align="left">按行切片,从UB ND tile读取128个half</td><td align="left">Vector</td></tr>
84+ <tr><td align="left">5</td><td align="left">asc_storealign</td><td align="left">将8个DataBlock按`dstNzC0Stride`写入UB NZ区域</td><td align="left">Vector,ND到NZ重排</td></tr>
85+ <tr><td align="left">6</td><td align="left">copy(copy_ub_to_gm)</td><td align="left">将NZ tile写回GM的紧凑NZ布局,跳过S2的填充空间</td><td align="left">NZ到NZ</td></tr>
86+ </table>
87+ 
88+ - Tensor API核心接口:
89+ 
90+ 1. **张量创建接口**:使用`make_frame_layout`和`make_pattern_layout`描述GM、UB Tensor的形状和布局,使用`make_tensor`和`make_mem_ptr`创建GM、UB Tensor。
91+ 
92+ 2. **切片接口**:使用`slice(make_coord(...), make_shape(...))`取得当前tile的行视图,源地址和目的地址均从Tensor视图获取。
93+ 
94+ 3. **数据搬运接口**:使用`make_copy`构造`copy_gm_to_ub`和`copy_ub_to_gm`,完成GM与UB之间的数据搬运;MTE3阶段的NZ目的Tensor layout表达UB中相邻C0列的实际步长。
95+ 
96+ 4. **寄存器搬运接口**:使用`asc_loadalign`读取一行128个half,使用`asc_storealign`的`block_stride`参数控制8个DataBlock的非连续写入。`block_stride`是本样例对比bank冲突的直接控制参数。
97+ 
98+ 5. **流水接口**:使用`asc_lock`和`asc_unlock`保护MTE2、Vector和MTE3阶段,使用两组UB buffer交替处理tile。
99+ 
100+ - ND到NZ核心实现:
101+ 
102+ `srcTensor`和`dstTensor`先通过Tensor API创建,`slice`只负责取得当前行的起始地址;8个DataBlock的非连续落点由`asc_storealign`的`dstNzC0Stride`参数表达。
103+ 
104+ ```cpp
105+ template <uint32_t dstNzC0Stride>
106+ __simd_vf__ inline void NdToNz(__ubuf__ half* dst, __ubuf__ half* src)
107+ {
108+ vector_bool mask = asc_create_mask_b16(PAT_ALL);
109+ vector_half value;
110+ asc_loadalign(value, src);
111+ asc_storealign(dst, value, dstNzC0Stride, 0, mask);
112+ }
113+ ```
114+ 
115+ 场景差异在kernel的最终调用处体现:
116+ 
117+ ```cpp
118+ if constexpr (SCENARIO_NUM == 1) {
119+ NdToNz<TILE_H>(dstRow.data().get(), srcRow.data().get());
120+ } else {
121+ NdToNz<TILE_H + BANK_CONFLICT_OFFSET>(dstRow.data().get(), srcRow.data().get());
122+ }
123+ ```
124+ 
125+ - 调用实现:
126+ 
127+ Host侧使用内核调用符`<<<>>>`启动`bank_conflict_kernel`,并通过`SCENARIO_NUM`选择对照场景。
128+ 
129+ - UB Bank结构与本样例中的冲突:
130+ 
131+ Ascend 950PR/Ascend 950DT的Unified Buffer划分为16个物理bank,并组织为8个bank group。bank `i`和bank `i+8`属于同一个bank group,关系为`bank group = bank % 8`。UB地址采用低位交织,连续地址每经过一个32B DataBlock,物理bank编号加1并按16取模。
132+ 
133+ 本样例关注`asc_storealign`一次写入8个DataBlock时的写写冲突。相邻落点之间的间距由`dstNzC0Stride`决定;当多个落点落入同一个bank group时,写入需要串行处理。
134+ 
135+ **图:Ascend 950PR/Ascend 950DT UB Bank结构示意图**
136+ 
137+ <img src="figures/ubBankStruct3510.png" width="80%">
138+ 
139+ **图:Ascend 950PR/Ascend 950DT UB Bank内存排布示意图**
140+ 
141+ <img src="figures/UB-3510.png" width="80%">
142+ 
143+ **场景1:紧凑排放**
144+ 
145+ 编译时设置`SCENARIO_NUM=1`。此时`dstNzC0Stride=144`,即`16 × 9`个DataBlock。对同一行而言,8个写落点的物理bank编号保持不变,因此8个写访问同一个bank和bank group,形成写写冲突。
146+ 
147+ **图:场景1紧凑排放下ND到NZ示意图**
148+ 
149+ <img src="figures/datand2nzS1.png" width="80%">
150+ 
151+ 以tile第一行为例,8个落点为`0、144、288、...、1008`个DataBlock,对应bank 0、bank 0、...、bank 0;其他行的起始bank随行地址变化,但同一条store中的8个落点仍落在同一个bank。
152+ 
153+ **图:场景1 UB bank冲突示意图**
154+ 
155+ <img src="figures/s1bank3510.png" width="80%">
156+ 
157+ **场景2:增加stride并偏移NZ buffer起点**
158+ 
159+ 编译时设置`SCENARIO_NUM=2`。此时`dstNzC0Stride=145`,即`16 × 9 + 1`个DataBlock。每次跳转后物理bank编号加1,8个写落点依次进入8个不同的bank group。
160+ 
161+ 代码同时将`nzPtr`的起始地址额外偏移8个DataBlock(`NZ_BASE_SHIFT_DATA_BLOCKS=8`)。因此以第一行为例,`asc_loadalign`从ND buffer读取bank 0~7,`asc_storealign`向NZ buffer写入bank 8~15,错开首行读写使用的物理bank,降低同拍物理bank重叠。增加的stride空间只用于改变UB落点,UB到GM搬运通过NZ Tensor的layout跳过填充位置,输出仍是紧凑NZ布局。
162+ 
163+ **图:场景2增加stride后的ND到NZ示意图**
164+ 
165+ <img src="figures/datand2nzS2.png" width="80%">
166+ 
167+ **图:场景2 UB bank分散落点示意图**
168+ 
169+ <img src="figures/s2bank3510.png" width="80%">
170+ 
171+## Tensor API实现特点
172+ 
173+| 特性 | 本样例实现 |
174+|------|------------|
175+| 张量表示 | 使用Tensor对象描述GM、UB ND tile和UB NZ tile |
176+| 张量切片 | 使用`slice`取得每个tile和每行的起始地址 |
177+| 数据搬运 | 使用`copy`完成GM到UB、UB到GM搬运 |
178+| ND到NZ重排 | 使用`asc_loadalign`和`asc_storealign`完成向量寄存器搬运 |
179+| Bank冲突对比 | 通过`dstNzC0Stride=144/145`对比紧凑排放和bank分散排放 |
180+| 地址偏移 | 场景2通过8个DataBlock的NZ起始偏移,在起始位置错开ND读取和NZ写入的物理bank |
181+| 双缓冲 | 使用ping-pong UB buffer交替处理tile |
182+| 尾块处理 | 使用`actualTileH`限制最后一个tile的有效行数 |
183+ 
184+## 性能数据
185+ 
186+以下数据为Ascend 950PR/Ascend 950DT在`144 × 128` tile、64个block配置下的实测结果。
187+ 
188+| 场景 | `dstNzC0Stride` | Task Duration(μs) | `aiv_time`(μs) | `aiv_total_cycles` | `aiv_vec_time`(μs) | `aiv_vec_ratio` | `aiv_scalar_time`(μs) | `aiv_scalar_ratio` | `aiv_mte2_time`(μs) | `aiv_mte2_ratio` | `aiv_mte3_time`(μs) | `aiv_mte3_ratio` | `icache_miss_rate` |
189+| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
190+| S1 | 144 | 262.628 | 261.96 | 14112428 | **254.637** | 0.972 | 3.851 | 0.015 | 93.445 | 0.357 | 47.817 | 0.183 | 0.006 |
191+| S2 | 145 | 222.964 | 222.18 | 12052109 | **214.199** | 0.964 | 3.823 | 0.017 | 111.712 | 0.503 | 41.139 | 0.185 | 0.009 |
192+ 
193+S2的`aiv_vec_time`由254.637μs降低到214.199μs,说明增加stride后写写bank冲突明显减少。
194+ 
195+## 编译运行
196+ 
197+在本样例根目录下执行如下步骤,编译并执行样例。
198+ 
199+- 配置环境变量
200+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../docs/zh/quick_start.md#prepare&install),配置环境变量,**当前仅支持使用[CANN master](../../../../docs/zh/quick_start.md#cann-install)**。
201+ ```bash
202+ source ${install_path}/cann/set_env.sh
203+ ```
204+ 
205+ > **说明:** `${install_path}` 为CANN包安装目录,未指定安装目录时默认安装至 `/usr/local/Ascend` 下。
206+ 
207+- 样例执行
208+ 
209+ 以场景1为例,在本样例目录下执行如下命令。
210+ 
211+ ```bash
212+ SCENARIO_NUM=1
213+ mkdir -p build && cd build; # 创建并进入build目录
214+ cmake -DSCENARIO_NUM=${SCENARIO_NUM} -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # 编译工程(默认npu模式)
215+ python3 ../scripts/gen_data.py # 生成测试输入数据
216+ ./demo # 执行编译生成的可执行程序,执行样例
217+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # 验证输出结果是否正确,确认算法逻辑正确
218+ ```
219+ 
220+ 编译场景2时,将`SCENARIO_NUM`设置为2即可。
221+ 
222+ 使用NPU仿真模式时,添加`-DCMAKE_ASC_RUN_MODE=sim`参数即可。
223+ 
224+ ```bash
225+ cmake -DSCENARIO_NUM=${SCENARIO_NUM} -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU仿真模式
226+ ```
227+ 
228+ > **注意:** 切换编译模式前需清理cmake缓存,可在build目录下执行`rm CMakeCache.txt`后重新cmake。
229+ 
230+- 编译选项说明
231+ 
232+ | 选项 | 可选值 | 说明 |
233+ |------|--------|------|
234+ | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 运行模式:NPU运行、NPU仿真 |
235+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU架构:dav-3510对应Ascend 950PR/Ascend 950DT |
236+ | `SCENARIO_NUM` | 1、2 | 1为紧凑排放,2为增加stride并偏移NZ buffer起点 |
237+ 
238+ > **说明:** 本样例仅支持dav-3510架构(对应Ascend 950PR/Ascend 950DT)。
239+ 
240+- 执行结果
241+ 
242+ 执行结果如下,说明精度对比成功。
243+ 
244+ ```bash
245+ test pass!
246+ ```
@@ -0,0 +1,248 @@
1+# ND2NZ Bank Conflict Optimization Example Based on Tensor API
2+ 
3+## Overview
4+ 
5+Based on the static Tensor API programming model, this example converts an `8192 x 8192` half matrix from ND layout to a NZ layout. Two scenarios compare bank conflicts during the UB Vector write stage and the corresponding avoidance method.
6+ 
7+Data movement between GM and UB uses the Tensor API `copy` interface. Register accesses for the ND-to-NZ rearrangement use the C APIs `asc_loadalign` and `asc_storealign`. Each `asc_storealign` writes eight DataBlocks, and its `block_stride` controls the distance between adjacent DataBlocks so that the bank-conflict behavior can be compared directly.
8+ 
9+## Supported Products and CANN Software Versions
10+ 
11+| Product | CANN Software Version |
12+|---------|------------------------|
13+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
14+ 
15+## Directory Structure
16+ 
17+```text
18+├── bank_conflict
19+│ ├── scripts
20+│ │ ├── gen_data.py // Input data and ground truth generation script
21+│ │ └── verify_result.py // Ground truth comparison file
22+│ ├── figures // Figures
23+│ ├── CMakeLists.txt // Build project file
24+│ ├── data_utils.h // Data read/write functions
25+│ ├── bank_conflict.asc // Ascend C example implementation
26+│ └── README.md // Example documentation
27+```
28+ 
29+## Example Description
30+ 
31+- Example functionality:
32+ 
33+ This example converts the input matrix `x` from ND layout to the NZ layout of the output matrix `z`.
34+ 
35+ A C0 block contains 16 half elements, that is, one 32-byte DataBlock. Each row of a `144 x 128` tile contains eight C0 blocks. The Vector write stage writes these eight DataBlocks to the corresponding eight C0 columns in the NZ region.
36+ 
37+ - `x`: input matrix, logical shape `[M, N]`, half, ND layout
38+ - `z`: output matrix, logical shape `[M, N]`, half, NZ layout
39+ 
40+- Example specifications:
41+ 
42+ The example uses `M=8192` and `N=8192` and launches 64 Vector blocks. Each block processes a row split and a column split using `144 x 128` tiles. The valid height of the final row tile is passed through `actualTileH`.
43+ 
44+ <table>
45+ <tr><td rowspan="1" align="center">Example Type (OpType)</td><td colspan="4" align="center">ND2NZ</td></tr>
46+ <tr><td rowspan="2" align="center">Example Input</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td><td align="center">format</td></tr>
47+ <tr><td align="center">x</td><td align="center">[M, N]</td><td align="center">float16</td><td align="center">ND</td></tr>
48+ <tr><td rowspan="1" align="center">Example Output</td><td align="center">z</td><td align="center">[M, N]</td><td align="center">float16</td><td align="center">NZ</td></tr>
49+ <tr><td rowspan="1" align="center">Kernel Function Name</td><td colspan="4" align="center">bank_conflict_kernel</td></tr>
50+ </table>
51+ 
52+ Compile-time parameters are listed below:
53+ 
54+ | Parameter | Value | Description |
55+ | :--- | :---: | :--- |
56+ | `TOTAL_M` | 8192 | Number of rows in the input matrix |
57+ | `TOTAL_N` | 8192 | Number of columns in the input matrix |
58+ | `ROW_SPLITS` | 8 | Number of row splits |
59+ | `COL_SPLITS` | 8 | Number of column splits |
60+ | `TOTAL_BLOCKS` | 64 | Number of launched blocks |
61+ | `TILE_H` | 144 | Maximum number of rows in a tile |
62+ | `TILE_W` | 128 | Number of columns in a tile |
63+ | `C0_ELEMS` | 16 | Number of half elements in one C0 block |
64+ | `TILE_C0_COLS` | 8 | Number of C0 columns in one tile |
65+ | `SCENARIO_NUM` | 1, 2 | Bank-conflict comparison scenario |
66+ | `dstNzC0Stride` | S1=144, S2=145 | Distance between adjacent C0-column start positions, in DataBlocks |
67+ 
68+ > **Terminology:** A DataBlock is the data unit processed by a Vector instruction and is 32 bytes in size. One DataBlock contains 16 half elements.
69+ 
70+ **Figure: ND and NZ data layout**
71+ 
72+ <img src="figures/nd2nz.png" width="80%">
73+ 
74+- Example implementation:
75+ 
76+ - Implementation process:
77+ 
78+ <table>
79+ <tr><th align="left">Step</th><th align="left">Tensor API/C API Operation</th><th align="left">Function</th><th align="left">Layout or Execution Unit</th></tr>
80+ <tr><td align="left">1</td><td align="left">Compile-time constants</td><td align="left">Define matrix, tile, partitioning, and scenario parameters</td><td align="left">Not applicable</td></tr>
81+ <tr><td align="left">2</td><td align="left">make_tensor + layout</td><td align="left">Create GM, UB source, and UB destination Tensor views</td><td align="left">GM uses ND; NZ write strides are expressed by the Vector interface and the MTE3 layout respectively</td></tr>
82+ <tr><td align="left">3</td><td align="left">copy(copy_gm_to_ub)</td><td align="left">Move the valid-height ND tile from GM to UB</td><td align="left">ND to ND</td></tr>
83+ <tr><td align="left">4</td><td align="left">slice + asc_loadalign</td><td align="left">Slice by row and read 128 half elements from the UB ND tile</td><td align="left">Vector</td></tr>
84+ <tr><td align="left">5</td><td align="left">asc_storealign</td><td align="left">Write eight DataBlocks to the UB NZ region with `dstNzC0Stride`</td><td align="left">Vector, ND to NZ rearrangement</td></tr>
85+ <tr><td align="left">6</td><td align="left">copy(copy_ub_to_gm)</td><td align="left">Write the NZ tile back to the compact NZ layout in GM, skipping the padding used by S2</td><td align="left">NZ to NZ</td></tr>
86+ </table>
87+ 
88+ - Tensor API core interfaces:
89+ 
90+ 1. **Tensor construction interface:** Use `make_frame_layout` and `make_pattern_layout` to describe GM and UB Tensor shapes and layouts, and use `make_tensor` and `make_mem_ptr` to create the GM and UB Tensors.
91+ 
92+ 2. **Slicing interface:** Use `slice(make_coord(...), make_shape(...))` to obtain the row view of the current tile. Both source and destination addresses are obtained from Tensor views.
93+ 
94+ 3. **Data movement interface:** Use `make_copy` to construct `copy_gm_to_ub` and `copy_ub_to_gm`, completing data movement between GM and UB. The NZ destination Tensor layout in the MTE3 stage describes the actual stride between adjacent C0 columns in UB.
95+ 
96+ 4. **Register movement interface:** Use `asc_loadalign` to read one row of 128 half elements and the `block_stride` parameter of `asc_storealign` to control the non-contiguous writes of eight DataBlocks. `block_stride` is the direct control parameter for the bank-conflict comparison in this example.
97+ 
98+ 5. **Pipeline interface:** Use `asc_lock` and `asc_unlock` to protect the MTE2, Vector, and MTE3 stages, and use two UB buffers to process tiles in ping-pong mode.
99+ 
100+ - Core ND-to-NZ implementation:
101+ 
102+ `srcTensor` and `dstTensor` are first constructed with the Tensor API. `slice` only obtains the starting address of each row; the non-contiguous destinations of the eight DataBlocks are specified by the `dstNzC0Stride` argument of `asc_storealign`.
103+ 
104+ ```cpp
105+ template <uint32_t dstNzC0Stride>
106+ __simd_vf__ inline void NdToNz(__ubuf__ half* dst, __ubuf__ half* src)
107+ {
108+ vector_bool mask = asc_create_mask_b16(PAT_ALL);
109+ vector_half value;
110+ asc_loadalign(value, src);
111+ asc_storealign(dst, value, dstNzC0Stride, 0, mask);
112+ }
113+ ```
114+ 
115+ The scenario difference is exposed at the final call site in the kernel:
116+ 
117+ ```cpp
118+ if constexpr (SCENARIO_NUM == 1) {
119+ NdToNz<TILE_H>(dstRow.data().get(), srcRow.data().get());
120+ } else {
121+ NdToNz<TILE_H + BANK_CONFLICT_OFFSET>(dstRow.data().get(), srcRow.data().get());
122+ }
123+ ```
124+ 
125+ - Invocation implementation:
126+ 
127+ The host-side invocation uses the kernel call operator `<<<>>>` to launch `bank_conflict_kernel`. The `SCENARIO_NUM` parameter selects the comparison scenario.
128+ 
129+ - UB bank structure and conflicts in this example:
130+ 
131+ The Unified Buffer of Ascend 950PR/Ascend 950DT is divided into 16 physical banks and organized into eight bank groups. Banks `i` and `i+8` belong to the same bank group, so `bank group = bank % 8`. UB addresses use low-order interleaving: for every 32-byte DataBlock traversed by a consecutive address, the physical bank number increases by one modulo 16.
132+ 
133+ This example focuses on write-write conflicts when one `asc_storealign` writes eight DataBlocks. The distance between adjacent destinations is controlled by `dstNzC0Stride`; when multiple destinations fall into the same bank group, the writes must be serialized.
134+ 
135+ **Figure: UB bank structure of Ascend 950PR/Ascend 950DT**
136+ 
137+ <img src="figures/ubBankStruct3510.png" width="80%">
138+ 
139+ **Figure: UB bank memory layout of Ascend 950PR/Ascend 950DT**
140+ 
141+ <img src="figures/UB-3510.png" width="80%">
142+ 
143+ **Scenario 1: Compact placement**
144+ 
145+ Build with `SCENARIO_NUM=1`. In this scenario, `dstNzC0Stride=144`, which is `16 x 9` DataBlocks. For one row, the physical bank number of all eight write destinations remains unchanged, so the eight accesses use the same bank and bank group, causing write-write conflicts.
146+ 
147+ **Figure: ND-to-NZ layout with compact placement in Scenario 1**
148+ 
149+ <img src="figures/datand2nzS1.png" width="80%">
150+ 
151+ Taking the first row of a tile as an example, the eight destinations are DataBlocks `0, 144, 288, ..., 1008`, corresponding to bank 0, bank 0, ..., bank 0. The starting bank changes with the row address, but the eight destinations of one store still fall into the same bank.
152+ 
153+ **Figure: UB bank conflicts in Scenario 1**
154+ 
155+ <img src="figures/s1bank3510.png" width="80%">
156+ 
157+ **Scenario 2: Increased stride and shifted NZ buffer base**
158+ 
159+ Build with `SCENARIO_NUM=2`. In this scenario, `dstNzC0Stride=145`, which is `16 x 9 + 1` DataBlocks. The physical bank number increases by one at every jump, so the eight write destinations enter eight different bank groups.
160+ 
161+ The code also shifts the initial `nzPtr` address by eight DataBlocks (`NZ_BASE_SHIFT_DATA_BLOCKS=8`). For the first row, `asc_loadalign` reads banks 0-7 and `asc_storealign` writes banks 8-15, separating the physical banks used by the initial read and write and reducing same-cycle bank overlap. The additional stride is only used to change UB destinations; the UB-to-GM transfer uses the NZ Tensor layout to skip the padding, so the output remains in compact NZ format.
162+ 
163+ **Figure: ND-to-NZ layout with increased stride in Scenario 2**
164+ 
165+ <img src="figures/datand2nzS2.png" width="80%">
166+ 
167+ **Figure: Distributed UB bank destinations in Scenario 2**
168+ 
169+ <img src="figures/s2bank3510.png" width="80%">
170+ 
171+## Tensor API Implementation Features
172+ 
173+| Feature | Example Implementation |
174+|---------|------------------------|
175+| Tensor representation | Use Tensor objects to describe GM, UB ND tiles, and UB NZ tiles |
176+| Tensor slicing | Use `slice` to obtain each tile and row start address |
177+| Data movement | Use `copy` for GM-to-UB and UB-to-GM transfers |
178+| ND-to-NZ rearrangement | Use `asc_loadalign` and `asc_storealign` for Vector register movement |
179+| Bank-conflict comparison | Compare compact and distributed placement with `dstNzC0Stride=144/145` |
180+| Address offset | Scenario 2 shifts the NZ base by eight DataBlocks to separate the physical banks used by the initial ND read and NZ write |
181+| Double buffering | Use ping-pong UB buffers to process tiles alternately |
182+| Tail-tile handling | Use `actualTileH` to limit the valid rows in the final tile |
183+ 
184+## Performance Data
185+ 
186+The following data was measured on Ascend 950PR/Ascend 950DT with `144 x 128` tiles and 64 launched blocks.
187+ 
188+| Scenario | `dstNzC0Stride` | Task Duration (us) | `aiv_time` (us) | `aiv_total_cycles` | `aiv_vec_time` (us) | `aiv_vec_ratio` | `aiv_scalar_time` (us) | `aiv_scalar_ratio` | `aiv_mte2_time` (us) | `aiv_mte2_ratio` | `aiv_mte3_time` (us) | `aiv_mte3_ratio` | `icache_miss_rate` |
189+| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
190+| S1 | 144 | 262.628 | 261.96 | 14112428 | **254.637** | 0.972 | 3.851 | 0.015 | 93.445 | 0.357 | 47.817 | 0.183 | 0.006 |
191+| S2 | 145 | 222.964 | 222.18 | 12052109 | **214.199** | 0.964 | 3.823 | 0.017 | 111.712 | 0.503 | 41.139 | 0.185 | 0.009 |
192+ 
193+The `aiv_vec_time` of S2 decreases from 254.637 us to 214.199 us, indicating that the increased stride significantly reduces write-write bank conflicts.
194+ 
195+## Build and Run
196+ 
197+Run the following steps in the root directory of this example to build and run the example.
198+ 
199+- Configure environment variables
200+ 
201+ Configure environment variables according to the CANN development kit [installation method](../../../../docs/en/quick_start.md#prepare&install) in the current environment. **Currently only [CANN master](../../../../docs/en/quick_start.md#cann-install) is supported.**
202+ 
203+ ```bash
204+ source ${install_path}/cann/set_env.sh
205+ ```
206+ 
207+ > **Note:** `${install_path}` is the CANN package installation directory. When no installation directory is specified, the default is `/usr/local/Ascend`.
208+ 
209+- Run the example
210+ 
211+ The following commands use Scenario 1 as an example. Run them in this example directory.
212+ 
213+ ```bash
214+ SCENARIO_NUM=1
215+ mkdir -p build && cd build; # Create and enter the build directory
216+ cmake -DSCENARIO_NUM=${SCENARIO_NUM} -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # Build the project (default NPU mode)
217+ python3 ../scripts/gen_data.py # Generate test input data
218+ ./demo # Run the compiled executable
219+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # Verify output correctness
220+ ```
221+ 
222+ To build Scenario 2, set `SCENARIO_NUM=2`.
223+ 
224+ To use NPU simulation mode, add the `-DCMAKE_ASC_RUN_MODE=sim` parameter:
225+ 
226+ ```bash
227+ cmake -DSCENARIO_NUM=${SCENARIO_NUM} -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU simulation mode
228+ ```
229+ 
230+ > **Note:** Clear the CMake cache before switching build modes. Run `rm CMakeCache.txt` in the build directory and then run CMake again.
231+ 
232+- Build option description
233+ 
234+ | Option | Available Values | Description |
235+ |--------|------------------|-------------|
236+ | `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | Run mode: NPU execution or NPU simulation |
237+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU architecture; dav-3510 corresponds to Ascend 950PR/Ascend 950DT |
238+ | `SCENARIO_NUM` | 1, 2 | 1: compact placement; 2: increased stride and shifted NZ buffer base |
239+ 
240+ > **Note:** This example only supports the dav-3510 architecture (Ascend 950PR/Ascend 950DT).
241+ 
242+- Execution result
243+ 
244+ The following output indicates that the precision comparison succeeded.
245+ 
246+ ```bash
247+ test pass!
248+ ```
@@ -0,0 +1,195 @@
1+/**
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 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+ * \file bank_conflict.asc
13+ * \brief Tensor API ND-to-NZ bank-conflict sample for Ascend 950PR/Ascend 950DT
14+ */
15+ 
16+#include <cstddef>
17+#include <cstdint>
18+ 
19+#include "acl/acl.h"
20+#include "c_api/asc_simd.h"
21+#include "data_utils.h"
22+#include "tensor_api/tensor.h"
23+ 
24+#ifndef SCENARIO_NUM
25+#define SCENARIO_NUM 1
26+#endif
27+ 
28+namespace {
29+constexpr uint32_t TOTAL_M = 8192;
30+constexpr uint32_t TOTAL_N = 8192;
31+constexpr uint32_t ROW_SPLITS = 8;
32+constexpr uint32_t COL_SPLITS = 8;
33+constexpr uint32_t TILE_H = 144;
34+constexpr uint32_t TILE_W = 128;
35+constexpr uint32_t C0_ELEMS = 16;
36+constexpr uint32_t TILE_C0_COLS = TILE_W / C0_ELEMS;
37+constexpr uint32_t TOTAL_ROW_TILES = (TOTAL_M + TILE_H - 1) / TILE_H;
38+constexpr uint32_t TOTAL_COL_TILES = TOTAL_N / TILE_W;
39+constexpr uint32_t TOTAL_BLOCKS = ROW_SPLITS * COL_SPLITS;
40+ 
41+// S1 uses the compact NZ stride. S2 adds one DataBlock to the stride between
42+// C0 blocks so the eight writes in one store land in different bank groups.
43+constexpr uint32_t BANK_CONFLICT_OFFSET = 1;
44+constexpr bool ADD_BANK_OFFSET = SCENARIO_NUM == 2;
45+constexpr uint32_t LOCAL_COLUMN_STRIDE = ADD_BANK_OFFSET ? TILE_H + BANK_CONFLICT_OFFSET : TILE_H;
46+constexpr uint32_t ND_BUFFER_ELEMS = TILE_H * TILE_W;
47+constexpr uint32_t NZ_DATA_BLOCKS = (TILE_C0_COLS - 1) * LOCAL_COLUMN_STRIDE + TILE_H;
48+constexpr uint32_t NZ_SLOT_DATA_BLOCKS = (NZ_DATA_BLOCKS + 15) / 16 * 16;
49+constexpr uint32_t NZ_SLOT_ELEMS = NZ_SLOT_DATA_BLOCKS * C0_ELEMS;
50+ 
51+// Keep the optimized member of each pair at bank 8, as in the 3510 reference
52+// sample. The baseline member starts at bank 0.
53+constexpr uint32_t NZ_BASE_SHIFT_DATA_BLOCKS = ADD_BANK_OFFSET ? 8 : 0;
54+constexpr uint32_t NZ_PONG_PAD_DATA_BLOCKS = (16 - (NZ_SLOT_DATA_BLOCKS % 16)) % 16;
55+constexpr uint32_t ND_PING_OFFSET = 0;
56+constexpr uint32_t ND_PONG_OFFSET = ND_PING_OFFSET + ND_BUFFER_ELEMS;
57+constexpr uint32_t NZ_PING_OFFSET = ND_PONG_OFFSET + ND_BUFFER_ELEMS + NZ_BASE_SHIFT_DATA_BLOCKS * C0_ELEMS;
58+constexpr uint32_t NZ_PONG_OFFSET = NZ_PING_OFFSET + NZ_SLOT_ELEMS + NZ_PONG_PAD_DATA_BLOCKS * C0_ELEMS;
59+constexpr uint32_t UB_STORAGE_ELEMS = NZ_PONG_OFFSET + NZ_SLOT_ELEMS;
60+ 
61+static_assert(SCENARIO_NUM >= 1 && SCENARIO_NUM <= 2, "SCENARIO_NUM must be 1 or 2");
62+static_assert(TOTAL_N % TILE_W == 0, "TOTAL_N must be divisible by TILE_W");
63+static_assert(TOTAL_COL_TILES % COL_SPLITS == 0, "column tiles must be divisible by COL_SPLITS");
64+static_assert(TOTAL_ROW_TILES >= ROW_SPLITS, "ROW_SPLITS cannot exceed the number of row tiles");
65+static_assert(TILE_W % C0_ELEMS == 0, "TILE_W must be C0 aligned");
66+} // namespace
67+ 
68+template <uint32_t dstNzC0Stride>
69+__simd_vf__ inline void NdToNz(__ubuf__ half* dst, __ubuf__ half* src)
70+{
71+ vector_bool mask = asc_create_mask_b16(PAT_ALL);
72+ vector_half value;
73+ asc_loadalign(value, src);
74+ asc_storealign(dst, value, dstNzC0Stride, 0, mask);
75+}
76+ 
77+__global__ __vector__ void bank_conflict_kernel(__gm__ half* x, __gm__ half* z)
78+{
79+ asc_init();
80+ using namespace asc::te;
81+ 
82+ const uint32_t blockIdx = block_idx;
83+ if (blockIdx >= TOTAL_BLOCKS) {
84+ return;
85+ }
86+ 
87+ const uint32_t rowSplit = blockIdx / COL_SPLITS;
88+ const uint32_t colSplit = blockIdx % COL_SPLITS;
89+ const uint32_t baseRowTiles = TOTAL_ROW_TILES / ROW_SPLITS;
90+ const uint32_t extraRowTiles = TOTAL_ROW_TILES % ROW_SPLITS;
91+ const uint32_t rowTileBegin = rowSplit * baseRowTiles + ((rowSplit < extraRowTiles) ? rowSplit : extraRowTiles);
92+ const uint32_t rowTileCount = baseRowTiles + ((rowSplit < extraRowTiles) ? 1 : 0);
93+ const uint32_t colTilesPerSplit = TOTAL_COL_TILES / COL_SPLITS;
94+ const uint32_t colTileBegin = colSplit * colTilesPerSplit;
95+ const uint32_t tilesPerBlock = rowTileCount * colTilesPerSplit;
96+ 
97+ __ubuf__ half ubStorage[UB_STORAGE_ELEMS];
98+ auto gmXLayout = make_frame_layout<nd_layout_ptn, layout_trait_default<half>>(TOTAL_M, TOTAL_N);
99+ auto ndLayout = make_frame_layout<nd_layout_ptn, layout_trait_default<half>>(TILE_H, TILE_W);
100+ auto gmX = make_tensor(make_mem_ptr(x), gmXLayout);
101+ auto copyGmToUb = make_copy(copy_gm_to_ub{}, gm_to_ub_trait_default{});
102+ auto copyUbToGm = make_copy(copy_ub_to_gm{}, ub_to_gm_trait_default{});
103+ 
104+ for (uint32_t tileIdx = 0; tileIdx < tilesPerBlock; ++tileIdx) {
105+ const uint32_t slot = tileIdx & 1;
106+ const uint32_t tileRow = rowTileBegin + tileIdx / colTilesPerSplit;
107+ const uint32_t tileCol = colTileBegin + tileIdx % colTilesPerSplit;
108+ const uint32_t rowStart = tileRow * TILE_H;
109+ const uint32_t colStart = tileCol * TILE_W;
110+ const uint32_t remainRows = TOTAL_M - rowStart;
111+ const uint32_t actualTileH = remainRows < TILE_H ? remainRows : TILE_H;
112+ 
113+ __ubuf__ half* ndPtr = ubStorage + (slot == 0 ? ND_PING_OFFSET : ND_PONG_OFFSET);
114+ __ubuf__ half* nzPtr = ubStorage + (slot == 0 ? NZ_PING_OFFSET : NZ_PONG_OFFSET);
115+ auto ndTensor = make_tensor(make_mem_ptr(ndPtr), ndLayout);
116+ 
117+ asc_lock(PIPE_MTE2, slot);
118+ copy(copyGmToUb, ndTensor, gmX, zero_coord, make_coord(rowStart, colStart), make_shape(actualTileH, TILE_W));
119+ asc_unlock(PIPE_MTE2, slot);
120+ 
121+ asc_lock(PIPE_V, slot);
122+ auto srcLayout =
123+ make_pattern_layout<nd_layout_ptn, half>(make_shape(TILE_H, TILE_W), make_stride(TILE_W, _1{}));
124+ auto dstLayout =
125+ make_pattern_layout<nd_layout_ptn, half>(make_shape(TILE_H, C0_ELEMS), make_stride(C0_ELEMS, _1{}));
126+ auto srcTensor = make_tensor(make_mem_ptr(ndPtr), srcLayout);
127+ auto dstTensor = make_tensor(make_mem_ptr(nzPtr), dstLayout);
128+ for (uint32_t row = 0; row < actualTileH; ++row) {
129+ auto srcRow = srcTensor.slice(make_coord(row, 0), make_shape(1, TILE_W));
130+ auto dstRow = dstTensor.slice(make_coord(row, 0), make_shape(1, C0_ELEMS));
131+ if constexpr (SCENARIO_NUM == 1) {
132+ NdToNz<TILE_H>(dstRow.data().get(), srcRow.data().get());
133+ } else {
134+ NdToNz<TILE_H + BANK_CONFLICT_OFFSET>(dstRow.data().get(), srcRow.data().get());
135+ }
136+ }
137+ asc_unlock(PIPE_V, slot);
138+ 
139+ const uint32_t dstDataBlockOffset = rowStart + (colStart / C0_ELEMS) * TOTAL_M;
140+ auto nzLayout = make_pattern_layout<nd_layout_ptn, half>(
141+ make_shape(TILE_C0_COLS, actualTileH * C0_ELEMS), make_stride(LOCAL_COLUMN_STRIDE * C0_ELEMS, _1{}));
142+ auto gmZLayout = make_pattern_layout<nd_layout_ptn, half>(
143+ make_shape(TILE_C0_COLS, actualTileH * C0_ELEMS), make_stride(TOTAL_M * C0_ELEMS, _1{}));
144+ auto nzTensor = make_tensor(make_mem_ptr(nzPtr), nzLayout);
145+ auto gmZ = make_tensor(make_mem_ptr(z + dstDataBlockOffset * C0_ELEMS), gmZLayout);
146+ 
147+ asc_lock(PIPE_MTE3, slot);
148+ copy(copyUbToGm, gmZ, nzTensor);
149+ asc_unlock(PIPE_MTE3, slot);
150+ }
151+ 
152+ asc_sync_pipe(PIPE_ALL);
153+}
154+ 
155+int32_t main(int32_t argc, char* argv[])
156+{
157+ (void)argc;
158+ (void)argv;
159+ 
160+ constexpr size_t inputByteSize = static_cast<size_t>(TOTAL_M) * TOTAL_N * sizeof(half);
161+ constexpr size_t outputByteSize = static_cast<size_t>(TOTAL_M) * TOTAL_N * sizeof(half);
162+ 
163+ aclInit(nullptr);
164+ int32_t deviceId = 0;
165+ aclrtSetDevice(deviceId);
166+ aclrtStream stream = nullptr;
167+ aclrtCreateStream(&stream);
168+ 
169+ half* xHost = nullptr;
170+ half* zHost = nullptr;
171+ half* xDevice = nullptr;
172+ half* zDevice = nullptr;
173+ aclrtMallocHost((void**)(&xHost), inputByteSize);
174+ aclrtMallocHost((void**)(&zHost), outputByteSize);
175+ aclrtMalloc((void**)&xDevice, inputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
176+ aclrtMalloc((void**)&zDevice, outputByteSize, ACL_MEM_MALLOC_HUGE_FIRST);
177+ 
178+ ReadFile("./input/input.bin", xHost, inputByteSize);
179+ aclrtMemcpy(xDevice, inputByteSize, xHost, inputByteSize, ACL_MEMCPY_HOST_TO_DEVICE);
180+ 
181+ bank_conflict_kernel<<<TOTAL_BLOCKS, 0, stream>>>(xDevice, zDevice);
182+ aclrtSynchronizeStream(stream);
183+ 
184+ aclrtMemcpy(zHost, outputByteSize, zDevice, outputByteSize, ACL_MEMCPY_DEVICE_TO_HOST);
185+ WriteFile("./output/output.bin", zHost, outputByteSize);
186+ 
187+ aclrtFree(xDevice);
188+ aclrtFree(zDevice);
189+ aclrtFreeHost(xHost);
190+ aclrtFreeHost(zHost);
191+ aclrtDestroyStream(stream);
192+ aclrtResetDevice(deviceId);
193+ aclFinalize();
194+ return 0;
195+}
@@ -0,0 +1,81 @@
1+/**
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 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+#ifndef BANK_CONFLICT_DATA_UTILS_H
12+#define BANK_CONFLICT_DATA_UTILS_H
13+ 
14+#include <fcntl.h>
15+#include <sys/stat.h>
16+#include <unistd.h>
17+ 
18+#include <cstddef>
19+#include <cstdio>
20+#include <fstream>
21+#include <string>
22+ 
23+// Read exactly expectedSize bytes. Tensor samples use binary files whose
24+// shape is fixed by the compile-time sample configuration, so accepting a
25+// truncated or stale file would otherwise make a run appear successful.
26+inline bool ReadFile(const std::string& path, void* buffer, size_t expectedSize)
27+{
28+ if (buffer == nullptr) {
29+ std::fprintf(stderr, "[ERROR] null input buffer for %s\n", path.c_str());
30+ return false;
31+ }
32+ 
33+ struct stat fileStat {};
34+ if (stat(path.c_str(), &fileStat) != 0 || !S_ISREG(fileStat.st_mode)) {
35+ std::fprintf(stderr, "[ERROR] input file does not exist: %s\n", path.c_str());
36+ return false;
37+ }
38+ const size_t fileSize = static_cast<size_t>(fileStat.st_size);
39+ if (fileSize != expectedSize) {
40+ std::fprintf(
41+ stderr, "[ERROR] invalid file size for %s: expected %zu, got %zu\n", path.c_str(), expectedSize, fileSize);
42+ return false;
43+ }
44+ 
45+ std::ifstream file(path, std::ios::binary);
46+ if (!file.read(static_cast<char*>(buffer), static_cast<std::streamsize>(expectedSize))) {
47+ std::fprintf(stderr, "[ERROR] failed to read file: %s\n", path.c_str());
48+ return false;
49+ }
50+ return true;
51+}
52+ 
53+inline bool WriteFile(const std::string& path, const void* buffer, size_t size)
54+{
55+ if (buffer == nullptr) {
56+ std::fprintf(stderr, "[ERROR] null output buffer for %s\n", path.c_str());
57+ return false;
58+ }
59+ 
60+ const int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
61+ if (fd < 0) {
62+ std::fprintf(stderr, "[ERROR] failed to open output file: %s\n", path.c_str());
63+ return false;
64+ }
65+ 
66+ const char* data = static_cast<const char*>(buffer);
67+ size_t written = 0;
68+ while (written < size) {
69+ const ssize_t count = write(fd, data + written, size - written);
70+ if (count <= 0) {
71+ std::fprintf(stderr, "[ERROR] failed to write output file: %s\n", path.c_str());
72+ (void)close(fd);
73+ return false;
74+ }
75+ written += static_cast<size_t>(count);
76+ }
77+ (void)close(fd);
78+ return true;
79+}
80+ 
81+#endif // BANK_CONFLICT_DATA_UTILS_H
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:4e0b1fcb7f95f3c50b310803902c6bc3497624b32ebb18753b90d7d2ccf34155
3+size 489826
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:e55384daaf33d9357c9be7f36406801304c30bc8acb17d2f6223e4eac7f8b58e
3+size 42056
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:fd3dafa2487444152ecea41c8661f10fcce4b0505119c84c9008f52605d2981e
3+size 42656
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:e52ab7bf6e9fba4d09bd6c065d16dff5869e0b72139a08488507b951d234b2db
3+size 159517
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:e65f916f8c268bf083a8ce168e5ed78a1b0164c828d9a10ed45cee5b007bcce1
3+size 527750
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:2d1f1e7c013454bc82aee6347f16d7f0359a6e00fb8152288a6890d6d78712d5
3+size 545941
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:1a8ce721d64ca9558e0ca0ae7fb6d0dddc600dd5d1c1956b656e6564ba4ecf1b
3+size 411262
@@ -0,0 +1,68 @@
1+#!/usr/bin/env python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2026 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+"""Generate an ND input matrix and its compact NZ reference."""
15+ 
16+from __future__ import annotations
17+ 
18+import argparse
19+from pathlib import Path
20+ 
21+import numpy as np
22+ 
23+ 
24+DEFAULT_M = 8192
25+DEFAULT_N = 8192
26+DEFAULT_SEED = 2026
27+C0 = 16
28+ 
29+ 
30+def nd_to_nz(matrix: np.ndarray) -> np.ndarray:
31+ m, n = matrix.shape
32+ if m <= 0 or n <= 0 or n % C0 != 0:
33+ raise ValueError(f"matrix shape must have positive dimensions and N divisible by {C0}: {matrix.shape}")
34+ blocks = matrix.reshape(m, n // C0, C0)
35+ return np.ascontiguousarray(blocks.transpose(1, 0, 2)).reshape(-1)
36+ 
37+ 
38+def generate_data(m: int, n: int, seed: int) -> None:
39+ if m <= 0 or n <= 0 or m % C0 != 0 or n % C0 != 0:
40+ raise ValueError(f"M and N must be positive multiples of {C0}, got M={m}, N={n}")
41+ 
42+ rng = np.random.default_rng(seed)
43+ # Integer-valued half input keeps the expected result exactly
44+ # representable and makes failures easy to inspect in a simulator dump.
45+ matrix = rng.integers(-128, 129, size=(m, n), dtype=np.int16).astype(np.float16)
46+ golden = nd_to_nz(matrix)
47+ 
48+ input_dir = Path("input")
49+ output_dir = Path("output")
50+ input_dir.mkdir(parents=True, exist_ok=True)
51+ output_dir.mkdir(parents=True, exist_ok=True)
52+ matrix.tofile(input_dir / "input.bin")
53+ golden.tofile(output_dir / "golden.bin")
54+ print(f"generated ND input: shape=({m}, {n}), seed={seed}")
55+ print(f"generated NZ golden: elements={golden.size}")
56+ 
57+ 
58+def parse_args() -> argparse.Namespace:
59+ parser = argparse.ArgumentParser(description=__doc__)
60+ parser.add_argument("--m", type=int, default=DEFAULT_M, help=f"input rows (default: {DEFAULT_M})")
61+ parser.add_argument("--n", type=int, default=DEFAULT_N, help=f"input columns (default: {DEFAULT_N})")
62+ parser.add_argument("--seed", type=int, default=DEFAULT_SEED, help=f"random seed (default: {DEFAULT_SEED})")
63+ return parser.parse_args()
64+ 
65+ 
66+if __name__ == "__main__":
67+ args = parse_args()
68+ generate_data(args.m, args.n, args.seed)
@@ -0,0 +1,70 @@
1+#!/usr/bin/env python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2026 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+"""Verify the compact NZ output produced by the bank-conflict sample."""
15+ 
16+from __future__ import annotations
17+ 
18+import argparse
19+from pathlib import Path
20+ 
21+import numpy as np
22+ 
23+ 
24+DEFAULT_M = 8192
25+DEFAULT_N = 8192
26+ 
27+ 
28+def load_data(path: Path, expected_elements: int) -> np.ndarray:
29+ values = np.fromfile(path, dtype=np.float16)
30+ if values.size != expected_elements:
31+ raise ValueError(f"{path} contains {values.size} half values, expected {expected_elements}")
32+ return values
33+ 
34+ 
35+def verify(output_path: Path, golden_path: Path, m: int, n: int) -> bool:
36+ if m <= 0 or n <= 0:
37+ raise ValueError("matrix dimensions must be positive")
38+ expected_elements = m * n
39+ output = load_data(output_path, expected_elements)
40+ golden = load_data(golden_path, expected_elements)
41+ equal = output == golden
42+ if np.all(equal):
43+ print(f"test pass! verified {expected_elements} compact NZ elements")
44+ return True
45+ 
46+ failed = np.flatnonzero(~equal)
47+ for flat_index in failed[:10]:
48+ index = int(flat_index)
49+ print(f"mismatch at flat index {index}: expected={golden[index]}, actual={output[index]}")
50+ print(f"[ERROR] {failed.size} of {expected_elements} elements differ")
51+ return False
52+ 
53+ 
54+def parse_args() -> argparse.Namespace:
55+ parser = argparse.ArgumentParser(description=__doc__)
56+ parser.add_argument("output", type=Path)
57+ parser.add_argument("golden", type=Path)
58+ parser.add_argument("--m", type=int, default=DEFAULT_M, help=f"input rows (default: {DEFAULT_M})")
59+ parser.add_argument("--n", type=int, default=DEFAULT_N, help=f"input columns (default: {DEFAULT_N})")
60+ return parser.parse_args()
61+ 
62+ 
63+if __name__ == "__main__":
64+ args = parse_args()
65+ try:
66+ passed = verify(args.output, args.golden, args.m, args.n)
67+ except (OSError, ValueError) as error:
68+ print(f"[ERROR] {error}")
69+ raise SystemExit(1)
70+ raise SystemExit(0 if passed else 1)
@@ -11,9 +11,7 @@ C[b] = A[b] * B[b] + Bias[b], b = 0, 1, ..., B - 1
11 11 
12| 产品 | CANN软件版本 |12| 产品 | CANN软件版本 |
13|------|-------------|13|------|-------------|
14-| <cann-filter npu-type="950">Ascend 950PR/Ascend 950DT</cann-filter> | >= CANN 9.1.0 |14+| <cann-filter npu-type="950">Ascend 950PR/Ascend 950DT</cann-filter> | >= CANN 9.2.0 |
15- 
16-> **说明:** 该样例依赖尚未正式发布的CANN特性,请使用最新的CANN master包。
17 15 
18## 目录结构介绍16## 目录结构介绍
19 17 
@@ -11,9 +11,7 @@ C[b] = A[b] * B[b] + Bias[b], b = 0, 1, ..., B - 1
11 11 
12| Product | CANN Version |12| Product | CANN Version |
13|---------|-------------|13|---------|-------------|
14-| <cann-filter npu-type="950">Ascend 950PR/Ascend 950DT</cann-filter> | >= CANN 9.1.0 |14+| <cann-filter npu-type="950">Ascend 950PR/Ascend 950DT</cann-filter> | >= CANN 9.2.0 |
15- 
16-> **Note:** This example depends on CANN features that have not been officially released. Use the latest CANN master package.
17 15 
18## Directory Structure16## Directory Structure
19 17 
@@ -10,7 +10,7 @@
10 10 
11| 产品 | CANN软件版本 |11| 产品 | CANN软件版本 |
12|------|-------------|12|------|-------------|
13-| Ascend 950PR/Ascend 950DT | >= CANN 9.1.0 |13+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
14 14 
15## 目录结构介绍15## 目录结构介绍
16 16 
@@ -10,7 +10,7 @@ This sample supports three Global Memory input/output data formats (NC1HWC0, NCH
10 10 
11| Product | CANN Software Version |11| Product | CANN Software Version |
12|---------|----------------------|12|---------|----------------------|
13-| Ascend 950PR/Ascend 950DT | >= CANN 9.1.0 |13+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
14 14 
15## Directory Structure15## Directory Structure
16 16 
@@ -8,9 +8,7 @@
8 8 
9| 产品 | CANN软件版本 |9| 产品 | CANN软件版本 |
10|------|-------------|10|------|-------------|
11-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |11+| Ascend 950PR/Ascend 950DT | >=CANN 9.2.0 |
12- 
13-> **说明:** 该样例依赖尚未正式发布的CANN特性,请使用最新的CANN master包。
14 12 
15## 目录结构介绍13## 目录结构介绍
16 14 
@@ -9,9 +9,7 @@ This example implements dynamic shape matrix multiplication with Bias based on t
9 9 
10| Product | CANN Version |10| Product | CANN Version |
11|---------|-------------|11|---------|-------------|
12-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |12+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
13- 
14-> **Note:** This example depends on CANN features that have not been officially released. Use the latest CANN master package.
15 13 
16## Directory Structure14## Directory Structure
17 15 
@@ -8,9 +8,7 @@
8 8 
9| 产品 | CANN软件版本 |9| 产品 | CANN软件版本 |
10|------|-------------|10|------|-------------|
11-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |11+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12- 
13-> **说明:** 该样例依赖尚未正式发布的CANN特性,请使用最新的CANN master包。
14 12 
15## 目录结构介绍13## 目录结构介绍
16 14 
@@ -9,9 +9,7 @@ This example implements dynamic Shape matrix multiplication with Bias based on t
9 9 
10| Product | CANN Version |10| Product | CANN Version |
11|---------|-------------|11|---------|-------------|
12-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |12+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
13- 
14-> **Note:** This example depends on CANN features that have not been officially released. Use the latest CANN master package.
15 13 
16## Directory Structure14## Directory Structure
17 15 
@@ -0,0 +1,40 @@
1+# ----------------------------------------------------------------------------------------------------------
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 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+set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu, sim")
15+set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510")
16+option(CANN_ASC_USE_EXPERIMENTAL "Enable required CANN ASC APIs" OFF)
17+ 
18+if(NOT CMAKE_ASC_RUN_MODE STREQUAL "npu" AND NOT CMAKE_ASC_RUN_MODE STREQUAL "sim")
19+ message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be 'npu' or 'sim'")
20+endif()
21+if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510")
22+ message(FATAL_ERROR "matmul_bias_fusion only supports dav-3510")
23+endif()
24+if(NOT CANN_ASC_USE_EXPERIMENTAL)
25+ message(FATAL_ERROR "matmul_bias_fusion requires CANN_ASC_USE_EXPERIMENTAL=ON")
26+endif()
27+ 
28+find_package(ASC REQUIRED)
29+project(matmul_bias_fusion LANGUAGES ASC CXX)
30+ 
31+add_executable(demo matmul_bias_fusion.asc)
32+set(SAMPLE_M 1024)
33+set(SAMPLE_K 256)
34+set(SAMPLE_N 1024)
35+file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/sample_config.json"
36+ CONTENT "{\"m\": ${SAMPLE_M}, \"k\": ${SAMPLE_K}, \"n\": ${SAMPLE_N}}\n")
37+target_compile_options(demo PRIVATE
38+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>
39+ $<$<AND:$<COMPILE_LANGUAGE:ASC>,$<BOOL:${CANN_ASC_USE_EXPERIMENTAL}>>:-DCANN_ASC_USE_EXPERIMENTAL>
40+)
@@ -0,0 +1,225 @@
1+# 基于Tensor API实现的Matmul Bias CV融合样例
2+ 
3+## 概述
4+ 
5+本样例基于Tensor API编程方式实现Cube和Vector的CV融合计算。Cube侧使用Tensor API完成矩阵乘法和Bias融合,Vector侧使用VF接口将Cube结果与Residual逐元素相加,最终实现:
6+ 
7+$$
8+Y = A \times B + Bias + Residual
9+$$
10+ 
11+样例使用一个`__mix__(1, 2)` kernel,同时启动1个AIC和2个AIV。Cube将L0C结果通过`copy_l0c_to_ub`的`dual_dst_mode::split_m`按M轴拆分到两个Vector子块,Vector完成加法后将结果写回GM,展示同一kernel内的CV数据传递和流水协同。
12+ 
13+## 本样例支持的产品及CANN软件版本
14+ 
15+| 产品 | CANN软件版本 |
16+|------|-------------|
17+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
18+ 
19+> **说明:** 该样例依赖尚未正式发布的CANN特性,请使用最新的CANN master包。
20+ 
21+## 目录结构介绍
22+ 
23+```text
24+├── matmul_bias_fusion
25+│ ├── scripts
26+│ │ ├── gen_data.py // 输入数据和float32真值生成脚本
27+│ │ └── verify_result.py // 输出与真值对比脚本
28+│ ├── CMakeLists.txt // 编译工程文件
29+│ ├── data_utils.h // 数据读入写出函数
30+│ ├── matmul_bias_fusion.asc // Ascend C样例实现和调用样例
31+│ └── README.md // 样例说明文档
32+```
33+ 
34+## 样例描述
35+ 
36+- 样例功能:
37+ 
38+ 1. **Cube侧Matmul和Bias融合**
39+ 
40+ Cube侧将A和B从GM搬运到L1,再搬运到L0A/L0B,使用`mmad`完成矩阵乘法。Bias从GM经L1和Bias表搬运到L0Bias,仅在每个输出tile的第一次`mmad`中传入;后续K迭代只累加矩阵乘结果,避免重复添加Bias。
41+ 
42+ 2. **Vector侧Residual加法**
43+ 
44+ Cube侧把L0C中的`float`结果搬运到UB。`dual_dst_mode::split_m`将一个tile沿M轴平均拆为两个目标,分别提供给两个AIV。每个AIV从对应半块读取Cube结果和GM中的Residual,调用`ComputeAdd`完成逐元素相加,再将结果写回GM。
45+ 
46+ 3. **CV流水协同**
47+ 
48+ 输出tile使用两组UB slot(`PIPE_DEPTH=2`)交替复用。AIC在复用slot前等待两个AIV完成上一轮消费;完成L0C到UB搬运后通知AIV;两个AIV完成加法和UB到GM写回后再通知AIC。跨AIC/AIV通知使用`asc_sync_block_wait`和`asc_sync_block_arrive`,不会为Vector路径另起一个kernel。
49+ 
50+ 4. **计算公式**
51+ 
52+ Bias按列广播,Residual与矩阵结果逐元素相加:
53+ 
54+ $$
55+ T_{m,n}=\sum_{k=0}^{K-1} A_{m,k}B_{k,n}+Bias_n
56+ $$
57+ $$
58+ Y_{m,n}=T_{m,n}+Residual_{m,n}
59+ $$
60+ 
61+- `ComputeAdd`实现:
62+ 
63+ `ComputeAdd`是标记为`__simd_vf__`的Vector函数,输入和输出均为UB中的一维Tensor。函数先通过`update_mask<float>(length)`生成有效元素掩码,再对两个输入Tensor执行带掩码的`load`,计算`lhs + rhs`,最后使用`store`写入输出Tensor。`length`由当前列尾块的有效元素数决定,因此不会访问tile中的padding元素。
64+ 
65+ ```cpp
66+ template <typename Src0Tensor, typename Src1Tensor, typename DstTensor>
67+ __simd_vf__ inline void ComputeAdd(Src0Tensor src0, Src1Tensor src1,
68+ DstTensor dst, uint32_t length)
69+ {
70+ const auto coord = asc::te::make_coord(0);
71+ auto mask = asc::te::experimental::update_mask<float>(length);
72+ auto lhs = asc::te::experimental::load(src0, coord).with_mask(mask);
73+ auto rhs = asc::te::experimental::load(src1, coord).with_mask(mask);
74+ asc::te::experimental::store(dst, coord, lhs + rhs);
75+ }
76+ ```
77+ 
78+- 样例规格:
79+ 
80+ 默认Shape为`M=1024`、`N=1024`、`K=256`。每个Cube block处理`singleCoreM=256`、`singleCoreN=128`的输出区域,共启动32个mixed block。
81+ 
82+ <table border="2">
83+ <caption>样例规格表</caption>
84+ <tr><td rowspan="1" align="left">样例类型(OpType)</td><td colspan="4" align="left">Matmul with Bias and Residual</td></tr>
85+ <tr><td rowspan="6" align="left">样例输入</td><td align="left">name</td><td align="left">shape</td><td align="left">data type</td><td align="left">format</td></tr>
86+ <tr><td align="left">A(矩阵A)</td><td align="left">[M, K]</td><td align="left">half</td><td align="left">ND</td></tr>
87+ <tr><td align="left">B(矩阵B)</td><td align="left">[K, N]</td><td align="left">half</td><td align="left">ND</td></tr>
88+ <tr><td align="left">Bias</td><td align="left">[N]</td><td align="left">float</td><td align="left">ND</td></tr>
89+ <tr><td align="left">Residual</td><td align="left">[M, N]</td><td align="left">float</td><td align="left">ND</td></tr>
90+ <tr><td align="left">tiling</td><td align="left">MatmulTiling结构体</td><td align="left">int32_t</td><td align="left">ND</td></tr>
91+ <tr><td rowspan="1" align="left">样例输出</td><td align="left">Y(输出矩阵)</td><td align="left">[M, N]</td><td align="left">float</td><td align="left">ND</td></tr>
92+ <tr><td rowspan="1" align="left">核函数名</td><td colspan="4" align="left">matmul_bias_fusion</td></tr>
93+ </table>
94+ 
95+ 编译期参数默认值如下:
96+ 
97+ | 参数 | 默认值 | 说明 |
98+ | :--- | :---: | :--- |
99+ | `BASE_M` | 128 | Cube输出tile的M维大小 |
100+ | `BASE_N` | 128 | Cube输出tile的N维大小 |
101+ | `BASE_K` | 64 | Cube K维基础分块大小 |
102+ | `STEP_M` | 1 | L1 M维步进 |
103+ | `STEP_N` | 1 | L1 N维步进 |
104+ | `STEP_K` | 4 | L1 K维步进 |
105+ | `VECTOR_LEN` | 64 | 一次Vector加法的最大元素数 |
106+ | `PIPE_DEPTH` | 2 | UB slot数量 |
107+ 
108+ 运行时Tiling参数默认值如下:
109+ 
110+ | 参数 | 默认值 | 说明 |
111+ | :--- | :---: | :--- |
112+ | `m` | 1024 | 矩阵A的行数 |
113+ | `n` | 1024 | 矩阵B的列数 |
114+ | `k` | 256 | 矩阵A的列数/矩阵B的行数 |
115+ | `singleCoreM` | 256 | 单个Cube block处理的M维大小 |
116+ | `singleCoreN` | 128 | 单个Cube block处理的N维大小 |
117+ | `singleCoreK` | 256 | 单个Cube block处理的K维大小 |
118+ 
119+## 样例实现
120+ 
121+### Tensor布局和数据搬运
122+ 
123+| Tensor | 布局 | 用途 |
124+| :--- | :--- | :--- |
125+| GM中的A、B、Bias、Residual、Y | `nd_ext_layout_ptn`(ND) | 描述主存中的输入和输出 |
126+| L1中的A、B | `nz_layout_ptn`(NZ) | 为Cube搬运和计算准备数据 |
127+| L1中的Bias | `nd_ext_layout_ptn`(ND) | 暂存Bias列向量 |
128+| L0A | `nz_layout_ptn`(NZ) | Cube矩阵A |
129+| L0B | `zn_layout_ptn`(ZN) | Cube矩阵B |
130+| L0C | `nz_layout_ptn`(NZ) | float矩阵乘累加结果 |
131+| UB中的tile和Vector临时Tensor | ND/一维布局 | AIC到AIV的数据交接及VF计算 |
132+ 
133+### 实现流程
134+ 
135+| 步骤 | Tensor API/C API操作 | 功能 | 布局或执行单元 |
136+| :--- | :--- | :--- | :--- |
137+| 1 | `make_tensor`、`make_mem_ptr`、`make_frame_layout` | 创建GM、L1、L0和UB Tensor视图,并按block索引取得当前M/N区域 | GM为ND,Cube缓存为NZ/ZN |
138+| 2 | `copy(copy_gm_to_l1)` | 搬运A、B和Bias到L1 | A/B为ND到NZ,Bias保持ND |
139+| 3 | `copy(copy_l1_to_l0a/copy_l1_to_l0b/copy_l1_to_biastable)` | 搬运Cube输入和Bias到L0A、L0B、L0Bias | 准备Cube计算 |
140+| 4 | `mmad` | 按K维迭代完成矩阵乘累加,并在第一次迭代注入Bias | AIC/Cube |
141+| 5 | `copy(copy_l0c_to_ub)` | 使用`dual_dst_mode::split_m`把L0C tile拆成两个M半块 | L0C结果按M轴双目标搬运到两个AIV各自的UB |
142+| 6 | `asc_sync_block_wait/arrive` | 在AIC和两个AIV之间传递每个slot的就绪和消费完成事件 | CV同步 |
143+| 7 | `copy(copy_ub_to_ub)`、`copy(copy_gm_to_ub)` | 读取Cube半块和Residual到Vector临时UB | AIV/Vector |
144+| 8 | `ComputeAdd` | 对有效元素执行masked `load`、逐元素加法和`store` | AIV/VF |
145+| 9 | `copy(copy_ub_to_gm)` | 将加法结果写回Y对应的GM区域 | AIV到GM |
146+ 
147+### Cube侧Matmul流程
148+ 
149+每个AIC block根据`block_idx`定位一个`singleCoreM × singleCoreN`区域,在该区域内按`BASE_M`、`BASE_N`划分输出tile。对每个tile,A和B沿K轴按`BASE_K`循环搬运并调用`mmad`:第一次调用设置`init_with_zero=true`并传入L0Bias,后续调用设置`init_with_zero=false`,从而得到`A × B + Bias`的L0C结果。
150+ 
151+### Vector侧加法流程
152+ 
153+每个AIV通过`asc_get_sub_block_id()`确定自己负责的M半块。收到AIC对应slot的通知后,逐行、逐`VECTOR_LEN`列处理:先将UB中的Cube结果复制到Vector临时Tensor,再把Residual从GM搬到UB,调用`ComputeAdd`,最后将输出Tensor复制到Y的GM切片。两个AIV负责互不重叠的行区间。
154+ 
155+### L0C到UB的双目标和同步
156+ 
157+`copy_l0c_to_ub`使用以下trait:
158+ 
159+```cpp
160+{ asc::te::round_mode::default_round, false, false,
161+ asc::te::dual_dst_mode::split_m }
162+```
163+ 
164+对于每个输出tile,AIC把前半M写入sub-block 0、后半M写入sub-block 1。两组slot按`sequence % PIPE_DEPTH`复用,AIC到AIV的flag为8、9,AIV到AIC的flag为10、11。AIC在重用slot前通过`PIPE_MTE2`等待两个AIV完成,AIC完成搬运后在`PIPE_FIX`通知AIV;AIV在`PIPE_S`等待数据就绪,并在`PIPE_MTE3`完成写回后通知AIC,保证UB不会在Vector读取前被覆盖,形成完整的CV流水依赖。
165+ 
166+## Tensor API实现特点
167+ 
168+| 特性 | 本样例实现 |
169+| :--- | :--- |
170+| 张量表示 | 使用Tensor对象描述GM、L1、L0C和UB中的各级数据 |
171+| 矩阵计算 | 使用`mmad`完成Cube侧矩阵乘加,Bias仅在首次K迭代注入 |
172+| CV融合 | 使用一个`__mix__(1, 2)` kernel连接1个AIC和2个AIV |
173+| 双目标搬运 | 使用`copy_l0c_to_ub`的`dual_dst_mode::split_m`按M轴拆分 |
174+| Vector计算 | 使用`__simd_vf__`函数`ComputeAdd`完成加法 |
175+| 数据同步 | 使用固定flag的`asc_sync_block_wait/arrive`实现slot级交接 |
176+| 尾块处理 | 以`curM`、`curN`和`length`限制有效区域,避免读取padding |
177+ 
178+## 编译运行
179+ 
180+在本样例根目录下执行如下步骤,编译并执行样例。
181+ 
182+- 配置环境变量
183+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../docs/zh/quick_start.md#prepare&install),配置环境变量。**当前仅支持使用[CANN master](../../../../docs/zh/quick_start.md#cann-install)**。
184+ ```bash
185+ source ${install_path}/cann/set_env.sh
186+ ```
187+ 
188+ > **说明:** `${install_path}` 为CANN包安装目录,未指定安装目录时默认安装至 `/usr/local/Ascend` 下。
189+ 
190+- 样例执行
191+ 在本样例目录下执行如下命令。
192+ 
193+ ```bash
194+ mkdir -p build && cd build; # 创建并进入build目录
195+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DCANN_ASC_USE_EXPERIMENTAL=ON ..;make -j; # 编译工程,默认NPU模式
196+ python3 ../scripts/gen_data.py # 生成测试输入数据
197+ ./demo # 执行编译生成的可执行程序,执行样例
198+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # 验证输出结果是否正确,确认算法逻辑正确
199+ ```
200+ 
201+ 使用NPU仿真模式时,添加`-DCMAKE_ASC_RUN_MODE=sim`参数即可。
202+ 
203+ ```bash
204+ cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DCANN_ASC_USE_EXPERIMENTAL=ON ..;make -j; # NPU仿真模式
205+ ```
206+ 
207+ > **注意:** 切换编译模式前需清理cmake缓存,可在build目录下执行`rm CMakeCache.txt`后重新cmake。
208+ 
209+- 编译选项说明
210+ 
211+ | 选项 | 可选值 | 说明 |
212+ |------|--------|------|
213+ | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 运行模式:NPU运行、NPU仿真 |
214+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU架构:dav-3510对应Ascend 950PR/Ascend 950DT |
215+ | `CANN_ASC_USE_EXPERIMENTAL` | `ON` | 本样例编译所需的Tensor API开关 |
216+ 
217+ > **说明:** 本样例仅支持dav-3510架构(对应Ascend 950PR/Ascend 950DT)。
218+ 
219+- 执行结果
220+ 
221+ 执行结果如下,说明精度对比成功。
222+ 
223+ ```bash
224+ test pass!
225+ ```
@@ -0,0 +1,225 @@
1+# Matmul Bias CV Fusion Example Based on Tensor API
2+ 
3+## Overview
4+ 
5+This example implements Cube and Vector CV-fused computation with the Tensor API programming model. The Cube side performs matrix multiplication with Bias, and the Vector side adds the Residual element by element to the Cube result:
6+ 
7+$$
8+Y = A \times B + Bias + Residual
9+$$
10+ 
11+The example uses one `__mix__(1, 2)` kernel to start one AIC and two AIVs. Cube transfers the L0C result to two Vector sub-blocks along the M dimension by using `dual_dst_mode::split_m` of `copy_l0c_to_ub`. Each Vector sub-block adds its corresponding Residual data and writes the result back to Global Memory. This demonstrates CV data exchange and pipeline coordination in one kernel.
12+ 
13+## Supported Products and CANN Software Versions
14+ 
15+| Product | CANN Software Version |
16+|---------|----------------------|
17+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
18+ 
19+> **Note:** This example depends on CANN features that have not been officially released. Use the latest CANN master package.
20+ 
21+## Directory Structure
22+ 
23+```text
24+├── matmul_bias_fusion
25+│ ├── scripts
26+│ │ ├── gen_data.py // Input data and float32 ground-truth generation script
27+│ │ └── verify_result.py // Output and ground-truth comparison script
28+│ ├── CMakeLists.txt // Build project file
29+│ ├── data_utils.h // Data read/write functions
30+│ ├── matmul_bias_fusion.asc // Ascend C sample implementation and invocation example
31+│ └── README.md // Example description document
32+```
33+ 
34+## Example Description
35+ 
36+- Example functionality:
37+ 
38+ 1. **Cube-side Matmul and Bias fusion**
39+ 
40+ The Cube side transfers A and B from Global Memory to L1, and then to L0A/L0B, before using `mmad` for matrix multiplication. Bias is transferred from Global Memory through L1 and the Bias table to L0Bias. It is passed to only the first `mmad` of each output tile; subsequent K iterations accumulate the matrix multiplication result without adding Bias again.
41+ 
42+ 2. **Vector-side Residual addition**
43+ 
44+ Cube transfers the `float` result in L0C to UB. `dual_dst_mode::split_m` divides one tile evenly along the M dimension and sends the two halves to the two AIVs. Each AIV reads its half of the Cube result and the corresponding Residual data from Global Memory, calls `ComputeAdd` for element-wise addition, and writes the result back to Global Memory.
45+ 
46+ 3. **CV pipeline coordination**
47+ 
48+ Two UB slots (`PIPE_DEPTH=2`) are reused alternately for output tiles. Before reusing a slot, AIC waits for both AIVs to finish consuming the previous tile. After the L0C-to-UB transfer, AIC notifies the AIVs. After both AIVs finish the addition and UB-to-Global Memory transfer, they notify AIC. `asc_sync_block_wait` and `asc_sync_block_arrive` implement the AIC/AIV synchronization, so the Vector path does not require a separate kernel.
49+ 
50+ 4. **Computation formula**
51+ 
52+ Bias is broadcast along the column dimension, and Residual is added element by element:
53+ 
54+ $$
55+ T_{m,n}=\sum_{k=0}^{K-1} A_{m,k}B_{k,n}+Bias_n
56+ $$
57+ $$
58+ Y_{m,n}=T_{m,n}+Residual_{m,n}
59+ $$
60+ 
61+- `ComputeAdd` implementation:
62+ 
63+ `ComputeAdd` is a Vector function marked with `__simd_vf__`. Both its inputs and output are one-dimensional UB Tensors. The function first creates a valid-element mask with `update_mask<float>(length)`, then performs masked `load` operations on the two input Tensors, computes `lhs + rhs`, and finally writes the result with `store`. `length` is the number of valid elements in the current tail block, so padding elements in a tile are not accessed.
64+ 
65+ ```cpp
66+ template <typename Src0Tensor, typename Src1Tensor, typename DstTensor>
67+ __simd_vf__ inline void ComputeAdd(Src0Tensor src0, Src1Tensor src1,
68+ DstTensor dst, uint32_t length)
69+ {
70+ const auto coord = asc::te::make_coord(0);
71+ auto mask = asc::te::experimental::update_mask<float>(length);
72+ auto lhs = asc::te::experimental::load(src0, coord).with_mask(mask);
73+ auto rhs = asc::te::experimental::load(src1, coord).with_mask(mask);
74+ asc::te::experimental::store(dst, coord, lhs + rhs);
75+ }
76+ ```
77+ 
78+- Example specifications:
79+ 
80+ The default shape is `M=1024`, `N=1024`, and `K=256`. Each Cube block processes an output region of `singleCoreM=256` by `singleCoreN=128`, and 32 mixed blocks are launched.
81+ 
82+ <table border="2">
83+ <caption>Example Specifications</caption>
84+ <tr><td rowspan="1" align="left">Example Type (OpType)</td><td colspan="4" align="left">Matmul with Bias and Residual</td></tr>
85+ <tr><td rowspan="6" align="left">Example Input</td><td align="left">name</td><td align="left">shape</td><td align="left">data type</td><td align="left">format</td></tr>
86+ <tr><td align="left">A (Matrix A)</td><td align="left">[M, K]</td><td align="left">half</td><td align="left">ND</td></tr>
87+ <tr><td align="left">B (Matrix B)</td><td align="left">[K, N]</td><td align="left">half</td><td align="left">ND</td></tr>
88+ <tr><td align="left">Bias</td><td align="left">[N]</td><td align="left">float</td><td align="left">ND</td></tr>
89+ <tr><td align="left">Residual</td><td align="left">[M, N]</td><td align="left">float</td><td align="left">ND</td></tr>
90+ <tr><td align="left">tiling</td><td align="left">MatmulTiling structure</td><td align="left">int32_t</td><td align="left">ND</td></tr>
91+ <tr><td rowspan="1" align="left">Example Output</td><td align="left">Y (Output matrix)</td><td align="left">[M, N]</td><td align="left">float</td><td align="left">ND</td></tr>
92+ <tr><td rowspan="1" align="left">Kernel Function Name</td><td colspan="4" align="left">matmul_bias_fusion</td></tr>
93+ </table>
94+ 
95+ The default compile-time parameter values are as follows:
96+ 
97+ | Parameter | Default | Description |
98+ | :--- | :---: | :--- |
99+ | `BASE_M` | 128 | M dimension of a Cube output tile |
100+ | `BASE_N` | 128 | N dimension of a Cube output tile |
101+ | `BASE_K` | 64 | Basic block size of the Cube K dimension |
102+ | `STEP_M` | 1 | L1 M dimension step |
103+ | `STEP_N` | 1 | L1 N dimension step |
104+ | `STEP_K` | 4 | L1 K dimension step |
105+ | `VECTOR_LEN` | 64 | Maximum number of elements in one Vector addition |
106+ | `PIPE_DEPTH` | 2 | Number of UB slots |
107+ 
108+ The default runtime tiling parameter values are as follows:
109+ 
110+ | Parameter | Default | Description |
111+ | :--- | :---: | :--- |
112+ | `m` | 1024 | Number of rows of matrix A |
113+ | `n` | 1024 | Number of columns of matrix B |
114+ | `k` | 256 | Number of columns of matrix A / number of rows of matrix B |
115+ | `singleCoreM` | 256 | M dimension processed by one Cube block |
116+ | `singleCoreN` | 128 | N dimension processed by one Cube block |
117+ | `singleCoreK` | 256 | K dimension processed by one Cube block |
118+ 
119+## Example Implementation
120+ 
121+### Tensor Layouts and Data Movement
122+ 
123+| Tensor | Layout | Purpose |
124+| :--- | :--- | :--- |
125+| A, B, Bias, Residual, and Y in Global Memory | `nd_ext_layout_ptn` (ND) | Describe input and output data in Global Memory |
126+| A and B in L1 | `nz_layout_ptn` (NZ) | Prepare data for Cube transfer and computation |
127+| Bias in L1 | `nd_ext_layout_ptn` (ND) | Temporarily store the Bias vector |
128+| L0A | `nz_layout_ptn` (NZ) | Cube matrix A |
129+| L0B | `zn_layout_ptn` (ZN) | Cube matrix B |
130+| L0C | `nz_layout_ptn` (NZ) | Float matrix multiplication accumulation result |
131+| Tile and Vector temporary Tensors in UB | ND/one-dimensional layout | AIC-to-AIV data handoff and Vector computation |
132+ 
133+### Implementation Process
134+ 
135+| Step | Tensor API/C API operation | Function | Layout or execution unit |
136+| :--- | :--- | :--- | :--- |
137+| 1 | `make_tensor`, `make_mem_ptr`, `make_frame_layout` | Create GM, L1, L0, and UB Tensor views, and obtain the current M/N region from the block index | GM uses ND; Cube buffers use NZ/ZN |
138+| 2 | `copy(copy_gm_to_l1)` | Transfer A, B, and Bias to L1 | A/B: ND to NZ; Bias remains ND |
139+| 3 | `copy(copy_l1_to_l0a/copy_l1_to_l0b/copy_l1_to_biastable)` | Transfer Cube inputs and Bias to L0A, L0B, and L0Bias | Prepare Cube computation |
140+| 4 | `mmad` | Complete matrix multiply-accumulate along K and inject Bias in the first iteration | AIC/Cube |
141+| 5 | `copy(copy_l0c_to_ub)` | Split the L0C tile into two M halves with `dual_dst_mode::split_m` | Transfer the L0C result to the UB of the two AIVs |
142+| 6 | `asc_sync_block_wait/arrive` | Pass ready and consumed events for each slot between AIC and the two AIVs | CV synchronization |
143+| 7 | `copy(copy_ub_to_ub)`, `copy(copy_gm_to_ub)` | Read the Cube half-tile and Residual into temporary Vector UB buffers | AIV/Vector |
144+| 8 | `ComputeAdd` | Perform masked load, element-wise addition, and store for valid elements | AIV/Vector |
145+| 9 | `copy(copy_ub_to_gm)` | Write the addition result to the corresponding Global Memory region of Y | AIV to Global Memory |
146+ 
147+### Cube-side Matmul Flow
148+ 
149+Each AIC block uses `block_idx` to locate a `singleCoreM` by `singleCoreN` region and divides that region into output tiles using `BASE_M` and `BASE_N`. For each tile, A and B are transferred along the K dimension in `BASE_K` blocks and passed to `mmad`. The first call sets `init_with_zero=true` and passes L0Bias; subsequent calls set `init_with_zero=false` and accumulate the matrix multiplication result. The resulting L0C tile is therefore `A x B + Bias`.
150+ 
151+### Vector-side Addition Flow
152+ 
153+Each AIV uses `asc_get_sub_block_id()` to determine its M half. After receiving the notification for the corresponding AIC slot, it processes each row and each `VECTOR_LEN`-element column block. It first copies the Cube result from UB to a Vector temporary Tensor, then transfers Residual from Global Memory to UB, calls `ComputeAdd`, and finally copies the output Tensor to the corresponding Y slice in Global Memory. The two AIVs process non-overlapping row ranges.
154+ 
155+### Dual-destination L0C-to-UB Transfer and Synchronization
156+ 
157+`copy_l0c_to_ub` uses the following trait:
158+ 
159+```cpp
160+{ asc::te::round_mode::default_round, false, false,
161+ asc::te::dual_dst_mode::split_m }
162+```
163+ 
164+For each output tile, AIC writes the first M half to sub-block 0 and the second M half to sub-block 1. Two slot groups are reused according to `sequence % PIPE_DEPTH`. The AIC-to-AIV flags are 8 and 9, and the AIV-to-AIC flags are 10 and 11. Before reusing a slot, AIC waits on `PIPE_MTE2` for both AIVs to finish. After the transfer, AIC notifies the AIVs on `PIPE_FIX`. Each AIV waits for data on `PIPE_S` and notifies AIC on `PIPE_MTE3` after writing the result back. This prevents UB from being overwritten before Vector consumption and establishes the complete CV pipeline dependency.
165+ 
166+## Tensor API Implementation Features
167+ 
168+| Feature | Implementation in this example |
169+| :--- | :--- |
170+| Tensor representation | Use Tensor objects to describe data at the GM, L1, L0C, and UB levels |
171+| Matrix computation | Use `mmad` for Cube-side matrix multiply-accumulate; inject Bias only in the first K iteration |
172+| CV fusion | Use one `__mix__(1, 2)` kernel to connect one AIC and two AIVs |
173+| Dual-destination transfer | Use `dual_dst_mode::split_m` of `copy_l0c_to_ub` to split along M |
174+| Vector computation | Use the `__simd_vf__` function `ComputeAdd` for addition |
175+| Data synchronization | Use fixed flags with `asc_sync_block_wait/arrive` for slot-level handoff |
176+| Tail-block handling | Limit the valid region with `curM`, `curN`, and `length` to avoid reading padding |
177+ 
178+## Build and Run
179+ 
180+Execute the following steps in the root directory of this example to build and run it.
181+ 
182+- Configure environment variables
183+ Configure environment variables according to the [installation method](../../../../docs/en/quick_start.md#prepare&install) of the CANN development kit package on the current environment. **Currently only [CANN master](../../../../docs/en/quick_start.md#cann-install) is supported.**
184+ ```bash
185+ source ${install_path}/cann/set_env.sh
186+ ```
187+ 
188+ > **Note:** `${install_path}` is the CANN package installation directory. When no installation directory is specified, the default installation path is `/usr/local/Ascend`.
189+ 
190+- Run the example
191+ Execute the following commands in the example directory.
192+ 
193+ ```bash
194+ mkdir -p build && cd build; # Create and enter the build directory
195+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DCANN_ASC_USE_EXPERIMENTAL=ON ..;make -j; # Build the project, default NPU mode
196+ python3 ../scripts/gen_data.py # Generate test input data
197+ ./demo # Run the compiled executable to execute the example
198+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # Verify output correctness and confirm algorithm logic
199+ ```
200+ 
201+ To use NPU simulation mode, add the `-DCMAKE_ASC_RUN_MODE=sim` parameter.
202+ 
203+ ```bash
204+ cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 -DCANN_ASC_USE_EXPERIMENTAL=ON ..;make -j; # NPU simulation mode
205+ ```
206+ 
207+ > **Note:** Clear the CMake cache before switching build modes. Run `rm CMakeCache.txt` in the build directory and then run CMake again.
208+ 
209+- Build option description
210+ 
211+ | Option | Available Values | Description |
212+ |--------|------------------|-------------|
213+ | `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | Run mode: NPU execution, NPU simulation |
214+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU architecture: dav-3510 corresponds to Ascend 950PR/Ascend 950DT |
215+ | `CANN_ASC_USE_EXPERIMENTAL` | `ON` | Required Tensor API switch for building this example |
216+ 
217+ > **Note:** This example only supports the dav-3510 architecture (corresponding to Ascend 950PR/Ascend 950DT).
218+ 
219+- Execution result
220+ 
221+ The following execution result indicates that the precision comparison succeeded.
222+ 
223+ ```bash
224+ test pass!
225+ ```
@@ -0,0 +1,111 @@
1+/**
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 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+#ifndef MATMUL_BIAS_FUSION_DATA_UTILS_H
12+#define MATMUL_BIAS_FUSION_DATA_UTILS_H
13+ 
14+#include <fcntl.h>
15+#include <sys/stat.h>
16+#include <unistd.h>
17+ 
18+#include <cstddef>
19+#include <cstdio>
20+#include <fstream>
21+#include <string>
22+ 
23+// Read a binary file whose size is part of the sample's ABI. Keeping the
24+// exact-size check here catches stale data generated for a different shape.
25+inline bool ReadFile(const std::string& path, void* buffer, size_t expectedSize)
26+{
27+ if (buffer == nullptr) {
28+ std::fprintf(stderr, "[ERROR] null input buffer for %s\n", path.c_str());
29+ return false;
30+ }
31+ 
32+ struct stat fileStat {};
33+ if (stat(path.c_str(), &fileStat) != 0 || !S_ISREG(fileStat.st_mode)) {
34+ std::fprintf(stderr, "[ERROR] input file does not exist: %s\n", path.c_str());
35+ return false;
36+ }
37+ const size_t fileSize = static_cast<size_t>(fileStat.st_size);
38+ if (fileSize != expectedSize) {
39+ std::fprintf(
40+ stderr, "[ERROR] invalid file size for %s: expected %zu, got %zu\n", path.c_str(), expectedSize, fileSize);
41+ return false;
42+ }
43+ 
44+ std::ifstream file(path, std::ios::binary);
45+ if (!file.read(static_cast<char*>(buffer), static_cast<std::streamsize>(expectedSize))) {
46+ std::fprintf(stderr, "[ERROR] failed to read file: %s\n", path.c_str());
47+ return false;
48+ }
49+ return true;
50+}
51+ 
52+// Compatibility overload used by copy-out Tensor API examples. It reports
53+// the actual file size while protecting the caller's allocation.
54+inline bool ReadFile(const std::string& path, size_t& fileSize, void* buffer, size_t bufferSize)
55+{
56+ fileSize = 0;
57+ if (buffer == nullptr) {
58+ std::fprintf(stderr, "[ERROR] null input buffer for %s\n", path.c_str());
59+ return false;
60+ }
61+ 
62+ struct stat fileStat {};
63+ if (stat(path.c_str(), &fileStat) != 0 || !S_ISREG(fileStat.st_mode)) {
64+ std::fprintf(stderr, "[ERROR] input file does not exist: %s\n", path.c_str());
65+ return false;
66+ }
67+ const size_t size = static_cast<size_t>(fileStat.st_size);
68+ if (size == 0 || size > bufferSize) {
69+ std::fprintf(
70+ stderr, "[ERROR] invalid file size for %s: file=%zu, buffer=%zu\n", path.c_str(), size, bufferSize);
71+ return false;
72+ }
73+ 
74+ std::ifstream file(path, std::ios::binary);
75+ if (!file.read(static_cast<char*>(buffer), static_cast<std::streamsize>(size))) {
76+ std::fprintf(stderr, "[ERROR] failed to read file: %s\n", path.c_str());
77+ return false;
78+ }
79+ fileSize = size;
80+ return true;
81+}
82+ 
83+inline bool WriteFile(const std::string& path, const void* buffer, size_t size)
84+{
85+ if (buffer == nullptr) {
86+ std::fprintf(stderr, "[ERROR] null output buffer for %s\n", path.c_str());
87+ return false;
88+ }
89+ 
90+ const int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
91+ if (fd < 0) {
92+ std::fprintf(stderr, "[ERROR] failed to open output file: %s\n", path.c_str());
93+ return false;
94+ }
95+ 
96+ const char* data = static_cast<const char*>(buffer);
97+ size_t written = 0;
98+ while (written < size) {
99+ const ssize_t count = write(fd, data + written, size - written);
100+ if (count <= 0) {
101+ std::fprintf(stderr, "[ERROR] failed to write output file: %s\n", path.c_str());
102+ (void)close(fd);
103+ return false;
104+ }
105+ written += static_cast<size_t>(count);
106+ }
107+ (void)close(fd);
108+ return true;
109+}
110+ 
111+#endif // MATMUL_BIAS_FUSION_DATA_UTILS_H
@@ -0,0 +1,396 @@
1+/**
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 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+ * \file matmul_bias_fusion.asc
13+ * \brief Cube matmul with bias fused with Vector residual addition.
14+ */
15+ 
16+#include <cstdint>
17+ 
18+#include "acl/acl.h"
19+#include "c_api/asc_simd.h"
20+#include "c_api/sync/sync.h"
21+#include "data_utils.h"
22+#include "tensor_api/experimental/vector_compute.h"
23+#include "tensor_api/tensor.h"
24+ 
25+struct MatmulTiling {
26+ int32_t m;
27+ int32_t n;
28+ int32_t k;
29+ int32_t singleCoreM;
30+ int32_t singleCoreN;
31+ int32_t singleCoreK;
32+};
33+ 
34+struct CoreIterInfo {
35+ uint32_t mIter;
36+ uint32_t mIterIdx;
37+ uint32_t nIterIdx;
38+ int32_t actualSingleCoreM;
39+ int32_t actualSingleCoreN;
40+};
41+ 
42+constexpr uint32_t MATRIX_M = 1024;
43+constexpr uint32_t MATRIX_N = 1024;
44+constexpr uint32_t MATRIX_K = 256;
45+constexpr uint32_t SINGLE_CORE_M = 256;
46+constexpr uint32_t SINGLE_CORE_N = 128;
47+constexpr uint32_t BASE_M = 128;
48+constexpr uint32_t BASE_N = 128;
49+constexpr uint32_t BASE_K = 64;
50+constexpr uint32_t STEP_M = 1;
51+constexpr uint32_t STEP_N = 1;
52+constexpr uint32_t STEP_K = 4;
53+constexpr uint32_t VECTOR_LEN = BASE_N < 64 ? BASE_N : 64;
54+constexpr uint32_t PIPE_DEPTH = 2;
55+constexpr int64_t AIC_TO_AIV_FLAGS[PIPE_DEPTH] = {8, 9};
56+constexpr int64_t AIV_TO_AIC_FLAGS[PIPE_DEPTH] = {10, 11};
57+ 
58+static_assert(MATRIX_M % SINGLE_CORE_M == 0, "M must be evenly distributed across Cube cores");
59+static_assert(SINGLE_CORE_M % BASE_M == 0, "singleCoreM must contain complete Cube tiles");
60+static_assert(BASE_M % 2 == 0, "dual-destination split_m requires an even tile M");
61+ 
62+constexpr asc::te::l0c_to_ub_trait COPY_L0C2UB_TRAIT = {
63+ asc::te::round_mode::default_round, false, false, asc::te::dual_dst_mode::split_m};
64+struct CopyL0C2UBTraitCustom {
65+ using TraitType = asc::te::l0c_to_ub_trait;
66+ static constexpr const TraitType value = COPY_L0C2UB_TRAIT;
67+};
68+ 
69+__aicore__ inline void CopyTilingFromGM(__gm__ MatmulTiling* srcInfo, MatmulTiling& dstInfo)
70+{
71+ auto srcPtr = reinterpret_cast<__gm__ int32_t*>(srcInfo);
72+ auto dstPtr = reinterpret_cast<int32_t*>(&dstInfo);
73+ for (size_t i = 0; i < sizeof(MatmulTiling) / sizeof(int32_t); ++i) {
74+ dstPtr[i] = srcPtr[i];
75+ }
76+}
77+ 
78+__aicore__ inline CoreIterInfo CalcCoreIterInfo(const MatmulTiling& tiling)
79+{
80+ const uint32_t mIter = (tiling.m + tiling.singleCoreM - 1) / tiling.singleCoreM;
81+ const uint32_t mIterIdx = block_idx % mIter;
82+ const uint32_t nIterIdx = block_idx / mIter;
83+ int32_t actualSingleCoreM = tiling.m - mIterIdx * tiling.singleCoreM;
84+ actualSingleCoreM = actualSingleCoreM < tiling.singleCoreM ? actualSingleCoreM : tiling.singleCoreM;
85+ int32_t actualSingleCoreN = tiling.n - nIterIdx * tiling.singleCoreN;
86+ actualSingleCoreN = actualSingleCoreN < tiling.singleCoreN ? actualSingleCoreN : tiling.singleCoreN;
87+ return {mIter, mIterIdx, nIterIdx, actualSingleCoreM, actualSingleCoreN};
88+}
89+ 
90+template <typename Src0Tensor, typename Src1Tensor, typename DstTensor>
91+__simd_vf__ inline void ComputeAdd(Src0Tensor src0, Src1Tensor src1, DstTensor dst, uint32_t length)
92+{
93+ const auto coord = asc::te::make_coord(0);
94+ auto mask = asc::te::experimental::update_mask<float>(length);
95+ auto lhs = asc::te::experimental::load(src0, coord).with_mask(mask);
96+ auto rhs = asc::te::experimental::load(src1, coord).with_mask(mask);
97+ asc::te::experimental::store(dst, coord, lhs + rhs);
98+}
99+ 
100+template <typename A_TYPE, typename B_TYPE, typename C_TYPE, typename BIAS_TYPE>
101+__global__ __mix__(1, 2) void matmul_bias_fusion(
102+ __gm__ A_TYPE* a, __gm__ B_TYPE* b, __gm__ BIAS_TYPE* bias, __gm__ C_TYPE* residual, __gm__ C_TYPE* y,
103+ __gm__ MatmulTiling* tilingInfo)
104+{
105+ asc_init();
106+ using namespace asc::te;
107+ 
108+ MatmulTiling tiling;
109+ CopyTilingFromGM(tilingInfo, tiling);
110+ const CoreIterInfo iterInfo = CalcCoreIterInfo(tiling);
111+ 
112+ auto gmA = make_tensor(make_mem_ptr(a), make_frame_layout<nd_ext_layout_ptn>(tiling.m, tiling.k));
113+ auto gmB = make_tensor(make_mem_ptr(b), make_frame_layout<nd_ext_layout_ptn>(tiling.k, tiling.n));
114+ auto gmBias = make_tensor(make_mem_ptr(bias), make_frame_layout<nd_ext_layout_ptn>(1, tiling.n));
115+ auto gmResidual = make_tensor(make_mem_ptr(residual), make_frame_layout<nd_ext_layout_ptn>(tiling.m, tiling.n));
116+ auto gmY = make_tensor(make_mem_ptr(y), make_frame_layout<nd_ext_layout_ptn>(tiling.m, tiling.n));
117+ 
118+ auto globalA = gmA.slice(
119+ make_coord(iterInfo.mIterIdx * tiling.singleCoreM, 0),
120+ make_shape(iterInfo.actualSingleCoreM, tiling.singleCoreK));
121+ auto globalB = gmB.slice(
122+ make_coord(0, iterInfo.nIterIdx * tiling.singleCoreN),
123+ make_shape(tiling.singleCoreK, iterInfo.actualSingleCoreN));
124+ auto globalBias =
125+ gmBias.slice(make_coord(0, iterInfo.nIterIdx * tiling.singleCoreN), make_shape(1, iterInfo.actualSingleCoreN));
126+ 
127+ const uint32_t mLoop = (iterInfo.actualSingleCoreM + BASE_M - 1) / BASE_M;
128+ const uint32_t nLoop = (iterInfo.actualSingleCoreN + BASE_N - 1) / BASE_N;
129+ const uint32_t kLoop = (tiling.singleCoreK + BASE_K - 1) / BASE_K;
130+ const uint32_t tileM = (iterInfo.actualSingleCoreM % BASE_M != 0) ? iterInfo.actualSingleCoreM % BASE_M : BASE_M;
131+ const uint32_t tileN = (iterInfo.actualSingleCoreN % BASE_N != 0) ? iterInfo.actualSingleCoreN % BASE_N : BASE_N;
132+ const uint32_t tileK = (tiling.singleCoreK % BASE_K != 0) ? tiling.singleCoreK % BASE_K : BASE_K;
133+ 
134+ // The split-m copy writes half of each tile into the local UB of each AIV.
135+ // Two fixed regions are used so Cube can hand off the next tile while Vector consumes the previous one.
136+ __ubuf__ C_TYPE ubBuf[PIPE_DEPTH * BASE_M * BASE_N / 2];
137+ auto ubTensor = make_tensor(make_mem_ptr(ubBuf), make_frame_layout<nd_ext_layout_ptn>(PIPE_DEPTH * BASE_M, BASE_N));
138+ 
139+ if ASCEND_IS_AIC {
140+ constexpr uint32_t L1_INDEX = 0;
141+ constexpr uint32_t L0_INDEX = 1;
142+ constexpr uint32_t L0C_INDEX = 2;
143+ constexpr uint32_t L1_BIAS_INDEX = 3;
144+ constexpr uint32_t L0_BIAS_INDEX = 4;
145+ 
146+ __cbuf__ A_TYPE l1ABuf[BASE_M * STEP_M * BASE_K * STEP_K];
147+ __cbuf__ B_TYPE l1BBuf[BASE_K * STEP_K * BASE_N * STEP_N];
148+ __cbuf__ BIAS_TYPE l1BiasBuf[BASE_N * STEP_N];
149+ __ca__ A_TYPE l0ABuf[BASE_M * BASE_K];
150+ __cb__ B_TYPE l0BBuf[BASE_K * BASE_N];
151+ __biasbuf__ BIAS_TYPE l0BiasBuf[BASE_N];
152+ __cc__ C_TYPE l0CBuf[BASE_M * BASE_N];
153+ 
154+ auto l1A = make_tensor(
155+ make_mem_ptr(l1ABuf), make_frame_layout<nz_layout_ptn, A_TYPE>(BASE_M * STEP_M, BASE_K * STEP_K));
156+ auto l1B = make_tensor(
157+ make_mem_ptr(l1BBuf), make_frame_layout<nz_layout_ptn, B_TYPE>(BASE_K * STEP_K, BASE_N * STEP_N));
158+ auto l1Bias = make_tensor(make_mem_ptr(l1BiasBuf), make_frame_layout<nd_ext_layout_ptn>(1, BASE_N * STEP_N));
159+ auto l0APtr = make_mem_ptr(l0ABuf);
160+ auto l0BPtr = make_mem_ptr(l0BBuf);
161+ auto l0BiasPtr = make_mem_ptr(l0BiasBuf);
162+ auto l0CPtr = make_mem_ptr(l0CBuf);
163+ auto gm2l1 = make_copy(copy_gm_to_l1{}, gm_to_l1_trait_default{});
164+ auto l1tol0a = make_copy(copy_l1_to_l0a{}, l1_to_l0a_trait_default{});
165+ auto l1tol0b = make_copy(copy_l1_to_l0b{}, l1_to_l0b_trait_default{});
166+ auto l1tobt = make_copy(copy_l1_to_biastable{}, l1_to_biastable_trait_default{});
167+ auto l0c2ub = make_copy(copy_l0c_to_ub{}, CopyL0C2UBTraitCustom{});
168+ auto mm = make_mmad(mmad_operation{}, asc::te::mmad_trait_default{});
169+ 
170+ for (uint32_t i = 0; i < mLoop; ++i) {
171+ const uint16_t curM = (i + 1 == mLoop) ? tileM : BASE_M;
172+ for (uint32_t j = 0; j < nLoop; ++j) {
173+ const uint16_t curN = (j + 1 == nLoop) ? tileN : BASE_N;
174+ const uint32_t sequence = i * nLoop + j;
175+ const uint32_t slot = sequence % PIPE_DEPTH;
176+ if (sequence >= PIPE_DEPTH) {
177+ asc_sync_block_wait(PIPE_MTE2, AIV_TO_AIC_FLAGS[slot]);
178+ }
179+ 
180+ auto l0C = make_tensor(l0CPtr, make_frame_layout<nz_layout_ptn>(curM, curN));
181+ auto l0Bias = make_tensor(l0BiasPtr, make_frame_layout<nd_ext_layout_ptn>(1, curN));
182+ 
183+ asc_lock(PIPE_MTE2, L1_BIAS_INDEX);
184+ copy(gm2l1, l1Bias, globalBias.slice(make_coord(0, j * BASE_N), make_shape(1, curN)));
185+ asc_unlock(PIPE_MTE2, L1_BIAS_INDEX);
186+ asc_lock(PIPE_MTE1, L1_BIAS_INDEX);
187+ asc_lock(PIPE_MTE1, L0_BIAS_INDEX);
188+ copy(l1tobt, l0Bias, l1Bias.slice(make_coord(0, 0), make_shape(1, curN)));
189+ asc_unlock(PIPE_MTE1, L0_BIAS_INDEX);
190+ asc_unlock(PIPE_MTE1, L1_BIAS_INDEX);
191+ 
192+ for (uint32_t kIter = 0; kIter < kLoop; ++kIter) {
193+ const uint16_t curK = (kIter + 1 == kLoop) ? tileK : BASE_K;
194+ auto l0A = make_tensor(l0APtr, make_frame_layout<nz_layout_ptn, A_TYPE>(curM, curK));
195+ auto l0B = make_tensor(l0BPtr, make_frame_layout<zn_layout_ptn, B_TYPE>(curK, curN));
196+ 
197+ if (kIter % STEP_K == 0) {
198+ uint16_t curStepK = static_cast<uint16_t>(tiling.singleCoreK - kIter * BASE_K);
199+ curStepK = curStepK < BASE_K * STEP_K ? curStepK : BASE_K * STEP_K;
200+ asc_lock(PIPE_MTE2, L1_INDEX);
201+ copy(
202+ gm2l1, l1A,
203+ globalA.slice(make_coord(i * BASE_M, kIter * BASE_K), make_shape(curM, curStepK)));
204+ copy(
205+ gm2l1, l1B,
206+ globalB.slice(make_coord(kIter * BASE_K, j * BASE_N), make_shape(curStepK, curN)));
207+ asc_unlock(PIPE_MTE2, L1_INDEX);
208+ asc_lock(PIPE_MTE1, L1_INDEX);
209+ }
210+ 
211+ asc_lock(PIPE_MTE1, L0_INDEX);
212+ copy(l1tol0a, l0A, l1A.slice(make_coord(0, kIter % STEP_K * BASE_K), make_shape(curM, curK)));
213+ copy(l1tol0b, l0B, l1B.slice(make_coord(kIter % STEP_K * BASE_K, 0), make_shape(curK, curN)));
214+ if ((kIter + 1) % STEP_K == 0 || kIter + 1 == kLoop) {
215+ asc_unlock(PIPE_MTE1, L1_INDEX);
216+ }
217+ asc_unlock(PIPE_MTE1, L0_INDEX);
218+ asc_lock(PIPE_M, L0_INDEX);
219+ if (kIter == 0) {
220+ asc_lock(PIPE_M, L0C_INDEX);
221+ asc_lock(PIPE_M, L0_BIAS_INDEX);
222+ asc::te::mmad(
223+ mm.with(mmad_params(curM, curN, curK, unit_flag_mode::disable, true)), l0C, l0A, l0B,
224+ l0Bias);
225+ asc_unlock(PIPE_M, L0_BIAS_INDEX);
226+ } else {
227+ asc::te::mmad(
228+ mm.with(mmad_params(curM, curN, curK, unit_flag_mode::disable, false)), l0C, l0A, l0B);
229+ }
230+ if (kIter == kLoop - 1) {
231+ asc_unlock(PIPE_M, L0C_INDEX);
232+ }
233+ asc_unlock(PIPE_M, L0_INDEX);
234+ }
235+ 
236+ asc_lock(PIPE_FIX, L0C_INDEX);
237+ copy(l0c2ub, ubTensor.slice(make_coord(slot * BASE_M / 2, 0), make_shape(curM, curN)), l0C);
238+ asc_sync_block_arrive(PIPE_FIX, AIC_TO_AIV_FLAGS[slot]);
239+ asc_unlock(PIPE_FIX, L0C_INDEX);
240+ }
241+ }
242+ const uint32_t tileCount = mLoop * nLoop;
243+ const uint32_t firstOutstanding = tileCount > PIPE_DEPTH ? tileCount - PIPE_DEPTH : 0;
244+ for (uint32_t sequence = firstOutstanding; sequence < tileCount; ++sequence) {
245+ asc_sync_block_wait(PIPE_MTE2, AIV_TO_AIC_FLAGS[sequence % PIPE_DEPTH]);
246+ }
247+ }
248+ 
249+ if ASCEND_IS_AIV {
250+ __ubuf__ C_TYPE valueBuf[VECTOR_LEN];
251+ __ubuf__ C_TYPE residualBuf[VECTOR_LEN];
252+ __ubuf__ C_TYPE outputBuf[VECTOR_LEN];
253+ auto vectorLayout = make_layout(make_shape(VECTOR_LEN));
254+ auto copyLayout = make_frame_layout<nd_ext_layout_ptn>(1, VECTOR_LEN);
255+ auto valueVec = make_tensor(make_mem_ptr(valueBuf), vectorLayout);
256+ auto residualVec = make_tensor(make_mem_ptr(residualBuf), vectorLayout);
257+ auto outputVec = make_tensor(make_mem_ptr(outputBuf), vectorLayout);
258+ auto valueCopy = make_tensor(make_mem_ptr(valueBuf), copyLayout);
259+ auto residualCopy = make_tensor(make_mem_ptr(residualBuf), copyLayout);
260+ auto outputCopy = make_tensor(make_mem_ptr(outputBuf), copyLayout);
261+ auto ub2ub = make_copy(copy_ub_to_ub{}, ub_to_ub_trait_default{});
262+ auto gm2ub = make_copy(copy_gm_to_ub{});
263+ auto ub2gm = make_copy(copy_ub_to_gm{});
264+ const uint32_t subBlockId = static_cast<uint32_t>(asc_get_sub_block_id());
265+ 
266+ for (uint32_t i = 0; i < mLoop; ++i) {
267+ const uint16_t curM = (i + 1 == mLoop) ? tileM : BASE_M;
268+ const uint16_t halfM = curM / 2;
269+ for (uint32_t j = 0; j < nLoop; ++j) {
270+ const uint16_t curN = (j + 1 == nLoop) ? tileN : BASE_N;
271+ const uint32_t sequence = i * nLoop + j;
272+ const uint32_t slot = sequence % PIPE_DEPTH;
273+ asc_sync_block_wait(PIPE_S, AIC_TO_AIV_FLAGS[slot]);
274+ for (uint32_t row = 0; row < halfM; ++row) {
275+ const uint32_t globalRow =
276+ iterInfo.mIterIdx * tiling.singleCoreM + i * BASE_M + subBlockId * halfM + row;
277+ for (uint32_t column = 0; column < curN; column += VECTOR_LEN) {
278+ const uint32_t length = curN - column < VECTOR_LEN ? curN - column : VECTOR_LEN;
279+ auto ubPart =
280+ ubTensor.slice(make_coord(slot * BASE_M / 2 + row, column), make_shape(1, length));
281+ auto residualPart = gmResidual.slice(
282+ make_coord(globalRow, iterInfo.nIterIdx * tiling.singleCoreN + j * BASE_N + column),
283+ make_shape(1, length));
284+ auto outputPart = gmY.slice(
285+ make_coord(globalRow, iterInfo.nIterIdx * tiling.singleCoreN + j * BASE_N + column),
286+ make_shape(1, length));
287+ asc_lock(PIPE_MTE2, 0);
288+ copy(ub2ub, valueCopy.slice(make_coord(0, 0), make_shape(1, length)), ubPart);
289+ copy(gm2ub, residualCopy.slice(make_coord(0, 0), make_shape(1, length)), residualPart);
290+ asc_unlock(PIPE_MTE2, 0);
291+ asc_lock(PIPE_V, 0);
292+ ComputeAdd(valueVec, residualVec, outputVec, length);
293+ asc_unlock(PIPE_V, 0);
294+ asc_lock(PIPE_MTE3, 0);
295+ copy(ub2gm, outputPart, outputCopy.slice(make_coord(0, 0), make_shape(1, length)));
296+ asc_unlock(PIPE_MTE3, 0);
297+ }
298+ }
299+ asc_sync_block_arrive(PIPE_MTE3, AIV_TO_AIC_FLAGS[slot]);
300+ }
301+ }
302+ }
303+ asc_sync_pipe(PIPE_ALL);
304+}
305+ 
306+int32_t main(int32_t argc, char* argv[])
307+{
308+ using A_TYPE = half;
309+ using B_TYPE = half;
310+ using C_TYPE = float;
311+ using BIAS_TYPE = float;
312+ 
313+ MatmulTiling tiling;
314+ tiling.m = MATRIX_M;
315+ tiling.n = MATRIX_N;
316+ tiling.k = MATRIX_K;
317+ tiling.singleCoreM = SINGLE_CORE_M;
318+ tiling.singleCoreN = SINGLE_CORE_N;
319+ tiling.singleCoreK = MATRIX_K;
320+ 
321+ const uint32_t mBlocks = (tiling.m + tiling.singleCoreM - 1) / tiling.singleCoreM;
322+ const uint32_t nBlocks = (tiling.n + tiling.singleCoreN - 1) / tiling.singleCoreN;
323+ const uint32_t numBlocks = mBlocks * nBlocks;
324+ 
325+ size_t aFileSize = tiling.m * tiling.k * sizeof(A_TYPE);
326+ size_t bFileSize = tiling.k * tiling.n * sizeof(B_TYPE);
327+ size_t biasFileSize = tiling.n * sizeof(BIAS_TYPE);
328+ size_t matrixFileSize = tiling.m * tiling.n * sizeof(C_TYPE);
329+ 
330+ aclInit(nullptr);
331+ int32_t deviceId = 0;
332+ aclrtSetDevice(deviceId);
333+ aclrtStream stream = nullptr;
334+ aclrtCreateStream(&stream);
335+ 
336+ uint8_t *aHost, *bHost, *biasHost, *residualHost, *yHost;
337+ A_TYPE* aDevice;
338+ B_TYPE* bDevice;
339+ BIAS_TYPE* biasDevice;
340+ C_TYPE* residualDevice;
341+ C_TYPE* yDevice;
342+ 
343+ aclrtMallocHost((void**)(&aHost), aFileSize);
344+ aclrtMallocHost((void**)(&bHost), bFileSize);
345+ aclrtMallocHost((void**)(&biasHost), biasFileSize);
346+ aclrtMallocHost((void**)(&residualHost), matrixFileSize);
347+ aclrtMallocHost((void**)(&yHost), matrixFileSize);
348+ aclrtMalloc((void**)&aDevice, aFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
349+ aclrtMalloc((void**)&bDevice, bFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
350+ aclrtMalloc((void**)&biasDevice, biasFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
351+ aclrtMalloc((void**)&residualDevice, matrixFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
352+ aclrtMalloc((void**)&yDevice, matrixFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
353+ 
354+ ReadFile("./input/a.bin", aHost, aFileSize);
355+ ReadFile("./input/b.bin", bHost, bFileSize);
356+ ReadFile("./input/bias.bin", biasHost, biasFileSize);
357+ ReadFile("./input/residual.bin", residualHost, matrixFileSize);
358+ 
359+ aclrtMemcpy(aDevice, aFileSize, aHost, aFileSize, ACL_MEMCPY_HOST_TO_DEVICE);
360+ aclrtMemcpy(bDevice, bFileSize, bHost, bFileSize, ACL_MEMCPY_HOST_TO_DEVICE);
361+ aclrtMemcpy(biasDevice, biasFileSize, biasHost, biasFileSize, ACL_MEMCPY_HOST_TO_DEVICE);
362+ aclrtMemcpy(residualDevice, matrixFileSize, residualHost, matrixFileSize, ACL_MEMCPY_HOST_TO_DEVICE);
363+ 
364+ MatmulTiling* tilingHost;
365+ MatmulTiling* tilingDevice;
366+ aclrtMallocHost((void**)(&tilingHost), sizeof(MatmulTiling));
367+ aclrtMalloc((void**)&tilingDevice, sizeof(MatmulTiling), ACL_MEM_MALLOC_HUGE_FIRST);
368+ *tilingHost = tiling;
369+ aclrtMemcpy(tilingDevice, sizeof(MatmulTiling), tilingHost, sizeof(MatmulTiling), ACL_MEMCPY_HOST_TO_DEVICE);
370+ 
371+ matmul_bias_fusion<A_TYPE, B_TYPE, C_TYPE, BIAS_TYPE>
372+ <<<numBlocks, 0, stream>>>(aDevice, bDevice, biasDevice, residualDevice, yDevice, tilingDevice);
373+ aclrtSynchronizeStream(stream);
374+ 
375+ aclrtMemcpy(yHost, matrixFileSize, yDevice, matrixFileSize, ACL_MEMCPY_DEVICE_TO_HOST);
376+ WriteFile("./output/output.bin", yHost, matrixFileSize);
377+ 
378+ aclrtFree(aDevice);
379+ aclrtFree(bDevice);
380+ aclrtFree(biasDevice);
381+ aclrtFree(residualDevice);
382+ aclrtFree(yDevice);
383+ aclrtFree(tilingDevice);
384+ aclrtFreeHost(aHost);
385+ aclrtFreeHost(bHost);
386+ aclrtFreeHost(biasHost);
387+ aclrtFreeHost(residualHost);
388+ aclrtFreeHost(yHost);
389+ aclrtFreeHost(tilingHost);
390+ 
391+ aclrtDestroyStream(stream);
392+ aclrtResetDevice(deviceId);
393+ aclFinalize();
394+ 
395+ return 0;
396+}
@@ -0,0 +1,81 @@
1+#!/usr/bin/env python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2026 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+"""Generate matmul+bias+residual inputs and the float32 reference result."""
16+ 
17+from __future__ import annotations
18+ 
19+import argparse
20+import json
21+from pathlib import Path
22+ 
23+import numpy as np
24+ 
25+ 
26+# CMake writes the same full-size sample_config.json for both run modes.
27+# The constants below keep standalone script execution consistent with it.
28+DEFAULT_M = 1024
29+DEFAULT_K = 256
30+DEFAULT_N = 1024
31+DEFAULT_SEED = 2026
32+ 
33+ 
34+def configured_dimensions() -> tuple[int, int, int]:
35+ config_path = Path("sample_config.json")
36+ if not config_path.is_file():
37+ return DEFAULT_M, DEFAULT_K, DEFAULT_N
38+ config = json.loads(config_path.read_text(encoding="utf-8"))
39+ return int(config["m"]), int(config["k"]), int(config["n"])
40+ 
41+ 
42+def generate_data(m: int, k: int, n: int, seed: int) -> None:
43+ if min(m, k, n) <= 0:
44+ raise ValueError("matrix dimensions must be positive")
45+ 
46+ rng = np.random.default_rng(seed)
47+ a = rng.uniform(-1.0, 1.0, size=(m, k)).astype(np.float16)
48+ b = rng.uniform(-1.0, 1.0, size=(k, n)).astype(np.float16)
49+ bias = rng.uniform(-1.0, 1.0, size=n).astype(np.float32)
50+ residual = rng.uniform(-1.0, 1.0, size=(m, n)).astype(np.float32)
51+ 
52+ # The device accumulates half inputs into float output and then AIV adds
53+ # residual. Compute the reference in float32 in the same order.
54+ golden = np.matmul(a.astype(np.float32), b.astype(np.float32))
55+ golden += bias[None, :]
56+ golden += residual
57+ 
58+ input_dir = Path("input")
59+ output_dir = Path("output")
60+ input_dir.mkdir(parents=True, exist_ok=True)
61+ output_dir.mkdir(parents=True, exist_ok=True)
62+ a.tofile(input_dir / "a.bin")
63+ b.tofile(input_dir / "b.bin")
64+ bias.tofile(input_dir / "bias.bin")
65+ residual.tofile(input_dir / "residual.bin")
66+ golden.astype(np.float32).tofile(output_dir / "golden.bin")
67+ 
68+ 
69+def parse_args() -> argparse.Namespace:
70+ default_m, default_k, default_n = configured_dimensions()
71+ parser = argparse.ArgumentParser(description=__doc__)
72+ parser.add_argument("--m", type=int, default=default_m, help=f"rows of A/output (default: {default_m})")
73+ parser.add_argument("--k", type=int, default=default_k, help=f"inner dimension (default: {default_k})")
74+ parser.add_argument("--n", type=int, default=default_n, help=f"columns of B/output (default: {default_n})")
75+ parser.add_argument("--seed", type=int, default=DEFAULT_SEED, help=f"random seed (default: {DEFAULT_SEED})")
76+ return parser.parse_args()
77+ 
78+ 
79+if __name__ == "__main__":
80+ args = parse_args()
81+ generate_data(args.m, args.k, args.n, args.seed)
@@ -0,0 +1,94 @@
1+#!/usr/bin/env python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2026 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+"""Compare a device result with the float32 matmul+bias+residual golden."""
16+ 
17+from __future__ import annotations
18+ 
19+import argparse
20+import json
21+from pathlib import Path
22+ 
23+import numpy as np
24+ 
25+ 
26+DEFAULT_M = 1024
27+DEFAULT_N = 1024
28+RELATIVE_TOLERANCE = 1e-3
29+ABSOLUTE_TOLERANCE = 1e-3
30+ 
31+ 
32+def configured_dimensions() -> tuple[int, int]:
33+ config_path = Path("sample_config.json")
34+ if not config_path.is_file():
35+ return DEFAULT_M, DEFAULT_N
36+ config = json.loads(config_path.read_text(encoding="utf-8"))
37+ return int(config["m"]), int(config["n"])
38+ 
39+ 
40+def load_matrix(path: Path, elements: int) -> np.ndarray:
41+ values = np.fromfile(path, dtype=np.float32)
42+ if values.size != elements:
43+ raise ValueError(f"{path} contains {values.size} float32 values, expected {elements}")
44+ return values.reshape(-1)
45+ 
46+ 
47+def verify(output_path: Path, golden_path: Path, m: int, n: int) -> bool:
48+ if min(m, n) <= 0:
49+ raise ValueError("matrix dimensions must be positive")
50+ expected_elements = m * n
51+ output = load_matrix(output_path, expected_elements)
52+ golden = load_matrix(golden_path, expected_elements)
53+ absolute_error = np.abs(output - golden)
54+ relative_error = absolute_error / np.maximum(np.abs(golden), np.finfo(np.float32).tiny)
55+ max_absolute_error = float(np.max(absolute_error)) if output.size else 0.0
56+ max_relative_error = float(np.max(relative_error)) if output.size else 0.0
57+ close = np.isclose(output, golden, rtol=RELATIVE_TOLERANCE, atol=ABSOLUTE_TOLERANCE, equal_nan=True)
58+ if np.all(close):
59+ print(f"test pass! max absolute error: {max_absolute_error:.6e}, max relative error: {max_relative_error:.6e}")
60+ return True
61+ 
62+ failed = np.flatnonzero(~close)
63+ first = int(failed[0])
64+ row, column = divmod(first, n)
65+ print(
66+ f"first mismatch at ({row}, {column}): "
67+ f"expected={golden[first]:.9f}, actual={output[first]:.9f}, "
68+ f"absolute_error={absolute_error[first]:.6e}, relative_error={relative_error[first]:.6e}"
69+ )
70+ print(
71+ f"[ERROR] {failed.size} of {expected_elements} elements exceed tolerance; "
72+ f"max absolute error: {max_absolute_error:.6e}, max relative error: {max_relative_error:.6e}"
73+ )
74+ return False
75+ 
76+ 
77+def parse_args() -> argparse.Namespace:
78+ default_m, default_n = configured_dimensions()
79+ parser = argparse.ArgumentParser(description=__doc__)
80+ parser.add_argument("output", type=Path)
81+ parser.add_argument("golden", type=Path)
82+ parser.add_argument("--m", type=int, default=default_m, help=f"output rows (default: {default_m})")
83+ parser.add_argument("--n", type=int, default=default_n, help=f"output columns (default: {default_n})")
84+ return parser.parse_args()
85+ 
86+ 
87+if __name__ == "__main__":
88+ args = parse_args()
89+ try:
90+ passed = verify(args.output, args.golden, args.m, args.n)
91+ except (OSError, ValueError) as error:
92+ print(f"[ERROR] {error}")
93+ raise SystemExit(1)
94+ raise SystemExit(0 if passed else 1)
@@ -10,8 +10,6 @@
10|------|-------------|10|------|-------------|
11| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |11| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12 12 
13-> **说明:** 该样例依赖尚未正式发布的CANN特性,请使用最新的CANN master包。
14- 
15## 目录结构13## 目录结构
16 14 
17```text15```text
@@ -10,8 +10,6 @@ This example introduces how to implement a high-performance MxFP4 Matmul kernel
10|------|-------------|10|------|-------------|
11| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |11| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12 12 
13-> **Note:** This example depends on CANN features that have not been officially released yet. Please use the latest CANN master package.
14- 
15## Directory Structure13## Directory Structure
16 14 
17```text15```text
@@ -0,0 +1,30 @@
1+# ----------------------------------------------------------------------------------------------------------
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 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+set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu, sim")
15+set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510")
16+ 
17+if(NOT CMAKE_ASC_RUN_MODE STREQUAL "npu" AND NOT CMAKE_ASC_RUN_MODE STREQUAL "sim")
18+ message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be 'npu' or 'sim'")
19+endif()
20+if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510")
21+ message(FATAL_ERROR "matmul_split_k only supports dav-3510")
22+endif()
23+ 
24+find_package(ASC REQUIRED)
25+project(matmul_split_k LANGUAGES ASC CXX)
26+ 
27+add_executable(demo matmul_split_k.asc)
28+target_compile_options(demo PRIVATE
29+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>
30+)
@@ -0,0 +1,140 @@
1+# 基于Tensor API实现的Split-K Matmul算子样例
2+ 
3+## 概述
4+ 
5+本样例基于静态Tensor API编程范式实现多核矩阵乘计算,使用Tensor API的高层次抽象接口完成矩阵搬运、切片和乘加流程。计算沿K轴切分,各核的计算结果通过原子加法累加到输出矩阵。
6+ 
7+## 本样例支持的产品及CANN软件版本
8+ 
9+| 产品 | CANN软件版本 |
10+|------|-------------|
11+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12+ 
13+## 目录结构介绍
14+ 
15+```text
16+├── matmul_split_k
17+│ ├── scripts
18+│ │ ├── gen_data.py // 输入数据和真值数据生成脚本文件
19+│ │ └── verify_result.py // 真值对比文件
20+│ ├── CMakeLists.txt // 编译工程文件
21+│ ├── data_utils.h // 数据读入写出函数
22+│ ├── matmul_split_k.asc // Ascend C样例实现
23+│ └── README.md // 样例说明文档
24+```
25+ 
26+## 样例描述
27+ 
28+- 样例功能:
29+ Matmul计算公式:
30+ $$
31+ C = A * B
32+ $$
33+- 样例规格:
34+ 本样例参数M = 16, N = 16, K = 1024,沿K轴均匀切分为4份,调用4个核完成计算,输入输出规格如下表所示。
35+ <table>
36+ <tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="4" align="center">Matmul</td></tr>
37+ <tr><td rowspan="3" align="center">样例输入</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td><td align="center">format</td></tr>
38+ <tr><td align="center">A</td><td align="center">[M, K]</td><td align="center">float16</td><td align="center">ND</td></tr>
39+ <tr><td align="center">B</td><td align="center">[K, N]</td><td align="center">float16</td><td align="center">ND</td></tr>
40+ <tr><td rowspan="1" align="center">样例输出</td><td align="center">C</td><td align="center">[M, N]</td><td align="center">float32</td><td align="center">ND</td></tr>
41+ <tr><td rowspan="1" align="center">核函数名</td><td colspan="4" align="center">matmul_split_k_kernel</td></tr>
42+ </table>
43+ 
44+- 样例实现:
45+ - 实现流程:
46+ <table>
47+ <tr><th align="left">步骤</th><th align="left">Tensor API操作</th><th align="left">功能</th><th align="left">布局转换</th></tr>
48+ <tr><td align="left">1</td><td align="left">常量化Tiling参数</td><td align="left">通过编译期常量定义kernel所需参数</td><td align="left">不涉及</td></tr>
49+ <tr><td align="left">2</td><td align="left">make_tensor + slice</td><td align="left">创建GM张量,沿K轴均匀切分为4份,并根据核索引切片获取当前核处理的数据块</td><td align="left">ND格式</td></tr>
50+ <tr><td align="left">3</td><td align="left">copy(copy_gm_to_l1)</td><td align="left">将A矩阵和B矩阵的当前K轴分片从GM搬运到L1</td><td align="left">ND->NZ格式转换</td></tr>
51+ <tr><td align="left">4</td><td align="left">copy(copy_l1_to_l0a/copy_l1_to_l0b)</td><td align="left">将数据从L1搬运到L0A和L0B</td><td align="left">L1->L0A: NZ->NZ<br>L1->L0B: NZ->ZN</td></tr>
52+ <tr><td align="left">5</td><td align="left">mmad</td><td align="left">完成当前K轴分片的矩阵乘加计算</td><td align="left">矩阵乘结果为NZ格式</td></tr>
53+ <tr><td align="left">6</td><td align="left">asc_set_atomic_add_float + copy(copy_l0c_to_gm)</td><td align="left">启用float原子加法,将各核的L0C结果累加到同一个GM输出矩阵</td><td align="left">NZ->ND格式转换</td></tr>
54+ </table>
55+ 
56+ Host在Kernel启动前将GM输出矩阵C清零;原子累加写回完成后,Kernel调用asc_disable_dma_atomic关闭DMA原子加法。
57+ 
58+ - Tensor API核心接口:
59+ 1. **张量创建接口**:使用make_tensor + make_mem_ptr + make_frame_layout创建各级张量
60+ - GM张量:nd_ext_layout_ptn布局(ND格式扩展)
61+ - L1/L0张量:nz_layout_ptn/zn_layout_ptn布局(适配cube计算单元)
62+ 
63+ 2. **数据搬运接口**:使用copy及其atom对象
64+ - copy_gm_to_l1:GM到L1的数据搬运,自动处理ND→NZ格式转换
65+ - copy_l1_to_l0a/copy_l1_to_l0b:L1到L0A/L0B的数据搬运
66+ - copy_l0c_to_gm:L0C到GM的数据搬运,自动处理NZ→ND格式转换
67+ 
68+ 3. **矩阵乘接口**:使用mmad及其atom对象
69+ - 自动管理累加控制(init_with_zero参数)
70+ 
71+ 4. **切片接口**:使用slice + make_coord + make_shape获取张量的子区域
72+ - 实现分核逻辑:沿K轴均匀切分,每个核处理一个K轴分片
73+ 
74+ 5. **原子累加接口**:使用asc_set_atomic_add_float配置L0C到GM的float原子加法
75+ - 将各K轴分片的计算结果累加到同一个输出矩阵,写回完成后使用asc_disable_dma_atomic关闭原子加法
76+ 
77+ - 调用实现
78+ 使用内核调用符<<<>>>调用核函数。
79+ 
80+## Tensor API实现特点
81+ 
82+本样例主要使用以下Tensor API能力完成实现:
83+ 
84+| 特性 | 本样例实现 |
85+|------|------------|
86+| 内存管理 | 使用数组方式分配内存,自动管理偏移 |
87+| 张量表示 | 使用张量对象直接描述GM、L1、L0数据 |
88+| 数据搬运 | 使用copy完成跨层搬运 |
89+| 格式转换 | 依赖布局模式自动完成 NZ / ZN 转换 |
90+| 分核逻辑 | 使用slice沿K轴获取当前核处理的数据分片 |
91+| 计算接口 | 使用mmad完成矩阵乘加,使用原子加法累加各分片结果 |
92+ 
93+## 编译运行
94+ 
95+在本样例根目录下执行如下步骤,编译并执行样例。
96+ 
97+- 配置环境变量
98+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../docs/zh/quick_start.md#prepare&install),配置环境变量,**当前仅支持使用[CANN master](../../../../docs/zh/quick_start.md#cann-install)**。
99+ ```bash
100+ source ${install_path}/cann/set_env.sh
101+ ```
102+ 
103+ > **说明:** `${install_path}` 为CANN包安装目录,未指定安装目录时默认安装至 `/usr/local/Ascend` 下。
104+ 
105+- 样例执行
106+ 
107+ 在本样例目录下执行如下命令。
108+ ```bash
109+ mkdir -p build && cd build; # 创建并进入build目录
110+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # 编译工程(默认npu模式)
111+ python3 ../scripts/gen_data.py # 生成测试输入数据
112+ ./demo # 执行编译生成的可执行程序,执行样例
113+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # 验证输出结果是否正确,确认算法逻辑正确
114+ ```
115+ 
116+ 使用NPU仿真模式时,添加`-DCMAKE_ASC_RUN_MODE=sim`参数即可。
117+ 
118+ 示例如下:
119+ 
120+ ```bash
121+ cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU仿真模式
122+ ```
123+ 
124+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行`rm CMakeCache.txt`后重新cmake。
125+ 
126+- 编译选项说明
127+ 
128+ | 选项 | 可选值 | 说明 |
129+ |------|--------|------|
130+ | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 运行模式:NPU 运行、NPU仿真 |
131+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
132+ 
133+ > **说明:** 本样例仅支持dav-3510架构(对应 Ascend 950PR/Ascend 950DT)。
134+ 
135+- 执行结果
136+ 执行结果如下,说明精度对比成功。
137+ 
138+ ```bash
139+ test pass!
140+ ```
@@ -0,0 +1,138 @@
1+# Split-K Matmul Operator Example Based on Tensor API
2+ 
3+## Overview
4+ 
5+This example implements multi-core matrix multiplication based on the static Tensor API programming paradigm. It uses the high-level Tensor API interfaces for data movement, slicing, and multiply-accumulate operations. The computation is split along the K axis, and each core's partial result is accumulated into the output matrix with atomic addition.
6+ 
7+## Supported Products and CANN Software Versions
8+ 
9+| Product | CANN Software Version |
10+|---------|----------------------|
11+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12+ 
13+## Directory Structure
14+ 
15+```text
16+├── matmul_split_k
17+│ ├── scripts
18+│ │ ├── gen_data.py // Input data and golden data generation script
19+│ │ └── verify_result.py // Golden value comparison file
20+│ ├── CMakeLists.txt // Build project file
21+│ ├── data_utils.h // Data read/write functions
22+│ ├── matmul_split_k.asc // Ascend C sample implementation
23+│ └── README.md // Example documentation
24+```
25+ 
26+## Example Description
27+ 
28+- Example functionality:
29+ Matmul calculation formula:
30+ $$
31+ C = A * B
32+ $$
33+- Example specifications:
34+ This example uses M = 16, N = 16, and K = 1024. The K axis is evenly split into four parts, and four cores perform the computation. The input and output specifications are shown in the following table.
35+ <table>
36+ <tr><td rowspan="1" align="center">Example Type (OpType)</td><td colspan="4" align="center">Matmul</td></tr>
37+ <tr><td rowspan="3" align="center">Example Input</td><td align="center">name</td><td align="center">shape</td><td align="center">data type</td><td align="center">format</td></tr>
38+ <tr><td align="center">A</td><td align="center">[M, K]</td><td align="center">float16</td><td align="center">ND</td></tr>
39+ <tr><td align="center">B</td><td align="center">[K, N]</td><td align="center">float16</td><td align="center">ND</td></tr>
40+ <tr><td rowspan="1" align="center">Example Output</td><td align="center">C</td><td align="center">[M, N]</td><td align="center">float32</td><td align="center">ND</td></tr>
41+ <tr><td rowspan="1" align="center">Kernel Function Name</td><td colspan="4" align="center">matmul_split_k_kernel</td></tr>
42+ </table>
43+ 
44+- Example implementation:
45+ - Implementation process:
46+ <table>
47+ <tr><th align="left">Step</th><th align="left">Tensor API Operation</th><th align="left">Function</th><th align="left">Layout Transformation</th></tr>
48+ <tr><td align="left">1</td><td align="left">Constant Tiling Parameters</td><td align="left">Define the parameters required by the kernel through compile-time constants</td><td align="left">Not applicable</td></tr>
49+ <tr><td align="left">2</td><td align="left">make_tensor + slice</td><td align="left">Create GM tensors, split the K axis into four equal parts, and slice the data block processed by the current core according to its core index</td><td align="left">ND format</td></tr>
50+ <tr><td align="left">3</td><td align="left">copy(copy_gm_to_l1)</td><td align="left">Move the current K-axis slices of matrices A and B from GM to L1</td><td align="left">ND->NZ format conversion</td></tr>
51+ <tr><td align="left">4</td><td align="left">copy(copy_l1_to_l0a/copy_l1_to_l0b)</td><td align="left">Move data from L1 to L0A and L0B</td><td align="left">L1->L0A: NZ->NZ<br>L1->L0B: NZ->ZN</td></tr>
52+ <tr><td align="left">5</td><td align="left">mmad</td><td align="left">Complete matrix multiply-accumulate computation for the current K-axis slice</td><td align="left">The matrix multiplication result is in NZ format</td></tr>
53+ <tr><td align="left">6</td><td align="left">asc_set_atomic_add_float + copy(copy_l0c_to_gm)</td><td align="left">Enable float atomic addition and accumulate the L0C results from all cores into the same GM output matrix</td><td align="left">NZ->ND format conversion</td></tr>
54+ </table>
55+ 
56+ The host clears the GM output matrix C before launching the kernel. After the atomic accumulation write-back is complete, the kernel calls `asc_disable_dma_atomic` to disable DMA atomic addition.
57+ 
58+ - Tensor API core interfaces:
59+ 1. **Tensor creation interface**: Use `make_tensor` + `make_mem_ptr` + `make_frame_layout` to create tensors at each memory level.
60+ - GM tensors: `nd_ext_layout_ptn` layout (ND format extension)
61+ - L1/L0 tensors: `nz_layout_ptn`/`zn_layout_ptn` layouts (adapted to the cube compute unit)
62+ 
63+ 2. **Data movement interface**: Use `copy` and its atom objects.
64+ - `copy_gm_to_l1`: Move data from GM to L1 and automatically perform ND to NZ format conversion.
65+ - `copy_l1_to_l0a`/`copy_l1_to_l0b`: Move data from L1 to L0A/L0B.
66+ - `copy_l0c_to_gm`: Move data from L0C to GM and automatically perform NZ to ND format conversion.
67+ 
68+ 3. **Matrix multiplication interface**: Use `mmad` and its atom objects.
69+ - Accumulation control is managed automatically through the `init_with_zero` parameter.
70+ 
71+ 4. **Slicing interface**: Use `slice` + `make_coord` + `make_shape` to obtain tensor sub-regions.
72+ - Implement the multi-core split: split the K axis evenly so that each core processes one K-axis slice.
73+ 
74+ 5. **Atomic accumulation interface**: Use `asc_set_atomic_add_float` to configure float atomic addition for L0C to GM write-back.
75+ - Accumulate the results of all K-axis slices into the same output matrix, then use `asc_disable_dma_atomic` to disable atomic addition after write-back.
76+ 
77+ - Invocation implementation:
78+ Use the kernel call operator `<<<>>>` to invoke the kernel function.
79+ 
80+## Tensor API Implementation Features
81+ 
82+This example primarily uses the following Tensor API capabilities:
83+ 
84+| Feature | Example Implementation |
85+|---------|------------------------|
86+| Memory management | Allocate memory with arrays and manage offsets automatically |
87+| Tensor representation | Use tensor objects to describe GM, L1, and L0 data directly |
88+| Data movement | Use `copy` for movement between memory levels |
89+| Format conversion | Rely on layout patterns to automatically convert between NZ and ZN |
90+| Multi-core split | Use `slice` along the K axis to obtain the data slice processed by the current core |
91+| Computation interface | Use `mmad` for matrix multiply-accumulate and atomic addition to accumulate partial results |
92+ 
93+## Build and Run
94+ 
95+Run the following steps in the root directory of this example to build and run it.
96+ 
97+- Configure environment variables
98+ Configure environment variables according to the [installation method](../../../../docs/en/quick_start.md#prepare&install) of the CANN development kit package in the current environment. **Currently only [CANN master](../../../../docs/en/quick_start.md#cann-install) is supported.**
99+ ```bash
100+ source ${install_path}/cann/set_env.sh
101+ ```
102+ 
103+ > **Note:** `${install_path}` is the CANN package installation directory. When no installation directory is specified, it defaults to `/usr/local/Ascend`.
104+ 
105+- Run the example
106+ 
107+ Run the following commands in the example directory.
108+ ```bash
109+ mkdir -p build && cd build; # Create and enter the build directory
110+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # Build the project (default NPU mode)
111+ python3 ../scripts/gen_data.py # Generate test input data
112+ ./demo # Run the compiled executable
113+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # Verify the output result
114+ ```
115+ 
116+ To use NPU simulation mode, add the `-DCMAKE_ASC_RUN_MODE=sim` parameter. Example:
117+ 
118+ ```bash
119+ cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU simulation mode
120+ ```
121+ 
122+ > **Note:** Clear the cmake cache before switching build modes. Run `rm CMakeCache.txt` in the build directory and then run cmake again.
123+ 
124+- Build option description
125+ 
126+ | Option | Available Values | Description |
127+ |--------|------------------|-------------|
128+ | `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | Run mode: NPU execution, NPU simulation |
129+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU architecture: dav-3510 corresponds to Ascend 950PR/Ascend 950DT |
130+ 
131+ > **Note:** This example only supports dav-3510 architecture (corresponding to Ascend 950PR/Ascend 950DT).
132+ 
133+- Execution result
134+ The following execution result indicates that the precision comparison succeeded.
135+ 
136+ ```bash
137+ test pass!
138+ ```
@@ -0,0 +1,63 @@
1+/**
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 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+#ifndef MATMUL_SPLIT_K_DATA_UTILS_H
12+#define MATMUL_SPLIT_K_DATA_UTILS_H
13+ 
14+#include <fcntl.h>
15+#include <sys/stat.h>
16+#include <unistd.h>
17+ 
18+#include <cstdio>
19+#include <fstream>
20+#include <string>
21+ 
22+inline bool ReadFile(const std::string& path, void* buffer, size_t expectedSize)
23+{
24+ struct stat fileStat {};
25+ if (stat(path.c_str(), &fileStat) != 0 || !S_ISREG(fileStat.st_mode)) {
26+ std::fprintf(stderr, "[ERROR] input file does not exist: %s\n", path.c_str());
27+ return false;
28+ }
29+ if (static_cast<size_t>(fileStat.st_size) != expectedSize) {
30+ std::fprintf(
31+ stderr, "[ERROR] invalid file size for %s: expected %zu, got %zu\n", path.c_str(), expectedSize,
32+ static_cast<size_t>(fileStat.st_size));
33+ return false;
34+ }
35+ std::ifstream file(path, std::ios::binary);
36+ if (!file.read(static_cast<char*>(buffer), expectedSize)) {
37+ std::fprintf(stderr, "[ERROR] failed to read file: %s\n", path.c_str());
38+ return false;
39+ }
40+ return true;
41+}
42+ 
43+inline bool WriteFile(const std::string& path, const void* buffer, size_t size)
44+{
45+ if (buffer == nullptr) {
46+ std::fprintf(stderr, "[ERROR] output buffer is null\n");
47+ return false;
48+ }
49+ const int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
50+ if (fd < 0) {
51+ std::fprintf(stderr, "[ERROR] failed to open output file: %s\n", path.c_str());
52+ return false;
53+ }
54+ const ssize_t written = write(fd, buffer, size);
55+ close(fd);
56+ if (written < 0 || static_cast<size_t>(written) != size) {
57+ std::fprintf(stderr, "[ERROR] failed to write output file: %s\n", path.c_str());
58+ return false;
59+ }
60+ return true;
61+}
62+ 
63+#endif // MATMUL_SPLIT_K_DATA_UTILS_H
@@ -0,0 +1,149 @@
1+/**
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 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+ * \file matmul_split_k.asc
13+ * \brief Split-K matmul based on Tensor API with C API atomic accumulation.
14+ */
15+ 
16+#include <cstdint>
17+ 
18+#include "acl/acl.h"
19+#include "c_api/asc_simd.h"
20+#include "c_api/atomic/datamove_atomic.h"
21+#include "data_utils.h"
22+#include "tensor_api/tensor.h"
23+ 
24+constexpr uint32_t M = 16;
25+constexpr uint32_t K = 1024;
26+constexpr uint32_t N = 16;
27+constexpr uint32_t SPLIT_K = 4;
28+constexpr uint32_t BASE_K = K / SPLIT_K;
29+ 
30+static_assert(K % SPLIT_K == 0, "K must be divisible by SPLIT_K");
31+ 
32+__global__ __cube__ void matmul_split_k_kernel(__gm__ half* a, __gm__ half* b, __gm__ float* c)
33+{
34+ asc_init();
35+ using namespace asc::te;
36+ 
37+ const uint32_t splitIdx = block_idx;
38+ if (splitIdx >= SPLIT_K) {
39+ return;
40+ }
41+ const uint32_t kOffset = splitIdx * BASE_K;
42+ 
43+ auto gmA = make_tensor(make_mem_ptr(a), make_frame_layout<nd_ext_layout_ptn>(M, K));
44+ auto gmB = make_tensor(make_mem_ptr(b), make_frame_layout<nd_ext_layout_ptn>(K, N));
45+ auto gmC = make_tensor(make_mem_ptr(c), make_frame_layout<nd_ext_layout_ptn>(M, N));
46+ auto aTile = gmA.slice(make_coord(0, kOffset), make_shape(M, BASE_K));
47+ auto bTile = gmB.slice(make_coord(kOffset, 0), make_shape(BASE_K, N));
48+ 
49+ auto l1ALayout = make_frame_layout<nz_layout_ptn>(M, BASE_K);
50+ auto l1BLayout = make_frame_layout<nz_layout_ptn>(BASE_K, N);
51+ auto l0ALayout = make_frame_layout<nz_layout_ptn>(M, BASE_K);
52+ auto l0BLayout = make_frame_layout<zn_layout_ptn>(BASE_K, N);
53+ auto l0CLayout = make_frame_layout<nz_layout_ptn>(M, N);
54+ __cbuf__ half l1ABuf[M * BASE_K];
55+ __cbuf__ half l1BBuf[BASE_K * N];
56+ __ca__ half l0ABuf[M * BASE_K];
57+ __cb__ half l0BBuf[BASE_K * N];
58+ __cc__ float l0CBuf[M * N];
59+ 
60+ auto l1A = make_tensor(make_mem_ptr(l1ABuf), l1ALayout);
61+ auto l1B = make_tensor(make_mem_ptr(l1BBuf), l1BLayout);
62+ auto l0A = make_tensor(make_mem_ptr(l0ABuf), l0ALayout);
63+ auto l0B = make_tensor(make_mem_ptr(l0BBuf), l0BLayout);
64+ auto l0C = make_tensor(make_mem_ptr(l0CBuf), l0CLayout);
65+ 
66+ auto gm2l1 = make_copy(copy_gm_to_l1{}, gm_to_l1_trait_default{});
67+ auto l1tol0a = make_copy(copy_l1_to_l0a{}, l1_to_l0a_trait_default{});
68+ auto l1tol0b = make_copy(copy_l1_to_l0b{}, l1_to_l0b_trait_default{});
69+ auto l0c2gm = make_copy(copy_l0c_to_gm{}, l0c_to_gm_trait_default{});
70+ auto mm = make_mmad(mmad_operation{}, mmad_trait_default{});
71+ 
72+ constexpr uint32_t L1_ID = 0;
73+ constexpr uint32_t L0_ID = 1;
74+ constexpr uint32_t L0C_ID = 2;
75+ asc_lock(PIPE_M, L0C_ID);
76+ asc_lock(PIPE_MTE2, L1_ID);
77+ copy(gm2l1, l1A, aTile);
78+ copy(gm2l1, l1B, bTile);
79+ asc_unlock(PIPE_MTE2, L1_ID);
80+ asc_lock(PIPE_MTE1, L1_ID);
81+ asc_lock(PIPE_MTE1, L0_ID);
82+ copy(l1tol0a, l0A, l1A);
83+ copy(l1tol0b, l0B, l1B);
84+ asc_unlock(PIPE_MTE1, L0_ID);
85+ asc_unlock(PIPE_MTE1, L1_ID);
86+ asc_lock(PIPE_M, L0_ID);
87+ auto params = mmad_params{M, N, BASE_K, unit_flag_mode::disable, true};
88+ mmad(mm.with(params), l0C, l0A, l0B);
89+ asc_unlock(PIPE_M, L0_ID);
90+ asc_unlock(PIPE_M, L0C_ID);
91+ 
92+ // Each Cube core contributes one K slice to the same output matrix.
93+ asc_lock(PIPE_FIX, L0C_ID);
94+ asc_set_atomic_add_float();
95+ copy(l0c2gm, gmC, l0C);
96+ asc_disable_dma_atomic();
97+ asc_unlock(PIPE_FIX, L0C_ID);
98+ asc_sync_pipe(PIPE_ALL);
99+}
100+ 
101+int32_t main(int32_t argc, char* argv[])
102+{
103+ size_t aBytes = static_cast<size_t>(M) * K * sizeof(half);
104+ size_t bBytes = static_cast<size_t>(K) * N * sizeof(half);
105+ size_t cBytes = static_cast<size_t>(M) * N * sizeof(float);
106+ 
107+ aclInit(nullptr);
108+ int32_t deviceId = 0;
109+ aclrtSetDevice(deviceId);
110+ aclrtStream stream = nullptr;
111+ aclrtCreateStream(&stream);
112+ 
113+ half* aHost;
114+ half* aDevice;
115+ aclrtMallocHost((void**)(&aHost), aBytes);
116+ aclrtMalloc((void**)&aDevice, aBytes, ACL_MEM_MALLOC_HUGE_FIRST);
117+ ReadFile("./input/x1_gm.bin", aHost, aBytes);
118+ aclrtMemcpy(aDevice, aBytes, aHost, aBytes, ACL_MEMCPY_HOST_TO_DEVICE);
119+ 
120+ half* bHost;
121+ half* bDevice;
122+ aclrtMallocHost((void**)(&bHost), bBytes);
123+ aclrtMalloc((void**)&bDevice, bBytes, ACL_MEM_MALLOC_HUGE_FIRST);
124+ ReadFile("./input/x2_gm.bin", bHost, bBytes);
125+ aclrtMemcpy(bDevice, bBytes, bHost, bBytes, ACL_MEMCPY_HOST_TO_DEVICE);
126+ 
127+ float* cHost;
128+ float* cDevice;
129+ aclrtMallocHost((void**)(&cHost), cBytes);
130+ aclrtMalloc((void**)&cDevice, cBytes, ACL_MEM_MALLOC_HUGE_FIRST);
131+ // Atomic accumulation requires the shared output matrix to start at zero.
132+ aclrtMemset(cDevice, cBytes, 0, cBytes);
133+ 
134+ matmul_split_k_kernel<<<SPLIT_K, 0, stream>>>(aDevice, bDevice, cDevice);
135+ aclrtSynchronizeStream(stream);
136+ aclrtMemcpy(cHost, cBytes, cDevice, cBytes, ACL_MEMCPY_DEVICE_TO_HOST);
137+ WriteFile("./output/output.bin", cHost, cBytes);
138+ 
139+ aclrtFree(aDevice);
140+ aclrtFree(bDevice);
141+ aclrtFree(cDevice);
142+ aclrtFreeHost(aHost);
143+ aclrtFreeHost(bHost);
144+ aclrtFreeHost(cHost);
145+ aclrtDestroyStream(stream);
146+ aclrtResetDevice(deviceId);
147+ aclFinalize();
148+ return 0;
149+}
@@ -0,0 +1,41 @@
1+#!/usr/bin/python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2026 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+from pathlib import Path
15+ 
16+import numpy as np
17+ 
18+ 
19+M = 16
20+K = 1024
21+N = 16
22+SEED = 2026
23+ 
24+ 
25+def generate_data() -> None:
26+ rng = np.random.default_rng(SEED)
27+ matrix_a = rng.uniform(-1.0, 1.0, size=(M, K)).astype(np.float16)
28+ matrix_b = rng.uniform(-1.0, 1.0, size=(K, N)).astype(np.float16)
29+ golden = np.matmul(matrix_a.astype(np.float32), matrix_b.astype(np.float32))
30+ 
31+ input_dir = Path("input")
32+ output_dir = Path("output")
33+ input_dir.mkdir(exist_ok=True)
34+ output_dir.mkdir(exist_ok=True)
35+ matrix_a.tofile(input_dir / "x1_gm.bin")
36+ matrix_b.tofile(input_dir / "x2_gm.bin")
37+ golden.astype(np.float32).tofile(output_dir / "golden.bin")
38+ 
39+ 
40+if __name__ == "__main__":
41+ generate_data()
@@ -0,0 +1,59 @@
1+#!/usr/bin/python3
2+# coding=utf-8
3+ 
4+# ----------------------------------------------------------------------------------------------------------
5+# Copyright (c) 2026 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+import argparse
15+from pathlib import Path
16+ 
17+import numpy as np
18+ 
19+ 
20+M = 16
21+N = 16
22+RELATIVE_TOLERANCE = 1e-3
23+ABSOLUTE_TOLERANCE = 1e-3
24+ 
25+ 
26+def load_matrix(path: Path) -> np.ndarray:
27+ matrix = np.fromfile(path, dtype=np.float32)
28+ expected_size = M * N
29+ if matrix.size != expected_size:
30+ raise ValueError(f"{path} contains {matrix.size} elements, expected {expected_size}")
31+ return matrix.reshape(M, N)
32+ 
33+ 
34+def verify(output_path: Path, golden_path: Path) -> bool:
35+ output = load_matrix(output_path)
36+ golden = load_matrix(golden_path)
37+ close = np.isclose(output, golden, rtol=RELATIVE_TOLERANCE, atol=ABSOLUTE_TOLERANCE, equal_nan=True)
38+ if np.all(close):
39+ max_error = float(np.max(np.abs(output - golden)))
40+ print(f"test pass! max absolute error: {max_error:.6e}")
41+ return True
42+ 
43+ failed = np.argwhere(~close)
44+ for row, column in failed[:10]:
45+ print(f"mismatch at ({row}, {column}): expected={golden[row, column]:.9f}, actual={output[row, column]:.9f}")
46+ print(f"[ERROR] {failed.shape[0]} of {M * N} elements exceed tolerance")
47+ return False
48+ 
49+ 
50+def parse_args() -> argparse.Namespace:
51+ parser = argparse.ArgumentParser()
52+ parser.add_argument("output", type=Path)
53+ parser.add_argument("golden", type=Path)
54+ return parser.parse_args()
55+ 
56+ 
57+if __name__ == "__main__":
58+ args = parse_args()
59+ raise SystemExit(0 if verify(args.output, args.golden) else 1)
@@ -8,9 +8,7 @@
8 8 
9| 产品 | CANN软件版本 |9| 产品 | CANN软件版本 |
10|------|-------------|10|------|-------------|
11-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |11+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12- 
13-> **说明:** 该样例依赖尚未正式发布的CANN特性,请使用最新的CANN master包。
14 12 
15## 目录结构介绍13## 目录结构介绍
16 14 
@@ -8,9 +8,7 @@ This example implements multi-core matrix multiplication computation based on th
8 8 
9| Product | CANN Software Version |9| Product | CANN Software Version |
10|---------|----------------------|10|---------|----------------------|
11-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |11+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12- 
13-> **Note:** This example depends on CANN features that are not yet officially released. Please use the latest CANN master package.
14 12 
15## Directory Structure13## Directory Structure
16 14 
@@ -8,9 +8,7 @@
8 8 
9| 产品 | CANN软件版本 |9| 产品 | CANN软件版本 |
10|------|-------------|10|------|-------------|
11-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |11+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12- 
13-> **说明:** 该样例依赖尚未正式发布的CANN特性,请使用最新的CANN master包。
14 12 
15## 目录结构介绍13## 目录结构介绍
16 14 
@@ -8,7 +8,7 @@ This example implements dynamic Shape matrix multiplication and inline quantizat
8 8 
9| Product | CANN Version |9| Product | CANN Version |
10|---------|-------------|10|---------|-------------|
11-| Ascend 950PR/Ascend 950DT | > CANN 9.1.0 |11+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
12 12 
13> **Note:** This example depends on CANN features that have not been officially released. Use the latest CANN master package.13> **Note:** This example depends on CANN features that have not been officially released. Use the latest CANN master package.
14 14