Merged
add matmul_gelu high performance #1814
add matmul_gelu high performance #1814
Merged
zc1110Add on Apr 25
Total: 8 files changed+1418-0
@@ -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+ 
12+cmake_minimum_required(VERSION 3.16)
13+ 
14+set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu, cpu, sim")
15+set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-2201, dav-3510")
16+set(SCENARIO_NUM 1 CACHE STRING "Scenario: 1=CV融合(GM中转), 2=CV融合(UB直通,仅A5)")
17+ 
18+find_package(ASC REQUIRED)
19+ 
20+project(kernel_samples LANGUAGES ASC CXX)
21+ 
22+add_executable(demo
23+ mmad_gelu.asc
24+)
25+if(CMAKE_ASC_ARCHITECTURES STREQUAL "dav-2201")
26+ set(NPU_ARCH_ID 2201)
27+elseif(CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510")
28+ set(NPU_ARCH_ID 3510)
29+else()
30+ message(FATAL_ERROR "Unsupported CMAKE_ASC_ARCHITECTURES=${CMAKE_ASC_ARCHITECTURES}, only dav-2201 and dav-3510 are supported")
31+endif()
32+message(STATUS "[INFO] SCENARIO_NUM is ${SCENARIO_NUM}")
33+ 
34+target_compile_definitions(demo PRIVATE
35+ NPU_ARCH=${NPU_ARCH_ID}
36+ SCENARIO_NUM=${SCENARIO_NUM}
37+)
38+ 
39+target_compile_options(demo PRIVATE
40+ $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}>
41+)
@@ -0,0 +1,407 @@
1+# Matmul Gelu最佳实践样例
2+ 
3+## 概述
4+ 
5+本样例基于静态Tensor编程范式,展示了Cube-Vector(CV)融合的实现方法,将Matmul矩阵乘法与GELU激活函数融合到同一AI Core中并行执行。AIC侧完成Matmul计算后通过Fixpipe将结果输出到GM或UB,AIV侧从GM或UB读取数据完成GELU向量计算。其中Matmul部分的优化细节参考[Matmul基础API最佳实践样例](../../01_matrix_compute_practices/matmul_basic_api_high_performance/README.md),GELU部分的优化细节参考[Gelu性能调优样例](../../02_reg_vector_compute_practices/gelu_high_performance/README.md)。
6+ 
7+## 支持的产品
8+ 
9+- Ascend 950PR/Ascend 950DT
10+- Atlas A3 训练系列产品/Atlas A3 推理系列产品
11+- Atlas A2 训练系列产品/Atlas A2 推理系列产品
12+ 
13+## 目录结构介绍
14+ 
15+```
16+├── matmul_gelu_high_performance
17+│ ├── scripts
18+│ │ ├── gen_data.py // 输入数据和真值数据生成脚本文件
19+│ │ └── verify_result.py // 真值对比文件
20+│ ├── CMakeLists.txt // 编译工程文件
21+│ ├── data_utils.h // 数据读入写出函数
22+│ └── mmad_gelu.asc // Ascend C样例实现
23+```
24+ 
25+## 样例描述
26+ 
27+Matmul + GELU计算公式:
28+ 
29+$$
30+C = GELU(A * B)
31+$$
32+ 
33+$$
34+GELU(x) \approx \frac{x}{1 + e^{-1.595769 \cdot (x + 0.044715 \cdot x^3)}}
35+$$
36+ 
37+- A为左矩阵,形状为[M, K],数据类型为float16;B为右矩阵,形状为[K, N],数据类型为float16,B矩阵以转置方式存储
38+- C为目的操作数,存放Matmul+GELU计算结果,形状为[M, N],数据类型为float32
39+ 
40+- 样例规格:
41+ 
42+<table>
43+<tr><td rowspan="1" align="center">样例类型(OpType)</td><td colspan="5" align="center">Matmul + GELU</td></tr>
44+<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><td align="center">isTrans</td></tr>
45+<tr><td align="center">A</td><td align="center">[M, K]</td><td align="center">float16</td><td align="center">ND</td><td align="center">false</td></tr>
46+<tr><td align="center">B</td><td align="center">[K, N]</td><td align="center">float16</td><td align="center">ND</td><td align="center">true</td></tr>
47+<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><td align="center">-</td></tr>
48+<tr><td rowspan="1" align="center">核函数名</td><td colspan="5" align="center">mmad_vector_custom</td></tr>
49+</table>
50+ 
51+## 样例实现
52+ 
53+### 性能指标说明
54+ 
55+| 指标 | 说明 |
56+|------------------------|----------------------------------------------------------------------|
57+| Task Duration(μs) | 整个任务执行的总时间,算子执行时间以该参数为准 |
58+| Block Num | 使用的核数(Block 数量) |
59+| aicore_time(μs) | AI Core 的平均执行时间 |
60+| aic_mac_time(μs) | cube 类型指令(矩阵类运算指令)耗时 |
61+| aic_mac_ratio | cube 类型指令(矩阵类运算指令)的 cycle 数在 total cycle 数中的占用比 |
62+| aic_mte1_time(μs) | mte1 类型指令(L1 -> L0A/L0B 搬运)耗时 |
63+| aic_mte1_ratio | mte1 类型指令(L1 -> L0A/L0B 搬运)的 cycle 数在 total cycle 数中的占用比 |
64+| aic_mte2_time(μs) | mte2 类型指令(GM -> L1 搬运)耗时 |
65+| aic_mte2_ratio | mte2 类型指令(GM -> L1 搬运)的 cycle 数在 total cycle 数中的占用比 |
66+| aic_fixpipe_time(μs) | fixpipe 类型指令(L0C -> GM/UB 搬运)耗时 |
67+| aic_fixpipe_ratio | fixpipe 类型指令(L0C -> GM/UB 搬运)的 cycle 数在 total cycle 数中的占用比 |
68+| aiv_time(μs) | Task 在 AI Vector Core 上的执行时间 |
69+| aiv_vec_time(μs) | vec 类型指令(向量类运算指令)耗时 |
70+| aiv_vec_ratio | vec 类型指令(向量类运算指令)的 cycle 数在 total cycle 数中的占用比 |
71+| aiv_scalar_time(μs) | scalar 类型指令(标量类运算指令)耗时 |
72+| aiv_scalar_ratio | scalar 类型指令(标量类运算指令)的 cycle 数在 total cycle 数中的占用比 |
73+| aiv_mte2_time(μs) | mte2 类型指令(GM -> UB 搬运类指令)耗时 |
74+| aiv_mte2_ratio | mte2 类型指令(GM -> UB 搬运类指令)的 cycle 数在 total cycle 数中的占用比 |
75+| aiv_mte3_time(μs) | mte3 类型指令(UB -> GM 搬运类指令)耗时 |
76+| aiv_mte3_ratio | mte3 类型指令(UB -> GM 搬运类指令)的 cycle 数在 total cycle 数中的占用比 |
77+ 
78+### 数据流路径
79+ 
80+本样例提供两种CV融合场景:
81+ 
82+**Scenario 1:CV融合-GM中转**(A2/A3/Ascend 950PR均支持)
83+ 
84+```
85+GM ──(MTE2)──> L1 ──(MTE1)──> L0A/L0B ──(Cube)──> L0C ──(Fixpipe)──> GM ──(MTE2)──> UB ──(Gelu)──> UB ──(MTE3)──> GM
86+```
87+ 
88+**Scenario 2:CV融合-UB直通**(仅Ascend 950PR支持)
89+ 
90+Ascend 950PR新增L0C->UB的通路,A2/A3不支持,芯片能力增强,因此在Ascend 950PR架构中可以不经过GM直接将矩阵乘结果输出到UB进行GELU计算
91+ 
92+```
93+GM ──(MTE2)──> L1 ──(MTE1)──> L0A/L0B ──(Cube)──> L0C ──(Fixpipe)──> UB ──(Gelu)──> UB ──(MTE3)──> GM
94+```
changxianyu

