Merged
TensorAPI添加自定义Op样例 #6174
TensorAPI添加自定义Op样例 #6174
Merged
ca1kwAdd on Sep 18
Total: 9 files changed+808-0
@@ -15,3 +15,4 @@
15| [conv2d_forward_tensor_api](./conv2d_forward_tensor_api) | 基于Tensor API实现Conv2D Forward计算,支持NC1HWC0、NCHW和NHWC三种GM输入/输出格式 | Ascend 950PR/Ascend 950DT |15| [conv2d_forward_tensor_api](./conv2d_forward_tensor_api) | 基于Tensor API实现Conv2D Forward计算,支持NC1HWC0、NCHW和NHWC三种GM输入/输出格式 | Ascend 950PR/Ascend 950DT |
16| [mmad_tensor_api](./mmad_tensor_api) | 基于Tensor API实现动态Shape矩阵乘法和随路量化计算 | Ascend 950PR/Ascend 950DT |16| [mmad_tensor_api](./mmad_tensor_api) | 基于Tensor API实现动态Shape矩阵乘法和随路量化计算 | Ascend 950PR/Ascend 950DT |
17| [matmul_mxfp4_tensor_api_high_performance](./matmul_mxfp4_tensor_api_high_performance) | MxFP4 Matmul Tensor API高性能样例,展示基于静态Tensor编程的高性能实现路径 | Ascend 950PR/Ascend 950DT |17| [matmul_mxfp4_tensor_api_high_performance](./matmul_mxfp4_tensor_api_high_performance) | MxFP4 Matmul Tensor API高性能样例,展示基于静态Tensor编程的高性能实现路径 | Ascend 950PR/Ascend 950DT |
18+| [custom_op_tensor_api](./custom_op_tensor_api) | 基于自定义Tensor API Copy Operation实现batch输入展平和共享权重QKV投影 | Ascend 950PR/Ascend 950DT |
hyolee
hyoleehyoleeSep 20

讨论栏里关于本次的提交信息补充下

