Merged
新增算子generic_block_sparse_attetnion #10628
新增算子generic_block_sparse_attetnion #10628
Merged
WangJinChengAdd on Aug 25
Total: 101 files changed+22418-0
@@ -0,0 +1,18 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# -----------------------------------------------------------------------------------------------------------
9+ 
10+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
11+if(NOT ENABLE_TEST AND NOT BENCHMARK)
12+ list(REMOVE_ITEM CURRENT_DIRS tests)
13+endif()
14+foreach(SUB_DIR ${CURRENT_DIRS})
15+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
16+ add_subdirectory(${SUB_DIR})
17+ endif()
18+endforeach()
@@ -0,0 +1,223 @@
1+# GenericBlockSparseAttention
2+ 
3+## 产品支持情况
4+ 
5+| 产品 | 是否支持 |
6+| ------------------------------------------------------------ | :------: |
7+| <term>Ascend 950PR/Ascend 950DT</term> | √ |
8+| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | √ |
9+| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | √ |
10+| <term>Atlas 200I/500 A2 推理产品</term> | × |
11+| <term>Atlas 推理系列产品</term> | × |
12+| <term>Atlas 训练系列产品</term> | × |
13+ 
14+## 功能说明
15+ 
16+- 算子功能:
17+ 
18+ `GenericBlockSparseAttention`是基于CATLASS模板库实现的高性能块稀疏注意力算子,支持沿S轴的块级稀疏模式。通过`sparseBlockIdx`指定每个Q块选择的KV块,通过`sparseBlockCount`指定每个Q块实际保留的KV块数量。调用前须先执行`aclnnGenericBlockSparseAttentionMetadata`生成`metadataOptional`。
19+ 
20+ 典型调用流程如下:
21+ 
22+ 1. 准备`query`、`key`、`value`、`sparseBlockIdx`、`sparseBlockCount`、`cuSeqLengthsQOptional`、`cuSeqLengthsKvOptional`、`blockTableOptional`等输入。
23+ 2. 调用`aclnnGenericBlockSparseAttentionMetadata`生成`metadataOptional`。
24+ 3. 调用`aclnnGenericBlockSparseAttention`,将上一步得到的`metadataOptional`传入主算子。
25+ 
26+- 计算公式:
27+ 
28+ 稀疏块大小:$blockShapeX \times blockShapeY$
29+ 
30+ $$
31+ attentionOut = Softmax(scaleValue \cdot query \cdot key_{sparse}^{T} + atten\_mask) \cdot value_{sparse}
32+ $$
33+ 
34+ 其中$key_{sparse}$、$value_{sparse}$为按`sparseBlockIdx`/`sparseBlockCount`从Paged KV Cache中选取的KV块。
35+ 
36+## 参数说明
37+ 
38+> **说明:**<br>
39+> 参数维度含义:B表示Batch Size,T表示Total tokens,N表示Head Num,D表示Head Dim,topK表示`sparseBlockIdx`最后一维`maxSparseBlockCount`。<br>
40+> TND中的N为query的headNum(记为N1),PAGED_BBND中的N为key/value的headNum(记为N2)。GQA下N1与N2可以不同,约束见下文。
41+ 
42+<table style="undefined;table-layout: fixed; width: 1200px"><colgroup>
43+ <col style="width: 220px">
44+ <col style="width: 120px">
45+ <col style="width: 520px">
46+ <col style="width: 180px">
47+ <col style="width: 100px">
48+ </colgroup>
49+ <thead>
50+ <tr>
51+ <th>参数名</th>
52+ <th>输入/输出/属性</th>
53+ <th>描述</th>
54+ <th>数据类型</th>
55+ <th>数据格式</th>
56+ </tr>
57+ </thead>
58+ <tbody>
59+ <tr>
60+ <td>query</td>
61+ <td>输入</td>
62+ <td>公式中的query。layoutQ为"TND"时,shape为[T, N, D],N为query的headNum(N1)。</td>
63+ <td>FLOAT16、BFLOAT16、FLOAT8_E4M3FN</td>
64+ <td>ND</td>
65+ </tr>
66+ <tr>
67+ <td>key</td>
68+ <td>输入</td>
69+ <td>公式中的key。layoutKv为"PAGED_BBND"时,shape为[numBlocks, blockSize, N, D],N为kv的headNum(N2)。</td>
70+ <td>FLOAT16、BFLOAT16、FLOAT8_E4M3FN</td>
71+ <td>ND</td>
72+ </tr>
73+ <tr>
74+ <td>value</td>
75+ <td>输入</td>
76+ <td>公式中的value,shape与key一致。</td>
77+ <td>FLOAT16、BFLOAT16、FLOAT8_E4M3FN</td>
78+ <td>ND</td>
79+ </tr>
80+ <tr>
81+ <td>sparseBlockIdx</td>
82+ <td>输入</td>
83+ <td>稀疏块索引。TND + isPackedGQA=1时,shape为[N, totalQBlocks, topK],N为kv的headNum(N2)。</td>
84+ <td>INT32</td>
85+ <td>ND</td>
86+ </tr>
87+ <tr>
88+ <td>sparseBlockCount</td>
89+ <td>输入</td>
90+ <td>每个Q块实际选择的KV块数量。TND + isPackedGQA=1时,shape为[N, totalQBlocks],N为kv的headNum(N2)。</td>
91+ <td>INT32</td>
92+ <td>ND</td>
93+ </tr>
94+ <tr>
95+ <td>cuSeqLengthsQOptional</td>
96+ <td>输入</td>
97+ <td>各batch中query序列长度前缀和,layoutQ为"TND"时必传,shape为[B+1,]。</td>
98+ <td>INT64</td>
99+ <td>ND</td>
100+ </tr>
101+ <tr>
102+ <td>cuSeqLengthsKvOptional</td>
103+ <td>输入</td>
104+ <td>各batch中key/value序列长度前缀和,layoutKv为"PAGED_BBND"时必传,shape为[B+1,]。</td>
105+ <td>INT64</td>
106+ <td>ND</td>
107+ </tr>
108+ <tr>
109+ <td>sequsedQOptional</td>
110+ <td>可选输入</td>
111+ <td>各batch中query实际有效长度;不传时按cu前缀和差分得到的存储长度处理。</td>
112+ <td>INT32</td>
113+ <td>ND</td>
114+ </tr>
115+ <tr>
116+ <td>sequsedKvOptional</td>
117+ <td>可选输入</td>
118+ <td>各batch中kv实际有效长度;不传时按cu前缀和差分得到的存储长度处理。</td>
119+ <td>INT32</td>
120+ <td>ND</td>
121+ </tr>
122+ <tr>
123+ <td>blockTableOptional</td>
124+ <td>输入</td>
125+ <td>PagedAttention页表,shape为[B, maxNumBlocksPerBatch]。</td>
126+ <td>INT32</td>
127+ <td>ND</td>
128+ </tr>
129+ <tr>
130+ <td>blockShape</td>
131+ <td>属性</td>
132+ <td>稀疏块形状[blockShapeX, blockShapeY],当前仅支持[1, 128]。</td>
133+ <td>INT64</td>
134+ <td>-</td>
135+ </tr>
136+ <tr>
137+ <td>isPackedGQA</td>
138+ <td>属性</td>
139+ <td>同group内qHead是否共享稀疏pattern,当前仅支持1。</td>
140+ <td>INT64</td>
141+ <td>-</td>
142+ </tr>
143+ <tr>
144+ <td>layoutQ</td>
145+ <td>属性</td>
146+ <td>query数据排布格式,当前仅支持"TND"。</td>
147+ <td>STRING</td>
148+ <td>-</td>
149+ </tr>
150+ <tr>
151+ <td>layoutKv</td>
152+ <td>属性</td>
153+ <td>key/value数据排布格式,当前仅支持"PAGED_BBND"。</td>
154+ <td>STRING</td>
155+ <td>-</td>
156+ </tr>
157+ <tr>
158+ <td>scaleValue</td>
159+ <td>属性</td>
160+ <td>缩放系数;传0时算子内按$1/\sqrt{D}$处理。</td>
161+ <td>DOUBLE</td>
162+ <td>-</td>
163+ </tr>
164+ <tr>
165+ <td>maskType</td>
166+ <td>属性</td>
167+ <td>掩码类型,当前仅支持1(内置causal mask)。</td>
168+ <td>INT64</td>
169+ <td>-</td>
170+ </tr>
171+ <tr>
172+ <td>quantType</td>
173+ <td>属性</td>
174+ <td>量化类型;当前支持0,Ascend 950上可选5。</td>
175+ <td>INT64</td>
176+ <td>-</td>
177+ </tr>
178+ <tr>
179+ <td>softmaxPrecision</td>
180+ <td>属性</td>
181+ <td>Softmax计算精度级别,取值0或1。</td>
182+ <td>INT64</td>
183+ <td>-</td>
184+ </tr>
185+ <tr>
186+ <td>returnSoftmaxlse</td>
187+ <td>属性</td>
188+ <td>是否输出softmaxLse,当前仅支持0。</td>
189+ <td>INT64</td>
190+ <td>-</td>
191+ </tr>
192+ <tr>
193+ <td>attentionOut</td>
194+ <td>输出</td>
195+ <td>公式中的attentionOut,数据类型和shape与query保持一致。</td>
196+ <td>FLOAT16、BFLOAT16</td>
197+ <td>ND</td>
198+ </tr>
199+ <tr>
200+ <td>softmaxLseOptional</td>
201+ <td>输出</td>
202+ <td>Softmax log-sum-exp中间结果;当前不支持,须传入nullptr。</td>
203+ <td>FLOAT</td>
204+ <td>ND</td>
205+ </tr>
206+ </tbody>
207+</table>
208+ 
209+## 约束说明
210+ 
211+- 调用前须先执行`aclnnGenericBlockSparseAttentionMetadata`生成`metadataOptional`,再调用本接口;metadata须与当前输入/属性配套,每次调用须重新生成。
212+- query/key/value的headDim(D)当前仅支持128;KV页blockSize当前仅支持128,且须等于blockShapeY。
213+- TND + isPackedGQA=1时:totalQBlocks按cuSeqLengthsQ差分得到的存储长度分块;sparse分块与QKV寻址均按该存储长度,不以seqused重切分;topK须≥`sparseBlockCount`中所有元素的最大值,当前上限为256。
214+- sequsedQOptional/sequsedKvOptional与cu前缀和同时传入时:分核/任务空间按各batch实际有效长度(seqused)累加;各batch的seqused元素须≤对应cu存储长度,且须与Metadata侧完全一致。
215+- 输入query、key、value的数据类型必须一致。
216+- 输入query的headNum为N1,输入key和value的headNum为N2,则N1 >= N2且N1 % N2 == 0;groupSize=N1/N2当前须≤128。
217+- PAGED_BBND下key/value仅dim0(物理页轴)可非连续;页内blockSize×N2×D须连续。
218+ 
219+## 调用说明
220+ 
221+| 调用方式 | 样例代码 | 说明 |
222+| -------- | -------- | ---- |
223+| aclnn API | [test_aclnn_generic_block_sparse_attention](./examples/test_aclnn_generic_block_sparse_attention.cpp) | 通过[aclnnGenericBlockSparseAttention](./docs/aclnnGenericBlockSparseAttention.md)两段式接口调用GenericBlockSparseAttention算子 |
@@ -0,0 +1,353 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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.cpp
13+ * \brief GenericBlockSparseAttention + Metadata 算子调用示例
14+ *
15+ * Regular path: layoutQ=TND, layoutKv=PAGED_BBND, maskType=1, blockShape=[1,128], D=128.
16+ */
17+ 
18+#include <algorithm>
19+#include <cmath>
20+#include <cstdint>
21+#include <cstring>
22+#include <iostream>
23+#include <numeric>
24+#include <vector>
25+#include "acl/acl.h"
26+#include "aclnnop/aclnn_generic_block_sparse_attention.h"
27+#include "aclnnop/aclnn_generic_block_sparse_attention_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+uint16_t FloatToFp16(float f)
53+{
54+ uint32_t bits;
55+ std::memcpy(&bits, &f, sizeof(bits));
56+ uint32_t sign = (bits >> 31) & 0x1u;
57+ int32_t exp = static_cast<int32_t>((bits >> 23) & 0xffu) - 127 + 15;
58+ uint32_t mant = (bits >> 13) & 0x3ffu;
59+ if (exp <= 0) {
60+ return static_cast<uint16_t>(sign << 15);
61+ }
62+ if (exp >= 31) {
63+ return static_cast<uint16_t>((sign << 15) | 0x7c00u);
64+ }
65+ return static_cast<uint16_t>((sign << 15) | (static_cast<uint32_t>(exp) << 10) | mant);
66+}
67+ 
68+float Fp16ToFloat(uint16_t h)
69+{
70+ uint32_t sign = (h >> 15) & 0x1u;
71+ uint32_t exp = (h >> 10) & 0x1fu;
72+ uint32_t mant = h & 0x3ffu;
73+ uint32_t f;
74+ if (exp == 0) {
75+ f = (sign << 31) | (mant << 13);
76+ } else if (exp == 31) {
77+ f = (sign << 31) | 0x7f800000u | (mant << 13);
78+ } else {
79+ f = (sign << 31) | ((exp + 127u - 15u) << 23) | (mant << 13);
80+ }
81+ float result;
82+ std::memcpy(&result, &f, sizeof(result));
83+ return result;
84+}
85+ 
86+void PrintOutResult(const std::vector<int64_t> &shape, void **deviceAddr)
87+{
88+ auto size = GetShapeSize(shape);
89+ std::vector<uint16_t> resultData(size, 0);
90+ auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
91+ size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
92+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
93+ for (int64_t i = 0; i < size && i < 10; i++) {
94+ LOG_PRINT("result[%ld] is: %f\n", i, Fp16ToFloat(resultData[i]));
95+ }
96+}
97+ 
98+int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream)
99+{
100+ auto ret = aclInit(nullptr);
101+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
102+ ret = aclrtSetDevice(deviceId);
103+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
104+ ret = aclrtCreateContext(context, deviceId);
105+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
106+ ret = aclrtSetCurrentContext(*context);
107+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret); return ret);
108+ ret = aclrtCreateStream(stream);
109+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
110+ return 0;
111+}
112+ 
113+template <typename T>
114+int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
115+ aclDataType dataType, aclTensor **tensor)
116+{
117+ auto size = GetShapeSize(shape) * sizeof(T);
118+ if (size > 0) {
119+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
120+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
121+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
122+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
123+ } else {
124+ *deviceAddr = nullptr;
125+ }
126+ 
127+ std::vector<int64_t> strides(shape.size(), 1);
128+ for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; i--) {
129+ strides[i] = shape[i + 1] * strides[i + 1];
130+ }
131+ 
132+ *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
133+ shape.data(), shape.size(), *deviceAddr);
134+ return 0;
135+}
136+ 
137+std::vector<uint16_t> MakeFp16Data(int64_t size, float value)
138+{
139+ std::vector<uint16_t> data(static_cast<size_t>(size), FloatToFp16(value));
140+ return data;
141+}
142+ 
143+} // namespace
144+ 
145+int main()
146+{
147+ // 1. (固定写法)device/stream初始化,参考acl API手册
148+ // 根据自己的实际device填写deviceId
149+ int32_t deviceId = 0;
150+ aclrtContext context = nullptr;
151+ aclrtStream stream = nullptr;
152+ auto ret = Init(deviceId, &context, &stream);
153+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
154+ 
155+ // Regular path smoke case: TND query + PAGED_BBND KV
156+ int64_t B = 1;
157+ int64_t S1 = 4;
158+ int64_t S2 = 256;
159+ int64_t N1 = 4;
160+ int64_t N2 = 1;
161+ int64_t D = 128;
162+ int64_t topK = 2;
163+ int64_t blockSize = 128;
164+ int64_t blockShapeX = 1;
165+ double scaleValue = 1.0 / sqrt(static_cast<double>(D));
166+ 
167+ int64_t T = B * S1;
168+ int64_t maxBlocks = (S2 + blockSize - 1) / blockSize;
169+ int64_t totalQBlocks = T; // blockShapeX == 1
170+ 
171+ // 2. 构造输入与输出,需要根据API的接口自定义构造
172+ std::vector<int64_t> qShape = {T, N1, D};
173+ std::vector<int64_t> kvShape = {maxBlocks, blockSize, N2, D};
174+ std::vector<int64_t> sparseIdxShape = {N2, totalQBlocks, topK};
175+ std::vector<int64_t> sparseCountShape = {N2, totalQBlocks};
176+ std::vector<int64_t> blockTableShape = {B, maxBlocks};
177+ std::vector<int64_t> cuSeqQShape = {B + 1};
178+ std::vector<int64_t> cuSeqKvShape = {B + 1};
179+ std::vector<int64_t> metadataShape = {1024};
180+ std::vector<int64_t> attnOutShape = {T, N1, D};
181+ 
182+ void *qDeviceAddr = nullptr;
183+ void *kDeviceAddr = nullptr;
184+ void *vDeviceAddr = nullptr;
185+ void *sparseIdxDeviceAddr = nullptr;
186+ void *sparseCountDeviceAddr = nullptr;
187+ void *metadataDeviceAddr = nullptr;
188+ void *cuSeqQDeviceAddr = nullptr;
189+ void *cuSeqKvDeviceAddr = nullptr;
190+ void *blockTableDeviceAddr = nullptr;
191+ void *attnOutDeviceAddr = nullptr;
192+ 
193+ aclTensor *q = nullptr;
194+ aclTensor *k = nullptr;
195+ aclTensor *v = nullptr;
196+ aclTensor *sparseIdx = nullptr;
197+ aclTensor *sparseCount = nullptr;
198+ aclTensor *metadata = nullptr;
199+ aclTensor *cuSeqQ = nullptr;
200+ aclTensor *cuSeqKv = nullptr;
201+ aclTensor *blockTable = nullptr;
202+ aclTensor *attnOut = nullptr;
203+ 
204+ int64_t qSize = GetShapeSize(qShape);
205+ int64_t kvSize = GetShapeSize(kvShape);
206+ int64_t sparseIdxSize = GetShapeSize(sparseIdxShape);
207+ int64_t sparseCountSize = GetShapeSize(sparseCountShape);
208+ int64_t blockTableSize = GetShapeSize(blockTableShape);
209+ int64_t attnOutSize = GetShapeSize(attnOutShape);
210+ 
211+ std::vector<uint16_t> qHostData = MakeFp16Data(qSize, 1.0f);
212+ std::vector<uint16_t> kHostData = MakeFp16Data(kvSize, 1.0f);
jiang-lirui

没有在SIG吧接口评审通过

likedislike
WangJinCheng
WangJinCheng
Aug 29 Comments:
likedislike
213+ std::vector<uint16_t> vHostData = MakeFp16Data(kvSize, 1.0f);
214+ std::vector<int32_t> sparseIdxHostData(sparseIdxSize, -1);
215+ std::vector<int32_t> sparseCountHostData(sparseCountSize, 0);
216+ std::vector<int32_t> blockTableHostData(blockTableSize);
217+ std::iota(blockTableHostData.begin(), blockTableHostData.end(), 0);
218+ std::vector<int64_t> cuSeqQHostData = {0, S1};
219+ std::vector<int64_t> cuSeqKvHostData = {0, S2};
220+ std::vector<int32_t> metadataHostData(1024, 0);
221+ std::vector<uint16_t> attnOutHostData = MakeFp16Data(attnOutSize, 0.0f);
222+ 
223+ // Causal-like sparse window: keep up to topK trailing KV blocks per Q token.
224+ int64_t history = S2 - S1;
225+ for (int64_t qBlock = 0; qBlock < totalQBlocks; qBlock++) {
226+ int64_t visible = history + qBlock + 1;
227+ int64_t lastKvBlock = std::min(maxBlocks - 1, (visible - 1) / blockSize);
228+ int64_t count = std::min(topK, lastKvBlock + 1);
229+ int64_t start = lastKvBlock - count + 1;
230+ for (int64_t i = 0; i < count; i++) {
231+ sparseIdxHostData[qBlock * topK + i] = static_cast<int32_t>(start + i);
232+ }
233+ sparseCountHostData[qBlock] = static_cast<int32_t>(count);
234+ }
235+ 
236+ ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
237+ CHECK_RET(ret == ACL_SUCCESS, return ret);
238+ ret = CreateAclTensor(kHostData, kvShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
239+ CHECK_RET(ret == ACL_SUCCESS, return ret);
240+ ret = CreateAclTensor(vHostData, kvShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v);
241+ CHECK_RET(ret == ACL_SUCCESS, return ret);
242+ ret = CreateAclTensor(sparseIdxHostData, sparseIdxShape, &sparseIdxDeviceAddr, aclDataType::ACL_INT32, &sparseIdx);
243+ CHECK_RET(ret == ACL_SUCCESS, return ret);
244+ ret = CreateAclTensor(sparseCountHostData, sparseCountShape, &sparseCountDeviceAddr, aclDataType::ACL_INT32,
245+ &sparseCount);
246+ CHECK_RET(ret == ACL_SUCCESS, return ret);
247+ ret = CreateAclTensor(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
248+ CHECK_RET(ret == ACL_SUCCESS, return ret);
249+ ret = CreateAclTensor(cuSeqQHostData, cuSeqQShape, &cuSeqQDeviceAddr, aclDataType::ACL_INT64, &cuSeqQ);
250+ CHECK_RET(ret == ACL_SUCCESS, return ret);
251+ ret = CreateAclTensor(cuSeqKvHostData, cuSeqKvShape, &cuSeqKvDeviceAddr, aclDataType::ACL_INT64, &cuSeqKv);
252+ CHECK_RET(ret == ACL_SUCCESS, return ret);
253+ ret = CreateAclTensor(blockTableHostData, blockTableShape, &blockTableDeviceAddr, aclDataType::ACL_INT32,
254+ &blockTable);
255+ CHECK_RET(ret == ACL_SUCCESS, return ret);
256+ ret = CreateAclTensor(attnOutHostData, attnOutShape, &attnOutDeviceAddr, aclDataType::ACL_FLOAT16, &attnOut);
257+ CHECK_RET(ret == ACL_SUCCESS, return ret);
258+ 
259+ const int64_t blockShapeData[] = {blockShapeX, blockSize};
260+ aclIntArray *blockShape = aclCreateIntArray(blockShapeData, 2);
261+ CHECK_RET(blockShape != nullptr, LOG_PRINT("aclCreateIntArray failed\n"); return -1);
262+ 
263+ char layoutQ[] = "TND";
264+ char layoutKv[] = "PAGED_BBND";
265+ 
266+ // 3. 先调用 Metadata,再调用主算子
267+ uint64_t metadataWorkspaceSize = 0;
268+ aclOpExecutor *metadataExecutor = nullptr;
269+ ret = aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize(
270+ sparseIdx, sparseCount, cuSeqQ, cuSeqKv, nullptr, nullptr, S1, S2, N1, N2, D, blockShape, 1, layoutQ, layoutKv,
271+ 1, 0, 1, -1, -1, metadata, &metadataWorkspaceSize, &metadataExecutor);
272+ CHECK_RET(ret == ACL_SUCCESS,
273+ LOG_PRINT("aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
274+ return ret);
275+ 
276+ void *metadataWorkspaceAddr = nullptr;
277+ if (metadataWorkspaceSize > 0) {
278+ ret = aclrtMalloc(&metadataWorkspaceAddr, metadataWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
279+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
280+ }
281+ 
282+ ret = aclnnGenericBlockSparseAttentionMetadata(metadataWorkspaceAddr, metadataWorkspaceSize, metadataExecutor,
283+ stream);
284+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGenericBlockSparseAttentionMetadata failed. ERROR: %d\n", ret);
285+ return ret);
286+ 
287+ // 4. (固定写法)同步等待任务执行结束
288+ ret = aclrtSynchronizeStream(stream);
289+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream after metadata failed. ERROR: %d\n", ret);
290+ return ret);
291+ 
292+ uint64_t workspaceSize = 0;
293+ aclOpExecutor *executor = nullptr;
294+ ret = aclnnGenericBlockSparseAttentionGetWorkspaceSize(
295+ q, k, v, sparseIdx, sparseCount, metadata, nullptr, nullptr, nullptr, nullptr, nullptr, cuSeqQ, cuSeqKv,
296+ nullptr, nullptr, blockTable, blockShape, 1, layoutQ, layoutKv, scaleValue, 1, 0, 0.0, 1, -1, -1, 0, attnOut,
297+ nullptr, &workspaceSize, &executor);
298+ CHECK_RET(ret == ACL_SUCCESS,
299+ LOG_PRINT("aclnnGenericBlockSparseAttentionGetWorkspaceSize failed. ERROR: %d\n", ret);
300+ return ret);
301+ 
302+ void *workspaceAddr = nullptr;
303+ if (workspaceSize > 0) {
304+ ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
305+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
306+ }
307+ 
308+ ret = aclnnGenericBlockSparseAttention(workspaceAddr, workspaceSize, executor, stream);
309+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGenericBlockSparseAttention failed. ERROR: %d\n", ret); return ret);
310+ 
311+ ret = aclrtSynchronizeStream(stream);
312+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
313+ 
314+ // 5.获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改
315+ PrintOutResult(attnOutShape, &attnOutDeviceAddr);
316+ 
317+ // 6. 释放aclTensor,需要根据具体API的接口定义修改
318+ aclDestroyIntArray(blockShape);
319+ aclDestroyTensor(q);
320+ aclDestroyTensor(k);
321+ aclDestroyTensor(v);
322+ aclDestroyTensor(sparseIdx);
323+ aclDestroyTensor(sparseCount);
324+ aclDestroyTensor(metadata);
325+ aclDestroyTensor(cuSeqQ);
326+ aclDestroyTensor(cuSeqKv);
327+ aclDestroyTensor(blockTable);
328+ aclDestroyTensor(attnOut);
329+ 
330+ // 7. 释放device资源
331+ aclrtFree(qDeviceAddr);
332+ aclrtFree(kDeviceAddr);
333+ aclrtFree(vDeviceAddr);
334+ aclrtFree(sparseIdxDeviceAddr);
335+ aclrtFree(sparseCountDeviceAddr);
336+ aclrtFree(metadataDeviceAddr);
337+ aclrtFree(cuSeqQDeviceAddr);
338+ aclrtFree(cuSeqKvDeviceAddr);
339+ aclrtFree(blockTableDeviceAddr);
340+ aclrtFree(attnOutDeviceAddr);
341+ if (metadataWorkspaceSize > 0) {
342+ aclrtFree(metadataWorkspaceAddr);
343+ }
344+ if (workspaceSize > 0) {
345+ aclrtFree(workspaceAddr);
346+ }
347+ aclrtDestroyStream(stream);
348+ aclrtDestroyContext(context);
349+ aclrtResetDevice(deviceId);
350+ aclFinalize();
351+ 
352+ return 0;
353+}
@@ -0,0 +1,28 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
8+# -----------------------------------------------------------------------------------------------------------
9+add_op_to_compiled_list()
10+ 
11+if (BUILD_OPEN_PROJECT)
12+ target_sources(op_host_aclnnExc PRIVATE
13+ generic_block_sparse_attention_def.cpp
14+ )
15+endif()
16+ 
17+if (BUILD_OPS_RTY_KERNEL)
18+ add_ops_compile_options(
19+ OP_NAME GenericBlockSparseAttention
20+ OPTIONS --cce-auto-sync=off
21+ -DASCENDC_DUMP=1
22+ -Wno-deprecated-declarations
23+ -Werror
24+ -fpermissive
25+ )
26+else()
27+ add_modules_sources(OPTYPE generic_block_sparse_attention ACLNNTYPE aclnn_exclude)
28+endif()
@@ -0,0 +1,129 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include "register/op_def_registry.h"
12+ 
13+namespace ops {
14+ 
15+class GenericBlockSparseAttention : public OpDef {
16+public:
17+ explicit GenericBlockSparseAttention(const char *name)
18+ : OpDef(name)
19+ {
20+ this->Input("query")
21+ .ParamType(REQUIRED)
22+ .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN})
Huang-Peng

疑似笔误/建议确认:query/key/value 的 DataType 列表中 DT_FLOAT8_E4M3FN 重复出现两次({FP16, BF16, E4M3FN, E4M3FN}),与 attention_out 的 {FP16, BF16, FP16, BF16} 等 4 槽位列表的成对模式不一致。若第 4 个槽位本意是另一种 FP8 类型(如 E5M2)或与文档(仅支持 FLOAT8_E4M3FN、须 quantType=5)保持一致,请确认并修正;当前 aclnn 侧 CheckDataType 也只接受 E4M3FN。若确为占位重复,建议加注释说明,避免后续按此模式误填类型。

likedislike
WangJinCheng
WangJinCheng
Aug 26 Comments:
likedislike
23+ .FormatList({ge::FORMAT_ND})
24+ .AutoContiguous();
25+ this->Input("key")
26+ .ParamType(REQUIRED)
27+ .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN})
28+ .FormatList({ge::FORMAT_ND})
29+ .IgnoreContiguous();
30+ this->Input("value")
31+ .ParamType(REQUIRED)
32+ .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN})
33+ .FormatList({ge::FORMAT_ND})
34+ .IgnoreContiguous();
35+ this->Input("sparse_block_idx")
36+ .ParamType(REQUIRED)
37+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
38+ .FormatList({ge::FORMAT_ND})
39+ .AutoContiguous();
40+ this->Input("sparse_block_count")
41+ .ParamType(REQUIRED)
42+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
43+ .FormatList({ge::FORMAT_ND})
44+ .AutoContiguous();
45+ this->Input("metadata")
46+ .ParamType(OPTIONAL)
47+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
48+ .FormatList({ge::FORMAT_ND})
49+ .AutoContiguous();
50+ this->Input("atten_mask")
51+ .ParamType(OPTIONAL)
52+ .DataType({ge::DT_BOOL, ge::DT_BOOL, ge::DT_BOOL, ge::DT_BOOL})
53+ .FormatList({ge::FORMAT_ND})
54+ .AutoContiguous();
55+ this->Input("q_dequant_scale")
56+ .ParamType(OPTIONAL)
57+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
58+ .FormatList({ge::FORMAT_ND})
59+ .AutoContiguous();
60+ this->Input("k_dequant_scale")
61+ .ParamType(OPTIONAL)
62+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
63+ .FormatList({ge::FORMAT_ND})
64+ .AutoContiguous();
65+ this->Input("v_dequant_scale")
66+ .ParamType(OPTIONAL)
67+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
68+ .FormatList({ge::FORMAT_ND})
69+ .AutoContiguous();
70+ this->Input("p_quant_scale")
71+ .ParamType(OPTIONAL)
72+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
73+ .FormatList({ge::FORMAT_ND})
74+ .AutoContiguous();
75+ this->Input("cu_seq_lengths_q")
76+ .ParamType(OPTIONAL)
77+ .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64})
78+ .FormatList({ge::FORMAT_ND})
79+ .AutoContiguous();
80+ this->Input("cu_seq_lengths_kv")
81+ .ParamType(OPTIONAL)
82+ .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64})
83+ .FormatList({ge::FORMAT_ND})
84+ .AutoContiguous();
85+ this->Input("seqused_q")
86+ .ParamType(OPTIONAL)
87+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
88+ .FormatList({ge::FORMAT_ND})
89+ .AutoContiguous();
90+ this->Input("seqused_kv")
91+ .ParamType(OPTIONAL)
92+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
93+ .FormatList({ge::FORMAT_ND})
94+ .AutoContiguous();
95+ this->Input("block_table")
96+ .ParamType(OPTIONAL)
97+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
98+ .FormatList({ge::FORMAT_ND})
99+ .AutoContiguous();
100+ this->Output("attention_out")
101+ .ParamType(REQUIRED)
102+ .DataType({ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16})
103+ .FormatList({ge::FORMAT_ND});
104+ this->Output("softmax_lse")
105+ .ParamType(OPTIONAL)
106+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
107+ .FormatList({ge::FORMAT_ND});
108+ 
109+ this->Attr("block_shape").AttrType(OPTIONAL).ListInt({1, 128});
110+ this->Attr("is_packed_gqa").AttrType(OPTIONAL).Int(1);
111+ this->Attr("layout_q").AttrType(OPTIONAL).String("TND");
112+ this->Attr("layout_kv").AttrType(OPTIONAL).String("TND");
113+ this->Attr("scale_value").AttrType(OPTIONAL).Float(0.0);
114+ this->Attr("mask_type").AttrType(OPTIONAL).Int(0);
115+ this->Attr("quant_type").AttrType(OPTIONAL).Int(0);
116+ this->Attr("dst_type_max").AttrType(OPTIONAL).Float(0.0);
117+ this->Attr("softmax_precision").AttrType(OPTIONAL).Int(0);
118+ this->Attr("win_left").AttrType(OPTIONAL).Int(-1);
119+ this->Attr("win_right").AttrType(OPTIONAL).Int(-1);
120+ this->Attr("return_softmax_lse").AttrType(OPTIONAL).Int(0);
121+ this->AICore().AddConfig("ascend910b");
122+ this->AICore().AddConfig("ascend910_93");
123+ this->AICore().AddConfig("ascend950");
124+ }
125+};
126+ 
127+OP_ADD(GenericBlockSparseAttention);
128+ 
129+} // namespace ops
@@ -0,0 +1,208 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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 <string>
14+#include "log/log.h"
15+#include "log/error_code.h"
16+ 
17+using namespace ge;
18+ 
19+namespace ops {
20+ 
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 BLOCK_TABLE_INDEX = 15;
25+static constexpr uint32_t ATTENTION_OUT_INDEX = 0;
26+static constexpr uint32_t SOFTMAX_LSE_INDEX = 1;
27+ 
28+// Keep attr indices in sync with OpDef / tiling.
29+static constexpr uint32_t ATTR_LAYOUT_Q_INDEX = 2;
30+static constexpr uint32_t ATTR_LAYOUT_KV_INDEX = 3;
31+static constexpr uint32_t ATTR_RETURN_SOFTMAX_LSE_INDEX = 11;
32+ 
33+static constexpr uint32_t TND_DIM_T = 0;
34+static constexpr uint32_t TND_DIM_N = 1;
35+static constexpr uint32_t TND_DIM_D = 2;
36+static constexpr uint32_t TND_DIM_NUM = 3;
37+ 
38+// PAGED_BBND: [blockNum, blockSize, Nkv, D]
39+static constexpr uint32_t PAGED_BBND_DIM_BLOCK_NUM = 0;
40+static constexpr uint32_t PAGED_BBND_DIM_BLOCK_SIZE = 1;
41+static constexpr uint32_t PAGED_BBND_DIM_KV_HEAD = 2;
42+static constexpr uint32_t PAGED_BBND_DIM_D = 3;
43+static constexpr uint32_t PAGED_BBND_DIM_NUM = 4;
44+static constexpr uint32_t LSE_DIM_D = 1;
45+ 
46+static constexpr int32_t UNKNOWN_DIMS = -2;
47+ 
48+static bool IsUnknownRankShape(const gert::Shape *shape)
49+{
50+ return shape != nullptr && shape->GetDimNum() == 1 && shape->GetDim(0) == UNKNOWN_DIMS;
51+}
52+ 
53+static void SetUnknownOutShapes(gert::Shape *attentionOutShape, gert::Shape *softmaxLseShape)
54+{
55+ attentionOutShape->SetDimNum(1);
56+ (*attentionOutShape)[0] = UNKNOWN_DIMS;
57+ softmaxLseShape->SetDimNum(1);
58+ (*softmaxLseShape)[0] = UNKNOWN_DIMS;
59+}
60+ 
61+static void SetEmptyLseShape(gert::Shape *softmaxLseShape)
62+{
63+ // return_softmax_lse=0 → placeholder {0}.
64+ softmaxLseShape->SetDimNum(1);
65+ (*softmaxLseShape)[0] = 0;
66+}
67+ 
68+static ge::graphStatus InferShapeGenericBlockSparseAttention(gert::InferShapeContext *context)
69+{
70+ if (context == nullptr) {
71+ OP_LOGE("GenericBlockSparseAttention", "context is nullptr!");
72+ return ge::GRAPH_FAILED;
73+ }
74+ 
75+ OP_LOGD(context->GetNodeName(), "Enter GenericBlockSparseAttention InferShape impl.");
76+ 
77+ const gert::Shape *queryShape = context->GetInputShape(QUERY_INDEX);
78+ OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);
79+ 
80+ const gert::Shape *keyShape = context->GetInputShape(KEY_INDEX);
81+ OP_CHECK_NULL_WITH_CONTEXT(context, keyShape);
82+ 
83+ const gert::Shape *valueShape = context->GetInputShape(VALUE_INDEX);
84+ OP_CHECK_NULL_WITH_CONTEXT(context, valueShape);
85+ 
86+ gert::Shape *attentionOutShape = context->GetOutputShape(ATTENTION_OUT_INDEX);
87+ OP_CHECK_NULL_WITH_CONTEXT(context, attentionOutShape);
88+ 
89+ gert::Shape *softmaxLseShape = context->GetOutputShape(SOFTMAX_LSE_INDEX);
90+ OP_CHECK_NULL_WITH_CONTEXT(context, softmaxLseShape);
91+ 
92+ // Any of Q/K/V unknown-rank → propagate unknown outs.
93+ if (IsUnknownRankShape(queryShape) || IsUnknownRankShape(keyShape) || IsUnknownRankShape(valueShape)) {
94+ SetUnknownOutShapes(attentionOutShape, softmaxLseShape);
95+ return ge::GRAPH_SUCCESS;
96+ }
97+ 
98+ auto attrs = context->GetAttrs();
99+ OP_CHECK_NULL_WITH_CONTEXT(context, attrs);
100+ 
101+ const char *layoutQPtr = attrs->GetAttrPointer<char>(ATTR_LAYOUT_Q_INDEX);
102+ const char *layoutKvPtr = attrs->GetAttrPointer<char>(ATTR_LAYOUT_KV_INDEX);
103+ const std::string layoutQ = (layoutQPtr != nullptr) ? layoutQPtr : "TND";
104+ const std::string layoutKv = (layoutKvPtr != nullptr) ? layoutKvPtr : "TND";
105+ 
106+ // Only TND query + PAGED_BBND KV are supported.
107+ // Metadata, stride, quant, and reserved-attr checks stay in tiling.
108+ if (layoutQ != "TND" || layoutKv != "PAGED_BBND") {
109+ OP_LOGE(context->GetNodeName(),
110+ "Unsupported layout_q=%s, layout_kv=%s. Regular path requires layout_q=TND and "
111+ "layout_kv=PAGED_BBND.",
112+ layoutQ.c_str(), layoutKv.c_str());
113+ return ge::GRAPH_FAILED;
114+ }
115+ 
116+ if (queryShape->GetDimNum() != TND_DIM_NUM) {
117+ OP_LOGE(context->GetNodeName(), "layout_q=TND requires queryDims=3, but got %zu.", queryShape->GetDimNum());
118+ return ge::GRAPH_FAILED;
119+ }
120+ 
121+ // Light PAGED_BBND check; dim0-stride / origin vs storage stay in tiling.
122+ if (keyShape->GetDimNum() != PAGED_BBND_DIM_NUM || valueShape->GetDimNum() != PAGED_BBND_DIM_NUM) {
123+ OP_LOGE(context->GetNodeName(),
124+ "layout_kv=PAGED_BBND requires key/value dims=4 [blockNum,blockSize,Nkv,D], "
125+ "but got keyDims=%zu, valueDims=%zu.",
126+ keyShape->GetDimNum(), valueShape->GetDimNum());
127+ return ge::GRAPH_FAILED;
128+ }
129+ 
130+ const int64_t qD = queryShape->GetDim(TND_DIM_D);
131+ const int64_t kBlockNum = keyShape->GetDim(PAGED_BBND_DIM_BLOCK_NUM);
132+ const int64_t kBlockSize = keyShape->GetDim(PAGED_BBND_DIM_BLOCK_SIZE);
133+ const int64_t kNkv = keyShape->GetDim(PAGED_BBND_DIM_KV_HEAD);
134+ const int64_t kD = keyShape->GetDim(PAGED_BBND_DIM_D);
135+ const int64_t vBlockNum = valueShape->GetDim(PAGED_BBND_DIM_BLOCK_NUM);
136+ const int64_t vBlockSize = valueShape->GetDim(PAGED_BBND_DIM_BLOCK_SIZE);
137+ const int64_t vNkv = valueShape->GetDim(PAGED_BBND_DIM_KV_HEAD);
138+ const int64_t vD = valueShape->GetDim(PAGED_BBND_DIM_D);
139+ 
140+ if (kD != qD || vD != qD) {
141+ OP_LOGE(context->GetNodeName(), "key/value D must match query D=%ld, but got keyD=%ld, valueD=%ld.", qD, kD,
142+ vD);
143+ return ge::GRAPH_FAILED;
144+ }
145+ if (kBlockNum != vBlockNum || kBlockSize != vBlockSize || kNkv != vNkv) {
146+ OP_LOGE(context->GetNodeName(),
147+ "key/value PAGED_BBND dims [blockNum,blockSize,Nkv] must match, "
148+ "got key=[%ld,%ld,%ld], value=[%ld,%ld,%ld].",
149+ kBlockNum, kBlockSize, kNkv, vBlockNum, vBlockSize, vNkv);
150+ return ge::GRAPH_FAILED;
151+ }
152+ 
153+ const gert::Shape *blockTableShape = context->GetOptionalInputShape(BLOCK_TABLE_INDEX);
154+ if (blockTableShape == nullptr) {
155+ OP_LOGE(context->GetNodeName(), "layout_kv=PAGED_BBND requires block_table, but it is nullptr.");
156+ return ge::GRAPH_FAILED;
157+ }
158+ 
159+ *attentionOutShape = *queryShape;
160+ 
161+ const int64_t *lseFlagPtr = attrs->GetAttrPointer<int64_t>(ATTR_RETURN_SOFTMAX_LSE_INDEX);
162+ const int64_t returnSoftmaxLse = (lseFlagPtr != nullptr) ? *lseFlagPtr : 0;
163+ if (returnSoftmaxLse != 0 && returnSoftmaxLse != 1) {
164+ OP_LOGE(context->GetNodeName(), "Unsupported return_softmax_lse=%ld, only 0 or 1 are supported.",
165+ returnSoftmaxLse);
166+ return ge::GRAPH_FAILED;
167+ }
168+ 
169+ if (returnSoftmaxLse == 1) {
170+ softmaxLseShape->SetDimNum(TND_DIM_NUM);
171+ (*softmaxLseShape)[TND_DIM_T] = queryShape->GetDim(TND_DIM_T);
172+ (*softmaxLseShape)[TND_DIM_N] = queryShape->GetDim(TND_DIM_N);
173+ (*softmaxLseShape)[TND_DIM_D] = LSE_DIM_D;
174+ } else {
175+ SetEmptyLseShape(softmaxLseShape);
176+ }
177+ 
178+ OP_LOGD(context->GetNodeName(), "GenericBlockSparseAttention InferShape success.");
179+ return ge::GRAPH_SUCCESS;
180+}
181+ 
182+ge::graphStatus InferDataTypeGenericBlockSparseAttention(gert::InferDataTypeContext *context)
183+{
184+ if (context == nullptr) {
185+ return ge::GRAPH_FAILED;
186+ }
187+ auto dtype = context->GetInputDataType(QUERY_INDEX);
188+ if (dtype == ge::DT_FLOAT8_E4M3FN) {
189+ // FP8 input: derive output dtype from user-provided attentionOut tensor.
190+ dtype = context->GetOutputDataType(ATTENTION_OUT_INDEX);
191+ if (dtype != ge::DT_FLOAT16 && dtype != ge::DT_BF16) {
192+ OP_LOGE(context->GetNodeName(),
193+ "When query is float8_e4m3fn, attentionOut dtype must be float16 or bfloat16, "
194+ "but got %d.",
195+ static_cast<int32_t>(dtype));
196+ return ge::GRAPH_FAILED;
197+ }
198+ }
199+ context->SetOutputDataType(ATTENTION_OUT_INDEX, dtype);
200+ context->SetOutputDataType(SOFTMAX_LSE_INDEX, ge::DT_FLOAT);
201+ return ge::GRAPH_SUCCESS;
202+}
203+ 
204+IMPL_OP_INFERSHAPE(GenericBlockSparseAttention)
205+ .InferShape(InferShapeGenericBlockSparseAttention)
206+ .InferDataType(InferDataTypeGenericBlockSparseAttention);
207+ 
208+} // namespace ops
@@ -0,0 +1,157 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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_BLOCK_SPARSE_ATTENTION_TILING_H
12+#define GENERIC_BLOCK_SPARSE_ATTENTION_TILING_H
13+ 
14+#include <cstdint>
15+#include <string>
16+#include "register/tilingdata_base.h"
17+#include "tiling/platform/platform_ascendc.h"
18+#include "tiling/tiling_api.h"
19+#include "register/op_def_registry.h"
20+ 
21+namespace optiling {
22+ 
23+// Host tiling-key bases (BSA-style bitfields). Full keys live in op_kernel tilingkey.h.
24+constexpr uint64_t GBSA_OP_ARCH22_BASE = 9200000000000000ULL; // aicore220
25+constexpr uint64_t GBSA_OP_ARCH35_BASE = 9250000000000000ULL; // aicore310
26+constexpr uint64_t GBSA_LSE_OUT_OFFSET = 100000000ULL;
27+ 
28+BEGIN_TILING_DATA_DEF(GenericBlockSparseAttentionTilingData)
29+TILING_DATA_FIELD_DEF(uint32_t, batch);
30+TILING_DATA_FIELD_DEF(uint32_t, numHeads);
31+TILING_DATA_FIELD_DEF(uint32_t, kvHeads);
32+TILING_DATA_FIELD_DEF(uint32_t, embeddingSize);
33+TILING_DATA_FIELD_DEF(uint32_t, blockShapeX);
34+TILING_DATA_FIELD_DEF(uint32_t, blockShapeY);
35+TILING_DATA_FIELD_DEF(uint32_t, blockSize);
36+TILING_DATA_FIELD_DEF(uint32_t, topK);
37+TILING_DATA_FIELD_DEF(uint32_t, qBlockNum);
38+TILING_DATA_FIELD_DEF(uint32_t, maxBlocksPerBatch);
39+TILING_DATA_FIELD_DEF(float, scaleValue);
40+// Workspace大小
41+TILING_DATA_FIELD_DEF(uint64_t, mm1OutSize);
42+TILING_DATA_FIELD_DEF(uint64_t, smOnlineOutSize);
43+TILING_DATA_FIELD_DEF(uint64_t, mm2OutSize);
44+TILING_DATA_FIELD_DEF(uint64_t, updateSize);
45+TILING_DATA_FIELD_DEF(uint64_t, workSpaceSize);
46+TILING_DATA_FIELD_DEF(uint64_t, tilingKey);
47+TILING_DATA_FIELD_DEF(uint32_t, groupSize);
48+TILING_DATA_FIELD_DEF(uint32_t, qBaseTile);
49+TILING_DATA_FIELD_DEF(uint32_t, kvBaseTile);
50+TILING_DATA_FIELD_DEF(uint32_t, mm1L1TileM);
51+TILING_DATA_FIELD_DEF(uint32_t, mm1L1TileN);
52+TILING_DATA_FIELD_DEF(uint32_t, mm1L1TileKLeft);
53+TILING_DATA_FIELD_DEF(uint32_t, mm1L1TileKRight);
54+TILING_DATA_FIELD_DEF(uint32_t, mm2L1TileM);
55+TILING_DATA_FIELD_DEF(uint32_t, mm2L1TileN);
56+TILING_DATA_FIELD_DEF(uint32_t, mm2L1TileKLeft);
57+TILING_DATA_FIELD_DEF(uint32_t, mm2L1TileKRight);
58+TILING_DATA_FIELD_DEF(uint32_t, qL1BufNum);
59+TILING_DATA_FIELD_DEF(uint32_t, kL1BufNum);
60+TILING_DATA_FIELD_DEF(uint32_t, vL1BufNum);
61+TILING_DATA_FIELD_DEF(uint32_t, pL1BufNum);
62+// PAGED_BBND page base stride in elements (dim0). Allows first-axis non-contiguous KV cache.
63+TILING_DATA_FIELD_DEF(uint64_t, kStride0);
64+TILING_DATA_FIELD_DEF(uint64_t, vStride0);
65+END_TILING_DATA_DEF;
66+REGISTER_TILING_DATA_CLASS(GenericBlockSparseAttention, GenericBlockSparseAttentionTilingData)
67+ 
68+struct GenericBlockSparseAttentionCompileInfo {
69+ uint32_t inputDataByte = 2;
70+ ge::DataType inputDataType;
71+ 
72+ uint32_t coreNum = 0;
73+ uint32_t aivNum = 0;
74+ uint32_t aicNum = 0;
75+ uint64_t ubSize = 0;
76+ uint64_t l1Size = 0;
77+ uint64_t sysWorkspaceSize = 0;
78+ platform_ascendc::SocVersion socVersion;
79+};
80+ 
81+class GBSATiling {
82+public:
83+ GBSATiling() = default;
84+ ~GBSATiling() = default;
85+ 
86+ ge::graphStatus GetTiling(gert::TilingContext *context, GenericBlockSparseAttentionTilingData &tilingData);
87+ ge::graphStatus SetTilingData(gert::TilingContext *context, GenericBlockSparseAttentionTilingData &tilingData);
88+ 
89+private:
90+ ge::graphStatus GetNpuInfo(gert::TilingContext *context);
91+ ge::graphStatus ParseAttrs(gert::TilingContext *context);
92+ ge::graphStatus ParseCapabilityAttrs(gert::TilingContext *context);
93+ ge::graphStatus CheckReservedAttrs(gert::TilingContext *context);
94+ ge::graphStatus GetInputLayout(gert::TilingContext *context);
95+ ge::graphStatus ParseInputTensors(gert::TilingContext *context);
96+ ge::graphStatus ParseQueryKeyShapes(gert::TilingContext *context);
97+ ge::graphStatus ParseSparseTensors(gert::TilingContext *context);
98+ ge::graphStatus ParseBlockTable(gert::TilingContext *context);
99+ ge::graphStatus ParseQkvDtype(gert::TilingContext *context);
100+ ge::graphStatus CalculateWorkSpace(gert::TilingContext *context);
101+ ge::graphStatus FillTilingData(gert::TilingContext *context);
102+ ge::graphStatus CheckAttentionOutDtype(gert::TilingContext *context);
103+ ge::graphStatus CheckSoftmaxPrecision(gert::TilingContext *context);
104+ ge::graphStatus CheckQuantConfig(gert::TilingContext *context);
105+ ge::graphStatus CheckMetadata(gert::TilingContext *context);
106+ ge::graphStatus CheckReservedOptionalInputs(gert::TilingContext *context);
107+ ge::graphStatus CheckCuSeqLengths(gert::TilingContext *context);
108+ ge::graphStatus ParseKvCacheStride0(gert::TilingContext *context);
109+ uint64_t GenerateTilingKey();
110+ 
111+ uint32_t batch_ = 0;
112+ uint32_t numHeads_ = 0;
113+ uint32_t kvHeads_ = 0;
114+ uint32_t embeddingSize_ = 0;
115+ // Regular path only supports blockShapeX=1; default must match.
116+ uint32_t blockShapeX_ = 1;
117+ uint32_t blockShapeY_ = 128;
118+ uint32_t blockSize_ = 128;
119+ uint32_t topK_ = 16;
120+ uint32_t qBlockNum_ = 0;
121+ uint32_t maxBlocksPerBatch_ = 0;
122+ float scaleValue_ = 0.0f;
123+ uint32_t softmaxPrecision_ = 0;
124+ int64_t isPackedGQA_ = 1;
125+ int64_t softmaxLseFlag_ = 0;
126+ bool returnSoftmaxlse_ = false;
127+ bool blockTablePresent_ = false;
128+ 
129+ uint64_t mm1OutSize_ = 0;
130+ uint64_t smOnlineOutSize_ = 0;
131+ uint64_t mm2OutSize_ = 0;
132+ uint64_t updateSize_ = 0;
133+ uint64_t workSpaceSize_ = 0;
134+ 
135+ uint32_t blockDim_ = 0;
136+ uint32_t aicNum_ = 0;
137+ uint64_t libapiSize_ = 0;
138+ uint32_t socVer_ = 0;
139+ 
140+ ge::DataType dataType_ = ge::DT_FLOAT16;
141+ ge::DataType attentionOutDtype_ = ge::DT_FLOAT16;
142+ 
143+ std::string layoutQ_ = "TND";
144+ std::string layoutKv_ = "TND";
145+ int64_t maskType_ = 0;
146+ int64_t quantType_ = 0;
147+ 
148+ // Default = contiguous PAGED_BBND page size; overwritten when KV is a dim0-strided view.
149+ uint64_t kStride0_ = 0;
150+ uint64_t vStride0_ = 0;
151+ 
152+ GenericBlockSparseAttentionTilingData *tilingData_ = nullptr;
153+};
154+ 
155+} // namespace optiling
156+ 
157+#endif // GENERIC_BLOCK_SPARSE_ATTENTION_TILING_H
@@ -0,0 +1,374 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include "aclnn_generic_block_sparse_attention.h"
12+ 
13+#include "generic_block_sparse_attention.h"
14+#include "aclnn_kernels/contiguous.h"
15+#include "opdev/make_op_executor.h"
16+#include "opdev/op_dfx.h"
17+#include "opdev/tensor_view_utils.h"
18+#include "opdev/common_types.h"
19+#include "opdev/op_errno.h"
20+#include "opdev/op_executor.h"
21+#include "opdev/op_log.h"
22+#include <algorithm>
23+#include <string>
24+#include <unordered_map>
25+ 
26+using namespace op;
27+ 
28+#ifdef __cplusplus
29+extern "C" {
30+#endif
31+ 
32+namespace {
33+ 
34+static constexpr int64_t LSE_OUT = 1;
35+ 
36+static bool CheckDataType(const aclTensor *query, const aclTensor *key, const aclTensor *value)
37+{
38+ const DataType qDtype = query->GetDataType();
39+ const DataType kDtype = key->GetDataType();
40+ const DataType vDtype = value->GetDataType();
41+ 
42+ static const std::unordered_map<DataType, std::vector<DataType>> validKvType = {
43+ {DataType::DT_FLOAT16, {DataType::DT_FLOAT16}},
44+ {DataType::DT_BF16, {DataType::DT_BF16}},
45+ {DataType::DT_FLOAT8_E4M3FN, {DataType::DT_FLOAT8_E4M3FN}},
46+ };
47+ 
48+ auto iter = validKvType.find(qDtype);
49+ if (iter == validKvType.end()) {
50+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "Unsupported query datatype %d.", static_cast<int>(qDtype));
51+ return false;
52+ }
53+ 
54+ if (std::find(iter->second.begin(), iter->second.end(), kDtype) == iter->second.end() ||
55+ std::find(iter->second.begin(), iter->second.end(), vDtype) == iter->second.end()) {
56+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "Key/Value datatype mismatch with query.");
57+ return false;
58+ }
59+ 
60+ return true;
61+}
62+ 
63+static aclnnStatus CheckMandatoryTensors(const aclTensor *query, const aclTensor *key, const aclTensor *value,
64+ const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount)
65+{
66+ CHECK_RET(query != nullptr, ACLNN_ERR_PARAM_NULLPTR);
67+ CHECK_RET(key != nullptr, ACLNN_ERR_PARAM_NULLPTR);
68+ CHECK_RET(value != nullptr, ACLNN_ERR_PARAM_NULLPTR);
69+ CHECK_RET(sparseBlockIdx != nullptr, ACLNN_ERR_PARAM_NULLPTR);
70+ CHECK_RET(sparseBlockCount != nullptr, ACLNN_ERR_PARAM_NULLPTR);
71+ return ACLNN_SUCCESS;
72+}
73+ 
74+static aclnnStatus ParseBlockShape(const aclIntArray *blockShape)
75+{
76+ if (blockShape == nullptr) {
77+ OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "blockShape must not be null.");
78+ return ACLNN_ERR_PARAM_NULLPTR;
79+ }
80+ 
81+ if (blockShape->Size() != 2U) {
82+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "blockShape must contain two elements [x, y].");
83+ return ACLNN_ERR_PARAM_INVALID;
84+ }
85+ 
86+ const int64_t *data = blockShape->GetData();
87+ if (data == nullptr) {
88+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "blockShape data is null.");
89+ return ACLNN_ERR_PARAM_INVALID;
90+ }
91+ 
92+ if (data[0] <= 0 || data[1] <= 0) {
93+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "blockShape values must be positive, got [%ld, %ld].", data[0], data[1]);
94+ return ACLNN_ERR_PARAM_INVALID;
95+ }
96+ 
97+ return ACLNN_SUCCESS;
98+}
99+ 
100+static aclnnStatus ValidateParams(const aclTensor *query, const aclTensor *key, const aclTensor *value,
101+ const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount,
102+ const aclIntArray *blockShape, char *layoutQ, char *layoutKv)
103+{
104+ CHECK_RET(CheckMandatoryTensors(query, key, value, sparseBlockIdx, sparseBlockCount) == ACLNN_SUCCESS,
105+ ACLNN_ERR_PARAM_NULLPTR);
106+ 
107+ if (!CheckDataType(query, key, value)) {
108+ return ACLNN_ERR_PARAM_INVALID;
109+ }
110+ 
111+ if (layoutQ == nullptr || layoutKv == nullptr) {
112+ OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "layoutQ/layoutKv must not be null.");
113+ return ACLNN_ERR_PARAM_NULLPTR;
114+ }
115+ 
116+ const std::string layoutQStr = op::ToString(layoutQ).GetString();
117+ const std::string layoutKvStr = op::ToString(layoutKv).GetString();
118+ if (layoutQStr != "TND") {
119+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "layoutQ only supports TND, got %s.", layoutQStr.c_str());
120+ return ACLNN_ERR_PARAM_INVALID;
121+ }
122+ if (layoutKvStr != "PAGED_BBND") {
123+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "layoutKv only supports PAGED_BBND, got %s.", layoutKvStr.c_str());
124+ return ACLNN_ERR_PARAM_INVALID;
125+ }
126+ 
127+ aclnnStatus ret = ParseBlockShape(blockShape);
128+ if (ret != ACLNN_SUCCESS) {
129+ return ret;
130+ }
131+ 
132+ return ACLNN_SUCCESS;
133+}
134+ 
135+static aclnnStatus ValidateAdditionalParams(int64_t softmaxPrecision, const aclTensor *attentionOut,
136+ uint64_t *workspaceSize, aclOpExecutor **executor)
137+{
138+ if (softmaxPrecision != 0 && softmaxPrecision != 1) {
139+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "softmaxPrecision must be 0 or 1, got %ld.", softmaxPrecision);
140+ return ACLNN_ERR_PARAM_INVALID;
141+ }
142+ 
143+ CHECK_RET(attentionOut != nullptr, ACLNN_ERR_PARAM_NULLPTR);
144+ CHECK_RET(workspaceSize != nullptr, ACLNN_ERR_PARAM_NULLPTR);
145+ CHECK_RET(executor != nullptr, ACLNN_ERR_PARAM_NULLPTR);
146+ return ACLNN_SUCCESS;
147+}
148+ 
149+// layoutQ / layoutKv are string attrs; keep as string end-to-end.
150+static std::string ConvertLayoutString(char *layoutStr)
151+{
152+ return op::ToString(layoutStr).GetString();
153+}
154+ 
155+// Contiguous non-KV inputs for aclnn L0 InferShape (torch_npu often has view=ND, storage=1D;
156+// GetInputShape may return storage unless Contiguous/CreateView normalizes the descriptor).
157+// Keep Contiguous even when OpDef has AutoContiguous.
158+// Do NOT Contiguous key/value here — dim0-strided KV is handled by NormalizeDim0KvTensor
159+// (CreateView + SetStorageShape(viewShape)).
160+static aclnnStatus MakeContiguous(const aclTensor *&query, const aclTensor *&sparseBlockIdx,
161+ const aclTensor *&sparseBlockCount, const aclTensor *&metadataOptional,
162+ const aclTensor *&attenMaskOptional, const aclTensor *&qDequantScaleOptional,
163+ const aclTensor *&kDequantScaleOptional, const aclTensor *&vDequantScaleOptional,
164+ const aclTensor *&pQuantScaleOptional, const aclTensor *&cuSeqLengthsQOptional,
165+ const aclTensor *&cuSeqLengthsKvOptional, const aclTensor *&sequsedQOptional,
166+ const aclTensor *&sequsedKvOptional, const aclTensor *&blockTableOptional,
167+ aclOpExecutor *executor)
168+{
169+ query = l0op::Contiguous(query, executor);
170+ CHECK_RET(query != nullptr, ACLNN_ERR_PARAM_NULLPTR);
171+ sparseBlockIdx = l0op::Contiguous(sparseBlockIdx, executor);
172+ CHECK_RET(sparseBlockIdx != nullptr, ACLNN_ERR_PARAM_NULLPTR);
173+ sparseBlockCount = l0op::Contiguous(sparseBlockCount, executor);
174+ CHECK_RET(sparseBlockCount != nullptr, ACLNN_ERR_PARAM_NULLPTR);
175+ 
176+ metadataOptional = l0op::Contiguous(metadataOptional, executor);
177+ CHECK_RET(metadataOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
178+ if (attenMaskOptional != nullptr) {
179+ attenMaskOptional = l0op::Contiguous(attenMaskOptional, executor);
180+ CHECK_RET(attenMaskOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
181+ }
182+ if (qDequantScaleOptional != nullptr) {
183+ qDequantScaleOptional = l0op::Contiguous(qDequantScaleOptional, executor);
184+ CHECK_RET(qDequantScaleOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
185+ }
186+ if (kDequantScaleOptional != nullptr) {
187+ kDequantScaleOptional = l0op::Contiguous(kDequantScaleOptional, executor);
188+ CHECK_RET(kDequantScaleOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
189+ }
190+ if (vDequantScaleOptional != nullptr) {
191+ vDequantScaleOptional = l0op::Contiguous(vDequantScaleOptional, executor);
192+ CHECK_RET(vDequantScaleOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
193+ }
194+ if (pQuantScaleOptional != nullptr) {
195+ pQuantScaleOptional = l0op::Contiguous(pQuantScaleOptional, executor);
196+ CHECK_RET(pQuantScaleOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
197+ }
198+ if (cuSeqLengthsQOptional != nullptr) {
199+ cuSeqLengthsQOptional = l0op::Contiguous(cuSeqLengthsQOptional, executor);
200+ CHECK_RET(cuSeqLengthsQOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
201+ }
202+ if (cuSeqLengthsKvOptional != nullptr) {
203+ cuSeqLengthsKvOptional = l0op::Contiguous(cuSeqLengthsKvOptional, executor);
204+ CHECK_RET(cuSeqLengthsKvOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
205+ }
206+ if (sequsedQOptional != nullptr) {
207+ sequsedQOptional = l0op::Contiguous(sequsedQOptional, executor);
208+ CHECK_RET(sequsedQOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
209+ }
210+ if (sequsedKvOptional != nullptr) {
211+ sequsedKvOptional = l0op::Contiguous(sequsedKvOptional, executor);
212+ CHECK_RET(sequsedKvOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
213+ }
214+ if (blockTableOptional != nullptr) {
215+ blockTableOptional = l0op::Contiguous(blockTableOptional, executor);
216+ CHECK_RET(blockTableOptional != nullptr, ACLNN_ERR_INNER_NULLPTR);
217+ }
218+ return ACLNN_SUCCESS;
219+}
220+ 
221+// Only dim0 may be non-contiguous for PAGED_BBND KV.
222+static bool IsFirstAxisOnlyNonContiguous(const aclTensor *tensor, const char *name)
223+{
224+ if (tensor == nullptr || IsContiguous(tensor)) {
225+ return true;
226+ }
227+ 
228+ const auto &viewShape = tensor->GetViewShape();
229+ const int64_t dimNum = static_cast<int64_t>(viewShape.GetDimNum());
230+ if (dimNum <= 1) {
231+ OP_LOGW("%s is non-contiguous with dim num[%ld] <= 1, it will be forced contiguous.", name, dimNum);
232+ return false;
233+ }
234+ 
235+ const auto &viewStrides = tensor->GetViewStrides();
236+ if (viewStrides.size() < static_cast<size_t>(dimNum)) {
237+ OP_LOGW("%s view strides num[%zu] < dim num[%ld], it will be forced contiguous.", name, viewStrides.size(),
238+ dimNum);
239+ return false;
240+ }
241+ 
242+ int64_t expectedStride = 1;
243+ for (int64_t dim = dimNum - 1; dim >= 1; --dim) {
244+ if (viewShape.GetDim(dim) != 1 && viewStrides[static_cast<size_t>(dim)] != expectedStride) {
245+ OP_LOGW("%s is non-contiguous at axis[%ld]: actual stride[%ld], expected[%ld], shape[%s]. "
246+ "It will be forced contiguous.",
247+ name, dim, viewStrides[static_cast<size_t>(dim)], expectedStride,
248+ op::ToString(viewShape).GetString());
249+ return false;
250+ }
251+ expectedStride *= viewShape.GetDim(dim);
252+ }
253+ return true;
254+}
255+ 
256+// CreateView + SetStorageShape(viewShape): InferShape/GetInputShape often reads storage;
257+// forcing storage==view keeps ND dims for tiling while preserving view strides (zero-copy).
258+static const aclTensor *CreateStrideAwareView(const aclTensor *tensor, const char *name, aclOpExecutor *executor)
259+{
260+ auto strideView = executor->CreateView(tensor, tensor->GetViewShape(), tensor->GetStorageShape(),
261+ tensor->GetViewStrides(), tensor->GetViewOffset());
262+ if (strideView == nullptr) {
263+ OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "CreateStrideAwareView for %s failed.", name);
264+ return nullptr;
265+ }
266+ const_cast<aclTensor *>(strideView)->SetStorageShape(tensor->GetViewShape());
267+ return strideView;
268+}
269+ 
270+// Contiguous KV: Contiguous (normalize descriptor). Dim0-only holes: stride-aware view.
271+// Other non-contig: Contiguous fallback (tiling rejects non-dim0 holes for PAGED_BBND).
272+static const aclTensor *NormalizeDim0KvTensor(const aclTensor *tensor, const char *name, aclOpExecutor *executor)
273+{
274+ if (tensor == nullptr) {
275+ return nullptr;
276+ }
277+ if (IsContiguous(tensor)) {
278+ return l0op::Contiguous(tensor, executor);
279+ }
280+ if (IsFirstAxisOnlyNonContiguous(tensor, name)) {
281+ return CreateStrideAwareView(tensor, name, executor);
282+ }
283+ return l0op::Contiguous(tensor, executor);
284+}
285+ 
286+} // namespace
287+ 
288+__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttentionGetWorkspaceSize(
289+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseBlockIdx,
290+ const aclTensor *sparseBlockCount, const aclTensor *metadataOptional, const aclTensor *attenMaskOptional,
291+ const aclTensor *qDequantScaleOptional, const aclTensor *kDequantScaleOptional,
292+ const aclTensor *vDequantScaleOptional, const aclTensor *pQuantScaleOptional,
293+ const aclTensor *cuSeqLengthsQOptional, const aclTensor *cuSeqLengthsKvOptional, const aclTensor *sequsedQOptional,
294+ const aclTensor *sequsedKvOptional, const aclTensor *blockTableOptional, const aclIntArray *blockShape,
295+ int64_t isPackedGQA, char *layoutQ, char *layoutKv, double scaleValue, int64_t maskType, int64_t quantType,
296+ double dstTypeMax, int64_t softmaxPrecision, int64_t winLeft, int64_t winRight, int64_t returnSoftmaxlse,
297+ aclTensor *attentionOut, aclTensor *softmaxLseOptional, uint64_t *workspaceSize, aclOpExecutor **executor)
298+{
299+ aclnnStatus ret =
300+ ValidateParams(query, key, value, sparseBlockIdx, sparseBlockCount, blockShape, layoutQ, layoutKv);
301+ if (ret != ACLNN_SUCCESS) {
302+ return ret;
303+ }
304+ 
305+ ret = ValidateAdditionalParams(softmaxPrecision, attentionOut, workspaceSize, executor);
306+ if (ret != ACLNN_SUCCESS) {
307+ return ret;
308+ }
309+ 
310+ L2_DFX_PHASE_1(aclnnGenericBlockSparseAttention,
311+ DFX_IN(query, key, value, sparseBlockIdx, sparseBlockCount, metadataOptional, attenMaskOptional,
312+ qDequantScaleOptional, kDequantScaleOptional, vDequantScaleOptional, pQuantScaleOptional,
313+ cuSeqLengthsQOptional, cuSeqLengthsKvOptional, sequsedQOptional, sequsedKvOptional,
314+ blockTableOptional, blockShape, isPackedGQA, layoutQ, layoutKv, scaleValue, maskType,
315+ quantType, dstTypeMax, softmaxPrecision, winLeft, winRight, returnSoftmaxlse),
316+ DFX_OUT(attentionOut, softmaxLseOptional));
317+ 
318+ auto uniqueExecutor = CREATE_EXECUTOR();
319+ CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_NULLPTR);
320+ auto *executorImpl = uniqueExecutor.get();
321+ 
322+ ret = MakeContiguous(query, sparseBlockIdx, sparseBlockCount, metadataOptional, attenMaskOptional,
323+ qDequantScaleOptional, kDequantScaleOptional, vDequantScaleOptional, pQuantScaleOptional,
324+ cuSeqLengthsQOptional, cuSeqLengthsKvOptional, sequsedQOptional, sequsedKvOptional,
325+ blockTableOptional, executorImpl);
326+ if (ret != ACLNN_SUCCESS) {
327+ return ret;
328+ }
329+ 
330+ std::string layoutQStr = ConvertLayoutString(layoutQ);
331+ std::string layoutKvStr = ConvertLayoutString(layoutKv);
332+ 
333+ const aclTensor *keyFinal = NormalizeDim0KvTensor(key, "key", executorImpl);
334+ CHECK_RET(keyFinal != nullptr, ACLNN_ERR_INNER_NULLPTR);
335+ const aclTensor *valueFinal = NormalizeDim0KvTensor(value, "value", executorImpl);
336+ CHECK_RET(valueFinal != nullptr, ACLNN_ERR_INNER_NULLPTR);
337+ 
338+ auto outputs = l0op::GenericBlockSparseAttention(
339+ query, keyFinal, valueFinal, sparseBlockIdx, sparseBlockCount, metadataOptional, attenMaskOptional,
340+ qDequantScaleOptional, kDequantScaleOptional, vDequantScaleOptional, pQuantScaleOptional, cuSeqLengthsQOptional,
341+ cuSeqLengthsKvOptional, sequsedQOptional, sequsedKvOptional, blockTableOptional, blockShape, isPackedGQA,
342+ layoutQStr.c_str(), layoutKvStr.c_str(), scaleValue, maskType, quantType, dstTypeMax, softmaxPrecision, winLeft,
343+ winRight, returnSoftmaxlse, attentionOut, executorImpl);
344+ 
345+ if (outputs[0] == nullptr) {
346+ OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "GenericBlockSparseAttention returned nullptr output.");
347+ return ACLNN_ERR_INNER_NULLPTR;
348+ }
349+ 
350+ auto viewCopyResult = l0op::ViewCopy(outputs[0], attentionOut, executorImpl);
351+ CHECK_RET(viewCopyResult != nullptr, ACLNN_ERR_INNER_NULLPTR);
352+ if (returnSoftmaxlse == LSE_OUT) {
353+ CHECK_RET(outputs[1] != nullptr, ACLNN_ERR_INNER_NULLPTR);
354+ auto viewCopyLseResult = l0op::ViewCopy(outputs[1], softmaxLseOptional, executorImpl);
355+ CHECK_RET(viewCopyLseResult != nullptr, ACLNN_ERR_INNER_NULLPTR);
356+ }
357+ 
358+ *workspaceSize = executorImpl->GetWorkspaceSize();
359+ uniqueExecutor.ReleaseTo(executor);
360+ return ACLNN_SUCCESS;
361+}
362+ 
363+__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttention(void *workspace,
364+ uint64_t workspaceSize,
365+ aclOpExecutor *executor,
366+ aclrtStream stream)
367+{
368+ L2_DFX_PHASE_2(aclnnGenericBlockSparseAttention);
369+ return CommonOpExecutorRun(workspace, workspaceSize, executor, stream);
370+}
371+ 
372+#ifdef __cplusplus
373+}
374+#endif
@@ -0,0 +1,40 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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_BLOCK_SPARSE_ATTENTION_H_
12+#define ACLNN_GENERIC_BLOCK_SPARSE_ATTENTION_H_
13+ 
14+#include "aclnn/acl_meta.h"
15+ 
16+#ifdef __cplusplus
17+extern "C" {
18+#endif
19+ 
20+__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttentionGetWorkspaceSize(
21+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseBlockIdx,
22+ const aclTensor *sparseBlockCount, const aclTensor *metadataOptional, const aclTensor *attenMaskOptional,
23+ const aclTensor *qDequantScaleOptional, const aclTensor *kDequantScaleOptional,
24+ const aclTensor *vDequantScaleOptional, const aclTensor *pQuantScaleOptional,
25+ const aclTensor *cuSeqLengthsQOptional, const aclTensor *cuSeqLengthsKvOptional, const aclTensor *sequsedQOptional,
26+ const aclTensor *sequsedKvOptional, const aclTensor *blockTableOptional, const aclIntArray *blockShape,
27+ int64_t isPackedGQA, char *layoutQ, char *layoutKv, double scaleValue, int64_t maskType, int64_t quantType,
28+ double dstTypeMax, int64_t softmaxPrecision, int64_t winLeft, int64_t winRight, int64_t returnSoftmaxlse,
29+ aclTensor *attentionOut, aclTensor *softmaxLseOptional, uint64_t *workspaceSize, aclOpExecutor **executor);
30+ 
31+__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttention(void *workspace,
32+ uint64_t workspaceSize,
33+ aclOpExecutor *executor,
34+ aclrtStream stream);
35+ 
36+#ifdef __cplusplus
37+}
38+#endif
39+ 
40+#endif // ACLNN_GENERIC_BLOCK_SPARSE_ATTENTION_H_
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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 "generic_block_sparse_attention.h"
12+ 
13+#include "opdev/make_op_executor.h"
14+#include "opdev/op_dfx.h"
15+ 
16+using namespace op;
17+ 
18+namespace l0op {
19+ 
20+OP_TYPE_REGISTER(GenericBlockSparseAttention);
21+ 
22+const std::array<const aclTensor *, 2> GenericBlockSparseAttention(
23+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseBlockIdx,
24+ const aclTensor *sparseBlockCount, const aclTensor *metadataOptional, const aclTensor *attenMaskOptional,
25+ const aclTensor *qDequantScaleOptional, const aclTensor *kDequantScaleOptional,
26+ const aclTensor *vDequantScaleOptional, const aclTensor *pQuantScaleOptional,
27+ const aclTensor *cuSeqLengthsQOptional, const aclTensor *cuSeqLengthsKvOptional, const aclTensor *sequsedQOptional,
28+ const aclTensor *sequsedKvOptional, const aclTensor *blockTableOptional, const aclIntArray *blockShape,
29+ int64_t isPackedGQA, const char *layoutQ, const char *layoutKv, double scaleValue, int64_t maskType,
30+ int64_t quantType, double dstTypeMax, int64_t softmaxPrecision, int64_t winLeft, int64_t winRight,
31+ int64_t returnSoftmaxlse, const aclTensor *attentionOut, aclOpExecutor *executor)
32+{
33+ L0_DFX(GenericBlockSparseAttention, query, key, value, sparseBlockIdx, sparseBlockCount, metadataOptional,
34+ attenMaskOptional, qDequantScaleOptional, kDequantScaleOptional, vDequantScaleOptional, pQuantScaleOptional,
35+ cuSeqLengthsQOptional, cuSeqLengthsKvOptional, sequsedQOptional, sequsedKvOptional, blockTableOptional,
36+ blockShape, isPackedGQA, layoutQ, layoutKv, scaleValue, maskType, quantType, dstTypeMax, softmaxPrecision,
37+ winLeft, winRight, returnSoftmaxlse);
38+ 
39+ DataType outDtype =
40+ (query->GetDataType() == DataType::DT_FLOAT8_E4M3FN) ? attentionOut->GetDataType() : query->GetDataType();
41+ auto attentionOutTensor = executor->AllocTensor(outDtype, Format::FORMAT_ND, Format::FORMAT_ND);
42+ auto softmaxLseTensor = executor->AllocTensor(DataType::DT_FLOAT, Format::FORMAT_ND, Format::FORMAT_ND);
43+ 
44+ auto ret = INFER_SHAPE(
45+ GenericBlockSparseAttention,
46+ OP_INPUT(query, key, value, sparseBlockIdx, sparseBlockCount, metadataOptional, attenMaskOptional,
47+ qDequantScaleOptional, kDequantScaleOptional, vDequantScaleOptional, pQuantScaleOptional,
48+ cuSeqLengthsQOptional, cuSeqLengthsKvOptional, sequsedQOptional, sequsedKvOptional,
49+ blockTableOptional),
50+ OP_OUTPUT(attentionOutTensor, softmaxLseTensor),
51+ OP_ATTR(blockShape, static_cast<int64_t>(isPackedGQA), layoutQ, layoutKv, static_cast<float>(scaleValue),
52+ static_cast<int64_t>(maskType), static_cast<int64_t>(quantType), static_cast<float>(dstTypeMax),
53+ static_cast<int64_t>(softmaxPrecision), static_cast<int64_t>(winLeft), static_cast<int64_t>(winRight),
54+ static_cast<int64_t>(returnSoftmaxlse)));
55+ if (ret != ACLNN_SUCCESS) {
56+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "GenericBlockSparseAttention infer shape failed.");
57+ return {nullptr, nullptr};
58+ }
59+ 
60+ ADD_TO_LAUNCHER_LIST_AICORE(
61+ GenericBlockSparseAttention,
62+ OP_INPUT(query, key, value, sparseBlockIdx, sparseBlockCount, metadataOptional, attenMaskOptional,
63+ qDequantScaleOptional, kDequantScaleOptional, vDequantScaleOptional, pQuantScaleOptional,
64+ cuSeqLengthsQOptional, cuSeqLengthsKvOptional, sequsedQOptional, sequsedKvOptional,
65+ blockTableOptional),
66+ OP_OUTPUT(attentionOutTensor, softmaxLseTensor),
67+ OP_ATTR(blockShape, static_cast<int64_t>(isPackedGQA), layoutQ, layoutKv, static_cast<float>(scaleValue),
68+ static_cast<int64_t>(maskType), static_cast<int64_t>(quantType), static_cast<float>(dstTypeMax),
69+ static_cast<int64_t>(softmaxPrecision), static_cast<int64_t>(winLeft), static_cast<int64_t>(winRight),
70+ static_cast<int64_t>(returnSoftmaxlse)));
71+ 
72+ return {attentionOutTensor, softmaxLseTensor};
73+}
74+ 
75+} // namespace l0op
@@ -0,0 +1,32 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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_BLOCK_SPARSE_ATTENTION_H_
12+#define GENERIC_BLOCK_SPARSE_ATTENTION_H_
13+ 
14+#include <array>
15+#include "opdev/op_executor.h"
16+ 
17+namespace l0op {
18+ 
19+const std::array<const aclTensor *, 2> GenericBlockSparseAttention(
20+ const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseBlockIdx,
21+ const aclTensor *sparseBlockCount, const aclTensor *metadataOptional, const aclTensor *attenMaskOptional,
22+ const aclTensor *qDequantScaleOptional, const aclTensor *kDequantScaleOptional,
23+ const aclTensor *vDequantScaleOptional, const aclTensor *pQuantScaleOptional,
24+ const aclTensor *cuSeqLengthsQOptional, const aclTensor *cuSeqLengthsKvOptional, const aclTensor *sequsedQOptional,
25+ const aclTensor *sequsedKvOptional, const aclTensor *blockTableOptional, const aclIntArray *blockShape,
26+ int64_t isPackedGQA, const char *layoutQ, const char *layoutKv, double scaleValue, int64_t maskType,
27+ int64_t quantType, double dstTypeMax, int64_t softmaxPrecision, int64_t winLeft, int64_t winRight,
28+ int64_t returnSoftmaxlse, const aclTensor *attentionOut, aclOpExecutor *executor);
29+ 
30+} // namespace l0op
31+ 
32+#endif // GENERIC_BLOCK_SPARSE_ATTENTION_H_
@@ -0,0 +1,475 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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_BLOCK_SPARSE_ATTENTION_KERNEL_ARCH22_H
12+#define GENERIC_BLOCK_SPARSE_ATTENTION_KERNEL_ARCH22_H
13+ 
14+#include "../kernel_common.hpp"
15+#include "../generic_block_sparse_attention_metadata_kernel.h"
16+#include "kernel_utils.hpp"
17+ 
18+using namespace NpuArch;
19+ 
20+namespace GbsaKernelArch22 {
21+ 
22+template <class BlockMmadQK, class EpilogueOnlineSoftmax, class BlockMmadPV, class EpilogueRescaleO>
23+class GbsaRegularKernelArch22 {
24+public:
25+ using ArchTag = typename BlockMmadPV::ArchTag;
26+ 
27+ using ElementQ = typename BlockMmadQK::ElementA;
28+ using ElementK = typename BlockMmadQK::ElementB;
29+ using ElementS = typename EpilogueOnlineSoftmax::ElementInput;
30+ using ElementP = typename BlockMmadPV::ElementA;
31+ using ElementV = typename BlockMmadPV::ElementB;
32+ using ElementOTmp = typename BlockMmadPV::ElementC;
33+ using ElementO = typename BlockMmadQK::ElementA;
34+ 
35+ using LayoutQ = layout::RowMajor;
36+ using LayoutK = layout::ColumnMajor;
37+ using LayoutS = layout::RowMajor;
38+ using LayoutP = layout::RowMajor;
39+ using LayoutV = layout::RowMajor;
40+ using LayoutO = layout::RowMajor;
41+ using LayoutOTmp = layout::RowMajor;
42+ using LayoutLse = layout::RowMajor;
43+ using LayoutUpdate = layout::RowMajor;
44+ 
45+ static constexpr uint32_t PRE_LAUNCH = 2;
46+ static constexpr uint32_t MAX_CROSS_CORE_BUF_STAGES = PRE_LAUNCH + 1;
47+ static constexpr uint64_t WORKSPACE_BLOCK_SIZE_DB = 131072;
48+ static constexpr uint32_t QK_READY_ID = 1;
49+ static constexpr uint32_t SOFTMAX_READY_ID = 2;
50+ static constexpr uint32_t PV_READY_ID = 3;
51+ 
52+ __aicore__ inline GbsaRegularKernelArch22() {}
53+ 
54+ __aicore__ inline void operator()(GbsaKernelParamsArch22 const &params)
55+ {
56+ __gm__ GenericBlockSparseAttn::GenericBlockSparseAttentionTilingData *tilingData =
57+ reinterpret_cast<__gm__ GenericBlockSparseAttn::GenericBlockSparseAttentionTilingData *>(params.tiling);
58+ FetchTilingData(tilingData, params.metaData);
59+ 
60+ AscendC::GlobalTensor<ElementQ> gQ;
61+ gQ.SetGlobalBuffer((__gm__ ElementQ *)params.q);
62+ AscendC::GlobalTensor<ElementK> gK;
63+ gK.SetGlobalBuffer((__gm__ ElementK *)params.k);
64+ AscendC::GlobalTensor<ElementV> gV;
65+ gV.SetGlobalBuffer((__gm__ ElementV *)params.v);
66+ AscendC::GlobalTensor<int32_t> gSparseBlockIdx;
67+ gSparseBlockIdx.SetGlobalBuffer((__gm__ int32_t *)params.sparseBlockIdx);
68+ AscendC::GlobalTensor<int32_t> gBlockTable;
69+ gBlockTable.SetGlobalBuffer((__gm__ int32_t *)params.blockTable);
70+ AscendC::GlobalTensor<int32_t> gSparseBlockCount;
71+ gSparseBlockCount.SetGlobalBuffer((__gm__ int32_t *)params.sparseBlockCount);
72+ AscendC::GlobalTensor<int64_t> gCuSeqLengths;
73+ if (params.cuSeqLengths != nullptr) {
74+ gCuSeqLengths.SetGlobalBuffer((__gm__ int64_t *)params.cuSeqLengths);
75+ }
76+ AscendC::GlobalTensor<int64_t> gCuSeqLengthsKv;
77+ if (params.cuSeqLengthsKv != nullptr) {
78+ gCuSeqLengthsKv.SetGlobalBuffer((__gm__ int64_t *)params.cuSeqLengthsKv);
79+ }
80+ AscendC::GlobalTensor<int32_t> gSequsedQ;
81+ const bool hasSequsedQ = (params.sequsedQ != nullptr);
82+ if (hasSequsedQ) {
83+ gSequsedQ.SetGlobalBuffer((__gm__ int32_t *)params.sequsedQ);
84+ }
85+ AscendC::GlobalTensor<int32_t> gSequsedKv;
86+ const bool hasSequsedKv = (params.sequsedKv != nullptr);
87+ if (hasSequsedKv) {
88+ gSequsedKv.SetGlobalBuffer((__gm__ int32_t *)params.sequsedKv);
89+ }
90+ AscendC::GlobalTensor<ElementO> gO;
91+ gO.SetGlobalBuffer((__gm__ ElementO *)params.o);
92+ AscendC::GlobalTensor<float> gLse;
93+ gLse.SetGlobalBuffer((__gm__ float *)params.softmaxLse);
94+ 
95+ // Workspace: [S][P][OTmp][OUpdate][identity]. Identity must not precede gS —
96+ // Fixpipe into GM immediately after identity was flaky on arch22.
97+ AscendC::GlobalTensor<ElementS> gS;
98+ gS.SetGlobalBuffer((__gm__ ElementS *)params.workSpace);
99+ AscendC::GlobalTensor<ElementP> gP;
100+ gP.SetGlobalBuffer((__gm__ ElementP *)(params.workSpace + mm1OutSize_));
101+ AscendC::GlobalTensor<ElementOTmp> gOTmp;
102+ gOTmp.SetGlobalBuffer((__gm__ ElementOTmp *)(params.workSpace + mm1OutSize_ + smOnlineOutSize_));
103+ AscendC::GlobalTensor<ElementOTmp> gOUpdate;
104+ gOUpdate.SetGlobalBuffer(
105+ (__gm__ ElementOTmp *)(params.workSpace + mm1OutSize_ + smOnlineOutSize_ + mm2OutSize_));
106+ AscendC::GlobalTensor<int32_t> gIdentityIdx;
107+ gIdentityIdx.SetGlobalBuffer(
108+ (__gm__ int32_t *)(params.workSpace + mm1OutSize_ + smOnlineOutSize_ + mm2OutSize_ + updateSize_));
109+ 
110+ uint32_t coreIdx = AscendC::GetBlockIdx();
111+ uint32_t coreNum = AscendC::GetBlockNum();
112+ 
113+#ifdef __DAV_C220_CUBE__
114+ // Initialize Cube core hardware events
115+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID0);
116+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID1);
117+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID2);
118+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID3);
119+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID4);
120+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID5);
121+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID6);
122+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID7);
123+ AscendC::SetFlag<AscendC::HardEvent::FIX_M>(EVENT_ID0);
124+ AscendC::SetFlag<AscendC::HardEvent::FIX_M>(EVENT_ID1);
125+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID0);
126+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID1);
127+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID2);
128+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID3);
129+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID4);
130+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID5);
131+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID6);
132+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID7);
133+ 
134+ static constexpr uint32_t L1_QK_SIZE =
135+ BlockMmadQK::L1TileShape::M * BlockMmadQK::L1TileShape::K * sizeof(ElementQ) +
136+ BlockMmadQK::L1TileShape::N * BlockMmadQK::L1TileShape::K * sizeof(ElementK) * 2;
137+ BlockMmadQK blockMmadQK(resource);
138+ BlockMmadPV blockMmadPV(resource, L1_QK_SIZE);
139+#endif
140+ 
141+#ifdef __DAV_C220_VEC__
142+ // Initialize hardware events for vector core
143+ AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID0);
144+ AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID1);
145+ AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID4);
146+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID2);
147+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID3);
148+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID4);
149+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID5);
150+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID6);
151+ 
152+ AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0);
153+ AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID1);
154+ AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID3);
155+ AscendC::SetFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID2);
156+ AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID2);
157+ EpilogueOnlineSoftmax epilogueOnlineSoftmax(resource, scaleValue_);
158+ EpilogueRescaleO epilogueRescaleO(resource);
159+ 
160+ coreIdx = AscendC::GetBlockIdx() / AscendC::GetSubBlockNum();
161+#endif
162+ 
163+#ifdef __DAV_C220_CUBE__
164+ coreIdx = AscendC::GetBlockIdx();
165+ for (uint32_t i = 0; i < topK_; i++) {
166+ gIdentityIdx.SetValue(i, 0);
167+ }
168+#endif
169+ AscendC::SyncAll<false>();
170+ 
171+ uint32_t groupSize = groupSize_;
172+ int64_t strideQO = qHeads_ * embed_;
173+ int64_t strideKVRow = kvHeads_ * embed_;
174+ uint32_t embedRound = RoundUp(embed_, 16);
175+ uint32_t rowNumRound = RoundUp(groupSize, 16);
176+ 
177+ for (uint32_t taskIdx = coreIdx; taskIdx < totalTaskNum_; taskIdx += coreNum) {
178+ uint32_t qToken = taskIdx / kvHeads_;
179+ uint32_t kvHeadIdx = taskIdx % kvHeads_;
180+ uint32_t qHeadStart = kvHeadIdx * groupSize;
181+ uint32_t batchIdx = 0;
182+ uint32_t qTokenInBatch = qToken;
183+ // Task space = packed actual Q tokens (seqused if present, else cu storage).
184+ // GM / sparse index use cu storage offsets (pad at end of each batch segment).
185+ uint32_t accum = 0;
186+ for (uint32_t b = 0; b < batch_; ++b) {
187+ uint32_t storageLen = static_cast<uint32_t>(gCuSeqLengths.GetValue(static_cast<int64_t>(b + 1)) -
188+ gCuSeqLengths.GetValue(static_cast<int64_t>(b)));
189+ uint32_t batchLen =
190+ hasSequsedQ ? static_cast<uint32_t>(gSequsedQ.GetValue(static_cast<int64_t>(b))) : storageLen;
191+ if (qToken < accum + batchLen) {
192+ batchIdx = b;
193+ qTokenInBatch = qToken - accum;
194+ break;
195+ }
196+ accum += batchLen;
197+ }
198+ 
199+ uint32_t kvStorageLen = static_cast<uint32_t>(gCuSeqLengthsKv.GetValue(static_cast<int64_t>(batchIdx + 1)) -
200+ gCuSeqLengthsKv.GetValue(static_cast<int64_t>(batchIdx)));
201+ uint32_t qStorageLen = static_cast<uint32_t>(gCuSeqLengths.GetValue(static_cast<int64_t>(batchIdx + 1)) -
202+ gCuSeqLengths.GetValue(static_cast<int64_t>(batchIdx)));
203+ uint32_t kvSeqlen = hasSequsedKv ?
204+ static_cast<uint32_t>(gSequsedKv.GetValue(static_cast<int64_t>(batchIdx))) :
205+ kvStorageLen;
206+ uint32_t qSeqlen =
207+ hasSequsedQ ? static_cast<uint32_t>(gSequsedQ.GetValue(static_cast<int64_t>(batchIdx))) : qStorageLen;
208+ // Padding / empty request: actual q_len or kv_len == 0 → skip this batch.
209+ // Need kvSeqlen >= qSeqlen for unsigned historyLen = kv - q.
210+ if (qSeqlen == 0 || kvSeqlen == 0 || kvSeqlen < qSeqlen) {
211+ continue;
212+ }
213+ 
214+ int64_t qStorageToken =
215+ gCuSeqLengths.GetValue(static_cast<int64_t>(batchIdx)) + static_cast<int64_t>(qTokenInBatch);
216+ int64_t gmOffsetQ = qStorageToken * strideQO + static_cast<int64_t>(qHeadStart) * embed_;
217+ int64_t gmOffsetO = gmOffsetQ;
218+ 
219+ // TND + isPackedGQA=1: sparseBlockIdx 3D [N_kv, totalQBlocks, topK]
220+ // totalQBlocks spans storage (cu) blocks; align with metadata qStorageBlockStarts.
221+ uint32_t globalQBlock = 0;
222+ for (uint32_t b = 0; b < batchIdx; ++b) {
223+ uint32_t qLen = static_cast<uint32_t>(gCuSeqLengths.GetValue(static_cast<int64_t>(b + 1)) -
224+ gCuSeqLengths.GetValue(static_cast<int64_t>(b)));
225+ globalQBlock += (qLen + blockShapeX_ - 1) / blockShapeX_;
226+ }
227+ globalQBlock += qTokenInBatch / blockShapeX_;
228+ int64_t sparseIdxBase =
229+ static_cast<int64_t>(kvHeadIdx) * qBlockNum_ * topK_ + static_cast<int64_t>(globalQBlock) * topK_;
230+ uint32_t validTopK = topK_;
231+ if (params.sparseBlockCount != nullptr) {
232+ // sparseBlockCount 2D: [N_kv, totalQBlocks]
233+ int64_t countOffset = static_cast<int64_t>(kvHeadIdx) * qBlockNum_ + static_cast<int64_t>(globalQBlock);
234+ validTopK = static_cast<uint32_t>(gSparseBlockCount.GetValue(countOffset));
235+ }
236+ if (validTopK == 0)
237+ continue;
238+ 
239+ uint32_t historyLen = kvSeqlen - qSeqlen;
240+ uint32_t lastBlockTileSize = (historyLen + qTokenInBatch) % blockShapeY_ + 1;
241+ 
242+ constexpr uint32_t MAX_VALID_TOPK = 256U;
243+ 
244+ uint32_t kvSLoopNum = validTopK;
245+ int32_t validPhysicalIds[MAX_VALID_TOPK];
monologue815

[严重] 栈数组 validPhysicalIds[MAX_VALID_TOPK] + validTileSize[MAX_VALID_TOPK] 可能导致栈溢出

当 topK_=256 时,这两个数组占用 2KB 栈空间(256*4 + 256*4)。Ascend C kernel 的栈空间非常有限,加上其他局部变量,可能逼近或超出栈上限,导致未定义行为。

建议:将这些数组放入 workspace 的 per-core 区域,或使用 UB/LocalTensor 替代栈分配。同一问题也存在于 Arch35 kernel(L198)和 FullQuant kernel(L206)。

likedislike
WangJinCheng
WangJinCheng
Aug 30 Comments:
likedislike
246+ uint32_t validTileSize[MAX_VALID_TOPK];
247+ uint32_t lastLogicalBlockId = (historyLen + qTokenInBatch) / blockShapeY_;
248+ uint32_t actualLoopNum = 0;
249+ for (uint32_t i = 0; i < kvSLoopNum && i < topK_; i++) {
250+ int32_t logicalId = gSparseBlockIdx.GetValue(sparseIdxBase + i);
251+ if (logicalId < 0 || static_cast<uint32_t>(logicalId) >= maxBlocksPerBatch_)
252+ continue;
253+ int64_t btOffset = static_cast<int64_t>(batchIdx) * maxBlocksPerBatch_ + logicalId;
254+ int32_t physicalId = gBlockTable.GetValue(btOffset);
255+ validPhysicalIds[actualLoopNum] = physicalId;
256+ validTileSize[actualLoopNum] =
257+ (static_cast<uint32_t>(logicalId) == lastLogicalBlockId) ? lastBlockTileSize : blockShapeY_;
258+ actualLoopNum++;
259+ }
260+ if (actualLoopNum == 0) {
261+ continue;
262+ }
263+ kvSLoopNum = actualLoopNum;
264+ // Disable prefetch when kv blocks <= PRE_LAUNCH (avoids empty CrossCore rounds).
265+ uint32_t preLaunch = (kvSLoopNum > PRE_LAUNCH) ? PRE_LAUNCH : 0;
266+ 
267+ uint32_t rowNum = groupSize;
268+ int64_t blockTOffset = static_cast<int64_t>(batchIdx) * maxBlocksPerBatch_;
269+ // qS tile along TND S-axis; equals tokens per Q-block (tiling currently requires ==1).
270+ uint32_t qSBlockSize = blockShapeX_;
271+ 
272+#ifdef __DAV_C220_CUBE__
273+ // Load Q into L1 once per task
274+ LayoutQ gmQLayout(rowNum, embed_);
275+ blockMmadQK.loadQGM(gQ[gmOffsetQ], gmQLayout, rowNum, groupSize, embed_);
276+#endif
277+ 
278+#ifdef __DAV_C220_VEC__
279+ // Rescale LSE treats layout*.shape(0) as qS (must match qSBlockSize arg).
280+ LayoutO gmOLayout(qSBlockSize, strideQO);
281+ LayoutLse gmLseLayout(qSBlockSize, qHeads_);
282+#endif
283+ for (uint32_t kvBlockIdx = 0; kvBlockIdx < kvSLoopNum + preLaunch; kvBlockIdx++) {
284+ // === Stage 1+2: QK Matmul & Online Softmax ===
285+ if (kvBlockIdx < kvSLoopNum) {
286+ uint32_t kvSTileSizeAct = validTileSize[kvBlockIdx];
287+ int32_t physicalBlockId = validPhysicalIds[kvBlockIdx];
288+ int64_t gmOffsetK = static_cast<int64_t>(physicalBlockId) * static_cast<int64_t>(kStride0_) +
289+ static_cast<int64_t>(kvHeadIdx) * embed_;
290+ 
291+ uint32_t stageId = kvBlockIdx % MAX_CROSS_CORE_BUF_STAGES;
292+ uint64_t gmOffsetS =
293+ static_cast<uint64_t>(coreIdx) * WORKSPACE_BLOCK_SIZE_DB * MAX_CROSS_CORE_BUF_STAGES +
294+ static_cast<uint64_t>(stageId) * WORKSPACE_BLOCK_SIZE_DB;
295+ 
296+#ifdef __DAV_C220_CUBE__
297+ // Stage 1: QK Matmul
298+ LayoutK gmKLayout(strideKVRow, blockSize_);
299+ LayoutS ubSLayout(rowNumRound, RoundUp(kvSTileSizeAct, 16));
300+ GemmCoord actualBlockShapeQK{rowNum, kvSTileSizeAct, embed_};
301+ 
302+ blockMmadQK(gQ[gmOffsetQ], gK[gmOffsetK], gS[gmOffsetS], gBlockTable[blockTOffset], gIdentityIdx,
303+ gmQLayout, gmKLayout, ubSLayout, actualBlockShapeQK, 0, 0, blockSize_, strideKVRow,
304+ blockSize_, 1, 1, kvSTileSizeAct);
305+ 
306+ NpuArch::Arch::CrossCoreSetFlag<0x2, PIPE_FIX>(qkReady_);
307+#endif
308+ 
309+#ifdef __DAV_C220_VEC__
310+ // Stage 2: Online Softmax
311+ uint64_t gmOffsetP = gmOffsetS;
312+ LayoutS ubSLayout(rowNumRound, RoundUp(kvSTileSizeAct, 16));
313+ LayoutP ubPLayout(rowNumRound, RoundUp(kvSTileSizeAct, 16));
314+ GemmCoord actualBlockShapeQK{rowNum, kvSTileSizeAct, embed_};
315+ 
316+ NpuArch::Arch::CrossCoreWaitFlag(qkReady_);
317+ 
318+ epilogueOnlineSoftmax(gP[gmOffsetP], gS[gmOffsetS], ubPLayout, ubSLayout, actualBlockShapeQK,
319+ (kvBlockIdx == 0), 0, qSBlockSize, groupSize, stageId, softmaxReady_);
320+#endif
321+ }
322+ 
323+ // === Stage 3+4: PV Matmul & RescaleO ===
324+ if (kvBlockIdx >= preLaunch) {
325+ uint32_t kvBlockIdxDe = kvBlockIdx - preLaunch;
326+ uint32_t kvSTileSizeAct = validTileSize[kvBlockIdxDe];
327+ int32_t physicalBlockIdV = validPhysicalIds[kvBlockIdxDe];
328+ int64_t gmOffsetV = static_cast<int64_t>(physicalBlockIdV) * static_cast<int64_t>(vStride0_) +
329+ static_cast<int64_t>(kvHeadIdx) * embed_;
330+ 
331+ uint32_t stageId = kvBlockIdxDe % MAX_CROSS_CORE_BUF_STAGES;
332+ uint64_t gmOffsetP =
333+ static_cast<uint64_t>(coreIdx) * WORKSPACE_BLOCK_SIZE_DB * MAX_CROSS_CORE_BUF_STAGES +
334+ static_cast<uint64_t>(stageId) * WORKSPACE_BLOCK_SIZE_DB;
335+ uint64_t gmOffsetOTmp =
336+ static_cast<uint64_t>(coreIdx) * WORKSPACE_BLOCK_SIZE_DB * MAX_CROSS_CORE_BUF_STAGES +
337+ static_cast<uint64_t>(stageId) * WORKSPACE_BLOCK_SIZE_DB;
338+ 
339+#ifdef __DAV_C220_CUBE__
340+ // Stage 3: PV Matmul
341+ LayoutP ubPLayout(rowNumRound, RoundUp(kvSTileSizeAct, 16));
342+ LayoutV gmVLayout(blockSize_, strideKVRow);
343+ LayoutOTmp ubOTmpLayout(rowNumRound, embedRound);
344+ GemmCoord actualBlockShapePV{rowNum, embed_, kvSTileSizeAct};
345+ 
346+ blockMmadPV(gP[gmOffsetP], gV[gmOffsetV], gOTmp[gmOffsetOTmp], gBlockTable[blockTOffset],
347+ gIdentityIdx, ubPLayout, gmVLayout, ubOTmpLayout, actualBlockShapePV, 0, 0, blockSize_,
348+ kvSTileSizeAct, strideKVRow, 1, softmaxReady_, blockSize_, 1, 1);
349+ NpuArch::Arch::CrossCoreSetFlag<0x2, PIPE_FIX>(pvReady_);
350+#endif
351+ 
352+#ifdef __DAV_C220_VEC__
353+ // Stage 4: RescaleO
354+ uint64_t gmOffsetUpdate = static_cast<uint64_t>(coreIdx) * WORKSPACE_BLOCK_SIZE_DB;
355+ LayoutOTmp ubOTmpLayout(rowNumRound, embedRound);
356+ LayoutUpdate ubUpdateLayout(rowNumRound, embedRound);
357+ GemmCoord actualBlockShapePV{rowNum, embed_, validTileSize[kvBlockIdxDe]};
358+ 
359+ NpuArch::Arch::CrossCoreWaitFlag(pvReady_);
360+ 
361+ // LSE GM must use storage token index (same as O), not packed task qToken.
362+ epilogueRescaleO(gO[gmOffsetO], gOTmp[gmOffsetOTmp], gOUpdate[gmOffsetUpdate],
363+ gLse[qStorageToken * qHeads_ + qHeadStart], gmOLayout, ubOTmpLayout,
364+ ubUpdateLayout, gmLseLayout, actualBlockShapePV, qSBlockSize, groupSize,
365+ (kvBlockIdxDe == 0), (kvBlockIdxDe == kvSLoopNum - 1), stageId);
366+#endif
367+ }
368+ }
369+ }
370+ 
371+#ifdef __DAV_C220_CUBE__
372+ // Wait for all Cube core events
373+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID0);
374+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID1);
375+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID2);
376+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID3);
377+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID4);
378+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID5);
379+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID6);
380+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(EVENT_ID7);
381+ AscendC::WaitFlag<AscendC::HardEvent::FIX_M>(EVENT_ID0);
382+ AscendC::WaitFlag<AscendC::HardEvent::FIX_M>(EVENT_ID1);
383+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID0);
384+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID1);
385+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID2);
386+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID3);
387+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID4);
388+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID5);
389+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID6);
390+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(EVENT_ID7);
391+#endif
392+ 
393+#ifdef __DAV_C220_VEC__
394+ // Wait for all VECTOR core events
395+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID2);
396+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID3);
397+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID4);
398+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID5);
399+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID6);
400+ 
401+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID0);
402+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID1);
403+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID2);
404+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_V>(EVENT_ID4);
405+ AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID0);
406+ AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID1);
407+ AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID2);
408+ AscendC::WaitFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID3);
409+#endif
410+ AscendC::PipeBarrier<PIPE_ALL>();
411+ }
412+ 
413+private:
414+ __aicore__ inline void FetchTilingData(
415+ __gm__ GenericBlockSparseAttn::GenericBlockSparseAttentionTilingData *tilingData, GM_ADDR metaData)
416+ {
417+ batch_ = tilingData->batch;
418+ qHeads_ = tilingData->numHeads;
419+ kvHeads_ = tilingData->kvHeads;
420+ embed_ = tilingData->embeddingSize;
421+ blockShapeY_ = tilingData->blockShapeY;
422+ blockShapeX_ = tilingData->blockShapeX;
423+ blockSize_ = tilingData->blockSize;
424+ qBlockNum_ = tilingData->qBlockNum;
425+ topK_ = tilingData->topK;
426+ maxBlocksPerBatch_ = tilingData->maxBlocksPerBatch;
427+ // Full AICPU metadata protocol overlay (no tiling fallback for task schedule).
428+ __gm__ GbsaMetadata::Metadata *meta = reinterpret_cast<__gm__ GbsaMetadata::Metadata *>(metaData);
429+ totalTaskNum_ = static_cast<uint32_t>(meta->saTotalTaskNum);
430+ scaleValue_ = tilingData->scaleValue;
431+ groupSize_ = tilingData->groupSize;
432+ qBaseTile_ = tilingData->qBaseTile;
433+ kvBaseTile_ = tilingData->kvBaseTile;
434+ mm1OutSize_ = tilingData->mm1OutSize;
435+ smOnlineOutSize_ = tilingData->smOnlineOutSize;
436+ mm2OutSize_ = tilingData->mm2OutSize;
437+ updateSize_ = tilingData->updateSize;
438+ kStride0_ = tilingData->kStride0;
439+ vStride0_ = tilingData->vStride0;
440+ }
441+ 
442+ Arch::Resource<ArchTag> resource;
443+ Arch::CrossCoreFlag qkReady_{QK_READY_ID};
444+ Arch::CrossCoreFlag softmaxReady_{SOFTMAX_READY_ID};
445+ Arch::CrossCoreFlag pvReady_{PV_READY_ID};
446+ // basic shape info
447+ uint32_t batch_;
448+ uint32_t qHeads_;
449+ uint32_t kvHeads_;
450+ uint32_t embed_;
451+ uint32_t blockShapeY_;
452+ uint32_t blockShapeX_;
453+ uint32_t blockSize_;
454+ uint32_t qBlockNum_;
455+ uint32_t topK_;
456+ uint32_t maxBlocksPerBatch_;
457+ uint32_t totalTaskNum_;
458+ float scaleValue_;
459+ uint32_t groupSize_;
460+ // PAGED_BBND page base strides (elements); may exceed blockSize*Nkv*D when dim0 is strided.
461+ uint64_t kStride0_;
462+ uint64_t vStride0_;
463+ // base tile info
464+ uint32_t qBaseTile_;
465+ uint32_t kvBaseTile_;
466+ // workspace partition sizes
467+ uint64_t mm1OutSize_;
468+ uint64_t smOnlineOutSize_;
469+ uint64_t mm2OutSize_;
470+ uint64_t updateSize_;
471+};
472+ 
473+} // namespace GbsaKernelArch22
474+ 
475+#endif // GENERIC_BLOCK_SPARSE_ATTENTION_KERNEL_ARCH22_H
@@ -0,0 +1,76 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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+#ifndef GBSA_ARCH22_KERNEL_UTILS
11+#define GBSA_ARCH22_KERNEL_UTILS
12+ 
13+#include "../attn_infra/base_defs.hpp"
14+#include "../attn_infra/arch/arch.hpp"
15+#include "../attn_infra/layout/layout.hpp"
16+ 
17+#include "../attn_infra/gemm/block/block_mmad.hpp"
18+#include "../attn_infra/gemm/dispatch_policy.hpp"
19+#include "../attn_infra/gemm/gemm_type.hpp"
20+ 
21+#include "../attn_infra/arch/cross_core_sync.hpp"
22+#include "../attn_infra/arch/resource.hpp"
23+#include "../attn_infra/epilogue/block/block_epilogue.hpp"
24+#include "../attn_infra/epilogue/dispatch_policy.hpp"
25+#include "kernel_operator.h"
26+#include "lib/matmul_intf.h"
27+#include "kernel_tiling/kernel_tiling.h"
28+namespace GbsaKernelArch22 {
29+ 
30+// Regular (non-quantized) kernel params.
31+// Inputs order: q, k, v, sparseBlockIdx, sparseBlockCount, metaData,
32+// cuSeqLengths, cuSeqLengthsKv, sequsedQ, sequsedKv, blockTable
33+struct GbsaKernelParamsArch22 {
34+ GM_ADDR q;
35+ GM_ADDR k;
36+ GM_ADDR v;
37+ GM_ADDR sparseBlockIdx;
38+ GM_ADDR sparseBlockCount;
39+ GM_ADDR metaData;
40+ GM_ADDR cuSeqLengths;
41+ GM_ADDR cuSeqLengthsKv;
42+ GM_ADDR sequsedQ;
43+ GM_ADDR sequsedKv;
44+ GM_ADDR blockTable;
45+ GM_ADDR o;
46+ GM_ADDR softmaxLse;
47+ GM_ADDR workSpace;
48+ GM_ADDR tiling;
49+ 
50+ __aicore__ inline GbsaKernelParamsArch22() {}
51+ __aicore__ inline GbsaKernelParamsArch22(GM_ADDR q_, GM_ADDR k_, GM_ADDR v_, GM_ADDR sparseBlockIdx_,
52+ GM_ADDR sparseBlockCount_, GM_ADDR metaData_, GM_ADDR cuSeqLengths_,
53+ GM_ADDR cuSeqLengthsKv_, GM_ADDR sequsedQ_, GM_ADDR sequsedKv_,
54+ GM_ADDR blockTable_, GM_ADDR o_, GM_ADDR softmaxLse_, GM_ADDR workSpace_,
55+ GM_ADDR tiling_)
56+ : q(q_),
57+ k(k_),
58+ v(v_),
59+ sparseBlockIdx(sparseBlockIdx_),
60+ sparseBlockCount(sparseBlockCount_),
61+ metaData(metaData_),
62+ cuSeqLengths(cuSeqLengths_),
63+ cuSeqLengthsKv(cuSeqLengthsKv_),
64+ sequsedQ(sequsedQ_),
65+ sequsedKv(sequsedKv_),
66+ blockTable(blockTable_),
67+ o(o_),
68+ softmaxLse(softmaxLse_),
69+ workSpace(workSpace_),
70+ tiling(tiling_)
71+ {}
72+};
73+ 
74+} // namespace GbsaKernelArch22
75+ 
76+#endif // GBSA_ARCH22_KERNEL_UTILS
@@ -0,0 +1,553 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
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 "../arch35/kernel_utils.hpp"
12+#include "../kernel_common.hpp"
13+#include "../generic_block_sparse_attention_metadata_kernel.h"
14+ 
15+using namespace NpuArch;
16+using namespace tla;
17+ 
18+namespace GbsaKernelArch35 {
19+ 
20+template <class BlockMmadQK, class EpilogueOnlineSoftmax, class BlockMmadPV, class EpilogueRescaleO, Format qFormat,
21+ Format kvFormat>
22+class GbsaRegularKernelArch35 {
23+public:
24+ using ArchTag = typename BlockMmadPV::ArchTag;
25+ 
26+ using ElementQ = typename BlockMmadQK::ElementA;
27+ using ElementK = typename BlockMmadQK::ElementB;
28+ using ElementS = typename EpilogueOnlineSoftmax::ElementInput;
29+ using ElementP = typename BlockMmadPV::ElementA;
30+ using ElementV = typename BlockMmadPV::ElementB;
31+ using ElementOTmp = typename BlockMmadPV::ElementC;
32+ using ElementO = typename BlockMmadQK::ElementA;
33+ using ElementLse = typename EpilogueRescaleO::ElementLse;
34+ 
35+ using LayoutQ = layout::RowMajor;
36+ using LayoutK = layout::ColumnMajor;
37+ using LayoutS = layout::RowMajor;
38+ using LayoutP = layout::RowMajor;
39+ using LayoutV = layout::RowMajor;
40+ using LayoutO = layout::RowMajor;
41+ using LayoutOTmp = layout::RowMajor;
42+ using LayoutLse = layout::RowMajor;
43+ 
44+ using LayoutTagL1P = typename BlockMmadPV::LayoutTagL1A;
45+ 
46+ static constexpr uint32_t PRE_LAUNCH = 2;
47+ static constexpr uint32_t MAX_CROSS_CORE_BUF_STAGES = PRE_LAUNCH + 1;
48+ static constexpr uint32_t UB_S_OTMP_BUF_STAGES = 2;
49+ 
50+ __aicore__ inline GbsaRegularKernelArch35() {}
51+ 
52+ __aicore__ inline void operator()(GbsaKernelParamsArch35 const &params)
53+ {
54+ __gm__ GenericBlockSparseAttn::GenericBlockSparseAttentionTilingData *tilingData =
55+ reinterpret_cast<__gm__ GenericBlockSparseAttn::GenericBlockSparseAttentionTilingData *>(params.tiling);
56+ FetchBaseShapeInfo(tilingData, params.metaData);
57+ CalcOnChipBufTileInfo(tilingData);
58+ 
59+ AscendC::GlobalTensor<ElementQ> gQ;
60+ gQ.SetGlobalBuffer((__gm__ ElementQ *)params.q);
61+ AscendC::GlobalTensor<ElementK> gK;
62+ gK.SetGlobalBuffer((__gm__ ElementK *)params.k);
63+ AscendC::GlobalTensor<ElementK> gV;
64+ gV.SetGlobalBuffer((__gm__ ElementK *)params.v);
65+ AscendC::GlobalTensor<int32_t> gSparseBlockIdx;
66+ gSparseBlockIdx.SetGlobalBuffer((__gm__ int32_t *)params.sparseBlockIdx);
67+ AscendC::GlobalTensor<int32_t> gBlockTable;
68+ gBlockTable.SetGlobalBuffer((__gm__ int32_t *)params.blockTable);
69+ AscendC::GlobalTensor<int32_t> gSparseBlockCount;
70+ gSparseBlockCount.SetGlobalBuffer((__gm__ int32_t *)params.sparseBlockCount);
71+ AscendC::GlobalTensor<int64_t> gCuSeqLengths;
72+ if (params.cuSeqLengths != nullptr) {
73+ gCuSeqLengths.SetGlobalBuffer((__gm__ int64_t *)params.cuSeqLengths);
74+ }
75+ AscendC::GlobalTensor<int64_t> gCuSeqLengthsKv;
76+ if (params.cuSeqLengthsKv != nullptr) {
77+ gCuSeqLengthsKv.SetGlobalBuffer((__gm__ int64_t *)params.cuSeqLengthsKv);
78+ }
79+ AscendC::GlobalTensor<int32_t> gSequsedQ;
80+ const bool hasSequsedQ = (params.sequsedQ != nullptr);
81+ if (hasSequsedQ) {
82+ gSequsedQ.SetGlobalBuffer((__gm__ int32_t *)params.sequsedQ);
83+ }
84+ AscendC::GlobalTensor<int32_t> gSequsedKv;
85+ const bool hasSequsedKv = (params.sequsedKv != nullptr);
86+ if (hasSequsedKv) {
87+ gSequsedKv.SetGlobalBuffer((__gm__ int32_t *)params.sequsedKv);
88+ }
89+ AscendC::GlobalTensor<ElementO> gO;
90+ gO.SetGlobalBuffer((__gm__ ElementO *)params.o);
91+ AscendC::GlobalTensor<ElementLse> gLse;
92+ gLse.SetGlobalBuffer((__gm__ ElementLse *)params.softmaxLse);
93+ AscendC::GlobalTensor<int32_t> gIdentityIdx;
94+ gIdentityIdx.SetGlobalBuffer((__gm__ int32_t *)params.workSpace);
95+ 
96+ AscendC::LocalTensor<ElementP> l1PTensor[MAX_CROSS_CORE_BUF_STAGES];
97+ AscendC::LocalTensor<ElementS> ubSTensor[UB_S_OTMP_BUF_STAGES];
98+ AscendC::LocalTensor<ElementOTmp> ubOTmpTensor[UB_S_OTMP_BUF_STAGES];
99+ InitCrossCoreDstBuf(l1PTensor, ubSTensor, ubOTmpTensor);
100+