Merged
新增kimiK3反向算子 #11006
周云飞Add on Aug 31
新增kimiK3反向算子 #11006
Merged
Total: 34 files changed+5062-0
| @@ -716,6 +716,16 @@ Ascend 950支持的算子分类和算子列表如下: | |||
| 716 | <td>AI Core</td> | 716 | <td>AI Core</td> |
| 717 | <td>mhc_sinkhorn的反向算子。</td> | 717 | <td>mhc_sinkhorn的反向算子。</td> |
| 718 | </tr> | 718 | </tr> |
| 719 | + <tr> | ||
| 720 | + <td>mhc</td> | ||
| 721 | + <td><a href="../../mhc/block_attention_residuals_grad/README.md">block_attention_residuals_grad</a></td> | ||
| 722 | + <td>✓</td> | ||
| 723 | + <td>✓</td> | ||
| 724 | + <td>✓</td> | ||
| 725 | + <td>✓</td> | ||
| 726 | + <td>AI Core</td> | ||
| 727 | + <td>BlockAttentionResiduals的反向算子,计算partial_block、block_res、proj_weight、norm_weight的梯度。</td> | ||
| 728 | + </tr> | ||
| 719 | <tr> | 729 | <tr> |
| 720 | <td>moe</td> | 730 | <td>moe</td> |
| 721 | <td><a href="../../moe/moe_compute_expert_tokens/README.md">moe_compute_expert_tokens</a></td> | 731 | <td><a href="../../moe/moe_compute_expert_tokens/README.md">moe_compute_expert_tokens</a></td> |
| @@ -48,6 +48,7 @@ | |||
| 48 | |[aclnnAttentionWorkerCombine](../../attention/attention_worker_combine/docs/aclnnAttentionWorkerCombine.md)|Attention和FFN分离部署场景下,Attention侧数据融合算子,将多个计算单元处理的注意力token数据进行融合,结合专家权重对结果进行加权,输出最终的注意力融合结果,并更新层ID。|默认确定性实现| - | | 48 | |[aclnnAttentionWorkerCombine](../../attention/attention_worker_combine/docs/aclnnAttentionWorkerCombine.md)|Attention和FFN分离部署场景下,Attention侧数据融合算子,将多个计算单元处理的注意力token数据进行融合,结合专家权重对结果进行加权,输出最终的注意力融合结果,并更新层ID。|默认确定性实现| - | |
| 49 | |[aclnnBatchMatMulReduceScatterAlltoAll](../../mc2/batch_mat_mul_reduce_scatter_allto_all/docs/aclnnBatchMatMulReduceScatterAlltoAll.md)|BatchMatMulReduceScatterAllToAll是通算融合算子,实现BatchMatMul计算与ReduceScatter、AllToAll集合通信并行的算子。|默认确定性实现| - | | 49 | |[aclnnBatchMatMulReduceScatterAlltoAll](../../mc2/batch_mat_mul_reduce_scatter_allto_all/docs/aclnnBatchMatMulReduceScatterAlltoAll.md)|BatchMatMulReduceScatterAllToAll是通算融合算子,实现BatchMatMul计算与ReduceScatter、AllToAll集合通信并行的算子。|默认确定性实现| - | |
| 50 | |[aclnnBlitzSparseAttention](../../experimental/attention/blitz_sparse_attention/docs/aclnnBlitzSparseAttention.md)|全量推理场景的FlashAttention算子,支持sparse优化、actualSeqLengthsKv优化、int8量化功能、innerPrecise参数(用于支持高精度或者高性能模式选择)。|-|-| | 50 | |[aclnnBlitzSparseAttention](../../experimental/attention/blitz_sparse_attention/docs/aclnnBlitzSparseAttention.md)|全量推理场景的FlashAttention算子,支持sparse优化、actualSeqLengthsKv优化、int8量化功能、innerPrecise参数(用于支持高精度或者高性能模式选择)。|-|-| |
| 51 | +|[aclnnBlockAttentionResidualsGrad](../../mhc/block_attention_residuals_grad/docs/aclnnBlockAttentionResidualsGrad.md)|aclnnBlockAttentionResidualsGrad 是 BlockAttentionResiduals(注意力残差)的反向传播算子,根据前向保存的inv_norm、probs和上游梯度grad_hidden_states,计算partial_block、block_res、proj_weight、norm_weight的梯度。|默认确定性实现|默认确定性实现| | ||
| 51 | |[aclnnBlockAttnResPrepare](../../attention/block_attn_res_prepare/docs/aclnnBlockAttnResPrepare.md)|计算历史残差块与伪 Query 的块间注意力,输出 softmax 加权分子、logit 最大值和指数和,供后续阶段融合当前残差。|-|默认确定性实现| | 52 | |[aclnnBlockAttnResPrepare](../../attention/block_attn_res_prepare/docs/aclnnBlockAttnResPrepare.md)|计算历史残差块与伪 Query 的块间注意力,输出 softmax 加权分子、logit 最大值和指数和,供后续阶段融合当前残差。|-|默认确定性实现| |
| 52 | |[aclnnBlockAttnResUpdate](../../attention/block_attn_res_update/docs/aclnnBlockAttnResUpdate.md)|将`delta`原地累加到`partialBlockRef`,计算更新后`partialBlockRef`的RMSNorm score,并与历史online softmax中间状态合并,输出当前层结果`h`。|-|默认确定性实现| | 53 | |[aclnnBlockAttnResUpdate](../../attention/block_attn_res_update/docs/aclnnBlockAttnResUpdate.md)|将`delta`原地累加到`partialBlockRef`,计算更新后`partialBlockRef`的RMSNorm score,并与历史online softmax中间状态合并,输出当前层结果`h`。|-|默认确定性实现| |
| 53 | |[aclnnBlockSparseAttention](../../attention/block_sparse_attention/docs/aclnnBlockSparseAttention.md)|BlockSparseAttention通过BlockSparseMask指定每个Q块选择的KV块,实现高效的稀疏注意力计算。|默认确定性实现|默认确定性实现| | 54 | |[aclnnBlockSparseAttention](../../attention/block_sparse_attention/docs/aclnnBlockSparseAttention.md)|BlockSparseAttention通过BlockSparseMask指定每个Q块选择的KV块,实现高效的稀疏注意力计算。|默认确定性实现|默认确定性实现| |
| @@ -1556,6 +1556,16 @@ | |||
| 1556 | <td>AI Core</td> | 1556 | <td>AI Core</td> |
| 1557 | <td>mhc_pre_sinkhorn算子的反向传播,基于一系列计算得到MHC架构中hidden层的梯度。</td> | 1557 | <td>mhc_pre_sinkhorn算子的反向传播,基于一系列计算得到MHC架构中hidden层的梯度。</td> |
| 1558 | </tr> | 1558 | </tr> |
| 1559 | + <tr> | ||
| 1560 | + <td>mhc</td> | ||
| 1561 | + <td><a href="../../mhc/block_attention_residuals_grad/README.md">block_attention_residuals_grad</a></td> | ||
| 1562 | + <td>✓</td> | ||
| 1563 | + <td>✓</td> | ||
| 1564 | + <td>✓</td> | ||
| 1565 | + <td>✓</td> | ||
| 1566 | + <td>AI Core</td> | ||
| 1567 | + <td>BlockAttentionResiduals的反向算子,根据前向保存的inv_norm、probs和上游梯度grad_hidden_states,计算partial_block、block_res、proj_weight、norm_weight的梯度。</td> | ||
| 1568 | + </tr> | ||
| 1559 | <tr> | 1569 | <tr> |
| 1560 | <td>mamba</td> | 1570 | <td>mamba</td> |
| 1561 | <td><a href="../../mamba/causal_conv1d/README.md">causal_conv1d</a></td> | 1571 | <td><a href="../../mamba/causal_conv1d/README.md">causal_conv1d</a></td> |
| @@ -0,0 +1,19 @@ | |||
| 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 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 12 | +if(NOT ENABLE_TEST AND NOT BENCHMARK) | ||
| 13 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 14 | +endif() | ||
| 15 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 16 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 17 | + add_subdirectory(${SUB_DIR}) | ||
| 18 | + endif() | ||
| 19 | +endforeach() | ||
| @@ -0,0 +1,231 @@ | |||
| 1 | +# BlockAttentionResidualsGrad | ||
| 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 | +- **算子功能**:`BlockAttentionResidualsGrad` 是正向算子 `BlockAttentionResiduals`(注意力残差)的反向传播算子,融合 softmax、RMS 归一化与注意力输出的反向计算。 | ||
| 17 | +- **主要输出**:`gradPartialBlock`、`gradBlockRes`、`gradProjWeight`、`gradNormWeight`。 | ||
| 18 | +- **前向缓存依赖**:前向保存的 `invNorm`、`probs`;当前版本直接使用保存结果计算,不依赖 `validBlockNum` 重新构造掩码。 | ||
| 19 | + | ||
| 20 | +- **计算公式**: | ||
| 21 | + | ||
| 22 | +反向计算中的拼接 value、归一化中间量定义如下: | ||
| 23 | + | ||
| 24 | +$$ | ||
| 25 | +V_{t,i,h} = | ||
| 26 | +\begin{cases} | ||
| 27 | +block\_res_{t,i,h}, & i < N \\ | ||
| 28 | +partial\_block_{t,h}, & i = N | ||
| 29 | +\end{cases} | ||
| 30 | +$$ | ||
| 31 | + | ||
| 32 | +$$ | ||
| 33 | +k_{t,i,h} = V_{t,i,h} \cdot inv\_norm_{t,i} | ||
| 34 | +$$ | ||
| 35 | + | ||
| 36 | +$$ | ||
| 37 | +score\_weight_{h} = norm\_weight_{h} \cdot proj\_weight_{0,h} | ||
| 38 | +$$ | ||
| 39 | + | ||
| 40 | +`out` 对 `V`、`probs` 的反向梯度: | ||
| 41 | + | ||
| 42 | +$$ | ||
| 43 | +g_{t,i} = \sum_{h=0}^{H-1} grad\_output_{t,h} \cdot V_{t,i,h} | ||
| 44 | +$$ | ||
| 45 | + | ||
| 46 | +$$ | ||
| 47 | +grad\_score_{t,i} = probs_{t,i} \cdot \left(g_{t,i} - \sum_{j=0}^{N} probs_{t,j} \cdot g_{t,j}\right) | ||
| 48 | +$$ | ||
| 49 | + | ||
| 50 | +经 `score_weight` 与 RMS 归一化回传的梯度: | ||
| 51 | + | ||
| 52 | +$$ | ||
| 53 | +grad\_k_{t,i,h} = grad\_score_{t,i} \cdot score\_weight_{h} | ||
| 54 | +$$ | ||
| 55 | + | ||
| 56 | +$$ | ||
| 57 | +grad\_score\_weight_{h} = \sum_{t=0}^{T-1}\sum_{i=0}^{N} grad\_score_{t,i} \cdot k_{t,i,h} | ||
| 58 | +$$ | ||
| 59 | + | ||
| 60 | +$$ | ||
| 61 | +grad\_inv\_norm_{t,i} = \sum_{h=0}^{H-1} grad\_k_{t,i,h} \cdot V_{t,i,h} | ||
| 62 | +$$ | ||
| 63 | + | ||
| 64 | +`V` 的总梯度及最终输出梯度: | ||
| 65 | + | ||
| 66 | +$$ | ||
| 67 | +grad\_V_{t,i,h} = grad\_output_{t,h} \cdot probs_{t,i} + grad\_k_{t,i,h} \cdot inv\_norm_{t,i} | ||
| 68 | + - \frac{grad\_inv\_norm_{t,i} \cdot inv\_norm_{t,i}^{3}}{H} \cdot V_{t,i,h} | ||
| 69 | +$$ | ||
| 70 | + | ||
| 71 | +$$ | ||
| 72 | +grad\_block\_res_{t,i,h} = grad\_V_{t,i,h}, \quad i < N | ||
| 73 | +$$ | ||
| 74 | + | ||
| 75 | +$$ | ||
| 76 | +grad\_partial\_block_{t,h} = grad\_V_{t,N,h} | ||
| 77 | +$$ | ||
| 78 | + | ||
| 79 | +$$ | ||
| 80 | +grad\_norm\_weight_{h} = grad\_score\_weight_{h} \cdot proj\_weight_{0,h} | ||
| 81 | +$$ | ||
| 82 | + | ||
| 83 | +$$ | ||
| 84 | +grad\_proj\_weight_{0,h} = grad\_score\_weight_{h} \cdot norm\_weight_{h} | ||
| 85 | +$$ | ||
| 86 | + | ||
| 87 | +其中 $T$ 为 token 数,$N$ 为 `blockRes` 的 block 数,$H$ 为 hidden size。 | ||
| 88 | + | ||
| 89 | +## 参数说明 | ||
| 90 | + | ||
| 91 | +<table style="table-layout: fixed; width: 1200px"><colgroup> | ||
| 92 | + <col style="width: 220px"> | ||
| 93 | + <col style="width: 120px"> | ||
| 94 | + <col style="width: 520px"> | ||
| 95 | + <col style="width: 220px"> | ||
| 96 | + <col style="width: 120px"> | ||
| 97 | + </colgroup> | ||
| 98 | + <thead> | ||
| 99 | + <tr> | ||
| 100 | + <th>参数名</th> | ||
| 101 | + <th>输入/输出/属性</th> | ||
| 102 | + <th>描述</th> | ||
| 103 | + <th>数据类型</th> | ||
| 104 | + <th>数据格式</th> | ||
| 105 | + </tr> | ||
| 106 | + </thead> | ||
| 107 | + <tbody> | ||
| 108 | + <tr> | ||
| 109 | + <td>partialBlock</td> | ||
| 110 | + <td>输入</td> | ||
| 111 | + <td>前向输入前缀和,拼接后作为第 $N+1$ 个 value,shape 为 $[T,H]$。</td> | ||
| 112 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 113 | + <td>ND</td> | ||
| 114 | + </tr> | ||
| 115 | + <tr> | ||
| 116 | + <td>blockRes</td> | ||
| 117 | + <td>输入</td> | ||
| 118 | + <td>前向输入分块残差,拼接后作为前 $N$ 个 value,shape 为 $[T,N,H]$。</td> | ||
| 119 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 120 | + <td>ND</td> | ||
| 121 | + </tr> | ||
| 122 | + <tr> | ||
| 123 | + <td>projWeight</td> | ||
| 124 | + <td>输入</td> | ||
| 125 | + <td>前向投影权重,与 normWeight 共同构成 score_weight,shape 为 $[1,H]$。</td> | ||
| 126 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 127 | + <td>ND</td> | ||
| 128 | + </tr> | ||
| 129 | + <tr> | ||
| 130 | + <td>normWeight</td> | ||
| 131 | + <td>输入</td> | ||
| 132 | + <td>前向归一化权重,与 projWeight 共同构成 score_weight,shape 为 $[H]$。</td> | ||
| 133 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 134 | + <td>ND</td> | ||
| 135 | + </tr> | ||
| 136 | + <tr> | ||
| 137 | + <td>gradHiddenStates</td> | ||
| 138 | + <td>输入</td> | ||
| 139 | + <td>前向输出 out 的上游梯度,shape 为 $[T,H]$。</td> | ||
| 140 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 141 | + <td>ND</td> | ||
| 142 | + </tr> | ||
| 143 | + <tr> | ||
| 144 | + <td>invNorm</td> | ||
| 145 | + <td>输入</td> | ||
| 146 | + <td>前向保存的逐行归一化系数,shape 为 $[T,N+1]$。</td> | ||
| 147 | + <td>FLOAT32</td> | ||
| 148 | + <td>ND</td> | ||
| 149 | + </tr> | ||
| 150 | + <tr> | ||
| 151 | + <td>probs</td> | ||
| 152 | + <td>输入</td> | ||
| 153 | + <td>前向 softmax 输出概率,shape 为 $[T,N+1]$。</td> | ||
| 154 | + <td>FLOAT32</td> | ||
| 155 | + <td>ND</td> | ||
| 156 | + </tr> | ||
| 157 | + <tr> | ||
| 158 | + <td>validBlockNum</td> | ||
| 159 | + <td>属性</td> | ||
| 160 | + <td>预留属性,默认值为 0,当前版本不参与计算。</td> | ||
| 161 | + <td>INT64</td> | ||
| 162 | + <td>-</td> | ||
| 163 | + </tr> | ||
| 164 | + <tr> | ||
| 165 | + <td>gradPartialBlock</td> | ||
| 166 | + <td>输出</td> | ||
| 167 | + <td>partialBlock 的梯度,shape 与 partialBlock 一致。</td> | ||
| 168 | + <td>同主输入</td> | ||
| 169 | + <td>ND</td> | ||
| 170 | + </tr> | ||
| 171 | + <tr> | ||
| 172 | + <td>gradBlockRes</td> | ||
| 173 | + <td>输出</td> | ||
| 174 | + <td>blockRes 的梯度,shape 与 blockRes 一致。</td> | ||
| 175 | + <td>同主输入</td> | ||
| 176 | + <td>ND</td> | ||
| 177 | + </tr> | ||
| 178 | + <tr> | ||
| 179 | + <td>gradProjWeight</td> | ||
| 180 | + <td>输出</td> | ||
| 181 | + <td>projWeight 的梯度,shape 与 projWeight 一致。</td> | ||
| 182 | + <td>同主输入</td> | ||
| 183 | + <td>ND</td> | ||
| 184 | + </tr> | ||
| 185 | + <tr> | ||
| 186 | + <td>gradNormWeight</td> | ||
| 187 | + <td>输出</td> | ||
| 188 | + <td>normWeight 的梯度,shape 与 normWeight 一致。</td> | ||
| 189 | + <td>同主输入</td> | ||
| 190 | + <td>ND</td> | ||
| 191 | + </tr> | ||
| 192 | + </tbody> | ||
| 193 | +</table> | ||
| 194 | + | ||
| 195 | +## 约束说明 | ||
| 196 | + | ||
| 197 | +- $T \ge 1$,$0 \le N \le 128$,$H \ge 1$;各张量中的 $T$、$H$ 以及 `invNorm/probs` 的第 2 维 $N+1$ 需保持一致。 | ||
| 198 | +- 主输入 `partialBlock/blockRes/projWeight/normWeight/gradHiddenStates` 支持 FLOAT16、BFLOAT16、FLOAT32,dtype 需一致;`invNorm/probs` 仅支持 FLOAT32。 | ||
| 199 | +- 输入支持非连续 Tensor,接口内部会先转为 Contiguous 再计算。 | ||
| 200 | +- 输出 dtype 与对应主输入保持一致。 | ||
| 201 | +- `validBlockNum` 为预留属性,不同取值不影响当前版本的计算结果。 | ||
| 202 | +- `aclnnBlockAttentionResidualsGrad` 默认确定性实现。 | ||
| 203 | + | ||
| 204 | +## 调用说明 | ||
| 205 | + | ||
| 206 | +<table><thead> | ||
| 207 | + <tr> | ||
| 208 | + <th>调用方式</th> | ||
| 209 | + <th>调用样例</th> | ||
| 210 | + <th>说明</th> | ||
| 211 | + </tr> | ||
| 212 | +</thead> | ||
| 213 | +<tbody> | ||
| 214 | + <tr> | ||
| 215 | + <td>aclnn 调用</td> | ||
| 216 | + <td><a href="./examples/test_aclnn_block_attention_residuals_grad.cpp">test_aclnn_block_attention_residuals_grad.cpp</a></td> | ||
| 217 | + <td>通过 <a href="./docs/aclnnBlockAttentionResidualsGrad.md">aclnnBlockAttentionResidualsGrad.md</a> 调用算子。</td> | ||
| 218 | + </tr> | ||
| 219 | + <tr> | ||
| 220 | + <td>SPLIT_H 示例</td> | ||
| 221 | + <td><a href="./examples/test_aclnn_block_attention_residuals_grad_split_h.cpp">test_aclnn_block_attention_residuals_grad_split_h.cpp</a></td> | ||
| 222 | + <td>演示大 H 场景下 SPLIT_H 模板的调用方式。</td> | ||
| 223 | + </tr> | ||
| 224 | +</tbody> | ||
| 225 | +</table> | ||
| 226 | + | ||
| 227 | +```bash | ||
| 228 | +# 在 ops-transformer 仓库根目录执行 | ||
| 229 | +bash build.sh --pkg --soc=ascend950 --ops=block_attention_residuals_grad | ||
| 230 | +bash build.sh --run_example block_attention_residuals_grad eager cust --soc=ascend950 --vendor_name=custom | ||
| 231 | +``` | ||
| @@ -0,0 +1,524 @@ | |||
| 1 | +# aclnnBlockAttentionResidualsGrad | ||
| 2 | + | ||
| 3 | +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/mhc/block_attention_residuals_grad) | ||
| 4 | + | ||
| 5 | +## 产品支持情况 | ||
| 6 | + | ||
| 7 | +<!-- npu="950" id1 --> | ||
| 8 | +- <term>Ascend 950PR/Ascend 950DT</term>:支持 | ||
| 9 | +<!-- end id1 --> | ||
| 10 | +<!-- npu="A3" id2 --> | ||
| 11 | +- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:支持 | ||
| 12 | +<!-- end id2 --> | ||
| 13 | +<!-- npu="910b" id3 --> | ||
| 14 | +- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:支持 | ||
| 15 | +<!-- end id3 --> | ||
| 16 | +<!-- npu="310b" id4 --> | ||
| 17 | +- <term>Atlas 200I/500 A2 推理产品</term>:不支持 | ||
| 18 | +<!-- end id4 --> | ||
| 19 | +<!-- npu="310p" id5 --> | ||
| 20 | +- <term>Atlas 推理系列产品</term>:不支持 | ||
| 21 | +<!-- end id5 --> | ||
| 22 | +<!-- npu="910" id6 --> | ||
| 23 | +- <term>Atlas 训练系列产品</term>:不支持 | ||
| 24 | +<!-- end id6 --> | ||
| 25 | + | ||
| 26 | +## 功能说明 | ||
| 27 | + | ||
| 28 | +- 接口功能:`BlockAttentionResidualsGrad` 是正向算子 `BlockAttentionResiduals`(注意力残差)的反向传播算子,该接口根据前向保存的invNorm、probs以及正向参数projWeight、normWeight,结合gradHiddenStates,计算partialBlock、blockRes、projWeight和normWeight的梯度。validBlockNum是预留属性,当前版本不参与计算,取值不会影响输出。 | ||
| 29 | + | ||
| 30 | +- 计算公式: | ||
| 31 | + | ||
| 32 | + $$ | ||
| 33 | + g_{t,i} = \sum_{h=0}^{H-1} grad\_output_{t,h} \cdot v_{t,i,h} | ||
| 34 | + $$ | ||
| 35 | + | ||
| 36 | + $$ | ||
| 37 | + grad\_score_{t,i} = probs_{t,i} \cdot \left(g_{t,i} - \sum_{j=0}^{N} probs_{t,j} \cdot g_{t,j}\right) | ||
| 38 | + $$ | ||
| 39 | + | ||
| 40 | + $$ | ||
| 41 | + grad\_k_{t,i,h} = grad\_score_{t,i} \cdot score\_weight_{h} | ||
| 42 | + $$ | ||
| 43 | + | ||
| 44 | + $$ | ||
| 45 | + grad\_score\_weight_{h} = \sum_{t=0}^{T-1} \sum_{i=0}^{N} grad\_score_{t,i} \cdot k_{t,i,h} | ||
| 46 | + $$ | ||
| 47 | + | ||
| 48 | + $$ | ||
| 49 | + grad\_inv\_rms_{t,i} = \sum_{h=0}^{H-1} grad\_k_{t,i,h} \cdot v_{t,i,h} | ||
| 50 | + $$ | ||
| 51 | + | ||
| 52 | + $$ | ||
| 53 | + grad\_v_{t,i,h} = grad\_output_{t,h} \cdot probs_{t,i} + grad\_k_{t,i,h} \cdot inv\_rms_{t,i} - \frac{grad\_inv\_rms_{t,i} \cdot inv\_rms_{t,i}^{3}}{H} \cdot v_{t,i,h} | ||
| 54 | + $$ | ||
| 55 | + | ||
| 56 | + 其中: | ||
| 57 | + | ||
| 58 | + $$ | ||
| 59 | + grad\_block\_res_{t,i,h} = grad\_v_{t,i,h}, \quad i < N | ||
| 60 | + $$ | ||
| 61 | + | ||
| 62 | + $$ | ||
| 63 | + grad\_partial\_block_{t,h} = grad\_v_{t,N,h} | ||
| 64 | + $$ | ||
| 65 | + | ||
| 66 | + $$ | ||
| 67 | + grad\_norm\_weight_{h} = grad\_score\_weight_{h} \cdot proj\_weight_{0,h} | ||
| 68 | + $$ | ||
| 69 | + | ||
| 70 | + $$ | ||
| 71 | + grad\_proj\_weight_{0,h} = grad\_score\_weight_{h} \cdot norm\_weight_{h} | ||
| 72 | + $$ | ||
| 73 | + | ||
| 74 | + 当前版本直接使用前向保存的probs进行反向计算,不根据validBlockNum重新构造掩码。 | ||
| 75 | + | ||
| 76 | +## 函数原型 | ||
| 77 | + | ||
| 78 | +每个算子分为[两段式接口](../../../docs/zh/context/two_phase_api.md),必须先调用“aclnnBlockAttentionResidualsGradGetWorkspaceSize”接口获取计算所需workspace大小以及包含算子计算流程的执行器,再调用“aclnnBlockAttentionResidualsGrad”接口执行计算。 | ||
| 79 | + | ||
| 80 | +```c++ | ||
| 81 | +aclnnStatus aclnnBlockAttentionResidualsGradGetWorkspaceSize( | ||
| 82 | + const aclTensor *partialBlock, | ||
| 83 | + const aclTensor *blockRes, | ||
| 84 | + const aclTensor *projWeight, | ||
| 85 | + const aclTensor *normWeight, | ||
| 86 | + const aclTensor *gradHiddenStates, | ||
| 87 | + const aclTensor *invNorm, | ||
| 88 | + const aclTensor *probs, | ||
| 89 | + int64_t validBlockNum, | ||
| 90 | + const aclTensor *gradPartialBlock, | ||
| 91 | + const aclTensor *gradBlockRes, | ||
| 92 | + const aclTensor *gradProjWeight, | ||
| 93 | + const aclTensor *gradNormWeight, | ||
| 94 | + uint64_t *workspaceSize, | ||
| 95 | + aclOpExecutor **executor); | ||
| 96 | +``` | ||
| 97 | +```c++ | ||
| 98 | +aclnnStatus aclnnBlockAttentionResidualsGrad( | ||
| 99 | + void *workspace, | ||
| 100 | + uint64_t workspaceSize, | ||
| @@ -0,0 +1,201 @@ | |||
| 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 <iostream> | ||
Outdated 【review】该算子缺乏docs文件 ![]() ![]() | |||
| 12 | +#include <vector> | ||
| 13 | +#include <cstring> | ||
| 14 | +#include "acl/acl.h" | ||
| 15 | +#include "aclnnop/aclnn_block_attention_residuals_grad.h" | ||
| 16 | + | ||
| 17 | +#define CHECK_RET(cond, return_expr) \ | ||
| 18 | + do { \ | ||
| 19 | + if (!(cond)) { \ | ||
| 20 | + return_expr; \ | ||
| 21 | + } \ | ||
| 22 | + } while (0) | ||
| 23 | + | ||
| 24 | +#define LOG_PRINT(message, ...) \ | ||
| 25 | + do { \ | ||
| 26 | + printf(message, ##__VA_ARGS__); \ | ||
| 27 | + } while (0) | ||
| 28 | + | ||
| 29 | +int64_t GetShapeSize(const std::vector<int64_t> &shape) | ||
| 30 | +{ | ||
| 31 | + int64_t shapeSize = 1; | ||
| 32 | + for (auto i : shape) { | ||
| 33 | + shapeSize *= i; | ||
| 34 | + } | ||
| 35 | + return shapeSize; | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +int Init(int32_t deviceId, aclrtStream *stream) | ||
| 39 | +{ | ||
| 40 | + auto ret = aclInit(nullptr); | ||
| 41 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); | ||
| 42 | + ret = aclrtSetDevice(deviceId); | ||
| 43 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); | ||
| 44 | + ret = aclrtCreateStream(stream); | ||
| 45 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); | ||
| 46 | + return 0; | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +template <typename T> | ||
| 50 | +int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr, | ||
| 51 | + aclDataType dataType, aclTensor **tensor) | ||
| 52 | +{ | ||
| 53 | + auto size = GetShapeSize(shape) * sizeof(T); | ||
| 54 | + auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 55 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret); | ||
| 56 | + ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 57 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); | ||
| 58 | + | ||
| 59 | + std::vector<int64_t> strides(shape.size(), 1); | ||
| 60 | + for (int64_t i = shape.size() - 2; i >= 0; i--) { | ||
| 61 | + strides[i] = shape[i + 1] * strides[i + 1]; | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, | ||
| 65 | + shape.data(), shape.size(), *deviceAddr); | ||
| 66 | + return 0; | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +int main() | ||
| 70 | +{ | ||
| 71 | + int32_t deviceId = 0; | ||
| 72 | + aclrtStream stream; | ||
| 73 | + auto ret = Init(deviceId, &stream); | ||
| 74 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); | ||
| 75 | + | ||
| 76 | + // Test shapes: B = 2, N = 4, H = 64, N1 = N + 1 = 5 | ||
| 77 | + const int64_t B = 2; | ||
| 78 | + const int64_t N = 4; | ||
| 79 | + const int64_t H = 64; | ||
| 80 | + const int64_t N1 = N + 1; | ||
| 81 | + const int64_t validBlockNum = N; // Reserved attribute; currently not used by the kernel. | ||
| 82 | + | ||
| 83 | + std::vector<int64_t> partialBlockShape = {B, H}; | ||
| 84 | + std::vector<int64_t> blockResShape = {B, N, H}; | ||
| 85 | + std::vector<int64_t> projWeightShape = {1, H}; | ||
| 86 | + std::vector<int64_t> normWeightShape = {H}; | ||
| 87 | + std::vector<int64_t> gradHiddenStatesShape = {B, H}; | ||
| 88 | + std::vector<int64_t> invNormShape = {B, N1}; | ||
| 89 | + std::vector<int64_t> probsShape = {B, N1}; | ||
| 90 | + | ||
| 91 | + std::vector<uint16_t> partialBlockData(GetShapeSize(partialBlockShape), 0x3C00); // FP16 1.0 | ||
| 92 | + std::vector<uint16_t> blockResData(GetShapeSize(blockResShape), 0x3C00); | ||
| 93 | + std::vector<uint16_t> projWeightData(GetShapeSize(projWeightShape), 0x3C00); | ||
| 94 | + std::vector<uint16_t> normWeightData(GetShapeSize(normWeightShape), 0x3C00); | ||
| 95 | + std::vector<uint16_t> gradHiddenStatesData(GetShapeSize(gradHiddenStatesShape), 0x3C00); | ||
| 96 | + std::vector<float> invNormData(GetShapeSize(invNormShape), 1.0f); | ||
| 97 | + std::vector<float> probsData(GetShapeSize(probsShape), 1.0f); | ||
| 98 | + | ||
| 99 | + aclTensor *partial_block = nullptr, *block_res = nullptr, *proj_weight = nullptr, *norm_weight = nullptr; | ||
| 100 | + aclTensor *grad_hidden_states = nullptr, *inv_norm = nullptr, *probs = nullptr; | ||
| 101 | + void *d_partial_block = nullptr, *d_block_res = nullptr, *d_proj_weight = nullptr, *d_norm_weight = nullptr; | ||
| 102 | + void *d_grad_hidden_states = nullptr, *d_inv_norm = nullptr, *d_probs = nullptr; | ||
| 103 | + | ||
| 104 | + ret = CreateAclTensor(partialBlockData, partialBlockShape, &d_partial_block, aclDataType::ACL_FLOAT16, | ||
| 105 | + &partial_block); | ||
| 106 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 107 | + ret = CreateAclTensor(blockResData, blockResShape, &d_block_res, aclDataType::ACL_FLOAT16, &block_res); | ||
| 108 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 109 | + ret = CreateAclTensor(projWeightData, projWeightShape, &d_proj_weight, aclDataType::ACL_FLOAT16, &proj_weight); | ||
| 110 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 111 | + ret = CreateAclTensor(normWeightData, normWeightShape, &d_norm_weight, aclDataType::ACL_FLOAT16, &norm_weight); | ||
| 112 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 113 | + ret = CreateAclTensor(gradHiddenStatesData, gradHiddenStatesShape, &d_grad_hidden_states, aclDataType::ACL_FLOAT16, | ||
| 114 | + &grad_hidden_states); | ||
| 115 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 116 | + ret = CreateAclTensor(invNormData, invNormShape, &d_inv_norm, aclDataType::ACL_FLOAT, &inv_norm); | ||
| 117 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 118 | + ret = CreateAclTensor(probsData, probsShape, &d_probs, aclDataType::ACL_FLOAT, &probs); | ||
| 119 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 120 | + | ||
| 121 | + aclTensor *grad_partial_block = nullptr, *grad_block_res = nullptr, *grad_proj_weight = nullptr, | ||
| 122 | + *grad_norm_weight = nullptr; | ||
| 123 | + void *d_grad_partial_block = nullptr, *d_grad_block_res = nullptr, *d_grad_proj_weight = nullptr, | ||
| 124 | + *d_grad_norm_weight = nullptr; | ||
| 125 | + | ||
| 126 | + std::vector<uint16_t> gradPartialBlockData(GetShapeSize(partialBlockShape), 0); | ||
| 127 | + std::vector<uint16_t> gradBlockResData(GetShapeSize(blockResShape), 0); | ||
| 128 | + std::vector<uint16_t> gradProjWeightData(GetShapeSize(projWeightShape), 0); | ||
| 129 | + std::vector<uint16_t> gradNormWeightData(GetShapeSize(normWeightShape), 0); | ||
| 130 | + | ||
| 131 | + ret = CreateAclTensor(gradPartialBlockData, partialBlockShape, &d_grad_partial_block, aclDataType::ACL_FLOAT16, | ||
| 132 | + &grad_partial_block); | ||
| 133 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 134 | + ret = | ||
| 135 | + CreateAclTensor(gradBlockResData, blockResShape, &d_grad_block_res, aclDataType::ACL_FLOAT16, &grad_block_res); | ||
| 136 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 137 | + ret = CreateAclTensor(gradProjWeightData, projWeightShape, &d_grad_proj_weight, aclDataType::ACL_FLOAT16, | ||
| 138 | + &grad_proj_weight); | ||
| 139 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 140 | + ret = CreateAclTensor(gradNormWeightData, normWeightShape, &d_grad_norm_weight, aclDataType::ACL_FLOAT16, | ||
| 141 | + &grad_norm_weight); | ||
| 142 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 143 | + | ||
| 144 | + uint64_t workspaceSize = 0; | ||
| 145 | + aclOpExecutor *executor; | ||
| 146 | + | ||
| 147 | + ret = aclnnBlockAttentionResidualsGradGetWorkspaceSize( | ||
| 148 | + partial_block, block_res, proj_weight, norm_weight, grad_hidden_states, inv_norm, probs, validBlockNum, | ||
| 149 | + grad_partial_block, grad_block_res, grad_proj_weight, grad_norm_weight, &workspaceSize, &executor); | ||
| 150 | + CHECK_RET(ret == ACL_SUCCESS, | ||
| 151 | + LOG_PRINT("aclnnBlockAttentionResidualsGradGetWorkspaceSize failed. ERROR: %d\n", ret); | ||
| 152 | + return ret); | ||
| 153 | + | ||
| 154 | + void *workspaceAddr = nullptr; | ||
| 155 | + if (workspaceSize > static_cast<uint64_t>(0)) { | ||
| 156 | + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 157 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret); | ||
| 158 | + } | ||
| 159 | + ret = aclnnBlockAttentionResidualsGrad(workspaceAddr, workspaceSize, executor, stream); | ||
| 160 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockAttentionResidualsGrad failed. ERROR: %d\n", ret); return ret); | ||
| 161 | + | ||
| 162 | + ret = aclrtSynchronizeStream(stream); | ||
| 163 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); | ||
| 164 | + | ||
| 165 | + LOG_PRINT("BlockAttentionResidualsGrad example ran successfully!\n"); | ||
| 166 | + | ||
| 167 | + // clean up inputs | ||
| 168 | + aclDestroyTensor(partial_block); | ||
| 169 | + aclDestroyTensor(block_res); | ||
| 170 | + aclDestroyTensor(proj_weight); | ||
| 171 | + aclDestroyTensor(norm_weight); | ||
| 172 | + aclDestroyTensor(grad_hidden_states); | ||
| 173 | + aclDestroyTensor(inv_norm); | ||
| 174 | + aclDestroyTensor(probs); | ||
| 175 | + aclrtFree(d_partial_block); | ||
| 176 | + aclrtFree(d_block_res); | ||
| 177 | + aclrtFree(d_proj_weight); | ||
| 178 | + aclrtFree(d_norm_weight); | ||
| 179 | + aclrtFree(d_grad_hidden_states); | ||
| 180 | + aclrtFree(d_inv_norm); | ||
| 181 | + aclrtFree(d_probs); | ||
| 182 | + | ||
| 183 | + // clean up outputs | ||
| 184 | + aclDestroyTensor(grad_partial_block); | ||
| 185 | + aclDestroyTensor(grad_block_res); | ||
| 186 | + aclDestroyTensor(grad_proj_weight); | ||
| 187 | + aclDestroyTensor(grad_norm_weight); | ||
| 188 | + aclrtFree(d_grad_partial_block); | ||
| 189 | + aclrtFree(d_grad_block_res); | ||
| 190 | + aclrtFree(d_grad_proj_weight); | ||
| 191 | + aclrtFree(d_grad_norm_weight); | ||
| 192 | + | ||
| 193 | + if (workspaceSize > static_cast<uint64_t>(0)) { | ||
| 194 | + aclrtFree(workspaceAddr); | ||
| 195 | + } | ||
| 196 | + aclrtDestroyStream(stream); | ||
| 197 | + aclrtResetDevice(deviceId); | ||
| 198 | + aclFinalize(); | ||
| 199 | + | ||
| 200 | + return 0; | ||
| 201 | +} | ||
Amhc/block_attention_residuals_grad/examples/test_aclnn_block_attention_residuals_grad_split_h.cpp+214-0
| @@ -0,0 +1,214 @@ | |||
| 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 <iostream> | ||
| 12 | +#include <algorithm> | ||
| 13 | +#include <vector> | ||
| 14 | +#include <cstring> | ||
| 15 | +#include "acl/acl.h" | ||
| 16 | +#include "aclnnop/aclnn_block_attention_residuals_grad.h" | ||
| 17 | + | ||
| 18 | +#define CHECK_RET(cond, return_expr) \ | ||
| 19 | + do { \ | ||
| 20 | + if (!(cond)) { \ | ||
| 21 | + return_expr; \ | ||
| 22 | + } \ | ||
| 23 | + } while (0) | ||
| 24 | + | ||
| 25 | +#define LOG_PRINT(message, ...) \ | ||
| 26 | + do { \ | ||
| 27 | + printf(message, ##__VA_ARGS__); \ | ||
| 28 | + } while (0) | ||
| 29 | + | ||
| 30 | +int64_t GetShapeSize(const std::vector<int64_t> &shape) | ||
| 31 | +{ | ||
| 32 | + int64_t shapeSize = 1; | ||
| 33 | + for (auto i : shape) { | ||
| 34 | + shapeSize *= i; | ||
| 35 | + } | ||
| 36 | + return shapeSize; | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +int Init(int32_t deviceId, aclrtStream *stream) | ||
| 40 | +{ | ||
| 41 | + auto ret = aclInit(nullptr); | ||
| 42 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); | ||
| 43 | + ret = aclrtSetDevice(deviceId); | ||
| 44 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); | ||
| 45 | + ret = aclrtCreateStream(stream); | ||
| 46 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); | ||
| 47 | + return 0; | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +template <typename T> | ||
| 51 | +int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr, | ||
| 52 | + aclDataType dataType, aclTensor **tensor) | ||
| 53 | +{ | ||
| 54 | + auto size = GetShapeSize(shape) * sizeof(T); | ||
| 55 | + auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 56 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret); | ||
| 57 | + ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 58 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); | ||
| 59 | + | ||
| 60 | + std::vector<int64_t> strides(shape.size(), 1); | ||
| 61 | + for (int64_t i = shape.size() - 2; i >= 0; i--) { | ||
| 62 | + strides[i] = shape[i + 1] * strides[i + 1]; | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, | ||
| 66 | + shape.data(), shape.size(), *deviceAddr); | ||
| 67 | + return 0; | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +int main() | ||
| 71 | +{ | ||
| 72 | + int32_t deviceId = 0; | ||
| 73 | + aclrtStream stream; | ||
| 74 | + auto ret = Init(deviceId, &stream); | ||
| 75 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); | ||
| 76 | + | ||
| 77 | + // SPLIT_H 用例:Ascend 910B 上 FP16、K=3 时,H=8192 超过 FULL_H 的 UB 容量。 | ||
| 78 | + // Kernel 日志应输出:hMode=1, kernel=SPLIT_H。 | ||
| 79 | + const int64_t B = 2; | ||
| 80 | + const int64_t N = 2; | ||
| 81 | + const int64_t H = 8192; | ||
| 82 | + const int64_t N1 = N + 1; | ||
| 83 | + const int64_t validBlockNum = N; // Reserved attribute; currently not used by the kernel. | ||
| 84 | + | ||
| 85 | + std::vector<int64_t> partialBlockShape = {B, H}; | ||
| 86 | + std::vector<int64_t> blockResShape = {B, N, H}; | ||
| 87 | + std::vector<int64_t> projWeightShape = {1, H}; | ||
| 88 | + std::vector<int64_t> normWeightShape = {H}; | ||
| 89 | + std::vector<int64_t> gradHiddenStatesShape = {B, H}; | ||
| 90 | + std::vector<int64_t> invNormShape = {B, N1}; | ||
| 91 | + std::vector<int64_t> probsShape = {B, N1}; | ||
| 92 | + | ||
| 93 | + std::vector<uint16_t> partialBlockData(GetShapeSize(partialBlockShape), 0x3C00); // FP16 1.0 | ||
| 94 | + std::vector<uint16_t> blockResData(GetShapeSize(blockResShape), 0x0000); | ||
| 95 | + std::vector<uint16_t> projWeightData(GetShapeSize(projWeightShape), 0x3C00); | ||
| 96 | + std::vector<uint16_t> normWeightData(GetShapeSize(normWeightShape), 0x3C00); | ||
| 97 | + std::vector<uint16_t> gradHiddenStatesData(GetShapeSize(gradHiddenStatesShape), 0x3C00); | ||
| 98 | + std::vector<float> invNormData(GetShapeSize(invNormShape), 1.0f); | ||
| 99 | + std::vector<float> probsData(GetShapeSize(probsShape), 0.0f); | ||
| 100 | + | ||
| 101 | + // 让三个 V block 的值不同,配合非均匀 probs 产生非零 gradScore 和 varianceScale。 | ||
| 102 | + for (int64_t batch = 0; batch < B; ++batch) { | ||
| 103 | + std::fill_n(blockResData.begin() + (batch * N) * H, H, static_cast<uint16_t>(0x3800)); // FP16 0.5 | ||
| 104 | + std::fill_n(blockResData.begin() + (batch * N + 1) * H, H, | ||
| 105 | + static_cast<uint16_t>(0x3E00)); // FP16 1.5 | ||
| 106 | + probsData[batch * N1] = 0.2f; | ||
| 107 | + probsData[batch * N1 + 1] = 0.3f; | ||
| 108 | + probsData[batch * N1 + 2] = 0.5f; | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + aclTensor *partial_block = nullptr, *block_res = nullptr, *proj_weight = nullptr, *norm_weight = nullptr; | ||
| 112 | + aclTensor *grad_hidden_states = nullptr, *inv_norm = nullptr, *probs = nullptr; | ||
| 113 | + void *d_partial_block = nullptr, *d_block_res = nullptr, *d_proj_weight = nullptr, *d_norm_weight = nullptr; | ||
| 114 | + void *d_grad_hidden_states = nullptr, *d_inv_norm = nullptr, *d_probs = nullptr; | ||
| 115 | + | ||
| 116 | + ret = CreateAclTensor(partialBlockData, partialBlockShape, &d_partial_block, aclDataType::ACL_FLOAT16, | ||
| 117 | + &partial_block); | ||
| 118 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 119 | + ret = CreateAclTensor(blockResData, blockResShape, &d_block_res, aclDataType::ACL_FLOAT16, &block_res); | ||
| 120 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 121 | + ret = CreateAclTensor(projWeightData, projWeightShape, &d_proj_weight, aclDataType::ACL_FLOAT16, &proj_weight); | ||
| 122 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 123 | + ret = CreateAclTensor(normWeightData, normWeightShape, &d_norm_weight, aclDataType::ACL_FLOAT16, &norm_weight); | ||
| 124 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 125 | + ret = CreateAclTensor(gradHiddenStatesData, gradHiddenStatesShape, &d_grad_hidden_states, aclDataType::ACL_FLOAT16, | ||
| 126 | + &grad_hidden_states); | ||
| 127 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 128 | + ret = CreateAclTensor(invNormData, invNormShape, &d_inv_norm, aclDataType::ACL_FLOAT, &inv_norm); | ||
| 129 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 130 | + ret = CreateAclTensor(probsData, probsShape, &d_probs, aclDataType::ACL_FLOAT, &probs); | ||
| 131 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 132 | + | ||
| 133 | + aclTensor *grad_partial_block = nullptr, *grad_block_res = nullptr, *grad_proj_weight = nullptr, | ||
| 134 | + *grad_norm_weight = nullptr; | ||
| 135 | + void *d_grad_partial_block = nullptr, *d_grad_block_res = nullptr, *d_grad_proj_weight = nullptr, | ||
| 136 | + *d_grad_norm_weight = nullptr; | ||
| 137 | + | ||
| 138 | + std::vector<uint16_t> gradPartialBlockData(GetShapeSize(partialBlockShape), 0); | ||
| 139 | + std::vector<uint16_t> gradBlockResData(GetShapeSize(blockResShape), 0); | ||
| 140 | + std::vector<uint16_t> gradProjWeightData(GetShapeSize(projWeightShape), 0); | ||
| 141 | + std::vector<uint16_t> gradNormWeightData(GetShapeSize(normWeightShape), 0); | ||
| 142 | + | ||
| 143 | + ret = CreateAclTensor(gradPartialBlockData, partialBlockShape, &d_grad_partial_block, aclDataType::ACL_FLOAT16, | ||
| 144 | + &grad_partial_block); | ||
| 145 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 146 | + ret = | ||
| 147 | + CreateAclTensor(gradBlockResData, blockResShape, &d_grad_block_res, aclDataType::ACL_FLOAT16, &grad_block_res); | ||
| 148 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 149 | + ret = CreateAclTensor(gradProjWeightData, projWeightShape, &d_grad_proj_weight, aclDataType::ACL_FLOAT16, | ||
| 150 | + &grad_proj_weight); | ||
| 151 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 152 | + ret = CreateAclTensor(gradNormWeightData, normWeightShape, &d_grad_norm_weight, aclDataType::ACL_FLOAT16, | ||
| 153 | + &grad_norm_weight); | ||
| 154 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 155 | + | ||
| 156 | + uint64_t workspaceSize = 0; | ||
| 157 | + aclOpExecutor *executor; | ||
| 158 | + | ||
| 159 | + ret = aclnnBlockAttentionResidualsGradGetWorkspaceSize( | ||
| 160 | + partial_block, block_res, proj_weight, norm_weight, grad_hidden_states, inv_norm, probs, validBlockNum, | ||
| 161 | + grad_partial_block, grad_block_res, grad_proj_weight, grad_norm_weight, &workspaceSize, &executor); | ||
| 162 | + CHECK_RET(ret == ACL_SUCCESS, | ||
| 163 | + LOG_PRINT("aclnnBlockAttentionResidualsGradGetWorkspaceSize failed. ERROR: %d\n", ret); | ||
| 164 | + return ret); | ||
| 165 | + LOG_PRINT("Run SPLIT_H example: B=%ld, N=%ld, H=%ld, workspaceSize=%lu bytes\n", B, N, H, workspaceSize); | ||
| 166 | + | ||
| 167 | + void *workspaceAddr = nullptr; | ||
| 168 | + if (workspaceSize > static_cast<uint64_t>(0)) { | ||
| 169 | + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 170 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret); | ||
| 171 | + } | ||
| 172 | + ret = aclnnBlockAttentionResidualsGrad(workspaceAddr, workspaceSize, executor, stream); | ||
| 173 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockAttentionResidualsGrad failed. ERROR: %d\n", ret); return ret); | ||
| 174 | + | ||
| 175 | + ret = aclrtSynchronizeStream(stream); | ||
| 176 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); | ||
| 177 | + | ||
| 178 | + LOG_PRINT("BlockAttentionResidualsGrad SPLIT_H example ran successfully!\n"); | ||
| 179 | + | ||
| 180 | + // clean up inputs | ||
| 181 | + aclDestroyTensor(partial_block); | ||
| 182 | + aclDestroyTensor(block_res); | ||
| 183 | + aclDestroyTensor(proj_weight); | ||
| 184 | + aclDestroyTensor(norm_weight); | ||
| 185 | + aclDestroyTensor(grad_hidden_states); | ||
| 186 | + aclDestroyTensor(inv_norm); | ||
| 187 | + aclDestroyTensor(probs); | ||
| 188 | + aclrtFree(d_partial_block); | ||
| 189 | + aclrtFree(d_block_res); | ||
| 190 | + aclrtFree(d_proj_weight); | ||
| 191 | + aclrtFree(d_norm_weight); | ||
| 192 | + aclrtFree(d_grad_hidden_states); | ||
| 193 | + aclrtFree(d_inv_norm); | ||
| 194 | + aclrtFree(d_probs); | ||
| 195 | + | ||
| 196 | + // clean up outputs | ||
| 197 | + aclDestroyTensor(grad_partial_block); | ||
| 198 | + aclDestroyTensor(grad_block_res); | ||
| 199 | + aclDestroyTensor(grad_proj_weight); | ||
| 200 | + aclDestroyTensor(grad_norm_weight); | ||
| 201 | + aclrtFree(d_grad_partial_block); | ||
| 202 | + aclrtFree(d_grad_block_res); | ||
| 203 | + aclrtFree(d_grad_proj_weight); | ||
| 204 | + aclrtFree(d_grad_norm_weight); | ||
| 205 | + | ||
| 206 | + if (workspaceSize > static_cast<uint64_t>(0)) { | ||
| 207 | + aclrtFree(workspaceAddr); | ||
| 208 | + } | ||
| 209 | + aclrtDestroyStream(stream); | ||
| 210 | + aclrtResetDevice(deviceId); | ||
| 211 | + aclFinalize(); | ||
| 212 | + | ||
| 213 | + return 0; | ||
| 214 | +} | ||
| @@ -0,0 +1,11 @@ | |||
| 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 | +add_graph_plugin_sources() | ||
| @@ -0,0 +1,39 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file block_attention_residuals_grad_proto.h | ||
| 13 | + * \brief block_attention_residuals_grad | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef OPS_BUILT_IN_OP_PROTO_INC_BLOCK_ATTENTION_RESIDUALS_GRAD_H_ | ||
| 17 | +#define OPS_BUILT_IN_OP_PROTO_INC_BLOCK_ATTENTION_RESIDUALS_GRAD_H_ | ||
| 18 | + | ||
| 19 | +#include "graph/operator_reg.h" | ||
| 20 | + | ||
| 21 | +namespace ge { | ||
| 22 | + | ||
| 23 | +REG_OP(BlockAttentionResidualsGrad) | ||
| 24 | + .INPUT(partial_block, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
缺少资料 ![]() ![]() | |||
| 25 | + .INPUT(block_res, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 26 | + .INPUT(proj_weight, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 27 | + .INPUT(norm_weight, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 28 | + .INPUT(grad_hidden_states, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 29 | + .INPUT(inv_norm, TensorType({DT_FLOAT})) | ||
| 30 | + .INPUT(probs, TensorType({DT_FLOAT})) | ||
| 31 | + .OUTPUT(grad_partial_block, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 32 | + .OUTPUT(grad_block_res, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 33 | + .OUTPUT(grad_proj_weight, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 34 | + .OUTPUT(grad_norm_weight, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT})) | ||
| 35 | + .ATTR(valid_block_num, Int, 0) | ||
| 36 | + .OP_END_FACTORY_REG(BlockAttentionResidualsGrad) | ||
| 37 | +} // namespace ge | ||
| 38 | + | ||
| 39 | +#endif // OPS_BUILT_IN_OP_PROTO_INC_BLOCK_ATTENTION_RESIDUALS_GRAD_H_ | ||
| @@ -0,0 +1,37 @@ | |||
| 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 | + block_attention_residuals_grad_def.cpp | ||
| 14 | + ) | ||
| 15 | + if("${ASCEND_COMPUTE_UNIT}" STREQUAL "ascend950") | ||
| 16 | + add_ops_compile_options( | ||
| 17 | + OP_NAME BlockAttentionResidualsGrad | ||
| 18 | + COMPUTE_UNIT Ascend950PR_9599 | ||
| 19 | + OPTIONS --cce-auto-sync=off | ||
| 20 | + -mllvm | ||
| 21 | + -cce-aicore-dcci-before-kernel-end=false | ||
| 22 | + -Wno-deprecated-declarations | ||
| 23 | + -Werror | ||
| 24 | + ) | ||
| 25 | + else() | ||
| 26 | + add_ops_compile_options( | ||
| 27 | + OP_NAME BlockAttentionResidualsGrad | ||
| 28 | + OPTIONS --cce-auto-sync=on | ||
| 29 | + -Wno-deprecated-declarations | ||
| 30 | + -Werror | ||
| 31 | + ) | ||
| 32 | + endif() | ||
| 33 | +endif() | ||
| 34 | + | ||
| 35 | +if(NOT BUILD_OPS_RTY_KERNEL) | ||
| 36 | + add_modules_sources(OPTYPE block_attention_residuals_grad ACLNNTYPE aclnn_exclude) | ||
| 37 | +endif() | ||
| @@ -0,0 +1,101 @@ | |||
| 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 BlockAttentionResidualsGrad : public OpDef { | ||
| 15 | +public: | ||
| 16 | + explicit BlockAttentionResidualsGrad(const char *name) | ||
| 17 | + : OpDef(name) | ||
| 18 | + { | ||
| 19 | + this->Input("partial_block") | ||
| 20 | + .ParamType(REQUIRED) | ||
| 21 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 22 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 23 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
【review】自动转连续配置加上,补上 ![]() ![]() | |||
| 24 | + this->Input("block_res") | ||
| 25 | + .ParamType(REQUIRED) | ||
| 26 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 27 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 28 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 29 | + this->Input("proj_weight") | ||
| 30 | + .ParamType(REQUIRED) | ||
| 31 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 32 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 33 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 34 | + this->Input("norm_weight") | ||
| 35 | + .ParamType(REQUIRED) | ||
| 36 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 37 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 38 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 39 | + this->Input("grad_hidden_states") | ||
| 40 | + .ParamType(REQUIRED) | ||
| 41 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 42 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 43 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 44 | + this->Input("inv_norm") | ||
| 45 | + .ParamType(REQUIRED) | ||
| 46 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 47 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 48 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 49 | + this->Input("probs") | ||
| 50 | + .ParamType(REQUIRED) | ||
| 51 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 52 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 53 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 54 | + // Reserved attribute. It is exposed for interface compatibility and is not used by the current kernel. | ||
| 55 | + this->Attr("valid_block_num").AttrType(OPTIONAL).Int(0); | ||
| 56 | + this->Output("grad_partial_block") | ||
| 57 | + .ParamType(REQUIRED) | ||
| 58 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 59 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 60 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 61 | + this->Output("grad_block_res") | ||
| 62 | + .ParamType(REQUIRED) | ||
| 63 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 64 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 65 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 66 | + this->Output("grad_proj_weight") | ||
| 67 | + .ParamType(REQUIRED) | ||
| 68 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 69 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 70 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 71 | + this->Output("grad_norm_weight") | ||
| 72 | + .ParamType(REQUIRED) | ||
| 73 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT}) | ||
| 74 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 75 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 76 | + | ||
| 77 | + OpAICoreConfig aicoreConfigA2; | ||
| 78 | + aicoreConfigA2.DynamicCompileStaticFlag(true) | ||
| 79 | + .DynamicFormatFlag(false) | ||
| 80 | + .DynamicRankSupportFlag(true) | ||
| 81 | + .DynamicShapeSupportFlag(true) | ||
| 82 | + .NeedCheckSupportFlag(false) | ||
| 83 | + .PrecisionReduceFlag(true) | ||
| 84 | + .ExtendCfgInfo("opFile.value", "block_attention_residuals_grad"); // Matches the kernel entry file name. | ||
| 85 | + this->AICore().AddConfig("ascend910b", aicoreConfigA2); | ||
【review】aicoreConfigA2命令不规范,不要这么使用 ![]() ![]() | |||
| 86 | + this->AICore().AddConfig("ascend910_93", aicoreConfigA2); | ||
| 87 | + | ||
| 88 | + OpAICoreConfig configA5; | ||
| 89 | + configA5.DynamicCompileStaticFlag(true) | ||
| 90 | + .DynamicFormatFlag(false) | ||
| 91 | + .DynamicRankSupportFlag(true) | ||
| 92 | + .DynamicShapeSupportFlag(true) | ||
| 93 | + .NeedCheckSupportFlag(false) | ||
| 94 | + .PrecisionReduceFlag(true) | ||
【review】确认一下这个开关是不是一定要开 ![]() ![]() | |||
| 95 | + .ExtendCfgInfo("opFile.value", "block_attention_residuals_grad_apt"); // A5 regbase kernel entry. | ||
| 96 | + this->AICore().AddConfig("ascend950", configA5); | ||
| 97 | + } | ||
| 98 | +}; | ||
| 99 | + | ||
| 100 | +OP_ADD(BlockAttentionResidualsGrad); | ||
| 101 | +} // namespace ops | ||
| @@ -0,0 +1,140 @@ | |||
| 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_impl_registry.h" | ||
| 12 | +#include "log/log.h" | ||
| 13 | + | ||
| 14 | +using namespace ge; | ||
| 15 | + | ||
| 16 | +namespace ops { | ||
| 17 | +namespace { | ||
| 18 | +// Input tensor positions (matching the op def registration order). | ||
| 19 | +constexpr size_t INPUT_PARTIAL_BLOCK = 0; | ||
| 20 | +constexpr size_t INPUT_BLOCK_RES = 1; | ||
| 21 | +constexpr size_t INPUT_PROJ_WEIGHT = 2; | ||
| 22 | +constexpr size_t INPUT_NORM_WEIGHT = 3; | ||
| 23 | +constexpr size_t INPUT_GRAD_HIDDEN_STATES = 4; | ||
| 24 | +constexpr size_t INPUT_INV_NORM = 5; | ||
| 25 | +constexpr size_t INPUT_PROBS = 6; | ||
| 26 | + | ||
| 27 | +// Output tensor positions. | ||
| 28 | +constexpr size_t OUTPUT_GRAD_PARTIAL_BLOCK = 0; | ||
| 29 | +constexpr size_t OUTPUT_GRAD_BLOCK_RES = 1; | ||
| 30 | +constexpr size_t OUTPUT_GRAD_PROJ_WEIGHT = 2; | ||
| 31 | +constexpr size_t OUTPUT_GRAD_NORM_WEIGHT = 3; | ||
| 32 | + | ||
| 33 | +// Fixed tensor ranks of the op. | ||
| 34 | +constexpr size_t RANK_1D = 1; | ||
| 35 | +constexpr size_t RANK_2D = 2; | ||
| 36 | +constexpr size_t RANK_3D = 3; | ||
| 37 | + | ||
| 38 | +// Shape axis positions of the fixed layouts: | ||
| 39 | +// [B, H] partial_block / grad_hidden_states | ||
| 40 | +// [B, N, H] block_res | ||
| 41 | +// [1, H] proj_weight | ||
| 42 | +// [H] norm_weight | ||
| 43 | +// [B, N + 1] inv_norm / probs | ||
| 44 | +constexpr size_t DIM_BATCH = 0; | ||
| 45 | +constexpr size_t DIM_HIDDEN = 1; // [B, H] / [1, H] 的 H 轴 | ||
| 46 | +constexpr size_t DIM_BLOCK = 1; // [B, N, H] 的 N 轴;[B, N + 1] 的 N + 1 轴 | ||
| 47 | +constexpr size_t DIM_BLOCK_RES_HIDDEN = 2; | ||
| 48 | +constexpr size_t DIM_WEIGHT_ROW = 0; // proj_weight [1, H] 的固定 1 轴 | ||
| 49 | +constexpr size_t DIM_NORM_WEIGHT = 0; // norm_weight [H] 的唯一轴 | ||
| 50 | +} // namespace | ||
| 51 | + | ||
| 52 | +static bool CheckShapeBlockAttentionResidualsGrad(gert::InferShapeContext *context, int64_t &B, int64_t &N, int64_t &H) | ||
| 53 | +{ | ||
| 54 | + const gert::Shape *psShape = context->GetInputShape(INPUT_PARTIAL_BLOCK); | ||
| 55 | + const gert::Shape *brShape = context->GetInputShape(INPUT_BLOCK_RES); | ||
| 56 | + const gert::Shape *pwShape = context->GetInputShape(INPUT_PROJ_WEIGHT); | ||
| 57 | + const gert::Shape *nwShape = context->GetInputShape(INPUT_NORM_WEIGHT); | ||
| 58 | + const gert::Shape *gradHiddenStateShape = context->GetInputShape(INPUT_GRAD_HIDDEN_STATES); | ||
| 59 | + const gert::Shape *irShape = context->GetInputShape(INPUT_INV_NORM); | ||
| 60 | + const gert::Shape *pbShape = context->GetInputShape(INPUT_PROBS); | ||
【review】要增加shape为-1和-2场景推导 ![]() ![]() | |||
| 61 | + | ||
| 62 | + if (psShape->GetDimNum() != RANK_2D || brShape->GetDimNum() != RANK_3D || pwShape->GetDimNum() != RANK_2D || | ||
| 63 | + nwShape->GetDimNum() != RANK_1D || gradHiddenStateShape->GetDimNum() != RANK_2D || | ||
| 64 | + irShape->GetDimNum() != RANK_2D || pbShape->GetDimNum() != RANK_2D) { | ||
| 65 | + return false; | ||
【review】这里要增加日志打印 ![]() ![]() | |||
| 66 | + } | ||
| 67 | + | ||
| 68 | + B = psShape->GetDim(DIM_BATCH); | ||
| 69 | + H = psShape->GetDim(DIM_HIDDEN); | ||
| 70 | + N = brShape->GetDim(DIM_BLOCK); | ||
| 71 | + | ||
| 72 | + if (brShape->GetDim(DIM_BATCH) != B || gradHiddenStateShape->GetDim(DIM_BATCH) != B || | ||
| 73 | + irShape->GetDim(DIM_BATCH) != B || pbShape->GetDim(DIM_BATCH) != B) { | ||
| 74 | + return false; | ||
| 75 | + } | ||
| 76 | + if (brShape->GetDim(DIM_BLOCK_RES_HIDDEN) != H || pwShape->GetDim(DIM_WEIGHT_ROW) != 1 || | ||
| 77 | + pwShape->GetDim(DIM_HIDDEN) != H || nwShape->GetDim(DIM_NORM_WEIGHT) != H || | ||
| 78 | + gradHiddenStateShape->GetDim(DIM_HIDDEN) != H) { | ||
| 79 | + return false; | ||
| 80 | + } | ||
| 81 | + if (irShape->GetDim(DIM_BLOCK) != N + 1 || pbShape->GetDim(DIM_BLOCK) != N + 1) { | ||
| 82 | + return false; | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + return true; | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +static ge::graphStatus InferShapeBlockAttentionResidualsGrad(gert::InferShapeContext *context) | ||
| 89 | +{ | ||
| 90 | + int64_t B = 0, N = 0, H = 0; | ||
| 91 | + if (!CheckShapeBlockAttentionResidualsGrad(context, B, N, H)) { | ||
| 92 | + return GRAPH_FAILED; | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + // grad_partial_block [B, H] = partial_block | ||
| 96 | + context->GetOutputShape(OUTPUT_GRAD_PARTIAL_BLOCK)->SetDimNum(RANK_2D); | ||
| 97 | + context->GetOutputShape(OUTPUT_GRAD_PARTIAL_BLOCK)->SetDim(DIM_BATCH, B); | ||
| 98 | + context->GetOutputShape(OUTPUT_GRAD_PARTIAL_BLOCK)->SetDim(DIM_HIDDEN, H); | ||
| 99 | + | ||
| 100 | + // grad_block_res [B, N, H] = block_res | ||
| 101 | + context->GetOutputShape(OUTPUT_GRAD_BLOCK_RES)->SetDimNum(RANK_3D); | ||
| 102 | + context->GetOutputShape(OUTPUT_GRAD_BLOCK_RES)->SetDim(DIM_BATCH, B); | ||
| 103 | + context->GetOutputShape(OUTPUT_GRAD_BLOCK_RES)->SetDim(DIM_BLOCK, N); | ||
| 104 | + context->GetOutputShape(OUTPUT_GRAD_BLOCK_RES)->SetDim(DIM_BLOCK_RES_HIDDEN, H); | ||
| 105 | + | ||
| 106 | + // grad_proj_weight [H] = proj_weight | ||
| 107 | + context->GetOutputShape(OUTPUT_GRAD_PROJ_WEIGHT)->SetDimNum(RANK_2D); | ||
| 108 | + context->GetOutputShape(OUTPUT_GRAD_PROJ_WEIGHT)->SetDim(DIM_WEIGHT_ROW, 1); | ||
| 109 | + context->GetOutputShape(OUTPUT_GRAD_PROJ_WEIGHT)->SetDim(DIM_HIDDEN, H); | ||
| 110 | + | ||
| 111 | + // grad_norm_weight [H] = norm_weight | ||
| 112 | + context->GetOutputShape(OUTPUT_GRAD_NORM_WEIGHT)->SetDimNum(RANK_1D); | ||
| 113 | + context->GetOutputShape(OUTPUT_GRAD_NORM_WEIGHT)->SetDim(DIM_NORM_WEIGHT, H); | ||
| 114 | + | ||
| 115 | + return GRAPH_SUCCESS; | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +static ge::graphStatus InferDataTypeBlockAttentionResidualsGrad(gert::InferDataTypeContext *context) | ||
【review】增加输入之前的dtype校验 ![]() ![]() | |||
| 119 | +{ | ||
| 120 | + const auto invNormDtype = context->GetInputDataType(INPUT_INV_NORM); | ||
| 121 | + const auto probsDtype = context->GetInputDataType(INPUT_PROBS); | ||
| 122 | + if (invNormDtype != ge::DT_FLOAT || probsDtype != ge::DT_FLOAT) { | ||
| 123 | + OP_LOGE(context->GetNodeName(), "inv_norm and probs only support fp32, got %d and %d", | ||
| 124 | + static_cast<int>(invNormDtype), static_cast<int>(probsDtype)); | ||
| 125 | + return GRAPH_FAILED; | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + auto dtype = context->GetInputDataType(INPUT_PARTIAL_BLOCK); | ||
| 129 | + context->SetOutputDataType(OUTPUT_GRAD_PARTIAL_BLOCK, dtype); | ||
| 130 | + context->SetOutputDataType(OUTPUT_GRAD_BLOCK_RES, dtype); | ||
| 131 | + context->SetOutputDataType(OUTPUT_GRAD_PROJ_WEIGHT, dtype); | ||
| 132 | + context->SetOutputDataType(OUTPUT_GRAD_NORM_WEIGHT, dtype); | ||
| 133 | + | ||
| 134 | + return GRAPH_SUCCESS; | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +IMPL_OP_INFERSHAPE(BlockAttentionResidualsGrad) | ||
| 138 | + .InferShape(InferShapeBlockAttentionResidualsGrad) | ||
| 139 | + .InferDataType(InferDataTypeBlockAttentionResidualsGrad); | ||
| 140 | +} // namespace ops | ||
| @@ -0,0 +1,374 @@ | |||
| 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 <cstdio> | ||
| 12 | +#include "log/log.h" | ||
| 13 | +#include "register/op_impl_registry.h" | ||
| 14 | +#include "op_host/tiling_util.h" | ||
| 15 | +#include "op_host/tiling_templates_registry.h" | ||
| 16 | +#include "block_attention_residuals_grad_tiling.h" | ||
| 17 | +#include "platform/platform_info.h" | ||
| 18 | +#include "tiling/platform/platform_ascendc.h" | ||
| 19 | +#include "../op_kernel/block_attention_residuals_grad_tiling_key.h" | ||
| 20 | +namespace optiling { | ||
| 21 | +using namespace Ops::Transformer::OpTiling; | ||
| 22 | +constexpr uint32_t ALIGN_512B = 512; | ||
| 23 | +constexpr uint32_t ALIGN_256B = 256; | ||
| 24 | +constexpr uint32_t ALIGN_32B = 32; | ||
| 25 | +constexpr uint64_t UB_RESERVE_BYTES = 8UL * 1024UL; | ||
| 26 | +// FULL_H kernel 的 H 轴 buffer 至少预留 64 个元素(归约尾部清零需要)。 | ||
| 27 | +constexpr int64_t H_REDUCE_LANE_NUM = 64; | ||
| 28 | +// 各路径 Buffer 构成,与 kernel InitBuffer 逐项对应,避免 UB 估算公式散落魔鬼数字。 | ||
| 29 | +constexpr uint64_t A22_H_FP32_BUF_NUM = 6UL; | ||
| 30 | +constexpr uint64_t A22_FULL_H_META_BUF_NUM = 4UL; | ||
| 31 | +constexpr uint64_t A22_SPLIT_H_META_BUF_NUM = 6UL; | ||
| 32 | +constexpr uint64_t A35_FULL_H_FP32_BUF_NUM = 6UL; | ||
| 33 | +constexpr uint64_t A35_FULL_H_INPUT_BUF_NUM = 4UL; | ||
| 34 | +constexpr uint64_t A35_FULL_H_META_BUF_NUM = 4UL; | ||
| 35 | +constexpr uint64_t A35_SPLIT_H_FP32_BUF_NUM = 7UL; | ||
| 36 | +constexpr uint64_t A35_SPLIT_H_INPUT_BUF_NUM = 4UL; | ||
| 37 | +constexpr uint64_t A35_SPLIT_H_META_BUF_NUM = 6UL; | ||
| 38 | +constexpr uint64_t SCALAR_SLOT_NUM = 6UL; | ||
| 39 | +constexpr uint64_t SCALAR_ELEM_PER_SLOT = 8UL; | ||
| 40 | +constexpr uint64_t A35_H_INPUT_ALIGN_ELEMS = 16UL; | ||
| 41 | +constexpr int64_t FP32_ELEM_PER_32B = 8; | ||
| 42 | +constexpr int64_t FP16_ELEM_PER_32B = 16; | ||
| 43 | +constexpr int64_t MAX_NUM_BLOCKS = 128; | ||
| 44 | + | ||
| 45 | +static uint64_t AlignUp(uint64_t value, uint64_t alignment) | ||
| 46 | +{ | ||
| 47 | + return (value + alignment - 1UL) / alignment * alignment; | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +static uint64_t CalcArch22FullHUbBytes(int64_t H, int64_t totalBlocks, uint32_t dtypeBytes) | ||
| 51 | +{ | ||
| 52 | + const int64_t hBufElems = H > H_REDUCE_LANE_NUM ? H : H_REDUCE_LANE_NUM; | ||
| 53 | + const uint64_t hFloatBytes = AlignUp(static_cast<uint64_t>(hBufElems) * sizeof(float), ALIGN_32B); | ||
| 54 | + const uint64_t hInputBytes = AlignUp(static_cast<uint64_t>(hBufElems) * dtypeBytes, ALIGN_32B); | ||
| 55 | + const uint64_t metaBytes = AlignUp(static_cast<uint64_t>(totalBlocks) * sizeof(float), ALIGN_32B); | ||
| 56 | + return A22_H_FP32_BUF_NUM * hFloatBytes + hInputBytes + A22_FULL_H_META_BUF_NUM * metaBytes + ALIGN_32B; | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +// A2/A3 SPLIT_H 比 FULL_H 多两个 K 轴 Kahan 补偿 Buffer。 | ||
| 60 | +static uint64_t CalcArch22SplitHUbBytes(int64_t hiddenTileSize, int64_t totalBlocks, uint32_t dtypeBytes) | ||
| 61 | +{ | ||
| 62 | + const uint64_t hFloatBytes = AlignUp(static_cast<uint64_t>(hiddenTileSize) * sizeof(float), ALIGN_32B); | ||
| 63 | + const uint64_t hInputBytes = AlignUp(static_cast<uint64_t>(hiddenTileSize) * dtypeBytes, ALIGN_32B); | ||
| 64 | + const uint64_t metaBytes = AlignUp(static_cast<uint64_t>(totalBlocks) * sizeof(float), ALIGN_32B); | ||
| 65 | + return A22_H_FP32_BUF_NUM * hFloatBytes + hInputBytes + A22_SPLIT_H_META_BUF_NUM * metaBytes + ALIGN_32B; | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +// A5 FULL_H 用 6 个 H 轴 FP32 Buffer(gswAcc 直接 MTE3 写 Workspace)+ 4 个输入 Buffer | ||
| 69 | +// + 4 个 K 轴 Buffer;FP32 按 256B、输入按 16 元素对齐。 | ||
| 70 | +static uint64_t CalcArch35FullHUbBytes(int64_t H, int64_t totalBlocks, uint32_t dtypeBytes) | ||
| 71 | +{ | ||
| 72 | + const uint64_t hFloatBytes = AlignUp(static_cast<uint64_t>(H) * sizeof(float), ALIGN_256B); | ||
| 73 | + const uint64_t hInputBytes = AlignUp(static_cast<uint64_t>(H), A35_H_INPUT_ALIGN_ELEMS) * dtypeBytes; | ||
| 74 | + const uint64_t metaBytes = AlignUp(static_cast<uint64_t>(totalBlocks) * sizeof(float), ALIGN_256B); | ||
| 75 | + constexpr uint64_t scalarBytes = SCALAR_SLOT_NUM * SCALAR_ELEM_PER_SLOT * sizeof(float); | ||
| 76 | + return A35_FULL_H_FP32_BUF_NUM * hFloatBytes + A35_FULL_H_INPUT_BUF_NUM * hInputBytes + | ||
| 77 | + A35_FULL_H_META_BUF_NUM * metaBytes + scalarBytes; | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +static int64_t CalcArch22HiddenTileSize(uint64_t ubSize, int64_t H, int64_t totalBlocks, uint32_t dtypeBytes) | ||
| 81 | +{ | ||
| 82 | + // 为运行时和编译器未体现在显式 InitBuffer 中的开销预留安全空间。 | ||
| 83 | + if (ubSize <= UB_RESERVE_BYTES) { | ||
| 84 | + return 0; | ||
| 85 | + } | ||
| 86 | + const uint64_t availableUb = ubSize - UB_RESERVE_BYTES; | ||
| 87 | + | ||
| 88 | + // K 轴 Buffer 必须整段驻留 UB,不能随 H 切分缩小。 | ||
| 89 | + const uint64_t fixedBytes = | ||
| 90 | + A22_SPLIT_H_META_BUF_NUM * AlignUp(static_cast<uint64_t>(totalBlocks) * sizeof(float), ALIGN_32B) + ALIGN_32B; | ||
| 91 | + if (availableUb <= fixedBytes) { | ||
| 92 | + return 0; | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + // 每个 H 元素占 6 个 FP32 Buffer + 1 个 T 输入/输出 Buffer,仅这部分随 H 切分缩小。 | ||
| 96 | + const uint64_t bytesPerH = A22_H_FP32_BUF_NUM * sizeof(float) + dtypeBytes; | ||
| 97 | + | ||
| 98 | + // FP32 每 32 字节包含 8 个元素,FP16/BF16 每 32 字节包含 16 个元素。 | ||
| 99 | + const int64_t alignElements = dtypeBytes == sizeof(float) ? FP32_ELEM_PER_32B : FP16_ELEM_PER_32B; | ||
| 100 | + | ||
| 101 | + // 先根据线性 UB 模型计算能够容纳的最大对齐 H tile: | ||
| 102 | + // fixedBytes + maxTile * bytesPerH <= availableUb。 | ||
| 103 | + int64_t maxTile = static_cast<int64_t>((availableUb - fixedBytes) / bytesPerH); | ||
| 104 | + maxTile = maxTile / alignElements * alignElements; | ||
| 105 | + | ||
| 106 | + // 用独立对齐的精确模型回退校验,防止 Host Tiling 超 Kernel UB。 | ||
| 107 | + while (maxTile > 0 && CalcArch22SplitHUbBytes(maxTile, totalBlocks, dtypeBytes) > availableUb) { | ||
| 108 | + maxTile -= alignElements; | ||
| 109 | + } | ||
| 110 | + if (maxTile <= 0) { | ||
| 111 | + return 0; | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + // 先求最少 tile 数再均分 H,避免尾块过小。 | ||
| 115 | + const int64_t initialTileNum = (H + maxTile - 1) / maxTile; | ||
| 116 | + int64_t tileSize = (H + initialTileNum - 1) / initialTileNum; | ||
| 117 | + tileSize = (tileSize + alignElements - 1) / alignElements * alignElements; | ||
| 118 | + | ||
| 119 | + // 均分后若超 maxTile,回退到已校验的 maxTile。 | ||
| 120 | + return tileSize <= maxTile ? tileSize : maxTile; | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +// A5 SPLIT_H 沿用 FULL_H tile Buffer 构成:7 个 H 轴 FP32 Buffer(含 wkspOutQue)、 | ||
| 124 | +// 4 个输入 Buffer、6 个 K 轴 FP32 Buffer + 标量槽。 | ||
| 125 | +static uint64_t CalcArch35SplitHUbBytes(int64_t hiddenTileSize, int64_t totalBlocks, uint32_t dtypeBytes) | ||
| 126 | +{ | ||
| 127 | + const uint64_t hFloatBytes = AlignUp(static_cast<uint64_t>(hiddenTileSize) * sizeof(float), ALIGN_256B); | ||
| 128 | + const uint64_t hInputBytes = AlignUp(static_cast<uint64_t>(hiddenTileSize) * dtypeBytes, ALIGN_256B); | ||
| 129 | + const uint64_t metaBytes = AlignUp(static_cast<uint64_t>(totalBlocks) * sizeof(float), ALIGN_256B); | ||
| 130 | + constexpr uint64_t scalarBytes = SCALAR_SLOT_NUM * SCALAR_ELEM_PER_SLOT * sizeof(float); | ||
| 131 | + return A35_SPLIT_H_FP32_BUF_NUM * hFloatBytes + A35_SPLIT_H_INPUT_BUF_NUM * hInputBytes + | ||
| 132 | + A35_SPLIT_H_META_BUF_NUM * metaBytes + scalarBytes; | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +static int64_t CalcArch35HiddenTileSize(uint64_t ubSize, int64_t H, int64_t totalBlocks, uint32_t dtypeBytes) | ||
| 136 | +{ | ||
| 137 | + if (ubSize <= UB_RESERVE_BYTES) { | ||
| 138 | + return 0; | ||
| 139 | + } | ||
| 140 | + const uint64_t availableUb = ubSize - UB_RESERVE_BYTES; | ||
| 141 | + constexpr uint64_t scalarBytes = SCALAR_SLOT_NUM * SCALAR_ELEM_PER_SLOT * sizeof(float); | ||
| 142 | + const uint64_t fixedBytes = | ||
| 143 | + A35_SPLIT_H_META_BUF_NUM * AlignUp(static_cast<uint64_t>(totalBlocks) * sizeof(float), ALIGN_256B) + | ||
| 144 | + scalarBytes; | ||
| 145 | + if (availableUb <= fixedBytes) { | ||
| 146 | + return 0; | ||
| 147 | + } | ||
| 148 | + | ||
| 149 | + const uint64_t bytesPerH = A35_SPLIT_H_FP32_BUF_NUM * sizeof(float) + A35_SPLIT_H_INPUT_BUF_NUM * dtypeBytes; | ||
| 150 | + // tile 同时满足 FP32 和原始 dtype Buffer 的 256B 对齐。 | ||
| 151 | + // FP16/BF16 为 128 元素,FP32 为 64 元素。 | ||
| 152 | + const int64_t alignElements = static_cast<int64_t>(ALIGN_256B / dtypeBytes); | ||
| 153 | + int64_t maxTile = static_cast<int64_t>((availableUb - fixedBytes) / bytesPerH); | ||
| 154 | + maxTile = maxTile / alignElements * alignElements; | ||
| 155 | + while (maxTile > 0 && CalcArch35SplitHUbBytes(maxTile, totalBlocks, dtypeBytes) > availableUb) { | ||
| 156 | + maxTile -= alignElements; | ||
| 157 | + } | ||
| 158 | + if (maxTile <= 0) { | ||
| 159 | + return 0; | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + const int64_t tileNum = (H + maxTile - 1) / maxTile; | ||
| 163 | + int64_t tileSize = (H + tileNum - 1) / tileNum; | ||
| 164 | + tileSize = (tileSize + alignElements - 1) / alignElements * alignElements; | ||
| 165 | + return tileSize <= maxTile ? tileSize : maxTile; | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +struct HiddenTilingResult { | ||
| 169 | + const char *archName; | ||
| 170 | + uint64_t requiredFull; | ||
| 171 | + int64_t hiddenTileSize; | ||
| 172 | + bool splitH; | ||
| 173 | +}; | ||
| 174 | + | ||
| 175 | +// 架构差异集中在这一个函数中。TilingFunc 只消费最终计算结果。 | ||
| 176 | +static HiddenTilingResult CalcHiddenTiling(const gert::TilingContext *ctx, uint64_t ub, int64_t H, int64_t totalBlocks, | ||
| 177 | + uint32_t dtypeBytes) | ||
| 178 | +{ | ||
| 179 | + const uint64_t availableUb = ub > UB_RESERVE_BYTES ? ub - UB_RESERVE_BYTES : 0; | ||
| 180 | + HiddenTilingResult result{}; | ||
| 181 | + if (IsRegbaseSocVersion(ctx)) { | ||
| 182 | + result.archName = "arch35"; | ||
| 183 | + result.requiredFull = CalcArch35FullHUbBytes(H, totalBlocks, dtypeBytes); | ||
| 184 | + result.splitH = result.requiredFull > availableUb; | ||
| 185 | + result.hiddenTileSize = H; | ||
| 186 | + if (result.splitH) { | ||
| 187 | + result.hiddenTileSize = CalcArch35HiddenTileSize(ub, H, totalBlocks, dtypeBytes); | ||
| 188 | + } | ||
| 189 | + } else { | ||
| 190 | + result.archName = "arch22"; | ||
| 191 | + result.requiredFull = CalcArch22FullHUbBytes(H, totalBlocks, dtypeBytes); | ||
| 192 | + result.splitH = result.requiredFull > availableUb; | ||
| 193 | + result.hiddenTileSize = H; | ||
| 194 | + if (result.splitH) { | ||
| 195 | + result.hiddenTileSize = CalcArch22HiddenTileSize(ub, H, totalBlocks, dtypeBytes); | ||
| 196 | + } | ||
| 197 | + } | ||
| 198 | + return result; | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +static void PrintInfo(gert::TilingContext *ctx, BlockAttentionResidualsGradTilingData &td) | ||
| 202 | +{ | ||
| 203 | + OP_LOGD(ctx, | ||
| 204 | + " B=%ld N=%ld N1=%ld H=%ld hTile=%ld hTileNum=%ld cores=%ld perWksp=%lu " | ||
| 205 | + "gradScoresOff=%lu varianceScaleOff=%lu", | ||
| 206 | + td.get_batchSize(), td.get_numBlocks(), td.get_totalBlocks(), td.get_hiddenSize(), td.get_hiddenTileSize(), | ||
| 207 | + td.get_hiddenTileNum(), td.get_coreNum(), td.get_perCoreWkspBytes(), td.get_gradScoresWkspOff(), | ||
| 208 | + td.get_varianceScaleWkspOff()); | ||
| 209 | +} | ||
| 210 | + | ||
| 211 | +static ge::graphStatus GetPlatformInfo(gert::TilingContext *ctx, uint64_t &ub, uint32_t &coreNum) | ||
| 212 | +{ | ||
| 213 | + auto ci = ctx->GetCompileInfo<BlockAttentionResidualsGradCompileInfo>(); | ||
| 214 | + coreNum = ci->coreNum; | ||
| 215 | + ub = ci->ubSize; | ||
| 216 | + return ge::GRAPH_SUCCESS; | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +static ge::graphStatus Check(gert::TilingContext *ctx) | ||
【review】这个函数名字改成有实际意义的名字 ![]() ![]() | |||
| 220 | +{ | ||
| 221 | + auto ps = EnsureNotScalar(ctx->GetInputShape(0)->GetStorageShape()); | ||
| 222 | + auto br = EnsureNotScalar(ctx->GetInputShape(1)->GetStorageShape()); | ||
| 223 | + OP_CHECK_IF(ps.GetDimNum() != 2, OP_LOGE(ctx, "partial_block must be 2D"), return ge::GRAPH_FAILED); | ||
| 224 | + OP_CHECK_IF(br.GetDimNum() != 3, OP_LOGE(ctx, "block_res must be 3D"), return ge::GRAPH_FAILED); | ||
| 225 | + | ||
| 226 | + int64_t B = ps.GetDim(0); | ||
| 227 | + int64_t H = ps.GetDim(1); | ||
| 228 | + int64_t Bb = br.GetDim(0); | ||
| 229 | + int64_t N = br.GetDim(1); | ||
| 230 | + int64_t Hb = br.GetDim(2); | ||
| 231 | + OP_CHECK_IF(B <= 0 || N < 0 || H <= 0, OP_LOGE(ctx, "B and H must be positive and N must be non-negative"), | ||
| 232 | + return ge::GRAPH_FAILED); | ||
| 233 | + OP_CHECK_IF(B != Bb || H != Hb, OP_LOGE(ctx, "shape mismatch"), return ge::GRAPH_FAILED); | ||
| 234 | + // K 轴 meta Buffer 按 totalBlocks = N + 1 驻留 UB,N > MAX_NUM_BLOCKS 时超出设计上限。 | ||
| 235 | + OP_CHECK_IF(N > MAX_NUM_BLOCKS, OP_LOGE(ctx, "numBlocks N must be <= %ld, got %ld", MAX_NUM_BLOCKS, N), | ||
| 236 | + return ge::GRAPH_FAILED); | ||
| 237 | + | ||
| 238 | + OP_LOGD(ctx, "shape: B=%ld N=%ld H=%ld", B, N, H); | ||
| 239 | + return ge::GRAPH_SUCCESS; | ||
| 240 | +} | ||
| 241 | + | ||
| 242 | +// 返回算子支持的输入类型字节数;0 表示不支持的类型。 | ||
| 243 | +static uint32_t GetSupportedDtypeBytes(ge::DataType dataType) | ||
| 244 | +{ | ||
| 245 | + switch (dataType) { | ||
| 246 | + case ge::DT_FLOAT16: | ||
| 247 | + case ge::DT_BF16: | ||
| 248 | + return sizeof(uint16_t); | ||
【review】这个uint16改成float16 ![]() ![]() | |||
| 249 | + case ge::DT_FLOAT: | ||
| 250 | + return sizeof(float); | ||
| 251 | + default: | ||
| 252 | + return 0; | ||
| 253 | + } | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +static ge::graphStatus DoTiling(gert::TilingContext *ctx, int64_t B, int64_t N, int64_t H, uint32_t coreNum, | ||
| 257 | + int64_t hiddenTileSize, bool splitH) | ||
| 258 | +{ | ||
| 259 | + // number of blocks (including the prefix-sum block) | ||
| 260 | + int64_t N1 = N + 1; | ||
| 261 | + | ||
| 262 | + // per-core workspace: H floats, 512B-aligned for DMA efficiency | ||
| 263 | + uint64_t perWksp = (static_cast<uint64_t>(H) * sizeof(float) + ALIGN_512B - 1) / ALIGN_512B * ALIGN_512B; | ||
| 264 | + | ||
| 265 | + BlockAttentionResidualsGradTilingData td; | ||
| 266 | + td.set_batchSize(B); | ||
| 267 | + td.set_numBlocks(N); | ||
| 268 | + td.set_totalBlocks(N1); | ||
| 269 | + td.set_hiddenSize(H); | ||
| 270 | + td.set_hiddenTileSize(hiddenTileSize); | ||
| 271 | + td.set_hiddenTileNum((H + hiddenTileSize - 1) / hiddenTileSize); | ||
| 272 | + // per-core batch range and workspace offset are computed in kernel via GetBlockIdx() | ||
| 273 | + td.set_coreBatchStart(0); | ||
| 274 | + td.set_coreBatchEnd(B); | ||
| 275 | + td.set_coreBatchCount(0); | ||
| 276 | + td.set_gradScoreWeightWkspOff(0); | ||
| 277 | + td.set_coreNum(static_cast<int64_t>(coreNum)); | ||
| 278 | + td.set_perCoreWkspBytes(perWksp); | ||
| 279 | + const uint64_t metaWkspBytes = | ||
| 280 | + AlignUp(static_cast<uint64_t>(B) * static_cast<uint64_t>(N1) * sizeof(float), ALIGN_512B); | ||
| 281 | + const uint64_t gradScoresWkspOff = splitH ? perWksp * static_cast<uint64_t>(coreNum) : 0UL; | ||
| 282 | + td.set_gradScoresWkspOff(gradScoresWkspOff); | ||
| 283 | + td.set_varianceScaleWkspOff(splitH ? gradScoresWkspOff + metaWkspBytes : 0UL); | ||
| 284 | + | ||
| 285 | + // Hard SyncAll requires all launched cores to start together in batch mode. | ||
| 286 | + ctx->SetScheduleMode(1); | ||
| 287 | + ctx->SetBlockDim(coreNum); | ||
| 288 | + td.SaveToBuffer(ctx->GetRawTilingData()->GetData(), ctx->GetRawTilingData()->GetCapacity()); | ||
| 289 | + ctx->GetRawTilingData()->SetDataSize(td.GetDataSize()); | ||
| 290 | + | ||
| 291 | + PrintInfo(ctx, td); | ||
| 292 | + return ge::GRAPH_SUCCESS; | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +static ge::graphStatus CalcWorkspaceSize(gert::TilingContext *ctx, bool splitH) | ||
| 296 | +{ | ||
| 297 | + int64_t H = EnsureNotScalar(ctx->GetInputShape(0)->GetStorageShape()).GetDim(1); | ||
| 298 | + int64_t B = EnsureNotScalar(ctx->GetInputShape(0)->GetStorageShape()).GetDim(0); | ||
| 299 | + int64_t N = EnsureNotScalar(ctx->GetInputShape(1)->GetStorageShape()).GetDim(1); | ||
| 300 | + auto ci = ctx->GetCompileInfo<BlockAttentionResidualsGradCompileInfo>(); | ||
| 301 | + uint64_t per = (static_cast<uint64_t>(H) * sizeof(float) + ALIGN_512B - 1) / ALIGN_512B * ALIGN_512B; | ||
| 302 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(ctx->GetPlatformInfo()); | ||
| 303 | + uint64_t sysWorkspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); | ||
| 304 | + size_t *ws = ctx->GetWorkspaceSizes(1); | ||
| 305 | + OP_CHECK_NULL_WITH_CONTEXT(ctx, ws); | ||
| 306 | + uint64_t userWorkspaceSize = per * static_cast<uint64_t>(ci->coreNum); | ||
| 307 | + if (splitH) { | ||
| 308 | + const uint64_t metaWkspBytes = | ||
| 309 | + AlignUp(static_cast<uint64_t>(B) * static_cast<uint64_t>(N + 1) * sizeof(float), ALIGN_512B); | ||
| 310 | + // 分别保存 gradScore[B, K] 和 varianceScale[B, K]。 | ||
| 311 | + userWorkspaceSize += 2UL * metaWkspBytes; | ||
| 312 | + } | ||
| 313 | + ws[0] = static_cast<size_t>(userWorkspaceSize + sysWorkspaceSize); | ||
| 314 | + return ge::GRAPH_SUCCESS; | ||
| 315 | +} | ||
| 316 | + | ||
| 317 | +static ge::graphStatus TilingFunc(gert::TilingContext *ctx) | ||
【review】ctx这个命名改成context ![]() ![]() | |||
| 318 | +{ | ||
| 319 | + uint64_t ub = 0; | ||
| 320 | + uint32_t coreNum = 0; | ||
| 321 | + OP_CHECK_IF(GetPlatformInfo(ctx, ub, coreNum) != ge::GRAPH_SUCCESS, OP_LOGE(ctx, "get platform info failed"), | ||
| 322 | + return ge::GRAPH_FAILED); | ||
| 323 | + OP_CHECK_IF(Check(ctx) != ge::GRAPH_SUCCESS, OP_LOGE(ctx, "check shape failed"), return ge::GRAPH_FAILED); | ||
| 324 | + | ||
| 325 | + auto inputDesc = ctx->GetInputDesc(0); | ||
| 326 | + OP_CHECK_NULL_WITH_CONTEXT(ctx, inputDesc); | ||
| 327 | + const ge::DataType dataType = inputDesc->GetDataType(); | ||
| 328 | + const uint32_t dtypeBytes = GetSupportedDtypeBytes(dataType); | ||
【review】将这2行整改成checkDtype() ![]() ![]() | |||
| 329 | + OP_CHECK_IF(dtypeBytes == 0, OP_LOGE(ctx, "unsupported dtype: %d", static_cast<int32_t>(dataType)), | ||
| 330 | + return ge::GRAPH_FAILED); | ||
| 331 | + auto ps = EnsureNotScalar(ctx->GetInputShape(0)->GetStorageShape()); | ||
| 332 | + auto br = EnsureNotScalar(ctx->GetInputShape(1)->GetStorageShape()); | ||
| 333 | + const int64_t H = ps.GetDim(1); | ||
| 334 | + const int64_t totalBlocks = br.GetDim(1) + 1; | ||
| 335 | + const uint64_t availableUb = ub > UB_RESERVE_BYTES ? ub - UB_RESERVE_BYTES : 0; | ||
| 336 | + const HiddenTilingResult hiddenTiling = CalcHiddenTiling(ctx, ub, H, totalBlocks, dtypeBytes); | ||
| 337 | + OP_CHECK_IF(hiddenTiling.hiddenTileSize <= 0, OP_LOGE(ctx, "failed to calculate a valid H tile"), | ||
| 338 | + return ge::GRAPH_FAILED); | ||
| 339 | + | ||
| 340 | + const uint64_t tilingKey = | ||
| 341 | + hiddenTiling.splitH ? GET_TPL_TILING_KEY(TPL_H_MODE_SPLIT) : GET_TPL_TILING_KEY(TPL_H_MODE_FULL); | ||
| 342 | + ctx->SetTilingKey(tilingKey); | ||
| 343 | + OP_LOGD(ctx, "tiling path: path=%s arch=%s H=%ld K=%ld dtypeBytes=%u requiredFull=%lu available=%lu hTile=%ld", | ||
| 344 | + hiddenTiling.splitH ? "SPLIT_H" : "FULL_H", hiddenTiling.archName, H, totalBlocks, dtypeBytes, | ||
| 345 | + hiddenTiling.requiredFull, availableUb, hiddenTiling.hiddenTileSize); | ||
| 346 | + | ||
| 347 | + OP_CHECK_IF(DoTiling(ctx, ps.GetDim(0), br.GetDim(1), H, coreNum, hiddenTiling.hiddenTileSize, | ||
| 348 | + hiddenTiling.splitH) != ge::GRAPH_SUCCESS, | ||
| 349 | + OP_LOGE(ctx, "tiling failed"), return ge::GRAPH_FAILED); | ||
| 350 | + OP_CHECK_IF(CalcWorkspaceSize(ctx, hiddenTiling.splitH) != ge::GRAPH_SUCCESS, OP_LOGE(ctx, "workspace failed"), | ||
| 351 | + return ge::GRAPH_FAILED); | ||
| 352 | + return ge::GRAPH_SUCCESS; | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +static ge::graphStatus Parse(gert::TilingParseContext *ctx) | ||
| 356 | +{ | ||
| 357 | + auto ci = ctx->GetCompiledInfo<BlockAttentionResidualsGradCompileInfo>(); | ||
| 358 | + OP_CHECK_NULL_WITH_CONTEXT(ctx, ci); | ||
| 359 | + | ||
| 360 | + auto plat = platform_ascendc::PlatformAscendC(ctx->GetPlatformInfo()); | ||
| 361 | + uint32_t aivNum = plat.GetCoreNumAiv(); | ||
| 362 | + ci->coreNum = aivNum; | ||
| 363 | + OP_CHECK_IF(ci->coreNum == 0, OP_LOGE(ctx, "coreNum is 0"), return ge::GRAPH_FAILED); | ||
| 364 | + plat.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ci->ubSize); | ||
| 365 | + OP_CHECK_IF(ci->ubSize == 0, OP_LOGE(ctx, "ubSize is 0"), return ge::GRAPH_FAILED); | ||
| 366 | + | ||
| 367 | + OP_LOGD(ctx, "parse: ub=%luB coreNum=%u", ci->ubSize, ci->coreNum); | ||
| 368 | + return ge::GRAPH_SUCCESS; | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +IMPL_OP_OPTILING(BlockAttentionResidualsGrad) | ||
| 372 | + .Tiling(TilingFunc) | ||
【review】这个命名要加上算子名字 ![]() ![]() | |||
| 373 | + .TilingParse<BlockAttentionResidualsGradCompileInfo>(Parse); | ||
【review】这个parse命名要加上算子名字 ![]() ![]() | |||
| 374 | +} // namespace optiling | ||
| @@ -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 | + | ||
| 11 | +#ifndef _BLOCK_ATTENTION_RESIDUALS_GRAD_TILING_DATA_H_ | ||
| 12 | +#define _BLOCK_ATTENTION_RESIDUALS_GRAD_TILING_DATA_H_ | ||
| 13 | +#include "register/op_impl_registry.h" | ||
| 14 | +#include "register/tilingdata_base.h" | ||
| 15 | +namespace optiling { | ||
| 16 | +BEGIN_TILING_DATA_DEF(BlockAttentionResidualsGradTilingData) | ||
| 17 | +TILING_DATA_FIELD_DEF(int64_t, batchSize); | ||
| 18 | +TILING_DATA_FIELD_DEF(int64_t, numBlocks); | ||
| 19 | +TILING_DATA_FIELD_DEF(int64_t, totalBlocks); | ||
| 20 | +TILING_DATA_FIELD_DEF(int64_t, hiddenSize); | ||
| 21 | +TILING_DATA_FIELD_DEF(int64_t, hiddenTileSize); | ||
| 22 | +TILING_DATA_FIELD_DEF(int64_t, hiddenTileNum); | ||
| 23 | +TILING_DATA_FIELD_DEF(int64_t, coreBatchStart); | ||
| 24 | +TILING_DATA_FIELD_DEF(int64_t, coreBatchEnd); | ||
| 25 | +TILING_DATA_FIELD_DEF(int64_t, coreBatchCount); | ||
| 26 | +TILING_DATA_FIELD_DEF(uint64_t, gradScoreWeightWkspOff); | ||
| 27 | +TILING_DATA_FIELD_DEF(int64_t, coreNum); | ||
| 28 | +TILING_DATA_FIELD_DEF(uint64_t, perCoreWkspBytes); | ||
| 29 | +TILING_DATA_FIELD_DEF(uint64_t, gradScoresWkspOff); | ||
| 30 | +TILING_DATA_FIELD_DEF(uint64_t, varianceScaleWkspOff); | ||
| 31 | +END_TILING_DATA_DEF; | ||
| 32 | +REGISTER_TILING_DATA_CLASS(BlockAttentionResidualsGrad, BlockAttentionResidualsGradTilingData); | ||
| 33 | +} // namespace optiling | ||
| 34 | +struct BlockAttentionResidualsGradCompileInfo { | ||
| 35 | + uint64_t ubSize = 0; | ||
| 36 | + uint32_t coreNum = 0; | ||
| 37 | +}; | ||
| 38 | +#endif | ||
| @@ -0,0 +1,30 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file block_attention_residuals_grad_tiling_key.h | ||
| 13 | + * \brief block_attention_residuals_grad tiling key declare | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef __BLOCK_ATTENTION_RESIDUALS_GRAD_TILING_KEY_H__ | ||
| 17 | +#define __BLOCK_ATTENTION_RESIDUALS_GRAD_TILING_KEY_H__ | ||
| 18 | + | ||
| 19 | +#include "ascendc/host_api/tiling/template_argument.h" | ||
| 20 | + | ||
| 21 | +#define TPL_H_MODE_FULL 0 | ||
| 22 | +#define TPL_H_MODE_SPLIT 1 | ||
| 23 | + | ||
| 24 | +ASCENDC_TPL_ARGS_DECL(BlockAttentionResidualsGrad, | ||
| 25 | + ASCENDC_TPL_UINT_DECL(hMode, 2, ASCENDC_TPL_UI_LIST, TPL_H_MODE_FULL, TPL_H_MODE_SPLIT)); | ||
| 26 | + | ||
| 27 | +ASCENDC_TPL_SEL(ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(hMode, ASCENDC_TPL_UI_LIST, TPL_H_MODE_FULL, | ||
| 28 | + TPL_H_MODE_SPLIT))); | ||
| 29 | + | ||
| 30 | +#endif | ||
| @@ -0,0 +1,82 @@ | |||
| 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 "aclnn_block_attention_residuals_grad.h" | ||
| 12 | +#include "block_attention_residuals_grad.h" | ||
| 13 | +#include "aclnn_kernels/common/op_error_check.h" | ||
| 14 | +#include "opdev/make_op_executor.h" | ||
| 15 | +#include "opdev/op_executor.h" | ||
| 16 | +#include "aclnn/aclnn_base.h" | ||
| 17 | +#include "opdev/op_log.h" | ||
| 18 | +#include "opdev/op_dfx.h" | ||
| 19 | + | ||
| 20 | +#include "aclnn_kernels/contiguous.h" | ||
| 21 | + | ||
| 22 | +using namespace op; | ||
| 23 | + | ||
| 24 | +#ifdef __cplusplus | ||
| 25 | +extern "C" { | ||
| 26 | +#endif | ||
| 27 | + | ||
| 28 | +aclnnStatus aclnnBlockAttentionResidualsGradGetWorkspaceSize( | ||
| 29 | + const aclTensor *partialBlock, const aclTensor *blockRes, const aclTensor *projWeight, const aclTensor *normWeight, | ||
| 30 | + const aclTensor *gradHiddenStates, const aclTensor *invNorm, const aclTensor *probs, int64_t validBlockNum, | ||
| 31 | + const aclTensor *gradPartialBlock, const aclTensor *gradBlockRes, const aclTensor *gradProjWeight, | ||
| 32 | + const aclTensor *gradNormWeight, uint64_t *workspaceSize, aclOpExecutor **executor) | ||
| 33 | +{ | ||
| 34 | + L2_DFX_PHASE_1( | ||
| 35 | + aclnnBlockAttentionResidualsGrad, | ||
| 36 | + DFX_IN(partialBlock, blockRes, projWeight, normWeight, gradHiddenStates, invNorm, probs, validBlockNum), | ||
| 37 | + DFX_OUT(gradPartialBlock, gradBlockRes, gradProjWeight, gradNormWeight)); | ||
| 38 | + auto uniqueExecutor = CREATE_EXECUTOR(); | ||
| 39 | + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); | ||
| 40 | + | ||
| 41 | + // 与正向算子对齐:输入统一转 Contiguous 后再下发 | ||
| 42 | + auto partialBlock_ = l0op::Contiguous(partialBlock, uniqueExecutor.get()); | ||
| 43 | + CHECK_RET(partialBlock_ != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 44 | + auto blockRes_ = l0op::Contiguous(blockRes, uniqueExecutor.get()); | ||
| 45 | + CHECK_RET(blockRes_ != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 46 | + auto projWeight_ = l0op::Contiguous(projWeight, uniqueExecutor.get()); | ||
| 47 | + CHECK_RET(projWeight_ != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 48 | + auto normWeight_ = l0op::Contiguous(normWeight, uniqueExecutor.get()); | ||
| 49 | + CHECK_RET(normWeight_ != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 50 | + auto gradHiddenState_ = l0op::Contiguous(gradHiddenStates, uniqueExecutor.get()); | ||
| 51 | + CHECK_RET(gradHiddenState_ != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 52 | + auto invNorm_ = l0op::Contiguous(invNorm, uniqueExecutor.get()); | ||
| 53 | + CHECK_RET(invNorm_ != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 54 | + auto probs_ = l0op::Contiguous(probs, uniqueExecutor.get()); | ||
| 55 | + CHECK_RET(probs_ != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 56 | + | ||
| 57 | + auto output = l0op::BlockAttentionResidualsGrad( | ||
| 58 | + partialBlock_, blockRes_, projWeight_, normWeight_, gradHiddenState_, invNorm_, probs_, validBlockNum, | ||
| 59 | + const_cast<aclTensor *>(gradPartialBlock), const_cast<aclTensor *>(gradBlockRes), | ||
| 60 | + const_cast<aclTensor *>(gradProjWeight), const_cast<aclTensor *>(gradNormWeight), uniqueExecutor.get()); | ||
| 61 | + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 62 | + | ||
| 63 | + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); | ||
| 64 | + uniqueExecutor.ReleaseTo(executor); | ||
| 65 | + | ||
| 66 | + return ACLNN_SUCCESS; | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +aclnnStatus aclnnBlockAttentionResidualsGrad(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, | ||
| 70 | + aclrtStream stream) | ||
| 71 | +{ | ||
| 72 | + auto ret = CommonOpExecutorRun(workspace, workspaceSize, executor, stream); | ||
| 73 | + if (ret != 0) { | ||
| 74 | + OP_LOGE(ACLNN_ERR_INNER, "BlockAttentionResidualsGrad launch failed, ret = %d.", ret); | ||
| 75 | + return ret; | ||
| 76 | + } | ||
| 77 | + return ret; | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +#ifdef __cplusplus | ||
| 81 | +} | ||
| 82 | +#endif | ||
| @@ -0,0 +1,76 @@ | |||
| 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_BLOCK_ATTENTION_RESIDUALS_GRAD_H | ||
| 12 | +#define OP_API_INC_ACLNN_BLOCK_ATTENTION_RESIDUALS_GRAD_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 aclnnBlockAttentionResidualsGrad的第一段接口,根据具体的计算流程,计算workspace大小。 | ||
| 23 | + * @domain aclnn_ops_infer | ||
| 24 | + * | ||
| 25 | + * @param [in] partialBlock: 表示公式中的partialBlock,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 26 | + * | ||
| 27 | + * @param [in] blockRes: 表示公式中的blockRes,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 28 | + * @param [in] | ||
| 29 | + * projWeight: 表示公式中的projWeight,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 30 | + * @param [in] | ||
| 31 | + * normWeight: 表示公式中的normWeight,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 32 | + * @param [in] | ||
| 33 | + * gradHiddenStates: | ||
| 34 | + * 表示上游梯度gradHiddenStates,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 35 | + * @param | ||
| 36 | + * [in] invNorm: 表示逆RMS归一化系数invNorm,数据类型支持FLOAT32,数据格式支持ND。 | ||
| 37 | + * @param [in] probs: | ||
| 38 | + * 表示softmax概率probs,数据类型支持FLOAT32,数据格式支持ND。 | ||
| 39 | + * @param [in] validBlockNum: | ||
| 40 | + * 表示预留属性,当前内核未使用,默认值为0。 | ||
| 41 | + * @param [out] gradPartialBlock: | ||
| 42 | + * 表示partialBlock的梯度,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 43 | + * @param [out] gradBlockRes: | ||
| 44 | + * 表示blockRes的梯度,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 45 | + * @param [out] gradProjWeight: | ||
| 46 | + * 表示projWeight的梯度,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 47 | + * @param [out] gradNormWeight: | ||
| 48 | + * 表示normWeight的梯度,数据类型支持FLOAT16、BFLOAT16、FLOAT32,数据格式支持ND。 | ||
| 49 | + * @param [out] workspaceSize: | ||
| 50 | + * 返回用户需要在npu device侧申请的workspace大小。 | ||
| 51 | + * @param [out] executor: 返回op执行器,包含算子计算流程。 | ||
| 52 | + * @return aclnnStatus: 返回状态码。 | ||
| 53 | + */ | ||
| 54 | +ACLNN_API aclnnStatus aclnnBlockAttentionResidualsGradGetWorkspaceSize( | ||
【review】新增算子需要适配以下文件,请check. ![]() ![]() | |||
| 55 | + const aclTensor *partialBlock, const aclTensor *blockRes, const aclTensor *projWeight, const aclTensor *normWeight, | ||
| 56 | + const aclTensor *gradHiddenStates, const aclTensor *invNorm, const aclTensor *probs, int64_t validBlockNum, | ||
| 57 | + const aclTensor *gradPartialBlock, const aclTensor *gradBlockRes, const aclTensor *gradProjWeight, | ||
| 58 | + const aclTensor *gradNormWeight, uint64_t *workspaceSize, aclOpExecutor **executor); | ||
| 59 | + | ||
| 60 | +/** | ||
| 61 | + * @brief aclnnBlockAttentionResidualsGrad的第二段接口,用于执行计算。 | ||
| 62 | + * @param [in] workspace: 在npu device侧申请的workspace内存起址。 | ||
| 63 | + * @param [in] workspaceSize: 在npu | ||
| 64 | + * device侧申请的workspace大小,由第一段接口aclnnBlockAttentionResidualsGradGetWorkspaceSize获取。 | ||
| 65 | + * @param [in] executor: op执行器,包含了算子计算流程。 | ||
| 66 | + * @param [in] stream: acl stream流。 | ||
| 67 | + * @return aclnnStatus: 返回状态码。 | ||
| 68 | + */ | ||
| 69 | +ACLNN_API aclnnStatus aclnnBlockAttentionResidualsGrad(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, | ||
【review】 aclnn接口的h文件需要增加注释:可以参考gmm算子的接口文件。 ![]() ![]() | |||
| 70 | + aclrtStream stream); | ||
| 71 | + | ||
| 72 | +#ifdef __cplusplus | ||
| 73 | +} | ||
| 74 | +#endif | ||
| 75 | + | ||
| 76 | +#endif // OP_API_INC_ACLNN_BLOCK_ATTENTION_RESIDUALS_GRAD_H | ||
| @@ -0,0 +1,56 @@ | |||
| 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 "block_attention_residuals_grad.h" | ||
| 12 | +#include "opdev/make_op_executor.h" | ||
| 13 | +#include "opdev/op_def.h" | ||
| 14 | +#include "opdev/op_dfx.h" | ||
| 15 | +#include "opdev/op_executor.h" | ||
| 16 | +#include "opdev/op_log.h" | ||
| 17 | + | ||
| 18 | +using namespace op; | ||
| 19 | + | ||
| 20 | +namespace l0op { | ||
| 21 | + | ||
| 22 | +OP_TYPE_REGISTER(BlockAttentionResidualsGrad); | ||
| 23 | + | ||
| 24 | +const aclTensor *BlockAttentionResidualsGrad(const aclTensor *partialBlock, const aclTensor *blockRes, | ||
| 25 | + const aclTensor *projWeight, const aclTensor *normWeight, | ||
| 26 | + const aclTensor *gradHiddenStates, const aclTensor *invNorm, | ||
| 27 | + const aclTensor *probs, int64_t validBlockNum, aclTensor *gradPartialBlock, | ||
| 28 | + aclTensor *gradBlockRes, aclTensor *gradProjWeight, | ||
| 29 | + aclTensor *gradNormWeight, aclOpExecutor *executor) | ||
| 30 | +{ | ||
| 31 | + L0_DFX(BlockAttentionResidualsGrad, partialBlock, blockRes, projWeight, normWeight, gradHiddenStates, invNorm, | ||
| 32 | + probs, validBlockNum, gradPartialBlock, gradBlockRes, gradProjWeight, gradNormWeight); | ||
| 33 | + | ||
| 34 | + auto ret = | ||
| 35 | + INFER_SHAPE(BlockAttentionResidualsGrad, | ||
| 36 | + OP_INPUT(partialBlock, blockRes, projWeight, normWeight, gradHiddenStates, invNorm, probs), | ||
| 37 | + OP_OUTPUT(gradPartialBlock, gradBlockRes, gradProjWeight, gradNormWeight), OP_ATTR(validBlockNum)); | ||
| 38 | + if (ret != ACLNN_SUCCESS) { | ||
| 39 | + OP_LOGE(ACLNN_ERR_INNER_STATIC_WORKSPACE_INVALID, "BlockAttentionResidualsGrad INFER_SHAPE failed."); | ||
| 40 | + return nullptr; | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + auto launcherRet = ADD_TO_LAUNCHER_LIST_AICORE( | ||
| 44 | + BlockAttentionResidualsGrad, | ||
| 45 | + OP_INPUT(partialBlock, blockRes, projWeight, normWeight, gradHiddenStates, invNorm, probs), | ||
| 46 | + OP_OUTPUT(gradPartialBlock, gradBlockRes, gradProjWeight, gradNormWeight), OP_ATTR(validBlockNum)); | ||
| 47 | + if (launcherRet != ACLNN_SUCCESS) { | ||
| 48 | + OP_LOGE(ACLNN_ERR_INNER_STATIC_WORKSPACE_INVALID, | ||
| 49 | + "BlockAttentionResidualsGrad ADD_TO_LAUNCHER_LIST_AICORE failed."); | ||
| 50 | + return nullptr; | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + return gradPartialBlock; | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +} // namespace l0op | ||
| @@ -0,0 +1,25 @@ | |||
| 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_BLOCK_ATTENTION_RESIDUALS_GRAD_H_ | ||
| 12 | +#define OP_API_INC_LEVEL0_BLOCK_ATTENTION_RESIDUALS_GRAD_H_ | ||
| 13 | + | ||
| 14 | +#include "opdev/op_executor.h" | ||
| 15 | + | ||
| 16 | +namespace l0op { | ||
| 17 | +const aclTensor *BlockAttentionResidualsGrad(const aclTensor *partialBlock, const aclTensor *blockRes, | ||
| 18 | + const aclTensor *projWeight, const aclTensor *normWeight, | ||
| 19 | + const aclTensor *gradHiddenStates, const aclTensor *invNorm, | ||
| 20 | + const aclTensor *probs, int64_t validBlockNum, aclTensor *gradPartialBlock, | ||
| 21 | + aclTensor *gradBlockRes, aclTensor *gradProjWeight, | ||
| 22 | + aclTensor *gradNormWeight, aclOpExecutor *executor); | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +#endif // OP_API_INC_LEVEL0_BLOCK_ATTENTION_RESIDUALS_GRAD_H_ | ||
| @@ -0,0 +1,699 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file arch22/block_attention_residuals_grad.h | ||
| 13 | + * \brief block_attention_residuals_grad kernel: B-axis split, outer B, inner N, H intact. | ||
| 14 | + * | ||
| 15 | + * Loop (per core): | ||
| 16 | + * for batch in coreBatchStart_ .. coreBatchEnd_ (outer, B split) | ||
| 17 | + * CopyInToken + PrecomputeGradProbs + SoftmaxBackwardN1 | ||
| 18 | + * for blk in 0 .. N+1 (inner, all blocks) | ||
| 19 | + * ComputeGradV + CopyOutToken | ||
| 20 | + * WriteGradScoreWeight (partial sum to workspace) | ||
| 21 | + * SyncAll | ||
| 22 | + * core 0: ReduceAndWriteWeights (cross-core sum, write grad_norm_weight / grad_proj_weight) | ||
| 23 | + */ | ||
| 24 | + | ||
| 25 | +#ifndef BLOCK_ATTENTION_RESIDUALS_GRAD_H | ||
| 26 | +#define BLOCK_ATTENTION_RESIDUALS_GRAD_H | ||
| 27 | + | ||
| 28 | +#include "kernel_operator.h" | ||
| 29 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 30 | +#include "../block_attention_residuals_grad_tiling_data.h" | ||
| 31 | +#include "../block_attention_residuals_grad_tiling_key.h" | ||
| 32 | + | ||
| 33 | +namespace NsBlockAttentionResidualsGrad { | ||
| 34 | +using namespace AscendC; | ||
| 35 | + | ||
| 36 | +// ---- half-interval reduce,参照 attn_res_fwd/op_kernel/arch22/reduce_common.h ---- | ||
| 37 | +// src 就地 half-interval fold 后 Kahan 补偿求和归约到独立 dst[0];无 sharedTmpBuffer。 | ||
| 38 | +constexpr uint32_t ARG_ELEM_PER_REP_FP32 = 64; | ||
| 39 | +constexpr int32_t ARG_HALF_INTERVAL = 2; | ||
| 40 | +constexpr int32_t ARG_INDEX_TWO = 2; | ||
| 41 | +constexpr int32_t ARG_INDEX_FOUR = 4; | ||
| 42 | +constexpr int32_t ARG_INDEX_EIGHT = 8; | ||
| 43 | +constexpr int32_t ARG_INDEX_SIXTEEN = 16; | ||
| 44 | +// K 轴元数据按 32B 对齐搬入 UB。 | ||
| 45 | +constexpr uint32_t META_ALIGN_BYTES = 32U; | ||
| 46 | + | ||
| 47 | +__aicore__ inline int32_t ArgFindPowerTwo(int32_t n) | ||
| 48 | +{ | ||
| 49 | + n |= n >> 1; | ||
| 50 | + n |= n >> ARG_INDEX_TWO; | ||
| 51 | + n |= n >> ARG_INDEX_FOUR; | ||
| 52 | + n |= n >> ARG_INDEX_EIGHT; | ||
| 53 | + n |= n >> ARG_INDEX_SIXTEEN; | ||
| 54 | + return (n + 1) >> 1; | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +__aicore__ inline float ReduceSumKahan(const LocalTensor<float> &srcLocal, int32_t count); | ||
| 58 | + | ||
| 59 | +__aicore__ inline void ReduceSumHalfInterval(const LocalTensor<float> &dstLocal, const LocalTensor<float> &srcLocal, | ||
| 60 | + int32_t count) | ||
| 61 | +{ | ||
| 62 | + if (likely(count > static_cast<int32_t>(ARG_ELEM_PER_REP_FP32))) { | ||
| 63 | + int32_t bodyCount = ArgFindPowerTwo(count); | ||
| 64 | + int32_t tailCount = count - bodyCount; | ||
| 65 | + if (tailCount > 0) { | ||
| 66 | + Add(srcLocal, srcLocal, srcLocal[bodyCount], tailCount); | ||
| 67 | + PipeBarrier<PIPE_V>(); | ||
| 68 | + } | ||
| 69 | + while (bodyCount > static_cast<int32_t>(ARG_ELEM_PER_REP_FP32)) { | ||
| 70 | + bodyCount = bodyCount / ARG_HALF_INTERVAL; | ||
| 71 | + Add(srcLocal, srcLocal, srcLocal[bodyCount], bodyCount); | ||
| 72 | + PipeBarrier<PIPE_V>(); | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | + // 最后对折半后的部分和做 Kahan 补偿求和,减少 FP32 归约舍入。 | ||
| 76 | + const int32_t reduceCount = | ||
| 77 | + (count > static_cast<int32_t>(ARG_ELEM_PER_REP_FP32)) ? static_cast<int32_t>(ARG_ELEM_PER_REP_FP32) : count; | ||
| 78 | + PipeBarrier<PIPE_V>(); | ||
| 79 | + dstLocal.SetValue(0, ReduceSumKahan(srcLocal, reduceCount)); | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +// Kahan 补偿求和:H 较小(count<64)时逐标量累加,减少 FP32 归约的累积舍入。 | ||
| 83 | +// 调用方负责在向量写 src 之后、GetValue 之前做必要的同步。 | ||
| 84 | +__aicore__ inline float ReduceSumKahan(const LocalTensor<float> &srcLocal, int32_t count) | ||
| 85 | +{ | ||
| 86 | + float sum = 0.0f; | ||
| 87 | + float comp = 0.0f; | ||
| 88 | + for (int32_t i = 0; i < count; i++) { | ||
| 89 | + float y = srcLocal.GetValue(i) - comp; | ||
| 90 | + float t = sum + y; | ||
| 91 | + comp = (t - sum) - y; | ||
| 92 | + sum = t; | ||
| 93 | + } | ||
| 94 | + return sum; | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +template <typename T> | ||
| 98 | +__aicore__ inline void KahanSumUpdate(LocalTensor<T> &inputTensor, LocalTensor<T> sumTensorList[2], const int32_t len, | ||
| 99 | + int32_t &outPos) | ||
| 100 | +{ | ||



原文:## 接口说明
修改建议:参考其他readme文档,修改接口说明为调用说明,采用表格形式 https://gitcode.com/cann/ops-transformer/blob/master/mhc/mhc_post_backward/README.md