Merged
Add generic_block_sparse_attention_metadata Op #10657
lijiamin2025Add on Aug 26
Add generic_block_sparse_attention_metadata Op #10657
Merged
Total: 21 files changed+3139-0
新增算子在其他目录也要修改一下,cmake,doc之类的


| @@ -0,0 +1,23 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 12 | +list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 13 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 14 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 15 | + add_subdirectory(${SUB_DIR}) | ||
| 16 | + endif() | ||
| 17 | +endforeach() | ||
| 18 | + | ||
| 19 | +# Compiled operator directories are appended after the common UT discovery pass, so register this operator's | ||
| 20 | +# tests explicitly to ensure build.sh -u discovers its cases. | ||
| 21 | +if(ENABLE_TEST AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt") | ||
| 22 | + add_subdirectory(tests) | ||
| 23 | +endif() | ||
Aattention/generic_block_sparse_attention_metadata/docs/aclnnGenericBlockSparseAttentionMetadata.md+481-0
| @@ -0,0 +1,481 @@ | |||
| 1 | +# aclnnGenericBlockSparseAttentionMetadata | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +<!-- npu="950" id1 --> | ||
| 6 | +- <term>Ascend 950PR/Ascend 950DT</term>:支持 | ||
| 7 | +<!-- end id1 --> | ||
| 8 | +<!-- npu="A3" id2 --> | ||
| 9 | +- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:支持 | ||
| 10 | +<!-- end id2 --> | ||
| 11 | +<!-- npu="910b" id3 --> | ||
| 12 | +- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:支持 | ||
| 13 | +<!-- end id3 --> | ||
| 14 | +<!-- npu="310b" id4 --> | ||
| 15 | +- <term>Atlas 200I/500 A2 推理产品</term>:不支持 | ||
| 16 | +<!-- end id4 --> | ||
| 17 | +<!-- npu="310p" id5 --> | ||
| 18 | +- <term>Atlas 推理系列产品</term>:不支持 | ||
| 19 | +<!-- end id5 --> | ||
| 20 | +<!-- npu="910" id6 --> | ||
| 21 | +- <term>Atlas 训练系列产品</term>:不支持 | ||
| 22 | +<!-- end id6 --> | ||
| 23 | + | ||
| 24 | +## 功能说明 | ||
| 25 | + | ||
| 26 | +- 接口功能:生成`aclnnGenericBlockSparseAttention`计算所需的`metadataOptional`。 | ||
| 27 | +- 输出`metadataOptional`必须作为主算子`aclnnGenericBlockSparseAttention`的`metadataOptional`输入使用;每次调用主算子前均须重新生成。 | ||
| 28 | +- `metadataOptional`为不透明数据,调用者不应解析或修改其中的内容。 | ||
| 29 | + | ||
| 30 | +## 函数原型 | ||
| 31 | + | ||
| 32 | +每个算子分为[两段式接口](../../../docs/zh/context/two_phase_api.md),必须先调用`aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize`获取workspace大小,再调用`aclnnGenericBlockSparseAttentionMetadata`执行计算。 | ||
| 33 | + | ||
| 34 | +```cpp | ||
| 35 | +aclnnStatus aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize( | ||
| 36 | + const aclTensor *sparseBlockIdx, | ||
| 37 | + const aclTensor *sparseBlockCount, | ||
| 38 | + const aclTensor *cuSeqLengthsQOptional, | ||
| 39 | + const aclTensor *cuSeqLengthsKvOptional, | ||
| 40 | + const aclTensor *sequsedQOptional, | ||
| 41 | + const aclTensor *sequsedKvOptional, | ||
| 42 | + int64_t maxQSeqLen, | ||
| 43 | + int64_t maxKvSeqLen, | ||
| 44 | + int64_t numQHeads, | ||
| 45 | + int64_t numKvHeads, | ||
| 46 | + int64_t headDim, | ||
| 47 | + const aclIntArray *blockShape, | ||
| 48 | + int64_t isPackedGQA, | ||
| 49 | + const char *layoutQ, | ||
| 50 | + const char *layoutKv, | ||
| 51 | + int64_t maskType, | ||
| 52 | + int64_t quantType, | ||
| 53 | + int64_t softmaxPrecision, | ||
| 54 | + int64_t winLeft, | ||
| 55 | + int64_t winRight, | ||
| 56 | + const aclTensor *metadataOptional, | ||
| 57 | + uint64_t *workspaceSize, | ||
| 58 | + aclOpExecutor **executor); | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +```cpp | ||
| 62 | +aclnnStatus aclnnGenericBlockSparseAttentionMetadata( | ||
| 63 | + void *workspace, | ||
| 64 | + uint64_t workspaceSize, | ||
| 65 | + aclOpExecutor *executor, | ||
| 66 | + aclrtStream stream); | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +## aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize | ||
| 70 | + | ||
| 71 | +- **参数说明** | ||
| 72 | + | ||
| 73 | +<table style="undefined;table-layout: fixed; width: 1800px"><colgroup> | ||
| 74 | +<col style="width: 190px"><col style="width: 90px"><col style="width: 420px"><col style="width: 430px"> | ||
| 75 | +<col style="width: 100px"><col style="width: 90px"><col style="width: 280px"><col style="width: 100px"> | ||
| 76 | +</colgroup><thead><tr><th>参数名</th><th>输入/输出</th><th>描述</th><th>使用说明</th><th>数据类型</th><th>数据格式</th><th>维度(shape)</th><th>非连续Tensor</th></tr></thead><tbody> | ||
格式单行 ![]() ![]() | |||
| 77 | +<tr> | ||
| 78 | + <td>sparseBlockIdx</td> | ||
| 79 | + <td>输入</td> | ||
| 80 | + <td>稀疏块索引数组,指定每个Q块选择的KV块索引。</td> | ||
| 81 | + <td> | ||
| 82 | + 存储每个Q块选择的KV块索引,支持的shape随query布局变化: | ||
| 83 | + <ul> | ||
| 84 | + <li>query为TND布局时:</li> | ||
| 85 | + <ul> | ||
| 86 | + <li>每个qHead对应的KV稀疏pattern不一致(isPackedGQA=0):<br>[headNum, totalQBlocks, maxSparseBlockCount]</li> | ||
| 87 | + <li>GQA/MQA下,同group每个qHead对应的KV稀疏pattern一致(isPackedGQA=1):<br>[numKeyValueHeads, totalQBlocks, maxSparseBlockCount]</li> | ||
| 88 | + </ul> | ||
| 89 | + <li>query为BNSD/BSND布局时:</li> | ||
| 90 | + <ul> | ||
| 91 | + <li>每个qHead对应的KV稀疏pattern不一致(isPackedGQA=0):<br>[batch, headNum, ceilDiv(maxQSeqLength, blockShapeX), maxSparseBlockCount]</li> | ||
| 92 | + <li>GQA/MQA下,同group每个qHead对应的KV稀疏pattern一致(isPackedGQA=1):<br>[batch, numKeyValueHeads, ceilDiv(maxQSeqLength, blockShapeX), maxSparseBlockCount]</li> | ||
| 93 | + </ul> | ||
| 94 | + </ul> | ||
| 95 | + 其中 totalQBlocks = Σ ceilDiv(qStorageLen_i, blockShapeX),i 为 batch 索引;qStorageLen_i 为 cuSeqLengthsQOptional 前缀和差分得到的<strong>存储长度</strong>(与seqused双长度语义见约束说明)。 | ||
| 96 | +<br>maxSparseBlockCount为sparseBlockCount tensor中所有元素的最大值,即所有Q块选择的KV块数量的最大值。传入值须 >= 该最大值,当前上限为256。 | ||
| 97 | + </td> | ||
| 98 | + <td>INT32</td> | ||
| 99 | + <td>ND</td> | ||
| 100 | + <td>3/4</td> | ||
| 101 | + <td>×</td> | ||
| 102 | + </tr> | ||
| 103 | +<tr> | ||
| 104 | + <td>sparseBlockCount</td> | ||
| 105 | + <td>输入</td> | ||
| 106 | + <td>每个Q块实际选择的KV块数量。</td> | ||
| 107 | + <td> | ||
| 108 | + 存储每个Q块实际选择的KV块数量,支持的shape随query布局变化: | ||
| 109 | + <ul> | ||
| 110 | + <li>query为TND布局时:</li> | ||
| 111 | + <ul> | ||
| 112 | + <li>每个qHead对应的KV稀疏pattern不一致(isPackedGQA=0):<br>[headNum, totalQBlocks]</li> | ||
| 113 | + <li>GQA/MQA下,同group每个qHead对应的KV稀疏pattern一致(isPackedGQA=1):<br>[numKeyValueHeads, totalQBlocks]</li> | ||
| 114 | + </ul> | ||
| 115 | + <li>query为BNSD/BSND布局时:</li> | ||
| 116 | + <ul> | ||
| 117 | + <li>每个qHead对应的KV稀疏pattern不一致(isPackedGQA=0):<br>[batch, headNum, ceilDiv(maxQSeqLength, blockShapeX)]</li> | ||
| 118 | + <li>GQA/MQA下,同group每个qHead对应的KV稀疏pattern一致(isPackedGQA=1):<br>[batch, numKeyValueHeads, ceilDiv(maxQSeqLength, blockShapeX)]</li> | ||
| 119 | + </ul> | ||
| 120 | + </ul> | ||
| 121 | + </td> | ||
| 122 | + <td>INT32</td> | ||
| 123 | + <td>ND</td> | ||
| 124 | + <td>2/3</td> | ||
| 125 | + <td>×</td> | ||
| 126 | + </tr> | ||
| 127 | +<tr> | ||
| 128 | + <td>cuSeqLengthsQOptional</td> | ||
| 129 | + <td>输入</td> | ||
| 130 | + <td>描述每个Batch对应的query序列长度,以前缀和形式存储。</td> | ||
| 131 | + <td>可选输入,用于变长序列场景: | ||
| 132 | + <ul> | ||
| 133 | + <li>当layoutQ为"TND"时:该项输入必须配置</li> | ||
| 134 | + <li>当layoutQ为"BNSD""BSND"时:如配置该项输入,算子内会按该输入指定的实际序列长度进行处理;<br>如不配置该项输入(传入nullptr),算子内会按照query的shape中的S进行处理。</li> | ||
| 135 | + </ul> | ||
| 136 | + </td> | ||
| 137 | + <td>INT64</td> | ||
| 138 | + <td>-</td> | ||
| 139 | + <td>1</td> | ||
| 140 | + <td>-</td> | ||
| 141 | + </tr> | ||
| 142 | +<tr> | ||
| 143 | + <td>cuSeqLengthsKvOptional</td> | ||
| 144 | + <td>输入</td> | ||
| 145 | + <td>描述每个Batch对应的key/value序列长度,以前缀和形式存储。</td> | ||
| 146 | + <td>可选输入,用于变长序列场景: | ||
| 147 | + <ul> | ||
| 148 | + <li>当layoutKv为"TND"/"PAGED_BBND"/"PAGED_BNBD"时:该项输入必须配置</li> | ||
| 149 | + <li>当layoutKv为"BNSD""BSND"时:如配置该项输入,算子内会按该输入指定的实际序列长度进行处理;<br>如不配置该项输入(传入nullptr),算子内会按照key/value的shape中的S进行处理。</li> | ||
| 150 | + </ul> | ||
| 151 | + </td> | ||
| 152 | + <td>INT64</td> | ||
| 153 | + <td>-</td> | ||
| 154 | + <td>1</td> | ||
| 155 | + <td>-</td> | ||
| 156 | + </tr> | ||
| 157 | +<tr> | ||
| 158 | + <td>sequsedQOptional</td> | ||
| 159 | + <td>输入</td> | ||
| 160 | + <td>各batch中query的实际序列长度。</td> | ||
| 161 | + <td> | ||
| 162 | + <ul> | ||
| 163 | + <li>不指定序列长度可传入nullptr,表示和cuSeqLengthsQOptional差分得到的存储长度相同。</li> | ||
| 164 | + <li>综合约束请见<a href="#约束说明">约束说明</a>。</li> | ||
| 165 | + </ul> | ||
| 166 | + </td> | ||
| 167 | + <td>INT32</td> | ||
| 168 | + <td>ND</td> | ||
| 169 | + <td>1</td> | ||
| 170 | + <td>×</td> | ||
| 171 | + </tr> | ||
| 172 | +<tr> | ||
| 173 | + <td>sequsedKvOptional</td> | ||
| 174 | + <td>输入</td> | ||
| 175 | + <td>各batch中kv的实际序列长度。</td> | ||
| 176 | + <td> | ||
| 177 | + <ul> | ||
| 178 | + <li>不指定序列长度可传入nullptr,表示和cuSeqLengthsKvOptional差分得到的存储长度相同。</li> | ||
| 179 | + <li>综合约束请见<a href="#约束说明">约束说明</a>。</li> | ||
| 180 | + </ul> | ||
| 181 | + </td> | ||
| 182 | + <td>INT32</td> | ||
| 183 | + <td>ND</td> | ||
| 184 | + <td>1</td> | ||
| 185 | + <td>×</td> | ||
| 186 | + </tr> | ||
| 187 | +<tr> | ||
| 188 | + <td>maxQSeqLen</td> | ||
| 189 | + <td>输入</td> | ||
| 190 | + <td>主算子Query的最大Sequence Length。</td> | ||
| 191 | + <td>必须大于0,并与主算子Query及长度类输入保持一致。</td> | ||
| 192 | + <td>INT64</td> | ||
| 193 | + <td>-</td> | ||
| 194 | + <td>-</td> | ||
| 195 | + <td>-</td> | ||
| 196 | + </tr> | ||
| 197 | +<tr> | ||
| 198 | + <td>maxKvSeqLen</td> | ||
| 199 | + <td>输入</td> | ||
| 200 | + <td>主算子Key/Value的最大Sequence Length。</td> | ||
| 201 | + <td>必须大于0,并与主算子Key/Value及长度类输入保持一致。</td> | ||
| 202 | + <td>INT64</td> | ||
| 203 | + <td>-</td> | ||
| 204 | + <td>-</td> | ||
| 205 | + <td>-</td> | ||
| 206 | + </tr> | ||
| 207 | +<tr> | ||
| 208 | + <td>numQHeads</td> | ||
| 209 | + <td>输入</td> | ||
| 210 | + <td>主算子Query的head数。</td> | ||
| 211 | + <td>必须大于0,且须满足`numQHeads >= numKvHeads`、`numQHeads % numKvHeads == 0`和`numQHeads / numKvHeads <= 128`。</td> | ||
| 212 | + <td>INT64</td> | ||
| 213 | + <td>-</td> | ||
| 214 | + <td>-</td> | ||
| 215 | + <td>-</td> | ||
| 216 | + </tr> | ||
| 217 | +<tr> | ||
| 218 | + <td>numKvHeads</td> | ||
| 219 | + <td>输入</td> | ||
| 220 | + <td>主算子Key/Value的head数。</td> | ||
| 221 | + <td>必须大于0,并与主算子Key/Value的head数保持一致。</td> | ||
| 222 | + <td>INT64</td> | ||
| 223 | + <td>-</td> | ||
| 224 | + <td>-</td> | ||
| 225 | + <td>-</td> | ||
| 226 | + </tr> | ||
| 227 | +<tr> | ||
| 228 | + <td>headDim</td> | ||
| 229 | + <td>输入</td> | ||
| 230 | + <td>主算子Query、Key和Value每个head的特征维度。</td> | ||
| 231 | + <td>当前仅支持128。</td> | ||
| 232 | + <td>INT64</td> | ||
| 233 | + <td>-</td> | ||
| 234 | + <td>-</td> | ||
| 235 | + <td>-</td> | ||
| 236 | + </tr> | ||
| 237 | +<tr> | ||
| 238 | + <td>blockShape</td> | ||
| 239 | + <td>输入</td> | ||
| 240 | + <td>代表稀疏块形状数组。</td> | ||
| 241 | + <td>含两个元素[blockShapeX, blockShapeY]。<br>blockShapeX支持任意值,不可超过int64表示范围。<br>blockShapeY支持按16对齐的任意值,不可超过int64表示范围。<br>开启量化时的额外约束见「量化相关说明」。<br>当前仅支持blockShape=[1,128]。</td> | ||
| 242 | + <td>INT64</td> | ||
| 243 | + <td>-</td> | ||
| 244 | + <td>-</td> | ||
| 245 | + <td>-</td> | ||
| 246 | + </tr> | ||
| 247 | +<tr> | ||
| 248 | + <td>isPackedGQA</td> | ||
| 249 | + <td>输入</td> | ||
| 250 | + <td>代表进行块状稀疏时,同一个group内的qHead是否共享同样的稀疏pattern<br>(注:不同batch之间不会共享同样的稀疏pattern,该入参仅区分head维度的共享情况)。</td> | ||
| 251 | + <td>若取值为0,则代表同一个group内的qHead不共享同样的稀疏pattern;<br>若取值为1,则代表同一个group内的qHead共享同样的稀疏pattern。<br>当前仅支持1。</td> | ||
| 252 | + <td>INT64</td> | ||
| 253 | + <td>-</td> | ||
| 254 | + <td>-</td> | ||
| 255 | + <td>-</td> | ||
| 256 | + </tr> | ||
| 257 | +<tr> | ||
| 258 | + <td>layoutQ</td> | ||
| 259 | + <td>输入</td> | ||
| 260 | + <td>代表输入query的数据排布格式。</td> | ||
| 261 | + <td>目标支持"TND""BNSD""BSND",详见「layout对应关系说明」。当前仅支持"TND"。</td> | ||
| 262 | + <td>String</td> | ||
| 263 | + <td>-</td> | ||
| 264 | + <td>-</td> | ||
| 265 | + <td>-</td> | ||
| 266 | + </tr> | ||
| 267 | +<tr> | ||
| 268 | + <td>layoutKv</td> | ||
| 269 | + <td>输入</td> | ||
| 270 | + <td>代表输入key、value的数据排布格式。</td> | ||
| 271 | + <td>目标支持"TND""BNSD""BSND""PAGED_BBND""PAGED_BNBD",详见「layout对应关系说明」。当前仅支持"PAGED_BBND"。</td> | ||
| 272 | + <td>String</td> | ||
| 273 | + <td>-</td> | ||
| 274 | + <td>-</td> | ||
| 275 | + <td>-</td> | ||
| 276 | + </tr> | ||
| 277 | +<tr> | ||
| 278 | + <td>maskType</td> | ||
| 279 | + <td>输入</td> | ||
| 280 | + <td>表示attention计算中的掩码类型。</td> | ||
| 281 | + <td> | ||
| 282 | + 取值0~5,含义见「掩码说明」。<br> | ||
| 283 | + 当前仅支持1(causal mask)。 | ||
| 284 | + </td> | ||
| 285 | + <td>INT64</td> | ||
| 286 | + <td>-</td> | ||
| 287 | + <td>-</td> | ||
| 288 | + <td>-</td> | ||
| 289 | + </tr> | ||
| 290 | +<tr> | ||
| 291 | + <td>quantType</td> | ||
| 292 | + <td>输入</td> | ||
| 293 | + <td>代表采用的量化手段。</td> | ||
| 294 | + <td> | ||
| 295 | + 取值0~5,完整配置见「量化相关说明」:<br> | ||
| 296 | + 当前可用:0;Ascend 950上可选5。取值1~4传入将校验失败。 | ||
| 297 | + </td> | ||
| 298 | + <td>INT64</td> | ||
| 299 | + <td>-</td> | ||
| 300 | + <td>-</td> | ||
| 301 | + <td>-</td> | ||
| 302 | + </tr> | ||
| 303 | +<tr> | ||
| 304 | + <td>softmaxPrecision</td> | ||
| 305 | + <td>输入</td> | ||
| 306 | + <td>Softmax计算采取的精度级别。</td> | ||
| 307 | + <td> | ||
| 308 | + 控制online softmax阶段以及rescale阶段运算使用的数据类型。取值0或1: | ||
| 309 | + <ul> | ||
| 310 | + <li>0:online softmax和rescale全部采取fp32,适合追求计算精度的场景。</li> | ||
| 311 | + <li>1:混合精度;online softmax采取fp16/bf16(与attentionOut相同),rescale采取fp32,online softmax阶段可能数值溢出。</li> | ||
| 312 | + </ul> | ||
| 313 | + 芯片约束见「约束说明」(Ascend 950仅1;Atlas A2/A3上FP16可0/1,BF16仅0;FP8路径仅1)。 | ||
| 314 | + </td> | ||
| 315 | + <td>INT64</td> | ||
| 316 | + <td>-</td> | ||
| 317 | + <td>-</td> | ||
| 318 | + <td>-</td> | ||
| 319 | + </tr> | ||
| 320 | +<tr> | ||
| 321 | + <td>winLeft</td> | ||
| 322 | + <td>输入</td> | ||
| 323 | + <td>滑窗attention场景下,滑窗需要向前包含多少个token。</td> | ||
| 324 | + <td>用于滑窗attention;不使能时必须为-1,需与maskType配合,见「掩码说明」。当前只支持传入-1。</td> | ||
| 325 | + <td>INT64</td> | ||
| 326 | + <td>-</td> | ||
| 327 | + <td>-</td> | ||
| 328 | + <td>-</td> | ||
| 329 | + </tr> | ||
| 330 | +<tr> | ||
| 331 | + <td>winRight</td> | ||
| 332 | + <td>输入</td> | ||
| 333 | + <td>滑窗attention场景下,滑窗需要向后包含多少个token。</td> | ||
| 334 | + <td>用于滑窗attention;不使能时必须为-1,需与maskType配合,见「掩码说明」。当前只支持传入-1。</td> | ||
| 335 | + <td>INT64</td> | ||
| 336 | + <td>-</td> | ||
| 337 | + <td>-</td> | ||
| 338 | + <td>-</td> | ||
| 339 | + </tr> | ||
| 340 | +<tr> | ||
| 341 | + <td>metadataOptional</td> | ||
| 342 | + <td>输出</td> | ||
| 343 | + <td>AICPU算子aclnnGenericBlockSparseAttentionMetadata的分核结果。</td> | ||
| 344 | + <td> | ||
| 345 | + 必须传入。由aclnnGenericBlockSparseAttentionMetadata算子生成,每次调用主算子前须重新生成。调用者须预先申请INT32、shape为[1024]的Device侧Tensor;其内容为不透明格式,不应解析、修改或跨不同输入和属性复用。 | ||
| 346 | + </td> | ||
| 347 | + <td>INT32</td> | ||
| 348 | + <td>ND</td> | ||
| 349 | + <td>1</td> | ||
| 350 | + <td>×</td> | ||
| 351 | + </tr> | ||
| 352 | +<tr> | ||
| 353 | + <td>workspaceSize</td> | ||
| 354 | + <td>输出</td> | ||
| 355 | + <td>返回Device侧workspace大小。</td> | ||
| 356 | + <td>调用者应按返回值申请workspace。</td> | ||
| 357 | + <td>-</td> | ||
| 358 | + <td>-</td> | ||
| 359 | + <td>-</td> | ||
| 360 | + <td>-</td> | ||
| 361 | + </tr> | ||
| 362 | +<tr> | ||
| 363 | + <td>executor</td> | ||
| 364 | + <td>输出</td> | ||
| 365 | + <td>返回包含算子计算流程的执行器。</td> | ||
| 366 | + <td>不可为空。</td> | ||
| 367 | + <td>-</td> | ||
| 368 | + <td>-</td> | ||
| 369 | + <td>-</td> | ||
| 370 | + <td>-</td> | ||
| 371 | + </tr> | ||
| 372 | +</tbody></table> | ||
| 373 | + | ||
| 374 | +- **返回值** | ||
| 375 | + | ||
| 376 | + 返回`aclnnStatus`状态码,具体参见[aclnn返回码](../../../docs/zh/context/aclnn_return_code.md)。 | ||
| 377 | + | ||
| 378 | +## aclnnGenericBlockSparseAttentionMetadata | ||
| 379 | + | ||
| 380 | +- **参数说明** | ||
| 381 | + | ||
| 382 | +<table style="undefined;table-layout: fixed; width: 1200px"> | ||
| 383 | +<colgroup> | ||
| 384 | +<col style="width: 180px"> | ||
| 385 | +<col style="width: 120px"> | ||
| 386 | +<col style="width: 900px"> | ||
| 387 | +</colgroup> | ||
| 388 | +<thead> | ||
| 389 | +<tr> | ||
| 390 | + <th>参数名</th> | ||
| 391 | + <th>输入/输出</th> | ||
| 392 | + <th>描述</th> | ||
| 393 | + </tr> | ||
| 394 | +</thead> | ||
| 395 | +<tbody> | ||
| 396 | +<tr> | ||
| 397 | + <td>workspace</td> | ||
| 398 | + <td>输入</td> | ||
| 399 | + <td>Device侧workspace地址;workspaceSize为0时可传nullptr。</td> | ||
| 400 | + </tr> | ||
| 401 | +<tr> | ||
| 402 | + <td>workspaceSize</td> | ||
| 403 | + <td>输入</td> | ||
| 404 | + <td>第一段接口返回的workspace大小。</td> | ||
| 405 | + </tr> | ||
| 406 | +<tr> | ||
| 407 | + <td>executor</td> | ||
| 408 | + <td>输入</td> | ||
| 409 | + <td>第一段接口返回的执行器。</td> | ||
| 410 | + </tr> | ||
| 411 | +<tr> | ||
| 412 | + <td>stream</td> | ||
| 413 | + <td>输入</td> | ||
| 414 | + <td>执行任务的ACL Stream。</td> | ||
| 415 | + </tr> | ||
| 416 | +</tbody> | ||
| 417 | +</table> | ||
| 418 | + | ||
| 419 | +- **返回值** | ||
| 420 | + | ||
| 421 | + 返回`aclnnStatus`状态码,具体参见[aclnn返回码](../../../docs/zh/context/aclnn_return_code.md)。 | ||
| 422 | + | ||
| 423 | +## 约束说明 | ||
| 424 | + | ||
| 425 | +- 本接口必须与`aclnnGenericBlockSparseAttention`配套使用。所有对应的Tensor和属性须与随后调用的主算子完全一致,每次调用主算子前均须重新生成`metadataOptional`。 | ||
| 426 | +- `layoutQ`当前仅支持`"TND"`;`layoutKv`当前仅支持`"PAGED_BBND"`。 | ||
| 427 | +- `isPackedGQA`当前仅支持1。 | ||
| 428 | +- `maskType`当前仅支持1,表示算子内置causal mask;`winLeft`和`winRight`当前仅支持-1。 | ||
| 429 | +- `blockShape`当前仅支持`[1, 128]`,`headDim`当前仅支持128。 | ||
| 430 | +- 当前TND且`isPackedGQA=1`时,`sparseBlockIdx`的shape为`[numKvHeads, totalQBlocks, maxSparseBlockCount]`,`sparseBlockCount`的shape为`[numKvHeads, totalQBlocks]`。`totalQBlocks`按`cuSeqLengthsQOptional`前缀和差分得到的Query存储长度分块;`maxSparseBlockCount`须不小于`sparseBlockCount`中所有元素的最大值,且当前不超过256。 | ||
| 431 | +- `cuSeqLengthsQOptional`和`cuSeqLengthsKvOptional`当前必须传入,两者均为前缀和形式。 | ||
| 432 | +- `sequsedQOptional`和`sequsedKvOptional`可选。不传时,实际长度等于对应cu前缀和差分得到的存储长度;传入时,分核和任务空间按各Batch实际有效长度累加,稀疏块分块与QKV寻址仍按cu存储长度计算,每个元素须不大于对应Batch的存储长度。 | ||
| 433 | +- `quantType`当前支持0;Ascend 950上可选5。取值1~4当前不支持。取5时,主算子Query、Key、Value须为FLOAT8_E4M3FN,attentionOut须为FLOAT16或BFLOAT16。 | ||
| 434 | +- `softmaxPrecision`取值为0或1:Ascend 950仅支持1;Atlas A2/A3上,FLOAT16支持0或1,BFLOAT16仅支持0;FLOAT8路径仅支持1。 | ||
| 435 | +- `numQHeads`和`numKvHeads`须满足`numQHeads >= numKvHeads`且`numQHeads % numKvHeads == 0`;`groupSize = numQHeads / numKvHeads`当前须不超过128。 | ||
| 436 | +- 输出`metadataOptional`固定为INT32、shape为`[1024]`,对应主算子的`metadataOptional`输入,不得解析、修改或跨不同输入和属性复用。 | ||
| 437 | + | ||
| 438 | +## 调用示例 | ||
| 439 | + | ||
| 440 | +以下示例展示两段式接口调用顺序。Tensor创建、输入拷贝和资源释放方式请参考[编译与运行样例](../../../docs/zh/context/compile_and_run_sample.md)。 | ||
| 441 | + | ||
| 442 | +```cpp | ||
| 443 | +#include "acl/acl.h" | ||
| 444 | +#include "aclnnop/aclnn_generic_block_sparse_attention_metadata.h" | ||
| 445 | + | ||
| 446 | +aclnnStatus RunMetadata(const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, | ||
| 447 | + const aclTensor *cuSeqLengthsQOptional, const aclTensor *cuSeqLengthsKvOptional, | ||
| 448 | + aclTensor *metadataOptional, aclrtStream stream) | ||
| 449 | +{ | ||
| 450 | + const int64_t blockShapeData[] = {1, 128}; | ||
| 451 | + aclIntArray *blockShape = aclCreateIntArray(blockShapeData, 2); | ||
| 452 | + if (blockShape == nullptr) { | ||
| 453 | + return ACL_ERROR_BAD_ALLOC; | ||
| 454 | + } | ||
| 455 | + uint64_t workspaceSize = 0; | ||
| 456 | + aclOpExecutor *executor = nullptr; | ||
| 457 | + aclnnStatus ret = aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize( | ||
| 458 | + sparseBlockIdx, sparseBlockCount, cuSeqLengthsQOptional, cuSeqLengthsKvOptional, nullptr, nullptr, | ||
| 459 | + 16, 2048, 32, 8, 128, blockShape, 1, "TND", "PAGED_BBND", | ||
| 460 | + 1, 0, 0, -1, -1, metadataOptional, &workspaceSize, &executor); | ||
| 461 | + aclDestroyIntArray(blockShape); | ||
| 462 | + if (ret != ACL_SUCCESS) { | ||
| 463 | + return ret; | ||
| 464 | + } | ||
| 465 | + void *workspace = nullptr; | ||
| 466 | + if (workspaceSize > 0) { | ||
| 467 | + ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 468 | + if (ret != ACL_SUCCESS) { | ||
| 469 | + return ret; | ||
| 470 | + } | ||
| 471 | + } | ||
| 472 | + ret = aclnnGenericBlockSparseAttentionMetadata(workspace, workspaceSize, executor, stream); | ||
| 473 | + if (ret == ACL_SUCCESS) { | ||
| 474 | + ret = aclrtSynchronizeStream(stream); | ||
| 475 | + } | ||
| 476 | + if (workspace != nullptr) { | ||
| 477 | + aclrtFree(workspace); | ||
| 478 | + } | ||
| 479 | + return ret; | ||
| 480 | +} | ||
| 481 | +``` | ||
| @@ -0,0 +1,414 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/** | ||
| 12 | + * @file test_aclnn_generic_block_sparse_attention_metadata.cpp | ||
| 13 | + */ | ||
| 14 | +#include <algorithm> | ||
| 15 | +#include <cstdint> | ||
| 16 | +#include <cstdio> | ||
| 17 | +#include <cstdlib> | ||
| 18 | +#include <functional> | ||
| 19 | +#include <string> | ||
| 20 | +#include <utility> | ||
| 21 | +#include <vector> | ||
| 22 | + | ||
| 23 | +#include "acl/acl.h" | ||
| 24 | +#include "aclnnop/aclnn_generic_block_sparse_attention_metadata.h" | ||
| 25 | +#include "securec.h" | ||
| 26 | + | ||
| 27 | +#include "../generic_block_sparse_attention_metadata.h" | ||
| 28 | + | ||
| 29 | +#define CHECK_LOG_RET(condition, returnValue, format, ...) \ | ||
| 30 | + do { \ | ||
| 31 | + if (!(condition)) { \ | ||
| 32 | + std::printf(format "\n", ##__VA_ARGS__); \ | ||
| 33 | + return (returnValue); \ | ||
| 34 | + } \ | ||
| 35 | + } while (0) | ||
| 36 | + | ||
| 37 | +namespace { | ||
| 38 | + | ||
| 39 | +namespace metadata_protocol = optiling::generic_block_sparse_attention_metadata; | ||
| 40 | + | ||
| 41 | +constexpr int32_t INVALID_BLOCK_INDEX = -1; | ||
| 42 | +constexpr int32_t DEVICE_ID_ARG_INDEX = 1; | ||
| 43 | +constexpr int64_t GBSA_BLOCK_SHAPE_X = 1; | ||
| 44 | +constexpr int64_t GBSA_BLOCK_SHAPE_Y = 128; | ||
| 45 | +constexpr int64_t GBSA_HEAD_DIM = 128; | ||
| 46 | +constexpr int64_t GBSA_IS_PACKED_GQA = 1; | ||
| 47 | +constexpr int64_t GBSA_MASK_TYPE = 1; | ||
| 48 | +constexpr int64_t GBSA_QUANT_TYPE = 0; | ||
| 49 | +constexpr int64_t GBSA_SOFTMAX_PRECISION = 0; | ||
| 50 | +constexpr int64_t GBSA_WINDOW_SIZE = -1; | ||
| 51 | + | ||
| 52 | +struct ScopeGuard { | ||
| 53 | + explicit ScopeGuard(std::function<void()> callback) | ||
| 54 | + : callback_(std::move(callback)) | ||
| 55 | + {} | ||
| 56 | + ScopeGuard(const ScopeGuard &) = delete; | ||
| 57 | + ScopeGuard &operator=(const ScopeGuard &) = delete; | ||
| 58 | + ~ScopeGuard() | ||
| 59 | + { | ||
| 60 | + callback_(); | ||
| 61 | + } | ||
| 62 | + | ||
| 63 | +private: | ||
| 64 | + std::function<void()> callback_; | ||
| 65 | +}; | ||
| 66 | + | ||
| 67 | +struct Tensor { | ||
| 68 | + void *hostAddr = nullptr; | ||
| 69 | + void *deviceAddr = nullptr; | ||
| 70 | + aclTensor *tensor = nullptr; | ||
| 71 | + size_t byteSize = 0U; | ||
| 72 | +}; | ||
| 73 | + | ||
| 74 | +struct CaseContext { | ||
| 75 | + std::string name; | ||
| 76 | + Tensor sparseBlockIdx; | ||
| 77 | + Tensor sparseBlockCount; | ||
| 78 | + Tensor cuSeqLengths; | ||
| 79 | + Tensor cuSeqLengthsKv; | ||
| 80 | + Tensor seqUsedQ; | ||
| 81 | + Tensor seqUsedKv; | ||
| 82 | + Tensor metadata; | ||
| 83 | + aclIntArray *blockShape = nullptr; | ||
| 84 | + int64_t maxQSeqLen = 0; | ||
| 85 | + int64_t maxKvSeqLen = 0; | ||
| 86 | + int64_t numQHeads = 0; | ||
| 87 | + int64_t numKvHeads = 0; | ||
| 88 | + int64_t headDim = 0; | ||
| 89 | + const char *qInputLayout = nullptr; | ||
| 90 | + const char *kvInputLayout = nullptr; | ||
| 91 | + int32_t expectedSaTotalTaskNum = 0; | ||
| 92 | + bool expectDecodeSchedule = false; | ||
| 93 | +}; | ||
| 94 | + | ||
| 95 | +int64_t GetElementNum(const std::vector<int64_t> &shape) | ||
| 96 | +{ | ||
| 97 | + int64_t elementNum = 1; | ||
| 98 | + for (const int64_t dim : shape) { | ||
| 99 | + elementNum *= dim; | ||
| 100 | + } | ||
| 101 | + return elementNum; | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +aclnnStatus CreateTensor(aclDataType dataType, const std::vector<int64_t> &shape, const void *hostData, Tensor &tensor) | ||
| 105 | +{ | ||
| 106 | + tensor.byteSize = static_cast<size_t>(GetElementNum(shape)) * aclDataTypeSize(dataType); | ||
| 107 | + aclError ret = aclrtMallocHost(&tensor.hostAddr, tensor.byteSize); | ||
| 108 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMallocHost failed, error: %d", ret); | ||
| 109 | + if (hostData == nullptr) { | ||
| 110 | + const errno_t memsetRet = memset_s(tensor.hostAddr, tensor.byteSize, 0, tensor.byteSize); | ||
| 111 | + CHECK_LOG_RET(memsetRet == EOK, ACL_ERROR_FAILURE, "memset_s tensor host memory failed, error: %d", memsetRet); | ||
| 112 | + } else { | ||
| 113 | + const errno_t memcpyRet = memcpy_s(tensor.hostAddr, tensor.byteSize, hostData, tensor.byteSize); | ||
| 114 | + CHECK_LOG_RET(memcpyRet == EOK, ACL_ERROR_FAILURE, "memcpy_s tensor host data failed, error: %d", memcpyRet); | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + ret = aclrtMalloc(&tensor.deviceAddr, tensor.byteSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 118 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMalloc failed, error: %d", ret); | ||
| 119 | + tensor.tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, ACL_FORMAT_ND, shape.data(), | ||
| 120 | + shape.size(), tensor.deviceAddr); | ||
| 121 | + CHECK_LOG_RET(tensor.tensor != nullptr, ACL_ERROR_BAD_ALLOC, "aclCreateTensor failed"); | ||
| 122 | + | ||
| 123 | + ret = aclrtMemcpy(tensor.deviceAddr, tensor.byteSize, tensor.hostAddr, tensor.byteSize, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 124 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "copy tensor to device failed, error: %d", ret); | ||
| 125 | + return ACL_SUCCESS; | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +template <typename T> | ||
| 129 | +aclnnStatus CreateTensor(aclDataType dataType, const std::vector<int64_t> &shape, const std::vector<T> &hostData, | ||
| 130 | + Tensor &tensor) | ||
| 131 | +{ | ||
| 132 | + const int64_t elementNum = GetElementNum(shape); | ||
| 133 | + CHECK_LOG_RET(elementNum == static_cast<int64_t>(hostData.size()), ACL_ERROR_INVALID_PARAM, | ||
| 134 | + "tensor shape and host data size do not match"); | ||
| 135 | + return CreateTensor(dataType, shape, hostData.data(), tensor); | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +void DestroyTensor(Tensor &tensor) | ||
| 139 | +{ | ||
| 140 | + if (tensor.tensor != nullptr) { | ||
| 141 | + aclDestroyTensor(tensor.tensor); | ||
| 142 | + tensor.tensor = nullptr; | ||
| 143 | + } | ||
| 144 | + if (tensor.deviceAddr != nullptr) { | ||
| 145 | + aclrtFree(tensor.deviceAddr); | ||
| 146 | + tensor.deviceAddr = nullptr; | ||
| 147 | + } | ||
| 148 | + if (tensor.hostAddr != nullptr) { | ||
| 149 | + aclrtFreeHost(tensor.hostAddr); | ||
| 150 | + tensor.hostAddr = nullptr; | ||
| 151 | + } | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +void DestroyCase(CaseContext &context) | ||
| 155 | +{ | ||
| 156 | + DestroyTensor(context.sparseBlockIdx); | ||
| 157 | + DestroyTensor(context.sparseBlockCount); | ||
| 158 | + DestroyTensor(context.cuSeqLengths); | ||
| 159 | + DestroyTensor(context.cuSeqLengthsKv); | ||
| 160 | + DestroyTensor(context.seqUsedQ); | ||
| 161 | + DestroyTensor(context.seqUsedKv); | ||
| 162 | + DestroyTensor(context.metadata); | ||
| 163 | + if (context.blockShape != nullptr) { | ||
| 164 | + aclDestroyIntArray(context.blockShape); | ||
| 165 | + context.blockShape = nullptr; | ||
| 166 | + } | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +std::vector<int32_t> MakeSparseBlockIndices(const std::vector<int32_t> &blockCounts, int64_t capacity) | ||
| 170 | +{ | ||
| 171 | + std::vector<int32_t> indices(blockCounts.size() * static_cast<size_t>(capacity), INVALID_BLOCK_INDEX); | ||
| 172 | + for (size_t task = 0; task < blockCounts.size(); ++task) { | ||
| 173 | + for (int32_t block = 0; block < blockCounts[task]; ++block) { | ||
| 174 | + indices[task * static_cast<size_t>(capacity) + static_cast<size_t>(block)] = block; | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | + return indices; | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +aclnnStatus CreateCommonArgs(CaseContext &context) | ||
| 181 | +{ | ||
| 182 | + const std::vector<int64_t> blockShapeData = {GBSA_BLOCK_SHAPE_X, GBSA_BLOCK_SHAPE_Y}; | ||
| 183 | + context.blockShape = aclCreateIntArray(blockShapeData.data(), blockShapeData.size()); | ||
| 184 | + CHECK_LOG_RET(context.blockShape != nullptr, ACL_ERROR_BAD_ALLOC, "aclCreateIntArray failed"); | ||
| 185 | + return CreateTensor(ACL_INT32, {metadata_protocol::METADATA_TOTAL_SIZE}, nullptr, context.metadata); | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +aclnnStatus CreateTndDecodeCase(CaseContext &context) | ||
| 189 | +{ | ||
| 190 | + constexpr int64_t batchSize = 1; | ||
| 191 | + constexpr int64_t qStorageLength = 2; | ||
| 192 | + constexpr int64_t kvStorageLength = 2048; | ||
| 193 | + constexpr int64_t numQHeads = 4; | ||
| 194 | + constexpr int64_t numKvHeads = 1; | ||
| 195 | + constexpr int64_t sparseBlockCapacity = 12; | ||
| 196 | + constexpr int32_t firstQBlockCount = 12; | ||
| 197 | + constexpr int32_t secondQBlockCount = 3; | ||
| 198 | + | ||
| 199 | + context.name = "TND decode schedule"; | ||
| 200 | + context.maxQSeqLen = qStorageLength; | ||
| 201 | + context.maxKvSeqLen = kvStorageLength; | ||
| 202 | + context.numQHeads = numQHeads; | ||
| 203 | + context.numKvHeads = numKvHeads; | ||
| 204 | + context.headDim = GBSA_HEAD_DIM; | ||
| 205 | + context.qInputLayout = "TND"; | ||
| 206 | + context.kvInputLayout = "PAGED_BBND"; | ||
| 207 | + context.expectedSaTotalTaskNum = static_cast<int32_t>(qStorageLength * numKvHeads); | ||
| 208 | + context.expectDecodeSchedule = true; | ||
| 209 | + | ||
| 210 | + const std::vector<int32_t> blockCounts = {firstQBlockCount, secondQBlockCount}; | ||
| 211 | + const std::vector<int32_t> blockIndices = MakeSparseBlockIndices(blockCounts, sparseBlockCapacity); | ||
| 212 | + aclnnStatus ret = CreateTensor(ACL_INT32, {numKvHeads, qStorageLength, sparseBlockCapacity}, blockIndices, | ||
| 213 | + context.sparseBlockIdx); | ||
| 214 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND sparseBlockIdx failed, error: %d", ret); | ||
| 215 | + ret = CreateTensor(ACL_INT32, {numKvHeads, qStorageLength}, blockCounts, context.sparseBlockCount); | ||
| 216 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND sparseBlockCount failed, error: %d", ret); | ||
| 217 | + const std::vector<int64_t> cuSeqLengths = {0, qStorageLength}; | ||
| 218 | + ret = CreateTensor(ACL_INT64, {static_cast<int64_t>(cuSeqLengths.size())}, cuSeqLengths, context.cuSeqLengths); | ||
| 219 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND cuSeqLengths failed, error: %d", ret); | ||
| 220 | + const std::vector<int64_t> cuSeqLengthsKv = {0, kvStorageLength}; | ||
| 221 | + ret = | ||
| 222 | + CreateTensor(ACL_INT64, {static_cast<int64_t>(cuSeqLengthsKv.size())}, cuSeqLengthsKv, context.cuSeqLengthsKv); | ||
| 223 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND cuSeqLengthsKv failed, error: %d", ret); | ||
| 224 | + const std::vector<int32_t> seqUsedQ = {static_cast<int32_t>(qStorageLength)}; | ||
| 225 | + ret = CreateTensor(ACL_INT32, {batchSize}, seqUsedQ, context.seqUsedQ); | ||
| 226 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND seqUsedQ failed, error: %d", ret); | ||
| 227 | + return CreateCommonArgs(context); | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +aclnnStatus CreateTndSeqUsedCase(CaseContext &context) | ||
| 231 | +{ | ||
| 232 | + constexpr int64_t batchSize = 2; | ||
| 233 | + constexpr int64_t qStorageLengthPerBatch = 4; | ||
| 234 | + constexpr int64_t totalQStorageLength = batchSize * qStorageLengthPerBatch; | ||
| 235 | + constexpr int64_t kvStorageLengthPerBatch = 2048; | ||
| 236 | + constexpr int64_t numQHeads = 4; | ||
| 237 | + constexpr int64_t numKvHeads = 1; | ||
| 238 | + constexpr int64_t sparseBlockCapacity = totalQStorageLength; | ||
| 239 | + constexpr int32_t firstBatchUsedQ = 2; | ||
| 240 | + constexpr int32_t secondBatchUsedQ = 3; | ||
| 241 | + constexpr int32_t firstBlockCount = 1; | ||
| 242 | + | ||
| 243 | + context.name = "TND cuSeqLengths and seqUsedQ"; | ||
| 244 | + context.maxQSeqLen = qStorageLengthPerBatch; | ||
| 245 | + context.maxKvSeqLen = kvStorageLengthPerBatch; | ||
| 246 | + context.numQHeads = numQHeads; | ||
| 247 | + context.numKvHeads = numKvHeads; | ||
| 248 | + context.headDim = GBSA_HEAD_DIM; | ||
| 249 | + context.qInputLayout = "TND"; | ||
| 250 | + context.kvInputLayout = "PAGED_BBND"; | ||
| 251 | + context.expectedSaTotalTaskNum = (firstBatchUsedQ + secondBatchUsedQ) * static_cast<int32_t>(numKvHeads); | ||
| 252 | + | ||
| 253 | + // The two batches occupy physical Q ranges [0, 4) and [4, 8). seqUsedQ selects [0, 2) and [4, 7). | ||
| 254 | + const std::vector<int64_t> cuSeqLengths = {0, qStorageLengthPerBatch, totalQStorageLength}; | ||
| 255 | + const std::vector<int32_t> seqUsedQ = {firstBatchUsedQ, secondBatchUsedQ}; | ||
| 256 | + std::vector<int32_t> blockCounts(static_cast<size_t>(totalQStorageLength)); | ||
| 257 | + for (size_t index = 0; index < blockCounts.size(); ++index) { | ||
| 258 | + blockCounts[index] = firstBlockCount + static_cast<int32_t>(index); | ||
| 259 | + } | ||
| 260 | + const std::vector<int32_t> blockIndices = MakeSparseBlockIndices(blockCounts, sparseBlockCapacity); | ||
| 261 | + aclnnStatus ret = CreateTensor(ACL_INT32, {numKvHeads, totalQStorageLength, sparseBlockCapacity}, blockIndices, | ||
| 262 | + context.sparseBlockIdx); | ||
| 263 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND sparseBlockIdx failed, error: %d", ret); | ||
| 264 | + ret = CreateTensor(ACL_INT32, {numKvHeads, totalQStorageLength}, blockCounts, context.sparseBlockCount); | ||
| 265 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND sparseBlockCount failed, error: %d", ret); | ||
| 266 | + ret = CreateTensor(ACL_INT64, {static_cast<int64_t>(cuSeqLengths.size())}, cuSeqLengths, context.cuSeqLengths); | ||
| 267 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND cuSeqLengths failed, error: %d", ret); | ||
| 268 | + const std::vector<int64_t> cuSeqLengthsKv = {0, kvStorageLengthPerBatch, batchSize * kvStorageLengthPerBatch}; | ||
| 269 | + ret = | ||
| 270 | + CreateTensor(ACL_INT64, {static_cast<int64_t>(cuSeqLengthsKv.size())}, cuSeqLengthsKv, context.cuSeqLengthsKv); | ||
| 271 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND cuSeqLengthsKv failed, error: %d", ret); | ||
| 272 | + ret = CreateTensor(ACL_INT32, {batchSize}, seqUsedQ, context.seqUsedQ); | ||
| 273 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND seqUsedQ failed, error: %d", ret); | ||
| 274 | + return CreateCommonArgs(context); | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +void PrintMetadata(const std::string &caseName, const int32_t *metadata) | ||
| 278 | +{ | ||
| 279 | + using namespace metadata_protocol; | ||
| 280 | + std::printf("\n[%s]\n", caseName.c_str()); | ||
| 281 | + std::printf("header: magic=0x%08X, version=%d, usedSize=%d, saUsedCoreNum=%d, saTotalTaskNum=%d, " | ||
| 282 | + "fdActiveCoreNum=%d, decodePerCoreTaskNum=%d, combineTaskNum=%d\n", | ||
| 283 | + static_cast<uint32_t>(metadata[MAGIC_INDEX]), metadata[VERSION_INDEX], | ||
| 284 | + metadata[METADATA_USED_SIZE_INDEX], metadata[SA_USED_CORE_NUM_INDEX], metadata[SA_TOTAL_TASK_NUM_INDEX], | ||
| 285 | + metadata[FD_ACTIVE_CORE_NUM_INDEX], metadata[DECODE_PER_CORE_TASK_NUM_INDEX], | ||
| 286 | + metadata[COMBINE_TASK_NUM_INDEX]); | ||
| 287 | + | ||
| 288 | + const int32_t decodeCoreNum = std::min<int32_t>(metadata[FD_ACTIVE_CORE_NUM_INDEX], MAX_DECODE_CORE_NUM); | ||
| 289 | + for (int32_t core = 0; core < decodeCoreNum; ++core) { | ||
| 290 | + std::printf("decode[%d]: baseTask=[%d, %d), firstBlockStart=%d, lastBlockEnd=%d\n", core, | ||
| 291 | + metadata[GetDecodeScheduleIndex(core, DECODE_BASE_TASK_START_INDEX)], | ||
| 292 | + metadata[GetDecodeScheduleIndex(core, DECODE_BASE_TASK_END_INDEX)], | ||
| 293 | + metadata[GetDecodeScheduleIndex(core, DECODE_FIRST_BLOCK_START_INDEX)], | ||
| 294 | + metadata[GetDecodeScheduleIndex(core, DECODE_LAST_BLOCK_END_INDEX)]); | ||
| 295 | + } | ||
| 296 | + const int32_t combineTaskNum = std::min<int32_t>(metadata[COMBINE_TASK_NUM_INDEX], MAX_COMBINE_TASK_NUM); | ||
| 297 | + for (int32_t combine = 0; combine < combineTaskNum; ++combine) { | ||
| 298 | + std::printf("combine[%d]: baseTask=%d, firstCore=%d, partialStart=%d, partialCount=%d\n", combine, | ||
| 299 | + metadata[GetCombineScheduleIndex(combine, COMBINE_BASE_TASK_INDEX)], | ||
| 300 | + metadata[GetCombineScheduleIndex(combine, COMBINE_FIRST_CORE_INDEX)], | ||
| 301 | + metadata[GetCombineScheduleIndex(combine, COMBINE_PARTIAL_START_INDEX)], | ||
| 302 | + metadata[GetCombineScheduleIndex(combine, COMBINE_PARTIAL_COUNT_INDEX)]); | ||
| 303 | + } | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +aclnnStatus ValidateMetadata(const CaseContext &context, const int32_t *metadata) | ||
| 307 | +{ | ||
| 308 | + using namespace metadata_protocol; | ||
| 309 | + CHECK_LOG_RET(metadata[MAGIC_INDEX] == METADATA_MAGIC, ACL_ERROR_FAILURE, "%s: unexpected metadata magic", | ||
| 310 | + context.name.c_str()); | ||
| 311 | + CHECK_LOG_RET(metadata[VERSION_INDEX] == METADATA_VERSION, ACL_ERROR_FAILURE, "%s: unexpected metadata version", | ||
| 312 | + context.name.c_str()); | ||
| 313 | + CHECK_LOG_RET(metadata[METADATA_USED_SIZE_INDEX] == static_cast<int32_t>(METADATA_USED_SIZE), ACL_ERROR_FAILURE, | ||
| 314 | + "%s: unexpected metadata used size", context.name.c_str()); | ||
| 315 | + CHECK_LOG_RET(metadata[SA_TOTAL_TASK_NUM_INDEX] == context.expectedSaTotalTaskNum, ACL_ERROR_FAILURE, | ||
| 316 | + "%s: expected saTotalTaskNum=%d, but got %d", context.name.c_str(), context.expectedSaTotalTaskNum, | ||
| 317 | + metadata[SA_TOTAL_TASK_NUM_INDEX]); | ||
| 318 | + CHECK_LOG_RET( | ||
| 319 | + metadata[SA_USED_CORE_NUM_INDEX] > 0 && metadata[SA_USED_CORE_NUM_INDEX] <= metadata[SA_TOTAL_TASK_NUM_INDEX], | ||
| 320 | + ACL_ERROR_FAILURE, "%s: invalid saUsedCoreNum=%d", context.name.c_str(), metadata[SA_USED_CORE_NUM_INDEX]); | ||
| 321 | + if (context.expectDecodeSchedule) { | ||
| 322 | + CHECK_LOG_RET(metadata[FD_ACTIVE_CORE_NUM_INDEX] > 0, ACL_ERROR_FAILURE, "%s: DecodeSchedule was not generated", | ||
| 323 | + context.name.c_str()); | ||
| 324 | + CHECK_LOG_RET(metadata[COMBINE_TASK_NUM_INDEX] > 0, ACL_ERROR_FAILURE, "%s: CombineSchedule was not generated", | ||
| 325 | + context.name.c_str()); | ||
| 326 | + } | ||
| 327 | + return ACL_SUCCESS; | ||
| 328 | +} | ||
| 329 | + | ||
| 330 | +aclnnStatus RunCase(CaseContext &context, aclrtStream stream) | ||
| 331 | +{ | ||
| 332 | + uint64_t workspaceSize = 0U; | ||
| 333 | + aclOpExecutor *executor = nullptr; | ||
| 334 | + aclnnStatus ret = aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize( | ||
| 335 | + context.sparseBlockIdx.tensor, context.sparseBlockCount.tensor, context.cuSeqLengths.tensor, | ||
| 336 | + context.cuSeqLengthsKv.tensor, context.seqUsedQ.tensor, context.seqUsedKv.tensor, context.maxQSeqLen, | ||
| 337 | + context.maxKvSeqLen, context.numQHeads, context.numKvHeads, context.headDim, context.blockShape, | ||
| 338 | + GBSA_IS_PACKED_GQA, context.qInputLayout, context.kvInputLayout, GBSA_MASK_TYPE, GBSA_QUANT_TYPE, | ||
| 339 | + GBSA_SOFTMAX_PRECISION, GBSA_WINDOW_SIZE, GBSA_WINDOW_SIZE, context.metadata.tensor, &workspaceSize, &executor); | ||
| 340 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, | ||
| 341 | + "%s: aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize failed, error: %d", | ||
| 342 | + context.name.c_str(), ret); | ||
| 343 | + | ||
| 344 | + void *workspace = nullptr; | ||
| 345 | + if (workspaceSize > 0U) { | ||
| 346 | + ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 347 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "%s: allocate workspace failed, error: %d", context.name.c_str(), ret); | ||
| 348 | + } | ||
| 349 | + ScopeGuard workspaceGuard([&workspace]() { | ||
| 350 | + if (workspace != nullptr) { | ||
| 351 | + aclrtFree(workspace); | ||
| 352 | + } | ||
| 353 | + }); | ||
| 354 | + | ||
| 355 | + ret = aclnnGenericBlockSparseAttentionMetadata(workspace, workspaceSize, executor, stream); | ||
| 356 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "%s: execute metadata failed, error: %d", context.name.c_str(), ret); | ||
| 357 | + ret = aclrtSynchronizeStream(stream); | ||
| 358 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "%s: synchronize stream failed, error: %d", context.name.c_str(), ret); | ||
| 359 | + ret = aclrtMemcpy(context.metadata.hostAddr, context.metadata.byteSize, context.metadata.deviceAddr, | ||
| 360 | + context.metadata.byteSize, ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 361 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "%s: copy metadata to host failed, error: %d", context.name.c_str(), ret); | ||
| 362 | + | ||
| 363 | + const auto *metadata = static_cast<const int32_t *>(context.metadata.hostAddr); | ||
| 364 | + PrintMetadata(context.name, metadata); | ||
| 365 | + return ValidateMetadata(context, metadata); | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +aclnnStatus InitAcl(int32_t deviceId, aclrtStream &stream) | ||
| 369 | +{ | ||
| 370 | + aclError ret = aclInit(nullptr); | ||
| 371 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclInit failed, error: %d", ret); | ||
| 372 | + ret = aclrtSetDevice(deviceId); | ||
| 373 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtSetDevice failed, error: %d", ret); | ||
| 374 | + ret = aclrtCreateStream(&stream); | ||
| 375 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtCreateStream failed, error: %d", ret); | ||
| 376 | + return ACL_SUCCESS; | ||
| 377 | +} | ||
| 378 | + | ||
| 379 | +void FinalizeAcl(int32_t deviceId, aclrtStream stream) | ||
| 380 | +{ | ||
| 381 | + if (stream != nullptr) { | ||
| 382 | + aclrtDestroyStream(stream); | ||
| 383 | + } | ||
| 384 | + aclrtResetDevice(deviceId); | ||
| 385 | + aclFinalize(); | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +} // namespace | ||
| 389 | + | ||
| 390 | +int main(int argc, char *argv[]) | ||
| 391 | +{ | ||
| 392 | + const int32_t deviceId = argc > DEVICE_ID_ARG_INDEX ? std::atoi(argv[DEVICE_ID_ARG_INDEX]) : 0; | ||
| 393 | + aclrtStream stream = nullptr; | ||
| 394 | + aclnnStatus ret = InitAcl(deviceId, stream); | ||
| 395 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "initialize ACL failed, error: %d", ret); | ||
| 396 | + ScopeGuard aclGuard([&stream, deviceId]() { FinalizeAcl(deviceId, stream); }); | ||
| 397 | + | ||
| 398 | + CaseContext decodeContext; | ||
| 399 | + ScopeGuard decodeGuard([&decodeContext]() { DestroyCase(decodeContext); }); | ||
| 400 | + ret = CreateTndDecodeCase(decodeContext); | ||
| 401 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND decode example failed, error: %d", ret); | ||
| 402 | + ret = RunCase(decodeContext, stream); | ||
| 403 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "run TND decode example failed, error: %d", ret); | ||
| 404 | + | ||
| 405 | + CaseContext tndContext; | ||
| 406 | + ScopeGuard tndGuard([&tndContext]() { DestroyCase(tndContext); }); | ||
| 407 | + ret = CreateTndSeqUsedCase(tndContext); | ||
| 408 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "create TND example failed, error: %d", ret); | ||
| 409 | + ret = RunCase(tndContext, stream); | ||
| 410 | + CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "run TND example failed, error: %d", ret); | ||
| 411 | + | ||
| 412 | + std::printf("\nAll GenericBlockSparseAttentionMetadata examples passed.\n"); | ||
| 413 | + return ACL_SUCCESS; | ||
| 414 | +} | ||
| @@ -0,0 +1,89 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| 12 | +#define GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| 13 | + | ||
| 14 | +#include <cstdint> | ||
| 15 | + | ||
| 16 | +namespace optiling { | ||
| 17 | +namespace generic_block_sparse_attention_metadata { | ||
| 18 | + | ||
| 19 | +using MetadataType = int32_t; | ||
| 20 | + | ||
| 21 | +constexpr uint32_t METADATA_TOTAL_SIZE = 1024U; | ||
| 22 | +constexpr uint32_t MAX_AIC_CORE_NUM = 36U; | ||
| 23 | +constexpr uint32_t MAX_DECODE_CORE_NUM = 32U; | ||
| 24 | +constexpr uint32_t MAX_COMBINE_TASK_NUM = 32U; | ||
| 25 | +// FD scheduling capacity is independent from sparseBlockIdx.shape[-1]. | ||
| 26 | +constexpr uint32_t MAX_FD_ACTIVE_CORE_NUM = MAX_DECODE_CORE_NUM; | ||
| 27 | +constexpr uint32_t MAX_FD_PARTIAL_PER_BASE_TASK = MAX_DECODE_CORE_NUM; | ||
| 28 | +constexpr uint32_t MAX_SPARSE_BLOCK_CAPACITY = 16U; | ||
| 29 | +constexpr MetadataType METADATA_MAGIC = 0x5341534D; | ||
| 30 | +constexpr MetadataType METADATA_VERSION = 8; | ||
| 31 | + | ||
| 32 | +enum FdScheduleFlag : uint32_t { | ||
| 33 | + FD_SCHEDULE_ENABLED = 1U << 0, | ||
| 34 | + FD_ACTUAL_BLOCK_PREFIX = 1U << 1, | ||
| 35 | +}; | ||
| 36 | + | ||
| 37 | +enum HeaderIndex : uint32_t { | ||
| 38 | + MAGIC_INDEX = 0U, | ||
| 39 | + VERSION_INDEX = 1U, | ||
| 40 | + METADATA_USED_SIZE_INDEX = 2U, | ||
| 41 | + SA_USED_CORE_NUM_INDEX = 3U, | ||
| 42 | + SA_TOTAL_TASK_NUM_INDEX = 4U, | ||
| 43 | + FD_ACTIVE_CORE_NUM_INDEX = 5U, | ||
| 44 | + DECODE_PER_CORE_TASK_NUM_INDEX = 6U, | ||
| 45 | + COMBINE_TASK_NUM_INDEX = 7U, | ||
| 46 | + FD_SCHEDULE_FLAGS_INDEX = 8U, | ||
| 47 | + FD_TOTAL_FLAT_TASK_NUM_INDEX = 9U, | ||
| 48 | + FD_PARTIAL_TASK_NUM_INDEX = 10U, | ||
| 49 | + CONFIG_SIGNATURE_INDEX = 11U, | ||
| 50 | + HEADER_SIZE = 16U, | ||
| 51 | +}; | ||
| 52 | + | ||
| 53 | +enum DecodeScheduleIndex : uint32_t { | ||
| 54 | + DECODE_BASE_TASK_START_INDEX = 0U, | ||
| 55 | + DECODE_BASE_TASK_END_INDEX = 1U, | ||
| 56 | + DECODE_FIRST_BLOCK_START_INDEX = 2U, | ||
| 57 | + DECODE_LAST_BLOCK_END_INDEX = 3U, | ||
| 58 | + DECODE_SCHEDULE_FIELD_NUM = 4U, | ||
| 59 | +}; | ||
| 60 | + | ||
| 61 | +enum CombineScheduleIndex : uint32_t { | ||
| 62 | + COMBINE_BASE_TASK_INDEX = 0U, | ||
| 63 | + COMBINE_FIRST_CORE_INDEX = 1U, | ||
| 64 | + COMBINE_PARTIAL_START_INDEX = 2U, | ||
| 65 | + COMBINE_PARTIAL_COUNT_INDEX = 3U, | ||
| 66 | + COMBINE_SCHEDULE_FIELD_NUM = 4U, | ||
| 67 | +}; | ||
| 68 | + | ||
| 69 | +constexpr uint32_t DECODE_SCHEDULE_OFFSET = HEADER_SIZE; | ||
| 70 | +constexpr uint32_t COMBINE_SCHEDULE_OFFSET = DECODE_SCHEDULE_OFFSET + MAX_DECODE_CORE_NUM * DECODE_SCHEDULE_FIELD_NUM; | ||
| 71 | +constexpr uint32_t METADATA_USED_SIZE = COMBINE_SCHEDULE_OFFSET + MAX_COMBINE_TASK_NUM * COMBINE_SCHEDULE_FIELD_NUM; | ||
| 72 | + | ||
| 73 | +inline constexpr uint32_t GetDecodeScheduleIndex(uint32_t coreIdx, uint32_t fieldIdx) | ||
| 74 | +{ | ||
| 75 | + return DECODE_SCHEDULE_OFFSET + coreIdx * DECODE_SCHEDULE_FIELD_NUM + fieldIdx; | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +inline constexpr uint32_t GetCombineScheduleIndex(uint32_t combineTaskIdx, uint32_t fieldIdx) | ||
| 79 | +{ | ||
| 80 | + return COMBINE_SCHEDULE_OFFSET + combineTaskIdx * COMBINE_SCHEDULE_FIELD_NUM + fieldIdx; | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +static_assert(METADATA_USED_SIZE == 272U, "unexpected metadata used size"); | ||
| 84 | +static_assert(METADATA_USED_SIZE <= METADATA_TOTAL_SIZE, "metadata schedule exceeds output buffer"); | ||
| 85 | + | ||
| 86 | +} // namespace generic_block_sparse_attention_metadata | ||
| 87 | +} // namespace optiling | ||
| 88 | + | ||
| 89 | +#endif // GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | + | ||
| 3 | +# Keep the public Generic ACLNN header in the configured install source list. | ||
| 4 | +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS | ||
| 5 | + "${CMAKE_CURRENT_SOURCE_DIR}/op_api/aclnn_generic_block_sparse_attention_metadata.h") | ||
| 6 | + | ||
| 7 | +add_op_to_compiled_list() | ||
| 8 | +add_modules_sources(OPTYPE generic_block_sparse_attention_metadata ACLNNTYPE aclnn) | ||
| @@ -0,0 +1,428 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_CHECK_H | ||
| 12 | +#define GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_CHECK_H | ||
| 13 | + | ||
| 14 | +#include <cstring> | ||
| 15 | +#include <string> | ||
| 16 | + | ||
| 17 | +#include "opdev/data_type_utils.h" | ||
| 18 | +#include "opdev/op_log.h" | ||
| 19 | +#include "../generic_block_sparse_attention_metadata.h" | ||
| 20 | + | ||
| 21 | +namespace { | ||
| 22 | +constexpr int64_t GBSA_METADATA_DIM_NUM = 1; | ||
| 23 | +constexpr int64_t GBSA_SEQ_LENGTH_DIM_NUM = 1; | ||
| 24 | +constexpr int64_t GBSA_TND_SPARSE_BLOCK_IDX_DIM_NUM = 3; | ||
| 25 | +constexpr int64_t GBSA_TND_SPARSE_BLOCK_COUNT_DIM_NUM = 2; | ||
| 26 | +constexpr int64_t GBSA_BATCHED_SPARSE_BLOCK_IDX_DIM_NUM = 4; | ||
| 27 | +constexpr int64_t GBSA_BATCHED_SPARSE_BLOCK_COUNT_DIM_NUM = 3; | ||
| 28 | + | ||
| 29 | +constexpr int64_t GBSA_CURRENT_HEAD_DIM = 128; | ||
| 30 | +constexpr int64_t GBSA_CURRENT_MAX_GROUP_SIZE = 128; | ||
| 31 | +constexpr int64_t GBSA_CURRENT_BLOCK_SHAPE_X = 1; | ||
| 32 | +constexpr int64_t GBSA_CURRENT_BLOCK_SHAPE_Y = 128; | ||
| 33 | +constexpr int64_t GBSA_CURRENT_IS_PACKED_GQA = 1; | ||
| 34 | +constexpr int64_t GBSA_CURRENT_MAX_SPARSE_BLOCK_COUNT = 256; | ||
| 35 | +constexpr int64_t GBSA_QUANT_TYPE_NONE = 0; | ||
| 36 | +constexpr int64_t GBSA_QUANT_TYPE_FLOAT8 = 5; | ||
| 37 | +constexpr int64_t GBSA_SOFTMAX_PRECISION_HIGH = 0; | ||
| 38 | +constexpr int64_t GBSA_SOFTMAX_PRECISION_MIXED = 1; | ||
| 39 | +constexpr int64_t GBSA_CURRENT_MASK_TYPE = 1; | ||
| 40 | +constexpr int64_t GBSA_CURRENT_WINDOW_SIZE = -1; | ||
| 41 | + | ||
| 42 | +bool GbsaTensorValid(const aclTensor *tensor) | ||
| 43 | +{ | ||
| 44 | + return tensor != nullptr && tensor->GetViewShape().GetDimNum() > 0; | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +bool GbsaIsLayout(const char *layout, const char *expected) | ||
| 48 | +{ | ||
| 49 | + return layout != nullptr && std::strcmp(layout, expected) == 0; | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +aclnnStatus CheckGbsaTensorDataType(const aclTensor *tensor, aclDataType expectedDataType, const char *expectedTypeName, | ||
| 53 | + const char *tensorName) | ||
| 54 | +{ | ||
| 55 | + aclDataType dataType = ACL_DT_UNDEFINED; | ||
| 56 | + aclGetDataType(tensor, &dataType); | ||
| 57 | + if (dataType != expectedDataType) { | ||
| 58 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s must be %s.", tensorName, expectedTypeName); | ||
| 59 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 60 | + } | ||
| 61 | + return ACLNN_SUCCESS; | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +aclnnStatus CheckGbsaTensorDim(const aclTensor *tensor, int64_t expectedDim, const char *tensorName) | ||
| 65 | +{ | ||
| 66 | + if (tensor->GetViewShape().GetDimNum() != expectedDim) { | ||
| 67 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s dimension must be %ld.", tensorName, expectedDim); | ||
| 68 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 69 | + } | ||
| 70 | + return ACLNN_SUCCESS; | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +aclnnStatus CheckGbsaRequiredInt32Tensor(const aclTensor *tensor, const char *tensorName) | ||
| 74 | +{ | ||
| 75 | + if (!GbsaTensorValid(tensor)) { | ||
| 76 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s must be provided.", tensorName); | ||
| 77 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 78 | + } | ||
| 79 | + return CheckGbsaTensorDataType(tensor, ACL_INT32, "INT32", tensorName); | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +aclnnStatus CheckGbsaRequiredInputs(const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, | ||
| 83 | + const aclTensor *metadata) | ||
| 84 | +{ | ||
| 85 | + aclnnStatus status = CheckGbsaRequiredInt32Tensor(sparseBlockIdx, "sparseBlockIdx"); | ||
| 86 | + if (status != ACLNN_SUCCESS) { | ||
| 87 | + return status; | ||
| 88 | + } | ||
| 89 | + status = CheckGbsaRequiredInt32Tensor(sparseBlockCount, "SparseBlockCount"); | ||
| 90 | + if (status != ACLNN_SUCCESS) { | ||
| 91 | + return status; | ||
| 92 | + } | ||
| 93 | + return CheckGbsaRequiredInt32Tensor(metadata, "metadata"); | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +aclnnStatus CheckGbsaMetadataShape(const aclTensor *metadata) | ||
| 97 | +{ | ||
| 98 | + aclnnStatus status = CheckGbsaTensorDim(metadata, GBSA_METADATA_DIM_NUM, "metadata"); | ||
| 99 | + if (status != ACLNN_SUCCESS) { | ||
| 100 | + return status; | ||
| 101 | + } | ||
| 102 | + if (metadata->GetViewShape().GetDim(0) != | ||
| 103 | + static_cast<int64_t>(optiling::generic_block_sparse_attention_metadata::METADATA_TOTAL_SIZE)) { | ||
| 104 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "metadata shape must be [%u].", | ||
| 105 | + optiling::generic_block_sparse_attention_metadata::METADATA_TOTAL_SIZE); | ||
| 106 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 107 | + } | ||
| 108 | + return ACLNN_SUCCESS; | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +aclnnStatus CheckGbsaPositiveScalarAttr(int64_t attrValue, const char *attrName) | ||
| 112 | +{ | ||
| 113 | + if (attrValue <= 0) { | ||
| 114 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s must be greater than 0, but got %lld.", attrName, attrValue); | ||
| 115 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 116 | + } | ||
| 117 | + return ACLNN_SUCCESS; | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +aclnnStatus CheckGbsaHeadAttrs(int64_t numQHeads, int64_t numKvHeads) | ||
| 121 | +{ | ||
| 122 | + if (numQHeads < numKvHeads || numQHeads % numKvHeads != 0) { | ||
| 123 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, | ||
| 124 | + "numQHeads must be greater than or equal to and divisible by numKvHeads, but got numQHeads=%lld " | ||
| 125 | + "and numKvHeads=%lld.", | ||
| 126 | + numQHeads, numKvHeads); | ||
| 127 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 128 | + } | ||
| 129 | + const int64_t groupSize = numQHeads / numKvHeads; | ||
| 130 | + if (groupSize > GBSA_CURRENT_MAX_GROUP_SIZE) { | ||
| 131 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "groupSize must be less than or equal to %lld, but got %lld.", | ||
| 132 | + GBSA_CURRENT_MAX_GROUP_SIZE, groupSize); | ||
| 133 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 134 | + } | ||
| 135 | + return ACLNN_SUCCESS; | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +aclnnStatus CheckGbsaBlockAttrs(int64_t blockShapeX, int64_t blockShapeY, int64_t isPackedGQA) | ||
| 139 | +{ | ||
| 140 | + if (blockShapeX != GBSA_CURRENT_BLOCK_SHAPE_X) { | ||
| 141 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "blockShapeX currently only supports %lld, but got %lld.", | ||
| 142 | + GBSA_CURRENT_BLOCK_SHAPE_X, blockShapeX); | ||
| 143 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 144 | + } | ||
| 145 | + if (blockShapeY != GBSA_CURRENT_BLOCK_SHAPE_Y) { | ||
| 146 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "blockShapeY currently only supports %lld, but got %lld.", | ||
| 147 | + GBSA_CURRENT_BLOCK_SHAPE_Y, blockShapeY); | ||
| 148 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 149 | + } | ||
| 150 | + if (isPackedGQA != GBSA_CURRENT_IS_PACKED_GQA) { | ||
| 151 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "isPackedGQA currently only supports %lld, but got %lld.", | ||
| 152 | + GBSA_CURRENT_IS_PACKED_GQA, isPackedGQA); | ||
| 153 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 154 | + } | ||
| 155 | + return ACLNN_SUCCESS; | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +aclnnStatus CheckGbsaScalarAttrs(int64_t maxQSeqLen, int64_t maxKvSeqLen, int64_t numQHeads, int64_t numKvHeads, | ||
| 159 | + int64_t headDim, int64_t blockShapeX, int64_t blockShapeY, int64_t isPackedGQA) | ||
| 160 | +{ | ||
| 161 | + const struct { | ||
| 162 | + int64_t value; | ||
| 163 | + const char *name; | ||
| 164 | + } positiveAttrs[] = {{maxQSeqLen, "maxQSeqLen"}, {maxKvSeqLen, "maxKvSeqLen"}, {numQHeads, "numQHeads"}, | ||
| 165 | + {numKvHeads, "numKvHeads"}, {headDim, "headDim"}, {blockShapeY, "blockShapeY"}}; | ||
| 166 | + for (const auto &attr : positiveAttrs) { | ||
| 167 | + const aclnnStatus status = CheckGbsaPositiveScalarAttr(attr.value, attr.name); | ||
| 168 | + if (status != ACLNN_SUCCESS) { | ||
| 169 | + return status; | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | + aclnnStatus status = CheckGbsaHeadAttrs(numQHeads, numKvHeads); | ||
| 173 | + if (status != ACLNN_SUCCESS) { | ||
| 174 | + return status; | ||
| 175 | + } | ||
| 176 | + if (headDim != GBSA_CURRENT_HEAD_DIM) { | ||
| 177 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "headDim currently only supports %lld, but got %lld.", GBSA_CURRENT_HEAD_DIM, | ||
| 178 | + headDim); | ||
| 179 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 180 | + } | ||
| 181 | + return CheckGbsaBlockAttrs(blockShapeX, blockShapeY, isPackedGQA); | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +aclnnStatus CheckGbsaLayouts(const char *qInputLayout, const char *kvInputLayout) | ||
| 185 | +{ | ||
| 186 | + if (!GbsaIsLayout(qInputLayout, "TND")) { | ||
| 187 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "qInputLayout currently only supports TND."); | ||
| 188 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 189 | + } | ||
| 190 | + if (!GbsaIsLayout(kvInputLayout, "PAGED_BBND")) { | ||
| 191 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "kvInputLayout currently only supports PAGED_BBND."); | ||
| 192 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 193 | + } | ||
| 194 | + return ACLNN_SUCCESS; | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +aclnnStatus CheckGbsaOptionalSeqLength(const aclTensor *tensor, int64_t batch, aclDataType dataType, | ||
| 198 | + int64_t expectedElements, const char *typeName, const char *tensorName) | ||
| 199 | +{ | ||
| 200 | + if (!GbsaTensorValid(tensor)) { | ||
| 201 | + return ACLNN_SUCCESS; | ||
| 202 | + } | ||
| 203 | + aclnnStatus status = CheckGbsaTensorDataType(tensor, dataType, typeName, tensorName); | ||
| 204 | + if (status != ACLNN_SUCCESS) { | ||
| 205 | + return status; | ||
| 206 | + } | ||
| 207 | + status = CheckGbsaTensorDim(tensor, GBSA_SEQ_LENGTH_DIM_NUM, tensorName); | ||
| 208 | + if (status != ACLNN_SUCCESS) { | ||
| 209 | + return status; | ||
| 210 | + } | ||
| 211 | + if (tensor->GetViewShape().GetDim(0) != expectedElements) { | ||
| 212 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s shape does not match batch %lld.", tensorName, batch); | ||
| 213 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 214 | + } | ||
| 215 | + return ACLNN_SUCCESS; | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +aclnnStatus GetGbsaBatch(const aclTensor *sparseBlockIdx, const aclTensor *cuSeqLengthsOptional, | ||
| 219 | + const char *qInputLayout, int64_t &batch) | ||
| 220 | +{ | ||
| 221 | + if (!GbsaIsLayout(qInputLayout, "TND")) { | ||
| 222 | + batch = sparseBlockIdx->GetViewShape().GetDim(0); | ||
| 223 | + return batch >= 0 ? ACLNN_SUCCESS : ACLNN_ERR_PARAM_INVALID; | ||
| 224 | + } | ||
| 225 | + if (!GbsaTensorValid(cuSeqLengthsOptional)) { | ||
| 226 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "cuSeqLengths is required for TND query."); | ||
| 227 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 228 | + } | ||
| 229 | + if (cuSeqLengthsOptional->GetViewShape().GetDimNum() != GBSA_SEQ_LENGTH_DIM_NUM || | ||
| 230 | + cuSeqLengthsOptional->GetViewShape().GetDim(0) < GBSA_SEQ_LENGTH_DIM_NUM) { | ||
| 231 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "cuSeqLengths shape must be [batch + 1]."); | ||
| 232 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 233 | + } | ||
| 234 | + batch = cuSeqLengthsOptional->GetViewShape().GetDim(0) - 1; | ||
| 235 | + return ACLNN_SUCCESS; | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +aclnnStatus CheckGbsaSparseTensorShapes(const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, | ||
| 239 | + int64_t maxQSeqLen, int64_t numQHeads, int64_t numKvHeads, int64_t blockShapeX, | ||
| 240 | + int64_t isPackedGQA, const char *qInputLayout, int64_t batch) | ||
| 241 | +{ | ||
| 242 | + const int64_t sparseHeads = isPackedGQA == GBSA_CURRENT_IS_PACKED_GQA ? numKvHeads : numQHeads; | ||
| 243 | + if (GbsaIsLayout(qInputLayout, "TND")) { | ||
| 244 | + if (CheckGbsaTensorDim(sparseBlockIdx, GBSA_TND_SPARSE_BLOCK_IDX_DIM_NUM, "sparseBlockIdx") != ACLNN_SUCCESS || | ||
| 245 | + CheckGbsaTensorDim(sparseBlockCount, GBSA_TND_SPARSE_BLOCK_COUNT_DIM_NUM, "SparseBlockCount") != | ||
| 246 | + ACLNN_SUCCESS) { | ||
| 247 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 248 | + } | ||
| 249 | + if (sparseBlockIdx->GetViewShape().GetDim(0) != sparseHeads || | ||
| 250 | + sparseBlockCount->GetViewShape().GetDim(0) != sparseHeads || | ||
| 251 | + sparseBlockIdx->GetViewShape().GetDim(1) != sparseBlockCount->GetViewShape().GetDim(1) || | ||
| 252 | + sparseBlockIdx->GetViewShape().GetDim(2) <= 0) { | ||
| 253 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "TND sparse block tensor shapes do not match attrs."); | ||
| 254 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 255 | + } | ||
| 256 | + return ACLNN_SUCCESS; | ||
| 257 | + } | ||
| 258 | + | ||
| 259 | + if (CheckGbsaTensorDim(sparseBlockIdx, GBSA_BATCHED_SPARSE_BLOCK_IDX_DIM_NUM, "sparseBlockIdx") != ACLNN_SUCCESS || | ||
| 260 | + CheckGbsaTensorDim(sparseBlockCount, GBSA_BATCHED_SPARSE_BLOCK_COUNT_DIM_NUM, "SparseBlockCount") != | ||
| 261 | + ACLNN_SUCCESS) { | ||
| 262 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 263 | + } | ||
| 264 | + const int64_t qBlocks = maxQSeqLen / blockShapeX + static_cast<int64_t>(maxQSeqLen % blockShapeX != 0); | ||
| 265 | + if (sparseBlockIdx->GetViewShape().GetDim(0) != batch || sparseBlockCount->GetViewShape().GetDim(0) != batch || | ||
| 266 | + sparseBlockIdx->GetViewShape().GetDim(1) != sparseHeads || | ||
| 267 | + sparseBlockCount->GetViewShape().GetDim(1) != sparseHeads || | ||
| 268 | + sparseBlockIdx->GetViewShape().GetDim(2) != qBlocks || sparseBlockCount->GetViewShape().GetDim(2) != qBlocks || | ||
| 269 | + sparseBlockIdx->GetViewShape().GetDim(3) <= 0) { | ||
| 270 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "BSND/BNSD sparse block tensor shapes do not match attrs."); | ||
| 271 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 272 | + } | ||
| 273 | + return ACLNN_SUCCESS; | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +aclnnStatus CheckGbsaSeqLengthInputs(const aclTensor *cuSeqLengthsOptional, const aclTensor *cuSeqLengthsKvOptional, | ||
| 277 | + const aclTensor *seqUsedQOptional, const aclTensor *seqUsedKvOptional, | ||
| 278 | + int64_t batch, const char *qInputLayout, const char *kvInputLayout) | ||
| 279 | +{ | ||
| 280 | + // Legacy issue: when BSND/BNSD provides both cuSeqLengths and seqUsedQ, the device side does not yet verify that | ||
| 281 | + // seqUsedQ is no greater than the corresponding prefix-sum difference. | ||
| 282 | + if (GbsaIsLayout(qInputLayout, "TND") && !GbsaTensorValid(cuSeqLengthsOptional)) { | ||
| 283 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "cuSeqLengths is required for TND query."); | ||
| 284 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 285 | + } | ||
| 286 | + const bool kvSeqLengthsRequired = GbsaIsLayout(kvInputLayout, "TND") || GbsaIsLayout(kvInputLayout, "PAGED_BBND") || | ||
| 287 | + GbsaIsLayout(kvInputLayout, "PAGED_BNBD"); | ||
| 288 | + if (kvSeqLengthsRequired && !GbsaTensorValid(cuSeqLengthsKvOptional)) { | ||
| 289 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "cuSeqLengthsKv is required for TND or paged KV."); | ||
| 290 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 291 | + } | ||
| 292 | + aclnnStatus status = | ||
| 293 | + CheckGbsaOptionalSeqLength(cuSeqLengthsOptional, batch, ACL_INT64, batch + 1, "INT64", "cuSeqLengths"); | ||
| 294 | + if (status != ACLNN_SUCCESS) { | ||
| 295 | + return status; | ||
| 296 | + } | ||
| 297 | + status = CheckGbsaOptionalSeqLength(cuSeqLengthsKvOptional, batch, ACL_INT64, batch + 1, "INT64", "cuSeqLengthsKv"); | ||
| 298 | + if (status != ACLNN_SUCCESS) { | ||
| 299 | + return status; | ||
| 300 | + } | ||
| 301 | + status = CheckGbsaOptionalSeqLength(seqUsedQOptional, batch, ACL_INT32, batch, "INT32", "seqUsedQ"); | ||
| 302 | + if (status != ACLNN_SUCCESS) { | ||
| 303 | + return status; | ||
| 304 | + } | ||
| 305 | + return CheckGbsaOptionalSeqLength(seqUsedKvOptional, batch, ACL_INT32, batch, "INT32", "seqUsedKv"); | ||
| 306 | +} | ||
| 307 | + | ||
| 308 | +aclnnStatus CheckGbsaQuantType(int64_t quantType, bool isArch35) | ||
| 309 | +{ | ||
| 310 | + if (quantType != GBSA_QUANT_TYPE_NONE && quantType != GBSA_QUANT_TYPE_FLOAT8) { | ||
| 311 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "quantType only supports %lld or %lld, but got %lld.", GBSA_QUANT_TYPE_NONE, | ||
| 312 | + GBSA_QUANT_TYPE_FLOAT8, quantType); | ||
| 313 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 314 | + } | ||
| 315 | + if (quantType == GBSA_QUANT_TYPE_FLOAT8 && !isArch35) { | ||
| 316 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "quantType %lld is only supported on Atlas A5.", GBSA_QUANT_TYPE_FLOAT8); | ||
| 317 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 318 | + } | ||
| 319 | + return ACLNN_SUCCESS; | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +aclnnStatus CheckGbsaSoftmaxPrecision(int64_t softmaxPrecision, bool isArch35) | ||
| 323 | +{ | ||
| 324 | + if (softmaxPrecision != GBSA_SOFTMAX_PRECISION_HIGH && softmaxPrecision != GBSA_SOFTMAX_PRECISION_MIXED) { | ||
| 325 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "softmaxPrecision only supports %lld or %lld, but got %lld.", | ||
| 326 | + GBSA_SOFTMAX_PRECISION_HIGH, GBSA_SOFTMAX_PRECISION_MIXED, softmaxPrecision); | ||
| 327 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 328 | + } | ||
| 329 | + if (isArch35 && softmaxPrecision != GBSA_SOFTMAX_PRECISION_MIXED) { | ||
| 330 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "softmaxPrecision only supports %lld on Atlas A5.", | ||
| 331 | + GBSA_SOFTMAX_PRECISION_MIXED); | ||
| 332 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 333 | + } | ||
| 334 | + return ACLNN_SUCCESS; | ||
| 335 | +} | ||
| 336 | + | ||
| 337 | +aclnnStatus CheckGbsaPlatformAttrs(int64_t quantType, int64_t softmaxPrecision, bool isArch35) | ||
| 338 | +{ | ||
| 339 | + aclnnStatus status = CheckGbsaQuantType(quantType, isArch35); | ||
| 340 | + if (status != ACLNN_SUCCESS) { | ||
| 341 | + return status; | ||
| 342 | + } | ||
| 343 | + return CheckGbsaSoftmaxPrecision(softmaxPrecision, isArch35); | ||
| 344 | +} | ||
| 345 | + | ||
| 346 | +aclnnStatus CheckGbsaMaskAttrs(int64_t maskType, int64_t windowSizeLeft, int64_t windowSizeRight) | ||
| 347 | +{ | ||
| 348 | + if (maskType != GBSA_CURRENT_MASK_TYPE) { | ||
| 349 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "maskType currently only supports %lld, but got %lld.", GBSA_CURRENT_MASK_TYPE, | ||
| 350 | + maskType); | ||
| 351 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 352 | + } | ||
| 353 | + if (windowSizeLeft != GBSA_CURRENT_WINDOW_SIZE || windowSizeRight != GBSA_CURRENT_WINDOW_SIZE) { | ||
| 354 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, | ||
| 355 | + "windowSizeLeft and windowSizeRight currently only support %lld, but got %lld and %lld.", | ||
| 356 | + GBSA_CURRENT_WINDOW_SIZE, windowSizeLeft, windowSizeRight); | ||
| 357 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 358 | + } | ||
| 359 | + return ACLNN_SUCCESS; | ||
| 360 | +} | ||
| 361 | + | ||
| 362 | +aclnnStatus CheckGbsaSparseBlockCapacity(const aclTensor *sparseBlockIdx) | ||
| 363 | +{ | ||
| 364 | + const int64_t dimNum = sparseBlockIdx->GetViewShape().GetDimNum(); | ||
| 365 | + const int64_t capacity = sparseBlockIdx->GetViewShape().GetDim(dimNum - 1); | ||
| 366 | + if (capacity > GBSA_CURRENT_MAX_SPARSE_BLOCK_COUNT) { | ||
| 367 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "sparseBlockIdx last dimension currently cannot exceed %lld, but got %lld.", | ||
| 368 | + GBSA_CURRENT_MAX_SPARSE_BLOCK_COUNT, capacity); | ||
| 369 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 370 | + } | ||
| 371 | + return ACLNN_SUCCESS; | ||
| 372 | +} | ||
| 373 | + | ||
| 374 | +aclnnStatus CheckGbsaMetadataParams(const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, | ||
| 375 | + const aclTensor *cuSeqLengthsOptional, const aclTensor *cuSeqLengthsKvOptional, | ||
| 376 | + const aclTensor *seqUsedQOptional, const aclTensor *seqUsedKvOptional, | ||
| 377 | + int64_t maxQSeqLen, int64_t maxKvSeqLen, int64_t numQHeads, int64_t numKvHeads, | ||
| 378 | + int64_t headDim, int64_t blockShapeX, int64_t blockShapeY, int64_t isPackedGQA, | ||
| 379 | + const char *qInputLayout, const char *kvInputLayout, int64_t maskType, | ||
| 380 | + int64_t quantType, int64_t softmaxPrecision, int64_t windowSizeLeft, | ||
| 381 | + int64_t windowSizeRight, bool isArch35, const aclTensor *metadata) | ||
| 382 | +{ | ||
| 383 | + aclnnStatus status = CheckGbsaRequiredInputs(sparseBlockIdx, sparseBlockCount, metadata); | ||
| 384 | + if (status != ACLNN_SUCCESS) { | ||
| 385 | + return status; | ||
| 386 | + } | ||
| 387 | + status = CheckGbsaScalarAttrs(maxQSeqLen, maxKvSeqLen, numQHeads, numKvHeads, headDim, blockShapeX, blockShapeY, | ||
| 388 | + isPackedGQA); | ||
| 389 | + if (status != ACLNN_SUCCESS) { | ||
| 390 | + return status; | ||
| 391 | + } | ||
| 392 | + status = CheckGbsaLayouts(qInputLayout, kvInputLayout); | ||
| 393 | + if (status != ACLNN_SUCCESS) { | ||
| 394 | + return status; | ||
| 395 | + } | ||
| 396 | + status = CheckGbsaMetadataShape(metadata); | ||
| 397 | + if (status != ACLNN_SUCCESS) { | ||
| 398 | + return status; | ||
| 399 | + } | ||
| 400 | + int64_t batch = 0; | ||
| 401 | + status = GetGbsaBatch(sparseBlockIdx, cuSeqLengthsOptional, qInputLayout, batch); | ||
| 402 | + if (status != ACLNN_SUCCESS) { | ||
| 403 | + return status; | ||
| 404 | + } | ||
| 405 | + status = CheckGbsaSparseTensorShapes(sparseBlockIdx, sparseBlockCount, maxQSeqLen, numQHeads, numKvHeads, | ||
| 406 | + blockShapeX, isPackedGQA, qInputLayout, batch); | ||
| 407 | + if (status != ACLNN_SUCCESS) { | ||
| 408 | + return status; | ||
| 409 | + } | ||
| 410 | + status = CheckGbsaSparseBlockCapacity(sparseBlockIdx); | ||
| 411 | + if (status != ACLNN_SUCCESS) { | ||
| 412 | + return status; | ||
| 413 | + } | ||
| 414 | + status = CheckGbsaSeqLengthInputs(cuSeqLengthsOptional, cuSeqLengthsKvOptional, seqUsedQOptional, seqUsedKvOptional, | ||
| 415 | + batch, qInputLayout, kvInputLayout); | ||
| 416 | + if (status != ACLNN_SUCCESS) { | ||
| 417 | + return status; | ||
| 418 | + } | ||
| 419 | + status = CheckGbsaPlatformAttrs(quantType, softmaxPrecision, isArch35); | ||
| 420 | + if (status != ACLNN_SUCCESS) { | ||
| 421 | + return status; | ||
| 422 | + } | ||
| 423 | + return CheckGbsaMaskAttrs(maskType, windowSizeLeft, windowSizeRight); | ||
| 424 | +} | ||
| 425 | + | ||
| 426 | +} // namespace | ||
| 427 | + | ||
| 428 | +#endif // GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_CHECK_H | ||
| @@ -0,0 +1,104 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include "aclnn_generic_block_sparse_attention_metadata.h" | ||
| 12 | +#include "generic_block_sparse_attention_metadata.h" | ||
| 13 | + | ||
| 14 | +#include "aclnn/aclnn_base.h" | ||
| 15 | +#include "aclnn_kernels/common/op_error_check.h" | ||
| 16 | +#include "aclnn_kernels/contiguous.h" | ||
| 17 | +#include "opdev/make_op_executor.h" | ||
| 18 | +#include "opdev/op_dfx.h" | ||
| 19 | +#include "opdev/op_executor.h" | ||
| 20 | +#include "opdev/op_log.h" | ||
| 21 | +#include "opdev/platform.h" | ||
| 22 | +#include "../generic_block_sparse_attention_metadata_check.h" | ||
| 23 | + | ||
| 24 | +#ifdef __cplusplus | ||
| 25 | +extern "C" { | ||
| 26 | +#endif | ||
| 27 | + | ||
| 28 | +namespace { | ||
| 29 | + | ||
| 30 | +aclnnStatus ParseBlockShape(const aclIntArray *blockShape, int64_t &blockShapeX, int64_t &blockShapeY) | ||
| 31 | +{ | ||
| 32 | + if (blockShape == nullptr || blockShape->Size() != 2U || blockShape->GetData() == nullptr) { | ||
| 33 | + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "blockShape must contain exactly two elements [x, y]."); | ||
| 34 | + return ACLNN_ERR_PARAM_INVALID; | ||
| 35 | + } | ||
| 36 | + blockShapeX = blockShape->GetData()[0]; | ||
| 37 | + blockShapeY = blockShape->GetData()[1]; | ||
| 38 | + return ACLNN_SUCCESS; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +const aclTensor *MakeContiguousOptional(const aclTensor *tensor, aclOpExecutor *executor) | ||
| 42 | +{ | ||
| 43 | + return tensor == nullptr ? nullptr : l0op::Contiguous(tensor, executor); | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +} // namespace | ||
| 47 | + | ||
| 48 | +aclnnStatus aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize( | ||
| 49 | + const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, const aclTensor *cuSeqLengthsQOptional, | ||
| 50 | + const aclTensor *cuSeqLengthsKvOptional, const aclTensor *sequsedQOptional, const aclTensor *sequsedKvOptional, | ||
| 51 | + int64_t maxQSeqLen, int64_t maxKvSeqLen, int64_t numQHeads, int64_t numKvHeads, int64_t headDim, | ||
| 52 | + const aclIntArray *blockShape, int64_t isPackedGQA, const char *layoutQ, const char *layoutKv, int64_t maskType, | ||
| 53 | + int64_t quantType, int64_t softmaxPrecision, int64_t winLeft, int64_t winRight, const aclTensor *metadataOptional, | ||
| 54 | + uint64_t *workspaceSize, aclOpExecutor **executor) | ||
| 55 | +{ | ||
| 56 | + if (workspaceSize == nullptr || executor == nullptr) { | ||
| 57 | + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "workspaceSize/executor must not be null."); | ||
| 58 | + return ACLNN_ERR_INNER_NULLPTR; | ||
| 59 | + } | ||
| 60 | + int64_t blockShapeX = 0; | ||
| 61 | + int64_t blockShapeY = 0; | ||
| 62 | + aclnnStatus status = ParseBlockShape(blockShape, blockShapeX, blockShapeY); | ||
| 63 | + CHECK_RET(status == ACLNN_SUCCESS, status); | ||
| 64 | + | ||
| 65 | + auto uniqueExecutor = CREATE_EXECUTOR(); | ||
| 66 | + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); | ||
| 67 | + const op::PlatformInfo &platformInfo = op::GetCurrentPlatformInfo(); | ||
| 68 | + const uint32_t aicCoreNum = platformInfo.GetCubeCoreNum(); | ||
| 69 | + const bool isArch35 = platformInfo.GetCurNpuArch() == NpuArch::DAV_3510; | ||
| 70 | + status = | ||
| 71 | + CheckGbsaMetadataParams(sparseBlockIdx, sparseBlockCount, cuSeqLengthsQOptional, cuSeqLengthsKvOptional, | ||
| 72 | + sequsedQOptional, sequsedKvOptional, maxQSeqLen, maxKvSeqLen, numQHeads, numKvHeads, | ||
| 73 | + headDim, blockShapeX, blockShapeY, isPackedGQA, layoutQ, layoutKv, maskType, quantType, | ||
| 74 | + softmaxPrecision, winLeft, winRight, isArch35, metadataOptional); | ||
| 75 | + CHECK_RET(status == ACLNN_SUCCESS, status); | ||
| 76 | + | ||
| 77 | + const aclTensor *idxContiguous = l0op::Contiguous(sparseBlockIdx, uniqueExecutor.get()); | ||
| 78 | + CHECK_RET(idxContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 79 | + const aclTensor *countContiguous = l0op::Contiguous(sparseBlockCount, uniqueExecutor.get()); | ||
| 80 | + CHECK_RET(countContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 81 | + const aclTensor *cuQContiguous = MakeContiguousOptional(cuSeqLengthsQOptional, uniqueExecutor.get()); | ||
| 82 | + CHECK_RET(cuSeqLengthsQOptional == nullptr || cuQContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 83 | + const aclTensor *seqUsedQContiguous = MakeContiguousOptional(sequsedQOptional, uniqueExecutor.get()); | ||
| 84 | + CHECK_RET(sequsedQOptional == nullptr || seqUsedQContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 85 | + | ||
| 86 | + const aclTensor *output = l0op::GenericBlockSparseAttentionMetadata( | ||
| 87 | + idxContiguous, countContiguous, cuQContiguous, cuSeqLengthsKvOptional, seqUsedQContiguous, sequsedKvOptional, | ||
| 88 | + maxQSeqLen, numQHeads, numKvHeads, headDim, blockShapeX, blockShapeY, isPackedGQA, layoutQ, aicCoreNum, | ||
| 89 | + metadataOptional, uniqueExecutor.get()); | ||
| 90 | + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); | ||
| 91 | + *workspaceSize = 0; | ||
| 92 | + uniqueExecutor.ReleaseTo(executor); | ||
| 93 | + return ACLNN_SUCCESS; | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +aclnnStatus aclnnGenericBlockSparseAttentionMetadata(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, | ||
| 97 | + aclrtStream stream) | ||
| 98 | +{ | ||
| 99 | + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +#ifdef __cplusplus | ||
| 103 | +} | ||
| 104 | +#endif | ||
| @@ -0,0 +1,37 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef ACLNN_GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| 12 | +#define ACLNN_GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| 13 | + | ||
| 14 | +#include "aclnn/aclnn_base.h" | ||
| 15 | + | ||
| 16 | +#ifdef __cplusplus | ||
| 17 | +extern "C" { | ||
| 18 | +#endif | ||
| 19 | + | ||
| 20 | +__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttentionMetadataGetWorkspaceSize( | ||
补充注释 ![]() ![]() | |||
| 21 | + const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, const aclTensor *cuSeqLengthsQOptional, | ||
| 22 | + const aclTensor *cuSeqLengthsKvOptional, const aclTensor *sequsedQOptional, const aclTensor *sequsedKvOptional, | ||
| 23 | + int64_t maxQSeqLen, int64_t maxKvSeqLen, int64_t numQHeads, int64_t numKvHeads, int64_t headDim, | ||
| 24 | + const aclIntArray *blockShape, int64_t isPackedGQA, const char *layoutQ, const char *layoutKv, int64_t maskType, | ||
| 25 | + int64_t quantType, int64_t softmaxPrecision, int64_t winLeft, int64_t winRight, const aclTensor *metadataOptional, | ||
| 26 | + uint64_t *workspaceSize, aclOpExecutor **executor); | ||
| 27 | + | ||
| 28 | +__attribute__((visibility("default"))) aclnnStatus aclnnGenericBlockSparseAttentionMetadata(void *workspace, | ||
| 29 | + uint64_t workspaceSize, | ||
| 30 | + aclOpExecutor *executor, | ||
| 31 | + aclrtStream stream); | ||
| 32 | + | ||
| 33 | +#ifdef __cplusplus | ||
| 34 | +} | ||
| 35 | +#endif | ||
| 36 | + | ||
| 37 | +#endif // ACLNN_GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| @@ -0,0 +1,48 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include "generic_block_sparse_attention_metadata.h" | ||
| 12 | + | ||
| 13 | +#include "opdev/aicpu/aicpu_task.h" | ||
| 14 | +#include "opdev/make_op_executor.h" | ||
| 15 | +#include "opdev/op_def.h" | ||
| 16 | +#include "opdev/op_dfx.h" | ||
| 17 | +#include "opdev/op_log.h" | ||
| 18 | + | ||
| 19 | +using namespace op; | ||
| 20 | + | ||
| 21 | +namespace l0op { | ||
| 22 | + | ||
| 23 | +OP_TYPE_REGISTER(GenericBlockSparseAttentionMetadata); | ||
| 24 | + | ||
| 25 | +const aclTensor *GenericBlockSparseAttentionMetadata( | ||
| 26 | + const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, const aclTensor *cuSeqLengthsOptional, | ||
| 27 | + const aclTensor *cuSeqLengthsKvOptional, const aclTensor *seqUsedQOptional, const aclTensor *seqUsedKvOptional, | ||
| 28 | + int64_t maxQSeqLen, int64_t numQHeads, int64_t numKvHeads, int64_t headDim, int64_t blockShapeX, | ||
| 29 | + int64_t blockShapeY, int64_t isPackedGQA, const char *qInputLayout, int64_t aicCoreNum, const aclTensor *metadata, | ||
| 30 | + aclOpExecutor *executor) | ||
| 31 | +{ | ||
| 32 | + static internal::AicpuTaskSpace space("GenericBlockSparseAttentionMetadata"); | ||
| 33 | + auto ret = ADD_TO_LAUNCHER_LIST_AICPU( | ||
| 34 | + GenericBlockSparseAttentionMetadata, | ||
| 35 | + OP_ATTR_NAMES({"max_q_seq_len", "num_q_heads", "num_kv_heads", "head_dim", "block_shape_x", "block_shape_y", | ||
| 36 | + "is_packed_gqa", "q_input_layout", "aic_core_num"}), | ||
| 37 | + OP_INPUT(sparseBlockIdx, sparseBlockCount, cuSeqLengthsOptional, cuSeqLengthsKvOptional, seqUsedQOptional, | ||
| 38 | + seqUsedKvOptional), | ||
| 39 | + OP_OUTPUT(metadata), | ||
| 40 | + OP_ATTR(maxQSeqLen, numQHeads, numKvHeads, headDim, blockShapeX, blockShapeY, isPackedGQA, qInputLayout, | ||
| 41 | + aicCoreNum)); | ||
| 42 | + OP_CHECK(ret == ACL_SUCCESS, | ||
| 43 | + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "GenericBlockSparseAttentionMetadata AICPU launch registration failed."), | ||
| 44 | + return nullptr); | ||
| 45 | + return metadata; | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +} // namespace l0op | ||
| @@ -0,0 +1,27 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef L0_GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| 12 | +#define L0_GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| 13 | + | ||
| 14 | +#include "opdev/op_executor.h" | ||
| 15 | + | ||
| 16 | +namespace l0op { | ||
| 17 | + | ||
| 18 | +const aclTensor *GenericBlockSparseAttentionMetadata( | ||
| 19 | + const aclTensor *sparseBlockIdx, const aclTensor *sparseBlockCount, const aclTensor *cuSeqLengthsOptional, | ||
| 20 | + const aclTensor *cuSeqLengthsKvOptional, const aclTensor *seqUsedQOptional, const aclTensor *seqUsedKvOptional, | ||
| 21 | + int64_t maxQSeqLen, int64_t numQHeads, int64_t numKvHeads, int64_t headDim, int64_t blockShapeX, | ||
| 22 | + int64_t blockShapeY, int64_t isPackedGQA, const char *qInputLayout, int64_t aicCoreNum, const aclTensor *metadata, | ||
| 23 | + aclOpExecutor *executor); | ||
| 24 | + | ||
| 25 | +} // namespace l0op | ||
| 26 | + | ||
| 27 | +#endif // L0_GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_H | ||
| @@ -0,0 +1,20 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | + | ||
| 3 | +if (BUILD_WITH_INSTALLED_DEPENDENCY_CANN_PKG) | ||
| 4 | + if (NOT (UT_TEST_ALL OR OP_KERNEL_AICPU_UT)) | ||
| 5 | + add_definitions(-D_GLIBCXX_USE_CXX11_ABI=1) | ||
| 6 | + set(CMAKE_CXX_COMPILER ${ASCEND_DIR}/toolkit/toolchain/hcc/bin/aarch64-target-linux-gnu-g++) | ||
| 7 | + endif() | ||
| 8 | + | ||
| 9 | + file(GLOB_RECURSE JSON_FILE ${CMAKE_CURRENT_SOURCE_DIR}/*.json) | ||
| 10 | + set_property(GLOBAL APPEND PROPERTY AICPU_JSON_FILES ${JSON_FILE}) | ||
| 11 | + | ||
| 12 | + file(GLOB AICPU_SRC ${CMAKE_CURRENT_SOURCE_DIR}/*_aicpu.cpp) | ||
| 13 | + set(OBJ_NAME generic_block_sparse_attention_metadata_cust_obj) | ||
| 14 | + add_aicpu_cust_kernel_modules(${OBJ_NAME}) | ||
| 15 | + target_sources(${OBJ_NAME} PRIVATE ${AICPU_SRC}) | ||
| 16 | +endif() | ||
| 17 | + | ||
| 18 | +if (UT_TEST_ALL OR OP_KERNEL_AICPU_UT) | ||
| 19 | + AddAicpuOpTestCase(generic_block_sparse_attention_metadata) | ||
| 20 | +endif() | ||
| @@ -0,0 +1,317 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include "log.h" | ||
| 12 | +#include "generic_block_sparse_attention_metadata_aicpu.h" | ||
| 13 | + | ||
| 14 | +namespace aicpu { | ||
| 15 | +namespace { | ||
| 16 | + | ||
| 17 | +constexpr uint32_t KERNEL_STATUS_OK = 0U; | ||
| 18 | +constexpr uint32_t KERNEL_STATUS_PARAM_INVALID = 1U; | ||
| 19 | +constexpr int32_t TND_SPARSE_BLOCK_IDX_DIM_NUM = 3; | ||
| 20 | +constexpr int32_t TND_SPARSE_BLOCK_COUNT_DIM_NUM = 2; | ||
| 21 | +constexpr int32_t BATCHED_SPARSE_BLOCK_IDX_DIM_NUM = 4; | ||
| 22 | +constexpr int32_t BATCHED_SPARSE_BLOCK_COUNT_DIM_NUM = 3; | ||
| 23 | +constexpr int32_t TND_BLOCK_CAPACITY_DIM_INDEX = 2; | ||
| 24 | +constexpr int32_t BATCHED_Q_BLOCK_DIM_INDEX = 2; | ||
| 25 | +constexpr int32_t BATCHED_BLOCK_CAPACITY_DIM_INDEX = 3; | ||
| 26 | + | ||
| 27 | +bool HasTensorShape(const Tensor *tensor) | ||
| 28 | +{ | ||
| 29 | + return tensor != nullptr && tensor->GetTensorShape() != nullptr; | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +bool HasTensorData(const Tensor *tensor) | ||
| 33 | +{ | ||
| 34 | + return tensor != nullptr && tensor->GetData() != nullptr; | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +} // namespace | ||
| 38 | + | ||
| 39 | +uint32_t GenericBlockSparseAttentionMetadataAicpu::Compute(CpuKernelContext &ctx) | ||
| 40 | +{ | ||
| 41 | + if (!Prepare(ctx)) { | ||
| 42 | + return KERNEL_STATUS_PARAM_INVALID; | ||
| 43 | + } | ||
| 44 | + std::vector<int64_t> qSeqLens; | ||
| 45 | + std::vector<int64_t> qStorageBlockStarts; | ||
| 46 | + std::vector<int64_t> validBlockNums; | ||
| 47 | + if (!ParseQSeqLens(qSeqLens, qStorageBlockStarts) || | ||
| 48 | + !ParseValidBlockNums(qSeqLens, qStorageBlockStarts, validBlockNums) || | ||
| 49 | + !GenerateMetadata(qSeqLens, validBlockNums)) { | ||
| 50 | + return KERNEL_STATUS_PARAM_INVALID; | ||
| 51 | + } | ||
| 52 | + return KERNEL_STATUS_OK; | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +bool GenericBlockSparseAttentionMetadataAicpu::Prepare(CpuKernelContext &ctx) | ||
| 56 | +{ | ||
| 57 | + sparseBlockIdx_ = ctx.Input(static_cast<uint32_t>(ParamId::SPARSE_BLOCK_IDX)); | ||
| 58 | + sparseBlockCount_ = ctx.Input(static_cast<uint32_t>(ParamId::SPARSE_BLOCK_COUNT)); | ||
| 59 | + cuSeqLengths_ = ctx.Input(static_cast<uint32_t>(ParamId::CU_SEQ_LENGTHS)); | ||
| 60 | + seqUsedQ_ = ctx.Input(static_cast<uint32_t>(ParamId::SEQ_USED_Q)); | ||
| 61 | + metadata_ = ctx.Output(static_cast<uint32_t>(ParamId::METADATA)); | ||
| 62 | + // An omitted optional input is represented by an empty Tensor in the AICPU context. | ||
| 63 | + if (!HasTensorData(cuSeqLengths_)) { | ||
| 64 | + cuSeqLengths_ = nullptr; | ||
| 65 | + } | ||
| 66 | + if (!HasTensorData(seqUsedQ_)) { | ||
| 67 | + seqUsedQ_ = nullptr; | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + const bool attrsValid = | ||
| 71 | + GetAttrValue(ctx, "max_q_seq_len", maxQSeqLen_) && GetAttrValue(ctx, "num_q_heads", numQHeads_) && | ||
| 72 | + GetAttrValue(ctx, "num_kv_heads", numKvHeads_) && GetAttrValue(ctx, "head_dim", headDim_) && | ||
| 73 | + GetAttrValue(ctx, "block_shape_x", blockShapeX_) && GetAttrValue(ctx, "block_shape_y", blockShapeY_) && | ||
| 74 | + GetAttrValue(ctx, "is_packed_gqa", isPackedGQA_) && GetAttrValue(ctx, "q_input_layout", qInputLayout_) && | ||
| 75 | + GetAttrValue(ctx, "aic_core_num", aicCoreNum_); | ||
| 76 | + return attrsValid && CheckInputs(); | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +bool GenericBlockSparseAttentionMetadataAicpu::CheckOptionalTensor(const Tensor *tensor, DataType dataType, | ||
| 80 | + int64_t elementNum, const char *tensorName) const | ||
| 81 | +{ | ||
| 82 | + if (tensor == nullptr) { | ||
| 83 | + return true; | ||
| 84 | + } | ||
| 85 | + if (!HasTensorShape(tensor) || !HasTensorData(tensor) || tensor->GetDataType() != dataType || | ||
| 86 | + tensor->GetTensorShape()->GetDims() != 1 || tensor->GetTensorShape()->GetDimSize(0) != elementNum) { | ||
| 87 | + KERNEL_LOG_ERROR("%s has invalid dtype or shape.", tensorName); | ||
| 88 | + return false; | ||
| 89 | + } | ||
| 90 | + return true; | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +bool GenericBlockSparseAttentionMetadataAicpu::CheckInputs() | ||
| 94 | +{ | ||
| 95 | + using namespace optiling::generic_block_sparse_attention_metadata; | ||
| 96 | + // Keep memory-safety checks at the AICPU boundary because the kernel can be reused independently of ACLNN. | ||
| 97 | + if (!HasTensorShape(sparseBlockIdx_) || !HasTensorShape(sparseBlockCount_) || !HasTensorData(sparseBlockCount_) || | ||
| 98 | + !HasTensorData(metadata_)) { | ||
| 99 | + KERNEL_LOG_ERROR("sparse block tensors and metadata must be valid."); | ||
| 100 | + return false; | ||
| 101 | + } | ||
| 102 | + if (sparseBlockIdx_->GetDataType() != DT_INT32 || sparseBlockCount_->GetDataType() != DT_INT32 || | ||
| 103 | + metadata_->GetDataType() != DT_INT32 || metadata_->GetTensorShape() == nullptr || | ||
| 104 | + metadata_->GetTensorShape()->GetDims() != 1 || | ||
| 105 | + metadata_->GetTensorShape()->GetDimSize(0) < METADATA_TOTAL_SIZE) { | ||
| 106 | + KERNEL_LOG_ERROR("sparse block tensors and metadata must be INT32 with valid shapes."); | ||
| 107 | + return false; | ||
| 108 | + } | ||
| 109 | + if (maxQSeqLen_ <= 0 || numQHeads_ <= 0 || numKvHeads_ <= 0 || headDim_ <= 0 || blockShapeX_ != 1 || | ||
| 110 | + blockShapeY_ <= 0 || (isPackedGQA_ != 0 && isPackedGQA_ != 1) || aicCoreNum_ <= 0 || | ||
| 111 | + aicCoreNum_ > MAX_AIC_CORE_NUM) { | ||
| 112 | + KERNEL_LOG_ERROR("Invalid scheduling attrs for GenericBlockSparseAttentionMetadata."); | ||
| 113 | + return false; | ||
| 114 | + } | ||
| 115 | + if (qInputLayout_ != "TND" && qInputLayout_ != "BSND" && qInputLayout_ != "BNSD") { | ||
| 116 | + KERNEL_LOG_ERROR("q_input_layout only supports TND, BSND or BNSD."); | ||
| 117 | + return false; | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + sparseHeadNum_ = isPackedGQA_ == 1 ? numKvHeads_ : numQHeads_; | ||
| 121 | + const auto idxShape = sparseBlockIdx_->GetTensorShape(); | ||
| 122 | + const auto countShape = sparseBlockCount_->GetTensorShape(); | ||
| 123 | + if (qInputLayout_ == "TND") { | ||
| 124 | + if (idxShape->GetDims() != TND_SPARSE_BLOCK_IDX_DIM_NUM || | ||
| 125 | + countShape->GetDims() != TND_SPARSE_BLOCK_COUNT_DIM_NUM || idxShape->GetDimSize(0) != sparseHeadNum_ || | ||
| 126 | + countShape->GetDimSize(0) != sparseHeadNum_ || countShape->GetDimSize(1) != idxShape->GetDimSize(1)) { | ||
| 127 | + KERNEL_LOG_ERROR("TND sparse block tensor shapes do not match attrs."); | ||
| 128 | + return false; | ||
| 129 | + } | ||
| 130 | + qBlockStorageNum_ = idxShape->GetDimSize(1); | ||
| 131 | + blockIndexStride_ = idxShape->GetDimSize(TND_BLOCK_CAPACITY_DIM_INDEX); | ||
| 132 | + if (!HasTensorShape(cuSeqLengths_) || cuSeqLengths_->GetTensorShape()->GetDims() != 1) { | ||
| 133 | + KERNEL_LOG_ERROR("cu_seq_lengths is required for TND query."); | ||
| 134 | + return false; | ||
| 135 | + } | ||
| 136 | + batchSize_ = cuSeqLengths_->GetTensorShape()->GetDimSize(0) - 1; | ||
| 137 | + } else { | ||
| 138 | + if (idxShape->GetDims() != BATCHED_SPARSE_BLOCK_IDX_DIM_NUM || | ||
| 139 | + countShape->GetDims() != BATCHED_SPARSE_BLOCK_COUNT_DIM_NUM) { | ||
| 140 | + KERNEL_LOG_ERROR("BSND/BNSD sparse block tensors must be 4D and 3D, but got %dD and %dD.", | ||
| 141 | + idxShape->GetDims(), countShape->GetDims()); | ||
| 142 | + return false; | ||
| 143 | + } | ||
| 144 | + if (idxShape->GetDimSize(0) != countShape->GetDimSize(0)) { | ||
| 145 | + KERNEL_LOG_ERROR("sparse block batch dims differ: idx=%lld, count=%lld.", idxShape->GetDimSize(0), | ||
| 146 | + countShape->GetDimSize(0)); | ||
| 147 | + return false; | ||
| 148 | + } | ||
| 149 | + if (idxShape->GetDimSize(1) != sparseHeadNum_ || countShape->GetDimSize(1) != sparseHeadNum_) { | ||
| 150 | + KERNEL_LOG_ERROR("sparse block head dims must be %lld, but got idx=%lld, count=%lld.", sparseHeadNum_, | ||
| 151 | + idxShape->GetDimSize(1), countShape->GetDimSize(1)); | ||
| 152 | + return false; | ||
| 153 | + } | ||
| 154 | + if (idxShape->GetDimSize(BATCHED_Q_BLOCK_DIM_INDEX) != countShape->GetDimSize(BATCHED_Q_BLOCK_DIM_INDEX)) { | ||
| 155 | + KERNEL_LOG_ERROR("sparse block Q dims differ: idx=%lld, count=%lld.", | ||
| 156 | + idxShape->GetDimSize(BATCHED_Q_BLOCK_DIM_INDEX), | ||
| 157 | + countShape->GetDimSize(BATCHED_Q_BLOCK_DIM_INDEX)); | ||
| 158 | + return false; | ||
| 159 | + } | ||
| 160 | + if (idxShape->GetDimSize(BATCHED_Q_BLOCK_DIM_INDEX) != maxQSeqLen_) { | ||
| 161 | + KERNEL_LOG_ERROR("sparse block Q dim must equal max_q_seq_len: Q dim=%lld, max_q_seq_len=%lld.", | ||
| 162 | + idxShape->GetDimSize(BATCHED_Q_BLOCK_DIM_INDEX), maxQSeqLen_); | ||
| 163 | + return false; | ||
| 164 | + } | ||
| 165 | + batchSize_ = idxShape->GetDimSize(0); | ||
| 166 | + qBlockStorageNum_ = idxShape->GetDimSize(BATCHED_Q_BLOCK_DIM_INDEX); | ||
| 167 | + blockIndexStride_ = idxShape->GetDimSize(BATCHED_BLOCK_CAPACITY_DIM_INDEX); | ||
| 168 | + } | ||
| 169 | + if (batchSize_ < 0 || qBlockStorageNum_ < 0 || blockIndexStride_ <= 0) { | ||
| 170 | + KERNEL_LOG_ERROR("Invalid batch, Q block or sparse block capacity."); | ||
| 171 | + return false; | ||
| 172 | + } | ||
| 173 | + if (!CheckOptionalTensor(cuSeqLengths_, DT_INT64, batchSize_ + 1, "cu_seq_lengths") || | ||
| 174 | + !CheckOptionalTensor(seqUsedQ_, DT_INT32, batchSize_, "seq_used_q")) { | ||
| 175 | + return false; | ||
| 176 | + } | ||
| 177 | + return true; | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +bool GenericBlockSparseAttentionMetadataAicpu::ParseQSeqLens(std::vector<int64_t> &qSeqLens, | ||
| 181 | + std::vector<int64_t> &qStorageBlockStarts) const | ||
| 182 | +{ | ||
| 183 | + // Get valid Qseq len vector. Qseq priroty: seqUsedQ, cuSeqLengths, maxQSeqLen. | ||
| 184 | + // qSeqLens :actual Qseqlens in batch. qStorageBlockStarts : | ||
| 185 | + // Qblocks start(1 qtoken) in batch base on cuSeq(maybe pad). | ||
| 186 | + if (qInputLayout_ == "TND") { | ||
| 187 | + const auto *prefix = static_cast<const int64_t *>(cuSeqLengths_->GetData()); | ||
| 188 | + std::vector<int64_t> cuSeqLengths(prefix, prefix + batchSize_ + 1); | ||
| 189 | + std::vector<int64_t> seqUsedQ; | ||
| 190 | + if (seqUsedQ_ != nullptr) { | ||
| 191 | + const auto *seqUsed = static_cast<const int32_t *>(seqUsedQ_->GetData()); | ||
| 192 | + seqUsedQ.assign(seqUsed, seqUsed + batchSize_); | ||
| 193 | + } | ||
| 194 | + if (!generic_block_sparse_attention_metadata::BuildTndQSeqLayout(cuSeqLengths, seqUsedQ, seqUsedQ_ != nullptr, | ||
| 195 | + maxQSeqLen_, blockShapeX_, qBlockStorageNum_, | ||
| 196 | + qSeqLens, qStorageBlockStarts)) { | ||
| 197 | + KERNEL_LOG_ERROR("TND Q sequence lengths do not match sparse block storage."); | ||
| 198 | + return false; | ||
| 199 | + } | ||
| 200 | + return true; | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + qSeqLens.assign(static_cast<size_t>(batchSize_), maxQSeqLen_); | ||
| 204 | + qStorageBlockStarts.clear(); | ||
| 205 | + if (seqUsedQ_ != nullptr) { | ||
| 206 | + const auto *seqUsed = static_cast<const int32_t *>(seqUsedQ_->GetData()); | ||
| 207 | + for (int64_t batchIdx = 0; batchIdx < batchSize_; ++batchIdx) { | ||
| 208 | + const int64_t qSeqLen = seqUsed[batchIdx]; | ||
| 209 | + if (qSeqLen < 0 || qSeqLen > maxQSeqLen_) { | ||
| 210 | + KERNEL_LOG_ERROR("seq_used_q[%lld]=%lld is outside [0, %lld].", batchIdx, qSeqLen, maxQSeqLen_); | ||
| 211 | + return false; | ||
| 212 | + } | ||
| 213 | + qSeqLens[static_cast<size_t>(batchIdx)] = qSeqLen; | ||
| 214 | + } | ||
| 215 | + return true; | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + if (cuSeqLengths_ == nullptr) { | ||
| 219 | + return true; | ||
| 220 | + } | ||
| 221 | + const auto *prefix = static_cast<const int64_t *>(cuSeqLengths_->GetData()); | ||
| 222 | + if (prefix[0] != 0) { | ||
| 223 | + KERNEL_LOG_ERROR("cu_seq_lengths[0] must be 0, but got %lld.", prefix[0]); | ||
| 224 | + return false; | ||
| 225 | + } | ||
| 226 | + for (int64_t batchIdx = 0; batchIdx < batchSize_; ++batchIdx) { | ||
| 227 | + if (prefix[batchIdx + 1] < prefix[batchIdx]) { | ||
| 228 | + KERNEL_LOG_ERROR("cu_seq_lengths must be nondecreasing at batch %lld.", batchIdx); | ||
| 229 | + return false; | ||
| 230 | + } | ||
| 231 | + const int64_t qSeqLen = prefix[batchIdx + 1] - prefix[batchIdx]; | ||
| 232 | + if (qSeqLen > maxQSeqLen_) { | ||
| 233 | + KERNEL_LOG_ERROR("Q sequence length %lld exceeds max_q_seq_len %lld at batch %lld.", qSeqLen, maxQSeqLen_, | ||
| 234 | + batchIdx); | ||
| 235 | + return false; | ||
| 236 | + } | ||
| 237 | + qSeqLens[static_cast<size_t>(batchIdx)] = qSeqLen; | ||
| 238 | + } | ||
| 239 | + return true; | ||
| 240 | +} | ||
| 241 | + | ||
| 242 | +bool GenericBlockSparseAttentionMetadataAicpu::ParseValidBlockNums(const std::vector<int64_t> &qSeqLens, | ||
| 243 | + const std::vector<int64_t> &qStorageBlockStarts, | ||
| 244 | + std::vector<int64_t> &validBlockNums) const | ||
| 245 | +{ | ||
| 246 | + const auto *counts = static_cast<const int32_t *>(sparseBlockCount_->GetData()); | ||
| 247 | + if (qInputLayout_ == "TND") { | ||
| 248 | + if (!generic_block_sparse_attention_metadata::GatherTndValidBlockNums(counts, sparseHeadNum_, qBlockStorageNum_, | ||
| 249 | + blockShapeX_, blockIndexStride_, qSeqLens, | ||
| 250 | + qStorageBlockStarts, validBlockNums)) { | ||
| 251 | + KERNEL_LOG_ERROR("Failed to gather TND sparse block counts."); | ||
| 252 | + return false; | ||
| 253 | + } | ||
| 254 | + return true; | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + validBlockNums.clear(); | ||
| 258 | + for (int64_t batchIdx = 0; batchIdx < batchSize_; ++batchIdx) { | ||
| 259 | + const int64_t qBlockNum = | ||
| 260 | + generic_block_sparse_attention_metadata::CeilDivQSeq(qSeqLens[static_cast<size_t>(batchIdx)], blockShapeX_); | ||
| 261 | + for (int64_t qBlock = 0; qBlock < qBlockNum; ++qBlock) { | ||
| 262 | + for (int64_t sparseHead = 0; sparseHead < sparseHeadNum_; ++sparseHead) { | ||
| 263 | + const int64_t offset = (batchIdx * sparseHeadNum_ + sparseHead) * qBlockStorageNum_ + qBlock; | ||
| 264 | + const int64_t count = counts[offset]; | ||
| 265 | + if (count < 0 || count > blockIndexStride_) { | ||
| 266 | + KERNEL_LOG_ERROR("sparse_block_count[%lld]=%lld exceeds capacity %lld.", offset, count, | ||
| 267 | + blockIndexStride_); | ||
| 268 | + return false; | ||
| 269 | + } | ||
| 270 | + validBlockNums.push_back(count); | ||
| 271 | + } | ||
| 272 | + } | ||
| 273 | + } | ||
| 274 | + return true; | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +bool GenericBlockSparseAttentionMetadataAicpu::GenerateMetadata(const std::vector<int64_t> &qSeqLens, | ||
| 278 | + const std::vector<int64_t> &validBlockNums) | ||
| 279 | +{ | ||
| 280 | + generic_block_sparse_attention_metadata::ScheduleInput input; | ||
| 281 | + input.batchSize = batchSize_; | ||
| 282 | + input.numQHeads = numQHeads_; | ||
| 283 | + input.numKvHeads = numKvHeads_; | ||
| 284 | + input.maxQSeqLen = maxQSeqLen_; | ||
| 285 | + input.headDim = headDim_; | ||
| 286 | + input.blockShapeX = blockShapeX_; | ||
| 287 | + input.blockShapeY = blockShapeY_; | ||
| 288 | + input.blockIndexStride = blockIndexStride_; | ||
| 289 | + input.qBlockStorageNum = qBlockStorageNum_; | ||
| 290 | + input.isPackedGQA = isPackedGQA_; | ||
| 291 | + input.aicCoreNum = aicCoreNum_; | ||
| 292 | + input.qSeqLens = qSeqLens; | ||
| 293 | + input.validBlockNums = validBlockNums; | ||
| 294 | + | ||
| 295 | + generic_block_sparse_attention_metadata::ScheduleResult result; | ||
| 296 | + const auto scheduleStatus = generic_block_sparse_attention_metadata::BuildSchedule(input, result); | ||
| 297 | + if (scheduleStatus != generic_block_sparse_attention_metadata::ScheduleStatus::SUCCESS) { | ||
| 298 | + KERNEL_LOG_ERROR("Failed to build metadata schedule, status=%u.", static_cast<uint32_t>(scheduleStatus)); | ||
| 299 | + return false; | ||
| 300 | + } | ||
| 301 | + auto *metadata = | ||
| 302 | + static_cast<optiling::generic_block_sparse_attention_metadata::MetadataType *>(metadata_->GetData()); | ||
| 303 | + const auto encodeStatus = generic_block_sparse_attention_metadata::EncodeMetadata( | ||
| 304 | + result, metadata, optiling::generic_block_sparse_attention_metadata::METADATA_TOTAL_SIZE); | ||
| 305 | + if (encodeStatus != generic_block_sparse_attention_metadata::ScheduleStatus::SUCCESS) { | ||
| 306 | + KERNEL_LOG_ERROR("Failed to encode metadata, status=%u.", static_cast<uint32_t>(encodeStatus)); | ||
| 307 | + return false; | ||
| 308 | + } | ||
| 309 | + return true; | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +namespace { | ||
| 313 | +const char *KERNEL_TYPE = "GenericBlockSparseAttentionMetadata"; | ||
| 314 | +REGISTER_CPU_KERNEL(KERNEL_TYPE, GenericBlockSparseAttentionMetadataAicpu); | ||
| 315 | +} // namespace | ||
| 316 | + | ||
| 317 | +} // namespace aicpu | ||
| @@ -0,0 +1,75 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_AICPU_H | ||
| 12 | +#define GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_AICPU_H | ||
| 13 | + | ||
| 14 | +#include <cstdint> | ||
| 15 | +#include <string> | ||
| 16 | +#include <vector> | ||
| 17 | + | ||
| 18 | +#include "cpu_context.h" | ||
| 19 | +#include "cpu_kernel.h" | ||
| 20 | +#include "cpu_tensor.h" | ||
| 21 | +#include "../../common/op_kernel/aicpu_common.h" | ||
| 22 | +#include "generic_block_sparse_attention_metadata_q_seq_utils.h" | ||
| 23 | +#include "generic_block_sparse_attention_metadata_scheduler.h" | ||
| 24 | + | ||
| 25 | +namespace aicpu { | ||
| 26 | + | ||
| 27 | +class GenericBlockSparseAttentionMetadataAicpu : public CpuKernel { | ||
| 28 | +public: | ||
| 29 | + GenericBlockSparseAttentionMetadataAicpu() = default; | ||
| 30 | + ~GenericBlockSparseAttentionMetadataAicpu() = default; | ||
| 31 | + uint32_t Compute(CpuKernelContext &ctx) override; | ||
| 32 | + | ||
| 33 | +private: | ||
| 34 | + bool Prepare(CpuKernelContext &ctx); | ||
| 35 | + bool CheckInputs(); | ||
| 36 | + bool ParseQSeqLens(std::vector<int64_t> &qSeqLens, std::vector<int64_t> &qStorageBlockStarts) const; | ||
| 37 | + bool ParseValidBlockNums(const std::vector<int64_t> &qSeqLens, const std::vector<int64_t> &qStorageBlockStarts, | ||
| 38 | + std::vector<int64_t> &validBlockNums) const; | ||
| 39 | + bool GenerateMetadata(const std::vector<int64_t> &qSeqLens, const std::vector<int64_t> &validBlockNums); | ||
| 40 | + bool CheckOptionalTensor(const Tensor *tensor, DataType dataType, int64_t elementNum, const char *tensorName) const; | ||
| 41 | + | ||
| 42 | + Tensor *sparseBlockIdx_ = nullptr; | ||
| 43 | + Tensor *sparseBlockCount_ = nullptr; | ||
| 44 | + Tensor *cuSeqLengths_ = nullptr; | ||
| 45 | + Tensor *seqUsedQ_ = nullptr; | ||
| 46 | + Tensor *metadata_ = nullptr; | ||
| 47 | + | ||
| 48 | + int64_t batchSize_ = 0; | ||
| 49 | + int64_t maxQSeqLen_ = 0; | ||
| 50 | + int64_t numQHeads_ = 0; | ||
| 51 | + int64_t numKvHeads_ = 0; | ||
| 52 | + int64_t headDim_ = 0; | ||
| 53 | + int64_t blockShapeX_ = 1; | ||
| 54 | + int64_t blockShapeY_ = 0; | ||
| 55 | + int64_t isPackedGQA_ = 1; | ||
| 56 | + int64_t aicCoreNum_ = 0; | ||
| 57 | + int64_t sparseHeadNum_ = 0; | ||
| 58 | + int64_t qBlockStorageNum_ = 0; // QShape nums of SparseBlockCount last dim. | ||
| 59 | + int64_t blockIndexStride_ = 0; // maxSparseBlockCount : the max value of valid blocks. | ||
| 60 | + std::string qInputLayout_; | ||
| 61 | + | ||
| 62 | + enum class ParamId : uint32_t { | ||
| 63 | + SPARSE_BLOCK_IDX = 0U, | ||
| 64 | + SPARSE_BLOCK_COUNT = 1U, | ||
| 65 | + CU_SEQ_LENGTHS = 2U, | ||
| 66 | + CU_SEQ_LENGTHS_KV = 3U, | ||
| 67 | + SEQ_USED_Q = 4U, | ||
| 68 | + SEQ_USED_KV = 5U, | ||
| 69 | + METADATA = 0U, | ||
| 70 | + }; | ||
| 71 | +}; | ||
| 72 | + | ||
| 73 | +} // namespace aicpu | ||
| 74 | + | ||
| 75 | +#endif // GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_AICPU_H | ||
| @@ -0,0 +1,15 @@ | |||
| 1 | +{ | ||
| 2 | + "GenericBlockSparseAttentionMetadata": { | ||
| 3 | + "opInfo": { | ||
| 4 | + "computeCost": "100", | ||
| 5 | + "engine": "DNN_VM_AICPU", | ||
| 6 | + "flagAsync": "False", | ||
| 7 | + "flagPartial": "False", | ||
| 8 | + "functionName": "RunCpuKernel", | ||
| 9 | + "kernelSo": "libtransformer_aicpu_kernels.so", | ||
| 10 | + "opKernelLib": "CUSTAICPUKernel", | ||
| 11 | + "userDefined": "True", | ||
| 12 | + "workspaceSize": "100" | ||
| 13 | + } | ||
| 14 | + } | ||
| 15 | +} | ||
| @@ -0,0 +1,106 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_Q_SEQ_UTILS_H | ||
| 12 | +#define GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_Q_SEQ_UTILS_H | ||
| 13 | + | ||
| 14 | +#include <cstddef> | ||
| 15 | +#include <cstdint> | ||
| 16 | +#include <limits> | ||
| 17 | +#include <vector> | ||
| 18 | + | ||
| 19 | +namespace aicpu { | ||
| 20 | +namespace generic_block_sparse_attention_metadata { | ||
| 21 | + | ||
| 22 | +inline int64_t CeilDivQSeq(int64_t value, int64_t divisor) | ||
| 23 | +{ | ||
| 24 | + return value == 0 ? 0 : (value - 1) / divisor + 1; | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +inline bool BuildTndQSeqLayout(const std::vector<int64_t> &cuSeqLengths, const std::vector<int64_t> &seqUsedQ, | ||
| 28 | + bool hasSeqUsedQ, int64_t maxQSeqLen, int64_t blockShapeX, int64_t qBlockStorageNum, | ||
| 29 | + std::vector<int64_t> &actualQSeqLens, std::vector<int64_t> &qStorageBlockStarts) | ||
| 30 | +{ | ||
| 31 | + if (cuSeqLengths.empty() || cuSeqLengths.front() != 0 || maxQSeqLen <= 0 || blockShapeX <= 0 || | ||
| 32 | + qBlockStorageNum < 0) { | ||
| 33 | + return false; | ||
| 34 | + } | ||
| 35 | + const std::size_t batchSize = cuSeqLengths.size() - 1U; | ||
| 36 | + if (hasSeqUsedQ && seqUsedQ.size() != batchSize) { | ||
| 37 | + return false; | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + actualQSeqLens.assign(batchSize, 0); | ||
| 41 | + qStorageBlockStarts.assign(batchSize, 0); | ||
| 42 | + int64_t storageBlockBase = 0; | ||
| 43 | + for (std::size_t batchIdx = 0; batchIdx < batchSize; ++batchIdx) { | ||
| 44 | + // cuSeq is prefixSum(must increase). CuSeq is not nullptr when TND, QseqLens maybe pad in batch. | ||
| 45 | + if (cuSeqLengths[batchIdx] < 0 || cuSeqLengths[batchIdx + 1U] < cuSeqLengths[batchIdx]) { | ||
| 46 | + return false; | ||
| 47 | + } | ||
| 48 | + const int64_t storageQSeqLen = cuSeqLengths[batchIdx + 1U] - cuSeqLengths[batchIdx]; | ||
| 49 | + if (storageQSeqLen > maxQSeqLen) { | ||
| 50 | + return false; | ||
| 51 | + } | ||
| 52 | + const int64_t actualQSeqLen = hasSeqUsedQ ? seqUsedQ[batchIdx] : storageQSeqLen; | ||
| 53 | + if (actualQSeqLen < 0 || actualQSeqLen > storageQSeqLen) { | ||
| 54 | + return false; | ||
| 55 | + } | ||
| 56 | + actualQSeqLens[batchIdx] = actualQSeqLen; // actual qTokens in batch. | ||
| 57 | + qStorageBlockStarts[batchIdx] = storageBlockBase; // Qblock base in batch. | ||
| 58 | + | ||
| 59 | + const int64_t storageBlockNum = | ||
| 60 | + CeilDivQSeq(storageQSeqLen, blockShapeX); // total Qblocks in batch base on cuSeq. | ||
| 61 | + if (storageBlockBase > std::numeric_limits<int64_t>::max() - storageBlockNum) { | ||
| 62 | + return false; | ||
| 63 | + } | ||
| 64 | + storageBlockBase += storageBlockNum; | ||
| 65 | + } | ||
| 66 | + // totalQBlocks in params. | ||
| 67 | + return storageBlockBase == qBlockStorageNum; | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +inline bool GatherTndValidBlockNums(const int32_t *counts, int64_t sparseHeadNum, int64_t qBlockStorageNum, | ||
| 71 | + int64_t blockShapeX, int64_t blockIndexStride, | ||
| 72 | + const std::vector<int64_t> &actualQSeqLens, | ||
| 73 | + const std::vector<int64_t> &qStorageBlockStarts, | ||
| 74 | + std::vector<int64_t> &validBlockNums) | ||
| 75 | +{ | ||
| 76 | + if (counts == nullptr || sparseHeadNum <= 0 || qBlockStorageNum < 0 || blockShapeX <= 0 || blockIndexStride <= 0 || | ||
| 77 | + actualQSeqLens.size() != qStorageBlockStarts.size()) { | ||
| 78 | + return false; | ||
| 79 | + } | ||
| 80 | + validBlockNums.clear(); // only contain the base tasks have valid blocks. | ||
| 81 | + for (std::size_t batchIdx = 0; batchIdx < actualQSeqLens.size(); ++batchIdx) { | ||
| 82 | + // only support blockX=1 now. | ||
| 83 | + const int64_t actualQBlockNum = CeilDivQSeq(actualQSeqLens[batchIdx], blockShapeX); | ||
| 84 | + if (qStorageBlockStarts[batchIdx] < 0 || qStorageBlockStarts[batchIdx] > qBlockStorageNum || | ||
| 85 | + actualQBlockNum > qBlockStorageNum - qStorageBlockStarts[batchIdx]) { | ||
| 86 | + return false; | ||
| 87 | + } | ||
| 88 | + for (int64_t qBlock = 0; qBlock < actualQBlockNum; ++qBlock) { | ||
| 89 | + const int64_t globalQBlock = qStorageBlockStarts[batchIdx] + qBlock; | ||
| 90 | + for (int64_t sparseHead = 0; sparseHead < sparseHeadNum; ++sparseHead) { | ||
| 91 | + const int64_t offset = sparseHead * qBlockStorageNum + globalQBlock; | ||
| 92 | + const int64_t count = counts[offset]; | ||
| 93 | + if (count < 0 || count > blockIndexStride) { | ||
| 94 | + return false; | ||
| 95 | + } | ||
| 96 | + validBlockNums.push_back(count); | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + return true; | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +} // namespace generic_block_sparse_attention_metadata | ||
| 104 | +} // namespace aicpu | ||
| 105 | + | ||
| 106 | +#endif // GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_Q_SEQ_UTILS_H | ||
| @@ -0,0 +1,485 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#ifndef GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_SCHEDULER_H | ||
| 12 | +#define GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_SCHEDULER_H | ||
| 13 | + | ||
| 14 | +#include <algorithm> | ||
| 15 | +#include <array> | ||
| 16 | +#include <cmath> | ||
| 17 | +#include <cstddef> | ||
| 18 | +#include <cstdint> | ||
| 19 | +#include <limits> | ||
| 20 | +#include <vector> | ||
| 21 | + | ||
| 22 | +#include "../generic_block_sparse_attention_metadata.h" | ||
| 23 | + | ||
| 24 | +namespace aicpu { | ||
| 25 | +namespace generic_block_sparse_attention_metadata { | ||
| 26 | + | ||
| 27 | +enum class ScheduleStatus : uint32_t { | ||
| 28 | + SUCCESS = 0U, | ||
| 29 | + INVALID_PARAM = 1U, | ||
| 30 | + OVERFLOW = 2U, | ||
| 31 | + METADATA_TOO_SMALL = 3U, | ||
| 32 | + SCHEDULE_TOO_LARGE = 4U, | ||
| 33 | +}; | ||
| 34 | + | ||
| 35 | +struct ScheduleInput { | ||
| 36 | + int64_t batchSize = 0; | ||
| 37 | + int64_t numQHeads = 0; | ||
| 38 | + int64_t numKvHeads = 0; | ||
| 39 | + int64_t maxQSeqLen = 0; | ||
| 40 | + int64_t headDim = 0; | ||
| 41 | + int64_t blockShapeX = 1; | ||
| 42 | + int64_t blockShapeY = 0; | ||
| 43 | + int64_t blockIndexStride = 0; | ||
| 44 | + int64_t qBlockStorageNum = 0; | ||
| 45 | + int64_t isPackedGQA = 1; | ||
| 46 | + int64_t aicCoreNum = 0; | ||
| 47 | + std::vector<int64_t> qSeqLens; // seqUsed/cuQLens/maxQLen | ||
| 48 | + // qUnit-major, sparseHead-minor logical order. | ||
| 49 | + std::vector<int64_t> validBlockNums; | ||
| 50 | +}; | ||
| 51 | + | ||
| 52 | +struct DecodeSchedule { | ||
| 53 | + int64_t baseTaskStart = 0; | ||
| 54 | + int64_t baseTaskEnd = 0; | ||
| 55 | + int64_t firstBlockStart = 0; | ||
| 56 | + int64_t lastBlockEnd = 0; | ||
| 57 | +}; | ||
| 58 | + | ||
| 59 | +struct CombineSchedule { | ||
| 60 | + int64_t baseTask = 0; | ||
| 61 | + int64_t firstCore = 0; | ||
| 62 | + int64_t partialStart = 0; | ||
| 63 | + int64_t partialCount = 0; | ||
| 64 | +}; | ||
| 65 | + | ||
| 66 | +struct ScheduleResult { | ||
| 67 | + int64_t saUsedCoreNum = 0; | ||
| 68 | + int64_t saTotalTaskNum = 0; | ||
| 69 | + int64_t totalQTokenNum = 0; | ||
| 70 | + int64_t sparseHeadNum = 0; | ||
| 71 | + int64_t groupSize = 0; | ||
| 72 | + int64_t fdActiveCoreNum = 0; | ||
| 73 | + int64_t decodePerCoreTaskNum = 0; | ||
| 74 | + int64_t combineTaskNum = 0; | ||
| 75 | + int64_t fdScheduleFlags = 0; | ||
| 76 | + int64_t fdTotalFlatTaskNum = 0; | ||
| 77 | + int64_t fdPartialTaskNum = 0; | ||
| 78 | + int64_t configSignature = 0; | ||
| 79 | + std::vector<int64_t> qLogicalStarts; | ||
| 80 | + std::vector<int64_t> blockPrefix; | ||
| 81 | + std::array<DecodeSchedule, optiling::generic_block_sparse_attention_metadata::MAX_DECODE_CORE_NUM> | ||
| 82 | + decodeSchedules{}; | ||
| 83 | + std::array<CombineSchedule, optiling::generic_block_sparse_attention_metadata::MAX_COMBINE_TASK_NUM> | ||
| 84 | + combineSchedules{}; | ||
| 85 | +}; | ||
| 86 | + | ||
| 87 | +struct TaskInfo { | ||
| 88 | + int64_t qUnit = 0; | ||
| 89 | + int64_t sparseHeadIdx = 0; | ||
| 90 | + int64_t batchIdx = 0; | ||
| 91 | + int64_t qTokenInBatch = 0; | ||
| 92 | + int64_t kvHeadIdx = 0; | ||
| 93 | + int64_t qHeadStart = 0; | ||
| 94 | + int64_t qHeadCount = 0; | ||
| 95 | +}; | ||
| 96 | + | ||
| 97 | +ScheduleStatus BuildSchedule(const ScheduleInput &input, ScheduleResult &result); | ||
| 98 | +ScheduleStatus DecodeTask(const ScheduleInput &input, const ScheduleResult &result, int64_t taskIdx, | ||
| 99 | + TaskInfo &taskInfo); | ||
| 100 | +ScheduleStatus EncodeMetadata(const ScheduleResult &result, | ||
| 101 | + optiling::generic_block_sparse_attention_metadata::MetadataType *metadata, | ||
| 102 | + size_t metadataElementNum); | ||
| 103 | + | ||
| 104 | +namespace { | ||
| 105 | + | ||
| 106 | +using optiling::generic_block_sparse_attention_metadata::MetadataType; | ||
| 107 | + | ||
| 108 | +constexpr uint64_t FD_COST_M16 = 125U; | ||
| 109 | +constexpr uint64_t FD_COST_N = 740U; | ||
| 110 | +constexpr uint64_t FD_COST_M16_N = 35U; | ||
| 111 | +constexpr uint64_t FD_LAUNCH_COST = 278U; | ||
| 112 | + | ||
| 113 | +uint32_t HashConfigValue(uint32_t hash, uint32_t value) | ||
| 114 | +{ | ||
| 115 | + constexpr uint32_t FNV_PRIME = 16777619U; | ||
| 116 | + for (uint32_t shift = 0; shift < 32U; shift += 8U) { | ||
| 117 | + hash ^= (value >> shift) & 0xFFU; | ||
| 118 | + hash *= FNV_PRIME; | ||
| 119 | + } | ||
| 120 | + return hash; | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +uint32_t CalculateConfigSignature(const ScheduleInput &input) | ||
| 124 | +{ | ||
| 125 | + uint32_t hash = 2166136261U; | ||
| 126 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.batchSize)); | ||
| 127 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.numQHeads)); | ||
| 128 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.numKvHeads)); | ||
| 129 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.headDim)); | ||
| 130 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.blockShapeX)); | ||
| 131 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.blockShapeY)); | ||
| 132 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.blockIndexStride)); | ||
| 133 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.qBlockStorageNum)); | ||
| 134 | + hash = HashConfigValue(hash, static_cast<uint32_t>(input.isPackedGQA)); | ||
| 135 | + return hash; | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +bool AddOverflow(int64_t lhs, int64_t rhs, int64_t &result) | ||
| 139 | +{ | ||
| 140 | + if (lhs < 0 || rhs < 0 || lhs > std::numeric_limits<int64_t>::max() - rhs) { | ||
| 141 | + return true; | ||
| 142 | + } | ||
| 143 | + result = lhs + rhs; | ||
| 144 | + return false; | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +bool MulOverflow(int64_t lhs, int64_t rhs, int64_t &result) | ||
| 148 | +{ | ||
| 149 | + if (lhs < 0 || rhs < 0 || (lhs != 0 && rhs > std::numeric_limits<int64_t>::max() / lhs)) { | ||
| 150 | + return true; | ||
| 151 | + } | ||
| 152 | + result = lhs * rhs; | ||
| 153 | + return false; | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +bool AddOverflow(uint64_t lhs, uint64_t rhs, uint64_t &result) | ||
| 157 | +{ | ||
| 158 | + if (lhs > std::numeric_limits<uint64_t>::max() - rhs) { | ||
| 159 | + return true; | ||
| 160 | + } | ||
| 161 | + result = lhs + rhs; | ||
| 162 | + return false; | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +bool MulOverflow(uint64_t lhs, uint64_t rhs, uint64_t &result) | ||
| 166 | +{ | ||
| 167 | + if (lhs != 0U && rhs > std::numeric_limits<uint64_t>::max() / lhs) { | ||
| 168 | + return true; | ||
| 169 | + } | ||
| 170 | + result = lhs * rhs; | ||
| 171 | + return false; | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +bool FitsMetadataType(int64_t value) | ||
| 175 | +{ | ||
| 176 | + return value >= static_cast<int64_t>(std::numeric_limits<MetadataType>::min()) && | ||
| 177 | + value <= static_cast<int64_t>(std::numeric_limits<MetadataType>::max()); | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +int64_t CeilDiv(int64_t lhs, int64_t rhs) | ||
| 181 | +{ | ||
| 182 | + return lhs == 0 ? 0 : (lhs - 1) / rhs + 1; | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +uint32_t CalcFdBestCore(uint64_t totalCost, uint64_t launchCost, uint32_t maxCore) | ||
| 186 | +{ | ||
| 187 | + if (totalCost == 0U || launchCost == 0U || maxCore == 0U) { | ||
| 188 | + return 0U; | ||
| 189 | + } | ||
| 190 | + const double ratio = static_cast<double>(totalCost) / static_cast<double>(launchCost); | ||
| 191 | + const double root = (std::sqrt(1.0 + 4.0 * ratio) - 1.0) / 2.0; | ||
| 192 | + const uint32_t bestCore = static_cast<uint32_t>(std::ceil(root)); | ||
| 193 | + return std::max(1U, std::min(bestCore, maxCore)); | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +ScheduleStatus AccumulateFdCost(int64_t m16, int64_t validBlockNum, uint64_t &totalCost, uint64_t &totalValidBlockNum) | ||
| 197 | +{ | ||
| 198 | + uint64_t mCost = 0U; | ||
| 199 | + uint64_t nCost = 0U; | ||
| 200 | + uint64_t mn = 0U; | ||
| 201 | + uint64_t mnCost = 0U; | ||
| 202 | + uint64_t taskCost = 0U; | ||
| 203 | + if (MulOverflow(FD_COST_M16, static_cast<uint64_t>(m16), mCost) || | ||
| 204 | + MulOverflow(FD_COST_N, static_cast<uint64_t>(validBlockNum), nCost) || | ||
| 205 | + MulOverflow(static_cast<uint64_t>(m16), static_cast<uint64_t>(validBlockNum), mn) || | ||
| 206 | + MulOverflow(FD_COST_M16_N, mn, mnCost) || AddOverflow(mCost, nCost, taskCost) || | ||
| 207 | + AddOverflow(taskCost, mnCost, taskCost) || AddOverflow(totalCost, taskCost, totalCost) || | ||
| 208 | + AddOverflow(totalValidBlockNum, static_cast<uint64_t>(validBlockNum), totalValidBlockNum)) { | ||
| 209 | + return ScheduleStatus::OVERFLOW; | ||
| 210 | + } | ||
| 211 | + return ScheduleStatus::SUCCESS; | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +bool IsScheduleInputValid(const ScheduleInput &input) | ||
| 215 | +{ | ||
| 216 | + using namespace optiling::generic_block_sparse_attention_metadata; | ||
| 217 | + return input.batchSize >= 0 && input.numQHeads > 0 && input.numKvHeads > 0 && input.maxQSeqLen > 0 && | ||
| 218 | + input.headDim > 0 && input.blockShapeX == 1 && input.blockShapeY > 0 && input.blockIndexStride > 0 && | ||
| 219 | + input.qBlockStorageNum > 0 && (input.isPackedGQA == 0 || input.isPackedGQA == 1) && input.aicCoreNum > 0 && | ||
| 220 | + input.aicCoreNum <= MAX_AIC_CORE_NUM && input.qSeqLens.size() == static_cast<size_t>(input.batchSize); | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +ScheduleStatus BuildSaTaskInfo(const ScheduleInput &input, ScheduleResult &result) | ||
| 224 | +{ | ||
| 225 | + result.groupSize = input.numQHeads / input.numKvHeads; | ||
建议确认: ![]() ![]() | |||
| 226 | + result.sparseHeadNum = input.isPackedGQA == 1 ? input.numKvHeads : input.numQHeads; | ||
| 227 | + result.qLogicalStarts.resize(static_cast<size_t>(input.batchSize) + 1U, 0); | ||
| 228 | + | ||
| 229 | + int64_t totalQTokenNum = 0; | ||
| 230 | + for (int64_t batchIdx = 0; batchIdx < input.batchSize; ++batchIdx) { | ||
| 231 | + const int64_t qSeqLen = input.qSeqLens[static_cast<size_t>(batchIdx)]; | ||
| 232 | + if (qSeqLen < 0 || qSeqLen > input.maxQSeqLen) { | ||
| 233 | + return ScheduleStatus::INVALID_PARAM; | ||
| 234 | + } | ||
| 235 | + result.qLogicalStarts[static_cast<size_t>(batchIdx)] = totalQTokenNum; // the Q tokens start position in batch. | ||
| 236 | + if (AddOverflow(totalQTokenNum, qSeqLen, totalQTokenNum) || !FitsMetadataType(totalQTokenNum)) { | ||
| 237 | + return ScheduleStatus::OVERFLOW; | ||
| 238 | + } | ||
| 239 | + } | ||
| 240 | + result.qLogicalStarts[static_cast<size_t>(input.batchSize)] = totalQTokenNum; | ||
| 241 | + result.totalQTokenNum = totalQTokenNum; | ||
| 242 | + if (MulOverflow(totalQTokenNum, result.sparseHeadNum, result.saTotalTaskNum) || | ||
| 243 | + !FitsMetadataType(result.saTotalTaskNum)) { | ||
| 244 | + return ScheduleStatus::OVERFLOW; | ||
| 245 | + } | ||
| 246 | + if (input.validBlockNums.size() != static_cast<size_t>(result.saTotalTaskNum)) { | ||
| 247 | + return ScheduleStatus::INVALID_PARAM; | ||
| 248 | + } | ||
| 249 | + result.saUsedCoreNum = std::min(result.saTotalTaskNum, input.aicCoreNum); | ||
| 250 | + return ScheduleStatus::SUCCESS; | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +ScheduleStatus BuildBlockPrefix(const ScheduleInput &input, ScheduleResult &result, uint64_t &totalCost, | ||
| 254 | + uint64_t &totalValidBlockNum) | ||
| 255 | +{ | ||
| 256 | + result.blockPrefix.resize(static_cast<size_t>(result.saTotalTaskNum) + 1U, 0); | ||
| 257 | + const int64_t qHeadCount = input.isPackedGQA == 1 ? result.groupSize : 1; | ||
| 258 | + const int64_t m16 = CeilDiv(qHeadCount, 16); | ||
| 259 | + for (int64_t task = 0; task < result.saTotalTaskNum; ++task) { | ||
| 260 | + const int64_t validBlockNum = input.validBlockNums[static_cast<size_t>(task)]; | ||
| 261 | + if (validBlockNum < 0 || validBlockNum > input.blockIndexStride) { | ||
| 262 | + return ScheduleStatus::INVALID_PARAM; | ||
| 263 | + } | ||
| 264 | + int64_t prefix = 0; | ||
| 265 | + if (AddOverflow(result.blockPrefix[static_cast<size_t>(task)], validBlockNum, prefix) || | ||
| 266 | + !FitsMetadataType(prefix)) { | ||
| 267 | + return ScheduleStatus::OVERFLOW; | ||
| 268 | + } | ||
| 269 | + result.blockPrefix[static_cast<size_t>(task) + 1U] = prefix; | ||
| 270 | + if (validBlockNum > 0) { | ||
| 271 | + const ScheduleStatus status = AccumulateFdCost(m16, validBlockNum, totalCost, totalValidBlockNum); | ||
| 272 | + if (status != ScheduleStatus::SUCCESS) { | ||
| 273 | + return status; | ||
| 274 | + } | ||
| 275 | + } | ||
| 276 | + } | ||
| 277 | + return ScheduleStatus::SUCCESS; | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +bool ShouldBuildDecodeSchedule(const ScheduleInput &input, const ScheduleResult &result, uint64_t totalCost, | ||
| 281 | + uint64_t totalValidBlockNum) | ||
| 282 | +{ | ||
| 283 | + const int64_t totalSplitTaskNum = result.blockPrefix.back(); | ||
| 284 | + // Decode scheduling uses the FD kernel cost model calibrated for D=128 and blockShapeY=128. | ||
| 285 | + const bool fdShapeSupported = | ||
| 286 | + input.headDim == 128 && input.blockShapeY == 128 && input.blockIndexStride >= 12 && | ||
| 287 | + input.blockIndexStride <= | ||
| 288 | + static_cast<int64_t>(optiling::generic_block_sparse_attention_metadata::MAX_SPARSE_BLOCK_CAPACITY) && | ||
| 289 | + result.groupSize > 0 && result.groupSize <= 128 && input.maxQSeqLen >= result.totalQTokenNum && | ||
| 290 | + result.saTotalTaskNum > 0 && | ||
| 291 | + static_cast<uint64_t>(result.saTotalTaskNum) * 10U < static_cast<uint64_t>(input.aicCoreNum) * 3U; | ||
| 292 | + return fdShapeSupported && totalSplitTaskNum > result.saUsedCoreNum && totalCost > 0U && totalValidBlockNum > 0U; | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +ScheduleStatus BuildDecodeCoreSchedules(ScheduleResult &result, int64_t totalSplitTaskNum) | ||
| 296 | +{ | ||
| 297 | + for (int64_t coreIdx = 0; coreIdx < result.fdActiveCoreNum; ++coreIdx) { | ||
| 298 | + DecodeSchedule &schedule = result.decodeSchedules[static_cast<size_t>(coreIdx)]; | ||
| 299 | + const int64_t flatStart = std::min(coreIdx * result.decodePerCoreTaskNum, totalSplitTaskNum); | ||
| 300 | + const int64_t flatEnd = std::min(flatStart + result.decodePerCoreTaskNum, totalSplitTaskNum); | ||
| 301 | + if (flatStart == flatEnd) { | ||
| 302 | + continue; | ||
| 303 | + } | ||
| 304 | + const auto firstIt = std::upper_bound(result.blockPrefix.begin(), result.blockPrefix.end(), flatStart); | ||
| 305 | + const auto lastIt = std::upper_bound(result.blockPrefix.begin(), result.blockPrefix.end(), flatEnd - 1); | ||
| 306 | + if (firstIt == result.blockPrefix.begin() || lastIt == result.blockPrefix.begin()) { | ||
| 307 | + return ScheduleStatus::INVALID_PARAM; | ||
| 308 | + } | ||
| 309 | + const int64_t firstTask = static_cast<int64_t>(firstIt - result.blockPrefix.begin()) - 1; | ||
| 310 | + const int64_t lastTask = static_cast<int64_t>(lastIt - result.blockPrefix.begin()) - 1; | ||
| 311 | + schedule.baseTaskStart = firstTask; | ||
| 312 | + schedule.baseTaskEnd = lastTask + 1; | ||
| 313 | + schedule.firstBlockStart = flatStart - result.blockPrefix[static_cast<size_t>(firstTask)]; | ||
| 314 | + schedule.lastBlockEnd = flatEnd - result.blockPrefix[static_cast<size_t>(lastTask)]; | ||
| 315 | + } | ||
| 316 | + return ScheduleStatus::SUCCESS; | ||
| 317 | +} | ||
| 318 | + | ||
| 319 | +ScheduleStatus BuildCombineSchedules(ScheduleResult &result) | ||
| 320 | +{ | ||
| 321 | + using namespace optiling::generic_block_sparse_attention_metadata; | ||
| 322 | + int64_t partialTaskNum = 0; | ||
| 323 | + for (int64_t task = 0; task < result.saTotalTaskNum; ++task) { | ||
| 324 | + const int64_t taskStart = result.blockPrefix[static_cast<size_t>(task)]; | ||
| 325 | + const int64_t taskEnd = result.blockPrefix[static_cast<size_t>(task) + 1U]; | ||
| 326 | + if (taskStart == taskEnd) { | ||
| 327 | + continue; | ||
| 328 | + } | ||
| 329 | + const int64_t firstCore = taskStart / result.decodePerCoreTaskNum; | ||
| 330 | + const int64_t lastCore = (taskEnd - 1) / result.decodePerCoreTaskNum; | ||
| 331 | + const int64_t partialCount = lastCore - firstCore + 1; | ||
| 332 | + if (partialCount <= 1) { | ||
| 333 | + continue; | ||
| 334 | + } | ||
| 335 | + if (partialCount > result.fdActiveCoreNum || | ||
| 336 | + partialCount > static_cast<int64_t>(MAX_FD_PARTIAL_PER_BASE_TASK) || firstCore < 0 || | ||
| 337 | + firstCore + partialCount > result.fdActiveCoreNum) { | ||
| 338 | + return ScheduleStatus::SCHEDULE_TOO_LARGE; | ||
| 339 | + } | ||
| 340 | + if (result.combineTaskNum >= MAX_COMBINE_TASK_NUM) { | ||
| 341 | + return ScheduleStatus::SCHEDULE_TOO_LARGE; | ||
| 342 | + } | ||
| 343 | + CombineSchedule &combine = result.combineSchedules[static_cast<size_t>(result.combineTaskNum++)]; | ||
| 344 | + combine.baseTask = task; | ||
| 345 | + combine.firstCore = firstCore; | ||
| 346 | + combine.partialStart = partialTaskNum; | ||
| 347 | + combine.partialCount = partialCount; | ||
| 348 | + if (AddOverflow(partialTaskNum, partialCount, partialTaskNum) || !FitsMetadataType(partialTaskNum)) { | ||
| 349 | + return ScheduleStatus::OVERFLOW; | ||
| 350 | + } | ||
| 351 | + } | ||
| 352 | + result.fdPartialTaskNum = partialTaskNum; | ||
| 353 | + return ScheduleStatus::SUCCESS; | ||
| 354 | +} | ||
| 355 | + | ||
| 356 | +} // namespace | ||
| 357 | + | ||
| 358 | +inline ScheduleStatus BuildSchedule(const ScheduleInput &input, ScheduleResult &result) | ||
| 359 | +{ | ||
| 360 | + using namespace optiling::generic_block_sparse_attention_metadata; | ||
| 361 | + result = {}; | ||
| 362 | + if (!IsScheduleInputValid(input)) { | ||
| 363 | + return ScheduleStatus::INVALID_PARAM; | ||
| 364 | + } | ||
| 365 | + result.configSignature = static_cast<int64_t>(CalculateConfigSignature(input)); | ||
| 366 | + result.fdScheduleFlags = static_cast<int64_t>(FD_ACTUAL_BLOCK_PREFIX); | ||
| 367 | + ScheduleStatus status = BuildSaTaskInfo(input, result); | ||
| 368 | + if (status != ScheduleStatus::SUCCESS) { | ||
| 369 | + return status; | ||
| 370 | + } | ||
| 371 | + uint64_t totalCost = 0U; | ||
| 372 | + uint64_t totalValidBlockNum = 0U; | ||
| 373 | + status = BuildBlockPrefix(input, result, totalCost, totalValidBlockNum); | ||
| 374 | + if (status != ScheduleStatus::SUCCESS) { | ||
| 375 | + return status; | ||
| 376 | + } | ||
| 377 | + const int64_t totalSplitTaskNum = result.blockPrefix.back(); | ||
| 378 | + result.fdTotalFlatTaskNum = totalSplitTaskNum; | ||
| 379 | + if (!ShouldBuildDecodeSchedule(input, result, totalCost, totalValidBlockNum)) { | ||
| 380 | + return ScheduleStatus::SUCCESS; | ||
| 381 | + } | ||
| 382 | + const uint64_t maxCoreLimit = std::min<uint64_t>( | ||
| 383 | + std::min<uint64_t>(static_cast<uint64_t>(input.aicCoreNum), MAX_FD_ACTIVE_CORE_NUM), totalValidBlockNum); | ||
| 384 | + const int64_t bestCoreNum = CalcFdBestCore(totalCost, FD_LAUNCH_COST, static_cast<uint32_t>(maxCoreLimit)); | ||
| 385 | + if (bestCoreNum == 0) { | ||
| 386 | + return ScheduleStatus::SUCCESS; | ||
| 387 | + } | ||
| 388 | + result.decodePerCoreTaskNum = CeilDiv(totalSplitTaskNum, bestCoreNum); | ||
| 389 | + result.fdActiveCoreNum = CeilDiv(totalSplitTaskNum, result.decodePerCoreTaskNum); | ||
| 390 | + status = BuildDecodeCoreSchedules(result, totalSplitTaskNum); | ||
| 391 | + if (status != ScheduleStatus::SUCCESS) { | ||
| 392 | + return status; | ||
| 393 | + } | ||
| 394 | + status = BuildCombineSchedules(result); | ||
| 395 | + if (status == ScheduleStatus::SUCCESS) { | ||
| 396 | + result.fdScheduleFlags |= static_cast<int64_t>(FD_SCHEDULE_ENABLED); | ||
| 397 | + } | ||
| 398 | + return status; | ||
| 399 | +} | ||
| 400 | + | ||
| 401 | +inline ScheduleStatus DecodeTask(const ScheduleInput &input, const ScheduleResult &result, int64_t taskIdx, | ||
| 402 | + TaskInfo &taskInfo) | ||
| 403 | +{ | ||
| 404 | + if (taskIdx < 0 || taskIdx >= result.saTotalTaskNum || result.sparseHeadNum <= 0 || | ||
| 405 | + result.qLogicalStarts.size() != static_cast<size_t>(input.batchSize) + 1U) { | ||
| 406 | + return ScheduleStatus::INVALID_PARAM; | ||
| 407 | + } | ||
| 408 | + taskInfo = {}; | ||
| 409 | + taskInfo.qUnit = taskIdx / result.sparseHeadNum; | ||
| 410 | + taskInfo.sparseHeadIdx = taskIdx % result.sparseHeadNum; | ||
| 411 | + if (input.isPackedGQA == 1) { | ||
| 412 | + taskInfo.kvHeadIdx = taskInfo.sparseHeadIdx; | ||
| 413 | + taskInfo.qHeadStart = taskInfo.sparseHeadIdx * result.groupSize; | ||
| 414 | + taskInfo.qHeadCount = result.groupSize; | ||
| 415 | + } else { | ||
| 416 | + taskInfo.qHeadStart = taskInfo.sparseHeadIdx; | ||
| 417 | + taskInfo.qHeadCount = 1; | ||
| 418 | + if (result.groupSize <= 0) { | ||
| 419 | + return ScheduleStatus::INVALID_PARAM; | ||
| 420 | + } | ||
| 421 | + taskInfo.kvHeadIdx = taskInfo.sparseHeadIdx / result.groupSize; | ||
| 422 | + } | ||
| 423 | + const auto batchIt = std::upper_bound(result.qLogicalStarts.begin(), result.qLogicalStarts.end(), taskInfo.qUnit); | ||
| 424 | + if (batchIt == result.qLogicalStarts.begin()) { | ||
| 425 | + return ScheduleStatus::INVALID_PARAM; | ||
| 426 | + } | ||
| 427 | + taskInfo.batchIdx = static_cast<int64_t>(batchIt - result.qLogicalStarts.begin()) - 1; | ||
| 428 | + if (taskInfo.batchIdx >= input.batchSize) { | ||
| 429 | + return ScheduleStatus::INVALID_PARAM; | ||
| 430 | + } | ||
| 431 | + taskInfo.qTokenInBatch = taskInfo.qUnit - result.qLogicalStarts[static_cast<size_t>(taskInfo.batchIdx)]; | ||
| 432 | + return ScheduleStatus::SUCCESS; | ||
| 433 | +} | ||
| 434 | + | ||
| 435 | +inline ScheduleStatus EncodeMetadata(const ScheduleResult &result, MetadataType *metadata, size_t metadataElementNum) | ||
| 436 | +{ | ||
| 437 | + using namespace optiling::generic_block_sparse_attention_metadata; | ||
| 438 | + if (metadata == nullptr || metadataElementNum < METADATA_TOTAL_SIZE || result.fdActiveCoreNum < 0 || | ||
| 439 | + result.fdActiveCoreNum > MAX_DECODE_CORE_NUM || result.combineTaskNum < 0 || | ||
| 440 | + result.combineTaskNum > MAX_COMBINE_TASK_NUM || result.fdPartialTaskNum < 0 || result.fdTotalFlatTaskNum < 0) { | ||
| 441 | + return ScheduleStatus::METADATA_TOO_SMALL; | ||
| 442 | + } | ||
| 443 | + std::fill(metadata, metadata + METADATA_TOTAL_SIZE, 0); | ||
| 444 | + metadata[MAGIC_INDEX] = METADATA_MAGIC; | ||
| 445 | + metadata[VERSION_INDEX] = METADATA_VERSION; | ||
| 446 | + metadata[METADATA_USED_SIZE_INDEX] = static_cast<MetadataType>(METADATA_USED_SIZE); | ||
| 447 | + metadata[SA_USED_CORE_NUM_INDEX] = static_cast<MetadataType>(result.saUsedCoreNum); | ||
| 448 | + metadata[SA_TOTAL_TASK_NUM_INDEX] = static_cast<MetadataType>(result.saTotalTaskNum); | ||
| 449 | + metadata[FD_ACTIVE_CORE_NUM_INDEX] = static_cast<MetadataType>(result.fdActiveCoreNum); | ||
| 450 | + metadata[DECODE_PER_CORE_TASK_NUM_INDEX] = static_cast<MetadataType>(result.decodePerCoreTaskNum); | ||
| 451 | + metadata[COMBINE_TASK_NUM_INDEX] = static_cast<MetadataType>(result.combineTaskNum); | ||
| 452 | + metadata[FD_SCHEDULE_FLAGS_INDEX] = static_cast<MetadataType>(result.fdScheduleFlags); | ||
| 453 | + metadata[FD_TOTAL_FLAT_TASK_NUM_INDEX] = static_cast<MetadataType>(result.fdTotalFlatTaskNum); | ||
| 454 | + metadata[FD_PARTIAL_TASK_NUM_INDEX] = static_cast<MetadataType>(result.fdPartialTaskNum); | ||
| 455 | + metadata[CONFIG_SIGNATURE_INDEX] = static_cast<MetadataType>(result.configSignature); | ||
| 456 | + | ||
| 457 | + for (uint32_t coreIdx = 0; coreIdx < MAX_DECODE_CORE_NUM; ++coreIdx) { | ||
| 458 | + const DecodeSchedule &schedule = result.decodeSchedules[coreIdx]; | ||
| 459 | + metadata[GetDecodeScheduleIndex(coreIdx, DECODE_BASE_TASK_START_INDEX)] = | ||
| 460 | + static_cast<MetadataType>(schedule.baseTaskStart); | ||
| 461 | + metadata[GetDecodeScheduleIndex(coreIdx, DECODE_BASE_TASK_END_INDEX)] = | ||
| 462 | + static_cast<MetadataType>(schedule.baseTaskEnd); | ||
| 463 | + metadata[GetDecodeScheduleIndex(coreIdx, DECODE_FIRST_BLOCK_START_INDEX)] = | ||
| 464 | + static_cast<MetadataType>(schedule.firstBlockStart); | ||
| 465 | + metadata[GetDecodeScheduleIndex(coreIdx, DECODE_LAST_BLOCK_END_INDEX)] = | ||
| 466 | + static_cast<MetadataType>(schedule.lastBlockEnd); | ||
| 467 | + } | ||
| 468 | + for (uint32_t combineIdx = 0; combineIdx < MAX_COMBINE_TASK_NUM; ++combineIdx) { | ||
| 469 | + const CombineSchedule &schedule = result.combineSchedules[combineIdx]; | ||
| 470 | + metadata[GetCombineScheduleIndex(combineIdx, COMBINE_BASE_TASK_INDEX)] = | ||
| 471 | + static_cast<MetadataType>(schedule.baseTask); | ||
| 472 | + metadata[GetCombineScheduleIndex(combineIdx, COMBINE_FIRST_CORE_INDEX)] = | ||
| 473 | + static_cast<MetadataType>(schedule.firstCore); | ||
| 474 | + metadata[GetCombineScheduleIndex(combineIdx, COMBINE_PARTIAL_START_INDEX)] = | ||
| 475 | + static_cast<MetadataType>(schedule.partialStart); | ||
| 476 | + metadata[GetCombineScheduleIndex(combineIdx, COMBINE_PARTIAL_COUNT_INDEX)] = | ||
| 477 | + static_cast<MetadataType>(schedule.partialCount); | ||
| 478 | + } | ||
| 479 | + return ScheduleStatus::SUCCESS; | ||
| 480 | +} | ||
| 481 | + | ||
| 482 | +} // namespace generic_block_sparse_attention_metadata | ||
| 483 | +} // namespace aicpu | ||
| 484 | + | ||
| 485 | +#endif // GENERIC_BLOCK_SPARSE_ATTENTION_METADATA_SCHEDULER_H | ||
| @@ -0,0 +1,17 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 13 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 14 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 15 | + add_subdirectory(${SUB_DIR}) | ||
| 16 | + endif() | ||
| 17 | +endforeach() | ||
| @@ -0,0 +1,17 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 13 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 14 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 15 | + add_subdirectory(${SUB_DIR}) | ||
| 16 | + endif() | ||
| 17 | +endforeach() | ||
| @@ -0,0 +1,14 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +if(UT_TEST_ALL OR OP_HOST_UT) | ||
| 13 | + add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) | ||
| 14 | +endif() | ||