| @@ -12,6 +12,7 @@ | |||
| 12 | |--------------------------------------------------------------------------------------------| ---------------------------------------------------- | --- | | 12 | |--------------------------------------------------------------------------------------------| ---------------------------------------------------- | --- | |
| 13 | | [batch_matmul_tensor_api](./batch_matmul_tensor_api) | 本样例基于Tensor API编程方式实现带Bias的Batch Matmul计算 | Ascend 950PR/Ascend 950DT | | 13 | | [batch_matmul_tensor_api](./batch_matmul_tensor_api) | 本样例基于Tensor API编程方式实现带Bias的Batch Matmul计算 | Ascend 950PR/Ascend 950DT | |
| 14 | | [batch_matmul](./batch_matmul) | 本样例介绍在输入为float数据类型并且左、右矩阵均不转置的场景下,带batch的矩阵乘法,其中GM -> L1通路采用DataCopy(Nd2NzParams)批量搬运,L0C -> GM、L0C -> L1通路采用Fixpipe批量搬运,L1 -> L0A / L0B搬运和Mmad矩阵乘循环执行batch次 | Ascend 950PR/Ascend 950DT<br>Atlas A3 训练系列产品/Atlas A3 推理系列产品<br>Atlas A2 训练系列产品/Atlas A2 推理系列产品 | | 14 | | [batch_matmul](./batch_matmul) | 本样例介绍在输入为float数据类型并且左、右矩阵均不转置的场景下,带batch的矩阵乘法,其中GM -> L1通路采用DataCopy(Nd2NzParams)批量搬运,L0C -> GM、L0C -> L1通路采用Fixpipe批量搬运,L1 -> L0A / L0B搬运和Mmad矩阵乘循环执行batch次 | Ascend 950PR/Ascend 950DT<br>Atlas A3 训练系列产品/Atlas A3 推理系列产品<br>Atlas A2 训练系列产品/Atlas A2 推理系列产品 | |
| 15 | +| [conv2d_forward_tensor_api](./conv2d_forward_tensor_api) | 本样例基于Tensor API编程方式实现Conv2D Forward计算,支持NC1HWC0、NCHW、NHWC三种GM输入/输出格式,通过`CopyGM2L1`(随路格式转换)、`CopyL12L0A`(Img2Col空间展开)、`Mmad`(矩阵乘)和`CopyL0C2GM`完成完整卷积流程 | Ascend 950PR/Ascend 950DT | | ||
| 15 | | [fixpipe_l0c2gm](./fixpipe_l0c2gm) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从L0C Buffer搬出到GM(Global Memory) | Ascend 950PR/Ascend 950DT<br>Atlas A3 训练系列产品/Atlas A3 推理系列产品<br>Atlas A2 训练系列产品/Atlas A2 推理系列产品 | | 16 | | [fixpipe_l0c2gm](./fixpipe_l0c2gm) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从L0C Buffer搬出到GM(Global Memory) | Ascend 950PR/Ascend 950DT<br>Atlas A3 训练系列产品/Atlas A3 推理系列产品<br>Atlas A2 训练系列产品/Atlas A2 推理系列产品 | |
| 16 | | [fixpipe_l0c2l1](./fixpipe_l0c2l1) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从L0C Buffer搬出到L1(L1 Buffer) | Ascend 950PR/Ascend 950DT<br>Atlas A3 训练系列产品/Atlas A3 推理系列产品<br>Atlas A2 训练系列产品/Atlas A2 推理系列产品 | | 17 | | [fixpipe_l0c2l1](./fixpipe_l0c2l1) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从L0C Buffer搬出到L1(L1 Buffer) | Ascend 950PR/Ascend 950DT<br>Atlas A3 训练系列产品/Atlas A3 推理系列产品<br>Atlas A2 训练系列产品/Atlas A2 推理系列产品 | |
| 17 | | [fixpipe_l0c2ub](./fixpipe_l0c2ub) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从L0C Buffer搬出到UB(Unified Buffer) | Ascend 950PR/Ascend 950DT | | 18 | | [fixpipe_l0c2ub](./fixpipe_l0c2ub) | 本样例介绍如何使用Fixpipe将矩阵乘的结果从L0C Buffer搬出到UB(Unified Buffer) | Ascend 950PR/Ascend 950DT | |
| @@ -12,6 +12,7 @@ This sample set introduces typical usage of different features of matrix computa | |||
| 12 | | Directory Name | Function Description | Supported Products | | 12 | | Directory Name | Function Description | Supported Products | |
| 13 | |--------------------------------------------------------------------------------------------| ---------------------------------------------------- | --- | | 13 | |--------------------------------------------------------------------------------------------| ---------------------------------------------------- | --- | |
| 14 | | [batch_matmul_tensor_api](./batch_matmul_tensor_api) | This sample implements Batch Matmul with Bias using the Tensor API programming mode | Ascend 950PR/Ascend 950DT | | 14 | | [batch_matmul_tensor_api](./batch_matmul_tensor_api) | This sample implements Batch Matmul with Bias using the Tensor API programming mode | Ascend 950PR/Ascend 950DT | |
| 15 | +| [conv2d_forward_tensor_api](./conv2d_forward_tensor_api) | This sample implements Conv2D Forward computation using the Tensor API programming mode, supporting NC1HWC0, NCHW, and NHWC GM input/output formats. It completes the full convolution flow via `CopyGM2L1` (on-the-fly format conversion), `CopyL12L0A` (Img2Col spatial unrolling), `Mmad` (matrix multiplication), and `CopyL0C2GM` | Ascend 950PR/Ascend 950DT | | ||
| 15 | | [batch_matmul](./batch_matmul) | This sample introduces batch matrix multiplication with float data type input and both left/right matrices non-transposed. The GM -> L1 path uses DataCopy with Nd2NzParams for batch data movement, the L0C -> GM and L0C -> L1 paths use Fixpipe for batch data movement, and L1 -> L0A / L0B movement plus Mmad matrix multiplication are executed batch times | Ascend 950PR/Ascend 950DT<br>Atlas A3 Training Series Products/Atlas A3 Inference Series Products<br>Atlas A2 Training Series Products/Atlas A2 Inference Series Products | | 16 | | [batch_matmul](./batch_matmul) | This sample introduces batch matrix multiplication with float data type input and both left/right matrices non-transposed. The GM -> L1 path uses DataCopy with Nd2NzParams for batch data movement, the L0C -> GM and L0C -> L1 paths use Fixpipe for batch data movement, and L1 -> L0A / L0B movement plus Mmad matrix multiplication are executed batch times | Ascend 950PR/Ascend 950DT<br>Atlas A3 Training Series Products/Atlas A3 Inference Series Products<br>Atlas A2 Training Series Products/Atlas A2 Inference Series Products | |
| 16 | | [fixpipe_l0c2gm](./fixpipe_l0c2gm) | This sample introduces how to use Fixpipe to move matrix multiplication results from L0C Buffer to GM (Global Memory) | Ascend 950PR/Ascend 950DT<br>Atlas A3 Training Series Products/Atlas A3 Inference Series Products<br>Atlas A2 Training Series Products/Atlas A2 Inference Series Products | | 17 | | [fixpipe_l0c2gm](./fixpipe_l0c2gm) | This sample introduces how to use Fixpipe to move matrix multiplication results from L0C Buffer to GM (Global Memory) | Ascend 950PR/Ascend 950DT<br>Atlas A3 Training Series Products/Atlas A3 Inference Series Products<br>Atlas A2 Training Series Products/Atlas A2 Inference Series Products | |
| 17 | | [fixpipe_l0c2l1](./fixpipe_l0c2l1) | This sample introduces how to use Fixpipe to move matrix multiplication results from L0C Buffer to L1 (L1 Buffer) | Ascend 950PR/Ascend 950DT<br>Atlas A3 Training Series Products/Atlas A3 Inference Series Products<br>Atlas A2 Training Series Products/Atlas A2 Inference Series Products | | 18 | | [fixpipe_l0c2l1](./fixpipe_l0c2l1) | This sample introduces how to use Fixpipe to move matrix multiplication results from L0C Buffer to L1 (L1 Buffer) | Ascend 950PR/Ascend 950DT<br>Atlas A3 Training Series Products/Atlas A3 Inference Series Products<br>Atlas A2 Training Series Products/Atlas A2 Inference Series Products | |
| @@ -0,0 +1,33 @@ | |||
| 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 | +set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu, sim") | ||
| 13 | +set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510") | ||
| 14 | + | ||
| 15 | +find_package(ASC REQUIRED) | ||
| 16 | + | ||
| 17 | +project(kernel_samples LANGUAGES ASC CXX) | ||
| 18 | + | ||
| 19 | +add_executable(demo | ||
| 20 | + conv2d_forward_tensor_api.asc | ||
| 21 | +) | ||
| 22 | + | ||
| 23 | +# 场景参数(通过命令行传入) | ||
| 24 | +# SCENARIO_NUM: 输入/输出 GM 格式场景编号 | ||
| 25 | +# 0 - GM 输入输出均为 NC1HWC0 | ||
| 26 | +# 1 - GM 输入输出均为 NCHW | ||
| 27 | +# 2 - GM 输入输出均为 NHWC | ||
| 28 | +set(SCENARIO_NUM "0" CACHE STRING "Scenario number (0=NC1HWC0, 1=NCHW, 2=NHWC)") | ||
| 29 | +add_definitions(-DSCENARIO_NUM=${SCENARIO_NUM}) | ||
| 30 | + | ||
| 31 | +target_compile_options(demo PRIVATE | ||
| 32 | + $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}> | ||
| 33 | +) | ||
| @@ -0,0 +1,149 @@ | |||
| 1 | +# Conv2D Forward Tensor API 样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
| 4 | + | ||
| 5 | +本样例介绍如何使用Tensor API实现Conv2D Forward计算,展示FeatureMap从Global Memory搬入L1 Buffer、通过`CopyL12L0A`(Img2Col)完成空间展开、使用`Mmad`进行矩阵乘累加,并通过`CopyL0C2GM`将结果搬回Global Memory的完整流程。 | ||
| 6 | + | ||
| 7 | +本样例支持三种Global Memory输入/输出数据格式(NC1HWC0、NCHW、NHWC),通过编译时参数`SCENARIO_NUM`切换。选用3x3卷积核、padding、stride=2、dilation=2和多C1通道组合,演示常见卷积场景和Tensor API接口使用。 | ||
| 8 | + | ||
| 9 | +## 本样例支持的产品及CANN软件版本 | ||
| 10 | + | ||
| 11 | +| 产品 | CANN软件版本 | | ||
| 12 | +|------|-------------| | ||
| 13 | +| Ascend 950PR/Ascend 950DT | >= CANN 9.1.0 | | ||
| 14 | + | ||
| 15 | +## 目录结构介绍 | ||
| 16 | + | ||
| 17 | +```text | ||
| 18 | +├── conv2d_forward_tensor_api | ||
| 19 | +│ ├── scripts | ||
| 20 | +│ │ ├── gen_data.py // 输入数据和真值数据生成脚本 | ||
| 21 | +│ │ └── verify_result.py // 验证输出数据和真值数据是否一致的验证脚本 | ||
| 22 | +│ ├── CMakeLists.txt // 编译工程文件 | ||
| 23 | +│ ├── data_utils.h // 数据读入写出函数 | ||
| 24 | +│ ├── conv2d_forward_tensor_api.asc // Ascend C Tensor API样例实现与调用样例 | ||
| 25 | +│ └── README.md // 样例说明文档 | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +## 样例规格 | ||
| 29 | + | ||
| 30 | +本样例固定使用如下Conv2D规格,核函数名为 `conv2d_forward_tensor_api_custom`。每个AI Core处理一个batch,共使用4个AI Core。 | ||
| 31 | + | ||
| 32 | +<a name="表1"></a> | ||
| 33 | +<table border="2" align="center"> | ||
| 34 | +<caption style="font-weight: normal;"> | ||
| 35 | + <span style="font-weight: bold; font-size: 1.2em;">📌 表1:样例规格</span></caption> | ||
| 36 | +<tr><td rowspan="1" align="center">参数</td><td align="center">取值</td><td align="center">说明</td></tr> | ||
| 37 | +<tr><td align="center">FeatureMap</td><td align="center">[N, H, W, C] = [4, 9, 9, 32]</td><td>Global Memory输入为half类型,按场景选择NC1HWC0/NCHW/NHWC排布</td></tr> | ||
| 38 | +<tr><td align="center">Weight</td><td align="center">[Cout, C, Kh, Kw] = [16, 32, 3, 3]</td><td>Global Memory输入为half类型,按[K, Cout]二维排布展开</td></tr> | ||
| 39 | +<tr><td align="center">卷积参数</td><td align="center">stride = [2, 2],dilation = [2, 2],padding = [2, 2, 2, 2],padValue = 1</td><td>padding顺序为[top, bottom, left, right]</td></tr> | ||
| 40 | +<tr><td align="center">Output</td><td align="center">[N, HOut, WOut, Cout] = [4, 5, 5, 16]</td><td>Global Memory输出为half类型,格式与输入一致</td></tr> | ||
| 41 | +</table> | ||
| 42 | + | ||
| 43 | +其中,`C1`和`C0`是FeatureMap在L1 Buffer上采用NC1HWC0格式时的通道拆分维度。`C0`表示每个通道块包含的元素个数,本样例中为16;`C1`表示通道块个数。由于`C = 32`,因此`C1 = C / C0 = 2`、`C0 = 16`。 | ||
| 44 | + | ||
| 45 | +有效卷积核尺寸计算如下: | ||
| 46 | + | ||
| 47 | +$$ | ||
| 48 | +K_{\text{effective}} = dilation \times (K_h - 1) + 1 = 2 \times (3 - 1) + 1 = 5 | ||
| 49 | +$$ | ||
| 50 | + | ||
| 51 | +输出H/W计算如下: | ||
| 52 | + | ||
| 53 | +$$ | ||
| 54 | +\begin{aligned} | ||
| 55 | +H_{out} &= \frac{H + pad_{top} + pad_{bottom} - K_{\text{effective}}}{stride_h} + 1 = \frac{9 + 2 + 2 - 5}{2} + 1 = 5 \\ | ||
| 56 | +W_{out} &= \frac{W + pad_{left} + pad_{right} - K_{\text{effective}}}{stride_w} + 1 = \frac{9 + 2 + 2 - 5}{2} + 1 = 5 | ||
| 57 | +\end{aligned} | ||
| 58 | +$$ | ||
| 59 | + | ||
| 60 | +矩阵乘规格为`M = HOut * WOut = 25`,`K = C * Kh * Kw = 288`,`N = Cout = 16`。 | ||
| 61 | + | ||
| 62 | +## 场景详细说明 | ||
| 63 | + | ||
| 64 | +本样例通过编译参数`SCENARIO_NUM`选择不同的Global Memory数据格式,`SCENARIO_NUM`不同取值对应的含义如下表所示。 | ||
| 65 | + | ||
| 66 | +<a name="表2"></a> | ||
| 67 | +<table border="2" align="center"> | ||
| 68 | +<caption style="font-weight: normal;"> | ||
| 69 | + <span style="font-weight: bold; font-size: 1.2em;">📌 表2:SCENARIO_NUM不同取值的含义</span></caption> | ||
| 70 | +<tr><td rowspan="1" align="center">SCENARIO_NUM</td><td align="center">FeatureMap输入布局</td><td align="center">Output输出布局</td><td align="center">Global Memory→L1 Buffer转换</td><td align="center">L0C Buffer→Global Memory转换</td></tr> | ||
| 71 | +<tr><td align="center">0</td><td align="center">NC1HWC0 [1, C1, H, W, C0]</td><td align="center">NC1HWC0 [1, Cout_C1, HOut, WOut, C0]</td><td align="center">NC1HWC0直搬</td><td align="center">NC1HWC0直搬</td></tr> | ||
| 72 | +<tr><td align="center">1</td><td align="center">NCHW [1, C, H, W]</td><td align="center">NCHW [1, Cout, HOut, WOut]</td><td align="center">NCHW→NC1HWC0(dn2nz)</td><td align="center">NC1HWC0→NCHW(nz2dn)</td></tr> | ||
| 73 | +<tr><td align="center">2</td><td align="center">NHWC [1, H, W, C]</td><td align="center">NHWC [1, HOut, WOut, Cout]</td><td align="center">NHWC→NC1HWC0(nd2nz)</td><td align="center">NC1HWC0→NHWC(nz2nd)</td></tr> | ||
| 74 | +</table> | ||
| 75 | + | ||
| 76 | +**场景0:NC1HWC0输入输出** | ||
| 77 | +- 输入:FeatureMap [1, 2, 9, 9, 16] half类型,NC1HWC0格式;Weight [K, Cout] half类型 | ||
| 78 | +- 输出:Output [1, 1, 5, 5, 16] half类型,NC1HWC0格式 | ||
| 79 | +- 实现:Global Memory→L1 Buffer使用`CopyGM2L1`直搬NC1HWC0数据,L0C Buffer→Global Memory使用`CopyL0C2GM`直搬 | ||
| 80 | + | ||
| 81 | +**场景1:NCHW输入输出** | ||
| 82 | +- 输入:FeatureMap [1, 32, 9, 9] half类型,NCHW格式;Weight [K, Cout] half类型 | ||
| 83 | +- 输出:Output [1, 16, 5, 5] half类型,NCHW格式 | ||
| 84 | +- 实现:Global Memory→L1 Buffer使用`CopyGM2L1`将NCHW随路转换为NC1HWC0(dn2nz),L0C Buffer→Global Memory使用`CopyL0C2GM`将NC1HWC0转换为NCHW(nz2dn) | ||
| 85 | + | ||
| 86 | +**场景2:NHWC输入输出** | ||
| 87 | +- 输入:FeatureMap [1, 9, 9, 32] half类型,NHWC格式;Weight [K, Cout] half类型 | ||
| 88 | +- 输出:Output [1, 5, 5, 16] half类型,NHWC格式 | ||
| 89 | +- 实现:Global Memory→L1 Buffer使用`CopyGM2L1`将NHWC随路转换为NC1HWC0(nd2nz),L0C Buffer→Global Memory使用`CopyL0C2GM`将NC1HWC0转换为NHWC(nz2nd) | ||
| 90 | + | ||
| 91 | +核心流程如下: | ||
| 92 | + | ||
| 93 | +1. 将单batch FeatureMap从Global Memory搬到L1 Buffer,调用Copy接口通过`CopyGM2L1` `Operation`搬运能力,统一为NC1HWC0布局。`CopyGM2L1`根据Global Memory源端格式自动路由搬运路径(NCHW走dn2nz、NHWC走nd2nz、NC1HWC0直搬)。同时将Weight从Global Memory搬运到L1 Buffer,完成ND到ZN格式转换。 | ||
| 94 | +2. 将L1 Buffer上的FeatureMap执行img2col空间展开搬到L0A Buffer,调用Copy接口通过`CopyL12L0A` `Operation`的Img2Col搬运能力,完成3x3卷积核在stride=2、dilation=2下的展开与padding填充。 | ||
| 95 | +3. 将L1 Buffer上的Weight搬到L0B Buffer,调用Copy接口通过`CopyL12L0B` `Operation`搬运能力。 | ||
| 96 | +4. 使用 `Mmad` 完成矩阵乘计算,L0A Buffer(NZ) × L0B Buffer(ZN) → L0C Buffer(NZ)。 | ||
| 97 | +5. 使用 `CopyL0C2GM` 将L0C Buffer结果按目的格式搬回Global Memory(NCHW走nz2dn、NHWC走nz2nd、NC1HWC0直搬)。 | ||
| 98 | + | ||
| 99 | +## 编译运行 | ||
| 100 | + | ||
| 101 | +在本样例根目录下执行如下步骤,编译并执行样例。 | ||
| 102 | + | ||
| 103 | +- 配置环境变量 | ||
| 104 | + | ||
| 105 | + 请根据当前环境上CANN开发套件包的[安装方式](../../../../../docs/zh/quick_start.md#prepare&install),配置环境变量。 | ||
| 106 | + ```bash | ||
| 107 | + source ${install_path}/cann/set_env.sh | ||
| 108 | + ``` | ||
| 109 | + | ||
| 110 | + > **说明:** `${install_path}`为CANN包安装目录,未指定安装目录时默认安装至`/usr/local/Ascend`下。 | ||
| 111 | + | ||
| 112 | +- 样例执行 | ||
| 113 | + | ||
| 114 | + 在本样例目录下执行如下命令。 | ||
| 115 | + ```bash | ||
| 116 | + SCENARIO_NUM=0 | ||
| 117 | + mkdir -p build && cd build; # 创建并进入build目录 | ||
| 118 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # 编译工程(默认dav-3510 NPU模式) | ||
| 119 | + python3 ../scripts/gen_data.py --scenario=$SCENARIO_NUM # 生成测试输入数据 | ||
| 120 | + ./demo # 执行编译生成的可执行程序,执行样例 | ||
| 121 | + python3 ../scripts/verify_result.py output/output.bin output/golden.bin # 验证输出结果是否正确 | ||
| 122 | + ``` | ||
| 123 | + | ||
| 124 | + 切换输入/输出格式:将`-DSCENARIO_NUM=0`改为`1`(NCHW)或`2`(NHWC),重新编译运行即可。 | ||
| 125 | + | ||
| 126 | + 使用NPU仿真模式时,添加`-DCMAKE_ASC_RUN_MODE=sim`参数即可。 | ||
| 127 | + | ||
| 128 | + 示例如下: | ||
| 129 | + | ||
| 130 | + ```bash | ||
| 131 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU仿真模式 | ||
| 132 | + ``` | ||
| 133 | + | ||
| 134 | + > **注意:** 切换编译模式前需清理cmake缓存,可在build目录下执行`rm CMakeCache.txt`后重新cmake。 | ||
| 135 | + | ||
| 136 | +- 编译选项说明 | ||
| 137 | + | ||
| 138 | + | 选项 | 可选值 | 说明 | | ||
| 139 | + |------|--------|------| | ||
| 140 | + | `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 运行模式:NPU运行、NPU仿真 | | ||
| 141 | + | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU架构:dav-3510对应Ascend 950PR/Ascend 950DT | | ||
| 142 | + | `SCENARIO_NUM` | `0`(默认)、`1`、`2` | 场景编号:0=NC1HWC0,1=NCHW,2=NHWC | | ||
| 143 | + | ||
| 144 | +- 执行结果 | ||
| 145 | + | ||
| 146 | + 执行结果如下,说明精度对比成功。 | ||
| 147 | + ```bash | ||
| 148 | + test pass! | ||
| 149 | + ``` | ||
| @@ -0,0 +1,149 @@ | |||
| 1 | +# Conv2D Forward Tensor API Sample | ||
| 2 | + | ||
| 3 | +## Overview | ||
| 4 | + | ||
| 5 | +This sample demonstrates how to implement Conv2D Forward computation using the Tensor API. It shows the complete pipeline: moving the FeatureMap from Global Memory to L1 Buffer, performing spatial unfolding via `CopyL12L0A` (Img2Col), accumulating matrix multiplication with `Mmad`, and moving results back to Global Memory via `CopyL0C2GM`. | ||
| 6 | + | ||
| 7 | +This sample supports three Global Memory input/output data formats (NC1HWC0, NCHW, NHWC), switched via the compile-time parameter `SCENARIO_NUM`. It uses a 3x3 convolution kernel with padding, stride=2, dilation=2, and multiple C1 channel combinations to demonstrate common convolution scenarios and Tensor API usage. | ||
| 8 | + | ||
| 9 | +## Supported Products and CANN Software Versions | ||
| 10 | + | ||
| 11 | +| Product | CANN Software Version | | ||
| 12 | +|---------|----------------------| | ||
| 13 | +| Ascend 950PR/Ascend 950DT | >= CANN 9.1.0 | | ||
| 14 | + | ||
| 15 | +## Directory Structure | ||
| 16 | + | ||
| 17 | +```text | ||
| 18 | +├── conv2d_forward_tensor_api | ||
| 19 | +│ ├── scripts | ||
| 20 | +│ │ ├── gen_data.py // Script for generating input and golden data | ||
| 21 | +│ │ └── verify_result.py // Script for verifying output against golden data | ||
| 22 | +│ ├── CMakeLists.txt // Build project file | ||
| 23 | +│ ├── data_utils.h // Data read/write functions | ||
| 24 | +│ ├── conv2d_forward_tensor_api.asc // Ascend C Tensor API sample implementation and invocation | ||
| 25 | +│ └── README.md // Sample documentation | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +## Sample Specifications | ||
| 29 | + | ||
| 30 | +This sample uses the following fixed Conv2D specification. The kernel function name is `conv2d_forward_tensor_api_custom`. Each AI Core processes one batch, and 4 AI Cores are used in total. | ||
| 31 | + | ||
| 32 | +<a name="table1"></a> | ||
| 33 | +<table border="2" align="center"> | ||
| 34 | +<caption style="font-weight: normal;"> | ||
| 35 | + <span style="font-weight: bold; font-size: 1.2em;">📌 Table 1: Sample Specifications</span></caption> | ||
| 36 | +<tr><td rowspan="1" align="center">Parameter</td><td align="center">Value</td><td align="center">Description</td></tr> | ||
| 37 | +<tr><td align="center">FeatureMap</td><td align="center">[N, H, W, C] = [4, 9, 9, 32]</td><td>Global Memory input is half type, layout selected per scenario: NC1HWC0/NCHW/NHWC</td></tr> | ||
| 38 | +<tr><td align="center">Weight</td><td align="center">[Cout, C, Kh, Kw] = [16, 32, 3, 3]</td><td>Global Memory input is half type, laid out as [K, Cout] in 2D</td></tr> | ||
| 39 | +<tr><td align="center">Convolution params</td><td align="center">stride = [2, 2], dilation = [2, 2], padding = [2, 2, 2, 2], padValue = 1</td><td>padding order is [top, bottom, left, right]</td></tr> | ||
| 40 | +<tr><td align="center">Output</td><td align="center">[N, HOut, WOut, Cout] = [4, 5, 5, 16]</td><td>Global Memory output is half type, same format as input</td></tr> | ||
| 41 | +</table> | ||
| 42 | + | ||
| 43 | +Here, `C1` and `C0` are the channel split dimensions of the FeatureMap when using the NC1HWC0 layout on the L1 Buffer. `C0` represents the number of elements per channel block, which is 16 in this sample; `C1` represents the number of channel blocks. Since `C = 32`, we have `C1 = C / C0 = 2` and `C0 = 16`. | ||
| 44 | + | ||
| 45 | +The effective kernel size is calculated as: | ||
| 46 | + | ||
| 47 | +$$ | ||
| 48 | +K_{\text{effective}} = dilation \times (K_h - 1) + 1 = 2 \times (3 - 1) + 1 = 5 | ||
| 49 | +$$ | ||
| 50 | + | ||
| 51 | +The output H/W is calculated as: | ||
| 52 | + | ||
| 53 | +$$ | ||
| 54 | +\begin{aligned} | ||
| 55 | +H_{out} &= \frac{H + pad_{top} + pad_{bottom} - K_{\text{effective}}}{stride_h} + 1 = \frac{9 + 2 + 2 - 5}{2} + 1 = 5 \\ | ||
| 56 | +W_{out} &= \frac{W + pad_{left} + pad_{right} - K_{\text{effective}}}{stride_w} + 1 = \frac{9 + 2 + 2 - 5}{2} + 1 = 5 | ||
| 57 | +\end{aligned} | ||
| 58 | +$$ | ||
| 59 | + | ||
| 60 | +The matrix multiplication specification is `M = HOut * WOut = 25`, `K = C * Kh * Kw = 288`, `N = Cout = 16`. | ||
| 61 | + | ||
| 62 | +## Scenario Details | ||
| 63 | + | ||
| 64 | +This sample selects different Global Memory data formats via the compile parameter `SCENARIO_NUM`. The meanings of different `SCENARIO_NUM` values are shown in the table below. | ||
| 65 | + | ||
| 66 | +<a name="table2"></a> | ||
| 67 | +<table border="2" align="center"> | ||
| 68 | +<caption style="font-weight: normal;"> | ||
| 69 | + <span style="font-weight: bold; font-size: 1.2em;">📌 Table 2: Meanings of SCENARIO_NUM Values</span></caption> | ||
| 70 | +<tr><td rowspan="1" align="center">SCENARIO_NUM</td><td align="center">FeatureMap Input Layout</td><td align="center">Output Layout</td><td align="center">Global Memory → L1 Buffer Conversion</td><td align="center">L0C Buffer → Global Memory Conversion</td></tr> | ||
| 71 | +<tr><td align="center">0</td><td align="center">NC1HWC0 [1, C1, H, W, C0]</td><td align="center">NC1HWC0 [1, Cout_C1, HOut, WOut, C0]</td><td align="center">NC1HWC0 direct copy</td><td align="center">NC1HWC0 direct copy</td></tr> | ||
| 72 | +<tr><td align="center">1</td><td align="center">NCHW [1, C, H, W]</td><td align="center">NCHW [1, Cout, HOut, WOut]</td><td align="center">NCHW → NC1HWC0 (dn2nz)</td><td align="center">NC1HWC0 → NCHW (nz2dn)</td></tr> | ||
| 73 | +<tr><td align="center">2</td><td align="center">NHWC [1, H, W, C]</td><td align="center">NHWC [1, HOut, WOut, Cout]</td><td align="center">NHWC → NC1HWC0 (nd2nz)</td><td align="center">NC1HWC0 → NHWC (nz2nd)</td></tr> | ||
| 74 | +</table> | ||
| 75 | + | ||
| 76 | +**Scenario 0: NC1HWC0 Input/Output** | ||
| 77 | +- Input: FeatureMap [1, 2, 9, 9, 16] half type, NC1HWC0 format; Weight [K, Cout] half type | ||
| 78 | +- Output: Output [1, 1, 5, 5, 16] half type, NC1HWC0 format | ||
| 79 | +- Implementation: Global Memory → L1 Buffer uses `CopyGM2L1` to directly copy NC1HWC0 data; L0C Buffer → Global Memory uses `CopyL0C2GM` direct copy | ||
| 80 | + | ||
| 81 | +**Scenario 1: NCHW Input/Output** | ||
| 82 | +- Input: FeatureMap [1, 32, 9, 9] half type, NCHW format; Weight [K, Cout] half type | ||
| 83 | +- Output: Output [1, 16, 5, 5] half type, NCHW format | ||
| 84 | +- Implementation: Global Memory → L1 Buffer uses `CopyGM2L1` to convert NCHW to NC1HWC0 on the fly (dn2nz); L0C Buffer → Global Memory uses `CopyL0C2GM` to convert NC1HWC0 to NCHW (nz2dn) | ||
| 85 | + | ||
| 86 | +**Scenario 2: NHWC Input/Output** | ||
| 87 | +- Input: FeatureMap [1, 9, 9, 32] half type, NHWC format; Weight [K, Cout] half type | ||
| 88 | +- Output: Output [1, 5, 5, 16] half type, NHWC format | ||
| 89 | +- Implementation: Global Memory → L1 Buffer uses `CopyGM2L1` to convert NHWC to NC1HWC0 on the fly (nd2nz); L0C Buffer → Global Memory uses `CopyL0C2GM` to convert NC1HWC0 to NHWC (nz2nd) | ||
| 90 | + | ||
| 91 | +Core workflow: | ||
| 92 | + | ||
| 93 | +1. Move the single-batch FeatureMap from Global Memory to L1 Buffer by calling the Copy interface via the `CopyGM2L1` `Operation` capability, unifying to the NC1HWC0 layout. `CopyGM2L1` auto-routes the copy path based on the Global Memory source format (NCHW via dn2nz, NHWC via nd2nz, NC1HWC0 direct). Simultaneously, move the Weight from Global Memory to L1 Buffer, performing ND-to-ZN format conversion. | ||
| 94 | +2. Perform img2col spatial unfolding of the FeatureMap on L1 Buffer to L0A Buffer, calling the Copy interface via the `CopyL12L0A` `Operation` Img2Col capability, completing the 3x3 kernel unfolding and padding under stride=2, dilation=2. | ||
| 95 | +3. Move the Weight from L1 Buffer to L0B Buffer, calling the Copy interface via the `CopyL12L0B` `Operation` capability. | ||
| 96 | +4. Use `Mmad` to perform matrix multiplication: L0A Buffer(NZ) × L0B Buffer(ZN) → L0C Buffer(NZ). | ||
| 97 | +5. Use `CopyL0C2GM` to move the L0C Buffer result back to Global Memory in the target format (NCHW via nz2dn, NHWC via nz2nd, NC1HWC0 direct). | ||
| 98 | + | ||
| 99 | +## Build and Run | ||
| 100 | + | ||
| 101 | +Execute the following steps in the sample root directory to build and run the sample. | ||
| 102 | + | ||
| 103 | +- Configure environment variables | ||
| 104 | + | ||
| 105 | + Refer to the CANN development kit [installation guide](../../../../../docs/en/quick_start.md#prepare&install) to configure environment variables. | ||
| 106 | + ```bash | ||
| 107 | + source ${install_path}/cann/set_env.sh | ||
| 108 | + ``` | ||
| 109 | + | ||
| 110 | + > **Note:** `${install_path}` is the CANN installation directory. If not specified, it defaults to `/usr/local/Ascend`. | ||
| 111 | + | ||
| 112 | +- Run the sample | ||
| 113 | + | ||
| 114 | + Execute the following commands in the sample directory. | ||
| 115 | + ```bash | ||
| 116 | + SCENARIO_NUM=0 | ||
| 117 | + mkdir -p build && cd build; # Create and enter the build directory | ||
| 118 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # Build the project (default dav-3510 NPU mode) | ||
| 119 | + python3 ../scripts/gen_data.py --scenario=$SCENARIO_NUM # Generate test input data | ||
| 120 | + ./demo # Run the compiled executable | ||
| 121 | + python3 ../scripts/verify_result.py output/output.bin output/golden.bin # Verify output correctness | ||
| 122 | + ``` | ||
| 123 | + | ||
| 124 | + To switch input/output format: change `-DSCENARIO_NUM=0` to `1` (NCHW) or `2` (NHWC), then rebuild and run. | ||
| 125 | + | ||
| 126 | + To use NPU simulation mode, add the `-DCMAKE_ASC_RUN_MODE=sim` parameter. | ||
| 127 | + | ||
| 128 | + Example: | ||
| 129 | + | ||
| 130 | + ```bash | ||
| 131 | + cmake -DSCENARIO_NUM=$SCENARIO_NUM -DCMAKE_ASC_RUN_MODE=sim -DCMAKE_ASC_ARCHITECTURES=dav-3510 ..;make -j; # NPU simulation mode | ||
| 132 | + ``` | ||
| 133 | + | ||
| 134 | + > **Note:** Before switching build modes, clean the cmake cache by running `rm CMakeCache.txt` in the build directory, then re-run cmake. | ||
| 135 | + | ||
| 136 | +- Build options | ||
| 137 | + | ||
| 138 | + | Option | Values | Description | | ||
| 139 | + |--------|--------|-------------| | ||
| 140 | + | `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | Run mode: NPU execution, NPU simulation | | ||
| 141 | + | `CMAKE_ASC_ARCHITECTURES` | `dav-3510` | NPU architecture: dav-3510 corresponds to Ascend 950PR/Ascend 950DT | | ||
| 142 | + | `SCENARIO_NUM` | `0` (default), `1`, `2` | Scenario number: 0=NC1HWC0, 1=NCHW, 2=NHWC | | ||
| 143 | + | ||
| 144 | +- Execution result | ||
| 145 | + | ||
| 146 | + The following output indicates successful precision comparison. | ||
| 147 | + ```bash | ||
| 148 | + test pass! | ||
| 149 | + ``` | ||
| @@ -0,0 +1,247 @@ | |||
| 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 conv2d_forward_tensor_api.asc | ||
| 13 | + * \brief 使用 Tensor API 实现的极简 Conv2D Forward 样例: | ||
| 14 | + * GM(NCHW/NHWC/NC1HWC0) -> L1(NC1HWC0) -> L0A(img2col NZ) / L0B(NZ) -> L0C(NZ) -> GM(NCHW/NHWC/NC1HWC0)。 | ||
| 15 | + * 输入输出的 GM 格式由 SCENARIO_NUM 控制(编译时传入,见 CMakeLists.txt): | ||
| 16 | + * 0 - NC1HWC0 输入输出 | ||
| 17 | + * 1 - NCHW 输入输出 | ||
| 18 | + * 2 - NHWC 输入输出 | ||
| 19 | + * L1 fmap 统一为 NC1HWC0,由 GM->L1 按源格式路由(NCHW->NC1HWC0 走 dn2nz、 | ||
| 20 | + * NHWC->NC1HWC0 走 nd2nz、NC1HWC0->NC1HWC0 直搬);输出同理由 L0C->GM 按目的格式路由。 | ||
| 21 | + */ | ||
| 22 | +#include "acl/acl.h" | ||
| 23 | +#include "tensor_api/tensor.h" | ||
| 24 | +#include "basic_api/kernel_basic_intf.h" | ||
| 25 | +#include "basic_api/kernel_operator_block_sync_intf.h" | ||
| 26 | +#include "data_utils.h" | ||
| 27 | + | ||
| 28 | +constexpr uint32_t BLOCK_DIM = 4; | ||
| 29 | +constexpr uint32_t N = 4; | ||
| 30 | +constexpr uint32_t C1 = 2; | ||
| 31 | +constexpr uint32_t C0 = 16; | ||
| 32 | +constexpr uint32_t CIN = C1 * C0; // 32 | ||
| 33 | +constexpr uint32_t COUT = 16; | ||
| 34 | +constexpr uint32_t H = 9; | ||
| 35 | +constexpr uint32_t W = 9; | ||
| 36 | +constexpr uint32_t KH = 3; | ||
| 37 | +constexpr uint32_t KW = 3; | ||
| 38 | +constexpr uint32_t STRIDE_H = 2; | ||
| 39 | +constexpr uint32_t STRIDE_W = 2; | ||
| 40 | +constexpr uint32_t DILATION_H = 2; | ||
| 41 | +constexpr uint32_t DILATION_W = 2; | ||
| 42 | +constexpr uint32_t PAD_LEFT = 2; | ||
| 43 | +constexpr uint32_t PAD_RIGHT = 2; | ||
| 44 | +constexpr uint32_t PAD_TOP = 2; | ||
| 45 | +constexpr uint32_t PAD_BOTTOM = 2; | ||
| 46 | +constexpr uint32_t PAD_VALUE = 1; | ||
| 47 | + | ||
| 48 | +constexpr uint32_t HOUT = (H + PAD_TOP + PAD_BOTTOM - DILATION_H * (KH - 1) - 1) / STRIDE_H + 1; // 5 | ||
| 49 | +constexpr uint32_t WOUT = (W + PAD_LEFT + PAD_RIGHT - DILATION_W * (KW - 1) - 1) / STRIDE_W + 1; // 5 | ||
| 50 | + | ||
| 51 | +constexpr uint32_t M = HOUT * WOUT; // img2col 输出行数:25 | ||
| 52 | +constexpr uint32_t K = CIN * KH * KW; // img2col 输出列数:288 | ||
| 53 | +constexpr uint32_t COUT_N = COUT; // GEMM 的 N:16 | ||
| 54 | +constexpr uint32_t COUT_C1 = COUT / C0; // 输出 NC1HWC0 的 C1:1 | ||
| 55 | +constexpr uint32_t CUBE_BLOCK = 16; | ||
| 56 | +constexpr uint32_t M_ALIGN = (M + CUBE_BLOCK - 1) / CUBE_BLOCK * CUBE_BLOCK; // 32 | ||
| 57 | + | ||
| 58 | +constexpr uint32_t FMAP_BATCH_SIZE = H * W * CIN; // 单 batch fmap 元素数 | ||
| 59 | +constexpr uint32_t WEIGHT_SIZE = K * COUT_N; // weight 元素数([K, Cout]) | ||
| 60 | +constexpr uint32_t OUT_BATCH_SIZE = HOUT * WOUT * COUT; // 单 batch 输出元素数 | ||
| 61 | + | ||
| 62 | +extern "C" __global__ __cube__ void conv2d_forward_tensor_api_custom( | ||
| 63 | + __gm__ half* fmap, __gm__ half* weight, __gm__ half* out) | ||
| 64 | +{ | ||
| 65 | + AscendC::InitSocState(); | ||
| 66 | + using namespace AscendC::Te; | ||
| 67 | + | ||
| 68 | + // 场景编号:0=NC1HWC0, 1=NCHW, 2=NHWC(编译时由 SCENARIO_NUM 传入)。 | ||
| 69 | + constexpr uint32_t scenarioNum = SCENARIO_NUM; | ||
| 70 | + | ||
| 71 | + // 每个 cube 核处理一个 batch(N=4,BLOCK_DIM=4)。 | ||
| 72 | + uint32_t batchIdx = AscendC::GetBlockIdx(); | ||
| 73 | + if (batchIdx >= N) { | ||
| 74 | + return; | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + __cbuf__ half l1FmapBuf[FMAP_BATCH_SIZE]; | ||
| 78 | + __cbuf__ half l1WeightBuf[WEIGHT_SIZE]; | ||
| 79 | + __ca__ half l0ABuf[M_ALIGN * K]; | ||
| 80 | + __cb__ half l0BBuf[K * COUT_N]; | ||
| 81 | + __cc__ float l0CBuf[M_ALIGN * COUT_N]; | ||
| 82 | + | ||
| 83 | + // GM fmap 按 SCENARIO_NUM 构造:NCHW(1,C,H,W) / NHWC(1,H,W,C) / NC1HWC0(1,C1,H,W,C0)。 | ||
| 84 | + // CopyGM2L1 按源 pattern 路由(NCHW->NC1HWC0 走 dn2nz、NHWC->NC1HWC0 走 nd2nz、NC1HWC0 直搬)。 | ||
| 85 | + // 每个核取本 batch 对应的 GM 偏移。L1 fmap 统一为 NC1HWC0。 | ||
| 86 | + auto l1FmapTensor = MakeTensor( | ||
| 87 | + MakeMemPtr(l1FmapBuf), | ||
| 88 | + MakeFrameLayout<NC1HWC0LayoutPtn>( | ||
| 89 | + 1, static_cast<int32_t>(C1), static_cast<int32_t>(H), static_cast<int32_t>(W), static_cast<int32_t>(C0))); | ||
| 90 | + | ||
| 91 | + // weight GM 已按 [K, Cout] 行优先摆放(K 序 = (C1, KH, KW, C0)),用 NDExtLayoutPtn(行优先)与之一致。 | ||
| 92 | + auto gmWeightTensor = MakeTensor(MakeMemPtr(weight), MakeFrameLayout<NDExtLayoutPtn>(K, COUT_N)); | ||
| 93 | + auto l1WeightTensor = MakeTensor(MakeMemPtr(l1WeightBuf), MakeFrameLayout<ZNLayoutPtn, half>(K, COUT_N)); | ||
| 94 | + | ||
| 95 | + // L0A/L0C 容量按 M_ALIGN 对齐,但 Mmad 的 m 用实际 M(硬件按实际 m 计算有效行)。 | ||
| 96 | + auto l0ATensor = MakeTensor(MakeMemPtr(l0ABuf), MakeFrameLayout<NZLayoutPtn, half>(M_ALIGN, K)); | ||
| 97 | + auto l0BTensor = MakeTensor(MakeMemPtr(l0BBuf), MakeFrameLayout<ZNLayoutPtn, half>(K, COUT_N)); | ||
| 98 | + auto l0CTensor = MakeTensor(MakeMemPtr(l0CBuf), MakeFrameLayout<NZLayoutPtn>(M_ALIGN, COUT_N)); | ||
| 99 | + | ||
| 100 | + auto copyGM2L1Atom = MakeCopy(CopyGM2L1{}, CopyGM2L1TraitDefault{}); | ||
| 101 | + auto copyImg2ColAtom = MakeCopy(CopyL12L0A{}, CopyL12L0ATraitDefault{}); | ||
| 102 | + auto copyL12L0BAtom = MakeCopy(CopyL12L0B{}, CopyL12L0BTraitDefault{}); | ||
| 103 | + auto copyL0C2GMAtom = MakeCopy(CopyL0C2GM{}, CopyL0C2GMTraitDefault{}); | ||
| 104 | + auto mmadAtom = MakeMmad(MmadOperation{}, MmadTraitDefault{}); | ||
| 105 | + | ||
| 106 | + // Mutex 槽位锁 ID(单缓冲:L1=0, L0=1, L0C=2)。 | ||
| 107 | + constexpr uint32_t L1_Index = 0; | ||
| 108 | + constexpr uint32_t L0_Index = 1; | ||
| 109 | + constexpr uint32_t L0C_Index = 2; | ||
| 110 | + | ||
| 111 | + // GM fmap -> L1(NC1HWC0):按 SCENARIO_NUM 构造 GM fmap layout 并搬运。 | ||
| 112 | + AscendC::Mutex::Lock<PIPE_MTE2>(L1_Index); | ||
| 113 | + auto gmFmapMem = MakeMemPtr(fmap + batchIdx * FMAP_BATCH_SIZE); | ||
| 114 | + if constexpr (scenarioNum == 1) { | ||
| 115 | + auto gmFmapTensor = MakeTensor( | ||
| 116 | + gmFmapMem, MakeFrameLayout<NCHWLayoutPtn>( | ||
| 117 | + 1, static_cast<int32_t>(CIN), static_cast<int32_t>(H), static_cast<int32_t>(W))); | ||
| 118 | + Copy(copyGM2L1Atom, l1FmapTensor, gmFmapTensor); | ||
| 119 | + } else if constexpr (scenarioNum == 2) { | ||
| 120 | + auto gmFmapTensor = MakeTensor( | ||
| 121 | + gmFmapMem, MakeFrameLayout<NHWCLayoutPtn>( | ||
| 122 | + 1, static_cast<int32_t>(H), static_cast<int32_t>(W), static_cast<int32_t>(CIN))); | ||
| 123 | + Copy(copyGM2L1Atom, l1FmapTensor, gmFmapTensor); | ||
| 124 | + } else { | ||
| 125 | + auto gmFmapTensor = MakeTensor( | ||
| 126 | + gmFmapMem, MakeFrameLayout<NC1HWC0LayoutPtn>( | ||
| 127 | + 1, static_cast<int32_t>(C1), static_cast<int32_t>(H), static_cast<int32_t>(W), | ||
| 128 | + static_cast<int32_t>(C0))); | ||
| 129 | + Copy(copyGM2L1Atom, l1FmapTensor, gmFmapTensor); | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + // weight: GM(ND) -> L1(ZN) | ||
| 133 | + Copy(copyGM2L1Atom, l1WeightTensor, gmWeightTensor); | ||
| 134 | + | ||
| 135 | + AscendC::Mutex::Unlock<PIPE_MTE2>(L1_Index); | ||
| 136 | + AscendC::Mutex::Lock<PIPE_MTE1>(L1_Index); | ||
| 137 | + | ||
| 138 | + Img2ColParams<half> img2colParams; | ||
| 139 | + img2colParams.filterW = KW; | ||
| 140 | + img2colParams.filterH = KH; | ||
| 141 | + img2colParams.mExtension = M; | ||
| 142 | + img2colParams.kExtension = K; | ||
| 143 | + img2colParams.strideW = STRIDE_W; | ||
| 144 | + img2colParams.strideH = STRIDE_H; | ||
| 145 | + img2colParams.dilationFilterW = DILATION_W; | ||
| 146 | + img2colParams.dilationFilterH = DILATION_H; | ||
| 147 | + img2colParams.padList[0] = PAD_LEFT; // left | ||
| 148 | + img2colParams.padList[1] = PAD_RIGHT; // right | ||
| 149 | + img2colParams.padList[2] = PAD_TOP; // top | ||
| 150 | + img2colParams.padList[3] = PAD_BOTTOM; // bottom | ||
| 151 | + img2colParams.padValue = PAD_VALUE; | ||
| 152 | + // L1(NC1HWC0) -> L0A(NZ, img2col 展开) | ||
| 153 | + AscendC::Mutex::Lock<PIPE_MTE1>(L0_Index); | ||
| 154 | + Copy(copyImg2ColAtom.with(img2colParams), l0ATensor, l1FmapTensor); | ||
| 155 | + // L1(NZ) -> L0B(ZN) | ||
| 156 | + Copy(copyL12L0BAtom, l0BTensor, l1WeightTensor); | ||
| 157 | + AscendC::Mutex::Unlock<PIPE_MTE1>(L0_Index); | ||
| 158 | + AscendC::Mutex::Unlock<PIPE_MTE1>(L1_Index); | ||
| 159 | + | ||
| 160 | + AscendC::Mutex::Lock<PIPE_M>(L0_Index); | ||
| 161 | + // Mmad:L0A(NZ,M,K) x L0B(ZN,K,Cout) -> L0C(NZ,M,Cout) | ||
| 162 | + MmadParams mmadParams; | ||
| 163 | + mmadParams.m = M; | ||
| 164 | + mmadParams.n = COUT_N; | ||
| 165 | + mmadParams.k = K; | ||
| 166 | + mmadParams.cmatrixInitVal = true; | ||
| 167 | + Mmad(mmadAtom.with(mmadParams), l0CTensor, l0ATensor, l0BTensor); | ||
| 168 | + AscendC::Mutex::Unlock<PIPE_M>(L0_Index); | ||
| 169 | + | ||
| 170 | + // L0C(NZ) -> GM:输出逻辑 (1, C, HOUT, WOUT),C=COUT。按 SCENARIO_NUM 构造 GM out layout, | ||
| 171 | + // CopyL0C2GM 按目的 pattern 路由(NCHW 走 nz2dn、NHWC 走 nz2nd、NC1HWC0 直搬 NZ->NC1HWC0)。 | ||
| 172 | + AscendC::Mutex::Lock<PIPE_M>(L0C_Index); | ||
| 173 | + AscendC::Mutex::Lock<PIPE_FIX>(L0C_Index); | ||
| 174 | + auto gmOutMem = MakeMemPtr(out + batchIdx * OUT_BATCH_SIZE); | ||
| 175 | + if constexpr (scenarioNum == 1) { | ||
| 176 | + auto gmOutTensor = MakeTensor( | ||
| 177 | + gmOutMem, MakeFrameLayout<NCHWLayoutPtn>( | ||
| 178 | + 1, static_cast<int32_t>(COUT), static_cast<int32_t>(HOUT), static_cast<int32_t>(WOUT))); | ||
| 179 | + Copy(copyL0C2GMAtom, gmOutTensor, l0CTensor); | ||
| 180 | + } else if constexpr (scenarioNum == 2) { | ||
| 181 | + auto gmOutTensor = MakeTensor( | ||
| 182 | + gmOutMem, MakeFrameLayout<NHWCLayoutPtn>( | ||
| 183 | + 1, static_cast<int32_t>(HOUT), static_cast<int32_t>(WOUT), static_cast<int32_t>(COUT))); | ||
| 184 | + Copy(copyL0C2GMAtom, gmOutTensor, l0CTensor); | ||
| 185 | + } else { | ||
| 186 | + auto gmOutTensor = MakeTensor( | ||
| 187 | + gmOutMem, MakeFrameLayout<NC1HWC0LayoutPtn>( | ||
| 188 | + 1, static_cast<int32_t>(COUT_C1), static_cast<int32_t>(HOUT), static_cast<int32_t>(WOUT), | ||
| 189 | + static_cast<int32_t>(C0))); | ||
| 190 | + Copy(copyL0C2GMAtom, gmOutTensor, l0CTensor); | ||
| 191 | + } | ||
| 192 | + AscendC::Mutex::Unlock<PIPE_FIX>(L0C_Index); | ||
| 193 | + AscendC::Mutex::Unlock<PIPE_M>(L0C_Index); | ||
| 194 | + | ||
| 195 | + AscendC::PipeBarrier<PIPE_ALL>(); | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +int32_t main(int32_t argc, char* argv[]) | ||
| 199 | +{ | ||
| 200 | + size_t fmapFileSize = N * FMAP_BATCH_SIZE * sizeof(half); | ||
| 201 | + size_t weightFileSize = WEIGHT_SIZE * sizeof(half); | ||
| 202 | + size_t outFileSize = N * OUT_BATCH_SIZE * sizeof(half); | ||
| 203 | + uint32_t numBlocks = BLOCK_DIM; | ||
| 204 | + | ||
| 205 | + aclInit(nullptr); | ||
| 206 | + int32_t deviceId = 0; | ||
| 207 | + aclrtSetDevice(deviceId); | ||
| 208 | + aclrtStream stream = nullptr; | ||
| 209 | + aclrtCreateStream(&stream); | ||
| 210 | + | ||
| 211 | + uint8_t* fmapHost; | ||
| 212 | + half* fmapDevice; | ||
| 213 | + aclrtMallocHost((void**)(&fmapHost), fmapFileSize); | ||
| 214 | + aclrtMalloc((void**)&fmapDevice, fmapFileSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 215 | + ReadFile("./input/x1_gm.bin", fmapFileSize, fmapHost, fmapFileSize); | ||
| 216 | + aclrtMemcpy(fmapDevice, fmapFileSize, fmapHost, fmapFileSize, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 217 | + | ||
| 218 | + uint8_t* weightHost; | ||
| 219 | + half* weightDevice; | ||
| 220 | + aclrtMallocHost((void**)(&weightHost), weightFileSize); | ||
| 221 | + aclrtMalloc((void**)&weightDevice, weightFileSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 222 | + ReadFile("./input/x2_gm.bin", weightFileSize, weightHost, weightFileSize); | ||
| 223 | + aclrtMemcpy(weightDevice, weightFileSize, weightHost, weightFileSize, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 224 | + | ||
| 225 | + uint8_t* outHost; | ||
| 226 | + half* outDevice; | ||
| 227 | + aclrtMallocHost((void**)(&outHost), outFileSize); | ||
| 228 | + aclrtMalloc((void**)&outDevice, outFileSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 229 | + | ||
| 230 | + conv2d_forward_tensor_api_custom<<<numBlocks, nullptr, stream>>>(fmapDevice, weightDevice, outDevice); | ||
| 231 | + aclrtSynchronizeStream(stream); | ||
| 232 | + | ||
| 233 | + aclrtMemcpy(outHost, outFileSize, outDevice, outFileSize, ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 234 | + WriteFile("./output/output.bin", outHost, outFileSize); | ||
🟡 Medium Priority
建议:对所有 ACL/CANN runtime API 调用( ![]() ![]() Incorrect? | |||
| 235 | + | ||
| 236 | + aclrtFree(fmapDevice); | ||
| 237 | + aclrtFreeHost(fmapHost); | ||
| 238 | + aclrtFree(weightDevice); | ||
| 239 | + aclrtFreeHost(weightHost); | ||
| 240 | + aclrtFree(outDevice); | ||
| 241 | + aclrtFreeHost(outHost); | ||
| 242 | + | ||
| 243 | + aclrtDestroyStream(stream); | ||
| 244 | + aclrtResetDevice(deviceId); | ||
| 245 | + aclFinalize(); | ||
| 246 | + return 0; | ||
| 247 | +} | ||
| @@ -0,0 +1,86 @@ | |||||||||||||||||||
| 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 | ||||||||||||||||||
| 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); | ||||||||||||||||||
🟡 Medium Priority 第 58 行: 建议:检查 Suggestions
![]() ![]() Incorrect? 🟡 Medium Priority 第 58 行 建议:在 ![]() ![]() Incorrect? | |||||||||||||||||||
| 59 | + fileSize = size; | ||||||||||||||||||
| 60 | + file.close(); | ||||||||||||||||||
| 61 | + return true; | ||||||||||||||||||
| 62 | +} | ||||||||||||||||||
| 63 | + | ||||||||||||||||||
| 64 | +bool WriteFile(const std::string& filePath, const void* buffer, size_t size) | ||||||||||||||||||
| 65 | +{ | ||||||||||||||||||
| 66 | + if (buffer == nullptr) { | ||||||||||||||||||
| 67 | + ERROR_LOG("Write file failed. buffer is nullptr"); | ||||||||||||||||||
| 68 | + return false; | ||||||||||||||||||
| 69 | + } | ||||||||||||||||||
| 70 | + | ||||||||||||||||||
| 71 | + int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE); | ||||||||||||||||||
| 72 | + if (fd < 0) { | ||||||||||||||||||
| 73 | + ERROR_LOG("Open file failed. path = %s", filePath.c_str()); | ||||||||||||||||||
| 74 | + return false; | ||||||||||||||||||
| 75 | + } | ||||||||||||||||||
| 76 | + | ||||||||||||||||||
| 77 | + size_t writeSize = write(fd, buffer, size); | ||||||||||||||||||
🟡 Medium Priority 第 78 行: 建议:检查 Suggestions
![]() ![]() Incorrect? | |||||||||||||||||||
| 78 | + (void)close(fd); | ||||||||||||||||||
| 79 | + if (writeSize != size) { | ||||||||||||||||||
| 80 | + ERROR_LOG("Write file Failed."); | ||||||||||||||||||
| 81 | + return false; | ||||||||||||||||||
| 82 | + } | ||||||||||||||||||
| 83 | + | ||||||||||||||||||
| 84 | + return true; | ||||||||||||||||||
| 85 | +} | ||||||||||||||||||
| 86 | +#endif // DATA_UTILS_H | ||||||||||||||||||
| @@ -0,0 +1,140 @@ | |||
| 1 | +#!/usr/bin/python3 | ||
| 2 | +# coding=utf-8 | ||
| 3 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +import os | ||
| 14 | +import argparse | ||
| 15 | +import numpy as np | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +np.random.seed(19) | ||
| 19 | + | ||
| 20 | +BATCH = 4 | ||
| 21 | +C0 = 16 | ||
| 22 | +C1 = 2 | ||
| 23 | +CIN = C1 * C0 # 32 | ||
| 24 | +H = 9 | ||
| 25 | +W = 9 | ||
| 26 | +COUT = 16 | ||
| 27 | +KH = 3 | ||
| 28 | +KW = 3 | ||
| 29 | +STRIDE = (2, 2) | ||
| 30 | +DILATION = (2, 2) | ||
| 31 | +PADDING = (2, 2, 2, 2) # top, bottom, left, right | ||
| 32 | +PAD_VALUE = 1 | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def conv2d_nhwc(x, weight, stride, dilation, padding, pad_value=0): | ||
| 36 | + stride_h, stride_w = stride | ||
| 37 | + dilation_h, dilation_w = dilation | ||
| 38 | + pad_top, pad_bottom, pad_left, pad_right = padding | ||
| 39 | + n, h, w, cin = x.shape | ||
| 40 | + cout, _, kh, kw = weight.shape | ||
| 41 | + hout = (h + pad_top + pad_bottom - dilation_h * (kh - 1) - 1) // stride_h + 1 | ||
| 42 | + wout = (w + pad_left + pad_right - dilation_w * (kw - 1) - 1) // stride_w + 1 | ||
| 43 | + x_pad = np.pad( | ||
| 44 | + x, | ||
| 45 | + ((0, 0), (pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), | ||
| 46 | + mode="constant", | ||
| 47 | + constant_values=pad_value, | ||
| 48 | + ) | ||
| 49 | + y = np.zeros((n, hout, wout, cout), dtype=np.float32) | ||
| 50 | + | ||
| 51 | + for n_idx in range(n): | ||
| 52 | + for ho in range(hout): | ||
| 53 | + for wo in range(wout): | ||
| 54 | + for co in range(cout): | ||
| 55 | + acc = 0.0 | ||
| 56 | + for ci in range(cin): | ||
| 57 | + for hk in range(kh): | ||
| 58 | + for wk in range(kw): | ||
| 59 | + hi = ho * stride_h + hk * dilation_h | ||
| 60 | + wi = wo * stride_w + wk * dilation_w | ||
| 61 | + acc += float(x_pad[n_idx, hi, wi, ci]) * float( | ||
| 62 | + weight[co, ci, hk, wk] | ||
| 63 | + ) | ||
| 64 | + y[n_idx, ho, wo, co] = acc | ||
| 65 | + return y | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +def weight_to_k_cout(weight): | ||
| 69 | + # weight: [Cout, Cin, KH, KW],Cin = C1 * C0。K 序 = (C1, KH, KW, C0),与 img2col 硬件展开顺序一致。 | ||
| 70 | + cout, cin, kh, kw = weight.shape | ||
| 71 | + k = cin * kh * kw | ||
| 72 | + out = np.zeros((k, cout), dtype=np.float16) | ||
| 73 | + for co in range(cout): | ||
| 74 | + for c1 in range(C1): | ||
| 75 | + for c0 in range(C0): | ||
| 76 | + ci = c1 * C0 + c0 | ||
| 77 | + for hk in range(kh): | ||
| 78 | + for wk in range(kw): | ||
| 79 | + k_idx = ((c1 * kh + hk) * kw + wk) * C0 + c0 | ||
| 80 | + out[k_idx, co] = weight[co, ci, hk, wk] | ||
| 81 | + return out.reshape(-1) | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def to_nc1hwc0(x_nhwc, c1): | ||
| 85 | + # x_nhwc: [N, H, W, C],C = c1 * C0 -> NC1HWC0 排布。 | ||
| 86 | + n, h, w, c = x_nhwc.shape | ||
| 87 | + assert c == c1 * C0 | ||
| 88 | + x = x_nhwc.reshape(n, h, w, c1, C0) | ||
| 89 | + # NC1HWC0:N, C1, H, W, C0 | ||
| 90 | + x = np.transpose(x, (0, 3, 1, 2, 4)) | ||
| 91 | + return np.ascontiguousarray(x).reshape(-1) | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def to_nchw(x_nhwc): | ||
| 95 | + # x_nhwc: [N, H, W, C] -> NCHW: [N, C, H, W]。 | ||
| 96 | + return np.ascontiguousarray(np.transpose(x_nhwc, (0, 3, 1, 2))).reshape(-1) | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +def gen_golden_data(scenario): | ||
| 100 | + # scenario: 0=NC1HWC0, 1=NCHW, 2=NHWC(与样例 SCENARIO_NUM 对应)。 | ||
| 101 | + fmap = np.random.uniform(-1, 1, (BATCH, H, W, CIN)).astype(np.float16) | ||
| 102 | + weight = np.random.uniform(-1, 1, (COUT, CIN, KH, KW)).astype(np.float16) | ||
| 103 | + | ||
| 104 | + golden = conv2d_nhwc(fmap, weight, STRIDE, DILATION, PADDING, PAD_VALUE).astype( | ||
| 105 | + np.float16 | ||
| 106 | + ) | ||
| 107 | + | ||
| 108 | + os.makedirs("input", exist_ok=True) | ||
| 109 | + os.makedirs("output", exist_ok=True) | ||
| 110 | + | ||
| 111 | + # fmap GM 按场景摆盘。 | ||
| 112 | + if scenario == 1: | ||
| 113 | + to_nchw(fmap).tofile("./input/x1_gm.bin") | ||
| 114 | + elif scenario == 2: | ||
| 115 | + np.ascontiguousarray(fmap).reshape(-1).tofile("./input/x1_gm.bin") | ||
| 116 | + else: | ||
| 117 | + to_nc1hwc0(fmap, C1).tofile("./input/x1_gm.bin") | ||
| 118 | + | ||
| 119 | + # weight GM 始终按 [K, Cout] 行优先(K 序 = (C1, KH, KW, C0))。 | ||
| 120 | + weight_to_k_cout(weight).tofile("./input/x2_gm.bin") | ||
| 121 | + | ||
| 122 | + # golden GM 按场景摆盘。 | ||
| 123 | + if scenario == 1: | ||
| 124 | + to_nchw(golden).tofile("./output/golden.bin") | ||
| 125 | + elif scenario == 2: | ||
| 126 | + np.ascontiguousarray(golden).reshape(-1).tofile("./output/golden.bin") | ||
| 127 | + else: | ||
| 128 | + to_nc1hwc0(golden, COUT // C0).tofile("./output/golden.bin") | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +if __name__ == "__main__": | ||
| 132 | + parser = argparse.ArgumentParser() | ||
| 133 | + parser.add_argument( | ||
| 134 | + "--scenario", | ||
| 135 | + type=int, | ||
| 136 | + default=0, | ||
| 137 | + help="0=NC1HWC0, 1=NCHW, 2=NHWC (must match SCENARIO_NUM used to build)", | ||
| 138 | + ) | ||
| 139 | + args = parser.parse_args() | ||
| 140 | + gen_golden_data(args.scenario) | ||
| @@ -0,0 +1,51 @@ | |||
| 1 | +#!/usr/bin/python3 | ||
| 2 | +# coding=utf-8 | ||
| 3 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +import argparse | ||
| 14 | +import sys | ||
| 15 | +import numpy as np | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def verify_result(output, golden): | ||
| 19 | + output_data = np.fromfile(output, dtype=np.float16).astype(np.float32).reshape(-1) | ||
| 20 | + golden_data = np.fromfile(golden, dtype=np.float16).astype(np.float32).reshape(-1) | ||
| 21 | + diff = np.abs(output_data - golden_data) | ||
| 22 | + different_element_results = np.isclose( | ||
| 23 | + output_data, golden_data, rtol=1e-2, atol=1e-2, equal_nan=True | ||
| 24 | + ) | ||
| 25 | + different_element_indexes = np.where(different_element_results == False)[0] | ||
| 26 | + for real_index in different_element_indexes[:100]: | ||
| 27 | + expected = golden_data[real_index] | ||
| 28 | + actual = output_data[real_index] | ||
| 29 | + print( | ||
| 30 | + "data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f" | ||
| 31 | + % (real_index, expected, actual, abs(actual - expected) / expected) | ||
| 32 | + ) | ||
| 33 | + print(f"max diff: {diff.max() if diff.size else 0.0}") | ||
| 34 | + print( | ||
| 35 | + f"error ratio: {float(different_element_indexes.size) / golden_data.size if golden_data.size else 0.0:.4f}" | ||
| 36 | + ) | ||
| 37 | + return different_element_indexes.size == 0 | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +if __name__ == "__main__": | ||
| 41 | + parser = argparse.ArgumentParser() | ||
| 42 | + parser.add_argument("output", type=str) | ||
| 43 | + parser.add_argument("golden", type=str) | ||
| 44 | + args = parser.parse_args() | ||
| 45 | + try: | ||
| 46 | + if not verify_result(args.output, args.golden): | ||
| 47 | + raise ValueError("[ERROR] result error") | ||
| 48 | + print("test pass!") | ||
| 49 | + except Exception as err: | ||
| 50 | + print(err) | ||
| 51 | + sys.exit(1) | ||


🟡 Medium Priority
第 198 行
uint8_t* fmapHost;、第 205 行uint8_t* weightHost;、第 212 行uint8_t* outHost;声明时未初始化。若随后的aclrtMallocHost失败且返回值未检查(见上一问题),这些指针保持未初始化状态,传入ReadFile将导致未定义行为(大概率段错误)。建议:将
fmapHost、weightHost、outHost以及对应的 device 指针初始化为 nullptr,避免aclrtMallocHost/aclrtMalloc失败后使用未初始化指针。