likedislike
@@ -15,3 +15,4 @@ This directory contains samples that directly include `tensor_api/tensor.h` and
15| [conv2d_forward_tensor_api](./conv2d_forward_tensor_api) | Implements Conv2D Forward using the Tensor API and supports NC1HWC0, NCHW, and NHWC GM input/output formats | Ascend 950PR/Ascend 950DT |15| [conv2d_forward_tensor_api](./conv2d_forward_tensor_api) | Implements Conv2D Forward using the Tensor API and supports NC1HWC0, NCHW, and NHWC GM input/output formats | Ascend 950PR/Ascend 950DT |
16| [mmad_tensor_api](./mmad_tensor_api) | Implements dynamic-shape matrix multiplication and in-path quantization using the Tensor API | Ascend 950PR/Ascend 950DT |16| [mmad_tensor_api](./mmad_tensor_api) | Implements dynamic-shape matrix multiplication and in-path quantization using the Tensor API | Ascend 950PR/Ascend 950DT |
17| [matmul_mxfp4_tensor_api_high_performance](./matmul_mxfp4_tensor_api_high_performance) | High-performance MxFP4 Matmul Tensor API sample based on the static Tensor programming model | Ascend 950PR/Ascend 950DT |17| [matmul_mxfp4_tensor_api_high_performance](./matmul_mxfp4_tensor_api_high_performance) | High-performance MxFP4 Matmul Tensor API sample based on the static Tensor programming model | Ascend 950PR/Ascend 950DT |
18+| [custom_op_tensor_api](./custom_op_tensor_api) | Implements batched-input flattening and shared-weight QKV projection with a custom Tensor API Copy Operation | Ascend 950PR/Ascend 950DT |
@@ -0,0 +1,34 @@
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, sim")
14+set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510")
15+ 
16+if(NOT CMAKE_ASC_RUN_MODE STREQUAL "npu" AND NOT CMAKE_ASC_RUN_MODE STREQUAL "sim")
17+ message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be 'npu' or 'sim', got: '${CMAKE_ASC_RUN_MODE}'")
18+endif()
19+ 
20+if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510")
21+ message(FATAL_ERROR "custom_op_tensor_api only supports CMAKE_ASC_ARCHITECTURES=dav-3510")
22+endif()
23+ 
24+find_package(ASC REQUIRED)
25+ 
26+project(kernel_samples LANGUAGES ASC CXX)
27+ 
28+add_executable(demo
29+ custom_op_tensor_api.asc
30+)
31+ 
32+target_compile_options(demo PRIVATE
33+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>
34+)
@@ -0,0 +1,193 @@
1+# 基于Tensor API实现的自定义Op样例
2+ 
3+## 概述
4+ 
5+本样例基于Tensor API实现固定Shape的Query-Key-Value(QKV)投影,重点展示如何定义一个自定义Copy Operation,并将它接入Tensor API的Atom调用流程。
6+ 
7+在Transformer的自注意力计算中,输入隐藏状态通常需要分别经过三个线性投影,得到查询(Q)、键(K)和值(V)。三路结果的隐藏维度均为`H`,为了合并计算,可以沿最后一维连续拼接为`[B, S, 3H]`,其中`3H = H(Q) + H(K) + H(V)`。因此,本样例使用`weight[H, 3H]`和`bias[1, 3H]`一次完成三路投影,输出最后一维的前、中、后三段分别对应Q、K、V;后续注意力计算可再按这三个`H`维分段拆分。
8+ 
9+输入是Transformer中的隐藏状态(hidden_states),在样例中以Batch模式的三维Batch ND(N-Dimension,标准数据排列)张量表示,逻辑Shape为[B, S, H]。自定义Operation在Global Memory到L1 Buffer的搬运过程中,将输入的Batch维和Sequence维展平,即逻辑Shape从[B, S, H]转换到[B * S, H],同时完成ND到NZ(分形矩阵排列)的格式转换:
10+ 
11+```text
12+input_flat = reshape(input, [B * S, H])
13+output = input_flat * weight + bias
14+```
15+ 
16+其中`weight[H, 3H]`和`bias[1, 3H]`在所有Batch之间共享。Q、K、V三个投影结果在输出的最后一维中连续排列,本样例只负责投影计算,不再拆分Q、K、V。
17+ 
18+## 本样例支持的产品及CANN软件版本
19+ 
20+| 产品 | CANN软件版本 |
21+|------|--------------|
22+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
23+ 
24+## 目录结构介绍
25+ 
26+```text
27+├── scripts
28+│ ├── gen_data.py // 生成输入数据和CPU侧真值
29+│ └── verify_result.py // 比对样例输出和真值
30+├── CMakeLists.txt // 编译工程文件
31+├── custom_op_tensor_api.asc // 自定义Operation、Kernel和Host调用
32+├── data_utils.h // 二进制数据读写工具
33+├── README_en.md // 英文说明文档
34+└── README.md // 中文说明文档
35+```
36+ 
37+## 样例描述
38+ 
39+### 样例规格
40+ 
41+| Tensor | 逻辑Shape | Global Memory Format | 数据类型 | 说明 |
42+|--------|------------|-----------|----------|------|
43+| `input` | `[B, S, H] = [16, 64, 256]` | Batch ND | `half` | 输入隐藏状态 `hidden_states` |
44+| `weight` | `[H, 3H] = [256, 768]` | ND | `half` | 共享投影权重 |
45+| `bias` | `[1, 3H] = [768]` | ND | `half` | 共享偏置 |
46+| `output` | `[B*S, 3H] = [1024, 768]` | ND | `half` | 投影结果 |
47+ 
48+输出在逻辑上也可以解释为`[B, S, 3H] = [16, 64, 768]`。展平只改变逻辑索引,不需要额外的数据搬运。
49+ 
50+矩阵乘法参数为:
51+ 
52+```text
53+M = B * S = 1024
54+K = H = 256
55+N = 3 * H = 768
56+```
57+ 
58+### 自定义Copy Operation
59+ 
60+本样例的核心是`copy_slice_gm_to_l1`。输入需要自定义的原因是它的Global Memory源Tensor保留三维Batch ND的Stride,而L1 Buffer目标Tensor是二维NZ;权重和Bias是普通二维ND搬运,仍使用标准`copy_gm_to_l1`即可。
61+ 
62+矩阵乘法本身使用Tensor API已有的`mmad`和标准搬运Atom;只有输入从Global Memory搬到L1 Buffer时,需要同时完成“Batch ND展平”和“ND到NZ格式转换”,因此定义了这个自定义Copy Operation来封装底层搬运,并将不符合标准二维Copy语义的Batch输入搬运接入统一的Tensor API `copy(atom, dst, src)`调用流程。
63+ 
64+#### Operation实现
65+ 
66+`copy_slice_gm_to_l1`实现了一个静态模板函数`copy`,从源、目的Tensor中读取元素类型、Shape、Stride、目的NZ布局和Cache Mode,再根据这些信息生成底层C API所需的参数。它处理的逻辑格式为:
67+ 
68+| Tensor | 存储位置 | Shape | LayoutPattern |
69+|--------|----------|-------|---------------|
70+| 源 | Global Memory | `[B_tile, S, K_tile]` | Batch模式`nd_layout_ptn` |
71+| 目的 | L1 Buffer | `[B_tile * S, K_tile]` | `nz_layout_ptn` |
72+ 
73+当前Kernel每次处理一个`base_m`乘`base_k`的输入Tile,因此:
74+ 
75+```text
76+B_tile = base_m / S = 128 / 64 = 2
77+K_tile = base_k = 64
78+[2, 64, 64] Batch ND -> [128, 64] NZ
79+```
80+ 
81+Tensor API通过`copy_traits`将一个Copy Operation与其执行Trait绑定,`make_copy`再根据该Traits创建可调用的Atom。为了把`copy_slice_gm_to_l1`接入这条通用流程,样例提供了两个`copy_traits`特化:
82+ 
83+```cpp
84+// 传入自定义Trait时,保持该Trait并绑定当前Operation。
85+template <typename Trait>
86+struct copy_traits<copy_slice_gm_to_l1, Trait>
87+ : public copy_traits<copy_slice_gm_to_l1, Trait, copy_slice_gm_to_l1, Trait> {};
88+ 
89+// 未显式传入Trait时,默认使用Global Memory到L1 Buffer的标准Trait。
90+template <>
91+struct copy_traits<copy_slice_gm_to_l1> : public copy_traits<copy_slice_gm_to_l1, gm_to_l1_trait_default> {};
92+```
93+ 
94+这样,`copy_slice_gm_to_l1`就能像标准Copy Operation一样创建和调用:
95+ 
96+```cpp
97+const auto custom_copy_atom = make_copy(copy_slice_gm_to_l1{}, gm_to_l1_trait_default{});
98+copy(custom_copy_atom, input_l1_tensor, input_gm_slice);
99+```
100+ 
101+在Kernel中,自定义Atom只用于输入:
102+ 
103+```cpp
104+copy(custom_copy_atom, input_l1_tensor, input_gm_tensor.slice(...));
105+copy(weight_l1_tensor, weight_gm_tensor.slice(...));
106+```
107+ 
108+#### 参数推导
109+ 
110+Operation不把当前参数写死,而是从Tensor Layout推导搬运参数。对于当前`[2, 64, 64]`输入Slice和`half`类型,推导关系如下:
111+ 
112+| 参数 | 当前值 | 推导方式与含义 |
113+|------------|------------|------------------|
114+| `matrix_num` | 2 | 源Shape的Batch Tile,即`base_m / S` |
115+| `n_value` | 64 | 源Shape的Sequence长度,即`S` |
116+| `d_value` | 64 | 源Shape的K方向Tile,即`base_k` |
117+| `src_d_value` | 512 Byte | 源Stride中相邻Sequence行的间隔,即`H * sizeof(half)` |
118+| `src_nd_matrix_stride` | 32768 Byte | 源Stride中相邻Batch矩阵的间隔,即`S * H * sizeof(half)` |
119+| `dst_nz_n_stride` | 1 | 目标NZ相邻行的起始地址间隔,单位为32 Byte |
120+| `dst_nz_c0_stride` | 128 | 从目标NZ Layout的列Stride除以`c0_element<half>`得到,单位为32 Byte |
121+| `dst_nz_matrix_stride` | 64 | 目标NZ中相邻Batch矩阵的起始地址间隔,取值为`n_value`,单位为32 Byte;当前值对应2048 Byte |
122+| `enable_small_c0` | `false` | 当前`d_value=64`,不使用SmallC0模式 |
123+ 
124+其中,`src_d_value`和`src_nd_matrix_stride`使用源Tensor的原始Stride计算,而不是假定源数据已经展平;这样第二个Batch会从正确的Global Memory地址开始读取。`dst_nz_matrix_stride`保证多个Batch依次写入同一个`[base_m, base_k]` NZ目标,不发生覆盖。
125+ 
126+#### 底层C API调用
127+ 
128+参数推导完成后,`copy`函数将工作交给私有辅助函数`copy_gm_to_cbuf_multi_nd2nz`。该辅助函数负责数据类型分派、架构条件编译和底层指针转换:它根据数据类型将Tensor指针转换为`__gm__`和`__cbuf__`指针,当前支持`half`和`float`两种类型,并在编译期选择对应的C API重载。3510架构分支中,调用顺序固定为先设置NZ搬运参数,再执行ND2NZ搬运:
129+ 
130+```cpp
131+asc_set_gm2l1_nz_para(matrix_num, dst_nz_n_stride, dst_nz_c0_stride, dst_nz_matrix_stride);
132+asc_copy_gm2l1_nd2nz(
133+ dst, src, src_d_value, l2_cache_mode, n_value, d_value, src_nd_matrix_stride, enable_small_c0);
134+```
135+ 
136+源Tensor的Cache Mode通过`src.engine().get_cache_mode()`取得,并转换为C API要求的`asc_load_l2_cache_mode`后传入。`asc_set_gm2l1_nz_para`负责配置目标NZ的步长关系,`asc_copy_gm2l1_nd2nz`负责按源Stride读取多Batch ND矩阵并完成格式转换;两者缺一不可。
137+ 
138+#### 使用约束
139+ 
140+- 源Tensor必须是Global Memory中的三维Batch模式`nd_layout_ptn` Layout,目的Tensor必须是L1 Buffer中的二维`nz_layout_ptn` Layout,且二者的Shape满足`[B_tile, S, K_tile] -> [B_tile * S, K_tile]`。
141+- 源、目的Tensor元素类型必须一致,且必须是当前实现支持的`half`或`float`。
142+- 目的Tensor的行数必须等于`B_tile * S`,K方向大小必须等于`K_tile`。
143+- 目标NZ Layout必须提供可推导的C0列Stride。
144+- 当前底层实现只在`current_arch_version == arch_version::v3510`分支调用3510 C API;移植到其他架构时,需要补充对应架构的ND2NZ实现。
145+ 
146+## 编译运行
147+ 
148+在本样例根目录下执行如下步骤,编译并执行样例。
149+ 
150+- 配置环境变量
151+ 
152+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../docs/zh/quick_start.md#prepare&install),配置环境变量。
153+ 
154+ ```bash
155+ source ${install_path}/cann/set_env.sh
156+ ```
157+ 
158+ > **说明:** `${install_path}` 为CANN包安装目录,未指定安装目录时默认安装至`/usr/local/Ascend`下。
159+ 
160+- 样例执行
161+ 
162+ 在本样例目录下执行如下命令。
163+ 
164+ ```bash
165+ mkdir -p build && cd build; # 创建并进入build目录
166+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # 编译工程,默认NPU模式
167+ python3 ../scripts/gen_data.py # 生成测试输入数据和真值
168+ ./demo # 执行样例
169+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # 验证输出结果是否正确,确认算法逻辑正确
170+ ```
171+ 
172+ 使用NPU仿真模式时,添加`-DCMAKE_ASC_RUN_MODE=sim`参数即可。
173+ 
174+ 示例如下:
175+ 
176+ ```bash
177+ cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU仿真模式
178+ ```
179+ 
180+ > **注意:** 切换编译模式前需清理cmake缓存,可在build目录下执行`rm CMakeCache.txt`后重新cmake。
181+ 
182+- 编译选项说明
183+ 
184+ | 选项 | 可选值 | 说明 |
185+ |------|--------|------|
186+ | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 运行模式:NPU 运行、NPU仿真 |
187+ | `CMAKE_ASC_ARCHITECTURES` |`dav-3510` | NPU 架构:dav-3510 对应 Ascend 950PR/Ascend 950DT |
188+ 
189+ 执行结果如下,说明精度对比成功。
190+ 
191+ ```bash
192+ test pass!
193+ ```
@@ -0,0 +1,193 @@
1+# Tensor API Custom Op Sample
2+ 
3+## Overview
4+ 
5+This sample implements a fixed-shape Query-Key-Value (QKV) projection with the Tensor API. It focuses on how to define a custom Copy Operation and connect it to the Tensor API Atom invocation flow.
6+ 
7+In Transformer self-attention, the input hidden states are normally passed through three linear projections to obtain queries (Q), keys (K), and values (V). Each projection result has a hidden size of `H`. To combine the three computations, the results can be concatenated along the last dimension as `[B, S, 3H]`, where `3H = H(Q) + H(K) + H(V)`. This sample therefore uses `weight[H, 3H]` and `bias[1, 3H]` to perform the three projections at once. The first, middle, and last `H`-wide segments of the output correspond to Q, K, and V, respectively. The subsequent attention computation can split the output again by these three segments.
8+ 
9+The input is the Transformer hidden state (`hidden_states`). It is represented in this sample as a three-dimensional Batch ND (N-Dimension, standard data arrangement) tensor with logical shape `[B, S, H]`. While the input is moved from Global Memory to L1 Buffer, the custom Operation flattens the Batch and Sequence dimensions, changing the logical shape from `[B, S, H]` to `[B * S, H]`, and converts ND to NZ (fractal matrix arrangement):
10+ 
11+```text
12+input_flat = reshape(input, [B * S, H])
13+output = input_flat * weight + bias
14+```
15+ 
16+`weight[H, 3H]` and `bias[1, 3H]` are shared by all batches. The Q, K, and V projection results are stored contiguously in the last dimension of the output. This sample performs only the projection and does not split Q, K, and V.
17+ 
18+## Supported Products and CANN Versions
19+ 
20+| Product | CANN Version |
21+|---------|--------------|
22+| Ascend 950PR/Ascend 950DT | >= CANN 9.2.0 |
23+ 
24+## Directory Structure
25+ 
26+```text
27+├── scripts
28+│ ├── gen_data.py // Generate input data and CPU-side golden data
29+│ └── verify_result.py // Compare sample output with the golden data
30+├── CMakeLists.txt // Build project file
31+├── custom_op_tensor_api.asc // Custom Operation, Kernel, and host invocation
32+├── data_utils.h // Binary file read/write utilities
33+├── README_en.md // English documentation
34+└── README.md // Chinese documentation
35+```
36+ 
37+## Sample Description
38+ 
39+### Sample Specification
40+ 
41+| Tensor | Logical Shape | Global Memory Format | Data Type | Description |
42+|--------|---------------|-----------|-----------|-------------|
43+| `input` | `[B, S, H] = [16, 64, 256]` | Batch ND | `half` | Input hidden state `hidden_states` |
44+| `weight` | `[H, 3H] = [256, 768]` | ND | `half` | Shared projection weight |
45+| `bias` | `[1, 3H] = [768]` | ND | `half` | Shared bias |
46+| `output` | `[B*S, 3H] = [1024, 768]` | ND | `half` | Projection result |
47+ 
48+The output can also be interpreted logically as `[B, S, 3H] = [16, 64, 768]`. Flattening changes only logical indexing and does not require an additional data movement.
49+ 
50+The matrix multiplication parameters are:
51+ 
52+```text
53+M = B * S = 1024
54+K = H = 256
55+N = 3 * H = 768
56+```
57+ 
58+### Custom Copy Operation
59+ 
60+The core of this sample is `copy_slice_gm_to_l1`. The input requires a custom Operation because its Global Memory source tensor retains three-dimensional Batch ND strides while its L1 Buffer destination tensor is two-dimensional NZ. The weight and bias use ordinary two-dimensional ND transfers and can continue to use standard `copy_gm_to_l1`.
61+ 
62+The matrix multiplication itself uses the existing Tensor API `mmad` and standard copy Atoms. Only the input movement from Global Memory to L1 Buffer must simultaneously flatten Batch ND data and convert ND to NZ. The custom Copy Operation therefore encapsulates this underlying transfer and connects a batched input movement that does not fit standard two-dimensional Copy semantics to the unified Tensor API `copy(atom, dst, src)` flow.
63+ 
64+#### Operation Implementation
65+ 
66+`copy_slice_gm_to_l1` implements a static template function named `copy`. It reads the element type, shape, stride, destination NZ layout, and cache mode from the source and destination tensors, then derives the parameters required by the underlying C API. The logical format is:
67+ 
68+| Tensor | Location | Shape | LayoutPattern |
69+|--------|----------|-------|---------------|
70+| Source | Global Memory | `[B_tile, S, K_tile]` | Batched `nd_layout_ptn` |
71+| Destination | L1 Buffer | `[B_tile * S, K_tile]` | `nz_layout_ptn` |
72+ 
73+The Kernel processes one `base_m` by `base_k` input tile at a time, so:
74+ 
75+```text
76+B_tile = base_m / S = 128 / 64 = 2
77+K_tile = base_k = 64
78+[2, 64, 64] Batch ND -> [128, 64] NZ
79+```
80+ 
81+Tensor API binds a Copy Operation to its execution Trait through `copy_traits`, and `make_copy` creates an invocable Atom from that Trait. To connect `copy_slice_gm_to_l1` to this flow, the sample provides two `copy_traits` specializations:
82+ 
83+```cpp
84+// Preserve a caller-provided custom Trait and bind it to this Operation.
85+template <typename Trait>
86+struct copy_traits<copy_slice_gm_to_l1, Trait>
87+ : public copy_traits<copy_slice_gm_to_l1, Trait, copy_slice_gm_to_l1, Trait> {};
88+ 
89+// Use the default Global Memory-to-L1 Buffer Trait when no Trait is explicitly provided.
90+template <>
91+struct copy_traits<copy_slice_gm_to_l1> : public copy_traits<copy_slice_gm_to_l1, gm_to_l1_trait_default> {};
92+```
93+ 
94+This allows `copy_slice_gm_to_l1` to be created and invoked like a standard Copy Operation:
95+ 
96+```cpp
97+const auto custom_copy_atom = make_copy(copy_slice_gm_to_l1{}, gm_to_l1_trait_default{});
98+copy(custom_copy_atom, input_l1_tensor, input_gm_slice);
99+```
100+ 
101+In the Kernel, the custom Atom is used only for the input:
102+ 
103+```cpp
104+copy(custom_copy_atom, input_l1_tensor, input_gm_tensor.slice(...));
105+copy(weight_l1_tensor, weight_gm_tensor.slice(...));
106+```
107+ 
108+#### Parameter Derivation
109+ 
110+The Operation does not hard-code the sample parameters. Instead, it derives the transfer parameters from the tensor layouts. For the current `[2, 64, 64]` input slice and `half` type, the derivation is:
111+ 
112+| Parameter | Current Value | Derivation and Meaning |
113+|-----------|---------------|------------------------|
114+| `matrix_num` | 2 | Batch tile in the source shape, equal to `base_m / S` |
115+| `n_value` | 64 | Sequence length in the source shape, equal to `S` |
116+| `d_value` | 64 | K-direction tile in the source shape, equal to `base_k` |
117+| `src_d_value` | 512 bytes | Stride between adjacent sequence rows in the source, equal to `H * sizeof(half)` |
118+| `src_nd_matrix_stride` | 32768 bytes | Stride between adjacent batch matrices in the source, equal to `S * H * sizeof(half)` |
119+| `dst_nz_n_stride` | 1 | Offset between adjacent NZ rows in the destination, in 32-byte units |
120+| `dst_nz_c0_stride` | 128 | Destination NZ column stride divided by `c0_element<half>`, in 32-byte units |
121+| `dst_nz_matrix_stride` | 64 | Offset between adjacent batch matrices in the destination NZ, equal to `n_value` in 32-byte units; the current value corresponds to 2048 bytes |
122+| `enable_small_c0` | `false` | The current `d_value` is 64, so SmallC0 mode is not used |
123+ 
124+`src_d_value` and `src_nd_matrix_stride` are derived from the original source tensor strides rather than assuming that the source has already been flattened. This ensures that the second batch starts from the correct Global Memory address. `dst_nz_matrix_stride` ensures that multiple batches are written sequentially into the same `[base_m, base_k]` NZ destination without overwriting each other.
125+ 
126+#### Underlying C API Invocation
127+ 
128+After parameter derivation, the `copy` function delegates to the private helper `copy_gm_to_cbuf_multi_nd2nz`. This helper handles data-type dispatch, architecture-specific conditional compilation, and low-level pointer conversion. It converts tensor pointers to `__gm__` and `__cbuf__` pointers according to the data type, supports `half` and `float`, and selects the corresponding C API overload at compile time. In the 3510 architecture branch, it first sets the NZ transfer parameters and then performs the ND-to-NZ transfer:
129+ 
130+```cpp
131+asc_set_gm2l1_nz_para(matrix_num, dst_nz_n_stride, dst_nz_c0_stride, dst_nz_matrix_stride);
132+asc_copy_gm2l1_nd2nz(
133+ dst, src, src_d_value, l2_cache_mode, n_value, d_value, src_nd_matrix_stride, enable_small_c0);
134+```
135+ 
136+The source tensor cache mode is obtained through `src.engine().get_cache_mode()` and converted to the `asc_load_l2_cache_mode` type required by the C API. `asc_set_gm2l1_nz_para` configures the destination NZ stride relationship, while `asc_copy_gm2l1_nd2nz` reads multiple batch matrices using the source strides and performs the format conversion. Both calls are required.
137+ 
138+#### Usage Constraints
139+ 
140+- The source tensor must use a three-dimensional batched `nd_layout_ptn` layout in Global Memory, and the destination tensor must use a two-dimensional `nz_layout_ptn` layout in L1 Buffer. Their shapes must satisfy `[B_tile, S, K_tile] -> [B_tile * S, K_tile]`.
141+- The source and destination element types must be the same and must be `half` or `float`, as supported by the current implementation.
142+- The destination row count must equal `B_tile * S`, and the K-direction size must equal `K_tile`.
143+- The destination NZ layout must provide a derivable C0 column stride.
144+- The underlying implementation calls the 3510 C APIs only in the `current_arch_version == arch_version::v3510` branch. Porting to another architecture requires an architecture-specific ND-to-NZ implementation.
145+ 
146+## Build and Run
147+ 
148+Run the following steps in the sample root directory.
149+ 
150+- Configure environment variables.
151+ 
152+ Configure the environment variables according to the CANN development kit [installation method](../../../../docs/en/quick_start.md#prepare&install).
153+ 
154+ ```bash
155+ source ${install_path}/cann/set_env.sh
156+ ```
157+ 
158+ > **Note:** ${install_path} is the CANN installation directory. If no installation directory is specified, CANN is installed under `/usr/local/Ascend` by default.
159+ 
160+- Run the sample.
161+ 
162+ Run the following commands in the sample directory.
163+ 
164+ ```bash
165+ mkdir -p build && cd build; # Create and enter the build directory
166+ cmake -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # Build the project; NPU mode by default
167+ python3 ../scripts/gen_data.py # Generate test input and golden data
168+ ./demo # Run the sample
169+ python3 ../scripts/verify_result.py output/output.bin output/golden.bin # Verify that the output matches the golden data
170+ ```
171+ 
172+ For NPU simulation mode, add `-DCMAKE_ASC_RUN_MODE=sim`.
173+ 
174+ For example:
175+ 
176+ ```bash
177+ cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU simulation mode
178+ ```
179+ 
180+ > **Note:** Before switching build modes, clean the CMake cache. In the `build` directory, run `rm CMakeCache.txt` and run `cmake` again.
181+ 
182+- Build options
183+ 
184+ | Option | Values | Description |
185+ |--------|--------|-------------|
186+ | `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | Run mode: NPU or NPU simulation |
187+ | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU architecture; `dav-3510` corresponds to Ascend 950PR/Ascend 950DT |
188+ 
189+ The following output indicates that the precision comparison passed:
190+ 
191+ ```bash
192+ test pass!
193+ ```
@@ -0,0 +1,267 @@
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 custom_op_tensor_api.asc
13+ * \brief Batched QKV projection using a custom Tensor API copy operation.
14+ */
15+ 
16+#include <cstdint>
17+ 
18+#include "acl/acl.h"
19+#include "c_api/asc_simd.h"
20+#include "data_utils.h"
21+#include "tensor_api/tensor.h"
22+ 
23+namespace asc {
24+namespace te {
25+ 
26+// Flatten a batched [B, S, H] ND tensor into a [B * S, H] NZ tensor while copying it from GM to L1.
27+struct copy_slice_gm_to_l1 {
28+ template <typename Trait, const Trait& trait, typename DstTensor, typename SrcTensor>
29+ __aicore__ inline static void copy(const DstTensor& dst, const SrcTensor& src)
30+ {
31+ using src_type = typename SrcTensor::element_type;
32+ const auto src_layout = src.layout();
33+ const auto dst_layout = dst.layout();
34+ 
35+ const auto src_shape = src_layout.shape();
36+ const auto src_stride = src_layout.stride();
37+ const uint16_t matrix_num = static_cast<uint16_t>(get<0>(src_shape));
38+ const uint16_t n_value = static_cast<uint16_t>(get<1, 0>(src_shape));
39+ const uint32_t d_value = static_cast<uint32_t>(get<1, 1>(src_shape));
40+ const uint64_t src_d_value = get<1, 0>(src_stride) * sizeof(src_type);
41+ const uint64_t src_nd_matrix_stride = get<0>(src_stride) * sizeof(src_type);
42+ 
43+ constexpr uint16_t dst_nz_n_stride = 1;
44+ const auto dst_column_stride = get<1, 1>(dst_layout.stride());
45+ const uint16_t dst_nz_c0_stride = static_cast<uint16_t>(dst_column_stride / c0_element<src_type>);
46+ const uint16_t dst_nz_matrix_stride = static_cast<uint16_t>(n_value);
hyolee
hyoleehyoleeSep 20

这些变量命名还是沿用isa里的,c api已经优化过参数命名了吧,尽量和c api一致

likedislike
ca1kw
ca1kw
Sep 21 Comments:
likedislike
47+ const auto l2_cache_mode = static_cast<asc_load_l2_cache_mode>(src.engine().get_cache_mode());
48+ 
49+ if constexpr (sizeof(src_type) == sizeof(half)) {
50+ copy_gm_to_cbuf_multi_nd2nz(
51+ reinterpret_cast<__cbuf__ half*>(dst.data().get()), reinterpret_cast<__gm__ half*>(src.data().get()),
52+ matrix_num, dst_nz_n_stride, dst_nz_c0_stride, dst_nz_matrix_stride, src_d_value, l2_cache_mode,
53+ n_value, d_value, src_nd_matrix_stride, false);
54+ } else if constexpr (sizeof(src_type) == sizeof(float)) {
55+ copy_gm_to_cbuf_multi_nd2nz(
56+ reinterpret_cast<__cbuf__ float*>(dst.data().get()), reinterpret_cast<__gm__ float*>(src.data().get()),
57+ matrix_num, dst_nz_n_stride, dst_nz_c0_stride, dst_nz_matrix_stride, src_d_value, l2_cache_mode,
58+ n_value, d_value, src_nd_matrix_stride, false);
59+ }
60+ }
61+ 
62+private:
63+ template <typename DataType>
64+ __aicore__ inline static void copy_gm_to_cbuf_multi_nd2nz(
65+ __cbuf__ DataType* dst, __gm__ DataType* src, uint16_t matrix_num, uint16_t dst_nz_n_stride,
66+ uint16_t dst_nz_c0_stride, uint16_t dst_nz_matrix_stride, uint64_t src_d_value,
67+ asc_load_l2_cache_mode l2_cache_mode, uint16_t n_value, uint32_t d_value, uint64_t src_nd_matrix_stride,
68+ bool enable_small_c0)
69+ {
70+ if constexpr (current_arch_version == arch_version::v3510) {
71+ asc_set_gm2l1_nz_para(matrix_num, dst_nz_n_stride, dst_nz_c0_stride, dst_nz_matrix_stride);
72+ asc_copy_gm2l1_nd2nz(
73+ dst, src, src_d_value, l2_cache_mode, n_value, d_value, src_nd_matrix_stride, enable_small_c0);
74+ }
75+ }
76+};
77+ 
78+template <typename Trait>
79+struct copy_traits<copy_slice_gm_to_l1, Trait>
80+ : public copy_traits<copy_slice_gm_to_l1, Trait, copy_slice_gm_to_l1, Trait> {};
81+ 
82+template <>
83+struct copy_traits<copy_slice_gm_to_l1> : public copy_traits<copy_slice_gm_to_l1, gm_to_l1_trait_default> {};
84+ 
85+} // namespace te
86+} // namespace asc
87+ 
88+template <
89+ typename DataType, uint32_t batch, uint32_t sequence_length, uint32_t hidden_size, uint32_t projection_size,
90+ uint32_t single_core_m, uint32_t single_core_n, uint32_t single_core_k, uint32_t base_m, uint32_t base_n,
91+ uint32_t base_k>
92+__global__ __cube__ void custom_op_tensor_api(
93+ __gm__ DataType* input, __gm__ DataType* weight, __gm__ DataType* bias, __gm__ DataType* output)
94+{
95+ asc_init();
96+ using namespace asc::te;
97+ 
98+ constexpr uint32_t flattened_m = batch * sequence_length;
99+ constexpr uint32_t m_iter = flattened_m / single_core_m;
100+ constexpr uint32_t m_loop = single_core_m / base_m;
101+ constexpr uint32_t n_loop = single_core_n / base_n;
102+ constexpr uint32_t k_loop = single_core_k / base_k;
103+ 
104+ // Each Cube core computes a single_core_m x single_core_n region of the flattened [B * S, 3H] output.
105+ const uint32_t m_iter_index = block_idx % m_iter;
106+ const uint32_t n_iter_index = block_idx / m_iter;
107+ const uint32_t single_core_m_start = m_iter_index * single_core_m;
108+ const uint32_t single_core_n_start = n_iter_index * single_core_n;
109+ 
110+ __cbuf__ DataType input_l1_buffer[base_m * base_k];
111+ __cbuf__ DataType weight_l1_buffer[base_k * base_n];
112+ __cbuf__ DataType bias_l1_buffer[base_n];
113+ __ca__ DataType input_l0_buffer[base_m * base_k];
114+ __cb__ DataType weight_l0_buffer[base_k * base_n];
115+ __biasbuf__ float bias_l0_buffer[base_n];
116+ __cc__ float output_l0_buffer[base_m * base_n];
117+ 
118+ auto input_gm_tensor =
119+ make_tensor(make_mem_ptr(input), make_frame_layout<nd_layout_ptn>(batch, sequence_length, hidden_size));
120+ auto weight_gm_tensor =
121+ make_tensor(make_mem_ptr(weight), make_frame_layout<nd_layout_ptn>(hidden_size, projection_size));
122+ auto bias_gm_tensor = make_tensor(make_mem_ptr(bias), make_frame_layout<nd_layout_ptn>(1, projection_size));
123+ auto output_gm_tensor =
124+ make_tensor(make_mem_ptr(output), make_frame_layout<nd_layout_ptn>(flattened_m, projection_size));
125+ 
126+ auto input_l1_tensor =
127+ make_tensor(make_mem_ptr(input_l1_buffer), make_frame_layout<nz_layout_ptn, DataType>(base_m, base_k));
128+ auto weight_l1_tensor =
129+ make_tensor(make_mem_ptr(weight_l1_buffer), make_frame_layout<nz_layout_ptn, DataType>(base_k, base_n));
130+ auto bias_l1_tensor =
131+ make_tensor(make_mem_ptr(bias_l1_buffer), make_frame_layout<nd_layout_ptn, DataType>(1, base_n));
132+ auto input_l0_tensor =
133+ make_tensor(make_mem_ptr(input_l0_buffer), make_frame_layout<nz_layout_ptn, DataType>(base_m, base_k));
134+ auto weight_l0_tensor =
135+ make_tensor(make_mem_ptr(weight_l0_buffer), make_frame_layout<zn_layout_ptn, DataType>(base_k, base_n));
136+ auto bias_l0_tensor = make_tensor(make_mem_ptr(bias_l0_buffer), make_frame_layout<nd_layout_ptn>(1, base_n));
137+ auto output_l0_tensor =
138+ make_tensor(make_mem_ptr(output_l0_buffer), make_frame_layout<nz_layout_ptn>(base_m, base_n));
139+ 
140+ const auto custom_copy_atom = make_copy(copy_slice_gm_to_l1{}, gm_to_l1_trait_default{});
141+ const auto projection_mmad_atom = make_mmad(mmad_operation{}, mmad_trait_default{});
hyolee
hyoleehyoleeSep 20

有些可以直接用不带atom的实现,就不需要创建这么多atom

likedislike
142+ 
143+ constexpr uint8_t mutex_id = 0;
144+ for (uint32_t m_block_index = 0; m_block_index < m_loop; ++m_block_index) {
145+ const uint32_t m_start = single_core_m_start + m_block_index * base_m;
146+ const uint32_t batch_start = m_start / sequence_length;
147+ for (uint32_t n_block_index = 0; n_block_index < n_loop; ++n_block_index) {
148+ const uint32_t n_start = single_core_n_start + n_block_index * base_n;
149+ for (uint32_t k_tile_index = 0; k_tile_index < k_loop; ++k_tile_index) {
150+ const uint32_t k_start = k_tile_index * base_k;
151+ 
152+ asc_lock(PIPE_MTE2, mutex_id);
153+ copy(
154+ custom_copy_atom, input_l1_tensor,
155+ input_gm_tensor.slice(
156+ make_coord(batch_start, make_coord(0, k_start)),
157+ make_shape(base_m / sequence_length, make_shape(sequence_length, base_k))));
158+ copy(
159+ weight_l1_tensor, weight_gm_tensor.slice(make_coord(k_start, n_start), make_shape(base_k, base_n)));
160+ if (k_tile_index == 0) {
161+ copy(bias_l1_tensor, bias_gm_tensor.slice(make_coord(0, n_start), make_shape(1, base_n)));
162+ }
163+ asc_unlock(PIPE_MTE2, mutex_id);
164+ 
165+ asc_lock(PIPE_MTE1, mutex_id);
166+ copy(input_l0_tensor, input_l1_tensor);
167+ copy(weight_l0_tensor, weight_l1_tensor);
168+ if (k_tile_index == 0) {
169+ copy(bias_l0_tensor, bias_l1_tensor);
170+ }
171+ asc_unlock(PIPE_MTE1, mutex_id);
172+ 
173+ asc_lock(PIPE_M, mutex_id);
174+ const auto projection_atom = projection_mmad_atom.with(mmad_params{
175+ static_cast<uint16_t>(base_m), static_cast<uint16_t>(base_n), static_cast<uint16_t>(base_k),
176+ unit_flag_mode::disable, k_tile_index == 0});
177+ if (k_tile_index == 0) {
178+ mmad(projection_atom, output_l0_tensor, input_l0_tensor, weight_l0_tensor, bias_l0_tensor);
179+ } else {
180+ mmad(projection_atom, output_l0_tensor, input_l0_tensor, weight_l0_tensor);
181+ }
182+ asc_unlock(PIPE_M, mutex_id);
183+ }
184+ 
185+ asc_lock(PIPE_FIX, mutex_id);
186+ copy(output_gm_tensor.slice(make_coord(m_start, n_start), make_shape(base_m, base_n)), output_l0_tensor);
187+ asc_unlock(PIPE_FIX, mutex_id);
188+ }
189+ }
190+ asc_sync_pipe(PIPE_ALL);
191+}
192+ 
193+int32_t main(int32_t argc, char* argv[])
194+{
195+ (void)argc;
196+ (void)argv;
197+ 
198+ using DataType = half;
199+ constexpr uint32_t batch = 16;
200+ constexpr uint32_t sequence_length = 64;
201+ constexpr uint32_t hidden_size = 256;
202+ constexpr uint32_t projection_size = 3 * hidden_size;
203+ constexpr uint32_t single_core_m = 256;
204+ constexpr uint32_t single_core_n = 384;
205+ constexpr uint32_t single_core_k = hidden_size;
206+ constexpr uint32_t base_m = 128;
207+ constexpr uint32_t base_n = 192;
208+ constexpr uint32_t base_k = 64;
209+ constexpr uint32_t num_blocks = (batch * sequence_length / single_core_m) * (projection_size / single_core_n);
210+ 
211+ constexpr size_t input_size = batch * sequence_length * hidden_size * sizeof(DataType);
212+ constexpr size_t weight_size = hidden_size * projection_size * sizeof(DataType);
213+ constexpr size_t bias_size = projection_size * sizeof(DataType);
214+ constexpr size_t output_size = batch * sequence_length * projection_size * sizeof(DataType);
215+ 
216+ aclInit(nullptr);
217+ constexpr int32_t device_id = 0;
218+ aclrtSetDevice(device_id);
219+ aclrtStream stream = nullptr;
220+ aclrtCreateStream(&stream);
221+ 
222+ uint8_t* input_host = nullptr;
223+ uint8_t* weight_host = nullptr;
224+ uint8_t* bias_host = nullptr;
225+ uint8_t* output_host = nullptr;
226+ DataType* input_device = nullptr;
227+ DataType* weight_device = nullptr;
228+ DataType* bias_device = nullptr;
229+ DataType* output_device = nullptr;
230+ 
231+ aclrtMallocHost(reinterpret_cast<void**>(&input_host), input_size);
232+ aclrtMallocHost(reinterpret_cast<void**>(&weight_host), weight_size);
233+ aclrtMallocHost(reinterpret_cast<void**>(&bias_host), bias_size);
234+ aclrtMallocHost(reinterpret_cast<void**>(&output_host), output_size);
235+ aclrtMalloc(reinterpret_cast<void**>(&input_device), input_size, ACL_MEM_MALLOC_HUGE_FIRST);
236+ aclrtMalloc(reinterpret_cast<void**>(&weight_device), weight_size, ACL_MEM_MALLOC_HUGE_FIRST);
237+ aclrtMalloc(reinterpret_cast<void**>(&bias_device), bias_size, ACL_MEM_MALLOC_HUGE_FIRST);
238+ aclrtMalloc(reinterpret_cast<void**>(&output_device), output_size, ACL_MEM_MALLOC_HUGE_FIRST);
239+ 
240+ read_file("./input/input.bin", input_size, input_host);
241+ read_file("./input/weight.bin", weight_size, weight_host);
242+ read_file("./input/bias.bin", bias_size, bias_host);
243+ aclrtMemcpy(input_device, input_size, input_host, input_size, ACL_MEMCPY_HOST_TO_DEVICE);
244+ aclrtMemcpy(weight_device, weight_size, weight_host, weight_size, ACL_MEMCPY_HOST_TO_DEVICE);
245+ aclrtMemcpy(bias_device, bias_size, bias_host, bias_size, ACL_MEMCPY_HOST_TO_DEVICE);
246+ 
247+ custom_op_tensor_api<
248+ DataType, batch, sequence_length, hidden_size, projection_size, single_core_m, single_core_n, single_core_k,
249+ base_m, base_n, base_k><<<num_blocks, 0, stream>>>(input_device, weight_device, bias_device, output_device);
250+ aclrtSynchronizeStream(stream);
251+ 
252+ aclrtMemcpy(output_host, output_size, output_device, output_size, ACL_MEMCPY_DEVICE_TO_HOST);
253+ write_file("./output/output.bin", output_host, output_size);
254+ 
255+ aclrtFree(input_device);
256+ aclrtFree(weight_device);
257+ aclrtFree(bias_device);
258+ aclrtFree(output_device);
259+ aclrtFreeHost(input_host);
260+ aclrtFreeHost(weight_host);
261+ aclrtFreeHost(bias_host);
262+ aclrtFreeHost(output_host);
263+ aclrtDestroyStream(stream);
264+ aclrtResetDevice(device_id);
265+ aclFinalize();
266+ return 0;
267+}
@@ -0,0 +1,38 @@
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 CUSTOM_OP_TENSOR_API_DATA_UTILS_H
12+#define CUSTOM_OP_TENSOR_API_DATA_UTILS_H
13+ 
14+#include <cstddef>
15+#include <fstream>
16+#include <string>
17+ 
18+inline bool read_file(const std::string& file_path, size_t size, void* buffer)
19+{
20+ std::ifstream file(file_path, std::ios::binary);
21+ if (!file.is_open()) {
22+ return false;
23+ }
24+ file.read(static_cast<char*>(buffer), static_cast<std::streamsize>(size));
25+ return file.gcount() == static_cast<std::streamsize>(size);
26+}
27+ 
28+inline bool write_file(const std::string& file_path, const void* buffer, size_t size)
29+{
30+ std::ofstream file(file_path, std::ios::binary | std::ios::trunc);
31+ if (!file.is_open()) {
32+ return false;
33+ }
34+ file.write(static_cast<const char*>(buffer), static_cast<std::streamsize>(size));
35+ return file.good();
36+}
37+ 
38+#endif // CUSTOM_OP_TENSOR_API_DATA_UTILS_H
@@ -0,0 +1,42 @@
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 os
15+ 
16+import numpy as np
17+ 
18+ 
19+def generate_data():
20+ batch = 16
21+ sequence_length = 64
22+ hidden_size = 256
23+ projection_size = 3 * hidden_size
24+ 
25+ rng = np.random.default_rng(0)
26+ input_data = rng.uniform(-1.0, 1.0, (batch, sequence_length, hidden_size)).astype(np.float16)
27+ weight = rng.uniform(-1.0, 1.0, (hidden_size, projection_size)).astype(np.float16)
28+ bias = rng.uniform(-1.0, 1.0, (projection_size,)).astype(np.float16)
29+ 
30+ flattened_input = input_data.reshape(batch * sequence_length, hidden_size).astype(np.float32)
31+ golden = flattened_input @ weight.astype(np.float32) + bias.astype(np.float32)
32+ 
33+ os.makedirs("input", exist_ok=True)
34+ os.makedirs("output", exist_ok=True)
35+ input_data.tofile("input/input.bin")
36+ weight.tofile("input/weight.bin")
37+ bias.tofile("input/bias.bin")
38+ golden.astype(np.float16).tofile("output/golden.bin")
39+ 
40+ 
41+if __name__ == "__main__":
42+ generate_data()
@@ -0,0 +1,39 @@
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 sys
15+ 
16+import numpy as np
17+ 
18+ 
19+def verify_result(output_path, golden_path):
20+ output = np.fromfile(output_path, dtype=np.float16)
21+ golden = np.fromfile(golden_path, dtype=np.float16)
22+ if output.size != golden.size:
23+ print(f"result size mismatch: expected {golden.size}, actual {output.size}")
24+ return False
25+ 
26+ close_mask = np.isclose(output, golden, rtol=1e-3, atol=1e-3, equal_nan=True)
27+ error_indexes = np.flatnonzero(~close_mask)
28+ for index in error_indexes[:10]:
29+ print(f"data index: {index:06d}, expected: {golden[index]:.6f}, actual: {output[index]:.6f}")
30+ 
31+ error_ratio = error_indexes.size / golden.size
32+ print(f"error ratio: {error_ratio:.6f}")
33+ return error_ratio <= 1e-3
34+ 
35+ 
36+if __name__ == "__main__":
37+ if len(sys.argv) != 3 or not verify_result(sys.argv[1], sys.argv[2]):
38+ sys.exit(1)
39+ print("test pass!")