这里可以强调一下区别,Ascend 950PR新增L0C到UB的通路,A2/A3不支持,芯片能力增强之类的描述;另外表示描述,对外没有A5,统一用Ascend 950PR

likedislike
95+ 
96+### 核心特性
97+ 
98+本样例的Matmul部分采用与[Matmul基础API最佳实践样例](../../01_matrix_compute_practices/matmul_basic_api_high_performance/README.md)相同的优化手段(L1/L0双缓冲、大包搬运、细粒度流水同步、UnitFlag等),GELU部分在Ascend 950PR架构上采用RegBase方式,在A2/A3架构上采用MemBase方式。以下重点说明CV融合的实现机制。
99+ 
100+以下重点说明AIC↔AIV的CV融合机制。
101+ 
102+#### 1. CV融合架构:`__mix__(1,2)` 核函数
103+ 
104+本样例使用 `__global__ __mix__(1, 2)` 声明核函数,表示每个逻辑核由1个AIC和2个AIV组成。AIC侧负责Matmul计算,AIV侧负责GELU向量计算,两者在同一AI Core内按(baseM × baseN)块粒度流水并行。
105+ 
106+```cpp
107+__global__ __mix__(1, 2) void mmad_vector_custom(GM_ADDR a, GM_ADDR b, GM_ADDR c)
108+{
109+ AscendC::InitSocState();
110+ KernelMmadVector<...> op;
111+ op.Init(a, b, c);
112+ op.Process();
113+ AscendC::PipeBarrier<PIPE_ALL>();
114+}
115+```
116+ 
117+在 `Process()` 中,通过 `ASCEND_IS_AIC` 和 `ASCEND_IS_AIV` 宏区分AIC和AIV的执行路径:
118+ 
119+```cpp
120+if ASCEND_IS_AIC {
121+ // AIC侧:Buffer分配 + 计算循环 + Fixpipe搬出
122+ ProcessLoopAic(...);
123+}
124+if ASCEND_IS_AIV {
125+ // AIV侧:GELU向量计算 + 搬出至GM
126+ ProcessLoopAiv();
127+}
128+```
129+ 
130+#### 2. 跨核同步:AIC→AIV 数据就绪通知
131+ 
132+AIC侧每完成一个 (baseM × baseN)大小子块的Fixpipe输出后,通过 `CrossCoreSetFlag` 通知AIV侧数据已就绪;AIV侧通过 `CrossCoreWaitFlag` 等待该信号,然后开始GELU计算:
133+ 
134+```cpp
135+// AIC侧 CopyOutAic():
136+AscendC::CrossCoreSetFlag<0x2, PIPE_FIX>(0x8); // 通知AIV数据就绪
137+ 
138+// AIV侧 GeluAndCopyOutAivSeparate() / GeluAndCopyOutAiv():
139+AscendC::CrossCoreWaitFlag(0x8); // 等待AIC侧Fixpipe完成
140+```
141+ 
142+#### 3. Scenario 1:CV融合-GM中转
143+ 
144+AIC侧通过Fixpipe将L0C计算结果写入GM,AIV侧从GM读取数据到UB后进行GELU计算,再将结果写回GM。这种方式所有架构均支持。
145+ 
146+**AIC侧**:Fixpipe L0C → GM
147+ 
148+```cpp
149+// A2/A3架构
150+AscendC::FixpipeParamsV220 fixpipeParams;
151+fixpipeParams.nSize = curN;
152+fixpipeParams.mSize = curM;
153+fixpipeParams.srcStride = curMAlign;
154+fixpipeParams.dstStride = N;
155+AscendC::Fixpipe<float, float, CFG_ROW_MAJOR_GM>(cGM[...], cLocal, fixpipeParams);
156+ 
157+// Ascend 950PR架构
158+AscendC::FixpipeParamsArch3510<AscendC::CO2Layout::ROW_MAJOR> fixpipeParams;
159+fixpipeParams.mSize = curM;
160+fixpipeParams.nSize = curN;
161+fixpipeParams.srcStride = curMAlign;
162+fixpipeParams.dstStride = N;
163+AscendC::Fixpipe<float, float, CFG_ROW_MAJOR_GM>(cGM[...], cLocal, fixpipeParams);
164+```
165+ 
166+**AIV侧**:GM → xUB → GELU → geluOutUB → GM
167+ 
168+`__mix__(1,2)` 模式下每个逻辑核有2个AIV,Fixpipe输出到GM的M行数据按M/2行拆分给两个AIV处理。每个AIV通过 `GetSubBlockIdx() % 2` 获取自己的子块索引,独立完成各自M/2行的GELU计算:
169+ 
170+```cpp
171+uint32_t localSubIdx = AscendC::GetSubBlockIdx() % 2;
172+uint32_t gmOffset = mBlockIdx * baseM * N + nBlockIdx * baseN + localSubIdx * baseM / 2 * N;
173+ 
174+// Step 1: DataCopy GM → xUB
175+AscendC::DataCopyPad<float>(xUB, cGM[gmOffset], copyInParams, padParams);
176+ 
177+// Step 2: GELU计算
178+// A2/A3: GeluMemBaseCompute(xUB, geluOutUB, computeLen);
179+// Ascend 950PR: GeluRegBaseCompute(xUB, geluOutUB, computeLen);
180+ 
181+// Step 3: DataCopy geluOutUB → GM
182+AscendC::DataCopyPad<float>(cGM[gmOffset], geluOutUB, copyOutParams);
183+```
184+ 
185+#### 4. Scenario 2:CV融合-UB直通(仅Ascend 950PR支持)
186+ 
187+AIC侧通过Fixpipe将L0C计算结果直接写入UB,AIV侧无需从GM读取数据,直接在UB上进行GELU计算后将结果写回GM。这种方式省去了GM中转的读写开销,但仅Ascend 950PR架构Fixpipe从L0C到UB。
188+ 
189+**AIC侧**:Fixpipe L0C → UB(通过 `dualDstCtl=0b01` 开启双目标模式,按M维度拆分给2个AIV)
190+ 
191+```cpp
192+AscendC::FixpipeParamsArch3510<AscendC::CO2Layout::ROW_MAJOR> fixpipeParams;
193+fixpipeParams.mSize = AscendC::DivCeil(curM, 2) * 2;
194+fixpipeParams.nSize = curN;
195+fixpipeParams.srcStride = curMAlign;
196+fixpipeParams.dstStride = curN;
197+fixpipeParams.dualDstCtl = 0b01; // 按M维度拆分到2个AIV的UB
198+AscendC::Fixpipe<float, float, CFG_ROW_MAJOR_UB>(xUB, cLocal, fixpipeParams);
199+```
200+ 
201+**AIV侧**:UB → GELU → geluOutUB → GM
202+ 
203+AIV侧无需DataCopy GM→UB,直接对xUB进行GELU计算:
204+ 
205+```cpp
206+// GELU计算:xUB作为输入,geluOutUB作为输出
207+GeluRegBaseCompute(xUB, geluOutUB, computeLen);
208+ 
209+// DataCopy: geluOutUB → GM
210+uint32_t localSubIdx = AscendC::GetSubBlockIdx() % 2;
211+uint32_t offset = baseM / 2 * N;
212+AscendC::DataCopyPad<float>(cGM[mBlockIdx * baseM * N + nBlockIdx * baseN + localSubIdx * offset], geluOutUB, copyParams);
213+```
214+ 
215+#### 5. GELU计算实现
216+ 
217+**A2/A3架构**:使用MemBase方式(向量基础API + PipeBarrier),无需额外中间缓冲区,直接复用输出缓冲区:
218+ 
219+```cpp
220+__aicore__ inline void GeluMemBaseCompute(
221+ const AscendC::LocalTensor<float>& xLocal, const AscendC::LocalTensor<float>& yLocal, uint32_t n)
222+{
223+ AscendC::Mul(yLocal, xLocal, xLocal, n); // x²
224+ AscendC::PipeBarrier<PIPE_V>();
225+ AscendC::Mul(yLocal, yLocal, xLocal, n); // x³
226+ ……
227+}
228+```
229+ 
230+**Ascend 950PR架构**:使用RegBase方式(VF函数),中间计算在寄存器内完成,无需额外UB缓冲区,减少数据在UB和Reg之间的交互:
231+ 
232+```cpp
233+__simd_vf__ inline void GeluVf(__ubuf__ float* xAddr, __ubuf__ float* yAddr, uint32_t n, uint32_t loopNum)
234+{
235+ constexpr uint32_t oneRepeatSize = AscendC::GetVecLen() / sizeof(float);
236+ AscendC::Reg::MaskReg mask;
237+ AscendC::Reg::RegTensor<float> xReg, yReg;
238+ 
239+ for (uint16_t i = 0; i < loopNum; ++i) {
240+ mask = AscendC::Reg::UpdateMask<float>(n);
241+ AscendC::Reg::LoadAlign(xReg, xAddr + i * oneRepeatSize);
242+ AscendC::Reg::Mul(yReg, xReg, xReg, mask); // x²
243+ ……
244+ AscendC::Reg::StoreAlign(yAddr + i * oneRepeatSize, yReg, mask);
245+ }
246+}
247+```
248+ 
249+GELU公式的化简、RegBase API与VF融合的详细优化分析请参考[Gelu性能调优样例](../../02_reg_vector_compute_practices/gelu_high_performance/README.md)。
250+ 
251+#### 6. `__mix__(1,2)` 模式下的多核切分
252+ 
253+`__mix__(1,2)` 模式下,`GetBlockIdx()` 在AIC侧和AIV侧各自独立编号:AIC侧返回0~numAICores-1,AIV侧返回0~numAIVCores-1。由于每个逻辑核对应2个AIV,AIV侧需要将 `GetBlockIdx() / 2` 映射回逻辑核ID,从而与AIC侧使用相同的多核切分策略:
254+ 
255+```cpp
256+uint32_t logicCoreId;
257+if ASCEND_IS_AIC {
258+ logicCoreId = AscendC::GetBlockIdx();
259+} else {
260+ logicCoreId = AscendC::GetBlockIdx() / 2; // __mix__(1,2): 每个逻辑核对应2个AIV
261+}
262+uint32_t mIterIdx = logicCoreId % mIter;
263+uint32_t nIterIdx = logicCoreId / mIter;
264+```
265+ 
266+### 性能数据分析
267+ 
268+#### Atlas A2训练系列芯片性能数据
269+ 
270+- Scenario 1:CV融合-GM中转,singleCoreM=2048, singleCoreN=1536,24核
271+ 
272+| Scenario | Task Type | Task Duration(μs) | Block Num | Mix Block Num | aicore_time(μs) | aic_mac_time(μs) | aic_mac_ratio | aic_scalar_time(μs) | aic_scalar_ratio | aic_mte1_time(μs) | aic_mte1_ratio | aic_mte2_time(μs) | aic_mte2_ratio | aic_fixpipe_time(μs) | aic_fixpipe_ratio | aiv_time(μs) | 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 |
changxianyu

