Merged
[ChunkKdaFwd] 新增 KDA 分块正向算子 #9979
BartonFangAdd on Aug 12
[ChunkKdaFwd] 新增 KDA 分块正向算子 #9979
Merged
Total: 194 files changed+70492-0
| @@ -0,0 +1,17 @@ | |||
| 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 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 10 | +if(NOT ENABLE_TEST AND NOT BENCHMARK) | ||
| 11 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 12 | +endif() | ||
| 13 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 14 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 15 | + add_subdirectory(${SUB_DIR}) | ||
| 16 | + endif() | ||
| 17 | +endforeach() | ||
| @@ -0,0 +1,193 @@ | |||
| 1 | +# ChunkKdaFwd | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +| 产品 | 是否支持 | | ||
| 6 | +| :--- | :---: | | ||
| 7 | +| <term>Ascend 950PR/Ascend 950DT</term> | √ | | ||
| 8 | +| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | √ | | ||
| 9 | +| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | √ | | ||
| 10 | +| <term>Atlas 200I/500 A2 推理产品</term> | × | | ||
| 11 | +| <term>Atlas 推理系列产品</term> | × | | ||
| 12 | +| <term>Atlas 训练系列产品</term> | × | | ||
| 13 | + | ||
| 14 | +## 功能说明 | ||
| 15 | + | ||
| 16 | +- 算子功能:完成不涉及CP切分的KDA分块正向计算,计算注意力输出、最终状态以及可选的反向中间量。 | ||
| 17 | + | ||
| 18 | +- 计算公式: | ||
| 19 | + | ||
| 20 | + 将每条序列按$C=chunk\_size$划分为$M$个chunk。以第$c$个chunk为例,$i$、$j$为chunk内token下标,$l_c$为该chunk最后一个有效token下标。公式省略batch和head下标;GQA场景中,每个Value head使用其对应的Query/Key head。 | ||
| 21 | + | ||
| 22 | + 令$x_{c,i,d}=g_{c,i,d}+dt\_bias_d$,未传入`dt_bias`时令$dt\_bias_d=0$。激活后gate为: | ||
| 23 | + | ||
| 24 | + $$ | ||
| 25 | + \gamma_{c,i,d}= | ||
| 26 | + \begin{cases} | ||
| 27 | + g_{c,i,d}, & use\_gate\_in\_kernel=false,\\ | ||
| 28 | + -\exp(A_{log})\operatorname{softplus}(x_{c,i,d}), | ||
| 29 | + & use\_gate\_in\_kernel=true,\ safe\_gate=false,\\ | ||
| 30 | + lower\_bound\operatorname{sigmoid}(\exp(A_{log})x_{c,i,d}), | ||
| 31 | + & use\_gate\_in\_kernel=true,\ safe\_gate=true. | ||
| 32 | + \end{cases} | ||
| 33 | + $$ | ||
| 34 | + | ||
| 35 | + `gk`为chunk-local的log2累计gate: | ||
| 36 | + | ||
| 37 | + $$ | ||
| 38 | + gk_{c,i,d}=\frac{1}{\ln 2}\sum_{t=0}^{i}\gamma_{c,t,d}. | ||
| 39 | + $$ | ||
| 40 | + | ||
| 41 | + `qg`和`kg`分别为gate缩放后的Query和Key: | ||
| 42 | + | ||
| 43 | + $$ | ||
| 44 | + qg_{c,i,d}=q_{c,i,d}2^{gk_{c,i,d}},\qquad | ||
| 45 | + kg_{c,i,d}=k_{c,i,d}2^{gk_{c,l_c,d}-gk_{c,i,d}}. | ||
| 46 | + $$ | ||
| 47 | + | ||
| 48 | + 对同一chunk内的token $i$、$j$,`Aqk`为包含对角线的下三角Query-Key系数矩阵: | ||
| 49 | + | ||
| 50 | + $$ | ||
| 51 | + Aqk_{c,i,j}=\mathbb{1}_{j\le i}\cdot scale | ||
| 52 | + \sum_d q_{c,i,d}k_{c,j,d}2^{gk_{c,i,d}-gk_{c,j,d}}. | ||
| 53 | + $$ | ||
| 54 | + | ||
| 55 | + 严格下三角矩阵$L_c$及`Akk`为: | ||
| 56 | + | ||
| 57 | + $$ | ||
| 58 | + L_{c,i,j}=\mathbb{1}_{j<i}\cdot\beta_{c,i} | ||
| 59 | + \sum_d k_{c,i,d}k_{c,j,d}2^{gk_{c,i,d}-gk_{c,j,d}},\qquad | ||
| 60 | + Akk_c=(I+L_c)^{-1}. | ||
| 61 | + $$ | ||
| 62 | + | ||
| 63 | + 令$w^{seed}$和$u^{seed}$为: | ||
| 64 | + | ||
| 65 | + $$ | ||
| 66 | + w^{seed}_{c,i,d}=\beta_{c,i}k_{c,i,d}2^{gk_{c,i,d}},\qquad | ||
| 67 | + u^{seed}_{c,i,e}=\beta_{c,i}v_{c,i,e}. | ||
| 68 | + $$ | ||
| 69 | + | ||
| 70 | + `w`和`u`为: | ||
| 71 | + | ||
| 72 | + $$ | ||
| 73 | + w_c=Akk_c\,w^{seed}_c,\qquad u_c=Akk_c\,u^{seed}_c. | ||
| 74 | + $$ | ||
| 75 | + | ||
| 76 | + 令$h_c$为第$c$个chunk计算前的状态;传入`initial_state`时$h_0=initial\_state$,否则$h_0=0$。`v_new`和下一个chunk状态为: | ||
| 77 | + | ||
| 78 | + $$ | ||
| 79 | + v^{new}_c=u_c-w_c\,h_c, | ||
| 80 | + $$ | ||
| 81 | + | ||
| 82 | + $$ | ||
| 83 | + h_{c+1}=2^{gk_{c,l_c}}\odot h_c+kg_c^T\,v^{new}_c, | ||
| 84 | + $$ | ||
| 85 | + | ||
| 86 | + 其中$2^{gk_{c,l_c}}\odot h_c$表示按$K$维缩放状态矩阵。`h`输出保存各个chunk的输入状态,`final_state`为最后一个chunk更新后的状态: | ||
| 87 | + | ||
| 88 | + $$ | ||
| 89 | + h[c]=h_c,\qquad final\_state=h_M. | ||
| 90 | + $$ | ||
| 91 | + | ||
| 92 | + `attn_out`为: | ||
| 93 | + | ||
| 94 | + $$ | ||
| 95 | + attn\_out_c=scale\cdot qg_c\,h_c+Aqk_c\,v^{new}_c. | ||
| 96 | + $$ | ||
| 97 | + | ||
| 98 | + Python接口的第12项返回值为输入对象透传: | ||
| 99 | + | ||
| 100 | + $$ | ||
| 101 | + initial\_state\_out=initial\_state. | ||
| 102 | + $$ | ||
| 103 | + | ||
| 104 | + 可选输出参数只决定是否向调用方返回对应中间量,不改变上述计算语义。 | ||
| 105 | + | ||
| 106 | +## 参数说明 | ||
| 107 | + | ||
| 108 | +本文使用以下维度符号: | ||
| 109 | + | ||
| 110 | +- B:输入样本batch大小。 | ||
| 111 | +- S:rank-4输入的序列长度。 | ||
| 112 | +- T:rank-3输入的总token数。 | ||
| 113 | +- H:Query和Key的head数。 | ||
| 114 | +- HV:Value和gate的head数。 | ||
| 115 | +- K:Query和Key的head dim。 | ||
| 116 | +- V:Value的head dim。 | ||
| 117 | +- N:逻辑序列数。 | ||
| 118 | +- C:chunk大小。 | ||
| 119 | +- NC:未传入`cu_seqlens`时为每条序列的chunk数$\lceil S/C\rceil$;传入`cu_seqlens`时为所有逻辑序列的chunk总数。 | ||
| 120 | + | ||
| 121 | +| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 | | ||
| 122 | +| :--- | :--- | :--- | :--- | :--- | | ||
| 123 | +| q | 输入 | 公式中的Query。`BSND`为(B, S, H, K),`BNSD`为(B, H, S, K),`TND`为(T, H, K),`NTD`为(H, T, K)。 | FLOAT16、BFLOAT16 | ND | | ||
| 124 | +| k | 输入 | 公式中的Key。shape和数据类型必须与`q`相同。 | FLOAT16、BFLOAT16 | ND | | ||
| 125 | +| v | 输入 | 公式中的Value。`BSND`为(B, S, HV, V),`BNSD`为(B, HV, S, V),`TND`为(T, HV, V),`NTD`为(HV, T, V)。数据类型必须与`q`相同。 | FLOAT16、BFLOAT16 | ND | | ||
| 126 | +| g | 输入 | raw gate或已激活的自然对数gate。`BSND`为(B, S, HV, K),`BNSD`为(B, HV, S, K),`TND`为(T, HV, K),`NTD`为(HV, T, K)。 | FLOAT、BFLOAT16 | ND | | ||
| 127 | +| beta | 输入 | 公式中的Delta系数。`BSND`为(B, S, HV),`BNSD`为(B, HV, S),`TND`为(T, HV),`NTD`为(HV, T)。 | FLOAT、BFLOAT16 | ND | | ||
| 128 | +| a_log | 可选输入 | gate衰减参数,shape为(HV)。当`use_gate_in_kernel=true`时必须传入。 | FLOAT | ND | | ||
| 129 | +| dt_bias | 可选输入 | gate偏置,shape为(HV×K)。 | FLOAT | ND | | ||
| 130 | +| initial_state | 可选输入 | 初始状态。`state_v_first=false`时shape为(N, HV, K, V),否则为(N, HV, V, K)。 | FLOAT | ND | | ||
| 131 | +| cu_seqlens | 可选输入 | 变长序列累计长度,shape为(N+1),首元素为0,末元素为T或S,元素单调不减。 | INT64 | ND | | ||
| 132 | +| chunk_indices | 可选输入 | chunk索引,shape为(2×NC),按`(seq_id, chunk_id)`保存,必须采用sequence-major canonical顺序。传入时必须同时传入`cu_seqlens`。 | INT64 | ND | | ||
| 133 | +| attn_out | 输出 | 注意力输出。rank-4输入固定输出BSND格式(B, S, HV, V);rank-3输入固定输出TND格式(T, HV, V)。 | FLOAT16、BFLOAT16 | ND | | ||
| 134 | +| final_state | 可选输出 | 最终状态。`state_v_first=false`时shape为(N, HV, K, V),否则为(N, HV, V, K)。 | FLOAT | ND | | ||
| 135 | +| gk | 可选输出 | chunk-local log2累计gate。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K)。 | FLOAT | ND | | ||
| 136 | +| Aqk | 输出 | chunk内Query-Key系数矩阵。rank-4输入为(B, HV, S, C),rank-3输入为(HV, T, C)。 | FLOAT16、BFLOAT16 | ND | | ||
| 137 | +| Akk | 输出 | chunk内下三角求逆结果。rank-4输入为(B, HV, S, C),rank-3输入为(HV, T, C)。 | FLOAT16、BFLOAT16 | ND | | ||
| 138 | +| w | 可选输出 | 供反向使用的W中间量。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K)。 | FLOAT16、BFLOAT16 | ND | | ||
| 139 | +| u | 可选输出 | 供反向使用的U中间量。rank-4输入为(B, HV, S, V),rank-3输入为(HV, T, V)。 | FLOAT16、BFLOAT16 | ND | | ||
| 140 | +| qg | 可选输出 | 供反向使用的gate缩放Query。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K)。 | FLOAT16、BFLOAT16 | ND | | ||
| 141 | +| kg | 可选输出 | 供反向使用的gate缩放Key。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K)。 | FLOAT16、BFLOAT16 | ND | | ||
| 142 | +| v_new | 可选输出 | 供反向使用的Value中间量。rank-4输入为(B, HV, S, V),rank-3输入为(HV, T, V)。 | FLOAT16、BFLOAT16 | ND | | ||
| 143 | +| h | 可选输出 | 公开chunk状态。rank-4输入为(B, NC, HV, K, V),rank-3输入为(NC, HV, K, V);`state_v_first=true`时交换末两维。 | FLOAT16、BFLOAT16 | ND | | ||
| 144 | +| layout | 可选属性 | 输入布局。支持`BSND`、`BNSD`、`TND`、`NTD`,默认值为`BSND`。该属性只描述输入布局。 | STRING | - | | ||
| 145 | +| scale | 必选属性 | Query缩放系数。通常取$K^{-0.5}$。 | FLOAT | - | | ||
| 146 | +| chunk_size | 必选属性 | chunk大小。支持64、128,默认值为64。 | INT | - | | ||
| 147 | +| safe_gate | 必选属性 | 是否使用有界gate。默认值为false。 | BOOL | - | | ||
| 148 | +| lower_bound | 可选属性 | 有界gate下界。`safe_gate=true`时取值范围为[-5, 0),默认值为-5.0。 | FLOAT | - | | ||
| 149 | +| use_gate_in_kernel | 必选属性 | 是否在kernel内由raw gate计算激活。默认值为false。 | BOOL | - | | ||
| 150 | +| state_v_first | 可选属性 | 是否将状态张量末两维排列为(V, K)。默认值为false。 | BOOL | - | | ||
| 151 | + | ||
| 152 | +## Python返回策略 | ||
| 153 | + | ||
| 154 | +`cann_ops_transformer.ops.chunk_kda_fwd`固定返回12项。每一项的返回条件如下: | ||
| 155 | + | ||
| 156 | +| 返回项 | 返回条件 | | ||
| 157 | +| :--- | :--- | | ||
| 158 | +| attn_out | 始终返回。 | | ||
| 159 | +| final_state | `output_final_state=true`时返回,否则为`None`。 | | ||
| 160 | +| gk | `use_gate_in_kernel=false`或`disable_recompute=true`时返回,否则为`None`。 | | ||
| 161 | +| Aqk | 始终返回。 | | ||
| 162 | +| Akk | 始终返回。 | | ||
| 163 | +| w | `disable_recompute=true`时返回,否则为`None`。 | | ||
| 164 | +| u | `disable_recompute=true`时返回,否则为`None`。 | | ||
| 165 | +| qg | `disable_recompute=true`时返回,否则为`None`。 | | ||
| 166 | +| kg | `disable_recompute=true`时返回,否则为`None`。 | | ||
| 167 | +| v_new | `disable_recompute=true`时返回,否则为`None`。 | | ||
| 168 | +| h | `disable_recompute=true`或`return_intermediate_states=true`时返回,否则为`None`。 | | ||
| 169 | +| initial_state | 原样返回Python输入`initial_state`,不是aclnn输出。 | | ||
| 170 | + | ||
| 171 | +aclnn接口不接收`output_final_state`、`disable_recompute`或`return_intermediate_states`。L2只根据每个可选输出指针是否为空决定是否导出该输出。 | ||
| 172 | + | ||
| 173 | +## 约束说明 | ||
| 174 | + | ||
| 175 | +- H和HV必须为正整数,且满足HV≥H、HV≤128、HV % H=0。 | ||
| 176 | +- K和V取值范围为[16, 256],且必须为16的倍数。 | ||
| 177 | +- `chunk_size`仅支持64和128。 | ||
| 178 | +- `q`、`k`、`v`的数据类型必须相同。 | ||
| 179 | +- `use_gate_in_kernel=true`时,`a_log`必须传入;`dt_bias`可以不传入。 | ||
| 180 | +- `safe_gate=true`且`use_gate_in_kernel=true`时,`lower_bound`取值范围为[-5, 0)。 | ||
| 181 | +- rank-4变长输入要求B=1。 | ||
| 182 | +- 变长输入最多支持1024条逻辑序列。 | ||
| 183 | +- `layout`只描述输入。`attn_out`固定为sequence-major;供反向继续计算的中间输出固定为head-major;`final_state`和公开`h`按参数表约定输出。 | ||
| 184 | +- 默认支持确定性计算。 | ||
| 185 | + | ||
| 186 | +## 调用说明 | ||
| 187 | + | ||
| 188 | +| 调用方式 | 样例代码 | 说明 | | ||
| 189 | +| :--- | :--- | :--- | | ||
| 190 | +| aclnn接口 | [aclnnChunkKdaFwd](./docs/aclnnChunkKdaFwd.md) | 通过`aclnnChunkKdaFwdGetWorkspaceSize`和`aclnnChunkKdaFwd`调用。 | | ||
| 191 | +| pytest | [ChunkKdaFwd测试框架](./tests/pytest/README.md) | 覆盖功能、跨布局一致性、确定性和性能验证。 | | ||
| 192 | + | ||
| 193 | +阶段划分、平台模板和流水设计见[ChunkKdaFwd算子设计介绍](./docs/ChunkKdaFwd算子设计介绍.md)。 | ||
| @@ -0,0 +1,273 @@ | |||
| 1 | +# ChunkKdaFwd算子设计介绍 | ||
| 2 | + | ||
| 3 | +## 1 设计目标 | ||
| 4 | + | ||
| 5 | +1. 顶层接口对齐非 CP 的 FLA `chunk_kda_fwd`。 | ||
| 6 | +2. 不新增公开算子原型;A5 特化复用既有 `ChunkKdaFwd` L0 调用接口和 | ||
| 7 | + `chunk_kda_fwd` device kernel launch 入口。 | ||
| 8 | +3. A2/A3/A5 使用同一数学定义;A5 保留 regbase 双发射特化。 | ||
| 9 | +4. 输入 layout 与输出 layout 解耦。 | ||
| 10 | +5. FwdH 由 KDA 在 arch22/arch35 下分别维护,支持 key-wise gate 和 `state_v_first`。 | ||
| 11 | + | ||
| 12 | +## 2 计算过程 | ||
| 13 | + | ||
| 14 | +### 2.1 接口分层 | ||
| 15 | + | ||
| 16 | +```text | ||
| 17 | +raw g -> ChunkKdaFwd[ | ||
| 18 | + gate cumsum -> Prepare/Post-WU -> FwdH -> Finalize | ||
| 19 | +] -> attn_out | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +接口调用链按层级划分为: | ||
| 23 | + | ||
| 24 | +```text | ||
| 25 | +cann_ops_transformer.ops.chunk_kda_fwd | ||
| 26 | + -> PyTorch C++ extension wrapper | ||
| 27 | + -> aclnnChunkKdaFwd | ||
| 28 | + -> ChunkKdaFwd L0 注册与 launcher | ||
| 29 | + -> chunk_kda_fwd device kernel launch 入口 | ||
| 30 | + -> Gate / Prepare / Post-WU / FwdH / Finalize 内部阶段 | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +`aclnnChunkKdaFwd` 负责公开 layout 的连续化和必要视图转换,并调用一次已注册的 | ||
| 34 | +`ChunkKdaFwd` L0 接口。L0 launcher 继续使用 `chunk_kda_fwd` device kernel launch 入口。 | ||
| 35 | +Gate、Prepare、Post-WU、FwdH 和 Finalize 只是该 kernel 内部计算阶段,不注册 | ||
| 36 | +`ChunkKdaFwdPrepare`、`ChunkKdaFwdPostWu` 或 `ChunkKdaFwdFinalize` L0 算子。模板选择所需信息 | ||
| 37 | +均由既有输入、shape 和属性推导,不增加公开属性或接口字段。 | ||
| 38 | + | ||
| 39 | +### 2.2 计算阶段 | ||
| 40 | + | ||
| 41 | +#### 2.2.1 Gate Cumsum | ||
| 42 | + | ||
| 43 | +将 raw/已激活 gate 转为 FP32 chunk-local log2 累计值: | ||
| 44 | + | ||
| 45 | +```text | ||
| 46 | +gamma = g use_gate_in_kernel=false | ||
| 47 | +gamma = -exp(A_log) * softplus(g + dt_bias) use_gate_in_kernel=true, safe_gate=false | ||
| 48 | +gamma = lower_bound * sigmoid(exp(A_log) * (g + dt_bias)) use_gate_in_kernel=true, safe_gate=true | ||
| 49 | +gk = chunk_local_cumsum(gamma) / ln(2) | ||
| 50 | +``` | ||
| 51 | + | ||
| 52 | +#### 2.2.2 Prepare | ||
| 53 | + | ||
| 54 | +只读取 `q/k/v/gk/beta` 及变长元数据,产生: | ||
| 55 | + | ||
| 56 | +```text | ||
| 57 | +Aqk, Akk, qg, w_seed, u_seed | ||
| 58 | +``` | ||
| 59 | + | ||
| 60 | +```text | ||
| 61 | +qg[i] = q[i] * exp2(gk[i]) | ||
| 62 | +w_seed[i] = beta[i] * k[i] * exp2(gk[i]) | ||
| 63 | +u_seed[i] = beta[i] * v[i] | ||
| 64 | +``` | ||
| 65 | + | ||
| 66 | +score 点积以 BF16/FP16 为输入、FP32 累积。`Akk=(I+L)^{-1}` 的 `L`、单位阵、 | ||
| 67 | +对角块求逆、分块合并、Cube 输入/累积和 workspace 均为 FP32,并显式关闭 HF32;只在完整 | ||
| 68 | +FP32 求解结束后将公开 `Akk` 写回为 q dtype。 | ||
| 69 | + | ||
| 70 | +#### 2.2.3 Post-WU | ||
| 71 | + | ||
| 72 | +只读取 `k/gk/w_seed/Akk/u_seed`,产生: | ||
| 73 | + | ||
| 74 | +```text | ||
| 75 | +w, u, kg | ||
| 76 | +w = Akk @ w_seed | ||
| 77 | +u = Akk @ u_seed | ||
| 78 | +kg[i] = k[i] * exp2(gk[last] - gk[i]) | ||
| 79 | +``` | ||
| 80 | + | ||
| 81 | +`Akk` 的 head 循环按 `H_v` 执行,GQA 映射只在读取 q/k head 时换算,避免按 `H_k` 重复或漏算。 | ||
| 82 | +Post-WU 是否作为单独的内部阶段执行由 tiling 决定。满足 A5 dense-aligned 融合条件时,Prepare | ||
| 83 | +直接调用 Post-WU 计算组件;其他场景在 Prepare 结束并完成同步后执行内部 Post-WU 阶段。两种 | ||
| 84 | +方式都复用同一 `ChunkKdaFwd` L0 调用接口和 device kernel launch 入口。 | ||
| 85 | + | ||
| 86 | +#### 2.2.4 FwdH | ||
| 87 | + | ||
| 88 | +读取 `kg/w/u/gk` 和可选 `initial_state`,计算 chunk 间状态更新: | ||
| 89 | + | ||
| 90 | +```text | ||
| 91 | +v_new = u - w @ h_prev | ||
| 92 | +h_next = exp2(gk_last) * h_prev + kg^T @ v_new | ||
| 93 | +h[chunk] = h_prev | ||
| 94 | +final_state = h_after_last_chunk | ||
| 95 | +``` | ||
| 96 | + | ||
| 97 | +arch22 和 arch35 均使用 `ChunkKdaFwd` 目录内的 KDA 私有 FwdH 实现,不依赖其他算子的 | ||
| 98 | +kernel 源码。跨 chunk 的 `h_prev/h_next` 固定保存在 FP32 workspace 或 FP32 `final_state` 中; | ||
| 99 | +公开 `h` 仅作为反向保存快照按 q dtype 写回,不能反向参与下一 chunk 的状态更新。 | ||
| 100 | + | ||
| 101 | +#### 2.2.5 Finalize | ||
| 102 | + | ||
| 103 | +只读取 `qg/Aqk/v_new/h`,以 FP32 累积计算: | ||
| 104 | + | ||
| 105 | +```text | ||
| 106 | +attn_out = scale * (qg @ h) + Aqk @ v_new | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +`scale` 在第一项完成 FP32 点积后施加,不预先量化进 BF16 `qg`。 | ||
| 110 | + | ||
| 111 | +kernel 内直接按 BSND/TND 写出 `attn_out`。供反向使用的中间量保持 BNSD/NTD。 | ||
| 112 | + | ||
| 113 | +## 3 数值设计 | ||
| 114 | + | ||
| 115 | +- `q`、`k`、`v`和公式中以输入dtype保存的中间量作为矩阵乘输入,矩阵乘使用FP32累加。 | ||
| 116 | +- `Akk=(I+L)^{-1}`的$L$、单位阵、对角块求逆、分块合并、Cube输入和累加保持FP32,不启用HF32。 | ||
| 117 | +- chunk间状态$h_c$和`final_state`的计算保持FP32,不使用公开`h`的低精度快照继续下一个chunk的状态传播。 | ||
| 118 | +- `attn_out`的两项矩阵乘和加法使用FP32累加,在最终写回时转为输出dtype。 | ||
| 119 | + | ||
| 120 | +## 4 输出布局与重计算 | ||
| 121 | + | ||
| 122 | +### 4.1 状态布局 | ||
| 123 | + | ||
| 124 | +内部状态统一使用 `[...,K,V]`。`state_v_first=true` 时,L2 在进入 FwdH 前转置 initial state。 | ||
| 125 | +内部 `hCompute` 始终保持 head-major 供 Finalize 消费;公开 `hOut` 在 L2 导出边界转为 | ||
| 126 | +sequence-major,并按 `state_v_first` 决定末两维顺序。`final_state` 按序列排列,与 FLA 顶层 | ||
| 127 | +输出一致。 | ||
| 128 | + | ||
| 129 | +### 4.2 重计算策略 | ||
| 130 | + | ||
| 131 | +L2 不理解 autograd 重计算策略。`final_state/gk/w/u/qg/kg/v_new/h` 是相互独立的 | ||
| 132 | +`OPTIONAL_OUTPUT`;非空指针表示导出,空指针表示不公开该结果。arch35 快路径为隐藏输出传递 | ||
| 133 | +固定 ABI 占位,并由 tiling 在 kernel workspace 中承接实际中间结果;通用路径使用同一规则。 | ||
| 134 | +公开输出存在时直接作为内部目标使用。 | ||
| 135 | + | ||
| 136 | +PyTorch API包装层对齐fla-org `chunk_kda_fwd`提交 | ||
| 137 | +`0f0f0c97af39343855b43bbbaddcedfda5cb9d77`: | ||
| 138 | + | ||
| 139 | +- `attn_out` 始终返回。 | ||
| 140 | +- `final_state` 只在 `output_final_state=true` 时返回。 | ||
| 141 | +- `gk` 在 `use_gate_in_kernel=false` 或 `disable_recompute=true` 时返回。 | ||
| 142 | +- `Aqk` 始终返回。 | ||
| 143 | +- `Akk` 始终返回。 | ||
| 144 | +- `w` 在 `disable_recompute=true` 时返回。 | ||
| 145 | +- `u` 在 `disable_recompute=true` 时返回。 | ||
| 146 | +- `qg` 在 `disable_recompute=true` 时返回。 | ||
| 147 | +- `kg` 在 `disable_recompute=true` 时返回。 | ||
| 148 | +- `v_new` 在 `disable_recompute=true` 时返回。 | ||
| 149 | +- `h` 在 `disable_recompute=true` 或 `return_intermediate_states=true` 时返回。 | ||
| 150 | +- `initial_state` 由Python层原对象透传,不是aclnn输出。 | ||
| 151 | + | ||
| 152 | +内部 `hCompute` 与公开 `hOut` 是两个生命周期:`hCompute` 是 FwdH 到 Finalize 的必需 | ||
| 153 | +head-major 阶段结果,`hOut` 为空时由 kernel workspace 承接;`hOut` 非空时,L2 提供 head-major | ||
| 154 | +临时输出并在导出边界转为 sequence-major。该规则对齐非 CP 的低层 12 返回值接口; | ||
| 155 | +第 12 项 `initial_state` 由 Python 层原对象透传。 | ||
| 156 | + | ||
| 157 | +## 5 Tiling设计 | ||
| 158 | + | ||
| 159 | +本文中的“模板”指由 tiling 或 kernel 条件选择、具有独立数据切分或流水组织的计算路径。 | ||
| 160 | +C++ 中仅用于 dtype、常量传播或代码复用的普通 `template` helper 不单独列为场景模板。 | ||
| 161 | + | ||
| 162 | +### 5.1 接口与实现目录 | ||
| 163 | + | ||
| 164 | +`ChunkKdaFwd` 保留一套 L0 注册、launcher 和 `op_kernel/chunk_kda_fwd.cpp` device kernel launch | ||
| 165 | +入口。A2/A3 通用实现位于 `op_kernel/*.h`,A5 特化位于 `op_kernel/arch35/*.h`,A5 host 派生 | ||
| 166 | +选项位于 `op_host/arch35/chunk_kda_fwd_tiling_impl.h`。Prepare、Post-WU 和 Finalize 的 `.h` | ||
| 167 | +文件是同一 kernel 内部计算组件,不是独立 L0 算子接口。 | ||
| 168 | + | ||
| 169 | +### 5.2 编译期shape模板 | ||
| 170 | + | ||
| 171 | +| tiling key | 编译期常量 | A2/A3 实现 | A5 实现 | 覆盖场景 | | ||
| 172 | +| --- | --- | --- | --- | --- | | ||
| 173 | +| `key=1` 通用 shape 模板 | `COMPILE_BT/K/V=0/0/0` | 根目录通用实现 | 根目录通用实现 | 不满足 `chunk=64,K=128,V=128` 的 dense、tail、varlen、GQA 等场景 | | ||
| 174 | +| `key=2` chunk64/K128/V128 模板 | `COMPILE_BT/K/V=64/128/128` | 根目录通用实现,使用编译期常量 | `arch35` 特化实现 | `chunk=64,K=V=128` 的 dense、tail、varlen 和不同 head 数 | | ||
| 175 | + | ||
| 176 | +`SetTilingKey` 只检查 chunk、K、V,不检查 SoC、layout、是否 varlen 或是否存在尾块。因此 tiling | ||
| 177 | +key 表示 shape 模板族,不表示平台、接口或算子版本。平台差异由同一 key 编译时的架构分支选择。 | ||
| 178 | + | ||
| 179 | +### 5.3 A5 key2执行组合模板 | ||
| 180 | + | ||
| 181 | +`ConfigureChunkKdaFwdArch35` 从既有输入和输出实例化状态派生四个内部选项。选项不属于公开 | ||
| 182 | +属性,不改变 L0、aclnn L2 或 Python 接口。 | ||
| 183 | + | ||
| 184 | +| 执行组合 | 选择条件 | 内部阶段顺序 | | ||
| 185 | +| --- | --- | --- | | ||
| 186 | +| standalone Gate | `computeGateInPrepare=false` | Gate 完整执行并同步,再进入 Prepare | | ||
| 187 | +| Prepare 内联 Gate | BF16 q/k/v、raw g 为 FP32、存在 `A_log`、`use_gate_in_kernel=true`、`safe_gate=true` | Prepare AIV 在 gate-product 流水中计算 chunk-local gk | | ||
| 188 | +| A5 dense FwdH | BF16 且非 varlen、`T % 64 == 0` | 使用 `ChunkKdaFwdFwdH` arch35 dense 模板 | | ||
| 189 | +| Prepare/Post-WU 阶段内流水融合 | A5 key2、BF16、`safe_gate=true`、dense-aligned、`H_v % 2 == 0`,且未选择下一行模板 | Prepare AIC 按 head pair 生产后,直接调用 Post-WU 组件分批消费 | | ||
| 190 | +| Post-WU/FwdH 阶段内流水融合 | 上一行条件成立,同时 Gate 已在 Prepare 内计算,且不导出 `qg/v_new/h` | dense FwdH 直接完成 W/U 和状态传播所需计算 | | ||
| 191 | +| 独立内部 Post-WU 阶段 | 上述两种 Post-WU 融合均未选择 | Prepare 完成同步后调用 `RunChunkKdaPostWu` | | ||
| 192 | +| 通用 FwdH backend | FP16、varlen、存在非对齐尾块或不满足 dense FwdH 条件 | 选择 KDA 私有 `KdaFwdHTileShapes128/256` 模板 | | ||
| 193 | + | ||
| 194 | +因此“Prepare/Post-WU 融合”只描述满足表中条件的执行组合,不表示所有 key2 场景都取消了 | ||
| 195 | +内部 Post-WU 阶段。特别是 varlen 和非对齐尾块使用独立内部 Post-WU 阶段。 | ||
| 196 | + | ||
| 197 | +### 5.4 Gate与Prepare内部模板 | ||
| 198 | + | ||
| 199 | +| 模板 | 选择条件 | 主要实现 | | ||
| 200 | +| --- | --- | --- | | ||
| 201 | +| Gate 通用 chunk-cumsum | standalone Gate | 复用 `KdaGateCumsum::DispatchKdaGateCumsum`,支持 raw/已激活 gate 和 safe true/false | | ||
| 202 | +| Gate/Prepare arch35 regbase | A5 key2、BF16、raw FP32、`A_log`、safe gate | 16-row gate tile、两套 UB staging,MTE2 与 VEC 交叠;gk、qg、w seed 和 kg 因子成批生成 | | ||
| 203 | +| Prepare 通用 score/solve | key1,以及 A2/A3 key2 | 通用 Aqk/Akk MMAD、causal mask、三角 solve 和 seed 写回 | | ||
| 204 | +| Prepare arch35 key2 通用边界 | A5 key2 的 odd head、safe false、tail 或 varlen 等未命中成批融合的场景 | 保留同一数学定义,使用有界 score queue、AIC/AIV 握手和 padded tail | | ||
| 205 | +| Prepare arch35 safe-gate head-pair | A5 key2、safe gate、`H_v % 2 == 0` | 两个 head lane,共享两级 score queue;32-row score block;Akk solve 与后续 score 搬运交叠 | | ||
| 206 | +| Prepare arch35 full-chunk fused-score | 上一行且 `curT=64`,并命中 fused Post-WU | QK/Akk 两次 MMAD 使用手工 L1/L0 流水,Aqk/Akk mask 和 beta seed 在写回前完成 | | ||
| 207 | + | ||
| 208 | +### 5.5 Post-WU内部模板 | ||
| 209 | + | ||
| 210 | +| 模板 | 选择条件 | 主要实现 | | ||
| 211 | +| --- | --- | --- | | ||
| 212 | +| Post-WU 通用模板 | key1,以及 A2/A3 key2 | 通用 Cube/Vector 计算 `w=Akk@w_seed`、`u=Akk@u_seed`,并生成 kg | | ||
| 213 | +| Post-WU arch35 full-chunk head-pair | A5 key2、`curT=64`、融合组合 | 每批最多 4 个 chunk task、每 task 两个 head lane;Prepare 生产后直接消费 | | ||
| 214 | +| Post-WU arch35 full-chunk standalone | A5 key2、`curT=64`、未融合 | W/U 两套 MTE2 staging 与 MMAD/Fixpipe 流水;Kg 使用 16-row tile 和 32-row 双缓冲 | | ||
| 215 | +| Post-WU arch35 tail 16-63 | A5 key2、`16<=curT<64` | padded Cube 与按有效行写回,保留通用尾块同步协议 | | ||
| 216 | +| Post-WU arch35 BF16 sub-16 | A5 key2、BF16、`1<=curT<16` | `ComputeTailWuRegbaseArch35` 先完整暂存 W/U seed 和 Akk;单 AIV FP32 regbase 累加并写回,避免 W seed 与 W 输出原地复用时的跨 AIV 读写竞争 | | ||
| 217 | +| Post-WU arch35 sub-16 fallback | A5 key2、非 BF16、`1<=curT<16` | 使用通用逐行 Vector 路径;key1 和 A2/A3 由 Post-WU 通用模板覆盖 | | ||
| 218 | + | ||
| 219 | +Post-WU sub-16 模板的最坏 staging 为 | ||
| 220 | +`2*15*128*sizeof(BF16)+15*64*sizeof(BF16)=9,600 B`,不新增 workspace 或公开输出。 | ||
| 221 | + | ||
| 222 | +### 5.6 FwdH内部模板 | ||
| 223 | + | ||
| 224 | +| 模板 | 选择条件 | 主要实现 | | ||
| 225 | +| --- | --- | --- | | ||
| 226 | +| `KdaFwdHTileShapes128` | 通用 backend 且 `V<=128` | KDA 私有 arch22/arch35 FwdH;arch22 对完整/不小于 16 行的 chunk 使用 BF16 输入、FP32 累加的 Cube MMAD 计算 `kg^T@v_new`,仅 sub-16 尾块使用有界 Vector 兜底;跨 chunk 状态保持 FP32,支持 dense/varlen/tail | | ||
| 227 | +| `KdaFwdHTileShapes256` | 通用 backend 且 `128<V<=256` | V=256 分块,其他语义与 128 模板一致 | | ||
| 228 | +| `ChunkKdaFwdFwdH` arch35 dense | A5 key2、BF16、非 varlen、`T%64=0` | 16-token sub-chunk、4-slot L1 staging,AIC MMAD/Fixpipe 与 AIV gate/state 更新协作 | | ||
| 229 | +| arch35 dense fused Post-WU/FwdH | `fusePostWuIntoFwdH=true` | FwdH 从 Prepare seed 直接形成 W/U 与 v_new,不导出未请求的 qg/v_new/h | | ||
| 230 | + | ||
| 231 | +arch35 dense FwdH 的 state、W 和 v_new L1 slot 使用 ready/free credit 保护复用。AIV 在最后一个 | ||
| 232 | +task 完成后显式消费 AIC 返还的 terminal free credit,再退出 kernel,避免未消费 credit 进入后续执行。 | ||
| 233 | + | ||
| 234 | +### 5.7 Finalize内部模板 | ||
| 235 | + | ||
| 236 | +| 模板 | 选择条件 | 主要实现 | | ||
| 237 | +| --- | --- | --- | | ||
| 238 | +| Finalize 通用模板 | key1,以及 A2/A3 key2 | 通用 Cube 计算两项矩阵乘,AIV 完成 FP32 相加、类型转换与 sequence-major 写回 | | ||
| 239 | +| Finalize arch35 dense-aligned pipeline | A5 key2、非 varlen、`T%64=0` | `ProcessOutAicPipelinedArch35` 使用双 L1 slot,使下一输出 tile 的 MTE2 与当前 MTE1/MMAD/Fixpipe 交叠 | | ||
| 240 | +| Finalize arch35 full-chunk staged | A5 key2、`curT=64` 且未命中 dense-aligned pipeline | 分阶段计算 `scale*(qg@h)` 与 `Aqk@v_new`,保持 FP32 中间结果 | | ||
| 241 | +| Finalize arch35 tail 16-63 | A5 key2、`16<=curT<64` | padded Cube 计算两项结果,AIV 按有效行相加并写回 | | ||
| 242 | +| Finalize arch35 BF16 sub-16 | A5 key2、BF16、`1<=curT<16` | `ComputeTailOutputRegbaseRows` 一次暂存 h、v_new、qg 和 Aqk,单次 MTE2-to-V 交接后以 FP32 regbase 直接累加两项,绕开尾块标量 EventID 链 | | ||
| 243 | +| Finalize arch35 sub-16 fallback | A5 key2、非 BF16、`1<=curT<16` | 通用 FP32 Vector 逐行归约;key1 和 A2/A3 由 Finalize 通用模板覆盖 | | ||
| 244 | + | ||
| 245 | +Finalize sub-16 模板的最坏 staging 为 | ||
| 246 | +`(128*128+2*15*128+15*16)*sizeof(BF16)=40,928 B`,小于现有 `gateWritebackBuf_` | ||
| 247 | +在 key2 BF16 下的 `40,960 B`,因此阈值固定为 16,不依赖运行时试探。 | ||
| 248 | + | ||
| 249 | +所有模板保持相同公式、公开输出顺序、可选输出语义和 layout 契约。模板选择不得改变 | ||
| 250 | +`ChunkKdaFwd` L0、`aclnnChunkKdaFwd` 或 `cann_ops_transformer.ops.chunk_kda_fwd` 的接口。 | ||
| 251 | + | ||
| 252 | +## 6 流水设计 | ||
| 253 | + | ||
| 254 | +- Prepare 的右矩阵在 L1 驻留,避免 K/K^T 重复搬运和重复转置。 | ||
| 255 | +- AIC 使用 L1/L0 双缓冲组织 MTE2、MTE1、Cube、Fixpipe。 | ||
| 256 | +- AIV 使用输入 staging ping-pong,使下一 tile MTE2 与当前 tile VEC 重叠。 | ||
| 257 | +- A5 VEC 路径使用 regbase 双发射;数值主计算仍保持 FP32。 | ||
| 258 | +- inter-sub-chunk 合并使用独立 workspace 区域,避免阻塞主 tile 流水。 | ||
| 259 | + | ||
| 260 | +性能结论只使用 `msopprof`。目标回归 case 由本算子测试目录维护。 | ||
| 261 | +A5 的 H96/T16K、K=V=128、chunk=64、BF16 关键场景以 10 ms 为目标值;门禁读取 | ||
| 262 | +`ChunkKdaFwd` 主 kernel 和 BSND 输入的 `beta` 布局转换的全部有效样本,保守累加两个组件的 | ||
| 263 | +各自最大值;合计超过 11 ms 或任一组件未采集到有效样本都失败。 | ||
| 264 | +同一关键场景使用非零输入连续执行 50 次,要求 `attn_out/final_state/Aqk/Akk` 二进制一致。 | ||
| 265 | + | ||
| 266 | +## 7 验证矩阵 | ||
| 267 | + | ||
| 268 | +- 平台:A2/A3/A5。 | ||
| 269 | +- dtype:FP16/BF16。 | ||
| 270 | +- layout:BSND/BNSD/TND/NTD。 | ||
| 271 | +- gate:raw/已激活、safe true/false。 | ||
| 272 | +- Shape:K=128,V=128/256,chunk=64/128,dense/varlen/tail/GQA。 | ||
| 273 | +- 属性:final state、重计算策略、`state_v_first`。 | ||
| @@ -0,0 +1,632 @@ | |||
| 1 | +# aclnnChunkKdaFwd | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +<!-- npu="950" id1 --> | ||
| 6 | +- <term>Ascend 950PR/Ascend 950DT</term>:支持 | ||
| 7 | +<!-- end id1 --> | ||
| 8 | +<!-- npu="A3" id2 --> | ||
| 9 | +- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:支持 | ||
| 10 | +<!-- end id2 --> | ||
| 11 | +<!-- npu="910b" id3 --> | ||
| 12 | +- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:支持 | ||
| 13 | +<!-- end id3 --> | ||
| 14 | +<!-- npu="310b" id4 --> | ||
| 15 | +- <term>Atlas 200I/500 A2 推理产品</term>:不支持 | ||
| 16 | +<!-- end id4 --> | ||
| 17 | +<!-- npu="310p" id5 --> | ||
| 18 | +- <term>Atlas 推理系列产品</term>:不支持 | ||
| 19 | +<!-- end id5 --> | ||
| 20 | +<!-- npu="910" id6 --> | ||
| 21 | +- <term>Atlas 训练系列产品</term>:不支持 | ||
| 22 | +<!-- end id6 --> | ||
| 23 | + | ||
| 24 | +## 功能说明 | ||
| 25 | + | ||
| 26 | +- 接口功能:完成不涉及CP切分的KDA分块正向计算,输出注意力结果、最终状态和反向计算所需的中间量。 | ||
| 27 | + | ||
| 28 | +- 计算公式: | ||
| 29 | + | ||
| 30 | + 将每条序列按$C=chunkSize$划分为$M$个chunk。以第$c$个chunk为例,$i$、$j$表示chunk内token下标,$l_c$表示该chunk最后一个有效token下标。以下公式省略batch和head下标;GQA场景中,每个Value head使用对应的Query/Key head。 | ||
| 31 | + | ||
| 32 | + 令$x_{c,i,d}=g_{c,i,d}+dtBias_d$,未传入`dtBiasOptional`时令$dtBias_d=0$。激活后的gate为: | ||
| 33 | + | ||
| 34 | + $$ | ||
| 35 | + \gamma_{c,i,d}= | ||
| 36 | + \begin{cases} | ||
| 37 | + g_{c,i,d}, & useGateInKernel=false,\\ | ||
| 38 | + -\exp(A_{log})\operatorname{softplus}(x_{c,i,d}), | ||
| 39 | + & useGateInKernel=true,\ safeGate=false,\\ | ||
| 40 | + lowerBound\operatorname{sigmoid}(\exp(A_{log})x_{c,i,d}), | ||
| 41 | + & useGateInKernel=true,\ safeGate=true. | ||
| 42 | + \end{cases} | ||
| 43 | + $$ | ||
| 44 | + | ||
| 45 | + `gkOut`为chunk内以2为底的累计gate: | ||
| 46 | + | ||
| 47 | + $$ | ||
| 48 | + gk_{c,i,d}=\frac{1}{\ln 2}\sum_{t=0}^{i}\gamma_{c,t,d}. | ||
| 49 | + $$ | ||
| 50 | + | ||
| 51 | + `qgOut`和`kgOut`分别为gate缩放后的Query和Key: | ||
| 52 | + | ||
| 53 | + $$ | ||
| 54 | + qg_{c,i,d}=q_{c,i,d}2^{gk_{c,i,d}},\qquad | ||
| 55 | + kg_{c,i,d}=k_{c,i,d}2^{gk_{c,l_c,d}-gk_{c,i,d}}. | ||
| 56 | + $$ | ||
| 57 | + | ||
| 58 | + `aqkOut`为包含对角线的下三角Query-Key系数矩阵: | ||
| 59 | + | ||
| 60 | + $$ | ||
| 61 | + Aqk_{c,i,j}=\mathbb{1}_{j\le i}\cdot scale | ||
| 62 | + \sum_d q_{c,i,d}k_{c,j,d}2^{gk_{c,i,d}-gk_{c,j,d}}. | ||
| 63 | + $$ | ||
| 64 | + | ||
| 65 | + 定义严格下三角矩阵$L_c$,`akkOut`为$I+L_c$的逆矩阵: | ||
| 66 | + | ||
| 67 | + $$ | ||
| 68 | + L_{c,i,j}=\mathbb{1}_{j<i}\cdot\beta_{c,i} | ||
| 69 | + \sum_d k_{c,i,d}k_{c,j,d}2^{gk_{c,i,d}-gk_{c,j,d}},\qquad | ||
| 70 | + Akk_c=(I+L_c)^{-1}. | ||
| 71 | + $$ | ||
| 72 | + | ||
| 73 | + 定义$w^{seed}$和$u^{seed}$: | ||
| 74 | + | ||
| 75 | + $$ | ||
| 76 | + w^{seed}_{c,i,d}=\beta_{c,i}k_{c,i,d}2^{gk_{c,i,d}},\qquad | ||
| 77 | + u^{seed}_{c,i,e}=\beta_{c,i}v_{c,i,e}. | ||
| 78 | + $$ | ||
| 79 | + | ||
| 80 | + `wOut`和`uOut`为: | ||
| 81 | + | ||
| 82 | + $$ | ||
| 83 | + w_c=Akk_c\,w^{seed}_c,\qquad u_c=Akk_c\,u^{seed}_c. | ||
| 84 | + $$ | ||
| 85 | + | ||
| 86 | + 令$h_c$为第$c$个chunk计算前的状态。传入`initialStateOptional`时$h_0=initialStateOptional$,否则$h_0=0$。`vNewOut`、下一个chunk状态、`hOut`和`finalStateOut`为: | ||
| 87 | + | ||
| 88 | + $$ | ||
| 89 | + v^{new}_c=u_c-w_c\,h_c, | ||
| 90 | + $$ | ||
| 91 | + | ||
| 92 | + $$ | ||
| 93 | + h_{c+1}=2^{gk_{c,l_c}}\odot h_c+kg_c^T\,v^{new}_c, | ||
| 94 | + $$ | ||
| 95 | + | ||
| 96 | + $$ | ||
| 97 | + hOut[c]=h_c,\qquad finalStateOut=h_M. | ||
| 98 | + $$ | ||
| 99 | + | ||
| 100 | + 其中,$2^{gk_{c,l_c}}\odot h_c$表示沿$K$维缩放状态矩阵。`attnOut`为: | ||
| @@ -0,0 +1,38 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +add_op_to_compiled_list() | ||
| 11 | +if (BUILD_OPEN_PROJECT) | ||
| 12 | + target_sources(op_host_aclnnExc PRIVATE | ||
| 13 | + chunk_kda_fwd_def.cpp | ||
| 14 | + ) | ||
| 15 | +endif() | ||
| 16 | + | ||
| 17 | +add_modules_sources(OPTYPE chunk_kda_fwd ACLNNTYPE aclnn_exclude) | ||
| 18 | + | ||
| 19 | +set(CHUNK_KDA_CATLASS_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../op_kernel") | ||
| 20 | +if(NOT EXISTS "${CHUNK_KDA_CATLASS_INCLUDE_DIR}/tla/tensor.hpp") | ||
| 21 | + message(FATAL_ERROR | ||
| 22 | + "ChunkKdaFwd requires the vendored Catlass source under " | ||
| 23 | + "op_kernel/catlass and op_kernel/tla. Please make sure the directories are complete.") | ||
| 24 | +endif() | ||
| 25 | + | ||
| 26 | +add_ops_compile_options( | ||
| 27 | + OP_NAME ChunkKdaFwd | ||
| 28 | + OPTIONS --cce-auto-sync=off | ||
| 29 | + -Wno-deprecated-declarations | ||
| 30 | + -I${CHUNK_KDA_CATLASS_INCLUDE_DIR} | ||
| 31 | +) | ||
| 32 | +if("${ASCEND_COMPUTE_UNIT}" STREQUAL "ascend950") | ||
| 33 | + add_ops_compile_options( | ||
| 34 | + OP_NAME ChunkKdaFwd | ||
| 35 | + COMPUTE_UNIT Ascend950PR_9599 | ||
| 36 | + OPTIONS -DENABLE_CV_COMM_VIA_SSBUF=true | ||
| 37 | + ) | ||
| 38 | +endif() | ||
| @@ -0,0 +1,53 @@ | |||
| 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 | +namespace optiling::arch35 { | ||
| 14 | + | ||
| 15 | +struct ChunkKdaFwdArch35Options { | ||
| 16 | + bool computeGateInPrepare = false; | ||
| 17 | + bool fusePostWu = false; | ||
| 18 | + bool fusePostWuIntoFwdH = false; | ||
| 19 | + bool useDenseFwdH = false; | ||
| 20 | +}; | ||
| 21 | + | ||
| 22 | +inline ChunkKdaFwdArch35Options ConfigureChunkKdaFwdArch35( | ||
| 23 | + bool isAscend950, bool qIsBf16, bool rawGIsFp32, bool hasALog, | ||
| 24 | + bool useGateInKernel, bool safeGate, bool isVarLen, int64_t seqlen, | ||
| 25 | + int64_t vHeads, int64_t chunkSize, int64_t kDim, int64_t vDim, | ||
| 26 | + bool storeQG, bool storeVNew, bool storeH) | ||
| 27 | +{ | ||
| 28 | + ChunkKdaFwdArch35Options options; | ||
| 29 | + const bool shapeSupported = | ||
| 30 | + isAscend950 && chunkSize == 64 && kDim == 128 && vDim == 128; | ||
| 31 | + if (!shapeSupported) { | ||
| 32 | + return options; | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + // Tiling keys describe shape families independently of the SoC. These | ||
| 36 | + // options only enable arch35 sub-pipelines within the selected family. | ||
| 37 | + options.computeGateInPrepare = | ||
| 38 | + qIsBf16 && rawGIsFp32 && hasALog && | ||
| 39 | + useGateInKernel && safeGate; | ||
| 40 | + const bool denseAligned = !isVarLen && seqlen % chunkSize == 0; | ||
| 41 | + options.useDenseFwdH = denseAligned && qIsBf16; | ||
| 42 | + const bool canFusePreparePostWu = | ||
| 43 | + denseAligned && qIsBf16 && safeGate && vHeads % 2 == 0; | ||
| 44 | + options.fusePostWuIntoFwdH = | ||
| 45 | + options.useDenseFwdH && canFusePreparePostWu && | ||
| 46 | + options.computeGateInPrepare && | ||
| 47 | + !storeQG && !storeVNew && !storeH; | ||
| 48 | + options.fusePostWu = | ||
| 49 | + canFusePreparePostWu && !options.fusePostWuIntoFwdH; | ||
| 50 | + return options; | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +} // namespace optiling::arch35 | ||
| @@ -0,0 +1,99 @@ | |||
| 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 "register/op_def_registry.h" | ||
| 12 | + | ||
| 13 | +namespace ops { | ||
| 14 | +class ChunkKdaFwd : public OpDef { | ||
| 15 | +public: | ||
| 16 | + explicit ChunkKdaFwd(const char *name) | ||
| 17 | + : OpDef(name) | ||
| 18 | + { | ||
| 19 | + const std::initializer_list<ge::DataType> dataTypes = {ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT16, | ||
| 20 | + ge::DT_FLOAT16, ge::DT_BF16, ge::DT_BF16, | ||
| 21 | + ge::DT_BF16, ge::DT_BF16}; | ||
| 22 | + const std::initializer_list<ge::DataType> gateTypes = {ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_BF16, ge::DT_BF16, | ||
| 23 | + ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_BF16, ge::DT_BF16}; | ||
| 24 | + const std::initializer_list<ge::DataType> betaTypes = {ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT, ge::DT_BF16, | ||
| 25 | + ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT, ge::DT_BF16}; | ||
| 26 | + const std::initializer_list<ge::DataType> stateTypes = {ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, | ||
| 27 | + ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}; | ||
| 28 | + const std::initializer_list<ge::Format> formats = {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, | ||
| 29 | + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}; | ||
| 30 | + | ||
| 31 | + this->Input("q").ParamType(REQUIRED).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 32 | + this->Input("k").ParamType(REQUIRED).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 33 | + this->Input("v").ParamType(REQUIRED).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 34 | + this->Input("g").ParamType(REQUIRED).DataType(gateTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 35 | + this->Input("beta").ParamType(REQUIRED).DataType(betaTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 36 | + this->Input("a_log").ParamType(OPTIONAL).DataType(stateTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 37 | + this->Input("dt_bias").ParamType(OPTIONAL).DataType(stateTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 38 | + this->Input("initial_state") | ||
| 39 | + .ParamType(OPTIONAL) | ||
| 40 | + .DataType(stateTypes) | ||
| 41 | + .Format(formats) | ||
| 42 | + .UnknownShapeFormat(formats); | ||
| 43 | + this->Input("cu_seqlens") | ||
| 44 | + .ParamType(OPTIONAL) | ||
| 45 | + .ValueDepend(OPTIONAL) | ||
| 46 | + .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, | ||
| 47 | + ge::DT_INT64}) | ||
| 48 | + .Format(formats) | ||
| 49 | + .UnknownShapeFormat(formats); | ||
| 50 | + this->Input("chunk_indices") | ||
| 51 | + .ParamType(OPTIONAL) | ||
| 52 | + .ValueDepend(OPTIONAL) | ||
| 53 | + .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, | ||
| 54 | + ge::DT_INT64}) | ||
| 55 | + .Format(formats) | ||
| 56 | + .UnknownShapeFormat(formats); | ||
| 57 | + | ||
| 58 | + this->Output("attn_out").ParamType(REQUIRED).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 59 | + this->Output("final_state") | ||
| 60 | + .ParamType(OPTIONAL) | ||
| 61 | + .DataType(stateTypes) | ||
| 62 | + .Format(formats) | ||
| 63 | + .UnknownShapeFormat(formats); | ||
| 64 | + this->Output("gk").ParamType(OPTIONAL).DataType(stateTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 65 | + this->Output("Aqk").ParamType(REQUIRED).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 66 | + this->Output("Akk").ParamType(REQUIRED).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 67 | + this->Output("w").ParamType(OPTIONAL).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 68 | + this->Output("u").ParamType(OPTIONAL).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 69 | + this->Output("qg").ParamType(OPTIONAL).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 70 | + this->Output("kg").ParamType(OPTIONAL).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 71 | + this->Output("v_new").ParamType(OPTIONAL).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 72 | + this->Output("h").ParamType(OPTIONAL).DataType(dataTypes).Format(formats).UnknownShapeFormat(formats); | ||
| 73 | + | ||
| 74 | + this->Attr("layout").AttrType(OPTIONAL).String("BSND"); | ||
| 75 | + this->Attr("scale").AttrType(REQUIRED).Float(1.0); | ||
| 76 | + this->Attr("chunk_size").AttrType(REQUIRED).Int(64); | ||
| 77 | + this->Attr("safe_gate").AttrType(REQUIRED).Bool(false); | ||
| 78 | + this->Attr("lower_bound").AttrType(OPTIONAL).Float(-5.0); | ||
| 79 | + this->Attr("use_gate_in_kernel").AttrType(REQUIRED).Bool(false); | ||
| 80 | + this->Attr("state_v_first").AttrType(OPTIONAL).Bool(false); | ||
| 81 | + | ||
| 82 | + OpAICoreConfig config; | ||
| 83 | + config.DynamicCompileStaticFlag(true) | ||
| 84 | + .DynamicFormatFlag(true) | ||
| 85 | + .DynamicRankSupportFlag(true) | ||
| 86 | + .DynamicShapeSupportFlag(true) | ||
| 87 | + .NeedCheckSupportFlag(false) | ||
| 88 | + .PrecisionReduceFlag(true) | ||
| 89 | + .ExtendCfgInfo("prebuildPattern.value", "Opaque") | ||
| 90 | + .ExtendCfgInfo("coreType.value", "AiCore") | ||
| 91 | + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); | ||
| 92 | + this->AICore().AddConfig("ascend910b", config); | ||
| 93 | + this->AICore().AddConfig("ascend910_93", config); | ||
| 94 | + this->AICore().AddConfig("ascend950", config); | ||
| 95 | + } | ||
| 96 | +}; | ||
| 97 | + | ||
| 98 | +OP_ADD(ChunkKdaFwd); | ||
| 99 | +} // namespace ops | ||
| @@ -0,0 +1,390 @@ | |||
| 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 "chunk_kda_fwd_tiling.h" | ||
| 12 | + | ||
| 13 | +#include <algorithm> | ||
| 14 | +#include <cstdint> | ||
| 15 | +#include <cstring> | ||
| 16 | +#include <register/op_impl_registry.h> | ||
| 17 | +#include "arch35/chunk_kda_fwd_tiling_impl.h" | ||
| 18 | +#include "platform/soc_spec.h" | ||
| 19 | +#include "tiling/platform/platform_ascendc.h" | ||
| 20 | + | ||
| 21 | +namespace optiling { | ||
| 22 | +namespace { | ||
| 23 | +constexpr size_t INPUT_Q_IDX = 0; | ||
| 24 | +constexpr size_t INPUT_V_IDX = 2; | ||
| 25 | +constexpr size_t INPUT_G_IDX = 3; | ||
| 26 | +constexpr size_t INPUT_A_LOG_IDX = 5; | ||
| 27 | +constexpr size_t INPUT_DT_BIAS_IDX = 6; | ||
| 28 | +constexpr size_t INPUT_INITIAL_STATE_IDX = 7; | ||
| 29 | +constexpr size_t INPUT_CU_SEQLENS_IDX = 8; | ||
| 30 | +constexpr size_t INPUT_CHUNK_INDICES_IDX = 9; | ||
| 31 | + | ||
| 32 | +constexpr size_t OUTPUT_FINAL_STATE_IDX = 1; | ||
| 33 | +constexpr size_t OUTPUT_GK_IDX = 2; | ||
| 34 | +constexpr size_t OUTPUT_W_IDX = 5; | ||
| 35 | +constexpr size_t OUTPUT_U_IDX = 6; | ||
| 36 | +constexpr size_t OUTPUT_QG_IDX = 7; | ||
| 37 | +constexpr size_t OUTPUT_KG_IDX = 8; | ||
| 38 | +constexpr size_t OUTPUT_V_NEW_IDX = 9; | ||
| 39 | +constexpr size_t OUTPUT_H_IDX = 10; | ||
| 40 | + | ||
| 41 | +constexpr size_t ATTR_LAYOUT_IDX = 0; | ||
| 42 | +constexpr size_t ATTR_SCALE_IDX = 1; | ||
| 43 | +constexpr size_t ATTR_CHUNK_SIZE_IDX = 2; | ||
| 44 | +constexpr size_t ATTR_SAFE_GATE_IDX = 3; | ||
| 45 | +constexpr size_t ATTR_LOWER_BOUND_IDX = 4; | ||
| 46 | +constexpr size_t ATTR_USE_GATE_IDX = 5; | ||
| 47 | + | ||
| 48 | +constexpr uint64_t KDA_ALIGN = 512; | ||
| 49 | +constexpr uint64_t KDA_SOLVE_SCRATCH_SLOTS = 5; | ||
| 50 | +constexpr uint64_t KDA_SOLVE_PIPELINE_DEPTH = 4; | ||
| 51 | +constexpr uint64_t KDA_SCORE_QUEUE_SLOTS = 4; | ||
| 52 | +constexpr uint64_t KDA_SCORE_SCRATCH_PLANES = 3; | ||
| 53 | +constexpr uint64_t KDA_GDN_PIPELINE_DEPTH = 2; | ||
| 54 | +constexpr uint32_t KDA_BATCH_MODE = 1; | ||
| 55 | + | ||
| 56 | +uint64_t AlignWorkspace(uint64_t bytes) | ||
| 57 | +{ | ||
| 58 | + return (bytes + KDA_ALIGN - 1) / KDA_ALIGN * KDA_ALIGN; | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +uint64_t AllocateWorkspace(uint64_t &cursor, uint64_t bytes) | ||
| 62 | +{ | ||
| 63 | + const uint64_t offset = AlignWorkspace(cursor); | ||
| 64 | + cursor = offset + bytes; | ||
| 65 | + return offset; | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +bool HasOutput(gert::TilingContext *context, size_t index) | ||
| 69 | +{ | ||
| 70 | + const auto instanceInfo = context->GetIrOutputInstanceInfo(index); | ||
| 71 | + if (instanceInfo == nullptr || instanceInfo->GetInstanceNum() == 0) { | ||
| 72 | + return false; | ||
| 73 | + } | ||
| 74 | + const auto outputShape = context->GetOutputShape(instanceInfo->GetInstanceStart()); | ||
| 75 | + return outputShape != nullptr && | ||
| 76 | + outputShape->GetStorageShape().GetShapeSize() != 1; | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +struct ShapeInfo { | ||
| 80 | + int64_t rank = 0; | ||
| 81 | + int64_t batch = 0; | ||
| 82 | + int64_t seqlen = 0; | ||
| 83 | + int64_t qHeads = 0; | ||
| 84 | + int64_t vHeads = 0; | ||
| 85 | + int64_t kDim = 0; | ||
| 86 | + int64_t vDim = 0; | ||
| 87 | + bool sequenceMajor = false; | ||
| 88 | +}; | ||
| 89 | + | ||
| 90 | +bool ResolveShape(gert::TilingContext *context, const char *layout, ShapeInfo &info) | ||
| 91 | +{ | ||
| 92 | + const auto qShapePtr = context->GetInputShape(INPUT_Q_IDX); | ||
| 93 | + const auto vShapePtr = context->GetInputShape(INPUT_V_IDX); | ||
| 94 | + if (qShapePtr == nullptr || vShapePtr == nullptr || layout == nullptr) { | ||
| 95 | + return false; | ||
| 96 | + } | ||
| 97 | + const auto &qShape = qShapePtr->GetStorageShape(); | ||
| 98 | + const auto &vShape = vShapePtr->GetStorageShape(); | ||
| 99 | + info.rank = qShape.GetDimNum(); | ||
| 100 | + if (info.rank != vShape.GetDimNum() || (info.rank != 3 && info.rank != 4)) { | ||
| 101 | + return false; | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + info.sequenceMajor = std::strcmp(layout, "BSND") == 0 || std::strcmp(layout, "TND") == 0; | ||
| 105 | + if (info.rank == 4) { | ||
| 106 | + info.batch = qShape.GetDim(0); | ||
| 107 | + if (info.sequenceMajor) { | ||
| 108 | + info.seqlen = qShape.GetDim(1); | ||
| 109 | + info.qHeads = qShape.GetDim(2); | ||
| 110 | + info.vHeads = vShape.GetDim(2); | ||
| 111 | + } else { | ||
| 112 | + info.qHeads = qShape.GetDim(1); | ||
| 113 | + info.vHeads = vShape.GetDim(1); | ||
| 114 | + info.seqlen = qShape.GetDim(2); | ||
| 115 | + } | ||
| 116 | + info.kDim = qShape.GetDim(3); | ||
| 117 | + info.vDim = vShape.GetDim(3); | ||
| 118 | + } else { | ||
| 119 | + info.batch = 1; | ||
| 120 | + if (info.sequenceMajor) { | ||
| 121 | + info.seqlen = qShape.GetDim(0); | ||
| 122 | + info.qHeads = qShape.GetDim(1); | ||
| 123 | + info.vHeads = vShape.GetDim(1); | ||
| 124 | + } else { | ||
| 125 | + info.qHeads = qShape.GetDim(0); | ||
| 126 | + info.vHeads = vShape.GetDim(0); | ||
| 127 | + info.seqlen = qShape.GetDim(1); | ||
| 128 | + } | ||
| 129 | + info.kDim = qShape.GetDim(2); | ||
| 130 | + info.vDim = vShape.GetDim(2); | ||
| 131 | + } | ||
| 132 | + return info.batch > 0 && info.seqlen > 0 && info.qHeads > 0 && info.vHeads > 0 && | ||
| 133 | + info.kDim > 0 && info.vDim > 0 && info.vHeads % info.qHeads == 0; | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +bool ResolveSequenceInfo(gert::TilingContext *context, int64_t seqlen, int64_t chunkSize, | ||
| 137 | + int64_t batch, bool &isVarLen, int64_t &seqNum, | ||
| 138 | + int64_t &totalChunks) | ||
| 139 | +{ | ||
| 140 | + const auto cuTensor = context->GetOptionalInputTensor(INPUT_CU_SEQLENS_IDX); | ||
| 141 | + isVarLen = cuTensor != nullptr; | ||
| 142 | + seqNum = batch; | ||
| 143 | + totalChunks = (seqlen + chunkSize - 1) / chunkSize; | ||
| 144 | + if (!isVarLen) { | ||
| 145 | + return totalChunks > 0; | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + seqNum = cuTensor->GetStorageShape().GetDim(0) - 1; | ||
| 149 | + const int64_t *cu = cuTensor->GetData<int64_t>(); | ||
| 150 | + if (seqNum <= 0 || cu == nullptr || cu[0] != 0 || cu[seqNum] > seqlen) { | ||
| 151 | + return false; | ||
| 152 | + } | ||
| 153 | + totalChunks = 0; | ||
| 154 | + for (int64_t seq = 0; seq < seqNum; ++seq) { | ||
| 155 | + if (cu[seq] < 0 || cu[seq + 1] < cu[seq]) { | ||
| 156 | + return false; | ||
| 157 | + } | ||
| 158 | + totalChunks += (cu[seq + 1] - cu[seq] + chunkSize - 1) / chunkSize; | ||
| 159 | + } | ||
| 160 | + | ||
| 161 | + const auto chunkShape = context->GetOptionalInputShape(INPUT_CHUNK_INDICES_IDX); | ||
| 162 | + if (chunkShape != nullptr && | ||
| 163 | + chunkShape->GetStorageShape().GetShapeSize() != totalChunks * 2) { | ||
| 164 | + return false; | ||
| 165 | + } | ||
| 166 | + return totalChunks > 0; | ||
| 167 | +} | ||
| 168 | +} // namespace | ||
| 169 | + | ||
| 170 | +ge::graphStatus Tiling4ChunkKdaFwd(gert::TilingContext *context) | ||
| 171 | +{ | ||
| 172 | + const auto qDesc = context->GetInputDesc(INPUT_Q_IDX); | ||
| 173 | + const auto gDesc = context->GetInputDesc(INPUT_G_IDX); | ||
| 174 | + const auto attrs = context->GetAttrs(); | ||
| 175 | + if (qDesc == nullptr || gDesc == nullptr || attrs == nullptr) { | ||
| 176 | + return ge::GRAPH_FAILED; | ||
| 177 | + } | ||
| 178 | + | ||
| 179 | + const char *layout = attrs->GetStr(ATTR_LAYOUT_IDX); | ||
| 180 | + const float scale = static_cast<float>(*attrs->GetAttrPointer<double>(ATTR_SCALE_IDX)); | ||
| 181 | + const int64_t chunkSize = *attrs->GetAttrPointer<int64_t>(ATTR_CHUNK_SIZE_IDX); | ||
| 182 | + const bool safeGate = *attrs->GetAttrPointer<bool>(ATTR_SAFE_GATE_IDX); | ||
| 183 | + const float lowerBound = *attrs->GetAttrPointer<float>(ATTR_LOWER_BOUND_IDX); | ||
| 184 | + const bool useGateInKernel = *attrs->GetAttrPointer<bool>(ATTR_USE_GATE_IDX); | ||
| 185 | + if (chunkSize <= 0) { | ||
| 186 | + return ge::GRAPH_FAILED; | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + ShapeInfo shape; | ||
| 190 | + if (!ResolveShape(context, layout, shape)) { | ||
| 191 | + return ge::GRAPH_FAILED; | ||
| 192 | + } | ||
| 193 | + bool isVarLen = false; | ||
| 194 | + int64_t seqNum = 0; | ||
| 195 | + int64_t totalChunks = 0; | ||
| 196 | + if (!ResolveSequenceInfo(context, shape.seqlen, chunkSize, shape.batch, | ||
| 197 | + isVarLen, seqNum, totalChunks)) { | ||
| 198 | + return ge::GRAPH_FAILED; | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + const bool hasALog = context->GetOptionalInputDesc(INPUT_A_LOG_IDX) != nullptr; | ||
| 202 | + const bool hasDtBias = context->GetOptionalInputDesc(INPUT_DT_BIAS_IDX) != nullptr; | ||
| 203 | + const bool hasInitialState = context->GetOptionalInputDesc(INPUT_INITIAL_STATE_IDX) != nullptr; | ||
| 204 | + const bool storeFinalState = HasOutput(context, OUTPUT_FINAL_STATE_IDX); | ||
| 205 | + const bool storeGk = HasOutput(context, OUTPUT_GK_IDX); | ||
| 206 | + const bool storeW = HasOutput(context, OUTPUT_W_IDX); | ||
| 207 | + const bool storeU = HasOutput(context, OUTPUT_U_IDX); | ||
| 208 | + const bool storeQG = HasOutput(context, OUTPUT_QG_IDX); | ||
| 209 | + const bool storeKg = HasOutput(context, OUTPUT_KG_IDX); | ||
| 210 | + const bool storeVNew = HasOutput(context, OUTPUT_V_NEW_IDX); | ||
| 211 | + const bool storeH = HasOutput(context, OUTPUT_H_IDX); | ||
| 212 | + | ||
| 213 | + const auto platform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); | ||
| 214 | + // Detect the Ascend950 SoC by NPU arch (DAV_3510) instead of the SoC version | ||
| 215 | + // enum. The arch enum is stable across CANN releases, whereas the version | ||
| 216 | + // enum only gained ASCEND950 in newer toolkits (CANN 8.5.2 only has | ||
| 217 | + // ASCEND910_95), which would break host compilation on older CANN. | ||
| 218 | + const bool isAscend950 = platform.GetCurNpuArch() == NpuArch::DAV_3510; | ||
| 219 | + const uint32_t physicalCoreNum = | ||
| 220 | + std::max<uint32_t>(platform.GetCoreNumAic(), 1); | ||
| 221 | + const uint64_t fwdHTaskCount = static_cast<uint64_t>( | ||
| 222 | + isVarLen ? seqNum : shape.batch) * | ||
| 223 | + shape.vHeads; | ||
| 224 | + const uint32_t blockDim = isAscend950 ? static_cast<uint32_t>(std::min<uint64_t>( | ||
| 225 | + physicalCoreNum, std::max<uint64_t>(fwdHTaskCount, 1))) : | ||
| 226 | + physicalCoreNum; | ||
| 227 | + const bool useChunk64K128V128Template = | ||
| 228 | + chunkSize == 64 && shape.kDim == 128 && shape.vDim == 128; | ||
| 229 | + const auto arch35Options = arch35::ConfigureChunkKdaFwdArch35( | ||
| 230 | + isAscend950, qDesc->GetDataType() == ge::DT_BF16, | ||
| 231 | + gDesc->GetDataType() == ge::DT_FLOAT, hasALog, useGateInKernel, | ||
| 232 | + safeGate, isVarLen, shape.seqlen, shape.vHeads, chunkSize, | ||
| 233 | + shape.kDim, shape.vDim, storeQG, storeVNew, storeH); | ||
| 234 | + | ||
| 235 | + const uint64_t dataBytes = | ||
| 236 | + qDesc->GetDataType() == ge::DT_FLOAT ? sizeof(float) : sizeof(uint16_t); | ||
| 237 | + const uint64_t tokenHeads = static_cast<uint64_t>(shape.batch) * | ||
| 238 | + shape.vHeads * shape.seqlen; | ||
| 239 | + const uint64_t kTensorBytes = tokenHeads * shape.kDim * dataBytes; | ||
| 240 | + const uint64_t vTensorBytes = tokenHeads * shape.vDim * dataBytes; | ||
| 241 | + const uint64_t gkBytes = tokenHeads * shape.kDim * sizeof(float); | ||
| 242 | + const uint64_t stateElements = static_cast<uint64_t>(seqNum) * | ||
| 243 | + shape.vHeads * shape.kDim * shape.vDim; | ||
| 244 | + const uint64_t hChunkCount = isVarLen ? static_cast<uint64_t>(totalChunks) : static_cast<uint64_t>(shape.batch) * totalChunks; | ||
| 245 | + const uint64_t hBytes = hChunkCount * shape.vHeads * shape.kDim * | ||
| 246 | + shape.vDim * dataBytes; | ||
| 247 | + | ||
| 248 | + uint64_t cursor = 0; | ||
| 249 | + const uint64_t gkStorageOffset = storeGk ? 0 : AllocateWorkspace(cursor, gkBytes); | ||
| 250 | + const uint64_t finalStateStorageOffset = storeFinalState ? 0 : | ||
| 251 | + AllocateWorkspace(cursor, stateElements * sizeof(float)); | ||
| 252 | + const uint64_t wStorageOffset = storeW ? 0 : AllocateWorkspace(cursor, kTensorBytes); | ||
| 253 | + const uint64_t uStorageOffset = storeU ? 0 : AllocateWorkspace(cursor, vTensorBytes); | ||
| 254 | + const uint64_t qgStorageOffset = storeQG ? 0 : AllocateWorkspace(cursor, kTensorBytes); | ||
| 255 | + const uint64_t kgStorageOffset = storeKg ? 0 : AllocateWorkspace(cursor, kTensorBytes); | ||
| 256 | + const uint64_t vNewStorageBytes = | ||
| 257 | + arch35Options.useDenseFwdH && !storeVNew ? static_cast<uint64_t>(shape.batch) * shape.vHeads * chunkSize * | ||
| 258 | + shape.vDim * dataBytes : | ||
| 259 | + vTensorBytes; | ||
| 260 | + const uint64_t vNewStorageOffset = storeVNew ? 0 : | ||
| 261 | + AllocateWorkspace(cursor, vNewStorageBytes); | ||
| 262 | + const uint64_t hStorageBytes = | ||
| 263 | + arch35Options.useDenseFwdH && !storeH ? static_cast<uint64_t>(shape.batch) * shape.vHeads * shape.kDim * | ||
| 264 | + shape.vDim * dataBytes : | ||
| 265 | + hBytes; | ||
| 266 | + const uint64_t hStorageOffset = storeH ? 0 : AllocateWorkspace(cursor, hStorageBytes); | ||
| 267 | + const uint64_t qgScaledOffset = AllocateWorkspace(cursor, kTensorBytes); | ||
| 268 | + | ||
| 269 | + const uint64_t matrixBytes = tokenHeads * chunkSize * sizeof(float); | ||
| 270 | + const uint64_t prepareAqkFp32Offset = AllocateWorkspace(cursor, matrixBytes); | ||
| 271 | + const uint64_t prepareAkkFp32Offset = AllocateWorkspace(cursor, matrixBytes); | ||
| 272 | + const uint64_t prepareScratchOffset = AlignWorkspace(cursor); | ||
| 273 | + const uint64_t solveDepth = safeGate ? KDA_SOLVE_PIPELINE_DEPTH : 1; | ||
| 274 | + const uint64_t solveBytes = static_cast<uint64_t>(blockDim) * solveDepth * | ||
| 275 | + KDA_SOLVE_SCRATCH_SLOTS * chunkSize * chunkSize * sizeof(float); | ||
| 276 | + const uint64_t scoreBytes = static_cast<uint64_t>(blockDim) * | ||
| 277 | + KDA_SCORE_QUEUE_SLOTS * KDA_SCORE_SCRATCH_PLANES * chunkSize * | ||
| 278 | + shape.kDim * dataBytes; | ||
| 279 | + cursor = prepareScratchOffset + AlignWorkspace(solveBytes) + scoreBytes; | ||
| 280 | + | ||
| 281 | + const uint64_t postWuScratchOffset = AlignWorkspace(cursor); | ||
| 282 | + if (!arch35Options.fusePostWu && !arch35Options.fusePostWuIntoFwdH) { | ||
| 283 | + cursor = postWuScratchOffset + tokenHeads * shape.kDim * sizeof(float); | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + const uint64_t fwdHWorkspaceBaseOffset = AlignWorkspace(cursor); | ||
| 287 | + uint64_t fwdHCursor = 0; | ||
| 288 | + const uint64_t vWorkspaceOffset = AllocateWorkspace( | ||
| 289 | + fwdHCursor, static_cast<uint64_t>(blockDim) * chunkSize * shape.vDim * | ||
| 290 | + sizeof(float) * KDA_GDN_PIPELINE_DEPTH); | ||
| 291 | + const uint64_t vUpdateWorkspaceOffset = AllocateWorkspace( | ||
| 292 | + fwdHCursor, static_cast<uint64_t>(blockDim) * chunkSize * shape.vDim * | ||
| 293 | + sizeof(float) * KDA_GDN_PIPELINE_DEPTH); | ||
| 294 | + const uint64_t kDecayWorkspaceOffset = AllocateWorkspace( | ||
| 295 | + fwdHCursor, static_cast<uint64_t>(blockDim) * chunkSize * shape.kDim * | ||
| 296 | + sizeof(float) * KDA_GDN_PIPELINE_DEPTH); | ||
| 297 | + const uint64_t hWorkspaceOffset = AllocateWorkspace( | ||
| 298 | + fwdHCursor, static_cast<uint64_t>(blockDim) * shape.kDim * shape.vDim * | ||
| 299 | + sizeof(float) * KDA_GDN_PIPELINE_DEPTH); | ||
| 300 | + const uint64_t tokenBatch = isVarLen ? static_cast<uint64_t>(seqNum) : 1; | ||
| 301 | + const uint64_t numSeqWorkspaceOffset = AllocateWorkspace( | ||
| 302 | + fwdHCursor, (tokenBatch + 1) * sizeof(int64_t)); | ||
| 303 | + const uint64_t numChunksWorkspaceOffset = AllocateWorkspace( | ||
| 304 | + fwdHCursor, (tokenBatch + 1) * sizeof(int64_t)); | ||
| 305 | + cursor = fwdHWorkspaceBaseOffset + AlignWorkspace(fwdHCursor); | ||
| 306 | + | ||
| 307 | + const uint64_t outputScratchOffset = AllocateWorkspace( | ||
| 308 | + cursor, 2 * tokenHeads * shape.vDim * sizeof(float)); | ||
| 309 | + const uint64_t totalWorkspace = AlignWorkspace(cursor); | ||
| 310 | + | ||
| 311 | + context->SetBlockDim(blockDim); | ||
| 312 | + context->SetTilingKey(useChunk64K128V128Template ? 2 : 1); | ||
| 313 | + context->SetScheduleMode(KDA_BATCH_MODE); | ||
| 314 | + context->GetWorkspaceSizes(1)[0] = platform.GetLibApiWorkSpaceSize() + totalWorkspace; | ||
| 315 | + | ||
| 316 | + ChunkKdaFwdTilingData tiling; | ||
| 317 | + tiling.set_batch(shape.batch); | ||
| 318 | + tiling.set_seqNum(seqNum); | ||
| 319 | + tiling.set_qHeadNum(shape.qHeads); | ||
| 320 | + tiling.set_vHeadNum(shape.vHeads); | ||
| 321 | + tiling.set_seqlen(shape.seqlen); | ||
| 322 | + tiling.set_kHeadDim(shape.kDim); | ||
| 323 | + tiling.set_vHeadDim(shape.vDim); | ||
| 324 | + tiling.set_chunkSize(chunkSize); | ||
| 325 | + tiling.set_totalChunks(totalChunks); | ||
| 326 | + tiling.set_inputRank(shape.rank); | ||
| 327 | + tiling.set_scale(scale); | ||
| 328 | + tiling.set_lowerBound(lowerBound); | ||
| 329 | + tiling.set_hasInitialState(hasInitialState); | ||
| 330 | + tiling.set_isVarLen(isVarLen); | ||
| 331 | + tiling.set_safeGate(safeGate); | ||
| 332 | + tiling.set_inputSequenceMajor(shape.sequenceMajor); | ||
| 333 | + tiling.set_useGateInKernel(useGateInKernel); | ||
| 334 | + tiling.set_hasALog(hasALog); | ||
| 335 | + tiling.set_hasDtBias(hasDtBias); | ||
| 336 | + tiling.set_computeGateInPrepare(arch35Options.computeGateInPrepare); | ||
| 337 | + tiling.set_fusePostWu(arch35Options.fusePostWu); | ||
| 338 | + tiling.set_fusePostWuIntoFwdH(arch35Options.fusePostWuIntoFwdH); | ||
| 339 | + tiling.set_useDenseFwdH(arch35Options.useDenseFwdH); | ||
| 340 | + tiling.set_storeFinalState(storeFinalState); | ||
| 341 | + tiling.set_storeGk(storeGk); | ||
| 342 | + tiling.set_storeW(storeW); | ||
| 343 | + tiling.set_storeU(storeU); | ||
| 344 | + tiling.set_storeQG(storeQG); | ||
| 345 | + tiling.set_storeKg(storeKg); | ||
| 346 | + tiling.set_storeVNew(storeVNew); | ||
| 347 | + tiling.set_storeH(storeH); | ||
| 348 | + tiling.set_gateDataType(gDesc->GetDataType() == ge::DT_FLOAT ? 2 : | ||
| 349 | + (gDesc->GetDataType() == ge::DT_BF16 ? 1 : 0)); | ||
| 350 | + tiling.set_gateUsedCoreNum(static_cast<int64_t>(blockDim) * 2); | ||
| 351 | + tiling.set_prepareUsedCoreNum(blockDim); | ||
| 352 | + tiling.set_postWuUsedCoreNum(blockDim); | ||
| 353 | + tiling.set_outputUsedCoreNum(blockDim); | ||
| 354 | + tiling.set_gkStorageOffset(gkStorageOffset); | ||
| 355 | + tiling.set_finalStateStorageOffset(finalStateStorageOffset); | ||
| 356 | + tiling.set_wStorageOffset(wStorageOffset); | ||
| 357 | + tiling.set_uStorageOffset(uStorageOffset); | ||
| 358 | + tiling.set_qgStorageOffset(qgStorageOffset); | ||
| 359 | + tiling.set_kgStorageOffset(kgStorageOffset); | ||
| 360 | + tiling.set_vNewStorageOffset(vNewStorageOffset); | ||
| 361 | + tiling.set_hStorageOffset(hStorageOffset); | ||
| 362 | + tiling.set_qgScaledOffset(qgScaledOffset); | ||
| 363 | + tiling.set_prepareAqkFp32Offset(prepareAqkFp32Offset); | ||
| 364 | + tiling.set_prepareAkkFp32Offset(prepareAkkFp32Offset); | ||
| 365 | + tiling.set_prepareScratchOffset(prepareScratchOffset); | ||
| 366 | + tiling.set_postWuScratchOffset(postWuScratchOffset); | ||
| 367 | + tiling.set_outputScratchOffset(outputScratchOffset); | ||
| 368 | + tiling.set_fwdHWorkspaceBaseOffset(fwdHWorkspaceBaseOffset); | ||
| 369 | + tiling.set_vWorkspaceOffset(vWorkspaceOffset); | ||
| 370 | + tiling.set_vUpdateWorkspaceOffset(vUpdateWorkspaceOffset); | ||
| 371 | + tiling.set_kDecayWorkspaceOffset(kDecayWorkspaceOffset); | ||
| 372 | + tiling.set_hWorkspaceOffset(hWorkspaceOffset); | ||
| 373 | + tiling.set_numSeqWorkspaceOffset(numSeqWorkspaceOffset); | ||
| 374 | + tiling.set_numChunksWorkspaceOffset(numChunksWorkspaceOffset); | ||
| 375 | + tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), | ||
| 376 | + context->GetRawTilingData()->GetCapacity()); | ||
| 377 | + context->GetRawTilingData()->SetDataSize(tiling.GetDataSize()); | ||
| 378 | + return ge::GRAPH_SUCCESS; | ||
| 379 | +} | ||
| 380 | + | ||
| 381 | +ge::graphStatus TilingPrepare4ChunkKdaFwd(gert::TilingParseContext *context) | ||
| 382 | +{ | ||
| 383 | + (void)context; | ||
| 384 | + return ge::GRAPH_SUCCESS; | ||
| 385 | +} | ||
| 386 | + | ||
| 387 | +IMPL_OP_OPTILING(ChunkKdaFwd) | ||
| 388 | + .Tiling(Tiling4ChunkKdaFwd) | ||
| 389 | + .TilingParse<ChunkKdaFwdCompileInfo>(TilingPrepare4ChunkKdaFwd); | ||
| 390 | +} // namespace optiling | ||
| @@ -0,0 +1,84 @@ | |||
| 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 <cstdint> | ||
| 14 | +#include <register/tilingdata_base.h> | ||
| 15 | + | ||
| 16 | +namespace optiling { | ||
| 17 | + | ||
| 18 | +BEGIN_TILING_DATA_DEF(ChunkKdaFwdTilingData) | ||
| 19 | +TILING_DATA_FIELD_DEF(int64_t, batch); | ||
| 20 | +TILING_DATA_FIELD_DEF(int64_t, seqNum); | ||
| 21 | +TILING_DATA_FIELD_DEF(int64_t, qHeadNum); | ||
| 22 | +TILING_DATA_FIELD_DEF(int64_t, vHeadNum); | ||
| 23 | +TILING_DATA_FIELD_DEF(int64_t, seqlen); | ||
| 24 | +TILING_DATA_FIELD_DEF(int64_t, kHeadDim); | ||
| 25 | +TILING_DATA_FIELD_DEF(int64_t, vHeadDim); | ||
| 26 | +TILING_DATA_FIELD_DEF(int64_t, chunkSize); | ||
| 27 | +TILING_DATA_FIELD_DEF(int64_t, totalChunks); | ||
| 28 | +TILING_DATA_FIELD_DEF(int64_t, inputRank); | ||
| 29 | +TILING_DATA_FIELD_DEF(float, scale); | ||
| 30 | +TILING_DATA_FIELD_DEF(float, lowerBound); | ||
| 31 | +TILING_DATA_FIELD_DEF(bool, hasInitialState); | ||
| 32 | +TILING_DATA_FIELD_DEF(bool, isVarLen); | ||
| 33 | +TILING_DATA_FIELD_DEF(bool, safeGate); | ||
| 34 | +TILING_DATA_FIELD_DEF(bool, inputSequenceMajor); | ||
| 35 | +TILING_DATA_FIELD_DEF(bool, useGateInKernel); | ||
| 36 | +TILING_DATA_FIELD_DEF(bool, hasALog); | ||
| 37 | +TILING_DATA_FIELD_DEF(bool, hasDtBias); | ||
| 38 | +TILING_DATA_FIELD_DEF(bool, computeGateInPrepare); | ||
| 39 | +TILING_DATA_FIELD_DEF(bool, fusePostWu); | ||
| 40 | +TILING_DATA_FIELD_DEF(bool, fusePostWuIntoFwdH); | ||
| 41 | +TILING_DATA_FIELD_DEF(bool, useDenseFwdH); | ||
| 42 | +TILING_DATA_FIELD_DEF(bool, storeFinalState); | ||
| 43 | +TILING_DATA_FIELD_DEF(bool, storeGk); | ||
| 44 | +TILING_DATA_FIELD_DEF(bool, storeW); | ||
| 45 | +TILING_DATA_FIELD_DEF(bool, storeU); | ||
| 46 | +TILING_DATA_FIELD_DEF(bool, storeQG); | ||
| 47 | +TILING_DATA_FIELD_DEF(bool, storeKg); | ||
| 48 | +TILING_DATA_FIELD_DEF(bool, storeVNew); | ||
| 49 | +TILING_DATA_FIELD_DEF(bool, storeH); | ||
| 50 | + | ||
| 51 | +TILING_DATA_FIELD_DEF(int64_t, gateDataType); | ||
| 52 | +TILING_DATA_FIELD_DEF(int64_t, gateUsedCoreNum); | ||
| 53 | +TILING_DATA_FIELD_DEF(int64_t, prepareUsedCoreNum); | ||
| 54 | +TILING_DATA_FIELD_DEF(int64_t, postWuUsedCoreNum); | ||
| 55 | +TILING_DATA_FIELD_DEF(int64_t, outputUsedCoreNum); | ||
| 56 | + | ||
| 57 | +TILING_DATA_FIELD_DEF(int64_t, gkStorageOffset); | ||
| 58 | +TILING_DATA_FIELD_DEF(int64_t, finalStateStorageOffset); | ||
| 59 | +TILING_DATA_FIELD_DEF(int64_t, wStorageOffset); | ||
| 60 | +TILING_DATA_FIELD_DEF(int64_t, uStorageOffset); | ||
| 61 | +TILING_DATA_FIELD_DEF(int64_t, qgStorageOffset); | ||
| 62 | +TILING_DATA_FIELD_DEF(int64_t, kgStorageOffset); | ||
| 63 | +TILING_DATA_FIELD_DEF(int64_t, vNewStorageOffset); | ||
| 64 | +TILING_DATA_FIELD_DEF(int64_t, hStorageOffset); | ||
| 65 | +TILING_DATA_FIELD_DEF(int64_t, qgScaledOffset); | ||
| 66 | +TILING_DATA_FIELD_DEF(int64_t, prepareAqkFp32Offset); | ||
| 67 | +TILING_DATA_FIELD_DEF(int64_t, prepareAkkFp32Offset); | ||
| 68 | +TILING_DATA_FIELD_DEF(int64_t, prepareScratchOffset); | ||
| 69 | +TILING_DATA_FIELD_DEF(int64_t, postWuScratchOffset); | ||
| 70 | +TILING_DATA_FIELD_DEF(int64_t, outputScratchOffset); | ||
| 71 | + | ||
| 72 | +TILING_DATA_FIELD_DEF(int64_t, fwdHWorkspaceBaseOffset); | ||
| 73 | +TILING_DATA_FIELD_DEF(int64_t, vWorkspaceOffset); | ||
| 74 | +TILING_DATA_FIELD_DEF(int64_t, vUpdateWorkspaceOffset); | ||
| 75 | +TILING_DATA_FIELD_DEF(int64_t, kDecayWorkspaceOffset); | ||
| 76 | +TILING_DATA_FIELD_DEF(int64_t, hWorkspaceOffset); | ||
| 77 | +TILING_DATA_FIELD_DEF(int64_t, numSeqWorkspaceOffset); | ||
| 78 | +TILING_DATA_FIELD_DEF(int64_t, numChunksWorkspaceOffset); | ||
| 79 | +END_TILING_DATA_DEF; | ||
| 80 | + | ||
| 81 | +REGISTER_TILING_DATA_CLASS(ChunkKdaFwd, ChunkKdaFwdTilingData) | ||
| 82 | + | ||
| 83 | +struct ChunkKdaFwdCompileInfo {}; | ||
| 84 | +} // namespace optiling | ||
| @@ -0,0 +1,106 @@ | |||
| 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 OP_API_INC_ACLNN_CHUNK_KDA_FWD_H | ||
| 12 | +#define OP_API_INC_ACLNN_CHUNK_KDA_FWD_H | ||
| 13 | + | ||
| 14 | +#include "aclnn/aclnn_base.h" | ||
| 15 | +#include "aclnn_util.h" | ||
| 16 | + | ||
| 17 | +#ifdef __cplusplus | ||
| 18 | +extern "C" { | ||
| 19 | +#endif | ||
| 20 | + | ||
| 21 | +/** | ||
| 22 | + * @brief aclnnChunkKdaFwd的第一段接口,根据具体的计算流程,计算workspace大小 | ||
| 23 | + * @domain aclnn_ops_infer | ||
| 24 | + * | ||
| 25 | + * @param [in] q: Query输入。BSND为(B, S, H, K),BNSD为(B, H, S, K),TND为(T, H, K),NTD为(H, T, K),支持FLOAT16、BFLOAT16 | ||
| 26 | + * @param [in] k: Key输入。shape和数据类型必须与q相同,支持FLOAT16、BFLOAT16 | ||
| 27 | + * @param [in] v: Value输入。BSND为(B, S, HV, V),BNSD为(B, HV, S, V),TND为(T, HV, V),NTD为(HV, T, V),数据类型必须与q相同 | ||
| 28 | + * @param [in] g: raw gate或已激活的自然对数gate。BSND为(B, S, HV, K),BNSD为(B, HV, S, K),TND为(T, HV, K),NTD为(HV, T, K),支持FLOAT、BFLOAT16 | ||
| 29 | + * @param [in] beta: Delta系数。BSND为(B, S, HV),BNSD为(B, HV, S),TND为(T, HV),NTD为(HV, T),支持FLOAT、BFLOAT16 | ||
| 30 | + * @param [in] aLogOptional: gate衰减参数,shape为(HV),useGateInKernel=true时必须传入,支持FLOAT,可传nullptr | ||
| 31 | + * @param [in] dtBiasOptional: gate偏置,shape为(HV×K),支持FLOAT,可传nullptr | ||
| 32 | + * @param [in] initialStateOptional: 初始状态。stateVFirst=false时shape为(N, HV, K, V),否则为(N, HV, V, K),支持FLOAT,可传nullptr | ||
| 33 | + * @param [in] cuSeqlensOptional: 变长序列累计长度,shape为(N+1),首元素为0,末元素为T或S,元素单调不减,支持INT64,可传nullptr | ||
| 34 | + * @param [in] chunkIndicesOptional: chunk索引,shape为(2×NC),按(seq_id, chunk_id)保存,必须采用sequence-major canonical顺序, | ||
| 35 | + * 传入时必须同时传入cuSeqlensOptional,支持INT64,可传nullptr | ||
| 36 | + * @param [in] layout: 输入布局,支持"BSND"、"BNSD"、"TND"、"NTD",默认值为"BSND" | ||
| 37 | + * @param [in] scale: Query缩放系数,通常取K^(-0.5) | ||
| 38 | + * @param [in] chunkSize: chunk大小,支持64、128,默认值为64 | ||
| 39 | + * @param [in] safeGate: 是否使用有界gate,默认值为false | ||
| 40 | + * @param [in] lowerBound: 有界gate下界,safeGate=true时取值范围为[-5, 0),默认值为-5.0 | ||
| 41 | + * @param [in] useGateInKernel: 是否在kernel内由raw gate计算激活,默认值为false | ||
| 42 | + * @param [in] stateVFirst: 是否将状态张量末两维排列为(V, K),默认值为false | ||
| 43 | + * @param [in] attnOut: Attention输出tensor。rank-4输入固定为(B, S, HV, V),rank-3输入固定为(T, HV, V),支持FLOAT16、BFLOAT16 | ||
| 44 | + * @param [in] finalStateOut: 最终状态tensor。stateVFirst=false时shape为(N, HV, K, V),否则为(N, HV, V, K),支持FLOAT,不导出时传nullptr | ||
| 45 | + * @param [in] gkOut: chunk-local log2累计gate。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K),支持FLOAT,不导出时传nullptr | ||
| 46 | + * @param [in] aqkOut: chunk内Query-Key系数矩阵。rank-4输入为(B, HV, S, C),rank-3输入为(HV, T, C),支持FLOAT16、BFLOAT16 | ||
| 47 | + * @param [in] akkOut: chunk内下三角求逆结果。rank-4输入为(B, HV, S, C),rank-3输入为(HV, T, C),支持FLOAT16、BFLOAT16 | ||
| 48 | + * @param [in] wOut: 供反向使用的W中间量。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K),支持FLOAT16、BFLOAT16,不导出时传nullptr | ||
| 49 | + * @param [in] uOut: 供反向使用的U中间量。rank-4输入为(B, HV, S, V),rank-3输入为(HV, T, V),支持FLOAT16、BFLOAT16,不导出时传nullptr | ||
| 50 | + * @param [in] qgOut: 供反向使用的gate缩放Query。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K),支持FLOAT16、BFLOAT16,不导出时传nullptr | ||
| 51 | + * @param [in] kgOut: 供反向使用的gate缩放Key。rank-4输入为(B, HV, S, K),rank-3输入为(HV, T, K),支持FLOAT16、BFLOAT16,不导出时传nullptr | ||
| 52 | + * @param [in] vNewOut: 供反向使用的Value中间量。rank-4输入为(B, HV, S, V),rank-3输入为(HV, T, V),支持FLOAT16、BFLOAT16,不导出时传nullptr | ||
| 53 | + * @param [in] hOut: 公开chunk状态。rank-4输入为(B, NC, HV, K, V),rank-3输入为(NC, HV, K, V),stateVFirst=true时交换末两维, | ||
| 54 | + * 支持FLOAT16、BFLOAT16,不导出时传nullptr | ||
| 55 | + * @param [out] workspaceSize: 返回计算所需workspace大小 | ||
| 56 | + * @param [out] executor: 返回op执行器 | ||
| 57 | + * @return aclnnStatus: 返回状态码 | ||
| 58 | + */ | ||
| 59 | +aclnnStatus aclnnChunkKdaFwdGetWorkspaceSize( | ||
| 60 | + const aclTensor *q, | ||
| 61 | + const aclTensor *k, | ||
| 62 | + const aclTensor *v, | ||
| 63 | + const aclTensor *g, | ||
| 64 | + const aclTensor *beta, | ||
| 65 | + const aclTensor *aLogOptional, | ||
| 66 | + const aclTensor *dtBiasOptional, | ||
| 67 | + const aclTensor *initialStateOptional, | ||
| 68 | + const aclIntArray *cuSeqlensOptional, | ||
| 69 | + const aclIntArray *chunkIndicesOptional, | ||
| 70 | + const char *layout, | ||
| 71 | + double scale, | ||
| 72 | + int64_t chunkSize, | ||
| 73 | + bool safeGate, | ||
| 74 | + double lowerBound, | ||
| 75 | + bool useGateInKernel, | ||
| 76 | + bool stateVFirst, | ||
| 77 | + const aclTensor *attnOut, | ||
| 78 | + const aclTensor *finalStateOut, | ||
| 79 | + const aclTensor *gkOut, | ||
| 80 | + const aclTensor *aqkOut, | ||
| 81 | + const aclTensor *akkOut, | ||
| 82 | + const aclTensor *wOut, | ||
| 83 | + const aclTensor *uOut, | ||
| 84 | + const aclTensor *qgOut, | ||
| 85 | + const aclTensor *kgOut, | ||
| 86 | + const aclTensor *vNewOut, | ||
| 87 | + const aclTensor *hOut, | ||
| 88 | + uint64_t *workspaceSize, | ||
| 89 | + aclOpExecutor **executor); | ||
| 90 | + | ||
| 91 | +/** | ||
| 92 | + * @brief aclnnChunkKdaFwd的第二段接口,用于执行计算 | ||
| 93 | + * | ||
| 94 | + * @param [in] workspace: 工作空间地址 | ||
| 95 | + * @param [in] workspaceSize: 工作空间大小,由第一段接口aclnnChunkKdaFwdGetWorkspaceSize获取 | ||
| 96 | + * @param [in] executor: op执行器,包含了算子计算流程 | ||
| 97 | + * @param [in] stream: acl stream流 | ||
| 98 | + * @return aclnnStatus: 返回状态码 | ||
| 99 | + */ | ||
| 100 | +aclnnStatus aclnnChunkKdaFwd(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, aclrtStream stream); | ||
| 101 | + | ||
| 102 | +#ifdef __cplusplus | ||
| 103 | +} | ||
| 104 | +#endif | ||
| 105 | + | ||
| 106 | +#endif | ||
| @@ -0,0 +1,96 @@ | |||
| 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 "chunk_kda_fwd.h" | ||
| 12 | + | ||
| 13 | +#include "opdev/make_op_executor.h" | ||
| 14 | +#include "opdev/op_dfx.h" | ||
| 15 | +#include "opdev/op_log.h" | ||
| 16 | + | ||
| 17 | +using namespace op; | ||
| 18 | + | ||
| 19 | +namespace l0op { | ||
| 20 | +OP_TYPE_REGISTER(ChunkKdaFwd); | ||
| 21 | + | ||
| 22 | +KdaCoreOutputs KdaChunkForward( | ||
| 23 | + const aclTensor *q, | ||
| 24 | + const aclTensor *k, | ||
| 25 | + const aclTensor *v, | ||
| 26 | + const aclTensor *g, | ||
| 27 | + const aclTensor *beta, | ||
| 28 | + const aclTensor *aLogOptional, | ||
| 29 | + const aclTensor *dtBiasOptional, | ||
| 30 | + const aclTensor *initialStateOptional, | ||
| 31 | + const aclIntArray *cuSeqlensOptional, | ||
| 32 | + const aclIntArray *chunkIndicesOptional, | ||
| 33 | + double scale, | ||
| 34 | + int64_t chunkSize, | ||
| 35 | + bool safeGate, | ||
| 36 | + bool inputSequenceMajor, | ||
| 37 | + bool useGateInKernel, | ||
| 38 | + double lowerBound, | ||
| 39 | + const aclTensor *attnOut, | ||
| 40 | + const aclTensor *finalStateOut, | ||
| 41 | + const aclTensor *gkOut, | ||
| 42 | + const aclTensor *aqkOut, | ||
| 43 | + const aclTensor *akkOut, | ||
| 44 | + const aclTensor *wOut, | ||
| 45 | + const aclTensor *uOut, | ||
| 46 | + const aclTensor *qgOut, | ||
| 47 | + const aclTensor *kgOut, | ||
| 48 | + const aclTensor *vNewOut, | ||
| 49 | + const aclTensor *hOut, | ||
| 50 | + aclOpExecutor *executor) | ||
| 51 | +{ | ||
| 52 | + L0_DFX(KdaChunkForward, q, k, v, g, beta, aLogOptional, dtBiasOptional, | ||
| 53 | + initialStateOptional, cuSeqlensOptional, chunkIndicesOptional, | ||
| 54 | + scale, chunkSize, safeGate, inputSequenceMajor, useGateInKernel, | ||
| 55 | + lowerBound, attnOut, finalStateOut, gkOut, aqkOut, akkOut, | ||
| 56 | + wOut, uOut, qgOut, kgOut, vNewOut, hOut); | ||
| 57 | + | ||
| 58 | + const aclTensor *actualCuSeqlens = nullptr; | ||
| 59 | + if (cuSeqlensOptional != nullptr) { | ||
| 60 | + actualCuSeqlens = executor->ConvertToTensor(cuSeqlensOptional, DataType::DT_INT64); | ||
| 61 | + const_cast<aclTensor *>(actualCuSeqlens)->SetStorageFormat(Format::FORMAT_ND); | ||
| 62 | + const_cast<aclTensor *>(actualCuSeqlens)->SetViewFormat(Format::FORMAT_ND); | ||
| 63 | + const_cast<aclTensor *>(actualCuSeqlens)->SetOriginalFormat(Format::FORMAT_ND); | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + const aclTensor *actualChunkIndices = nullptr; | ||
| 67 | + if (chunkIndicesOptional != nullptr) { | ||
| 68 | + actualChunkIndices = executor->ConvertToTensor(chunkIndicesOptional, DataType::DT_INT64); | ||
| 69 | + if (actualChunkIndices == nullptr) { | ||
| 70 | + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "failed to convert chunk metadata to tensor."); | ||
| 71 | + return {}; | ||
| 72 | + } | ||
| 73 | + const_cast<aclTensor *>(actualChunkIndices)->SetStorageFormat(Format::FORMAT_ND); | ||
| 74 | + const_cast<aclTensor *>(actualChunkIndices)->SetViewFormat(Format::FORMAT_ND); | ||
| 75 | + const_cast<aclTensor *>(actualChunkIndices)->SetOriginalFormat(Format::FORMAT_ND); | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + auto ret = ADD_TO_LAUNCHER_LIST_AICORE( | ||
| 79 | + ChunkKdaFwd, | ||
| 80 | + OP_INPUT(q, k, v, g, beta, aLogOptional, dtBiasOptional, | ||
| 81 | + initialStateOptional, actualCuSeqlens, actualChunkIndices), | ||
| 82 | + OP_OUTPUT(attnOut, finalStateOut, gkOut, aqkOut, akkOut, wOut, uOut, | ||
| 83 | + qgOut, kgOut, vNewOut, hOut), | ||
| 84 | + OP_ATTR(inputSequenceMajor ? "BSND" : "BNSD", scale, chunkSize, | ||
| 85 | + safeGate, static_cast<float>(lowerBound), useGateInKernel, | ||
| 86 | + false)); | ||
| 87 | + if (ret != ACLNN_SUCCESS) { | ||
| 88 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, | ||
| 89 | + "ADD_TO_LAUNCHER_LIST_AICORE ChunkKdaFwd failed."); | ||
| 90 | + return {}; | ||
| 91 | + } | ||
| 92 | + return {attnOut, finalStateOut, gkOut, aqkOut, akkOut, wOut, uOut, | ||
| 93 | + qgOut, kgOut, vNewOut, hOut}; | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +} // namespace l0op | ||
| @@ -0,0 +1,32 @@ | |||
| 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 OP_API_INC_LEVEL0_OP_CHUNK_KDA_FWD_OP_H | ||
| 12 | +#define OP_API_INC_LEVEL0_OP_CHUNK_KDA_FWD_OP_H | ||
| 13 | + | ||
| 14 | +#include <array> | ||
| 15 | +#include "opdev/op_executor.h" | ||
| 16 | + | ||
| 17 | +namespace l0op { | ||
| 18 | +using KdaCoreOutputs = std::array<const aclTensor *, 11>; | ||
| 19 | + | ||
| 20 | +KdaCoreOutputs KdaChunkForward( | ||
| 21 | + const aclTensor *q, const aclTensor *k, const aclTensor *v, const aclTensor *g, const aclTensor *beta, | ||
| 22 | + const aclTensor *aLogOptional, const aclTensor *dtBiasOptional, | ||
| 23 | + const aclTensor *initialStateOptional, const aclIntArray *cuSeqlensOptional, | ||
| 24 | + const aclIntArray *chunkIndicesOptional, double scale, int64_t chunkSize, | ||
| 25 | + bool safeGate, bool inputSequenceMajor, bool useGateInKernel, double lowerBound, | ||
| 26 | + const aclTensor *attnOut, | ||
| 27 | + const aclTensor *finalStateOut, const aclTensor *gkOut, const aclTensor *aqkOut, | ||
| 28 | + const aclTensor *akkOut, const aclTensor *wOut, const aclTensor *uOut, const aclTensor *qgOut, | ||
| 29 | + const aclTensor *kgOut, const aclTensor *vNewOut, const aclTensor *hOut, aclOpExecutor *executor); | ||
| 30 | +} // namespace l0op | ||
| 31 | + | ||
| 32 | +#endif | ||
Aattention/chunk_kda_fwd/op_kernel/arch22/fwd_h/epilogue/block/block_epilogue_kda_fwdh_update.hpp+526-0
| @@ -0,0 +1,526 @@ | |||
| 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 CATLASS_EPILOGUE_BLOCK_BLOCK_EPILOGUE_KDA_FWDH_UPDATE_HPP | ||
| 12 | +#define CATLASS_EPILOGUE_BLOCK_BLOCK_EPILOGUE_KDA_FWDH_UPDATE_HPP | ||
| 13 | +#include "catlass/catlass.hpp" | ||
| 14 | +#include "catlass/arch/resource.hpp" | ||
| 15 | +#include "../kda_fwd_h_epilogue_policies.hpp" | ||
| 16 | +#include "catlass/gemm_coord.hpp" | ||
| 17 | +#include "catlass/matrix_coord.hpp" | ||
| 18 | +#include "catlass/epilogue/tile/tile_copy.hpp" | ||
| 19 | + | ||
| 20 | +namespace Catlass::Epilogue::Block { | ||
| 21 | + | ||
| 22 | +template <class HOutputType_, class GInputType_, class HInputType_, class HUpdateInputType_, class FinalStateType_, | ||
| 23 | + class KGatedTag> | ||
| 24 | +class BlockEpilogue<EpilogueAtlasKdaFwdHUpdate, HOutputType_, GInputType_, HInputType_, HUpdateInputType_, | ||
| 25 | + FinalStateType_, KGatedTag> { | ||
| 26 | + static constexpr bool kGated = KGatedTag::value; | ||
| 27 | + static constexpr bool scalarGated = KGatedTag::scalarGated; | ||
| 28 | + static constexpr bool useExp2 = KGatedTag::useExp2; | ||
| 29 | + static constexpr float LN2 = 0.6931471805599453f; | ||
| 30 | + | ||
| 31 | +public: | ||
| 32 | + using DispatchPolicy = EpilogueAtlasKdaFwdHUpdate; | ||
| 33 | + using ArchTag = typename DispatchPolicy::ArchTag; | ||
| 34 | + | ||
| 35 | + using HElementOutput = typename HOutputType_::Element; | ||
| 36 | + using GElementInput = typename GInputType_::Element; | ||
| 37 | + using HElementInput = typename HInputType_::Element; | ||
| 38 | + using HUpdateElementInput = typename HUpdateInputType_::Element; | ||
| 39 | + using FinalStateElement = typename FinalStateType_::Element; | ||
| 40 | + | ||
| 41 | + CATLASS_DEVICE | ||
| 42 | + BlockEpilogue(Arch::Resource<ArchTag> &resource) | ||
| 43 | + { | ||
| 44 | + constexpr uint32_t CALC_BUF_OFFSET = 0; | ||
| 45 | + constexpr uint32_t PING_BUF_0_OFFSET = 32 * 1024; | ||
| 46 | + constexpr uint32_t PING_BUF_1_OFFSET = 48 * 1024; | ||
| 47 | + constexpr uint32_t PING_BUF_2_OFFSET = 64 * 1024; | ||
| 48 | + constexpr uint32_t PING_BUF_3_OFFSET = 80 * 1024; | ||
| 49 | + constexpr uint32_t PONG_BUF_0_OFFSET = 96 * 1024; | ||
| 50 | + constexpr uint32_t PONG_BUF_1_OFFSET = 112 * 1024; | ||
| 51 | + constexpr uint32_t PONG_BUF_2_OFFSET = 128 * 1024; | ||
| 52 | + constexpr uint32_t PONG_BUF_3_OFFSET = 144 * 1024; | ||
| 53 | + constexpr uint32_t PING_G_BUF_OFFSET = 160 * 1024; | ||
| 54 | + constexpr uint32_t PONG_G_BUF_OFFSET = 161 * 1024; | ||
| 55 | + constexpr uint32_t PING_G_SUB_BUF_OFFSET = 162 * 1024; | ||
| 56 | + constexpr uint32_t PONG_G_SUB_BUF_OFFSET = 163 * 1024; | ||
| 57 | + constexpr uint32_t PING_G_INPUT_BUF_OFFSET = 164 * 1024; | ||
| 58 | + constexpr uint32_t PONG_G_INPUT_BUF_OFFSET = 165 * 1024; | ||
| 59 | + constexpr uint32_t SHARE_BUF_OFFSET = 166 * 1024; | ||
| 60 | + | ||
| 61 | + calcUbTensor = resource.ubBuf.template GetBufferByByte<float>(CALC_BUF_OFFSET); | ||
| 62 | + | ||
| 63 | + hUpdateUbTensor_ping = resource.ubBuf.template GetBufferByByte<float>(PING_BUF_0_OFFSET); | ||
| 64 | + gkBroadcastUbTensor_ping = resource.ubBuf.template GetBufferByByte<float>(PING_BUF_1_OFFSET); | ||
| 65 | + hUbTensor_ping = resource.ubBuf.template GetBufferByByte<HElementOutput>(PING_BUF_3_OFFSET); | ||
| 66 | + finalOutputUbTensor_ping = resource.ubBuf.template GetBufferByByte<FinalStateElement>(PING_BUF_3_OFFSET); | ||
| 67 | + glastUbTensor_ping = resource.ubBuf.template GetBufferByByte<float>(PING_G_INPUT_BUF_OFFSET); | ||
| 68 | + | ||
| 69 | + hUpdateUbTensor_pong = resource.ubBuf.template GetBufferByByte<float>(PONG_BUF_0_OFFSET); | ||
| 70 | + gkBroadcastUbTensor_pong = resource.ubBuf.template GetBufferByByte<float>(PONG_BUF_1_OFFSET); | ||
| 71 | + hUbTensor_pong = resource.ubBuf.template GetBufferByByte<HElementOutput>(PONG_BUF_3_OFFSET); | ||
| 72 | + finalOutputUbTensor_pong = resource.ubBuf.template GetBufferByByte<FinalStateElement>(PONG_BUF_3_OFFSET); | ||
| 73 | + glastUbTensor_pong = resource.ubBuf.template GetBufferByByte<float>(PONG_G_INPUT_BUF_OFFSET); | ||
| 74 | + | ||
| 75 | + if constexpr (kGated) { | ||
| 76 | + gkLastUbTensor_ping = resource.ubBuf.template GetBufferByByte<float>(PING_G_SUB_BUF_OFFSET); | ||
| 77 | + gkLastUbTensor_pong = resource.ubBuf.template GetBufferByByte<float>(PONG_G_SUB_BUF_OFFSET); | ||
| 78 | + gkInputUbTensor_ping = resource.ubBuf.template GetBufferByByte<GElementInput>(PING_G_INPUT_BUF_OFFSET); | ||
| 79 | + gkInputUbTensor_pong = resource.ubBuf.template GetBufferByByte<GElementInput>(PONG_G_INPUT_BUF_OFFSET); | ||
| 80 | + shareBufferGk_ = resource.ubBuf.template GetBufferByByte<uint8_t>(SHARE_BUF_OFFSET); | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + CATLASS_DEVICE | ||
| 85 | + ~BlockEpilogue() {} | ||
| 86 | + | ||
| 87 | + template <typename Element> | ||
| 88 | + CATLASS_DEVICE void CopyGmToUb(AscendC::LocalTensor<Element> dst, AscendC::GlobalTensor<Element> src, uint32_t rows, | ||
| 89 | + uint32_t cols, uint32_t srcStride) | ||
| 90 | + { | ||
| 91 | + if (cols == srcStride) { | ||
| 92 | + AscendC::DataCopy(dst, src, rows * cols); | ||
| 93 | + return; | ||
| 94 | + } | ||
| 95 | + AscendC::DataCopyExtParams copyParams{static_cast<uint16_t>(rows), | ||
| 96 | + static_cast<uint32_t>(cols * sizeof(Element)), | ||
| 97 | + static_cast<uint32_t>((srcStride - cols) * sizeof(Element)), 0, 0}; | ||
| 98 | + AscendC::DataCopyPadExtParams<Element> padParams{false, 0, 0, 0}; | ||
| 99 | + AscendC::DataCopyPad(dst, src, copyParams, padParams); | ||
| 100 | + } | ||
Aattention/chunk_kda_fwd/op_kernel/arch22/fwd_h/epilogue/block/block_epilogue_kda_fwdh_vnew.hpp+396-0
| @@ -0,0 +1,396 @@ | |||
| 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 CATLASS_EPILOGUE_BLOCK_BLOCK_EPILOGUE_KDA_FWDH_VNEW_HPP | ||
| 12 | +#define CATLASS_EPILOGUE_BLOCK_BLOCK_EPILOGUE_KDA_FWDH_VNEW_HPP | ||
| 13 | +#include "catlass/catlass.hpp" | ||
| 14 | +#include "catlass/arch/resource.hpp" | ||
| 15 | +#include "../kda_fwd_h_epilogue_policies.hpp" | ||
| 16 | +#include "catlass/gemm_coord.hpp" | ||
| 17 | +#include "catlass/matrix_coord.hpp" | ||
| 18 | +#include "catlass/epilogue/tile/tile_copy.hpp" | ||
| 19 | + | ||
| 20 | +namespace Catlass::Epilogue::Block { | ||
| 21 | + | ||
| 22 | +template <class VOutputType_, class GInputType_, class UInputType_, class WSInputType_, class FinalStateType_, | ||
| 23 | + class KGatedTag> | ||
| 24 | +class BlockEpilogue<EpilogueAtlasKdaFwdHVnew, VOutputType_, GInputType_, UInputType_, WSInputType_, FinalStateType_, | ||
| 25 | + KGatedTag> { | ||
| 26 | + static constexpr bool scalarGated = KGatedTag::scalarGated; | ||
| 27 | + static constexpr bool useExp2 = KGatedTag::useExp2; | ||
| 28 | + static constexpr float LN2 = 0.6931471805599453f; | ||
| 29 | + | ||
| 30 | +public: | ||
| 31 | + // Type aliases | ||
| 32 | + using DispatchPolicy = EpilogueAtlasKdaFwdHVnew; | ||
| 33 | + using ArchTag = typename DispatchPolicy::ArchTag; | ||
| 34 | + | ||
| 35 | + using VElementOutput = typename VOutputType_::Element; | ||
| 36 | + using GElementInput = typename GInputType_::Element; | ||
| 37 | + using UElementInput = typename UInputType_::Element; | ||
| 38 | + using WSElementInput = typename WSInputType_::Element; | ||
| 39 | + using FinalStateElement = typename FinalStateType_::Element; | ||
| 40 | + | ||
| 41 | + CATLASS_DEVICE | ||
| 42 | + BlockEpilogue(Arch::Resource<ArchTag> &resource) | ||
| 43 | + { | ||
| 44 | + constexpr uint32_t CALC_BUF_OFFSET = 0; | ||
| 45 | + constexpr uint32_t PING_BUF_0_OFFSET = 32 * 1024; | ||
| 46 | + constexpr uint32_t PING_BUF_1_OFFSET = 48 * 1024; | ||
| 47 | + constexpr uint32_t PING_BUF_2_OFFSET = 64 * 1024; | ||
| 48 | + constexpr uint32_t PING_BUF_3_OFFSET = 80 * 1024; | ||
| 49 | + constexpr uint32_t PONG_BUF_0_OFFSET = 96 * 1024; | ||
| 50 | + constexpr uint32_t PONG_BUF_1_OFFSET = 112 * 1024; | ||
| 51 | + constexpr uint32_t PONG_BUF_2_OFFSET = 128 * 1024; | ||
| 52 | + constexpr uint32_t PONG_BUF_3_OFFSET = 144 * 1024; | ||
| 53 | + constexpr uint32_t PING_G_BUF_OFFSET = 160 * 1024; | ||
| 54 | + constexpr uint32_t PONG_G_BUF_OFFSET = 161 * 1024; | ||
| 55 | + constexpr uint32_t PING_G_SUB_BUF_OFFSET = 162 * 1024; | ||
| 56 | + constexpr uint32_t PONG_G_SUB_BUF_OFFSET = 163 * 1024; | ||
| 57 | + constexpr uint32_t PING_G_INPUT_BUF_OFFSET = 164 * 1024; | ||
| 58 | + constexpr uint32_t PONG_G_INPUT_BUF_OFFSET = 165 * 1024; | ||
| 59 | + constexpr uint32_t SHARE_BUF_OFFSET = 166 * 1024; | ||
| 60 | + | ||
| 61 | + calcUbTensor = resource.ubBuf.template GetBufferByByte<float>(CALC_BUF_OFFSET); | ||
| 62 | + | ||
| 63 | + uUbTensor_ping = resource.ubBuf.template GetBufferByByte<UElementInput>(PING_BUF_2_OFFSET); | ||
| 64 | + wsUbTensor_ping = resource.ubBuf.template GetBufferByByte<float>(PING_BUF_0_OFFSET); | ||
| 65 | + gUbTensor_ping = resource.ubBuf.template GetBufferByByte<float>(PING_G_BUF_OFFSET); | ||
| 66 | + gLastUbTensor_ping = resource.ubBuf.template GetBufferByByte<float>(PING_G_SUB_BUF_OFFSET); | ||
| 67 | + gInputUbTensor_ping = resource.ubBuf.template GetBufferByByte<GElementInput>(PING_G_SUB_BUF_OFFSET); | ||
| 68 | + vNewOutputUbTensor_ping = resource.ubBuf.template GetBufferByByte<VElementOutput>(PING_BUF_2_OFFSET); | ||
| 69 | + vNewDecayUbTensor_ping = resource.ubBuf.template GetBufferByByte<VElementOutput>(PING_BUF_2_OFFSET); | ||
| 70 | + | ||
| 71 | + uUbTensor_pong = resource.ubBuf.template GetBufferByByte<UElementInput>(PONG_BUF_2_OFFSET); | ||
| 72 | + wsUbTensor_pong = resource.ubBuf.template GetBufferByByte<float>(PONG_BUF_0_OFFSET); | ||
| 73 | + gUbTensor_pong = resource.ubBuf.template GetBufferByByte<float>(PONG_G_BUF_OFFSET); | ||
| 74 | + gLastUbTensor_pong = resource.ubBuf.template GetBufferByByte<float>(PONG_G_SUB_BUF_OFFSET); | ||
| 75 | + gInputUbTensor_pong = resource.ubBuf.template GetBufferByByte<GElementInput>(PONG_G_SUB_BUF_OFFSET); | ||
| 76 | + vNewOutputUbTensor_pong = resource.ubBuf.template GetBufferByByte<VElementOutput>(PONG_BUF_2_OFFSET); | ||
| 77 | + vNewDecayUbTensor_pong = resource.ubBuf.template GetBufferByByte<VElementOutput>(PONG_BUF_2_OFFSET); | ||
| 78 | + | ||
| 79 | + shareBuffer_ = resource.ubBuf.template GetBufferByByte<uint8_t>(SHARE_BUF_OFFSET); | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + CATLASS_DEVICE | ||
| 83 | + ~BlockEpilogue() {} | ||
| 84 | + | ||
| 85 | + template <typename Element> | ||
| 86 | + CATLASS_DEVICE void CopyGmToUb(AscendC::LocalTensor<Element> dst, AscendC::GlobalTensor<Element> src, uint32_t rows, | ||
| 87 | + uint32_t cols, uint32_t srcStride) | ||
| 88 | + { | ||
| 89 | + if (cols == srcStride) { | ||
| 90 | + AscendC::DataCopy(dst, src, rows * cols); | ||
| 91 | + return; | ||
| 92 | + } | ||
| 93 | + AscendC::DataCopyExtParams copyParams{static_cast<uint16_t>(rows), | ||
| 94 | + static_cast<uint32_t>(cols * sizeof(Element)), | ||
| 95 | + static_cast<uint32_t>((srcStride - cols) * sizeof(Element)), 0, 0}; | ||
| 96 | + AscendC::DataCopyPadExtParams<Element> padParams{false, 0, 0, 0}; | ||
| 97 | + AscendC::DataCopyPad(dst, src, copyParams, padParams); | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + template <typename Element> | ||
| 101 | + CATLASS_DEVICE void CopyUbToGm(AscendC::GlobalTensor<Element> dst, AscendC::LocalTensor<Element> src, uint32_t rows, | ||
| 102 | + uint32_t cols, uint32_t dstStride) | ||
| 103 | + { | ||
| 104 | + if (cols == dstStride) { | ||
| 105 | + AscendC::DataCopy(dst, src, rows * cols); | ||
| 106 | + return; | ||
| 107 | + } | ||
| 108 | + AscendC::DataCopyExtParams copyParams{static_cast<uint16_t>(rows), | ||
| 109 | + static_cast<uint32_t>(cols * sizeof(Element)), 0, | ||
| 110 | + static_cast<uint32_t>((dstStride - cols) * sizeof(Element)), 0}; | ||
| 111 | + AscendC::DataCopyPad(dst, src, copyParams); | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + CATLASS_DEVICE | ||
| 115 | + void PrepareG(AscendC::LocalTensor<float> gUbTensor, AscendC::LocalTensor<float> gLastUbTensor, | ||
| 116 | + AscendC::LocalTensor<GElementInput> gInputUbTensor, | ||
| 117 | + AscendC::GlobalTensor<GElementInput> gInputThisSubBlock, uint32_t mActual, uint32_t pingpongFlag) | ||
| 118 | + { | ||
| 119 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID3 + pingpongFlag); | ||
| 120 | + if constexpr (!scalarGated) { | ||
| 121 | + AscendC::Duplicate<float>(gUbTensor, 1.0f, mActual); | ||
| 122 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 123 | + return; | ||
| 124 | + } | ||
| 125 | + if (mActual == 1) { | ||
| 126 | + AscendC::Duplicate<float>(gUbTensor, 1.0f, 1); | ||
| 127 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 128 | + return; | ||
| 129 | + } | ||
| 130 | + if constexpr (std::is_same<GElementInput, float>::value) { | ||
| 131 | + AscendC::DataCopyParams gUbParams{1, (uint16_t)(mActual * sizeof(float)), 0, 0}; | ||
| 132 | + AscendC::DataCopyPadParams gUbPadParams{false, 0, 0, 0}; | ||
| 133 | + AscendC::DataCopyPad(gUbTensor, gInputThisSubBlock, gUbParams, gUbPadParams); | ||
| 134 | + } else { | ||
| 135 | + AscendC::DataCopyParams gUbParams{1, (uint16_t)(mActual * sizeof(GElementInput)), 0, 0}; | ||
| 136 | + AscendC::DataCopyPadParams gUbPadParams{false, 0, 0, 0}; | ||
| 137 | + AscendC::DataCopyPad(gInputUbTensor, gInputThisSubBlock, gUbParams, gUbPadParams); | ||
| 138 | + } | ||
| 139 | + AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID3 + pingpongFlag); | ||
| 140 | + AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID3 + pingpongFlag); | ||
| 141 | + if constexpr (!std::is_same<GElementInput, float>::value) { | ||
| 142 | + AscendC::Cast(gUbTensor, gInputUbTensor, AscendC::RoundMode::CAST_NONE, mActual); | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + AscendC::SetFlag<AscendC::HardEvent::V_S>(EVENT_ID3 + pingpongFlag); | ||
| 146 | + AscendC::WaitFlag<AscendC::HardEvent::V_S>(EVENT_ID3 + pingpongFlag); | ||
| 147 | + float inputVal = gUbTensor.GetValue(mActual - 1); | ||
| 148 | + AscendC::SetFlag<AscendC::HardEvent::S_V>(EVENT_ID3 + pingpongFlag); | ||
| 149 | + AscendC::WaitFlag<AscendC::HardEvent::S_V>(EVENT_ID3 + pingpongFlag); | ||
| 150 | + | ||
| 151 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 152 | + AscendC::Duplicate<float>(gLastUbTensor, inputVal, mActual); | ||
| 153 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 154 | + | ||
| 155 | + AscendC::Sub<float>(gUbTensor, gLastUbTensor, gUbTensor, mActual); | ||
| 156 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 157 | + if constexpr (useExp2) { | ||
| 158 | + AscendC::Muls(gUbTensor, gUbTensor, LN2, mActual); | ||
| 159 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 160 | + } | ||
| 161 | + AscendC::Exp(gUbTensor, gUbTensor, mActual); | ||
| 162 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 163 | + } | ||
| 164 | + | ||
| 165 | + CATLASS_DEVICE | ||
| 166 | + void operator()(AscendC::GlobalTensor<VElementOutput> vnewOutput, | ||
| 167 | + AscendC::GlobalTensor<VElementOutput> vnewdecayOutput, AscendC::GlobalTensor<GElementInput> gInput, | ||
| 168 | + AscendC::GlobalTensor<UElementInput> uInput, AscendC::GlobalTensor<float> wsInput, | ||
| 169 | + uint32_t chunkSize, uint32_t vBlockDim, uint32_t vHeadDim, Arch::CrossCoreFlag cube1Done, | ||
| 170 | + Arch::CrossCoreFlag vec1Done, bool isInitialState, bool isFinalState, bool storeFinalState, | ||
| 171 | + bool waitWsFromMte3, bool isPing) | ||
| 172 | + { | ||
| 173 | + static constexpr uint32_t ROW_TILE = 16; | ||
| 174 | + uint32_t mActual = chunkSize; | ||
| 175 | + uint32_t nvActual = vBlockDim; | ||
| 176 | + uint32_t inputStride = vHeadDim; | ||
| 177 | + | ||
| 178 | + uint32_t subBlockIdx = AscendC::GetSubBlockIdx(); | ||
| 179 | + uint32_t subBlockNum = AscendC::GetSubBlockNum(); | ||
| 180 | + uint32_t rowsPerSubBlock = CeilDiv(mActual, subBlockNum); | ||
| 181 | + uint32_t rowBegin = subBlockIdx * rowsPerSubBlock; | ||
| 182 | + uint32_t rowEnd = rowBegin + rowsPerSubBlock; | ||
| 183 | + if (rowEnd > mActual) { | ||
| 184 | + rowEnd = mActual; | ||
| 185 | + } | ||
| 186 | + uint32_t pingpongFlag = isPing ? 0 : pongBaseEvent; | ||
| 187 | + if (rowBegin >= mActual) { | ||
| 188 | + Arch::CrossCoreWaitFlag(cube1Done); | ||
| 189 | + // A zero-row AIV lane still owns the EVENT0 hand-off consumed by V2. | ||
| 190 | + if (waitWsFromMte3) { | ||
| 191 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 192 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 193 | + } | ||
| 194 | + Arch::CrossCoreSetFlag<0x2, PIPE_MTE3>(vec1Done); | ||
| 195 | + return; | ||
| 196 | + } | ||
| 197 | + AscendC::ResetMask(); | ||
| 198 | + | ||
| 199 | + AscendC::GlobalTensor<GElementInput> gInputThisSubBlock = gInput; | ||
| 200 | + | ||
| 201 | + AscendC::LocalTensor<UElementInput> uUbTensor = isPing ? uUbTensor_ping : uUbTensor_pong; | ||
| 202 | + AscendC::LocalTensor<float> wsUbTensor = isPing ? wsUbTensor_ping : wsUbTensor_pong; | ||
| 203 | + AscendC::LocalTensor<float> gUbTensor = isPing ? gUbTensor_ping : gUbTensor_pong; | ||
| 204 | + AscendC::LocalTensor<float> gLastUbTensor = isPing ? gLastUbTensor_ping : gLastUbTensor_pong; | ||
| 205 | + AscendC::LocalTensor<GElementInput> gInputUbTensor = isPing ? gInputUbTensor_ping : gInputUbTensor_pong; | ||
| 206 | + AscendC::LocalTensor<VElementOutput> vNewOutputUbTensor = | ||
| 207 | + isPing ? vNewOutputUbTensor_ping : vNewOutputUbTensor_pong; | ||
| 208 | + AscendC::LocalTensor<VElementOutput> vNewDecayUbTensor = | ||
| 209 | + isPing ? vNewDecayUbTensor_ping : vNewDecayUbTensor_pong; | ||
| 210 | + | ||
| 211 | + if (nvActual <= 128 && nvActual == inputStride) { | ||
| 212 | + uint32_t mActualThisSubBlock = rowEnd - rowBegin; | ||
| 213 | + uint32_t gbrcRealStart = rowBegin & ~7; | ||
| 214 | + uint32_t gbrcEffStart = rowBegin - gbrcRealStart; | ||
| 215 | + uint32_t gbrcRealProcess = gbrcEffStart + mActualThisSubBlock; | ||
| 216 | + uint32_t dstShape_[2] = {gbrcRealProcess, nvActual}; | ||
| 217 | + uint32_t srcShape_[2] = {gbrcRealProcess, 1}; | ||
| 218 | + | ||
| 219 | + AscendC::GlobalTensor<VElementOutput> vnewOutputThisSubBlock = vnewOutput[rowBegin * inputStride]; | ||
| 220 | + AscendC::GlobalTensor<VElementOutput> vnewdecayOutputThisSubBlock = vnewdecayOutput[rowBegin * nvActual]; | ||
| 221 | + AscendC::GlobalTensor<UElementInput> uInputThisSubBlock = uInput[rowBegin * inputStride]; | ||
| 222 | + AscendC::GlobalTensor<float> wsInputThisSubBlock = wsInput[rowBegin * nvActual]; | ||
| 223 | + | ||
| 224 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1 + pingpongFlag); | ||
| 225 | + AscendC::DataCopy(uUbTensor, uInputThisSubBlock, mActualThisSubBlock * nvActual); | ||
| 226 | + AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID1 + pingpongFlag); | ||
| 227 | + AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID1 + pingpongFlag); | ||
| 228 | + AscendC::Cast(calcUbTensor, uUbTensor, AscendC::RoundMode::CAST_NONE, mActualThisSubBlock * nvActual); | ||
| 229 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 230 | + | ||
| 231 | + if constexpr (scalarGated) { | ||
| 232 | + PrepareG(gUbTensor, gLastUbTensor, gInputUbTensor, gInputThisSubBlock, mActual, pingpongFlag); | ||
| 233 | + } else { | ||
| 234 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID3 + pingpongFlag); | ||
| 235 | + } | ||
| 236 | + Arch::CrossCoreWaitFlag(cube1Done); | ||
| 237 | + | ||
| 238 | + if (waitWsFromMte3) { | ||
| 239 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 240 | + } else { | ||
| 241 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 242 | + } | ||
| 243 | + AscendC::DataCopy(wsUbTensor, wsInputThisSubBlock, mActualThisSubBlock * nvActual); | ||
| 244 | + AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0 + pingpongFlag); | ||
| 245 | + AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0 + pingpongFlag); | ||
| 246 | + | ||
| 247 | + AscendC::Sub<float>(wsUbTensor, calcUbTensor, wsUbTensor, mActualThisSubBlock * nvActual); | ||
| 248 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 249 | + | ||
| 250 | + uint32_t decayOffset = 0; | ||
| 251 | + if constexpr (scalarGated) { | ||
| 252 | + AscendC::Broadcast<float, 2, 1>(calcUbTensor, gUbTensor[gbrcRealStart], dstShape_, srcShape_, | ||
| 253 | + shareBuffer_); | ||
| 254 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 255 | + AscendC::Mul(calcUbTensor[gbrcEffStart * nvActual], wsUbTensor, calcUbTensor[gbrcEffStart * nvActual], | ||
| 256 | + mActualThisSubBlock * nvActual); | ||
| 257 | + decayOffset = gbrcEffStart * nvActual; | ||
| 258 | + } else { | ||
| 259 | + AscendC::Adds<float>(calcUbTensor, wsUbTensor, 0.0f, mActualThisSubBlock * nvActual); | ||
| 260 | + } | ||
| 261 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 262 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID3 + pingpongFlag); | ||
| 263 | + | ||
| 264 | + AscendC::Cast(vNewDecayUbTensor, calcUbTensor[decayOffset], AscendC::RoundMode::CAST_RINT, | ||
| 265 | + mActualThisSubBlock * nvActual); | ||
| 266 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 267 | + | ||
| 268 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 269 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 270 | + AscendC::DataCopy(vnewdecayOutputThisSubBlock, vNewDecayUbTensor, mActualThisSubBlock * nvActual); | ||
| 271 | + | ||
| 272 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID1 + pingpongFlag); | ||
| 273 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID1 + pingpongFlag); | ||
| 274 | + AscendC::Cast(vNewOutputUbTensor, wsUbTensor, AscendC::RoundMode::CAST_RINT, | ||
| 275 | + mActualThisSubBlock * nvActual); | ||
| 276 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 277 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 278 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 279 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 280 | + AscendC::DataCopy(vnewOutputThisSubBlock, vNewOutputUbTensor, mActualThisSubBlock * nvActual); | ||
| 281 | + Arch::CrossCoreSetFlag<0x2, PIPE_MTE3>(vec1Done); | ||
| 282 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1 + pingpongFlag); | ||
| 283 | + | ||
| 284 | + return; | ||
| 285 | + } | ||
| 286 | + | ||
| 287 | + if constexpr (scalarGated) { | ||
| 288 | + PrepareG(gUbTensor, gLastUbTensor, gInputUbTensor, gInputThisSubBlock, mActual, pingpongFlag); | ||
| 289 | + } else { | ||
| 290 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID3 + pingpongFlag); | ||
| 291 | + } | ||
| 292 | + Arch::CrossCoreWaitFlag(cube1Done); | ||
| 293 | + | ||
| 294 | + bool waitWsThisTileFromMte3 = waitWsFromMte3; | ||
| 295 | + for (uint32_t rowStart = rowBegin; rowStart < rowEnd;) { | ||
| 296 | + uint32_t alignExtra = rowStart & 7; | ||
| 297 | + uint32_t maxRowsThisTile = ROW_TILE - alignExtra; | ||
| 298 | + uint32_t rowsThisTile = rowEnd - rowStart; | ||
| 299 | + if (rowsThisTile > maxRowsThisTile) { | ||
| 300 | + rowsThisTile = maxRowsThisTile; | ||
| 301 | + } | ||
| 302 | + uint32_t gbrcRealStart = rowStart & ~7; | ||
| 303 | + uint32_t gbrcRealProcess = alignExtra + rowsThisTile; | ||
| 304 | + uint32_t dstShape_[2] = {gbrcRealProcess, nvActual}; | ||
| 305 | + uint32_t srcShape_[2] = {gbrcRealProcess, 1}; | ||
| 306 | + | ||
| 307 | + AscendC::GlobalTensor<VElementOutput> vnewOutputThisTile = vnewOutput[rowStart * inputStride]; | ||
| 308 | + AscendC::GlobalTensor<VElementOutput> vnewdecayOutputThisTile = vnewdecayOutput[rowStart * nvActual]; | ||
| 309 | + AscendC::GlobalTensor<UElementInput> uInputThisTile = uInput[rowStart * inputStride]; | ||
| 310 | + AscendC::GlobalTensor<float> wsInputThisTile = wsInput[rowStart * nvActual]; | ||
| 311 | + | ||
| 312 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1 + pingpongFlag); | ||
| 313 | + CopyGmToUb(uUbTensor, uInputThisTile, rowsThisTile, nvActual, inputStride); | ||
| 314 | + AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID1 + pingpongFlag); | ||
| 315 | + AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID1 + pingpongFlag); | ||
| 316 | + AscendC::Cast(calcUbTensor, uUbTensor, AscendC::RoundMode::CAST_NONE, rowsThisTile * nvActual); | ||
| 317 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 318 | + | ||
| 319 | + if (waitWsThisTileFromMte3) { | ||
| 320 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 321 | + } else { | ||
| 322 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 323 | + } | ||
| 324 | + AscendC::DataCopy(wsUbTensor, wsInputThisTile, rowsThisTile * nvActual); | ||
| 325 | + AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0 + pingpongFlag); | ||
| 326 | + AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0 + pingpongFlag); | ||
| 327 | + waitWsThisTileFromMte3 = false; | ||
| 328 | + | ||
| 329 | + AscendC::Sub<float>(wsUbTensor, calcUbTensor, wsUbTensor, rowsThisTile * nvActual); | ||
| 330 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 331 | + | ||
| 332 | + uint32_t decayOffset = 0; | ||
| 333 | + if constexpr (scalarGated) { | ||
| 334 | + AscendC::Broadcast<float, 2, 1>(calcUbTensor, gUbTensor[gbrcRealStart], dstShape_, srcShape_, | ||
| 335 | + shareBuffer_); | ||
| 336 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 337 | + AscendC::Mul(calcUbTensor[alignExtra * nvActual], wsUbTensor, calcUbTensor[alignExtra * nvActual], | ||
| 338 | + rowsThisTile * nvActual); | ||
| 339 | + decayOffset = alignExtra * nvActual; | ||
| 340 | + } else { | ||
| 341 | + AscendC::Adds<float>(calcUbTensor, wsUbTensor, 0.0f, rowsThisTile * nvActual); | ||
| 342 | + } | ||
| 343 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 344 | + | ||
| 345 | + AscendC::Cast(vNewDecayUbTensor, calcUbTensor[decayOffset], AscendC::RoundMode::CAST_RINT, | ||
| 346 | + rowsThisTile * nvActual); | ||
| 347 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 348 | + | ||
| 349 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 350 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 351 | + AscendC::DataCopy(vnewdecayOutputThisTile, vNewDecayUbTensor, rowsThisTile * nvActual); | ||
| 352 | + | ||
| 353 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID1 + pingpongFlag); | ||
| 354 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID1 + pingpongFlag); | ||
| 355 | + AscendC::Cast(vNewOutputUbTensor, wsUbTensor, AscendC::RoundMode::CAST_RINT, rowsThisTile * nvActual); | ||
| 356 | + AscendC::PipeBarrier<PIPE_V>(); | ||
| 357 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 358 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0 + pingpongFlag); | ||
| 359 | + AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID1 + pingpongFlag); | ||
| 360 | + CopyUbToGm(vnewOutputThisTile, vNewOutputUbTensor, rowsThisTile, nvActual, inputStride); | ||
| 361 | + if (rowStart + rowsThisTile >= rowEnd) { | ||
| 362 | + Arch::CrossCoreSetFlag<0x2, PIPE_MTE3>(vec1Done); | ||
| 363 | + } | ||
| 364 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1 + pingpongFlag); | ||
| 365 | + rowStart += rowsThisTile; | ||
| 366 | + } | ||
| 367 | + | ||
| 368 | + AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID3 + pingpongFlag); | ||
| 369 | + } | ||
| 370 | + | ||
| 371 | +private: | ||
| 372 | + uint32_t pongBaseEvent = 4; | ||
| 373 | + | ||
| 374 | + AscendC::LocalTensor<float> calcUbTensor; | ||
| 375 | + | ||
| 376 | + AscendC::LocalTensor<UElementInput> uUbTensor_ping; | ||
| 377 | + AscendC::LocalTensor<float> wsUbTensor_ping; | ||
| 378 | + AscendC::LocalTensor<float> gUbTensor_ping; | ||
| 379 | + AscendC::LocalTensor<float> gLastUbTensor_ping; | ||
| 380 | + AscendC::LocalTensor<GElementInput> gInputUbTensor_ping; | ||
| 381 | + AscendC::LocalTensor<VElementOutput> vNewOutputUbTensor_ping; | ||
| 382 | + AscendC::LocalTensor<VElementOutput> vNewDecayUbTensor_ping; | ||
| 383 | + | ||
| 384 | + AscendC::LocalTensor<UElementInput> uUbTensor_pong; | ||
| 385 | + AscendC::LocalTensor<float> wsUbTensor_pong; | ||
| 386 | + AscendC::LocalTensor<float> gUbTensor_pong; | ||
| 387 | + AscendC::LocalTensor<float> gLastUbTensor_pong; | ||
| 388 | + AscendC::LocalTensor<GElementInput> gInputUbTensor_pong; | ||
| 389 | + AscendC::LocalTensor<VElementOutput> vNewOutputUbTensor_pong; | ||
| 390 | + AscendC::LocalTensor<VElementOutput> vNewDecayUbTensor_pong; | ||
| 391 | + | ||
| 392 | + AscendC::LocalTensor<uint8_t> shareBuffer_; | ||
| 393 | +}; | ||
| 394 | +} // namespace Catlass::Epilogue::Block | ||
| 395 | + | ||
| 396 | +#endif | ||
| @@ -0,0 +1,28 @@ | |||
| 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 CATLASS_EPILOGUE_KDA_FWD_H_EPILOGUE_POLICIES_HPP | ||
| 12 | +#define CATLASS_EPILOGUE_KDA_FWD_H_EPILOGUE_POLICIES_HPP | ||
| 13 | + | ||
| 14 | +#include "catlass/catlass.hpp" | ||
| 15 | + | ||
| 16 | +namespace Catlass::Epilogue { | ||
| 17 | + | ||
| 18 | +struct EpilogueAtlasKdaFwdHVnew { | ||
| 19 | + using ArchTag = Arch::AtlasA2; | ||
| 20 | +}; | ||
| 21 | + | ||
| 22 | +struct EpilogueAtlasKdaFwdHUpdate { | ||
| 23 | + using ArchTag = Arch::AtlasA2; | ||
| 24 | +}; | ||
| 25 | + | ||
| 26 | +} // namespace Catlass::Epilogue | ||
| 27 | + | ||
| 28 | +#endif // CATLASS_EPILOGUE_KDA_FWD_H_EPILOGUE_POLICIES_HPP | ||