| @@ -243,7 +243,8 @@ | |||
| 243 | | [aclnnForeachTan](../../foreach/foreach_tan/docs/aclnnForeachTan.md) | 对输入张量列表的每个张量进行正切函数运算。 | 默认确定性实现 | 默认确定性实现 | | 243 | | [aclnnForeachTan](../../foreach/foreach_tan/docs/aclnnForeachTan.md) | 对输入张量列表的每个张量进行正切函数运算。 | 默认确定性实现 | 默认确定性实现 | |
| 244 | | [aclnnForeachTanh](../../foreach/foreach_tanh/docs/aclnnForeachTanh.md) | 对输入张量列表的每个张量进行双曲正切函数运算。 | 默认确定性实现 | 默认确定性实现 | | 244 | | [aclnnForeachTanh](../../foreach/foreach_tanh/docs/aclnnForeachTanh.md) | 对输入张量列表的每个张量进行双曲正切函数运算。 | 默认确定性实现 | 默认确定性实现 | |
| 245 | | [aclnnForeachZeroInplace](../../foreach/foreach_zero_inplace/docs/aclnnForeachZeroInplace.md) | 原地更新输入张量列表,输入张量列表的每个张量置为0。 | 默认确定性实现 | 默认确定性实现 | | 245 | | [aclnnForeachZeroInplace](../../foreach/foreach_zero_inplace/docs/aclnnForeachZeroInplace.md) | 原地更新输入张量列表,输入张量列表的每个张量置为0。 | 默认确定性实现 | 默认确定性实现 | |
| 246 | -| [aclnnFusedSgd](../../optim/fused_adamw/docs/aclnnFusedAdamw.md) | 实现fusedadamw算子。将传统 adamw 更新过程中原本分散的多个细粒度操作(如梯度缩放、权重衰减、动量更新、参数赋值等)融合为单个NPU Kernel执行。 | 默认确定性实现 | 默认确定性实现 | | 246 | +| [aclnnFusedAdam](../../optim/fused_adam/docs/aclnnFusedAdam.md) | 实现Adam优化器功能,支持多组参数列表(TensorList)一次调用完成Adam优化器功能。 | - | 默认确定性实现 | |
| 247 | +| [aclnnFusedAdamw](../../optim/fused_adamw/docs/aclnnFusedAdamw.md) | 实现fusedadamw算子。将传统 adamw 更新过程中原本分散的多个细粒度操作(如梯度缩放、权重衰减、动量更新、参数赋值等)融合为单个NPU Kernel执行。 | 默认确定性实现 | 默认确定性实现 | | ||
| 247 | | [aclnnFusedCrossEntropyLossWithMaxSum](../../loss/fused_cross_entropy_loss_with_max_sum/docs/aclnnFusedCrossEntropyLossWithMaxSum.md) | 词汇表并行场景下交叉熵计算模块的一部分,解决超大规模词汇表下的显存和计算效率问题,当前部分为计算loss与softMax的结果。 | 默认确定性实现 | 默认确定性实现 | | 248 | | [aclnnFusedCrossEntropyLossWithMaxSum](../../loss/fused_cross_entropy_loss_with_max_sum/docs/aclnnFusedCrossEntropyLossWithMaxSum.md) | 词汇表并行场景下交叉熵计算模块的一部分,解决超大规模词汇表下的显存和计算效率问题,当前部分为计算loss与softMax的结果。 | 默认确定性实现 | 默认确定性实现 | |
| 248 | | [aclnnFusedLinearOnlineMaxSum](../../matmul/fused_linear_online_max_sum/docs/aclnnFusedLinearOnlineMaxSum.md) | 功能等价Megatron的matmul与fused\_vocab\_parallel\_cross\_entropy的实现,支持vocabulary\_size维度切卡融合matmul与cross-entropy loss。 | 默认确定性实现 | - | | 249 | | [aclnnFusedLinearOnlineMaxSum](../../matmul/fused_linear_online_max_sum/docs/aclnnFusedLinearOnlineMaxSum.md) | 功能等价Megatron的matmul与fused\_vocab\_parallel\_cross\_entropy的实现,支持vocabulary\_size维度切卡融合matmul与cross-entropy loss。 | 默认确定性实现 | - | |
| 249 | | [aclnnFusedLinearCrossEntropyLossGrad](../../matmul/fused_linear_cross_entropy_loss_grad/docs/aclnnFusedLinearCrossEntropyLossGrad.md) | 是词汇表并行场景下交叉熵损失计算模块中的一部分,解决超大规模词汇表下的显存和计算效率问题,当前部分为梯度计算实现,用于计算叶子节点`input`和`weight`的梯度。 | 默认确定性实现 | - | | 250 | | [aclnnFusedLinearCrossEntropyLossGrad](../../matmul/fused_linear_cross_entropy_loss_grad/docs/aclnnFusedLinearCrossEntropyLossGrad.md) | 是词汇表并行场景下交叉熵损失计算模块中的一部分,解决超大规模词汇表下的显存和计算效率问题,当前部分为梯度计算实现,用于计算叶子节点`input`和`weight`的梯度。 | 默认确定性实现 | - | |
| @@ -4418,6 +4418,16 @@ | |||
| 4418 | <td>AI Core</td> | 4418 | <td>AI Core</td> |
| 4419 | <td>实现输入为tensorlist的adamw融合优化器功能。</td> | 4419 | <td>实现输入为tensorlist的adamw融合优化器功能。</td> |
| 4420 | </tr> | 4420 | </tr> |
| 4421 | + <tr> | ||
| 4422 | + <td>optim</td> | ||
| 4423 | + <td><a href="../../optim/fused_adam/README.md">fused_adam</a></td> | ||
| 4424 | + <td>✓</td> | ||
| 4425 | + <td>✓</td> | ||
| 4426 | + <td>✓</td> | ||
| 4427 | + <td>✗</td> | ||
| 4428 | + <td>AI Core</td> | ||
| 4429 | + <td>实现输入为tensorlist的adam融合优化器功能。</td> | ||
| 4430 | + </tr> | ||
| 4421 | <tr> | 4431 | <tr> |
| 4422 | <td>pooling</td> | 4432 | <td>pooling</td> |
| 4423 | <td><a href="../../pooling/adaptive_avg_pool3d/README.md">adaptive_avg_pool3d</a></td> | 4433 | <td><a href="../../pooling/adaptive_avg_pool3d/README.md">adaptive_avg_pool3d</a></td> |
| @@ -0,0 +1,12 @@ | |||
| 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 | +message(STATUS "=== Debug: start fused_adam.CMakeLists.txt ") | ||
| 12 | +add_modules_sources(HOSTNAME ${OPHOST_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR} OPTYPE fused_adam ACLNNTYPE aclnn_exclude) | ||
| @@ -0,0 +1,200 @@ | |||
| 1 | +# FusedAdam | ||
| 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 | +- **算子功能**: | ||
| 17 | + | ||
| 18 | +实现Adam优化器功能,支持多组参数列表(TensorList)一次调用完成Adam优化器功能。 | ||
| 19 | + | ||
| 20 | +- **计算公式**: | ||
| 21 | + | ||
| 22 | +$$ | ||
| 23 | +\begin{aligned} | ||
| 24 | +&t=t+1 \\ | ||
| 25 | + | ||
| 26 | +&\tilde{g}_t = \begin{cases} | ||
| 27 | +g_t / s & s \neq \text{None} \\ | ||
| 28 | +g_t & \text{otherwise} | ||
| 29 | +\end{cases} \\ | ||
| 30 | + | ||
| 31 | +&g_{t+1} = \tilde{g}_t \\ | ||
| 32 | + | ||
| 33 | +&\hat{g}_t = \begin{cases} | ||
| 34 | +-\tilde{g}_t & \text{maximize} \\ | ||
| 35 | +\tilde{g}_t & \text{otherwise} | ||
| 36 | +\end{cases} \\ | ||
| 37 | + | ||
| 38 | +&\bar{g}_t = \hat{g}_t + \lambda \cdot \theta_t \\ | ||
| 39 | + | ||
| 40 | +&m_t=\beta_1 m_{t-1} + (1-\beta_1) \bar{g}_t\\ | ||
| 41 | + | ||
| 42 | +&v_t=\beta_2 v_{t-1} + (1-\beta_2) \bar{g}_t^2\\ | ||
| 43 | + | ||
| 44 | +&max\_v_t= \begin{cases} \max(v_t,max\_v_{t-1}) & \text{amsgrad} \\ | ||
| 45 | +max\_v_{t-1} & \text{otherwise} | ||
| 46 | +\end{cases} \\ | ||
| 47 | + | ||
| 48 | +&\hat{m}_t=\frac{m_t}{1-\beta_1^t}\\ | ||
| 49 | + | ||
| 50 | +&\hat{v}_t= \begin{cases} \frac{max\_v_t}{1-\beta_2^t} & \text{amsgrad} \\ | ||
| 51 | +\frac{v_t}{1-\beta_2^t} & \text{otherwise} | ||
| 52 | +\end{cases} \\ | ||
| 53 | + | ||
| 54 | +&\theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{\hat{v}_t}+\epsilon} \hat{m}_t \\ | ||
| 55 | +\end{aligned} | ||
| 56 | +$$ | ||
| 57 | + | ||
| 58 | +## 参数说明 | ||
| 59 | + | ||
| 60 | +<table style="undefined;table-layout: fixed; width: 1080px"><colgroup> | ||
| 61 | +<col style="width: 155px"> | ||
| 62 | +<col style="width: 162px"> | ||
| 63 | +<col style="width: 380px"> | ||
| 64 | +<col style="width: 276px"> | ||
| 65 | +<col style="width: 107px"> | ||
| 66 | +</colgroup> | ||
| 67 | +<thead> | ||
| 68 | + <tr> | ||
| 69 | + <th>参数名</th> | ||
| 70 | + <th>输入/输出/属性</th> | ||
| 71 | + <th>描述</th> | ||
| 72 | + <th>数据类型</th> | ||
| 73 | + <th>数据格式</th> | ||
| 74 | + </tr></thead> | ||
| 75 | +<tbody> | ||
| 76 | + <tr> | ||
| 77 | + <td>paramsRef(aclTensorList*)</td> | ||
| 78 | + <td>输入/输出</td> | ||
| 79 | + <td><ul><li>不支持空Tensor。</li><li>待计算的权重列表,公式中的θ。</li></ul></td> | ||
| 80 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 81 | + <td>ND</td> | ||
| 82 | + </tr> | ||
| 83 | + <tr> | ||
| 84 | + <td>gradsRef(aclTensorList*)</td> | ||
| 85 | + <td>输入/输出</td> | ||
| 86 | + <td><ul><li>不支持空Tensor。</li><li>梯度数据列表,公式中的g<sub>t</sub>,仅在gradScale输入非空的时候会更新梯度。</li></ul></td> | ||
| 87 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 88 | + <td>ND</td> | ||
| 89 | + </tr> | ||
| 90 | + <tr> | ||
| 91 | + <td>expAvgsRef(aclTensorList*)</td> | ||
| 92 | + <td>输入/输出</td> | ||
| 93 | + <td><ul><li>不支持空Tensor。</li><li>一阶动量列表,公式中的m。</li></ul></td> | ||
| 94 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 95 | + <td>ND</td> | ||
| 96 | + </tr> | ||
| 97 | + <tr> | ||
| 98 | + <td>expAvgSqsRef(aclTensorList*)</td> | ||
| 99 | + <td>输入/输出</td> | ||
| 100 | + <td><ul><li>不支持空Tensor。</li><li>二阶动量列表,公式中的v,不能为负数。</li></ul></td> | ||
| 101 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 102 | + <td>ND</td> | ||
| 103 | + </tr> | ||
| 104 | + <tr> | ||
| 105 | + <td>maxExpAvgSqsRef(aclTensorList*)</td> | ||
| 106 | + <td>输入/输出</td> | ||
| 107 | + <td><ul><li>不支持空Tensor。</li><li>保存最大二阶矩列表,与更新后的expAvgSqsRef比较后取最大值输出。</li><li>此参数在amsgrad参数为true时必选,在amsgrad参数为false时可选。</li></ul></td> | ||
| 108 | + <td>FLOAT16、BFLOAT16、FLOAT32</td> | ||
| 109 | + <td>ND</td> | ||
| 110 | + </tr> | ||
| 111 | + <tr> | ||
| 112 | + <td>stateSteps(aclTensorList*)</td> | ||
| 113 | + <td>输入</td> | ||
| 114 | + <td><ul><li>不支持空Tensor。</li><li>迭代次数列表,公式中的t,需要大于0。</li></ul></td> | ||
| 115 | + <td>INT64、FLOAT32</td> | ||
| 116 | + <td>ND</td> | ||
| 117 | + </tr> | ||
| 118 | + <tr> | ||
| 119 | + <td>gradScaleOptional(aclTensor*)</td> | ||
| 120 | + <td>输入</td> | ||
| 121 | + <td>可选输入,梯度缩放因数s。当gradScaleOptional非空时,会据此更新并输出梯度(覆盖原有梯度)。</td> | ||
| 122 | + <td>FLOAT</td> | ||
| 123 | + <td>ND</td> | ||
| 124 | + </tr> | ||
| 125 | + <tr> | ||
| 126 | + <td>foundInfOptional(aclTensor*)</td> | ||
| 127 | + <td>输入</td> | ||
| 128 | + <td>可选输入,标识是否出现Inf/NaN。当foundInfOptional等于1时停止更新。</td> | ||
| 129 | + <td>FLOAT</td> | ||
| 130 | + <td>ND</td> | ||
| 131 | + </tr> | ||
| 132 | + <tr> | ||
| 133 | + <td>lr(double)</td> | ||
| 134 | + <td>属性</td> | ||
| 135 | + <td>学习率,公式中的η。</td> | ||
| 136 | + <td>DOUBLE</td> | ||
| 137 | + <td>-</td> | ||
| 138 | + </tr> | ||
| 139 | + <tr> | ||
| 140 | + <td>beta1(double)</td> | ||
| 141 | + <td>属性</td> | ||
| 142 | + <td>β<sub>1</sub>参数。</td> | ||
| 143 | + <td>DOUBLE</td> | ||
| 144 | + <td>-</td> | ||
| 145 | + </tr> | ||
| 146 | + <tr> | ||
| 147 | + <td>beta2(double)</td> | ||
| 148 | + <td>属性</td> | ||
| 149 | + <td>β<sub>2</sub>参数。</td> | ||
| 150 | + <td>DOUBLE</td> | ||
| 151 | + <td>-</td> | ||
| 152 | + </tr> | ||
| 153 | + <tr> | ||
| 154 | + <td>weightDecay(double)</td> | ||
| 155 | + <td>属性</td> | ||
| 156 | + <td>权重衰减系数,公式中的λ。</td> | ||
| 157 | + <td>DOUBLE</td> | ||
| 158 | + <td>-</td> | ||
| 159 | + </tr> | ||
| 160 | + <tr> | ||
| 161 | + <td>eps(double)</td> | ||
| 162 | + <td>属性</td> | ||
| 163 | + <td>防止除数为0。</td> | ||
| 164 | + <td>DOUBLE</td> | ||
| 165 | + <td>-</td> | ||
| 166 | + </tr> | ||
| 167 | + <tr> | ||
| 168 | + <td>amsgrad(bool)</td> | ||
| 169 | + <td>属性</td> | ||
| 170 | + <td>是否使用算法的AMSGrad变量。</td> | ||
| 171 | + <td>BOOL</td> | ||
| 172 | + <td>-</td> | ||
| 173 | + </tr> | ||
| 174 | + <tr> | ||
| 175 | + <td>maximize(bool)</td> | ||
| 176 | + <td>属性</td> | ||
| 177 | + <td>是否最大化参数。</td> | ||
| 178 | + <td>BOOL</td> | ||
| 179 | + <td>-</td> | ||
| 180 | + </tr> | ||
| 181 | +</tbody></table> | ||
| 182 | + | ||
| 183 | +## 约束说明 | ||
| 184 | + | ||
| 185 | +- 输入paramsRef、gradsRef、expAvgsRef、expAvgSqsRef这些tensorList中每个tensor不得为空,数据类型必须一致,且数据类型仅支持FLOAT16、BFLOAT16、FLOAT32。 | ||
| 186 | + | ||
| 187 | +- 输入tensorList中paramsRef、gradsRef、expAvgsRef、expAvgSqsRef中,tensor个数必须保持一致,且下标相同的tensor的shape必须保持一致。 | ||
| 188 | + | ||
| 189 | +- stateSteps类型为tensorList,支持INT64、FLOAT32,其tensor个数必须和paramsRef、gradsRef、expAvgsRef、expAvgSqsRef、maxExpAvgSqsRef一致。每个tensor元素个数至少为1,如果元素个数大于1则取第0个元素的值作为stateSteps的值。 | ||
| 190 | + | ||
| 191 | +- amsgrad为false时,maxExpAvgSqsRef可为空;amsgrad为true时,maxExpAvgSqsRef必选tensor数量,每个tensor的shape和dtype必须与paramsRef、gradsRef、expAvgsRef、expAvgSqsRef一致。 | ||
| 192 | + | ||
| 193 | +- 确定性计算: | ||
| 194 | + - aclnnFusedAdam默认确定性实现。 | ||
| 195 | + | ||
| 196 | +## 调用说明 | ||
| 197 | + | ||
| 198 | +| 调用方式 | 样例代码 | 说明 | | ||
| 199 | +| --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ||
| 200 | +| aclnn接口 | [test_aclnn_fused_adam](./examples/arch35/test_aclnn_fused_adam.cpp) | 通过[aclnnFusedAdam](docs/aclnnFusedAdam.md)接口方式调用FusedAdam算子。 | | ||
| @@ -0,0 +1,671 @@ | |||
| 1 | +# aclnnFusedAdam | ||
| 2 | + | ||
| 3 | +[📄 查看源码](https://gitcode.com/cann/ops-nn/tree/master/optim/fused_adam) | ||
| 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 | +- 接口功能:实现Adam优化器功能,支持多组参数列表(TensorList)一次调用完成Adam优化器功能。 | ||
| 29 | + | ||
| 30 | +- 计算公式: | ||
| 31 | + | ||
| 32 | +$$ | ||
| 33 | +\begin{aligned} | ||
| 34 | +&t=t+1 \\ | ||
| 35 | + | ||
| 36 | +&\tilde{g}_t = \begin{cases} | ||
| 37 | +g_t / s & s \neq \text{None} \\ | ||
| 38 | +g_t & \text{otherwise} | ||
| 39 | +\end{cases} \\ | ||
| 40 | + | ||
| 41 | +&g_{t+1} = \tilde{g}_t \\ | ||
| 42 | + | ||
| 43 | +&\hat{g}_t = \begin{cases} | ||
| 44 | +-\tilde{g}_t & \text{maximize} \\ | ||
| 45 | +\tilde{g}_t & \text{otherwise} | ||
| 46 | +\end{cases} \\ | ||
| 47 | + | ||
| 48 | +&\bar{g}_t = \hat{g}_t + \lambda \cdot \theta_t \\ | ||
| 49 | + | ||
| 50 | +&m_t=\beta_1 m_{t-1} + (1-\beta_1) \bar{g}_t\\ | ||
| 51 | + | ||
| 52 | +&v_t=\beta_2 v_{t-1} + (1-\beta_2) \bar{g}_t^2\\ | ||
| 53 | + | ||
| 54 | +&max\_v_t= \begin{cases} \max(v_t,max\_v_{t-1}) & \text{amsgrad} \\ | ||
| 55 | +max\_v_{t-1} & \text{otherwise} | ||
| 56 | +\end{cases} \\ | ||
| 57 | + | ||
| 58 | +&\hat{m}_t=\frac{m_t}{1-\beta_1^t}\\ | ||
| 59 | + | ||
| 60 | +&\hat{v}_t= \begin{cases} \frac{max\_v_t}{1-\beta_2^t} & \text{amsgrad} \\ | ||
| 61 | +\frac{v_t}{1-\beta_2^t} & \text{otherwise} | ||
| 62 | +\end{cases} \\ | ||
| 63 | + | ||
| 64 | +&\theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{\hat{v}_t}+\epsilon} \hat{m}_t \\ | ||
| 65 | +\end{aligned} | ||
| 66 | +$$ | ||
| 67 | + | ||
| 68 | +## 函数原型 | ||
| 69 | + | ||
| 70 | +每个算子分为[两段式接口](../../../docs/zh/context/two_phase_api.md),必须先调用“aclnnFusedAdamGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnFusedAdam”接口执行计算。 | ||
| 71 | + | ||
| 72 | +```cpp | ||
| 73 | +aclnnStatus aclnnFusedAdamGetWorkspaceSize( | ||
参数名未对齐 ![]() ![]() | |||
| 74 | + const aclTensorList* paramsRef, | ||
| 75 | + const aclTensorList* gradsRef, | ||
| 76 | + const aclTensorList* expAvgsRef, | ||
| 77 | + const aclTensorList* expAvgSqsRef, | ||
| 78 | + const aclTensorList* maxExpAvgSqsRef, | ||
| 79 | + const aclTensorList* stateSteps, | ||
| 80 | + const aclTensor* gradScaleOptional, | ||
| 81 | + const aclTensor* foundInfOptional, | ||
| 82 | + double lr, | ||
| 83 | + double beta1, | ||
| 84 | + double beta2, | ||
| 85 | + double weightDecay, | ||
| 86 | + double eps, | ||
| 87 | + bool amsgrad, | ||
| 88 | + bool maximize, | ||
| 89 | + uint64_t* workspaceSize, | ||
| 90 | + aclOpExecutor** executor) | ||
| 91 | +``` | ||
| 92 | + | ||
| 93 | +```cpp | ||
| 94 | +aclnnStatus aclnnFusedAdam( | ||
| 95 | + void* workspace, | ||
| 96 | + uint64_t workspaceSize, | ||
| 97 | + aclOpExecutor* executor, | ||
| 98 | + aclrtStream stream) | ||
| 99 | +``` | ||
| 100 | + | ||
| @@ -0,0 +1,284 @@ | |||
| 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 test_aclnn_fused_adam.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "acl/acl.h" | ||
| 17 | +#include "aclnnop/aclnn_fused_adam.h" | ||
| 18 | +#include <iostream> | ||
| 19 | +#include <vector> | ||
| 20 | + | ||
| 21 | +#define CHECK_RET(cond, return_expr) \ | ||
| 22 | + do { \ | ||
| 23 | + if (!(cond)) { \ | ||
| 24 | + return_expr; \ | ||
| 25 | + } \ | ||
| 26 | + } while (0) | ||
| 27 | + | ||
| 28 | +#define LOG_PRINT(message, ...) \ | ||
| 29 | + do { \ | ||
| 30 | + printf(message, ##__VA_ARGS__); \ | ||
| 31 | + } while (0) | ||
| 32 | + | ||
| 33 | +int64_t GetShapeSize(const std::vector<int64_t>& shape) | ||
| 34 | +{ | ||
| 35 | + int64_t shapeSize = 1; | ||
| 36 | + for (auto i : shape) { | ||
| 37 | + shapeSize *= i; | ||
| 38 | + } | ||
| 39 | + return shapeSize; | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +void PrintOutResult(std::vector<int64_t>& shape, void** deviceAddr) | ||
| 43 | +{ | ||
| 44 | + auto size = GetShapeSize(shape); | ||
| 45 | + std::vector<float> resultData(size, 0); | ||
| 46 | + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, | ||
| 47 | + size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 48 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); | ||
| 49 | + for (int64_t i = 0; i < size; i++) { | ||
| 50 | + LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]); | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +int Init(int32_t deviceId, aclrtStream* stream) | ||
| 55 | +{ | ||
| 56 | + auto ret = aclInit(nullptr); | ||
| 57 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); | ||
| 58 | + ret = aclrtSetDevice(deviceId); | ||
| 59 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); | ||
| 60 | + ret = aclrtCreateStream(stream); | ||
| 61 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); | ||
| 62 | + return 0; | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +template <typename T> | ||
| 66 | +int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, | ||
| 67 | + aclDataType dataType, aclTensor** tensor) | ||
| 68 | +{ | ||
| 69 | + auto size = GetShapeSize(shape) * sizeof(T); | ||
| 70 | + auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 71 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret); | ||
| 72 | + ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 73 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); | ||
| 74 | + | ||
| 75 | + std::vector<int64_t> strides(shape.size(), 1); | ||
| 76 | + for (int64_t i = shape.size() - 2; i >= 0; i--) { | ||
| 77 | + strides[i] = shape[i + 1] * strides[i + 1]; | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, | ||
| 81 | + shape.data(), shape.size(), *deviceAddr); | ||
| 82 | + return 0; | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +int main() | ||
| 86 | +{ | ||
| 87 | + // 1.(固定写法)device/stream初始化, 参考acl API手册 | ||
| 88 | + // 根据自己的实际device填写deviceId | ||
| 89 | + int32_t deviceId = 0; | ||
| 90 | + aclrtStream stream; | ||
| 91 | + auto ret = Init(deviceId, &stream); | ||
| 92 | + // check根据自己的需要处理 | ||
| 93 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); | ||
| 94 | + // 2.构造输入与输出,需要根据API的接口自定义构造 | ||
| 95 | + std::vector<float> paramsRefHostData1 = {1, 2, 3, 4, 5, 6, 7, 8}; | ||
| 96 | + std::vector<float> gradsHostData1 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}; | ||
| 97 | + std::vector<float> expavgsHostData1 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}; | ||
| 98 | + std::vector<float> expavgsqsHostData1 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}; | ||
| 99 | + std::vector<float> maxexpavgsqsHostData1 = {1, 2, 3, 4, 5, 6, 7, 8}; | ||
| 100 | + std::vector<float> stepsHostData1 = {3}; | ||
| 101 | + | ||
| 102 | + std::vector<float> paramsRefHostData2 = {9, 10, 11, 12}; | ||
| 103 | + std::vector<float> gradsHostData2 = {0.9, 1.0, 1.1, 1.2}; | ||
| 104 | + std::vector<float> expavgsHostData2 = {-1, -2, -3, -4}; | ||
| 105 | + std::vector<float> expavgsqsHostData2 = {1, 2, 3, 4}; | ||
| 106 | + std::vector<float> maxexpavgsqsHostData2 = {-1, -1, -1, -1}; | ||
| 107 | + std::vector<float> stepsHostData2 = {4}; | ||
| 108 | + | ||
| 109 | + std::vector<float> gradScaleOptionalHostData = {2}; | ||
| 110 | + | ||
| 111 | + std::vector<int64_t> inputShape1 = {2, 2, 2}; | ||
| 112 | + std::vector<int64_t> inputShape2 = {2, 2}; | ||
| 113 | + std::vector<int64_t> scalarShape = {1}; | ||
| 114 | + | ||
| 115 | + void* paramsRef1DeviceAddr = nullptr; | ||
| 116 | + void* grads1DeviceAddr = nullptr; | ||
| 117 | + void* expavgs1DeviceAddr = nullptr; | ||
| 118 | + void* expavgsqs1DeviceAddr = nullptr; | ||
| 119 | + void* maxexpavgsqs1DeviceAddr = nullptr; | ||
| 120 | + void* steps1DeviceAddr = nullptr; | ||
| 121 | + | ||
| 122 | + void* paramsRef2DeviceAddr = nullptr; | ||
| 123 | + void* grads2DeviceAddr = nullptr; | ||
| 124 | + void* expavgs2DeviceAddr = nullptr; | ||
| 125 | + void* expavgsqs2DeviceAddr = nullptr; | ||
| 126 | + void* maxexpavgsqs2DeviceAddr = nullptr; | ||
| 127 | + void* steps2DeviceAddr = nullptr; | ||
| 128 | + | ||
| 129 | + void* gradScaleOptionalDeviceAddr = nullptr; | ||
| 130 | + | ||
| 131 | + aclTensor* paramsRef1 = nullptr; | ||
| 132 | + aclTensor* grads1 = nullptr; | ||
| 133 | + aclTensor* expavgs1 = nullptr; | ||
| 134 | + aclTensor* expavgsqs1 = nullptr; | ||
| 135 | + aclTensor* maxexpavgsqs1 = nullptr; | ||
| 136 | + aclTensor* steps1 = nullptr; | ||
| 137 | + | ||
| 138 | + aclTensor* paramsRef2 = nullptr; | ||
| 139 | + aclTensor* grads2 = nullptr; | ||
| 140 | + aclTensor* expavgs2 = nullptr; | ||
| 141 | + aclTensor* expavgsqs2 = nullptr; | ||
| 142 | + aclTensor* maxexpavgsqs2 = nullptr; | ||
| 143 | + aclTensor* steps2 = nullptr; | ||
| 144 | + | ||
| 145 | + aclTensor* gradScaleOptional = nullptr; | ||
| 146 | + | ||
| 147 | + aclTensor* foundInfOptional = nullptr; | ||
| 148 | + | ||
| 149 | + ret = CreateAclTensor(paramsRefHostData1, inputShape1, ¶msRef1DeviceAddr, aclDataType::ACL_FLOAT, ¶msRef1); | ||
| 150 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 151 | + ret = CreateAclTensor(gradsHostData1, inputShape1, &grads1DeviceAddr, aclDataType::ACL_FLOAT, &grads1); | ||
| 152 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 153 | + ret = CreateAclTensor(expavgsHostData1, inputShape1, &expavgs1DeviceAddr, aclDataType::ACL_FLOAT, &expavgs1); | ||
| 154 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 155 | + ret = CreateAclTensor(expavgsqsHostData1, inputShape1, &expavgsqs1DeviceAddr, aclDataType::ACL_FLOAT, &expavgsqs1); | ||
| 156 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 157 | + ret = CreateAclTensor(maxexpavgsqsHostData1, inputShape1, &maxexpavgsqs1DeviceAddr, aclDataType::ACL_FLOAT, | ||
| 158 | + &maxexpavgsqs1); | ||
🟡 Medium Priority 变更行:examples/test_aclnn_fused_adam.cpp 第 158 行 影响的行为/契约: 失败模式:测试中 state_steps 的后 7(或 3)个元素为垃圾值,Adam 偏置校正(1-beta^step、sqrt(1-beta2^step))使用这些垃圾 step,得到非确定性的错误结果,示例输出的结果不可复现,同时存在 ASan/堆检查下的越界读报错。 建议:将第 97 行 stepsHostData1 改为 8 个元素、第 107 行 stepsHostData2 改为 4 个元素,使 host 数据元素数与传入 shape 的元素数一致(或改用 scalarShape={1} 创建 steps tensor),避免 aclrtMemcpy 越界读和垃圾 step 值。 ![]() ![]() Incorrect? | |||
| 159 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 160 | + ret = CreateAclTensor(stepsHostData1, inputShape1, &steps1DeviceAddr, aclDataType::ACL_FLOAT, &steps1); | ||
| 161 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 162 | + | ||
| 163 | + ret = CreateAclTensor(paramsRefHostData2, inputShape2, ¶msRef2DeviceAddr, aclDataType::ACL_FLOAT, ¶msRef2); | ||
| 164 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 165 | + ret = CreateAclTensor(gradsHostData2, inputShape2, &grads2DeviceAddr, aclDataType::ACL_FLOAT, &grads2); | ||
| 166 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 167 | + ret = CreateAclTensor(expavgsHostData2, inputShape2, &expavgs2DeviceAddr, aclDataType::ACL_FLOAT, &expavgs2); | ||
| 168 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 169 | + ret = CreateAclTensor(expavgsqsHostData2, inputShape2, &expavgsqs2DeviceAddr, aclDataType::ACL_FLOAT, &expavgsqs2); | ||
| 170 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 171 | + ret = CreateAclTensor(maxexpavgsqsHostData2, inputShape2, &maxexpavgsqs2DeviceAddr, aclDataType::ACL_FLOAT, | ||
| 172 | + &maxexpavgsqs2); | ||
| 173 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 174 | + ret = CreateAclTensor(stepsHostData2, inputShape2, &steps2DeviceAddr, aclDataType::ACL_FLOAT, &steps2); | ||
| 175 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 176 | + | ||
| 177 | + ret = CreateAclTensor(gradScaleOptionalHostData, scalarShape, &gradScaleOptionalDeviceAddr, aclDataType::ACL_FLOAT, | ||
| 178 | + &gradScaleOptional); | ||
| 179 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 180 | + | ||
| 181 | + std::vector<aclTensor*> paramsRefListData = {paramsRef1, paramsRef2}; | ||
| 182 | + std::vector<aclTensor*> gradsListData = {grads1, grads2}; | ||
| 183 | + std::vector<aclTensor*> expavgsListData = {expavgs1, expavgs2}; | ||
| 184 | + std::vector<aclTensor*> expavgsqsListData = {expavgsqs1, expavgsqs2}; | ||
| 185 | + std::vector<aclTensor*> maxexpavgsqsData = {maxexpavgsqs1, maxexpavgsqs2}; | ||
| 186 | + std::vector<aclTensor*> stepsListData = {steps1, steps2}; | ||
| 187 | + aclTensorList* paramsRefList = aclCreateTensorList(paramsRefListData.data(), paramsRefListData.size()); | ||
| 188 | + aclTensorList* gradsList = aclCreateTensorList(gradsListData.data(), gradsListData.size()); | ||
| 189 | + aclTensorList* expavgsList = aclCreateTensorList(expavgsListData.data(), expavgsListData.size()); | ||
| 190 | + aclTensorList* expavgsqsList = aclCreateTensorList(expavgsqsListData.data(), expavgsqsListData.size()); | ||
| 191 | + aclTensorList* maxexpavgsqsList = aclCreateTensorList(maxexpavgsqsData.data(), maxexpavgsqsData.size()); | ||
| 192 | + aclTensorList* stepsList = aclCreateTensorList(stepsListData.data(), stepsListData.size()); | ||
| 193 | + | ||
| 194 | + double lr = 0.001f; | ||
| 195 | + double beta1 = 0.9f; | ||
| 196 | + double beta2 = 0.999f; | ||
| 197 | + double weightDecay = 0.0f; | ||
| 198 | + double eps = 1e-8; | ||
| 199 | + bool amsgrad = true; | ||
| 200 | + bool maximize = false; | ||
| 201 | + // 3.调用API | ||
| 202 | + uint64_t workspaceSize = 0; | ||
| 203 | + aclOpExecutor* executor; | ||
| 204 | + // 调用aclnnFusedAdamGetWorkspaceSize第一段接口 | ||
| 205 | + ret = aclnnFusedAdamGetWorkspaceSize(paramsRefList, gradsList, expavgsList, expavgsqsList, maxexpavgsqsList, | ||
| 206 | + stepsList, gradScaleOptional, foundInfOptional, lr, beta1, beta2, weightDecay, | ||
| 207 | + eps, amsgrad, maximize, &workspaceSize, &executor); | ||
| 208 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedAdamGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); | ||
| 209 | + // 根据第一段接口计算出的workspaceSize申请device内存 | ||
| 210 | + void* workspaceAddr = nullptr; | ||
| 211 | + if (workspaceSize > 0) { | ||
| 212 | + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 213 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret); | ||
| 214 | + } | ||
| 215 | + // 调用aclnnXxx第二段接口 | ||
| 216 | + ret = aclnnFusedAdam(workspaceAddr, workspaceSize, executor, stream); | ||
| 217 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedAdam failed. ERROR: %d\n", ret); return ret); | ||
| 218 | + | ||
| 219 | + // 4.(固定写法)同步等待任务执行结束 | ||
| 220 | + ret = aclrtSynchronizeStream(stream); | ||
| 221 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); | ||
| 222 | + | ||
| 223 | + // 5.获取输出的值,将device侧内存上的结果拷贝至host侧 | ||
| 224 | + LOG_PRINT("====== Tensor 1-1 paramsRef1 results ======\n"); | ||
| 225 | + PrintOutResult(inputShape1, ¶msRef1DeviceAddr); | ||
| 226 | + LOG_PRINT("====== Tensor 1-2 grads1 results ======\n"); | ||
| 227 | + PrintOutResult(inputShape1, &grads1DeviceAddr); | ||
| 228 | + LOG_PRINT("====== Tensor 1-3 expavgs1 results ======\n"); | ||
| 229 | + PrintOutResult(inputShape1, &expavgs1DeviceAddr); | ||
| 230 | + LOG_PRINT("====== Tensor 1-4 expavgsqs1 results ======\n"); | ||
| 231 | + PrintOutResult(inputShape1, &expavgsqs1DeviceAddr); | ||
| 232 | + LOG_PRINT("====== Tensor 1-5 maxexpavgsqs1 results ======\n"); | ||
| 233 | + PrintOutResult(inputShape1, &maxexpavgsqs1DeviceAddr); | ||
| 234 | + | ||
| 235 | + LOG_PRINT("====== Tensor 2-1 paramsRef results ======\n"); | ||
| 236 | + PrintOutResult(inputShape2, ¶msRef2DeviceAddr); | ||
| 237 | + LOG_PRINT("====== Tensor 2-2 grads2 results ======\n"); | ||
| 238 | + PrintOutResult(inputShape2, &grads2DeviceAddr); | ||
| 239 | + LOG_PRINT("====== Tensor 2-3 expavgs2 results ======\n"); | ||
| 240 | + PrintOutResult(inputShape2, &expavgs2DeviceAddr); | ||
| 241 | + LOG_PRINT("====== Tensor 2-4 expavgsqs2 results ======\n"); | ||
| 242 | + PrintOutResult(inputShape2, &expavgsqs2DeviceAddr); | ||
| 243 | + LOG_PRINT("====== Tensor 2-5 maxexpavgsqs2 results ======\n"); | ||
| 244 | + PrintOutResult(inputShape2, &maxexpavgsqs2DeviceAddr); | ||
| 245 | + | ||
| 246 | + // 6.释放aclTensor | ||
| 247 | + aclDestroyTensorList(paramsRefList); | ||
| 248 | + aclDestroyTensorList(gradsList); | ||
| 249 | + aclDestroyTensorList(expavgsList); | ||
| 250 | + aclDestroyTensorList(expavgsqsList); | ||
| 251 | + aclDestroyTensorList(maxexpavgsqsList); | ||
| 252 | + aclDestroyTensorList(stepsList); | ||
| 253 | + aclDestroyTensor(gradScaleOptional); | ||
| 254 | + aclDestroyTensor(foundInfOptional); | ||
| 255 | + | ||
| 256 | + // 7.释放device资源 | ||
| 257 | + aclrtFree(paramsRef1DeviceAddr); | ||
| 258 | + aclrtFree(grads1DeviceAddr); | ||
| 259 | + aclrtFree(expavgs1DeviceAddr); | ||
| 260 | + aclrtFree(expavgsqs1DeviceAddr); | ||
| 261 | + aclrtFree(maxexpavgsqs1DeviceAddr); | ||
| 262 | + aclrtFree(steps1DeviceAddr); | ||
| 263 | + | ||
| 264 | + aclrtFree(paramsRef2DeviceAddr); | ||
| 265 | + aclrtFree(grads2DeviceAddr); | ||
| 266 | + aclrtFree(expavgs2DeviceAddr); | ||
| 267 | + aclrtFree(expavgsqs2DeviceAddr); | ||
| 268 | + aclrtFree(maxexpavgsqs2DeviceAddr); | ||
| 269 | + aclrtFree(steps2DeviceAddr); | ||
| 270 | + | ||
| 271 | + aclrtFree(gradScaleOptionalDeviceAddr); | ||
| 272 | + | ||
| 273 | + if (workspaceSize > 0) { | ||
| 274 | + aclrtFree(workspaceAddr); | ||
| 275 | + } | ||
| 276 | + | ||
| 277 | + ret = aclrtDestroyStream(stream); | ||
| 278 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("destroy stream failed. ERROR: %d\n", ret); return ret); | ||
| 279 | + ret = aclrtResetDevice(deviceId); | ||
| 280 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("reset device failed. ERROR: %d\n", ret); return ret); | ||
| 281 | + ret = aclFinalize(); | ||
| 282 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("finalize acl failed. ERROR: %d\n", ret); return ret); | ||
| 283 | + return 0; | ||
| 284 | +} | ||
| @@ -0,0 +1,357 @@ | |||
| 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 aclnn_fused_adam.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "aclnn_fused_adam.h" | ||
| 17 | +#include "aclnn_kernels/contiguous.h" | ||
| 18 | +#include "fused_adam.h" | ||
| 19 | +#include "aclnn_kernels/common/op_error_check.h" | ||
| 20 | +#include "aclnn_kernels/cast.h" | ||
| 21 | +#include "opdev/common_types.h" | ||
| 22 | +#include "opdev/data_type_utils.h" | ||
| 23 | +#include "opdev/format_utils.h" | ||
| 24 | +#include "opdev/op_dfx.h" | ||
| 25 | +#include "opdev/op_executor.h" | ||
| 26 | +#include "opdev/make_op_executor.h" | ||
| 27 | +#include "opdev/op_log.h" | ||
| 28 | +#include "opdev/shape_utils.h" | ||
| 29 | +#include "opdev/tensor_view_utils.h" | ||
| 30 | +#include "opdev/platform.h" | ||
| 31 | +#include "op_api/aclnn_util.h" | ||
| 32 | + | ||
| 33 | +using namespace op; | ||
| 34 | +#ifdef __cplusplus | ||
| 35 | +extern "C" { | ||
| 36 | +#endif | ||
| 37 | + | ||
| 38 | +namespace { | ||
| 39 | + | ||
| 40 | +static const std::initializer_list<op::DataType> INPUT_DTYPE_SUPPORT_LIST = { | ||
| 41 | + op::DataType::DT_FLOAT, op::DataType::DT_FLOAT16, op::DataType::DT_BF16}; | ||
| 42 | + | ||
| 43 | +static const std::initializer_list<op::DataType> STEP_DTYPE_SUPPORT_LIST = {op::DataType::DT_FLOAT, | ||
| 44 | + op::DataType::DT_INT64}; | ||
| 45 | + | ||
| 46 | +static bool CheckNotNull(const aclTensorList* paramsRef, const aclTensorList* gradsRef, const aclTensorList* expAvgsRef, | ||
| 47 | + const aclTensorList* expAvgSqsRef, const aclTensorList* stateSteps, | ||
| 48 | + const aclTensorList* maxExpAvgSqsRef) | ||
| 49 | +{ | ||
| 50 | + OP_CHECK_NULL(paramsRef, return false); | ||
| 51 | + for (uint64_t i = 0; i < paramsRef->Size(); i++) { | ||
| 52 | + OP_CHECK_NULL((*paramsRef)[i], return false); | ||
| 53 | + } | ||
| 54 | + OP_CHECK_NULL(gradsRef, return false); | ||
| 55 | + for (uint64_t i = 0; i < gradsRef->Size(); i++) { | ||
| 56 | + OP_CHECK_NULL((*gradsRef)[i], return false); | ||
| 57 | + } | ||
| 58 | + OP_CHECK_NULL(expAvgsRef, return false); | ||
| 59 | + for (uint64_t i = 0; i < expAvgsRef->Size(); i++) { | ||
| 60 | + OP_CHECK_NULL((*expAvgsRef)[i], return false); | ||
| 61 | + } | ||
| 62 | + OP_CHECK_NULL(expAvgSqsRef, return false); | ||
| 63 | + for (uint64_t i = 0; i < expAvgSqsRef->Size(); i++) { | ||
| 64 | + OP_CHECK_NULL((*expAvgSqsRef)[i], return false); | ||
| 65 | + } | ||
| 66 | + OP_CHECK_NULL(stateSteps, return false); | ||
| 67 | + for (uint64_t i = 0; i < stateSteps->Size(); i++) { | ||
| 68 | + OP_CHECK_NULL((*stateSteps)[i], return false); | ||
| 69 | + } | ||
| 70 | + if (maxExpAvgSqsRef != nullptr) { | ||
| 71 | + for (uint64_t i = 0; i < maxExpAvgSqsRef->Size(); i++) { | ||
| 72 | + OP_CHECK_NULL((*maxExpAvgSqsRef)[i], return false); | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | + return true; | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +static bool CheckTensorListCount(const aclTensorList* paramsRef, const aclTensorList* gradsRef, | ||
| 79 | + const aclTensorList* expAvgsRef, const aclTensorList* expAvgSqsRef, | ||
| 80 | + const aclTensorList* stateSteps, const aclTensorList* maxExpAvgSqsRef) | ||
| 81 | +{ | ||
| 82 | + auto tensorCount = paramsRef->Size(); | ||
| 83 | + if (tensorCount == 0) { | ||
| 84 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "paramsRef tensor list is empty."); | ||
| 85 | + return false; | ||
| 86 | + } | ||
| 87 | + if (gradsRef->Size() != tensorCount) { | ||
| 88 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "gradsRef tensor count does not match params."); | ||
| 89 | + return false; | ||
| 90 | + } | ||
| 91 | + if (expAvgsRef->Size() != tensorCount) { | ||
| 92 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "expAvgs tensor count does not match params."); | ||
| 93 | + return false; | ||
| 94 | + } | ||
| 95 | + if (expAvgSqsRef->Size() != tensorCount) { | ||
| 96 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "expAvgSqs tensor count does not match params."); | ||
| 97 | + return false; | ||
| 98 | + } | ||
| 99 | + if (stateSteps->Size() != tensorCount) { | ||
| 100 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "stateSteps tensor count does not match params."); | ||
| 101 | + return false; | ||
| 102 | + } | ||
| 103 | + if (maxExpAvgSqsRef != nullptr && maxExpAvgSqsRef->Size() != tensorCount) { | ||
| 104 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "maxExpAvgSqs tensor count does not match params."); | ||
| 105 | + return false; | ||
| 106 | + } | ||
| 107 | + return true; | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +static bool CheckDtype(const aclTensorList* paramsRef, const aclTensorList* gradsRef, const aclTensorList* expAvgsRef, | ||
| 111 | + const aclTensorList* expAvgSqsRef, const aclTensorList* stateSteps, | ||
| 112 | + const aclTensorList* maxExpAvgSqsRef) | ||
| 113 | +{ | ||
| 114 | + auto paramsTensor = (*paramsRef)[0]; | ||
| 115 | + auto stateStepsTensor = (*stateSteps)[0]; | ||
| 116 | + OP_CHECK_DTYPE_NOT_SUPPORT(paramsTensor, INPUT_DTYPE_SUPPORT_LIST, return false); | ||
| 117 | + OP_CHECK_DTYPE_NOT_SUPPORT(stateStepsTensor, STEP_DTYPE_SUPPORT_LIST, return false); | ||
| 118 | + op::DataType stepType = stateStepsTensor->GetDataType(); | ||
| 119 | + for (uint64_t i = 1; i < stateSteps->Size(); i++) { | ||
| 120 | + if ((*stateSteps)[i]->GetDataType() != stepType) { | ||
| 121 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "expects all stateSteps tensors with the same dtype."); | ||
| 122 | + return false; | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + op::DataType inputType = paramsTensor->GetDataType(); | ||
| 126 | + for (uint64_t i = 0; i < paramsRef->Size(); i++) { | ||
| 127 | + if ((*paramsRef)[i]->GetDataType() != inputType || (*gradsRef)[i]->GetDataType() != inputType || | ||
| 128 | + (*expAvgsRef)[i]->GetDataType() != inputType || (*expAvgSqsRef)[i]->GetDataType() != inputType) { | ||
| 129 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "expects all input tensors with the same dtype."); | ||
| 130 | + return false; | ||
| 131 | + } | ||
| 132 | + } | ||
| 133 | + if (maxExpAvgSqsRef != nullptr) { | ||
| 134 | + auto maxExpAvgSqsTensor = (*maxExpAvgSqsRef)[0]; | ||
| 135 | + OP_CHECK_DTYPE_NOT_SUPPORT(maxExpAvgSqsTensor, INPUT_DTYPE_SUPPORT_LIST, return false); | ||
| 136 | + OP_CHECK_DTYPE_NOT_SAME(paramsTensor, maxExpAvgSqsTensor, return false); | ||
| 137 | + for (uint64_t i = 0; i < maxExpAvgSqsRef->Size(); i++) { | ||
| 138 | + if ((*maxExpAvgSqsRef)[i]->GetDataType() != inputType) { | ||
| 139 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "expects all input tensors with the same dtype."); | ||
| 140 | + return false; | ||
| 141 | + } | ||
| 142 | + } | ||
| 143 | + } | ||
| 144 | + return true; | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +static void CheckOptionalTensorEmpty(const aclTensor*& tensor) | ||
| 148 | +{ | ||
| 149 | + if (tensor == nullptr) { | ||
| 150 | + OP_LOGI("gradScaleOptional is nullptr"); | ||
| 151 | + return; | ||
| 152 | + } | ||
| 153 | + if (tensor->IsEmpty()) { | ||
| 154 | + OP_LOGI("gradScaleOptional is empty, treating as nullptr."); | ||
| 155 | + tensor = nullptr; | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +static bool CheckAttr(double lr, double beta1, double beta2, double weightDecay, double eps, bool amsgrad, | ||
| 160 | + const aclTensorList* maxExpAvgSqsRef) | ||
| 161 | +{ | ||
| 162 | + if (lr < 0) { | ||
| 163 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "The lr[%f] shoule be greater or equal than 0", lr); | ||
| 164 | + return false; | ||
| 165 | + } | ||
| 166 | + if (beta1 < 0) { | ||
| 167 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "The beta1[%f] shoule be greater or equal than 0", beta1); | ||
| 168 | + return false; | ||
| 169 | + } | ||
| 170 | + if (beta2 < 0) { | ||
| 171 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "The beta2[%f] shoule be greater or equal than 0", beta2); | ||
| 172 | + return false; | ||
| 173 | + } | ||
| 174 | + if (weightDecay < 0) { | ||
| 175 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "The weightDecay[%f] shoule be greater or equal than 0", weightDecay); | ||
| 176 | + return false; | ||
| 177 | + } | ||
| 178 | + const float EPS = 1e-7f; | ||
| 179 | + if (eps > EPS || eps < 0) { | ||
| 180 | + OP_LOGW("An incorrect value for eps[%f] will affect accuracy, a value of 1e-8 is recommended.", eps); | ||
| 181 | + } | ||
| 182 | + if (amsgrad == true && maxExpAvgSqsRef == nullptr) { | ||
| 183 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "When amsgrad is true, maxExpAvgSqsRef should not be nullptr."); | ||
| 184 | + return false; | ||
| 185 | + } | ||
| 186 | + return true; | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +static bool CheckShape(const aclTensorList* paramsRef, const aclTensorList* grads, const aclTensorList* expAvgsRef, | ||
| 190 | + const aclTensorList* expAvgSqsRef, const aclTensorList* maxExpAvgSqsRef) | ||
| 191 | +{ | ||
| 192 | + for (uint64_t i = 0; i < paramsRef->Size(); i++) { | ||
| 193 | + op::Shape expectShape = (*paramsRef)[i]->GetViewShape(); | ||
| 194 | + if ((*grads)[i]->GetViewShape() != expectShape || (*expAvgsRef)[i]->GetViewShape() != expectShape || | ||
| 195 | + (*expAvgSqsRef)[i]->GetViewShape() != expectShape) { | ||
| 196 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "expects all input tensors with the same shape."); | ||
| 197 | + return false; | ||
| 198 | + } | ||
| 199 | + if (maxExpAvgSqsRef != nullptr && (*maxExpAvgSqsRef)[i]->GetViewShape() != expectShape) { | ||
| 200 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "expects all input tensors with the same shape."); | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + return true; | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +static aclnnStatus CheckParams(const aclTensorList* paramsRef, const aclTensorList* gradsRef, | ||
| 207 | + const aclTensorList* expAvgsRef, const aclTensorList* expAvgSqsRef, | ||
| 208 | + const aclTensorList* maxExpAvgSqsRef, const aclTensorList* stateSteps, double lr, | ||
| 209 | + double beta1, double beta2, double weightDecay, double eps, bool amsgrad) | ||
| 210 | +{ | ||
| 211 | + CHECK_RET(CheckAttr(lr, beta1, beta2, weightDecay, eps, amsgrad, maxExpAvgSqsRef), ACLNN_ERR_PARAM_INVALID); | ||
| 212 | + CHECK_RET(CheckNotNull(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, stateSteps, maxExpAvgSqsRef), | ||
| 213 | + ACLNN_ERR_PARAM_NULLPTR); | ||
| 214 | + CHECK_RET(CheckTensorListCount(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, stateSteps, maxExpAvgSqsRef), | ||
| 215 | + ACLNN_ERR_PARAM_INVALID); | ||
| 216 | + CHECK_RET(CheckDtype(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, stateSteps, maxExpAvgSqsRef), | ||
| 217 | + ACLNN_ERR_PARAM_INVALID); | ||
| 218 | + CHECK_RET(CheckShape(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef), ACLNN_ERR_PARAM_INVALID); | ||
| 219 | + return ACLNN_SUCCESS; | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +static const aclTensor* FlattenDimsForTensor(const aclTensor* tensor, aclOpExecutor* executor) | ||
| 223 | +{ | ||
| 224 | + op::Shape shapeTensor = tensor->GetViewShape(); | ||
| 225 | + int64_t dimNum = shapeTensor.GetDimNum(); | ||
| 226 | + | ||
| 227 | + op::Shape newShape; | ||
| 228 | + int64_t catdimSize = 1; | ||
| 229 | + for (int64_t i = 0; i < dimNum; i++) { | ||
| 230 | + catdimSize *= shapeTensor.GetDim(i); | ||
| 231 | + } | ||
| 232 | + newShape.AppendDim(catdimSize); | ||
| 233 | + auto reshapeTensor = executor->CreateView(tensor, tensor->GetViewShape(), tensor->GetViewOffset()); | ||
| 234 | + reshapeTensor->SetViewShape(newShape); | ||
| 235 | + reshapeTensor->SetOriginalShape(newShape); | ||
| 236 | + reshapeTensor->SetStorageShape(newShape); | ||
| 237 | + return reshapeTensor; | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +static const aclTensorList* MakeContiguousTensorList(const aclTensorList* tensorList, aclOpExecutor* executor) | ||
| 241 | +{ | ||
| 242 | + op::FVector<const aclTensor*> contiguousTensors; | ||
| 243 | + for (uint64_t i = 0; i < tensorList->Size(); i++) { | ||
| 244 | + if ((*tensorList)[i]->IsEmpty()) { | ||
| 245 | + continue; | ||
| 246 | + } | ||
| 247 | + auto contiguous = l0op::Contiguous((*tensorList)[i], executor); | ||
| 248 | + CHECK_RET(contiguous != nullptr, nullptr); | ||
| 249 | + contiguous = FlattenDimsForTensor(contiguous, executor); | ||
| 250 | + contiguousTensors.emplace_back(contiguous); | ||
| 251 | + } | ||
| 252 | + return executor->AllocTensorList(contiguousTensors.data(), contiguousTensors.size()); | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +static const aclTensorList* CastStateStepsToFloat(const aclTensorList* stateSteps, aclOpExecutor* executor) | ||
| 256 | +{ | ||
| 257 | + op::FVector<const aclTensor*> castedTensors; | ||
| 258 | + for (uint64_t i = 0; i < stateSteps->Size(); i++) { | ||
| 259 | + auto casted = l0op::Cast((*stateSteps)[i], DataType::DT_FLOAT, executor); | ||
| 260 | + CHECK_RET(casted != nullptr, nullptr); | ||
| 261 | + castedTensors.emplace_back(casted); | ||
| 262 | + } | ||
| 263 | + return executor->AllocTensorList(castedTensors.data(), castedTensors.size()); | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +static void ViewCopyTensorList(const aclTensorList* src, const aclTensorList* dst, aclOpExecutor* executor) | ||
| 267 | +{ | ||
| 268 | + uint64_t cnt = 0; | ||
| 269 | + for (uint64_t i = 0; i < dst->Size(); i++) { | ||
| 270 | + if ((*dst)[i]->IsEmpty()) { | ||
| 271 | + continue; | ||
| 272 | + } | ||
| 273 | + l0op::ViewCopy((*src)[cnt], (*dst)[i], executor); | ||
| 274 | + cnt += 1; | ||
| 275 | + } | ||
| 276 | +} | ||
| 277 | +} // namespace | ||
| 278 | + | ||
| 279 | +aclnnStatus aclnnFusedAdamGetWorkspaceSize(const aclTensorList* paramsRef, const aclTensorList* gradsRef, | ||
| 280 | + const aclTensorList* expAvgsRef, const aclTensorList* expAvgSqsRef, | ||
| 281 | + const aclTensorList* maxExpAvgSqsRef, const aclTensorList* stateSteps, | ||
| 282 | + const aclTensor* gradScaleOptional, const aclTensor* foundInfOptional, | ||
| 283 | + double lr, double beta1, double beta2, double weightDecay, double eps, | ||
| 284 | + bool amsgrad, bool maximize, uint64_t* workspaceSize, | ||
| 285 | + aclOpExecutor** executor) | ||
| 286 | +{ | ||
| 287 | + L2_DFX_PHASE_1(aclnnFusedAdam, | ||
| 288 | + DFX_IN(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef, stateSteps, gradScaleOptional, | ||
| 289 | + foundInfOptional, lr, beta1, beta2, weightDecay, eps, amsgrad, maximize), | ||
| 290 | + DFX_OUT(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef)); | ||
| 291 | + auto uniqueExecutor = CREATE_EXECUTOR(); | ||
| 292 | + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); | ||
| 293 | + auto ret = CheckParams(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef, stateSteps, lr, beta1, beta2, | ||
| 294 | + weightDecay, eps, amsgrad); | ||
| 295 | + CHECK_RET(ret == ACLNN_SUCCESS, ret); | ||
| 296 | + | ||
| 297 | + CheckOptionalTensorEmpty(gradScaleOptional); | ||
| 298 | + CheckOptionalTensorEmpty(foundInfOptional); | ||
| 299 | + | ||
| 300 | + if (gradScaleOptional != nullptr) { | ||
| 301 | + gradScaleOptional = l0op::Cast(gradScaleOptional, DataType::DT_FLOAT, uniqueExecutor.get()); | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + auto paramsContiguous = MakeContiguousTensorList(paramsRef, uniqueExecutor.get()); | ||
| 305 | + CHECK_RET(paramsContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 306 | + | ||
| 307 | + auto gradsContiguous = MakeContiguousTensorList(gradsRef, uniqueExecutor.get()); | ||
| 308 | + CHECK_RET(gradsContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 309 | + | ||
| 310 | + auto expAvgsRefContiguous = MakeContiguousTensorList(expAvgsRef, uniqueExecutor.get()); | ||
| 311 | + CHECK_RET(expAvgsRefContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 312 | + | ||
| 313 | + auto expAvgSqsRefContiguous = MakeContiguousTensorList(expAvgSqsRef, uniqueExecutor.get()); | ||
| 314 | + CHECK_RET(expAvgSqsRefContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 315 | + | ||
| 316 | + const aclTensorList* maxExpAvgSqsRefContiguous = nullptr; | ||
| 317 | + if (maxExpAvgSqsRef != nullptr) { | ||
| 318 | + maxExpAvgSqsRefContiguous = MakeContiguousTensorList(maxExpAvgSqsRef, uniqueExecutor.get()); | ||
| 319 | + CHECK_RET(maxExpAvgSqsRefContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 320 | + } | ||
| 321 | + | ||
| 322 | + const aclTensorList* stateStepsFloat = CastStateStepsToFloat(stateSteps, uniqueExecutor.get()); | ||
| 323 | + CHECK_RET(stateStepsFloat != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 324 | + | ||
| 325 | + auto [paramsOut, gradsOut, expAvgsOut, expAvgSqsOut, maxExpAvgSqsOut] = l0op::FusedAdam( | ||
| 326 | + paramsContiguous, gradsContiguous, expAvgsRefContiguous, expAvgSqsRefContiguous, maxExpAvgSqsRefContiguous, | ||
| 327 | + stateStepsFloat, gradScaleOptional, foundInfOptional, static_cast<float>(lr), static_cast<float>(beta1), | ||
| 328 | + static_cast<float>(beta2), static_cast<float>(weightDecay), static_cast<float>(eps), amsgrad, maximize, | ||
| 329 | + uniqueExecutor.get()); | ||
| 330 | + CHECK_RET(paramsOut != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 331 | + CHECK_RET(gradsOut != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 332 | + CHECK_RET(expAvgsOut != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 333 | + CHECK_RET(expAvgSqsOut != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 334 | + | ||
| 335 | + ViewCopyTensorList(paramsOut, paramsRef, uniqueExecutor.get()); | ||
| 336 | + ViewCopyTensorList(gradsOut, gradsRef, uniqueExecutor.get()); | ||
| 337 | + ViewCopyTensorList(expAvgsOut, expAvgsRef, uniqueExecutor.get()); | ||
| 338 | + ViewCopyTensorList(expAvgSqsOut, expAvgSqsRef, uniqueExecutor.get()); | ||
| 339 | + if (maxExpAvgSqsRef != nullptr) { | ||
| 340 | + ViewCopyTensorList(maxExpAvgSqsOut, maxExpAvgSqsRef, uniqueExecutor.get()); | ||
| 341 | + } | ||
| 342 | + | ||
| 343 | + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); | ||
| 344 | + uniqueExecutor.ReleaseTo(executor); | ||
| 345 | + | ||
| 346 | + return ACLNN_SUCCESS; | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | +aclnnStatus aclnnFusedAdam(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream) | ||
| 350 | +{ | ||
| 351 | + L2_DFX_PHASE_2(aclnnFusedAdam); | ||
| 352 | + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +#ifdef __cplusplus | ||
| 356 | +} | ||
| 357 | +#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 | +/*! | ||
| 12 | + * \file aclnn_fused_adam.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef _ACLNN_FUSED_ADAM_H_ | ||
| 17 | +#define _ACLNN_FUSED_ADAM_H_ | ||
| 18 | + | ||
| 19 | +#include "aclnn/aclnn_base.h" | ||
| 20 | +#include "aclnn_util.h" | ||
| 21 | + | ||
| 22 | +#ifdef __cplusplus | ||
| 23 | +extern "C" { | ||
| 24 | +#endif | ||
| 25 | + | ||
| 26 | +/** | ||
| 27 | + * @brief aclnnFusedAdam的第一段接口,根据具体的计算流程,计算workspace大小。 | ||
| 28 | + * @domain aclnn_ops_train | ||
| 29 | + * | ||
| 30 | + * 算子功能:融合applyadam优化器,支持params、grads、expAvgs、expAvgSqs、maxExpAvgSqs、stateSteps | ||
| 31 | + * 将参数更新、动量更新、梯度缩放等操作融合为单个kernel。 | ||
| 32 | + * | ||
| 33 | + * @param [in] paramsRef: device侧的aclTensorList,需要更新的参数列表。 | ||
| 34 | + * 数据类型支持FLOAT、FLOAT16、BFLOAT16。数据格式支持ND。 | ||
| 35 | + * @param [in] gradsRef: device侧的aclTensorList,梯度列表。数据类型、shape需要与params一致。 | ||
| 36 | + * @param [in] expAvgsRef: device侧的aclTensorList,优化器一阶矩。数据类型、shape需要与params一致。 | ||
| 37 | + * @param [in] expAvgSqsRef: device侧的aclTensorList,优化器二阶矩。数据类型、shape需要与params一致。 | ||
| 38 | + * @param [in] maxExpAvgSqsRef: device侧的aclTensorList,保存最大二阶矩。数据类型、shape需要与params一致。 | ||
| 39 | + * @param [in] stateSteps: device侧的aclTensorList,迭代次数。数据类型、shape需要与params一致。 | ||
| 40 | + * @param [in] gradScaleOptional: device侧的aclTensor,可选输入,梯度因数。数据类型、shape需要与params一致。 | ||
| 41 | + * @param [in] foundInfOptional: device侧的aclTensor,可选输入,等于1时停止更新。数据类型、shape需要与params一致。 | ||
| 42 | + * @param [in] lr: 学习率,数据类型DOUBLE。 | ||
| 43 | + * @param [in] beta1: 一阶矩衰减系数,数据类型DOUBLE。 | ||
| 44 | + * @param [in] beta2: 二阶矩衰减系数,数据类型DOUBLE。 | ||
| 45 | + * @param [in] weightDecay: 权重衰减系数,数据类型DOUBLE。 | ||
| 46 | + * @param [in] eps: 防止除数为0,数据类型DOUBLE。 | ||
| 47 | + * @param [in] amsgrad: 是否使用算法的AMSGrad变量,数据类型BOOL。 | ||
| 48 | + * @param [in] maximize: 是否最大化参数,数据类型BOOL。 | ||
| 49 | + * @param [out] workspaceSize: 返回用户在device侧申请的workspace大小。 | ||
| 50 | + * @param [out] executor: 返回op执行器。 | ||
| 51 | + * @return aclnnStatus: 返回状态码。 | ||
| 52 | + */ | ||
| 53 | +ACLNN_API aclnnStatus aclnnFusedAdamGetWorkspaceSize( | ||
| 54 | + const aclTensorList* paramsRef, const aclTensorList* gradsRef, const aclTensorList* expAvgsRef, | ||
| 55 | + const aclTensorList* expAvgSqsRef, const aclTensorList* maxExpAvgSqsRef, const aclTensorList* stateSteps, | ||
| 56 | + const aclTensor* gradScaleOptional, const aclTensor* foundInfOptional, double lr, double beta1, double beta2, | ||
| 57 | + double weightDecay, double eps, bool amsgrad, bool maximize, uint64_t* workspaceSize, aclOpExecutor** executor); | ||
| 58 | + | ||
| 59 | +/** | ||
| 60 | + * @brief aclnnFusedAdam的第二段接口,用于执行计算。 | ||
| 61 | + * | ||
| 62 | + * 算子功能:执行融合SGD优化器。 | ||
| 63 | + * @param [in] workspace: 在device侧申请的workspace内存起址。 | ||
| 64 | + * @param [in] workspaceSize: workspace大小,由aclnnFusedSgdGetWorkspaceSize获取。 | ||
| 65 | + * @param [in] executor: op执行器。 | ||
| 66 | + * @param [in] stream: acl stream流。 | ||
| 67 | + * @return aclnnStatus: 返回状态码。 | ||
| 68 | + */ | ||
| 69 | +ACLNN_API aclnnStatus aclnnFusedAdam(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, | ||
| 70 | + aclrtStream stream); | ||
| 71 | + | ||
| 72 | +#ifdef __cplusplus | ||
| 73 | +} | ||
| 74 | +#endif | ||
| 75 | + | ||
| 76 | +#endif // _ACLNN_FUSED_ADAM_H_ | ||
| @@ -0,0 +1,54 @@ | |||
| 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 fused_adam.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "fused_adam.h" | ||
| 17 | +#include "opdev/make_op_executor.h" | ||
| 18 | +#include "opdev/op_def.h" | ||
| 19 | +#include "opdev/op_dfx.h" | ||
| 20 | +#include "opdev/op_executor.h" | ||
| 21 | +#include "opdev/op_log.h" | ||
| 22 | +#include "opdev/shape_utils.h" | ||
| 23 | +#include "opdev/platform.h" | ||
| 24 | +#include "opdev/format_utils.h" | ||
| 25 | +#include "aclnn_kernels/common/op_error_check.h" | ||
| 26 | + | ||
| 27 | +using namespace op; | ||
| 28 | + | ||
| 29 | +namespace l0op { | ||
| 30 | +OP_TYPE_REGISTER(FusedAdam); | ||
| 31 | + | ||
| 32 | +std::tuple<const aclTensorList*, const aclTensorList*, const aclTensorList*, const aclTensorList*, const aclTensorList*> | ||
| 33 | +FusedAdam(const aclTensorList* paramsRef, const aclTensorList* gradsRef, const aclTensorList* expAvgsRef, | ||
| 34 | + const aclTensorList* expAvgSqsRef, const aclTensorList* maxExpAvgSqsRef, const aclTensorList* stateSteps, | ||
| 35 | + const aclTensor* gradScaleOptional, const aclTensor* foundInfOptional, float lr, float beta1, float beta2, | ||
| 36 | + float weightDecay, float eps, bool amsgrad, bool maximize, aclOpExecutor* executor) | ||
| 37 | +{ | ||
| 38 | + L0_DFX(FusedAdam, paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef, stateSteps, gradScaleOptional, | ||
| 39 | + foundInfOptional, lr, beta1, beta2, weightDecay, eps, amsgrad, maximize); | ||
| 40 | + | ||
| 41 | + auto retAicore = ADD_TO_LAUNCHER_LIST_AICORE( | ||
| 42 | + FusedAdam, | ||
| 43 | + OP_INPUT(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef, stateSteps, gradScaleOptional, | ||
| 44 | + foundInfOptional), | ||
| 45 | + OP_OUTPUT(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef), | ||
| 46 | + OP_ATTR(lr, beta1, beta2, weightDecay, eps, amsgrad, maximize)); | ||
| 47 | + if (retAicore != ACLNN_SUCCESS) { | ||
| 48 | + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "FusedAdam ADD_TO_LAUNCHER_LIST_AICORE failed."); | ||
| 49 | + } | ||
| 50 | + return std::tuple<const aclTensorList*, const aclTensorList*, const aclTensorList*, const aclTensorList*, | ||
| 51 | + const aclTensorList*>(paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, maxExpAvgSqsRef); | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +} // namespace l0op | ||
| @@ -0,0 +1,29 @@ | |||
| 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 fused_adam.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef _OP_API_INC_LEVEL0_OP_FUSED_ADAM_H_ | ||
| 17 | +#define _OP_API_INC_LEVEL0_OP_FUSED_ADAM_H_ | ||
| 18 | + | ||
| 19 | +#include "opdev/op_executor.h" | ||
| 20 | + | ||
| 21 | +namespace l0op { | ||
| 22 | +std::tuple<const aclTensorList*, const aclTensorList*, const aclTensorList*, const aclTensorList*, const aclTensorList*> | ||
| 23 | +FusedAdam(const aclTensorList* paramsRef, const aclTensorList* gradsRef, const aclTensorList* expAvgsRef, | ||
| 24 | + const aclTensorList* expAvgSqsRef, const aclTensorList* maxExpAvgSqsRef, const aclTensorList* stateSteps, | ||
| 25 | + const aclTensor* gradScaleOptional, const aclTensor* foundInfOptional, float lr, float beta1, float beta2, | ||
| 26 | + float weightDecay, float eps, bool amsgrad, bool maximize, aclOpExecutor* executor); | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +#endif // _OP_API_INC_LEVEL0_OP_FUSED_ADAM_H_ | ||
| @@ -0,0 +1,12 @@ | |||
| 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 | +message(STATUS "=== Debug: start ops.optim.fused_adam.graph_plugin.CMakeLists.txt ") | ||
| 12 | +add_graph_plugin_sources() | ||
| @@ -0,0 +1,126 @@ | |||
| 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 fused_adam_def.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#include "register/op_def_registry.h" | ||
| 16 | + | ||
| 17 | +namespace ops { | ||
| 18 | +static constexpr float LR_DEFAULT = 0.001f; | ||
| 19 | +static constexpr float BETA1_DEFAULT = 0.9f; | ||
| 20 | +static constexpr float BETA2_DEFAULT = 0.999f; | ||
| 21 | +static constexpr float WEIGHT_DECAY_DEFAULT = 0.0f; | ||
| 22 | +static constexpr float EPS_DEFAULT = 1e-8f; | ||
| 23 | + | ||
| 24 | +class FusedAdam : public OpDef { | ||
| 25 | +public: | ||
| 26 | + explicit FusedAdam(const char* name) : OpDef(name) | ||
| 27 | + { | ||
| 28 | + this->Input("params") | ||
| 29 | + .ParamType(DYNAMIC) | ||
| 30 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 31 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 32 | + .UnknownShapeFormat( | ||
| 33 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 34 | + .AutoContiguous(); | ||
| 35 | + this->Input("grads") | ||
| 36 | + .ParamType(DYNAMIC) | ||
| 37 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 38 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 39 | + .UnknownShapeFormat( | ||
| 40 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 41 | + .AutoContiguous(); | ||
| 42 | + this->Input("exp_avgs") | ||
| 43 | + .ParamType(DYNAMIC) | ||
| 44 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 45 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 46 | + .UnknownShapeFormat( | ||
| 47 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 48 | + .AutoContiguous(); | ||
| 49 | + this->Input("exp_avg_sqs") | ||
| 50 | + .ParamType(DYNAMIC) | ||
| 51 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 52 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 53 | + .UnknownShapeFormat( | ||
| 54 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 55 | + .AutoContiguous(); | ||
| 56 | + this->Input("max_exp_avg_sqs") | ||
| 57 | + .ParamType(DYNAMIC) | ||
| 58 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 59 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 60 | + .UnknownShapeFormat( | ||
| 61 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 62 | + .AutoContiguous(); | ||
| 63 | + this->Input("state_steps") | ||
| 64 | + .ParamType(DYNAMIC) | ||
| 65 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64}) | ||
| 66 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 67 | + .UnknownShapeFormat( | ||
| 68 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 69 | + .AutoContiguous(); | ||
| 70 | + this->Input("grad_scale") | ||
| 71 | + .ParamType(OPTIONAL) | ||
| 72 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 73 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 74 | + .UnknownShapeFormat( | ||
| 75 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 76 | + .AutoContiguous(); | ||
| 77 | + this->Input("found_inf") | ||
| 78 | + .ParamType(OPTIONAL) | ||
| 79 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 80 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 81 | + .UnknownShapeFormat( | ||
| 82 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 83 | + .AutoContiguous(); | ||
| 84 | + this->Output("params") | ||
| 85 | + .ParamType(DYNAMIC) | ||
| 86 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 87 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 88 | + .UnknownShapeFormat( | ||
| 89 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 90 | + this->Output("grads") | ||
| 91 | + .ParamType(DYNAMIC) | ||
| 92 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 93 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 94 | + .UnknownShapeFormat( | ||
| 95 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 96 | + this->Output("exp_avgs") | ||
| 97 | + .ParamType(DYNAMIC) | ||
| 98 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 99 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 100 | + .UnknownShapeFormat( | ||
| 101 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 102 | + this->Output("exp_avg_sqs") | ||
| 103 | + .ParamType(DYNAMIC) | ||
| 104 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 105 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 106 | + .UnknownShapeFormat( | ||
| 107 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 108 | + this->Output("max_exp_avg_sqs") | ||
| 109 | + .ParamType(DYNAMIC) | ||
| 110 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) | ||
| 111 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 112 | + .UnknownShapeFormat( | ||
| 113 | + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 114 | + this->Attr("lr").AttrType(OPTIONAL).Float(LR_DEFAULT); | ||
| 115 | + this->Attr("beta1").AttrType(OPTIONAL).Float(BETA1_DEFAULT); | ||
| 116 | + this->Attr("beta2").AttrType(OPTIONAL).Float(BETA2_DEFAULT); | ||
| 117 | + this->Attr("weight_decay").AttrType(OPTIONAL).Float(WEIGHT_DECAY_DEFAULT); | ||
| 118 | + this->Attr("eps").AttrType(OPTIONAL).Float(EPS_DEFAULT); | ||
| 119 | + this->Attr("amsgrad").AttrType(OPTIONAL).Bool(false); | ||
| 120 | + this->Attr("maximize").AttrType(OPTIONAL).Bool(false); | ||
| 121 | + this->AICore().AddConfig("ascend950"); | ||
| 122 | + } | ||
| 123 | +}; | ||
| 124 | + | ||
| 125 | +OP_ADD(FusedAdam); | ||
| 126 | +} // namespace ops | ||
| @@ -0,0 +1,135 @@ | |||
| 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 fused_adam_infershape.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "log/log.h" | ||
| 17 | +#include "register/op_impl_registry.h" | ||
| 18 | + | ||
| 19 | +using namespace ge; | ||
| 20 | +static constexpr size_t INPUT_PARAMS_INDEX = 0; | ||
| 21 | +static constexpr size_t INPUT_GRADS_INDEX = 1; | ||
| 22 | +static constexpr size_t INPUT_EXP_AVGS_INDEX = 2; | ||
| 23 | +static constexpr size_t INPUT_EXP_AVG_SQS_INDEX = 3; | ||
| 24 | +static constexpr size_t INPUT_MAX_EXP_AVG_SQS_INDEX = 4; | ||
| 25 | +static constexpr size_t OUTPUT_PARAMS_INDEX = 0; | ||
| 26 | +static constexpr size_t OUTPUT_GRADS_INDEX = 1; | ||
| 27 | +static constexpr size_t OUTPUT_EXP_AVGS_INDEX = 2; | ||
| 28 | +static constexpr size_t OUTPUT_EXP_AVG_SQS_INDEX = 3; | ||
| 29 | +static constexpr size_t OUTPUT_MAX_EXP_AVG_SQS_INDEX = 4; | ||
| 30 | + | ||
| 31 | +namespace ops { | ||
| 32 | +static ge::graphStatus InferShapeForFusedAdam(gert::InferShapeContext* context) | ||
| 33 | +{ | ||
| 34 | + OP_LOGD(context, "Begin to do InferShapeForFusedAdam."); | ||
| 35 | + | ||
| 36 | + auto computeNodeInfo = context->GetComputeNodeInfo(); | ||
| 37 | + OP_CHECK_NULL_WITH_CONTEXT(context, computeNodeInfo); | ||
| 38 | + | ||
| 39 | + auto paramsInstanceInfo = computeNodeInfo->GetInputInstanceInfo(INPUT_PARAMS_INDEX); | ||
| 40 | + OP_CHECK_NULL_WITH_CONTEXT(context, paramsInstanceInfo); | ||
| 41 | + auto inputNum = paramsInstanceInfo->GetInstanceNum(); | ||
| 42 | + if (inputNum == 0) { | ||
| 43 | + OP_LOGE(context, "input num must be greater than 0"); | ||
| 44 | + return ge::GRAPH_FAILED; | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + auto paramsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_PARAMS_INDEX); | ||
| 48 | + OP_CHECK_NULL_WITH_CONTEXT(context, paramsOutInstanceInfo); | ||
| 49 | + auto gradsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_GRADS_INDEX); | ||
| 50 | + OP_CHECK_NULL_WITH_CONTEXT(context, gradsOutInstanceInfo); | ||
| 51 | + auto expAvgsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_EXP_AVGS_INDEX); | ||
| 52 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgsOutInstanceInfo); | ||
| 53 | + auto expAvgSqsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_EXP_AVG_SQS_INDEX); | ||
| 54 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgSqsOutInstanceInfo); | ||
| 55 | + auto maxExpAvgSqsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_MAX_EXP_AVG_SQS_INDEX); | ||
| 56 | + OP_CHECK_NULL_WITH_CONTEXT(context, maxExpAvgSqsOutInstanceInfo); | ||
| 57 | + | ||
| 58 | + for (uint32_t i = 0; i < inputNum; i++) { | ||
| 59 | + const gert::Shape* paramsShape = context->GetDynamicInputShape(INPUT_PARAMS_INDEX, i); | ||
| 60 | + OP_CHECK_NULL_WITH_CONTEXT(context, paramsShape); | ||
| 61 | + const gert::Shape* gradsShape = context->GetDynamicInputShape(INPUT_GRADS_INDEX, i); | ||
| 62 | + OP_CHECK_NULL_WITH_CONTEXT(context, gradsShape); | ||
| 63 | + const gert::Shape* expAvgsShape = context->GetDynamicInputShape(INPUT_EXP_AVGS_INDEX, i); | ||
| 64 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgsShape); | ||
| 65 | + const gert::Shape* expAvgSqsShape = context->GetDynamicInputShape(INPUT_EXP_AVG_SQS_INDEX, i); | ||
| 66 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgSqsShape); | ||
| 67 | + const gert::Shape* maxExpAvgSqsShape = context->GetDynamicInputShape(INPUT_MAX_EXP_AVG_SQS_INDEX, i); | ||
| 68 | + OP_CHECK_NULL_WITH_CONTEXT(context, maxExpAvgSqsShape); | ||
| 69 | + | ||
| 70 | + if (*paramsShape != *gradsShape || *paramsShape != *expAvgsShape || *paramsShape != *expAvgSqsShape || | ||
| 71 | + *paramsShape != *maxExpAvgSqsShape) { | ||
| 72 | + OP_LOGE(context, "params, grads, exp_avgs, exp_avg_sqs and max_exp_avg_sqs should have the same shape"); | ||
| 73 | + return ge::GRAPH_FAILED; | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + gert::Shape* paramsRefShape = context->GetOutputShape(paramsOutInstanceInfo->GetInstanceStart() + i); | ||
| 77 | + OP_CHECK_NULL_WITH_CONTEXT(context, paramsRefShape); | ||
| 78 | + gert::Shape* gradsRefShape = context->GetOutputShape(gradsOutInstanceInfo->GetInstanceStart() + i); | ||
| 79 | + OP_CHECK_NULL_WITH_CONTEXT(context, gradsRefShape); | ||
| 80 | + gert::Shape* expAvgsRefShape = context->GetOutputShape(expAvgsOutInstanceInfo->GetInstanceStart() + i); | ||
| 81 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgsRefShape); | ||
| 82 | + gert::Shape* expAvgSqsRefShape = context->GetOutputShape(expAvgSqsOutInstanceInfo->GetInstanceStart() + i); | ||
| 83 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgSqsRefShape); | ||
| 84 | + gert::Shape* maxExpAvgSqsRefShape = context->GetOutputShape(maxExpAvgSqsOutInstanceInfo->GetInstanceStart() + | ||
| 85 | + i); | ||
| 86 | + OP_CHECK_NULL_WITH_CONTEXT(context, maxExpAvgSqsRefShape); | ||
| 87 | + | ||
| 88 | + *paramsRefShape = *paramsShape; | ||
| 89 | + *gradsRefShape = *gradsShape; | ||
| 90 | + *expAvgsRefShape = *expAvgsShape; | ||
| 91 | + *expAvgSqsRefShape = *expAvgSqsShape; | ||
| 92 | + *maxExpAvgSqsRefShape = *maxExpAvgSqsShape; | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + OP_LOGD(context, "End to do InferShapeForFusedAdam."); | ||
| 96 | + return ge::GRAPH_SUCCESS; | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +static graphStatus InferDataTypeForFusedAdam(gert::InferDataTypeContext* context) | ||
| 100 | +{ | ||
| 101 | + auto computeNodeInfo = context->GetComputeNodeInfo(); | ||
| 102 | + OP_CHECK_NULL_WITH_CONTEXT(context, computeNodeInfo); | ||
| 103 | + | ||
| 104 | + auto paramsInstanceInfo = computeNodeInfo->GetInputInstanceInfo(INPUT_PARAMS_INDEX); | ||
| 105 | + OP_CHECK_NULL_WITH_CONTEXT(context, paramsInstanceInfo); | ||
| 106 | + auto inputNum = paramsInstanceInfo->GetInstanceNum(); | ||
| 107 | + | ||
| 108 | + auto paramsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_PARAMS_INDEX); | ||
| 109 | + OP_CHECK_NULL_WITH_CONTEXT(context, paramsOutInstanceInfo); | ||
| 110 | + auto gradsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_GRADS_INDEX); | ||
| 111 | + OP_CHECK_NULL_WITH_CONTEXT(context, gradsOutInstanceInfo); | ||
| 112 | + auto expAvgsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_EXP_AVGS_INDEX); | ||
| 113 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgsOutInstanceInfo); | ||
| 114 | + auto expAvgSqsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_EXP_AVG_SQS_INDEX); | ||
| 115 | + OP_CHECK_NULL_WITH_CONTEXT(context, expAvgSqsOutInstanceInfo); | ||
| 116 | + auto maxExpAvgSqsOutInstanceInfo = context->GetIrOutputInstanceInfo(OUTPUT_MAX_EXP_AVG_SQS_INDEX); | ||
| 117 | + OP_CHECK_NULL_WITH_CONTEXT(context, maxExpAvgSqsOutInstanceInfo); | ||
| 118 | + | ||
| 119 | + for (uint32_t i = 0; i < inputNum; i++) { | ||
| 120 | + context->SetOutputDataType(paramsOutInstanceInfo->GetInstanceStart() + i, | ||
| 121 | + context->GetDynamicInputDataType(INPUT_PARAMS_INDEX, i)); | ||
| 122 | + context->SetOutputDataType(gradsOutInstanceInfo->GetInstanceStart() + i, | ||
| 123 | + context->GetDynamicInputDataType(INPUT_GRADS_INDEX, i)); | ||
| 124 | + context->SetOutputDataType(expAvgsOutInstanceInfo->GetInstanceStart() + i, | ||
| 125 | + context->GetDynamicInputDataType(INPUT_EXP_AVGS_INDEX, i)); | ||
| 126 | + context->SetOutputDataType(expAvgSqsOutInstanceInfo->GetInstanceStart() + i, | ||
| 127 | + context->GetDynamicInputDataType(INPUT_EXP_AVG_SQS_INDEX, i)); | ||
| 128 | + context->SetOutputDataType(maxExpAvgSqsOutInstanceInfo->GetInstanceStart() + i, | ||
| 129 | + context->GetDynamicInputDataType(INPUT_MAX_EXP_AVG_SQS_INDEX, i)); | ||
| 130 | + } | ||
| 131 | + return GRAPH_SUCCESS; | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +IMPL_OP_INFERSHAPE(FusedAdam).InferShape(InferShapeForFusedAdam).InferDataType(InferDataTypeForFusedAdam); | ||
| 135 | +} // namespace ops | ||
| @@ -0,0 +1,460 @@ | |||
| 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 fused_adam_tiling.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "../op_kernel/fused_adam_tiling_data.h" | ||
| 17 | +#include "fused_adam_tiling.h" | ||
| 18 | +#include "register/op_impl_registry.h" | ||
| 19 | +#include "util/math_util.h" | ||
| 20 | +#include "log/log.h" | ||
| 21 | +#include "tiling/platform/platform_ascendc.h" | ||
| 22 | +#include "op_common/op_host/util/platform_util.h" | ||
| 23 | +#include "platform/platform_infos_def.h" | ||
| 24 | +#include <algorithm> | ||
| 25 | +#include <graph/utils/type_utils.h> | ||
| 26 | + | ||
| 27 | +using namespace std; | ||
| 28 | +namespace optiling { | ||
| 29 | +constexpr uint32_t INPUT_PARAMS_IDX = 0; | ||
| 30 | +constexpr uint32_t INPUT_GRADS_IDX = 1; | ||
| 31 | +constexpr uint32_t INPUT_EXP_AVGS_IDX = 2; | ||
| 32 | +constexpr uint32_t INPUT_EXP_AVG_SQS_IDX = 3; | ||
| 33 | +constexpr uint32_t INPUT_MAX_EXP_AVG_SQS_IDX = 4; | ||
| 34 | +constexpr uint32_t INPUT_STATE_STEPS_IDX = 5; | ||
| 35 | +constexpr uint32_t INPUT_GRAD_SCALE_IDX = 6; | ||
| 36 | +constexpr uint32_t INPUT_FOUND_INF_IDX = 7; | ||
| 37 | +constexpr uint32_t ATTR_LR_IDX = 0; | ||
| 38 | +constexpr uint32_t ATTR_BETA1_IDX = 1; | ||
| 39 | +constexpr uint32_t ATTR_BETA2_IDX = 2; | ||
| 40 | +constexpr uint32_t ATTR_WEIGHT_DECAY_IDX = 3; | ||
| 41 | +constexpr uint32_t ATTR_EPS_IDX = 4; | ||
| 42 | +constexpr uint32_t ATTR_AMSGRAD_IDX = 5; | ||
| 43 | +constexpr uint32_t ATTR_MAXIMIZE_IDX = 6; | ||
| 44 | +constexpr uint32_t FP16_BF16_DTYPE_SIZE = 2; | ||
| 45 | +constexpr uint32_t FP32_DTYPE_SIZE = 4; | ||
| 46 | +static constexpr int32_t MAX_SUPPORT_DIM_NUMS = 8; | ||
| 47 | +static constexpr int32_t BLOCK_SIZE = 32; | ||
| 48 | +static constexpr int64_t SINGLE_CORE_PROCESS_BYTES_LOWER_BOUND = 1024; | ||
| 49 | +static constexpr uint64_t TILING_KEY_FLOAT = 0; | ||
| 50 | +static constexpr uint64_t TILING_KEY_HALF = 1; | ||
| 51 | +static constexpr uint64_t TILING_KEY_BF16 = 2; | ||
| 52 | + | ||
| 53 | +std::string FusedAdamTiling::TilingDataToString() | ||
| 54 | +{ | ||
| 55 | + std::string ans = "lr = " + std::to_string(lr_) + ", beta1 = " + std::to_string(beta1_) + | ||
| 56 | + ", beta2 = " + std::to_string(beta2_) + ", weightDecay = " + std::to_string(weightDecay_) + | ||
| 57 | + ", eps = " + std::to_string(eps_) + ", amsgrad = " + std::to_string(amsgrad_) + | ||
| 58 | + ", maximize = " + std::to_string(maximize_) + | ||
| 59 | + ", useGradScale = " + std::to_string(useGradScale_) + | ||
| 60 | + ", useFoundInf = " + std::to_string(useFoundInf_) + | ||
| 61 | + ", tensorNum = " + std::to_string(tensorNum_) + ", usedCoreNum = " + std::to_string(usedCoreNum_); | ||
| 62 | + ans += "\ni\tcnt\t\n"; | ||
| 63 | + for (uint32_t i = 0; i < tensorNum_; i++) { | ||
| 64 | + ans += std::to_string(i) + "\t" + std::to_string(tensorDataCountList_[i]) + "\n"; | ||
| 65 | + } | ||
| 66 | + ans += "i\tstart\tend\tso\teo\n"; | ||
| 67 | + for (uint32_t i = 0; i < usedCoreNum_; i++) { | ||
| 68 | + ans += std::to_string(i) + "\t" + std::to_string(tensorStartList_[i]) + "\t" + | ||
| 69 | + std::to_string(tensorEndList_[i]) + "\t" + std::to_string(tensorStartOffsetList_[i]) + "\t" + | ||
| 70 | + std::to_string(tensorEndOffsetList_[i]) + "\n"; | ||
| 71 | + } | ||
| 72 | + ans += "TilingKey: " + std::to_string(CalcTilingKey()) + "\n"; | ||
| 73 | + return ans; | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +// get coreNum_, ubSize_, sysWorkspaceSize_ | ||
| 77 | +ge::graphStatus FusedAdamTiling::GetPlatformInfo() | ||
| 78 | +{ | ||
| 79 | + auto platformInfo = tilingContext_->GetPlatformInfo(); | ||
| 80 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, platformInfo); | ||
| 81 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); | ||
| 82 | + coreNum_ = static_cast<uint32_t>(ascendcPlatform.GetCoreNumAiv()); | ||
| 83 | + OP_CHECK_IF(coreNum_ == 0, OP_LOGE(tilingContext_, "coreNum is 0"), return ge::GRAPH_FAILED); | ||
| 84 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize_); | ||
| 85 | + OP_CHECK_IF(ubSize_ == 0, OP_LOGE(tilingContext_, "ubSize is 0"), return ge::GRAPH_FAILED); | ||
| 86 | + sysWorkspaceSize_ = ascendcPlatform.GetLibApiWorkSpaceSize(); | ||
| 87 | + return ge::GRAPH_SUCCESS; | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +ge::graphStatus FusedAdamTiling::GetAttrInfo() | ||
| 91 | +{ | ||
| 92 | + auto* attrs = tilingContext_->GetAttrs(); | ||
| 93 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrs); | ||
| 94 | + | ||
| 95 | + const float* attrLr = attrs->GetAttrPointer<float>(ATTR_LR_IDX); | ||
| 96 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrLr); | ||
| 97 | + lr_ = static_cast<float>(*attrLr); | ||
| 98 | + | ||
| 99 | + const float* attrBeta1 = attrs->GetAttrPointer<float>(ATTR_BETA1_IDX); | ||
| 100 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrBeta1); | ||
| 101 | + beta1_ = static_cast<float>(*attrBeta1); | ||
| 102 | + | ||
| 103 | + const float* attrBeta2 = attrs->GetAttrPointer<float>(ATTR_BETA2_IDX); | ||
| 104 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrBeta2); | ||
| 105 | + beta2_ = static_cast<float>(*attrBeta2); | ||
| 106 | + | ||
| 107 | + const float* attrWeightDecay = attrs->GetAttrPointer<float>(ATTR_WEIGHT_DECAY_IDX); | ||
| 108 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrWeightDecay); | ||
| 109 | + weightDecay_ = static_cast<float>(*attrWeightDecay); | ||
| 110 | + | ||
| 111 | + const float* attrEps = attrs->GetAttrPointer<float>(ATTR_EPS_IDX); | ||
| 112 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrEps); | ||
| 113 | + eps_ = static_cast<float>(*attrEps); | ||
| 114 | + | ||
| 115 | + const bool* attrAmsgrad = attrs->GetAttrPointer<bool>(ATTR_AMSGRAD_IDX); | ||
| 116 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrAmsgrad); | ||
| 117 | + amsgrad_ = static_cast<uint32_t>(*attrAmsgrad ? 1 : 0); | ||
| 118 | + | ||
| 119 | + const bool* attrMaximize = attrs->GetAttrPointer<bool>(ATTR_MAXIMIZE_IDX); | ||
| 120 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, attrMaximize); | ||
| 121 | + maximize_ = static_cast<uint32_t>(*attrMaximize ? 1 : 0); | ||
| 122 | + | ||
| 123 | + return ge::GRAPH_SUCCESS; | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +uint32_t inline FusedAdamTiling::GetOptionalInput(uint32_t OPTIONAL_INPUT_IDX) | ||
| 127 | +{ | ||
| 128 | + auto tempInput = tilingContext_->GetOptionalInputTensor(OPTIONAL_INPUT_IDX); | ||
| 129 | + if (tempInput != nullptr) { | ||
| 130 | + const gert::Shape& inputShape = tempInput->GetStorageShape(); | ||
| 131 | + uint32_t dims = inputShape.GetDimNum(); | ||
| 132 | + bool flag = true; | ||
| 133 | + if (dims > 0) { | ||
| 134 | + for (uint32_t i = 0; i < dims; i++) { | ||
| 135 | + int64_t dimValue = inputShape.GetDim(i); | ||
| 136 | + if (dimValue == 0) { | ||
| 137 | + flag = false; | ||
| 138 | + break; | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | + } | ||
| 142 | + if (flag) { | ||
| 143 | + return 1; | ||
| 144 | + } else { | ||
| 145 | + return 0; | ||
| 146 | + } | ||
| 147 | + } else { | ||
| 148 | + return 0; | ||
| 149 | + } | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +ge::graphStatus FusedAdamTiling::CheckShapeAllPositive(const gert::Shape& shape, uint32_t idx) | ||
| 153 | +{ | ||
| 154 | + for (size_t i = 0; i < shape.GetDimNum(); i++) { | ||
| 155 | + OP_CHECK_IF(shape.GetDim(i) < 0, | ||
| 156 | + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( | ||
| 157 | + tilingContext_->GetNodeName(), "x", std::to_string(shape.GetDim(i)).c_str(), | ||
| 158 | + "All axes of tensors in the tensor list must be 0 or positive numbers. Currently, the " + | ||
| 159 | + std::to_string(i) + "th axis of the " + std::to_string(idx) + | ||
| 160 | + "th tensor in the tensor list does not meet the condition"), | ||
| 161 | + return ge::GRAPH_FAILED); | ||
| 162 | + } | ||
| 163 | + return ge::GRAPH_SUCCESS; | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +// check InputTensorList[paramIdx][tensorIdx] if is same with given shape and dtype. | ||
| 167 | +ge::graphStatus FusedAdamTiling::CheckShapeAndDType(uint32_t paramIdx, uint32_t tensorIdx, | ||
| 168 | + const gert::Shape& paramsShape, ge::DataType paramsDtype, | ||
| 169 | + const char* name) | ||
| 170 | +{ | ||
| 171 | + auto shapePtr = tilingContext_->GetDynamicInputShape(paramIdx, tensorIdx); | ||
| 172 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, shapePtr); | ||
| 173 | + if (shapePtr->GetStorageShape() != paramsShape) { | ||
| 174 | + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(tilingContext_->GetNodeName(), name, | ||
| 175 | + Ops::Base::ToString(shapePtr->GetStorageShape()).c_str(), | ||
| 176 | + "should have the same shape as params"); | ||
| 177 | + return ge::GRAPH_FAILED; | ||
| 178 | + } | ||
| 179 | + auto dtypeInputInner = tilingContext_->GetDynamicInputDesc(paramIdx, tensorIdx); | ||
| 180 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, dtypeInputInner); | ||
| 181 | + auto dtype = dtypeInputInner->GetDataType(); | ||
| 182 | + if (dtype != paramsDtype) { | ||
| 183 | + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(tilingContext_->GetNodeName(), name, Ops::Base::ToString(dtype).c_str(), | ||
| 184 | + "should have the same dtype as params"); | ||
| 185 | + return ge::GRAPH_FAILED; | ||
| 186 | + } | ||
| 187 | + return ge::GRAPH_SUCCESS; | ||
| 188 | +}; | ||
| 189 | + | ||
| 190 | +ge::graphStatus FusedAdamTiling::CheckStateSteps() | ||
| 191 | +{ | ||
| 192 | + auto computeNodeInfo = tilingContext_->GetComputeNodeInfo(); | ||
| 193 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, computeNodeInfo); | ||
| 194 | + | ||
| 195 | + auto anchorInstanceInfo = computeNodeInfo->GetInputInstanceInfo(INPUT_STATE_STEPS_IDX); | ||
| 196 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, anchorInstanceInfo); | ||
| 197 | + | ||
| 198 | + OP_CHECK_IF(tensorNum_ != anchorInstanceInfo->GetInstanceNum(), | ||
| 199 | + OP_LOGE(tilingContext_, "The stateSteps tensorList length is not match params."), | ||
| 200 | + return ge::GRAPH_FAILED); | ||
| 201 | + for (uint32_t i = 0; i < tensorNum_; i++) { | ||
| 202 | + auto tempDesc = tilingContext_->GetDynamicInputDesc(INPUT_STATE_STEPS_IDX, i); | ||
| 203 | + OP_CHECK_IF(tempDesc == nullptr, OP_LOGE(tilingContext_, "The stateSteps %u desc is null.", i), | ||
| 204 | + return ge::GRAPH_FAILED); | ||
| 205 | + auto tempDtype = tempDesc->GetDataType(); | ||
| 206 | + // Determine whether all data types are consistent. | ||
| 207 | + if (scalarType_ == ge::DT_UNDEFINED) { | ||
| 208 | + scalarType_ = tempDtype; | ||
| 209 | + if ((scalarType_ != ge::DT_FLOAT) && (scalarType_ != ge::DT_INT64)) { | ||
| 210 | + OP_LOGE_FOR_INVALID_DTYPE(tilingContext_->GetNodeName(), "stepStates", | ||
| 211 | + Ops::Base::ToString(scalarType_).c_str(), "float and int64"); | ||
| 212 | + return ge::GRAPH_FAILED; | ||
| 213 | + } | ||
| 214 | + } else if (tempDtype != scalarType_) { | ||
| 215 | + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( | ||
| 216 | + tilingContext_->GetNodeName(), "params", ge::TypeUtils::DataTypeToSerialString(scalarType_).c_str(), | ||
| 217 | + ("The dtypes of all tensors in the tensor list must be the same. " | ||
| 218 | + "Currently, the dtype of the " + | ||
| 219 | + std::to_string(i) + "th tensor is inconsistent with that (" + | ||
| 220 | + ge::TypeUtils::DataTypeToSerialString(scalarType_) + ") of other tensors") | ||
| 221 | + .c_str()); | ||
| 222 | + return ge::GRAPH_FAILED; | ||
| 223 | + } | ||
| 224 | + } | ||
| 225 | + return ge::GRAPH_SUCCESS; | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +ge::graphStatus FusedAdamTiling::GetInputTensorInfo() | ||
| 229 | +{ | ||
| 230 | + auto computeNodeInfo = tilingContext_->GetComputeNodeInfo(); | ||
| 231 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, computeNodeInfo); | ||
| 232 | + | ||
| 233 | + auto anchorInstanceInfo = computeNodeInfo->GetInputInstanceInfo(INPUT_PARAMS_IDX); | ||
| 234 | + OP_CHECK_NULL_WITH_CONTEXT(tilingContext_, anchorInstanceInfo); | ||
| 235 | + | ||
| 236 | + tensorNum_ = anchorInstanceInfo->GetInstanceNum(); | ||
| 237 | + OP_CHECK_IF( | ||
| 238 | + tensorNum_ > MAX_TENSOR_CONT_950 || tensorNum_ <= 0, | ||
| 239 | + OP_LOGE_FOR_INVALID_TENSORNUM(tilingContext_->GetNodeName(), "params", static_cast<int64_t>(tensorNum_), | ||
| 240 | + ("within the range [1, " + std::to_string(MAX_TENSOR_CONT_950) + "]").c_str()), | ||
| 241 | + return ge::GRAPH_FAILED); | ||
| 242 | + | ||
| 243 | + useGradScale_ = GetOptionalInput(INPUT_GRAD_SCALE_IDX); | ||
| 244 | + useFoundInf_ = GetOptionalInput(INPUT_FOUND_INF_IDX); | ||
| 245 | + | ||
| 246 | + totalDataCount_ = 0; | ||
| 247 | + dataType_ = ge::DT_UNDEFINED; | ||
| 248 | + for (uint32_t i = 0; i < tensorNum_; i++) { | ||
| 249 | + auto tempDesc = tilingContext_->GetDynamicInputDesc(INPUT_PARAMS_IDX, i); | ||
| 250 | + OP_CHECK_IF(tempDesc == nullptr, OP_LOGE(tilingContext_, "The input %u desc is null.", i), | ||
| 251 | + return ge::GRAPH_FAILED); | ||
| 252 | + auto paramsDtype = tempDesc->GetDataType(); | ||
| 253 | + // Determine whether all data types are consistent. | ||
| 254 | + if (dataType_ == ge::DT_UNDEFINED) { | ||
| 255 | + dataType_ = paramsDtype; | ||
| 256 | + if ((dataType_ != ge::DT_FLOAT) && (dataType_ != ge::DT_BF16) && (dataType_ != ge::DT_FLOAT16)) { | ||
| 257 | + OP_LOGE_FOR_INVALID_DTYPE(tilingContext_->GetNodeName(), "params/grads/exp_avgs/exp_avg_sqs", | ||
| 258 | + Ops::Base::ToString(paramsDtype).c_str(), "float16, bfloat16 and float"); | ||
| 259 | + return ge::GRAPH_FAILED; | ||
| 260 | + } | ||
| 261 | + } else if (paramsDtype != dataType_) { | ||
| 262 | + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( | ||
| 263 | + tilingContext_->GetNodeName(), "params", ge::TypeUtils::DataTypeToSerialString(paramsDtype).c_str(), | ||
| 264 | + ("The dtypes of all tensors in the tensor list must be the same. " | ||
| 265 | + "Currently, the dtype of the " + | ||
| 266 | + std::to_string(i) + "th tensor is inconsistent with that (" + | ||
| 267 | + ge::TypeUtils::DataTypeToSerialString(dataType_) + ") of other tensors") | ||
| 268 | + .c_str()); | ||
| 269 | + return ge::GRAPH_FAILED; | ||
| 270 | + } | ||
| 271 | + auto paramsShape = tilingContext_->GetDynamicInputShape(0, i); | ||
| 272 | + OP_CHECK_IF(paramsShape == nullptr, OP_LOGE(tilingContext_, "The input %u shape is null.", i), | ||
| 273 | + return ge::GRAPH_FAILED); | ||
| 274 | + // check max dim | ||
| 275 | + OP_CHECK_IF(paramsShape->GetStorageShape().GetDimNum() > MAX_SUPPORT_DIM_NUMS, | ||
| 276 | + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( | ||
| 277 | + tilingContext_->GetNodeName(), "params", | ||
| 278 | + std::to_string(paramsShape->GetStorageShape().GetDimNum()).c_str(), | ||
| 279 | + "The shape dim of the " + std::to_string(i) + | ||
| 280 | + "th tensor in the tensor list should be less than or equal to 8"), | ||
| 281 | + return ge::GRAPH_FAILED); | ||
| 282 | + if (CheckShapeAndDType(INPUT_GRADS_IDX, i, paramsShape->GetStorageShape(), paramsDtype, "grads") != | ||
| 283 | + ge::GRAPH_SUCCESS) { | ||
| 284 | + return ge::GRAPH_FAILED; | ||
| 285 | + } | ||
| 286 | + if (CheckShapeAndDType(INPUT_EXP_AVGS_IDX, i, paramsShape->GetStorageShape(), paramsDtype, "exp_avgs") != | ||
| 287 | + ge::GRAPH_SUCCESS) { | ||
| 288 | + return ge::GRAPH_FAILED; | ||
| 289 | + } | ||
| 290 | + if (CheckShapeAndDType(INPUT_EXP_AVG_SQS_IDX, i, paramsShape->GetStorageShape(), paramsDtype, "exp_avg_sqs") != | ||
| 291 | + ge::GRAPH_SUCCESS) { | ||
| 292 | + return ge::GRAPH_FAILED; | ||
| 293 | + } | ||
| 294 | + if (amsgrad_ != 0) { | ||
| 295 | + if (CheckShapeAndDType(INPUT_MAX_EXP_AVG_SQS_IDX, i, paramsShape->GetStorageShape(), paramsDtype, | ||
| 296 | + "max_exp_avg_sqs") != ge::GRAPH_SUCCESS) { | ||
| 297 | + return ge::GRAPH_FAILED; | ||
| 298 | + } | ||
| 299 | + } | ||
| 300 | + if (CheckStateSteps() != ge::GRAPH_SUCCESS) { | ||
| 301 | + return ge::GRAPH_FAILED; | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + // Make a 32-byte alignment for each Tensor | ||
| 305 | + tensorDataCountList_[i] = paramsShape->GetStorageShape().GetShapeSize(); | ||
| 306 | + if (CheckShapeAllPositive(paramsShape->GetStorageShape(), i) != ge::GRAPH_SUCCESS) { | ||
| 307 | + return ge::GRAPH_FAILED; | ||
| 308 | + } | ||
| 309 | + totalDataCount_ += tensorDataCountList_[i]; | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + return ge::GRAPH_SUCCESS; | ||
| 313 | +} | ||
| 314 | + | ||
| 315 | +ge::graphStatus FusedAdamTiling::CalcTilingData() | ||
| 316 | +{ | ||
| 317 | + int64_t sizePerElem = ge::GetSizeByDataType(dataType_); | ||
| 318 | + if (sizePerElem == 0) { | ||
| 319 | + OP_LOGE(tilingContext_, "sizePerElem must be greater than 0"); | ||
| 320 | + return ge::GRAPH_FAILED; | ||
| 321 | + } | ||
| 322 | + int64_t elementsPerBlock = BLOCK_SIZE / sizePerElem; | ||
| 323 | + int64_t blocksPerCore = SINGLE_CORE_PROCESS_BYTES_LOWER_BOUND / BLOCK_SIZE; | ||
| 324 | + usedCoreNum_ = std::min<uint64_t>(coreNum_, MAX_CORE_CONT_950); // just defense | ||
| 325 | + // 1. 计算每个张量的块数 | ||
| 326 | + uint64_t tensorBlockCount[MAX_TENSOR_CONT_950]; | ||
| 327 | + int64_t totalBlocks = 0; | ||
| 328 | + for (int64_t i = 0; i < tensorNum_; ++i) { | ||
| 329 | + tensorBlockCount[i] = (tensorDataCountList_[i] + elementsPerBlock - 1) / elementsPerBlock; | ||
| 330 | + (tensorDataCountList_[i] + elementsPerBlock - 1) / elementsPerBlock; | ||
| 331 | + totalBlocks += tensorBlockCount[i]; | ||
| 332 | + } | ||
| 333 | + uint32_t tempBlockPerCore = (totalBlocks + usedCoreNum_ - 1) / usedCoreNum_; | ||
| 334 | + blocksPerCore = max(blocksPerCore, static_cast<int64_t>(tempBlockPerCore)); | ||
| 335 | + if (blocksPerCore == 0) { | ||
| 336 | + OP_LOGE(tilingContext_, "blocksPerCore must be greater than 0"); | ||
| 337 | + return ge::GRAPH_FAILED; | ||
| 338 | + } | ||
| 339 | + usedCoreNum_ = (totalBlocks + blocksPerCore - 1) / blocksPerCore; | ||
| 340 | + if (totalDataCount_ == 0) { | ||
| 341 | + usedCoreNum_ = 1; | ||
| 342 | + tensorStartList_[0] = 0; | ||
| 343 | + tensorEndList_[0] = 0; | ||
| 344 | + tensorStartOffsetList_[0] = 0; | ||
| 345 | + tensorEndOffsetList_[0] = 0; | ||
| 346 | + return ge::GRAPH_SUCCESS; | ||
| 347 | + } | ||
| 348 | + int64_t tensorIdx = 0; // 当前张量索引 | ||
| 349 | + int64_t blockOffsetInTensor = 0; // 当前张量内的元素偏移(以elementsPerBlock为单位) | ||
| 350 | + for (uint32_t coreIdx = 0; coreIdx < usedCoreNum_; coreIdx++) { | ||
| 351 | + int64_t remainingBlocks = (coreIdx == usedCoreNum_ - 1) ? | ||
| 352 | + (totalBlocks - coreIdx * blocksPerCore) // 最后一个核:剩余块 | ||
| 353 | + : | ||
| 354 | + blocksPerCore; | ||
| 355 | + tensorStartList_[coreIdx] = tensorIdx; | ||
| 356 | + tensorStartOffsetList_[coreIdx] = blockOffsetInTensor * elementsPerBlock; | ||
| 357 | + // 消耗 coreBlocks 个块 | ||
| 358 | + while ((tensorBlockCount[tensorIdx] - blockOffsetInTensor) < remainingBlocks) { | ||
| 359 | + remainingBlocks -= tensorBlockCount[tensorIdx] - blockOffsetInTensor; | ||
| 360 | + blockOffsetInTensor = 0; | ||
| 361 | + tensorIdx++; | ||
| 362 | + } | ||
| 363 | + // here tensorBlockCount[tensorIdx] >= remainingBlocks | ||
| 364 | + tensorEndList_[coreIdx] = tensorIdx; | ||
| 365 | + if ((blockOffsetInTensor + remainingBlocks) == tensorBlockCount[tensorIdx]) { | ||
| 366 | + // 可能存在尾块不对齐 覆写之 | ||
| 367 | + tensorEndOffsetList_[coreIdx] = tensorDataCountList_[tensorIdx]; | ||
| 368 | + // both tensor and core match end | ||
| 369 | + tensorIdx++; | ||
| 370 | + blockOffsetInTensor = 0; | ||
| 371 | + } else { | ||
| 372 | + blockOffsetInTensor += remainingBlocks; | ||
| 373 | + tensorEndOffsetList_[coreIdx] = blockOffsetInTensor * elementsPerBlock; | ||
| 374 | + } | ||
| 375 | + } | ||
| 376 | + return ge::GRAPH_SUCCESS; | ||
| 377 | +} | ||
| 378 | + | ||
| 379 | +uint64_t FusedAdamTiling::CalcTilingKey() | ||
| 380 | +{ | ||
| 381 | + switch (dataType_) { | ||
| 382 | + case ge::DT_FLOAT: | ||
| 383 | + return TILING_KEY_FLOAT; | ||
| 384 | + case ge::DT_FLOAT16: | ||
| 385 | + return TILING_KEY_HALF; | ||
| 386 | + case ge::DT_BF16: | ||
| 387 | + return TILING_KEY_BF16; | ||
| 388 | + default: | ||
| 389 | + return 0; | ||
| 390 | + } | ||
| 391 | +} | ||
| 392 | + | ||
| 393 | +void FusedAdamTiling::SetTilingData(FusedAdamTilingData* tilingData) | ||
| 394 | +{ | ||
| 395 | + tilingData->lr = lr_; | ||
| 396 | + tilingData->beta1 = beta1_; | ||
| 397 | + tilingData->beta2 = beta2_; | ||
| 398 | + tilingData->weightDecay = weightDecay_; | ||
| 399 | + tilingData->eps = eps_; | ||
| 400 | + tilingData->amsgrad = amsgrad_; | ||
| 401 | + tilingData->maximize = maximize_; | ||
| 402 | + tilingData->useGradScale = useGradScale_; | ||
| 403 | + tilingData->useFoundInf = useFoundInf_; | ||
| 404 | + tilingData->tensorNum = tensorNum_; | ||
| 405 | + tilingData->usedCoreNum = usedCoreNum_; | ||
| 406 | + for (uint32_t i = 0; i < tensorNum_; i++) { | ||
| 407 | + tilingData->tensorDataCountList_[i] = tensorDataCountList_[i]; | ||
🔴 Critical 变更行:第56行类内声明 建议:声明与定义统一为 ![]() ![]() Incorrect? | |||
| 408 | + } | ||
| 409 | + for (uint32_t i = tensorNum_; i < MAX_TENSOR_CONT_950; i++) { | ||
| 410 | + tilingData->tensorDataCountList_[i] = 0; | ||
| 411 | + } | ||
| 412 | + for (uint32_t i = 0; i < usedCoreNum_; i++) { | ||
| 413 | + tilingData->tensorStartList_[i] = tensorStartList_[i]; | ||
| 414 | + tilingData->tensorEndList_[i] = tensorEndList_[i]; | ||
| 415 | + tilingData->tensorStartOffsetList_[i] = tensorStartOffsetList_[i]; | ||
| 416 | + tilingData->tensorEndOffsetList_[i] = tensorEndOffsetList_[i]; | ||
| 417 | + } | ||
| 418 | + for (uint32_t i = usedCoreNum_; i < MAX_CORE_CONT_950; i++) { | ||
| 419 | + tilingData->tensorStartList_[i] = 0; | ||
| 420 | + tilingData->tensorEndList_[i] = 0; | ||
| 421 | + tilingData->tensorStartOffsetList_[i] = 0; | ||
| 422 | + tilingData->tensorEndOffsetList_[i] = 0; | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + size_t* workspaceSize = tilingContext_->GetWorkspaceSizes(1); | ||
| 426 | + *workspaceSize = sysWorkspaceSize_; | ||
| 427 | + tilingContext_->SetTilingKey(CalcTilingKey()); | ||
| 428 | + tilingContext_->SetBlockDim(usedCoreNum_); | ||
| 429 | +} | ||
| 430 | + | ||
| 431 | +ge::graphStatus FusedAdamTilingFunc(gert::TilingContext* context) | ||
| 432 | +{ | ||
| 433 | + OP_LOGD(context, "FusedAdamTilingFunc"); | ||
| 434 | + FusedAdamTiling tilingGenerator(context); | ||
| 435 | + | ||
| 436 | + OP_CHECK_IF(tilingGenerator.GetPlatformInfo() != ge::GRAPH_SUCCESS, OP_LOGE(context, "GetPlatformInfo error"), | ||
| 437 | + return ge::GRAPH_FAILED); | ||
| 438 | + OP_CHECK_IF(tilingGenerator.GetAttrInfo() != ge::GRAPH_SUCCESS, OP_LOGE(context, "GetAttrInfo error"), | ||
| 439 | + return ge::GRAPH_FAILED); | ||
| 440 | + OP_CHECK_IF(tilingGenerator.GetInputTensorInfo() != ge::GRAPH_SUCCESS, OP_LOGE(context, "GetInputTensorInfo error"), | ||
| 441 | + return ge::GRAPH_FAILED); | ||
| 442 | + OP_CHECK_IF(tilingGenerator.CalcTilingData() != ge::GRAPH_SUCCESS, OP_LOGE(context, "CalcTilingData error"), | ||
🔴 Critical 变更行:第442行 建议:定义 ![]() ![]() Incorrect? | |||
| 443 | + return ge::GRAPH_FAILED); | ||
| 444 | + | ||
| 445 | + FusedAdamTilingData* tilingData = context->GetTilingData<FusedAdamTilingData>(); | ||
| 446 | + OP_CHECK_NULL_WITH_CONTEXT(context, tilingData); | ||
| 447 | + OP_CHECK_IF(memset_s(tilingData, sizeof(FusedAdamTilingData), 0, sizeof(FusedAdamTilingData)) != EOK, | ||
| 448 | + OP_LOGE(context, "set tiling data error"), return ge::GRAPH_FAILED); | ||
| 449 | + tilingGenerator.SetTilingData(tilingData); | ||
| 450 | + OP_LOGD(context, "tiling data: %s", tilingGenerator.TilingDataToString().c_str()); | ||
| 451 | + return ge::GRAPH_SUCCESS; | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +ge::graphStatus TilingPrepare4FusedAdam([[maybe_unused]] gert::TilingParseContext* context) | ||
| 455 | +{ | ||
| 456 | + return ge::GRAPH_SUCCESS; | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +IMPL_OP_OPTILING(FusedAdam).Tiling(FusedAdamTilingFunc).TilingParse<FusedAdamCompileInfo>(TilingPrepare4FusedAdam); | ||
| 460 | +} // namespace optiling | ||
| @@ -0,0 +1,74 @@ | |||
| 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 fused_adam_tiling.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef _OPS_BUILD_IN_OP_TILING_RUNTIME_FUSED_ADAM_TILING_H_ | ||
| 17 | +#define _OPS_BUILD_IN_OP_TILING_RUNTIME_FUSED_ADAM_TILING_H_ | ||
| 18 | + | ||
| 19 | +#include "register/tilingdata_base.h" | ||
| 20 | +#include "op_host/tiling_base_util.h" | ||
| 21 | +#include "../op_kernel/fused_adam_tiling_data.h" | ||
| 22 | + | ||
| 23 | +namespace optiling { | ||
| 24 | + | ||
| 25 | +struct FusedAdamCompileInfo {}; | ||
| 26 | + | ||
| 27 | +class FusedAdamTiling { | ||
| 28 | +public: | ||
| 29 | + explicit FusedAdamTiling(gert::TilingContext* context) : tilingContext_(context) {}; | ||
| 30 | + | ||
| 31 | + ge::graphStatus CalcTilingData(); | ||
| 32 | + uint64_t CalcTilingKey(); | ||
| 33 | + void SetTilingData(FusedAdamTilingData* tilingData); | ||
| 34 | + ge::graphStatus GetPlatformInfo(); | ||
| 35 | + ge::graphStatus GetAttrInfo(); | ||
| 36 | + ge::graphStatus GetInputTensorInfo(); | ||
| 37 | + uint32_t GetOptionalInput(uint32_t OPTIONAL_INPUT_IDX); | ||
| 38 | + ge::graphStatus CheckShapeAllPositive(const gert::Shape& shape, uint32_t idx); | ||
| 39 | + std::string TilingDataToString(); | ||
| 40 | + ge::graphStatus CheckShapeAndDType(uint32_t paramIdx, uint32_t tensorIdx, const gert::Shape& paramsShape, | ||
| 41 | + ge::DataType, const char* name); | ||
| 42 | + ge::graphStatus CheckStateSteps(); | ||
| 43 | + | ||
| 44 | +private: | ||
| 45 | + gert::TilingContext* tilingContext_; | ||
| 46 | + | ||
| 47 | + float lr_; | ||
| 48 | + float beta1_; | ||
| 49 | + float beta2_; | ||
| 50 | + float weightDecay_; | ||
| 51 | + float eps_; | ||
| 52 | + uint32_t amsgrad_; | ||
| 53 | + uint32_t maximize_; | ||
| 54 | + uint32_t useGradScale_; | ||
| 55 | + uint32_t useFoundInf_; | ||
| 56 | + | ||
| 57 | + uint32_t coreNum_; | ||
| 58 | + uint64_t ubSize_; | ||
| 59 | + uint64_t sysWorkspaceSize_; | ||
| 60 | + | ||
| 61 | + uint32_t usedCoreNum_; | ||
| 62 | + | ||
| 63 | + ge::DataType dataType_ = ge::DT_UNDEFINED; | ||
| 64 | + ge::DataType scalarType_ = ge::DT_UNDEFINED; | ||
| 65 | + uint32_t tensorNum_; | ||
| 66 | + uint64_t totalDataCount_ = 0; | ||
| 67 | + uint64_t tensorDataCountList_[MAX_TENSOR_CONT_950] = {0}; | ||
| 68 | + uint32_t tensorStartList_[MAX_CORE_CONT_950] = {0}; | ||
| 69 | + uint32_t tensorEndList_[MAX_CORE_CONT_950] = {0}; | ||
| 70 | + uint64_t tensorStartOffsetList_[MAX_CORE_CONT_950] = {0}; | ||
| 71 | + uint64_t tensorEndOffsetList_[MAX_CORE_CONT_950] = {0}; | ||
| 72 | +}; | ||
| 73 | +} // namespace optiling | ||
| 74 | +#endif // _OPS_BUILD_IN_OP_TILING_RUNTIME_FUSED_ADAMW_TILING_H_ | ||
| @@ -0,0 +1,72 @@ | |||
| 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 fused_adam.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#include "kernel_operator_list_tensor_intf.h" | ||
| 16 | +#include "fused_adam_regbase.h" | ||
| 17 | +#include "fused_adam_tiling_data.h" | ||
| 18 | + | ||
| 19 | +using namespace AscendC; | ||
| 20 | +using namespace FusedAdam; | ||
| 21 | + | ||
| 22 | +extern "C" __global__ __aicore__ void fused_adam(GM_ADDR params, GM_ADDR grads, GM_ADDR exp_avgs, GM_ADDR exp_avg_sqs, | ||
| 23 | + GM_ADDR max_exp_avg_sqs, GM_ADDR state_steps, GM_ADDR grad_scale, | ||
| 24 | + GM_ADDR found_inf, GM_ADDR params_ref, GM_ADDR grads_ref, | ||
| 25 | + GM_ADDR exp_avgs_ref, GM_ADDR exp_avg_sqs_ref, | ||
| 26 | + GM_ADDR max_exp_avg_sqs_ref, GM_ADDR workspace, GM_ADDR tiling) | ||
| 27 | +{ | ||
| 28 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); | ||
| 29 | + AscendC::TPipe pipe; | ||
| 30 | + REGISTER_TILING_DEFAULT(FusedAdamTilingData); | ||
| 31 | + GET_TILING_DATA_WITH_STRUCT(FusedAdamTilingData, tilingData, tiling); | ||
| 32 | + | ||
Outdated 🔴 Critical 变更行:第30/35/40行 建议:改为对象定义 ![]() ![]() Incorrect? | |||
| 33 | + bool amsgrad_ = tilingData.amsgrad == 1 ? true : false; | ||
| 34 | + | ||
| 35 | + if (TILING_KEY_IS(0)) { | ||
| 36 | + if (amsgrad_) { | ||
| 37 | + FusedAdamKernelRegBase<float, true> op(&pipe); | ||
| 38 | + op.Init(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, grad_scale, found_inf, | ||
| 39 | + params_ref, grads_ref, exp_avgs_ref, exp_avg_sqs_ref, max_exp_avg_sqs_ref, tilingData); | ||
| 40 | + op.Process(); | ||
| 41 | + } else { | ||
| 42 | + FusedAdamKernelRegBase<float, false> op(&pipe); | ||
| 43 | + op.Init(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, grad_scale, found_inf, | ||
| 44 | + params_ref, grads_ref, exp_avgs_ref, exp_avg_sqs_ref, max_exp_avg_sqs_ref, tilingData); | ||
| 45 | + op.Process(); | ||
| 46 | + } | ||
| 47 | + } else if (TILING_KEY_IS(1)) { | ||
| 48 | + if (amsgrad_) { | ||
| 49 | + FusedAdamKernelRegBase<half, true> op(&pipe); | ||
| 50 | + op.Init(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, grad_scale, found_inf, | ||
| 51 | + params_ref, grads_ref, exp_avgs_ref, exp_avg_sqs_ref, max_exp_avg_sqs_ref, tilingData); | ||
| 52 | + op.Process(); | ||
| 53 | + } else { | ||
| 54 | + FusedAdamKernelRegBase<half, false> op(&pipe); | ||
| 55 | + op.Init(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, grad_scale, found_inf, | ||
| 56 | + params_ref, grads_ref, exp_avgs_ref, exp_avg_sqs_ref, max_exp_avg_sqs_ref, tilingData); | ||
| 57 | + op.Process(); | ||
| 58 | + } | ||
| 59 | + } else if (TILING_KEY_IS(2)) { | ||
| 60 | + if (amsgrad_) { | ||
| 61 | + FusedAdamKernelRegBase<bfloat16_t, true> op(&pipe); | ||
| 62 | + op.Init(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, grad_scale, found_inf, | ||
| 63 | + params_ref, grads_ref, exp_avgs_ref, exp_avg_sqs_ref, max_exp_avg_sqs_ref, tilingData); | ||
| 64 | + op.Process(); | ||
| 65 | + } else { | ||
| 66 | + FusedAdamKernelRegBase<bfloat16_t, false> op(&pipe); | ||
| 67 | + op.Init(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, grad_scale, found_inf, | ||
| 68 | + params_ref, grads_ref, exp_avgs_ref, exp_avg_sqs_ref, max_exp_avg_sqs_ref, tilingData); | ||
| 69 | + op.Process(); | ||
| 70 | + } | ||
| 71 | + } | ||
| 72 | +} | ||


算子名称应该是fused_adam