Merged
add data_copy example #2124
li-yuanjie-daAdd on May 12
add data_copy example #2124
Merged
li-yuanjie-daAdd on May 12
Total: 11 files changed+923-4
@@ -1,13 +1,15 @@
1# Matrix Compute API样例介绍1# Matrix Compute API样例介绍
2## 概述2## 概述
3本样例集介绍了矩阵计算API不同特性的典型用法,给出了对应的端到端实现。目录下的样例命名按照"API名称_通路",如下:3本样例集介绍了矩阵计算API不同特性的典型用法,给出了对应的端到端实现。目录下的样例命名按照"API名称_通路",如下:
4-1. **load_data_**:以"load_data_"开头的样例介绍L1 Buffer -> L0 Buffer的相关API;4+1. **data_copy**:以"data_copy"开头的样例介绍Global Memory -> L1 Buffer的相关API;
5-2. **mmad_**:以"mmad_"开头的样例介绍矩阵乘法Mmad API;5+2. **load_data**:以"load_data"开头的样例介绍L1 Buffer -> L0 Buffer的相关API;
6-3. **fixpipe_**:以"fixpipe_"开头的样例介绍L0C Buffer → GM/L1 Buffer/UB的相关API;6+3. **mmad**:以"mmad"开头的样例介绍矩阵乘法Mmad API;
7+4. **fixpipe**:以"fixpipe"开头的样例介绍L0C Buffer → Global Memory/L1 Buffer/Unified Buffer的相关API;
7 8 
8## 样例列表9## 样例列表
9| 目录名称 | 功能描述 |10| 目录名称 | 功能描述 |
10|--------------------------------------------------------------------------------------------| ---------------------------------------------------- |11|--------------------------------------------------------------------------------------------| ---------------------------------------------------- |
12+| [data_copy_gm2l1](./data_copy_gm2l1) | 本样例介绍如何使用DataCopy将输入数据从GM(Global Memory)搬出到L1(L1 Buffer) |
11| [fixpipe_l0c2gm](./fixpipe_l0c2gm) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从CO1(L0C Buffer)搬出到GM(Global Memory) |13| [fixpipe_l0c2gm](./fixpipe_l0c2gm) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从CO1(L0C Buffer)搬出到GM(Global Memory) |
12| [fixpipe_l0c2ub](./fixpipe_l0c2ub) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从CO1(L0C Buffer)搬出到UB(Unified Buffer) |14| [fixpipe_l0c2ub](./fixpipe_l0c2ub) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从CO1(L0C Buffer)搬出到UB(Unified Buffer) |
13| [fixpipe_l0c2l1](./fixpipe_l0c2l1) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从CO1(L0C Buffer)搬出到L1(L1 Buffer) |15| [fixpipe_l0c2l1](./fixpipe_l0c2l1) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从CO1(L0C Buffer)搬出到L1(L1 Buffer) |
@@ -0,0 +1,41 @@
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_ARCHITECTURES "dav-2201" CACHE STRING "NPU architecture: dav-2201, dav-3510")
14+ 
15+find_package(ASC REQUIRED)
16+ 
17+project(kernel_samples LANGUAGES ASC CXX)
18+ 
19+add_executable(demo
20+ data_copy_gm2l1.asc
21+)
22+ 
23+target_link_libraries(demo PRIVATE)
24+ 
25+# 场景参数(通过命令行传入)
26+# SCENARIO_NUM: 场景编号
27+# 1 - 输入格式NZ,输入数据类型half
28+# 2 - 输入格式ND,输入数据类型half
29+# 3 - 输入格式DN,输入数据类型half
30+# 4 - 输入格式ND,输入数据类型half,使能bias
31+# 5 - 输入格式ND,输入数据类型half,使能Vector量化
32+set(SCENARIO_NUM "1" CACHE STRING "Scene number (1-5)")
33+if(SCENARIO_NUM EQUAL 3 AND CMAKE_ASC_ARCHITECTURES STREQUAL "dav-2201")
34+ message(FATAL_ERROR "When SCENARIO_NUM=3, only CMAKE_ASC_ARCHITECTURES=dav-3510 is supported.")
35+endif()
36+ 
37+add_definitions(-DSCENARIO_NUM=${SCENARIO_NUM})
38+ 
39+target_compile_options(demo PRIVATE
40+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>
41+)
@@ -0,0 +1,129 @@
1+# data_copy_gm2l1样例
2+ 
3+## 概述
4+ 
5+本样例介绍如何使用DataCopy将输入数据从GM(Global Memory)搬出到L1(L1 Buffer),支持多种输入格式(Nz、ND、DN)、Bias矩阵搬入、量化矩阵搬入等功能。
6+ 
7+## 支持的产品
8+ 
9+- Ascend 950PR/Ascend 950DT
10+- Atlas A3 训练系列产品/Atlas A3 推理系列产品
11+- Atlas A2 训练系列产品/Atlas A2 推理系列产品
12+ 
13+## 目录结构介绍
14+ 
15+```
16+├── data_copy_gm2l1
17+│ ├── figures // 图示
18+│ ├── scripts
19+│ │ ├── gen_data.py // 输入数据和真值数据生成脚本
20+│ │ └── verify_result.py // 验证输出数据和真值数据是否一致的验证脚本
21+│ ├── data_utils.h // 数据读入写出函数
22+│ └── data_copy_gm2l1.asc // Ascend C样例实现 & 调用样例
23+```
24+ 
25+## 场景详细说明
26+ 
27+本样例通过编译参数 `SCENARIO_NUM` 选择不同的输入场景, SCENARIO_NUM不同取值对应的含义如下表所示。所有场景基于相同的矩阵乘规格:[M, K, N] = [128, 128, 256],核函数名为 `data_copy_gm2l1`。
28+ 
29+<table>
30+<caption style="font-weight: normal;">
31+ <span style="font-weight: bold; font-size: 1.2em;">📌 表1:scenarioNum不同取值的含义</span></caption>
32+<tr><td rowspan="1" align="center">scenarioNum</td><td align="center">输入格式</td><td align="center">输入数据类型</td><td align="center">输出数据类型</td><td align="center">是否使能Bias</td><td align="center">是否使能Vector量化</td></tr>
33+<tr><td align="center">1</td><td align="center">Nz</td><td align="center">half</td><td align="center">float</td><td align="center">否</td><td align="center">否</td></tr>
34+<tr><td align="center">2</td><td align="center">ND</td><td align="center">half</td><td align="center">float</td><td align="center">否</td><td align="center">否</td></tr>
35+<tr><td align="center">3</td><td align="center">DN</td><td align="center">half</td><td align="center">float</td><td align="center">否</td><td align="center">否</td></tr>
36+<tr><td align="center">4</td><td align="center">ND</td><td align="center">half</td><td align="center">float</td><td align="center">是</td><td align="center">否</td></tr>
37+<tr><td align="center">5</td><td align="center">ND</td><td align="center">half</td><td align="center">int8_t</td><td align="center">否</td><td align="center">是</td></tr>
38+</table>
39+ 
40+**场景1:输入格式Nz,输入数据类型half**
41+- 输入:A [128, 128] half类型,Nz格式;B [128, 256] half类型,Nz格式
42+- 输出:C [128, 256] float类型,ND格式
43+- 实现:使用 `DataCopyParams` 将NZ格式的输入数据从GM搬运到L1
44+- 说明:输入数据为Nz格式,直接搬运到L1,无需格式转换
45+<p align="center">
46+ <img src="figures/data_copy_gm2l1_NZ2NZ.png" width="800">
47+</p>
48+ 
49+**场景2:输入格式ND,输入数据类型half**
50+- 输入:A [128, 128] half类型,ND格式;B [128, 256] half类型,ND格式
51+- 输出:C [128, 256] float类型,ND格式
52+- 实现:使用 `Nd2NzParams` 将ND格式的输入数据从GM搬运到L1,自动转换为Nz格式
53+- 说明:输入数据为ND格式,在搬运过程中自动转换为Nz格式
54+<p align="center">
55+ <img src="figures/data_copy_gm2l1_ND2NZ.png" width="800">
56+</p>
57+ 
58+**场景3:输入格式DN,输入数据类型half(仅Ascend 950PR/Ascend 950DT支持)**
59+- 输入:A [128, 128] half类型,DN格式;B [128, 256] half类型,DN格式
60+- 输出:C [128, 256] float类型,ND格式
61+- 实现:使用 `Dn2NzParams` 将DN格式的输入数据从GM搬运到L1,自动转换为Nz格式
62+- 说明:输入数据为DN格式,在搬运过程中自动转换为Nz格式,DN格式仅Ascend 950PR/Ascend 950DT支持
63+<p align="center">
64+ <img src="figures/data_copy_gm2l1_DN2NZ.png" width="800">
65+</p>
66+ 
67+**场景4:输入格式ND,输入数据类型half,使能Bias**
68+- 输入:A [128, 128] half类型,ND格式;B [128, 256] half类型,ND格式;Bias [256] float类型
69+- 输出:C [128, 256] float类型,ND格式
70+- 实现:使用 `Nd2NzParams` 将输入数据和Bias从GM搬运到L1,执行矩阵乘计算时通过 `Mmad(c, a, b, bias, mmadParams)` 加入Bias
71+- 说明:在矩阵乘计算过程中加入Bias,Bias通过C1搬运到C2,然后参与矩阵乘计算
72+ 
73+**场景5:输入格式ND,输入数据类型half,使能Vector量化**
74+- 输入:A [128, 128] half类型,ND格式;B [128, 256] half类型,ND格式;量化参数 [256] uint64_t类型
75+- 输出:C [128, 256] int8_t类型,ND格式
76+- 实现:使用 `Nd2NzParams` 将输入数据从GM搬运到L1,执行矩阵乘计算,量化参数通过 `DataCopy` 从GM搬运到L1,然后使用 `Fixpipe<outputType, l0cType, AscendC::CFG_ROW_MAJOR>(cGM, c, quantAlphaTensor, fixpipeParams)` 进行Vector量化输出
77+- 说明:矩阵乘计算结果为float类型,通过Vector量化转换为int8_t类型,C矩阵的每一列对应一个量化参数
78+ 
79+## 编译运行
80+ 
81+在本样例根目录下执行如下步骤,编译并执行样例。
82+- 配置环境变量
83+ 请根据当前环境上CANN开发套件包的[安装方式](../../../../../../docs/quick_start.md#prepare&install),选择对应配置环境变量的命令。
84+ - 默认路径,root用户安装CANN软件包
85+ ```bash
86+ source /usr/local/Ascend/cann/set_env.sh
87+ ```
88+ 
89+ - 默认路径,非root用户安装CANN软件包
90+ ```bash
91+ source $HOME/Ascend/cann/set_env.sh
92+ ```
93+ 
94+ - 指定路径install_path,安装CANN软件包
95+ ```bash
96+ source ${install_path}/cann/set_env.sh
97+ ```
98+ 
99+- 样例执行
100+ ```bash
101+ SCENARIO_NUM=1
102+ mkdir -p build && cd build; # 创建并进入build目录
103+ cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_ARCHITECTURES=dav-2201 ..;make -j; # 编译工程,默认npu模式
104+ python3 ../scripts/gen_data.py -scenarioNum=$SCENARIO_NUM # 生成测试输入数据
105+ ./demo # 执行编译生成的可执行程序,执行样例
106+ python3 ../scripts/verify_result.py output/output.bin ./output/golden.bin # 验证输出结果是否正确
107+ ```
108+ 
109+ 使用 CPU调试 或 NPU仿真 模式时,添加 `-DCMAKE_ASC_RUN_MODE=cpu` 或 `-DCMAKE_ASC_RUN_MODE=sim` 参数即可。
110+
111+ 示例如下:
112+ ```bash
113+ cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=cpu -DCMAKE_ASC_ARCHITECTURES=dav-2201 ..;make -j; # CPU调试模式
114+ cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-2201 ..;make -j; # NPU仿真模式
115+ ```
116+ 
117+ > **注意:** 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
118+ 
119+- 编译选项说明
120+ | 选项 | 可选值 | 说明 |
121+ |------|--------|------|
122+ | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`cpu`、`sim` | 运行模式:NPU 运行、CPU调试、NPU仿真 |
123+ | `CMAKE_ASC_ARCHITECTURES` | `dav-2201`(默认)、`dav-3510` | NPU 架构:dav-2201 对应 Atlas A2 训练系列产品/Atlas A2 推理系列产品和Atlas A3 训练系列产品/Atlas A3 推理系列产品,dav-3510 对应 Ascend 950PR/Ascend 950DT |
124+ | `SCENARIO_NUM` | 1-5 | 场景编号,场景3仅支持dav-3510架构 |
125+ 
126+ 执行结果如下,说明精度对比成功。
127+ ```bash
128+ test pass!
129+ ```
@@ -0,0 +1,434 @@
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 data_copy_gm2l1.asc
13+ * \brief 本样例介绍如何使用DataCopy将输入数据从GM(Global Memory)搬出到L1(L1 Buffer)
14+ */
15+ 
16+#include "acl/acl.h"
17+#include "kernel_operator.h"
18+#include "data_utils.h"
19+ 
20+#ifdef ASCENDC_CPU_DEBUG
21+#include "cpu_debug_launch.h"
hw-zjy
hw-zjyhw-zjyMay 15

不支持cpu模式的话,这个头文件可以去掉

likedislike
li-yuanjie-da
li-yuanjie-da
May 18 Comments:
likedislike
22+#endif
23+ 
24+// half type, cube block: [16, 16]
25+constexpr uint32_t CUBE_BLOCK = 16;
26+constexpr uint32_t C0_SIZE = 32;
27+constexpr uint32_t CUBE_BLOCK_SIZE = 16 * 16;
28+ 
29+constexpr static uint16_t LIMIT_MNSIZE = 10;
30+constexpr static uint16_t ALIGN_NUM = 16;
31+ 
32+template <class inputType, class outputType, class l0cType, uint32_t baseM, uint32_t baseK, uint32_t baseN>
33+class KernelDataCopy {
34+public:
35+ __aicore__ inline KernelDataCopy()
36+ {
37+ AscendC::InitSocState();
38+ aSingleSize = baseM * baseK;
39+ bSingleSize = baseK * baseN;
40+ cSingleSize = baseM * baseN;
41+ 
42+ // A 不转置
43+ aSizeAlignL1 = CeilAlign(baseM, CUBE_BLOCK) * CeilAlign(baseK, C0_SIZE);
44+ aSizeAlignL0 = CeilAlign(baseM, CUBE_BLOCK) * CeilAlign(baseK, C0_SIZE);
45+ // B 不转置
46+ bSizeAlignL1 = CeilAlign(baseK, C0_SIZE) * CeilAlign(baseN, C0_SIZE);
47+ bSizeAlignL0 = CeilAlign(baseK, C0_SIZE) * CeilAlign(baseN, C0_SIZE);
48+ // C矩阵无视数据类型和a、b是否转置,m,n都向16对齐
49+ cSizeAlignL0 = CeilAlign(baseM, CUBE_BLOCK) * CeilAlign(baseN, CUBE_BLOCK);
50+#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510)
51+ // 对于Ascend 950PR/Ascend 950DT,C1->C2,要求待搬运数据的连续传输数据块长度(blockLen)的单位是32B,且数据类型为b32时值需为偶数
52+ biasSizeAlign = CeilAlign(CeilDivision(baseN * sizeof(outputType), 32), 2) * 32;
53+#else
54+ // Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品,C1->C2,要求blockLen的单位是64B
55+ biasSizeAlign = CeilAlign(baseN * sizeof(outputType), 64);
56+#endif
57+ }
58+ 
59+ __aicore__ inline void Init(GM_ADDR a, GM_ADDR b, GM_ADDR c, GM_ADDR bias, GM_ADDR quantAlpha)
60+ {
61+ aGM.SetGlobalBuffer((__gm__ inputType *)a);
62+ bGM.SetGlobalBuffer((__gm__ inputType *)b);
63+ cGM.SetGlobalBuffer((__gm__ outputType *)c);
64+ biasGM.SetGlobalBuffer((__gm__ outputType *)bias);
65+ quantAlphaGM.SetGlobalBuffer((__gm__ uint64_t *)quantAlpha);
66+ }
67+ 
68+ __aicore__ inline void Process()
69+ {
70+ AscendC::LocalTensor<inputType> a1Local(AscendC::TPosition::A1, a1Addr, aSizeAlignL1);
71+ AscendC::LocalTensor<inputType> a2Local(AscendC::TPosition::A2, a2Addr, aSizeAlignL0);
72+ AscendC::LocalTensor<inputType> b1Local(AscendC::TPosition::B1, b1Addr, bSizeAlignL1);
73+ AscendC::LocalTensor<inputType> b2Local(AscendC::TPosition::B2, b2Addr, bSizeAlignL0);
74+ AscendC::LocalTensor<outputType> bias1Local(AscendC::TPosition::C1, c1Addr, biasSizeAlign);
75+ AscendC::LocalTensor<outputType> bias2Local(AscendC::TPosition::C2, c2Addr, biasSizeAlign);
76+ AscendC::LocalTensor<l0cType> c(AscendC::TPosition::CO1, co1Addr, cSizeAlignL0);
77+ AscendC::LocalTensor<uint64_t> quantAlphaTensor(AscendC::TPosition::C1, c1Addr, baseN);
78+ 
79+ if constexpr (SCENARIO_NUM == 1) {
80+ CopyInNz2Nz(a1Local, b1Local);
81+ } else if constexpr (SCENARIO_NUM == 3) {
82+ CopyInDn2Nz(a1Local, b1Local);
83+ } else {
84+ CopyInNd2Nz(a1Local, b1Local);
85+ }
86+ if constexpr (SCENARIO_NUM == 4) {
87+ CopyInBias(bias1Local);
88+ }
89+ AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE1>(EVENT_ID0);
90+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_MTE1>(EVENT_ID0);
91+ SplitA(a1Local, a2Local);
92+ SplitB(b1Local, b2Local);
93+ if constexpr (SCENARIO_NUM == 4) {
94+ SplitBias(bias1Local, bias2Local);
95+ }
96+ AscendC::SetFlag<AscendC::HardEvent::MTE1_M>(EVENT_ID0);
97+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_M>(EVENT_ID0);
98+ Compute(c, a2Local, b2Local, bias2Local);
99+ 
100+ // vector quant mode
101+ if constexpr (SCENARIO_NUM == 5) {
102+ CopyQuantAlphaGmToL1(quantAlphaTensor);
103+ }
104+ 
105+ AscendC::SetFlag<AscendC::HardEvent::M_FIX>(EVENT_ID0);
106+ AscendC::WaitFlag<AscendC::HardEvent::M_FIX>(EVENT_ID0);
107+ CopyOut(c, quantAlphaTensor);
108+ }
109+ 
110+private:
111+ __aicore__ inline uint16_t CeilDivision(uint16_t numerator, uint16_t denominator)
112+ {
113+ return (numerator + denominator - 1) / denominator;
114+ }
115+ 
116+ __aicore__ inline uint16_t CeilAlign(uint16_t numerator, uint16_t denominator)
117+ {
118+ return (numerator + denominator - 1) / denominator * denominator;
119+ }
120+ 
121+ __aicore__ inline void CopyQuantAlphaGmToL1(AscendC::LocalTensor<uint64_t> quantAlphaTensor)
122+ {
123+ AscendC::SetFlag<AscendC::HardEvent::FIX_MTE2>(EVENT_ID0);
124+ AscendC::WaitFlag<AscendC::HardEvent::FIX_MTE2>(EVENT_ID0);
125+ uint16_t burstLen = CeilAlign(baseN * sizeof(uint64_t), 128) / 32;
126+ AscendC::DataCopyParams intriParams{ 1, burstLen, 0, 0 };
127+ AscendC::DataCopy(quantAlphaTensor, quantAlphaGM, intriParams);
128+ AscendC::SetFlag<AscendC::HardEvent::MTE2_FIX>(EVENT_ID0);
129+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_FIX>(EVENT_ID0);
130+ }
131+ 
132+ __aicore__ inline void CopyInNd2Nz(AscendC::LocalTensor<inputType> a1Local, AscendC::LocalTensor<inputType> b1Local)
133+ {
134+ AscendC::Nd2NzParams nd2nzA1Params;
135+ // 传输ND矩阵的数目
136+ nd2nzA1Params.ndNum = 1;
137+ nd2nzA1Params.nValue = baseM;
138+ nd2nzA1Params.dValue = baseK;
139+ // 源操作数相邻ND矩阵起始地址间的偏移,单位为元素。
140+ nd2nzA1Params.srcNdMatrixStride = 0;
141+ nd2nzA1Params.srcDValue = baseK;
142+ // 目的Nz矩阵中,来自源操作数同一行的多行数据相邻行起始地址间的偏移,取值范围:dstNzC0Stride∈[1, 16384],单位:C0_SIZE(32B)。
143+ nd2nzA1Params.dstNzC0Stride = CeilAlign(baseM, CUBE_BLOCK);
144+ // 目的Nz矩阵中,Z型矩阵相邻行起始地址之间的偏移。单位:C0_SIZE(32B)。
145+ nd2nzA1Params.dstNzNStride = 1;
146+ // 目的Nz矩阵中,相邻Nz矩阵起始地址间的偏移,单位为元素。
147+ nd2nzA1Params.dstNzMatrixStride = 0;
148+ AscendC::DataCopy(a1Local, aGM, nd2nzA1Params);
149+ 
150+ AscendC::Nd2NzParams nd2nzB1Params;
151+ nd2nzB1Params.ndNum = 1;
152+ nd2nzB1Params.nValue = baseK;
153+ nd2nzB1Params.dValue = baseN;
154+ nd2nzB1Params.srcNdMatrixStride = 0;
155+ nd2nzB1Params.srcDValue = baseN;
156+ nd2nzB1Params.dstNzC0Stride = CeilAlign(baseK, CUBE_BLOCK);
157+ nd2nzB1Params.dstNzNStride = 1;
158+ nd2nzB1Params.dstNzMatrixStride = 0;
159+ AscendC::DataCopy(b1Local, bGM, nd2nzB1Params);
160+ }
161+ 
162+ __aicore__ inline void CopyInNz2Nz(AscendC::LocalTensor<inputType> a1Local, AscendC::LocalTensor<inputType> b1Local)
163+ {
164+ AscendC::DataCopyParams repeatA1Params;
165+ repeatA1Params.blockCount = 1;
166+ repeatA1Params.blockLen = aSingleSize * sizeof(inputType) / AscendC::ONE_BLK_SIZE;
167+ AscendC::DataCopy(a1Local, aGM, repeatA1Params);
168+ 
169+ AscendC::DataCopyParams repeatB1Params;
170+ repeatB1Params.blockCount = 1;
171+ repeatB1Params.blockLen = bSingleSize * sizeof(inputType) / AscendC::ONE_BLK_SIZE;
172+ AscendC::DataCopy(b1Local, bGM, repeatB1Params);
173+ }
174+ 
175+ __aicore__ inline void CopyInDn2Nz(AscendC::LocalTensor<inputType> a1Local, AscendC::LocalTensor<inputType> b1Local)
176+ {
177+#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 2201)
178+ assert(false && "Only dav-3510 support DN!");
179+#elif defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510)
180+ AscendC::Dn2NzParams dn2nzA1Params;
181+ // 传输DN矩阵的数目
182+ dn2nzA1Params.dnNum = 1;
183+ dn2nzA1Params.nValue = baseM;
184+ dn2nzA1Params.dValue = baseK;
185+ // 源操作数相邻DN矩阵起始地址间的偏移,单位为元素。
186+ dn2nzA1Params.srcDnMatrixStride = 0;
187+ dn2nzA1Params.srcDValue = baseM;
188+ // 目的Nz矩阵中,来自源操作数同一列的多行数据相邻行起始地址间的偏移,取值范围:dstNzC0Stride∈[1, 16384],单位:C0_SIZE(32B)。
189+ dn2nzA1Params.dstNzC0Stride = CeilAlign(baseM, CUBE_BLOCK);
190+ // 目的Nz矩阵中,Z型矩阵相邻行起始地址之间的偏移。单位:C0_SIZE(32B)。
191+ dn2nzA1Params.dstNzNStride = 1;
192+ // 目的Nz矩阵中,相邻Nz矩阵起始地址间的偏移,单位为元素。
193+ dn2nzA1Params.dstNzMatrixStride = 0;
194+ AscendC::DataCopy(a1Local, aGM, dn2nzA1Params);
195+ 
196+ AscendC::Dn2NzParams dn2nzB1Params;
197+ dn2nzB1Params.dnNum = 1;
198+ dn2nzB1Params.nValue = baseK;
199+ dn2nzB1Params.dValue = baseN;
200+ dn2nzB1Params.srcDnMatrixStride = 0;
201+ dn2nzB1Params.srcDValue = baseK;
202+ dn2nzB1Params.dstNzC0Stride = CeilAlign(baseK, CUBE_BLOCK);
203+ dn2nzB1Params.dstNzNStride = 1;
204+ dn2nzB1Params.dstNzMatrixStride = 0;
205+ AscendC::DataCopy(b1Local, bGM, dn2nzB1Params);
206+#endif
207+ }
208+ 
209+ __aicore__ inline void CopyInBias(AscendC::LocalTensor<outputType> bias1Local)
210+ {
211+ // 由于N可能非32B对齐,“基础数据搬运”无法处理非对齐数据,且“DataCopyPad”不支持GM到L1的搬运,
212+ // 因此,使用“随路转换ND2Nz搬运”实现Bias的GM到L1搬运,确保搬运到L1数据32B对齐。
213+ AscendC::Nd2NzParams nd2nzC1Params = {1, 1, baseN, 0, baseN, 1, 1, 0};
214+ AscendC::DataCopy(bias1Local, biasGM, nd2nzC1Params);
215+ }
216+ 
217+ __aicore__ inline void SplitA(AscendC::LocalTensor<inputType> a1Local, AscendC::LocalTensor<inputType> a2Local)
218+ {
219+#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 2201)
220+ uint32_t dstOffset = CeilDivision(baseK, CUBE_BLOCK) * CUBE_BLOCK_SIZE;
221+ uint32_t srcOffset = CUBE_BLOCK_SIZE;
222+ // Nz -> Zz
223+ AscendC::LoadData2DParams loadDataParams;
224+ loadDataParams.repeatTimes = CeilDivision(baseK, CUBE_BLOCK);
225+ loadDataParams.srcStride = CeilDivision(baseM, CUBE_BLOCK);
226+ loadDataParams.dstGap = 0;
227+ loadDataParams.ifTranspose = false;
228+ for (int i = 0; i < CeilDivision(baseM, CUBE_BLOCK); ++i) {
229+ AscendC::LoadData(a2Local[i * dstOffset], a1Local[i * srcOffset], loadDataParams);
230+ }
231+#elif defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510)
232+ AscendC::LoadData2DParamsV2 loadDataParams;
233+ loadDataParams.mStep = CeilDivision(baseM, CUBE_BLOCK);
234+ loadDataParams.kStep = CeilDivision(baseK, C0_SIZE / sizeof(inputType));
235+ loadDataParams.srcStride = CeilDivision(baseM, CUBE_BLOCK);
236+ loadDataParams.dstStride = CeilDivision(baseM, CUBE_BLOCK);
237+ AscendC::LoadData(a2Local, a1Local, loadDataParams);
238+#endif
239+ }
240+ 
241+ __aicore__ inline void SplitB(AscendC::LocalTensor<inputType> b1Local, AscendC::LocalTensor<inputType> b2Local)
242+ {
243+ uint32_t dstOffset = CeilDivision(baseN, CUBE_BLOCK) * CUBE_BLOCK_SIZE;
244+ uint32_t srcOffset = CUBE_BLOCK_SIZE;
245+ // Nz -> Zn
246+ AscendC::LoadData2DParams loadDataParams;
247+ loadDataParams.startIndex = 0;
248+ loadDataParams.repeatTimes = CeilDivision(baseN, CUBE_BLOCK);
249+ loadDataParams.srcStride = CeilDivision(baseK, CUBE_BLOCK);
250+ loadDataParams.dstGap = 0;
251+ loadDataParams.ifTranspose = true;
252+ for (int i = 0; i < CeilDivision(baseK, CUBE_BLOCK); ++i) {
253+ AscendC::LoadData(b2Local[i * dstOffset], b1Local[i * srcOffset], loadDataParams);
254+ }
255+ }
256+ 
257+ __aicore__ inline void SplitBias(AscendC::LocalTensor<outputType> bias1Local, AscendC::LocalTensor<outputType> bias2Local)
258+ {
259+#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510)
260+ AscendC::DataCopyParams c12c2Params = {1, static_cast<uint16_t>(biasSizeAlign / 32), 0, 0};
261+#else
262+ AscendC::DataCopyParams c12c2Params = {1, static_cast<uint16_t>(biasSizeAlign / 64), 0, 0};
263+#endif
264+ AscendC::DataCopy(bias2Local, bias1Local, c12c2Params);
265+ }
266+ 
267+ __aicore__ inline void Compute(AscendC::LocalTensor<l0cType> c, AscendC::LocalTensor<inputType> a, AscendC::LocalTensor<inputType> b, AscendC::LocalTensor<outputType> bias)
268+ {
269+ AscendC::MmadParams mmadParams;
270+ mmadParams.m = baseM;
271+ mmadParams.n = CeilAlign(baseN, C0_SIZE);
272+ mmadParams.k = baseK;
273+ if constexpr (SCENARIO_NUM == 4) {
274+ // 带Bias且传入biasTensor的场景,该场景下cmatrixSource参数无效
275+ mmadParams.cmatrixInitVal = false;
276+ AscendC::Mmad(c, a, b, bias, mmadParams);
277+ } else {
278+ AscendC::Mmad(c, a, b, mmadParams);
279+ }
280+ 
281+ if ((baseM / ALIGN_NUM) * (baseN / ALIGN_NUM) < LIMIT_MNSIZE) {
282+ AscendC::PipeBarrier<PIPE_M>();
283+ }
284+ }
285+ 
286+ __aicore__ inline void CopyOut(AscendC::LocalTensor<l0cType>& c, AscendC::LocalTensor<uint64_t>& quantAlphaTensor)
287+ {
288+#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 2201)
289+ AscendC::FixpipeParamsV220 fixpipeParams;
290+ fixpipeParams.ndNum = 1;
291+ fixpipeParams.srcNdStride = 0;
292+ fixpipeParams.dstNdStride = 0;
293+#elif defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510)
294+ AscendC::FixpipeParamsArch3510<AscendC::CO2Layout::ROW_MAJOR> fixpipeParams;
295+#endif
296+ fixpipeParams.mSize = baseM;
297+ fixpipeParams.srcStride = CeilAlign(baseM, CUBE_BLOCK);
298+ // Original nSize
299+ fixpipeParams.nSize = baseN;
300+ fixpipeParams.dstStride = baseN;
301+ if constexpr (SCENARIO_NUM == 5) {
302+ // vector quant
303+ fixpipeParams.quantPre = QuantMode_t::VQF322B8_PRE;
304+ AscendC::Fixpipe<outputType, l0cType, AscendC::CFG_ROW_MAJOR>(cGM, c, quantAlphaTensor, fixpipeParams);
305+ } else {
306+ AscendC::Fixpipe<outputType, l0cType, AscendC::CFG_ROW_MAJOR>(cGM, c, fixpipeParams);
307+ }
308+ }
309+ 
310+private:
311+ static constexpr uint32_t a1Addr = 0;
312+ static constexpr uint32_t a2Addr = 0;
313+ static constexpr uint32_t b1Addr = 64 * 1024;
314+ static constexpr uint32_t b2Addr = 0;
315+ static constexpr uint32_t co1Addr = 0;
316+ // Vector quant参数 需要从GM拷贝到L1
317+ static constexpr uint32_t c1Addr = 128 * 1024;
318+ static constexpr uint32_t c2Addr = 0;
319+ 
320+ AscendC::GlobalTensor<inputType> aGM;
321+ AscendC::GlobalTensor<inputType> bGM;
322+ AscendC::GlobalTensor<outputType> cGM;
323+ AscendC::GlobalTensor<outputType> biasGM;
324+ AscendC::GlobalTensor<uint64_t> quantAlphaGM;
325+ 
326+ uint32_t aSingleSize, bSingleSize, cSingleSize;
327+ uint32_t aSizeAlignL1, bSizeAlignL1;
328+ uint32_t aSizeAlignL0, bSizeAlignL0, cSizeAlignL0;
329+ uint32_t biasSizeAlign;
330+};
331+ 
332+template <uint32_t M, uint32_t K, uint32_t N>
333+__global__ __cube__ void data_copy_gm2l1(GM_ADDR a, GM_ADDR b, GM_ADDR c, GM_ADDR bias, GM_ADDR quantAlpha)
334+{
335+ if constexpr (SCENARIO_NUM == 5) {
336+ KernelDataCopy<half, int8_t, float, M, K, N> op;
337+ op.Init(a, b, c, bias, quantAlpha);
338+ op.Process();
339+ } else {
340+ KernelDataCopy<half, float, float, M, K, N> op;
341+ op.Init(a, b, c, bias, quantAlpha);
342+ op.Process();
343+ }
344+ AscendC::PipeBarrier<PIPE_ALL>();
345+}
346+ 
347+int32_t main(int32_t argc, char *argv[])
348+{
349+ // A No Trans, B No Trans
350+ constexpr uint32_t M = 128;
351+ constexpr uint32_t K = 128;
352+ constexpr uint32_t N = 256;
353+ size_t aFileSize = M * K * sizeof(half);
354+ size_t bFileSize = K * N * sizeof(half);
355+ size_t cFileSize, biasFileSize;
356+ if constexpr (SCENARIO_NUM == 5) {
357+ cFileSize = M * N * sizeof(int8_t);
358+ } else {
359+ cFileSize = M * N * sizeof(float);
360+ biasFileSize = N * sizeof(float);
361+ }
362+ size_t quantAlphaSize = 1 * N * sizeof(uint64_t);
363+ uint32_t numBlocks = 1;
364+ 
365+ aclInit(nullptr);
366+ int32_t deviceId = 0;
367+ aclrtSetDevice(deviceId);
368+ aclrtStream stream = nullptr;
369+ aclrtCreateStream(&stream);
370+ 
371+ uint8_t *aHost;
372+ uint8_t *aDevice;
373+ aclrtMallocHost((void **)(&aHost), aFileSize);
374+ aclrtMalloc((void **)&aDevice, aFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
375+ ReadFile("./input/x1_gm.bin", aFileSize, aHost, aFileSize);
376+ aclrtMemcpy(aDevice, aFileSize, aHost, aFileSize, ACL_MEMCPY_HOST_TO_DEVICE);
377+ 
378+ uint8_t *bHost;
379+ uint8_t *bDevice;
380+ aclrtMallocHost((void **)(&bHost), bFileSize);
381+ aclrtMalloc((void **)&bDevice, bFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
382+ ReadFile("./input/x2_gm.bin", bFileSize, bHost, bFileSize);
383+ aclrtMemcpy(bDevice, bFileSize, bHost, bFileSize, ACL_MEMCPY_HOST_TO_DEVICE);
384+ 
385+ uint8_t *cHost;
386+ uint8_t *cDevice;
387+ aclrtMallocHost((void **)(&cHost), cFileSize);
388+ aclrtMalloc((void **)&cDevice, cFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
389+ 
390+ uint8_t *quantAlphaHost;
391+ uint8_t *quantAlphaDevice;
392+ // vector quant mode
393+ if constexpr (SCENARIO_NUM == 5) {
394+ aclrtMallocHost((void **)(&quantAlphaHost), quantAlphaSize);
395+ aclrtMalloc((void **)&quantAlphaDevice, quantAlphaSize, ACL_MEM_MALLOC_HUGE_FIRST);
396+ ReadFile("./input/quant_pre.bin", quantAlphaSize, quantAlphaHost, quantAlphaSize);
397+ aclrtMemcpy(quantAlphaDevice, quantAlphaSize, quantAlphaHost, quantAlphaSize, ACL_MEMCPY_HOST_TO_DEVICE);
398+ }
399+ 
400+ uint8_t *biasHost;
401+ uint8_t *biasDevice;
402+ if constexpr (SCENARIO_NUM == 4) {
403+ aclrtMallocHost((void **)(&biasHost), biasFileSize);
404+ aclrtMalloc((void **)&biasDevice, biasFileSize, ACL_MEM_MALLOC_HUGE_FIRST);
405+ ReadFile("./input/bias_gm.bin", biasFileSize, biasHost, biasFileSize);
406+ aclrtMemcpy(biasDevice, biasFileSize, biasHost, biasFileSize, ACL_MEMCPY_HOST_TO_DEVICE);
407+ }
408+ 
409+ data_copy_gm2l1<M, K, N><<<numBlocks, nullptr, stream>>>(aDevice, bDevice, cDevice, biasDevice, quantAlphaDevice);
410+ aclrtSynchronizeStream(stream);
411+ 
412+ aclrtMemcpy(cHost, cFileSize, cDevice, cFileSize, ACL_MEMCPY_DEVICE_TO_HOST);
413+ WriteFile("./output/output.bin", cHost, cFileSize);
414+ 
415+ aclrtFree(aDevice);
416+ aclrtFreeHost(aHost);
417+ aclrtFree(bDevice);
418+ aclrtFreeHost(bHost);
419+ aclrtFree(cDevice);
420+ aclrtFreeHost(cHost);
421+ if constexpr (SCENARIO_NUM == 4) {
422+ aclrtFree(biasDevice);
423+ aclrtFreeHost(biasHost);
424+ }
425+ if constexpr (SCENARIO_NUM == 5) {
426+ aclrtFree(quantAlphaDevice);
427+ aclrtFreeHost(quantAlphaHost);
428+ }
429+ 
430+ aclrtDestroyStream(stream);
431+ aclrtResetDevice(deviceId);
432+ aclFinalize();
433+ return 0;
434+}
@@ -0,0 +1,94 @@
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+/* !
13+ * \file data_utils.h
14+ * \brief
15+ */
16+ 
17+#ifndef DATA_UTILS_H
18+#define DATA_UTILS_H
19+#include <fcntl.h>
20+#include <sys/stat.h>
21+#include <unistd.h>
22+#include <fstream>
23+ 
24+#define ERROR_LOG(fmt, args...) fprintf(stdout, "[ERROR] " fmt "\n", ##args)
25+ 
26+bool ReadFile(const std::string &filePath, size_t &fileSize, void *buffer, size_t bufferSize)
27+{
28+ struct stat sBuf;
29+ int fileStatus = stat(filePath.data(), &sBuf);
30+ if (fileStatus == -1) {
31+ ERROR_LOG("failed to get file");
32+ return false;
33+ }
34+ if (S_ISREG(sBuf.st_mode) == 0) {
35+ ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
36+ return false;
37+ }
38+ 
39+ std::ifstream file;
40+ file.open(filePath, std::ios::binary);
41+ if (!file.is_open()) {
42+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
43+ return false;
44+ }
45+ 
46+ std::filebuf *buf = file.rdbuf();
47+ size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
48+ if (size == 0) {
49+ ERROR_LOG("file size is 0");
50+ file.close();
51+ return false;
52+ }
53+ if (size > bufferSize) {
54+ ERROR_LOG("file size is larger than buffer size");
55+ file.close();
56+ return false;
57+ }
58+ buf->pubseekpos(0, std::ios::in);
59+ buf->sgetn(static_cast<char *>(buffer), size);
60+ fileSize = size;
61+ file.close();
62+ return true;
63+}
64+ 
65+/**
66+ * @brief Write data to file
67+ * @param [in] filePath: file path
68+ * @param [in] buffer: data to write to file
69+ * @param [in] size: size to write
70+ * @return write result
71+ */
72+bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
73+{
74+ if (buffer == nullptr) {
75+ ERROR_LOG("Write file failed. buffer is nullptr");
76+ return false;
77+ }
78+ 
79+ int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
80+ if (fd < 0) {
81+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
82+ return false;
83+ }
84+ 
85+ size_t writeSize = write(fd, buffer, size);
86+ (void)close(fd);
87+ if (writeSize != size) {
88+ ERROR_LOG("Write file Failed.");
89+ return false;
90+ }
91+ 
92+ return true;
93+}
94+#endif // DATA_UTILS_H
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:70d7036288a6179691184ffdbf9050a758978887a76b7e73c2e3a1ad336e737b
3+size 170614
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:6e9a533fa1ef51d5d73ef63a163fff8ffe6d8d901ffbf1fb847cca9325f527b8
3+size 170156
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:471c15f7dcc9448a30106a06aee82bd494df5cc0331d365b55c5617c0891ea46
3+size 234807
@@ -0,0 +1,153 @@
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+import argparse
16+import copy
17+import struct
18+import numpy as np
19+np.random.seed(9)
20+ 
21+def extract_relu_params(relu_pre):
22+ relu_pre = int(relu_pre)
23+ relu_alpha_bits = (relu_pre >> 13) & 0xFFFFF # 提取M2的20位[31:13],0xFFFFF是20位掩码
24+ sign_bit = (relu_alpha_bits >> 18) & 0x1
25+ exponent = (relu_alpha_bits >> 10) & 0xFF
26+ mantissa = relu_alpha_bits & 0x3FF
27+ exponent_bias = 127 # 假设指数偏倚量为127,与float32一致
28+ relu_alpha = (-1) ** sign_bit * (1 + mantissa / 1024) * (2 ** (exponent - exponent_bias))
29+ return relu_alpha
30+ 
31+def extract_quant_params(quant_pre):
32+ """
33+ 从uint64类型的quant_gm中提取M1、offset、sign参数
34+ param:
35+ quant_pre:uint64类型的整数
36+ return:
37+ quant_alpha:自定义格式(1,8,10)的浮点数
38+ offset:9位整数
39+ sign:1位布尔值(0或1)
40+ """
41+ quant_pre = int(quant_pre)
42+ quant_alpha_bits = (quant_pre >> 13) & 0xFFFFF # 提取M1的20位[31:13],0xFFFFF是20位掩码
43+ mode_control_bit = (quant_pre >> 36) & 0x1 # 提取mode_ctrl bit的一位[36],0x1是1位掩码
44+ offset = (quant_pre >> 37) & 0x1FF # 提取offset的9位[45:37],0x1FF是9位掩码
45+ sign = (quant_pre >> 46) & 0x1 # 提取sign的一位[46],0x1是1位掩码
46+ n = (quant_pre >> 32) & 0xF
47+ # 解析M1为(1,8,10)格式的浮点数
48+ sign_bit = (quant_alpha_bits >> 18) & 0x1
49+ exponent = (quant_alpha_bits >> 10) & 0xFF
50+ mantissa = quant_alpha_bits & 0x3FF
51+ exponent_bias = 127 # 假设指数偏倚量为127,与float32一致
52+ quant_alpha = (-1) ** sign_bit * (1 + mantissa / 1024) * (2 ** (exponent - exponent_bias))
53+ return quant_alpha, offset, sign, n, mode_control_bit
54+ 
55+def saturation(value, min_val, max_val, target_type):
56+ """
57+ 将输入的浮点数进行饱和处理,并转换为目标类型
58+ """
59+ x_clamped = np.clip(value, min_val, max_val)
60+ return np.round(x_clamped).astype(target_type)
61+ 
62+def qf322b8_pre(data, quant_pre, relu_pre):
63+ """
64+ float32 -> int8/uint8
65+ """
66+ quant_alpha, offset, sign, n_shift, mode_control_bit = extract_quant_params(quant_pre)
67+ # sign = 0
68+ relu_alpha = extract_relu_params(relu_pre)
69+ if mode_control_bit == 1:
70+ data = data / (2 ** n_shift)
71+ data = saturation(data, -32768, 32767, np.int16)
72+ data = data.astype(np.float32)
73+ if data >= 0:
74+ data = data * quant_alpha
75+ else:
76+ data = data * relu_alpha
77+ quant_data = saturation(data, -256, 255, np.int16) + offset
78+ if sign:
79+ return saturation(quant_data, -128, 127, np.int8)
80+ else:
81+ return saturation(quant_data, 0, 255, np.uint8)
82+ 
83+def pre_quant_relu(golden, dst_type, m, n, pre_quant_mode, pre_relu_mode):
84+ quant_scalar = 2
85+ norm_relu_alpha = 0
86+ 
87+ relu_alpha = 1
88+ if pre_relu_mode == 0:
89+ relu_alpha = quant_scalar
90+ elif pre_relu_mode == 1:
91+ relu_alpha = norm_relu_alpha
92+ relu_alpha = struct.unpack('!I', struct.pack('!f', relu_alpha))[0]
93+ 
94+ # 1 * n 量化系数为全为quant scalar的量化tensor
95+ temp_quant_tensor = ((quant_scalar * np.ones((1, n), dtype=np.float32)).astype(np.float32))[0]
96+ temp_quant_tensor_api = copy.deepcopy(temp_quant_tensor).astype(np.uint64)
97+ for i, _ in enumerate(temp_quant_tensor_api):
98+ temp_quant_tensor_api[i] = struct.unpack('!I', struct.pack('!f', temp_quant_tensor[i]))[0]
99+ if dst_type == np.int8:
100+ # np.int8 sign is true
101+ temp_quant_tensor_api[i] = temp_quant_tensor_api[i] | np.uint64(0x400000000000)
102+ quant_tensor = np.frombuffer(temp_quant_tensor_api, np.uint64)
103+ quant_tensor = quant_tensor.astype(np.uint64)
104+ if pre_quant_mode == 2:
105+ quant_tensor.tofile("./input/quant_pre.bin")
106+ quant_golden = np.zeros((m, n), dtype=np.int8)
107+ for i in range(m):
108+ for j in range(n):
109+ quant_golden[i, j] = qf322b8_pre(golden[i, j], quant_tensor[j], relu_alpha)
110+ return quant_golden
111+ 
112+def gen_golden_data(scenarioNum=1):
113+ M = 128
114+ K = 128
115+ N = 256
116+ 
117+ input_type = np.dtype("float16")
118+ output_type = np.dtype("float32")
119+ x1_gm = np.random.uniform(-1, 3, [M, K]).astype(input_type)
120+ x2_gm = np.random.uniform(-1, 3, [K, N]).astype(input_type)
121+ bias_gm = np.random.uniform(-1, 3, [N]).astype(np.float32)
122+ golden = np.matmul(x1_gm.astype(np.float32), x2_gm.astype(np.float32)).astype(np.float32)
123+ # print(golden)
124+ os.makedirs("input", exist_ok=True)
125+ os.makedirs("output", exist_ok=True)
126+ 
127+ if scenarioNum == 1:
128+ block_cols = 16
129+ x1_gm = x1_gm.reshape((int(M / 16), 16, int(K / block_cols), block_cols)).transpose(2, 0, 1, 3).astype(input_type)
130+ x2_gm = x2_gm.reshape((int(K / 16), 16, int(N / block_cols), block_cols)).transpose(2, 0, 1, 3).astype(input_type)
131+ elif scenarioNum == 2:
132+ pass
133+ elif scenarioNum == 3:
134+ x1_gm = x1_gm.transpose(1, 0)
135+ x2_gm = x2_gm.transpose(1, 0)
136+ elif scenarioNum == 4:
137+ golden += bias_gm
138+ elif scenarioNum == 5:
139+ output_type = np.dtype("int8")
140+ golden = pre_quant_relu(golden, output_type, M, N, 2, 0) #vector
141+ 
142+ x1_gm.astype(input_type).tofile("./input/x1_gm.bin")
143+ x2_gm.astype(input_type).tofile("./input/x2_gm.bin")
144+ if scenarioNum == 4:
145+ bias_gm.tofile("./input/bias_gm.bin")
146+ golden.astype(output_type).tofile("./output/golden.bin")
147+
148+ 
149+if __name__ == "__main__":
150+ parser = argparse.ArgumentParser()
151+ parser.add_argument('-scenarioNum', type=int, default=1, choices=range(1, 8))
152+ args = parser.parse_args()
153+ gen_golden_data(args.scenarioNum)
@@ -0,0 +1,56 @@
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+import numpy as np
16+ 
17+ 
18+# for float32
19+relative_tol = 1e-6
20+absolute_tol = 1e-9
21+error_tol = 1e-4
22+ 
23+ 
24+def verify_result(output, golden):
25+ output = np.fromfile(output, dtype=np.float32).reshape(-1)
26+ golden = np.fromfile(golden, dtype=np.float32).reshape(-1)
27+ different_element_results = np.isclose(output,
28+ golden,
29+ rtol=relative_tol,
30+ atol=absolute_tol,
31+ equal_nan=True)
32+ different_element_indexes = np.where(different_element_results == False)[0]
33+ for index in range(len(different_element_indexes)):
34+ real_index = different_element_indexes[index]
35+ golden_data = golden[real_index]
36+ output_data = output[real_index]
37+ print(
38+ "data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f" %
39+ (real_index, golden_data, output_data,
40+ abs(output_data - golden_data) / golden_data))
41+ if index == 100:
42+ break
43+ error_ratio = float(different_element_indexes.size) / golden.size
44+ return error_ratio <= error_tol
45+ 
46+ 
47+if __name__ == '__main__':
48+ try:
49+ res = verify_result(sys.argv[1], sys.argv[2])
50+ if not res:
51+ raise ValueError("[ERROR] result error")
52+ else:
53+ print("test pass!")
54+ except Exception as e:
55+ print(e)
56+ sys.exit(1)
@@ -14,6 +14,7 @@
14 14 
15```15```
16├── fixpipe_l0c2gm16├── fixpipe_l0c2gm
17+│ ├── figures // 图示
17│ ├── scripts18│ ├── scripts
18│ │ ├── gen_data.py // 输入数据和真值数据生成脚本19│ │ ├── gen_data.py // 输入数据和真值数据生成脚本
19│ │ └── verify_result.py // 验证输出数据和真值数据是否一致的验证脚本20│ │ └── verify_result.py // 验证输出数据和真值数据是否一致的验证脚本
@@ -162,7 +163,7 @@
162 | 选项 | 可选值 | 说明 |163 | 选项 | 可选值 | 说明 |
163 |------|--------|------|164 |------|--------|------|
164 | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 运行模式:NPU 运行、NPU仿真 |165 | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 运行模式:NPU 运行、NPU仿真 |
165- | `CMAKE_ASC_ARCHITECTURES` | `dav-2201`(默认)、`dav-3510` | NPU 架构,dav-2201 对应 Atlas A2 训练系列产品/Atlas A2 推理系列产品和Atlas A3 训练系列产品/Atlas A3 推理系列产品,dav-3510 对应 Ascend 950PR/Ascend 950DT |166+ | `CMAKE_ASC_ARCHITECTURES` | `dav-2201`(默认)、`dav-3510` | NPU 架构:dav-2201 对应 Atlas A2 训练系列产品/Atlas A2 推理系列产品和Atlas A3 训练系列产品/Atlas A3 推理系列产品,dav-3510 对应 Ascend 950PR/Ascend 950DT |
166 | `SCENARIO_NUM` | 1-7 | 场景编号 |167 | `SCENARIO_NUM` | 1-7 | 场景编号 |
167 168 
168 执行结果如下,说明精度对比成功。169 执行结果如下,说明精度对比成功。