数据这里有个很奇怪的点,为什么融合之后的vector计算耗时比单独跑Gelu计算的vector耗时少?可以看下MIX_AIC的vector耗时更少

likedislike
273+|------|-----------|-------------------|-----------|---------------|-----------------|------------------|---------------|---------------------|------------------|------------------|----------------|------------------|----------------|---------------------|-------------------|--------------|-----------------|---------------|---------------------|------------------|------------------|----------------|------------------|----------------|
274+|Gelu计算 | AI_VECTOR_CORE | 369.827 | 48 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 358.91 | 236.506 | 0.659 | 8.293 | 0.023 | 316.672 | 0.882 | 150.033 | 0.418 |
275+| Matmul计算 | AI_CORE | 4227.605 | 24 | 0 | 3760.55 | 3083.197 | 0.82 | 338.636 | 0.09 | 2516.081 | 0.669 | 3685.713 | 0.98 | 193.704 | 0.052 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
276+| Scenario 1 | MIX_AIC | 4236.944 | 24 | 48 | 3770.16 | 3083.235 | 0.818 | 531.971 | 0.141 | 2520.852 | 0.669 | 3687.839 | 0.978 | 193.933 | 0.051 | 3773.6 | 174.327 | 0.046 | 2.016 | 0.001 | 90.315 | 0.024 | 66.373 | 0.018 |
277+ 
278+#### Ascend 950PR芯片性能数据
279+ 
280+- Scenario 1:CV融合-GM中转,singleCoreM=2048, singleCoreN=1024,32核
281+- Scenario 2:CV融合-UB直通,singleCoreM=2048, singleCoreN=1024,32核
282+ 
283+| Scenario | Task Type | Task Duration(μs) | Block Num | Mix Block Num | aicore_time(μs) | aic_mac_time(μs) | aic_mac_ratio | aic_scalar_time(μs) | aic_scalar_ratio | aic_mte1_time(μs) | aic_mte1_ratio | aic_mte2_time(μs) | aic_mte2_ratio | aic_fixpipe_time(μs) | aic_fixpipe_ratio | aiv_time(μs) | 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 |
284+|------|-----------|-------------------|-----------|---------------|-----------------|------------------|---------------|---------------------|------------------|------------------|----------------|------------------|----------------|------------------|----------------|---------------------|-------------------|--------------|-----------------|---------------|---------------------|------------------|------------------|----------------|
285+| Gelu计算(RegBase) | AI_VECTOR_CORE | 348.868 | 64 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 347.99 | 66.277 | 0.19 | 3.03 | 0.009 | 320.543 | 0.921 | 314.547 | 0.904 |
286+| Matmul计算 | AI_CORE | 2601.311 | 32 | 0 | 2600.55 | 2593.264 | 0.997 | 104.582 | 0.04 | 816.91 | 0.314 | 1875.057 | 0.721 | 252.163 | 0.097 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
287+| Scenario 1 | MIX_AIC | 2606.91 | 32 | 64 | 2605.9 | 2597.856 | 0.997 | 105.131 | 0.04 | 818.781 | 0.314 | 1917.737 | 0.736 | 252.231 | 0.097 | 2605.93 | 59.897 | 0.023 | 1.783 | 0.001 | 57.145 | 0.022 | 50.516 | 0.019 |
288+| Scenario 2 | MIX_AIC | 2573.584 | 32 | 64 | 2572.67 | 2565.251 | 0.997 | 104.669 | 0.041 | 819.934 | 0.319 | 2096.38 | 0.815 | 212.403 | 0.083 | 2572.69 | 60.438 | 0.023 | 1.138 | 0 | 0.005 | 0 | 68.76 | 0.027 |
289+ 
290+#### 性能数据解读
291+ 
292+**Scenario 1:CV融合-GM中转**
293+ 
294+以Ascend 950PR芯片数据为例:
295+- 单独Gelu任务耗时348.868μs,单独Matmul任务耗时2601.311μs
296+- Scenario 1融合后总耗时2606.91μs,与Matmul单独执行时间基本一致
297+ 
298+这表明采用CV融合方式编写时,AIV的Vector计算时间基本被AIC的Cube计算时间完全覆盖。由于Cube和Vector可以并行执行,整体任务执行时间不是简单的C+V叠加,而是基本等于Cube计算时间(即Matmul时间),实现了高效的流水并行。
299+ 
300+下图展示了Scenario 1(CV融合-GM中转)场景下AIC和AIV的流水并行执行过程。AIC侧完成Matmul计算后通过Fixpipe将结果写入GM,AIV侧从GM读取数据完成GELU计算,两者按(baseM × baseN)块粒度流水并行:
301+ 
302+![Scenario1 CV融合-GM中转流水并行](figure/CVParallell_L0C_GM_UB.png)
303+ 
304+> **备注:** 流水图基于产品线CANN包msopprof工具上板获取,获取命令:`msprof op --aic-metrics=PipeUtilization`
305+ 
306+**MTE2时间显著减少的原因:**
307+ 
308+对比数据可以发现:
309+- 单独Gelu计算的aiv_mte2_time为320.543μs
310+- Scenario 1中aiv_mte2_time仅为57.145μs,减少约82.2%
311+ 
312+原因分析:虽然Scenario 1中AIV也需要从GM将数据读取到UB,但AIC的Fixpipe将Matmul计算结果写入GM后,数据会被缓存在L2 Cache中。当AIV发起MTE2操作从GM读取数据时,由于数据已在L2 Cache中命中,实际是从L2 Cache读取而非从GM读取,因此MTE2时间显著减少。这也是CV融合场景下的一个隐式性能优化点。
313+ 
314+**Scenario 2:CV融合-UB直通**
315+ 
316+以Ascend 950PR芯片数据为例:
317+- Scenario 2融合后总耗时2573.584μs,相比Scenario 1的2606.91μs进一步减少约33μs
318+- Scenario 2中aiv_mte2_time仅为0.005μs,相比Scenario 1的57.145μs几乎降为零
319+ 
320+下图展示了Scenario 2(CV融合-UB直通)场景下AIC和AIV的流水并行执行过程。AIC侧完成Matmul计算后通过Fixpipe将结果直接写入UB(不经过GM中转),AIV侧直接在UB上进行GELU计算,省去了GM→UB的MTE2搬运开销:
321+ 
322+![Scenario2 CV融合-UB直通流水并行](figure/CVParallell_L0C_UB.png)
323+ 
324+ 
325+## 编译运行
326+ 
327+在本样例根目录下执行如下步骤,编译并执行样例。
328+ 
329+### 配置环境变量
330+ 
331+请根据当前环境上 CANN 开发套件包的[安装方式](../../../../../docs/quick_start.md#prepare&install),选择对应配置环境变量的命令。
332+ 
333+- 默认路径,root 用户安装 CANN 软件包
334+ 
335+ ```bash
336+ source /usr/local/Ascend/cann/set_env.sh
337+ ```
338+ 
339+- 默认路径,非 root 用户安装 CANN 软件包
340+ 
341+ ```bash
342+ source $HOME/Ascend/cann/set_env.sh
343+ ```
344+ 
345+- 指定路径 install_path,安装 CANN 软件包
346+ 
347+ ```bash
348+ source ${install_path}/cann/set_env.sh
349+ ```
350+ 
351+### 样例执行
352+ 
353+```bash
354+SCENARIO=1 # 选择执行场景(1为CV融合-GM中转,2为CV融合-UB直通,仅Ascend 950PR支持)
355+mkdir -p build && cd build; # 创建并进入 build 目录
356+cmake -DSCENARIO_NUM=$SCENARIO -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # 编译工程(默认npu模式)
357+python3 ../scripts/gen_data.py # 生成测试输入数据
358+./demo # 执行编译生成的可执行程序
359+python3 ../scripts/verify_result.py output/output.bin output/golden.bin
360+```
361+ 
362+使用 NPU仿真 模式时,添加 `-DCMAKE_ASC_RUN_MODE=sim` 参数即可。
363+ 
364+示例:
365+ 
366+```bash
367+cmake -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-2201 ..;make -j; # NPU 仿真模式
368+```
369+ 
370+> **注意:**
371+> - 切换编译模式前需清理 cmake 缓存,可在 build 目录下执行 `rm CMakeCache.txt` 后重新 cmake。
372+> - A2/A3架构仅支持Scenario 1(GM中转),选择Scenario 2会触发编译期 `static_assert` 报错。
373+ 
374+### 编译选项说明
375+ 
376+| 参数 | 说明 | 可选值 | 默认值 |
377+|------|------|---------|--------|
378+| `SCENARIO_NUM` | CV融合场景 | 1: CV融合-GM中转;2: CV融合-UB直通(仅Ascend 950PR支持) | `1` |
379+| `CMAKE_ASC_RUN_MODE` | 运行模式 | `npu`、`sim` | `npu` |
380+| `CMAKE_ASC_ARCHITECTURES` | NPU 硬件架构 | `dav-2201`、`dav-3510` | `dav-3510` |
381+ 
382+执行结果如下,说明精度对比成功。
383+ 
384+```bash
385+test pass!
386+```
387+ 
388+### 性能分析
389+ 
390+使用 `msprof` 工具获取详细性能数据:
391+ 
392+```bash
393+msprof ./demo # 分析样例性能
394+```
395+ 
396+当前目录下会生成 PROF_ 前缀的文件夹,`mindstudio_profiler_output` 目录保存 Host 和各个 Device 的性能数据汇总,性能数据分析推荐查看该目录下文件:
397+ 
398+```bash
399+PROF_xxxx_XXXXXX
400+├── device_{id}
401+└── host
402+└── mindstudio_profiler_log
403+└── mindstudio_profiler_output # 保存 Host 和各个 Device 的性能数据汇总
404+ ├── msprof_*.json
405+ ├── xx_*.csv
406+ └── README.txt
407+```
@@ -0,0 +1,93 @@
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_utils.h
13+ * \brief Utility functions for reading and writing binary files
14+ */
15+ 
16+#ifndef DATA_UTILS_H
17+#define DATA_UTILS_H
18+#include <fcntl.h>
19+#include <sys/stat.h>
20+#include <unistd.h>
21+#include <fstream>
22+ 
23+#define ERROR_LOG(fmt, args...) fprintf(stdout, "[ERROR] " fmt "\n", ##args)
24+ 
25+bool ReadFile(const std::string& filePath, size_t& fileSize, void* buffer, size_t bufferSize)
26+{
27+ struct stat sBuf;
28+ int fileStatus = stat(filePath.data(), &sBuf);
29+ if (fileStatus == -1) {
30+ ERROR_LOG("failed to get file");
31+ return false;
32+ }
33+ if (S_ISREG(sBuf.st_mode) == 0) {
34+ ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
35+ return false;
36+ }
37+ 
38+ std::ifstream file;
39+ file.open(filePath, std::ios::binary);
40+ if (!file.is_open()) {
41+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
42+ return false;
43+ }
44+ 
45+ std::filebuf* buf = file.rdbuf();
46+ size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
47+ if (size == 0) {
48+ ERROR_LOG("file size is 0");
49+ file.close();
50+ return false;
51+ }
52+ if (size > bufferSize) {
53+ ERROR_LOG("file size is larger than buffer size");
54+ file.close();
55+ return false;
56+ }
57+ buf->pubseekpos(0, std::ios::in);
58+ buf->sgetn(static_cast<char*>(buffer), size);
59+ fileSize = size;
60+ file.close();
61+ return true;
62+}
63+ 
64+/**
65+ * @brief Write data to file
66+ * @param [in] filePath: file path
67+ * @param [in] buffer: data to write to file
68+ * @param [in] size: size to write
69+ * @return write result
70+ */
71+bool WriteFile(const std::string& filePath, const void* buffer, size_t size)
72+{
73+ if (buffer == nullptr) {
74+ ERROR_LOG("Write file failed. buffer is nullptr");
75+ return false;
76+ }
77+ 
78+ int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
79+ if (fd < 0) {
80+ ERROR_LOG("Open file failed. path = %s", filePath.c_str());
81+ return false;
82+ }
83+ 
84+ size_t writeSize = write(fd, buffer, size);
85+ (void)close(fd);
86+ if (writeSize != size) {
87+ ERROR_LOG("Write file Failed.");
88+ return false;
89+ }
90+ 
91+ return true;
92+}
93+#endif // DATA_UTILS_H
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:2c436a6fdd2bfd6fd18add005b5148ed4a7c75e060380745629342416914e87f
3+size 273438
@@ -0,0 +1,3 @@
1+version https://git-lfs.github.com/spec/v1
2+oid sha256:ebd85d315768c69827fa299f90400b60f5eec5f4e5e27caf42091ab1f27428d7
3+size 245219
@@ -0,0 +1,48 @@
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+ 
15+import os
16+import numpy as np
17+ 
18+ 
19+def gen_golden_data():
20+ m, n, k, is_bias = 8192, 8192, 8192, False
21+ 
22+ os.makedirs("input", exist_ok=True)
23+ os.makedirs("output", exist_ok=True)
24+ 
25+ x1_gm = np.random.uniform(-1, 1, [m, k]).astype(np.float16)
26+ x2_gm = np.random.uniform(-1, 1, [k, n]).astype(np.float16)
27+ matmul_result = np.matmul(x1_gm.astype(np.float32), x2_gm.astype(np.float32))
28+ 
29+ # Apply GELU activation: GELU(x) ≈ x / (1 + e^(-2·√(2/π)·(x + 0.044715·x³)))
30+ # where -2·√(2/π) ≈ -1.595769
31+ # Use float64 for intermediate computation to avoid overflow in x³ and exp()
32+ matmul_f64 = matmul_result.astype(np.float64)
33+ coeff = -1.595769
34+ exponent = coeff * (matmul_f64 + 0.044715 * (matmul_f64 ** 3))
35+ # Clip exponent to [-88, 88] to avoid exp() overflow in float64
36+ # For exponent > 88: exp()→∞, GELU(x)→0 (x is large negative)
37+ # For exponent < -88: exp()→0, GELU(x)→x (x is large positive)
38+ golden = (matmul_f64 / (1.0 + np.exp(np.clip(exponent, -88.0, 88.0)))).astype(np.float32)
39+ 
40+ x1_gm.tofile("./input/x1_gm.bin")
41+ # x2_gm transpose to match B matrix transpose
42+ x2_gm = x2_gm.transpose()
43+ x2_gm.tofile("./input/x2_gm.bin")
44+ golden.tofile("./output/golden.bin")
45+ 
46+ 
47+if __name__ == "__main__":
48+ gen_golden_data()
@@ -0,0 +1,58 @@
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+ 
15+import sys
16+import numpy as np
17+ 
18+ 
19+# for float32
20+relative_tol = 1e-3
21+absolute_tol = 1e-3
22+error_tol = 1e-3
23+ 
24+ 
25+def verify_result(output, golden):
26+ output = np.fromfile(output, dtype=np.float32).reshape(-1)
27+ golden = np.fromfile(golden, dtype=np.float32).reshape(-1)
28+ different_element_results = np.isclose(output,
29+ golden,
30+ rtol=relative_tol,
31+ atol=absolute_tol,
32+ equal_nan=True)
33+ different_element_indexes = np.where(different_element_results == False)[0]
34+ for index in range(len(different_element_indexes)):
35+ real_index = different_element_indexes[index]
36+ golden_data = golden[real_index]
37+ output_data = output[real_index]
38+ print(
39+ "data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f" %
40+ (real_index, golden_data, output_data,
41+ abs(output_data - golden_data) / golden_data))
42+ if index == 100:
43+ break
44+ error_ratio = float(different_element_indexes.size) / golden.size
45+ print("error ratio: %.4f, tolerance: %.4f" % (error_ratio, error_tol))
46+ return error_ratio <= error_tol
47+ 
48+ 
49+if __name__ == '__main__':
50+ try:
51+ res = verify_result(sys.argv[1], sys.argv[2])
52+ if not res:
53+ raise ValueError("[ERROR] result error")
54+ else:
55+ print("test pass!")
56+ except Exception as e:
57+ print(e)
58+ sys.exit(1)