Merged
add_generic_sparse_attention_grad #11003
add_generic_sparse_attention_grad #11003
Merged
陈俊卓Add on Aug 31
Total: 41 files changed+7363-0
@@ -0,0 +1,19 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+if(NOT ENABLE_TEST AND NOT BENCHMARK)
13+ list(REMOVE_ITEM CURRENT_DIRS tests)
14+endif()
15+foreach(SUB_DIR ${CURRENT_DIRS})
16+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
17+ add_subdirectory(${SUB_DIR})
18+ endif()
19+endforeach()
@@ -0,0 +1,252 @@
1+# GenericBlockSparseAttentionGrad
chenjiao

交付件不全

likedislike
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++ 算子功能:GenericBlockSparseAttentionGrad是通用块稀疏注意力的反向计算算子。依据`rsvdBlockIdx`/`rsvdBlockCount`(稀疏块索引表)定义的索引,仅在被选中的KV块上计算和传播梯度,支持动态、可变长的分块稀疏模式。调用前须先通过`aclnnGenericBlockSparseAttentionGradMetadata`生成分核`metadata`。
17++ 计算公式:
18+ 
19+$$
20+P = SimpleSoftmax(Mask(Q @ selectedK^{T} \cdot scale), lse)
21+$$
22+ 
23+$$
24+dP = dO @ selectedV^{T}
25+$$
26+ 
27+$$
28+dS = P \odot (dP - SoftmaxGrad(dO, O))
29+$$
30+ 
31+$$
32+dQ = dS @ selectedK \cdot scale
33+$$
34+ 
35+$$
36+dK = dS^{T} @ Q \cdot scale
37+$$
38+ 
39+$$
40+dV = P^{T} @ dO
41+$$
42+ 
43+## 参数说明
44+ 
45+<table class="tg"><thead>
46+ <tr>
47+ <th class="tg-0pky">参数名</th>
48+ <th class="tg-0pky">输入/输出/属性</th>
49+ <th class="tg-0pky">描述</th>
50+ <th class="tg-0pky">数据类型</th>
51+ <th class="tg-0pky">数据格式</th>
52+ </tr></thead>
53+<tbody>
54+ <tr>
55+ <td class="tg-0pky">query</td>
56+ <td class="tg-0pky">输入</td>
57+ <td class="tg-0pky">attention结构的输入Q。</td>
58+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
59+ <td class="tg-0pky">ND</td>
60+ </tr>
61+ <tr>
62+ <td class="tg-0pky">key</td>
63+ <td class="tg-0pky">输入</td>
64+ <td class="tg-0pky">attention结构的输入K。</td>
65+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
66+ <td class="tg-0pky">ND</td>
67+ </tr>
68+ <tr>
69+ <td class="tg-0pky">value</td>
70+ <td class="tg-0pky">输入</td>
71+ <td class="tg-0pky">attention结构的输入V,shape与key相同。</td>
72+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
73+ <td class="tg-0pky">ND</td>
74+ </tr>
75+ <tr>
76+ <td class="tg-0pky">dout</td>
77+ <td class="tg-0pky">输入</td>
78+ <td class="tg-0pky">注意力输出矩阵的梯度。</td>
79+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
80+ <td class="tg-0pky">ND</td>
81+ </tr>
82+ <tr>
83+ <td class="tg-0pky">out</td>
84+ <td class="tg-0pky">输入</td>
85+ <td class="tg-0pky">注意力输出矩阵。</td>
86+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
87+ <td class="tg-0pky">ND</td>
88+ </tr>
89+ <tr>
90+ <td class="tg-0pky">lse</td>
91+ <td class="tg-0pky">输入</td>
92+ <td class="tg-0pky">注意力正向计算的输出lse。</td>
93+ <td class="tg-0pky">FLOAT32</td>
94+ <td class="tg-0pky">ND</td>
95+ </tr>
96+ <tr>
97+ <td class="tg-0pky">rsvdBlockIdx</td>
98+ <td class="tg-0pky">输入</td>
99+ <td class="tg-0pky">稀疏块索引数组,指定每个KV块选择的Q块/token索引。</td>
100+ <td class="tg-0pky">INT32</td>
101+ <td class="tg-0pky">ND</td>
102+ </tr>
103+ <tr>
104+ <td class="tg-0pky">rsvdBlockCount</td>
105+ <td class="tg-0pky">输入</td>
106+ <td class="tg-0pky">指定每个KV块实际选择的Q数量。</td>
107+ <td class="tg-0pky">INT32</td>
108+ <td class="tg-0pky">ND</td>
109+ </tr>
110+ <tr>
111+ <td class="tg-0pky">metadata</td>
112+ <td class="tg-0pky">输入</td>
113+ <td class="tg-0pky">由GenericBlockSparseAttentionGradMetadata生成的分核信息。</td>
114+ <td class="tg-0pky">INT64</td>
115+ <td class="tg-0pky">ND</td>
116+ </tr>
117+ <tr>
118+ <td class="tg-0pky">attenMaskOptional</td>
119+ <td class="tg-0pky">可选输入</td>
120+ <td class="tg-0pky">atten_mask,当前暂不支持,应传nullptr。</td>
121+ <td class="tg-0pky">BOOL</td>
122+ <td class="tg-0pky">ND</td>
123+ </tr>
124+ <tr>
125+ <td class="tg-0pky">cuSeqLengthsOptional</td>
126+ <td class="tg-0pky">可选输入</td>
127+ <td class="tg-0pky">TND layout下query的累积序列长度。</td>
128+ <td class="tg-0pky">INT64</td>
129+ <td class="tg-0pky">ND</td>
130+ </tr>
131+ <tr>
132+ <td class="tg-0pky">cuSeqLengthsKvOptional</td>
133+ <td class="tg-0pky">可选输入</td>
134+ <td class="tg-0pky">TND layout下key/value的累积序列长度。</td>
135+ <td class="tg-0pky">INT64</td>
136+ <td class="tg-0pky">ND</td>
137+ </tr>
138+ <tr>
139+ <td class="tg-0pky">sequsedQOptional</td>
140+ <td class="tg-0pky">可选输入</td>
141+ <td class="tg-0pky">各batch中query的实际序列长度。</td>
142+ <td class="tg-0pky">INT32</td>
143+ <td class="tg-0pky">ND</td>
144+ </tr>
145+ <tr>
146+ <td class="tg-0pky">sequsedKvOptional</td>
147+ <td class="tg-0pky">可选输入</td>
148+ <td class="tg-0pky">各batch中kv的实际序列长度。</td>
149+ <td class="tg-0pky">INT32</td>
150+ <td class="tg-0pky">ND</td>
151+ </tr>
152+ <tr>
153+ <td class="tg-0pky">blockShape</td>
154+ <td class="tg-0pky">属性</td>
155+ <td class="tg-0pky">稀疏块形状[blockShapeX, blockShapeY],当前支持[1, 128]。</td>
156+ <td class="tg-0pky">INT64</td>
157+ <td class="tg-0pky">-</td>
158+ </tr>
159+ <tr>
160+ <td class="tg-0pky">isPackedGqa</td>
161+ <td class="tg-0pky">属性</td>
162+ <td class="tg-0pky">同一group内qHead是否共享稀疏pattern,当前仅支持1。</td>
163+ <td class="tg-0pky">INT64</td>
164+ <td class="tg-0pky">-</td>
165+ </tr>
166+ <tr>
167+ <td class="tg-0pky">qInputLayout</td>
168+ <td class="tg-0pky">属性</td>
169+ <td class="tg-0pky">query侧layout格式,支持TND/BNSD/BSND。</td>
170+ <td class="tg-0pky">STRING</td>
171+ <td class="tg-0pky">-</td>
172+ </tr>
173+ <tr>
174+ <td class="tg-0pky">kvInputLayout</td>
175+ <td class="tg-0pky">属性</td>
176+ <td class="tg-0pky">key/value侧layout格式,须与qInputLayout一致。</td>
177+ <td class="tg-0pky">STRING</td>
178+ <td class="tg-0pky">-</td>
179+ </tr>
180+ <tr>
181+ <td class="tg-0pky">scaleValue</td>
182+ <td class="tg-0pky">属性</td>
183+ <td class="tg-0pky">缩放系数,建议值为1/sqrt(D)。</td>
184+ <td class="tg-0pky">FLOAT</td>
185+ <td class="tg-0pky">-</td>
186+ </tr>
187+ <tr>
188+ <td class="tg-0pky">maskType</td>
189+ <td class="tg-0pky">属性</td>
190+ <td class="tg-0pky">mask模式,当前仅支持1(RIGHT_DOWN_CAUSAL)。</td>
191+ <td class="tg-0pky">INT64</td>
192+ <td class="tg-0pky">-</td>
193+ </tr>
194+ <tr>
195+ <td class="tg-0pky">softmaxPrecision</td>
196+ <td class="tg-0pky">属性</td>
197+ <td class="tg-0pky">Softmax精度级别,取值0或1,当前实现传0。</td>
198+ <td class="tg-0pky">INT64</td>
199+ <td class="tg-0pky">-</td>
200+ </tr>
201+ <tr>
202+ <td class="tg-0pky">windowSizeLeft</td>
203+ <td class="tg-0pky">属性</td>
204+ <td class="tg-0pky">滑窗向前包含token数,不使能时须为-1。</td>
205+ <td class="tg-0pky">INT64</td>
206+ <td class="tg-0pky">-</td>
207+ </tr>
208+ <tr>
209+ <td class="tg-0pky">windowSizeRight</td>
210+ <td class="tg-0pky">属性</td>
211+ <td class="tg-0pky">滑窗向后包含token数,不使能时须为-1。</td>
212+ <td class="tg-0pky">INT64</td>
213+ <td class="tg-0pky">-</td>
214+ </tr>
215+ <tr>
216+ <td class="tg-0pky">dQuery</td>
217+ <td class="tg-0pky">输出</td>
218+ <td class="tg-0pky">query的梯度。</td>
219+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
220+ <td class="tg-0pky">ND</td>
221+ </tr>
222+ <tr>
223+ <td class="tg-0pky">dKey</td>
224+ <td class="tg-0pky">输出</td>
225+ <td class="tg-0pky">key的梯度。</td>
226+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
227+ <td class="tg-0pky">ND</td>
228+ </tr>
229+ <tr>
230+ <td class="tg-0pky">dValue</td>
231+ <td class="tg-0pky">输出</td>
232+ <td class="tg-0pky">value的梯度。</td>
233+ <td class="tg-0pky">FLOAT16、BFLOAT16</td>
234+ <td class="tg-0pky">ND</td>
235+ </tr>
236+</tbody></table>
237+ 
238+## 约束说明
239+ 
240+* <term>Ascend 950PR/Ascend 950DT</term>:支持FLOAT16、BFLOAT16的query/key/value/dout/out/dQuery/dKey/dValue,且数据类型保持一致;lse为FLOAT32。
241+* 须先调用GenericBlockSparseAttentionGradMetadata生成metadata,再调用本算子。
242+* qInputLayout与kvInputLayout须相同,取值TND/BNSD/BSND;TND布局下须传入对应cuSeqLengths。
243+* HeadDim固定为128;N1/N2取值范围[1, 128],且N1 % N2 == 0。
244+* blockShape当前仅支持[1, 128];isPackedGqa当前仅支持1;maskType当前仅支持1。
245+* windowSizeLeft/windowSizeRight不使能时必须为-1;attenMaskOptional当前应传nullptr。
246+* 默认为非确定性实现,暂不支持确定性实现。
247+ 
248+## 调用说明
249+ 
250+| 调用方式 | 样例代码 | 说明 |
251+| ----------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
252+| aclnn接口 | [test_aclnn_generic_block_sparse_attention_grad](./examples/test_aclnn_generic_block_sparse_attention_grad.cpp) | 通过[aclnnGenericBlockSparseAttentionGrad](./docs/aclnnGenericBlockSparseAttentionGrad.md)接口方式调用GenericBlockSparseAttentionGrad算子。 |
@@ -0,0 +1,306 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file test_aclnn_generic_block_sparse_attention_grad.cpp
13+ * \brief GenericBlockSparseAttentionGrad + Metadata 调用示例 (BNSD Layout)
14+ *
15+ * 流程:先调用 aclnnGenericBlockSparseAttentionGradMetadata 生成分核 metadata,
16+ * 再调用 aclnnGenericBlockSparseAttentionGrad 计算 dQ/dK/dV。
17+ */
18+ 
19+#include <cmath>
20+#include <cstdint>
21+#include <cstring>
22+#include <iostream>
23+#include <vector>
24+ 
25+#include "acl/acl.h"
26+#include "aclnnop/aclnn_generic_block_sparse_attention_grad.h"
27+#include "aclnnop/aclnn_generic_block_sparse_attention_grad_metadata.h"
28+ 
29+#define CHECK_RET(cond, return_expr) \
30+ do { \
31+ if (!(cond)) { \
32+ return_expr; \
33+ } \
34+ } while (0)
35+ 
36+#define LOG_PRINT(message, ...) \
37+ do { \
38+ printf(message, ##__VA_ARGS__); \
39+ } while (0)
40+ 
41+namespace {
42+ 
43+int64_t GetShapeSize(const std::vector<int64_t> &shape)
44+{
45+ int64_t shapeSize = 1;
46+ for (auto i : shape) {
47+ shapeSize *= i;
48+ }
49+ return shapeSize;
50+}
51+ 
52+void PrintOutResult(const std::vector<int64_t> &shape, void **deviceAddr)
53+{
54+ auto size = GetShapeSize(shape);
55+ std::vector<uint16_t> resultData(static_cast<size_t>(size), 0);
56+ auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
57+ static_cast<size_t>(size) * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
58+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
59+ for (int64_t i = 0; i < size && i < 8; ++i) {
60+ LOG_PRINT("result[%ld] raw_fp16_bits=0x%04x\n", i, static_cast<unsigned>(resultData[i]));
61+ }
62+}
63+ 
64+int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream)
65+{
66+ auto ret = aclInit(nullptr);
67+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
68+ ret = aclrtSetDevice(deviceId);
69+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
70+ ret = aclrtCreateContext(context, deviceId);
71+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
72+ ret = aclrtSetCurrentContext(*context);
73+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret); return ret);
74+ ret = aclrtCreateStream(stream);
75+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
76+ return 0;
77+}
78+ 
79+template <typename T>
80+int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
81+ aclDataType dataType, aclTensor **tensor)
82+{
83+ auto size = GetShapeSize(shape) * static_cast<int64_t>(sizeof(T));
84+ auto ret = aclrtMalloc(deviceAddr, static_cast<size_t>(size), ACL_MEM_MALLOC_HUGE_FIRST);
85+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
86+ ret = aclrtMemcpy(*deviceAddr, static_cast<size_t>(size), hostData.data(), static_cast<size_t>(size),
87+ ACL_MEMCPY_HOST_TO_DEVICE);
88+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
89+ 
90+ std::vector<int64_t> strides(shape.size(), 1);
91+ for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; --i) {
92+ strides[i] = shape[i + 1] * strides[i + 1];
93+ }
94+ 
95+ *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
96+ shape.data(), shape.size(), *deviceAddr);
97+ CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed\n"); return -1);
98+ return 0;
99+}
100+ 
101+} // namespace
102+ 
103+int main()
104+{
105+ // 1. device/context/stream 初始化
106+ int32_t deviceId = 0;
107+ aclrtContext context = nullptr;
108+ aclrtStream stream = nullptr;
109+ auto ret = Init(deviceId, &context, &stream);
110+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
111+ 
112+ // 2. BNSD smoke 参数(对齐 GSAG 约束:D=128, blockShape=[1,128])
113+ const int64_t B = 1;
114+ const int64_t N1 = 1;
115+ const int64_t N2 = 1;
116+ const int64_t S1 = 128;
117+ const int64_t S2 = 128;
118+ const int64_t D = 128;
119+ const int64_t blockX = 1;
120+ const int64_t blockY = 128;
121+ const int64_t J = (S2 + blockY - 1) / blockY;
122+ const int64_t maskType = 1;
123+ const int64_t isPackedGqa = 1;
124+ const int64_t softmaxPrecision = 0;
125+ const int64_t windowLeft = -1;
126+ const int64_t windowRight = -1;
127+ const double scaleValue = 1.0 / std::sqrt(static_cast<double>(D));
128+ // metadata elems = TASK_LIST_OFFSET(80) + B * N1 * J * TASK_ENTRY_SIZE(4)
129+ const int64_t metaSize = 80 + B * N1 * J * 4;
130+ 
131+ std::vector<int64_t> qShape = {B, N1, S1, D};
132+ std::vector<int64_t> kvShape = {B, N2, S2, D};
133+ std::vector<int64_t> lseShape = {B, N1, S1};
134+ std::vector<int64_t> idxShape = {B, N2, J, S1};
135+ std::vector<int64_t> cntShape = {B, N2, J};
136+ std::vector<int64_t> metaShape = {metaSize};
137+ 
138+ // 3. Host 数据:小常数输入 + 单 KV 块全选 Q
139+ std::vector<uint16_t> qHost(static_cast<size_t>(GetShapeSize(qShape)), 0x2E66); // ~0.1
140+ std::vector<uint16_t> kHost(static_cast<size_t>(GetShapeSize(kvShape)), 0x2E66);
141+ std::vector<uint16_t> vHost(static_cast<size_t>(GetShapeSize(kvShape)), 0x2E66);
142+ std::vector<uint16_t> doutHost(static_cast<size_t>(GetShapeSize(qShape)), 0x211E); // ~0.01
143+ std::vector<uint16_t> outHost(static_cast<size_t>(GetShapeSize(qShape)), 0x2E66);
144+ std::vector<float> lseHost(static_cast<size_t>(GetShapeSize(lseShape)), 5.0f);
145+ std::vector<int32_t> idxHost(static_cast<size_t>(GetShapeSize(idxShape)), -1);
146+ std::vector<int32_t> cntHost(static_cast<size_t>(GetShapeSize(cntShape)), 0);
147+ std::vector<int64_t> metaHost(static_cast<size_t>(metaSize), 0);
148+ std::vector<uint16_t> dqHost(static_cast<size_t>(GetShapeSize(qShape)), 0);
149+ std::vector<uint16_t> dkHost(static_cast<size_t>(GetShapeSize(kvShape)), 0);
150+ std::vector<uint16_t> dvHost(static_cast<size_t>(GetShapeSize(kvShape)), 0);
151+ 
152+ for (int64_t q = 0; q < S1; ++q) {
153+ idxHost[static_cast<size_t>(q)] = static_cast<int32_t>(q);
154+ }
155+ cntHost[0] = static_cast<int32_t>(S1);
156+ 
157+ void *qAddr = nullptr;
158+ void *kAddr = nullptr;
159+ void *vAddr = nullptr;
160+ void *doutAddr = nullptr;
161+ void *outAddr = nullptr;
162+ void *lseAddr = nullptr;
163+ void *idxAddr = nullptr;
164+ void *cntAddr = nullptr;
165+ void *metaAddr = nullptr;
166+ void *dqAddr = nullptr;
167+ void *dkAddr = nullptr;
168+ void *dvAddr = nullptr;
169+ 
170+ aclTensor *q = nullptr;
171+ aclTensor *k = nullptr;
172+ aclTensor *v = nullptr;
173+ aclTensor *dout = nullptr;
174+ aclTensor *out = nullptr;
175+ aclTensor *lse = nullptr;
176+ aclTensor *idx = nullptr;
177+ aclTensor *cnt = nullptr;
178+ aclTensor *metadata = nullptr;
179+ aclTensor *dq = nullptr;
180+ aclTensor *dk = nullptr;
181+ aclTensor *dv = nullptr;
182+ 
183+ ret = CreateAclTensor(qHost, qShape, &qAddr, aclDataType::ACL_FLOAT16, &q);
184+ CHECK_RET(ret == ACL_SUCCESS, return ret);
185+ ret = CreateAclTensor(kHost, kvShape, &kAddr, aclDataType::ACL_FLOAT16, &k);
186+ CHECK_RET(ret == ACL_SUCCESS, return ret);
187+ ret = CreateAclTensor(vHost, kvShape, &vAddr, aclDataType::ACL_FLOAT16, &v);
188+ CHECK_RET(ret == ACL_SUCCESS, return ret);
189+ ret = CreateAclTensor(doutHost, qShape, &doutAddr, aclDataType::ACL_FLOAT16, &dout);
190+ CHECK_RET(ret == ACL_SUCCESS, return ret);
191+ ret = CreateAclTensor(outHost, qShape, &outAddr, aclDataType::ACL_FLOAT16, &out);
192+ CHECK_RET(ret == ACL_SUCCESS, return ret);
193+ ret = CreateAclTensor(lseHost, lseShape, &lseAddr, aclDataType::ACL_FLOAT, &lse);
194+ CHECK_RET(ret == ACL_SUCCESS, return ret);
195+ ret = CreateAclTensor(idxHost, idxShape, &idxAddr, aclDataType::ACL_INT32, &idx);
196+ CHECK_RET(ret == ACL_SUCCESS, return ret);
197+ ret = CreateAclTensor(cntHost, cntShape, &cntAddr, aclDataType::ACL_INT32, &cnt);
198+ CHECK_RET(ret == ACL_SUCCESS, return ret);
199+ ret = CreateAclTensor(metaHost, metaShape, &metaAddr, aclDataType::ACL_INT64, &metadata);
200+ CHECK_RET(ret == ACL_SUCCESS, return ret);
201+ ret = CreateAclTensor(dqHost, qShape, &dqAddr, aclDataType::ACL_FLOAT16, &dq);
202+ CHECK_RET(ret == ACL_SUCCESS, return ret);
203+ ret = CreateAclTensor(dkHost, kvShape, &dkAddr, aclDataType::ACL_FLOAT16, &dk);
204+ CHECK_RET(ret == ACL_SUCCESS, return ret);
205+ ret = CreateAclTensor(dvHost, kvShape, &dvAddr, aclDataType::ACL_FLOAT16, &dv);
206+ CHECK_RET(ret == ACL_SUCCESS, return ret);
207+ 
208+ const int64_t blockShapeData[] = {blockX, blockY};
209+ aclIntArray *blockShape = aclCreateIntArray(blockShapeData, 2);
210+ CHECK_RET(blockShape != nullptr, LOG_PRINT("aclCreateIntArray failed\n"); return -1);
211+ 
212+ char qLayout[] = "BNSD";
213+ char kvLayout[] = "BNSD";
214+ 
215+ // 4. 先跑 Metadata
216+ uint64_t metaWsSize = 0;
217+ aclOpExecutor *metaExecutor = nullptr;
218+ LOG_PRINT("Calling aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize...\n");
219+ ret = aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize(
220+ idx, cnt, nullptr, nullptr, nullptr, nullptr, S1, S2, N1, N2, D, blockShape, isPackedGqa, qLayout, kvLayout,
221+ maskType, softmaxPrecision, windowLeft, windowRight, metadata, &metaWsSize, &metaExecutor);
222+ CHECK_RET(ret == ACL_SUCCESS,
223+ LOG_PRINT("aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
224+ return ret);
225+ 
226+ void *metaWs = nullptr;
227+ if (metaWsSize > 0) {
228+ ret = aclrtMalloc(&metaWs, metaWsSize, ACL_MEM_MALLOC_HUGE_FIRST);
229+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
230+ }
231+ ret = aclnnGenericBlockSparseAttentionGradMetadata(metaWs, metaWsSize, metaExecutor, stream);
232+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGenericBlockSparseAttentionGradMetadata failed. ERROR: %d\n", ret);
233+ return ret);
234+ 
235+ // 5. 再跑 Grad
236+ uint64_t workspaceSize = 0;
237+ aclOpExecutor *executor = nullptr;
238+ LOG_PRINT("Calling aclnnGenericBlockSparseAttentionGradGetWorkspaceSize...\n");
239+ ret = aclnnGenericBlockSparseAttentionGradGetWorkspaceSize(
240+ q, k, v, dout, out, lse, idx, cnt, metadata, nullptr /*attenMask*/, nullptr /*cuQ*/, nullptr /*cuKv*/,
241+ nullptr /*sequsedQ*/, nullptr /*sequsedKv*/, blockShape, isPackedGqa, qLayout, kvLayout, scaleValue, maskType,
242+ softmaxPrecision, windowLeft, windowRight, dq, dk, dv, &workspaceSize, &executor);
243+ CHECK_RET(ret == ACL_SUCCESS,
244+ LOG_PRINT("aclnnGenericBlockSparseAttentionGradGetWorkspaceSize failed. ERROR: %d\n", ret);
245+ return ret);
246+ CHECK_RET(executor != nullptr, LOG_PRINT("executor is null\n"); return -1);
247+ LOG_PRINT("Workspace size required: %lu bytes\n", static_cast<unsigned long>(workspaceSize));
248+ 
249+ void *workspace = nullptr;
250+ if (workspaceSize > 0) {
251+ ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
252+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
253+ }
254+ 
255+ LOG_PRINT("Calling aclnnGenericBlockSparseAttentionGrad...\n");
256+ ret = aclnnGenericBlockSparseAttentionGrad(workspace, workspaceSize, executor, stream);
257+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGenericBlockSparseAttentionGrad failed. ERROR: %d\n", ret);
258+ return ret);
259+ 
260+ ret = aclrtSynchronizeStream(stream);
261+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
262+ 
263+ LOG_PRINT("dQuery sample:\n");
264+ PrintOutResult(qShape, &dqAddr);
265+ 
266+ // 6. 资源释放
267+ aclDestroyIntArray(blockShape);
268+ aclDestroyTensor(q);
269+ aclDestroyTensor(k);
270+ aclDestroyTensor(v);
271+ aclDestroyTensor(dout);
272+ aclDestroyTensor(out);
273+ aclDestroyTensor(lse);
274+ aclDestroyTensor(idx);
275+ aclDestroyTensor(cnt);
276+ aclDestroyTensor(metadata);
277+ aclDestroyTensor(dq);
278+ aclDestroyTensor(dk);
279+ aclDestroyTensor(dv);
280+ 
281+ aclrtFree(qAddr);
282+ aclrtFree(kAddr);
283+ aclrtFree(vAddr);
284+ aclrtFree(doutAddr);
285+ aclrtFree(outAddr);
286+ aclrtFree(lseAddr);
287+ aclrtFree(idxAddr);
288+ aclrtFree(cntAddr);
289+ aclrtFree(metaAddr);
290+ aclrtFree(dqAddr);
291+ aclrtFree(dkAddr);
292+ aclrtFree(dvAddr);
293+ if (metaWsSize > 0) {
294+ aclrtFree(metaWs);
295+ }
296+ if (workspaceSize > 0) {
297+ aclrtFree(workspace);
298+ }
299+ aclrtDestroyStream(stream);
300+ aclrtDestroyContext(context);
301+ aclrtResetDevice(deviceId);
302+ aclFinalize();
303+ 
304+ LOG_PRINT("GenericBlockSparseAttentionGrad test completed successfully.\n");
305+ return 0;
306+}
@@ -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+add_op_to_compiled_list()
11+ 
12+set(generic_block_sparse_attention_grad_depends attention/generic_block_sparse_attention_grad_metadata CACHE INTERNAL
13+ "Dependencies for generic_block_sparse_attention_grad")
14+ 
15+if (BUILD_OPEN_PROJECT)
16+ target_sources(op_host_aclnnExc PRIVATE
17+ generic_block_sparse_attention_grad_def.cpp
18+ )
19+endif()
20+ 
21+set(CONDITION_UNIT ${ASCEND_COMPUTE_UNIT})
22+if("${CONDITION_UNIT}" STREQUAL "ascend950")
23+ add_ops_compile_options(
24+ OP_NAME GenericBlockSparseAttentionGrad
25+ COMPUTE_UNIT Ascend950PR_9599
26+ OPTIONS -DENABLE_CV_COMM_VIA_SSBUF=true
27+ )
28+endif()
29+ 
30+if (BUILD_OPS_RTY_KERNEL)
31+ add_ops_compile_options(
32+ OP_NAME GenericBlockSparseAttentionGrad
33+ OPTIONS --cce-auto-sync=off
34+ -Wno-deprecated-declarations
35+ -Werror
36+ -fpermissive
37+ )
38+else()
39+ add_modules_sources(OPTYPE generic_block_sparse_attention_grad ACLNNTYPE aclnn_exclude)
40+endif()
41+ 
42+if(NOT BUILD_OPS_RTY_KERNEL)
43+ add_tiling_modules()
44+ target_sources(${OPHOST_NAME}_tiling_obj PRIVATE
45+ ./arch35/generic_block_sparse_attention_grad_tiling_arch35.cpp
46+ )
47+endif()
@@ -0,0 +1,334 @@
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 generic_block_sparse_attention_grad_tiling_arch35.cpp
13+ * \brief Arch35 tiling for GenericBlockSparseAttentionGrad (design §4.7 / §6).
14+ */
15+ 
16+#include "err/ops_err.h"
17+#include "log/log.h"
18+#include "op_host/tiling_base.h"
19+#include "op_host/tiling_templates_registry.h"
20+#include "tiling/platform/platform_ascendc.h"
21+#include "../generic_block_sparse_attention_grad_tiling.h"
22+ 
23+namespace optiling {
24+namespace GSAG_ARC35 {
25+ 
26+static constexpr int64_t HEAD_DIM = 128;
27+static constexpr int64_t BASE_M = 128;
28+static constexpr int64_t MAX_HEAD_NUM = 128;
29+static constexpr uint32_t SUPPORTED_MASK_TYPE = 1;
30+ 
31+int64_t AlignTo(int64_t x, int64_t align)
32+{
33+ return (x + align - 1) / align * align;
34+}
35+ 
36+class GenericBlockSparseAttentionGradArch35Tiling : public Ops::Transformer::OpTiling::TilingBaseClass {
37+public:
38+ explicit GenericBlockSparseAttentionGradArch35Tiling(gert::TilingContext *context_)
39+ : TilingBaseClass(context_)
40+ {}
41+ 
42+protected:
43+ bool IsCapable() override
44+ {
45+ if (context_->GetDeterministic() == 1) {
46+ OP_LOGE(context_->GetNodeName(), "GenericBlockSparseAttentionGrad does not support Deterministic.");
47+ return false;
48+ }
49+ if (dataType_ != ge::DT_FLOAT16 && dataType_ != ge::DT_BF16) {
50+ OP_LOGE(context_->GetNodeName(), "only support DT_FLOAT16 and DT_BF16.");
51+ return false;
52+ }
53+ if (headDim_ != HEAD_DIM) {
54+ OP_LOGE(context_->GetNodeName(), "only support head_dim 128.");
55+ return false;
56+ }
57+ if (blockShapeX_ != 1) {
58+ OP_LOGE(context_->GetNodeName(), "only support block_shape[0] == 1.");
59+ return false;
60+ }
61+ if (blockShapeY_ < 128 || blockShapeY_ % 64 != 0) {
62+ OP_LOGE(context_->GetNodeName(), "block_shape[1] must be >= 128 and 64-aligned.");
63+ return false;
64+ }
65+ // Cube tile baseN shares UB/L1 with baseM; current layout budgets baseN<=128.
66+ if (blockShapeY_ > BASE_M) {
67+ OP_LOGE(context_->GetNodeName(), "block_shape[1]=%ld exceeds supported cube baseN=%ld (UB/L1 budget).",
68+ blockShapeY_, BASE_M);
69+ return false;
70+ }
71+ if (isPackedGqa_ != 1) {
72+ OP_LOGE(context_->GetNodeName(), "only support is_packed_gqa == 1.");
73+ return false;
74+ }
75+ if (qHeadNum_ <= 0 || qHeadNum_ > MAX_HEAD_NUM) {
76+ OP_LOGE(context_->GetNodeName(), "qHeadNum=%ld must be in [1, %ld].", qHeadNum_, MAX_HEAD_NUM);
77+ return false;
78+ }
79+ if (kvHeadNum_ <= 0 || kvHeadNum_ > MAX_HEAD_NUM) {
80+ OP_LOGE(context_->GetNodeName(), "kvHeadNum=%ld must be in [1, %ld].", kvHeadNum_, MAX_HEAD_NUM);
81+ return false;
82+ }
83+ if (maskType_ != SUPPORTED_MASK_TYPE) {
84+ OP_LOGE(context_->GetNodeName(), "only support mask_type == %u, got %u.", SUPPORTED_MASK_TYPE, maskType_);
85+ return false;
86+ }
87+ return true;
88+ }
89+ 
90+ ge::graphStatus GetShapeAttrsInfo() override
91+ {
92+ // Inputs: query=0, key=1, value=2, ..., rsvd_block_idx=6, rsvd_block_count=7, metadata=8
93+ // Optional: atten_mask=9, cu_seq_lengths=10, cu_seq_lengths_kv=11, seqused_q=12, seqused_kv=13.
94+ auto qInputDesc = context_->GetInputDesc(0);
95+ const gert::StorageShape *queryShape = context_->GetInputShape(0);
96+ const gert::StorageShape *keyShape = context_->GetInputShape(1);
97+ const gert::StorageShape *valueShape = context_->GetInputShape(2);
98+ const gert::StorageShape *idxShape = context_->GetInputShape(6);
99+ const gert::StorageShape *cntShape = context_->GetInputShape(7);
100+ const gert::StorageShape *metaShape = context_->GetInputShape(8);
101+ 
102+ const auto *attrs = context_->GetAttrs();
103+ if (attrs == nullptr || qInputDesc == nullptr || queryShape == nullptr || keyShape == nullptr ||
104+ valueShape == nullptr || idxShape == nullptr || cntShape == nullptr || metaShape == nullptr) {
105+ OP_LOGE(context_->GetNodeName(), "required inputs/attrs are null.");
106+ return ge::GRAPH_FAILED;
107+ }
108+ 
109+ dataType_ = qInputDesc->GetDataType();
110+ 
111+ // Attrs: block_shape, is_packed_gqa, q_input_layout, kv_input_layout, scale_value,
112+ // mask_type, softmax_precision, window_size_left, window_size_right
113+ const auto *blockShapeList = attrs->GetListInt(0);
114+ isPackedGqa_ = static_cast<int32_t>(*attrs->GetAttrPointer<int64_t>(1));
115+ qLayout_ = attrs->GetAttrPointer<char>(2);
116+ kvLayout_ = attrs->GetAttrPointer<char>(3);
117+ softmaxScale_ = *attrs->GetAttrPointer<float>(4);
118+ maskType_ = static_cast<uint32_t>(*attrs->GetAttrPointer<int64_t>(5));
119+ windowSizeLeft_ = static_cast<int32_t>(*attrs->GetAttrPointer<int64_t>(7));
120+ windowSizeRight_ = static_cast<int32_t>(*attrs->GetAttrPointer<int64_t>(8));
121+ 
122+ if (qLayout_ == nullptr || kvLayout_ == nullptr || strcmp(qLayout_, kvLayout_) != 0) {
123+ OP_LOGE(context_->GetNodeName(), "q_input_layout must equal kv_input_layout.");
124+ return ge::GRAPH_FAILED;
125+ }
126+ 
127+ if (blockShapeList != nullptr && blockShapeList->GetSize() >= 2) {
128+ const int64_t *data = blockShapeList->GetData();
129+ blockShapeX_ = static_cast<int32_t>(data[0]);
130+ blockShapeY_ = static_cast<int32_t>(data[1]);
131+ } else {
132+ blockShapeX_ = 1;
133+ blockShapeY_ = 128;
134+ }
135+ 
136+ if (idxShape->GetOriginShape().GetDimNum() != 4 || cntShape->GetOriginShape().GetDimNum() != 3) {
137+ OP_LOGE(context_->GetNodeName(), "rsvd_block_idx must be 4D and rsvd_block_count must be 3D.");
138+ return ge::GRAPH_FAILED;
139+ }
140+ batchNum_ = idxShape->GetStorageShape().GetDim(0);
141+ kvHeadNum_ = idxShape->GetStorageShape().GetDim(1);
142+ numJ_ = idxShape->GetStorageShape().GetDim(2);
143+ maxS1_ = idxShape->GetStorageShape().GetDim(3);
144+ 
145+ if (strcmp(qLayout_, TND_STR) == 0) {
146+ if (queryShape->GetOriginShape().GetDimNum() != 3) {
147+ OP_LOGE(context_->GetNodeName(), "TND query must be 3D.");
148+ return ge::GRAPH_FAILED;
149+ }
150+ auto cuQ = context_->GetOptionalInputTensor(10);
151+ auto cuKv = context_->GetOptionalInputTensor(11);
152+ if (cuQ == nullptr || cuKv == nullptr) {
153+ OP_LOGE(context_->GetNodeName(), "TND requires cu_seq_lengths and cu_seq_lengths_kv.");
154+ return ge::GRAPH_FAILED;
155+ }
156+ // seqused_q/kv (inputs 12/13) are dynamic device values. They are
157+ // consumed by the kernel, while cu tensors retain packed-TND offsets.
158+ qSeqLen_ = queryShape->GetStorageShape().GetDim(0);
159+ qHeadNum_ = queryShape->GetStorageShape().GetDim(1);
160+ headDim_ = queryShape->GetStorageShape().GetDim(2);
161+ kvSeqLen_ = keyShape->GetStorageShape().GetDim(0);
162+ if (static_cast<int64_t>(keyShape->GetStorageShape().GetDim(1)) != kvHeadNum_) {
163+ OP_LOGE(context_->GetNodeName(), "key N2 mismatch with rsvd_block_idx.");
164+ return ge::GRAPH_FAILED;
165+ }
166+ } else if (strcmp(qLayout_, BSND_STR) == 0) {
167+ batchNum_ = queryShape->GetStorageShape().GetDim(0);
168+ qSeqLen_ = queryShape->GetStorageShape().GetDim(1);
169+ qHeadNum_ = queryShape->GetStorageShape().GetDim(2);
170+ headDim_ = queryShape->GetStorageShape().GetDim(3);
171+ kvSeqLen_ = keyShape->GetStorageShape().GetDim(1);
172+ kvHeadNum_ = keyShape->GetStorageShape().GetDim(2);
173+ } else if (strcmp(qLayout_, BNSD_STR) == 0) {
174+ batchNum_ = queryShape->GetStorageShape().GetDim(0);
175+ qHeadNum_ = queryShape->GetStorageShape().GetDim(1);
176+ qSeqLen_ = queryShape->GetStorageShape().GetDim(2);
177+ headDim_ = queryShape->GetStorageShape().GetDim(3);
178+ kvHeadNum_ = keyShape->GetStorageShape().GetDim(1);
179+ kvSeqLen_ = keyShape->GetStorageShape().GetDim(2);
180+ } else {
181+ OP_LOGE(context_->GetNodeName(), "layout must be TND/BSND/BNSD.");
182+ return ge::GRAPH_FAILED;
183+ }
184+ 
185+ if (kvHeadNum_ <= 0 || qHeadNum_ % kvHeadNum_ != 0) {
186+ OP_LOGE(context_->GetNodeName(), "qHeadNum must be divisible by kvHeadNum.");
187+ return ge::GRAPH_FAILED;
188+ }
189+ qGroup_ = qHeadNum_ / kvHeadNum_;
190+ 
191+ tilingData_.set_batchNum(batchNum_);
192+ tilingData_.set_qSeqLen(qSeqLen_);
193+ tilingData_.set_kvSeqLen(kvSeqLen_);
194+ tilingData_.set_qGroup(qGroup_);
195+ tilingData_.set_qHeadNum(qHeadNum_);
196+ tilingData_.set_kvHeadNum(kvHeadNum_);
197+ tilingData_.set_headDim(headDim_);
198+ tilingData_.set_softmaxScale(softmaxScale_);
199+ tilingData_.set_maxS1(maxS1_);
200+ tilingData_.set_numJ(numJ_);
201+ tilingData_.set_maskType(maskType_);
202+ tilingData_.set_isPackedGqa(static_cast<uint32_t>(isPackedGqa_));
203+ tilingData_.set_windowSizeLeft(windowSizeLeft_);
204+ tilingData_.set_windowSizeRight(windowSizeRight_);
205+ return ge::GRAPH_SUCCESS;
206+ }
207+ 
208+ ge::graphStatus GetPlatformInfo() override
209+ {
210+ return ge::GRAPH_SUCCESS;
211+ }
212+ 
213+ ge::graphStatus DoOpTiling() override
214+ {
215+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(context_->GetPlatformInfo());
216+ auto cubeCoreNum = ascendcPlatform.GetCoreNumAic();
217+ uint32_t baseM = BASE_M;
218+ uint32_t baseN = static_cast<uint32_t>(blockShapeY_);
219+ 
220+ tilingData_.set_BlockX(static_cast<uint32_t>(blockShapeX_));
221+ tilingData_.set_BlockY(static_cast<uint32_t>(blockShapeY_));
222+ tilingData_.set_cubeCoreNum(cubeCoreNum);
223+ tilingData_.set_baseM(baseM);
224+ tilingData_.set_baseN(baseN);
225+ context_->SetBlockDim(cubeCoreNum);
226+ context_->SetScheduleMode(1);
227+ return ge::GRAPH_SUCCESS;
228+ }
229+ 
230+ ge::graphStatus DoLibApiTiling() override
231+ {
232+ constexpr uint32_t elementNum = 8 * 1024;
233+ uint32_t processS1Size = elementNum / static_cast<uint32_t>(headDim_);
234+ auto inputShape = ge::Shape({processS1Size, static_cast<int64_t>(headDim_)});
235+ uint32_t tmpSpaceSize = AscendC::GetSoftMaxGradMaxTmpSize(inputShape, sizeof(float), true, true);
236+ AscendC::SoftMaxGradTilingFunc(inputShape, sizeof(float), tmpSpaceSize, tilingData_.softmaxGradFrontTilingData,
237+ true);
238+ tilingData_.set_sftgTmpSpaceSize(tmpSpaceSize);
239+ return ge::GRAPH_SUCCESS;
240+ }
241+ 
242+ ge::graphStatus GetWorkspaceSize() override
243+ {
244+ // Design §4.7: sftg → dq → dk → dv (fp32 user workspace)
245+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(context_->GetPlatformInfo());
246+ uint64_t sysWorkspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize();
247+ uint64_t usrOffset = 0;
248+ uint64_t dqSize = 0;
249+ uint64_t dkSize = 0;
250+ uint64_t sftgSize = 0;
251+ 
252+ if (strcmp(qLayout_, TND_STR) == 0) {
253+ dqSize = static_cast<uint64_t>(qSeqLen_) * qHeadNum_ * headDim_;
254+ dkSize = static_cast<uint64_t>(kvSeqLen_) * kvHeadNum_ * headDim_;
255+ // Pad sftg so DataCopy of last EvenCore tail cannot write past the buffer
256+ // (T=1024 / 56 AIVs leaves a non-16-aligned tail that may round up).
257+ sftgSize = static_cast<uint64_t>(AlignTo(static_cast<int64_t>(qSeqLen_) * qHeadNum_ * 8, 256));
258+ } else {
259+ dqSize = static_cast<uint64_t>(batchNum_) * qSeqLen_ * qHeadNum_ * headDim_;
260+ dkSize = static_cast<uint64_t>(batchNum_) * kvSeqLen_ * kvHeadNum_ * headDim_;
261+ sftgSize = static_cast<uint64_t>(AlignTo(static_cast<int64_t>(batchNum_) * qHeadNum_ * qSeqLen_ * 8, 256));
262+ }
263+ 
264+ tilingData_.set_dqSize(dqSize);
265+ tilingData_.set_dkSize(dkSize);
266+ tilingData_.set_sftgWorkspaceOffset(usrOffset);
267+ usrOffset += sftgSize * sizeof(float);
268+ tilingData_.set_dqWorkspaceOffset(usrOffset);
269+ usrOffset += dqSize * sizeof(float);
270+ tilingData_.set_dkWorkspaceOffset(usrOffset);
271+ usrOffset += dkSize * sizeof(float);
272+ tilingData_.set_dvWorkspaceOffset(usrOffset);
273+ usrOffset += dkSize * sizeof(float);
274+ // Per-cube dQ_sel scratch (2 ping-pong slots): Fixpipe [baseM, D] then Vector scatter.
275+ tilingData_.set_dqSelWorkspaceOffset(usrOffset);
276+ usrOffset += tilingData_.get_cubeCoreNum() * 2 * tilingData_.get_baseM() * headDim_ * sizeof(float);
277+ 
278+ context_->GetWorkspaceSizes(1)[0] = sysWorkspaceSize + usrOffset;
279+ return ge::GRAPH_SUCCESS;
280+ }
281+ 
282+ ge::graphStatus PostTiling() override
283+ {
284+ tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity());
285+ context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize());
286+ return ge::GRAPH_SUCCESS;
287+ }
288+ 
289+ uint64_t GetTilingKey() const override
290+ {
291+ // 1000 BF16 BSND, 1001 FP16 BSND, 1002 BF16 BNSD, 1003 FP16 BNSD, 1004 BF16 TND, 1005 FP16 TND
292+ uint64_t key = 1000;
293+ key = (dataType_ == ge::DT_BF16) ? key : key + 0b001;
294+ if (strcmp(qLayout_, BSND_STR) == 0) {
295+ key += 0b000;
296+ } else if (strcmp(qLayout_, BNSD_STR) == 0) {
297+ key += 0b010;
298+ } else if (strcmp(qLayout_, TND_STR) == 0) {
299+ key += 0b100;
300+ }
301+ return key;
302+ }
303+ 
304+private:
305+ GenericBlockSparseAttentionGradTilingDataArch35 tilingData_;
306+ ge::DataType dataType_{ge::DT_FLOAT16};
307+ const char *qLayout_{nullptr};
308+ const char *kvLayout_{nullptr};
309+ static constexpr const char *BSND_STR = "BSND";
310+ static constexpr const char *BNSD_STR = "BNSD";
311+ static constexpr const char *TND_STR = "TND";
312+ int64_t batchNum_{0};
313+ int64_t qSeqLen_{0};
314+ int64_t kvSeqLen_{0};
315+ int64_t qHeadNum_{0};
316+ int64_t kvHeadNum_{0};
317+ int64_t qGroup_{0};
318+ int64_t headDim_{0};
319+ int64_t maxS1_{0};
320+ int64_t numJ_{0};
321+ int32_t blockShapeX_{1};
322+ int32_t blockShapeY_{128};
323+ int32_t isPackedGqa_{1};
324+ uint32_t maskType_{0};
325+ float softmaxScale_{1.0f};
326+ int32_t windowSizeLeft_{-1};
327+ int32_t windowSizeRight_{-1};
328+};
329+ 
330+REGISTER_TILING_TEMPLATE_WITH_ARCH(GenericBlockSparseAttentionGrad, GenericBlockSparseAttentionGradArch35Tiling,
331+ static_cast<int32_t>(NpuArch::DAV_3510), 1);
332+ 
333+} // namespace GSAG_ARC35
334+} // namespace optiling
@@ -0,0 +1,110 @@
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 generic_block_sparse_attention_grad_def.cpp
13+ * \brief GE OpDef for GenericBlockSparseAttentionGrad (IR aligned with design / xlsx).
14+ */
15+ 
16+#include "register/op_def_registry.h"
17+ 
18+namespace ops {
19+ 
20+class GenericBlockSparseAttentionGrad : public OpDef {
21+public:
22+ explicit GenericBlockSparseAttentionGrad(const char *name) : OpDef(name)
23+ {
24+ this->Input("query")
25+ .ParamType(REQUIRED)
26+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
27+ .FormatList({ge::FORMAT_ND});
28+ this->Input("key")
29+ .ParamType(REQUIRED)
30+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
31+ .FormatList({ge::FORMAT_ND});
32+ this->Input("value")
33+ .ParamType(REQUIRED)
34+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
35+ .FormatList({ge::FORMAT_ND});
36+ this->Input("dout")
37+ .ParamType(REQUIRED)
38+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
39+ .FormatList({ge::FORMAT_ND});
40+ this->Input("out")
41+ .ParamType(REQUIRED)
42+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
43+ .FormatList({ge::FORMAT_ND});
44+ this->Input("lse")
45+ .ParamType(REQUIRED)
46+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT})
47+ .FormatList({ge::FORMAT_ND});
48+ this->Input("rsvd_block_idx")
49+ .ParamType(REQUIRED)
50+ .DataType({ge::DT_INT32, ge::DT_INT32})
51+ .FormatList({ge::FORMAT_ND});
52+ this->Input("rsvd_block_count")
53+ .ParamType(REQUIRED)
54+ .DataType({ge::DT_INT32, ge::DT_INT32})
55+ .FormatList({ge::FORMAT_ND});
56+ this->Input("metadata")
57+ .ParamType(REQUIRED)
58+ .DataType({ge::DT_INT64, ge::DT_INT64})
59+ .FormatList({ge::FORMAT_ND});
60+ this->Input("atten_mask")
61+ .ParamType(OPTIONAL)
62+ .DataType({ge::DT_BOOL, ge::DT_BOOL})
63+ .FormatList({ge::FORMAT_ND});
64+ this->Input("cu_seq_lengths")
65+ .ParamType(OPTIONAL)
66+ .DataType({ge::DT_INT64, ge::DT_INT64})
67+ .FormatList({ge::FORMAT_ND});
68+ this->Input("cu_seq_lengths_kv")
69+ .ParamType(OPTIONAL)
70+ .DataType({ge::DT_INT64, ge::DT_INT64})
71+ .FormatList({ge::FORMAT_ND});
72+ this->Input("seqused_q")
73+ .ParamType(OPTIONAL)
74+ .DataType({ge::DT_INT32, ge::DT_INT32})
75+ .FormatList({ge::FORMAT_ND});
76+ this->Input("seqused_kv")
77+ .ParamType(OPTIONAL)
78+ .DataType({ge::DT_INT32, ge::DT_INT32})
79+ .FormatList({ge::FORMAT_ND});
80+ 
81+ this->Output("dQuery")
82+ .ParamType(REQUIRED)
83+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
84+ .FormatList({ge::FORMAT_ND});
85+ this->Output("dKey")
86+ .ParamType(REQUIRED)
87+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
88+ .FormatList({ge::FORMAT_ND});
89+ this->Output("dValue")
90+ .ParamType(REQUIRED)
91+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
92+ .FormatList({ge::FORMAT_ND});
93+ 
94+ this->Attr("block_shape").AttrType(OPTIONAL).ListInt({1, 128});
95+ this->Attr("is_packed_gqa").AttrType(OPTIONAL).Int(1);
96+ this->Attr("q_input_layout").AttrType(OPTIONAL).String("TND");
97+ this->Attr("kv_input_layout").AttrType(OPTIONAL).String("TND");
98+ this->Attr("scale_value").AttrType(OPTIONAL).Float(1.0);
99+ this->Attr("mask_type").AttrType(OPTIONAL).Int(1);
100+ this->Attr("softmax_precision").AttrType(OPTIONAL).Int(0);
101+ this->Attr("window_size_left").AttrType(OPTIONAL).Int(-1);
102+ this->Attr("window_size_right").AttrType(OPTIONAL).Int(-1);
103+ 
104+ this->AICore().AddConfig("ascend950");
105+ }
106+};
107+ 
108+OP_ADD(GenericBlockSparseAttentionGrad);
109+ 
110+} // namespace ops
@@ -0,0 +1,57 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <graph/utils/type_utils.h>
12+#include <register/op_impl_registry.h>
13+#include "log/log.h"
14+#include "log/error_code.h"
15+ 
16+using namespace ge;
17+ 
18+namespace ops {
19+ 
20+// IR input indices: query=0, key=1, value=2
21+static constexpr uint32_t QUERY_INDEX = 0;
22+static constexpr uint32_t KEY_INDEX = 1;
23+static constexpr uint32_t VALUE_INDEX = 2;
24+static constexpr uint32_t DQ_OUT_INDEX = 0;
25+static constexpr uint32_t DK_OUT_INDEX = 1;
26+static constexpr uint32_t DV_OUT_INDEX = 2;
27+ 
28+static ge::graphStatus InferShapeGenericBlockSparseAttentionGrad(gert::InferShapeContext *context)
29+{
30+ if (context == nullptr) {
31+ OP_LOGE("GenericBlockSparseAttentionGrad", "context is nullptr!");
32+ return ge::GRAPH_FAILED;
33+ }
34+ 
35+ const gert::Shape *queryShape = context->GetInputShape(QUERY_INDEX);
36+ OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);
37+ const gert::Shape *keyShape = context->GetInputShape(KEY_INDEX);
38+ OP_CHECK_NULL_WITH_CONTEXT(context, keyShape);
39+ const gert::Shape *valueShape = context->GetInputShape(VALUE_INDEX);
40+ OP_CHECK_NULL_WITH_CONTEXT(context, valueShape);
41+ 
42+ gert::Shape *dqOutShape = context->GetOutputShape(DQ_OUT_INDEX);
43+ OP_CHECK_NULL_WITH_CONTEXT(context, dqOutShape);
44+ gert::Shape *dkOutShape = context->GetOutputShape(DK_OUT_INDEX);
45+ OP_CHECK_NULL_WITH_CONTEXT(context, dkOutShape);
46+ gert::Shape *dvOutShape = context->GetOutputShape(DV_OUT_INDEX);
47+ OP_CHECK_NULL_WITH_CONTEXT(context, dvOutShape);
48+ 
49+ *dqOutShape = *queryShape;
50+ *dkOutShape = *keyShape;
51+ *dvOutShape = *valueShape;
52+ return ge::GRAPH_SUCCESS;
53+}
54+ 
55+IMPL_OP_INFERSHAPE(GenericBlockSparseAttentionGrad).InferShape(InferShapeGenericBlockSparseAttentionGrad);
56+ 
57+} // namespace ops
@@ -0,0 +1,45 @@
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 generic_block_sparse_attention_grad_tiling.cpp
13+ * \brief Tiling registration for GenericBlockSparseAttentionGrad.
14+ */
15+ 
16+#include <register/op_impl_registry.h>
17+#include "op_host/tiling_templates_registry.h"
18+#include "generic_block_sparse_attention_grad_tiling.h"
19+#include "err/ops_err.h"
20+ 
21+using namespace ge;
22+ 
23+namespace optiling {
24+namespace gsag {
25+ 
26+ASCENDC_EXTERN_C ge::graphStatus TilingGenericBlockSparseAttentionGrad(gert::TilingContext *context)
27+{
28+ OP_CHECK_IF(context == nullptr,
29+ OPS_REPORT_VECTOR_INNER_ERR("GenericBlockSparseAttentionGrad", "Context is nullptr."),
30+ return ge::GRAPH_FAILED);
31+ return Ops::Transformer::OpTiling::TilingRegistryArch::GetInstance().DoTilingImpl(context);
32+}
33+ 
34+ASCENDC_EXTERN_C ge::graphStatus TilingPrepareGenericBlockSparseAttentionGrad(gert::TilingParseContext *context)
35+{
36+ (void)context;
37+ return ge::GRAPH_SUCCESS;
38+}
39+ 
40+IMPL_OP_OPTILING(GenericBlockSparseAttentionGrad)
41+ .Tiling(TilingGenericBlockSparseAttentionGrad)
42+ .TilingParse<GenericBlockSparseAttentionGradCompileInfo>(TilingPrepareGenericBlockSparseAttentionGrad);
43+ 
44+} // namespace gsag
45+} // namespace optiling
@@ -0,0 +1,75 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef GENERIC_SPARSE_ATTENTION_GRAD_TILING_H
12+#define GENERIC_SPARSE_ATTENTION_GRAD_TILING_H
13+ 
14+#include <cstdint>
15+#include "register/tilingdata_base.h"
16+#include "tiling/platform/platform_ascendc.h"
17+#include "tiling/tiling_api.h"
18+#include "register/op_def_registry.h"
19+ 
20+namespace optiling {
21+ 
22+BEGIN_TILING_DATA_DEF(GenericBlockSparseAttentionGradTilingDataArch35)
23+TILING_DATA_FIELD_DEF(uint64_t, cubeCoreNum);
24+TILING_DATA_FIELD_DEF(uint64_t, batchNum);
25+TILING_DATA_FIELD_DEF(uint64_t, qSeqLen); // TND: T1 total tokens
26+TILING_DATA_FIELD_DEF(uint64_t, kvSeqLen); // TND: T2 total tokens
27+TILING_DATA_FIELD_DEF(uint64_t, qGroup);
28+TILING_DATA_FIELD_DEF(uint64_t, qHeadNum);
29+TILING_DATA_FIELD_DEF(uint64_t, kvHeadNum);
30+TILING_DATA_FIELD_DEF(uint64_t, headDim);
31+TILING_DATA_FIELD_DEF(uint64_t, baseM);
32+TILING_DATA_FIELD_DEF(uint64_t, baseN);
33+TILING_DATA_FIELD_DEF(uint64_t, maxS1);
34+TILING_DATA_FIELD_DEF(uint64_t, numJ);
35+TILING_DATA_FIELD_DEF(uint64_t, dqSize);
36+TILING_DATA_FIELD_DEF(uint64_t, dkSize);
37+TILING_DATA_FIELD_DEF(uint64_t, dqWorkspaceOffset);
38+TILING_DATA_FIELD_DEF(uint64_t, dkWorkspaceOffset);
39+TILING_DATA_FIELD_DEF(uint64_t, dvWorkspaceOffset);
40+TILING_DATA_FIELD_DEF(uint64_t, sftgWorkspaceOffset);
41+TILING_DATA_FIELD_DEF(uint64_t, dqSelWorkspaceOffset);
42+TILING_DATA_FIELD_DEF(float, softmaxScale);
43+TILING_DATA_FIELD_DEF(uint32_t, sftgTmpSpaceSize);
44+TILING_DATA_FIELD_DEF(uint32_t, BlockX);
45+TILING_DATA_FIELD_DEF(uint32_t, BlockY);
46+TILING_DATA_FIELD_DEF(uint32_t, maskType);
47+TILING_DATA_FIELD_DEF(uint32_t, isPackedGqa);
48+TILING_DATA_FIELD_DEF(int32_t, windowSizeLeft);
49+TILING_DATA_FIELD_DEF(int32_t, windowSizeRight);
50+TILING_DATA_FIELD_DEF_STRUCT(SoftMaxTiling, softmaxGradFrontTilingData);
51+END_TILING_DATA_DEF;
52+ 
53+REGISTER_TILING_DATA_CLASS(GenericBlockSparseAttentionGrad, GenericBlockSparseAttentionGradTilingDataArch35)
54+ 
55+struct GenericBlockSparseAttentionGradCompileInfo {
56+ uint32_t inputDataByte = 2;
57+ ge::DataType inputDataType;
58+ uint32_t coreNum = 0;
59+ uint32_t aivNum = 0;
60+ uint32_t aicNum = 0;
61+ uint64_t ubSize = 0;
62+ uint64_t l1Size = 0;
63+ uint64_t sysWorkspaceSize = 0;
64+ platform_ascendc::SocVersion socVersion;
65+};
66+ 
67+enum class GsagInputLayout : uint32_t {
68+ TND = 0,
69+ BNSD = 1,
70+ BSND = 2
71+};
72+ 
73+} // namespace optiling
74+ 
75+#endif // GENERIC_SPARSE_ATTENTION_GRAD_TILING_H
@@ -0,0 +1,199 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file aclnn_generic_block_sparse_attention_grad.cpp
13+ * \brief L2 aclnn API for GenericBlockSparseAttentionGrad.
14+ */
15+ 
16+#include "aclnn_generic_block_sparse_attention_grad.h"
17+#include "generic_block_sparse_attention_grad.h"
18+#include "aclnn_kernels/contiguous.h"
19+#include "aclnn_kernels/common/op_error_check.h"
20+#include "opdev/make_op_executor.h"
21+#include "opdev/op_dfx.h"
22+#include "opdev/common_types.h"
23+ 
24+using namespace op;
25+ 
26+#ifdef __cplusplus
27+extern "C" {
28+#endif
29+ 
30+namespace {
31+ 
32+static constexpr int64_t GSAG_MAX_HEAD_NUM = 128;
33+static constexpr int64_t GSAG_SUPPORTED_MASK_TYPE = 1;
34+ 
35+inline bool TensorOk(const aclTensor *t)
36+{
37+ return t != nullptr && t->GetViewShape().GetDimNum() > 0;
38+}
39+ 
40+int64_t GetHeadNumFromQuery(const aclTensor *query, const char *layout)
41+{
42+ const auto &shape = query->GetViewShape();
43+ if (strcmp(layout, "TND") == 0) {
44+ return shape.GetDimNum() >= 2 ? shape.GetDim(1) : -1;
45+ }
46+ if (strcmp(layout, "BNSD") == 0) {
47+ return shape.GetDimNum() >= 2 ? shape.GetDim(1) : -1;
48+ }
49+ if (strcmp(layout, "BSND") == 0) {
50+ return shape.GetDimNum() >= 3 ? shape.GetDim(2) : -1;
51+ }
52+ return -1;
53+}
54+ 
55+int64_t GetHeadNumFromKey(const aclTensor *key, const char *layout)
56+{
57+ const auto &shape = key->GetViewShape();
58+ if (strcmp(layout, "TND") == 0) {
59+ return shape.GetDimNum() >= 2 ? shape.GetDim(1) : -1;
60+ }
61+ if (strcmp(layout, "BNSD") == 0) {
62+ return shape.GetDimNum() >= 2 ? shape.GetDim(1) : -1;
63+ }
64+ if (strcmp(layout, "BSND") == 0) {
65+ return shape.GetDimNum() >= 3 ? shape.GetDim(2) : -1;
66+ }
67+ return -1;
68+}
69+ 
70+aclnnStatus Validate(const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *dout,
71+ const aclTensor *out, const aclTensor *lse, const aclTensor *rsvdBlockIdx,
72+ const aclTensor *rsvdBlockCount, const aclTensor *metadata, const aclIntArray *blockShape,
73+ int64_t isPackedGqa, char *qInputLayout, char *kvInputLayout, int64_t maskType,
74+ int64_t windowSizeLeft, int64_t windowSizeRight, const aclTensor *dQuery, const aclTensor *dKey,
75+ const aclTensor *dValue)
76+{
77+ CHECK_RET(TensorOk(query) && TensorOk(key) && TensorOk(value) && TensorOk(dout) && TensorOk(out) && TensorOk(lse),
78+ ACLNN_ERR_PARAM_NULLPTR);
79+ CHECK_RET(TensorOk(rsvdBlockIdx) && TensorOk(rsvdBlockCount) && TensorOk(metadata), ACLNN_ERR_PARAM_NULLPTR);
80+ CHECK_RET(TensorOk(dQuery) && TensorOk(dKey) && TensorOk(dValue), ACLNN_ERR_PARAM_NULLPTR);
81+ CHECK_RET(qInputLayout != nullptr && kvInputLayout != nullptr, ACLNN_ERR_PARAM_NULLPTR);
82+ CHECK_RET(strcmp(qInputLayout, kvInputLayout) == 0, ACLNN_ERR_PARAM_INVALID);
83+ CHECK_RET(isPackedGqa == 1, ACLNN_ERR_PARAM_INVALID);
84+ CHECK_RET(maskType == GSAG_SUPPORTED_MASK_TYPE, ACLNN_ERR_PARAM_INVALID);
85+ CHECK_RET(windowSizeLeft == -1 && windowSizeRight == -1, ACLNN_ERR_PARAM_INVALID);
86+ if (blockShape != nullptr) {
87+ CHECK_RET(blockShape->Size() >= 2, ACLNN_ERR_PARAM_INVALID);
88+ CHECK_RET((*blockShape)[0] == 1, ACLNN_ERR_PARAM_INVALID);
89+ CHECK_RET((*blockShape)[1] >= 128 && ((*blockShape)[1] % 64 == 0), ACLNN_ERR_PARAM_INVALID);
90+ }
91+ const int64_t qHeadNum = GetHeadNumFromQuery(query, qInputLayout);
92+ const int64_t kvHeadNum = GetHeadNumFromKey(key, kvInputLayout);
93+ CHECK_RET(qHeadNum > 0 && qHeadNum <= GSAG_MAX_HEAD_NUM, ACLNN_ERR_PARAM_INVALID);
94+ CHECK_RET(kvHeadNum > 0 && kvHeadNum <= GSAG_MAX_HEAD_NUM, ACLNN_ERR_PARAM_INVALID);
95+ CHECK_RET(qHeadNum % kvHeadNum == 0, ACLNN_ERR_PARAM_INVALID);
96+ DataType qDtype = query->GetDataType();
97+ CHECK_RET(qDtype == ACL_FLOAT16 || qDtype == ACL_BF16, ACLNN_ERR_PARAM_INVALID);
98+ CHECK_RET(key->GetDataType() == qDtype && value->GetDataType() == qDtype && dout->GetDataType() == qDtype &&
99+ out->GetDataType() == qDtype,
100+ ACLNN_ERR_PARAM_INVALID);
101+ CHECK_RET(lse->GetDataType() == ACL_FLOAT, ACLNN_ERR_PARAM_INVALID);
102+ CHECK_RET(rsvdBlockIdx->GetDataType() == ACL_INT32 && rsvdBlockCount->GetDataType() == ACL_INT32,
103+ ACLNN_ERR_PARAM_INVALID);
104+ CHECK_RET(metadata->GetDataType() == ACL_INT64, ACLNN_ERR_PARAM_INVALID);
105+ return ACLNN_SUCCESS;
106+}
107+ 
108+} // namespace
109+ 
110+aclnnStatus aclnnGenericBlockSparseAttentionGradGetWorkspaceSize(
111+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *dout, const aclTensor *out,
112+ const aclTensor *lse, const aclTensor *rsvdBlockIdx, const aclTensor *rsvdBlockCount, const aclTensor *metadata,
113+ const aclTensor *attenMaskOptional, const aclTensor *cuSeqLengthsOptional, const aclTensor *cuSeqLengthsKvOptional,
114+ const aclTensor *sequsedQOptional, const aclTensor *sequsedKvOptional, const aclIntArray *blockShape,
115+ int64_t isPackedGqa, char *qInputLayout, char *kvInputLayout, double scaleValue, int64_t maskType,
116+ int64_t softmaxPrecision, int64_t windowSizeLeft, int64_t windowSizeRight, aclTensor *dQuery, aclTensor *dKey,
117+ aclTensor *dValue, uint64_t *workspaceSize, aclOpExecutor **executor)
118+{
119+ CHECK_RET(workspaceSize != nullptr && executor != nullptr, ACLNN_ERR_INNER_NULLPTR);
120+ L2_DFX_PHASE_1(aclnnGenericBlockSparseAttentionGrad,
121+ DFX_IN(query, key, value, dout, out, lse, rsvdBlockIdx, rsvdBlockCount, metadata, attenMaskOptional,
122+ cuSeqLengthsOptional, cuSeqLengthsKvOptional, sequsedQOptional, sequsedKvOptional, blockShape,
123+ isPackedGqa, qInputLayout, kvInputLayout, scaleValue, maskType, softmaxPrecision,
124+ windowSizeLeft, windowSizeRight),
125+ DFX_OUT(dQuery, dKey, dValue));
126+ 
127+ auto uniqueExecutor = CREATE_EXECUTOR();
128+ CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
129+ 
130+ auto ret =
131+ Validate(query, key, value, dout, out, lse, rsvdBlockIdx, rsvdBlockCount, metadata, blockShape, isPackedGqa,
132+ qInputLayout, kvInputLayout, maskType, windowSizeLeft, windowSizeRight, dQuery, dKey, dValue);
133+ CHECK_RET(ret == ACLNN_SUCCESS, ret);
134+ 
135+ auto queryC = l0op::Contiguous(query, uniqueExecutor.get());
136+ auto keyC = l0op::Contiguous(key, uniqueExecutor.get());
137+ auto valueC = l0op::Contiguous(value, uniqueExecutor.get());
138+ auto doutC = l0op::Contiguous(dout, uniqueExecutor.get());
139+ auto outC = l0op::Contiguous(out, uniqueExecutor.get());
140+ auto lseC = l0op::Contiguous(lse, uniqueExecutor.get());
141+ auto idxC = l0op::Contiguous(rsvdBlockIdx, uniqueExecutor.get());
142+ auto cntC = l0op::Contiguous(rsvdBlockCount, uniqueExecutor.get());
143+ auto metaC = l0op::Contiguous(metadata, uniqueExecutor.get());
144+ CHECK_RET(queryC && keyC && valueC && doutC && outC && lseC && idxC && cntC && metaC, ACLNN_ERR_INNER_NULLPTR);
145+ 
146+ const aclTensor *attenC = nullptr;
147+ if (attenMaskOptional != nullptr) {
148+ attenC = l0op::Contiguous(attenMaskOptional, uniqueExecutor.get());
149+ CHECK_RET(attenC != nullptr, ACLNN_ERR_INNER_NULLPTR);
150+ }
151+ const aclTensor *cuQC = nullptr;
152+ if (cuSeqLengthsOptional != nullptr) {
153+ cuQC = l0op::Contiguous(cuSeqLengthsOptional, uniqueExecutor.get());
154+ CHECK_RET(cuQC != nullptr, ACLNN_ERR_INNER_NULLPTR);
155+ }
156+ const aclTensor *cuKvC = nullptr;
157+ if (cuSeqLengthsKvOptional != nullptr) {
158+ cuKvC = l0op::Contiguous(cuSeqLengthsKvOptional, uniqueExecutor.get());
159+ CHECK_RET(cuKvC != nullptr, ACLNN_ERR_INNER_NULLPTR);
160+ }
161+ const aclTensor *sequsedQC = nullptr;
162+ if (sequsedQOptional != nullptr) {
163+ sequsedQC = l0op::Contiguous(sequsedQOptional, uniqueExecutor.get());
164+ CHECK_RET(sequsedQC != nullptr, ACLNN_ERR_INNER_NULLPTR);
165+ }
166+ const aclTensor *sequsedKvC = nullptr;
167+ if (sequsedKvOptional != nullptr) {
168+ sequsedKvC = l0op::Contiguous(sequsedKvOptional, uniqueExecutor.get());
169+ CHECK_RET(sequsedKvC != nullptr, ACLNN_ERR_INNER_NULLPTR);
170+ }
171+ 
172+ auto outs = l0op::GenericBlockSparseAttentionGrad(
173+ queryC, keyC, valueC, doutC, outC, lseC, idxC, cntC, metaC, attenC, cuQC, cuKvC, sequsedQC, sequsedKvC,
174+ blockShape, isPackedGqa, qInputLayout, kvInputLayout, scaleValue, maskType, softmaxPrecision, windowSizeLeft,
175+ windowSizeRight, uniqueExecutor.get());
176+ CHECK_RET(outs[0] != nullptr && outs[1] != nullptr && outs[2] != nullptr, ACLNN_ERR_INNER_NULLPTR);
177+ 
178+ auto dqView = l0op::ViewCopy(outs[0], dQuery, uniqueExecutor.get());
179+ auto dkView = l0op::ViewCopy(outs[1], dKey, uniqueExecutor.get());
180+ auto dvView = l0op::ViewCopy(outs[2], dValue, uniqueExecutor.get());
181+ CHECK_RET(dqView != nullptr && dkView != nullptr && dvView != nullptr, ACLNN_ERR_INNER_NULLPTR);
182+ 
183+ *workspaceSize = uniqueExecutor->GetWorkspaceSize();
184+ uniqueExecutor.ReleaseTo(executor);
185+ return ACLNN_SUCCESS;
186+}
187+ 
188+__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttentionGrad(void *workspace,
189+ uint64_t workspaceSize,
190+ aclOpExecutor *executor,
191+ const aclrtStream stream)
192+{
193+ L2_DFX_PHASE_2(aclnnGenericBlockSparseAttentionGrad);
194+ return CommonOpExecutorRun(workspace, workspaceSize, executor, stream);
195+}
196+ 
197+#ifdef __cplusplus
198+}
199+#endif
@@ -0,0 +1,45 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef ACLNN_GENERIC_SPARSE_ATTENTION_GRAD_H
12+#define ACLNN_GENERIC_SPARSE_ATTENTION_GRAD_H
13+ 
14+#include "aclnn/acl_meta.h"
15+ 
16+#ifdef __cplusplus
17+extern "C" {
18+#endif
19+ 
20+/**
21+ * @brief First-stage API: compute workspace size for GenericBlockSparseAttentionGrad.
22+ * @domain aclnn_ops_train
23+ */
24+__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttentionGradGetWorkspaceSize(
25+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *dout, const aclTensor *out,
26+ const aclTensor *lse, const aclTensor *rsvdBlockIdx, const aclTensor *rsvdBlockCount, const aclTensor *metadata,
27+ const aclTensor *attenMaskOptional, const aclTensor *cuSeqLengthsOptional, const aclTensor *cuSeqLengthsKvOptional,
28+ const aclTensor *sequsedQOptional, const aclTensor *sequsedKvOptional, const aclIntArray *blockShape,
29+ int64_t isPackedGqa, char *qInputLayout, char *kvInputLayout, double scaleValue, int64_t maskType,
30+ int64_t softmaxPrecision, int64_t windowSizeLeft, int64_t windowSizeRight, aclTensor *dQuery, aclTensor *dKey,
31+ aclTensor *dValue, uint64_t *workspaceSize, aclOpExecutor **executor);
32+ 
33+/**
34+ * @brief Second-stage API: execute GenericBlockSparseAttentionGrad.
35+ */
36+__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttentionGrad(void *workspace,
37+ uint64_t workspaceSize,
38+ aclOpExecutor *executor,
39+ const aclrtStream stream);
40+ 
41+#ifdef __cplusplus
42+}
43+#endif
44+ 
45+#endif // ACLNN_GENERIC_SPARSE_ATTENTION_GRAD_H
@@ -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 generic_block_sparse_attention_grad.cpp
13+ * \brief L0 AICore launcher for GenericBlockSparseAttentionGrad.
14+ */
15+ 
16+#include "generic_block_sparse_attention_grad.h"
17+#include "opdev/make_op_executor.h"
18+#include "opdev/op_dfx.h"
19+ 
20+using namespace op;
21+ 
22+namespace l0op {
23+ 
24+OP_TYPE_REGISTER(GenericBlockSparseAttentionGrad);
25+ 
26+const std::array<const aclTensor *, 3> GenericBlockSparseAttentionGrad(
27+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *dout, const aclTensor *out,
28+ const aclTensor *lse, const aclTensor *rsvdBlockIdx, const aclTensor *rsvdBlockCount, const aclTensor *metadata,
29+ const aclTensor *attenMaskOptional, const aclTensor *cuSeqLengthsOptional, const aclTensor *cuSeqLengthsKvOptional,
30+ const aclTensor *sequsedQOptional, const aclTensor *sequsedKvOptional, const aclIntArray *blockShape,
31+ int64_t isPackedGqa, char *qInputLayout, char *kvInputLayout, double scaleValue, int64_t maskType,
32+ int64_t softmaxPrecision, int64_t windowSizeLeft, int64_t windowSizeRight, aclOpExecutor *executor)
33+{
34+ const char *safeKvLayout = (kvInputLayout != nullptr) ? kvInputLayout : qInputLayout;
35+ L0_DFX(GenericBlockSparseAttentionGrad, query, key, value, dout, out, lse, rsvdBlockIdx, rsvdBlockCount, metadata,
36+ attenMaskOptional, cuSeqLengthsOptional, cuSeqLengthsKvOptional, blockShape, isPackedGqa, qInputLayout,
37+ safeKvLayout, scaleValue, maskType, softmaxPrecision, windowSizeLeft, windowSizeRight);
38+ 
39+ const aclTensor *attenMaskTensor =
40+ (attenMaskOptional != nullptr) ? attenMaskOptional :
41+ executor->AllocTensor(DataType::DT_BOOL, Format::FORMAT_ND, Format::FORMAT_ND);
42+ const aclTensor *cuSeqTensor = (cuSeqLengthsOptional != nullptr) ?
43+ cuSeqLengthsOptional :
44+ executor->AllocTensor(DataType::DT_INT64, Format::FORMAT_ND, Format::FORMAT_ND);
45+ const aclTensor *cuSeqKvTensor =
46+ (cuSeqLengthsKvOptional != nullptr) ?
47+ cuSeqLengthsKvOptional :
48+ executor->AllocTensor(DataType::DT_INT64, Format::FORMAT_ND, Format::FORMAT_ND);
49+ const aclTensor *sequsedQTensor =
50+ (sequsedQOptional != nullptr) ? sequsedQOptional :
51+ executor->AllocTensor(DataType::DT_INT32, Format::FORMAT_ND, Format::FORMAT_ND);
52+ const aclTensor *sequsedKvTensor =
53+ (sequsedKvOptional != nullptr) ?
54+ sequsedKvOptional :
55+ executor->AllocTensor(DataType::DT_INT32, Format::FORMAT_ND, Format::FORMAT_ND);
56+ 
57+ const int64_t defaultBlockShape[] = {1, 128};
58+ const aclIntArray *blockShapeAttr =
59+ (blockShape != nullptr) ? blockShape : executor->AllocIntArray(defaultBlockShape, 2);
60+ 
61+ auto dQuery = executor->AllocTensor(query->GetDataType(), Format::FORMAT_ND, Format::FORMAT_ND);
62+ auto dKey = executor->AllocTensor(key->GetDataType(), Format::FORMAT_ND, Format::FORMAT_ND);
63+ auto dValue = executor->AllocTensor(value->GetDataType(), Format::FORMAT_ND, Format::FORMAT_ND);
64+ 
65+ auto ret = INFER_SHAPE(
66+ GenericBlockSparseAttentionGrad,
67+ OP_INPUT(query, key, value, dout, out, lse, rsvdBlockIdx, rsvdBlockCount, metadata, attenMaskTensor,
68+ cuSeqTensor, cuSeqKvTensor, sequsedQTensor, sequsedKvTensor),
69+ OP_OUTPUT(dQuery, dKey, dValue),
70+ OP_ATTR(blockShapeAttr, static_cast<int64_t>(isPackedGqa), qInputLayout, safeKvLayout,
71+ static_cast<float>(scaleValue), static_cast<int64_t>(maskType), static_cast<int64_t>(softmaxPrecision),
72+ static_cast<int64_t>(windowSizeLeft), static_cast<int64_t>(windowSizeRight)));
73+ if (ret != ACLNN_SUCCESS) {
74+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "GenericBlockSparseAttentionGrad infer shape failed.");
75+ return {nullptr, nullptr, nullptr};
76+ }
77+ 
78+ ADD_TO_LAUNCHER_LIST_AICORE(
79+ GenericBlockSparseAttentionGrad,
80+ OP_INPUT(query, key, value, dout, out, lse, rsvdBlockIdx, rsvdBlockCount, metadata, attenMaskTensor,
81+ cuSeqTensor, cuSeqKvTensor, sequsedQTensor, sequsedKvTensor),
82+ OP_OUTPUT(dQuery, dKey, dValue),
83+ OP_ATTR(blockShapeAttr, static_cast<int64_t>(isPackedGqa), qInputLayout, safeKvLayout,
84+ static_cast<float>(scaleValue), static_cast<int64_t>(maskType), static_cast<int64_t>(softmaxPrecision),
85+ static_cast<int64_t>(windowSizeLeft), static_cast<int64_t>(windowSizeRight)));
86+ 
87+ return {dQuery, dKey, dValue};
88+}
89+ 
90+} // namespace l0op
@@ -0,0 +1,27 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef L0_GENERIC_SPARSE_ATTENTION_GRAD_H
12+#define L0_GENERIC_SPARSE_ATTENTION_GRAD_H
13+ 
14+#include <array>
15+#include "opdev/op_executor.h"
16+ 
17+namespace l0op {
18+const std::array<const aclTensor *, 3> GenericBlockSparseAttentionGrad(
19+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *dout, const aclTensor *out,
20+ const aclTensor *lse, const aclTensor *rsvdBlockIdx, const aclTensor *rsvdBlockCount, const aclTensor *metadata,
21+ const aclTensor *attenMaskOptional, const aclTensor *cuSeqLengthsOptional, const aclTensor *cuSeqLengthsKvOptional,
22+ const aclTensor *sequsedQOptional, const aclTensor *sequsedKvOptional, const aclIntArray *blockShape,
23+ int64_t isPackedGqa, char *qInputLayout, char *kvInputLayout, double scaleValue, int64_t maskType,
24+ int64_t softmaxPrecision, int64_t windowSizeLeft, int64_t windowSizeRight, aclOpExecutor *executor);
25+} // namespace l0op
26+ 
27+#endif
@@ -0,0 +1,247 @@
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 addr_compute.h
13+ * \brief Metadata-driven task scheduling for GSAG (design §3.1.2 / §4.2).
14+ * Atomic unit (b,n2,j) stays on one AIC; g=0..G-1 continuous; KV L1 reuse.
15+ * count is further tiled by baseM (design §3.1.2 cost model).
16+ */
17+ 
18+#pragma once
19+#include "common_header.h"
20+#include "../../../generic_block_sparse_attention_grad_metadata/op_kernel/generic_block_sparse_attention_grad_metadata.h"
21+ 
22+using namespace AscendC;
23+using namespace optiling;
24+ 
25+namespace GSAG_ARC35 {
26+ 
27+template <typename GSAG_TYPE>
28+class AddrComputeModule {
29+ using TILING_CLASS = typename GSAG_TYPE::tiling_class;
30+ static constexpr uint32_t INPUT_LAYOUT = GSAG_TYPE::input_layout;
31+ 
32+public:
33+ __aicore__ inline void Init(const TILING_CLASS *tilingData, __gm__ uint8_t *cuSeqQ, __gm__ uint8_t *cuSeqKv,
34+ __gm__ uint8_t *sequsedQ, __gm__ uint8_t *sequsedKv, __gm__ uint8_t *rsvdBlockIdx,
35+ __gm__ uint8_t *rsvdBlockCount, __gm__ uint8_t *metadata)
36+ {
37+ tilingData_ = tilingData;
38+ cuSeqQ_ = cuSeqQ;
39+ cuSeqKv_ = cuSeqKv;
40+ sequsedQ_ = sequsedQ;
41+ sequsedKv_ = sequsedKv;
42+ rsvdBlockIdx_ = rsvdBlockIdx;
43+ rsvdBlockCount_ = rsvdBlockCount;
44+ metadata_ = reinterpret_cast<__gm__ int64_t *>(metadata);
45+ 
46+ cubeCoreIdx_ = GetBlockIdx();
47+ if ASCEND_IS_AIV {
48+ cubeCoreIdx_ = GetBlockIdx() / 2;
49+ }
50+ 
51+ constInfo_.q_head_num = static_cast<int32_t>(tilingData->qHeadNum);
52+ constInfo_.kv_head_num = static_cast<int32_t>(tilingData->kvHeadNum);
53+ constInfo_.block_x = static_cast<int32_t>(tilingData->BlockX);
54+ constInfo_.block_y = static_cast<int32_t>(tilingData->BlockY);
55+ constInfo_.head_dim = static_cast<int32_t>(tilingData->headDim);
56+ constInfo_.max_s1 = static_cast<int32_t>(tilingData->maxS1);
57+ constInfo_.num_j = static_cast<int32_t>(tilingData->numJ);
58+ constInfo_.group_size = static_cast<int32_t>(tilingData->qGroup);
59+ baseM_ = static_cast<int32_t>(tilingData->baseM);
60+ 
61+ taskStart_ = static_cast<int32_t>(metadata_[CORE_TASK_START_OFFSET + cubeCoreIdx_]);
62+ taskEnd_ = static_cast<int32_t>(metadata_[CORE_TASK_END_OFFSET + cubeCoreIdx_]);
63+ cursor_ = taskStart_;
64+ lastB_ = -1;
65+ lastN2_ = -1;
66+ lastJ_ = -1;
67+ kvPingPong_ = 0;
68+ s1Offset_ = 0;
69+ s1Remain_ = 0;
70+ curCount_ = 0;
71+ inMetaTask_ = false;
72+ }
73+ 
74+ __aicore__ inline void GetRunTimeInfo(RunTimeInfo &info)
75+ {
76+ info = {};
77+ if (!inMetaTask_) {
78+ if (cursor_ >= taskEnd_) {
79+ info.need_compute = 0;
80+ return;
81+ }
82+ if (!LoadMetaTask()) {
83+ info.need_compute = 0;
84+ return;
85+ }
86+ }
87+ 
88+ const int32_t m = s1Remain_ > baseM_ ? baseM_ : s1Remain_;
89+ FillRunTimeInfo(info, m);
90+ 
91+ s1Offset_ += m;
92+ s1Remain_ -= m;
93+ if (s1Remain_ <= 0) {
94+ inMetaTask_ = false;
95+ cursor_++;
96+ }
97+ }
98+ 
99+private:
100+ __aicore__ inline bool LoadMetaTask()
101+ {
102+ while (cursor_ < taskEnd_) {
103+ const uint32_t base = TASK_LIST_OFFSET + static_cast<uint32_t>(cursor_) * TASK_ENTRY_SIZE;
104+ curB_ = static_cast<int32_t>(metadata_[base + TASK_B]);
105+ curN2_ = static_cast<int32_t>(metadata_[base + TASK_N2]);
106+ curJ_ = static_cast<int32_t>(metadata_[base + TASK_J]);
107+ curG_ = static_cast<int32_t>(metadata_[base + TASK_G]);
108+ 
109+ if constexpr (INPUT_LAYOUT == TND) {
110+ curQPrefix_ = GetSeqPrefix(curB_, cuSeqQ_);
111+ curKvPrefix_ = GetSeqPrefix(curB_, cuSeqKv_);
112+ curActS1_ = GetSeqUsedLen(curB_, sequsedQ_, cuSeqQ_);
113+ curActS2_ = GetSeqUsedLen(curB_, sequsedKv_, cuSeqKv_);
114+ } else {
115+ curQPrefix_ = 0;
116+ curKvPrefix_ = 0;
117+ curActS1_ = tilingData_->qSeqLen;
118+ curActS2_ = tilingData_->kvSeqLen;
119+ }
120+ 
121+ const int64_t countOffset =
122+ (static_cast<int64_t>(curB_) * constInfo_.kv_head_num + curN2_) * constInfo_.num_j + curJ_;
123+ curCount_ = reinterpret_cast<__gm__ int32_t *>(rsvdBlockCount_)[countOffset];
124+ // Guard against corrupt / out-of-range counts (avoids GetValue into -1 pad → AIC 264).
125+ if (curCount_ < 0) {
126+ curCount_ = 0;
127+ } else if (curCount_ > constInfo_.max_s1) {
128+ curCount_ = constInfo_.max_s1;
129+ }
130+ curIdxBase_ = countOffset * static_cast<int64_t>(constInfo_.max_s1);
131+ 
132+ curS2Start_ = curJ_ * constInfo_.block_y;
133+ curKvBlockLen_ = constInfo_.block_y;
134+ if (curS2Start_ + curKvBlockLen_ > curActS2_) {
135+ curKvBlockLen_ = static_cast<int32_t>(curActS2_ - curS2Start_);
136+ }
137+ 
138+ if (curCount_ > 0 && curKvBlockLen_ > 0) {
139+ s1Offset_ = 0;
140+ s1Remain_ = curCount_;
141+ inMetaTask_ = true;
142+ return true;
143+ }
144+ cursor_++;
145+ }
146+ return false;
147+ }
148+ 
149+ __aicore__ inline void FillRunTimeInfo(RunTimeInfo &info, int32_t m)
150+ {
151+ const int32_t n1Cur = curN2_ * constInfo_.group_size + curG_;
152+ const bool sameKv = (curB_ == lastB_ && curN2_ == lastN2_ && curJ_ == lastJ_);
153+ if (!sameKv) {
154+ kvPingPong_ = 1 - kvPingPong_;
155+ lastB_ = curB_;
156+ lastN2_ = curN2_;
157+ lastJ_ = curJ_;
158+ }
159+ 
160+ info.taskId = cursor_;
161+ info.bIdx = curB_;
162+ info.n2Idx = curN2_;
163+ info.gIdx = curG_;
164+ info.n1Idx = n1Cur;
165+ info.kvBlockIdx = curJ_;
166+ info.s2Idx = curS2Start_;
167+ info.s1Idx = s1Offset_;
168+ info.last_q_seq_sum = static_cast<int32_t>(curQPrefix_);
169+ info.last_kv_seq_sum = static_cast<int32_t>(curKvPrefix_);
170+ info.cur_q_seq_len = static_cast<int32_t>(curActS1_);
171+ info.cur_kv_seq_len = static_cast<int32_t>(curActS2_);
172+ info.s1Len = m;
173+ info.s2Len = curKvBlockLen_;
174+ // RoundUp(m, C0_SIZE) for NZ fractal / Fixpipe mSize.
175+ info.s1LenAlign = RoundUp(static_cast<int64_t>(m), static_cast<int64_t>(C0_SIZE));
176+ info.s2LenAlign = RoundUp(static_cast<int64_t>(curKvBlockLen_), static_cast<int64_t>(C0_SIZE));
177+ info.sparseIdxOffset = curIdxBase_ + s1Offset_;
178+ info.sparseCount = m;
179+ info.use_sparse_gather = 1;
180+ // First tile of a new (b,n2,j): reload KV into L1
181+ info.need_copy_kv = sameKv ? 0 : 1;
182+ info.kv_ping_pong_idx = kvPingPong_;
183+ info.mask_type = static_cast<int32_t>(tilingData_->maskType);
184+ info.keyGmOffset = GetQKVGmOffset<INPUT_LAYOUT>(curKvPrefix_, curActS2_, constInfo_.kv_head_num,
185+ constInfo_.head_dim, curB_, curS2Start_, curN2_);
186+ info.lseGmOffset = GetLseGmOffset<INPUT_LAYOUT>(curQPrefix_, curActS1_, constInfo_.q_head_num, curB_, 0, n1Cur);
187+ info.sftgGmOffset =
188+ GetSftgGmOffset<INPUT_LAYOUT>(curQPrefix_, curActS1_, constInfo_.q_head_num, curB_, 0, n1Cur);
189+ info.queryGmOffset = 0;
190+ info.need_compute = 1;
191+ 
192+ // Last tile of last g on this KV block → dump dK/dV
193+ const bool lastS1Tile = (s1Remain_ - m) <= 0;
194+ info.is_singlekv_last = 0;
195+ if (lastS1Tile) {
196+ const int32_t nextCursor = cursor_ + 1;
197+ if (nextCursor >= taskEnd_) {
198+ info.is_singlekv_last = 1;
199+ } else {
200+ const uint32_t nextBase = TASK_LIST_OFFSET + static_cast<uint32_t>(nextCursor) * TASK_ENTRY_SIZE;
201+ if (static_cast<int32_t>(metadata_[nextBase + TASK_B]) != curB_ ||
202+ static_cast<int32_t>(metadata_[nextBase + TASK_N2]) != curN2_ ||
203+ static_cast<int32_t>(metadata_[nextBase + TASK_J]) != curJ_) {
204+ info.is_singlekv_last = 1;
205+ }
206+ }
207+ }
208+ }
209+ 
210+ const TILING_CLASS *tilingData_{nullptr};
211+ __gm__ uint8_t *cuSeqQ_{nullptr};
212+ __gm__ uint8_t *cuSeqKv_{nullptr};
213+ __gm__ uint8_t *sequsedQ_{nullptr};
214+ __gm__ uint8_t *sequsedKv_{nullptr};
215+ __gm__ uint8_t *rsvdBlockIdx_{nullptr};
216+ __gm__ uint8_t *rsvdBlockCount_{nullptr};
217+ __gm__ int64_t *metadata_{nullptr};
218+ ConstInfo constInfo_{};
219+ int32_t cubeCoreIdx_{0};
220+ int32_t taskStart_{0};
221+ int32_t taskEnd_{0};
222+ int32_t cursor_{0};
223+ int32_t lastB_{-1};
224+ int32_t lastN2_{-1};
225+ int32_t lastJ_{-1};
226+ int32_t kvPingPong_{0};
227+ int32_t baseM_{128};
228+ 
229+ // Current metadata task state (for baseM tiling of count)
230+ bool inMetaTask_{false};
231+ int32_t curB_{0};
232+ int32_t curN2_{0};
233+ int32_t curJ_{0};
234+ int32_t curG_{0};
235+ int32_t curCount_{0};
236+ int64_t curIdxBase_{0};
237+ int32_t curS2Start_{0};
238+ int32_t curKvBlockLen_{0};
239+ int64_t curQPrefix_{0};
240+ int64_t curKvPrefix_{0};
241+ int64_t curActS1_{0};
242+ int64_t curActS2_{0};
243+ int32_t s1Offset_{0};
244+ int32_t s1Remain_{0};
245+};
246+ 
247+} // namespace GSAG_ARC35
@@ -0,0 +1,192 @@
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 common_header.h
13+ * \brief Flags / layout / RunTimeInfo for GenericBlockSparseAttentionGrad (design §3.5 / §4.1).
14+ */
15+ 
16+#ifndef GSAG_ARC35_COMMON_HEADER_H
17+#define GSAG_ARC35_COMMON_HEADER_H
18+ 
19+namespace GSAG_ARC35 {
20+ 
21+#define SET_FLAG(trigger, waiter, e) AscendC::SetFlag<AscendC::HardEvent::trigger##_##waiter>((e))
22+#define WAIT_FLAG(trigger, waiter, e) AscendC::WaitFlag<AscendC::HardEvent::trigger##_##waiter>((e))
23+ 
24+static constexpr uint32_t BSND = 0;
25+static constexpr uint32_t BNSD = 1;
26+static constexpr uint32_t TND = 2;
27+ 
28+static constexpr uint32_t QK = 10;
29+static constexpr uint32_t DYV = 11;
30+static constexpr uint32_t DQ = 12;
31+static constexpr uint32_t DK = 13;
32+static constexpr uint32_t DV = 14;
33+ 
34+static constexpr uint32_t C0_SIZE = 16;
35+static constexpr uint32_t BLOCK_SIZE = 32; // Ascend DataCopy block unit (bytes)
36+// MIX 1:2 AIV split: each half must be a full C0 fractal → mAlign multiple of 2 * C0_SIZE.
37+static constexpr int32_t AIV_M_SPLIT_ALIGN = static_cast<int32_t>(C0_SIZE * 2);
38+static constexpr uint32_t FLAG_CUBE_POST = 4; // end-of-main only: Cube → Vec before SendVecPost
39+// Cube → Vec: Cube finished prior MM345 and is about to Wait gather (taskId>0).
40+static constexpr uint32_t FLAG_C_GATHER_ARM = 5;
41+// Cube → Vec: MM345(last) finished; dq_sel ready for Scatter (mode-4 base/+16).
42+static constexpr uint32_t FLAG_C_MM345_DONE = 6;
43+// Ping-pong gather sync (FAG-style IDs 7/9): Q/dO L1 handoff Vector → Cube.
44+static constexpr uint32_t FLAG_V_GATHER_C_PING = 7;
45+static constexpr uint32_t FLAG_V_GATHER_C_PONG = 9;
46+// MM12→Softmax per ping-pong slot. Pong uses mode-4 flags 13/14 (mode-2 ping 0/1).
47+static constexpr uint32_t FLAG_C1_V1_PING = 0;
48+static constexpr uint32_t FLAG_C1_V1_PONG = 13;
49+static constexpr uint32_t FLAG_C2_V2_PING = 1;
50+static constexpr uint32_t FLAG_C2_V2_PONG = 14;
51+// Softmax(last) → MM345(last) (single producer per round).
52+static constexpr uint32_t FLAG_V1_C3 = 2;
53+static constexpr uint32_t FLAG_V2_C45 = 3;
54+// Cube↔Vec without AIV0/AIV1 subblock flag split.
55+static constexpr uint32_t CROSS_CORE_SYNC_MODE_2 = 2;
56+// FAG arch35: mode=4 + flag / flag+16 for AIV0/AIV1 subblock isolation.
57+static constexpr uint32_t CROSS_CORE_SYNC_MODE = 4;
58+static constexpr uint32_t AIV0_AIV1_FLAG_OFFSET = 16;
59+ 
60+struct ConstInfo {
61+ int32_t q_head_num{0};
62+ int32_t kv_head_num{0};
63+ int32_t block_x{0};
64+ int32_t block_y{0};
65+ int32_t head_dim{0};
66+ int32_t max_s1{0};
67+ int32_t num_j{0};
68+ int32_t group_size{0};
69+};
70+ 
71+/**
72+ * Per-task runtime info. Cube/Vec reuse s1Len/s2Len as m/n (count / kvBlockLen).
73+ * Sparse Gather uses sparseIdxOffset + count; KV share via need_copy_kv.
74+ */
75+struct RunTimeInfo {
76+ int32_t taskId{0};
77+ int32_t bIdx{0};
78+ int32_t n1Idx{0}; // n1_cur = n2*G + g
79+ int32_t n2Idx{0};
80+ int32_t gIdx{0};
81+ int32_t kvBlockIdx{0}; // j
82+ int32_t s1Idx{0}; // unused for sparse gather path; kept for VecOp compatibility
83+ int32_t s2Idx{0}; // s2_start = j * By
84+ int32_t last_q_seq_sum{0};
85+ int32_t last_kv_seq_sum{0};
86+ int32_t cur_q_seq_len{0};
87+ int32_t cur_kv_seq_len{0};
88+ int32_t need_compute{0};
89+ int32_t need_copy_kv{0};
90+ int32_t kv_ping_pong_idx{0};
91+ int32_t is_singlekv_last{0};
92+ int32_t use_sparse_gather{1};
93+ int32_t mask_type{0};
94+ int64_t s1Len{0}; // m = count
95+ int64_t s2Len{0}; // n = kv block len
96+ int64_t s1LenAlign{0};
97+ int64_t s2LenAlign{0};
98+ int64_t queryGmOffset{0}; // unused when gathering; Scatter/dQ base uses sparse path
99+ int64_t keyGmOffset{0};
100+ int64_t lseGmOffset{0};
101+ int64_t sftgGmOffset{0};
102+ int64_t sparseIdxOffset{0}; // base of sparseBlockIdx[b,n2,j,0]
103+ int64_t sparseCount{0};
104+};
105+ 
106+inline __aicore__ uint32_t max(const uint32_t a, const uint32_t b)
107+{
108+ return a > b ? a : b;
109+}
110+ 
111+template <typename T>
112+inline __aicore__ T CeilDiv(const T dividend, const T divisor)
113+{
114+ return (dividend + divisor - 1) / divisor;
115+}
116+ 
117+template <typename T>
118+inline __aicore__ T RoundUp(const T val, const T align)
119+{
120+ return (val + align - 1) / align * align;
121+}
122+ 
123+// MIX 1:2: dualDst + AIV1 NZ L1 only when each half is a C0_SIZE-row fractal.
124+__aicore__ inline bool GsagAivMSplit(int32_t mAlign)
125+{
126+ return (mAlign >= AIV_M_SPLIT_ALIGN) && ((mAlign % AIV_M_SPLIT_ALIGN) == 0);
127+}
128+ 
129+__aicore__ inline int64_t GetSeqLen(int32_t i, __gm__ uint8_t *seqLen)
130+{
131+ if (seqLen == nullptr) {
132+ return 0;
133+ }
134+ const __gm__ int64_t *cu = (__gm__ int64_t *)seqLen;
135+ return cu[i + 1] - cu[i];
136+}
137+ 
138+__aicore__ inline int64_t GetSeqPrefix(int32_t i, __gm__ uint8_t *seqLen)
139+{
140+ if (i <= 0 || seqLen == nullptr) {
141+ return 0;
142+ }
143+ return ((__gm__ int64_t *)seqLen)[i];
144+}
145+ 
146+// seqused stores per-batch compute lengths; cu stores packed-TND offsets.
147+// If seqused is absent, the effective compute length equals the packed length.
148+__aicore__ inline int64_t GetSeqUsedLen(int32_t i, __gm__ uint8_t *seqused, __gm__ uint8_t *cuSeqLen)
149+{
150+ if (seqused != nullptr) {
151+ return static_cast<int64_t>(((__gm__ int32_t *)seqused)[i]);
152+ }
153+ return GetSeqLen(i, cuSeqLen);
154+}
155+ 
156+template <uint32_t INPUT_LAYOUT>
157+__aicore__ inline int64_t GetQKVGmOffset(int64_t lastBatchSum, int64_t currentSeqLen, int64_t headNum, int64_t headDim,
158+ int64_t batchIdx, int64_t seqlenIdx, int64_t nIdx)
159+{
160+ if constexpr (INPUT_LAYOUT == BSND) {
161+ return batchIdx * (currentSeqLen * headNum * headDim) + (seqlenIdx * headNum * headDim) + (nIdx * headDim);
162+ } else if constexpr (INPUT_LAYOUT == BNSD) {
163+ return batchIdx * (headNum * currentSeqLen * headDim) + (nIdx * currentSeqLen * headDim) +
164+ (seqlenIdx * headDim);
165+ } else {
166+ return lastBatchSum * (headNum * headDim) + (seqlenIdx * headNum * headDim) + (nIdx * headDim);
167+ }
168+}
169+ 
170+template <uint32_t INPUT_LAYOUT>
171+__aicore__ inline int64_t GetLseGmOffset(int64_t lastBatchSum, int64_t currentSeqLen, int64_t headNum, int64_t batchIdx,
172+ int64_t seqlenIdx, int64_t n1Idx)
173+{
174+ if constexpr (INPUT_LAYOUT == TND) {
175+ return lastBatchSum * headNum + (seqlenIdx * headNum) + n1Idx;
176+ }
177+ return batchIdx * (headNum * currentSeqLen) + n1Idx * currentSeqLen + seqlenIdx;
178+}
179+ 
180+template <uint32_t INPUT_LAYOUT>
181+__aicore__ inline int64_t GetSftgGmOffset(int64_t lastBatchSum, int64_t currentSeqLen, int64_t headNum,
182+ int64_t batchIdx, int64_t seqlenIdx, int64_t n1Idx)
183+{
184+ if constexpr (INPUT_LAYOUT == TND) {
185+ return lastBatchSum * headNum * 8 + n1Idx * currentSeqLen * 8 + seqlenIdx * 8;
186+ }
187+ return batchIdx * (headNum * currentSeqLen) * 8 + n1Idx * currentSeqLen * 8 + seqlenIdx * 8;
188+}
189+ 
190+} // namespace GSAG_ARC35
191+ 
192+#endif
@@ -0,0 +1,625 @@
1+/**
2+ * Copyright (c) 2025 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+#pragma once
11+#include "common_header.h"
12+using namespace AscendC;
13+ 
14+namespace GSAG_ARC35 {
15+ 
16+template <typename BSA_TYPE>
17+class CubeOp {
18+ using INPUT_TYPE = typename BSA_TYPE::input_type;
19+ static constexpr uint32_t INPUT_LAYOUT = BSA_TYPE::input_layout;
20+ using TILING_CLASS = typename BSA_TYPE::tiling_class;
21+ static constexpr bool DETERMINISTIC_ENABLE = BSA_TYPE::deterministic_enable;
22+ 
23+private:
24+ int32_t batch_num_;
25+ int32_t q_seq_len_;
26+ int32_t kv_seq_len_;
27+ int32_t q_group_;
28+ int32_t q_head_num_;
29+ int32_t kv_head_num_;
30+ int32_t head_dim_;
31+ int32_t head_dim_align_;
32+ int32_t event_ping_pong_flag{0};
33+ uint32_t q_stride_;
34+ uint32_t kv_stride_;
35+ // l1_tensor
36+ LocalTensor<INPUT_TYPE> query_l1_tensor_ping_;
37+ LocalTensor<INPUT_TYPE> query_l1_tensor_pong_;
38+ LocalTensor<INPUT_TYPE> key_l1_tensor_ping_;
39+ LocalTensor<INPUT_TYPE> key_l1_tensor_pong_;
40+ LocalTensor<INPUT_TYPE> value_l1_tensor_ping_;
41+ LocalTensor<INPUT_TYPE> value_l1_tensor_pong_;
42+ LocalTensor<INPUT_TYPE> dy_l1_tensor_ping_;
43+ LocalTensor<INPUT_TYPE> dy_l1_tensor_pong_;
44+ // l0_tensor
45+ LocalTensor<INPUT_TYPE> l0_a_tensor_ping_;
46+ LocalTensor<INPUT_TYPE> l0_a_tensor_pong_;
47+ LocalTensor<INPUT_TYPE> l0_b_tensor_ping_;
48+ LocalTensor<INPUT_TYPE> l0_b_tensor_pong_;
49+ LocalTensor<float> l0_c_tensor_ping_;
50+ LocalTensor<float> l0_c_tensor_pong_;
51+ // dk\dvL0C
52+ LocalTensor<float> l0_c_dk_tensor_;
53+ LocalTensor<float> l0_c_dv_tensor_;
54+ static constexpr int32_t L1_SIZE = 512 * 1024;
55+ static constexpr int32_t L0_AB_SIZE = 64 * 1024;
56+ static constexpr int32_t L0_C_SIZE = 256 * 1024;
57+ static constexpr int32_t BASE_BLOCK_SIZE = 128 * 128;
58+ TEventID event_ping_ = EVENT_ID3;
59+ TEventID event_pong_ = EVENT_ID4;
60+ GlobalTensor<int32_t> sparse_idx_gm_;
61+ GlobalTensor<float> dq_sel_workspace_;
62+ int32_t q_token_stride_{0};
63+ int32_t base_m_{128};
64+ int64_t dq_sel_slot_elems_{0};
65+ 
66+public:
67+ __aicore__ inline CubeOp(){};
68+ __aicore__ inline void Init(const TILING_CLASS *tilingData, TPipe *tPipe, TBuf<TPosition::A1> &l1_buffer,
69+ uint32_t l1_offset, const LocalTensor<INPUT_TYPE> &query_l1_tensor_ping,
70+ const LocalTensor<INPUT_TYPE> &query_l1_tensor_pong,
71+ const LocalTensor<INPUT_TYPE> &dy_l1_tensor_ping,
72+ const LocalTensor<INPUT_TYPE> &dy_l1_tensor_pong,
73+ __gm__ uint8_t *rsvdBlockIdx = nullptr, __gm__ uint8_t *workspace = nullptr)
74+ {
75+ this->batch_num_ = tilingData->batchNum;
76+ this->q_seq_len_ = tilingData->qSeqLen;
77+ this->kv_seq_len_ = tilingData->kvSeqLen;
78+ this->q_group_ = tilingData->qGroup;
79+ this->q_head_num_ = tilingData->qHeadNum;
80+ this->kv_head_num_ = tilingData->kvHeadNum;
81+ this->head_dim_ = tilingData->headDim;
82+ this->head_dim_align_ = RoundUp(head_dim_, static_cast<int32_t>(C0_SIZE));
83+ this->base_m_ = static_cast<int32_t>(tilingData->baseM);
84+ uint32_t base_m = tilingData->baseM;
85+ uint32_t base_n = tilingData->baseN;
86+ if constexpr (INPUT_LAYOUT == BSND) {
87+ q_stride_ = q_head_num_ * head_dim_;
88+ kv_stride_ = kv_head_num_ * head_dim_;
89+ } else if constexpr (INPUT_LAYOUT == BNSD) {
90+ q_stride_ = head_dim_;
91+ kv_stride_ = head_dim_;
92+ } else if constexpr (INPUT_LAYOUT == TND) {
93+ q_stride_ = q_head_num_ * head_dim_;
94+ kv_stride_ = kv_head_num_ * head_dim_;
95+ }
96+ 
97+ TBuf<TPosition::A2> l0_a_buffer_;
98+ TBuf<TPosition::B2> l0_b_buffer_;
99+ TBuf<TPosition::CO1> l0_c_buffer_;
100+ tPipe->InitBuffer(l0_a_buffer_, L0_AB_SIZE);