Merged
新增situglu和situglugrad算子 #8651
guijianweiAdd on Aug 13
新增situglu和situglugrad算子 #8651
Merged
Merged fromguijianwei/ops-nnsitu_commitintocann/ops-nnmaster
Total: 55 files changed+5398-0
| @@ -9,9 +9,13 @@ | |||
| 9 | # ----------------------------------------------------------------------------------------------------------- | 9 | # ----------------------------------------------------------------------------------------------------------- |
| 10 | 10 | ||
| 11 | __all__ = [ | 11 | __all__ = [ |
| 12 | + "situ_glu", | ||
| 13 | + "situ_glu_grad", | ||
| 12 | "swiglu_group", | 14 | "swiglu_group", |
| 13 | "swiglu_group_quant", | 15 | "swiglu_group_quant", |
| 14 | ] | 16 | ] |
| 15 | 17 | ||
| 18 | +from .situ_glu import situ_glu | ||
| 19 | +from .situ_glu_grad import situ_glu_grad | ||
| 16 | from .swiglu_group import swiglu_group | 20 | from .swiglu_group import swiglu_group |
| 17 | from .swiglu_group_quant import swiglu_group_quant | 21 | from .swiglu_group_quant import swiglu_group_quant |
| @@ -0,0 +1,20 @@ | |||
| 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: CURRENT_DIRS =${CURRENT_DIRS} ") | ||
| 12 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 13 | +if(NOT ENABLE_TEST AND NOT BENCHMARK) | ||
| 14 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 15 | +endif() | ||
| 16 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 17 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 18 | + add_subdirectory(${SUB_DIR}) | ||
| 19 | + endif() | ||
| 20 | +endforeach() | ||
| @@ -0,0 +1,130 @@ | |||
| 1 | +# SituGlu | ||
| 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 | +- 算子功能:SiTU门控线性单元(SiTU Gated Linear Unit)激活函数。对输入张量x沿指定维度切分为门控(gate)与上路径(up)两半,按SiTU公式计算输出。 | ||
| 17 | + | ||
| 18 | +- 计算公式或计算流程: | ||
| 19 | + | ||
| 20 | + 对给定的输入张量x,其维度为[a, b, c, d, e, f, g, ...],算子SituGlu对其进行以下计算: | ||
| 21 | + | ||
| 22 | + 1. 将x基于输入参数dim进行合轴,合轴后维度为[pre, cut],其中cut必须为偶数。令h = cut // 2。 | ||
| 23 | + | ||
| 24 | + 2. 根据输入参数activate_left对x进行前后切分: | ||
| 25 | + | ||
| 26 | + - activate_left为true时(默认): | ||
| 27 | + | ||
| 28 | + $$ | ||
| 29 | + gate = x[:, :h], \quad up = x[:, h:] | ||
| 30 | + $$ | ||
| 31 | + | ||
| 32 | + - activate_left为false时: | ||
| 33 | + | ||
| 34 | + $$ | ||
| 35 | + gate = x[:, h:], \quad up = x[:, :h] | ||
| 36 | + $$ | ||
| 37 | + | ||
| 38 | + 3. 根据输入参数beta、linear_beta进行SiTU计算: | ||
| 39 | + | ||
| 40 | + $$ | ||
| 41 | + situ\_a = \beta \cdot \tanh\left(\frac{gate}{\beta}\right) \cdot \text{sigmoid}(gate) | ||
| 42 | + $$ | ||
| 43 | + | ||
| 44 | + 当linear_beta > 0时: | ||
| 45 | + | ||
| 46 | + $$ | ||
| 47 | + up = linear\_beta \cdot \tanh\left(\frac{up}{linear\_beta}\right) | ||
| 48 | + $$ | ||
| 49 | + | ||
| 50 | + 4. 输出: | ||
| 51 | + | ||
| 52 | + $$ | ||
| 53 | + y = situ\_a \cdot up | ||
| 54 | + $$ | ||
| 55 | + | ||
| 56 | + 5. 重塑输出张量y的维度数量与合轴前的x的维度数量一致,dim轴上的大小为x的一半,其他维度与x相同。 | ||
| 57 | + | ||
| 58 | +## 参数说明 | ||
| 59 | + | ||
| 60 | +<table style="undefined;table-layout: fixed; width: 1576px"><colgroup> | ||
| 61 | + <col style="width: 170px"> | ||
| 62 | + <col style="width: 170px"> | ||
| 63 | + <col style="width: 200px"> | ||
| 64 | + <col style="width: 200px"> | ||
| 65 | + <col style="width: 170px"> | ||
| 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>x</td> | ||
| 78 | + <td>输入</td> | ||
| 79 | + <td>公式中的输入x,dim维度会被均分为门控(gate)与上路径(up)两部分。</td> | ||
| 80 | + <td>FLOAT、FLOAT16、BFLOAT16</td> | ||
| 81 | + <td>ND</td> | ||
| 82 | + </tr> | ||
| 83 | + <tr> | ||
| 84 | + <td>dim</td> | ||
| 85 | + <td>属性</td> | ||
| 86 | + <td><ul><li>切分维度。</li><li>取值范围为[-x.dim(), x.dim()-1]。</li><li>默认值为-1。</li></ul></td> | ||
| 87 | + <td>INT64</td> | ||
| 88 | + <td>-</td> | ||
| 89 | + </tr> | ||
| 90 | + <tr> | ||
| 91 | + <td>beta</td> | ||
| 92 | + <td>属性</td> | ||
| 93 | + <td><ul><li>SiTU门控部分的缩放系数,控制tanh非线性强度。</li><li>默认值为1.0。</li></ul></td> | ||
| 94 | + <td>FLOAT</td> | ||
| 95 | + <td>-</td> | ||
| 96 | + </tr> | ||
| 97 | + <tr> | ||
| 98 | + <td>linear_beta</td> | ||
| 99 | + <td>属性</td> | ||
| 100 | + <td><ul><li>up路径线性tanh的缩放系数。</li><li>大于0时对up施加有界化变换,小于等于0时up直接透传。</li><li>默认值为0.0。</li></ul></td> | ||
| 101 | + <td>FLOAT</td> | ||
| 102 | + <td>-</td> | ||
| 103 | + </tr> | ||
| 104 | + <tr> | ||
| 105 | + <td>activate_left</td> | ||
| 106 | + <td>属性</td> | ||
| 107 | + <td><ul><li>切分x时gate是否为前半部分。</li><li>true表示gate为前半、up为后半;false表示gate为后半、up为前半。</li><li>默认值为true。</li></ul></td> | ||
| 108 | + <td>BOOL</td> | ||
| 109 | + <td>-</td> | ||
| 110 | + </tr> | ||
| 111 | + <tr> | ||
| 112 | + <td>y</td> | ||
| 113 | + <td>输出</td> | ||
| 114 | + <td>公式中的y,SiTU激活结果,dim维度大小为x的一半。</td> | ||
| 115 | + <td>FLOAT、FLOAT16、BFLOAT16</td> | ||
| 116 | + <td>ND</td> | ||
| 117 | + </tr> | ||
| 118 | + </tbody></table> | ||
| 119 | + | ||
| 120 | +## 约束说明 | ||
| 121 | + | ||
| 122 | +- 支持非连续Tensor。 | ||
| 123 | + | ||
| 124 | +## 调用说明 | ||
| 125 | + | ||
| 126 | +| 调用方式 | 样例代码 | 说明 | | ||
| 127 | +| ---------------- | --------------------------- | --------------------------------------------------- | | ||
| 128 | +| aclnn API | [test_aclnn_situ_glu](./examples/test_aclnn_situ_glu.cpp) | 通过[aclnnSituGlu](./docs/aclnnSituGlu.md)接口调用SituGlu算子。 | | ||
| 129 | +| GE图模式 | - | 通过[算子IR](./op_graph/situ_glu_proto.h)构图方式调用SituGlu算子。 | | ||
| 130 | +| PyTorch API | - | 通过[situ_glu](./docs/torchapi_situ_glu.md)接口调用SituGlu算子。 | | ||
| @@ -0,0 +1,451 @@ | |||
| 1 | +# aclnnSituGlu | ||
| 2 | + | ||
| 3 | +[查看源码](https://gitcode.com/cann/ops-nn/tree/master/activation/situ_glu) | ||
| 4 | + | ||
| 5 | +## 产品支持情况 | ||
| 6 | + | ||
| 7 | +<!-- npu="950" id1 --> | ||
| 8 | + | ||
| 9 | +- <term>Ascend 950PR/Ascend 950DT</term>:支持 | ||
| 10 | + | ||
| 11 | +<!-- end id1 --> | ||
| 12 | + | ||
| 13 | +<!-- npu="A3" id2 --> | ||
| 14 | + | ||
| 15 | +- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:支持 | ||
| 16 | + | ||
| 17 | +<!-- end id2 --> | ||
| 18 | + | ||
| 19 | +<!-- npu="910b" id3 --> | ||
| 20 | + | ||
| 21 | +- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:支持 | ||
| 22 | + | ||
| 23 | +<!-- end id3 --> | ||
| 24 | + | ||
| 25 | +<!-- npu="310b" id4 --> | ||
| 26 | + | ||
| 27 | +- <term>Atlas 200I/500 A2 推理产品</term>:不支持 | ||
| 28 | + | ||
| 29 | +<!-- end id4 --> | ||
| 30 | + | ||
| 31 | +<!-- npu="310p" id5 --> | ||
| 32 | + | ||
| 33 | +- <term>Atlas 推理系列产品</term>:不支持 | ||
| 34 | + | ||
| 35 | +<!-- end id5 --> | ||
| 36 | + | ||
| 37 | +<!-- npu="910" id6 --> | ||
| 38 | + | ||
| 39 | +- <term>Atlas 训练系列产品</term>:不支持 | ||
| 40 | + | ||
| 41 | +<!-- end id6 --> | ||
| 42 | + | ||
| 43 | +## 功能说明 | ||
| 44 | + | ||
| 45 | +- 接口功能:SiTU门控线性单元(SiTU Gated Linear Unit)激活函数。对输入张量x沿指定维度切分为门控(gate)与上路径(up)两半,按SiTU公式计算输出。 | ||
| 46 | +- 计算公式: | ||
| 47 | + | ||
| 48 | + 对给定的输入张量x,其维度为[a, b, c, d, e, f, g, ...],aclnnSituGlu对其执行以下计算: | ||
| 49 | + | ||
| 50 | + 1. 将x基于输入参数dim进行合轴,合轴后维度为[pre, cut]。其中cut轴为需要切分为两个张量的轴,cut必须为偶数。令h = cut // 2。 | ||
| 51 | + | ||
| 52 | + 2. 根据输入参数activateLeft对x进行前后切分: | ||
| 53 | + | ||
| 54 | + - activateLeft为true时: | ||
| 55 | + | ||
| 56 | + $$ | ||
| 57 | + gate = x[:, :h], \quad up = x[:, h:] | ||
| 58 | + $$ | ||
| 59 | + | ||
| 60 | + - activateLeft为false时: | ||
| 61 | + | ||
| 62 | + $$ | ||
| 63 | + gate = x[:, h:], \quad up = x[:, :h] | ||
| 64 | + $$ | ||
| 65 | + | ||
| 66 | + 3. 根据输入参数beta、linearBeta进行SiTU计算: | ||
| 67 | + | ||
| 68 | + $$ | ||
| 69 | + situ\_a = \beta \cdot \tanh\left(\frac{gate}{\beta}\right) \cdot \text{sigmoid}(gate) | ||
| 70 | + $$ | ||
| 71 | + | ||
| 72 | + 当linearBeta > 0时: | ||
| 73 | + | ||
| 74 | + $$ | ||
| 75 | + up = linearBeta \cdot \tanh\left(\frac{up}{linearBeta}\right) | ||
| 76 | + $$ | ||
| 77 | + | ||
| 78 | + 4. 输出: | ||
| 79 | + | ||
| 80 | + $$ | ||
| 81 | + y = situ\_a \cdot up | ||
| 82 | + $$ | ||
| 83 | + | ||
| 84 | + 5. 重塑输出张量y的维度数量与合轴前的x的维度数量一致,dim轴上的大小为x的一半,其他维度与x相同。 | ||
| 85 | + | ||
| 86 | +## 函数原型 | ||
| 87 | + | ||
| 88 | +每个算子分为[两段式接口](../../../docs/zh/context/two_phase_api.md),必须先调用"aclnnSituGluGetWorkspaceSize"接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用"aclnnSituGlu"接口执行计算。 | ||
| 89 | + | ||
| 90 | +```cpp | ||
| 91 | +aclnnStatus aclnnSituGluGetWorkspaceSize( | ||
| 92 | + const aclTensor *x, | ||
| 93 | + int64_t dim, | ||
| 94 | + double beta, | ||
| 95 | + double linearBeta, | ||
| 96 | + bool activateLeft, | ||
| 97 | + const aclTensor *out, | ||
| 98 | + uint64_t *workspaceSize, | ||
| 99 | + aclOpExecutor **executor) | ||
| 100 | +``` | ||
| 101 | + | ||
| 102 | +```cpp | ||
| 103 | +aclnnStatus aclnnSituGlu( | ||
| 104 | + void *workspace, | ||
| 105 | + uint64_t workspaceSize, | ||
| 106 | + aclOpExecutor *executor, | ||
| 107 | + aclrtStream stream) | ||
| 108 | +``` | ||
| 109 | + | ||
| 110 | +## aclnnSituGluGetWorkspaceSize | ||
| 111 | + | ||
| 112 | +- **参数说明** | ||
| 113 | + | ||
| 114 | + <table style="undefined;table-layout: fixed; width: 1550px"><colgroup> | ||
| 115 | + <col style="width: 180px"> | ||
| 116 | + <col style="width: 120px"> | ||
| 117 | + <col style="width: 280px"> | ||
| 118 | + <col style="width: 320px"> | ||
| 119 | + <col style="width: 250px"> | ||
| 120 | + <col style="width: 120px"> | ||
| 121 | + <col style="width: 140px"> | ||
| 122 | + <col style="width: 140px"> | ||
| 123 | + </colgroup> | ||
| 124 | + <thead> | ||
| 125 | + <tr> | ||
| 126 | + <th>参数名</th> | ||
| 127 | + <th>输入/输出</th> | ||
| 128 | + <th>描述</th> | ||
| 129 | + <th>使用说明</th> | ||
| 130 | + <th>数据类型</th> | ||
| 131 | + <th>数据格式</th> | ||
| 132 | + <th>维度(shape)</th> | ||
| 133 | + <th>非连续Tensor</th> | ||
| 134 | + </tr></thead> | ||
| 135 | + <tbody> | ||
| 136 | + <tr> | ||
| 137 | + <td>x(aclTensor*)</td> | ||
| 138 | + <td>输入</td> | ||
| 139 | + <td>公式中的输入x。</td> | ||
| 140 | + <td><ul><li>支持空Tensor(输出为对应空Tensor)。</li><li>shape必须在入参dim对应的维度上为偶数。</li></ul></td> | ||
| 141 | + <td>FLOAT、FLOAT16、BFLOAT16</td> | ||
| 142 | + <td>ND</td> | ||
| 143 | + <td>1-8</td> | ||
| 144 | + <td>√</td> | ||
| 145 | + </tr> | ||
| 146 | + <tr> | ||
| 147 | + <td>dim(int64_t)</td> | ||
| 148 | + <td>输入</td> | ||
| 149 | + <td>公式中的输入dim,表示对x进行合轴以及切分的维度序号。</td> | ||
| 150 | + <td>取值范围为[-x.dim(), x.dim()-1]。</td> | ||
| 151 | + <td>-</td> | ||
| 152 | + <td>-</td> | ||
| 153 | + <td>-</td> | ||
| 154 | + <td>-</td> | ||
| 155 | + </tr> | ||
| 156 | + <tr> | ||
| 157 | + <td>beta(double)</td> | ||
| 158 | + <td>输入</td> | ||
| 159 | + <td>公式中的输入beta,SiTU门控部分的缩放系数。</td> | ||
| 160 | + <td>建议为非零值。</td> | ||
| 161 | + <td>-</td> | ||
| 162 | + <td>-</td> | ||
| 163 | + <td>-</td> | ||
| 164 | + <td>-</td> | ||
| 165 | + </tr> | ||
| 166 | + <tr> | ||
| 167 | + <td>linearBeta(double)</td> | ||
| 168 | + <td>输入</td> | ||
| 169 | + <td>公式中的输入linearBeta,up路径线性tanh的缩放系数。小于等于0时up路径不进行变换。</td> | ||
| 170 | + <td>-</td> | ||
| 171 | + <td>-</td> | ||
| 172 | + <td>-</td> | ||
| 173 | + <td>-</td> | ||
| 174 | + <td>-</td> | ||
| 175 | + </tr> | ||
| 176 | + <tr> | ||
| 177 | + <td>activateLeft(bool)</td> | ||
| 178 | + <td>输入</td> | ||
| 179 | + <td>公式中的输入activateLeft,表示切分x时gate是否为前半部分。</td> | ||
| 180 | + <td>true表示gate为前半、up为后半;false表示gate为后半、up为前半。</td> | ||
| 181 | + <td>-</td> | ||
| 182 | + <td>-</td> | ||
| 183 | + <td>-</td> | ||
| 184 | + <td>-</td> | ||
| 185 | + </tr> | ||
| 186 | + <tr> | ||
| 187 | + <td>out(aclTensor*)</td> | ||
| 188 | + <td>输出</td> | ||
| 189 | + <td>公式中的输出y。</td> | ||
| 190 | + <td><ul><li>支持空Tensor。</li><li>shape在入参dim对应的维度上为x的一半,其他维度与x一致。</li><li>数据类型与x一致。</li></ul></td> | ||
| 191 | + <td>FLOAT、FLOAT16、BFLOAT16</td> | ||
| 192 | + <td>ND</td> | ||
| 193 | + <td>1-8</td> | ||
| 194 | + <td>×</td> | ||
| 195 | + </tr> | ||
| 196 | + <tr> | ||
| 197 | + <td>workspaceSize(uint64_t*)</td> | ||
| 198 | + <td>输出</td> | ||
| 199 | + <td>返回需要在Device侧申请的workspace大小。</td> | ||
| 200 | + <td>-</td> | ||
| 201 | + <td>-</td> | ||
| 202 | + <td>-</td> | ||
| 203 | + <td>-</td> | ||
| 204 | + <td>-</td> | ||
| 205 | + </tr> | ||
| 206 | + <tr> | ||
| 207 | + <td>executor(aclOpExecutor**)</td> | ||
| 208 | + <td>输出</td> | ||
| 209 | + <td>返回op执行器,包含了算子计算流程。</td> | ||
| 210 | + <td>-</td> | ||
| 211 | + <td>-</td> | ||
| 212 | + <td>-</td> | ||
| 213 | + <td>-</td> | ||
| 214 | + <td>-</td> | ||
| 215 | + </tr> | ||
| 216 | + </tbody></table> | ||
| 217 | + | ||
| 218 | +- **返回值** | ||
| 219 | + | ||
| 220 | + aclnnStatus:返回状态码,具体参见[aclnn返回码](../../../docs/zh/context/aclnn_return_code.md)。 | ||
| 221 | + | ||
| 222 | + 第一段接口完成入参校验,出现以下场景时报错: | ||
| 223 | + | ||
| 224 | + <table style="undefined;table-layout: fixed; width: 1100px"><colgroup> | ||
| 225 | + <col style="width: 300px"> | ||
| 226 | + <col style="width: 150px"> | ||
| 227 | + <col style="width: 650px"> | ||
| 228 | + </colgroup> | ||
| 229 | + <thead> | ||
| 230 | + <tr> | ||
| 231 | + <th>返回值</th> | ||
| 232 | + <th>错误码</th> | ||
| 233 | + <th>描述</th> | ||
| 234 | + </tr> | ||
| 235 | + </thead> | ||
| 236 | + <tbody> | ||
| 237 | + <tr> | ||
| 238 | + <td>ACLNN_ERR_PARAM_NULLPTR</td> | ||
| 239 | + <td>161001</td> | ||
| 240 | + <td>x、out存在空指针。</td> | ||
| 241 | + </tr> | ||
| 242 | + <tr> | ||
| 243 | + <td rowspan="5">ACLNN_ERR_PARAM_INVALID</td> | ||
| 244 | + <td rowspan="5">161002</td> | ||
| 245 | + <td>x或out的数据类型不在支持的范围之内。</td> | ||
| 246 | + </tr> | ||
| 247 | + <tr> | ||
| 248 | + <td>x或out的shape维度不在支持的范围之内。</td> | ||
| 249 | + </tr> | ||
| 250 | + <tr> | ||
| 251 | + <td>dim不在指定的取值范围内或x在dim对应维度上不能被2整除。</td> | ||
| 252 | + </tr> | ||
| 253 | + <tr> | ||
| 254 | + <td>out的维度数与x不一致,或out在dim对应维度上的大小不等于x的一半。</td> | ||
| 255 | + </tr> | ||
| 256 | + <tr> | ||
| 257 | + <td>out的数据类型与x不匹配。</td> | ||
| 258 | + </tr> | ||
| 259 | + </tbody></table> | ||
| 260 | + | ||
| 261 | +## aclnnSituGlu | ||
| 262 | + | ||
| 263 | +- **参数说明** | ||
| 264 | + | ||
| 265 | + <table style="undefined;table-layout: fixed; width: 1100px"><colgroup> | ||
| 266 | + <col style="width: 200px"> | ||
| 267 | + <col style="width: 130px"> | ||
| 268 | + <col style="width: 770px"> | ||
| 269 | + </colgroup> | ||
| 270 | + <thead> | ||
| 271 | + <tr> | ||
| 272 | + <th>参数名</th> | ||
| 273 | + <th>输入/输出</th> | ||
| 274 | + <th>描述</th> | ||
| 275 | + </tr> | ||
| 276 | + </thead> | ||
| 277 | + <tbody> | ||
| 278 | + <tr> | ||
| 279 | + <td>workspace</td> | ||
| 280 | + <td>输入</td> | ||
| 281 | + <td>在Device侧申请的workspace内存地址。</td> | ||
| 282 | + </tr> | ||
| 283 | + <tr> | ||
| 284 | + <td>workspaceSize</td> | ||
| 285 | + <td>输入</td> | ||
| 286 | + <td>在Device侧申请的workspace大小,由第一段接口aclnnSituGluGetWorkspaceSize获取。</td> | ||
| 287 | + </tr> | ||
| 288 | + <tr> | ||
| 289 | + <td>executor</td> | ||
| 290 | + <td>输入</td> | ||
| 291 | + <td>op执行器,包含了算子计算流程。</td> | ||
| 292 | + </tr> | ||
| 293 | + <tr> | ||
| 294 | + <td>stream</td> | ||
| 295 | + <td>输入</td> | ||
| 296 | + <td>指定执行任务的Stream。</td> | ||
| 297 | + </tr> | ||
| 298 | + </tbody></table> | ||
| 299 | + | ||
| 300 | +- **返回值** | ||
| 301 | + | ||
| 302 | + aclnnStatus:返回状态码,具体参见[aclnn返回码](../../../docs/zh/context/aclnn_return_code.md)。 | ||
| 303 | + | ||
| 304 | +## 约束说明 | ||
| 305 | + | ||
| 306 | +- 确定性说明:aclnnSituGlu默认确定性实现。 | ||
| 307 | + | ||
| 308 | +## 调用示例 | ||
| 309 | + | ||
| 310 | +示例代码如下,仅供参考,具体编译和执行过程请参考[编译与运行样例](../../../docs/zh/context/compile_and_run_sample.md)。 | ||
| 311 | + | ||
| 312 | +```cpp | ||
| 313 | +#include <iostream> | ||
| 314 | +#include <vector> | ||
| 315 | +#include "acl/acl.h" | ||
| 316 | +#include "aclnnop/aclnn_situ_glu.h" | ||
| 317 | + | ||
| 318 | +#define CHECK_RET(cond, return_expr) \ | ||
| 319 | + do { \ | ||
| 320 | + if (!(cond)) { \ | ||
| 321 | + return_expr; \ | ||
| 322 | + } \ | ||
| 323 | + } while (0) | ||
| 324 | + | ||
| 325 | +#define LOG_PRINT(message, ...) \ | ||
| 326 | + do { \ | ||
| 327 | + printf(message, ##__VA_ARGS__); \ | ||
| 328 | + } while (0) | ||
| 329 | + | ||
| 330 | +int64_t GetShapeSize(const std::vector<int64_t>& shape) | ||
| 331 | +{ | ||
| 332 | + int64_t shapeSize = 1; | ||
| 333 | + for (auto i : shape) { | ||
| 334 | + shapeSize *= i; | ||
| 335 | + } | ||
| 336 | + return shapeSize; | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +int Init(int32_t deviceId, aclrtStream* stream) | ||
| 340 | +{ | ||
| 341 | + // 固定写法,acl初始化 | ||
| 342 | + auto ret = aclInit(nullptr); | ||
| 343 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); | ||
| 344 | + ret = aclrtSetDevice(deviceId); | ||
| 345 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); | ||
| 346 | + ret = aclrtCreateStream(stream); | ||
| 347 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); | ||
| 348 | + return 0; | ||
| 349 | +} | ||
| 350 | + | ||
| 351 | +template <typename T> | ||
| 352 | +int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, | ||
| 353 | + aclDataType dataType, aclTensor** tensor) | ||
| 354 | +{ | ||
| 355 | + auto size = GetShapeSize(shape) * sizeof(T); | ||
| 356 | + // 调用aclrtMalloc申请device侧内存 | ||
| 357 | + auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 358 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret); | ||
| 359 | + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 | ||
| 360 | + ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 361 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); | ||
| 362 | + | ||
| 363 | + // 计算连续tensor的strides | ||
| 364 | + std::vector<int64_t> strides(shape.size(), 1); | ||
| 365 | + for (int64_t i = shape.size() - 2; i >= 0; i--) { | ||
| 366 | + strides[i] = shape[i + 1] * strides[i + 1]; | ||
| 367 | + } | ||
| 368 | + | ||
| 369 | + // 调用aclCreateTensor接口创建aclTensor | ||
| 370 | + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, | ||
| 371 | + shape.data(), shape.size(), *deviceAddr); | ||
| 372 | + return 0; | ||
| 373 | +} | ||
| 374 | + | ||
| 375 | +int main() | ||
| 376 | +{ | ||
| 377 | + // 1. (固定写法)device/stream初始化,参考acl API手册 | ||
| 378 | + int32_t deviceId = 0; | ||
| 379 | + aclrtStream stream; | ||
| 380 | + auto ret = Init(deviceId, &stream); | ||
| 381 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); | ||
| 382 | + | ||
| 383 | + // 2. 构造输入与输出 | ||
| 384 | + std::vector<int64_t> xShape = {2, 32}; | ||
| 385 | + std::vector<int64_t> outShape = {2, 16}; | ||
| 386 | + void* xDeviceAddr = nullptr; | ||
| 387 | + void* outDeviceAddr = nullptr; | ||
| 388 | + aclTensor* x = nullptr; | ||
| 389 | + aclTensor* out = nullptr; | ||
| 390 | + std::vector<float> xHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | ||
| 391 | + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, | ||
| 392 | + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, | ||
| 393 | + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}; | ||
| 394 | + std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | ||
| 395 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; | ||
| 396 | + | ||
| 397 | + int64_t dim = -1; | ||
| 398 | + double beta = 1.0; | ||
| 399 | + double linear_beta = 0.0; | ||
| 400 | + bool activate_left = true; | ||
| 401 | + // 创建x aclTensor | ||
| 402 | + ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x); | ||
| 403 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 404 | + // 创建out aclTensor | ||
| 405 | + ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out); | ||
| 406 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 407 | + | ||
| 408 | + // 3. 调用CANN算子库API | ||
| 409 | + uint64_t workspaceSize = 0; | ||
| 410 | + aclOpExecutor* executor; | ||
| 411 | + // 调用aclnnSituGlu第一段接口 | ||
| 412 | + ret = aclnnSituGluGetWorkspaceSize(x, dim, beta, linear_beta, activate_left, out, &workspaceSize, &executor); | ||
| 413 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituGluGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); | ||
| 414 | + // 根据第一段接口计算出的workspaceSize申请device内存 | ||
| 415 | + void* workspaceAddr = nullptr; | ||
| 416 | + if (workspaceSize > 0) { | ||
| 417 | + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 418 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret); | ||
| 419 | + } | ||
| 420 | + // 调用aclnnSituGlu第二段接口 | ||
| 421 | + ret = aclnnSituGlu(workspaceAddr, workspaceSize, executor, stream); | ||
| 422 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituGlu failed. ERROR: %d\n", ret); return ret); | ||
| 423 | + | ||
| 424 | + // 4. (固定写法)同步等待任务执行结束 | ||
| 425 | + ret = aclrtSynchronizeStream(stream); | ||
| 426 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); | ||
| 427 | + | ||
| 428 | + // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧 | ||
| 429 | + auto size = GetShapeSize(outShape); | ||
| 430 | + std::vector<float> resultData(size, 0); | ||
| 431 | + ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, | ||
| 432 | + size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 433 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret); | ||
| 434 | + for (int64_t i = 0; i < size; i++) { | ||
| 435 | + LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]); | ||
| 436 | + } | ||
| 437 | + // 6. 释放aclTensor | ||
| 438 | + aclDestroyTensor(x); | ||
| 439 | + aclDestroyTensor(out); | ||
| 440 | + // 7. 释放device资源 | ||
| 441 | + aclrtFree(xDeviceAddr); | ||
| 442 | + aclrtFree(outDeviceAddr); | ||
| 443 | + if (workspaceSize > 0) { | ||
| 444 | + aclrtFree(workspaceAddr); | ||
| 445 | + } | ||
| 446 | + aclrtDestroyStream(stream); | ||
| 447 | + aclrtResetDevice(deviceId); | ||
| 448 | + aclFinalize(); | ||
| 449 | + return 0; | ||
| 450 | +} | ||
| 451 | +``` | ||
| @@ -0,0 +1,154 @@ | |||
| 1 | +# situ_glu | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +<!-- npu="950" id1 --> | ||
| 6 | + | ||
| 7 | +- <term>Ascend 950PR/Ascend 950DT</term>:支持 | ||
| 8 | + | ||
| 9 | +<!-- end id1 --> | ||
| 10 | + | ||
| 11 | +<!-- npu="A3" id2 --> | ||
| 12 | + | ||
| 13 | +- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:支持 | ||
| 14 | + | ||
| 15 | +<!-- end id2 --> | ||
| 16 | + | ||
| 17 | +<!-- npu="910b" id3 --> | ||
| 18 | + | ||
| 19 | +- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:支持 | ||
| 20 | + | ||
| 21 | +<!-- end id3 --> | ||
| 22 | + | ||
| 23 | +<!-- npu="310b" id4 --> | ||
| 24 | + | ||
| 25 | +- <term>Atlas 200I/500 A2 推理产品</term>:不支持 | ||
| 26 | + | ||
| 27 | +<!-- end id4 --> | ||
| 28 | + | ||
| 29 | +<!-- npu="310p" id5 --> | ||
| 30 | + | ||
| 31 | +- <term>Atlas 推理系列产品</term>:不支持 | ||
| 32 | + | ||
| 33 | +<!-- end id5 --> | ||
| 34 | + | ||
| 35 | +<!-- npu="910" id6 --> | ||
| 36 | + | ||
| 37 | +- <term>Atlas 训练系列产品</term>:不支持 | ||
| 38 | + | ||
| 39 | +<!-- end id6 --> | ||
| 40 | + | ||
| 41 | +## 功能说明 | ||
| 42 | + | ||
| 43 | +- 接口功能: | ||
| 44 | + | ||
| 45 | + SiTU门控线性单元(SiTU Gated Linear Unit)激活函数。对输入张量`x`沿指定维度`dim`切分为门控(gate)与上路径(up)两半,按SiTU公式计算输出。底层封装`aclnnSituGlu`。 | ||
| 46 | + | ||
| 47 | +- 计算公式: | ||
| 48 | + | ||
| 49 | + 对给定的输入张量`x`,按以下步骤计算SiTU输出`y`: | ||
| 50 | + | ||
| 51 | + 1. 基于`dim`进行合轴,合轴后维度为`[pre, cut]`,其中`cut`必须为偶数。令`h = cut // 2`。 | ||
| 52 | + | ||
| 53 | + 2. 根据`activate_left`对`x`进行前后切分: | ||
| 54 | + | ||
| 55 | + - `activate_left=True`(默认):`gate = x[..., :h]`,`up = x[..., h:]` | ||
| 56 | + - `activate_left=False`:`gate = x[..., h:]`,`up = x[..., :h]` | ||
| 57 | + | ||
| 58 | + 3. 根据`beta`、`linear_beta`进行SiTU计算: | ||
| 59 | + | ||
| 60 | + $$ | ||
| 61 | + situ\_a = \beta \cdot \tanh\left(\frac{gate}{\beta}\right) \cdot \text{sigmoid}(gate) | ||
| 62 | + $$ | ||
| 63 | + | ||
| 64 | + 当`linear_beta > 0`时: | ||
| 65 | + | ||
| 66 | + $$ | ||
| 67 | + up = linear\_beta \cdot \tanh\left(\frac{up}{linear\_beta}\right) | ||
| 68 | + $$ | ||
| 69 | + | ||
| 70 | + 当`linear_beta <= 0`时,`up`直接透传。 | ||
| 71 | + | ||
| 72 | + 4. 输出: | ||
| 73 | + | ||
| 74 | + $$ | ||
| 75 | + y = situ\_a \cdot up | ||
| 76 | + $$ | ||
| 77 | + | ||
| 78 | + 5. 输出张量`y`的维度与`x`一致,`dim`轴上的大小为`x`的一半,其他维度与`x`相同。 | ||
| 79 | + | ||
| 80 | +## 函数原型 | ||
| 81 | + | ||
| 82 | +```python | ||
| 83 | +cann_ops_nn.situ_glu( | ||
| 84 | + x, | ||
| 85 | + *, | ||
| 86 | + dim=-1, | ||
| 87 | + beta=1.0, | ||
| 88 | + linear_beta=0.0, | ||
| 89 | + activate_left=True | ||
| 90 | +) -> Tensor | ||
| 91 | +``` | ||
| 92 | + | ||
| 93 | +## 参数说明 | ||
| 94 | + | ||
| 95 | +| 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) | | ||
| 96 | +| --- | --- | --- | --- | --- | --- | | ||
| 97 | +| `x` | Tensor | 必选 | SiTU输入,`dim`维度会被均分为门控(gate)与上路径(up)两部分。 | float16、float32、bfloat16 | 1-8维,`dim`维度为偶数 | | ||
| 98 | +| `dim` | int | 可选 | 切分维度,取值范围`[-x.dim(), x.dim()-1]`,默认`-1`。 | - | - | | ||
| 99 | +| `beta` | float | 可选 | SiTU门控部分的缩放系数,控制tanh非线性强度。建议为非零正值,默认`1.0`。 | - | - | | ||
| 100 | +| `linear_beta` | float | 可选 | up路径线性tanh的缩放系数。大于0时对up施加有界化变换;小于等于0时up直接透传。默认`0.0`。 | - | - | | ||
| 101 | +| `activate_left` | bool | 可选 | 切分`x`时gate是否为前半部分。`True`表示gate为前半、up为后半;`False`表示gate为后半、up为前半。默认`True`。 | - | - | | ||
| 102 | + | ||
| 103 | +## 返回值说明 | ||
| 104 | + | ||
| 105 | +| 参数名 | 参数类型 | 描述 | 数据类型 | 维度(shape) | | ||
| 106 | +| --- | --- | --- | --- | --- | | ||
| 107 | +| `y` | Tensor | SiTU激活结果。 | 与`x`一致 | 与`x`相同,但`dim`维度大小为`x.shape[dim] // 2` | | ||
| 108 | + | ||
| 109 | +## 约束说明 | ||
| 110 | + | ||
| 111 | +- 该接口支持训练、推理场景下使用。 | ||
| 112 | +- 该接口支持单算子模式和TorchAir图模式调用。 | ||
| 113 | +- `dim`非last维时,若尾部维度组合不满足半行32B对齐,会回退到Long-H路径,功能正确但性能略降。 | ||
| 114 | + | ||
| 115 | +## 确定性计算 | ||
| 116 | + | ||
| 117 | +- 默认支持确定性计算。 | ||
| 118 | + | ||
| 119 | +## 调用示例 | ||
| 120 | + | ||
| 121 | +- 单算子模式调用: | ||
| 122 | + | ||
| 123 | + ```python | ||
| 124 | + import torch | ||
| 125 | + import torch_npu | ||
| 126 | + import cann_ops_nn | ||
| 127 | + | ||
| 128 | + x = torch.randn(2, 32, dtype=torch.float32).npu() | ||
| 129 | + | ||
| 130 | + # 默认参数调用 | ||
| 131 | + y = cann_ops_nn.situ_glu(x) | ||
| 132 | + print(y.shape, y.dtype) # torch.Size([2, 16]) torch.float32 | ||
| 133 | + | ||
| 134 | + # 指定全部参数 | ||
| 135 | + y = cann_ops_nn.situ_glu(x, dim=-1, beta=1.0, linear_beta=0.0, activate_left=True) | ||
| 136 | + print(y.shape, y.dtype) | ||
| 137 | + ``` | ||
| 138 | + | ||
| 139 | +- TorchAir图模式调用: | ||
| 140 | + | ||
| 141 | + ```python | ||
| 142 | + import torch | ||
| 143 | + import torch_npu | ||
| 144 | + import torchair | ||
| 145 | + import cann_ops_nn | ||
| 146 | + | ||
| 147 | + class Model(torch.nn.Module): | ||
| 148 | + def forward(self, x): | ||
| 149 | + return cann_ops_nn.situ_glu(x, dim=-1, beta=1.0) | ||
| 150 | + | ||
| 151 | + model = torch.compile(Model().npu(), backend=torchair.get_npu_backend(), dynamic=False) | ||
| 152 | + x = torch.randn(2, 32, dtype=torch.float32).npu() | ||
| 153 | + y = model(x) | ||
| 154 | + ``` | ||
| @@ -0,0 +1,148 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include <iostream> | ||
| 12 | +#include <vector> | ||
| 13 | +#include "acl/acl.h" | ||
| 14 | +#include "aclnnop/aclnn_situ_glu.h" | ||
| 15 | + | ||
| 16 | +#define CHECK_RET(cond, return_expr) \ | ||
| 17 | + do { \ | ||
| 18 | + if (!(cond)) { \ | ||
| 19 | + return_expr; \ | ||
| 20 | + } \ | ||
| 21 | + } while (0) | ||
| 22 | + | ||
| 23 | +#define LOG_PRINT(message, ...) \ | ||
| 24 | + do { \ | ||
| 25 | + printf(message, ##__VA_ARGS__); \ | ||
| 26 | + } while (0) | ||
| 27 | + | ||
| 28 | +int64_t GetShapeSize(const std::vector<int64_t>& shape) | ||
| 29 | +{ | ||
| 30 | + int64_t shapeSize = 1; | ||
| 31 | + for (auto i : shape) { | ||
| 32 | + shapeSize *= i; | ||
| 33 | + } | ||
| 34 | + return shapeSize; | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +int Init(int32_t deviceId, aclrtStream* stream) | ||
| 38 | +{ | ||
| 39 | + // 固定写法,acl初始化 | ||
| 40 | + auto ret = aclInit(nullptr); | ||
| 41 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); | ||
| 42 | + ret = aclrtSetDevice(deviceId); | ||
| 43 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); | ||
| 44 | + ret = aclrtCreateStream(stream); | ||
| 45 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); | ||
| 46 | + return 0; | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +template <typename T> | ||
| 50 | +int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, | ||
| 51 | + aclDataType dataType, aclTensor** tensor) | ||
| 52 | +{ | ||
| 53 | + auto size = GetShapeSize(shape) * sizeof(T); | ||
| 54 | + // 调用aclrtMalloc申请device侧内存 | ||
| 55 | + auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 56 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret); | ||
| 57 | + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 | ||
| 58 | + ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 59 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); | ||
| 60 | + | ||
| 61 | + // 计算连续tensor的strides | ||
| 62 | + std::vector<int64_t> strides(shape.size(), 1); | ||
| 63 | + for (int64_t i = shape.size() - 2; i >= 0; i--) { | ||
| 64 | + strides[i] = shape[i + 1] * strides[i + 1]; | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + // 调用aclCreateTensor接口创建aclTensor | ||
| 68 | + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, | ||
| 69 | + shape.data(), shape.size(), *deviceAddr); | ||
| 70 | + return 0; | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +int main() | ||
| 74 | +{ | ||
| 75 | + // 1. (固定写法)device/stream初始化,参考acl API手册 | ||
| 76 | + int32_t deviceId = 0; | ||
| 77 | + aclrtStream stream; | ||
| 78 | + auto ret = Init(deviceId, &stream); | ||
| 79 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); | ||
| 80 | + | ||
| 81 | + // 2. 构造输入与输出 | ||
| 82 | + std::vector<int64_t> xShape = {2, 32}; | ||
| 83 | + std::vector<int64_t> outShape = {2, 16}; | ||
| 84 | + void* xDeviceAddr = nullptr; | ||
| 85 | + void* outDeviceAddr = nullptr; | ||
| 86 | + aclTensor* x = nullptr; | ||
| 87 | + aclTensor* out = nullptr; | ||
| 88 | + std::vector<float> xHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | ||
| 89 | + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, | ||
| 90 | + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, | ||
| 91 | + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}; | ||
| 92 | + std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | ||
| 93 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; | ||
| 94 | + | ||
| 95 | + int64_t dim = -1; | ||
| 96 | + double beta = 1.0; | ||
| 97 | + double linear_beta = 0.0; | ||
| 98 | + bool activate_left = true; | ||
| 99 | + // 创建x aclTensor | ||
| 100 | + ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x); | ||
| 101 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 102 | + // 创建out aclTensor | ||
| 103 | + ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out); | ||
| 104 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 105 | + | ||
| 106 | + // 3. 调用CANN算子库API | ||
| 107 | + uint64_t workspaceSize = 0; | ||
| 108 | + aclOpExecutor* executor; | ||
| 109 | + // 调用aclnnSituGlu第一段接口 | ||
| 110 | + ret = aclnnSituGluGetWorkspaceSize(x, dim, beta, linear_beta, activate_left, out, &workspaceSize, &executor); | ||
| 111 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituGluGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); | ||
| 112 | + // 根据第一段接口计算出的workspaceSize申请device内存 | ||
| 113 | + void* workspaceAddr = nullptr; | ||
| 114 | + if (workspaceSize > 0) { | ||
| 115 | + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 116 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret); | ||
| 117 | + } | ||
| 118 | + // 调用aclnnSituGlu第二段接口 | ||
| 119 | + ret = aclnnSituGlu(workspaceAddr, workspaceSize, executor, stream); | ||
| 120 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSituGlu failed. ERROR: %d\n", ret); return ret); | ||
| 121 | + | ||
| 122 | + // 4. (固定写法)同步等待任务执行结束 | ||
| 123 | + ret = aclrtSynchronizeStream(stream); | ||
| 124 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); | ||
| 125 | + | ||
| 126 | + // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧 | ||
| 127 | + auto size = GetShapeSize(outShape); | ||
| 128 | + std::vector<float> resultData(size, 0); | ||
| 129 | + ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, | ||
| 130 | + size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 131 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret); | ||
| 132 | + for (int64_t i = 0; i < size; i++) { | ||
| 133 | + LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]); | ||
| 134 | + } | ||
| 135 | + // 6. 释放aclTensor | ||
| 136 | + aclDestroyTensor(x); | ||
| 137 | + aclDestroyTensor(out); | ||
| 138 | + // 7. 释放device资源 | ||
| 139 | + aclrtFree(xDeviceAddr); | ||
| 140 | + aclrtFree(outDeviceAddr); | ||
| 141 | + if (workspaceSize > 0) { | ||
| 142 | + aclrtFree(workspaceAddr); | ||
| 143 | + } | ||
| 144 | + aclrtDestroyStream(stream); | ||
| 145 | + aclrtResetDevice(deviceId); | ||
| 146 | + aclFinalize(); | ||
| 147 | + return 0; | ||
| 148 | +} | ||
| @@ -0,0 +1,11 @@ | |||
| 1 | +# ---------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ---------------------------------------------------------------------------- | ||
| 10 | +message(STATUS "=== Debug: start ops.fusedop.situ_glu.op_graph.CMakeLists.txt ") | ||
| 11 | +add_graph_plugin_sources() | ||
The file is empty
| @@ -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 situ_glu_proto.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#ifndef OPS_BUILT_IN_OP_PROTO_INC_SITU_GLU_PROTO_H_ | ||
| 16 | +#define OPS_BUILT_IN_OP_PROTO_INC_SITU_GLU_PROTO_H_ | ||
| 17 | + | ||
| 18 | +#include "graph/operator_reg.h" | ||
| 19 | + | ||
| 20 | +namespace ge { | ||
| 21 | +/** | ||
| 22 | +* @brief SiTU gated linear unit activation. | ||
| 23 | + | ||
| 24 | +* @par Inputs: | ||
| 25 | +* One input: | ||
| 26 | +* @li x: A tensor. Type is float32/float16/bfloat16. The dim dimension must be divisible by 2. | ||
| 27 | + | ||
| 28 | +* @par Outputs: | ||
| 29 | +* One output: | ||
| 30 | +* y: A tensor. Type is float32/float16/bfloat16. The dim dimension is half of x. | ||
| 31 | + | ||
| 32 | +* @par Attributes: | ||
| 33 | +* Four attributes: | ||
| 34 | +* @li dim: An optional int. The dimension to be split, value in [-xDim, xDim-1], default is -1. | ||
| 35 | +* @li beta: An optional float. The scale factor for the SiTU gate activation, default is 1.0. | ||
| 36 | +* @li linear_beta: An optional float. The scale factor for the linear tanh on the up path. When <= 0, the up path is | ||
| 37 | +* used as-is. default is 0.0. | ||
| 38 | +* @li activate_left: An optional bool. Whether the left (front) half of x is the gate. true: gate is the front half and | ||
| 39 | +* up is the back half; false: gate is the back half and up is the front half. default is true. | ||
| 40 | + | ||
| 41 | +* @attention Constraints: | ||
| 42 | +* The dim dimension of x must be divisible by 2, and the dim dimension of y must be equal to the dim dimension of x | ||
| 43 | +* divided by 2. | ||
| 44 | +*/ | ||
| 45 | +REG_OP(SituGlu) | ||
| 46 | + .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16, DT_BF16})) | ||
| 47 | + .OUTPUT(y, TensorType({DT_FLOAT, DT_FLOAT16, DT_BF16})) | ||
| 48 | + .ATTR(dim, Int, -1) | ||
| 49 | + .ATTR(beta, Float, 1.0) | ||
| 50 | + .ATTR(linear_beta, Float, 0.0) | ||
| 51 | + .ATTR(activate_left, Bool, true) | ||
| 52 | + .OP_END_FACTORY_REG(SituGlu) | ||
| 53 | +} // namespace ge | ||
| 54 | +#endif // OPS_BUILT_IN_OP_PROTO_INC_SITU_GLU_PROTO_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: CURRENT_DIRS =${CURRENT_DIRS} ") | ||
| 12 | +add_modules_sources(HOSTNAME ${OPHOST_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR} OPTYPE situ_glu ACLNNTYPE aclnn) | ||
| @@ -0,0 +1,152 @@ | |||
| 1 | +{ | ||
| 2 | + "op_type": "SituGlu", | ||
| 3 | + "op_list": [ | ||
| 4 | + { | ||
| 5 | + "bin_filename": "SituGlu_fp32", | ||
| 6 | + "inputs": [ | ||
| 7 | + { | ||
| 8 | + "name": "x", | ||
| 9 | + "index": 0, | ||
| 10 | + "dtype": "float32", | ||
| 11 | + "format": "ND", | ||
| 12 | + "paramType": "required", | ||
| 13 | + "shape": [ | ||
| 14 | + -2 | ||
| 15 | + ] | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "outputs": [ | ||
| 19 | + { | ||
| 20 | + "name": "y", | ||
| 21 | + "index": 0, | ||
| 22 | + "dtype": "float32", | ||
| 23 | + "format": "ND", | ||
| 24 | + "paramType": "required", | ||
| 25 | + "shape": [ | ||
| 26 | + -2 | ||
| 27 | + ] | ||
| 28 | + } | ||
| 29 | + ], | ||
| 30 | + "attrs": [ | ||
| 31 | + { | ||
| 32 | + "name": "dim", | ||
| 33 | + "dtype": "int64", | ||
| 34 | + "value": -1 | ||
| 35 | + }, | ||
| 36 | + { | ||
| 37 | + "name": "beta", | ||
| 38 | + "dtype": "float32", | ||
| 39 | + "value": 1.0 | ||
| 40 | + }, | ||
| 41 | + { | ||
| 42 | + "name": "linear_beta", | ||
| 43 | + "dtype": "float32", | ||
| 44 | + "value": 0.0 | ||
| 45 | + }, | ||
| 46 | + { | ||
| 47 | + "name": "activate_left", | ||
| 48 | + "dtype": "bool", | ||
| 49 | + "value": true | ||
| 50 | + } | ||
| 51 | + ] | ||
| 52 | + }, | ||
| 53 | + { | ||
| 54 | + "bin_filename": "SituGlu_fp16", | ||
| 55 | + "inputs": [ | ||
| 56 | + { | ||
| 57 | + "name": "x", | ||
| 58 | + "index": 0, | ||
| 59 | + "dtype": "float16", | ||
| 60 | + "format": "ND", | ||
| 61 | + "paramType": "required", | ||
| 62 | + "shape": [ | ||
| 63 | + -2 | ||
| 64 | + ] | ||
| 65 | + } | ||
| 66 | + ], | ||
| 67 | + "outputs": [ | ||
| 68 | + { | ||
| 69 | + "name": "y", | ||
| 70 | + "index": 0, | ||
| 71 | + "dtype": "float16", | ||
| 72 | + "format": "ND", | ||
| 73 | + "paramType": "required", | ||
| 74 | + "shape": [ | ||
| 75 | + -2 | ||
| 76 | + ] | ||
| 77 | + } | ||
| 78 | + ], | ||
| 79 | + "attrs": [ | ||
| 80 | + { | ||
| 81 | + "name": "dim", | ||
| 82 | + "dtype": "int64", | ||
| 83 | + "value": -1 | ||
| 84 | + }, | ||
| 85 | + { | ||
| 86 | + "name": "beta", | ||
| 87 | + "dtype": "float32", | ||
| 88 | + "value": 1.0 | ||
| 89 | + }, | ||
| 90 | + { | ||
| 91 | + "name": "linear_beta", | ||
| 92 | + "dtype": "float32", | ||
| 93 | + "value": 0.0 | ||
| 94 | + }, | ||
| 95 | + { | ||
| 96 | + "name": "activate_left", | ||
| 97 | + "dtype": "bool", | ||
| 98 | + "value": true | ||
| 99 | + } | ||
| 100 | + ] | ||
| 101 | + }, | ||
| 102 | + { | ||
| 103 | + "bin_filename": "SituGlu_bf16", | ||
| 104 | + "inputs": [ | ||
| 105 | + { | ||
| 106 | + "name": "x", | ||
| 107 | + "index": 0, | ||
| 108 | + "dtype": "bfloat16", | ||
| 109 | + "format": "ND", | ||
| 110 | + "paramType": "required", | ||
| 111 | + "shape": [ | ||
| 112 | + -2 | ||
| 113 | + ] | ||
| 114 | + } | ||
| 115 | + ], | ||
| 116 | + "outputs": [ | ||
| 117 | + { | ||
| 118 | + "name": "y", | ||
| 119 | + "index": 0, | ||
| 120 | + "dtype": "bfloat16", | ||
| 121 | + "format": "ND", | ||
| 122 | + "paramType": "required", | ||
| 123 | + "shape": [ | ||
| 124 | + -2 | ||
| 125 | + ] | ||
| 126 | + } | ||
| 127 | + ], | ||
| 128 | + "attrs": [ | ||
| 129 | + { | ||
| 130 | + "name": "dim", | ||
| 131 | + "dtype": "int64", | ||
| 132 | + "value": -1 | ||
| 133 | + }, | ||
| 134 | + { | ||
| 135 | + "name": "beta", | ||
| 136 | + "dtype": "float32", | ||
| 137 | + "value": 1.0 | ||
| 138 | + }, | ||
| 139 | + { | ||
| 140 | + "name": "linear_beta", | ||
| 141 | + "dtype": "float32", | ||
| 142 | + "value": 0.0 | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "name": "activate_left", | ||
| 146 | + "dtype": "bool", | ||
| 147 | + "value": true | ||
| 148 | + } | ||
| 149 | + ] | ||
| 150 | + } | ||
| 151 | + ] | ||
| 152 | +} | ||
| @@ -0,0 +1,152 @@ | |||
| 1 | +{ | ||
| 2 | + "op_type": "SituGlu", | ||
| 3 | + "op_list": [ | ||
| 4 | + { | ||
| 5 | + "bin_filename": "SituGlu_fp32", | ||
| 6 | + "inputs": [ | ||
| 7 | + { | ||
| 8 | + "name": "x", | ||
| 9 | + "index": 0, | ||
| 10 | + "dtype": "float32", | ||
| 11 | + "format": "ND", | ||
| 12 | + "paramType": "required", | ||
| 13 | + "shape": [ | ||
| 14 | + -2 | ||
| 15 | + ] | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "outputs": [ | ||
| 19 | + { | ||
| 20 | + "name": "y", | ||
| 21 | + "index": 0, | ||
| 22 | + "dtype": "float32", | ||
| 23 | + "format": "ND", | ||
| 24 | + "paramType": "required", | ||
| 25 | + "shape": [ | ||
| 26 | + -2 | ||
| 27 | + ] | ||
| 28 | + } | ||
| 29 | + ], | ||
| 30 | + "attrs": [ | ||
| 31 | + { | ||
| 32 | + "name": "dim", | ||
| 33 | + "dtype": "int64", | ||
| 34 | + "value": -1 | ||
| 35 | + }, | ||
| 36 | + { | ||
| 37 | + "name": "beta", | ||
| 38 | + "dtype": "float32", | ||
| 39 | + "value": 1.0 | ||
| 40 | + }, | ||
| 41 | + { | ||
| 42 | + "name": "linear_beta", | ||
| 43 | + "dtype": "float32", | ||
| 44 | + "value": 0.0 | ||
| 45 | + }, | ||
| 46 | + { | ||
| 47 | + "name": "activate_left", | ||
| 48 | + "dtype": "bool", | ||
| 49 | + "value": true | ||
| 50 | + } | ||
| 51 | + ] | ||
| 52 | + }, | ||
| 53 | + { | ||
| 54 | + "bin_filename": "SituGlu_fp16", | ||
| 55 | + "inputs": [ | ||
| 56 | + { | ||
| 57 | + "name": "x", | ||
| 58 | + "index": 0, | ||
| 59 | + "dtype": "float16", | ||
| 60 | + "format": "ND", | ||
| 61 | + "paramType": "required", | ||
| 62 | + "shape": [ | ||
| 63 | + -2 | ||
| 64 | + ] | ||
| 65 | + } | ||
| 66 | + ], | ||
| 67 | + "outputs": [ | ||
| 68 | + { | ||
| 69 | + "name": "y", | ||
| 70 | + "index": 0, | ||
| 71 | + "dtype": "float16", | ||
| 72 | + "format": "ND", | ||
| 73 | + "paramType": "required", | ||
| 74 | + "shape": [ | ||
| 75 | + -2 | ||
| 76 | + ] | ||
| 77 | + } | ||
| 78 | + ], | ||
| 79 | + "attrs": [ | ||
| 80 | + { | ||
| 81 | + "name": "dim", | ||
| 82 | + "dtype": "int64", | ||
| 83 | + "value": -1 | ||
| 84 | + }, | ||
| 85 | + { | ||
| 86 | + "name": "beta", | ||
| 87 | + "dtype": "float32", | ||
| 88 | + "value": 1.0 | ||
| 89 | + }, | ||
| 90 | + { | ||
| 91 | + "name": "linear_beta", | ||
| 92 | + "dtype": "float32", | ||
| 93 | + "value": 0.0 | ||
| 94 | + }, | ||
| 95 | + { | ||
| 96 | + "name": "activate_left", | ||
| 97 | + "dtype": "bool", | ||
| 98 | + "value": true | ||
| 99 | + } | ||
| 100 | + ] | ||
| 101 | + }, | ||
| 102 | + { | ||
| 103 | + "bin_filename": "SituGlu_bf16", | ||
| 104 | + "inputs": [ | ||
| 105 | + { | ||
| 106 | + "name": "x", | ||
| 107 | + "index": 0, | ||
| 108 | + "dtype": "bfloat16", | ||
| 109 | + "format": "ND", | ||
| 110 | + "paramType": "required", | ||
| 111 | + "shape": [ | ||
| 112 | + -2 | ||
| 113 | + ] | ||
| 114 | + } | ||
| 115 | + ], | ||
| 116 | + "outputs": [ | ||
| 117 | + { | ||
| 118 | + "name": "y", | ||
| 119 | + "index": 0, | ||
| 120 | + "dtype": "bfloat16", | ||
| 121 | + "format": "ND", | ||
| 122 | + "paramType": "required", | ||
| 123 | + "shape": [ | ||
| 124 | + -2 | ||
| 125 | + ] | ||
| 126 | + } | ||
| 127 | + ], | ||
| 128 | + "attrs": [ | ||
| 129 | + { | ||
| 130 | + "name": "dim", | ||
| 131 | + "dtype": "int64", | ||
| 132 | + "value": -1 | ||
| 133 | + }, | ||
| 134 | + { | ||
| 135 | + "name": "beta", | ||
| 136 | + "dtype": "float32", | ||
| 137 | + "value": 1.0 | ||
| 138 | + }, | ||
| 139 | + { | ||
| 140 | + "name": "linear_beta", | ||
| 141 | + "dtype": "float32", | ||
| 142 | + "value": 0.0 | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "name": "activate_left", | ||
| 146 | + "dtype": "bool", | ||
| 147 | + "value": true | ||
| 148 | + } | ||
| 149 | + ] | ||
| 150 | + } | ||
| 151 | + ] | ||
| 152 | +} | ||
| @@ -0,0 +1,152 @@ | |||
| 1 | +{ | ||
| 2 | + "op_type": "SituGlu", | ||
| 3 | + "op_list": [ | ||
| 4 | + { | ||
| 5 | + "bin_filename": "SituGlu_fp32", | ||
| 6 | + "inputs": [ | ||
| 7 | + { | ||
| 8 | + "name": "x", | ||
| 9 | + "index": 0, | ||
| 10 | + "dtype": "float32", | ||
| 11 | + "format": "ND", | ||
| 12 | + "paramType": "required", | ||
| 13 | + "shape": [ | ||
| 14 | + -2 | ||
| 15 | + ] | ||
| 16 | + } | ||
| 17 | + ], | ||
| 18 | + "outputs": [ | ||
| 19 | + { | ||
| 20 | + "name": "y", | ||
| 21 | + "index": 0, | ||
| 22 | + "dtype": "float32", | ||
| 23 | + "format": "ND", | ||
| 24 | + "paramType": "required", | ||
| 25 | + "shape": [ | ||
| 26 | + -2 | ||
| 27 | + ] | ||
| 28 | + } | ||
| 29 | + ], | ||
| 30 | + "attrs": [ | ||
| 31 | + { | ||
| 32 | + "name": "dim", | ||
| 33 | + "dtype": "int64", | ||
| 34 | + "value": -1 | ||
| 35 | + }, | ||
| 36 | + { | ||
| 37 | + "name": "beta", | ||
| 38 | + "dtype": "float32", | ||
| 39 | + "value": 1.0 | ||
| 40 | + }, | ||
| 41 | + { | ||
| 42 | + "name": "linear_beta", | ||
| 43 | + "dtype": "float32", | ||
| 44 | + "value": 0.0 | ||
| 45 | + }, | ||
| 46 | + { | ||
| 47 | + "name": "activate_left", | ||
| 48 | + "dtype": "bool", | ||
| 49 | + "value": true | ||
| 50 | + } | ||
| 51 | + ] | ||
| 52 | + }, | ||
| 53 | + { | ||
| 54 | + "bin_filename": "SituGlu_fp16", | ||
| 55 | + "inputs": [ | ||
| 56 | + { | ||
| 57 | + "name": "x", | ||
| 58 | + "index": 0, | ||
| 59 | + "dtype": "float16", | ||
| 60 | + "format": "ND", | ||
| 61 | + "paramType": "required", | ||
| 62 | + "shape": [ | ||
| 63 | + -2 | ||
| 64 | + ] | ||
| 65 | + } | ||
| 66 | + ], | ||
| 67 | + "outputs": [ | ||
| 68 | + { | ||
| 69 | + "name": "y", | ||
| 70 | + "index": 0, | ||
| 71 | + "dtype": "float16", | ||
| 72 | + "format": "ND", | ||
| 73 | + "paramType": "required", | ||
| 74 | + "shape": [ | ||
| 75 | + -2 | ||
| 76 | + ] | ||
| 77 | + } | ||
| 78 | + ], | ||
| 79 | + "attrs": [ | ||
| 80 | + { | ||
| 81 | + "name": "dim", | ||
| 82 | + "dtype": "int64", | ||
| 83 | + "value": -1 | ||
| 84 | + }, | ||
| 85 | + { | ||
| 86 | + "name": "beta", | ||
| 87 | + "dtype": "float32", | ||
| 88 | + "value": 1.0 | ||
| 89 | + }, | ||
| 90 | + { | ||
| 91 | + "name": "linear_beta", | ||
| 92 | + "dtype": "float32", | ||
| 93 | + "value": 0.0 | ||
| 94 | + }, | ||
| 95 | + { | ||
| 96 | + "name": "activate_left", | ||
| 97 | + "dtype": "bool", | ||
| 98 | + "value": true | ||
| 99 | + } | ||
| 100 | + ] | ||
| 101 | + }, | ||
| 102 | + { | ||
| 103 | + "bin_filename": "SituGlu_bf16", | ||
| 104 | + "inputs": [ | ||
| 105 | + { | ||
| 106 | + "name": "x", | ||
| 107 | + "index": 0, | ||
| 108 | + "dtype": "bfloat16", | ||
| 109 | + "format": "ND", | ||
| 110 | + "paramType": "required", | ||
| 111 | + "shape": [ | ||
| 112 | + -2 | ||
| 113 | + ] | ||
| 114 | + } | ||
| 115 | + ], | ||
| 116 | + "outputs": [ | ||
| 117 | + { | ||
| 118 | + "name": "y", | ||
| 119 | + "index": 0, | ||
| 120 | + "dtype": "bfloat16", | ||
| 121 | + "format": "ND", | ||
| 122 | + "paramType": "required", | ||
| 123 | + "shape": [ | ||
| 124 | + -2 | ||
| 125 | + ] | ||
| 126 | + } | ||
| 127 | + ], | ||
| 128 | + "attrs": [ | ||
| 129 | + { | ||
| 130 | + "name": "dim", | ||
| 131 | + "dtype": "int64", | ||
| 132 | + "value": -1 | ||
| 133 | + }, | ||
| 134 | + { | ||
| 135 | + "name": "beta", | ||
| 136 | + "dtype": "float32", | ||
| 137 | + "value": 1.0 | ||
| 138 | + }, | ||
| 139 | + { | ||
| 140 | + "name": "linear_beta", | ||
| 141 | + "dtype": "float32", | ||
| 142 | + "value": 0.0 | ||
| 143 | + }, | ||
| 144 | + { | ||
| 145 | + "name": "activate_left", | ||
| 146 | + "dtype": "bool", | ||
| 147 | + "value": true | ||
| 148 | + } | ||
| 149 | + ] | ||
| 150 | + } | ||
| 151 | + ] | ||
| 152 | +} | ||
| @@ -0,0 +1,47 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file situ_glu_def.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#include <register/op_def_registry.h> | ||
| 16 | + | ||
| 17 | +namespace ops { | ||
| 18 | +constexpr float DEFAULT_BETA = 1.0; | ||
| 19 | +constexpr float DEFAULT_LINEAR_BETA = 0.0; | ||
| 20 | + | ||
| 21 | +static const std::vector<ge::DataType> xDtype = {ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}; | ||
| 22 | +static const std::vector<ge::Format> xFormat = {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}; | ||
| 23 | +static const std::vector<ge::Format> xUnknownFormat = {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}; | ||
| 24 | + | ||
| 25 | +class SituGlu : public OpDef { | ||
| 26 | +public: | ||
| 27 | + explicit SituGlu(const char* name) : OpDef(name) | ||
| 28 | + { | ||
| 29 | + this->Input("x") | ||
| 30 | + .ParamType(REQUIRED) | ||
| 31 | + .DataType(xDtype) | ||
| 32 | + .Format(xFormat) | ||
| 33 | + .UnknownShapeFormat(xUnknownFormat) | ||
| 34 | + .AutoContiguous(); | ||
| 35 | + this->Output("y").ParamType(REQUIRED).DataType(xDtype).Format(xFormat).UnknownShapeFormat(xUnknownFormat); | ||
| 36 | + this->Attr("dim").AttrType(OPTIONAL).Int(-1); | ||
| 37 | + this->Attr("beta").AttrType(OPTIONAL).Float(DEFAULT_BETA); | ||
| 38 | + this->Attr("linear_beta").AttrType(OPTIONAL).Float(DEFAULT_LINEAR_BETA); | ||
| 39 | + this->Attr("activate_left").AttrType(OPTIONAL).Bool(true); | ||
| 40 | + | ||
| 41 | + this->AICore().AddConfig("ascend910b"); | ||
| 42 | + this->AICore().AddConfig("ascend910_93"); | ||
| 43 | + this->AICore().AddConfig("ascend950"); | ||
| 44 | + } | ||
| 45 | +}; | ||
| 46 | +OP_ADD(SituGlu); | ||
| 47 | +} // namespace ops | ||
| @@ -0,0 +1,81 @@ | |||
| 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 situ_glu_infershape.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "log/log.h" | ||
| 17 | +#include "register/op_impl_registry.h" | ||
| 18 | +#include "error_util.h" | ||
| 19 | +#include "util/shape_util.h" | ||
| 20 | +using namespace ge; | ||
| 21 | + | ||
| 22 | +namespace { | ||
| 23 | +constexpr size_t GLU_IN_X = 0; | ||
| 24 | +constexpr size_t GLU_OUT_Y = 0; | ||
| 25 | +constexpr size_t GLU_ATTR_DIM = 0; | ||
| 26 | +const size_t SPLIT_NUM = 2; | ||
| 27 | +} // namespace | ||
| 28 | + | ||
| 29 | +namespace ops { | ||
| 30 | +static ge::graphStatus InferShapeForSituGlu(gert::InferShapeContext* context) | ||
| 31 | +{ | ||
| 32 | + OP_LOGD(context->GetNodeName(), "Begin to do InferShapeForSituGlu"); | ||
| 33 | + auto xShape = context->GetInputShape(GLU_IN_X); | ||
| 34 | + OPS_CHECK_NULL_WITH_CONTEXT(context, xShape); | ||
| 35 | + auto yShape = context->GetOutputShape(GLU_OUT_Y); | ||
| 36 | + OPS_CHECK_NULL_WITH_CONTEXT(context, yShape); | ||
| 37 | + auto attrs = context->GetAttrs(); | ||
| 38 | + OPS_CHECK_NULL_WITH_CONTEXT(context, attrs); | ||
| 39 | + | ||
| 40 | + auto splitDimPtr = attrs->GetAttrPointer<int64_t>(GLU_ATTR_DIM); | ||
| 41 | + OPS_CHECK_NULL_WITH_CONTEXT(context, splitDimPtr); | ||
| 42 | + if (Ops::Base::IsUnknownRank(*xShape)) { | ||
| 43 | + Ops::Base::SetUnknownRank(*yShape); | ||
| 44 | + return ge::GRAPH_SUCCESS; | ||
| 45 | + } | ||
| 46 | + auto splitDim = *splitDimPtr; | ||
| 47 | + if (splitDim < 0) { | ||
| 48 | + splitDim += xShape->GetDimNum(); | ||
| 49 | + } | ||
| 50 | + if (splitDim < 0 || splitDim >= static_cast<int64_t>(xShape->GetDimNum())) { | ||
| 51 | + OP_LOGE("SituGlu", "The value of attr [dim] must be in the range [-%zu, %zu], but got [%ld].", | ||
| 52 | + xShape->GetDimNum(), xShape->GetDimNum() - 1, splitDim); | ||
| 53 | + return GRAPH_FAILED; | ||
| 54 | + } | ||
| 55 | + OP_LOGD(context->GetNodeName(), "Begin to generate yShape"); | ||
| 56 | + *yShape = *xShape; | ||
| 57 | + // dynamic shape | ||
| 58 | + if (xShape->GetDim(splitDim) == -1) { | ||
| 59 | + return ge::GRAPH_SUCCESS; | ||
| 60 | + } | ||
| 61 | + if (xShape->GetDim(splitDim) < 0 || xShape->GetDim(splitDim) % SPLIT_NUM != 0) { | ||
| 62 | + OP_LOGE("SituGlu", "The shape [%s] is not divisible by 2.", Ops::Base::ToString(*xShape).c_str()); | ||
| 63 | + return GRAPH_FAILED; | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + yShape->SetDim(splitDim, xShape->GetDim(splitDim) / SPLIT_NUM); | ||
| 67 | + OP_LOGD(context->GetNodeName(), "End to do InferShapeForSituGlu"); | ||
| 68 | + return ge::GRAPH_SUCCESS; | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +static ge::graphStatus InferDataTypeForSituGlu(gert::InferDataTypeContext* context) | ||
| 72 | +{ | ||
| 73 | + OP_LOGD(context->GetNodeName(), "Begin to do InferDataTypeForSituGlu"); | ||
| 74 | + const ge::DataType dtype = context->GetInputDataType(0); | ||
| 75 | + ge::graphStatus ret = context->SetOutputDataType(0, dtype); | ||
| 76 | + OP_LOGD(context->GetNodeName(), "End to do InferDataTypeForSituGlu"); | ||
| 77 | + return ret; | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +IMPL_OP_INFERSHAPE(SituGlu).InferShape(InferShapeForSituGlu).InferDataType(InferDataTypeForSituGlu); | ||
| 81 | +} // namespace ops | ||
| @@ -0,0 +1,280 @@ | |||
| 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 situ_glu_tiling.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#include "situ_glu_tiling.h" | ||
| 16 | + | ||
| 17 | +using Ops::NN::Optiling::TilingRegistry; | ||
| 18 | +using namespace ge; | ||
| 19 | +namespace optiling { | ||
| 20 | +constexpr int64_t X_INDEX = 0; | ||
| 21 | +constexpr int64_t Y_INDEX = 0; | ||
| 22 | +constexpr int64_t DIM_INDEX = 0; | ||
| 23 | +constexpr int64_t BETA_INDEX = 1; | ||
| 24 | +constexpr int64_t LINEAR_BETA_INDEX = 2; | ||
| 25 | +constexpr int64_t ACTIVATE_LEFT_INDEX = 3; | ||
| 26 | +constexpr uint64_t WORKSPACE_SIZE = 16 * 1024 * 1024; | ||
| 27 | + | ||
| 28 | +constexpr int64_t BLOCK_SIZE = 32; | ||
| 29 | +constexpr int64_t SWI_FACTOR = 2; | ||
| 30 | +constexpr int64_t BLOCK_ELEM = BLOCK_SIZE / sizeof(float); // 8 floats per 32B block | ||
| 31 | +constexpr int64_t UB_RESERVE = 1024; | ||
| 32 | +constexpr int64_t FLOATS_PER_PAIR = 7; // xQueue(DB2*2=4) + yQueue(1) + tmpBuf1(1) + tmpBuf2(1) | ||
| 33 | + | ||
| 34 | +constexpr float BETA_DEFAULT = 1.0f; | ||
| 35 | +constexpr float LINEAR_BETA_DEFAULT = 0.0f; | ||
| 36 | +constexpr bool ACTIVATE_LEFT_DEFAULT = true; | ||
| 37 | + | ||
| 38 | +static const std::set<ge::DataType> SUPPORT_DTYPE = {ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}; | ||
| 39 | +// 获取INPUT/OUTPUT/ATTR信息 | ||
| 40 | +ge::graphStatus SituGluTiling::GetShapeAttrsInfo() { return ge::GRAPH_SUCCESS; } | ||
| 41 | +// 获取平台信息比如CoreNum、UB/L1/L0C资源大小 | ||
| 42 | +ge::graphStatus SituGluTiling::GetPlatformInfo() | ||
| 43 | +{ | ||
| 44 | + auto platformInfo = context_->GetPlatformInfo(); | ||
| 45 | + if (platformInfo == nullptr) { | ||
| 46 | + auto compileInfoPtr = context_->GetCompileInfo<SituGluCompileInfo>(); | ||
| 47 | + OP_CHECK_IF(compileInfoPtr == nullptr, OP_LOGE(context_, "compile info is null"), return ge::GRAPH_FAILED); | ||
| 48 | + coreNumAll_ = compileInfoPtr->coreNum; | ||
| 49 | + ubSize_ = compileInfoPtr->ubSize; | ||
| 50 | + } else { | ||
| 51 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); | ||
| 52 | + coreNumAll_ = ascendcPlatform.GetCoreNumAiv(); | ||
| 53 | + uint64_t ubSizePlatForm; | ||
| 54 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); | ||
| 55 | + ubSize_ = ubSizePlatForm; | ||
| 56 | + socVersion_ = ascendcPlatform.GetSocVersion(); | ||
| 57 | + } | ||
| 58 | + return ge::GRAPH_SUCCESS; | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +bool SituGluTiling::IsCapable() | ||
| 62 | +{ | ||
| 63 | + if (socVersion_ != platform_ascendc::SocVersion::ASCEND910_93 && | ||
| 64 | + socVersion_ != platform_ascendc::SocVersion::ASCEND910B && | ||
| 65 | + socVersion_ != platform_ascendc::SocVersion::ASCEND950) { | ||
| 66 | + return false; | ||
| 67 | + } | ||
| 68 | + return true; | ||
| 69 | +} | ||
| 70 | +// 计算数据切分TilingData | ||
| 71 | +ge::graphStatus SituGluTiling::DoOpTiling() | ||
| 72 | +{ | ||
| 73 | + // 校验并获取输入参数 | ||
| 74 | + if (GetShapeAttrsInfoInner() == ge::GRAPH_FAILED) { | ||
| 75 | + return ge::GRAPH_FAILED; | ||
| 76 | + } | ||
| 77 | + // 计算UB可以计算的最多pair数量(1个gate元素+1个up元素为1pair) | ||
| 78 | + CountMaxPair(); | ||
| 79 | + // 设置tilingKey | ||
| 80 | + tilingKey_ = 1; | ||
| 81 | + // 设置tiling结构体参数 | ||
| 82 | + tilingData_.set_coreNumAll(coreNumAll_); | ||
| 83 | + tilingData_.set_dimBatchSize(dimBatchSize_); | ||
| 84 | + tilingData_.set_dim2H(dim2H_); | ||
| 85 | + tilingData_.set_isLongH(isLongH_); | ||
| 86 | + tilingData_.set_ubMaxPair(ubMaxPair_); | ||
| 87 | + tilingData_.set_beta(beta_); | ||
| 88 | + tilingData_.set_linearBeta(linearBeta_); | ||
| 89 | + tilingData_.set_activateLeft(activateLeft_); | ||
| 90 | + return ge::GRAPH_SUCCESS; | ||
| 91 | +} | ||
| 92 | +// 计算高阶API的TilingData | ||
| 93 | +ge::graphStatus SituGluTiling::DoLibApiTiling() { return ge::GRAPH_SUCCESS; } | ||
| 94 | +// 计算Workspace 大小 | ||
| 95 | +ge::graphStatus SituGluTiling::GetWorkspaceSize() | ||
| 96 | +{ | ||
| 97 | + workspaceSize_ = WORKSPACE_SIZE; | ||
| 98 | + return ge::GRAPH_SUCCESS; | ||
| 99 | +} | ||
| 100 | +// 保存Tiling数据 | ||
| 101 | +ge::graphStatus SituGluTiling::PostTiling() | ||
| 102 | +{ | ||
| 103 | + context_->SetTilingKey(GetTilingKey()); | ||
| 104 | + context_->SetBlockDim(coreNumAll_); | ||
| 105 | + size_t* workspaces = context_->GetWorkspaceSizes(1); | ||
| 106 | + workspaces[0] = workspaceSize_; | ||
| 107 | + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); | ||
| 108 | + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); | ||
| 109 | + return ge::GRAPH_SUCCESS; | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +uint64_t SituGluTiling::GetTilingKey() const { return tilingKey_; } | ||
| 113 | + | ||
| 114 | +// Dump Tiling数据 | ||
| 115 | +void SituGluTiling::DumpTilingInfo() | ||
| 116 | +{ | ||
| 117 | + std::ostringstream info; | ||
| 118 | + info << "tilingKey_: " << tilingKey_; | ||
| 119 | + info << ", coreNumAll: " << tilingData_.get_coreNumAll(); | ||
| 120 | + info << ", ubSize_: " << ubSize_; | ||
| 121 | + info << ", xDims_: " << xDims_; | ||
| 122 | + info << ", cutDim_: " << cutDim_; | ||
| 123 | + info << ", dimBatchSize: " << tilingData_.get_dimBatchSize(); | ||
| 124 | + info << ", dim2H: " << tilingData_.get_dim2H(); | ||
| 125 | + info << ", isLongH: " << tilingData_.get_isLongH(); | ||
| 126 | + info << ", beta: " << tilingData_.get_beta(); | ||
| 127 | + info << ", linearBeta: " << tilingData_.get_linearBeta(); | ||
| 128 | + info << ", activateLeft: " << tilingData_.get_activateLeft(); | ||
| 129 | + info << ", ubMaxPair: " << tilingData_.get_ubMaxPair(); | ||
| 130 | + OP_LOGI(context_->GetNodeName(), "%s", info.str().c_str()); | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +ge::graphStatus SituGluTiling::GetShapeAttrsInfoInner() | ||
| 134 | +{ | ||
| 135 | + OP_CHECK_IF(CheckAndGetXAndAttrs() != ge::GRAPH_SUCCESS, | ||
| 136 | + OP_LOGE(context_->GetNodeName(), "check x and attrs failed."), return ge::GRAPH_FAILED); | ||
| 137 | + OP_CHECK_IF(CheckY() != ge::GRAPH_SUCCESS, OP_LOGE(context_->GetNodeName(), "check y param failed."), | ||
| 138 | + return ge::GRAPH_FAILED); | ||
| 139 | + return ge::GRAPH_SUCCESS; | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +ge::graphStatus SituGluTiling::CheckAndGetXAndAttrs() | ||
| 143 | +{ | ||
| 144 | + // 获取attr参数 | ||
| 145 | + auto* attrs = context_->GetAttrs(); | ||
| 146 | + OP_CHECK_NULL_WITH_CONTEXT(context_, attrs); | ||
| 147 | + auto* attrDim = attrs->GetAttrPointer<int>(DIM_INDEX); | ||
| 148 | + cutDim_ = attrDim == nullptr ? -1 : *attrDim; | ||
| 149 | + auto* attrBeta = attrs->GetAttrPointer<float>(BETA_INDEX); | ||
| 150 | + beta_ = attrBeta == nullptr ? BETA_DEFAULT : *attrBeta; | ||
| 151 | + auto* attrLinearBeta = attrs->GetAttrPointer<float>(LINEAR_BETA_INDEX); | ||
| 152 | + linearBeta_ = attrLinearBeta == nullptr ? LINEAR_BETA_DEFAULT : *attrLinearBeta; | ||
| 153 | + auto* attrActivateLeft = attrs->GetAttrPointer<bool>(ACTIVATE_LEFT_INDEX); | ||
| 154 | + bool activateLeft = attrActivateLeft == nullptr ? ACTIVATE_LEFT_DEFAULT : *attrActivateLeft; | ||
| 155 | + activateLeft_ = activateLeft ? 1 : 0; | ||
| 156 | + // 获取x shape | ||
| 157 | + auto shapeX = context_->GetInputShape(X_INDEX); | ||
| 158 | + OP_CHECK_NULL_WITH_CONTEXT(context_, shapeX); | ||
| 159 | + const gert::Shape& inputShapeX = shapeX->GetStorageShape(); | ||
| 160 | + xDims_ = inputShapeX.GetDimNum(); | ||
| 161 | + OP_CHECK_IF( | ||
| 162 | + (cutDim_ > (xDims_ - 1) || cutDim_ < -1 * xDims_), | ||
| 163 | + OP_LOGE(context_->GetNodeName(), "dim should in [-%ld, %ld], but get %ld,", xDims_, xDims_ - 1, cutDim_), | ||
| 164 | + return ge::GRAPH_FAILED); | ||
| 165 | + cutDim_ = cutDim_ < 0 ? (cutDim_ + xDims_) : cutDim_; // cutDim统一为正数 | ||
| 166 | + cutDimSize_ = inputShapeX.GetDim(cutDim_); | ||
| 167 | + // x合轴为2维:dimBatchSize为cutDim之前的各维乘积,dim2H为cutDim及之后的各维乘积 | ||
| 168 | + if (xDims_ == 1) { | ||
| 169 | + dimBatchSize_ = 1; | ||
| 170 | + dim2H_ = inputShapeX.GetDim(0); | ||
| 171 | + } else { | ||
| 172 | + for (int64_t i = 0; i < cutDim_; i++) { | ||
| 173 | + dimBatchSize_ *= inputShapeX.GetDim(i); | ||
| 174 | + } | ||
| 175 | + for (int64_t j = cutDim_; j < xDims_; j++) { | ||
| 176 | + dim2H_ *= inputShapeX.GetDim(j); | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + OP_CHECK_IF((cutDimSize_ % 2 == 1), | ||
| 180 | + OP_LOGE(context_->GetNodeName(), "x[dim] should be divisible by 2, but get %ld", cutDimSize_), | ||
| 181 | + return ge::GRAPH_FAILED); | ||
| 182 | + auto descX = context_->GetInputDesc(X_INDEX); | ||
| 183 | + OP_CHECK_NULL_WITH_CONTEXT(context_, descX); | ||
| 184 | + xDtype_ = descX->GetDataType(); | ||
| 185 | + OP_CHECK_IF((SUPPORT_DTYPE.find(xDtype_) == SUPPORT_DTYPE.end()), | ||
| 186 | + OP_LOGE(context_->GetNodeName(), "x dtype only support float32/float16/bfloat16, please check."), | ||
| 187 | + return ge::GRAPH_FAILED); | ||
| 188 | + return ge::GRAPH_SUCCESS; | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +ge::graphStatus SituGluTiling::CheckY() | ||
| 192 | +{ | ||
| 193 | + auto shapeY = context_->GetOutputShape(Y_INDEX); | ||
| 194 | + OP_CHECK_NULL_WITH_CONTEXT(context_, shapeY); | ||
| 195 | + const gert::Shape& inputShapeY = shapeY->GetStorageShape(); | ||
| 196 | + int64_t yDims = inputShapeY.GetDimNum(); | ||
| 197 | + auto descY = context_->GetInputDesc(Y_INDEX); | ||
| 198 | + OP_CHECK_NULL_WITH_CONTEXT(context_, descY); | ||
| 199 | + auto yDtype = descY->GetDataType(); | ||
| 200 | + OP_CHECK_IF((yDims != xDims_), | ||
| 201 | + OP_LOGE(context_->GetNodeName(), | ||
| 202 | + "the number of dimensions of y should be equal to dimensions of x, but get %ld.", yDims), | ||
| 203 | + return ge::GRAPH_FAILED); | ||
| 204 | + OP_CHECK_IF( | ||
| 205 | + (inputShapeY.GetDim(cutDim_) != (cutDimSize_ / SWI_FACTOR)), | ||
| 206 | + OP_LOGE(context_->GetNodeName(), "y[dim] should be equal to x[dim] divided by 2, but get %ld, expected %ld.", | ||
| 207 | + inputShapeY.GetDim(cutDim_), cutDimSize_ / SWI_FACTOR), | ||
| 208 | + return ge::GRAPH_FAILED); | ||
| 209 | + OP_CHECK_IF((yDtype != xDtype_), | ||
| 210 | + OP_LOGE(context_->GetNodeName(), "y dtype should be the same as x, please cheack."), | ||
| 211 | + return ge::GRAPH_FAILED); | ||
| 212 | + return ge::GRAPH_SUCCESS; | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +ge::graphStatus SituGluTiling::CountMaxPair() | ||
| 216 | +{ | ||
| 217 | + ubMaxPair_ = 1; | ||
| 218 | + int64_t numerator = static_cast<int64_t>(ubSize_) - UB_RESERVE; | ||
| 219 | + // fp32: xQueue(DB2*2 halves=4) + yQueue(1) + tmpBuf1(1) + tmpBuf2(1) = 7 floats/pair | ||
| 220 | + // fp16/bf16: xQueue(4 T) + yQueue(1 T) + 5 float bufs(tmp1/tmp2/gateF/upF/yF) = 5*4 + 5*T bytes/pair | ||
| 221 | + int64_t bytesPerPair = FLOATS_PER_PAIR * static_cast<int64_t>(sizeof(float)); | ||
| 222 | + int64_t alignElem = BLOCK_ELEM; // 32B / sizeof(float) = 8 | ||
| 223 | + if (xDtype_ == ge::DT_FLOAT16 || xDtype_ == ge::DT_BF16) { | ||
| 224 | + constexpr int64_t MIXED_TBUFS = 5; // tmp1 + tmp2 + gateF + upF + yF | ||
| 225 | + bytesPerPair = SWI_FACTOR * SWI_FACTOR * static_cast<int64_t>(sizeof(int16_t)) // xQueue: 2 halves * DB2 * T | ||
| 226 | + + static_cast<int64_t>(sizeof(int16_t)) // yQueue: 1 * T | ||
| 227 | + + MIXED_TBUFS * static_cast<int64_t>(sizeof(float)); | ||
| 228 | + alignElem = BLOCK_SIZE / static_cast<int64_t>(sizeof(int16_t)); // 16, 同时满足 T(16) 与 float(8) 的 32B 对齐 | ||
| 229 | + } | ||
| 230 | + ubMaxPair_ = numerator / bytesPerPair; | ||
| 231 | + ubMaxPair_ = ubMaxPair_ / alignElem * alignElem; // 32字节对齐 | ||
| 232 | + OP_CHECK_IF((numerator <= 0 || ubMaxPair_ <= 0), | ||
| 233 | + OP_LOGE(context_->GetNodeName(), "Input not supported, ub size is too small."), | ||
| 234 | + return ge::GRAPH_FAILED); | ||
| 235 | + int64_t dimH = dim2H_ / SWI_FACTOR; | ||
| 236 | + int64_t dsize = (xDtype_ == ge::DT_FLOAT16 || xDtype_ == ge::DT_BF16) ? static_cast<int64_t>(sizeof(int16_t)) : | ||
| 237 | + static_cast<int64_t>(sizeof(float)); | ||
| 238 | + // short-H 路径按行 stride 拷贝(blockCount>1),要求每个半行(dimH*dsize) 32B 对齐; | ||
| 239 | + // 否则回退到 long-H 连续单块拷贝路径,由 DataCopyPad 处理 sub-block 对齐。 | ||
| 240 | + bool halfRowAligned = (dimH * dsize) % BLOCK_SIZE == 0; | ||
| 241 | + isLongH_ = (ubMaxPair_ < dimH || !halfRowAligned) ? 1 : 0; | ||
| 242 | + | ||
| 243 | + return ge::GRAPH_SUCCESS; | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +REGISTER_TILING_TEMPLATE("SituGlu", SituGluTiling, 20000); | ||
| 247 | + | ||
| 248 | +ge::graphStatus TilingForSituGlu(gert::TilingContext* context) | ||
| 249 | +{ | ||
| 250 | + return TilingRegistry::GetInstance().DoTilingImpl(context); | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +ge::graphStatus TilingPrepareForSituGlu(gert::TilingParseContext* context) | ||
| 254 | +{ | ||
| 255 | + OP_LOGD(context, "TilingPrepareForSituGlu enter."); | ||
| 256 | + auto compileInfo = context->GetCompiledInfo<SituGluCompileInfo>(); | ||
| 257 | + OP_CHECK_NULL_WITH_CONTEXT(context, compileInfo); | ||
| 258 | + auto platformInfo = context->GetPlatformInfo(); | ||
| 259 | + OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo); | ||
| 260 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); | ||
| 261 | + compileInfo->coreNum = ascendcPlatform.GetCoreNumAiv(); | ||
| 262 | + OP_CHECK_IF((compileInfo->coreNum <= 0), | ||
| 263 | + OP_LOGE(context->GetNodeName(), "Get core num failed, core num: %u", | ||
| 264 | + static_cast<uint32_t>(compileInfo->coreNum)), | ||
| 265 | + return ge::GRAPH_FAILED); | ||
| 266 | + | ||
| 267 | + uint64_t ubSize; | ||
| 268 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize); | ||
| 269 | + compileInfo->ubSize = ubSize; | ||
| 270 | + OP_CHECK_IF( | ||
| 271 | + (compileInfo->ubSize <= 0), | ||
| 272 | + OP_LOGE(context->GetNodeName(), "Get ub size failed, ub size: %u", static_cast<uint32_t>(compileInfo->ubSize)), | ||
| 273 | + return ge::GRAPH_FAILED); | ||
| 274 | + | ||
| 275 | + OP_LOGD(context, "TilingPrepareForSituGlu exit."); | ||
| 276 | + return ge::GRAPH_SUCCESS; | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +IMPL_OP_OPTILING(SituGlu).Tiling(TilingForSituGlu).TilingParse<SituGluCompileInfo>(TilingPrepareForSituGlu); | ||
| 280 | +} // namespace optiling | ||
| @@ -0,0 +1,90 @@ | |||
| 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 situ_glu_tiling.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#ifndef AIR_CXX_RUNTIME_V2_OP_IMPL_SITU_GLU_H_ | ||
| 16 | +#define AIR_CXX_RUNTIME_V2_OP_IMPL_SITU_GLU_H_ | ||
| 17 | + | ||
| 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 "platform/platform_infos_def.h" | ||
| 23 | +#include "register/tilingdata_base.h" | ||
| 24 | +#include "tiling/tiling_api.h" | ||
| 25 | +#include "../op_graph/situ_glu_proto.h" | ||
| 26 | +#include "op_host/tiling_base.h" | ||
| 27 | +#include "op_host/tiling_templates_registry.h" | ||
| 28 | +#include "op_host/tiling_util.h" | ||
| 29 | + | ||
| 30 | +namespace optiling { | ||
| 31 | +using Ops::NN::Optiling::TilingBaseClass; | ||
| 32 | +BEGIN_TILING_DATA_DEF(SituGluTilingData) | ||
| 33 | +TILING_DATA_FIELD_DEF(int64_t, coreNumAll); | ||
| 34 | +TILING_DATA_FIELD_DEF(int64_t, dimBatchSize); | ||
| 35 | +TILING_DATA_FIELD_DEF(int64_t, dim2H); | ||
| 36 | +TILING_DATA_FIELD_DEF(int64_t, isLongH); | ||
| 37 | +TILING_DATA_FIELD_DEF(int64_t, ubMaxPair); | ||
| 38 | +TILING_DATA_FIELD_DEF(float, beta); | ||
| 39 | +TILING_DATA_FIELD_DEF(float, linearBeta); | ||
| 40 | +TILING_DATA_FIELD_DEF(int64_t, activateLeft); | ||
| 41 | +END_TILING_DATA_DEF; | ||
| 42 | + | ||
| 43 | +REGISTER_TILING_DATA_CLASS(SituGlu, SituGluTilingData) | ||
| 44 | + | ||
| 45 | +struct SituGluCompileInfo { | ||
| 46 | + uint64_t coreNum = 0; | ||
| 47 | + uint64_t ubSize = 0; | ||
| 48 | +}; | ||
| 49 | + | ||
| 50 | +class SituGluTiling : public TilingBaseClass { | ||
| 51 | +public: | ||
| 52 | + explicit SituGluTiling(gert::TilingContext* tilingContext) : TilingBaseClass(tilingContext) {} | ||
| 53 | + ~SituGluTiling() override {} | ||
| 54 | + | ||
| 55 | +protected: | ||
| 56 | + bool IsCapable() override; | ||
| 57 | + ge::graphStatus GetPlatformInfo() override; | ||
| 58 | + ge::graphStatus GetShapeAttrsInfo() override; | ||
| 59 | + ge::graphStatus DoOpTiling() override; | ||
| 60 | + ge::graphStatus DoLibApiTiling() override; | ||
| 61 | + uint64_t GetTilingKey() const override; | ||
| 62 | + ge::graphStatus GetWorkspaceSize() override; | ||
| 63 | + ge::graphStatus PostTiling() override; | ||
| 64 | + void DumpTilingInfo() override; | ||
| 65 | + ge::graphStatus GetShapeAttrsInfoInner(); | ||
| 66 | + ge::graphStatus CheckAndGetXAndAttrs(); | ||
| 67 | + ge::graphStatus CheckY(); | ||
| 68 | + ge::graphStatus CountMaxPair(); | ||
| 69 | + | ||
| 70 | +private: | ||
| 71 | + uint64_t tilingKey_ = 0; | ||
| 72 | + SituGluTilingData tilingData_; | ||
| 73 | + platform_ascendc::SocVersion socVersion_ = platform_ascendc::SocVersion::ASCEND910B; | ||
| 74 | + uint64_t coreNumAll_ = 0; | ||
| 75 | + uint64_t ubSize_ = 0; | ||
| 76 | + int64_t xDims_ = 0; | ||
| 77 | + int64_t cutDim_ = 0; | ||
| 78 | + int64_t dimBatchSize_ = 1; | ||
| 79 | + int64_t dim2H_ = 1; | ||
| 80 | + int64_t cutDimSize_ = 0; // size of x at cutDim (before halving), for CheckY validation | ||
| 81 | + int64_t isLongH_ = 0; | ||
| 82 | + ge::DataType xDtype_ = ge::DT_FLOAT; | ||
| 83 | + float beta_ = 1.0f; | ||
| 84 | + float linearBeta_ = 0.0f; | ||
| 85 | + int64_t activateLeft_ = 1; | ||
| 86 | + int64_t ubMaxPair_ = 0; | ||
| 87 | +}; | ||
| 88 | + | ||
| 89 | +} // namespace optiling | ||
| 90 | +#endif // AIR_CXX_RUNTIME_V2_OP_IMPL_SITU_GLU_H_ | ||
| @@ -0,0 +1,55 @@ | |||
| 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 situ_glu.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | +#include "kernel_operator.h" | ||
| 16 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 17 | +#include "situ_glu.hpp" | ||
| 18 | + | ||
| 19 | +using namespace AscendC; | ||
| 20 | +extern "C" __global__ __aicore__ void situ_glu(GM_ADDR xGM, GM_ADDR yGM, GM_ADDR workspace, GM_ADDR tiling) | ||
| 21 | +{ | ||
| 22 | + if (workspace == nullptr) { | ||
| 23 | + return; | ||
| 24 | + } | ||
| 25 | + GM_ADDR userspace = GetUserWorkspace(workspace); | ||
| 26 | + if (userspace == nullptr) { | ||
| 27 | + return; | ||
| 28 | + } | ||
| 29 | + TPipe pipe; | ||
| 30 | +#if (ORIG_DTYPE_X == DT_FLOAT) | ||
| 31 | + if (TILING_KEY_IS(1)) { | ||
| 32 | + GET_TILING_DATA_WITH_STRUCT(SituGluTilingData, tilingDataIn, tiling); | ||
| 33 | + const SituGluTilingData* __restrict__ tilingData = &tilingDataIn; | ||
| 34 | + SituGluOps::SituGluBase<float> op(&pipe); | ||
| 35 | + op.Init(xGM, yGM, tilingData); | ||
| 36 | + op.Process(); | ||
| 37 | + } | ||
| 38 | +#elif (ORIG_DTYPE_X == DT_FLOAT16) | ||
| 39 | + if (TILING_KEY_IS(1)) { | ||
| 40 | + GET_TILING_DATA_WITH_STRUCT(SituGluTilingData, tilingDataIn, tiling); | ||
| 41 | + const SituGluTilingData* __restrict__ tilingData = &tilingDataIn; | ||
| 42 | + SituGluOps::SituGluBase<half> op(&pipe); | ||
| 43 | + op.Init(xGM, yGM, tilingData); | ||
| 44 | + op.Process(); | ||
| 45 | + } | ||
| 46 | +#elif (ORIG_DTYPE_X == DT_BF16) | ||
| 47 | + if (TILING_KEY_IS(1)) { | ||
| 48 | + GET_TILING_DATA_WITH_STRUCT(SituGluTilingData, tilingDataIn, tiling); | ||
| 49 | + const SituGluTilingData* __restrict__ tilingData = &tilingDataIn; | ||
| 50 | + SituGluOps::SituGluBase<bfloat16_t> op(&pipe); | ||
| 51 | + op.Init(xGM, yGM, tilingData); | ||
| 52 | + op.Process(); | ||
| 53 | + } | ||
| 54 | +#endif | ||
| 55 | +} | ||
| @@ -0,0 +1,354 @@ | |||
| 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 situ_glu.hpp | ||
| 13 | + * \brief SiTU gated linear unit (float32, front-back split). | ||
| 14 | + * | ||
| 15 | + * Single template class covering all three dtypes: | ||
| 16 | + * - SituGluBase<float> -> fp32 native compute (no Cast) | ||
| 17 | + * - SituGluBase<half> -> Cast->float32 compute -> Cast back (CAST_NONE) | ||
| 18 | + * - SituGluBase<bfloat16_t> -> Cast->float32 compute -> Cast back (CAST_RINT) | ||
| 19 | + * | ||
| 20 | + * Compute (per element pair, activate_left controls which half is the gate): | ||
| 21 | + * situ_a = beta * tanh(gate / beta) * sigmoid(gate) | ||
| 22 | + * if linear_beta > 0: up = linear_beta * tanh(up / linear_beta) | ||
| 23 | + * y = situ_a * up | ||
| 24 | + */ | ||
| 25 | +#ifndef OPP_SITU_GLU_HPP | ||
| 26 | +#define OPP_SITU_GLU_HPP | ||
| 27 | +#include "kernel_operator.h" | ||
| 28 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 29 | + | ||
| 30 | +namespace SituGluOps { | ||
| 31 | +using namespace AscendC; | ||
| 32 | +constexpr static int64_t DB_BUFFER = 2; | ||
| 33 | +constexpr static int64_t BLOCK_SIZE = 32; | ||
| 34 | +constexpr static int64_t BLOCK_ELEM = BLOCK_SIZE / sizeof(float); | ||
| 35 | +constexpr static int64_t SWI_FACTOR = 2; | ||
| 36 | + | ||
| 37 | +// Type trait: true when T is bfloat16_t. | ||
| 38 | +// bf16 requires CAST_RINT on all platforms; CAST_NONE produces garbage on non-A2 (e.g. Ascend950). | ||
| 39 | +template <typename T> | ||
| 40 | +struct SituIsBf16 : std::false_type {}; | ||
| 41 | +template <> | ||
| 42 | +struct SituIsBf16<bfloat16_t> : std::true_type {}; | ||
| 43 | + | ||
| 44 | +template <typename T> | ||
| 45 | +class SituGluBase { | ||
| 46 | + static constexpr bool kIsFp32 = std::is_same<T, float>::value; | ||
| 47 | + | ||
| 48 | +public: | ||
| 49 | + __aicore__ inline SituGluBase(TPipe* pipe) { pipe_ = pipe; }; | ||
| 50 | + __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, const SituGluTilingData* tilingData); | ||
| 51 | + __aicore__ inline int64_t AlignBytes(int64_t number); | ||
| 52 | + __aicore__ inline void Process(); | ||
| 53 | + __aicore__ inline void CalTilingParam(); | ||
| 54 | + __aicore__ inline void ProcessSingleLoop(int64_t xOffset, int64_t yOffset); | ||
| 55 | + __aicore__ inline void CopyIn(int64_t xOffset); | ||
| 56 | + __aicore__ inline void CopyInShortH(LocalTensor<T>& xLocal, int64_t xOffset); | ||
| 57 | + __aicore__ inline void CopyInLongH(LocalTensor<T>& xLocal, int64_t xOffset); | ||
| 58 | + __aicore__ inline void Compute(LocalTensor<T>& xLocal, LocalTensor<float>& tmp1, LocalTensor<float>& tmp2, | ||
| 59 | + LocalTensor<T>& yLocal); | ||
| 60 | + __aicore__ inline void CopyOut(int64_t yOffset); | ||
| 61 | + | ||
| 62 | +private: | ||
| 63 | + __aicore__ inline void SituCore(LocalTensor<float> gate, LocalTensor<float> up, LocalTensor<float> tmp1, | ||
| 64 | + LocalTensor<float> tmp2, LocalTensor<float> y, int64_t n); | ||
| 65 | + | ||
| 66 | +protected: | ||
| 67 | + /* global memory address */ | ||
| 68 | + GlobalTensor<T> xGm_; | ||
| 69 | + GlobalTensor<T> yGm_; | ||
| 70 | + | ||
| 71 | + /* ascendc variable */ | ||
| 72 | + TPipe* pipe_ = nullptr; | ||
| 73 | + TQue<QuePosition::VECIN, DB_BUFFER> xQueue_; | ||
| 74 | + TQue<QuePosition::VECOUT, 1> yQueue_; | ||
| 75 | + TBuf<TPosition::VECCALC> tmpBuf1_; | ||
| 76 | + TBuf<TPosition::VECCALC> tmpBuf2_; | ||
| 77 | + // Cast-path scratch (only InitBuffer'd when T != float; declared unconditionally | ||
| 78 | + // because TBuf is a thin handle and unused declarations have no UB footprint). | ||
| 79 | + TBuf<TPosition::VECCALC> gateFBuf_; | ||
| 80 | + TBuf<TPosition::VECCALC> upFBuf_; | ||
| 81 | + TBuf<TPosition::VECCALC> yFBbuf_; | ||
| 82 | + | ||
| 83 | + uint32_t blockIdx_ = GetBlockIdx(); | ||
| 84 | + uint32_t usedCoreNum_ = 0; | ||
| 85 | + int64_t dimBatchSize_ = 0; | ||
| 86 | + int64_t dim2H_ = 0; | ||
| 87 | + int64_t dimH_ = 0; | ||
| 88 | + int64_t isLongH_ = 0; | ||
| 89 | + int64_t ubMaxPair_ = 0; | ||
| 90 | + int64_t blockOffset_ = 0; | ||
| 91 | + int64_t loopOffset_ = 0; | ||
| 92 | + int64_t loopTime_ = 0; | ||
| 93 | + int64_t pairFrontLoop_ = 0; | ||
| 94 | + int64_t pairLastLoop_ = 0; | ||
| 95 | + int64_t pairNum_ = 0; | ||
| 96 | + int64_t batchPreBlock_ = 0; | ||
| 97 | + int64_t halfOff_ = 0; // up half offset inside one xQueue buffer (unit: T element) | ||
| 98 | + int64_t xQueSpace_ = 0; // one xQueue buffer size (unit: byte) | ||
| 99 | + float beta_ = 1.0f; | ||
| 100 | + float linearBeta_ = 0.0f; | ||
| 101 | + int64_t activateLeft_ = 1; | ||
| 102 | + const SituGluTilingData* tl_ = nullptr; | ||
| 103 | +}; | ||
| 104 | + | ||
| 105 | +template <typename T> | ||
| 106 | +__aicore__ inline void SituGluBase<T>::Init(GM_ADDR x, GM_ADDR y, const SituGluTilingData* tilingData) | ||
| 107 | +{ | ||
| 108 | + tl_ = tilingData; | ||
| 109 | + dimBatchSize_ = tl_->dimBatchSize; | ||
| 110 | + dim2H_ = tl_->dim2H; | ||
| 111 | + dimH_ = dim2H_ / SWI_FACTOR; | ||
| 112 | + isLongH_ = tl_->isLongH; | ||
| 113 | + ubMaxPair_ = tl_->ubMaxPair; | ||
| 114 | + beta_ = tl_->beta; | ||
| 115 | + linearBeta_ = tl_->linearBeta; | ||
| 116 | + activateLeft_ = tl_->activateLeft; | ||
| 117 | + // one xQueue buffer holds gate + up (2 * ubMaxPair T elements), 32B aligned | ||
| 118 | + xQueSpace_ = SWI_FACTOR * AlignBytes(ubMaxPair_ * static_cast<int64_t>(sizeof(T))); | ||
| 119 | + halfOff_ = xQueSpace_ / static_cast<int64_t>(sizeof(T)) / SWI_FACTOR; | ||
| 120 | + xGm_.SetGlobalBuffer((__gm__ T*)x); | ||
| 121 | + yGm_.SetGlobalBuffer((__gm__ T*)y); | ||
| 122 | + pipe_->InitBuffer(xQueue_, DB_BUFFER, xQueSpace_); | ||
| 123 | + pipe_->InitBuffer(yQueue_, 1, AlignBytes(ubMaxPair_ * static_cast<int64_t>(sizeof(T)))); | ||
| 124 | + pipe_->InitBuffer(tmpBuf1_, AlignBytes(ubMaxPair_ * static_cast<int64_t>(sizeof(float)))); | ||
| 125 | + pipe_->InitBuffer(tmpBuf2_, AlignBytes(ubMaxPair_ * static_cast<int64_t>(sizeof(float)))); | ||
| 126 | + if constexpr (!kIsFp32) { | ||
| 127 | + pipe_->InitBuffer(gateFBuf_, AlignBytes(ubMaxPair_ * static_cast<int64_t>(sizeof(float)))); | ||
| 128 | + pipe_->InitBuffer(upFBuf_, AlignBytes(ubMaxPair_ * static_cast<int64_t>(sizeof(float)))); | ||
| 129 | + pipe_->InitBuffer(yFBbuf_, AlignBytes(ubMaxPair_ * static_cast<int64_t>(sizeof(float)))); | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +template <typename T> | ||
| 134 | +__aicore__ inline int64_t SituGluBase<T>::AlignBytes(int64_t number) | ||
| 135 | +{ | ||
| 136 | + return (number + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE; | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +template <typename T> | ||
| 140 | +__aicore__ inline void SituGluBase<T>::Process() | ||
| 141 | +{ | ||
| 142 | + if (dimBatchSize_ <= 0 || dim2H_ <= 0) { | ||
| 143 | + return; | ||
| 144 | + } | ||
| 145 | + CalTilingParam(); | ||
| 146 | + | ||
| 147 | + if (blockIdx_ < usedCoreNum_) { | ||
| 148 | + if (isLongH_ == 1) { | ||
| 149 | + // long H: outer loop over batch, inner loop over H tiles | ||
| 150 | + for (int64_t batchIdx = 0; batchIdx < batchPreBlock_; ++batchIdx) { | ||
| 151 | + int64_t xOffset = blockIdx_ * blockOffset_ + batchIdx * dim2H_; | ||
| 152 | + int64_t yOffset = blockIdx_ * blockOffset_ / SWI_FACTOR + batchIdx * dimH_; | ||
| 153 | + for (int64_t loopIdx = 0; loopIdx < loopTime_; ++loopIdx) { | ||
| 154 | + pairNum_ = loopIdx == (loopTime_ - 1) ? pairLastLoop_ : pairFrontLoop_; | ||
| 155 | + ProcessSingleLoop(xOffset, yOffset); | ||
| 156 | + xOffset += loopOffset_; | ||
| 157 | + yOffset += loopOffset_; | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | + } else { | ||
| 161 | + // short H: tile along batch | ||
| 162 | + int64_t xOffset = blockIdx_ * blockOffset_; | ||
| 163 | + int64_t yOffset = blockIdx_ * blockOffset_ / SWI_FACTOR; | ||
| 164 | + for (int64_t loopIdx = 0; loopIdx < loopTime_; ++loopIdx) { | ||
| 165 | + pairNum_ = loopIdx == (loopTime_ - 1) ? pairLastLoop_ : pairFrontLoop_; | ||
| 166 | + ProcessSingleLoop(xOffset, yOffset); | ||
| 167 | + xOffset += loopOffset_; | ||
| 168 | + yOffset += loopOffset_ / SWI_FACTOR; | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +template <typename T> | ||
| 175 | +__aicore__ inline void SituGluBase<T>::CalTilingParam() | ||
| 176 | +{ | ||
| 177 | + int64_t coreNum = tl_->coreNumAll; | ||
| 178 | + if (coreNum <= 0) { | ||
| 179 | + coreNum = 1; | ||
| 180 | + } | ||
| 181 | + // inter-core batch split | ||
| 182 | + int64_t batchFrontBlock = (dimBatchSize_ + coreNum - 1) / coreNum; | ||
| 183 | + if (batchFrontBlock <= 0) { | ||
| 184 | + batchFrontBlock = 1; | ||
| 185 | + } | ||
| 186 | + usedCoreNum_ = static_cast<uint32_t>((dimBatchSize_ + batchFrontBlock - 1) / batchFrontBlock); | ||
| 187 | + int64_t batchLastBlock = dimBatchSize_ - batchFrontBlock * (usedCoreNum_ - 1); | ||
| 188 | + batchPreBlock_ = blockIdx_ == (usedCoreNum_ - 1) ? batchLastBlock : batchFrontBlock; | ||
| 189 | + blockOffset_ = batchFrontBlock * dim2H_; | ||
| 190 | + if (isLongH_ == 0) { // dim2H small: intra-core batch split | ||
| 191 | + int64_t ubMaxBatch = ubMaxPair_ / dimH_; | ||
| 192 | + if (ubMaxBatch < 1) { | ||
| 193 | + ubMaxBatch = 1; | ||
| 194 | + } | ||
| 195 | + loopTime_ = (batchPreBlock_ + ubMaxBatch - 1) / ubMaxBatch; | ||
| 196 | + int64_t batchLastLoop = batchPreBlock_ - ubMaxBatch * (loopTime_ - 1); | ||
| 197 | + pairFrontLoop_ = ubMaxBatch * dimH_; | ||
| 198 | + pairLastLoop_ = batchLastLoop * dimH_; | ||
| 199 | + loopOffset_ = ubMaxBatch * dim2H_; | ||
| 200 | + } else { // dim2H large: intra-core dim2H split | ||
| 201 | + loopTime_ = (dimH_ + ubMaxPair_ - 1) / ubMaxPair_; | ||
| 202 | + pairLastLoop_ = dimH_ - ubMaxPair_ * (loopTime_ - 1); | ||
| 203 | + pairFrontLoop_ = ubMaxPair_; | ||
| 204 | + loopOffset_ = ubMaxPair_; | ||
| 205 | + } | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +template <typename T> | ||
| 209 | +__aicore__ inline void SituGluBase<T>::ProcessSingleLoop(int64_t xOffset, int64_t yOffset) | ||
| 210 | +{ | ||
| 211 | + CopyIn(xOffset); | ||
| 212 | + LocalTensor<T> xLocal = xQueue_.DeQue<T>(); | ||
| 213 | + LocalTensor<float> tmp1 = tmpBuf1_.Get<float>(); | ||
| 214 | + LocalTensor<float> tmp2 = tmpBuf2_.Get<float>(); | ||
| 215 | + LocalTensor<T> yLocal = yQueue_.AllocTensor<T>(); | ||
| 216 | + Compute(xLocal, tmp1, tmp2, yLocal); | ||
| 217 | + yQueue_.EnQue<T>(yLocal); | ||
| 218 | + CopyOut(yOffset); | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +template <typename T> | ||
| 222 | +__aicore__ inline void SituGluBase<T>::CopyIn(int64_t xOffset) | ||
| 223 | +{ | ||
| 224 | + LocalTensor<T> xLocal = xQueue_.AllocTensor<T>(); | ||
| 225 | + if (isLongH_ == 0) { | ||
| 226 | + CopyInShortH(xLocal, xOffset); | ||
| 227 | + } else { | ||
| 228 | + CopyInLongH(xLocal, xOffset); | ||
| 229 | + } | ||
| 230 | + xQueue_.EnQue(xLocal); | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +template <typename T> | ||
| 234 | +__aicore__ inline void SituGluBase<T>::CopyInShortH(LocalTensor<T>& xLocal, int64_t xOffset) | ||
| 235 | +{ | ||
| 236 | + DataCopyPadParams padParams{false, 0, 0, 0}; | ||
| 237 | + DataCopyParams dataCopyXParams; | ||
| 238 | + dataCopyXParams.blockCount = pairNum_ / dimH_; // batch rows in this tile | ||
| 239 | + dataCopyXParams.blockLen = dimH_ * sizeof(T); // half row | ||
| 240 | + dataCopyXParams.srcStride = dimH_ * sizeof(T); // skip up half between rows | ||
| 241 | + dataCopyXParams.dstStride = 0; | ||
| 242 | + DataCopyPad(xLocal, xGm_[xOffset], dataCopyXParams, padParams); | ||
| 243 | + DataCopyPad(xLocal[halfOff_], xGm_[xOffset + dimH_], dataCopyXParams, padParams); | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +template <typename T> | ||
| 247 | +__aicore__ inline void SituGluBase<T>::CopyInLongH(LocalTensor<T>& xLocal, int64_t xOffset) | ||
| 248 | +{ | ||
| 249 | + DataCopyPadParams padParams{false, 0, 0, 0}; | ||
| 250 | + DataCopyParams dataCopyXParams; | ||
| 251 | + dataCopyXParams.blockCount = 1; | ||
| 252 | + dataCopyXParams.blockLen = pairNum_ * sizeof(T); | ||
| 253 | + dataCopyXParams.srcStride = 0; | ||
| 254 | + dataCopyXParams.dstStride = 0; | ||
| 255 | + DataCopyPad(xLocal, xGm_[xOffset], dataCopyXParams, padParams); | ||
| 256 | + DataCopyPad(xLocal[halfOff_], xGm_[xOffset + dimH_], dataCopyXParams, padParams); | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +// Common core: situ_a = beta * tanh(gate/beta) * sigmoid(gate); y = situ_a * up' | ||
| 260 | +// gate, up, y are always LocalTensor<float> regardless of IO dtype T. | ||
| 261 | +template <typename T> | ||
| 262 | +__aicore__ inline void SituGluBase<T>::SituCore(LocalTensor<float> gate, LocalTensor<float> up, LocalTensor<float> tmp1, | ||
| 263 | + LocalTensor<float> tmp2, LocalTensor<float> y, int64_t n) | ||
| 264 | +{ | ||
| 265 | + // situ_a = beta * tanh(gate/beta) * sigmoid(gate) | ||
| 266 | + Muls(tmp1, gate, 1.0f / beta_, n); | ||
| 267 | + PipeBarrier<PIPE_V>(); | ||
| 268 | + Tanh(tmp1, tmp1, n); | ||
| 269 | + PipeBarrier<PIPE_V>(); | ||
| 270 | + Muls(tmp1, tmp1, beta_, n); | ||
| 271 | + PipeBarrier<PIPE_V>(); | ||
| 272 | + | ||
| 273 | + Sigmoid(tmp2, gate, n); | ||
| 274 | + PipeBarrier<PIPE_V>(); | ||
| 275 | + Mul(y, tmp1, tmp2, n); | ||
| 276 | + PipeBarrier<PIPE_V>(); | ||
| 277 | + | ||
| 278 | + if (linearBeta_ > 0.0f) { | ||
| 279 | + Muls(tmp1, up, 1.0f / linearBeta_, n); | ||
| 280 | + PipeBarrier<PIPE_V>(); | ||
| 281 | + Tanh(tmp1, tmp1, n); | ||
| 282 | + PipeBarrier<PIPE_V>(); | ||
| 283 | + Muls(tmp1, tmp1, linearBeta_, n); | ||
| 284 | + PipeBarrier<PIPE_V>(); | ||
| 285 | + Mul(y, y, tmp1, n); | ||
| 286 | + PipeBarrier<PIPE_V>(); | ||
| 287 | + } else { | ||
| 288 | + Mul(y, y, up, n); | ||
| 289 | + PipeBarrier<PIPE_V>(); | ||
| 290 | + } | ||
| 291 | +} | ||
| 292 | + | ||
| 293 | +template <typename T> | ||
| 294 | +__aicore__ inline void SituGluBase<T>::Compute(LocalTensor<T>& xLocal, LocalTensor<float>& tmp1, | ||
| 295 | + LocalTensor<float>& tmp2, LocalTensor<T>& yLocal) | ||
| 296 | +{ | ||
| 297 | + // front half of row -> xLocal[0:pairNum_]; back half -> xLocal[halfOff_:halfOff_+pairNum_] | ||
| 298 | + int64_t gateOff = (activateLeft_ == 1) ? 0 : halfOff_; | ||
| 299 | + int64_t upOff = (activateLeft_ == 1) ? halfOff_ : 0; | ||
| 300 | + | ||
| 301 | + if constexpr (kIsFp32) { | ||
| 302 | + // fp32 native path: gate/up come directly from xLocal, result goes to yLocal | ||
| 303 | + LocalTensor<float> gateLocal = xLocal[gateOff]; | ||
| 304 | + LocalTensor<float> upLocal = xLocal[upOff]; | ||
| 305 | + SituCore(gateLocal, upLocal, tmp1, tmp2, yLocal, pairNum_); | ||
| 306 | + xQueue_.FreeTensor(xLocal); | ||
| 307 | + } else { | ||
| 308 | + // mixed precision path (half / bf16): Cast T->float32, compute, Cast float32->T | ||
| 309 | + LocalTensor<float> gateF = gateFBuf_.Get<float>(); | ||
| 310 | + LocalTensor<float> upF = upFBuf_.Get<float>(); | ||
| 311 | + LocalTensor<float> yF = yFBbuf_.Get<float>(); | ||
| 312 | + | ||
| 313 | + // T -> float32 (lossless widening for both half and bf16) | ||
| 314 | + Cast(gateF, xLocal[gateOff], RoundMode::CAST_NONE, pairNum_); | ||
| 315 | + PipeBarrier<PIPE_V>(); | ||
| 316 | + Cast(upF, xLocal[upOff], RoundMode::CAST_NONE, pairNum_); | ||
| 317 | + PipeBarrier<PIPE_V>(); | ||
| 318 | + xQueue_.FreeTensor(xLocal); | ||
| 319 | + | ||
| 320 | + SituCore(gateF, upF, tmp1, tmp2, yF, pairNum_); | ||
| 321 | + | ||
| 322 | + // float32 -> T | ||
| 323 | + // bf16 requires CAST_RINT on all platforms; CAST_NONE produces garbage on non-A2 (e.g. Ascend950) | ||
| 324 | + if constexpr (SituIsBf16<T>::value) { | ||
| 325 | + Cast(yLocal, yF, RoundMode::CAST_RINT, pairNum_); | ||
| 326 | + } else { | ||
| 327 | + Cast(yLocal, yF, RoundMode::CAST_NONE, pairNum_); | ||
| 328 | + } | ||
| 329 | + PipeBarrier<PIPE_V>(); | ||
| 330 | + } | ||
| 331 | +} | ||
| 332 | + | ||
| 333 | +template <typename T> | ||
| 334 | +__aicore__ inline void SituGluBase<T>::CopyOut(int64_t yOffset) | ||
| 335 | +{ | ||
| 336 | + LocalTensor<T> yLocal = yQueue_.DeQue<T>(); | ||
| 337 | + DataCopyParams dataCopyParams; | ||
| 338 | + if (isLongH_ == 0) { // short H: strided output rows | ||
| 339 | + dataCopyParams.blockCount = pairNum_ / dimH_; | ||
| 340 | + dataCopyParams.blockLen = dimH_ * sizeof(T); | ||
| 341 | + dataCopyParams.srcStride = 0; | ||
| 342 | + dataCopyParams.dstStride = 0; | ||
| 343 | + } else { // long H: contiguous output tile | ||
| 344 | + dataCopyParams.blockCount = 1; | ||
| 345 | + dataCopyParams.blockLen = pairNum_ * sizeof(T); | ||
| 346 | + dataCopyParams.srcStride = 0; | ||
| 347 | + dataCopyParams.dstStride = 0; | ||
| 348 | + } | ||
| 349 | + DataCopyPad(yGm_[yOffset], yLocal, dataCopyParams); | ||
| 350 | + yQueue_.FreeTensor(yLocal); | ||
| 351 | +} | ||
| 352 | + | ||
| 353 | +} // namespace SituGluOps | ||
| 354 | +#endif // OPP_SITU_GLU_HPP | ||
| @@ -0,0 +1,87 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | +import torch | ||
| 13 | +import cann_ops_nn | ||
| 14 | + | ||
| 15 | +DTYPE_TOLERANCE = { | ||
| 16 | + torch.float16: (1e-3, 1e-3), | ||
| 17 | + torch.bfloat16: (1e-2, 1e-2), | ||
| 18 | + torch.float32: (1e-5, 1e-5), | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def compare_results(result_npu, result_cpu, dtype, name=""): | ||
| 23 | + rtol, atol = DTYPE_TOLERANCE.get(dtype, (1e-5, 1e-5)) | ||
| 24 | + result_on_cpu = result_npu.cpu() if result_npu.device.type != "cpu" else result_npu | ||
| 25 | + max_diff = (result_on_cpu - result_cpu).abs().max().item() | ||
| 26 | + print(f"{name} - max error: {max_diff:.6f}") | ||
| 27 | + assert torch.allclose( | ||
| 28 | + result_on_cpu.float(), result_cpu.float(), rtol=rtol, atol=atol | ||
| 29 | + ), f"Precision check failed: {name}" | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def situ_glu_cpu(x, dim=-1, beta=1.0, linear_beta=0.0, activate_left=True): | ||
| 33 | + d = x.shape[dim] // 2 | ||
| 34 | + left, right = x.split(d, dim=dim) | ||
| 35 | + if activate_left: | ||
| 36 | + gate, up = left, right | ||
| 37 | + else: | ||
| 38 | + gate, up = right, left | ||
| 39 | + | ||
| 40 | + gate = gate.to(torch.float32) | ||
| 41 | + up = up.to(torch.float32) | ||
| 42 | + situ_a = beta * torch.tanh(gate / beta) * torch.sigmoid(gate) | ||
| 43 | + if linear_beta is not None and linear_beta > 0: | ||
| 44 | + up = linear_beta * torch.tanh(up / linear_beta) | ||
| 45 | + return (situ_a * up).to(x.dtype) | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +NETWORK_SHAPES = [ | ||
| 49 | + (2, 32), | ||
| 50 | + (1, 4624, 6144), | ||
| 51 | + (15908, 3072), | ||
| 52 | +] | ||
| 53 | + | ||
| 54 | +DTYPES = [torch.float32, torch.float16] | ||
| 55 | + | ||
| 56 | +NET_DIM = -1 | ||
| 57 | +NET_BETA = 4.0 | ||
| 58 | +NET_LINEAR_BETA = 25.0 | ||
| 59 | +NET_ACTIVATE_LEFT = True | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def _make_x(shape, dtype): | ||
| 63 | + if dtype == torch.float32: | ||
| 64 | + return torch.randn(*shape, dtype=torch.float32).npu() | ||
| 65 | + return torch.randn(*shape, dtype=torch.float32).to(dtype).npu() | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +@pytest.mark.parametrize("shape", NETWORK_SHAPES) | ||
| 69 | +@pytest.mark.parametrize("dtype", DTYPES) | ||
| 70 | +def test_situ_glu_network(shape, dtype): | ||
| 71 | + x = _make_x(shape, dtype) | ||
| 72 | + y = cann_ops_nn.situ_glu( | ||
| 73 | + x, | ||
| 74 | + dim=NET_DIM, | ||
| 75 | + beta=NET_BETA, | ||
| 76 | + linear_beta=NET_LINEAR_BETA, | ||
| 77 | + activate_left=NET_ACTIVATE_LEFT, | ||
| 78 | + ) | ||
| 79 | + y_cpu = situ_glu_cpu( | ||
| 80 | + x.cpu(), | ||
| 81 | + dim=NET_DIM, | ||
| 82 | + beta=NET_BETA, | ||
| 83 | + linear_beta=NET_LINEAR_BETA, | ||
| 84 | + activate_left=NET_ACTIVATE_LEFT, | ||
| 85 | + ) | ||
| 86 | + assert y.dtype == x.dtype | ||
| 87 | + compare_results(y, y_cpu, dtype, name=f"situ_glu_network_{shape}_{dtype}") | ||
| @@ -0,0 +1,101 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ---------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ---------------------------------------------------------------------------- | ||
| 12 | +import ctypes | ||
| 13 | +import torch | ||
| 14 | +from atk.configs.dataset_config import InputDataset | ||
| 15 | +from atk.configs.results_config import TaskResult | ||
| 16 | +from atk.tasks.api_execute import register | ||
| 17 | +from atk.tasks.api_execute.base_api import BaseApi | ||
| 18 | +from atk.tasks.api_execute.aclnn_base_api import AclnnBaseApi | ||
| 19 | +from atk.tasks.backends.lib_interface.acl_wrapper import AclFormat | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def _situ_glu_forward(x, dim=-1, beta=1.0, linear_beta=0.0, activate_left=True): | ||
| 23 | + dtype = x.dtype | ||
| 24 | + if x.dtype in [torch.float16, torch.bfloat16]: | ||
| 25 | + x = x.to(torch.float32) | ||
| 26 | + | ||
| 27 | + dim_pos = dim if dim >= 0 else dim + x.dim() | ||
| 28 | + pre = 1 | ||
| 29 | + for i in range(dim_pos): | ||
| 30 | + pre *= x.shape[i] | ||
| 31 | + xf = x.reshape(pre, -1) | ||
| 32 | + h = xf.shape[1] // 2 | ||
| 33 | + | ||
| 34 | + if activate_left: | ||
| 35 | + gate = xf[:, :h] | ||
| 36 | + up = xf[:, h:] | ||
| 37 | + else: | ||
| 38 | + gate = xf[:, h:] | ||
| 39 | + up = xf[:, :h] | ||
| 40 | + | ||
| 41 | + situ_a = beta * torch.tanh(gate / beta) * torch.sigmoid(gate) | ||
| 42 | + if linear_beta > 0.0: | ||
| 43 | + up = linear_beta * torch.tanh(up / linear_beta) | ||
| 44 | + y = situ_a * up | ||
| 45 | + | ||
| 46 | + out_shape = list(x.shape) | ||
| 47 | + out_shape[dim_pos] = out_shape[dim_pos] // 2 | ||
| 48 | + y = y.reshape(out_shape) | ||
| 49 | + | ||
| 50 | + if dtype == torch.bfloat16: | ||
| 51 | + y = y.to(torch.bfloat16) | ||
| 52 | + elif dtype == torch.float16: | ||
| 53 | + y = y.to(torch.float16) | ||
| 54 | + return y | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +@register("function_situ_glu") | ||
| 58 | +class FunctionSituGlu(BaseApi): | ||
| 59 | + def __init__(self, task_result: TaskResult): | ||
| 60 | + super(FunctionSituGlu, self).__init__(task_result) | ||
| 61 | + self.run_modes = [] | ||
| 62 | + | ||
| 63 | + def __call__(self, input_data: InputDataset, with_output: bool = False): | ||
| 64 | + x = input_data.kwargs["x"] | ||
| 65 | + dim = int(input_data.kwargs.get("dim", -1)) | ||
| 66 | + beta = float(input_data.kwargs.get("beta", 1.0)) | ||
| 67 | + linear_beta = float(input_data.kwargs.get("linearBeta", 0.0)) | ||
| 68 | + activate_left = bool(input_data.kwargs.get("activateLeft", True)) | ||
| 69 | + | ||
| 70 | + return _situ_glu_forward(x, dim, beta, linear_beta, activate_left) | ||
| 71 | + | ||
| 72 | + def get_format(self, input_data: InputDataset, index=None, name=None): | ||
| 73 | + return AclFormat.ACL_FORMAT_ND | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +@register("aclnn_situ_glu") | ||
| 77 | +class AclnnSituGluApi(AclnnBaseApi): | ||
| 78 | + def __init__(self, task_result, backend): | ||
| 79 | + super(AclnnSituGluApi, self).__init__(task_result, backend) | ||
| 80 | + self.run_modes = [] | ||
| 81 | + | ||
| 82 | + def init_by_input_data(self, input_data: InputDataset): | ||
| 83 | + input_args, output_packages = super().init_by_input_data(input_data) | ||
| 84 | + kw = dict(input_data.kwargs) if input_data.kwargs else {} | ||
| 85 | + input_args[2] = ctypes.c_double(float(kw.get("beta", 1.0))) | ||
| 86 | + input_args[3] = ctypes.c_double(float(kw.get("linearBeta", 0.0))) | ||
| 87 | + return input_args, output_packages | ||
| 88 | + | ||
| 89 | + @classmethod | ||
| 90 | + def get_cpp_func_signature_type(cls): | ||
| 91 | + return ( | ||
| 92 | + "aclnnStatus aclnnSituGluGetWorkspaceSize(" | ||
| 93 | + "const aclTensor* x, " | ||
| 94 | + "int64_t dim, " | ||
| 95 | + "double beta, " | ||
| 96 | + "double linearBeta, " | ||
| 97 | + "bool activateLeft, " | ||
| 98 | + "const aclTensor* out, " | ||
| 99 | + "uint64_t* workspaceSize, " | ||
| 100 | + "aclOpExecutor** executor)" | ||
| 101 | + ) | ||
| @@ -0,0 +1,14 @@ | |||
| 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 | +from .situ_glu import situ_glu | ||
| 12 | +from .graph_convert_situ_glu import convert_situ_glu | ||
| 13 | + | ||
| 14 | +__all__ = ["situ_glu", "convert_situ_glu"] | ||
| @@ -0,0 +1,56 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include <torch/extension.h> | ||
| 12 | +#include "aclnn_common.h" | ||
| 13 | + | ||
| 14 | +namespace cann_ops_nn { | ||
| 15 | +namespace activation { | ||
| 16 | +namespace { | ||
| 17 | +constexpr int64_t kSplitFactor = 2; | ||
| 18 | + | ||
| 19 | +void CheckNpuTensor(const at::Tensor& tensor, const char* name) | ||
| 20 | +{ | ||
| 21 | + TORCH_CHECK(tensor.defined(), name, " must be defined"); | ||
| 22 | + TORCH_CHECK(torch_npu::utils::is_npu(tensor), name, " must be on NPU device"); | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +c10::SmallVector<int64_t, op_infer::SIZE> GetSituGluOutputShape(const at::Tensor& x, int64_t dim) | ||
| 26 | +{ | ||
| 27 | + TORCH_CHECK(x.dim() > 0, "x rank should be greater than 0"); | ||
| 28 | + int64_t actualDim = dim; | ||
| 29 | + if (actualDim < 0) { | ||
| 30 | + actualDim += x.dim(); | ||
| 31 | + } | ||
| 32 | + TORCH_CHECK(actualDim >= 0 && actualDim < x.dim(), "dim should be in [", -x.dim(), ", ", x.dim() - 1, "], but got ", | ||
| 33 | + dim); | ||
| 34 | + const int64_t dimSize = x.size(actualDim); | ||
| 35 | + TORCH_CHECK(dimSize % kSplitFactor == 0, "x size at dim ", actualDim, " should be even, but got ", dimSize); | ||
| 36 | + | ||
| 37 | + auto yShape = op_infer::array_to_small_vector(x.sizes()); | ||
| 38 | + yShape[actualDim] = dimSize / kSplitFactor; | ||
| 39 | + return yShape; | ||
| 40 | +} | ||
| 41 | +} // namespace | ||
| 42 | + | ||
| 43 | +at::Tensor situ_glu(const at::Tensor& x, int64_t dim, double beta, double linear_beta, bool activate_left) | ||
| 44 | +{ | ||
| 45 | + CheckNpuTensor(x, "x"); | ||
| 46 | + | ||
| 47 | + at::Tensor y = at::empty(GetSituGluOutputShape(x, dim), x.options()); | ||
| 48 | + | ||
| 49 | + ACLNN_CMD(aclnnSituGlu, x, dim, beta, linear_beta, activate_left, y); | ||
| 50 | + return y; | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +} // namespace activation | ||
| 54 | +} // namespace cann_ops_nn | ||
| 55 | + | ||
| 56 | +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("situ_glu", &cann_ops_nn::activation::situ_glu, "SituGlu on NPU"); } | ||
| @@ -0,0 +1,58 @@ | |||
| 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 | +# GE Converter for Graph Mode | ||
| 11 | + | ||
| 12 | +try: | ||
| 13 | + import torch | ||
| 14 | + from torchair.ge import attr | ||
| 15 | + from torchair.ge._ge_graph import Tensor, TensorSpec | ||
| 16 | + from torchair._ge_concrete_graph.compat_ir import ge_op, IrDef | ||
| 17 | + from torchair._ge_concrete_graph.fx2ge_converter import ( | ||
| 18 | + register_fx_node_ge_converter, | ||
| 19 | + ) | ||
| 20 | + | ||
| 21 | + _TORCHAIR_AVAILABLE = True | ||
| 22 | +except ImportError: | ||
| 23 | + _TORCHAIR_AVAILABLE = False | ||
| 24 | + | ||
| 25 | +if _TORCHAIR_AVAILABLE: | ||
| 26 | + | ||
| 27 | + @register_fx_node_ge_converter(torch.ops.cann_ops_nn.situ_glu.default) | ||
| 28 | + def convert_situ_glu( | ||
| 29 | + x: Tensor, | ||
| 30 | + *, | ||
| 31 | + dim: int = -1, | ||
| 32 | + beta: float = 1.0, | ||
| 33 | + linear_beta: float = 0.0, | ||
| 34 | + activate_left: bool = True, | ||
| 35 | + meta_outputs: TensorSpec = None, | ||
| 36 | + ): | ||
| 37 | + return ge_op( | ||
| 38 | + op_type="SituGlu", | ||
| 39 | + inputs={"x": x}, | ||
| 40 | + attrs={ | ||
| 41 | + "dim": attr.Int(dim), | ||
| 42 | + "beta": attr.Float(beta), | ||
| 43 | + "linear_beta": attr.Float(linear_beta), | ||
| 44 | + "activate_left": attr.Bool(activate_left), | ||
| 45 | + }, | ||
| 46 | + outputs=["y"], | ||
| 47 | + ir=IrDef("SituGlu") | ||
| 48 | + .input("x", "DT_FLOAT") | ||
| 49 | + .attr("dim", attr.Int(-1)) | ||
| 50 | + .attr("beta", attr.Float(1.0)) | ||
| 51 | + .attr("linear_beta", attr.Float(0.0)) | ||
| 52 | + .attr("activate_left", attr.Bool(True)) | ||
| 53 | + .output("y", "DT_FLOAT"), | ||
| 54 | + ) | ||
| 55 | +else: | ||
| 56 | + | ||
| 57 | + def convert_situ_glu(*args, **kwargs): | ||
| 58 | + raise RuntimeError("SituGlu graph converter: torchair is not available.") | ||
| @@ -0,0 +1,60 @@ | |||
| 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 | +from torch.library import impl | ||
| 12 | + | ||
| 13 | +from cann_ops_nn.op_builder import OpBuilder, get_as_library | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def _situ_glu_shape(x, dim=-1): | ||
| 17 | + if x.dim() < 1: | ||
| 18 | + raise RuntimeError("x rank should be greater than 0") | ||
| 19 | + actual_dim = dim if dim >= 0 else dim + x.dim() | ||
| 20 | + if actual_dim < 0 or actual_dim >= x.dim(): | ||
| 21 | + raise RuntimeError( | ||
| 22 | + f"dim should be in [{-x.dim()}, {x.dim() - 1}], but got {dim}" | ||
| 23 | + ) | ||
| 24 | + dim_size = x.size(actual_dim) | ||
| 25 | + if dim_size % 2 != 0: | ||
| 26 | + raise RuntimeError( | ||
| 27 | + f"x size at dim {actual_dim} should be even, but got {dim_size}" | ||
| 28 | + ) | ||
| 29 | + shape = list(x.shape) | ||
| 30 | + shape[actual_dim] = dim_size // 2 | ||
| 31 | + return shape | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +class SituGluOpBuilder(OpBuilder): | ||
| 35 | + def __init__(self): | ||
| 36 | + super().__init__("situ_glu") | ||
| 37 | + | ||
| 38 | + def sources(self): | ||
| 39 | + return [self.resolve_source("situ_glu.cpp")] | ||
| 40 | + | ||
| 41 | + def schema(self): | ||
| 42 | + return ( | ||
| 43 | + "situ_glu(Tensor x, *, int dim=-1, float beta=1.0, float linear_beta=0.0, " | ||
| 44 | + "bool activate_left=True) -> Tensor" | ||
| 45 | + ) | ||
| 46 | + | ||
| 47 | + def register_meta(self): | ||
| 48 | + @impl(get_as_library(), self.name, "Meta") | ||
| 49 | + def situ_glu_meta(x, *, dim=-1, beta=1.0, linear_beta=0.0, activate_left=True): | ||
| 50 | + return x.new_empty(_situ_glu_shape(x, dim)) | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +builder = SituGluOpBuilder() | ||
| 54 | +builder._ensure_initialized() | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +@impl(get_as_library(), builder.name, "PrivateUse1") | ||
| 58 | +def situ_glu(x, *, dim=-1, beta=1.0, linear_beta=0.0, activate_left=True): | ||
| 59 | + op_module = builder.load() | ||
| 60 | + return op_module.situ_glu(x, dim, beta, linear_beta, activate_left) | ||
| @@ -0,0 +1,20 @@ | |||
| 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: CURRENT_DIRS =${CURRENT_DIRS} ") | ||
| 12 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 13 | +if(NOT ENABLE_TEST AND NOT BENCHMARK) | ||
| 14 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 15 | +endif() | ||
| 16 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 17 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 18 | + add_subdirectory(${SUB_DIR}) | ||
| 19 | + endif() | ||
| 20 | +endforeach() | ||
| @@ -0,0 +1,131 @@ | |||
| 1 | +# SituGluGrad | ||
| 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 | +- 算子功能:SiTU门控线性单元(SiTU Gated Linear Unit)激活函数的反向梯度计算。根据上游梯度grad_y和前向输入x,计算输入x的梯度grad_x。 | ||
| 17 | + | ||
| 18 | +- 计算公式或计算流程: | ||
| 19 | + | ||
| 20 | + 对给定的输入张量x(维度为[..., cut],cut为偶数,令h = cut // 2)和上游梯度grad_y(维度为[..., h]): | ||
| 21 | + | ||
| 22 | + 1. 根据activate_left切分x为gate和up(各shape [..., h])。 | ||
| 23 | + | ||
| 24 | + 2. 计算前向中间量: | ||
| 25 | + | ||
| 26 | + $$ | ||
| 27 | + t = \tanh\left(\frac{gate}{\beta}\right), \quad s = \sigma(gate), \quad situ\_a = \beta \cdot t \cdot s | ||
| 28 | + $$ | ||
| 29 | + | ||
| 30 | + 当linear_beta > 0时:$up' = linear\_beta \cdot \tanh(up / linear\_beta)$,否则$up' = up$。 | ||
| 31 | + | ||
| 32 | + 3. 乘积法则: | ||
| 33 | + | ||
| 34 | + $$ | ||
| 35 | + grad\_situ\_a = grad\_y \cdot up', \quad grad\_up' = grad\_y \cdot situ\_a | ||
| 36 | + $$ | ||
| 37 | + | ||
| 38 | + 4. gate梯度: | ||
| 39 | + | ||
| 40 | + $$ | ||
| 41 | + grad\_gate = grad\_situ\_a \cdot s \cdot \left[ (1 - t^2) + \beta \cdot t \cdot (1 - s) \right] | ||
| 42 | + $$ | ||
| 43 | + | ||
| 44 | + 5. up梯度: | ||
| 45 | + | ||
| 46 | + - linear_beta > 0时:$grad\_up = grad\_up' \cdot (1 - \tanh^2(up / linear\_beta))$ | ||
| 47 | + - linear_beta ≤ 0时:$grad\_up = grad\_up'$ | ||
| 48 | + | ||
| 49 | + 6. 根据activate_left将grad_gate、grad_up拼接为grad_x(shape与x一致)。 | ||
| 50 | + | ||
| 51 | +## 参数说明 | ||
| 52 | + | ||
| 53 | +<table style="undefined;table-layout: fixed; width: 1576px"><colgroup> | ||
| 54 | + <col style="width: 170px"> | ||
| 55 | + <col style="width: 170px"> | ||
| 56 | + <col style="width: 200px"> | ||
| 57 | + <col style="width: 200px"> | ||
| 58 | + <col style="width: 170px"> | ||
| 59 | + </colgroup> | ||
| 60 | + <thead> | ||
| 61 | + <tr> | ||
| 62 | + <th>参数名</th> | ||
| 63 | + <th>输入/输出/属性</th> | ||
| 64 | + <th>描述</th> | ||
| 65 | + <th>数据类型</th> | ||
| 66 | + <th>数据格式</th> | ||
| 67 | + </tr></thead> | ||
| 68 | + <tbody> | ||
| 69 | + <tr> | ||
| 70 | + <td>grad_y</td> | ||
| 71 | + <td>输入</td> | ||
| 72 | + <td>反向传播上游梯度,dim维度大小为x的一半。</td> | ||
| 73 | + <td>FLOAT、FLOAT16、BFLOAT16</td> | ||
| 74 | + <td>ND</td> | ||
| 75 | + </tr> | ||
| 76 | + <tr> | ||
| 77 | + <td>x</td> | ||
| 78 | + <td>输入</td> | ||
| 79 | + <td>前向输入,dim维度会被均分为gate与up两部分。数据类型需与grad_y一致。</td> | ||
| 80 | + <td>FLOAT、FLOAT16、BFLOAT16</td> | ||
| 81 | + <td>ND</td> | ||
| 82 | + </tr> | ||
| 83 | + <tr> | ||
| 84 | + <td>dim</td> | ||
| 85 | + <td>属性</td> | ||
| 86 | + <td><ul><li>切分维度,需与前向SituGlu一致。</li><li>取值范围为[-x.dim(), x.dim()-1]。</li><li>默认值为-1。</li></ul></td> | ||
| 87 | + <td>INT64</td> | ||
| 88 | + <td>-</td> | ||
| 89 | + </tr> | ||
| 90 | + <tr> | ||
| 91 | + <td>beta</td> | ||
| 92 | + <td>属性</td> | ||
| 93 | + <td><ul><li>SiTU门控部分的缩放系数,需与前向SituGlu保持一致。</li><li>默认值为1.0。</li></ul></td> | ||
| 94 | + <td>FLOAT</td> | ||
| 95 | + <td>-</td> | ||
| 96 | + </tr> | ||
| 97 | + <tr> | ||
| 98 | + <td>linear_beta</td> | ||
| 99 | + <td>属性</td> | ||
| 100 | + <td><ul><li>up路径线性tanh的缩放系数,需与前向SituGlu保持一致。</li><li>默认值为0.0。</li></ul></td> | ||
| 101 | + <td>FLOAT</td> | ||
| 102 | + <td>-</td> | ||
| 103 | + </tr> | ||
| 104 | + <tr> | ||
| 105 | + <td>activate_left</td> | ||
| 106 | + <td>属性</td> | ||
| 107 | + <td><ul><li>切分x时gate是否为前半部分,需与前向SituGlu保持一致。</li><li>默认值为true。</li></ul></td> | ||
| 108 | + <td>BOOL</td> | ||
| 109 | + <td>-</td> | ||
| 110 | + </tr> | ||
| 111 | + <tr> | ||
| 112 | + <td>grad_x</td> | ||
| 113 | + <td>输出</td> | ||
| 114 | + <td>输入x的梯度,shape与x完全一致。</td> | ||
| 115 | + <td>FLOAT、FLOAT16、BFLOAT16</td> | ||
| 116 | + <td>ND</td> | ||
| 117 | + </tr> | ||
| 118 | + </tbody></table> | ||
| 119 | + | ||
| 120 | +## 约束说明 | ||
| 121 | + | ||
| 122 | +- 支持非连续Tensor。 | ||
| 123 | +- beta、linear_beta、activate_left、dim需与前向SituGlu调用时的取值一致,否则梯度结果不正确。 | ||
| 124 | + | ||
| 125 | +## 调用说明 | ||
| 126 | + | ||
| 127 | +| 调用方式 | 样例代码 | 说明 | | ||
| 128 | +| ---------------- | --------------------------- | --------------------------------------------------- | | ||
| 129 | +| aclnn API | - | 通过[aclnnSituGluGrad](./docs/aclnnSituGluGrad.md)接口调用SituGluGrad算子。 | | ||
| 130 | +| GE图模式 | - | 通过[算子IR](./op_graph/situ_glu_grad_proto.h)构图方式调用SituGluGrad算子。 | | ||
| 131 | +| PyTorch API | - | 通过[situ_glu_grad](./docs/torchapi_situ_glu_grad.md)接口调用SituGluGrad算子。 | | ||
最新代码不是不用写Cmake了吗?