Open
增加C API样例 #7443
LycheeeeeAdd on 12 days ago
增加C API样例 #7443
Open
Merged fromLycheeeee/asc-devkit_novmasterintocann/asc-devkitmaster
Total: 42 files changed+5852-0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# 算子样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
| 4 | + | ||
| 5 | +本目录提供基于Ascend C C API的典型算子样例,介绍激活函数、归一化、归一化与量化融合、注意力计算的实现及优化方法。 | ||
| 6 | + | ||
| 7 | +各样例针对其文档约定的数据类型、shape范围和运行条件实现,展示特定场景下的算子实现与优化,不作为泛化算子实现。 | ||
| 8 | + | ||
| 9 | +## 样例列表 | ||
| 10 | + | ||
| 11 | +| 目录 | 功能描述 | | ||
| 12 | +| --- | --- | | ||
| 13 | +| [activation](./activation) | 基于C API实现bfloat16_t类型的SiLU、GELU、SwiGLU和GeGLU,支持动态多维shape、Erf分段多项式、寄存器融合及多核双缓冲流水 | | ||
| 14 | +| [normalization](./normalization) | 基于C API实现float类型的LayerNorm,支持动态多维shape、中心化方差、二分折叠归约、双行参数复用及输入输出双缓冲,输出y、mean和rstd | | ||
| 15 | +| [rms_norm_quant](./rms_norm_quant) | 基于C API实现half类型的RMSNorm与int8_t标量量化,支持整行加载、四种归约路径、rstd精度修正及多核双缓冲 | | ||
| 16 | +| [attention](./attention) | 基于C API实现bfloat16_t类型、D=128的因果FlashAttention,支持动态B/N/S、五代延迟流水、四槽L0C队列、融合Softmax与NZ打包及单核跨任务双缓冲 | | ||
| @@ -0,0 +1,16 @@ | |||
| 1 | +# Operator Examples | ||
| 2 | + | ||
| 3 | +## Overview | ||
| 4 | + | ||
| 5 | +This directory provides typical operator examples using the Ascend C C API, demonstrating implementation and optimization methods for activation functions, normalization, fused normalization and quantization, and attention computation. | ||
| 6 | + | ||
| 7 | +Each example targets the data types, shape ranges, and execution conditions specified in its documentation. These examples demonstrate implementation and optimization for specific scenarios and are not general-purpose operator implementations. | ||
| 8 | + | ||
| 9 | +## Examples | ||
| 10 | + | ||
| 11 | +| Directory | Description | | ||
| 12 | +| --- | --- | | ||
| 13 | +| [activation](./activation) | Implements bfloat16_t SiLU, GELU, SwiGLU and GeGLU using the C API, with runtime multidimensional shapes, piecewise Erf polynomials, register fusion and a multicore double-buffered pipeline | | ||
| 14 | +| [normalization](./normalization) | Implements float LayerNorm using the C API, with runtime multidimensional shapes, centered variance, binary-fold reduction, paired-row parameter reuse and input/output double buffering; outputs y, mean and rstd | | ||
| 15 | +| [rms_norm_quant](./rms_norm_quant) | Implements half RMSNorm and scalar int8_t quantization using the C API, with full-row loading, four reduction paths, refined rstd and multicore double buffering | | ||
| 16 | +| [attention](./attention) | Implements bfloat16_t causal FlashAttention with D=128 using the C API, supporting dynamic B/N/S, a five-generation delayed pipeline, a four-slot L0C queue, fused Softmax/NZ packing, and inter-task double buffering within a single core | | ||
| @@ -0,0 +1,42 @@ | |||
| 1 | +# ---------------------------------------------------------------------------------------------------------- | ||
这个 PR 类型标签是 docs,但实际新增了 .asc、CMakeLists 和 Python 脚本这类可编译运行的代码,描述里「测试」章节还是空的。能否补上验证依据:用的 CANN 版本、在 dav-3510 上跑的是 sim 还是 npu、 ![]() ![]() | |||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +cmake_minimum_required(VERSION 3.16) | ||
| 12 | + | ||
| 13 | +set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu, sim") | ||
| 14 | +set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510") | ||
| 15 | + | ||
| 16 | +find_package(ASC REQUIRED) | ||
| 17 | + | ||
| 18 | +project(kernel_samples LANGUAGES ASC CXX) | ||
| 19 | + | ||
| 20 | +add_executable(demo | ||
| 21 | + activation.asc | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510") | ||
arch 和 run mode 的校验放在 add_executable 之后了。建议把这两个 if 挪到 find_package/project 之后、add_executable 之前,架构或运行模式填错时能更早报错。 ![]() ![]() | |||
| 25 | + message(FATAL_ERROR "This sample only supports CMAKE_ASC_ARCHITECTURES=dav-3510") | ||
| 26 | +endif() | ||
| 27 | + | ||
| 28 | +if(NOT CMAKE_ASC_RUN_MODE MATCHES "^(npu|sim)$") | ||
| 29 | + message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be npu or sim, but got ${CMAKE_ASC_RUN_MODE}") | ||
| 30 | +endif() | ||
| 31 | + | ||
| 32 | +target_link_libraries(demo PRIVATE | ||
| 33 | + tiling_api | ||
| 34 | + register | ||
| 35 | + platform | ||
| 36 | + m | ||
| 37 | +) | ||
| 38 | + | ||
| 39 | +target_compile_options(demo PRIVATE | ||
| 40 | + $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}> | ||
| 41 | + $<$<COMPILE_LANGUAGE:ASC>:--cce-auto-sync=off> | ||
| 42 | +) | ||
| @@ -0,0 +1,193 @@ | |||
| 1 | +# Activation样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
| 4 | + | ||
| 5 | +本样例使用Ascend C 语言扩展层 C API实现bfloat16_t(BF16)类型的SiLU、GELU、SwiGLU和GeGLU逐元素激活。支持运行时指定激活类型和1~4维连续输入,由多个Vector核(AIV)各自处理一段数据;核内通过双缓冲衔接数据搬运与矢量计算。GELU和GeGLU按Erf公式计算,不使用tanh近似。SwiGLU和GeGLU接收两个独立且shape相同的张量,核函数不拆分输入的最后一维。 | ||
| 6 | + | ||
| 7 | +## 本样例支持的产品及CANN软件版本 | ||
| 8 | + | ||
| 9 | +| 产品 | CANN软件版本 | | ||
| 10 | +|------|-------------| | ||
| 11 | +| Ascend 950PR&950DT系列产品 | >= CANN 9.3.0 | | ||
| 12 | + | ||
| 13 | +本样例固定使用`dav-3510`架构,仅支持NPU和仿真运行模式。 | ||
| 14 | + | ||
| 15 | +## 目录结构 | ||
| 16 | + | ||
| 17 | +```text | ||
| 18 | +activation | ||
| 19 | +├── scripts | ||
| 20 | +│ ├── gen_data.py # 可选:生成BF16输入和PyTorch参考结果 | ||
| 21 | +│ └── verify_result.py # 可选:校验二进制输出文件 | ||
| 22 | +├── CMakeLists.txt # 编译工程文件 | ||
| 23 | +├── activation.asc # 寄存器计算、核函数和Host入口 | ||
| 24 | +├── tiling.h # 参数解析、多核切分与分块配置 | ||
| 25 | +├── README.md | ||
| 26 | +└── README_en.md | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +## 样例描述 | ||
| 30 | + | ||
| 31 | +输入按连续存储顺序展平成一串元素,每个元素独立计算,输出保持输入shape和顺序。单输入模式将输入记为g;门控模式接收gate(g)和up(u),先对g计算激活,再逐元素乘u。不支持up广播、非连续输入、矩阵乘、偏置或反向计算。 | ||
| 32 | + | ||
| 33 | +**表1** 输入输出数据规格 | ||
| 34 | + | ||
| 35 | +| 数据 | 输入/输出 | 数据类型 | 默认Shape | 说明 | | ||
| 36 | +| --- | --- | --- | --- | --- | | ||
| 37 | +| g / gate | 输入 | bfloat16_t | `[32,128]` | 四种激活都使用。 | | ||
| 38 | +| up | 输入 | bfloat16_t | 与gate相同 | 仅SwiGLU和GeGLU参与计算。 | | ||
| 39 | +| output | 输出 | bfloat16_t | 与gate相同 | 逐元素结果,不改变布局。 | | ||
| 40 | +| 参考结果 | 校验 | double计算后舍入为bfloat16_t | 与output相同 | Host根据实际BF16输入生成,不参与Device计算。 | | ||
| 41 | + | ||
| 42 | +shape可为1~4维,各维必须为正整数,总元素数E必须满足`1≤E≤INT32_MAX`。每个核要求至少104 KiB UB,其中96 KiB为静态数据缓冲区,另预留8 KiB。默认运行`silu`,Host生成输入、启动计算并校验全部输出,无需准备数据文件。 | ||
| 43 | + | ||
| 44 | +### 计算公式与BF16舍入 | ||
| 45 | + | ||
| 46 | +令sigmoid和四种激活的数学公式为: | ||
| 47 | + | ||
| 48 | +$$ | ||
| 49 | +\operatorname{sigmoid}(g)=\frac{1}{1+\exp(-g)} | ||
| 50 | +$$ | ||
| 51 | + | ||
| 52 | +$$ | ||
| 53 | +\begin{aligned} | ||
| 54 | +\operatorname{SiLU}(g)&=g\cdot\operatorname{sigmoid}(g),\\ | ||
| 55 | +\operatorname{GELU}(g)&=\frac{g}{2}\left(1+\operatorname{erf}\left(\frac{g}{\sqrt{2}}\right)\right),\\ | ||
| 56 | +\operatorname{SwiGLU}(g,u)&=\operatorname{SiLU}(g)\cdot u,\\ | ||
| 57 | +\operatorname{GeGLU}(g,u)&=\operatorname{GELU}(g)\cdot u. | ||
| 58 | +\end{aligned} | ||
| 59 | +$$ | ||
| 60 | + | ||
| 61 | +实际实现将BF16输入转换为FP32后计算,但不仅在最终输出时舍入。以下中间舍入也是本样例的数值行为,不保证与全程FP32计算后仅转换一次的结果逐位一致: | ||
| 62 | + | ||
| 63 | +- SiLU和SwiGLU:FP32计算sigmoid,将sigmoid结果按最近偶数舍入转为BF16,再转回FP32与g相乘;SwiGLU继续乘u,最后才将输出转为BF16。 | ||
| 64 | +- GELU和GeGLU:先计算`g*0.7071067811865476f`,转为BF16后再转回FP32;计算Erf,再做一次相同舍入;随后依次计算`erf+1`、`g*0.5`及两者的乘积。GeGLU继续乘u,最后将输出转为BF16。 | ||
| 65 | +- Erf分段计算:按输入绝对值与`0x1.00c1fcp+0f`(FP32位模式`0x3F8060FE`)比较,选择两个多项式计算路径之一。两个路径都在寄存器中计算,由比较掩码和`asc_select`选取结果。代码保留乘法和加法顺序,不改写为融合乘加或tanh公式。 | ||
| 66 | + | ||
| 67 | +中间舍入通过以下函数完成,使用[asc_float2bfloat16_rn](../../../../docs/zh/api/SIMD-API/c_api/reg_compute/reg_convert/asc_float2bfloat16.md)转换后再扩展: | ||
这里以及后面几处都用了 ![]() ![]() | |||
| 68 | + | ||
| 69 | +```cpp | ||
| 70 | +asc_float2bfloat16_rn(rounded, value, mask, ASC_POSITION_EVEN); | ||
| 71 | +asc_bfloat162float(value, rounded, mask, ASC_POSITION_EVEN); | ||
| 72 | +``` | ||
| 73 | + | ||
| 74 | +内置输入及数据脚本覆盖g的`[-16,16]`、零附近和Erf分段边界附近数据,u覆盖`[-4,4]`。不承诺上述范围之外以及NaN、Inf输入的精度或特殊值语义;结果校验要求输出为有限值。 | ||
| 75 | + | ||
| 76 | +### 多核切分与尾核处理 | ||
| 77 | + | ||
| 78 | +**每个Vector核处理一个连续区间。** Host读取硬件Vector核数,也可由运行参数指定不超过硬件数量的正整数核数C。为避免小输入启动过多核,先按每4096个元素分配一个核,再将每核区间长度向上对齐到64个元素。具体计算为: | ||
| 79 | + | ||
| 80 | +```text | ||
| 81 | +wanted = min(C, ceil(E / 4096)) | ||
| 82 | +vectors = ceil(E / 64) | ||
| 83 | +block = ceil(vectors / wanted) * 64 | ||
| 84 | +used = ceil(E / block) | ||
| 85 | +tile = min(block, 8192) | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +实际启动used个核。编号k从0开始,负责从`k*block`起的`min(block,E-k*block)`个元素;只有最后一个核可能不足block。核内按tile分批,最后一批只处理剩余元素。尾核有效长度直接由E和核起点计算,不额外传递可推导的尾核参数。 | ||
| 89 | + | ||
| 90 | +例如,E为10001、指定C为4时,wanted为3,vectors为157,block为3392,实际启动3个核。三个核分别处理`[0,3392)`、`[3392,6784)`、`[6784,10001)`,有效元素数为3392、3392和3217,tile均为3392。最后17个元素由向量掩码控制,不转成逐元素标量计算。 | ||
| 91 | + | ||
| 92 | +每次向量函数(Vector Function,VF)迭代处理64个FP32元素,独立的remaining计数用于更新有效元素掩码;最后不足64个元素时,只写回有效位置。GM与UB之间也只搬运有效字节,Host无需对输入文件或输出shape补齐。 | ||
| 93 | + | ||
| 94 | +### UB布局与双缓冲 | ||
| 95 | + | ||
| 96 | +数据经过外部存储(Global Memory,GM)、Unified Buffer(UB)和寄存器三个层级。MTE2数据搬运流水负责GM到UB,矢量计算流水V执行向量函数,MTE3数据搬运流水负责UB到GM。相关定义见[Reg矢量计算编程](../../../../docs/zh/guide/programming_guide/programming_model/ai_core_simd_programming/c_pointer_programming/reg_vector_computation.md)。 | ||
| 97 | + | ||
| 98 | +**gate、up和output各分配两份缓冲区,交替使用。** 设每份容纳t个BF16元素,`t=tile`,则每份占`2*t`字节。每个核的UB起始布局如下: | ||
| 99 | + | ||
| 100 | +**表2** 每核UB数据布局 | ||
| 101 | + | ||
| 102 | +| 区域 | 字节偏移 | 两份缓冲区总容量 | 用途 | | ||
| 103 | +| --- | --- | --- | --- | | ||
| 104 | +| gate | 0 | `4*t`字节 | 当前批和下一批输入。 | | ||
| 105 | +| up | `4*t` | `4*t`字节 | 门控激活的第二路输入;单输入模式保留空间但不搬运up。 | | ||
| 106 | +| output | `8*t` | `4*t`字节 | 当前批和前一批输出。 | | ||
| 107 | + | ||
| 108 | +每类区域中,第0份从区域起点开始,第1份位于起点后`2*t`字节处。t最大8192,六份共`12*8192=98304`字节,即96 KiB。默认shape有4096个元素,t为4096,实际布局使用前48 KiB,但静态数组仍分配96 KiB;t随每核任务量变化,不根据UB容量动态扩大。 | ||
| 109 | + | ||
| 110 | +**先发起下一批输入搬运,再计算当前批。** 首批输入先搬入第0份缓冲区;处理第j批时,使用编号`j%2`的缓冲区,并预先发起第j+1批输入搬运。这样在处理多批数据时,MTE2可以与当前批矢量计算和输出搬运重叠,不必每批都先完成全部搬运再开始计算。 | ||
| 111 | + | ||
| 112 | +缓冲区复用依赖[核内同步](../../../../docs/zh/api/SIMD-API/c_api/sync/intra_core_sync/asc_sync_notify.md),不需要不同Vector核之间同步: | ||
| 113 | + | ||
| 114 | +- MTE2到V:输入搬入完成,才允许当前向量函数读取。 | ||
| 115 | +- V到MTE3:输出计算完成,才允许搬出。 | ||
| 116 | +- MTE3到MTE2:复用同一编号前,等待之前输出搬完,避免覆盖仍在使用的数据。 | ||
| 117 | + | ||
| 118 | +每份缓冲区使用独立事件ID;核结束前调用`asc_sync`等待未完成操作。例如,E为65537并指定单核时,block为65600、t为8192,共处理9批,前8批各8192个元素,最后1批仅1个元素,反复交替使用两份缓冲区。单批小输入走相同代码,但没有后续批可供重叠,不能据此宣称同样的性能收益。 | ||
| 119 | + | ||
| 120 | +## 性能优化方式 | ||
| 121 | + | ||
| 122 | +- **整条表达式融合**:指数、倒数、Erf和可选的门控乘法在同一个向量函数(VF)中完成,中间结果驻留寄存器,避免将各步结果反复写入GM或UB。门控模式在激活后直接乘up,不额外生成激活中间张量。 | ||
| 123 | +- **编译期路径选择**:GELU/SiLU与门控/非门控由模板参数组合,分别编译为四条计算路径;VF向量循环内没有运行时激活类型判断,单输入模式不加载up。 | ||
| 124 | +- **多核连续分块**:根据总元素数和可用Vector核数计算连续区间,约每4096个元素增加一个核,避免小输入启用过多核;大输入由多个核共同处理。分核公式和尾核示例见“多核切分与尾核处理”。 | ||
| 125 | +- **双缓冲预取**:gate、up和output分开存储,各有两份缓冲区交替使用;在计算当前批之前发起下一批输入搬运,使多批数据的搬入、计算和搬出有机会重叠。显式关闭编译器自动同步,通过核内事件控制数据就绪和缓冲区复用;单批输入没有后续批可供重叠。具体布局和同步关系见“UB布局与双缓冲”。 | ||
| 126 | +- **按任务长度分块与尾部掩码**:每批长度随核任务量变化,按64个元素对齐,最大8192个元素;不足一个向量的尾部由有效元素掩码处理,不退化为逐元素标量计算。搬运和写回只覆盖有效字节,不要求Host补齐数据;静态UB分配仍为96 KiB,不随分块长度缩小。 | ||
| 127 | +- **便于生成硬件循环**:VF采用从0开始、每次加1的`uint16_t`计数,最多128次迭代(8192/64);常量1及Erf使用的ln(2)在循环外生成,避免重复计算。这样的循环组织便于编译器生成硬件循环,但是否生成应以编译结果为准。 | ||
| 128 | + | ||
| 129 | +上述说明描述当前实现减少重复计算、搬运及等待的方式,不代表已测得特定加速比。 | ||
| 130 | + | ||
| 131 | +## 编译运行 | ||
| 132 | + | ||
| 133 | +配置CANN环境变量: | ||
| 134 | + | ||
| 135 | +```bash | ||
| 136 | +source ${install_path}/cann/set_env.sh | ||
| 137 | +``` | ||
| 138 | + | ||
| 139 | +> **说明:** `${install_path}`通常为root用户的`/usr/local/Ascend`或非root用户的`${HOME}/Ascend`。 | ||
| 140 | + | ||
| 141 | +在样例目录执行,无需单独生成数据: | ||
| 142 | + | ||
| 143 | +```bash | ||
| 144 | +mkdir -p build && cd build | ||
| 145 | +cmake .. | ||
| 146 | +make -j | ||
| 147 | +./demo | ||
| 148 | +``` | ||
| 149 | + | ||
| 150 | +默认运行Device 0上的SiLU,shape为`[32,128]`。运行参数为`demo [activation shape [cores]]`,activation为`silu`、`gelu`、`swiglu`或`geglu`,shape用逗号分隔。cores可省略,指定时必须为正整数且不超过硬件Vector核数;实际用核数仍按输入大小计算。 | ||
| 151 | + | ||
| 152 | +```bash | ||
| 153 | +./demo gelu 65 | ||
| 154 | +./demo swiglu 2,3,17,65 | ||
| 155 | +./demo geglu 65537 1 | ||
| 156 | +``` | ||
| 157 | + | ||
| 158 | +**表3** 编译选项 | ||
| 159 | + | ||
| 160 | +| 编译选项 | 可选值 | 说明 | | ||
| 161 | +| --- | --- | --- | | ||
| 162 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510`(默认) | 指定NPU架构。 | | ||
| 163 | +| `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | NPU或仿真模式;仿真使用独立build目录配置。 | | ||
| 164 | + | ||
| 165 | +仿真使用独立构建目录,在样例根目录执行: | ||
| 166 | + | ||
| 167 | +```bash | ||
| 168 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 169 | +cmake --build build/sim --parallel | ||
| 170 | +./build/sim/demo | ||
| 171 | +``` | ||
| 172 | + | ||
| 173 | +构建使用默认优化配置,并设置`--cce-auto-sync=off`,由代码显式安排同步。仿真耗时不能作为硬件性能结果。 | ||
| 174 | + | ||
| 175 | +### 执行结果 | ||
| 176 | + | ||
| 177 | +运行`./demo`后,程序自动生成输入和参考结果,并校验全部输出。执行结果如下,说明精度对比成功。校验失败时输出`test failed!`并返回非零退出码。 | ||
| 178 | + | ||
| 179 | +```text | ||
| 180 | +test pass! | ||
| 181 | +``` | ||
| 182 | + | ||
| 183 | +### 可选文件输入 | ||
| 184 | + | ||
| 185 | +如需使用文件输入,在安装CPU PyTorch和NumPy的环境中,于build目录执行: | ||
| 186 | + | ||
| 187 | +```bash | ||
| 188 | +python3 ../scripts/gen_data.py --activation geglu --shape 32,128 --data-dir data | ||
| 189 | +./demo --files geglu 32,128 data/input/gate.bin data/input/up.bin data/output/output.bin | ||
| 190 | +python3 ../scripts/verify_result.py data/output/output.bin data/output/golden.bin --shape 32,128 | ||
| 191 | +``` | ||
| 192 | + | ||
| 193 | +输入和输出文件均为连续BF16数据,长度须与shape一致;单输入模式也需提供up文件。数据生成脚本会创建所需目录,校验脚本显示`PASS`即表示通过。 | ||
| @@ -0,0 +1,195 @@ | |||
| 1 | +# Activation Example | ||
| 2 | + | ||
| 3 | +## Overview | ||
| 4 | + | ||
| 5 | +This example uses the Ascend C C API to implement bfloat16_t (BF16) SiLU, GELU, SwiGLU and GeGLU elementwise activations. Activation type and contiguous input shapes of rank 1–4 are configurable at runtime. Multiple Vector cores (AIVs) each process a separate interval, using double buffering to coordinate data transfers and vector computation. | ||
| 6 | + | ||
| 7 | +GELU/GeGLU use the Erf formula, not the tanh approximation. SwiGLU/GeGLU accept two separate tensors of equal shape; the kernel does not split the last input dimension. | ||
| 8 | + | ||
| 9 | +## Supported Products and CANN Versions | ||
| 10 | + | ||
| 11 | +| Product | CANN Version | | ||
| 12 | +|---------|-------------| | ||
| 13 | +| Ascend 950PR&950DT products | >= CANN 9.3.0 | | ||
| 14 | + | ||
| 15 | +This sample uses the `dav-3510` architecture and supports only NPU and NPU simulation modes. | ||
| 16 | + | ||
| 17 | +## Directory Structure | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +activation | ||
| 21 | +├── scripts | ||
| 22 | +│ ├── gen_data.py # Optional BF16 inputs and PyTorch reference generation | ||
| 23 | +│ └── verify_result.py # Optional binary output verification | ||
| 24 | +├── CMakeLists.txt # Build configuration | ||
| 25 | +├── activation.asc # Register computation, kernel and host entry | ||
| 26 | +├── tiling.h # Argument parsing, multicore partitioning and tiling | ||
| 27 | +├── README.md | ||
| 28 | +└── README_en.md | ||
| 29 | +``` | ||
| 30 | + | ||
| 31 | +## Example Description | ||
| 32 | + | ||
| 33 | +The input is flattened in contiguous storage order. Each element is processed independently, preserving output shape and order. Single-input modes name the input g. Gated modes accept gate (g) and up (u), compute the activation of g and multiply by u elementwise. Broadcasting up, noncontiguous inputs, matrix multiplication, bias and backward computation are not supported. | ||
| 34 | + | ||
| 35 | +**Table 1** Input and output specifications | ||
| 36 | + | ||
| 37 | +| Data | Direction | Type | Default shape | Description | | ||
| 38 | +| --- | --- | --- | --- | --- | | ||
| 39 | +| g / gate | Input | bfloat16_t | `[32,128]` | Used by all four activations. | | ||
| 40 | +| up | Input | bfloat16_t | Same as gate | Used in computation only by SwiGLU/GeGLU. | | ||
| 41 | +| output | Output | bfloat16_t | Same as gate | Elementwise result with unchanged layout. | | ||
| 42 | +| Reference | Verification | double computation rounded to bfloat16_t | Same as output | Generated on host using actual BF16 inputs; not used by Device computation. | | ||
| 43 | + | ||
| 44 | +Shapes have rank 1–4 with positive dimensions and total element count `1≤E≤INT32_MAX`. Each core requires at least 104 KiB UB: a 96 KiB static data buffer plus an 8 KiB reserve. By default, the example runs `silu`; host generates inputs, launches computation and verifies every output without input files. | ||
| 45 | + | ||
| 46 | +### Formulas and BF16 Rounding | ||
| 47 | + | ||
| 48 | +The mathematical formulas are: | ||
| 49 | + | ||
| 50 | +$$ | ||
| 51 | +\operatorname{sigmoid}(g)=\frac{1}{1+\exp(-g)} | ||
| 52 | +$$ | ||
| 53 | + | ||
| 54 | +$$ | ||
| 55 | +\begin{aligned} | ||
| 56 | +\operatorname{SiLU}(g)&=g\cdot\operatorname{sigmoid}(g),\\ | ||
| 57 | +\operatorname{GELU}(g)&=\frac{g}{2}\left(1+\operatorname{erf}\left(\frac{g}{\sqrt{2}}\right)\right),\\ | ||
| 58 | +\operatorname{SwiGLU}(g,u)&=\operatorname{SiLU}(g)\cdot u,\\ | ||
| 59 | +\operatorname{GeGLU}(g,u)&=\operatorname{GELU}(g)\cdot u. | ||
| 60 | +\end{aligned} | ||
| 61 | +$$ | ||
| 62 | + | ||
| 63 | +BF16 inputs are converted to FP32 for computation, but rounding occurs before the final output as well. These intermediate roundings are part of the example's numerical behavior, so results need not be bitwise identical to all-FP32 computation with a single final conversion: | ||
| 64 | + | ||
| 65 | +- SiLU/SwiGLU: compute sigmoid in FP32, round it to BF16 using round-to-nearest-even, expand to FP32 and multiply by g. SwiGLU then multiplies by u before final BF16 output conversion. | ||
| 66 | +- GELU/GeGLU: compute `g*0.7071067811865476f`, round to BF16 and expand to FP32. Compute Erf and apply the same rounding again. Then compute `erf+1`, `g*0.5` and their product in order. GeGLU multiplies by u before final BF16 output conversion. | ||
| 67 | +- Piecewise Erf: compare the input magnitude with `0x1.00c1fcp+0f` (FP32 bit pattern `0x3F8060FE`) to choose between two polynomial paths. Both are evaluated in registers; comparison masks and `asc_select` choose the result. Multiplication/addition order is preserved rather than rewritten as fused multiply-add or tanh. | ||
| 68 | + | ||
| 69 | +Intermediate rounding uses [asc_float2bfloat16_rn](../../../../docs/zh/api/SIMD-API/c_api/reg_compute/reg_convert/asc_float2bfloat16.md), followed by expansion: | ||
| 70 | + | ||
| 71 | +```cpp | ||
| 72 | +asc_float2bfloat16_rn(rounded, value, mask, ASC_POSITION_EVEN); | ||
| 73 | +asc_bfloat162float(value, rounded, mask, ASC_POSITION_EVEN); | ||
| 74 | +``` | ||
| 75 | + | ||
| 76 | +Built-in inputs and generation scripts cover g in `[-16,16]`, near-zero values and values around the Erf boundary, with u in `[-4,4]`. Accuracy outside these ranges and special-value semantics for NaN/Inf are not guaranteed. Verification requires finite outputs. | ||
| 77 | + | ||
| 78 | +### Multicore Partitioning and the Last Core | ||
| 79 | + | ||
| 80 | +**Each Vector core processes one contiguous interval.** Host queries the hardware Vector-core count. An optional positive requested count C must not exceed hardware. To avoid launching too many cores for small inputs, the example first budgets one core per 4096 elements, then rounds interval length up to a multiple of 64 elements: | ||
| 81 | + | ||
| 82 | +```text | ||
| 83 | +wanted = min(C, ceil(E / 4096)) | ||
| 84 | +vectors = ceil(E / 64) | ||
| 85 | +block = ceil(vectors / wanted) * 64 | ||
| 86 | +used = ceil(E / block) | ||
| 87 | +tile = min(block, 8192) | ||
| 88 | +``` | ||
| 89 | + | ||
| 90 | +The kernel launches used cores. Zero-based core k handles `min(block,E-k*block)` elements starting at `k*block`. Only the last core can have fewer than block elements. Each core processes batches of tile elements, with a shorter last batch if needed. The last core's valid count is derived directly from E and its start offset, without passing a redundant last-core parameter. | ||
| 91 | + | ||
| 92 | +For E=10001 and requested C=4, wanted=3, vectors=157, block=3392 and used=3. Cores process `[0,3392)`, `[3392,6784)` and `[6784,10001)`, containing 3392, 3392 and 3217 valid elements. All use tile=3392. The final 17 elements are controlled by a vector mask rather than scalar elementwise computation. | ||
| 93 | + | ||
| 94 | +Each Vector Function (VF) iteration processes 64 FP32 elements. A separate remaining counter updates the valid-element mask; a partial vector writes only valid positions. Transfers between GM and UB also use valid byte counts, so host files and output shapes require no padding. | ||
| 95 | + | ||
| 96 | +### UB Layout and Double Buffering | ||
| 97 | + | ||
| 98 | +Data passes through Global Memory (GM), Unified Buffer (UB) and registers. The MTE2 transfer pipeline moves GM data to UB; the V vector-computation pipeline executes vector functions; MTE3 moves UB data to GM. See [Register Vector Programming (Chinese)](../../../../docs/zh/guide/programming_guide/programming_model/ai_core_simd_programming/c_pointer_programming/reg_vector_computation.md) for these terms. | ||
| 99 | + | ||
| 100 | +**gate, up and output each have two alternating buffers.** Let each buffer hold t BF16 elements, where `t=tile`; each occupies `2*t` bytes. Each core's UB layout is: | ||
| 101 | + | ||
| 102 | +**Table 2** Per-core UB data layout | ||
| 103 | + | ||
| 104 | +| Region | Byte offset | Combined size of two buffers | Purpose | | ||
| 105 | +| --- | --- | --- | --- | | ||
| 106 | +| gate | 0 | `4*t` bytes | Current and next input batches. | | ||
| 107 | +| up | `4*t` | `4*t` bytes | Second input for gated modes; single-input modes reserve space without transferring up. | | ||
| 108 | +| output | `8*t` | `4*t` bytes | Current and previous output batches. | | ||
| 109 | + | ||
| 110 | +Within each region, buffer 0 starts at the region base and buffer 1 starts `2*t` bytes later. With maximum t=8192, six buffers occupy `12*8192=98304` bytes, or 96 KiB. The default shape has 4096 elements and t=4096, using the first 48 KiB of the layout; the static array still allocates 96 KiB. t depends on per-core workload and does not expand dynamically with UB capacity. | ||
| 111 | + | ||
| 112 | +**Start the next input transfer before computing the current batch.** The first input batch is loaded into buffer 0. Batch j uses buffer `j%2` while prefetching batch j+1. With multiple batches, MTE2 can overlap the current vector computation and output transfer instead of serializing every transfer and computation. | ||
| 113 | + | ||
| 114 | +Reuse relies on [intra-core synchronization](../../../../docs/zh/api/SIMD-API/c_api/sync/intra_core_sync/asc_sync_notify.md), without synchronization between different Vector cores: | ||
| 115 | + | ||
| 116 | +- MTE2 to V: input transfer completes before the vector function reads it. | ||
| 117 | +- V to MTE3: output computation completes before transfer to GM. | ||
| 118 | +- MTE3 to MTE2: before reusing a buffer index, wait for the earlier output transfer to complete so data still in use is not overwritten. | ||
| 119 | + | ||
| 120 | +Each buffer index uses a separate event ID. `asc_sync` waits for outstanding work before kernel exit. For example, E=65537 with one core gives block=65600 and t=8192: nine batches repeatedly alternate buffers, with eight batches of 8192 elements and a final batch of one element. Single-batch inputs use the same code but have no following batch to overlap; equal performance benefits are not assumed. | ||
| 121 | + | ||
| 122 | +## Performance Optimizations | ||
| 123 | + | ||
| 124 | +- **Fuse the complete expression**: exponentials, reciprocal, Erf and optional gating multiplication run in one Vector Function (VF). Intermediates remain in registers rather than repeatedly passing through GM or UB. Gated modes multiply by up immediately after activation, without a separate intermediate activation tensor. | ||
| 125 | +- **Select paths at compile time**: template parameters combine GELU/SiLU and gated/non-gated behavior into four compiled paths. The VF vector loop has no runtime activation-type checks; single-input modes do not load up. | ||
| 126 | +- **Partition contiguous intervals across cores**: total element count and available Vector cores determine continuous per-core intervals, budgeting approximately one core per 4096 elements. Small inputs avoid excessive core launches; large inputs use multiple cores. See “Multicore Partitioning and the Last Core” for formulas and a last-core example. | ||
| 127 | +- **Prefetch with double buffering**: gate, up and output use separate pairs of alternating buffers. The next input transfer starts before current-batch computation, allowing transfers and computation to overlap for multiple batches. Compiler automatic synchronization is explicitly disabled; intra-core events control data readiness and buffer reuse. Single-batch inputs have no next batch to overlap. See “UB Layout and Double Buffering” for layout and synchronization details. | ||
| 128 | +- **Adapt tile length and mask tails**: tile length depends on per-core workload, is aligned to 64 elements and is capped at 8192. Valid-element masks handle partial vectors without scalar elementwise fallback. Transfers and stores cover valid bytes only, requiring no host padding. Static UB allocation remains 96 KiB even for shorter tiles. | ||
| 129 | +- **Facilitate hardware-loop generation**: VF uses a zero-based, unit-step `uint16_t` counter with at most 128 iterations (8192/64). Constants such as 1 and the ln(2) used by Erf are generated outside the loop. This organization facilitates hardware-loop generation, which must be confirmed from compiler output. | ||
| 130 | + | ||
| 131 | +These mechanisms describe how the implementation reduces repeated computation, transfers and waiting, not measured speedup ratios. | ||
| 132 | + | ||
| 133 | +## Build and Run | ||
| 134 | + | ||
| 135 | +Configure CANN: | ||
| 136 | + | ||
| 137 | +```bash | ||
| 138 | +source ${install_path}/cann/set_env.sh | ||
| 139 | +``` | ||
| 140 | + | ||
| 141 | +> **Note:** `${install_path}` is typically `/usr/local/Ascend` for root or `${HOME}/Ascend` otherwise. | ||
| 142 | + | ||
| 143 | +From the example directory, without separate data generation: | ||
| 144 | + | ||
| 145 | +```bash | ||
| 146 | +mkdir -p build && cd build | ||
| 147 | +cmake .. | ||
| 148 | +make -j | ||
| 149 | +./demo | ||
| 150 | +``` | ||
| 151 | + | ||
| 152 | +The default is SiLU with shape `[32,128]` on Device 0. Arguments are `demo [activation shape [cores]]`, where activation is `silu`, `gelu`, `swiglu` or `geglu`, and shape is comma-separated. cores is optional; an explicit value must be positive and no greater than the hardware Vector-core count. Actual core usage still depends on input size. | ||
| 153 | + | ||
| 154 | +```bash | ||
| 155 | +./demo gelu 65 | ||
| 156 | +./demo swiglu 2,3,17,65 | ||
| 157 | +./demo geglu 65537 1 | ||
| 158 | +``` | ||
| 159 | + | ||
| 160 | +**Table 3** Build options | ||
| 161 | + | ||
| 162 | +| Option | Values | Description | | ||
| 163 | +| --- | --- | --- | | ||
| 164 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510` (default) | NPU architecture. | | ||
| 165 | +| `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | Hardware or simulation; configure simulation in a separate build directory. | | ||
| 166 | + | ||
| 167 | +For simulation, configure a separate build directory from the sample root: | ||
| 168 | + | ||
| 169 | +```bash | ||
| 170 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 171 | +cmake --build build/sim --parallel | ||
| 172 | +./build/sim/demo | ||
| 173 | +``` | ||
| 174 | + | ||
| 175 | +Builds use the default optimization settings and `--cce-auto-sync=off`, with synchronization explicitly arranged in code. Simulation timing is not a hardware performance measurement. | ||
| 176 | + | ||
| 177 | +### Execution Result | ||
| 178 | + | ||
| 179 | +Running `./demo` automatically generates inputs and reference results and verifies every output. The following execution result indicates that the precision comparison is successful. Verification failures print `test failed!` and return a nonzero exit code. | ||
| 180 | + | ||
| 181 | +```text | ||
| 182 | +test pass! | ||
| 183 | +``` | ||
| 184 | + | ||
| 185 | +### Optional File Inputs | ||
| 186 | + | ||
| 187 | +To use file inputs, run the following from the build directory in an environment with CPU PyTorch and NumPy: | ||
| 188 | + | ||
| 189 | +```bash | ||
| 190 | +python3 ../scripts/gen_data.py --activation geglu --shape 32,128 --data-dir data | ||
| 191 | +./demo --files geglu 32,128 data/input/gate.bin data/input/up.bin data/output/output.bin | ||
| 192 | +python3 ../scripts/verify_result.py data/output/output.bin data/output/golden.bin --shape 32,128 | ||
| 193 | +``` | ||
| 194 | + | ||
| 195 | +Input and output files contain contiguous BF16 data with lengths matching shape. Single-input modes also require an up file. The generator creates the required directories; `PASS` from the verification script indicates success. | ||
| @@ -0,0 +1,385 @@ | |||
| 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 | +#include <cmath> | ||
| 12 | +#include <cstring> | ||
| 13 | +#include <fstream> | ||
| 14 | +#include <iostream> | ||
| 15 | +#include <string> | ||
| 16 | +#include <vector> | ||
| 17 | + | ||
| 18 | +#include "acl/acl.h" | ||
| 19 | +#include "c_api/asc_simd.h" | ||
| 20 | +#include "platform/platform_ascendc.h" | ||
| 21 | +#include "tiling.h" | ||
| 22 | + | ||
| 23 | +__simd_callee__ inline vector_float round_bfloat16(vector_float value, vector_bool mask) | ||
| 24 | +{ | ||
| 25 | + vector_bfloat16_t rounded; | ||
| 26 | + asc_float2bfloat16_rn(rounded, value, mask, ASC_POSITION_EVEN); | ||
| 27 | + asc_bfloat162float(value, rounded, mask, ASC_POSITION_EVEN); | ||
| 28 | + return value; | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +__simd_callee__ inline vector_float erf_subsection( | ||
| 32 | + vector_float source, vector_float ln2_vector, vector_float ones_vector, vector_bool mask) | ||
| 33 | +{ | ||
| 34 | + vector_float square; | ||
| 35 | + vector_float small; | ||
| 36 | + vector_float large; | ||
| 37 | + vector_float absolute; | ||
| 38 | + vector_float negative; | ||
| 39 | + asc_mul(square, source, source, mask); | ||
| 40 | + // For x = source and t = x*x, the small-interval approximation is x + x*P(t). | ||
| 41 | + // P(t) = c0 + t*(c1 + t*(c2 + t*(c3 + t*(c4 + t*(c5 + t*c6))))). | ||
| 42 | + // The scalar coefficients below are applied in descending order, c6 through c0. | ||
| 43 | + asc_mul_scalar(small, square, 0x1.63d2d40000000p-14f, mask); | ||
对应的标量建议用注释说明实现的公式 ![]() ![]() | |||
| 44 | + asc_add_scalar(small, small, -0x1.ae9a400000000p-11f, mask); | ||
| 45 | + asc_mul(small, square, small, mask); | ||
| 46 | + asc_add_scalar(small, small, 0x1.55abd40000000p-8f, mask); | ||
| 47 | + asc_mul(small, square, small, mask); | ||
| 48 | + asc_add_scalar(small, small, -0x1.b837ce0000000p-6f, mask); | ||
| 49 | + asc_mul(small, square, small, mask); | ||
| 50 | + asc_add_scalar(small, small, 0x1.ce315e0000000p-4f, mask); | ||
| 51 | + asc_mul(small, square, small, mask); | ||
| 52 | + asc_add_scalar(small, small, -0x1.8127580000000p-2f, mask); | ||
| 53 | + asc_mul(small, square, small, mask); | ||
| 54 | + asc_add_scalar(small, small, 0x1.06eba60000000p-3f, mask); | ||
| 55 | + asc_mul(small, source, small, mask); | ||
| 56 | + asc_add(small, small, source, mask); | ||
| 57 | + asc_abs(absolute, source, mask); | ||
| 58 | + // For a = abs(x), the large-interval approximation is sign(x)*(1 - exp(-ln(2)*a*(1 + Q(a)))). | ||
| 59 | + // Q(a) = d0 + a*(d1 + a*(d2 + a*(d3 + a*(d4 + a*(d5 + a*d6))))). | ||
| 60 | + // The scalar coefficients below are applied in descending order, d6 through d0. | ||
| 61 | + asc_mul_scalar(large, absolute, 0x1.d698740000000p-14f, mask); | ||
| 62 | + asc_add_scalar(large, large, -0x1.5c00b60000000p-10f, mask); | ||
| 63 | + asc_mul(large, absolute, large, mask); | ||
| 64 | + asc_add_scalar(large, large, 0x1.13233e0000000p-7f, mask); | ||
| 65 | + asc_mul(large, absolute, large, mask); | ||
| 66 | + asc_add_scalar(large, large, -0x1.49b3340000000p-5f, mask); | ||
| 67 | + asc_mul(large, absolute, large, mask); | ||
| 68 | + asc_add_scalar(large, large, 0x1.46aa320000000p-3f, mask); | ||
| 69 | + asc_mul(large, absolute, large, mask); | ||
| 70 | + asc_add_scalar(large, large, 0x1.d369f20000000p-1f, mask); | ||
| 71 | + asc_mul(large, absolute, large, mask); | ||
| 72 | + asc_add_scalar(large, large, 0x1.4214280000000p-1f, mask); | ||
| 73 | + asc_mul_scalar(negative, absolute, -1.0f, mask); | ||
| 74 | + asc_mul(large, negative, large, mask); | ||
| 75 | + asc_add(large, large, negative, mask); | ||
| 76 | + asc_mul(large, ln2_vector, large, mask); | ||
| 77 | + asc_exp(large, large, mask); | ||
| 78 | + asc_sub(large, ones_vector, large, mask); | ||
| 79 | + asc_mul_scalar(negative, large, -1.0f, mask); | ||
| 80 | + vector_bool positive = asc_ge_scalar(source, 0.0f, mask); | ||
| 81 | + asc_select(large, large, negative, positive); | ||
| 82 | + // Switch polynomial intervals at abs(x) = 0x1.00c1fcp+0 (FP32 bits 0x3F8060FE). | ||
| 83 | + vector_bool use_large = asc_ge_scalar(absolute, 0x1.00c1fc0000000p+0f, mask); | ||
| 84 | + asc_select(large, large, small, use_large); | ||
| 85 | + return large; | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +template <bool GELU, bool GATED> | ||
| 89 | +__simd_vf__ inline void activation_vf( | ||
| 90 | + __ubuf__ bfloat16_t* gate, __ubuf__ bfloat16_t* up, __ubuf__ bfloat16_t* output, uint32_t elements, uint16_t loops) | ||
| 91 | +{ | ||
| 92 | + vector_bool full_mask = asc_create_mask_b32(PAT_ALL); | ||
| 93 | + vector_float ones_vector; | ||
| 94 | + vector_float ln2_vector; | ||
| 95 | + // Broadcast 1 for 1 - exp(...) in Erf and 1 / (1 + exp(-g)) in SiLU. | ||
| 96 | + asc_duplicate_scalar(ones_vector, 1.0f, full_mask); | ||
| 97 | + if constexpr (GELU) { | ||
| 98 | + // Compute the natural logarithm ln(2) once, outside the vector loop. | ||
| 99 | + asc_duplicate_scalar(ln2_vector, 2.0f, full_mask); | ||
| 100 | + asc_ln(ln2_vector, ln2_vector, full_mask); | ||
| 101 | + } | ||
| 102 | + uint32_t remaining = elements; | ||
| 103 | + for (uint16_t index = 0; index < loops; ++index) { | ||
| 104 | + uint32_t offset = static_cast<uint32_t>(index) * VECTOR_ELEMENTS; | ||
| 105 | + vector_bool mask = asc_update_mask_b32(remaining); | ||
| 106 | + vector_bfloat16_t packed; | ||
| 107 | + vector_float value; | ||
| 108 | + vector_float result; | ||
| 109 | + asc_loadalign_unpack(packed, gate + offset); | ||
| 110 | + asc_bfloat162float(value, packed, mask, ASC_POSITION_EVEN); | ||
| 111 | + if constexpr (GELU) { | ||
| 112 | + // GELU(g) = (g / 2) * (1 + erf(g / sqrt(2))); scale the Erf input by 1/sqrt(2). | ||
| 113 | + asc_mul_scalar(result, value, 0.7071067811865476f, mask); | ||
| 114 | + result = round_bfloat16(result, mask); | ||
| 115 | + result = erf_subsection(result, ln2_vector, ones_vector, mask); | ||
| 116 | + result = round_bfloat16(result, mask); | ||
| 117 | + asc_add_scalar(result, result, 1.0f, mask); | ||
| 118 | + asc_mul_scalar(value, value, 0.5f, mask); | ||
| 119 | + asc_mul(result, value, result, mask); | ||
| 120 | + } else { | ||
| 121 | + // SiLU(g) = g / (1 + exp(-g)); -1 forms -g and +1 forms the denominator. | ||
| 122 | + asc_mul_scalar(result, value, -1.0f, mask); | ||
| 123 | + asc_exp(result, result, mask); | ||
| 124 | + asc_add_scalar(result, result, 1.0f, mask); | ||
| 125 | + asc_div(result, ones_vector, result, mask); | ||
| 126 | + result = round_bfloat16(result, mask); | ||
| 127 | + asc_mul(result, value, result, mask); | ||
| 128 | + } | ||
| 129 | + if constexpr (GATED) { | ||
| 130 | + asc_loadalign_unpack(packed, up + offset); | ||
| 131 | + asc_bfloat162float(value, packed, mask, ASC_POSITION_EVEN); | ||
| 132 | + asc_mul(result, result, value, mask); | ||
| 133 | + } | ||
| 134 | + asc_float2bfloat16_rn(packed, result, mask, ASC_POSITION_EVEN); | ||
| 135 | + asc_storealign_pack( | ||
| 136 | + reinterpret_cast<__ubuf__ float*>(output + offset), reinterpret_cast<vector_float&>(packed), mask); | ||
| 137 | + } | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +template <bool GELU, bool GATED> | ||
| 141 | +__global__ __vector__ void activation_kernel( | ||
| 142 | + __gm__ bfloat16_t* gate, __gm__ bfloat16_t* up, __gm__ bfloat16_t* output, ActivationTilingData tiling) | ||
| 143 | +{ | ||
| 144 | + asc_init(); | ||
| 145 | + __ubuf__ bfloat16_t arena[UB_ARENA_BYTES / sizeof(bfloat16_t)]; | ||
| 146 | + __ubuf__ bfloat16_t* gate_local = arena; | ||
| 147 | + __ubuf__ bfloat16_t* up_local = gate_local + 2 * tiling.tile_elements; | ||
| 148 | + __ubuf__ bfloat16_t* output_local = up_local + 2 * tiling.tile_elements; | ||
| 149 | + uint32_t first = block_idx * tiling.block_elements; | ||
| 150 | + uint32_t count = tiling.elements - first < tiling.block_elements ? tiling.elements - first : tiling.block_elements; | ||
| 151 | + uint32_t batches = AscendC::Std::ceil_div(count, tiling.tile_elements); | ||
| 152 | + uint32_t first_count = count < tiling.tile_elements ? count : tiling.tile_elements; | ||
| 153 | + asc_copy_gm2ub(gate_local, gate + first, first_count * sizeof(bfloat16_t)); | ||
| 154 | + if constexpr (GATED) { | ||
| 155 | + asc_copy_gm2ub(up_local, up + first, first_count * sizeof(bfloat16_t)); | ||
| 156 | + } | ||
| 157 | + asc_sync_notify(PIPE_MTE2, PIPE_V, EVENT_ID0); | ||
| 158 | + for (uint32_t batch = 0; batch < batches; ++batch) { | ||
| 159 | + uint32_t slot = batch % 2; | ||
| 160 | + event_t event = static_cast<event_t>(slot); | ||
| 161 | + uint32_t begin = batch * tiling.tile_elements; | ||
| 162 | + uint32_t current = count - begin < tiling.tile_elements ? count - begin : tiling.tile_elements; | ||
| 163 | + if (batch + 1 < batches) { | ||
| 164 | + uint32_t next_slot = 1 - slot; | ||
| 165 | + event_t next_event = static_cast<event_t>(next_slot); | ||
| 166 | + if (batch + 1 >= 2) { | ||
| 167 | + asc_sync_wait(PIPE_MTE3, PIPE_MTE2, next_event); | ||
| 168 | + } | ||
| 169 | + uint32_t next_begin = begin + tiling.tile_elements; | ||
| 170 | + uint32_t next_count = count - next_begin < tiling.tile_elements ? count - next_begin : tiling.tile_elements; | ||
| 171 | + asc_copy_gm2ub( | ||
| 172 | + gate_local + next_slot * tiling.tile_elements, gate + first + next_begin, | ||
| 173 | + next_count * sizeof(bfloat16_t)); | ||
| 174 | + if constexpr (GATED) { | ||
| 175 | + asc_copy_gm2ub( | ||
| 176 | + up_local + next_slot * tiling.tile_elements, up + first + next_begin, | ||
| 177 | + next_count * sizeof(bfloat16_t)); | ||
| 178 | + } | ||
| 179 | + asc_sync_notify(PIPE_MTE2, PIPE_V, next_event); | ||
| 180 | + } | ||
| 181 | + asc_sync_wait(PIPE_MTE2, PIPE_V, event); | ||
| 182 | + activation_vf<GELU, GATED>( | ||
| 183 | + gate_local + slot * tiling.tile_elements, up_local + slot * tiling.tile_elements, | ||
| 184 | + output_local + slot * tiling.tile_elements, current, | ||
| 185 | + static_cast<uint16_t>(AscendC::Std::ceil_div(current, VECTOR_ELEMENTS))); | ||
| 186 | + asc_sync_notify(PIPE_V, PIPE_MTE3, event); | ||
| 187 | + asc_sync_wait(PIPE_V, PIPE_MTE3, event); | ||
| 188 | + asc_copy_ub2gm( | ||
| 189 | + output + first + begin, output_local + slot * tiling.tile_elements, current * sizeof(bfloat16_t)); | ||
| 190 | + if (batch + 2 < batches) { | ||
| 191 | + asc_sync_notify(PIPE_MTE3, PIPE_MTE2, event); | ||
| 192 | + } | ||
| 193 | + } | ||
| 194 | + asc_sync(); | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +void check_acl(aclError status) | ||
| 198 | +{ | ||
| 199 | + if (status != ACL_SUCCESS) | ||
| 200 | + throw std::runtime_error("ACL error: " + std::to_string(status)); | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +struct DeviceBuffer { | ||
| 204 | + void* data = nullptr; | ||
| 205 | + explicit DeviceBuffer(size_t bytes) { check_acl(aclrtMalloc(&data, bytes, ACL_MEM_MALLOC_HUGE_FIRST)); } | ||
| 206 | + ~DeviceBuffer() | ||
| 207 | + { | ||
| 208 | + if (data != nullptr) | ||
| 209 | + aclrtFree(data); | ||
| 210 | + } | ||
| 211 | + DeviceBuffer(const DeviceBuffer&) = delete; | ||
| 212 | + DeviceBuffer& operator=(const DeviceBuffer&) = delete; | ||
| 213 | +}; | ||
| 214 | + | ||
| 215 | +uint16_t to_bfloat16(float value) | ||
| 216 | +{ | ||
| 217 | + uint32_t bits; | ||
| 218 | + std::memcpy(&bits, &value, sizeof(bits)); | ||
| 219 | + return static_cast<uint16_t>((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +float from_bfloat16(uint16_t value) | ||
| 223 | +{ | ||
| 224 | + uint32_t bits = static_cast<uint32_t>(value) << 16; | ||
| 225 | + float result; | ||
| 226 | + std::memcpy(&result, &bits, sizeof(result)); | ||
| 227 | + return result; | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +void read_tensor(const std::string& path, std::vector<uint16_t>& data) | ||
| 231 | +{ | ||
| 232 | + std::ifstream input(path, std::ios::binary | std::ios::ate); | ||
| 233 | + size_t bytes = data.size() * sizeof(uint16_t); | ||
| 234 | + if (!input || input.tellg() != static_cast<std::streamoff>(bytes)) { | ||
| 235 | + throw std::invalid_argument("Wrong BF16 tensor file size: " + path); | ||
| 236 | + } | ||
| 237 | + input.seekg(0); | ||
| 238 | + input.read(reinterpret_cast<char*>(data.data()), bytes); | ||
| 239 | + if (!input) | ||
| 240 | + throw std::runtime_error("Unable to read " + path); | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +bool run_case( | ||
| 244 | + Activation activation, const std::vector<uint32_t>& shape, uint32_t cores, uint64_t ub_bytes, | ||
| 245 | + const std::vector<std::string>& paths = {}) | ||
| 246 | +{ | ||
| 247 | + auto tiling = make_tiling(shape, cores, ub_bytes); | ||
| 248 | + constexpr size_t GUARD_ELEMENTS = 128; | ||
| 249 | + size_t elements = tiling.elements; | ||
| 250 | + std::vector<uint16_t> gate(elements); | ||
| 251 | + std::vector<uint16_t> up(elements); | ||
| 252 | + std::vector<uint16_t> output(elements + 2 * GUARD_ELEMENTS, 0x55aau); | ||
| 253 | + for (size_t index = 0; index < elements; ++index) { | ||
| 254 | + float value = (static_cast<int32_t>((index * 613 + 19) % 8193) - 4096) / 256.0f; | ||
| 255 | + if (index % 7 == 0) | ||
| 256 | + value *= 0.00001f; | ||
| 257 | + gate[index] = to_bfloat16(value); | ||
| 258 | + up[index] = to_bfloat16((static_cast<int32_t>((index * 127 + 7) % 1025) - 512) / 128.0f); | ||
| 259 | + } | ||
| 260 | + if (!paths.empty()) { | ||
| 261 | + read_tensor(paths[0], gate); | ||
| 262 | + read_tensor(paths[1], up); | ||
| 263 | + } | ||
| 264 | + size_t bytes = elements * sizeof(uint16_t); | ||
| 265 | + DeviceBuffer gate_device(bytes + 256); | ||
| 266 | + DeviceBuffer up_device(bytes + 256); | ||
| 267 | + DeviceBuffer output_device(output.size() * sizeof(uint16_t)); | ||
| 268 | + check_acl(aclrtMemcpy(gate_device.data, bytes, gate.data(), bytes, ACL_MEMCPY_HOST_TO_DEVICE)); | ||
| 269 | + check_acl(aclrtMemcpy(up_device.data, bytes, up.data(), bytes, ACL_MEMCPY_HOST_TO_DEVICE)); | ||
| 270 | + check_acl(aclrtMemcpy( | ||
| 271 | + output_device.data, output.size() * sizeof(uint16_t), output.data(), output.size() * sizeof(uint16_t), | ||
| 272 | + ACL_MEMCPY_HOST_TO_DEVICE)); | ||
| 273 | + auto gate_ptr = static_cast<bfloat16_t*>(gate_device.data); | ||
| 274 | + auto up_ptr = static_cast<bfloat16_t*>(up_device.data); | ||
| 275 | + auto output_ptr = static_cast<bfloat16_t*>(output_device.data) + GUARD_ELEMENTS; | ||
| 276 | + switch (activation) { | ||
| 277 | + case Activation::SILU: | ||
| 278 | + activation_kernel<false, false> | ||
| 279 | + <<<tiling.used_core_num, nullptr, nullptr>>>(gate_ptr, up_ptr, output_ptr, tiling); | ||
| 280 | + break; | ||
| 281 | + case Activation::GELU: | ||
| 282 | + activation_kernel<true, false> | ||
| 283 | + <<<tiling.used_core_num, nullptr, nullptr>>>(gate_ptr, up_ptr, output_ptr, tiling); | ||
| 284 | + break; | ||
| 285 | + case Activation::SWIGLU: | ||
| 286 | + activation_kernel<false, true> | ||
| 287 | + <<<tiling.used_core_num, nullptr, nullptr>>>(gate_ptr, up_ptr, output_ptr, tiling); | ||
| 288 | + break; | ||
| 289 | + case Activation::GEGLU: | ||
| 290 | + activation_kernel<true, true> | ||
| 291 | + <<<tiling.used_core_num, nullptr, nullptr>>>(gate_ptr, up_ptr, output_ptr, tiling); | ||
| 292 | + break; | ||
| 293 | + } | ||
| 294 | + check_acl(aclrtSynchronizeDevice()); | ||
| 295 | + check_acl(aclrtMemcpy( | ||
| 296 | + output.data(), output.size() * sizeof(uint16_t), output_device.data, output.size() * sizeof(uint16_t), | ||
| 297 | + ACL_MEMCPY_DEVICE_TO_HOST)); | ||
| 298 | + bool gelu = activation == Activation::GELU || activation == Activation::GEGLU; | ||
| 299 | + bool gated = activation == Activation::SWIGLU || activation == Activation::GEGLU; | ||
| 300 | + size_t failures = 0; | ||
| 301 | + double max_error = 0; | ||
| 302 | + for (size_t index = 0; index < elements; ++index) { | ||
| 303 | + double value = from_bfloat16(gate[index]); | ||
| 304 | + double expected; | ||
| 305 | + if (gelu) { | ||
| 306 | + double scaled = from_bfloat16(to_bfloat16(static_cast<float>(value) * 0.7071067811865476f)); | ||
| 307 | + double erf_value = from_bfloat16(to_bfloat16(static_cast<float>(std::erf(scaled)))); | ||
| 308 | + expected = value * 0.5 * (erf_value + 1.0); | ||
| 309 | + } else { | ||
| 310 | + double sigmoid = from_bfloat16(to_bfloat16(static_cast<float>(1.0 / (1.0 + std::exp(-value))))); | ||
| 311 | + expected = value * sigmoid; | ||
| 312 | + } | ||
| 313 | + if (gated) | ||
| 314 | + expected *= from_bfloat16(up[index]); | ||
| 315 | + expected = from_bfloat16(to_bfloat16(static_cast<float>(expected))); | ||
| 316 | + double actual = from_bfloat16(output[GUARD_ELEMENTS + index]); | ||
| 317 | + double error = std::abs(actual - expected); | ||
| 318 | + max_error = std::max(max_error, error); | ||
| 319 | + if (!std::isfinite(actual) || error > 0.001 + 0.008 * std::abs(expected)) { | ||
| 320 | + if (failures < 3) | ||
| 321 | + std::cerr << "Mismatch at " << index << ": " << actual << " vs " << expected << '\n'; | ||
| 322 | + ++failures; | ||
| 323 | + } | ||
| 324 | + } | ||
| 325 | + for (size_t index = 0; index < GUARD_ELEMENTS; ++index) { | ||
| 326 | + if (output[index] != 0x55aau || output[GUARD_ELEMENTS + elements + index] != 0x55aau) | ||
| 327 | + ++failures; | ||
| 328 | + } | ||
| 329 | + if (!paths.empty()) { | ||
| 330 | + std::ofstream result(paths[2], std::ios::binary); | ||
| 331 | + result.write(reinterpret_cast<const char*>(output.data() + GUARD_ELEMENTS), bytes); | ||
| 332 | + if (!result) | ||
| 333 | + throw std::runtime_error("Unable to write output"); | ||
| 334 | + } | ||
| 335 | + std::cout << "activation=" << static_cast<uint32_t>(activation) << " elements=" << elements | ||
| 336 | + << " cores=" << tiling.used_core_num << " tile=" << tiling.tile_elements << " max_error=" << max_error | ||
| 337 | + << " guard=checked " << (failures == 0 ? "PASS" : "FAIL") << '\n'; | ||
| 338 | + std::cout << (failures == 0 ? "test pass!" : "test failed!") << '\n'; | ||
| 339 | + return failures == 0; | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +int main(int argc, char** argv) | ||
| 343 | +{ | ||
| 344 | + bool initialized = false; | ||
| 345 | + bool device_set = false; | ||
| 346 | + int status = 1; | ||
| 347 | + try { | ||
| 348 | + bool files = (argc == 7 || argc == 8) && std::string(argv[1]) == "--files"; | ||
| 349 | + if (argc != 1 && argc != 3 && argc != 4 && !files) { | ||
| 350 | + throw std::invalid_argument( | ||
| 351 | + "Usage: demo [activation shape [cores]] | --files activation shape gate.bin up.bin output.bin [cores]"); | ||
| 352 | + } | ||
| 353 | + Activation activation = parse_activation(argc >= 3 ? argv[files ? 2 : 1] : "silu"); | ||
| 354 | + auto shape = parse_shape(argc >= 3 ? argv[files ? 3 : 2] : "32,128"); | ||
| 355 | + make_tiling(shape, 1, UB_ARENA_BYTES + UB_RESERVED_BYTES); | ||
| 356 | + check_acl(aclInit(nullptr)); | ||
| 357 | + initialized = true; | ||
| 358 | + check_acl(aclrtSetDevice(0)); | ||
| 359 | + device_set = true; | ||
| 360 | + auto platform = platform_ascendc::PlatformAscendCManager::GetInstance(); | ||
| 361 | + if (platform == nullptr) | ||
| 362 | + throw std::runtime_error("Unable to query Ascend platform"); | ||
| 363 | + uint64_t ub_bytes = 0; | ||
| 364 | + platform->GetCoreMemSize(platform_ascendc::CoreMemType::UB, ub_bytes); | ||
| 365 | + uint32_t cores = platform->GetCoreNumAiv(); | ||
| 366 | + if (argc == 4 || (files && argc == 8)) { | ||
| 367 | + auto requested = parse_shape(argv[files ? 7 : 3]); | ||
| 368 | + if (requested.size() != 1 || requested[0] > cores) | ||
| 369 | + throw std::invalid_argument("Invalid core count"); | ||
| 370 | + cores = requested[0]; | ||
| 371 | + } | ||
| 372 | + std::vector<std::string> paths; | ||
| 373 | + if (files) | ||
| 374 | + paths = {argv[4], argv[5], argv[6]}; | ||
| 375 | + bool passed = run_case(activation, shape, cores, ub_bytes, paths); | ||
| 376 | + status = passed ? 0 : 1; | ||
| 377 | + } catch (const std::exception& error) { | ||
| 378 | + std::cerr << error.what() << std::endl; | ||
| 379 | + } | ||
| 380 | + if (device_set && aclrtResetDevice(0) != ACL_SUCCESS) | ||
| 381 | + status = 1; | ||
| 382 | + if (initialized && aclFinalize() != ACL_SUCCESS) | ||
| 383 | + status = 1; | ||
| 384 | + return status; | ||
| 385 | +} | ||
| @@ -0,0 +1,84 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +import argparse | ||
| 13 | +import math | ||
| 14 | +import os | ||
| 15 | +from pathlib import Path | ||
| 16 | + | ||
| 17 | +os.environ.setdefault("TORCH_DEVICE_BACKEND_AUTOLOAD", "0") | ||
| 18 | + | ||
| 19 | +import torch | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def parse_shape(text): | ||
| 23 | + dimensions = text.split(",") | ||
| 24 | + if not 1 <= len(dimensions) <= 4 or any(not value.isascii() or not value.isdigit() for value in dimensions): | ||
| 25 | + raise argparse.ArgumentTypeError("Shape must contain 1..4 positive comma-separated integers") | ||
| 26 | + shape = tuple(int(value) for value in dimensions) | ||
| 27 | + if any(value <= 0 for value in shape) or math.prod(shape) > 2147483647: | ||
| 28 | + raise argparse.ArgumentTypeError("Shape product must be in [1, INT32_MAX]") | ||
| 29 | + return shape | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def activation_golden(gate, up, activation): | ||
| 33 | + value = gate.float() | ||
| 34 | + if activation in ("gelu", "geglu"): | ||
| 35 | + scaled = (value * 0.7071067811865476).bfloat16().double() | ||
| 36 | + erf_value = torch.erf(scaled).float().bfloat16().float() | ||
| 37 | + result = (value * 0.5) * (erf_value + 1.0) | ||
| 38 | + else: | ||
| 39 | + sigmoid = torch.sigmoid(value.double()).float().bfloat16().float() | ||
| 40 | + result = value * sigmoid | ||
| 41 | + if activation in ("swiglu", "geglu"): | ||
| 42 | + result = result * up.float() | ||
| 43 | + return result.bfloat16() | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def save_bfloat16(path, tensor): | ||
| 47 | + tensor.contiguous().view(torch.int16).numpy().tofile(path) | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def gen_golden_data(activation, shape, data_dir, seed): | ||
| 51 | + data_dir = Path(data_dir) | ||
| 52 | + input_dir = data_dir / "input" | ||
| 53 | + output_dir = data_dir / "output" | ||
| 54 | + input_dir.mkdir(parents=True, exist_ok=True) | ||
| 55 | + output_dir.mkdir(parents=True, exist_ok=True) | ||
| 56 | + generator = torch.Generator(device="cpu").manual_seed(seed) | ||
| 57 | + count = math.prod(shape) | ||
| 58 | + gate = (torch.rand(count, generator=generator) * 32.0 - 16.0).bfloat16() | ||
| 59 | + up = (torch.rand(count, generator=generator) * 8.0 - 4.0).bfloat16() | ||
| 60 | + indices = torch.arange(count) | ||
| 61 | + gate[indices % 7 == 0] *= 0.00001 | ||
| 62 | + boundaries = torch.tensor( | ||
| 63 | + [0.0, -0.0, -16.0, 16.0, -1.421875, -1.4140625, 1.4140625, 1.421875, -0.00390625, 0.00390625], | ||
| 64 | + dtype=torch.bfloat16, | ||
| 65 | + ) | ||
| 66 | + copied = min(count, boundaries.numel()) | ||
| 67 | + gate[:copied] = boundaries[:copied] | ||
| 68 | + gate = gate.reshape(shape) | ||
| 69 | + up = up.reshape(shape) | ||
| 70 | + golden = activation_golden(gate, up, activation) | ||
| 71 | + save_bfloat16(input_dir / "gate.bin", gate) | ||
| 72 | + save_bfloat16(input_dir / "up.bin", up) | ||
| 73 | + save_bfloat16(output_dir / "golden.bin", golden) | ||
| 74 | + print(f"Generated {activation} shape={shape} dtype=bfloat16 seed={seed} in {data_dir}") | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +if __name__ == "__main__": | ||
| 78 | + parser = argparse.ArgumentParser(description="Generate BF16 activation inputs and Torch golden data") | ||
| 79 | + parser.add_argument("--activation", choices=["silu", "gelu", "swiglu", "geglu"], default="silu") | ||
| 80 | + parser.add_argument("--shape", type=parse_shape, default=parse_shape("32,128")) | ||
| 81 | + parser.add_argument("--data-dir", type=Path, default=Path(".")) | ||
| 82 | + parser.add_argument("--seed", type=int, default=20261026) | ||
| 83 | + arguments = parser.parse_args() | ||
| 84 | + gen_golden_data(arguments.activation, arguments.shape, arguments.data_dir, arguments.seed) | ||
| @@ -0,0 +1,59 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +import argparse | ||
| 13 | +import math | ||
| 14 | +import os | ||
| 15 | +from pathlib import Path | ||
| 16 | + | ||
| 17 | +os.environ.setdefault("TORCH_DEVICE_BACKEND_AUTOLOAD", "0") | ||
| 18 | + | ||
| 19 | +import numpy as np | ||
| 20 | +import torch | ||
| 21 | + | ||
| 22 | +from gen_data import parse_shape | ||
| 23 | + | ||
| 24 | +ABSOLUTE_TOL = 0.001 | ||
| 25 | +RELATIVE_TOL = 0.008 | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def read_bfloat16(path, elements): | ||
| 29 | + if path.stat().st_size != elements * 2: | ||
| 30 | + raise ValueError(f"Wrong BF16 file size: {path}, expected {elements * 2} bytes") | ||
| 31 | + bits = np.fromfile(path, dtype=np.int16) | ||
| 32 | + return torch.from_numpy(bits).view(torch.bfloat16).float() | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def verify_result(output_path, golden_path, shape): | ||
| 36 | + elements = math.prod(shape) | ||
| 37 | + output = read_bfloat16(output_path, elements) | ||
| 38 | + golden = read_bfloat16(golden_path, elements) | ||
| 39 | + difference = (output - golden).abs() | ||
| 40 | + matched = ( | ||
| 41 | + torch.isfinite(output) & torch.isfinite(golden) & (difference <= ABSOLUTE_TOL + RELATIVE_TOL * golden.abs()) | ||
| 42 | + ) | ||
| 43 | + mismatches = torch.nonzero(~matched).flatten() | ||
| 44 | + for index in mismatches[:10].tolist(): | ||
| 45 | + print(f"Mismatch at {index}: output={output[index].item()} golden={golden[index].item()}") | ||
| 46 | + print( | ||
| 47 | + f"Torch golden: elements={elements} mismatches={mismatches.numel()} " | ||
| 48 | + f"max_error={difference.max().item()} {'PASS' if mismatches.numel() == 0 else 'FAIL'}" | ||
| 49 | + ) | ||
| 50 | + return mismatches.numel() == 0 | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +if __name__ == "__main__": | ||
| 54 | + parser = argparse.ArgumentParser(description="Verify BF16 activation output against Torch golden") | ||
| 55 | + parser.add_argument("output", type=Path) | ||
| 56 | + parser.add_argument("golden", type=Path) | ||
| 57 | + parser.add_argument("--shape", type=parse_shape, default=parse_shape("32,128")) | ||
| 58 | + arguments = parser.parse_args() | ||
| 59 | + raise SystemExit(0 if verify_result(arguments.output, arguments.golden, arguments.shape) else 1) | ||
| @@ -0,0 +1,91 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef ACTIVATION_TILING_H | ||
| 12 | +#define ACTIVATION_TILING_H | ||
| 13 | + | ||
| 14 | +#include <algorithm> | ||
| 15 | +#include <cstdint> | ||
| 16 | +#include <stdexcept> | ||
| 17 | +#include <string> | ||
| 18 | +#include <vector> | ||
| 19 | + | ||
| 20 | +#include "utils/std/cmath.h" | ||
| 21 | + | ||
| 22 | +constexpr uint32_t VECTOR_ELEMENTS = 64; | ||
| 23 | +constexpr uint32_t MAX_TILE_ELEMENTS = 8192; | ||
| 24 | +constexpr uint32_t UB_ARENA_BYTES = MAX_TILE_ELEMENTS * 2 * 6; | ||
| 25 | +constexpr uint32_t UB_RESERVED_BYTES = 8192; | ||
| 26 | + | ||
| 27 | +enum class Activation : uint32_t { SILU, GELU, SWIGLU, GEGLU }; | ||
| 28 | + | ||
| 29 | +struct ActivationTilingData { | ||
| 30 | + uint32_t elements; | ||
| 31 | + uint32_t used_core_num; | ||
| 32 | + uint32_t block_elements; | ||
| 33 | + uint32_t tile_elements; | ||
| 34 | +}; | ||
| 35 | + | ||
| 36 | +inline Activation parse_activation(const std::string& name) | ||
| 37 | +{ | ||
| 38 | + if (name == "silu") | ||
| 39 | + return Activation::SILU; | ||
| 40 | + if (name == "gelu") | ||
| 41 | + return Activation::GELU; | ||
| 42 | + if (name == "swiglu") | ||
| 43 | + return Activation::SWIGLU; | ||
| 44 | + if (name == "geglu") | ||
| 45 | + return Activation::GEGLU; | ||
| 46 | + throw std::invalid_argument("Activation must be silu, gelu, swiglu or geglu"); | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +inline std::vector<uint32_t> parse_shape(const std::string& text) | ||
| 50 | +{ | ||
| 51 | + std::vector<uint32_t> shape; | ||
| 52 | + uint64_t value = 0; | ||
| 53 | + bool has_digit = false; | ||
| 54 | + for (char character : text + ",") { | ||
| 55 | + if (character >= '0' && character <= '9') { | ||
| 56 | + value = value * 10 + character - '0'; | ||
| 57 | + if (value > INT32_MAX) | ||
| 58 | + throw std::invalid_argument("Shape dimension overflow"); | ||
| 59 | + has_digit = true; | ||
| 60 | + } else if (character == ',' && has_digit && value != 0) { | ||
| 61 | + shape.push_back(static_cast<uint32_t>(value)); | ||
| 62 | + value = 0; | ||
| 63 | + has_digit = false; | ||
| 64 | + } else { | ||
| 65 | + throw std::invalid_argument("Shape must contain positive comma-separated integers"); | ||
| 66 | + } | ||
| 67 | + } | ||
| 68 | + return shape; | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +inline ActivationTilingData make_tiling(const std::vector<uint32_t>& shape, uint32_t core_count, uint64_t ub_bytes) | ||
| 72 | +{ | ||
| 73 | + if (shape.empty() || shape.size() > 4 || core_count == 0 || ub_bytes < UB_ARENA_BYTES + UB_RESERVED_BYTES) { | ||
| 74 | + throw std::invalid_argument("Requires rank 1..4, positive core count and at least 104 KiB UB"); | ||
| 75 | + } | ||
| 76 | + uint64_t elements = 1; | ||
| 77 | + for (uint32_t dimension : shape) { | ||
| 78 | + if (dimension == 0 || elements > INT32_MAX / dimension) { | ||
| 79 | + throw std::invalid_argument("Shape product must be in [1, INT32_MAX]"); | ||
| 80 | + } | ||
| 81 | + elements *= dimension; | ||
| 82 | + } | ||
| 83 | + uint32_t count = static_cast<uint32_t>(elements); | ||
| 84 | + uint32_t wanted_cores = std::min(core_count, AscendC::Std::ceil_div(count, 4096u)); | ||
| 85 | + uint32_t vectors = AscendC::Std::ceil_div(count, VECTOR_ELEMENTS); | ||
| 86 | + uint32_t block = AscendC::Std::ceil_div(vectors, wanted_cores) * VECTOR_ELEMENTS; | ||
| 87 | + uint32_t used = AscendC::Std::ceil_div(count, block); | ||
| 88 | + return {count, used, block, std::min(block, MAX_TILE_ELEMENTS)}; | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +#endif | ||
| @@ -0,0 +1,47 @@ | |||
| 1 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +cmake_minimum_required(VERSION 3.16) | ||
| 12 | + | ||
| 13 | +set(CMAKE_ASC_RUN_MODE "npu" CACHE STRING "Run mode: npu, sim") | ||
| 14 | +set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510") | ||
| 15 | + | ||
| 16 | +find_package(ASC REQUIRED) | ||
| 17 | + | ||
| 18 | +project(kernel_samples LANGUAGES ASC CXX) | ||
| 19 | + | ||
| 20 | +add_executable(demo | ||
| 21 | + flash_attention.asc | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510") | ||
| 25 | + message(FATAL_ERROR "This sample only supports CMAKE_ASC_ARCHITECTURES=dav-3510") | ||
| 26 | +endif() | ||
| 27 | + | ||
| 28 | +if(NOT CMAKE_ASC_RUN_MODE MATCHES "^(npu|sim)$") | ||
| 29 | + message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be npu or sim, but got ${CMAKE_ASC_RUN_MODE}") | ||
| 30 | +endif() | ||
| 31 | + | ||
| 32 | +if(CMAKE_ASC_RUN_MODE STREQUAL "sim") | ||
| 33 | + target_compile_definitions(demo PRIVATE SIM_COMPATIBLE) | ||
| 34 | +endif() | ||
| 35 | + | ||
| 36 | +target_link_libraries(demo PRIVATE | ||
| 37 | + tiling_api | ||
| 38 | + register | ||
| 39 | + platform | ||
| 40 | + m | ||
| 41 | +) | ||
| 42 | + | ||
| 43 | +target_compile_options(demo PRIVATE | ||
| 44 | + $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}> | ||
| 45 | + $<$<COMPILE_LANGUAGE:ASC>:-O3> | ||
| 46 | + $<$<COMPILE_LANGUAGE:ASC>:--cce-auto-sync=off> | ||
| 47 | +) | ||
| @@ -0,0 +1,228 @@ | |||
| 1 | +# FlashAttention样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
| 4 | + | ||
| 5 | +本样例使用Ascend C C API实现BF16因果FlashAttention,Q、K、V和O均采用连续`[B,N,S,128]`布局,其中B为批次数,N为注意力头数,S为序列长度,128为每个头的维度。支持运行时配置B、N和S,通过Cube核与Vector核协作分块完成计算,不在外部存储(Global Memory,GM)中保存完整注意力矩阵。 | ||
| 6 | + | ||
| 7 | +## 本样例支持的产品及CANN软件版本 | ||
| 8 | + | ||
| 9 | +| 产品 | CANN软件版本 | | ||
| 10 | +|------|-------------| | ||
| 11 | +| Ascend 950PR&950DT系列产品 | >= CANN 9.3.0 | | ||
| 12 | + | ||
| 13 | +本样例固定使用`dav-3510`架构,仅支持NPU和仿真运行模式。 | ||
| 14 | + | ||
| 15 | +## 目录结构 | ||
| 16 | + | ||
| 17 | +```text | ||
| 18 | +attention | ||
| 19 | +├── CMakeLists.txt # 编译工程文件 | ||
| 20 | +├── flash_attention.asc # 公共辅助函数、AIC/AIV计算及Host入口 | ||
| 21 | +├── tiling.h # 共享类型、分核及片上存储布局 | ||
| 22 | +├── README.md | ||
| 23 | +└── README_en.md | ||
| 24 | +``` | ||
| 25 | + | ||
| 26 | +## 样例描述 | ||
| 27 | + | ||
| 28 | +本样例用于多头自注意力计算。Q、K、V分别表示查询、键和值,三者的批次数B、注意力头数N和序列长度S相同,每个头的维度固定为128。下文“一行Q”表示一个序列位置的128个查询分量。每行Q只关注同一批次、同一注意力头中当前位置及之前的K,不能关注未来位置。样例只输出O,不输出注意力权重或Softmax统计量。 | ||
| 29 | + | ||
| 30 | +输入输出均为BF16,矩阵乘累加、Softmax状态及输出累加使用FP32。scale默认为`1/sqrt(128)`,也支持其他非零有限FP32值,包括负值。序列长度不要求是128的整数倍,尾块在片上补齐并按有效行列计算,不要求Host给Q/K/V补齐。B、N、S必须为正整数,并满足`B*N*S≤131072`。不支持Q/K/V头数不同的分组查询注意力(GQA)和多查询注意力(MQA)、不同Q/K序列长度、非因果模式、额外注意力掩码、位置编码、分页注意力、量化、随机丢弃(Dropout)及反向计算。 | ||
| 31 | + | ||
| 32 | +对每个批次和注意力头,数学行为为: | ||
| 33 | + | ||
| 34 | +$$ | ||
| 35 | +s_{i,j}=scale\cdot\sum_{d=0}^{127}Q_{i,d}K_{j,d},\qquad | ||
| 36 | +p_{i,j}=\frac{\exp(s_{i,j})}{\sum_{k=0}^{i}\exp(s_{i,k})}\quad(0\leq j\leq i) | ||
| 37 | +$$ | ||
| 38 | + | ||
| 39 | +$$ | ||
| 40 | +O_{i,d}=\sum_{j=0}^{i}p_{i,j}V_{j,d} | ||
| 41 | +$$ | ||
| 42 | + | ||
| 43 | +实际计算以128行Q和128行K/V为块,分块更新Softmax和输出,不构造完整的`S×S`矩阵。块内指数值在参与第二次矩阵乘前转换为BF16,分母仍由FP32指数值累加,最终结果经FP32除法后转为BF16,因此不保证与一次性高精度公式逐位一致。 | ||
| 44 | + | ||
| 45 | +**表1** 输入输出数据规格 | ||
| 46 | + | ||
| 47 | +| 数据 | 输入/输出 | 数据类型 | 默认Shape | 说明 | | ||
| 48 | +| --- | --- | --- | --- | --- | | ||
| 49 | +| Q、K、V | 输入 | BF16 | `[1,2,257,128]` | Host生成确定性数据,先舍入到BF16再上传。 | | ||
| 50 | +| O | 输出 | BF16 | `[1,2,257,128]` | 与输入同shape,按BNSD紧密连续存放。 | | ||
| 51 | +| scale | 参数 | FP32 | 标量 | 非零有限值,默认为`1/sqrt(128)`。 | | ||
| 52 | +| 参考结果 | 校验 | double | 与O对应 | 使用实际BF16输入计算因果Softmax参考值,不参与核内计算。 | | ||
| 53 | + | ||
| 54 | +### 计算流程与术语 | ||
| 55 | + | ||
| 56 | +每个Cube核(AIC)与两个Vector核(AIV)协作。一次任务处理128行Q,并分批读取它们能够关注的K/V,每批最多128行: | ||
| 57 | + | ||
| 58 | +1. Cube核计算`Q*Kᵀ`,得到当前块的注意力分数;Vector核再乘以scale。 | ||
| 59 | +2. Vector核更新Softmax的最大值和指数和,并生成参与下一次矩阵乘的BF16指数值,代码中记为P。这里的P尚未除以Softmax分母,不等同于公式中的归一化权重p。 | ||
| 60 | +3. Cube核计算`P*V`;Vector核将结果累加到当前Q块的输出中。 | ||
| 61 | +4. 所有可见K/V块处理完后,Vector核将累加结果除以Softmax分母,转换为BF16并写回外部存储(Global Memory,GM)。 | ||
| 62 | + | ||
| 63 | +L1、L0A、L0B和L0C Buffer(缓冲区)服务于矩阵计算;Unified Buffer(UB)存放矢量计算的中间数据;向量函数(Vector Function,VF)在寄存器上完成矢量计算。下文的存储、双缓冲和同步说明沿用Ascend C文档用语,可结合[内存层级](../../../../docs/zh/guide/programming_guide/programming_model/ai_core_simd_programming/c_pointer_programming/c_programming_overview.md#内存层级)及[基于Mutex实现多流水同步](../../../../docs/zh/guide/programming_guide/advanced_programming/advanced_kernel_programming/intra_core_sync/mutex_multi_pipeline_sync.md)阅读。 | ||
| 64 | + | ||
| 65 | +### 多核切分与Cube核、Vector核分工 | ||
| 66 | + | ||
| 67 | +**每个任务计算一个Q块的完整输出。** Q块高`br=128`,K/V块高`bc=128`,每个批次、每个注意力头包含`tr=ceil(S/128)`个Q块,任务总数为`T=B*N*tr`。请求核数为0或未指定时使用硬件可用Cube核数;否则使用指定值且不能超过硬件核数。实际使用`C=min(T,请求或硬件核数)`个Cube核,不分配无任务的核。核函数通过`__mix__(1,2)`配置每个Cube核与两个Vector核协作,下面以Cube核编号说明任务分配。 | ||
| 68 | + | ||
| 69 | +编号为k的Cube核及与其协作的两个Vector核处理任务`k,k+C,k+2C,...`,不是处理一个连续区间。任务编号先按批次、注意力头展开,再按Q块展开,代码中的索引关系为: | ||
| 70 | + | ||
| 71 | +```cpp | ||
| 72 | +const uint32_t batchHeadIdx = taskId / data.tr; | ||
| 73 | +const uint32_t tileIdx = taskId % data.tr; | ||
| 74 | +const uint32_t kvTileCount = GetKvTileCount<CAUSAL_MASK>(data, tileIdx); | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +其中`batchHeadIdx=b*N+n`,Q/O元素起点为`((b*N+n)*S+tileIdx*128)*128`。从0开始编号的第q个Q块只读取K/V块`0..q`,即`q+1`块;后面的整块都对应未来位置,可以直接跳过。越靠后的Q块要处理的K/V块越多,因此采用间隔分配,让不同Cube核分别承担较早和较晚的Q块,减轻工作量不均衡,但不保证任意shape下各核耗时相同。 | ||
| 78 | + | ||
| 79 | +例如,默认`[1,2,257,128]`的每个注意力头有3个Q块,共6个任务。若指定2个Cube核,第0个核处理任务0、2、4,即第0个注意力头的Q块0、2,以及第1个注意力头的Q块1;第1个核处理任务1、3、5。两者各处理6个K/V块。序列末块仅有1行有效Q,仍按固定块进行矩阵乘,但只由第一个Vector核写回1行,第二个Vector核不写回无效行。 | ||
| 80 | + | ||
| 81 | +**两个Vector核各负责64行Q。** Cube核完成`Q*Kᵀ`后,通过FIX流水搬运矩阵乘结果,分别送入两个Vector核的UB,每个Vector核负责64行Q。每个FP32向量寄存器的64个元素分别对应这64行Q;循环读取K的各行时,同时更新64行Q的最大值和指数和,不必逐行执行向量内归约。两个Vector核分别生成P并写入L1,供Cube核计算`P*V`;计算结果仍按相同的64行划分交给两个Vector核累加,各自维护输出,不需要与其他Cube核负责的任务合并结果。 | ||
| 82 | + | ||
| 83 | +### 片上存储与UB布局 | ||
| 84 | + | ||
| 85 | +每份缓冲区是一段固定大小的存储空间。双缓冲表示为同一类数据分配两份空间,交替用于搬运和计算;需要等待较晚阶段读取的数据则分配更多份,按编号循环复用。这里的份数表示实际分配的空间数量,不是计算轮数。随S增长只增加任务和K/V块数量,不扩大每个核使用的缓冲区。所有地址由`tiling.h`计算,Host检查容量后启动计算。 | ||
| 86 | + | ||
| 87 | +**表2** 每个Cube核的矩阵存储 | ||
| 88 | + | ||
| 89 | +| 存储 | 区域与缓冲区份数 | 实际占用 | 用途 | | ||
| 90 | +| --- | --- | --- | --- | | ||
| 91 | +| L1 | P五份160 KiB、K双缓冲64 KiB、Q双缓冲64 KiB、V五份160 KiB | 448 KiB | Q只搬入一次;P和V保留到对应的第二次矩阵乘完成读取。 | | ||
| 92 | +| L0A | 双缓冲 | 64 KiB | 两次矩阵乘的左操作数。 | | ||
| 93 | +| L0B | 双缓冲 | 64 KiB | 两次矩阵乘的右操作数。 | | ||
| 94 | +| L0C | 四份 | 256 KiB | 交错存放`Q*Kᵀ`和`P*V`的FP32结果,通过FIX流水搬出。 | | ||
| 95 | + | ||
| 96 | +L1按P、K、Q、V顺序排布,对应起始偏移为0、160、224、288 KiB。L0A/L0B以矩阵乘操作序号除以2的余数选择缓冲区,L0C以同一序号除以4的余数选择缓冲区。这里不能直接用K/V块号代替矩阵乘操作序号,因为每个K/V块都涉及两次矩阵乘,且两类矩阵乘交错执行。 | ||
| 97 | + | ||
| 98 | +Q/K/V通过MTE2数据搬运流水从GM搬入L1,同时由连续的ND格式转换为矩阵计算需要的NZ分形格式;不足128行时在L1补零。Q每任务仅搬入一次,供所有K/V块复用;K使用双缓冲接续搬入,V使用五份缓冲区,保留到对应的`P*V`计算读取它。L1到L0的搬运按矩阵乘需要使用转置接口,不另在GM中生成转置副本,减少额外搬运和中间存储。 | ||
| 99 | + | ||
| 100 | +**表3** 每个Vector核的UB布局(区域名对应代码变量) | ||
| 101 | + | ||
| 102 | +| 区域 | 字节偏移 | 容量 | 用途 | | ||
| 103 | +| --- | --- | --- | --- | | ||
| 104 | +| S双缓冲 | 0 | 65536字节 | 每份`128×64`个FP32分数;同一行K对应的64行Q分数连续存放。此处S是代码中的分数缓冲区名,不是序列长度。 | | ||
| 105 | +| deltaO双缓冲 | 65536 | 65536字节 | 每份`64×128`个FP32值,保存当前K/V块的`P*V`结果。 | | ||
| 106 | +| OAcc双缓冲 | 131072 | 65536字节 | 每份`64×128`个FP32值,累加已处理K/V块的输出,最终复用为BF16输出。 | | ||
| 107 | +| PWork双缓冲 | 196608 | 33024字节 | 每份可容纳`64×129`个BF16值,保存P及格式转换所需的补齐空间。 | | ||
| 108 | +| m | 229632 | 256字节 | 64行Q各一个FP32最大值。 | | ||
| 109 | +| l | 229888 | 256字节 | 64行Q各一个FP32 Softmax分母。 | | ||
| 110 | +| alpha五份 | 230144 | 1280字节 | 每份保存一个K/V块对应的64个FP32缩放系数,保留到该块的输出累加完成。 | | ||
| 111 | + | ||
| 112 | +每个Vector核合计使用231424字节,即226 KiB;m和l按Q行数存储,不为每行输出的128个分量重复保存。资源约束为至少512 KiB L1、64 KiB L0A、64 KiB L0B、256 KiB L0C、248 KiB UB;其中Host查询L1和UB,L0布局按目标架构固定容量检查。Q、K、V、O之外不分配GM工作区。 | ||
| 113 | + | ||
| 114 | +### 分块更新Softmax与数值稳定性 | ||
| 115 | + | ||
| 116 | +**读入一块K/V,就更新一次已有结果。** 这种逐块更新Softmax的方式也称为在线Softmax。对新K块的有效分数s,每行Q保存三个状态:已处理分数的最大值m、指数和l,以及尚未除以分母的输出累加值A(代码中为OAcc): | ||
| 117 | + | ||
| 118 | +$$ | ||
| 119 | +m'=\max(m,\max_j s_j),\quad \alpha=\exp(m-m'),\quad | ||
| 120 | +E_j=\exp(s_j-m') | ||
| 121 | +$$ | ||
| 122 | + | ||
| 123 | +$$ | ||
| 124 | +l'=\alpha l+\sum_j E_j,\qquad | ||
| 125 | +A'=\alpha A+\operatorname{BF16}(E)V,\qquad O=A/l | ||
| 126 | +$$ | ||
| 127 | + | ||
| 128 | +首块直接初始化状态,不读取旧m、l和A;后续块用alpha缩放之前累积的分母和输出,再加入当前块的结果。这样即使新块出现更大的分数,也能继续使用之前的计算结果。指数计算前减去当前最大值,避免直接对很大的正数求指数。实现用`asc_madd`完成分母和输出的乘加更新,每次处理两行Q的输出,复用控制和加载操作。该方法减少中间矩阵的GM读写及存储,不代表注意力计算量变为线性。 | ||
| 129 | + | ||
| 130 | +**同时处理四行K,减少连续更新同一变量的等待。** 最大值和指数和各使用四组独立变量,一次循环处理四行K,最后合并结果;不足四行的尾部单独处理。首块与后续块、对角块与非对角块在进入向量函数前选择对应模板,避免在每次矢量计算中重复判断。只有Q和K处于相同序列块的对角块需要逐元素判断未来位置,更早的整块无需这种判断。尾K块只处理`validBc`行,其余P位置清零。 | ||
| 131 | + | ||
| 132 | +对角块的Q/K起点相同,且块大小均为128,因此mask比较块内下标:Q为`subAivIdx*64+lane`,K为`keyRow`。两边共同的全局块偏移相消,不能只给Q下标加上`qTileIdx*128`。 | ||
| 133 | + | ||
| 134 | +### 流水并行与缓冲区复用 | ||
| 135 | + | ||
| 136 | +**计算后面的块时,继续处理前面块的结果。** 一个Q块通常需要读取多个K/V块。为减少Cube核等待Vector核的时间,代码不要求一个K/V块的所有步骤结束后才开始下一个块,而是交错执行不同块的矩阵计算、矢量计算和数据搬运。 | ||
| 137 | + | ||
| 138 | +具体到代码中的循环计数`epoch`:第j个K/V块在Cube侧第j轮计算`Q*Kᵀ`,在第`j+4`轮计算`P*V`;Vector侧在第`j+1`轮计算Softmax并准备P,在第`j+5`轮累加`P*V`结果。这些数字是各侧循环的位置,不是固定的硬件时钟间隔,实际读写顺序仍由同步接口保证。循环额外执行5轮,完成最后几个块尚未结束的计算和搬运。 | ||
| 139 | + | ||
| 140 | +P、V和alpha需要保留到后续步骤读取,因此分别分配五份缓冲区;S、deltaO和PWork使用双缓冲,L0C使用四份缓冲区。以下代码中的`Slot`表示所选缓冲区的编号;例如五份缓冲区按0、1、2、3、4、0的顺序复用: | ||
| 141 | + | ||
| 142 | +```cpp | ||
| 143 | +const uint32_t cvPipelineSlot = kvTile % CV_PIPELINE_SLOT_NUM; | ||
| 144 | +const uint32_t sSlot = kvTile % DB_SLOT_NUM; | ||
| 145 | +const uint32_t l0cSlot = mmadOpIdx % L0C_QUEUE_DEPTH; | ||
| 146 | +``` | ||
| 147 | + | ||
| 148 | +K/V块超过5个时,第6个块开始复用第1个块的缓冲区,复用前必须确认旧数据已被读取。短序列或仅有一个K/V块时也执行相同流程,但开始和结束阶段可重叠的工作较少,不能据此宣称所有shape都有同样收益。 | ||
| 149 | + | ||
| 150 | +**核内同步控制不同流水,核间同步通知数据何时可用。** 核内通过`asc_lock`和`asc_unlock`协调数据搬运流水与计算流水,保证同一缓冲区先完成写入再读取、完成读取后再覆盖。核间通过通知和等待传递两类信息:“数据已写好”和“缓冲区已读完”。对于S和deltaO,Cube核必须等两个Vector核都读完,才能覆盖对应缓冲区;对于P,必须等UB到L1的数据搬运完成后再通知Cube核,不能在向量函数刚生成P时就通知。相应代码为: | ||
| 151 | + | ||
| 152 | +```cpp | ||
| 153 | +CopyPWorkToL1(pSliceL1Local, pWorkSlotUBLocal, halfBr, bc); | ||
| 154 | +asc_unlock(PIPE_MTE3, pWorkMutexId); | ||
| 155 | +SetAivToAic<PIPE_MTE3>(SlotFlagId(FLAG_P_READY_BASE, cvPipelineSlot)); | ||
| 156 | +``` | ||
| 157 | + | ||
| 158 | +其中MTE3是执行UB到L1搬运的数据搬运流水。上板运行使用`asc_sync_block_arrive`和`asc_sync_block_wait`实现一个Cube核与两个Vector核之间的同步;仿真路径也显式覆盖两个Vector核。Q和OAcc的双缓冲在相邻任务间交替使用,允许前一任务输出搬出与后续任务计算重叠。核入口调用`asc_init`初始化状态,核末尾调用`asc_sync`完成收尾。构建启用`-O3`和`--cce-auto-sync=off`,由代码显式安排核内和核间同步,不能只删除同步来追求重叠。 | ||
| 159 | + | ||
| 160 | +### 合并数据格式转换,复用输出存储空间 | ||
| 161 | + | ||
| 162 | +**计算指数时,一并完成BF16转换和NZ格式准备。** 在求得最大值后的第二遍读取中,同一个向量函数完成指数计算、BF16类型转换、将有效16位数据集中到寄存器低半部分,以及按指定间隔存储。不先生成普通连续格式的P再单独做一次转置。每16行Q对应128个32字节数据块,额外留出1个数据块用于补齐;因此每份PWork的容量为`4×129×32=16512`字节,可容纳`64×129`个BF16值。UB到L1搬运时跳过这些补齐位置,得到矩阵计算需要的NZ格式。关键操作为: | ||
| 163 | + | ||
| 164 | +```cpp | ||
| 165 | +asc_exp_sub(exp0, s0, max0, all); | ||
| 166 | +asc_float2bfloat16_rna_sat(bf16_0, exp0, all, ASC_POSITION_EVEN); | ||
| 167 | +asc_pack_to_low( | ||
| 168 | + reinterpret_cast<vector_uint16_t&>(packed0), reinterpret_cast<vector_uint32_t&>(bf16_0)); | ||
| 169 | +asc_storealign_postupdate(pDstAddr, packed0, groupStrideBlocks, 1, b16HalfMask); | ||
| 170 | +``` | ||
| 171 | + | ||
| 172 | +**最终输出覆盖已不再使用的FP32累加结果。** 所有K/V块处理完后,向量函数将OAcc中交错存放的两组数据分开读取,分别除以对应行的分母l,再转换并合并为BF16输出。这些操作在同一个向量函数中完成。由于BF16占用空间是FP32的一半,结果写入当前OAcc缓冲区的前半段,无需另分配输出UB;仅转换和搬出有效Q行,避免尾块越界。 | ||
| 173 | + | ||
| 174 | +## 编译运行 | ||
| 175 | + | ||
| 176 | +配置CANN环境变量: | ||
| 177 | + | ||
| 178 | +```bash | ||
| 179 | +source ${install_path}/cann/set_env.sh | ||
| 180 | +``` | ||
| 181 | + | ||
| 182 | +> **说明:** `${install_path}`为CANN包安装目录;root用户默认为`/usr/local/Ascend`,非root用户默认为`${HOME}/Ascend`。 | ||
| 183 | + | ||
| 184 | +在本样例目录编译并运行,无需另外生成数据或执行校验脚本: | ||
| 185 | + | ||
| 186 | +```bash | ||
| 187 | +mkdir -p build && cd build | ||
| 188 | +cmake .. | ||
| 189 | +make -j | ||
| 190 | +./demo | ||
| 191 | +``` | ||
| 192 | + | ||
| 193 | +默认运行`[1,2,257,128]`,Host自动生成输入并逐元素校验O。改变shape无需重新编译: | ||
| 194 | + | ||
| 195 | +```bash | ||
| 196 | +./demo 1,2,257,128 2 | ||
| 197 | +./demo 1,3,769,128 1 | ||
| 198 | +./demo 1,2,769,128 1 4 | ||
| 199 | +./demo 1,2,513,128 1 0 -0.25 | ||
| 200 | +./demo --sampled 2,64,1024,128 | ||
| 201 | +``` | ||
| 202 | + | ||
| 203 | +在构建目录运行因果mask回归,覆盖128行块边界、两个Vector核、多个注意力头及流水缓冲区复用;所有输出均使用Host独立参考完整校验: | ||
| 204 | + | ||
| 205 | +```bash | ||
| 206 | +bash ../tests/causal_mask_test.sh ./demo | ||
| 207 | +``` | ||
| 208 | + | ||
| 209 | +参数顺序为`[--sampled] [B,N,S,128 [cores [pattern [scale]]]]`。cores为0或省略时自动选择。pattern仅控制Host生成的数据,不切换核函数算法:0为确定性三角函数输入,1为放大Q/K,2为全零,3为Q/K全零而V非零,4为跨K块递增分数。 | ||
| 210 | + | ||
| 211 | +未使用`--sampled`时,Host以实际BF16输入计算double参考,检查全部输出满足`abs(actual-reference)≤0.003+0.008*abs(reference)`。使用该选项时仍计算并检查整个输出有限、GM前后各128字节哨兵完整,但仅为块边界、序列中部和末行等选定query行计算参考,适合大规模输入,不等同于全部输出的数值验证。设置`FLASH_ATTENTION_DUMP_PATH=/tmp/output.bin`可导出本次BF16结果,不含哨兵。 | ||
| 212 | + | ||
| 213 | +### 编译选项与仿真 | ||
| 214 | + | ||
| 215 | +| 编译选项 | 可选值 | 说明 | | ||
| 216 | +| --- | --- | --- | | ||
| 217 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510`(默认) | 支持的NPU架构。 | | ||
| 218 | +| `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | NPU运行或仿真;不支持CPU孪生调试模式。 | | ||
| 219 | + | ||
| 220 | +在样例根目录配置并运行独立的仿真构建: | ||
| 221 | + | ||
| 222 | +```bash | ||
| 223 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 224 | +cmake --build build/sim --parallel | ||
| 225 | +./build/sim/demo 1,1,17,128 1 | ||
| 226 | +``` | ||
| 227 | + | ||
| 228 | +仿真构建定义`SIM_COMPATIBLE`,选择AIC/AIV配对同步路径。两种模式均使用Device 0。优化说明仅解释实现机制,不提供未经测量的加速比,仿真耗时不能作为硬件性能测量结果。 | ||
| @@ -0,0 +1,228 @@ | |||
| 1 | +# FlashAttention Example | ||
| 2 | + | ||
| 3 | +## Overview | ||
| 4 | + | ||
| 5 | +This example implements BF16 causal FlashAttention using the Ascend C C API. Q, K, V and O use contiguous `[B,N,S,128]` layout, where B is the batch count, N is the attention-head count, S is the sequence length and 128 is the head dimension. B, N and S are configurable at runtime. Cube and Vector cores cooperate on tiled computation without storing a complete attention matrix in Global Memory (GM). | ||
| 6 | + | ||
| 7 | +## Supported Products and CANN Versions | ||
| 8 | + | ||
| 9 | +| Product | CANN Version | | ||
| 10 | +|---------|-------------| | ||
| 11 | +| Ascend 950PR&950DT products | >= CANN 9.3.0 | | ||
| 12 | + | ||
| 13 | +This sample uses the `dav-3510` architecture and supports only NPU and NPU simulation modes. | ||
| 14 | + | ||
| 15 | +## Directory Structure | ||
| 16 | + | ||
| 17 | +```text | ||
| 18 | +attention | ||
| 19 | +├── CMakeLists.txt # Build configuration | ||
| 20 | +├── flash_attention.asc # Helpers, AIC/AIV computation and host entry | ||
| 21 | +├── tiling.h # Shared types, scheduling and SRAM layout | ||
| 22 | +├── README.md | ||
| 23 | +└── README_en.md | ||
| 24 | +``` | ||
| 25 | + | ||
| 26 | +## Example Description | ||
| 27 | + | ||
| 28 | +This example computes multi-head self-attention. Q, K and V are queries, keys and values, with the same batch count B, head count N and sequence length S. The head dimension is fixed at 128. A Q row contains the 128 query components for one sequence position. Each Q row attends only to its own and earlier positions within the same batch and head. The example returns O only, not attention weights or Softmax statistics. | ||
| 29 | + | ||
| 30 | +Inputs and outputs are BF16. Matrix accumulation, Softmax states and output accumulation use FP32. The default scale is `1/sqrt(128)`; other nonzero finite FP32 values, including negative values, are supported. S need not be a multiple of 128: incomplete tiles are padded on chip and processed using valid row/column counts, without host-side Q/K/V padding. B, N and S must be positive, with `B*N*S≤131072`. Unequal Q/K/V head counts (GQA/MQA), unequal Q/K sequence lengths, noncausal attention, additional attention masks, positional encoding, paged attention, quantization, Dropout and backward computation are not supported. | ||
| 31 | + | ||
| 32 | +For each batch and head: | ||
| 33 | + | ||
| 34 | +$$ | ||
| 35 | +s_{i,j}=scale\cdot\sum_{d=0}^{127}Q_{i,d}K_{j,d},\qquad | ||
| 36 | +p_{i,j}=\frac{\exp(s_{i,j})}{\sum_{k=0}^{i}\exp(s_{i,k})}\quad(0\leq j\leq i) | ||
| 37 | +$$ | ||
| 38 | + | ||
| 39 | +$$ | ||
| 40 | +O_{i,d}=\sum_{j=0}^{i}p_{i,j}V_{j,d} | ||
| 41 | +$$ | ||
| 42 | + | ||
| 43 | +Computation processes 128 Q rows and 128 K/V rows per tile, updating Softmax and output without materializing the full `S×S` matrix. Tile exponentials are converted to BF16 before the second matrix multiplication, while denominators accumulate FP32 exponentials. Final FP32 division is followed by BF16 conversion, so results are not guaranteed to be bitwise identical to a single high-precision evaluation. | ||
| 44 | + | ||
| 45 | +**Table 1** Input and output specifications | ||
| 46 | + | ||
| 47 | +| Data | Direction | Type | Default shape | Description | | ||
| 48 | +| --- | --- | --- | --- | --- | | ||
| 49 | +| Q/K/V | Input | BF16 | `[1,2,257,128]` | Deterministic host-generated data, rounded to BF16 before upload. | | ||
| 50 | +| O | Output | BF16 | `[1,2,257,128]` | Same shape, tightly packed BNSD. | | ||
| 51 | +| scale | Parameter | FP32 | Scalar | Nonzero and finite; defaults to `1/sqrt(128)`. | | ||
| 52 | +| Reference | Verification | double | Matches O | Causal Softmax using actual BF16 inputs; not used by the kernel. | | ||
| 53 | + | ||
| 54 | +### Computation Flow and Terminology | ||
| 55 | + | ||
| 56 | +Each Cube core (AIC) cooperates with two Vector cores (AIVs). One task processes 128 Q rows, reading the visible K/V data in tiles of up to 128 rows: | ||
| 57 | + | ||
| 58 | +1. The Cube core computes `Q*Kᵀ`; the Vector cores multiply the resulting scores by scale. | ||
| 59 | +2. The Vector cores update the Softmax maxima and exponential sums and generate BF16 exponentials, named P in the code. P has not been divided by the Softmax denominator and is not the normalized weight p in the formula. | ||
| 60 | +3. The Cube core computes `P*V`; the Vector cores accumulate the result for the current Q tile. | ||
| 61 | +4. After all visible K/V tiles, the Vector cores divide the accumulated output by the Softmax denominator, convert to BF16 and write to Global Memory (GM). | ||
| 62 | + | ||
| 63 | +L1, L0A, L0B and L0C Buffers serve matrix computation. Unified Buffer (UB) holds intermediate data for vector computation. A Vector Function (VF) performs vector computation on registers. The storage, double-buffering and synchronization terminology follows the Ascend C documentation; see [Memory Hierarchy (Chinese)](../../../../docs/zh/guide/programming_guide/programming_model/ai_core_simd_programming/c_pointer_programming/c_programming_overview.md#内存层级) and [Mutex-Based Multi-Pipeline Synchronization (Chinese)](../../../../docs/zh/guide/programming_guide/advanced_programming/advanced_kernel_programming/intra_core_sync/mutex_multi_pipeline_sync.md). | ||
| 64 | + | ||
| 65 | +### Multicore Scheduling and Cube/Vector Responsibilities | ||
| 66 | + | ||
| 67 | +**Each task computes the complete output for one Q tile.** Q tile height is `br=128`; K/V tile height is `bc=128`. Each batch/head contains `tr=ceil(S/128)` Q tiles, giving `T=B*N*tr` tasks. A requested core count of zero, or no count, uses available hardware Cube cores. Explicit counts cannot exceed hardware. The example uses `C=min(T,requested-or-hardware-count)` Cube cores, without idle cores. The kernel uses `__mix__(1,2)` to associate each Cube core with two Vector cores. Task distribution below is indexed by Cube core. | ||
| 68 | + | ||
| 69 | +Cube core k and its two cooperating Vector cores process tasks `k,k+C,k+2C,...`, rather than one contiguous interval. Tasks flatten batch/head first, then Q tiles: | ||
| 70 | + | ||
| 71 | +```cpp | ||
| 72 | +const uint32_t batchHeadIdx = taskId / data.tr; | ||
| 73 | +const uint32_t tileIdx = taskId % data.tr; | ||
| 74 | +const uint32_t kvTileCount = GetKvTileCount<CAUSAL_MASK>(data, tileIdx); | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +Here `batchHeadIdx=b*N+n`; the Q/O element offset is `((b*N+n)*S+tileIdx*128)*128`. Zero-based Q tile q visits K/V tiles `0..q`, or `q+1` tiles. Later entire tiles correspond to future positions and are skipped. Later Q tiles require more work, so cyclic distribution assigns earlier and later Q tiles to different Cube cores to reduce imbalance, without guaranteeing identical execution times for every shape. | ||
| 78 | + | ||
| 79 | +For default `[1,2,257,128]`, each head has three Q tiles, giving six tasks. With two Cube cores, core 0 handles tasks 0/2/4: head 0 Q tiles 0/2 and head 1 Q tile 1. Core 1 handles tasks 1/3/5. Each processes six K/V tiles. The final sequence tile has one valid Q row. Fixed-size matrix multiplication still runs, but only the first Vector core writes one output row; the second writes no invalid rows. | ||
| 80 | + | ||
| 81 | +**Each Vector core handles 64 Q rows.** After `Q*Kᵀ`, the Cube core transfers matrix results through the FIX pipeline into the two Vector cores' UBs, splitting the 128 Q rows into two sets of 64. The 64 elements of an FP32 vector register represent these 64 Q rows. Iterating over K rows updates all 64 maxima and exponential sums together, rather than reducing within a vector separately for each Q row. Both Vector cores write P to L1 for the Cube core's `P*V` computation. Results return using the same 64-row split. Each Vector core maintains its own output, without combining results from tasks assigned to other Cube cores. | ||
| 82 | + | ||
| 83 | +### On-Chip Storage and UB Layout | ||
| 84 | + | ||
| 85 | +Each buffer is a fixed-size memory region. Double buffering allocates two regions for the same data type and alternates between them for transfer and computation. Data needed by later stages uses more regions, reused cyclically. Buffer counts describe allocated storage, not iteration counts. Increasing S adds tasks and K/V tiles, not larger per-core buffers. `tiling.h` computes addresses; host checks capacities before launch. | ||
| 86 | + | ||
| 87 | +**Table 2** Matrix storage per Cube core | ||
| 88 | + | ||
| 89 | +| Memory | Regions and buffer counts | Usage | Purpose | | ||
| 90 | +| --- | --- | --- | --- | | ||
| 91 | +| L1 | P: five buffers, 160 KiB; K: double buffer, 64 KiB; Q: double buffer, 64 KiB; V: five buffers, 160 KiB | 448 KiB | Load Q once; retain P/V until the corresponding second matrix multiplication has read them. | | ||
| 92 | +| L0A | Double buffer | 64 KiB | Left operands for both matrix multiplications. | | ||
| 93 | +| L0B | Double buffer | 64 KiB | Right operands for both matrix multiplications. | | ||
| 94 | +| L0C | Four buffers | 256 KiB | Interleaved FP32 results of `Q*Kᵀ` and `P*V`, transferred through FIX. | | ||
| 95 | + | ||
| 96 | +L1 orders P/K/Q/V at offsets 0/160/224/288 KiB. L0A/L0B select buffers using the matrix-operation counter modulo two; L0C uses that counter modulo four. The K/V tile index cannot replace this counter: each tile involves two matrix multiplications, and the two kinds of operation interleave. | ||
| 97 | + | ||
| 98 | +The MTE2 data-transfer pipeline loads Q/K/V from GM to L1 while converting contiguous ND data to the NZ fractal format required by matrix computation. Incomplete 128-row tiles are zero-filled in L1. Q is loaded once per task and reused across all K/V tiles. K uses double buffering; V uses five buffers to remain available until its `P*V` operation reads it. L1-to-L0 transfers use transpose interfaces as required, avoiding separate transposed copies in GM and their extra transfers/storage. | ||
| 99 | + | ||
| 100 | +**Table 3** UB layout per Vector core (region names match code variables) | ||
| 101 | + | ||
| 102 | +| Region | Byte offset | Capacity | Purpose | | ||
| 103 | +| --- | --- | --- | --- | | ||
| 104 | +| S, double buffer | 0 | 65536 bytes | `128×64` FP32 scores per buffer; scores for 64 Q rows sharing one K row are contiguous. S here names a score buffer, not sequence length. | | ||
| 105 | +| deltaO, double buffer | 65536 | 65536 bytes | `64×128` FP32 values per buffer, holding the current tile's `P*V` result. | | ||
| 106 | +| OAcc, double buffer | 131072 | 65536 bytes | `64×128` FP32 values per buffer, accumulating processed tiles and reused for final BF16 output. | | ||
| 107 | +| PWork, double buffer | 196608 | 33024 bytes | Space for `64×129` BF16 values per buffer, including format-conversion padding. | | ||
| 108 | +| m | 229632 | 256 bytes | One FP32 maximum per Q row. | | ||
| 109 | +| l | 229888 | 256 bytes | One FP32 Softmax denominator per Q row. | | ||
| 110 | +| alpha, five buffers | 230144 | 1280 bytes | 64 FP32 scaling coefficients per K/V tile, retained until its output update completes. | | ||
| 111 | + | ||
| 112 | +Total UB usage per Vector core is 231424 bytes, or 226 KiB. m/l store one state per Q row, not one per output component. Resource requirements are at least 512 KiB L1, 64 KiB L0A, 64 KiB L0B, 256 KiB L0C and 248 KiB UB. Host queries L1/UB; L0 layouts are checked against target architecture capacities. No GM workspace is allocated beyond Q/K/V/O. | ||
| 113 | + | ||
| 114 | +### Incremental Softmax and Numerical Stability | ||
| 115 | + | ||
| 116 | +**Update previous results whenever another K/V tile arrives.** This tile-by-tile approach is also called online Softmax. For valid scores s in a new K tile, each Q row maintains three states: the maximum m across processed scores, exponential sum l and output accumulator A before division (OAcc in the code): | ||
| 117 | + | ||
| 118 | +$$ | ||
| 119 | +m'=\max(m,\max_j s_j),\quad \alpha=\exp(m-m'),\quad | ||
| 120 | +E_j=\exp(s_j-m') | ||
| 121 | +$$ | ||
| 122 | + | ||
| 123 | +$$ | ||
| 124 | +l'=\alpha l+\sum_j E_j,\qquad | ||
| 125 | +A'=\alpha A+\operatorname{BF16}(E)V,\qquad O=A/l | ||
| 126 | +$$ | ||
| 127 | + | ||
| 128 | +The first tile initializes states without reading old m/l/A. Later tiles scale the previous denominator and output by alpha before adding the new results. This preserves previous work even when a new tile introduces larger scores. Subtracting the current maximum avoids directly exponentiating large positive values. `asc_madd` performs denominator/output multiply-add updates; output updates process two Q rows at a time to reuse control and loads. This reduces GM intermediate traffic and storage, not attention arithmetic to linear complexity. | ||
| 129 | + | ||
| 130 | +**Process four K rows together to reduce dependencies.** Maxima and exponential sums each use four independent variables, processing four K rows per iteration and then combining results. Fewer than four remaining rows are handled separately. Templates for first/subsequent and diagonal/off-diagonal tiles are selected before entering the vector function, avoiding repeated decisions inside vector computation. Only diagonal tiles, where Q and K share the same sequence tile, need elementwise future-position checks. Earlier complete tiles do not. The last K tile processes `validBc` rows and clears remaining P positions. | ||
| 131 | + | ||
| 132 | +Diagonal Q/K tiles have the same origin and both contain 128 rows, so the mask compares tile-local indices: `subAivIdx*64+lane` for Q and `keyRow` for K. Their common global tile offset cancels; adding `qTileIdx*128` only to the Q index would be incorrect. | ||
| 133 | + | ||
| 134 | +### Pipeline Parallelism and Buffer Reuse | ||
| 135 | + | ||
| 136 | +**Continue processing earlier results while computing later tiles.** A Q tile usually visits multiple K/V tiles. To reduce Cube-core waiting for Vector cores, the implementation interleaves matrix computation, vector computation and data transfers from different tiles rather than finishing every stage of one tile before starting the next. | ||
| 137 | + | ||
| 138 | +In terms of the code's loop counter `epoch`, K/V tile j computes `Q*Kᵀ` at Cube iteration j and `P*V` at iteration `j+4`. Vector iterations `j+1` and `j+5` prepare Softmax/P and accumulate `P*V`, respectively. These numbers are positions in each side's loop, not fixed hardware-clock intervals. Synchronization interfaces enforce actual access order. Five extra iterations complete outstanding computations and transfers for the last tiles. | ||
| 139 | + | ||
| 140 | +P/V/alpha must remain available for later steps, so each uses five buffers. S/deltaO/PWork use double buffering; L0C uses four buffers. `Slot` in the following code is the selected buffer index. For example, five buffers are reused in order 0, 1, 2, 3, 4, 0: | ||
| 141 | + | ||
| 142 | +```cpp | ||
| 143 | +const uint32_t cvPipelineSlot = kvTile % CV_PIPELINE_SLOT_NUM; | ||
| 144 | +const uint32_t sSlot = kvTile % DB_SLOT_NUM; | ||
| 145 | +const uint32_t l0cSlot = mmadOpIdx % L0C_QUEUE_DEPTH; | ||
| 146 | +``` | ||
| 147 | + | ||
| 148 | +With more than five K/V tiles, the sixth reuses the first tile's buffer, after confirming its old data has been read. Short sequences and single-tile cases follow the same process, but have less work to overlap during startup and completion; equal benefits across all shapes are not assumed. | ||
| 149 | + | ||
| 150 | +**Intra-core synchronization orders pipelines; inter-core synchronization announces data availability.** Within a core, `asc_lock` and `asc_unlock` coordinate transfer and compute pipelines, ensuring writes complete before reads and reads complete before overwrites. Between cores, notifications and waits convey “data written” and “buffer read.” For S/deltaO, the Cube core cannot overwrite a buffer until both Vector cores have read it. For P, notification must follow completion of UB-to-L1 transfer, not just completion of the vector function that generated P: | ||
| 151 | + | ||
| 152 | +```cpp | ||
| 153 | +CopyPWorkToL1(pSliceL1Local, pWorkSlotUBLocal, halfBr, bc); | ||
| 154 | +asc_unlock(PIPE_MTE3, pWorkMutexId); | ||
| 155 | +SetAivToAic<PIPE_MTE3>(SlotFlagId(FLAG_P_READY_BASE, cvPipelineSlot)); | ||
| 156 | +``` | ||
| 157 | + | ||
| 158 | +MTE3 is the data-transfer pipeline performing this UB-to-L1 transfer. On hardware, `asc_sync_block_arrive` and `asc_sync_block_wait` synchronize one Cube core with both Vector cores; the simulation path also explicitly covers both Vector cores. Q/OAcc double buffers alternate across tasks, allowing previous output transfer to overlap later computation. `asc_init` initializes kernel state and `asc_sync` completes final work. Builds use `-O3` and `--cce-auto-sync=off`, with explicit intra-core/inter-core synchronization in the code. Removing synchronization alone is not an optimization. | ||
| 159 | + | ||
| 160 | +### Combining Format Conversion and Reusing Output Storage | ||
| 161 | + | ||
| 162 | +**Prepare BF16 data and NZ layout while computing exponentials.** In the second pass after finding maxima, one vector function computes exponentials, converts to BF16, gathers valid 16-bit values into the lower register half and stores at specified intervals. It does not first create contiguous P and then run a separate transpose. Each set of 16 Q rows uses 128 data blocks of 32 bytes plus one padding block. Thus each PWork buffer occupies `4×129×32=16512` bytes, holding `64×129` BF16 values. UB-to-L1 transfer skips padding to produce the NZ layout required by matrix computation. Key operations are: | ||
| 163 | + | ||
| 164 | +```cpp | ||
| 165 | +asc_exp_sub(exp0, s0, max0, all); | ||
| 166 | +asc_float2bfloat16_rna_sat(bf16_0, exp0, all, ASC_POSITION_EVEN); | ||
| 167 | +asc_pack_to_low( | ||
| 168 | + reinterpret_cast<vector_uint16_t&>(packed0), reinterpret_cast<vector_uint32_t&>(bf16_0)); | ||
| 169 | +asc_storealign_postupdate(pDstAddr, packed0, groupStrideBlocks, 1, b16HalfMask); | ||
| 170 | +``` | ||
| 171 | + | ||
| 172 | +**Overwrite FP32 accumulators once they are no longer needed.** After all K/V tiles, one vector function separates two interleaved groups loaded from OAcc, divides by each row's denominator l, then converts and combines BF16 output. BF16 occupies half the FP32 storage, so results reuse the first half of the current OAcc buffer without another output UB allocation. Only valid Q rows are converted and transferred, protecting sequence tails. | ||
| 173 | + | ||
| 174 | +## Build and Run | ||
| 175 | + | ||
| 176 | +Configure CANN: | ||
| 177 | + | ||
| 178 | +```bash | ||
| 179 | +source ${install_path}/cann/set_env.sh | ||
| 180 | +``` | ||
| 181 | + | ||
| 182 | +> **Note:** `${install_path}` is typically `/usr/local/Ascend` for root or `${HOME}/Ascend` otherwise. | ||
| 183 | + | ||
| 184 | +From the example directory, without separate data generation or verification scripts: | ||
| 185 | + | ||
| 186 | +```bash | ||
| 187 | +mkdir -p build && cd build | ||
| 188 | +cmake .. | ||
| 189 | +make -j | ||
| 190 | +./demo | ||
| 191 | +``` | ||
| 192 | + | ||
| 193 | +The default `[1,2,257,128]` input is generated and fully verified by host. Runtime shapes require no rebuild: | ||
| 194 | + | ||
| 195 | +```bash | ||
| 196 | +./demo 1,2,257,128 2 | ||
| 197 | +./demo 1,3,769,128 1 | ||
| 198 | +./demo 1,2,769,128 1 4 | ||
| 199 | +./demo 1,2,513,128 1 0 -0.25 | ||
| 200 | +./demo --sampled 2,64,1024,128 | ||
| 201 | +``` | ||
| 202 | + | ||
| 203 | +From the build directory, run the causal-mask regression covering 128-row tile boundaries, both Vector cores, multiple heads and pipeline-buffer reuse. Every output is checked against the independent host reference: | ||
| 204 | + | ||
| 205 | +```bash | ||
| 206 | +bash ../tests/causal_mask_test.sh ./demo | ||
| 207 | +``` | ||
| 208 | + | ||
| 209 | +Arguments are `[--sampled] [B,N,S,128 [cores [pattern [scale]]]]`. Zero/omitted cores selects automatically. Pattern controls host input generation, not the kernel algorithm: 0 is deterministic trigonometric data, 1 amplifies Q/K, 2 is all zero, 3 has zero Q/K and nonzero V, and 4 increases scores across K tiles. | ||
| 210 | + | ||
| 211 | +Without `--sampled`, every output is compared with a double reference using actual BF16 inputs, requiring `abs(actual-reference)≤0.003+0.008*abs(reference)`. Sampling still computes the entire output, checks every value is finite and both 128-byte GM sentinels are intact, but computes references only for selected query rows around tile boundaries, the sequence midpoint and the last row. It suits larger inputs and is not full numerical verification. Set `FLASH_ATTENTION_DUMP_PATH=/tmp/output.bin` to export raw BF16 output without sentinels. | ||
| 212 | + | ||
| 213 | +### Build Options and Simulation | ||
| 214 | + | ||
| 215 | +| Option | Values | Description | | ||
| 216 | +| --- | --- | --- | | ||
| 217 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510` (default) | Supported NPU architecture. | | ||
| 218 | +| `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | NPU execution or simulation; CPU debugging is not supported. | | ||
| 219 | + | ||
| 220 | +From the sample root, configure and run simulation in a separate directory: | ||
| 221 | + | ||
| 222 | +```bash | ||
| 223 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 224 | +cmake --build build/sim --parallel | ||
| 225 | +./build/sim/demo 1,1,17,128 1 | ||
| 226 | +``` | ||
| 227 | + | ||
| 228 | +Simulation builds define `SIM_COMPATIBLE` to select paired AIC/AIV synchronization. Device 0 is used in both modes. Optimization descriptions explain the implementation; they do not provide measured speedups, and simulation timing is not a hardware performance measurement. | ||
| @@ -0,0 +1,28 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +set -euo pipefail | ||
| 13 | + | ||
| 14 | +if [[ $# -ne 1 ]]; then | ||
| 15 | + echo "Usage: bash $0 /path/to/demo" >&2 | ||
| 16 | + exit 2 | ||
| 17 | +fi | ||
| 18 | + | ||
| 19 | +# Zero Q/K and nonzero V make every row a causal prefix mean. The demo checks | ||
| 20 | +# all rows against its independent host reference, including both AIV halves. | ||
| 21 | +for seq_len in 127 128 129 255 256 257; do | ||
| 22 | + "$1" "1,1,${seq_len},128" 1 3 | ||
| 23 | +done | ||
| 24 | + | ||
| 25 | +# Reuse pipeline slots across KV tiles and tasks on multiple cores/heads. | ||
| 26 | +"$1" 1,2,769,128 2 4 | ||
| 27 | +"$1" 1,2,257,128 2 0 -0.25 | ||
| 28 | +echo "PASS: 8 causal-mask cases" | ||
| @@ -0,0 +1,170 @@ | |||
| 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 | +#pragma once | ||
| 12 | + | ||
| 13 | +#include <cmath> | ||
| 14 | +#include <cstdint> | ||
| 15 | +#include <limits> | ||
| 16 | +#include "utils/std/cmath.h" | ||
| 17 | + | ||
| 18 | +namespace FlashAttention { | ||
| 19 | + | ||
| 20 | +constexpr uint32_t HEAD_DIM = 128; | ||
| 21 | + | ||
| 22 | +constexpr uint32_t CV_PIPELINE_SLOT_NUM = 5; | ||
| 23 | + | ||
| 24 | +constexpr uint32_t DB_SLOT_NUM = 2; | ||
| 25 | + | ||
| 26 | +constexpr uint32_t L0C_QUEUE_DEPTH = 4; | ||
| 27 | + | ||
| 28 | +struct SRAMLayoutAIC { | ||
| 29 | + uint32_t pL1Addr; | ||
| 30 | + uint32_t pL1Elems; | ||
| 31 | + uint32_t qL1Addr; | ||
| 32 | + uint32_t qL1Elems; | ||
| 33 | + uint32_t kL1Addr; | ||
| 34 | + uint32_t kL1Elems; | ||
| 35 | + uint32_t vL1Addr; | ||
| 36 | + uint32_t vL1Elems; | ||
| 37 | + uint32_t aL0AAddr; | ||
| 38 | + uint32_t aL0AElems; | ||
| 39 | + uint32_t bL0BAddr; | ||
| 40 | + uint32_t bL0BElems; | ||
| 41 | + uint32_t cL0CAddr; | ||
| 42 | + uint32_t cL0CElems; | ||
| 43 | +}; | ||
| 44 | + | ||
| 45 | +struct SRAMLayoutAIV { | ||
| 46 | + uint32_t sUBAddr; | ||
| 47 | + uint32_t sUBElems; | ||
| 48 | + uint32_t oDeltaUBAddr; | ||
| 49 | + uint32_t oDeltaUBElems; | ||
| 50 | + uint32_t oAccUBAddr; | ||
| 51 | + uint32_t oAccUBElems; | ||
| 52 | + uint32_t pWorkUBAddr; | ||
| 53 | + uint32_t pWorkUBElems; | ||
| 54 | + uint32_t mUBAddr; | ||
| 55 | + uint32_t lUBAddr; | ||
| 56 | + uint32_t alphaUBAddr; | ||
| 57 | + uint32_t rowStatsUBElems; | ||
| 58 | +}; | ||
| 59 | + | ||
| 60 | +struct FlashAttentionTilingData { | ||
| 61 | + uint32_t batchHeadNum; | ||
| 62 | + uint32_t seqLen; | ||
| 63 | + float scale; | ||
| 64 | + uint32_t br; | ||
| 65 | + uint32_t bc; | ||
| 66 | + uint32_t tr; | ||
| 67 | + uint32_t useAicNum; | ||
| 68 | + uint32_t numTasks; | ||
| 69 | + | ||
| 70 | + SRAMLayoutAIC layoutAIC; | ||
| 71 | + SRAMLayoutAIV layoutAIV; | ||
| 72 | +}; | ||
| 73 | + | ||
| 74 | +} // namespace FlashAttention | ||
| 75 | + | ||
| 76 | +namespace FlashAttention { | ||
| 77 | + | ||
| 78 | +constexpr uint32_t L1_CAPACITY_BYTES = 512 * 1024; | ||
| 79 | +constexpr uint32_t L0A_CAPACITY_BYTES = 64 * 1024; | ||
| 80 | +constexpr uint32_t L0B_CAPACITY_BYTES = 64 * 1024; | ||
| 81 | +constexpr uint32_t L0C_CAPACITY_BYTES = 256 * 1024; | ||
| 82 | +constexpr uint32_t UB_CAPACITY_BYTES = 248 * 1024; | ||
| 83 | + | ||
| 84 | +inline const char* MakeTiling( | ||
| 85 | + uint32_t batchSize, uint32_t headNum, uint32_t seqLen, float scale, uint32_t aicoreNum, | ||
| 86 | + FlashAttention::FlashAttentionTilingData& data) | ||
| 87 | +{ | ||
| 88 | + data = {}; | ||
| 89 | + data.br = 128; | ||
| 90 | + data.bc = 128; | ||
| 91 | + if (batchSize == 0) { | ||
| 92 | + return "B 必须大于 0"; | ||
| 93 | + } | ||
| 94 | + if (headNum == 0) { | ||
| 95 | + return "N 必须大于 0"; | ||
| 96 | + } | ||
| 97 | + if (seqLen == 0) { | ||
| 98 | + return "S 必须大于 0"; | ||
| 99 | + } | ||
| 100 | + if (scale == 0.0f || !std::isfinite(scale)) { | ||
| 101 | + return "scale 必须非 0 且为有限值"; | ||
| 102 | + } | ||
| 103 | + if (aicoreNum == 0) { | ||
| 104 | + return "可用 AIC 核数必须大于 0"; | ||
| 105 | + } | ||
| 106 | + const uint64_t batchHeadNum = static_cast<uint64_t>(batchSize) * headNum; | ||
| 107 | + if (batchHeadNum > std::numeric_limits<uint32_t>::max()) { | ||
| 108 | + return "B*N 超出 uint32_t 表示范围"; | ||
| 109 | + } | ||
| 110 | + if (batchHeadNum > 131072 || batchHeadNum * seqLen > 131072) { | ||
| 111 | + return "B*N*S must not exceed 131072"; | ||
| 112 | + } | ||
| 113 | + data.batchHeadNum = static_cast<uint32_t>(batchHeadNum); | ||
| 114 | + data.seqLen = seqLen; | ||
| 115 | + data.scale = scale; | ||
| 116 | + data.tr = AscendC::Std::ceil_div(seqLen, data.br); | ||
| 117 | + const uint64_t numTasks = batchHeadNum * data.tr; | ||
| 118 | + if (numTasks > std::numeric_limits<uint32_t>::max()) { | ||
| 119 | + return "任务数 B*N*ceil(S/128) 超出 uint32_t 表示范围"; | ||
| 120 | + } | ||
| 121 | + data.numTasks = static_cast<uint32_t>(numTasks); | ||
| 122 | + data.useAicNum = data.numTasks < aicoreNum ? data.numTasks : aicoreNum; | ||
| 123 | + | ||
| 124 | + auto& aic = data.layoutAIC; | ||
| 125 | + | ||
| 126 | + aic.pL1Addr = 0; | ||
| 127 | + aic.pL1Elems = FlashAttention::CV_PIPELINE_SLOT_NUM * data.br * data.bc; | ||
| 128 | + aic.kL1Addr = aic.pL1Addr + aic.pL1Elems * sizeof(uint16_t); | ||
| 129 | + aic.kL1Elems = FlashAttention::DB_SLOT_NUM * data.bc * FlashAttention::HEAD_DIM; | ||
| 130 | + aic.qL1Addr = aic.kL1Addr + aic.kL1Elems * sizeof(uint16_t); | ||
| 131 | + aic.qL1Elems = FlashAttention::DB_SLOT_NUM * data.br * FlashAttention::HEAD_DIM; | ||
| 132 | + aic.vL1Addr = aic.qL1Addr + aic.qL1Elems * sizeof(uint16_t); | ||
| 133 | + aic.vL1Elems = FlashAttention::CV_PIPELINE_SLOT_NUM * data.bc * FlashAttention::HEAD_DIM; | ||
| 134 | + | ||
| 135 | + aic.aL0AAddr = 0; | ||
| 136 | + aic.aL0AElems = FlashAttention::DB_SLOT_NUM * data.bc * | ||
| 137 | + (data.br > FlashAttention::HEAD_DIM ? data.br : FlashAttention::HEAD_DIM); | ||
| 138 | + aic.bL0BAddr = 0; | ||
| 139 | + aic.bL0BElems = FlashAttention::DB_SLOT_NUM * FlashAttention::HEAD_DIM * (data.br > data.bc ? data.br : data.bc); | ||
| 140 | + aic.cL0CAddr = 0; | ||
| 141 | + aic.cL0CElems = FlashAttention::L0C_QUEUE_DEPTH * data.br * | ||
| 142 | + (data.bc > FlashAttention::HEAD_DIM ? data.bc : FlashAttention::HEAD_DIM); | ||
| 143 | + | ||
| 144 | + auto& aiv = data.layoutAIV; | ||
| 145 | + const uint32_t halfBr = data.br / 2; | ||
| 146 | + aiv.sUBAddr = 0; | ||
| 147 | + aiv.sUBElems = FlashAttention::DB_SLOT_NUM * halfBr * data.bc; | ||
| 148 | + aiv.oDeltaUBAddr = aiv.sUBAddr + aiv.sUBElems * sizeof(float); | ||
| 149 | + aiv.oDeltaUBElems = FlashAttention::DB_SLOT_NUM * halfBr * FlashAttention::HEAD_DIM; | ||
| 150 | + aiv.oAccUBAddr = aiv.oDeltaUBAddr + aiv.oDeltaUBElems * sizeof(float); | ||
| 151 | + aiv.oAccUBElems = FlashAttention::DB_SLOT_NUM * halfBr * FlashAttention::HEAD_DIM; | ||
| 152 | + aiv.pWorkUBAddr = aiv.oAccUBAddr + aiv.oAccUBElems * sizeof(float); | ||
| 153 | + | ||
| 154 | + aiv.pWorkUBElems = FlashAttention::DB_SLOT_NUM * halfBr * (data.bc + 1); | ||
| 155 | + aiv.mUBAddr = aiv.pWorkUBAddr + aiv.pWorkUBElems * sizeof(uint16_t); | ||
| 156 | + aiv.rowStatsUBElems = halfBr; | ||
| 157 | + aiv.lUBAddr = aiv.mUBAddr + aiv.rowStatsUBElems * sizeof(float); | ||
| 158 | + aiv.alphaUBAddr = aiv.lUBAddr + aiv.rowStatsUBElems * sizeof(float); | ||
| 159 | + | ||
| 160 | + if (aic.vL1Addr + aic.vL1Elems * sizeof(uint16_t) > L1_CAPACITY_BYTES || | ||
| 161 | + aic.aL0AElems * sizeof(uint16_t) > L0A_CAPACITY_BYTES || | ||
| 162 | + aic.bL0BElems * sizeof(uint16_t) > L0B_CAPACITY_BYTES || aic.cL0CElems * sizeof(float) > L0C_CAPACITY_BYTES || | ||
| 163 | + aiv.alphaUBAddr + FlashAttention::CV_PIPELINE_SLOT_NUM * aiv.rowStatsUBElems * sizeof(float) > | ||
| 164 | + UB_CAPACITY_BYTES) { | ||
| 165 | + return "SRAM 布局超过片上空间容量"; | ||
| 166 | + } | ||
| 167 | + return nullptr; | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +} // namespace FlashAttention | ||
| @@ -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_RUN_MODE "npu" CACHE STRING "Run mode: npu, sim") | ||
| 14 | +set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510") | ||
| 15 | + | ||
| 16 | +find_package(ASC REQUIRED) | ||
| 17 | + | ||
| 18 | +project(kernel_samples LANGUAGES ASC CXX) | ||
| 19 | + | ||
| 20 | +add_executable(demo | ||
| 21 | + layer_norm.asc | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510") | ||
| 25 | + message(FATAL_ERROR "This sample only supports CMAKE_ASC_ARCHITECTURES=dav-3510") | ||
| 26 | +endif() | ||
| 27 | + | ||
| 28 | +if(NOT CMAKE_ASC_RUN_MODE MATCHES "^(npu|sim)$") | ||
| 29 | + message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be npu or sim, but got ${CMAKE_ASC_RUN_MODE}") | ||
| 30 | +endif() | ||
| 31 | + | ||
| 32 | +target_link_libraries(demo PRIVATE | ||
| 33 | + tiling_api | ||
| 34 | + register | ||
| 35 | + platform | ||
| 36 | + m | ||
| 37 | +) | ||
| 38 | + | ||
| 39 | +target_compile_options(demo PRIVATE | ||
| 40 | + $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}> | ||
| 41 | +) | ||
| @@ -0,0 +1,146 @@ | |||
| 1 | +# LayerNorm样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
| 4 | + | ||
| 5 | +本样例使用Ascend C C API实现FP32 LayerNorm,对输入的连续尾部维度进行归一化,并通过gamma和beta执行逐元素仿射变换,输出归一化结果y、均值mean和标准差倒数rstd。 | ||
| 6 | + | ||
| 7 | +样例采用先计算均值、再计算中心化方差的两遍归约,支持运行时多维shape、参数常驻、多核按行切分、核内动态分批及Ping/Pong Double Buffer流水。 | ||
| 8 | + | ||
| 9 | +## 本样例支持的产品及CANN软件版本 | ||
| 10 | + | ||
| 11 | +| 产品 | CANN软件版本 | | ||
| 12 | +|------|-------------| | ||
| 13 | +| Ascend 950PR&950DT系列产品 | >= CANN 9.3.0 | | ||
| 14 | + | ||
| 15 | +本样例固定使用`dav-3510`架构,仅支持NPU和仿真运行模式。 | ||
| 16 | + | ||
| 17 | +## 目录结构 | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +normalization | ||
| 21 | +├── scripts | ||
| 22 | +│ ├── gen_data.py # 生成输入数据和真值数据 | ||
| 23 | +│ └── verify_result.py # 校验输出结果 | ||
| 24 | +├── CMakeLists.txt # 编译工程文件 | ||
| 25 | +├── layer_norm.asc # 常量、VF计算、Kernel及Host侧实现 | ||
| 26 | +├── tiling.h # Shape校验、分核及UB容量计算 | ||
| 27 | +├── README.md | ||
| 28 | +└── README_en.md | ||
| 29 | +``` | ||
| 30 | + | ||
| 31 | +## 样例描述 | ||
| 32 | + | ||
| 33 | +本样例适用于多行FP32数据分别进行LayerNorm的场景。每行先求均值,再将每个元素减去均值,对差值的平方求平均,得到总体方差,不进行无偏校正。方差加上epsilon后计算平方根倒数,再将中心化后的输入乘以该倒数和对应位置的gamma,最后加上beta。gamma和beta在所有行间共享,且二者都必须提供。除y外,每行还输出一个mean和一个rstd;不输出variance。 | ||
| 34 | + | ||
| 35 | +归一化可以覆盖最后一维,也可以覆盖连续的多个尾部维度,gamma、beta的shape必须与这些维度逐维一致。例如,输入为`[batch, sequence, hidden]`、参数shape为`[hidden]`时,每个`[batch, sequence]`位置独立处理一行;参数shape为`[sequence, hidden]`时,每个batch独立处理一行。将归一化维度展开为长度R,其余前缀维度展开为行数A,得到逻辑矩阵`[A,R]`。参数shape与输入shape完全相同时,整个输入作为一行处理,mean和rstd各含一个元素。 | ||
| 36 | + | ||
| 37 | +每行支持1到9504个元素,每批加载完整的若干行,不将一行拆给多个核或跨批次分段加载。行数不要求是核数或批次大小的整数倍,行长也不要求按向量长度对齐;末核、末批和尾列按有效范围处理。x、gamma、beta及全部输出均为FP32,不支持混合精度、缺省gamma/beta或超出整行UB容量的输入。epsilon默认为`1e-5`,必须为正的有限FP32值。 | ||
| 38 | + | ||
| 39 | +计算公式为: | ||
| 40 | + | ||
| 41 | +$$ | ||
| 42 | +\mu_i=\frac{1}{R}\sum_{j=0}^{R-1}x_{i,j},\qquad | ||
| 43 | +v_i=\frac{1}{R}\sum_{j=0}^{R-1}(x_{i,j}-\mu_i)^2 | ||
| 44 | +$$ | ||
| 45 | + | ||
| 46 | +$$ | ||
| 47 | +rstd_i=\frac{1}{\sqrt{v_i+\varepsilon}},\qquad | ||
| 48 | +y_{i,j}=((x_{i,j}-\mu_i)\cdot rstd_i)\cdot\gamma_j+\beta_j | ||
| 49 | +$$ | ||
| 50 | + | ||
| 51 | +中间计算使用FP32。均值和方差归约采用二的幂次缩放,方差直接归约中心化平方,不使用`E[x²]-E[x]²`。rstd使用除法、平方根、Newton–Raphson及残差修正;仿射变换使用融合乘加指令。独立参考结果使用Torch的float64计算后保存为float32,校验时考虑FP32误差及均值舍入对归一化结果的影响。 | ||
| 52 | + | ||
| 53 | +**表1** 输入输出数据规格 | ||
| 54 | + | ||
| 55 | +| 数据 | 输入/输出 | 数据文件 | 数据类型 | 默认Shape | 说明 | | ||
| 56 | +| --- | --- | --- | --- | --- | --- | | ||
| 57 | +| x | 输入 | `data/input/x.bin` | float32 | `[13,1000]` | 支持运行时多维shape。 | | ||
| 58 | +| gamma | 输入 | `data/input/gamma.bin` | float32 | `[1000]` | 与归一化尾部维度逐维匹配。 | | ||
| 59 | +| beta | 输入 | `data/input/beta.bin` | float32 | `[1000]` | 与gamma同shape。 | | ||
| 60 | +| y | 输出 | `data/output/y.bin` | float32 | `[13,1000]` | 与x同shape,紧密连续存放。 | | ||
| 61 | +| mean | 输出 | `data/output/mean.bin` | float32 | `[13]` | Shape为输入的前缀维度,连续保存A个元素。 | | ||
| 62 | +| rstd | 输出 | `data/output/rstd.bin` | float32 | `[13]` | 与mean同shape。 | | ||
| 63 | +| golden | 真值 | `data/output/golden_{y,mean,rstd}.bin` | float32 | 与对应输出一致 | 独立Torch参考结果。 | | ||
| 64 | + | ||
| 65 | +### 多核切分与UB布局 | ||
| 66 | + | ||
| 67 | +**按行分核。** 只沿A维切分,R维保持完整,各核不需要交换归约结果。`coreCount`默认取硬件可用Vector Core数,也可指定不超过硬件核数的正整数。Host先计算`blockFactor=ceil(A/coreCount)`,再计算实际启动核数`usedCores=ceil(A/blockFactor)`,不启动空核,因此实际核数可能少于指定核数。第k核从第`k*blockFactor`行开始,处理`min(blockFactor,A-k*blockFactor)`行,对应GM元素起点为`k*blockFactor*R`;核索引从0开始。各核覆盖连续、互不重叠的行区间。 | ||
| 68 | + | ||
| 69 | +**核内分批。** Host为所有核计算相同的批次容量B,即`a_factor`。每核在自己的行区间内顺序执行`ceil(本核行数/B)`批,第t批从本核第`t*B`行开始,处理`min(B,本核行数-t*B)`行。偶数批使用Ping槽,奇数批使用Pong槽。gamma和beta每核仅搬入一次,跨行、跨批次复用。x/y以及mean/rstd各有两份槽,variance仅有一份当前批次工作区。 | ||
| 70 | + | ||
| 71 | +**行对齐与临时空间。** FP32向量长度`V=64`,UB block为32字节、可容纳8个float。GM中的行紧密存放R个元素,UB行步长为`S=ceil(R/8)*8`。统计区容量按`T=ceil(B/8)*8`对齐。UB中顺序存放gamma、beta、x Ping/Pong、y Ping/Pong、mean Ping/Pong、rstd Ping/Pong和variance;gamma、beta、x双槽区、y双槽区之后各保留V个float的向量访问保护空间。 | ||
| 72 | + | ||
| 73 | +gamma和beta共占`2*S`个float,x/y四个槽共占`4*B*S`个float,mean/rstd四个槽加variance共占`5*T`个float,四处保护空间共占`4*V`个float。因此,UB精确占用为: | ||
| 74 | + | ||
| 75 | +```text | ||
| 76 | +usedBytes = 4 * (2*S + 4*B*S + 5*T + 4*V) | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +**确定批次容量。** 静态UB池固定为224 KiB,另预留8 KiB,要求硬件UB不少于232 KiB。Host在`1..min(blockFactor,65535)`范围内二分搜索满足上述容量条件的最大B;若B=1也无法容纳则报错,不切换为分段归约。计算A和R时分别检查维度乘积的uint32溢出,分配GM时另检查总字节数溢出。二维DMA仅搬运有效的R列,尾列由mask处理,UB对齐及保护空间不写回GM。y、mean、rstd在GM中各有64个float的尾部保护区,保存结果前检查保护区是否被覆盖,输出文件本身不包含保护区。 | ||
| 80 | + | ||
| 81 | +例如,输入为`[97,1000]`、gamma/beta为`[1000]`,指定3核时,得到`blockFactor=33`、`usedCores=3`。三个核分别处理第0–32行、第33–65行、第66–96行,行数为33、33、31。此时`S=1000`,二分搜索得到`B=13`、`T=16`,UB占用217344字节;B增加到14时需要233344字节,超过224 KiB。每核均执行3批,前两核的批次行数为13、13、7,最后一核为13、13、5。默认`[13,1000]`输入在可用核数不少于13时启动13核,每核仅处理1行、执行1批。 | ||
| 82 | + | ||
| 83 | +### 归约与Double Buffer流水 | ||
| 84 | + | ||
| 85 | +**表2** 归约分支 | ||
| 86 | + | ||
| 87 | +| R范围 | 计算路径 | | ||
| 88 | +| --- | --- | | ||
| 89 | +| 1–64 | 单向量求均值,再归约中心化平方。 | | ||
| 90 | +| 65–128 | 两向量配对归约,尾部使用mask。 | | ||
| 91 | +| 129–9504 | 以不大于R的最大2次幂为主段,将尾段折叠后按128元素配对生成局部和,再进行末级归约。 | | ||
| 92 | + | ||
| 93 | +三种路径在VF外分发。长行按双向量尾折叠、单向量尾折叠及纯主段划分独立循环,最多64个局部和,循环内不判断归约模式。局部和临时复用当前y的UB区域,均值和方差先后使用该空间,并通过`VST_VLD`屏障保证可见性,归一化时再覆盖为最终y。归一化将前后半批行配对,共用gamma/beta寄存器加载,奇数尾行单独处理。 | ||
| 94 | + | ||
| 95 | +MTE2预取下一批输入与当前批计算重叠,`MTE2 → V`保证输入就绪,`V → MTE2`保护输入槽复用,`V → MTE3`保证输出可搬出,`MTE3 → V`保护y、mean和rstd槽复用。每核末尾执行全流水同步。常量、VF、Kernel和Host入口统一放在`layer_norm.asc`中,`tiling.h`通过显式`LayerNormConfig`接收配置,可独立包含。 | ||
| 96 | + | ||
| 97 | +## 编译运行 | ||
| 98 | + | ||
| 99 | +配置CANN环境变量,Python依赖为NumPy和CPU可用的Torch,不要求torch_npu: | ||
| 100 | + | ||
| 101 | +```bash | ||
| 102 | +source ${install_path}/cann/set_env.sh | ||
| 103 | +``` | ||
| 104 | + | ||
| 105 | +> **说明:** `${install_path}`为CANN包安装目录;root用户默认为`/usr/local/Ascend`,非root用户默认为`${HOME}/Ascend`。数据脚本默认禁用Torch设备后端自动加载。 | ||
| 106 | + | ||
| 107 | +在本样例目录编译并运行: | ||
| 108 | + | ||
| 109 | +```bash | ||
| 110 | +mkdir -p build && cd build | ||
| 111 | +cmake .. | ||
| 112 | +make -j | ||
| 113 | +python3 ../scripts/gen_data.py | ||
| 114 | +./demo | ||
| 115 | +python3 ../scripts/verify_result.py | ||
| 116 | +``` | ||
| 117 | + | ||
| 118 | +默认生成并验证`[13,1000]`输入及y、mean、rstd三个输出。改变shape无需重新编译,例如指定3核执行上述分批示例: | ||
| 119 | + | ||
| 120 | +```bash | ||
| 121 | +python3 ../scripts/gen_data.py --shape 97,1000 --normalized-shape 1000 | ||
| 122 | +./demo 97,1000 1000 1e-5 data/input/x.bin data/input/gamma.bin data/input/beta.bin data/output/y.bin data/output/mean.bin data/output/rstd.bin 3 | ||
| 123 | +python3 ../scripts/verify_result.py | ||
| 124 | +``` | ||
| 125 | + | ||
| 126 | +自定义参数顺序为`shape normalized_shape epsilon x.bin gamma.bin beta.bin y.bin mean.bin rstd.bin [cores]`,不指定cores时使用硬件核数。生成数据与执行时的shape、epsilon和文件路径应一致;数据脚本还支持`--pattern`、`--seed`和`--data-dir`,校验脚本可接收对应的数据目录。 | ||
| 127 | + | ||
| 128 | +### 编译选项与仿真 | ||
| 129 | + | ||
| 130 | +| 编译选项 | 可选值 | 说明 | | ||
| 131 | +| --- | --- | --- | | ||
| 132 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510`(默认) | 支持的NPU架构。 | | ||
| 133 | +| `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | NPU运行或仿真;不支持CPU孪生调试模式。 | | ||
| 134 | + | ||
| 135 | +仿真时,在样例根目录配置独立构建目录: | ||
| 136 | + | ||
| 137 | +```bash | ||
| 138 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 139 | +cmake --build build/sim --parallel | ||
| 140 | +``` | ||
| 141 | + | ||
| 142 | +在`build/sim`中生成数据、运行`./demo`并校验结果,脚本路径分别使用`../../scripts/gen_data.py`和`../../scripts/verify_result.py`。两种模式均使用Device 0;仿真耗时不能作为硬件性能测量结果。 | ||
| 143 | + | ||
| 144 | +### 结果校验 | ||
| 145 | + | ||
| 146 | +Host检查y、mean和rstd的尾部保护区;数值精度须另行运行校验脚本,`guards=PASS`不代表精度校验通过。全部输出必须为有限值。mean使用`atol=rtol=2e-5`,rstd使用`atol=rtol=1e-4`;y在`atol=rtol=1e-4`的基础上增加均值舍入的条件误差项,具体计算见`scripts/verify_result.py`。校验失败时脚本返回非零退出码。 | ||
| @@ -0,0 +1,146 @@ | |||
| 1 | +# LayerNorm Example | ||
| 2 | + | ||
| 3 | +## Overview | ||
| 4 | + | ||
| 5 | +This example implements FP32 LayerNorm using the Ascend C C API. It normalizes consecutive trailing dimensions, applies elementwise gamma and beta, and returns the normalized output y, mean and reciprocal standard deviation rstd. | ||
| 6 | + | ||
| 7 | +It computes the mean first and centered variance in a second pass, with runtime multidimensional shapes, resident parameters, row-based multicore partitioning, dynamic batches and Ping/Pong double buffering. | ||
| 8 | + | ||
| 9 | +## Supported Products and CANN Versions | ||
| 10 | + | ||
| 11 | +| Product | CANN Version | | ||
| 12 | +|---------|-------------| | ||
| 13 | +| Ascend 950PR&950DT products | >= CANN 9.3.0 | | ||
| 14 | + | ||
| 15 | +This sample uses the `dav-3510` architecture and supports only NPU and NPU simulation modes. | ||
| 16 | + | ||
| 17 | +## Directory Structure | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +normalization | ||
| 21 | +├── scripts | ||
| 22 | +│ ├── gen_data.py # Generate inputs and reference outputs | ||
| 23 | +│ └── verify_result.py # Verify outputs | ||
| 24 | +├── CMakeLists.txt # Build configuration | ||
| 25 | +├── layer_norm.asc # Constants, VF computation, kernel and host | ||
| 26 | +├── tiling.h # Shape checks, partitioning and UB sizing | ||
| 27 | +├── README.md | ||
| 28 | +└── README_en.md | ||
| 29 | +``` | ||
| 30 | + | ||
| 31 | +## Example Description | ||
| 32 | + | ||
| 33 | +This example independently normalizes rows of FP32 data. It first computes each row's mean, then averages the squared differences from that mean to obtain population variance without unbiased correction. It adds epsilon and computes the reciprocal square root. Each centered input element is multiplied by this value and the corresponding gamma, then beta is added. Gamma and beta are shared across rows and both are mandatory. In addition to y, each row produces one mean and one rstd; variance is not returned. | ||
| 34 | + | ||
| 35 | +Normalization can cover the last dimension or multiple consecutive trailing dimensions. Gamma and beta must match these dimensions exactly. For input `[batch, sequence, hidden]`, parameters shaped `[hidden]` give one independent row per `[batch, sequence]` position; parameters shaped `[sequence, hidden]` give one row per batch. Flatten the normalized dimensions into row length R and the prefix dimensions into row count A to obtain `[A,R]`. If the parameter shapes match the entire input, the input is one row and each statistics output contains one element. | ||
| 36 | + | ||
| 37 | +Rows can contain 1 to 9504 elements. Each batch loads complete rows; no row is split across cores or loaded in segments across batches. Row counts need not be multiples of the core count or batch size, and row lengths need not match vector alignment. The final core, batch and vector use their valid ranges. All inputs and outputs use FP32. Mixed precision, missing gamma/beta and rows exceeding full-row UB capacity are not supported. Epsilon defaults to `1e-5` and must be positive and finite in FP32. | ||
| 38 | + | ||
| 39 | +The computation is: | ||
| 40 | + | ||
| 41 | +$$ | ||
| 42 | +\mu_i=\frac{1}{R}\sum_{j=0}^{R-1}x_{i,j},\qquad | ||
| 43 | +v_i=\frac{1}{R}\sum_{j=0}^{R-1}(x_{i,j}-\mu_i)^2 | ||
| 44 | +$$ | ||
| 45 | + | ||
| 46 | +$$ | ||
| 47 | +rstd_i=\frac{1}{\sqrt{v_i+\varepsilon}},\qquad | ||
| 48 | +y_{i,j}=((x_{i,j}-\mu_i)\cdot rstd_i)\cdot\gamma_j+\beta_j | ||
| 49 | +$$ | ||
| 50 | + | ||
| 51 | +Intermediate arithmetic uses FP32. Reductions use power-of-two scaling and directly sum centered squares rather than `E[x²]-E[x]²`. The rstd calculation uses division, square root, Newton–Raphson and residual corrections. The affine transform uses fused multiply-add. Independent references use Torch float64 arithmetic and are stored as float32; verification accounts for FP32 error and the effect of rounded means on normalization. | ||
| 52 | + | ||
| 53 | +**Table 1** Input and output specifications | ||
| 54 | + | ||
| 55 | +| Tensor | Direction | File | Type | Default shape | Description | | ||
| 56 | +| --- | --- | --- | --- | --- | --- | | ||
| 57 | +| x | Input | `data/input/x.bin` | float32 | `[13,1000]` | Runtime multidimensional shape. | | ||
| 58 | +| gamma | Input | `data/input/gamma.bin` | float32 | `[1000]` | Matches normalized trailing dimensions. | | ||
| 59 | +| beta | Input | `data/input/beta.bin` | float32 | `[1000]` | Same shape as gamma. | | ||
| 60 | +| y | Output | `data/output/y.bin` | float32 | `[13,1000]` | Same shape as x, tightly packed. | | ||
| 61 | +| mean | Output | `data/output/mean.bin` | float32 | `[13]` | Prefix dimensions of x; A contiguous elements. | | ||
| 62 | +| rstd | Output | `data/output/rstd.bin` | float32 | `[13]` | Same shape as mean. | | ||
| 63 | +| golden | Reference | `data/output/golden_{y,mean,rstd}.bin` | float32 | Matches each output | Independent Torch reference. | | ||
| 64 | + | ||
| 65 | +### Multicore Partitioning and UB Layout | ||
| 66 | + | ||
| 67 | +**Partition rows across cores.** Only A is split; R stays intact, with no cross-core reduction. By default, `coreCount` is the available hardware Vector Core count; a positive count not exceeding this limit can also be specified. Host computes `blockFactor=ceil(A/coreCount)` and launches `usedCores=ceil(A/blockFactor)` cores. Empty cores are not launched, so the actual count can be less than requested. Core k starts at row `k*blockFactor`, processes `min(blockFactor,A-k*blockFactor)` rows, and starts at GM element offset `k*blockFactor*R`, with zero-based indexing. Row ranges are consecutive and non-overlapping. | ||
| 68 | + | ||
| 69 | +**Process batches within each core.** All cores share batch capacity B, named `a_factor`. A core processes `ceil(coreRows/B)` sequential batches. Batch t starts at local row `t*B` and contains `min(B,coreRows-t*B)` rows. Even batches use Ping and odd batches use Pong. Gamma and beta are loaded once per core and reused across rows and batches. x/y and mean/rstd each have two slots; variance has one current-batch workspace. | ||
| 70 | + | ||
| 71 | +**Alignment and workspace.** The FP32 vector length is `V=64`. A 32-byte UB block holds eight floats. GM rows contain R packed elements; UB row stride is `S=ceil(R/8)*8`. Statistics capacity is `T=ceil(B/8)*8`. Regions are ordered as gamma, beta, x Ping/Pong, y Ping/Pong, mean Ping/Pong, rstd Ping/Pong and variance. Gamma, beta, the x double-buffer region and the y double-buffer region are each followed by V floats of vector-access guard space. | ||
| 72 | + | ||
| 73 | +Gamma and beta occupy `2*S` floats, the four x/y slots occupy `4*B*S`, the four mean/rstd slots plus variance occupy `5*T`, and guards occupy `4*V`. Exact usage is: | ||
| 74 | + | ||
| 75 | +```text | ||
| 76 | +usedBytes = 4 * (2*S + 4*B*S + 5*T + 4*V) | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +**Choose batch capacity.** The static UB pool is 224 KiB with another 8 KiB reserved; hardware UB must be at least 232 KiB. Host binary-searches `1..min(blockFactor,65535)` for the largest B satisfying the exact capacity check. If even B=1 does not fit, processing is rejected rather than switching to segmented reduction. Dimension products forming A and R are separately checked for uint32 overflow, and GM allocation checks total byte size. Two-dimensional DMA transfers only valid columns, masks handle vector tails, and UB padding/guards are not written to GM. Each GM output has a 64-float trailing guard checked before saving; guards are not included in output files. | ||
| 80 | + | ||
| 81 | +For input `[97,1000]`, gamma/beta `[1000]` and three requested cores, `blockFactor=33` and `usedCores=3`. Cores process rows 0–32, 33–65 and 66–96: 33, 33 and 31 rows. Here `S=1000`, binary search gives `B=13`, `T=16` and 217344 bytes of UB usage. B=14 would require 233344 bytes, exceeding 224 KiB. Every core executes three batches: 13/13/7 rows on each of the first two cores and 13/13/5 on the last. For the default `[13,1000]` input, at least 13 available cores result in 13 launched cores, each processing one row in one batch. | ||
| 82 | + | ||
| 83 | +### Reduction and Double Buffering | ||
| 84 | + | ||
| 85 | +**Table 2** Reduction branches | ||
| 86 | + | ||
| 87 | +| R | Path | | ||
| 88 | +| --- | --- | | ||
| 89 | +| 1–64 | One-vector mean and centered-square reduction. | | ||
| 90 | +| 65–128 | Two-vector reduction with tail masks. | | ||
| 91 | +| 129–9504 | Fold the tail into the largest power-of-two main segment not exceeding R, generate partial sums per 128 elements, then reduce them. | | ||
| 92 | + | ||
| 93 | +Paths dispatch outside VF loops. Long rows use separate paired-tail, single-tail and main-only loops, producing at most 64 partial sums without a mode branch inside the loops. Partial sums temporarily reuse the current y UB region for the mean and variance in sequence. VST/VLD barriers ensure visibility before normalization replaces them with final y values. Normalization pairs rows from the first and second halves of a batch to share gamma/beta register loads; an odd final row is handled separately. | ||
| 94 | + | ||
| 95 | +MTE2 prefetch overlaps current computation. MTE2→V ensures input readiness, V→MTE2 protects input-slot reuse, V→MTE3 ensures output readiness, and MTE3→V protects y/mean/rstd-slot reuse. Full-pipeline synchronization occurs at each core's end. Constants, VF computation, kernel and host entry point are in `layer_norm.asc`; the self-contained `tiling.h` receives explicit `LayerNormConfig` configuration. | ||
| 96 | + | ||
| 97 | +## Build and Run | ||
| 98 | + | ||
| 99 | +Configure CANN. Python requires NumPy and CPU-capable Torch, not torch_npu: | ||
| 100 | + | ||
| 101 | +```bash | ||
| 102 | +source ${install_path}/cann/set_env.sh | ||
| 103 | +``` | ||
| 104 | + | ||
| 105 | +> **Note:** `${install_path}` is the CANN installation directory, typically `/usr/local/Ascend` for root or `${HOME}/Ascend` otherwise. The data script disables Torch device-backend autoloading by default. | ||
| 106 | + | ||
| 107 | +From the example directory: | ||
| 108 | + | ||
| 109 | +```bash | ||
| 110 | +mkdir -p build && cd build | ||
| 111 | +cmake .. | ||
| 112 | +make -j | ||
| 113 | +python3 ../scripts/gen_data.py | ||
| 114 | +./demo | ||
| 115 | +python3 ../scripts/verify_result.py | ||
| 116 | +``` | ||
| 117 | + | ||
| 118 | +The default input is `[13,1000]`; all three outputs are verified. Runtime shapes require no rebuild. For the three-core batching example: | ||
| 119 | + | ||
| 120 | +```bash | ||
| 121 | +python3 ../scripts/gen_data.py --shape 97,1000 --normalized-shape 1000 | ||
| 122 | +./demo 97,1000 1000 1e-5 data/input/x.bin data/input/gamma.bin data/input/beta.bin data/output/y.bin data/output/mean.bin data/output/rstd.bin 3 | ||
| 123 | +python3 ../scripts/verify_result.py | ||
| 124 | +``` | ||
| 125 | + | ||
| 126 | +Argument order is `shape normalized_shape epsilon x.bin gamma.bin beta.bin y.bin mean.bin rstd.bin [cores]`; omitting cores uses the hardware count. Shape, epsilon and paths must match generated data. The generator also accepts `--pattern`, `--seed` and `--data-dir`; the verifier accepts the corresponding data directory. | ||
| 127 | + | ||
| 128 | +### Build Options and Simulation | ||
| 129 | + | ||
| 130 | +| Option | Values | Description | | ||
| 131 | +| --- | --- | --- | | ||
| 132 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510` (default) | Supported NPU architecture. | | ||
| 133 | +| `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | NPU execution or simulation; CPU debugging is not supported. | | ||
| 134 | + | ||
| 135 | +For simulation, configure a separate build directory from the sample root: | ||
| 136 | + | ||
| 137 | +```bash | ||
| 138 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 139 | +cmake --build build/sim --parallel | ||
| 140 | +``` | ||
| 141 | + | ||
| 142 | +Generate data, run `./demo` and verify results from `build/sim`, using `../../scripts/gen_data.py` and `../../scripts/verify_result.py`. Device 0 is used in both modes. Simulation timing is not a hardware performance measurement. | ||
| 143 | + | ||
| 144 | +### Verification | ||
| 145 | + | ||
| 146 | +The host checks trailing guards for y, mean and rstd. Run the verification script to check numerical accuracy; `guards=PASS` alone does not certify accuracy. All outputs must be finite. Mean uses `atol=rtol=2e-5`; rstd uses `atol=rtol=1e-4`. For y, the base `atol=rtol=1e-4` tolerance also includes a conditioning term for mean rounding, defined in `scripts/verify_result.py`. The script returns nonzero on failure. | ||
| @@ -0,0 +1,97 @@ | |||
| 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 | +import argparse | ||
| 12 | +import json | ||
| 13 | +import math | ||
| 14 | +import os | ||
| 15 | +from pathlib import Path | ||
| 16 | + | ||
| 17 | +os.environ.setdefault("TORCH_DEVICE_BACKEND_AUTOLOAD", "0") | ||
| 18 | +import numpy as np | ||
| 19 | +import torch | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def parse_shape(text): | ||
| 23 | + parts = text.split(",") | ||
| 24 | + if not parts or any(not part.isascii() or not part.isdecimal() or int(part) <= 0 for part in parts): | ||
| 25 | + raise ValueError("Shape must contain positive comma-separated dimensions") | ||
| 26 | + return tuple(map(int, parts)) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def generate(shape, normalized_shape, epsilon, data_dir, pattern="random", seed=2026): | ||
| 30 | + if not shape or not normalized_shape or any(value <= 0 for value in shape + normalized_shape): | ||
| 31 | + raise ValueError("Shape must contain positive dimensions") | ||
| 32 | + if len(normalized_shape) > len(shape) or shape[-len(normalized_shape) :] != normalized_shape: | ||
| 33 | + raise ValueError("Normalized shape must match the trailing dimensions of x") | ||
| 34 | + if ( | ||
| 35 | + not math.isfinite(epsilon) | ||
| 36 | + or epsilon < np.finfo(np.float32).smallest_subnormal | ||
| 37 | + or epsilon > np.finfo(np.float32).max | ||
| 38 | + ): | ||
| 39 | + raise ValueError("Epsilon must be positive and finite") | ||
| 40 | + rows = math.prod(shape[: -len(normalized_shape)]) | ||
| 41 | + length = math.prod(normalized_shape) | ||
| 42 | + if rows > 2**32 - 1 or length > 9504: | ||
| 43 | + raise ValueError("Shape exceeds the FP32 Two Pass sample capacity") | ||
| 44 | + torch.manual_seed(seed) | ||
| 45 | + x = torch.randn(rows, length, dtype=torch.float32) | ||
| 46 | + if pattern == "constant": | ||
| 47 | + x = torch.arange(rows, dtype=torch.float32).remainder(7).sub(3).unsqueeze(1).expand(rows, length).clone() | ||
| 48 | + elif pattern == "offset": | ||
| 49 | + x = x * 0.5 + 32.0 | ||
| 50 | + elif pattern == "large": | ||
| 51 | + x = x * 1e12 | ||
| 52 | + elif pattern == "alternating": | ||
| 53 | + x = torch.arange(length).remainder(2).float().mul(2).sub(1).expand(rows, length).clone() | ||
| 54 | + elif pattern != "random": | ||
| 55 | + raise ValueError("Unknown data pattern") | ||
| 56 | + gamma = torch.randn(length, dtype=torch.float32) * 0.5 + 1.0 | ||
| 57 | + beta = torch.randn(length, dtype=torch.float32) * 0.25 | ||
| 58 | + wide = x.double() | ||
| 59 | + mean = wide.mean(dim=1) | ||
| 60 | + variance = (wide - mean[:, None]).square().mean(dim=1) | ||
| 61 | + rstd = torch.rsqrt(variance + float(np.float32(epsilon))) | ||
| 62 | + y = (wide - mean[:, None]) * rstd[:, None] * gamma.double() + beta.double() | ||
| 63 | + data_dir = Path(data_dir) | ||
| 64 | + (data_dir / "input").mkdir(parents=True, exist_ok=True) | ||
| 65 | + (data_dir / "output").mkdir(parents=True, exist_ok=True) | ||
| 66 | + for name, tensor in (("x", x), ("gamma", gamma), ("beta", beta)): | ||
| 67 | + tensor.numpy().astype("<f4").tofile(data_dir / "input" / f"{name}.bin") | ||
| 68 | + for name, tensor in (("y", y), ("mean", mean), ("rstd", rstd)): | ||
| 69 | + tensor.numpy().astype("<f4").tofile(data_dir / "output" / f"golden_{name}.bin") | ||
| 70 | + metadata = { | ||
| 71 | + "shape": shape, | ||
| 72 | + "normalized_shape": normalized_shape, | ||
| 73 | + "epsilon": epsilon, | ||
| 74 | + "pattern": pattern, | ||
| 75 | + "seed": seed, | ||
| 76 | + "a": rows, | ||
| 77 | + "r": length, | ||
| 78 | + "dtype": "float32", | ||
| 79 | + } | ||
| 80 | + (data_dir / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n") | ||
| 81 | + print(f"Generated FP32 A={rows} R={length} pattern={pattern}: {data_dir}") | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def main(): | ||
| 85 | + parser = argparse.ArgumentParser() | ||
| 86 | + parser.add_argument("--shape", default="13,1000", type=parse_shape) | ||
| 87 | + parser.add_argument("--normalized-shape", default="1000", type=parse_shape) | ||
| 88 | + parser.add_argument("--epsilon", type=float, default=1e-5) | ||
| 89 | + parser.add_argument("--pattern", choices=("random", "constant", "offset", "large", "alternating"), default="random") | ||
| 90 | + parser.add_argument("--seed", type=int, default=2026) | ||
| 91 | + parser.add_argument("--data-dir", type=Path, default=Path("data")) | ||
| 92 | + args = parser.parse_args() | ||
| 93 | + generate(args.shape, args.normalized_shape, args.epsilon, args.data_dir, args.pattern, args.seed) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +if __name__ == "__main__": | ||
| 97 | + main() | ||
| @@ -0,0 +1,57 @@ | |||
| 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 | +import argparse | ||
| 12 | +import json | ||
| 13 | +from pathlib import Path | ||
| 14 | + | ||
| 15 | +import numpy as np | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def verify(data_dir): | ||
| 19 | + data_dir = Path(data_dir) | ||
| 20 | + metadata = json.loads((data_dir / "metadata.json").read_text()) | ||
| 21 | + for name, count in (("y", metadata["a"] * metadata["r"]), ("mean", metadata["a"]), ("rstd", metadata["a"])): | ||
| 22 | + actual = np.fromfile(data_dir / "output" / f"{name}.bin", dtype="<f4") | ||
| 23 | + golden = np.fromfile(data_dir / "output" / f"golden_{name}.bin", dtype="<f4") | ||
| 24 | + if actual.size != count or golden.size != count: | ||
| 25 | + raise AssertionError(f"{name}: wrong output size") | ||
| 26 | + if not np.isfinite(actual).all() or not np.isfinite(golden).all(): | ||
| 27 | + raise AssertionError(f"{name}: non-finite values") | ||
| 28 | + atol, rtol = (2e-5, 2e-5) if name == "mean" else (1e-4, 1e-4) | ||
| 29 | + difference = np.abs(actual.astype(np.float64) - golden.astype(np.float64)) | ||
| 30 | + tolerance = atol + rtol * np.abs(golden.astype(np.float64)) | ||
| 31 | + if name == "y": | ||
| 32 | + mean = np.fromfile(data_dir / "output/golden_mean.bin", dtype="<f4") | ||
| 33 | + rstd = np.fromfile(data_dir / "output/golden_rstd.bin", dtype="<f4") | ||
| 34 | + gamma = np.fromfile(data_dir / "input/gamma.bin", dtype="<f4") | ||
| 35 | + if mean.size != metadata["a"] or rstd.size != metadata["a"] or gamma.size != metadata["r"]: | ||
| 36 | + raise AssertionError("Wrong reference statistics or gamma size") | ||
| 37 | + mean_ulp = np.abs(np.spacing(np.abs(mean))).astype(np.float64) | ||
| 38 | + conditioning = ( | ||
| 39 | + 2 | ||
| 40 | + * mean_ulp[:, None] | ||
| 41 | + * np.abs(rstd.astype(np.float64))[:, None] | ||
| 42 | + * np.abs(gamma.astype(np.float64))[None, :] | ||
| 43 | + ) | ||
| 44 | + tolerance += conditioning.reshape(-1) | ||
| 45 | + accepted = difference <= tolerance | ||
| 46 | + if not accepted.all(): | ||
| 47 | + index = int(np.flatnonzero(~accepted)[0]) | ||
| 48 | + raise AssertionError( | ||
| 49 | + f"{name}[{index}] actual={actual[index]} golden={golden[index]} error={difference[index]}" | ||
| 50 | + ) | ||
| 51 | + print(f"{name}: count={count} max_abs_error={difference.max():.8g} [PASS]") | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +if __name__ == "__main__": | ||
| 55 | + parser = argparse.ArgumentParser() | ||
| 56 | + parser.add_argument("data_dir", type=Path, nargs="?", default=Path("data")) | ||
| 57 | + verify(parser.parse_args().data_dir) | ||
| @@ -0,0 +1,146 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef LAYER_NORM_SAMPLE_TILING_H | ||
| 12 | +#define LAYER_NORM_SAMPLE_TILING_H | ||
| 13 | + | ||
| 14 | +#include <algorithm> | ||
| 15 | +#include <cmath> | ||
| 16 | +#include <cstdint> | ||
| 17 | +#include <limits> | ||
| 18 | +#include <stdexcept> | ||
| 19 | +#include <string> | ||
| 20 | +#include <vector> | ||
| 21 | +#include "utils/std/cmath.h" | ||
| 22 | + | ||
| 23 | +struct LayerNormConfig { | ||
| 24 | + uint32_t vector_length; | ||
| 25 | + uint32_t block_floats; | ||
| 26 | + uint32_t ub_arena_bytes; | ||
| 27 | + uint32_t ub_reserved_bytes; | ||
| 28 | +}; | ||
| 29 | + | ||
| 30 | +struct LayerNormTilingData { | ||
| 31 | + uint32_t a; | ||
| 32 | + uint32_t r; | ||
| 33 | + uint32_t r_align; | ||
| 34 | + uint32_t block_num; | ||
| 35 | + uint32_t a_block_factor; | ||
| 36 | + uint32_t a_factor; | ||
| 37 | + uint32_t stats_align; | ||
| 38 | + uint32_t r_head; | ||
| 39 | + uint16_t repeat1; | ||
| 40 | + uint16_t repeat2; | ||
| 41 | + uint16_t repeat3; | ||
| 42 | + uint16_t tail_count; | ||
| 43 | + float k2_rec; | ||
| 44 | + float k2_r_rec; | ||
| 45 | + float epsilon; | ||
| 46 | +}; | ||
| 47 | + | ||
| 48 | +inline std::vector<uint32_t> parse_shape(const std::string& text) | ||
| 49 | +{ | ||
| 50 | + std::vector<uint32_t> shape; | ||
| 51 | + size_t begin = 0; | ||
| 52 | + while (begin < text.size()) { | ||
| 53 | + size_t end = text.find(',', begin); | ||
| 54 | + std::string dim = text.substr(begin, end == std::string::npos ? end : end - begin); | ||
| 55 | + if (dim.empty() || dim.find_first_not_of("0123456789") != std::string::npos) { | ||
| 56 | + throw std::invalid_argument("Shape must contain positive comma-separated dimensions"); | ||
| 57 | + } | ||
| 58 | + uint64_t value = std::stoull(dim); | ||
| 59 | + if (value == 0 || value > std::numeric_limits<uint32_t>::max()) { | ||
| 60 | + throw std::invalid_argument("Shape dimension is outside the uint32 range"); | ||
| 61 | + } | ||
| 62 | + shape.push_back(static_cast<uint32_t>(value)); | ||
| 63 | + if (end == std::string::npos) { | ||
| 64 | + return shape; | ||
| 65 | + } | ||
| 66 | + begin = end + 1; | ||
| 67 | + } | ||
| 68 | + throw std::invalid_argument("Shape is empty or has a trailing comma"); | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +inline uint32_t checked_product(const std::vector<uint32_t>& shape, size_t begin, size_t end) | ||
| 72 | +{ | ||
| 73 | + uint32_t product = 1; | ||
| 74 | + for (size_t index = begin; index < end; ++index) { | ||
| 75 | + if (shape[index] == 0 || product > std::numeric_limits<uint32_t>::max() / shape[index]) { | ||
| 76 | + throw std::invalid_argument("Shape product is zero or exceeds uint32"); | ||
| 77 | + } | ||
| 78 | + product *= shape[index]; | ||
| 79 | + } | ||
| 80 | + return product; | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +inline uint64_t required_floats(uint32_t rows, uint32_t stride, const LayerNormConfig& config) | ||
| 84 | +{ | ||
| 85 | + uint64_t stats = AscendC::Std::ceil_div(rows, config.block_floats) * config.block_floats; | ||
| 86 | + return 2ULL * stride + 4ULL * rows * stride + 5 * stats + 4ULL * config.vector_length; | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +inline LayerNormTilingData make_tiling( | ||
| 90 | + const std::vector<uint32_t>& shape, const std::vector<uint32_t>& normalized_shape, uint32_t cores, | ||
| 91 | + uint64_t ub_bytes, const LayerNormConfig& config, float epsilon) | ||
| 92 | +{ | ||
| 93 | + if (normalized_shape.empty() || shape.size() < normalized_shape.size() || cores == 0 || config.vector_length == 0 || | ||
| 94 | + config.block_floats == 0 || !std::isfinite(epsilon) || epsilon <= 0 || | ||
| 95 | + ub_bytes < static_cast<uint64_t>(config.ub_arena_bytes) + config.ub_reserved_bytes) { | ||
| 96 | + throw std::invalid_argument("Invalid rank, core count, epsilon or UB capacity (232 KiB required)"); | ||
| 97 | + } | ||
| 98 | + size_t prefix = shape.size() - normalized_shape.size(); | ||
| 99 | + if (!std::equal(normalized_shape.begin(), normalized_shape.end(), shape.begin() + prefix)) { | ||
| 100 | + throw std::invalid_argument("Gamma and beta must match the normalized trailing dimensions of x"); | ||
| 101 | + } | ||
| 102 | + LayerNormTilingData td{}; | ||
| 103 | + td.a = checked_product(shape, 0, prefix); | ||
| 104 | + td.r = checked_product(normalized_shape, 0, normalized_shape.size()); | ||
| 105 | + if (td.r > config.ub_arena_bytes / (6 * sizeof(float))) { | ||
| 106 | + throw std::invalid_argument("The complete row does not fit the FP32 Two Pass UB layout"); | ||
| 107 | + } | ||
| 108 | + td.r_align = AscendC::Std::ceil_div(td.r, config.block_floats) * config.block_floats; | ||
| 109 | + td.a_block_factor = AscendC::Std::ceil_div(td.a, cores); | ||
| 110 | + td.block_num = AscendC::Std::ceil_div(td.a, td.a_block_factor); | ||
| 111 | + uint32_t low = 1; | ||
| 112 | + uint32_t high = std::min(td.a_block_factor, static_cast<uint32_t>(UINT16_MAX)); | ||
| 113 | + while (low <= high) { | ||
| 114 | + uint32_t mid = low + (high - low) / 2; | ||
| 115 | + if (required_floats(mid, td.r_align, config) * sizeof(float) <= config.ub_arena_bytes) { | ||
| 116 | + td.a_factor = mid; | ||
| 117 | + low = mid + 1; | ||
| 118 | + } else { | ||
| 119 | + high = mid - 1; | ||
| 120 | + } | ||
| 121 | + } | ||
| 122 | + if (td.a_factor == 0) { | ||
| 123 | + throw std::invalid_argument("The complete row does not fit the FP32 Two Pass UB layout"); | ||
| 124 | + } | ||
| 125 | + td.stats_align = AscendC::Std::ceil_div(td.a_factor, config.block_floats) * config.block_floats; | ||
| 126 | + td.r_head = config.vector_length; | ||
| 127 | + while (td.r_head * 2 <= td.r) | ||
| 128 | + td.r_head *= 2; | ||
| 129 | + uint32_t overflow = td.r_head < td.r ? td.r_head * 2 : td.r_head; | ||
| 130 | + td.k2_rec = 1.0f / overflow; | ||
| 131 | + td.k2_r_rec = static_cast<float>(overflow) / td.r; | ||
| 132 | + uint32_t partial_count = td.r > 128 ? td.r_head / 128 : 1; | ||
| 133 | + if (partial_count > config.vector_length) | ||
| 134 | + throw std::invalid_argument("Partial reduction exceeds one vector"); | ||
| 135 | + if (td.r > 128) { | ||
| 136 | + uint32_t tail = td.r - td.r_head; | ||
| 137 | + td.repeat1 = AscendC::Std::ceil_div(tail, config.vector_length) / 2; | ||
| 138 | + td.tail_count = td.repeat1 * 128 > tail ? 0 : tail % 128; | ||
| 139 | + td.repeat2 = AscendC::Std::ceil_div(static_cast<uint32_t>(td.tail_count), config.vector_length); | ||
| 140 | + td.repeat3 = (td.r_head - (td.repeat1 + td.repeat2) * 128) / 128; | ||
| 141 | + } | ||
| 142 | + td.epsilon = epsilon; | ||
| 143 | + return td; | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +#endif | ||
| @@ -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_RUN_MODE "npu" CACHE STRING "Run mode: npu, sim") | ||
| 14 | +set(CMAKE_ASC_ARCHITECTURES "dav-3510" CACHE STRING "NPU architecture: dav-3510") | ||
| 15 | + | ||
| 16 | +find_package(ASC REQUIRED) | ||
| 17 | + | ||
| 18 | +project(kernel_samples LANGUAGES ASC CXX) | ||
| 19 | + | ||
| 20 | +add_executable(demo | ||
| 21 | + rms_norm_quant.asc | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +if(NOT CMAKE_ASC_ARCHITECTURES STREQUAL "dav-3510") | ||
| 25 | + message(FATAL_ERROR "This sample only supports CMAKE_ASC_ARCHITECTURES=dav-3510") | ||
| 26 | +endif() | ||
| 27 | + | ||
| 28 | +if(NOT CMAKE_ASC_RUN_MODE MATCHES "^(npu|sim)$") | ||
| 29 | + message(FATAL_ERROR "CMAKE_ASC_RUN_MODE must be npu or sim, but got ${CMAKE_ASC_RUN_MODE}") | ||
| 30 | +endif() | ||
| 31 | + | ||
| 32 | +target_link_libraries(demo PRIVATE | ||
| 33 | + tiling_api | ||
| 34 | + register | ||
| 35 | + platform | ||
| 36 | + m | ||
| 37 | +) | ||
| 38 | + | ||
| 39 | +target_compile_options(demo PRIVATE | ||
| 40 | + $<$<COMPILE_LANGUAGE:ASC>:--npu-arch=${CMAKE_ASC_ARCHITECTURES}> | ||
| 41 | +) | ||
| @@ -0,0 +1,174 @@ | |||
| 1 | +# RmsNormQuant标量量化样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
| 4 | + | ||
| 5 | +本样例使用Ascend C C API实现RMSNorm与INT8标量量化融合计算。输入、gamma和scale为half类型,按gamma对应的尾部维度归一化,再乘标量scale并加INT8标量zeroPoint,输出INT8结果。 | ||
| 6 | + | ||
| 7 | +样例面向按尾部维度进行RMS归一化、并使用全局共享标量参数生成单路INT8输出的场景,采用参数复用、多核切分和Ping/Pong Double Buffer流水。 | ||
| 8 | + | ||
| 9 | +## 本样例支持的产品及CANN软件版本 | ||
| 10 | + | ||
| 11 | +| 产品 | CANN软件版本 | | ||
| 12 | +|------|-------------| | ||
| 13 | +| Ascend 950PR&950DT系列产品 | >= CANN 9.3.0 | | ||
| 14 | + | ||
| 15 | +本样例固定使用`dav-3510`架构,仅支持NPU和仿真运行模式。 | ||
| 16 | + | ||
| 17 | +## 目录结构 | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +rms_norm_quant | ||
| 21 | +├── scripts | ||
| 22 | +│ ├── gen_data.py # 生成输入数据和真值数据 | ||
| 23 | +│ └── verify_result.py # 校验输出结果 | ||
| 24 | +├── CMakeLists.txt # 编译工程文件 | ||
| 25 | +├── rms_norm_quant.asc # 共享常量、VF计算、Kernel及Host侧实现 | ||
| 26 | +├── tiling.h # Shape校验、分核及UB布局 | ||
| 27 | +├── data_utils.h # 二进制数据读写工具 | ||
| 28 | +├── README.md | ||
| 29 | +└── README_en.md | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +## 样例描述 | ||
| 33 | + | ||
| 34 | +本样例适用于将多行FP16数据分别归一化后量化为INT8的场景。每行先计算平方均值,加上epsilon并求平方根倒数,再依次乘以该行输入、对应位置的gamma和标量scale,最后加上标量zeroPoint并转换为INT8。gamma在所有行间共享,同一组scale和zeroPoint用于整个输入;输出仅包含量化结果,不单独输出rstd。 | ||
| 35 | + | ||
| 36 | +归一化可以覆盖输入的最后一维,也可以覆盖连续的多个尾部维度,但gamma的shape必须与这些尾部维度逐维一致。例如,输入为`[batch, sequence, hidden]`、gamma为`[hidden]`时,每个`[batch, sequence]`位置独立处理一行;gamma为`[sequence, hidden]`时,每个batch独立处理一行。将这些尾部维度展开为长度R,将其余前缀维度展开为行数A,得到逻辑矩阵`[A,R]`。若gamma与输入shape完全相同,则整个输入作为一行处理。 | ||
| 37 | + | ||
| 38 | +每行长度支持1到16384,必须能够连同所需参数和临时空间放入UB。输入行数、行长不要求是核数、批次大小或向量长度的整数倍,末核、末批及末尾不足一个向量的数据均按实际有效范围处理。每批加载完整的若干行,不将同一行拆给多个核或多次分段加载。本样例不支持beta加法、第二路输出、逐通道scale或zeroPoint,也不支持用scale做除法。计算公式为: | ||
| 39 | + | ||
| 40 | +$$ | ||
| 41 | +v_i=\frac{1}{R}\sum_{j=0}^{R-1}x_{i,j}^{2}+\varepsilon,\qquad | ||
| 42 | +rstd_i=\frac{1}{\sqrt{v_i}} | ||
| 43 | +$$ | ||
| 44 | + | ||
| 45 | +$$ | ||
| 46 | +q_{i,j}=((x_{i,j}\cdot rstd_i)\cdot\gamma_j)\cdot scale+zeroPoint | ||
| 47 | +$$ | ||
| 48 | + | ||
| 49 | +$$ | ||
| 50 | +y_{i,j}=\operatorname{asc\_half2int8\_rn} | ||
| 51 | +\left(\operatorname{asc\_float2half\_ro}(q_{i,j})\right) | ||
| 52 | +$$ | ||
| 53 | + | ||
| 54 | +中间计算使用FP32。rstd按`Div → Sqrt → Newton–Raphson`顺序进行精度修正,方差为`+Inf`时选择`0`,为`0`时选择`+Inf`,不额外添加`max(v,0)`。量化乘加按公式顺序执行,不合并为FMA;FP32转FP16使用`asc_float2half_ro`,FP16转INT8使用`asc_half2int8_rn`,不添加显式clamp或改用截断舍入。 | ||
| 55 | + | ||
| 56 | +本样例使用默认的全局饱和配置(`USE_GLOBAL`且CAST饱和开启,参见[饱和策略](../../../../docs/zh/api/SIMD-API/c_api/spr/asc_set_saturation_strategy.md)及[饱和开关](../../../../docs/zh/api/SIMD-API/c_api/spr/asc_set_saturation_flag.md)),因此`asc_half2int8_rn`的指令选项`NO_SAT`不等于实际执行整数回绕。`dav-3510`设备验证中,有限溢出值限制到`[-128,127]`,`+Inf/-Inf/NaN`分别得到`127/-128/0`。数据生成脚本中的`np.clip`模拟该转换结果,Kernel没有额外执行clamp。 | ||
| 57 | + | ||
| 58 | +**表1** 输入输出数据规格 | ||
| 59 | + | ||
| 60 | +| 数据 | 输入/输出 | 数据文件 | 数据类型 | 默认Shape | 说明 | | ||
| 61 | +| --- | --- | --- | --- | --- | --- | | ||
| 62 | +| x | 输入 | `input/x.bin` | half | `[13,8192]` | 支持运行时多维shape。 | | ||
| 63 | +| gamma | 输入 | `input/gamma.bin` | half | `[8192]` | 必须匹配x的尾部维度。 | | ||
| 64 | +| scale | 输入 | `input/scale.bin` | half | `[1]` | 标量量化系数,默认2.25。 | | ||
| 65 | +| zeroPoint | 输入 | `input/zero_point.bin` | int8_t | `[1]` | 标量量化偏置,默认-3。 | | ||
| 66 | +| y | 输出 | `output/y.bin` | int8_t | `[13,8192]` | 与x同shape,紧密连续存放。 | | ||
| 67 | +| golden | 真值 | `output/golden.bin` | int8_t | `[13,8192]` | 独立NumPy参考结果。 | | ||
| 68 | + | ||
| 69 | +### 多核切分与UB布局 | ||
| 70 | + | ||
| 71 | +FP32向量长度`V=64`,UB block为32字节。支持`1≤R≤4V²=16384`,且整行及参数必须通过UB容量检查;计算A和R时,分别检查对应维度乘积的uint32溢出。epsilon默认`1e-6`,直接作为FP32参与计算,不额外限制必须为正。 | ||
| 72 | + | ||
| 73 | +**按行分核。** 只沿A维切分,R维始终保持完整,各核之间没有跨核归约。`coreCount`默认取硬件可用Vector Core数,也可以指定不超过硬件核数的正整数。Host先用`ceil(A/coreCount)`确定每个普通核的行数`blockFactor`,再用`ceil(A/blockFactor)`确定实际启动核数`usedCores`,不启动没有数据的空核。因此,实际核数可能少于指定核数。核索引k从0开始,第k核从第`k*blockFactor`行开始,处理`min(blockFactor, A-k*blockFactor)`行;对应GM元素起点为`k*blockFactor*R`,所有核覆盖连续且互不重叠的行区间。 | ||
| 74 | + | ||
| 75 | +**表2** 分核和分批参数 | ||
| 76 | + | ||
| 77 | +| 参数 | 计算方式 | 说明 | | ||
| 78 | +| --- | --- | --- | | ||
| 79 | +| blockFactor | `ceil(A/coreCount)` | 每个非尾核分配的行数。 | | ||
| 80 | +| usedCores | `ceil(A/blockFactor)` | 实际启动核数。 | | ||
| 81 | +| blockTail | `A-(usedCores-1)*blockFactor` | 尾核实际行数。 | | ||
| 82 | +| rAlign | `ceil(R/V)*V` | UB行步长,GM中无padding。 | | ||
| 83 | +| fold | `2^floor(log2(ceil(R/16)*16-1))` | 二分归约折叠点,Host使用整数运算求取。 | | ||
| 84 | +| B | 按UB容量反推并限制到每核行数 | 每批行数,最后一批按实际剩余行数处理。 | | ||
| 85 | + | ||
| 86 | +**核内按批处理。** 每个核使用相同的批次容量B,在自己的行区间内顺序执行`ceil(本核行数/B)`批。第t批从本核第`t*B`行开始,实际行数为`min(B, 本核行数-t*B)`,最后一批不补齐逻辑行。批次0、2、4等使用Ping槽,批次1、3、5等使用Pong槽;每个槽最多容纳B条完整行。gamma、scale和zeroPoint在每核开始时各搬入一次,并在该核所有批次间复用。 | ||
| 87 | + | ||
| 88 | +**UB空间组成。** GM中的每行紧密存放R个元素,搬入UB后行步长向上对齐为`rAlign=ceil(R/V)*V`。各区按gamma、scale、zeroPoint、x Ping/Pong、y Ping/Pong、partial和rstd的顺序连续排布,起始地址均按32字节对齐。gamma占`2*rAlign`字节,scale和zeroPoint各预留32字节;两个FP16输入槽合计占`4*B*rAlign`字节,两个INT8输出槽合计占`2*B*rAlign`字节。partial和rstd是当前批次共享的FP32临时区,不各自设置Ping/Pong两份。令`P=ceil((fold/V)/V)*V`,当`R≤128`时不需要partial、P取0;其余情况下partial占`4*B*P`字节,rstd占`4*ceil(B/V)*V`字节。总占用为: | ||
| 89 | + | ||
| 90 | +```text | ||
| 91 | +usedBytes = 2*rAlign + 64 + 6*B*rAlign + 4*B*P + 4*ceil(B/V)*V | ||
| 92 | +``` | ||
| 93 | + | ||
| 94 | +**根据容量确定B。** 可用容量C取`min(248 KiB, hardwareUB-8 KiB)`。Host先预估固定开销`F=2*rAlign+64+4*V`和每行开销`D=6*rAlign+4*P+4`,将`floor((C-F)/D)`、`blockFactor`和65535三者的最小值作为初始B,再按上面的精确布局检查;若仍超出C则逐行减小B。固定开销已超限或连一行都无法容纳时,报错而不启动计算。二维DMA仅在紧密GM行与对齐UB行之间搬运有效数据,向量尾列使用mask,UB中的padding不写回GM。 | ||
| 95 | + | ||
| 96 | +例如,输入为`[97,8192]`、gamma为`[8192]`,指定3核,硬件UB为256 KiB时,得到`A=97`、`R=8192`、`blockFactor=33`,实际启动3核。三个核分别处理第0–32行、第33–65行、第66–96行,行数为33、33、31。此时`rAlign=8192`、`fold=4096`、`P=64`,由UB容量得到`B=4`,总占用为214336字节。前两个核各执行9批,前8批每批4行、末批1行;最后一个核执行8批,前7批每批4行、末批3行。默认`[13,8192]`输入在可用核数不少于13时则启动13核,每核处理1行、执行1批。 | ||
| 97 | + | ||
| 98 | +### 归约与Double Buffer流水 | ||
| 99 | + | ||
| 100 | +**表3** 归约分支 | ||
| 101 | + | ||
| 102 | +| R范围 | 计算路径 | | ||
| 103 | +| --- | --- | | ||
| 104 | +| 1–64 | 单向量平方后ReduceSum。 | | ||
| 105 | +| 65–128 | 两向量分别平方,尾部清零,相加后ReduceSum。 | | ||
| 106 | +| 129–8192 | 二分折叠、局部和、单向量收尾。 | | ||
| 107 | +| 8193–16384 | 二分折叠、局部和、两向量相加后收尾。 | | ||
| 108 | + | ||
| 109 | +四种路径在VF外通过模板分发,局部和存取间使用`VST_VLD`同步。x/y各使用两套Buffer,MTE2预取下一批与当前批计算、搬出重叠,槽复用前通过`MTE3 → MTE2`事件保证生命周期。 | ||
| 110 | + | ||
| 111 | +共享常量、VF计算、Kernel及Host运行入口统一放在`rms_norm_quant.asc`。`tiling.h`独立定义tiling结构和Host计算函数,通过`RmsNormQuantConfig`显式接收向量宽度与UB限制,不依赖主文件中的全局常量或包含顺序。 | ||
| 112 | + | ||
| 113 | +## 编译运行 | ||
| 114 | + | ||
| 115 | +配置CANN环境变量,需要Python 3及NumPy: | ||
| 116 | + | ||
| 117 | +```bash | ||
| 118 | +source ${install_path}/cann/set_env.sh | ||
| 119 | +``` | ||
| 120 | + | ||
| 121 | +> **说明:** `${install_path}`为CANN包安装目录;root用户默认为`/usr/local/Ascend`,非root用户默认为`${HOME}/Ascend`。 | ||
| 122 | + | ||
| 123 | +在本样例目录编译并运行: | ||
| 124 | + | ||
| 125 | +```bash | ||
| 126 | +mkdir -p build && cd build | ||
| 127 | +cmake .. | ||
| 128 | +make -j | ||
| 129 | +python3 ../scripts/gen_data.py | ||
| 130 | +./demo | ||
| 131 | +python3 ../scripts/verify_result.py | ||
| 132 | +``` | ||
| 133 | + | ||
| 134 | +在构建目录运行量化边界回归,覆盖四种归约分支、非对齐尾部、RINT舍入、有限溢出、Inf/NaN及零方差。定向用例要求输出完全一致: | ||
| 135 | + | ||
| 136 | +```bash | ||
| 137 | +python3 ../tests/quantization_test.py ./demo | ||
| 138 | +``` | ||
| 139 | + | ||
| 140 | +默认使用`dav-3510`架构、NPU运行模式和Device 0。仿真使用独立构建目录,在样例根目录执行: | ||
| 141 | + | ||
| 142 | +```bash | ||
| 143 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 144 | +cmake --build build/sim --parallel | ||
| 145 | +cd build/sim | ||
| 146 | +python3 ../../scripts/gen_data.py | ||
| 147 | +./demo | ||
| 148 | +python3 ../../scripts/verify_result.py | ||
| 149 | +``` | ||
| 150 | + | ||
| 151 | +仿真耗时不能作为硬件性能结果。以下动态shape命令在前述NPU构建目录`build`中执行。 | ||
| 152 | + | ||
| 153 | +动态shape示例,在build目录执行: | ||
| 154 | + | ||
| 155 | +```bash | ||
| 156 | +python3 ../scripts/gen_data.py --x-shape 2,3,16,32 --gamma-shape 16,32 | ||
| 157 | +./demo 2,3,16,32 16,32 input output 1 1e-6 | ||
| 158 | +python3 ../scripts/verify_result.py | ||
| 159 | +``` | ||
| 160 | + | ||
| 161 | +运行参数为`demo [x_shape gamma_shape input_dir output_dir [cores [epsilon]]]`,shape使用逗号分隔。不指定核数时查询硬件核数,输入数据长度必须与shape一致,输出目录由数据生成脚本创建。 | ||
| 162 | + | ||
| 163 | +**表4** 编译选项 | ||
| 164 | + | ||
| 165 | +| 编译选项 | 可选值 | 说明 | | ||
| 166 | +| --- | --- | --- | | ||
| 167 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510`(默认) | 指定NPU架构。 | | ||
| 168 | +| `CMAKE_ASC_RUN_MODE` | `npu`(默认)、`sim` | 选择NPU或NPU仿真模式。 | | ||
| 169 | + | ||
| 170 | +校验脚本比较全部INT8输出并检查文件长度。随机用例仅允许转换前FP32值在`±2e-6*max(1,abs(q))`误差区间内引起的量化边界差异,数量不超过`max(1,N/10000)`并单独报告;定向用例要求完全一致。Host同时检查Device输出前后各256字节保护区。默认数据校验成功时输出: | ||
| 171 | + | ||
| 172 | +```text | ||
| 173 | +PASS: 106496 INT8 outputs; exact=106496, bounded reduction-boundary differences=0 | ||
| 174 | +``` | ||
| @@ -0,0 +1,173 @@ | |||
| 1 | +# RmsNormQuant Scalar Quantization Example | ||
| 2 | + | ||
| 3 | +## Overview | ||
| 4 | + | ||
| 5 | +This example implements fused RMSNorm and scalar INT8 quantization using the Ascend C C API. Input, gamma and scale use FP16. Normalization is performed over the trailing dimensions matching gamma, followed by multiplication by scalar scale and addition of scalar INT8 zeroPoint, producing one INT8 output. | ||
| 6 | + | ||
| 7 | +The example normalizes trailing dimensions and produces a single INT8 output using globally shared scalar quantization parameters, with parameter reuse, multicore partitioning and Ping/Pong double buffering. | ||
| 8 | + | ||
| 9 | +## Supported Products and CANN Versions | ||
| 10 | + | ||
| 11 | +| Product | CANN Version | | ||
| 12 | +|---------|-------------| | ||
| 13 | +| Ascend 950PR&950DT products | >= CANN 9.3.0 | | ||
| 14 | + | ||
| 15 | +This sample uses the `dav-3510` architecture and supports only NPU and NPU simulation modes. | ||
| 16 | + | ||
| 17 | +## Directory Structure | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +rms_norm_quant | ||
| 21 | +├── scripts | ||
| 22 | +│ ├── gen_data.py # Generate inputs and reference outputs | ||
| 23 | +│ └── verify_result.py # Verify outputs | ||
| 24 | +├── CMakeLists.txt # Build configuration | ||
| 25 | +├── rms_norm_quant.asc # Constants, VF computation, kernel and host | ||
| 26 | +├── tiling.h # Shape checks, partitioning and UB layout | ||
| 27 | +├── data_utils.h # Binary file utilities | ||
| 28 | +├── README.md | ||
| 29 | +└── README_en.md | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +## Example Description | ||
| 33 | + | ||
| 34 | +This example independently normalizes rows of FP16 data and quantizes them to INT8. For each row, it computes the mean square, adds epsilon and computes the reciprocal square root. It then multiplies each input element by this value, the corresponding gamma element and scalar scale, adds scalar zeroPoint, and converts the result to INT8. Gamma is shared across rows; one scale and one zeroPoint apply to the entire input. Only the quantized output is returned, not rstd. | ||
| 35 | + | ||
| 36 | +Normalization can cover the last dimension or multiple consecutive trailing dimensions. Gamma must match these dimensions exactly. For an input shaped `[batch, sequence, hidden]`, gamma shaped `[hidden]` gives one independent row per `[batch, sequence]` position; gamma shaped `[sequence, hidden]` gives one row per batch. Flatten the normalized dimensions into row length R and the remaining prefix dimensions into row count A to obtain `[A,R]`. If gamma matches the entire input shape, the entire input is processed as one row. | ||
| 37 | + | ||
| 38 | +Row lengths from 1 to 16384 are supported, provided a complete row, parameters and workspace fit in UB. Row counts and lengths need not be multiples of the core count, batch size or vector width: the final core, batch and vector use their actual valid ranges. Each batch loads complete rows; a row is never split across cores or loaded in multiple segments. Beta addition, a second output, per-channel scale or zeroPoint, and division by scale are not supported. The computation is: | ||
| 39 | + | ||
| 40 | +$$ | ||
| 41 | +v_i=\frac{1}{R}\sum_{j=0}^{R-1}x_{i,j}^{2}+\varepsilon,\qquad rstd_i=1/\sqrt{v_i} | ||
| 42 | +$$ | ||
| 43 | + | ||
| 44 | +$$ | ||
| 45 | +q_{i,j}=((x_{i,j}\cdot rstd_i)\cdot\gamma_j)\cdot scale+zeroPoint | ||
| 46 | +$$ | ||
| 47 | + | ||
| 48 | +$$ | ||
| 49 | +y_{i,j}=\operatorname{asc\_half2int8\_rn} | ||
| 50 | +\left(\operatorname{asc\_float2half\_ro}(q_{i,j})\right) | ||
| 51 | +$$ | ||
| 52 | + | ||
| 53 | +Intermediate arithmetic uses FP32. The rstd correction follows the Div/Sqrt/Newton–Raphson sequence, with rstd=0 for positive-infinite variance and rstd=positive infinity for zero variance. No additional `max(v,0)` is applied. Quantization operations are not fused into FMA. The casts use `asc_float2half_ro` followed by `asc_half2int8_rn`, without explicit clamp or truncation rounding. | ||
| 54 | + | ||
| 55 | +This sample uses the default global saturation configuration (`USE_GLOBAL` with CAST saturation enabled; see [saturation strategy](../../../../docs/zh/api/SIMD-API/c_api/spr/asc_set_saturation_strategy.md) and [saturation flags](../../../../docs/zh/api/SIMD-API/c_api/spr/asc_set_saturation_flag.md)), so the `NO_SAT` instruction option of `asc_half2int8_rn` does not imply wrapping integer conversion. On `dav-3510`, device checks show finite overflow limited to `[-128,127]`, with `+Inf/-Inf/NaN` producing `127/-128/0`. The generator's `np.clip` models this conversion result; the kernel performs no extra clamp. | ||
| 56 | + | ||
| 57 | +**Table 1** Input and output specifications | ||
| 58 | + | ||
| 59 | +| Tensor | Direction | File | Type | Default shape | Description | | ||
| 60 | +| --- | --- | --- | --- | --- | --- | | ||
| 61 | +| x | Input | `input/x.bin` | half | `[13,8192]` | Runtime multidimensional shape. | | ||
| 62 | +| gamma | Input | `input/gamma.bin` | half | `[8192]` | Must match trailing x dimensions. | | ||
| 63 | +| scale | Input | `input/scale.bin` | half | `[1]` | Scalar scale, default 2.25. | | ||
| 64 | +| zeroPoint | Input | `input/zero_point.bin` | int8_t | `[1]` | Scalar offset, default -3. | | ||
| 65 | +| y | Output | `output/y.bin` | int8_t | `[13,8192]` | Same shape as x, tightly packed. | | ||
| 66 | +| golden | Reference | `output/golden.bin` | int8_t | `[13,8192]` | Independent NumPy reference. | | ||
| 67 | + | ||
| 68 | +### Multicore Partitioning and UB Layout | ||
| 69 | + | ||
| 70 | +The FP32 vector width is V=64 and the UB block size is 32 bytes. Supported R is `1..4*V*V=16384`, subject to full-row UB capacity checks. The dimension products forming A and R are separately checked for uint32 overflow. Epsilon defaults to `1e-6` and is used directly as FP32 without an additional positivity restriction. | ||
| 71 | + | ||
| 72 | +**Partition rows across cores.** Only A is split; R stays intact, with no cross-core reduction. By default, `coreCount` is the available hardware Vector Core count; a positive count not exceeding this limit can also be specified. Host first computes `blockFactor=ceil(A/coreCount)`, then launches `usedCores=ceil(A/blockFactor)` cores, with no empty cores. The actual count may therefore be less than requested. Core k, indexed from zero, starts at row `k*blockFactor` and processes `min(blockFactor, A-k*blockFactor)` rows. Its GM element offset is `k*blockFactor*R`. The cores cover consecutive, non-overlapping row ranges. | ||
| 73 | + | ||
| 74 | +**Table 2** Partitioning and batch parameters | ||
| 75 | + | ||
| 76 | +| Parameter | Calculation | Description | | ||
| 77 | +| --- | --- | --- | | ||
| 78 | +| blockFactor | `ceil(A/coreCount)` | Rows assigned to each non-tail core. | | ||
| 79 | +| usedCores | `ceil(A/blockFactor)` | Number of launched cores. | | ||
| 80 | +| blockTail | `A-(usedCores-1)*blockFactor` | Rows on the last core. | | ||
| 81 | +| rAlign | `ceil(R/V)*V` | UB row stride; GM has no padding. | | ||
| 82 | +| fold | `2^floor(log2(ceil(R/16)*16-1))` | Binary folding point, derived using integer arithmetic. | | ||
| 83 | +| B | Derived from UB capacity and capped by per-core rows | Batch rows; the final batch uses its actual row count. | | ||
| 84 | + | ||
| 85 | +**Process batches within each core.** All cores use the same batch capacity B. Each core processes its assigned rows in `ceil(coreRows/B)` sequential batches. Batch t starts at local row `t*B` and contains `min(B, coreRows-t*B)` rows, without adding logical rows to the final batch. Even-indexed batches use Ping and odd-indexed batches use Pong, with up to B complete rows per slot. Gamma, scale and zeroPoint are loaded once per core and reused across its batches. | ||
| 86 | + | ||
| 87 | +**UB layout.** GM rows contain R tightly packed elements; UB rows use the aligned stride `rAlign=ceil(R/V)*V`. UB regions are consecutive in the order gamma, scale, zeroPoint, x Ping/Pong, y Ping/Pong, partial sums and rstd, with 32-byte-aligned starts. Gamma occupies `2*rAlign` bytes; scale and zeroPoint each reserve 32 bytes. The two FP16 input slots occupy `4*B*rAlign` bytes in total, and the two INT8 output slots occupy `2*B*rAlign` bytes. Partial sums and rstd are FP32 workspaces shared by successive batches, without separate Ping/Pong copies. Let `P=ceil((fold/V)/V)*V`, or zero when `R≤128`, which requires no partial sums. Partial sums occupy `4*B*P` bytes and rstd occupies `4*ceil(B/V)*V` bytes. Total usage is: | ||
| 88 | + | ||
| 89 | +```text | ||
| 90 | +usedBytes = 2*rAlign + 64 + 6*B*rAlign + 4*B*P + 4*ceil(B/V)*V | ||
| 91 | +``` | ||
| 92 | + | ||
| 93 | +**Choose B from capacity.** Available capacity C is `min(248 KiB, hardwareUB-8 KiB)`. Host estimates fixed overhead `F=2*rAlign+64+4*V` and per-row overhead `D=6*rAlign+4*P+4`. The initial B is the minimum of `floor((C-F)/D)`, `blockFactor` and 65535. Host checks the exact layout above and decreases B one row at a time if necessary. If fixed overhead exceeds the limit or even one row cannot fit, processing is rejected before kernel launch. Two-dimensional DMA transfers valid data between packed GM rows and aligned UB rows. Masks handle tail columns, and UB padding is not written to GM. | ||
| 94 | + | ||
| 95 | +For example, input `[97,8192]`, gamma `[8192]`, three requested cores and 256 KiB hardware UB give `A=97`, `R=8192` and `blockFactor=33`, launching three cores. They process rows 0–32, 33–65 and 66–96, respectively: 33, 33 and 31 rows. Here `rAlign=8192`, `fold=4096`, `P=64` and `B=4`, using 214336 bytes of UB. Each of the first two cores executes nine batches: eight batches of four rows and a final batch of one row. The last core executes eight batches: seven batches of four rows and a final batch of three rows. For the default `[13,8192]` input, if at least 13 cores are available, 13 cores each process one row in one batch. | ||
| 96 | + | ||
| 97 | +### Reduction and Double Buffering | ||
| 98 | + | ||
| 99 | +**Table 3** Reduction branches | ||
| 100 | + | ||
| 101 | +| R | Path | | ||
| 102 | +| --- | --- | | ||
| 103 | +| 1–64 | One-vector square sum. | | ||
| 104 | +| 65–128 | Square two vectors, zero tail lanes, add and reduce. | | ||
| 105 | +| 129–8192 | Binary folding and partial sums, one-vector final reduction. | | ||
| 106 | +| 8193–16384 | Binary folding and partial sums, two-vector final reduction. | | ||
| 107 | + | ||
| 108 | +Template instances dispatch outside VF loops. VST/VLD barriers protect intermediate sums. Two slots per x/y buffer overlap MTE2 prefetch with computation/output. MTE3→MTE2 events protect slot reuse. | ||
| 109 | + | ||
| 110 | +Shared constants, VF computation, the kernel and host entry point are defined in `rms_norm_quant.asc`. The self-contained `tiling.h` receives vector width and UB limits explicitly through `RmsNormQuantConfig`, without depending on main-file globals or include order. | ||
| 111 | + | ||
| 112 | +## Build and Run | ||
| 113 | + | ||
| 114 | +Load the CANN environment. Python 3 and NumPy are required: | ||
| 115 | + | ||
| 116 | +```bash | ||
| 117 | +source ${install_path}/cann/set_env.sh | ||
| 118 | +``` | ||
| 119 | + | ||
| 120 | +`${install_path}` is the CANN installation directory: `/usr/local/Ascend` for root by default, or `${HOME}/Ascend` for non-root users. | ||
| 121 | + | ||
| 122 | +From the example directory: | ||
| 123 | + | ||
| 124 | +```bash | ||
| 125 | +mkdir -p build && cd build | ||
| 126 | +cmake .. | ||
| 127 | +make -j | ||
| 128 | +python3 ../scripts/gen_data.py | ||
| 129 | +./demo | ||
| 130 | +python3 ../scripts/verify_result.py | ||
| 131 | +``` | ||
| 132 | + | ||
| 133 | +From the build directory, run the quantization-boundary regression covering all four reduction branches, unaligned tails, RINT rounding, finite overflow, Inf/NaN and zero variance. Directed cases require exact output matches: | ||
| 134 | + | ||
| 135 | +```bash | ||
| 136 | +python3 ../tests/quantization_test.py ./demo | ||
| 137 | +``` | ||
| 138 | + | ||
| 139 | +Defaults are architecture `dav-3510`, NPU mode and Device 0. For simulation, use a separate build directory from the sample root: | ||
| 140 | + | ||
| 141 | +```bash | ||
| 142 | +cmake -S . -B build/sim -DCMAKE_ASC_RUN_MODE=sim | ||
| 143 | +cmake --build build/sim --parallel | ||
| 144 | +cd build/sim | ||
| 145 | +python3 ../../scripts/gen_data.py | ||
| 146 | +./demo | ||
| 147 | +python3 ../../scripts/verify_result.py | ||
| 148 | +``` | ||
| 149 | + | ||
| 150 | +Simulation timing is not a hardware performance measurement. Run the following dynamic-shape commands in the NPU build directory, `build`. | ||
| 151 | + | ||
| 152 | +Runtime shape example, from the build directory: | ||
| 153 | + | ||
| 154 | +```bash | ||
| 155 | +python3 ../scripts/gen_data.py --x-shape 2,3,16,32 --gamma-shape 16,32 | ||
| 156 | +./demo 2,3,16,32 16,32 input output 1 1e-6 | ||
| 157 | +python3 ../scripts/verify_result.py | ||
| 158 | +``` | ||
| 159 | + | ||
| 160 | +The interface is `demo [x_shape gamma_shape input_dir output_dir [cores [epsilon]]]`. Shapes use comma-separated dimensions. Hardware core count is queried when omitted. Input file lengths must match the shapes; the generator creates the output directory. | ||
| 161 | + | ||
| 162 | +**Table 4** Build options | ||
| 163 | + | ||
| 164 | +| Option | Values | Description | | ||
| 165 | +| --- | --- | --- | | ||
| 166 | +| `CMAKE_ASC_ARCHITECTURES` | `dav-3510` (default) | NPU architecture. | | ||
| 167 | +| `CMAKE_ASC_RUN_MODE` | `npu` (default), `sim` | NPU or simulation mode. | | ||
| 168 | + | ||
| 169 | +Verification checks every INT8 output and file length. Random cases allow only quantization-boundary differences within ±`2e-6*max(1,abs(q))` of the pre-cast FP32 value, limited to `max(1,N/10000)` and reported separately. Directed cases require exact matches. Host also checks 256-byte guards on both sides of device output. Successful default verification prints: | ||
| 170 | + | ||
| 171 | +```text | ||
| 172 | +PASS: 106496 INT8 outputs; exact=106496, bounded reduction-boundary differences=0 | ||
| 173 | +``` | ||
| @@ -0,0 +1,44 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef RMS_NORM_QUANT_SAMPLE_DATA_UTILS_H | ||
| 12 | +#define RMS_NORM_QUANT_SAMPLE_DATA_UTILS_H | ||
| 13 | + | ||
| 14 | +#include <fstream> | ||
| 15 | +#include <stdexcept> | ||
| 16 | +#include <string> | ||
| 17 | +#include <vector> | ||
| 18 | + | ||
| 19 | +template <typename DataType> | ||
| 20 | +std::vector<DataType> read_tensor(const std::string& path, size_t elements) | ||
| 21 | +{ | ||
| 22 | + std::ifstream input(path, std::ios::binary | std::ios::ate); | ||
| 23 | + size_t bytes = elements * sizeof(DataType); | ||
| 24 | + if (!input || input.tellg() != static_cast<std::streamoff>(bytes)) { | ||
| 25 | + throw std::invalid_argument("Wrong tensor file size: " + path); | ||
| 26 | + } | ||
| 27 | + std::vector<DataType> data(elements); | ||
| 28 | + input.seekg(0); | ||
| 29 | + input.read(reinterpret_cast<char*>(data.data()), bytes); | ||
| 30 | + if (!input) | ||
| 31 | + throw std::runtime_error("Unable to read " + path); | ||
| 32 | + return data; | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +template <typename DataType> | ||
| 36 | +void write_tensor(const std::string& path, const std::vector<DataType>& data) | ||
| 37 | +{ | ||
| 38 | + std::ofstream output(path, std::ios::binary); | ||
| 39 | + output.write(reinterpret_cast<const char*>(data.data()), data.size() * sizeof(DataType)); | ||
| 40 | + if (!output) | ||
| 41 | + throw std::runtime_error("Unable to write " + path); | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +#endif | ||


样例列表列了 activation/normalization/rms_norm_quant/attention 四个目录,但这次 diff 只看到 activation 目录下的文件。能否确认另外三个目录是同 PR 一起提交还是别处补上?避免 README 链到还不存在的目录。