已合并
feat(mixed_quant_sparse_flash_mla): migrate TurboQuant support to 9.2.0 #12425
wangbin207创建于 9月19日
feat(mixed_quant_sparse_flash_mla): migrate TurboQuant support to 9.2.0 #12425
已合并
共 49 个文件变更+5182-356
| @@ -5,8 +5,8 @@ | |||
| 5 | | 产品 | 是否支持 | | 5 | | 产品 | 是否支持 | |
| 6 | | :---------------------------------------------------------- | :------: | | 6 | | :---------------------------------------------------------- | :------: | |
| 7 | |<term>Ascend 950PR&950DT系列产品</term> | √ | | 7 | |<term>Ascend 950PR&950DT系列产品</term> | √ | |
| 8 | -|<term>Atlas A3系列产品</term> | × | | 8 | +|<term>Atlas A3系列产品</term> | √ | |
| 9 | -|<term>Atlas A2系列产品</term> | × | | 9 | +|<term>Atlas A2系列产品</term> | √ | |
| 10 | |<term>Atlas 200I/500 A2推理产品</term> | × | | 10 | |<term>Atlas 200I/500 A2推理产品</term> | × | |
| 11 | |<term>Atlas推理系列产品</term> | × | | 11 | |<term>Atlas推理系列产品</term> | × | |
| 12 | |<term>Atlas训练系列产品</term> | × | | 12 | |<term>Atlas训练系列产品</term> | × | |
| @@ -61,21 +61,21 @@ | |||
| 61 | <td>q</td> | 61 | <td>q</td> |
| 62 | <td>输入</td> | 62 | <td>输入</td> |
| 63 | <td>表示对应公式中的Q。</td> | 63 | <td>表示对应公式中的Q。</td> |
| 64 | - <td>BFLOAT16</td> | 64 | + <td>FLOAT16、BFLOAT16</td> |
| 65 | <td>ND</td> | 65 | <td>ND</td> |
| 66 | </tr> | 66 | </tr> |
| 67 | <tr> | 67 | <tr> |
| 68 | <td>ori_kv</td> | 68 | <td>ori_kv</td> |
| 69 | <td>可选输入</td> | 69 | <td>可选输入</td> |
| 70 | <td>表示对应公式中K和V的一部分,为原始不经压缩的量化KV,Key和Value共享同一份数据。由nope、rope、scale、padding拼接而成,详见quant_mode。</td> | 70 | <td>表示对应公式中K和V的一部分,为原始不经压缩的量化KV,Key和Value共享同一份数据。由nope、rope、scale、padding拼接而成,详见quant_mode。</td> |
| 71 | - <td>详见quant_mode</td> | 71 | + <td>FLOAT8_E4M3FN、FLOAT16、BFLOAT16</td> |
| 72 | <td>ND</td> | 72 | <td>ND</td> |
| 73 | </tr> | 73 | </tr> |
| 74 | <tr> | 74 | <tr> |
| 75 | <td>cmp_kv</td> | 75 | <td>cmp_kv</td> |
| 76 | <td>可选输入</td> | 76 | <td>可选输入</td> |
| 77 | <td>表示对应公式中K和V的一部分,为经过压缩的量化KV,Key和Value共享同一份数据。由nope、rope、scale、padding拼接而成,详见quant_mode。</td> | 77 | <td>表示对应公式中K和V的一部分,为经过压缩的量化KV,Key和Value共享同一份数据。由nope、rope、scale、padding拼接而成,详见quant_mode。</td> |
| 78 | - <td>详见quant_mode</td> | 78 | + <td>FLOAT8_E4M3FN、UINT8</td> |
| 79 | <td>ND</td> | 79 | <td>ND</td> |
| 80 | </tr> | 80 | </tr> |
| 81 | <tr> | 81 | <tr> |
| @@ -186,7 +186,7 @@ | |||
| 186 | <tr> | 186 | <tr> |
| 187 | <td>quant_mode</td> | 187 | <td>quant_mode</td> |
| 188 | <td>属性</td> | 188 | <td>属性</td> |
| 189 | - <td>表示量化模式。量化模式1表示K、V nope为per-token-group量化,K、V依次由rope(64,bfloat16)、nope(448,FLOAT8_E4M3FN)、scale(7,bfloat16)、pad(18B)拼接而成;量化模式2表示K、V nope为per-token-group量化,K、V依次由nope(448,FLOAT8_E4M3FN)、rope(64,bfloat16)、scale(7,FLOAT8_E8M0)、pad(1B)拼接而成。当前仅支持1和2,量化模式2仅支持layout_kv为PA_BBND。各量化模式均支持使用UINT8、FLOAT8_E4M3FN作为单字节存储视图,底层字节内容保持不变。</td> | 189 | + <td>表示量化模式。量化模式1表示K、V nope为per-token-group量化,K、V依次由rope(64,bfloat16)、nope(448,FLOAT8_E4M3FN)、scale(7,bfloat16)、pad(18B)拼接而成;量化模式2表示K、V nope为per-token-group量化,K、V依次由nope(448,FLOAT8_E4M3FN)、rope(64,bfloat16)、scale(7,FLOAT8_E8M0)、pad(1B)拼接而成;量化模式3表示融合TQ4反量化的TurboQuant模式。量化模式1和2均支持使用UINT8、FLOAT8_E4M3FN作为单字节存储视图,底层字节内容保持不变。</td> |
| 190 | <td>INT</td> | 190 | <td>INT</td> |
| 191 | <td>-</td> | 191 | <td>-</td> |
| 192 | </tr> | 192 | </tr> |
| @@ -271,7 +271,7 @@ | |||
| 271 | <td>attn_out</td> | 271 | <td>attn_out</td> |
| 272 | <td>输出</td> | 272 | <td>输出</td> |
| 273 | <td>表示对应公式中的输出O。</td> | 273 | <td>表示对应公式中的输出O。</td> |
| 274 | - <td>BFLOAT16</td> | 274 | + <td>FLOAT16、BFLOAT16</td> |
| 275 | <td>ND</td> | 275 | <td>ND</td> |
| 276 | </tr> | 276 | </tr> |
| 277 | <tr> | 277 | <tr> |
| @@ -286,6 +286,18 @@ | |||
| 286 | 286 | ||
| 287 | ## 约束说明 | 287 | ## 约束说明 |
| 288 | 288 | ||
| 289 | +<!-- npu="950" id1 --> | ||
| 290 | +- <term>Ascend 950PR&950DT系列产品</term>:仅支持`quant_mode=1/2`,q和attn_out仅支持BFLOAT16,ori_kv和cmp_kv仅支持FLOAT8_E4M3FN;quant_mode为1和2时kv_d分别为608和584,quant_mode为2时layout_kv仅支持PA_BBND。 | ||
| 291 | +<!-- end id1 --> | ||
| 292 | + | ||
| 293 | +<!-- npu="A3" id2 --> | ||
| 294 | +- <term>Atlas A3系列产品</term>:仅支持`quant_mode=3`的TurboQuant CSA场景,q、ori_kv和attn_out支持FLOAT16、BFLOAT16且数据类型一致,ori_kv的尾维为512,cmp_kv仅支持UINT8且尾维为258。 | ||
| 295 | +<!-- end id2 --> | ||
| 296 | + | ||
| 297 | +<!-- npu="910b" id3 --> | ||
| 298 | +- <term>Atlas A2系列产品</term>:仅支持`quant_mode=3`的TurboQuant CSA场景,q、ori_kv和attn_out支持FLOAT16、BFLOAT16且数据类型一致,ori_kv的尾维为512,cmp_kv仅支持UINT8且尾维为258。 | ||
| 299 | +<!-- end id3 --> | ||
| 300 | + | ||
| 289 | - 该接口支持推理场景下使用。 | 301 | - 该接口支持推理场景下使用。 |
| 290 | - 该接口支持aclgraph模式。 | 302 | - 该接口支持aclgraph模式。 |
| 291 | - 该接口支持batch一致性。 | 303 | - 该接口支持batch一致性。 |
| @@ -6,10 +6,10 @@ | |||
| 6 | - <term>Ascend 950PR&950DT系列产品</term>:支持 | 6 | - <term>Ascend 950PR&950DT系列产品</term>:支持 |
| 7 | <!-- end id1 --> | 7 | <!-- end id1 --> |
| 8 | <!-- npu="A3" id2 --> | 8 | <!-- npu="A3" id2 --> |
| 9 | -- <term>Atlas A3系列产品</term>:不支持 | 9 | +- <term>Atlas A3系列产品</term>:支持 |
| 10 | <!-- end id2 --> | 10 | <!-- end id2 --> |
| 11 | <!-- npu="910b" id3 --> | 11 | <!-- npu="910b" id3 --> |
| 12 | -- <term>Atlas A2系列产品</term>:不支持 | 12 | +- <term>Atlas A2系列产品</term>:支持 |
| 13 | <!-- end id3 --> | 13 | <!-- end id3 --> |
| 14 | <!-- npu="310b" id4 --> | 14 | <!-- npu="310b" id4 --> |
| 15 | - <term>Atlas 200I/500 A2推理产品</term>:不支持 | 15 | - <term>Atlas 200I/500 A2推理产品</term>:不支持 |
| @@ -176,8 +176,8 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 176 | <td>q(aclTensor*)</td> | 176 | <td>q(aclTensor*)</td> |
| 177 | <td>输入</td> | 177 | <td>输入</td> |
| 178 | <td>Query输入张量。</td> | 178 | <td>Query输入张量。</td> |
| 179 | - <td>不支持空Tensor。qN支持1-128;D仅支持512。</td> | 179 | + <td>qN支持1-128;D仅支持512。具体产品约束见约束说明。</td> |
| 180 | - <td>BFLOAT16</td> | 180 | + <td>FLOAT16、BFLOAT16</td> |
| 181 | <td>ND</td> | 181 | <td>ND</td> |
| 182 | <td> | 182 | <td> |
| 183 | <ul> | 183 | <ul> |
| @@ -191,8 +191,8 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 191 | <td>oriKvOptional(aclTensor*)</td> | 191 | <td>oriKvOptional(aclTensor*)</td> |
| 192 | <td>输入</td> | 192 | <td>输入</td> |
| 193 | <td>原始KV输入张量,Key与Value共享同一份数据。</td> | 193 | <td>原始KV输入张量,Key与Value共享同一份数据。</td> |
| 194 | - <td>SWA/CSA/HCA场景必须传入。量化KV布局由quantMode决定:quant_mode为1时,依次由rope(64,bfloat16)、nope(448,FLOAT8_E4M3FN)、scale(7,bfloat16)、pad(18B)拼接而成;quant_mode为2时,依次由nope(448,FLOAT8_E4M3FN)、rope(64,bfloat16)、scale(7,FLOAT8_E8M0)、pad(1B)拼接而成。当前仅支持1和2,量化模式2仅支持layout_kv为PA_BBND。各量化模式均支持使用UINT8、FLOAT8_E4M3FN作为单字节存储视图,底层字节内容保持不变。</td> | 194 | + <td>必须传入。quantMode=1/2保持原量化KV布局:模式1依次拼接rope(64,bfloat16)、nope(448,FLOAT8_E4M3FN)、scale(7,bfloat16)、pad(18B);模式2依次拼接nope(448,FLOAT8_E4M3FN)、rope(64,bfloat16)、scale(7,FLOAT8_E8M0)、pad(1B)。quantMode=3使用与q相同的FLOAT16或BFLOAT16原始KV,kvD=512。</td> |
| 195 | - <td>详见quantMode</td> | 195 | + <td>FLOAT8_E4M3FN、FLOAT16、BFLOAT16</td> |
| 196 | <td>ND</td> | 196 | <td>ND</td> |
| 197 | <td> | 197 | <td> |
| 198 | <ul> | 198 | <ul> |
| @@ -208,8 +208,8 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 208 | <td>cmpKvOptional(aclTensor*)</td> | 208 | <td>cmpKvOptional(aclTensor*)</td> |
| 209 | <td>输入</td> | 209 | <td>输入</td> |
| 210 | <td>压缩KV输入张量,Key与Value共享同一份数据。</td> | 210 | <td>压缩KV输入张量,Key与Value共享同一份数据。</td> |
| 211 | - <td>CSA/HCA场景必须传入,SWA场景不传入。量化KV布局由quantMode决定,同oriKvOptional。</td> | 211 | + <td>CSA/HCA场景必须传入,SWA场景不传入。quantMode=1/2的布局同oriKvOptional;quantMode=3使用UINT8 TQ4压缩KV,kvD=258。</td> |
| 212 | - <td>详见quantMode</td> | 212 | + <td>FLOAT8_E4M3FN、UINT8</td> |
| 213 | <td>ND</td> | 213 | <td>ND</td> |
| 214 | <td> | 214 | <td> |
| 215 | <ul> | 215 | <ul> |
| @@ -241,7 +241,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 241 | <td>cmpSparseIndicesOptional(aclTensor*)</td> | 241 | <td>cmpSparseIndicesOptional(aclTensor*)</td> |
| 242 | <td>输入</td> | 242 | <td>输入</td> |
| 243 | <td>代表离散取cmpKvCache的TopK索引。</td> | 243 | <td>代表离散取cmpKvCache的TopK索引。</td> |
| 244 | - <td>cmpKv稀疏场景必须传入,其他不传入。无效位置填-1,其余为非负整数。</td> | 244 | + <td>cmpKv稀疏场景必须传入,其他不传入。无效位置填-1,其余为非负整数;quantMode=3时固定为TND三维输入,cmpKvK仅支持512或1024。</td> |
| 245 | <td>INT32</td> | 245 | <td>INT32</td> |
| 246 | <td>ND</td> | 246 | <td>ND</td> |
| 247 | <td> | 247 | <td> |
| @@ -249,7 +249,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 249 | <li>layoutQ为BSND时:(b, qS, kvN, cmpKvK)</li> | 249 | <li>layoutQ为BSND时:(b, qS, kvN, cmpKvK)</li> |
| 250 | <li>layoutQ为TND时:(qT, kvN, cmpKvK)</li> | 250 | <li>layoutQ为TND时:(qT, kvN, cmpKvK)</li> |
| 251 | </ul> | 251 | </ul> |
| 252 | - 其中cmpKvK为对cmpKvOptional的TopK稀疏选择数,范围支持大于0。 | 252 | + 其中cmpKvK为对cmpKvOptional的TopK稀疏选择数,范围支持大于0;quantMode=3时仅支持512或1024。 |
| 253 | </td> | 253 | </td> |
| 254 | <td>√</td> | 254 | <td>√</td> |
| 255 | </tr> | 255 | </tr> |
| @@ -337,7 +337,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 337 | <td>cmpResidualKvOptional(aclTensor*)</td> | 337 | <td>cmpResidualKvOptional(aclTensor*)</td> |
| 338 | <td>输入</td> | 338 | <td>输入</td> |
| 339 | <td>压缩KV余数,用于恢复cmp侧mask使用的压缩前KV长度。</td> | 339 | <td>压缩KV余数,用于恢复cmp侧mask使用的压缩前KV长度。</td> |
| 340 | - <td>可选输入。传入时shape必须为(B,),第b个batch按cmp_len * cmpRatio + cmpResidualKvOptional[b]恢复压缩前KV长度;在cmpMaskMode为3且cmpRatio不等于1场景必传,cmpMaskMode为0或cmpRatio等于1时不允许传入。</td> | 340 | + <td>quantMode=1/2时可选输入。传入时shape必须为(B,),第b个batch按cmp_len * cmpRatio + cmpResidualKvOptional[b]恢复压缩前KV长度;在cmpMaskMode为3且cmpRatio不等于1场景必传,cmpMaskMode为0或cmpRatio等于1时不允许传入。quantMode=3时不支持传入。</td> |
| 341 | <td>INT32</td> | 341 | <td>INT32</td> |
| 342 | <td>ND</td> | 342 | <td>ND</td> |
| 343 | <td>(b,)</td> | 343 | <td>(b,)</td> |
| @@ -397,7 +397,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 397 | <td>quantMode(int64_t)</td> | 397 | <td>quantMode(int64_t)</td> |
| 398 | <td>输入</td> | 398 | <td>输入</td> |
| 399 | <td>表示量化模式。</td> | 399 | <td>表示量化模式。</td> |
| 400 | - <td>表示量化模式。量化模式1表示K、V nope为per-token-group量化,scale类型为bfloat16,量化模式2表示K、V nope为per-token-group量化,scale类型为FLOAT8_E8M0。当前仅支持1和2,量化模式2仅支持layout_kv为PA_BBND。</td> | 400 | + <td>表示量化模式。支持1、2、3:模式1的scale类型为bfloat16;模式2的scale类型为FLOAT8_E8M0且仅支持layoutKv为PA_BBND;模式3表示融合TQ4反量化的TurboQuant路径。具体产品支持的量化模式见约束说明。</td> |
| 401 | <td>-</td> | 401 | <td>-</td> |
| 402 | <td>-</td> | 402 | <td>-</td> |
| 403 | <td>-</td> | 403 | <td>-</td> |
| @@ -518,7 +518,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 518 | <td>输出</td> | 518 | <td>输出</td> |
| 519 | <td>注意力计算输出。</td> | 519 | <td>注意力计算输出。</td> |
| 520 | <td>-</td> | 520 | <td>-</td> |
| 521 | - <td>BFLOAT16</td> | 521 | + <td>与q的数据类型一致</td> |
| 522 | <td>ND</td> | 522 | <td>ND</td> |
| 523 | <td>与q的shape一致</td> | 523 | <td>与q的shape一致</td> |
| 524 | <td>×</td> | 524 | <td>×</td> |
| @@ -673,13 +673,41 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 673 | - aclnnMixedQuantSparseFlashMlaMetadata和aclnnMixedQuantSparseFlashMla的入参在调用时应该保持一致。由于算子分为两个接口分段调用,算子无法自行校验,正确性需要由用户自行保证。若接口传入参数不一致,会发生未定义行为(精度问题、非法内存访问导致的程序崩溃等)。 | 673 | - aclnnMixedQuantSparseFlashMlaMetadata和aclnnMixedQuantSparseFlashMla的入参在调用时应该保持一致。由于算子分为两个接口分段调用,算子无法自行校验,正确性需要由用户自行保证。若接口传入参数不一致,会发生未定义行为(精度问题、非法内存访问导致的程序崩溃等)。 |
| 674 | - oriTopkLengthOptional、cmpTopkLengthOptional表示ori/cmp sparseIndices实际参与计算的长度。其值不能大于sparseIndicesOptional的最后一维大小,且当sequsedQOptional传入时,topkLength对应有效部分的值需要大于等于0。 | 674 | - oriTopkLengthOptional、cmpTopkLengthOptional表示ori/cmp sparseIndices实际参与计算的长度。其值不能大于sparseIndicesOptional的最后一维大小,且当sequsedQOptional传入时,topkLength对应有效部分的值需要大于等于0。 |
| 675 | - 当oriMaskMode/cmpMaskMode为0时,oriKvK/cmpKvK需要大于等于oriTopkLengthOptional/cmpTopkLengthOptional的最大值。 | 675 | - 当oriMaskMode/cmpMaskMode为0时,oriKvK/cmpKvK需要大于等于oriTopkLengthOptional/cmpTopkLengthOptional的最大值。 |
| 676 | - - cmpResidualKvOptional配合cmpRatio使用,可恢复压缩前KV长度。且每个batch的值需要小于cmpRatio。仅当cmpMaskMode为3且cmpRatio不等于1时允许传入;cmpMaskMode为0或cmpRatio等于1时不允许传入。 | 676 | + - quantMode=1/2时,cmpResidualKvOptional配合cmpRatio使用,可恢复压缩前KV长度。且每个batch的值需要小于cmpRatio。仅当cmpMaskMode为3且cmpRatio不等于1时允许传入;cmpMaskMode为0或cmpRatio等于1时不允许传入。 |
| 677 | - - attnOutOut:tensor类型,公式中的输出,数据类型支持BFLOAT16。数据格式支持ND。限制:该输出参数的shape与入参q的shape保持一致,dtype与q一致。 | 677 | + - attnOutOut:tensor类型,公式中的输出。数据类型支持FLOAT16、BFLOAT16,数据格式支持ND,shape和dtype与q一致。 |
| 678 | - returnSoftmaxLse=False时返回shape为[1]的值为0的tensor;returnSoftmaxLse=True时返回FLOAT32的log-sum-exp结果。 | 678 | - returnSoftmaxLse=False时返回shape为[1]的值为0的tensor;returnSoftmaxLse=True时返回FLOAT32的log-sum-exp结果。 |
| 679 | - cuSeqlensQOptional、cuSeqlensOriKvOptional、cuSeqlensCmpKvOptional须满足首元素为0,且序列整体呈非递减排列,即任一元素不小于其前一个元素。 | 679 | - cuSeqlensQOptional、cuSeqlensOriKvOptional、cuSeqlensCmpKvOptional须满足首元素为0,且序列整体呈非递减排列,即任一元素不小于其前一个元素。 |
| 680 | - 当layoutKv为PA_BBND时,oriKvOptional和cmpKvOptional支持0轴非连续。 | 680 | - 当layoutKv为PA_BBND时,oriKvOptional和cmpKvOptional支持0轴非连续。 |
| 681 | - 各参数shape中以相同符号表示的维度,其对应轴的实际数值需保持一致。 | 681 | - 各参数shape中以相同符号表示的维度,其对应轴的实际数值需保持一致。 |
| 682 | 682 | ||
| 683 | +### 产品差异化约束 | ||
| 684 | + | ||
| 685 | +<!-- npu="950" id7 --> | ||
| 686 | +- <term>Ascend 950PR&950DT系列产品</term>: | ||
| 687 | + - 仅支持`quantMode=1/2`。q、attnOutOut的数据类型为BFLOAT16,oriKvOptional、cmpKvOptional的数据类型为FLOAT8_E4M3FN。 | ||
| 688 | + - 下文参数组约束适用于`quantMode=1/2`场景。 | ||
| 689 | +<!-- end id7 --> | ||
| 690 | + | ||
| 691 | +<!-- npu="A3" id8 --> | ||
| 692 | +- <term>Atlas A3系列产品</term>: | ||
| 693 | + - 仅支持`quantMode=3`的TurboQuant路径。 | ||
| 694 | + - q、attnOutOut:`layoutQOptional`为TND;数据类型为FLOAT16或BFLOAT16且保持一致;qN为4到128的4的倍数,qD为512,qT允许为0。 | ||
| 695 | + - oriKvOptional、cmpKvOptional:均必须传入,`layoutKvOptional`为PA_BBND。oriKvOptional的数据类型与q一致且kvD为512;cmpKvOptional的数据类型为UINT8且kvD为258。两者blockSize均为16到1024的16的倍数。 | ||
| 696 | + - 稀疏与PA参数:cmpSparseIndicesOptional、oriBlockTableOptional、cmpBlockTableOptional必须传入;cmpSparseIndicesOptional的shape为(qT, 1, 512)或(qT, 1, 1024)。oriSparseIndicesOptional、oriTopkLengthOptional、cmpTopkLengthOptional不支持传入。 | ||
| 697 | + - 序列参数:cuSeqlensQOptional、sequsedOriKvOptional必须传入;cuSeqlensOriKvOptional、cuSeqlensCmpKvOptional、sequsedQOptional、sequsedCmpKvOptional不支持传入。 | ||
| 698 | + - Mask与压缩参数:`oriMaskMode=4`、`cmpMaskMode=3`、`oriWinLeft>=0`、`oriWinRight=0`,`cmpRatio`仅支持4或128;cmpResidualKvOptional不支持传入。 | ||
| 699 | +<!-- end id8 --> | ||
| 700 | + | ||
| 701 | +<!-- npu="910b" id9 --> | ||
| 702 | +- <term>Atlas A2系列产品</term>: | ||
| 703 | + - 仅支持`quantMode=3`的TurboQuant路径。 | ||
| 704 | + - q、attnOutOut:`layoutQOptional`为TND;数据类型为FLOAT16或BFLOAT16且保持一致;qN为4到128的4的倍数,qD为512,qT允许为0。 | ||
| 705 | + - oriKvOptional、cmpKvOptional:均必须传入,`layoutKvOptional`为PA_BBND。oriKvOptional的数据类型与q一致且kvD为512;cmpKvOptional的数据类型为UINT8且kvD为258。两者blockSize均为16到1024的16的倍数。 | ||
| 706 | + - 稀疏与PA参数:cmpSparseIndicesOptional、oriBlockTableOptional、cmpBlockTableOptional必须传入;cmpSparseIndicesOptional的shape为(qT, 1, 512)或(qT, 1, 1024)。oriSparseIndicesOptional、oriTopkLengthOptional、cmpTopkLengthOptional不支持传入。 | ||
| 707 | + - 序列参数:cuSeqlensQOptional、sequsedOriKvOptional必须传入;cuSeqlensOriKvOptional、cuSeqlensCmpKvOptional、sequsedQOptional、sequsedCmpKvOptional不支持传入。 | ||
| 708 | + - Mask与压缩参数:`oriMaskMode=4`、`cmpMaskMode=3`、`oriWinLeft>=0`、`oriWinRight=0`,`cmpRatio`仅支持4或128;cmpResidualKvOptional不支持传入。 | ||
| 709 | +<!-- end id9 --> | ||
| 710 | + | ||
| 683 | ### 特性参数组 | 711 | ### 特性参数组 |
| 684 | 712 | ||
| 685 | | 特性参数组 | 参数字段名称 | | 713 | | 特性参数组 | 参数字段名称 | |
| @@ -731,7 +759,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 731 | <td>q</td> | 759 | <td>q</td> |
| 732 | <td> | 760 | <td> |
| 733 | <ul> | 761 | <ul> |
| 734 | - <li>dtype支持BFLOAT16</li> | 762 | + <li>dtype支持FLOAT16、BFLOAT16,其中quantMode=1/2仅支持BFLOAT16</li> |
| 735 | <li>layoutQ为BSND时,q的shape为(b, qS, qN, qD)</li> | 763 | <li>layoutQ为BSND时,q的shape为(b, qS, qN, qD)</li> |
| 736 | <li>layoutQ为TND时,q的shape为(qT, qN, qD)</li> | 764 | <li>layoutQ为TND时,q的shape为(qT, qN, qD)</li> |
| 737 | </ul> | 765 | </ul> |
| @@ -742,7 +770,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 742 | <td rowspan="4"> | 770 | <td rowspan="4"> |
| 743 | <ul> | 771 | <ul> |
| 744 | <li>q、attnOutOut的dtype、shape需相同</li> | 772 | <li>q、attnOutOut的dtype、shape需相同</li> |
| 745 | - <li>若cmpKvOptional传入,oriKvOptional与cmpKvOptional的dtype需一致</li> | 773 | + <li>quantMode=1/2时,若cmpKvOptional传入,oriKvOptional与cmpKvOptional的dtype需一致;quantMode=3时,q、oriKvOptional、attnOutOut的dtype需一致,cmpKvOptional为UINT8</li> |
| 746 | <li>layoutKv不为PA_BBND时,layoutQ和layoutKv需保持一致</li> | 774 | <li>layoutKv不为PA_BBND时,layoutQ和layoutKv需保持一致</li> |
| 747 | <li>layoutKv为PA_BBND时,layoutQ可为BSND或TND</li> | 775 | <li>layoutKv为PA_BBND时,layoutQ可为BSND或TND</li> |
| 748 | </ul> | 776 | </ul> |
| @@ -754,17 +782,16 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 754 | <li>qS > 0</li> | 782 | <li>qS > 0</li> |
| 755 | <li>0 < qN <= 128</li> | 783 | <li>0 < qN <= 128</li> |
| 756 | <li>qD = 512</li> | 784 | <li>qD = 512</li> |
| 757 | - <li>qT > 0</li> | 785 | + <li>quantMode=1/2时qT > 0,quantMode=3时qT >= 0</li> |
| 758 | <li>oriKvS > 0</li> | 786 | <li>oriKvS > 0</li> |
| 759 | <li>cmpKvS > 0</li> | 787 | <li>cmpKvS > 0</li> |
| 760 | <li>kvN = 1</li> | 788 | <li>kvN = 1</li> |
| 761 | - <li>quantMode=1时kvD=608,quantMode=2时kvD=584</li> | 789 | + <li>quantMode=1时kvD=608,quantMode=2时kvD=584;quantMode=3时oriKvOptional的kvD=512、cmpKvOptional的kvD=258</li> |
| 762 | <li>oriKvT > 0</li> | 790 | <li>oriKvT > 0</li> |
| 763 | <li>cmpKvT > 0</li> | 791 | <li>cmpKvT > 0</li> |
| 764 | <li>oriKvBlockNums > 0</li> | 792 | <li>oriKvBlockNums > 0</li> |
| 765 | <li>cmpKvBlockNums > 0</li> | 793 | <li>cmpKvBlockNums > 0</li> |
| 766 | - <li>1 <= oriKvBlockSize <= 1024</li> | 794 | + <li>1 <= oriKvBlockSize、cmpKvBlockSize <= 1024;quantMode=3时还要求blockSize为16的倍数</li> |
| 767 | - <li>1 <= cmpKvBlockSize <= 1024</li> | ||
| 768 | </ul> | 795 | </ul> |
| 769 | </td> | 796 | </td> |
| 770 | </tr> | 797 | </tr> |
| @@ -772,7 +799,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 772 | <td>oriKvOptional</td> | 799 | <td>oriKvOptional</td> |
| 773 | <td> | 800 | <td> |
| 774 | <ul> | 801 | <ul> |
| 775 | - <li>dtype支持FLOAT8_E4M3FN</li> | 802 | + <li>dtype支持FLOAT8_E4M3FN、FLOAT16、BFLOAT16;quantMode=3时支持FLOAT16、BFLOAT16且与q一致</li> |
| 776 | <li>layoutKv为BSND时,oriKvOptional的shape为(b, oriKvS, kvN, kvD)</li> | 803 | <li>layoutKv为BSND时,oriKvOptional的shape为(b, oriKvS, kvN, kvD)</li> |
| 777 | <li>layoutKv为TND时,oriKvOptional的shape为(oriKvT, kvN, kvD)</li> | 804 | <li>layoutKv为TND时,oriKvOptional的shape为(oriKvT, kvN, kvD)</li> |
| 778 | <li>layoutKv为PA_BBND时,oriKvOptional的shape为(oriKvBlockNums, oriKvBlockSize, kvN, kvD)</li> | 805 | <li>layoutKv为PA_BBND时,oriKvOptional的shape为(oriKvBlockNums, oriKvBlockSize, kvN, kvD)</li> |
| @@ -786,7 +813,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 786 | <td>attnOutOut</td> | 813 | <td>attnOutOut</td> |
| 787 | <td> | 814 | <td> |
| 788 | <ul> | 815 | <ul> |
| 789 | - <li>dtype支持BFLOAT16</li> | 816 | + <li>dtype支持FLOAT16、BFLOAT16;quantMode=3时需与q一致</li> |
| 790 | <li>layoutQ为BSND时,attnOutOut的shape为(b, qS, qN, qD)</li> | 817 | <li>layoutQ为BSND时,attnOutOut的shape为(b, qS, qN, qD)</li> |
| 791 | <li>layoutQ为TND时,attnOutOut的shape为(qT, qN, qD)</li> | 818 | <li>layoutQ为TND时,attnOutOut的shape为(qT, qN, qD)</li> |
| 792 | </ul> | 819 | </ul> |
| @@ -799,7 +826,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMla( | |||
| 799 | <td>cmpKvOptional</td> | 826 | <td>cmpKvOptional</td> |
| 800 | <td> | 827 | <td> |
| 801 | <ul> | 828 | <ul> |
| 802 | - <li>dtype支持FLOAT8_E4M3FN</li> | 829 | + <li>dtype支持FLOAT8_E4M3FN、UINT8;quantMode=3时固定为UINT8</li> |
| 803 | <li>layoutKv为BSND时,cmpKvOptional的shape为(b, cmpKvS, kvN, kvD)</li> | 830 | <li>layoutKv为BSND时,cmpKvOptional的shape为(b, cmpKvS, kvN, kvD)</li> |
| 804 | <li>layoutKv为TND时,cmpKvOptional的shape为(cmpKvT, kvN, kvD)</li> | 831 | <li>layoutKv为TND时,cmpKvOptional的shape为(cmpKvT, kvN, kvD)</li> |
| 805 | <li>layoutKv为PA_BBND时,cmpKvOptional的shape为(cmpKvBlockNums, cmpKvBlockSize, kvN, kvD)</li> | 832 | <li>layoutKv为PA_BBND时,cmpKvOptional的shape为(cmpKvBlockNums, cmpKvBlockSize, kvN, kvD)</li> |
| @@ -1192,6 +1219,7 @@ metadataOptional校验 | |||
| 1192 | <li>dtype支持INT32</li> | 1219 | <li>dtype支持INT32</li> |
| 1193 | <li>shape为(qT, kvN, cmpKvK)或(b, qS, kvN, cmpKvK)</li> | 1220 | <li>shape为(qT, kvN, cmpKvK)或(b, qS, kvN, cmpKvK)</li> |
| 1194 | <li>无效位置填-1,其余为非负整数</li> | 1221 | <li>无效位置填-1,其余为非负整数</li> |
| 1222 | + <li>quantMode=3时仅支持(qT, 1, 512)或(qT, 1, 1024)</li> | ||
| 1195 | </ul> | 1223 | </ul> |
| 1196 | </td> | 1224 | </td> |
| 1197 | <td> | 1225 | <td> |
| @@ -6,10 +6,10 @@ | |||
| 6 | - <term>Ascend 950PR&950DT系列产品</term>:支持 | 6 | - <term>Ascend 950PR&950DT系列产品</term>:支持 |
| 7 | <!-- end id1 --> | 7 | <!-- end id1 --> |
| 8 | <!-- npu="A3" id2 --> | 8 | <!-- npu="A3" id2 --> |
| 9 | -- <term>Atlas A3系列产品</term>:不支持 | 9 | +- <term>Atlas A3系列产品</term>:支持 |
| 10 | <!-- end id2 --> | 10 | <!-- end id2 --> |
| 11 | <!-- npu="910b" id3 --> | 11 | <!-- npu="910b" id3 --> |
| 12 | -- <term>Atlas A2系列产品</term>:不支持 | 12 | +- <term>Atlas A2系列产品</term>:支持 |
| 13 | <!-- end id3 --> | 13 | <!-- end id3 --> |
| 14 | <!-- npu="310b" id4 --> | 14 | <!-- npu="310b" id4 --> |
| 15 | - <term>Atlas 200I/500 A2推理产品</term>:不支持 | 15 | - <term>Atlas 200I/500 A2推理产品</term>:不支持 |
| @@ -154,7 +154,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 154 | | num_heads_q | int | 必选 | 表示q头数 | int32 | - | - | 154 | | num_heads_q | int | 必选 | 表示q头数 | int32 | - | - |
| 155 | | num_heads_kv | int | 必选 | 表示ori_kv/cmp_kv头数 | int32 | - | - | 155 | | num_heads_kv | int | 必选 | 表示ori_kv/cmp_kv头数 | int32 | - | - |
| 156 | | head_dim | int | 必选 | 表示每个注意力头的维度 | int32 | - | - | 156 | | head_dim | int | 必选 | 表示每个注意力头的维度 | int32 | - | - |
| 157 | -| quant_mode | int | 必选 | 表示量化模式。当前仅支持1和2。quant_mode为1时,依次由rope(64,bfloat16)、nope(448,float8_e4m3fn)、scale(7,bfloat16)、pad(18B)拼接而成;quant_mode为2时,依次由nope(448,float8_e4m3fn)、rope(64,bfloat16)、scale(7,float8_e8m0)、pad(1B)拼接而成。 | int32 | - | - | 157 | +| quant_mode | int | 必选 | 量化模式。支持1、2、3,模式3表示融合TQ4反量化的TurboQuant路径。具体产品支持的量化模式见约束说明。 | int32 | - | - |
| 158 | | cu_seqlens_q | tensor | 可选 | 表示输入q处理的变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> | 158 | | cu_seqlens_q | tensor | 可选 | 表示输入q处理的变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> |
| 159 | | cu_seqlens_ori_kv | tensor | 可选 | 表示输入ori_kv处理变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> | 159 | | cu_seqlens_ori_kv | tensor | 可选 | 表示输入ori_kv处理变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> |
| 160 | | cu_seqlens_cmp_kv | tensor | 可选 | 表示输入cmp_kv处理变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> | 160 | | cu_seqlens_cmp_kv | tensor | 可选 | 表示输入cmp_kv处理变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> |
| @@ -185,12 +185,12 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 185 | 185 | ||
| 186 | | 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 数据格式 | 维度 | | 186 | | 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 数据格式 | 维度 | |
| 187 | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | 187 | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | |
| 188 | -| q | tensor | 必选 | 表示公式中的q | bfloat16 | ND | <ul><li>(b, q_s, q_n, q_d)</li><li>(q_t, q_n, q_d)</li></ul> | 188 | +| q | tensor | 必选 | 表示公式中的q | float16、bfloat16 | ND | <ul><li>(b, q_s, q_n, q_d)</li><li>(q_t, q_n, q_d)</li></ul> |
| 189 | -| quant_mode | int | 必选 | 表示量化模式。当前仅支持1和2。quant_mode为1时,量化KV依次由rope(64,bfloat16)、nope(448,float8_e4m3fn)、scale(7,bfloat16)、pad(18B)拼接而成;quant_mode为2时,量化KV依次由nope(448,float8_e4m3fn)、rope(64,bfloat16)、scale(7,float8_e8m0)、pad(1B)拼接而成。各量化模式均支持使用UINT8、FLOAT8_E4M3FN作为单字节存储视图,底层字节内容保持不变。 | int32 | - | - | 189 | +| quant_mode | int | 必选 | 量化模式。支持1、2、3;模式1/2保持原FP8量化布局,模式3表示融合TQ4反量化。具体产品支持的量化模式见约束说明。 | int32 | - | - |
| 190 | -| ori_kv | tensor | 可选 | 表示原始量化KV输入,Key和Value共享同一份数据 | fp8_e4m3 | ND | <ul><li>(b, ori_kv_s, kv_n, kv_d)</li><li>(ori_kv_t, kv_n, kv_d)</li><li>(ori_kv_block_nums, ori_kv_block_size, kv_n, kv_d)</li></ul> | 190 | +| ori_kv | tensor | 可选 | 原始KV。quant_mode=1/2时使用fp8_e4m3;quant_mode=3时必须传入且dtype与q一致、kv_d=512。 | fp8_e4m3、float16、bfloat16 | ND | <ul><li>(b, ori_kv_s, kv_n, kv_d)</li><li>(ori_kv_t, kv_n, kv_d)</li><li>(ori_kv_block_nums, ori_kv_block_size, kv_n, kv_d)</li></ul> |
| 191 | -| cmp_kv | tensor | 可选 | 表示压缩量化KV输入,Key和Value共享同一份数据 | fp8_e4m3 | ND | <ul><li>(b, cmp_kv_s, kv_n, kv_d)</li><li>(cmp_kv_t, kv_n, kv_d)</li><li>(cmp_kv_block_nums, cmp_kv_block_size, kv_n, kv_d)</li></ul> | 191 | +| cmp_kv | tensor | 可选 | 压缩KV。quant_mode=1/2时使用fp8_e4m3;quant_mode=3时必须传入uint8 TQ4数据、kv_d=258。 | fp8_e4m3、uint8 | ND | <ul><li>(b, cmp_kv_s, kv_n, kv_d)</li><li>(cmp_kv_t, kv_n, kv_d)</li><li>(cmp_kv_block_nums, cmp_kv_block_size, kv_n, kv_d)</li></ul> |
| 192 | | ori_sparse_indices | tensor | 可选 | 表示原始KV topK索引,无效位置填-1 | int32 | ND | <ul><li>(q_t, kv_n, ori_kv_k)</li><li>(b, q_s, kv_n, ori_kv_k)</li></ul> | 192 | | ori_sparse_indices | tensor | 可选 | 表示原始KV topK索引,无效位置填-1 | int32 | ND | <ul><li>(q_t, kv_n, ori_kv_k)</li><li>(b, q_s, kv_n, ori_kv_k)</li></ul> |
| 193 | -| cmp_sparse_indices | tensor | 可选 | 表示压缩KV topK索引,无效位置填-1 | int32 | ND | <ul><li>(q_t, kv_n, cmp_kv_k)</li><li>(b, q_s, kv_n, cmp_kv_k)</li></ul> | 193 | +| cmp_sparse_indices | tensor | 可选 | 表示压缩KV topK索引,无效位置填-1;quant_mode=3时必须传入且cmp_kv_k仅支持512或1024。 | int32 | ND | <ul><li>(q_t, kv_n, cmp_kv_k)</li><li>(b, q_s, kv_n, cmp_kv_k)</li></ul> |
| 194 | | ori_block_table | tensor | 可选 | 表示PageAttention场景下ori_kv使用的block映射表 | int32 | ND | <ul><li>(b, ceil(ori_kv_s_max/ori_kv_block_size))</li></ul> | 194 | | ori_block_table | tensor | 可选 | 表示PageAttention场景下ori_kv使用的block映射表 | int32 | ND | <ul><li>(b, ceil(ori_kv_s_max/ori_kv_block_size))</li></ul> |
| 195 | | cmp_block_table | tensor | 可选 | 表示PageAttention场景下cmp_kv使用的block映射表 | int32 | ND | <ul><li>(b, ceil(cmp_kv_s_max/cmp_kv_block_size))</li></ul> | 195 | | cmp_block_table | tensor | 可选 | 表示PageAttention场景下cmp_kv使用的block映射表 | int32 | ND | <ul><li>(b, ceil(cmp_kv_s_max/cmp_kv_block_size))</li></ul> |
| 196 | | cu_seqlens_q | tensor | 可选 | 表示处理输入q变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> | 196 | | cu_seqlens_q | tensor | 可选 | 表示处理输入q变长序列的累积序列长度 | int32 | ND | <ul><li>(b+1,)</li></ul> |
| @@ -199,7 +199,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 199 | | seqused_q | tensor | 可选 | 表示输入q每batch中实际参与运算的序列长度 | int32 | ND | <ul><li>(b,)</li></ul> | 199 | | seqused_q | tensor | 可选 | 表示输入q每batch中实际参与运算的序列长度 | int32 | ND | <ul><li>(b,)</li></ul> |
| 200 | | seqused_ori_kv | tensor | 可选 | 表示输入ori_kv每batch中实际参与运算的序列长度 | int32 | ND | <ul><li>(b,)</li></ul> | 200 | | seqused_ori_kv | tensor | 可选 | 表示输入ori_kv每batch中实际参与运算的序列长度 | int32 | ND | <ul><li>(b,)</li></ul> |
| 201 | | seqused_cmp_kv | tensor | 可选 | 表示输入cmp_kv每batch中实际参与运算的序列长度 | int32 | ND | <ul><li>(b,)</li></ul> | 201 | | seqused_cmp_kv | tensor | 可选 | 表示输入cmp_kv每batch中实际参与运算的序列长度 | int32 | ND | <ul><li>(b,)</li></ul> |
| 202 | -| cmp_residual_kv | tensor | 可选 | 表示每batch中cmp_kv压缩后序列长度的余数。当cmp_mask_mode=3且cmp_ratio!=1时必传;当cmp_mask_mode=0或cmp_ratio=1时不允许传入。 | int32 | ND | <ul><li>(b,)</li></ul> | 202 | +| cmp_residual_kv | tensor | 可选 | 表示每batch中cmp_kv压缩后序列长度的余数。quant_mode=1/2时,当cmp_mask_mode=3且cmp_ratio!=1时必传;当cmp_mask_mode=0或cmp_ratio=1时不允许传入。quant_mode=3时不支持传入。 | int32 | ND | <ul><li>(b,)</li></ul> |
| 203 | | ori_topk_length | tensor | 可选 | 表示ori_sparse_indices实际参与计算的长度 | int32 | ND | <ul><li>(b, q_s, kv_n)</li><li>(q_t, kv_n)</li></ul> | 203 | | ori_topk_length | tensor | 可选 | 表示ori_sparse_indices实际参与计算的长度 | int32 | ND | <ul><li>(b, q_s, kv_n)</li><li>(q_t, kv_n)</li></ul> |
| 204 | | cmp_topk_length | tensor | 可选 | 表示cmp_sparse_indices实际参与计算的长度 | int32 | ND | <ul><li>(b, q_s, kv_n)</li><li>(q_t, kv_n)</li></ul> | 204 | | cmp_topk_length | tensor | 可选 | 表示cmp_sparse_indices实际参与计算的长度 | int32 | ND | <ul><li>(b, q_s, kv_n)</li><li>(q_t, kv_n)</li></ul> |
| 205 | | sinks | tensor | 可选 | 表示各注意力头设置独立可学习虚拟偏移项,用于维持长文本推理时的稳定性 | float32 | ND | <ul><li>(q_n,)</li></ul> | 205 | | sinks | tensor | 可选 | 表示各注意力头设置独立可学习虚拟偏移项,用于维持长文本推理时的稳定性 | float32 | ND | <ul><li>(q_n,)</li></ul> |
| @@ -228,7 +228,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 228 | 228 | ||
| 229 | | 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 数据格式 | 维度 | | 229 | | 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 数据格式 | 维度 | |
| 230 | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | 230 | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | |
| 231 | -| attention_out | tensor | 必选 | mixed_quant_sparse_flash_mla的计算输出 | bfloat16 | ND | <ul><li>(b, q_s, q_n, q_d)</li><li>(q_t, q_n, q_d)</li></ul> | 231 | +| attention_out | tensor | 必选 | mixed_quant_sparse_flash_mla的计算输出,dtype与q一致 | float16、bfloat16 | ND | <ul><li>(b, q_s, q_n, q_d)</li><li>(q_t, q_n, q_d)</li></ul> |
| 232 | | softmax_lse | tensor | 可选 | 对query乘key的结果先取max得到softmax_max,query乘key的结果减去softmax_max后取exp再取sum得到softmax_sum,最后对softmax_sum取log再加上softmax_max得到的结果。 | float32 | ND | <ul><li>(b, kv_n, q_s, q_n/kv_n)</li><li>(kv_n, q_t, q_n/kv_n)</li></ul> | 232 | | softmax_lse | tensor | 可选 | 对query乘key的结果先取max得到softmax_max,query乘key的结果减去softmax_max后取exp再取sum得到softmax_sum,最后对softmax_sum取log再加上softmax_max得到的结果。 | float32 | ND | <ul><li>(b, kv_n, q_s, q_n/kv_n)</li><li>(kv_n, q_t, q_n/kv_n)</li></ul> |
| 233 | 233 | ||
| 234 | ## 约束说明 | 234 | ## 约束说明 |
| @@ -238,13 +238,41 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 238 | - mixed_quant_sparse_flash_mla_metadata和mixed_quant_sparse_flash_mla的入参在调用时应该保持一致。由于算子分为两个接口分段调用,算子无法自行校验,正确性需要由用户自行保证。若接口传入参数不一致,会发生未定义行为(精度问题、非法内存访问导致的程序崩溃等)。 | 238 | - mixed_quant_sparse_flash_mla_metadata和mixed_quant_sparse_flash_mla的入参在调用时应该保持一致。由于算子分为两个接口分段调用,算子无法自行校验,正确性需要由用户自行保证。若接口传入参数不一致,会发生未定义行为(精度问题、非法内存访问导致的程序崩溃等)。 |
| 239 | - ori_topk_length、cmp_topk_length表示ori/cmp sparse_indices实际参与计算的长度。其值不能大于sparse_indices的最后一维大小,且当seqused_q传入时,topk_length对应有效部分的值需要大于等于0。 | 239 | - ori_topk_length、cmp_topk_length表示ori/cmp sparse_indices实际参与计算的长度。其值不能大于sparse_indices的最后一维大小,且当seqused_q传入时,topk_length对应有效部分的值需要大于等于0。 |
| 240 | - 当ori_mask_mode/cmp_mask_mode为0时,ori_kv_k/cmp_kv_k需要大于等于ori_topk_length/cmp_topk_length的最大值。 | 240 | - 当ori_mask_mode/cmp_mask_mode为0时,ori_kv_k/cmp_kv_k需要大于等于ori_topk_length/cmp_topk_length的最大值。 |
| 241 | - - cmp_residual_kv配合cmp_ratio使用,可恢复压缩前KV长度。且每个batch的值需要小于cmp_ratio,即cmp_residual_kv[i] < cmp_ratio。仅当cmp_mask_mode=3且cmp_ratio!=1时允许传入;当cmp_mask_mode=0或cmp_ratio=1时不允许传入。 | 241 | + - quant_mode=1/2时,cmp_residual_kv配合cmp_ratio使用,可恢复压缩前KV长度。且每个batch的值需要小于cmp_ratio,即cmp_residual_kv[i] < cmp_ratio。仅当cmp_mask_mode=3且cmp_ratio!=1时允许传入;当cmp_mask_mode=0或cmp_ratio=1时不允许传入。 |
| 242 | - - attention_out:tensor类型,公式中的输出,数据类型支持bfloat16。数据格式支持ND。限制:该输出参数的shape与入参q的shape保持一致,dtype与q一致。 | 242 | + - attention_out:tensor类型,公式中的输出。数据类型支持float16、bfloat16,数据格式支持ND,shape和dtype与q一致。 |
| 243 | - return_softmax_lse=False时返回shape为[1]的值为0的tensor;return_softmax_lse=True时返回float32的log-sum-exp结果。 | 243 | - return_softmax_lse=False时返回shape为[1]的值为0的tensor;return_softmax_lse=True时返回float32的log-sum-exp结果。 |
| 244 | - cu_seqlens_q、cu_seqlens_ori_kv、cu_seqlens_cmp_kv须满足首元素为0,且序列整体呈非递减排列,即任一元素不小于其前一个元素。 | 244 | - cu_seqlens_q、cu_seqlens_ori_kv、cu_seqlens_cmp_kv须满足首元素为0,且序列整体呈非递减排列,即任一元素不小于其前一个元素。 |
| 245 | - 当layout_kv为PA_BBND时,ori_kv和cmp_kv支持0轴非连续。 | 245 | - 当layout_kv为PA_BBND时,ori_kv和cmp_kv支持0轴非连续。 |
| 246 | - 各参数shape中以相同符号表示的维度,其对应轴的实际数值需保持一致。 | 246 | - 各参数shape中以相同符号表示的维度,其对应轴的实际数值需保持一致。 |
| 247 | 247 | ||
| 248 | +### 产品差异化约束 | ||
| 249 | + | ||
| 250 | +<!-- npu="950" id7 --> | ||
| 251 | +- <term>Ascend 950PR&950DT系列产品</term>: | ||
| 252 | + - 仅支持`quant_mode=1/2`。q、attention_out的数据类型为bfloat16,ori_kv、cmp_kv的数据类型为fp8_e4m3。 | ||
| 253 | + - 下文参数组约束适用于`quant_mode=1/2`场景。 | ||
| 254 | +<!-- end id7 --> | ||
| 255 | + | ||
| 256 | +<!-- npu="A3" id8 --> | ||
| 257 | +- <term>Atlas A3系列产品</term>: | ||
| 258 | + - 仅支持`quant_mode=3`的TurboQuant路径。 | ||
| 259 | + - q、attention_out:`layout_q`为TND;数据类型为float16或bfloat16且保持一致;q_n为4到128的4的倍数,q_d为512,q_t允许为0。 | ||
| 260 | + - ori_kv、cmp_kv:均必须传入,`layout_kv`为PA_BBND。ori_kv的数据类型与q一致且kv_d为512;cmp_kv的数据类型为uint8且kv_d为258。两者block_size均为16到1024的16的倍数。 | ||
| 261 | + - 稀疏与PA参数:cmp_sparse_indices、ori_block_table、cmp_block_table必须传入;cmp_sparse_indices的shape为(q_t, 1, 512)或(q_t, 1, 1024)。ori_sparse_indices、ori_topk_length、cmp_topk_length不支持传入。 | ||
| 262 | + - 序列参数:cu_seqlens_q、seqused_ori_kv必须传入;cu_seqlens_ori_kv、cu_seqlens_cmp_kv、seqused_q、seqused_cmp_kv不支持传入。 | ||
| 263 | + - Mask与压缩参数:`ori_mask_mode=4`、`cmp_mask_mode=3`、`ori_win_left>=0`、`ori_win_right=0`,`cmp_ratio`仅支持4或128;cmp_residual_kv不支持传入。 | ||
| 264 | +<!-- end id8 --> | ||
| 265 | + | ||
| 266 | +<!-- npu="910b" id9 --> | ||
| 267 | +- <term>Atlas A2系列产品</term>: | ||
| 268 | + - 仅支持`quant_mode=3`的TurboQuant路径。 | ||
| 269 | + - q、attention_out:`layout_q`为TND;数据类型为float16或bfloat16且保持一致;q_n为4到128的4的倍数,q_d为512,q_t允许为0。 | ||
| 270 | + - ori_kv、cmp_kv:均必须传入,`layout_kv`为PA_BBND。ori_kv的数据类型与q一致且kv_d为512;cmp_kv的数据类型为uint8且kv_d为258。两者block_size均为16到1024的16的倍数。 | ||
| 271 | + - 稀疏与PA参数:cmp_sparse_indices、ori_block_table、cmp_block_table必须传入;cmp_sparse_indices的shape为(q_t, 1, 512)或(q_t, 1, 1024)。ori_sparse_indices、ori_topk_length、cmp_topk_length不支持传入。 | ||
| 272 | + - 序列参数:cu_seqlens_q、seqused_ori_kv必须传入;cu_seqlens_ori_kv、cu_seqlens_cmp_kv、seqused_q、seqused_cmp_kv不支持传入。 | ||
| 273 | + - Mask与压缩参数:`ori_mask_mode=4`、`cmp_mask_mode=3`、`ori_win_left>=0`、`ori_win_right=0`,`cmp_ratio`仅支持4或128;cmp_residual_kv不支持传入。 | ||
| 274 | +<!-- end id9 --> | ||
| 275 | + | ||
| 248 | ### 特性参数组 | 276 | ### 特性参数组 |
| 249 | 277 | ||
| 250 | | 特性参数组 | 参数字段名称 | | 278 | | 特性参数组 | 参数字段名称 | |
| @@ -298,7 +326,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 298 | <td>q</td> | 326 | <td>q</td> |
| 299 | <td> | 327 | <td> |
| 300 | <ul> | 328 | <ul> |
| 301 | - <li>dtype支持bfloat16</li> | 329 | + <li>dtype支持float16、bfloat16,其中quant_mode=1/2仅支持bfloat16</li> |
| 302 | <li>layout_q为BSND时,q的shape为(b, q_s, q_n, q_d)</li> | 330 | <li>layout_q为BSND时,q的shape为(b, q_s, q_n, q_d)</li> |
| 303 | <li>layout_q为TND时,q的shape为(q_t, q_n, q_d)</li> | 331 | <li>layout_q为TND时,q的shape为(q_t, q_n, q_d)</li> |
| 304 | </ul> | 332 | </ul> |
| @@ -309,7 +337,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 309 | <td rowspan="4"> | 337 | <td rowspan="4"> |
| 310 | <ul> | 338 | <ul> |
| 311 | <li>q、attention_out的dtype、shape需相同</li> | 339 | <li>q、attention_out的dtype、shape需相同</li> |
| 312 | - <li>若cmp_kv传入,ori_kv与cmp_kv的dtype需一致</li> | 340 | + <li>quant_mode=1/2时,若cmp_kv传入,ori_kv与cmp_kv的dtype需一致;quant_mode=3时,q、ori_kv、attention_out的dtype需一致,cmp_kv为uint8</li> |
| 313 | <li>layout_kv不为PA_BBND时,layout_q和layout_kv需保持一致</li> | 341 | <li>layout_kv不为PA_BBND时,layout_q和layout_kv需保持一致</li> |
| 314 | <li>layout_kv为PA_BBND时,layout_q可为BSND或TND</li> | 342 | <li>layout_kv为PA_BBND时,layout_q可为BSND或TND</li> |
| 315 | </ul> | 343 | </ul> |
| @@ -321,17 +349,16 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 321 | <li>q_s > 0</li> | 349 | <li>q_s > 0</li> |
| 322 | <li>0 < q_n <= 128</li> | 350 | <li>0 < q_n <= 128</li> |
| 323 | <li>q_d = 512</li> | 351 | <li>q_d = 512</li> |
| 324 | - <li>q_t > 0</li> | 352 | + <li>quant_mode=1/2时q_t > 0,quant_mode=3时q_t >= 0</li> |
| 325 | <li>ori_kv_s > 0</li> | 353 | <li>ori_kv_s > 0</li> |
| 326 | <li>cmp_kv_s > 0</li> | 354 | <li>cmp_kv_s > 0</li> |
| 327 | <li>kv_n = 1</li> | 355 | <li>kv_n = 1</li> |
| 328 | - <li>quant_mode=1时kv_d=608,quant_mode=2时kv_d=584</li> | 356 | + <li>quant_mode=1时kv_d=608,quant_mode=2时kv_d=584;quant_mode=3时ori_kv的kv_d=512、cmp_kv的kv_d=258</li> |
| 329 | <li>ori_kv_t > 0</li> | 357 | <li>ori_kv_t > 0</li> |
| 330 | <li>cmp_kv_t > 0</li> | 358 | <li>cmp_kv_t > 0</li> |
| 331 | <li>ori_kv_block_nums > 0</li> | 359 | <li>ori_kv_block_nums > 0</li> |
| 332 | <li>cmp_kv_block_nums > 0</li> | 360 | <li>cmp_kv_block_nums > 0</li> |
| 333 | - <li>1 <= ori_kv_block_size <= 1024</li> | 361 | + <li>1 <= ori_kv_block_size、cmp_kv_block_size <= 1024;quant_mode=3时还要求block_size为16的倍数</li> |
| 334 | - <li>1 <= cmp_kv_block_size <= 1024</li> | ||
| 335 | </ul> | 362 | </ul> |
| 336 | </td> | 363 | </td> |
| 337 | </tr> | 364 | </tr> |
| @@ -339,7 +366,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 339 | <td>ori_kv</td> | 366 | <td>ori_kv</td> |
| 340 | <td> | 367 | <td> |
| 341 | <ul> | 368 | <ul> |
| 342 | - <li>dtype支持fp8_e4m3</li> | 369 | + <li>dtype支持fp8_e4m3、float16、bfloat16;quant_mode=3时支持float16、bfloat16且与q一致</li> |
| 343 | <li>layout_kv为BSND时,ori_kv的shape为(b, ori_kv_s, kv_n, kv_d)</li> | 370 | <li>layout_kv为BSND时,ori_kv的shape为(b, ori_kv_s, kv_n, kv_d)</li> |
| 344 | <li>layout_kv为TND时,ori_kv的shape为(ori_kv_t, kv_n, kv_d)</li> | 371 | <li>layout_kv为TND时,ori_kv的shape为(ori_kv_t, kv_n, kv_d)</li> |
| 345 | <li>layout_kv为PA_BBND时,ori_kv的shape为(ori_kv_block_nums, ori_kv_block_size, kv_n, kv_d)</li> | 372 | <li>layout_kv为PA_BBND时,ori_kv的shape为(ori_kv_block_nums, ori_kv_block_size, kv_n, kv_d)</li> |
| @@ -353,7 +380,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 353 | <td>attention_out</td> | 380 | <td>attention_out</td> |
| 354 | <td> | 381 | <td> |
| 355 | <ul> | 382 | <ul> |
| 356 | - <li>dtype支持bfloat16</li> | 383 | + <li>dtype支持float16、bfloat16;quant_mode=3时需与q一致</li> |
| 357 | <li>layout_q为BSND时,attention_out的shape为(b, q_s, q_n, q_d)</li> | 384 | <li>layout_q为BSND时,attention_out的shape为(b, q_s, q_n, q_d)</li> |
| 358 | <li>layout_q为TND时,attention_out的shape为(q_t, q_n, q_d)</li> | 385 | <li>layout_q为TND时,attention_out的shape为(q_t, q_n, q_d)</li> |
| 359 | </ul> | 386 | </ul> |
| @@ -366,7 +393,7 @@ cann_ops_transformer.mixed_quant_sparse_flash_mla( | |||
| 366 | <td>cmp_kv</td> | 393 | <td>cmp_kv</td> |
| 367 | <td> | 394 | <td> |
| 368 | <ul> | 395 | <ul> |
| 369 | - <li>dtype支持fp8_e4m3</li> | 396 | + <li>dtype支持fp8_e4m3、uint8;quant_mode=3时固定为uint8</li> |
| 370 | <li>layout_kv为BSND时,cmp_kv的shape为(b, cmp_kv_s, kv_n, kv_d)</li> | 397 | <li>layout_kv为BSND时,cmp_kv的shape为(b, cmp_kv_s, kv_n, kv_d)</li> |
| 371 | <li>layout_kv为TND时,cmp_kv的shape为(cmp_kv_t, kv_n, kv_d)</li> | 398 | <li>layout_kv为TND时,cmp_kv的shape为(cmp_kv_t, kv_n, kv_d)</li> |
| 372 | <li>layout_kv为PA_BBND时,cmp_kv的shape为(cmp_kv_block_nums, cmp_kv_block_size, kv_n, kv_d)</li> | 399 | <li>layout_kv为PA_BBND时,cmp_kv的shape为(cmp_kv_block_nums, cmp_kv_block_size, kv_n, kv_d)</li> |
| @@ -765,6 +792,7 @@ metadata校验 | |||
| 765 | <li>dtype支持int32</li> | 792 | <li>dtype支持int32</li> |
| 766 | <li>shape为(q_t, kv_n, cmp_kv_k)或(b, q_s, kv_n, cmp_kv_k)</li> | 793 | <li>shape为(q_t, kv_n, cmp_kv_k)或(b, q_s, kv_n, cmp_kv_k)</li> |
| 767 | <li>无效位置填-1,其余为非负整数</li> | 794 | <li>无效位置填-1,其余为非负整数</li> |
| 795 | + <li>quant_mode=3时仅支持(q_t, 1, 512)或(q_t, 1, 1024)</li> | ||
| 768 | </ul> | 796 | </ul> |
| 769 | </td> | 797 | </td> |
| 770 | <td> | 798 | <td> |
| @@ -55,8 +55,8 @@ aclnnStatus aclnnMixedQuantSparseFlashMlaGetWorkspaceSize( | |||
| 55 | { | 55 | { |
| 56 | OP_LOGD("start aclnnMixedQuantSparseFlashMlaGetWorkspaceSize"); | 56 | OP_LOGD("start aclnnMixedQuantSparseFlashMlaGetWorkspaceSize"); |
| 57 | 57 | ||
| 58 | - MixedQuantSparseFlashMlaKvTensorPreProcess(oriKvOptional, "ori_kv"); | 58 | + MixedQuantSparseFlashMlaKvTensorPreProcess(oriKvOptional, "ori_kv", quantMode); |
| 59 | - MixedQuantSparseFlashMlaKvTensorPreProcess(cmpKvOptional, "cmp_kv"); | 59 | + MixedQuantSparseFlashMlaKvTensorPreProcess(cmpKvOptional, "cmp_kv", quantMode); |
| 60 | MixedQuantSparseFlashMlaProcessSinks(sinksOptional); | 60 | MixedQuantSparseFlashMlaProcessSinks(sinksOptional); |
| 61 | 61 | ||
| 62 | aclnnStatus ret = CheckTensorContiguous(oriKvOptional, cmpKvOptional); | 62 | aclnnStatus ret = CheckTensorContiguous(oriKvOptional, cmpKvOptional); |
| @@ -26,9 +26,9 @@ extern "C" { | |||
| 26 | * @brief First phase of aclnnMixedQuantSparseFlashMla: calculate workspace size. | 26 | * @brief First phase of aclnnMixedQuantSparseFlashMla: calculate workspace size. |
| 27 | * @domain aclnn_ops_train_infer | 27 | * @domain aclnn_ops_train_infer |
| 28 | * | 28 | * |
| 29 | - * @param q [IN] query tensor, BF16. | 29 | + * @param q [IN] query tensor. BF16 for mode 1/2; FP16 or BF16 for mode 3. |
| 30 | - * @param oriKvOptional [IN] optional original KV tensor, FLOAT8_E4M3FN. | 30 | + * @param oriKvOptional [IN] original KV. FLOAT8_E4M3FN for mode 1/2; same dtype as q for mode 3. |
| 31 | - * @param cmpKvOptional [IN] optional compressed KV tensor, FLOAT8_E4M3FN. | 31 | + * @param cmpKvOptional [IN] compressed KV. FLOAT8_E4M3FN for mode 1/2; UINT8 TQ4 for mode 3. |
| 32 | * @param oriSparseIndicesOptional [IN] optional original KV sparse indices, INT32. | 32 | * @param oriSparseIndicesOptional [IN] optional original KV sparse indices, INT32. |
| 33 | * @param cmpSparseIndicesOptional [IN] optional compressed KV sparse indices, INT32. | 33 | * @param cmpSparseIndicesOptional [IN] optional compressed KV sparse indices, INT32. |
| 34 | * @param oriBlockTableOptional [IN] optional original KV block table, INT32. | 34 | * @param oriBlockTableOptional [IN] optional original KV block table, INT32. |
| @@ -44,7 +44,7 @@ extern "C" { | |||
| 44 | * @param cmpTopkLengthOptional [IN] optional compressed KV top-k lengths, INT32. | 44 | * @param cmpTopkLengthOptional [IN] optional compressed KV top-k lengths, INT32. |
| 45 | * @param sinksOptional [IN] optional attention sink weights, FLOAT32. | 45 | * @param sinksOptional [IN] optional attention sink weights, FLOAT32. |
| 46 | * @param metadataOptional [IN] optional pre-computed tiling metadata, INT32. | 46 | * @param metadataOptional [IN] optional pre-computed tiling metadata, INT32. |
| 47 | - * @param quantMode [IN] ATTR. Quantization mode. | 47 | + * @param quantMode [IN] ATTR. 1/2 on arch35, 3 (TurboQuant TQ4) on arch22. |
| 48 | * @param ropeHeadDim [IN] ATTR. RoPE head dimension. | 48 | * @param ropeHeadDim [IN] ATTR. RoPE head dimension. |
| 49 | * @param softmaxScale [IN] ATTR. Softmax scaling factor. | 49 | * @param softmaxScale [IN] ATTR. Softmax scaling factor. |
| 50 | * @param cmpRatio [IN] ATTR. Compressed KV ratio. | 50 | * @param cmpRatio [IN] ATTR. Compressed KV ratio. |
| @@ -56,7 +56,7 @@ extern "C" { | |||
| 56 | * @param layoutKvOptional [IN] ATTR. KV layout. | 56 | * @param layoutKvOptional [IN] ATTR. KV layout. |
| 57 | * @param topkValueMode [IN] ATTR. Top-k value mode. | 57 | * @param topkValueMode [IN] ATTR. Top-k value mode. |
| 58 | * @param returnSoftmaxLse [IN] ATTR. Whether to output softmax LSE. | 58 | * @param returnSoftmaxLse [IN] ATTR. Whether to output softmax LSE. |
| 59 | - * @param attnOut [OUT] Required attention output, BF16. | 59 | + * @param attnOut [OUT] Required attention output, same dtype and shape as q. |
| 60 | * @param softmaxLseOptional [OUT] Optional output. Softmax log-sum-exp, FLOAT32. | 60 | * @param softmaxLseOptional [OUT] Optional output. Softmax log-sum-exp, FLOAT32. |
| 61 | * Valid when returnSoftmaxLse=True. | 61 | * Valid when returnSoftmaxLse=True. |
| 62 | * @param workspaceSize [OUT] Workspace size in bytes. | 62 | * @param workspaceSize [OUT] Workspace size in bytes. |
| @@ -20,9 +20,11 @@ extern "C" { | |||
| 20 | 20 | ||
| 21 | namespace { | 21 | namespace { |
| 22 | 22 | ||
| 23 | -void MixedQuantSparseFlashMlaKvTensorPreProcess(const aclTensor *&kvTensor, const char *tensorName) | 23 | +constexpr int64_t TURBO_QUANT_MODE = 3; |
| 24 | + | ||
| 25 | +void MixedQuantSparseFlashMlaKvTensorPreProcess(const aclTensor *&kvTensor, const char *tensorName, int64_t quantMode) | ||
| 24 | { | 26 | { |
| 25 | - if (kvTensor != nullptr && kvTensor->GetDataType() == DataType::DT_UINT8) { | 27 | + if (quantMode != TURBO_QUANT_MODE && kvTensor != nullptr && kvTensor->GetDataType() == DataType::DT_UINT8) { |
| 26 | auto tensor = const_cast<aclTensor *>(kvTensor); | 28 | auto tensor = const_cast<aclTensor *>(kvTensor); |
| 27 | tensor->SetDataType(DataType::DT_FLOAT8_E4M3FN); | 29 | tensor->SetDataType(DataType::DT_FLOAT8_E4M3FN); |
| 28 | OP_LOGD("%s dtype is converted from uint8 to float8_e4m3fn.", tensorName); | 30 | OP_LOGD("%s dtype is converted from uint8 to float8_e4m3fn.", tensorName); |
| @@ -34,7 +34,7 @@ extern aclnnStatus aclnnInnerMixedQuantSparseFlashMlaGetWorkspaceSize( | |||
| 34 | extern aclnnStatus aclnnInnerMixedQuantSparseFlashMla(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, | 34 | extern aclnnStatus aclnnInnerMixedQuantSparseFlashMla(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, |
| 35 | const aclrtStream stream); | 35 | const aclrtStream stream); |
| 36 | 36 | ||
| 37 | -void MixedQuantSparseFlashMlaKvTensorPreProcess(const aclTensor *&kvTensor, const char *tensorName); | 37 | +void MixedQuantSparseFlashMlaKvTensorPreProcess(const aclTensor *&kvTensor, const char *tensorName, int64_t quantMode); |
| 38 | 38 | ||
| 39 | void MixedQuantSparseFlashMlaProcessSinks(const aclTensor *&sinksOptional); | 39 | void MixedQuantSparseFlashMlaProcessSinks(const aclTensor *&sinksOptional); |
| 40 | 40 | ||
| @@ -43,5 +43,6 @@ add_tiling_modules() | |||
| 43 | add_sparse_mla_common_checker_sources(${OPHOST_NAME}_tiling_obj) | 43 | add_sparse_mla_common_checker_sources(${OPHOST_NAME}_tiling_obj) |
| 44 | target_sources(${OPHOST_NAME}_tiling_obj PRIVATE | 44 | target_sources(${OPHOST_NAME}_tiling_obj PRIVATE |
| 45 | ${MIXED_QUANT_SPARSE_MLA_CHECKER_SRC_FILES} | 45 | ${MIXED_QUANT_SPARSE_MLA_CHECKER_SRC_FILES} |
| 46 | - mixed_quant_sparse_flash_mla_tiling.cpp | 46 | + ${CMAKE_CURRENT_SOURCE_DIR}/arch22/mixed_quant_sparse_flash_mla_tiling.cpp |
| 47 | + ${CMAKE_CURRENT_SOURCE_DIR}/arch35/mixed_quant_sparse_flash_mla_tiling.cpp | ||
| 47 | ) | 48 | ) |
| @@ -0,0 +1,98 @@ | |||
| 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 "../mixed_quant_sparse_flash_mla_tiling.h" | ||
| 12 | +#include "../../op_kernel/arch22/mixed_quant_sparse_flash_mla_tiling_data_arch22.h" | ||
| 13 | +#include "../../op_kernel/arch22/mixed_quant_sparse_flash_mla_template_tiling_key_arch22.h" | ||
| 14 | +#include <algorithm> | ||
| 15 | + | ||
| 16 | +using namespace ge; | ||
| 17 | +using namespace AscendC; | ||
| 18 | +namespace optiling { | ||
| 19 | + | ||
| 20 | +ge::graphStatus MixedQuantSparseFlashMlaTiling::DoTurboQuantTiling(MQSMLATilingInfo *tilingInfo) | ||
| 21 | +{ | ||
| 22 | + constexpr uint32_t S2_BASE_SIZE = 512; | ||
| 23 | + constexpr uint32_t BYTE_BLOCK = 32; | ||
| 24 | + constexpr uint32_t MM1_RES_ELEM_SIZE = 4; | ||
| 25 | + constexpr uint32_t VEC1_RES_ELEM_SIZE = 2; | ||
| 26 | + constexpr uint32_t MM2_RES_ELEM_SIZE = 4; | ||
| 27 | + constexpr uint32_t VEC2_RES_ELEM_SIZE = 4; | ||
| 28 | + constexpr uint32_t PRELOAD_NUM = 2; | ||
| 29 | + constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; | ||
| 30 | + constexpr uint32_t MERGE_CACHE_ELEM_SIZE = 2; | ||
| 31 | + auto align = [](uint32_t value, uint32_t alignment) { return (value + alignment - 1) / alignment * alignment; }; | ||
| 32 | + | ||
| 33 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); | ||
| 34 | + const uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); | ||
| 35 | + const uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); | ||
| 36 | + context_->SetBlockDim(ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum)); | ||
| 37 | + | ||
| 38 | + const uint32_t mBaseSize = tilingInfo->gSize; | ||
| 39 | + const uint32_t s2BaseSizeAlign = align(S2_BASE_SIZE, BYTE_BLOCK); | ||
| 40 | + // The kernel splits the full TND M dimension into tiles no larger than mBaseSize. | ||
| 41 | + const uint32_t cubeMSize = mBaseSize; | ||
| 42 | + const uint32_t mmResUbSize = s2BaseSizeAlign * align(cubeMSize, 16U); | ||
| 43 | + const uint32_t bmm2ResUbSize = align(tilingInfo->qkHeadDim, BYTE_BLOCK) * align(cubeMSize, 16U); | ||
| 44 | + | ||
| 45 | + size_t workspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); | ||
| 46 | + workspaceSize += static_cast<size_t>(PRELOAD_NUM) * mmResUbSize * (MM1_RES_ELEM_SIZE + VEC1_RES_ELEM_SIZE) * aicNum; | ||
| 47 | + workspaceSize += | ||
| 48 | + static_cast<size_t>(PRELOAD_NUM) * bmm2ResUbSize * (MM2_RES_ELEM_SIZE + VEC2_RES_ELEM_SIZE) * aicNum; | ||
| 49 | + workspaceSize += static_cast<size_t>(MERGE_CACHE_GM_BUF_NUM) * S2_BASE_SIZE * tilingInfo->qkHeadDim * | ||
| 50 | + MERGE_CACHE_ELEM_SIZE * aicNum; | ||
| 51 | + workspaceSize += static_cast<size_t>(MERGE_CACHE_GM_BUF_NUM) * S2_BASE_SIZE * sizeof(uint16_t) * aicNum; | ||
| 52 | + size_t *workspaces = context_->GetWorkspaceSizes(1); | ||
| 53 | + OP_CHECK_IF(workspaces == nullptr, OP_LOGE(tilingInfo->opName, "workspace sizes is nullptr"), | ||
| 54 | + return ge::GRAPH_FAILED); | ||
| 55 | + workspaces[0] = workspaceSize; | ||
| 56 | + | ||
| 57 | + auto *tqTilingData = context_->GetTilingData<MixedQuantSparseFlashMlaTqTilingData>(); | ||
| 58 | + OP_CHECK_IF(tqTilingData == nullptr, OP_LOGE(tilingInfo->opName, "tiling data is nullptr"), | ||
| 59 | + return ge::GRAPH_FAILED); | ||
| 60 | + tqTilingData->tqBaseParams.batchSize = tilingInfo->bSize; | ||
| 61 | + tqTilingData->tqBaseParams.qSeqSize = tilingInfo->s1Size; | ||
| 62 | + tqTilingData->tqBaseParams.kvSeqSize = tilingInfo->s2Size; | ||
| 63 | + tqTilingData->tqBaseParams.paBlockSize = tilingInfo->oriBlockSize; | ||
| 64 | + tqTilingData->tqBaseParams.oriBlockSize = tilingInfo->oriBlockSize; | ||
| 65 | + tqTilingData->tqBaseParams.cmpBlockSize = tilingInfo->cmpBlockSize; | ||
| 66 | + tqTilingData->tqBaseParams.oriMaxBlockNumPerBatch = tilingInfo->oriMaxBlockNumPerBatch; | ||
| 67 | + tqTilingData->tqBaseParams.nNumOfQInOneGroup = tilingInfo->gSize; | ||
| 68 | + tqTilingData->tqBaseParams.actualLenDimsQ = tilingInfo->actualLenDimsQ; | ||
| 69 | + tqTilingData->tqBaseParams.actualLenDimsKV = tilingInfo->actualLenDimsKV; | ||
| 70 | + tqTilingData->tqBaseParams.softmaxScale = tilingInfo->softmaxScale; | ||
| 71 | + tqTilingData->tqBaseParams.outputLayout = static_cast<uint32_t>(tilingInfo->outLayout); | ||
| 72 | + tqTilingData->tqBaseParams.oriMaskMode = tilingInfo->oriMaskMode; | ||
| 73 | + tqTilingData->tqBaseParams.oriKvStride0 = tilingInfo->oriKvStride; | ||
| 74 | + tqTilingData->tqBaseParams.oriWinLeft = tilingInfo->oriWinLeft; | ||
| 75 | + tqTilingData->tqBaseParams.oriWinRight = tilingInfo->oriWinRight; | ||
| 76 | + tqTilingData->tqBaseParams.sparseBlockSize = tilingInfo->sparseBlockSize; | ||
| 77 | + tqTilingData->tqBaseParams.usedCoreNum = aicNum; | ||
| 78 | + tqTilingData->tqBaseParams.mmResUbSize = mmResUbSize; | ||
| 79 | + tqTilingData->tqBaseParams.bmm2ResUbSize = bmm2ResUbSize; | ||
| 80 | + tqTilingData->tqBaseParams.mBaseSize = mBaseSize; | ||
| 81 | + tqTilingData->tqBaseParams.s2BaseSize = S2_BASE_SIZE; | ||
| 82 | + tqTilingData->tqBaseParams.returnSoftmaxLse = tilingInfo->returnSoftmaxLse; | ||
| 83 | + tqTilingData->tqBaseParams.kvQuantMode = static_cast<uint32_t>(tilingInfo->quantMode); | ||
| 84 | + tqTilingData->tqCmpParams.cmpMaxBlockNumPerBatch = tilingInfo->cmpMaxBlockNumPerBatch; | ||
| 85 | + tqTilingData->tqCmpParams.sparseBlockCount = tilingInfo->cmpSparseBlockCount; | ||
| 86 | + tqTilingData->tqCmpParams.cmpRatio = tilingInfo->cmpRatio; | ||
| 87 | + tqTilingData->tqCmpParams.cmpMaskMode = tilingInfo->cmpMaskMode; | ||
| 88 | + tqTilingData->tqCmpParams.cmpKvStride0 = tilingInfo->cmpKvStride; | ||
| 89 | + | ||
| 90 | + const uint64_t tilingKey = GET_TPL_TILING_KEY( | ||
| 91 | + 0U, static_cast<uint32_t>(tilingInfo->qLayout), static_cast<uint32_t>(tilingInfo->kvLayout), CSA_TEMPLATE, 0U, | ||
| 92 | + static_cast<uint32_t>(tilingInfo->quantMode), DTYPE_FP8_E4M3FN, 0U, 0U, 0U); | ||
| 93 | + context_->SetTilingKey(tilingKey); | ||
| 94 | + context_->SetScheduleMode(1); | ||
| 95 | + return ge::GRAPH_SUCCESS; | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +} // namespace optiling | ||
Aattention/mixed_quant_sparse_flash_mla/op_host/arch35/mixed_quant_sparse_flash_mla_tiling.cpp+179-0
| @@ -0,0 +1,179 @@ | |||
| 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 "../mixed_quant_sparse_flash_mla_tiling.h" | ||
| 12 | +#include "../../op_kernel/arch35/mixed_quant_sparse_flash_mla_template_tiling_key_arch35.h" | ||
| 13 | +#include <algorithm> | ||
| 14 | + | ||
| 15 | +using namespace ge; | ||
| 16 | +using namespace AscendC; | ||
| 17 | +namespace optiling { | ||
| 18 | + | ||
| 19 | +ge::graphStatus MixedQuantSparseFlashMlaTiling::DoCsaTiling(MQSMLATilingInfo *tilingInfo) | ||
| 20 | +{ | ||
| 21 | + if (tilingInfo->opParamInfo.cmpKv.tensor == nullptr) { | ||
| 22 | + OP_CHECK_IF( | ||
| 23 | + tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr, | ||
| 24 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("MixedQuantSparseFlashMla", "cmp_sparse_indices", | ||
| 25 | + "Cmp_sparse_indices must be empty when cmpKv is not provided"), | ||
| 26 | + return ge::GRAPH_FAILED); | ||
| 27 | + if (tilingInfo->opParamInfo.oriSparseIndices.tensor == nullptr) { | ||
| 28 | + perfMode_ = QSMLATemplateMode::SWA_TEMPLATE_MODE; | ||
| 29 | + } else { | ||
| 30 | + perfMode_ = QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE; | ||
| 31 | + } | ||
| 32 | + } else if (tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr) { | ||
| 33 | + if (tilingInfo->opParamInfo.oriSparseIndices.tensor == nullptr) { | ||
| 34 | + perfMode_ = QSMLATemplateMode::CSA_TEMPLATE_MODE; | ||
| 35 | + } else { | ||
| 36 | + perfMode_ = QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE; | ||
| 37 | + } | ||
| 38 | + } else { | ||
| 39 | + perfMode_ = QSMLATemplateMode::HCA_TEMPLATE_MODE; | ||
| 40 | + } | ||
| 41 | + // -------------set blockdim----------------- | ||
| 42 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); | ||
| 43 | + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); | ||
| 44 | + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); | ||
| 45 | + uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); | ||
| 46 | + context_->SetBlockDim(blockDim); | ||
| 47 | + OP_LOGI(tilingInfo->opName, "QSMLA block dim: %u aiv Num: %u aic Num: %u.", blockDim, aivNum, aicNum); | ||
| 48 | + | ||
| 49 | + // -------------set workspacesize----------------- | ||
| 50 | + constexpr uint32_t TRIPLE_BUFFER_NUM = 3; | ||
| 51 | + constexpr uint32_t S2_BASE_SIZE = 128; // S2轴基本块大小 | ||
| 52 | + constexpr uint32_t D_SIZE = 512; | ||
| 53 | + constexpr uint32_t VEC_RES_ELEM_SIZE = 2; // 2: fp16/bf16字节数 | ||
| 54 | + constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数 | ||
| 55 | + constexpr uint32_t UB_SIZE = 184 * 1024; | ||
| 56 | + constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128; | ||
| 57 | + constexpr int64_t QUANT_CONTIGUOUS_MODE = 1; | ||
| 58 | + constexpr uint32_t MAX_S2_SPLIT_NUM = 2; // 每核最多S2切分次数 | ||
| 59 | + constexpr uint32_t FLOAT_ELEM_SIZE = 4; // sizeof(float) | ||
| 60 | + constexpr uint32_t FD_BLOCK_ELEM = 8; // FD广播份数 | ||
| 61 | + constexpr uint32_t FD_MAX_SUM_REGION_NUM = 2; // max和sum两个区域 | ||
| 62 | + constexpr uint32_t BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM = 33; | ||
| 63 | + uint32_t alignedOriSparseBlockCount = (tilingInfo->oriSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / | ||
| 64 | + SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; | ||
| 65 | + uint32_t alignedCmpSparseBlockCount = (tilingInfo->cmpSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / | ||
| 66 | + SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; | ||
| 67 | + uint64_t oriUbSize = static_cast<uint64_t>(tilingInfo->oriMaxBlockNumPerBatch) * sizeof(int32_t) + | ||
| 68 | + static_cast<uint64_t>(alignedOriSparseBlockCount) * (sizeof(int32_t) + sizeof(int64_t)); | ||
| 69 | + uint64_t cmpUbSize = static_cast<uint64_t>(tilingInfo->cmpMaxBlockNumPerBatch) * sizeof(int32_t) + | ||
| 70 | + static_cast<uint64_t>(alignedCmpSparseBlockCount) * (sizeof(int32_t) + sizeof(int64_t)); | ||
| 71 | + bool oriBlockSizePowerOfTwo = | ||
| 72 | + tilingInfo->oriBlockSize > 0 && (tilingInfo->oriBlockSize & (tilingInfo->oriBlockSize - 1)) == 0; | ||
| 73 | + bool cmpBlockSizePowerOfTwo = | ||
| 74 | + tilingInfo->cmpBlockSize > 0 && (tilingInfo->cmpBlockSize & (tilingInfo->cmpBlockSize - 1)) == 0; | ||
| 75 | + bool blockSizeSupported = (perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE && cmpBlockSizePowerOfTwo) || | ||
| 76 | + (perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE && oriBlockSizePowerOfTwo) || | ||
| 77 | + (perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE && oriBlockSizePowerOfTwo && | ||
| 78 | + cmpBlockSizePowerOfTwo); | ||
| 79 | + uint64_t vectorizeUbSize = | ||
| 80 | + (perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE) ? | ||
| 81 | + cmpUbSize : | ||
| 82 | + ((perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE) ? oriUbSize : std::max(oriUbSize, cmpUbSize)); | ||
| 83 | + uint32_t vectorizeFlag = static_cast<uint32_t>((perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE || | ||
| 84 | + perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || | ||
| 85 | + perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) && | ||
| 86 | + tilingInfo->quantMode == QUANT_CONTIGUOUS_MODE && | ||
| 87 | + tilingInfo->kvLayout == MQSMLALayout::PA_BBND && | ||
| 88 | + blockSizeSupported && vectorizeUbSize <= UB_SIZE); | ||
| 89 | + | ||
| 90 | + size_t workspaceSize = static_cast<size_t>(ascendcPlatform.GetLibApiWorkSpaceSize()); | ||
| 91 | + bool isSplitG = tilingInfo->gSize > 64; // gSize超过64时采用Split-G | ||
| 92 | + workspaceSize += static_cast<size_t>(S2_BASE_SIZE) * D_SIZE * VEC_RES_ELEM_SIZE * TRIPLE_BUFFER_NUM * | ||
| 93 | + (isSplitG ? (aicNum >> 1) : aicNum); | ||
| 94 | + if (vectorizeFlag != 0) { | ||
| 95 | + uint64_t totalBS1 = (tilingInfo->qLayout == MQSMLALayout::TND) ? | ||
| 96 | + tilingInfo->s1Size : | ||
| 97 | + static_cast<uint64_t>(tilingInfo->bSize) * tilingInfo->s1Size; | ||
| 98 | + if (perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || | ||
| 99 | + perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { | ||
| 100 | + workspaceSize += totalBS1 * alignedOriSparseBlockCount * sizeof(int64_t); | ||
| 101 | + } | ||
| 102 | + if (perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE || | ||
| 103 | + perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { | ||
| 104 | + workspaceSize += totalBS1 * alignedCmpSparseBlockCount * sizeof(int64_t); | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | + uint32_t fdStagingMSize = tilingInfo->gSize; | ||
| 108 | + uint32_t fdStagingSlotNum = isSplitG ? (aicNum >> 1) : aicNum; | ||
| 109 | + if (tilingInfo->batchConsistency) { | ||
| 110 | + size_t combineElemSize = static_cast<size_t>(fdStagingMSize) * D_SIZE + | ||
| 111 | + static_cast<size_t>(FD_MAX_SUM_REGION_NUM) * fdStagingMSize * FD_BLOCK_ELEM; | ||
| 112 | + workspaceSize += 2ULL * fdStagingSlotNum * combineElemSize * FLOAT_ELEM_SIZE; | ||
| 113 | + workspaceSize += | ||
| 114 | + static_cast<size_t>(aicNum) * BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM * combineElemSize * FLOAT_ELEM_SIZE; | ||
| 115 | + } else { | ||
| 116 | + // 末尾的2对应每个split分别暂存max和sum。 | ||
| 117 | + size_t s2SplitStagingPerSlot = | ||
| 118 | + static_cast<size_t>(fdStagingMSize) * D_SIZE * FLOAT_ELEM_SIZE * MAX_S2_SPLIT_NUM + | ||
| 119 | + static_cast<size_t>(fdStagingMSize) * FD_BLOCK_ELEM * FLOAT_ELEM_SIZE * MAX_S2_SPLIT_NUM * | ||
| 120 | + FD_MAX_SUM_REGION_NUM; | ||
| 121 | + workspaceSize += s2SplitStagingPerSlot * fdStagingSlotNum; | ||
| 122 | + } | ||
| 123 | + size_t *workSpaces = context_->GetWorkspaceSizes(1); | ||
| 124 | + workSpaces[0] = workspaceSize; | ||
| 125 | + | ||
| 126 | + // -------------set tilingdata----------------- | ||
| 127 | + tilingData_.baseParams.set_batchSize(tilingInfo->bSize); | ||
| 128 | + tilingData_.baseParams.set_kvSeqSize(tilingInfo->s2Size); | ||
| 129 | + tilingData_.baseParams.set_cmpKvSeqSize(tilingInfo->cmpS2Size); | ||
| 130 | + tilingData_.baseParams.set_qSeqSize(tilingInfo->s1Size); | ||
| 131 | + tilingData_.baseParams.set_oriSparseBlockCount(tilingInfo->oriSparseBlockCount); | ||
| 132 | + tilingData_.baseParams.set_cmpSparseBlockCount(tilingInfo->cmpSparseBlockCount); | ||
| 133 | + tilingData_.baseParams.set_nNumOfQInOneGroup(tilingInfo->gSize); | ||
| 134 | + tilingData_.baseParams.set_paOriBlockSize(tilingInfo->oriBlockSize); | ||
| 135 | + tilingData_.baseParams.set_paCmpBlockSize(tilingInfo->cmpBlockSize); | ||
| 136 | + tilingData_.baseParams.set_oriMaxBlockNumPerBatch(tilingInfo->oriMaxBlockNumPerBatch); | ||
| 137 | + tilingData_.baseParams.set_cmpMaxBlockNumPerBatch(tilingInfo->cmpMaxBlockNumPerBatch); | ||
| 138 | + | ||
| 139 | + tilingData_.baseParams.set_tileSize(tilingInfo->tileSize); | ||
| 140 | + tilingData_.baseParams.set_ropeHeadDim(tilingInfo->ropeHeadDim); | ||
| 141 | + tilingData_.baseParams.set_softmaxScale(tilingInfo->softmaxScale); | ||
| 142 | + tilingData_.baseParams.set_oriKvStride(tilingInfo->oriKvStride); | ||
| 143 | + tilingData_.baseParams.set_cmpKvStride(tilingInfo->cmpKvStride); | ||
| 144 | + tilingData_.baseParams.set_cmpRatio(tilingInfo->cmpRatio); | ||
| 145 | + tilingData_.baseParams.set_oriMaskMode(tilingInfo->oriMaskMode); | ||
| 146 | + tilingData_.baseParams.set_cmpMaskMode(tilingInfo->cmpMaskMode); | ||
| 147 | + tilingData_.baseParams.set_oriWinLeft(tilingInfo->oriWinLeft); | ||
| 148 | + tilingData_.baseParams.set_oriWinRight(tilingInfo->oriWinRight); | ||
| 149 | + tilingData_.baseParams.set_sparseBlockSize(tilingInfo->sparseBlockSize); | ||
| 150 | + tilingData_.baseParams.set_dSize(tilingInfo->dSize); | ||
| 151 | + tilingData_.baseParams.set_dSizeVInput(tilingInfo->dSizeVInput); | ||
| 152 | + tilingData_.baseParams.set_returnSoftmaxLse(tilingInfo->returnSoftmaxLse); | ||
| 153 | + | ||
| 154 | + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); | ||
| 155 | + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); | ||
| 156 | + | ||
| 157 | + // -------------set tilingkey----------------- | ||
| 158 | + // DT_Q, DT_KV, DT_OUT, PAGE_ATTENTION, FLASH_DECODE, LAYOUT_T, KV_LAYOUT_T | ||
| 159 | + uint32_t qType = static_cast<uint32_t>(tilingInfo->qType); | ||
| 160 | + uint32_t oriKvType = static_cast<uint32_t>(tilingInfo->oriKvType); | ||
| 161 | + uint32_t outputType = static_cast<uint32_t>(tilingInfo->outputType); | ||
| 162 | + uint32_t qLayout = static_cast<uint32_t>(tilingInfo->qLayout); | ||
| 163 | + uint32_t inputKvLayout = static_cast<uint32_t>(tilingInfo->kvLayout); | ||
| 164 | + // maskmode为4+3,无topk len输入且不输出lse时, 走HIGH_PERF高性能模板 | ||
| 165 | + bool highPerf = (tilingInfo->oriMaskMode == 4 && tilingInfo->cmpMaskMode == 3) && | ||
| 166 | + tilingInfo->opParamInfo.oriTopkLength.tensor == nullptr && | ||
| 167 | + tilingInfo->opParamInfo.cmpTopkLength.tensor == nullptr && !tilingInfo->returnSoftmaxLse; | ||
| 168 | + uint64_t tilingKey = GET_TPL_TILING_KEY( | ||
| 169 | + 0U, qLayout, inputKvLayout, static_cast<uint32_t>(perfMode_), static_cast<uint32_t>(isSplitG), | ||
| 170 | + static_cast<uint32_t>(tilingInfo->quantMode), | ||
| 171 | + ((oriKvType == ge::DT_FLOAT8_E4M3FN) ? DTYPE_FP8_E4M3FN : DTYPE_HIF8), | ||
| 172 | + static_cast<uint32_t>(tilingInfo->batchConsistency), vectorizeFlag, static_cast<uint32_t>(highPerf)); | ||
| 173 | + context_->SetTilingKey(tilingKey); | ||
| 174 | + context_->SetScheduleMode(1); | ||
| 175 | + | ||
| 176 | + return ge::GRAPH_SUCCESS; | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +} // namespace optiling | ||
Mattention/mixed_quant_sparse_flash_mla/op_host/checkers/mixed_quant_sparse_flash_mla_checker.cpp+1-0
| @@ -22,6 +22,7 @@ CheckContext BuildContext(const MQSMLATilingInfo &info) | |||
| 22 | CheckContext context; | 22 | CheckContext context; |
| 23 | sparse_mla_checker::PopulateCommonContext(context, info); | 23 | sparse_mla_checker::PopulateCommonContext(context, info); |
| 24 | context.variant = sparse_mla_checker::OperatorVariant::MIXED_QUANT; | 24 | context.variant = sparse_mla_checker::OperatorVariant::MIXED_QUANT; |
| 25 | + context.npuArch = info.npuArch; | ||
| 25 | context.qHeadDim = info.qkHeadDim; | 26 | context.qHeadDim = info.qkHeadDim; |
| 26 | context.quantMode = info.quantMode; | 27 | context.quantMode = info.quantMode; |
| 27 | context.ropeHeadDim = info.ropeHeadDim; | 28 | context.ropeHeadDim = info.ropeHeadDim; |
| @@ -13,6 +13,7 @@ | |||
| 13 | 13 | ||
| 14 | namespace optiling { | 14 | namespace optiling { |
| 15 | namespace sparse_mla_checker { | 15 | namespace sparse_mla_checker { |
| 16 | +constexpr int64_t TURBO_QUANT_MODE = 3; | ||
| 16 | namespace { | 17 | namespace { |
| 17 | const char *Op(const CheckContext &context) | 18 | const char *Op(const CheckContext &context) |
| 18 | { | 19 | { |
| @@ -22,13 +23,61 @@ const char *Op(const CheckContext &context) | |||
| 22 | 23 | ||
| 23 | ge::graphStatus MixedQuantVariantChecker::CheckSinglePara(const CheckContext &context) const | 24 | ge::graphStatus MixedQuantVariantChecker::CheckSinglePara(const CheckContext &context) const |
| 24 | { | 25 | { |
| 25 | - OP_CHECK_IF(context.quantMode != 1 && context.quantMode != 2, | 26 | + OP_CHECK_IF( |
| 26 | - OP_LOGE_FOR_INVALID_VALUE(Op(context), "quant_mode", std::to_string(context.quantMode).c_str(), | 27 | + context.quantMode != 1 && context.quantMode != 2 && context.quantMode != TURBO_QUANT_MODE, |
| 27 | - "1 or 2"), | 28 | + OP_LOGE_FOR_INVALID_VALUE(Op(context), "quant_mode", std::to_string(context.quantMode).c_str(), "1, 2 or 3"), |
| 29 | + return ge::GRAPH_FAILED); | ||
| 30 | + const bool turboQuant = context.quantMode == TURBO_QUANT_MODE; | ||
| 31 | + OP_CHECK_IF( | ||
| 32 | + (turboQuant && context.npuArch != NpuArch::DAV_2201) || (!turboQuant && context.npuArch != NpuArch::DAV_3510), | ||
| 33 | + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( | ||
| 34 | + Op(context), "quant_mode", std::to_string(context.quantMode).c_str(), | ||
| 35 | + "quant_mode 3 is supported only on arch22; quant_mode 1/2 are supported only on arch35"), | ||
| 36 | + return ge::GRAPH_FAILED); | ||
| 37 | + // The RoPE part of the TurboQuant layout has a fixed 64-dimensional head. | ||
| 38 | + OP_CHECK_IF( | ||
| 39 | + context.ropeHeadDim != 64, | ||
| 40 | + OP_LOGE_FOR_INVALID_VALUE(Op(context), "rope_head_dim", std::to_string(context.ropeHeadDim).c_str(), "64"), | ||
| 41 | + return ge::GRAPH_FAILED); | ||
| 42 | + if (!turboQuant) { | ||
| 43 | + return ge::GRAPH_SUCCESS; | ||
| 44 | + } | ||
| 45 | + OP_CHECK_IF( | ||
| 46 | + context.qLayout != Layout::TND || context.kvLayout != Layout::PA_BBND, | ||
| 47 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "layout_q/layout_kv", "TurboQuant requires TND/PA_BBND"), | ||
| 48 | + return ge::GRAPH_FAILED); | ||
| 49 | + OP_CHECK_IF(context.qNumHeads % 4 != 0, | ||
| 50 | + OP_LOGE_FOR_INVALID_VALUE(Op(context), "q head count", std::to_string(context.qNumHeads).c_str(), | ||
| 51 | + "a multiple of 4"), | ||
| 28 | return ge::GRAPH_FAILED); | 52 | return ge::GRAPH_FAILED); |
| 29 | - OP_CHECK_IF(context.ropeHeadDim != 64, | 53 | + OP_CHECK_IF(context.cmpTopk != 512 && context.cmpTopk != 1024, |
| 30 | - OP_LOGE_FOR_INVALID_VALUE(Op(context), "rope_head_dim", | 54 | + OP_LOGE_FOR_INVALID_VALUE(Op(context), "cmp_sparse_indices K", std::to_string(context.cmpTopk).c_str(), |
| 31 | - std::to_string(context.ropeHeadDim).c_str(), "64"), | 55 | + "512 or 1024"), |
| 56 | + return ge::GRAPH_FAILED); | ||
| 57 | + OP_CHECK_IF( | ||
| 58 | + context.oriMaskMode != 4 || context.cmpMaskMode != 3 || context.oriWinRight != 0, | ||
| 59 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | ||
| 60 | + Op(context), "mask attributes", "TurboQuant requires ori_mask_mode=4, cmp_mask_mode=3 and ori_win_right=0"), | ||
| 61 | + return ge::GRAPH_FAILED); | ||
| 62 | + OP_CHECK_IF( | ||
| 63 | + context.oriWinLeft < 0 || (context.cmpRatio != 4 && context.cmpRatio != 128), | ||
| 64 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "TurboQuant attributes", | ||
| 65 | + "ori_win_left must be non-negative and cmp_ratio must be 4 or 128"), | ||
| 66 | + return ge::GRAPH_FAILED); | ||
| 67 | + OP_CHECK_IF(context.oriBlockSize <= 0 || context.oriBlockSize > 1024 || context.oriBlockSize % 16 != 0 || | ||
| 68 | + context.cmpBlockSize <= 0 || context.cmpBlockSize > 1024 || context.cmpBlockSize % 16 != 0, | ||
| 69 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | ||
| 70 | + Op(context), "KV block size", "TurboQuant block sizes must be in [16, 1024] and aligned to 16"), | ||
| 71 | + return ge::GRAPH_FAILED); | ||
| 72 | + const uint64_t minOriKvStride = | ||
| 73 | + static_cast<uint64_t>(context.oriBlockSize) * static_cast<uint64_t>(context.kvNumHeads) * 512U; | ||
| 74 | + const uint64_t minCmpKvStride = | ||
| 75 | + static_cast<uint64_t>(context.cmpBlockSize) * static_cast<uint64_t>(context.kvNumHeads) * 258U; | ||
| 76 | + OP_CHECK_IF(context.oriKvStrides.empty() || context.cmpKvStrides.empty() || context.oriKvStrides[0] < 0 || | ||
| 77 | + context.cmpKvStrides[0] < 0 || static_cast<uint64_t>(context.oriKvStrides[0]) < minOriKvStride || | ||
| 78 | + static_cast<uint64_t>(context.cmpKvStrides[0]) < minCmpKvStride, | ||
| 79 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | ||
| 80 | + Op(context), "KV stride", "The first-axis stride must cover one physical TurboQuant cache block"), | ||
| 32 | return ge::GRAPH_FAILED); | 81 | return ge::GRAPH_FAILED); |
| 33 | return ge::GRAPH_SUCCESS; | 82 | return ge::GRAPH_SUCCESS; |
| 34 | } | 83 | } |
| @@ -151,6 +151,8 @@ public: | |||
| 151 | uint32_t qTSize = 0; // 仅TND时生效 | 151 | uint32_t qTSize = 0; // 仅TND时生效 |
| 152 | 152 | ||
| 153 | uint32_t maxActualseq = 0; | 153 | uint32_t maxActualseq = 0; |
| 154 | + uint32_t actualLenDimsQ = 0; | ||
| 155 | + uint32_t actualLenDimsKV = 0; | ||
| 154 | bool actualSeqLenFlag = false; | 156 | bool actualSeqLenFlag = false; |
| 155 | bool isSameSeqAllKVTensor = true; | 157 | bool isSameSeqAllKVTensor = true; |
| 156 | 158 | ||
| @@ -282,6 +284,8 @@ public: | |||
| 282 | int64_t dSizeKV_ = 0; | 284 | int64_t dSizeKV_ = 0; |
| 283 | int64_t oriKvStride_ = 0; | 285 | int64_t oriKvStride_ = 0; |
| 284 | int64_t cmpKvStride_ = 0; | 286 | int64_t cmpKvStride_ = 0; |
| 287 | + uint32_t actualLenDimsQ_ = 0; | ||
| 288 | + uint32_t actualLenDimsKV_ = 0; | ||
| 285 | std::vector<int64_t> oriKvStridesVec_; | 289 | std::vector<int64_t> oriKvStridesVec_; |
| 286 | std::vector<int64_t> cmpKvStridesVec_; | 290 | std::vector<int64_t> cmpKvStridesVec_; |
| 287 | // Layout | 291 | // Layout |
| @@ -22,18 +22,18 @@ public: | |||
| 22 | { | 22 | { |
| 23 | this->Input("q") | 23 | this->Input("q") |
| 24 | .ParamType(REQUIRED) | 24 | .ParamType(REQUIRED) |
| 25 | - .DataTypeList({ge::DT_BF16}) | 25 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) |
| 26 | - .FormatList({ge::FORMAT_ND}) | 26 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) |
| 27 | .AutoContiguous(); | 27 | .AutoContiguous(); |
| 28 | this->Input("ori_kv") | 28 | this->Input("ori_kv") |
| 29 | .ParamType(OPTIONAL) | 29 | .ParamType(OPTIONAL) |
| 30 | - .DataType({ge::DT_FLOAT8_E4M3FN}) | 30 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) |
| 31 | - .FormatList({ge::FORMAT_ND}) | 31 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) |
| 32 | .IgnoreContiguous(); | 32 | .IgnoreContiguous(); |
| 33 | this->Input("cmp_kv") | 33 | this->Input("cmp_kv") |
| 34 | .ParamType(OPTIONAL) | 34 | .ParamType(OPTIONAL) |
| 35 | - .DataType({ge::DT_FLOAT8_E4M3FN}) | 35 | + .DataType({ge::DT_UINT8, ge::DT_UINT8}) |
| 36 | - .FormatList({ge::FORMAT_ND}) | 36 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) |
| 37 | .IgnoreContiguous(); | 37 | .IgnoreContiguous(); |
| 38 | this->Input("ori_sparse_indices") | 38 | this->Input("ori_sparse_indices") |
| 39 | .ParamType(OPTIONAL) | 39 | .ParamType(OPTIONAL) |
| @@ -112,8 +112,8 @@ public: | |||
| 112 | .AutoContiguous(); | 112 | .AutoContiguous(); |
| 113 | this->Output("attn_out") | 113 | this->Output("attn_out") |
| 114 | .ParamType(REQUIRED) | 114 | .ParamType(REQUIRED) |
| 115 | - .DataTypeList({ge::DT_BF16}) | 115 | + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) |
| 116 | - .FormatList({ge::FORMAT_ND}); | 116 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); |
| 117 | this->Output("softmax_lse") | 117 | this->Output("softmax_lse") |
| 118 | .ParamType(OPTIONAL) | 118 | .ParamType(OPTIONAL) |
| 119 | .DataTypeList({ge::DT_FLOAT}) | 119 | .DataTypeList({ge::DT_FLOAT}) |
| @@ -139,7 +139,116 @@ public: | |||
| 139 | .NeedCheckSupportFlag(false) | 139 | .NeedCheckSupportFlag(false) |
| 140 | .PrecisionReduceFlag(true) | 140 | .PrecisionReduceFlag(true) |
| 141 | .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); | 141 | .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); |
| 142 | - this->AICore().AddConfig("ascend950", aicore_config); | 142 | + this->AICore().AddConfig("ascend910b", aicore_config); |
| 143 | + this->AICore().AddConfig("ascend910_93", aicore_config); | ||
| 144 | + | ||
| 145 | + OpAICoreConfig aicore_config_950; | ||
| 146 | + aicore_config_950.Input("q") | ||
| 147 | + .ParamType(REQUIRED) | ||
| 148 | + .DataTypeList({ge::DT_BF16}) | ||
| 149 | + .FormatList({ge::FORMAT_ND}) | ||
| 150 | + .AutoContiguous(); | ||
| 151 | + aicore_config_950.Input("ori_kv") | ||
| 152 | + .ParamType(OPTIONAL) | ||
| 153 | + .DataTypeList({ge::DT_FLOAT8_E4M3FN}) | ||
| 154 | + .FormatList({ge::FORMAT_ND}) | ||
| 155 | + .IgnoreContiguous(); | ||
| 156 | + aicore_config_950.Input("cmp_kv") | ||
| 157 | + .ParamType(OPTIONAL) | ||
| 158 | + .DataTypeList({ge::DT_FLOAT8_E4M3FN}) | ||
| 159 | + .FormatList({ge::FORMAT_ND}) | ||
| 160 | + .IgnoreContiguous(); | ||
| 161 | + aicore_config_950.Input("ori_sparse_indices") | ||
| 162 | + .ParamType(OPTIONAL) | ||
| 163 | + .DataTypeList({ge::DT_INT32}) | ||
| 164 | + .FormatList({ge::FORMAT_ND}) | ||
| 165 | + .AutoContiguous(); | ||
| 166 | + aicore_config_950.Input("cmp_sparse_indices") | ||
| 167 | + .ParamType(OPTIONAL) | ||
| 168 | + .DataTypeList({ge::DT_INT32}) | ||
| 169 | + .FormatList({ge::FORMAT_ND}) | ||
| 170 | + .AutoContiguous(); | ||
| 171 | + aicore_config_950.Input("ori_block_table") | ||
| 172 | + .ParamType(OPTIONAL) | ||
| 173 | + .DataTypeList({ge::DT_INT32}) | ||
| 174 | + .FormatList({ge::FORMAT_ND}) | ||
| 175 | + .AutoContiguous(); | ||
| 176 | + aicore_config_950.Input("cmp_block_table") | ||
| 177 | + .ParamType(OPTIONAL) | ||
| 178 | + .DataTypeList({ge::DT_INT32}) | ||
| 179 | + .FormatList({ge::FORMAT_ND}) | ||
| 180 | + .AutoContiguous(); | ||
| 181 | + aicore_config_950.Input("cu_seqlens_q") | ||
| 182 | + .ParamType(OPTIONAL) | ||
| 183 | + .DataTypeList({ge::DT_INT32}) | ||
| 184 | + .FormatList({ge::FORMAT_ND}) | ||
| 185 | + .AutoContiguous(); | ||
| 186 | + aicore_config_950.Input("cu_seqlens_ori_kv") | ||
| 187 | + .ParamType(OPTIONAL) | ||
| 188 | + .DataTypeList({ge::DT_INT32}) | ||
| 189 | + .FormatList({ge::FORMAT_ND}) | ||
| 190 | + .AutoContiguous(); | ||
| 191 | + aicore_config_950.Input("cu_seqlens_cmp_kv") | ||
| 192 | + .ParamType(OPTIONAL) | ||
| 193 | + .DataTypeList({ge::DT_INT32}) | ||
| 194 | + .FormatList({ge::FORMAT_ND}) | ||
| 195 | + .AutoContiguous(); | ||
| 196 | + aicore_config_950.Input("seqused_q") | ||
| 197 | + .ParamType(OPTIONAL) | ||
| 198 | + .DataTypeList({ge::DT_INT32}) | ||
| 199 | + .FormatList({ge::FORMAT_ND}) | ||
| 200 | + .AutoContiguous(); | ||
| 201 | + aicore_config_950.Input("seqused_ori_kv") | ||
| 202 | + .ParamType(OPTIONAL) | ||
| 203 | + .DataTypeList({ge::DT_INT32}) | ||
| 204 | + .FormatList({ge::FORMAT_ND}) | ||
| 205 | + .AutoContiguous(); | ||
| 206 | + aicore_config_950.Input("seqused_cmp_kv") | ||
| 207 | + .ParamType(OPTIONAL) | ||
| 208 | + .DataTypeList({ge::DT_INT32}) | ||
| 209 | + .FormatList({ge::FORMAT_ND}) | ||
| 210 | + .AutoContiguous(); | ||
| 211 | + aicore_config_950.Input("cmp_residual_kv") | ||
| 212 | + .ParamType(OPTIONAL) | ||
| 213 | + .DataTypeList({ge::DT_INT32}) | ||
| 214 | + .FormatList({ge::FORMAT_ND}) | ||
| 215 | + .AutoContiguous(); | ||
| 216 | + aicore_config_950.Input("ori_topk_length") | ||
| 217 | + .ParamType(OPTIONAL) | ||
| 218 | + .DataTypeList({ge::DT_INT32}) | ||
| 219 | + .FormatList({ge::FORMAT_ND}) | ||
| 220 | + .AutoContiguous(); | ||
| 221 | + aicore_config_950.Input("cmp_topk_length") | ||
| 222 | + .ParamType(OPTIONAL) | ||
| 223 | + .DataTypeList({ge::DT_INT32}) | ||
| 224 | + .FormatList({ge::FORMAT_ND}) | ||
| 225 | + .AutoContiguous(); | ||
| 226 | + aicore_config_950.Input("sinks") | ||
| 227 | + .ParamType(OPTIONAL) | ||
| 228 | + .DataTypeList({ge::DT_FLOAT}) | ||
| 229 | + .FormatList({ge::FORMAT_ND}) | ||
| 230 | + .AutoContiguous(); | ||
| 231 | + aicore_config_950.Input("metadata") | ||
| 232 | + .ParamType(OPTIONAL) | ||
| 233 | + .DataTypeList({ge::DT_INT32}) | ||
| 234 | + .FormatList({ge::FORMAT_ND}) | ||
| 235 | + .AutoContiguous(); | ||
| 236 | + aicore_config_950.Output("attn_out") | ||
| 237 | + .ParamType(REQUIRED) | ||
| 238 | + .DataTypeList({ge::DT_BF16}) | ||
| 239 | + .FormatList({ge::FORMAT_ND}); | ||
| 240 | + aicore_config_950.Output("softmax_lse") | ||
| 241 | + .ParamType(OPTIONAL) | ||
| 242 | + .DataTypeList({ge::DT_FLOAT}) | ||
| 243 | + .FormatList({ge::FORMAT_ND}); | ||
| 244 | + aicore_config_950.DynamicCompileStaticFlag(true) | ||
| 245 | + .DynamicFormatFlag(true) | ||
| 246 | + .DynamicRankSupportFlag(true) | ||
| 247 | + .DynamicShapeSupportFlag(true) | ||
| 248 | + .NeedCheckSupportFlag(false) | ||
| 249 | + .PrecisionReduceFlag(true) | ||
| 250 | + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); | ||
| 251 | + this->AICore().AddConfig("ascend950", aicore_config_950); | ||
| 143 | } | 252 | } |
| 144 | }; | 253 | }; |
| 145 | OP_ADD(MixedQuantSparseFlashMla); | 254 | OP_ADD(MixedQuantSparseFlashMla); |
| @@ -16,7 +16,6 @@ | |||
| 16 | #include "mixed_quant_sparse_flash_mla_check.h" | 16 | #include "mixed_quant_sparse_flash_mla_check.h" |
| 17 | #include "checkers/mixed_quant_sparse_flash_mla_checker.h" | 17 | #include "checkers/mixed_quant_sparse_flash_mla_checker.h" |
| 18 | #include "../../sparse_flash_mla/op_host/checkers/checker_adapter.h" | 18 | #include "../../sparse_flash_mla/op_host/checkers/checker_adapter.h" |
| 19 | -#include "../op_kernel/mixed_quant_sparse_flash_mla_template_tiling_key.h" | ||
| 20 | #include "mixed_quant_sparse_flash_mla_tiling.h" | 19 | #include "mixed_quant_sparse_flash_mla_tiling.h" |
| 21 | #include <algorithm> | 20 | #include <algorithm> |
| 22 | 21 | ||
| @@ -121,7 +120,7 @@ ge::graphStatus MQSMLAInfoParser::GetNpuInfo() | |||
| 121 | 120 | ||
| 122 | socVersion_ = ascendcPlatform.GetSocVersion(); | 121 | socVersion_ = ascendcPlatform.GetSocVersion(); |
| 123 | npuArch_ = ascendcPlatform.GetCurNpuArch(); | 122 | npuArch_ = ascendcPlatform.GetCurNpuArch(); |
| 124 | - if (npuArch_ != NpuArch::DAV_3510) { | 123 | + if (npuArch_ != NpuArch::DAV_2201 && npuArch_ != NpuArch::DAV_3510) { |
| 125 | OP_LOGE(opName_, "NpuArch[%d] is not support.", static_cast<int32_t>(npuArch_)); | 124 | OP_LOGE(opName_, "NpuArch[%d] is not support.", static_cast<int32_t>(npuArch_)); |
| 126 | return GRAPH_FAILED; | 125 | return GRAPH_FAILED; |
| 127 | } | 126 | } |
| @@ -503,6 +502,19 @@ ge::graphStatus MQSMLAInfoParser::GetSparseBlockCount() | |||
| 503 | ge::graphStatus MQSMLAInfoParser::GetActualseqInfo() | 502 | ge::graphStatus MQSMLAInfoParser::GetActualseqInfo() |
| 504 | { | 503 | { |
| 505 | maxActualseq_ = s2Size_; | 504 | maxActualseq_ = s2Size_; |
| 505 | + if (npuArch_ != NpuArch::DAV_2201) { | ||
| 506 | + return ge::GRAPH_SUCCESS; | ||
| 507 | + } | ||
| 508 | + if (qLayout_ == MQSMLALayout::TND && opParamInfo_.cuSeqLensQ.tensor != nullptr) { | ||
| 509 | + actualLenDimsQ_ = static_cast<uint32_t>(opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() - 1); | ||
| 510 | + } else if (opParamInfo_.seqUsedQ.tensor != nullptr) { | ||
| 511 | + actualLenDimsQ_ = static_cast<uint32_t>(opParamInfo_.seqUsedQ.tensor->GetShapeSize()); | ||
| 512 | + } | ||
| 513 | + if (kvLayout_ == MQSMLALayout::PA_BBND && opParamInfo_.sequsedOriKv.tensor != nullptr) { | ||
| 514 | + actualLenDimsKV_ = static_cast<uint32_t>(opParamInfo_.sequsedOriKv.tensor->GetShapeSize()); | ||
| 515 | + } else if (opParamInfo_.cuSeqLensOriKv.tensor != nullptr) { | ||
| 516 | + actualLenDimsKV_ = static_cast<uint32_t>(opParamInfo_.cuSeqLensOriKv.tensor->GetShapeSize() - 1); | ||
| 517 | + } | ||
| 506 | return ge::GRAPH_SUCCESS; | 518 | return ge::GRAPH_SUCCESS; |
| 507 | } | 519 | } |
| 508 | 520 | ||
| @@ -531,6 +543,9 @@ ge::graphStatus MQSMLAInfoParser::GetKvstride() | |||
| 531 | } | 543 | } |
| 532 | } else if (kvLayout_ == MQSMLALayout::PA_BBND) { | 544 | } else if (kvLayout_ == MQSMLALayout::PA_BBND) { |
| 533 | oriKvStride_ = oriBlockSize_ * n2Size_ * dSizeKV_; | 545 | oriKvStride_ = oriBlockSize_ * n2Size_ * dSizeKV_; |
| 546 | + if (npuArch_ == NpuArch::DAV_2201) { | ||
| 547 | + oriKvStridesVec_.push_back(oriKvStride_); | ||
| 548 | + } | ||
| 534 | } | 549 | } |
| 535 | if (cmpKvStrides != nullptr && cmpKvStrides->GetDimNum() > 0) { | 550 | if (cmpKvStrides != nullptr && cmpKvStrides->GetDimNum() > 0) { |
| 536 | for (size_t i = 0; i < cmpKvStrides->GetDimNum(); i++) { | 551 | for (size_t i = 0; i < cmpKvStrides->GetDimNum(); i++) { |
| @@ -540,7 +555,13 @@ ge::graphStatus MQSMLAInfoParser::GetKvstride() | |||
| 540 | cmpKvStride_ = cmpKvStrides->GetStride(0); | 555 | cmpKvStride_ = cmpKvStrides->GetStride(0); |
| 541 | } | 556 | } |
| 542 | } else if (kvLayout_ == MQSMLALayout::PA_BBND) { | 557 | } else if (kvLayout_ == MQSMLALayout::PA_BBND) { |
| 543 | - cmpKvStride_ = cmpBlockSize_ * n2Size_ * dSizeKV_; | 558 | + if (npuArch_ == NpuArch::DAV_2201) { |
| 559 | + const int64_t cmpHeadDim = GetAxisNum(cmpKvShape_, MQSMLAAxis::D, kvLayout_); | ||
| 560 | + cmpKvStride_ = static_cast<int64_t>(cmpBlockSize_) * n2Size_ * cmpHeadDim; | ||
| 561 | + cmpKvStridesVec_.push_back(cmpKvStride_); | ||
| 562 | + } else { | ||
| 563 | + cmpKvStride_ = cmpBlockSize_ * n2Size_ * dSizeKV_; | ||
| 564 | + } | ||
| 544 | } | 565 | } |
| 545 | return ge::GRAPH_SUCCESS; | 566 | return ge::GRAPH_SUCCESS; |
| 546 | } | 567 | } |
| @@ -562,6 +583,8 @@ void MQSMLAInfoParser::GenerateInfo(MQSMLATilingInfo &qsmlaInfo) | |||
| 562 | qsmlaInfo.gSize = gSize_; | 583 | qsmlaInfo.gSize = gSize_; |
| 563 | qsmlaInfo.qkHeadDim = qkHeadDim_; | 584 | qsmlaInfo.qkHeadDim = qkHeadDim_; |
| 564 | qsmlaInfo.qTSize = qTSize_; | 585 | qsmlaInfo.qTSize = qTSize_; |
| 586 | + qsmlaInfo.actualLenDimsQ = actualLenDimsQ_; | ||
| 587 | + qsmlaInfo.actualLenDimsKV = actualLenDimsKV_; | ||
| 565 | qsmlaInfo.oriSparseBlockCount = oriSparseBlockCount_; | 588 | qsmlaInfo.oriSparseBlockCount = oriSparseBlockCount_; |
| 566 | qsmlaInfo.cmpSparseBlockCount = cmpSparseBlockCount_; | 589 | qsmlaInfo.cmpSparseBlockCount = cmpSparseBlockCount_; |
| 567 | 590 | ||
| @@ -650,162 +673,10 @@ static ge::graphStatus TilingPrepareForMixedQuantSparseFlashMla(gert::TilingPars | |||
| 650 | // --------------------------MixedQuantSparseFlashMlaTiling类成员函数定义----------------------- | 673 | // --------------------------MixedQuantSparseFlashMlaTiling类成员函数定义----------------------- |
| 651 | ge::graphStatus MixedQuantSparseFlashMlaTiling::DoOpTiling(MQSMLATilingInfo *tilingInfo) | 674 | ge::graphStatus MixedQuantSparseFlashMlaTiling::DoOpTiling(MQSMLATilingInfo *tilingInfo) |
| 652 | { | 675 | { |
| 653 | - if (tilingInfo->opParamInfo.cmpKv.tensor == nullptr) { | 676 | + if (tilingInfo->npuArch == NpuArch::DAV_2201) { |
| 654 | - OP_CHECK_IF( | 677 | + return DoTurboQuantTiling(tilingInfo); |
| 655 | - tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr, | ||
| 656 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("MixedQuantSparseFlashMla", "cmp_sparse_indices", | ||
| 657 | - "Cmp_sparse_indices must be empty when cmpKv is not provided"), | ||
| 658 | - return ge::GRAPH_FAILED); | ||
| 659 | - if (tilingInfo->opParamInfo.oriSparseIndices.tensor == nullptr) { | ||
| 660 | - perfMode_ = QSMLATemplateMode::SWA_TEMPLATE_MODE; | ||
| 661 | - } else { | ||
| 662 | - perfMode_ = QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE; | ||
| 663 | - } | ||
| 664 | - } else if (tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr) { | ||
| 665 | - if (tilingInfo->opParamInfo.oriSparseIndices.tensor == nullptr) { | ||
| 666 | - perfMode_ = QSMLATemplateMode::CSA_TEMPLATE_MODE; | ||
| 667 | - } else { | ||
| 668 | - perfMode_ = QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE; | ||
| 669 | - } | ||
| 670 | - } else { | ||
| 671 | - perfMode_ = QSMLATemplateMode::HCA_TEMPLATE_MODE; | ||
| 672 | } | 678 | } |
| 673 | - // -------------set blockdim----------------- | 679 | + return DoCsaTiling(tilingInfo); |
| 674 | - auto ascendcPlatform = platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); | ||
| 675 | - uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); | ||
| 676 | - uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); | ||
| 677 | - uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); | ||
| 678 | - context_->SetBlockDim(blockDim); | ||
| 679 | - OP_LOGI(tilingInfo->opName, "QSMLA block dim: %u aiv Num: %u aic Num: %u.", blockDim, aivNum, aicNum); | ||
| 680 | - | ||
| 681 | - // -------------set workspacesize----------------- | ||
| 682 | - constexpr uint32_t TRIPLE_BUFFER_NUM = 3; | ||
| 683 | - constexpr uint32_t S2_BASE_SIZE = 128; // S2轴基本块大小 | ||
| 684 | - constexpr uint32_t D_SIZE = 512; | ||
| 685 | - constexpr uint32_t VEC_RES_ELEM_SIZE = 2; // 2: fp16/bf16字节数 | ||
| 686 | - constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数 | ||
| 687 | - constexpr uint32_t UB_SIZE = 184 * 1024; | ||
| 688 | - constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128; | ||
| 689 | - constexpr int64_t QUANT_CONTIGUOUS_MODE = 1; | ||
| 690 | - constexpr uint32_t MAX_S2_SPLIT_NUM = 2; // 每核最多S2切分次数 | ||
| 691 | - constexpr uint32_t FLOAT_ELEM_SIZE = 4; // sizeof(float) | ||
| 692 | - constexpr uint32_t FD_BLOCK_ELEM = 8; // FD广播份数 | ||
| 693 | - constexpr uint32_t FD_MAX_SUM_REGION_NUM = 2; // max和sum两个区域 | ||
| 694 | - constexpr uint32_t BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM = 33; | ||
| 695 | - uint32_t alignedOriSparseBlockCount = (tilingInfo->oriSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / | ||
| 696 | - SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; | ||
| 697 | - uint32_t alignedCmpSparseBlockCount = (tilingInfo->cmpSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / | ||
| 698 | - SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; | ||
| 699 | - uint64_t oriUbSize = static_cast<uint64_t>(tilingInfo->oriMaxBlockNumPerBatch) * sizeof(int32_t) + | ||
| 700 | - static_cast<uint64_t>(alignedOriSparseBlockCount) * (sizeof(int32_t) + sizeof(int64_t)); | ||
| 701 | - uint64_t cmpUbSize = static_cast<uint64_t>(tilingInfo->cmpMaxBlockNumPerBatch) * sizeof(int32_t) + | ||
| 702 | - static_cast<uint64_t>(alignedCmpSparseBlockCount) * (sizeof(int32_t) + sizeof(int64_t)); | ||
| 703 | - bool oriBlockSizePowerOfTwo = | ||
| 704 | - tilingInfo->oriBlockSize > 0 && (tilingInfo->oriBlockSize & (tilingInfo->oriBlockSize - 1)) == 0; | ||
| 705 | - bool cmpBlockSizePowerOfTwo = | ||
| 706 | - tilingInfo->cmpBlockSize > 0 && (tilingInfo->cmpBlockSize & (tilingInfo->cmpBlockSize - 1)) == 0; | ||
| 707 | - bool blockSizeSupported = (perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE && cmpBlockSizePowerOfTwo) || | ||
| 708 | - (perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE && oriBlockSizePowerOfTwo) || | ||
| 709 | - (perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE && oriBlockSizePowerOfTwo && | ||
| 710 | - cmpBlockSizePowerOfTwo); | ||
| 711 | - uint64_t vectorizeUbSize = | ||
| 712 | - (perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE) ? | ||
| 713 | - cmpUbSize : | ||
| 714 | - ((perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE) ? oriUbSize : std::max(oriUbSize, cmpUbSize)); | ||
| 715 | - uint32_t vectorizeFlag = static_cast<uint32_t>((perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE || | ||
| 716 | - perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || | ||
| 717 | - perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) && | ||
| 718 | - tilingInfo->quantMode == QUANT_CONTIGUOUS_MODE && | ||
| 719 | - tilingInfo->kvLayout == MQSMLALayout::PA_BBND && | ||
| 720 | - blockSizeSupported && vectorizeUbSize <= UB_SIZE); | ||
| 721 | - | ||
| 722 | - size_t workspaceSize = static_cast<size_t>(ascendcPlatform.GetLibApiWorkSpaceSize()); | ||
| 723 | - bool isSplitG = tilingInfo->gSize > 64; // gSize超过64时采用Split-G | ||
| 724 | - workspaceSize += static_cast<size_t>(S2_BASE_SIZE) * D_SIZE * VEC_RES_ELEM_SIZE * TRIPLE_BUFFER_NUM * | ||
| 725 | - (isSplitG ? (aicNum >> 1) : aicNum); | ||
| 726 | - if (vectorizeFlag != 0) { | ||
| 727 | - uint64_t totalBS1 = (tilingInfo->qLayout == MQSMLALayout::TND) ? | ||
| 728 | - tilingInfo->s1Size : | ||
| 729 | - static_cast<uint64_t>(tilingInfo->bSize) * tilingInfo->s1Size; | ||
| 730 | - if (perfMode_ == QSMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || | ||
| 731 | - perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { | ||
| 732 | - workspaceSize += totalBS1 * alignedOriSparseBlockCount * sizeof(int64_t); | ||
| 733 | - } | ||
| 734 | - if (perfMode_ == QSMLATemplateMode::CSA_TEMPLATE_MODE || | ||
| 735 | - perfMode_ == QSMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { | ||
| 736 | - workspaceSize += totalBS1 * alignedCmpSparseBlockCount * sizeof(int64_t); | ||
| 737 | - } | ||
| 738 | - } | ||
| 739 | - uint32_t fdStagingMSize = tilingInfo->gSize; | ||
| 740 | - uint32_t fdStagingSlotNum = isSplitG ? (aicNum >> 1) : aicNum; | ||
| 741 | - if (tilingInfo->batchConsistency) { | ||
| 742 | - size_t combineElemSize = static_cast<size_t>(fdStagingMSize) * D_SIZE + | ||
| 743 | - static_cast<size_t>(FD_MAX_SUM_REGION_NUM) * fdStagingMSize * FD_BLOCK_ELEM; | ||
| 744 | - workspaceSize += 2ULL * fdStagingSlotNum * combineElemSize * FLOAT_ELEM_SIZE; | ||
| 745 | - workspaceSize += | ||
| 746 | - static_cast<size_t>(aicNum) * BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM * combineElemSize * FLOAT_ELEM_SIZE; | ||
| 747 | - } else { | ||
| 748 | - // 末尾的2对应每个split分别暂存max和sum。 | ||
| 749 | - size_t s2SplitStagingPerSlot = | ||
| 750 | - static_cast<size_t>(fdStagingMSize) * D_SIZE * FLOAT_ELEM_SIZE * MAX_S2_SPLIT_NUM + | ||
| 751 | - static_cast<size_t>(fdStagingMSize) * FD_BLOCK_ELEM * FLOAT_ELEM_SIZE * MAX_S2_SPLIT_NUM * | ||
| 752 | - FD_MAX_SUM_REGION_NUM; | ||
| 753 | - workspaceSize += s2SplitStagingPerSlot * fdStagingSlotNum; | ||
| 754 | - } | ||
| 755 | - size_t *workSpaces = context_->GetWorkspaceSizes(1); | ||
| 756 | - workSpaces[0] = workspaceSize; | ||
| 757 | - | ||
| 758 | - // -------------set tilingdata----------------- | ||
| 759 | - tilingData_.baseParams.set_batchSize(tilingInfo->bSize); | ||
| 760 | - tilingData_.baseParams.set_kvSeqSize(tilingInfo->s2Size); | ||
| 761 | - tilingData_.baseParams.set_cmpKvSeqSize(tilingInfo->cmpS2Size); | ||
| 762 | - tilingData_.baseParams.set_qSeqSize(tilingInfo->s1Size); | ||
| 763 | - tilingData_.baseParams.set_oriSparseBlockCount(tilingInfo->oriSparseBlockCount); | ||
| 764 | - tilingData_.baseParams.set_cmpSparseBlockCount(tilingInfo->cmpSparseBlockCount); | ||
| 765 | - tilingData_.baseParams.set_nNumOfQInOneGroup(tilingInfo->gSize); | ||
| 766 | - tilingData_.baseParams.set_paOriBlockSize(tilingInfo->oriBlockSize); | ||
| 767 | - tilingData_.baseParams.set_paCmpBlockSize(tilingInfo->cmpBlockSize); | ||
| 768 | - tilingData_.baseParams.set_oriMaxBlockNumPerBatch(tilingInfo->oriMaxBlockNumPerBatch); | ||
| 769 | - tilingData_.baseParams.set_cmpMaxBlockNumPerBatch(tilingInfo->cmpMaxBlockNumPerBatch); | ||
| 770 | - | ||
| 771 | - tilingData_.baseParams.set_tileSize(tilingInfo->tileSize); | ||
| 772 | - tilingData_.baseParams.set_ropeHeadDim(tilingInfo->ropeHeadDim); | ||
| 773 | - tilingData_.baseParams.set_softmaxScale(tilingInfo->softmaxScale); | ||
| 774 | - tilingData_.baseParams.set_oriKvStride(tilingInfo->oriKvStride); | ||
| 775 | - tilingData_.baseParams.set_cmpKvStride(tilingInfo->cmpKvStride); | ||
| 776 | - tilingData_.baseParams.set_cmpRatio(tilingInfo->cmpRatio); | ||
| 777 | - tilingData_.baseParams.set_oriMaskMode(tilingInfo->oriMaskMode); | ||
| 778 | - tilingData_.baseParams.set_cmpMaskMode(tilingInfo->cmpMaskMode); | ||
| 779 | - tilingData_.baseParams.set_oriWinLeft(tilingInfo->oriWinLeft); | ||
| 780 | - tilingData_.baseParams.set_oriWinRight(tilingInfo->oriWinRight); | ||
| 781 | - tilingData_.baseParams.set_sparseBlockSize(tilingInfo->sparseBlockSize); | ||
| 782 | - tilingData_.baseParams.set_dSize(tilingInfo->dSize); | ||
| 783 | - tilingData_.baseParams.set_dSizeVInput(tilingInfo->dSizeVInput); | ||
| 784 | - tilingData_.baseParams.set_returnSoftmaxLse(tilingInfo->returnSoftmaxLse); | ||
| 785 | - | ||
| 786 | - tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); | ||
| 787 | - context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); | ||
| 788 | - | ||
| 789 | - // -------------set tilingkey----------------- | ||
| 790 | - // DT_Q, DT_KV, DT_OUT, PAGE_ATTENTION, FLASH_DECODE, LAYOUT_T, KV_LAYOUT_T | ||
| 791 | - uint32_t qType = static_cast<uint32_t>(tilingInfo->qType); | ||
| 792 | - uint32_t oriKvType = static_cast<uint32_t>(tilingInfo->oriKvType); | ||
| 793 | - uint32_t outputType = static_cast<uint32_t>(tilingInfo->outputType); | ||
| 794 | - uint32_t qLayout = static_cast<uint32_t>(tilingInfo->qLayout); | ||
| 795 | - uint32_t inputKvLayout = static_cast<uint32_t>(tilingInfo->kvLayout); | ||
| 796 | - // maskmode为4+3,无topk len输入且不输出lse时, 走HIGH_PERF高性能模板 | ||
| 797 | - bool highPerf = (tilingInfo->oriMaskMode == 4 && tilingInfo->cmpMaskMode == 3) && | ||
| 798 | - tilingInfo->opParamInfo.oriTopkLength.tensor == nullptr && | ||
| 799 | - tilingInfo->opParamInfo.cmpTopkLength.tensor == nullptr && !tilingInfo->returnSoftmaxLse; | ||
| 800 | - uint64_t tilingKey = GET_TPL_TILING_KEY( | ||
| 801 | - 0U, qLayout, inputKvLayout, static_cast<uint32_t>(perfMode_), static_cast<uint32_t>(isSplitG), | ||
| 802 | - static_cast<uint32_t>(tilingInfo->quantMode), | ||
| 803 | - ((oriKvType == ge::DT_FLOAT8_E4M3FN) ? DTYPE_FP8_E4M3FN : DTYPE_HIF8), | ||
| 804 | - static_cast<uint32_t>(tilingInfo->batchConsistency), vectorizeFlag, static_cast<uint32_t>(highPerf)); | ||
| 805 | - context_->SetTilingKey(tilingKey); | ||
| 806 | - context_->SetScheduleMode(1); | ||
| 807 | - | ||
| 808 | - return ge::GRAPH_SUCCESS; | ||
| 809 | } | 680 | } |
| 810 | 681 | ||
| 811 | // --------------------------Tiling函数定义--------------------------- | 682 | // --------------------------Tiling函数定义--------------------------- |
| @@ -29,10 +29,6 @@ | |||
| 29 | 29 | ||
| 30 | namespace optiling { | 30 | namespace optiling { |
| 31 | 31 | ||
| 32 | -std::vector<int64_t> ToVector(const gert::Shape &shape); | ||
| 33 | -std::string ToStringRaw(const gert::Shape &shape); | ||
| 34 | -std::string MQSMLALayoutToSerialString(MQSMLALayout layout); | ||
| 35 | - | ||
| 36 | // -----------算子TilingData定义--------------- | 32 | // -----------算子TilingData定义--------------- |
| 37 | BEGIN_TILING_DATA_DEF(MixedQuantSparseFlashMlaBaseParams) | 33 | BEGIN_TILING_DATA_DEF(MixedQuantSparseFlashMlaBaseParams) |
| 38 | TILING_DATA_FIELD_DEF(uint32_t, batchSize) | 34 | TILING_DATA_FIELD_DEF(uint32_t, batchSize) |
| @@ -77,6 +73,8 @@ public: | |||
| 77 | ge::graphStatus DoOpTiling(MQSMLATilingInfo *tilingInfo); | 73 | ge::graphStatus DoOpTiling(MQSMLATilingInfo *tilingInfo); |
| 78 | 74 | ||
| 79 | private: | 75 | private: |
| 76 | + ge::graphStatus DoTurboQuantTiling(MQSMLATilingInfo *tilingInfo); | ||
| 77 | + ge::graphStatus DoCsaTiling(MQSMLATilingInfo *tilingInfo); | ||
| 80 | gert::TilingContext *context_ = nullptr; | 78 | gert::TilingContext *context_ = nullptr; |
| 81 | QSMLATemplateMode perfMode_ = QSMLATemplateMode::SWA_TEMPLATE_MODE; | 79 | QSMLATemplateMode perfMode_ = QSMLATemplateMode::SWA_TEMPLATE_MODE; |
| 82 | MixedQuantSparseFlashMlaTilingData tilingData_; | 80 | MixedQuantSparseFlashMlaTilingData tilingData_; |
| @@ -0,0 +1,62 @@ | |||
| 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 mixed_quant_sparse_flash_mla_template_tiling_key_arch22.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_ARCH22_H | ||
| 17 | +#define MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_ARCH22_H | ||
| 18 | + | ||
| 19 | +#include "ascendc/host_api/tiling/template_argument.h" | ||
| 20 | + | ||
| 21 | +#define QSMLA_LAYOUT_BSND 0 | ||
| 22 | +#define QSMLA_LAYOUT_TND 1 | ||
| 23 | +#define QSMLA_LAYOUT_PA_BBND 2 | ||
| 24 | +#define ASCENDC_TPL_4_BW 4 | ||
| 25 | +#define SWA_TEMPLATE 0 | ||
| 26 | +#define HCA_TEMPLATE 1 | ||
| 27 | +#define CSA_TEMPLATE 2 | ||
| 28 | +#define ORI_SPARSE_TEMPLATE 3 | ||
| 29 | +#define ORI_CMP_SPARSE_TEMPLATE 4 | ||
| 30 | +#define QUANT_CONTIGUOUS 1 | ||
| 31 | +#define QUANT_NONCONTIGUOUS 2 | ||
| 32 | +#define TURBO_QUANT 3 | ||
| 33 | +#define DTYPE_FP8_E4M3FN 0 | ||
| 34 | +#define DTYPE_HIF8 1 | ||
| 35 | + | ||
| 36 | +ASCENDC_TPL_ARGS_DECL(MixedQuantSparseFlashMla, ASCENDC_TPL_BOOL_DECL(FLASH_DECODE, 0, 1), | ||
| 37 | + ASCENDC_TPL_UINT_DECL(LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QSMLA_LAYOUT_BSND, | ||
| 38 | + QSMLA_LAYOUT_TND), | ||
| 39 | + ASCENDC_TPL_UINT_DECL(KV_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QSMLA_LAYOUT_PA_BBND, | ||
| 40 | + QSMLA_LAYOUT_TND, QSMLA_LAYOUT_BSND), | ||
| 41 | + ASCENDC_TPL_UINT_DECL(TEMPLATE_MODE, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, SWA_TEMPLATE, | ||
| 42 | + HCA_TEMPLATE, CSA_TEMPLATE, ORI_SPARSE_TEMPLATE, ORI_CMP_SPARSE_TEMPLATE), | ||
| 43 | + ASCENDC_TPL_BOOL_DECL(SPLIT_G, 0, 1), | ||
| 44 | + ASCENDC_TPL_UINT_DECL(QUANT_MODE, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, QUANT_CONTIGUOUS, | ||
| 45 | + QUANT_NONCONTIGUOUS, TURBO_QUANT), | ||
| 46 | + ASCENDC_TPL_UINT_DECL(KV_DTYPE, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, DTYPE_FP8_E4M3FN, | ||
| 47 | + DTYPE_HIF8), | ||
| 48 | + ASCENDC_TPL_BOOL_DECL(BATCH_CONSISTENCY, 0, 1), ASCENDC_TPL_BOOL_DECL(IS_VEC_S2PHYADDR, 0, 1), | ||
| 49 | + ASCENDC_TPL_BOOL_DECL(HIGH_PERF, 0, 1), ); | ||
| 50 | + | ||
| 51 | +ASCENDC_TPL_SEL(ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), | ||
| 52 | + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, QSMLA_LAYOUT_TND), | ||
| 53 | + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, QSMLA_LAYOUT_PA_BBND), | ||
| 54 | + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, CSA_TEMPLATE), | ||
| 55 | + ASCENDC_TPL_BOOL_SEL(SPLIT_G, 0), | ||
| 56 | + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, TURBO_QUANT), | ||
| 57 | + ASCENDC_TPL_UINT_SEL(KV_DTYPE, ASCENDC_TPL_UI_LIST, DTYPE_FP8_E4M3FN), | ||
| 58 | + ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0), | ||
| 59 | + ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0), | ||
| 60 | + ASCENDC_TPL_BOOL_SEL(HIGH_PERF, 0), ), ); | ||
| 61 | + | ||
| 62 | +#endif // MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_ARCH22_H | ||
| @@ -0,0 +1,64 @@ | |||
| 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 mixed_quant_sparse_flash_mla_tiling_data_arch22.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef MIXED_QUANT_SPARSE_FLASH_MLA_TILING_DATA_ARCH22_H | ||
| 17 | +#define MIXED_QUANT_SPARSE_FLASH_MLA_TILING_DATA_ARCH22_H | ||
| 18 | + | ||
| 19 | +#include <cstdint> | ||
| 20 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 21 | + | ||
| 22 | +namespace optiling { | ||
| 23 | +struct MixedQuantSparseFlashMlaTqBaseParams { | ||
| 24 | + uint32_t batchSize; | ||
| 25 | + uint32_t qSeqSize; | ||
| 26 | + uint32_t kvSeqSize; | ||
| 27 | + int64_t paBlockSize; | ||
| 28 | + int64_t oriBlockSize; | ||
| 29 | + int64_t cmpBlockSize; | ||
| 30 | + uint32_t oriMaxBlockNumPerBatch; | ||
| 31 | + uint32_t nNumOfQInOneGroup; | ||
| 32 | + uint32_t actualLenDimsQ; | ||
| 33 | + uint32_t actualLenDimsKV; | ||
| 34 | + float softmaxScale; | ||
| 35 | + uint32_t outputLayout; | ||
| 36 | + uint64_t oriMaskMode; | ||
| 37 | + int64_t oriKvStride0; | ||
| 38 | + int64_t oriWinLeft; | ||
| 39 | + int64_t oriWinRight; | ||
| 40 | + int64_t sparseBlockSize; | ||
| 41 | + uint32_t usedCoreNum; | ||
| 42 | + uint32_t mmResUbSize; | ||
| 43 | + uint32_t bmm2ResUbSize; | ||
| 44 | + uint32_t mBaseSize; | ||
| 45 | + uint32_t s2BaseSize; | ||
| 46 | + bool returnSoftmaxLse; | ||
| 47 | + uint32_t kvQuantMode; | ||
| 48 | +}; | ||
| 49 | + | ||
| 50 | +struct MixedQuantSparseFlashMlaTqCmpParams { | ||
| 51 | + uint32_t cmpMaxBlockNumPerBatch; | ||
| 52 | + uint32_t sparseBlockCount; | ||
| 53 | + int64_t cmpRatio; | ||
| 54 | + uint64_t cmpMaskMode; | ||
| 55 | + int64_t cmpKvStride0; | ||
| 56 | +}; | ||
| 57 | + | ||
| 58 | +struct MixedQuantSparseFlashMlaTqTilingData { | ||
| 59 | + MixedQuantSparseFlashMlaTqBaseParams tqBaseParams; | ||
| 60 | + MixedQuantSparseFlashMlaTqCmpParams tqCmpParams; | ||
| 61 | +}; | ||
| 62 | +} // namespace optiling | ||
| 63 | + | ||
| 64 | +#endif // MIXED_QUANT_SPARSE_FLASH_MLA_TILING_DATA_ARCH22_H | ||
Aattention/mixed_quant_sparse_flash_mla/op_kernel/arch22/mixed_quant_sparse_flash_mla_tq_common.h+388-0
| @@ -0,0 +1,388 @@ | |||
| 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 mixed_quant_sparse_flash_mla_tq_common.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef MIXED_QUANT_SPARSE_FLASH_MLA_TQ_COMMON_H | ||
| 17 | +#define MIXED_QUANT_SPARSE_FLASH_MLA_TQ_COMMON_H | ||
| 18 | + | ||
| 19 | +#include "kernel_vec_intf.h" | ||
| 20 | +#include "kernel_cube_intf.h" | ||
| 21 | +#include "adv_api/activation/softmaxflashv2.h" | ||
| 22 | +#include "adv_api/math/log.h" | ||
| 23 | +#include "lib/matmul_intf.h" | ||
| 24 | +#include "lib/matrix/matmul/tiling.h" | ||
| 25 | + | ||
| 26 | +namespace SASKernel { | ||
| 27 | +using namespace AscendC; | ||
| 28 | +// 将isCheckTiling设置为false, 输入输出的max&sum&exp的shape为(m, 1) | ||
| 29 | +constexpr SoftmaxConfig SAS_SOFTMAX_FLASHV2_CFG_WITHOUT_BRC = {false, 0, 0, SoftmaxMode::SOFTMAX_OUTPUT_WITHOUT_BRC}; | ||
| 30 | + | ||
| 31 | +enum class SAS_RUN_MODE { | ||
| 32 | + SWA_MODE = 0, | ||
| 33 | + CSA_MODE = 1, | ||
| 34 | + CFA_MODE = 2, | ||
| 35 | +}; | ||
| 36 | + | ||
| 37 | +enum class SAS_LAYOUT { | ||
| 38 | + BSND = 0, | ||
| 39 | + TND = 1, | ||
| 40 | + PA_BSND = 2, | ||
| 41 | + PA_BNSD = 3 | ||
| 42 | +}; | ||
| 43 | + | ||
| 44 | +template <typename Q_T, typename KV_T, typename OUT_T, const bool FLASH_DECODE = false, | ||
| 45 | + SAS_LAYOUT LAYOUT_T = SAS_LAYOUT::BSND, SAS_LAYOUT KV_LAYOUT_T = SAS_LAYOUT::PA_BSND, int TEMPLATE_MODE = 0, | ||
| 46 | + typename... Args> | ||
| 47 | +struct SASType { | ||
| 48 | + using queryType = Q_T; | ||
| 49 | + using kvType = KV_T; | ||
| 50 | + using outputType = OUT_T; | ||
| 51 | + static constexpr bool flashDecode = FLASH_DECODE; | ||
| 52 | + static constexpr SAS_LAYOUT layout = LAYOUT_T; | ||
| 53 | + static constexpr SAS_LAYOUT kvLayout = KV_LAYOUT_T; | ||
| 54 | + static constexpr bool pageAttention = (KV_LAYOUT_T == SAS_LAYOUT::PA_BSND || KV_LAYOUT_T == SAS_LAYOUT::PA_BNSD); | ||
| 55 | + static constexpr int templateMode = TEMPLATE_MODE; | ||
| 56 | +}; | ||
| 57 | + | ||
| 58 | +// ================================Util functions================================== | ||
| 59 | +template <typename T1, typename T2> | ||
| 60 | +__aicore__ inline T1 SASAlign(T1 num, T2 rnd) | ||
| 61 | +{ | ||
| 62 | + return (rnd == 0) ? 0 : ((num + rnd - 1) / rnd * rnd); | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +template <typename T1, typename T2> | ||
| 66 | +__aicore__ inline T1 CeilDiv(T1 num, T2 rnd) | ||
| 67 | +{ | ||
| 68 | + return (rnd == 0) ? 0 : ((num + rnd - 1) / rnd); | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +template <typename T1, typename T2> | ||
| 72 | +__aicore__ inline T1 Min(T1 a, T2 b) | ||
| 73 | +{ | ||
| 74 | + return (a > b) ? b : a; | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +template <typename T1, typename T2> | ||
| 78 | +__aicore__ inline T1 Max(T1 a, T2 b) | ||
| 79 | +{ | ||
| 80 | + return (a > b) ? a : b; | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +template <typename T> | ||
| 84 | +__aicore__ inline size_t BlockAlign(size_t s) | ||
| 85 | +{ | ||
| 86 | + if constexpr (IsSameType<T, int4b_t>::value) { | ||
| 87 | + return (s + 63) / 64 * 64; | ||
| 88 | + } | ||
| 89 | + size_t n = (32 / sizeof(T)); | ||
| 90 | + return (s + n - 1) / n * n; | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +struct PAShape { | ||
| 94 | + uint32_t blockSize; | ||
| 95 | + uint32_t headNum; // 一般为kv的head num,对应n2 | ||
| 96 | + uint32_t headDim; // 512 对应d | ||
| 97 | + uint32_t kvStride; | ||
| 98 | + uint32_t maxblockNumPerBatch; // block table 每一行的最大个数 | ||
| 99 | + uint32_t actHeadDim; // 实际拷贝col大小,考虑到N切块 s*d, 对应d | ||
| 100 | + uint32_t copyRowNum; // 总共要拷贝的行数 | ||
| 101 | + uint32_t copyRowNumAlign; | ||
| 102 | +}; | ||
| 103 | + | ||
| 104 | +struct Position { | ||
| 105 | + uint32_t bIdx; | ||
| 106 | + uint32_t n2Idx; | ||
| 107 | + uint32_t s2Idx; | ||
| 108 | + uint32_t dIdx; | ||
| 109 | +}; | ||
| 110 | + | ||
| 111 | +// 场景:query、key、value GM to L1 | ||
| 112 | +// GM按ND格式存储 | ||
| 113 | +// L1按NZ格式存储 | ||
| 114 | +// GM的行、列、列的stride | ||
| 115 | +template <typename T> | ||
| 116 | +__aicore__ inline void DataCopyGmNDToL1(LocalTensor<T> &l1Tensor, GlobalTensor<T> &gmTensor, uint32_t rowAct, | ||
| 117 | + uint32_t rowAlign, | ||
| 118 | + uint32_t col, // D | ||
| 119 | + uint32_t colStride) // D or N*D | ||
| 120 | +{ | ||
| 121 | + Nd2NzParams nd2nzPara; | ||
| 122 | + nd2nzPara.ndNum = 1; | ||
| 123 | + nd2nzPara.nValue = rowAct; // nd矩阵的行数 | ||
| 124 | + // T为int4场景下,dValue = col / 2,srcDValue = colStride / 2 | ||
| 125 | + nd2nzPara.dValue = col; // nd矩阵的列数 | ||
| 126 | + nd2nzPara.srcDValue = colStride; // 同一nd矩阵相邻行起始地址间的偏移 | ||
| 127 | + nd2nzPara.dstNzC0Stride = rowAlign; | ||
| 128 | + nd2nzPara.dstNzNStride = 1; | ||
| 129 | + nd2nzPara.srcNdMatrixStride = 0; | ||
| 130 | + nd2nzPara.dstNzMatrixStride = 0; | ||
| 131 | + DataCopy(l1Tensor, gmTensor, nd2nzPara); | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/* | ||
| 135 | + 适用PA数据从GM拷贝到L1,支持ND、NZ数据; | ||
| 136 | + PA的layout分 BNBD(blockNum,N,blockSize,D) BBH(blockNum,blockSize,N*D | ||
| 137 | + BSH\BSND\TND 为BBH | ||
| 138 | + shape.copyRowNumAlign 需要16字节对齐,如拷贝k矩阵,一次拷贝128*512,遇到尾块 10*512 需对齐到16*512 | ||
| 139 | +*/ | ||
| 140 | +template <typename T, SAS_LAYOUT SRC_LAYOUT = SAS_LAYOUT::PA_BSND> | ||
| 141 | +__aicore__ inline void DataCopyPA(LocalTensor<T> &dstTensor, // l1 | ||
| 142 | + GlobalTensor<T> &srcTensor, // gm | ||
| 143 | + GlobalTensor<int32_t> &blockTableGm, | ||
| 144 | + const PAShape &shape, // blockSize, headNum, headDim | ||
| 145 | + const Position &startPos) // bacthIdx nIdx curSeqIdx | ||
| 146 | +{ | ||
| 147 | + uint32_t copyFinishRowCnt = 0; | ||
| 148 | + uint64_t blockTableBaseOffset = startPos.bIdx * shape.maxblockNumPerBatch; | ||
| 149 | + uint32_t curS2Idx = startPos.s2Idx; | ||
| 150 | + uint32_t blockElementCnt = 32 / sizeof(T); | ||
| 151 | + while (copyFinishRowCnt < shape.copyRowNum) { | ||
| 152 | + uint64_t blockIdOffset = curS2Idx / shape.blockSize; // 获取block table上的索引 | ||
| 153 | + uint64_t reaminRowCnt = curS2Idx % shape.blockSize; // 获取在单个块上超出的行数 | ||
| 154 | + uint64_t idInBlockTable = | ||
| 155 | + blockTableGm.GetValue(blockTableBaseOffset + blockIdOffset); // 从block table上的获取编号 | ||
| 156 | + uint32_t copyRowCnt = shape.blockSize - reaminRowCnt; // 一次只能处理一个Block | ||
| 157 | + if (copyFinishRowCnt + copyRowCnt > shape.copyRowNum) { | ||
| 158 | + copyRowCnt = shape.copyRowNum - copyFinishRowCnt; // 一个block未拷满 | ||
| 159 | + } | ||
| 160 | + // uint64_t offset = idInBlockTable * shape.blockSize * shape.headNum * shape.headDim; // PA的偏移 | ||
| 161 | + uint64_t offset = idInBlockTable * shape.kvStride; // PA的偏移 | ||
| 162 | + uint64_t dStride = shape.headDim; | ||
| 163 | + if constexpr (SRC_LAYOUT == SAS_LAYOUT::BSND || SRC_LAYOUT == SAS_LAYOUT::TND || | ||
| 164 | + SRC_LAYOUT == SAS_LAYOUT::PA_BSND) { | ||
| 165 | + offset += (uint64_t)(startPos.n2Idx * shape.headDim) + reaminRowCnt * shape.headDim * shape.headNum + | ||
| 166 | + startPos.dIdx; | ||
| 167 | + dStride = shape.headDim * shape.headNum; | ||
| 168 | + } else { | ||
| 169 | + offset += (uint64_t)(startPos.n2Idx * shape.headDim * shape.blockSize) + reaminRowCnt * shape.headDim + | ||
| 170 | + startPos.dIdx; | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + uint32_t dValue = shape.actHeadDim; | ||
| 174 | + uint32_t srcDValue = dStride; | ||
| 175 | + LocalTensor<T> tmpDstTensor = dstTensor[copyFinishRowCnt * blockElementCnt]; | ||
| 176 | + GlobalTensor<T> tmpSrcTensor = srcTensor[offset]; | ||
| 177 | + | ||
| 178 | + DataCopyGmNDToL1<T>(tmpDstTensor, tmpSrcTensor, copyRowCnt, shape.copyRowNumAlign, dValue, srcDValue); | ||
| 179 | + copyFinishRowCnt += copyRowCnt; | ||
| 180 | + curS2Idx += copyRowCnt; | ||
| 181 | + } | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +struct RunInfo { | ||
| 185 | + uint32_t loop = 0; | ||
| 186 | + uint32_t cmpLoop = 0; // 用于判断取 用于merge的4块GM 中的哪一块 | ||
| 187 | + uint32_t bIdx = 0; | ||
| 188 | + uint32_t gIdx = 0; | ||
| 189 | + uint32_t s1Idx = 0; | ||
| 190 | + uint32_t s2Idx = 0; | ||
| 191 | + uint32_t n2IdxReal = 0; | ||
| 192 | + uint32_t relativeS2Idx = 0; | ||
| 193 | + uint32_t bn2IdxInCurCore = 0; | ||
| 194 | + uint32_t curSInnerLoopTimes = 0; | ||
| 195 | + uint64_t tndBIdxOffsetForQ = 0; | ||
| 196 | + uint64_t tndBIdxOffsetForKV = 0; | ||
| 197 | + uint64_t tensorCmpBOffset = 0; | ||
| 198 | + uint64_t tensorAOffset = 0; | ||
| 199 | + uint64_t tensorBOffset = 0; | ||
| 200 | + uint64_t attenOutOffset = 0; | ||
| 201 | + uint64_t attenMaskOffset = 0; | ||
| 202 | + uint64_t topKBaseOffset = 0; | ||
| 203 | + uint32_t actualSingleProcessSInnerSize = 0; | ||
| 204 | + uint32_t actualSingleProcessSInnerSizeAlign = 0; | ||
| 205 | + uint32_t actualSingleProcessSInnerOriSize = 0; | ||
| 206 | + uint32_t actualSingleProcessSInnerOriAlignSize = 0; | ||
| 207 | + uint32_t actualSingleProcessSInnerCmpSize = 0; | ||
| 208 | + uint32_t actualSingleProcessSInnerCmpAlignSize = 0; | ||
| 209 | + uint32_t s2BatchOffset = 0; | ||
| 210 | + uint32_t gSize = 0; | ||
| 211 | + uint32_t s1Size = 0; | ||
| 212 | + uint32_t s2Size = 0; | ||
| 213 | + uint32_t mSize = 0; | ||
| 214 | + uint32_t mSizeV = 0; | ||
| 215 | + uint32_t mSizeVStart = 0; | ||
| 216 | + uint32_t tndIsS2SplitCore = 0; | ||
| 217 | + uint32_t tndCoreStartKVSplitPos = 0; | ||
| 218 | + bool isFirstSInnerLoop = false; | ||
| 219 | + bool isBmm2Output = false; | ||
| 220 | + bool isValid = false; | ||
| 221 | + bool isLastS2Loop = 0; | ||
| 222 | + int64_t inValidRowCount = 0; | ||
| 223 | + | ||
| 224 | + uint64_t actS1Size = 1; | ||
| 225 | + uint64_t actS2SizeOri = 0ULL; | ||
| 226 | + static constexpr uint32_t n2Idx = 0; | ||
| 227 | + uint32_t gS1Idx = 0; | ||
| 228 | + uint64_t actS2Size = 1; | ||
| 229 | + uint64_t actOriS2Size = 1; | ||
| 230 | + uint32_t actMBaseSize = 0; | ||
| 231 | + int32_t nextTokensPerBatch = 0; | ||
| 232 | + int64_t threshold = 0; | ||
| 233 | + uint64_t curOffsetInSparseBlock = 0; | ||
| 234 | + uint32_t curTopKIdx = 0; | ||
| 235 | + bool isOriOnly = true; // 判断当前块是在Ori部分还是Cmp部分 | ||
| 236 | + bool isOriCmpMix = false; | ||
| 237 | + uint8_t resv[2]; | ||
| 238 | + uint64_t s2StartPoint = 0; | ||
| 239 | + int64_t cmpS2IdStart = 0; | ||
| 240 | + int64_t cmpS2IdLimit = 0; | ||
| 241 | + int32_t v0S2DealSize = 0; | ||
| 242 | + int32_t v0S2Start = 0; | ||
| 243 | + uint32_t oriDealSize = 0; | ||
| 244 | + int32_t cmpMaskRight = 0; | ||
| 245 | +}; | ||
| 246 | + | ||
| 247 | +struct ConstInfo { | ||
| 248 | + // CUBE与VEC核间同步的模式 | ||
| 249 | + static constexpr uint32_t SAS_SYNC_MODE2 = 2; | ||
| 250 | + // BUFFER的字节数 | ||
| 251 | + static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; | ||
| 252 | + static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; | ||
| 253 | + static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; | ||
| 254 | + static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; | ||
| 255 | + static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; | ||
| 256 | + static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; | ||
| 257 | + static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; | ||
| 258 | + static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; | ||
| 259 | + static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; | ||
| 260 | + static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; | ||
| 261 | + // FP32的0值和极大值 | ||
| 262 | + static constexpr float FLOAT_ZERO = 0; | ||
| 263 | + static constexpr float FLOAT_MAX = 3.402823466e+38F; | ||
| 264 | + | ||
| 265 | + // preLoad的总次数 | ||
| 266 | + uint32_t preLoadNum = 0U; | ||
| 267 | + uint32_t nBufferMBaseSize = 0U; | ||
| 268 | + // CUBE和VEC的核间同步EventID | ||
| 269 | + uint32_t syncV0C1 = 0U; | ||
| 270 | + uint32_t syncC1V1 = 0U; | ||
| 271 | + uint32_t syncV1C2 = 0U; | ||
| 272 | + uint32_t syncC2V2 = 0U; | ||
| 273 | + | ||
| 274 | + uint32_t mmResUbSize = 0U; // Matmul1输出结果GM上的大小 | ||
| 275 | + uint32_t vec1ResUbSize = 0U; // Vector1输出结果GM上的大小 | ||
| 276 | + uint32_t bmm2ResUbSize = 0U; // Matmul2输出结果GM上的大小 | ||
| 277 | + uint64_t batchSize = 0ULL; | ||
| 278 | + uint64_t gSize = 0ULL; | ||
| 279 | + uint64_t qHeadNum = 0ULL; | ||
| 280 | + uint64_t kvHeadNum = 0; | ||
| 281 | + uint64_t headDim = 0; | ||
| 282 | + uint64_t kvSeqSize = 0ULL; // kv最大S长度 | ||
| 283 | + uint64_t qSeqSize = 1ULL; // q最大S长度 | ||
| 284 | + int64_t kvCacheBlockSize = 0; // PA场景的block size | ||
| 285 | + uint64_t paCmpBlockSize = 0; | ||
| 286 | + uint64_t paOriBlockSize = 0; | ||
| 287 | + int64_t orikvCacheBlockSize = 0; | ||
| 288 | + int64_t cmpkvCacheBlockSize = 0; | ||
| 289 | + uint32_t oriMaxBlockNumPerBatch = 0; // PA场景的最大单batch block number | ||
| 290 | + uint32_t cmpMaxBlockNumPerBatch = 0; | ||
| 291 | + uint32_t splitKVNum = 0U; // S2核间切分的切分份数 | ||
| 292 | + SAS_LAYOUT outputLayout; // 输出的Transpose格式 | ||
| 293 | + uint32_t oriMaskMode = 0; | ||
| 294 | + uint32_t cmpMaskMode = 0; | ||
| 295 | + uint64_t oriKvStride0 = 0; | ||
| 296 | + uint64_t cmpKvStride0 = 0; | ||
| 297 | + uint32_t kvQuantMode = 0; | ||
| 298 | + bool needInit = false; | ||
| 299 | + uint32_t templateMode = 0; | ||
| 300 | + | ||
| 301 | + // FlashDecoding | ||
| 302 | + uint32_t actualCombineLoopSize = 0U; // FlashDecoding场景, S2在核间切分的最大份数 | ||
| 303 | + uint64_t combineLseOffset = 0ULL; | ||
| 304 | + uint64_t combineAccumOutOffset = 0ULL; | ||
| 305 | + | ||
| 306 | + uint32_t actualLenDimsQ = 0U; // query的actualSeqLength 的维度 | ||
| 307 | + uint32_t actualLenDimsKV = 0U; // KV 的actualSeqLength 的维度 | ||
| 308 | + | ||
| 309 | + // TND | ||
| 310 | + uint32_t s2Start = 0U; // TND场景下,S2的起始位置 | ||
| 311 | + uint32_t s2End = 0U; // 单核TND场景下S2循环index上限 | ||
| 312 | + | ||
| 313 | + uint32_t bN2Start = 0U; | ||
| 314 | + uint32_t bN2End = 0U; | ||
| 315 | + uint32_t gS1Start = 0U; | ||
| 316 | + uint32_t gS1End = 0U; | ||
| 317 | + | ||
| 318 | + uint32_t tndFDCoreArrLen = 0U; // TNDFlashDecoding相关分核信息array的长度 | ||
| 319 | + uint32_t coreStartKVSplitPos = 0U; // TNDFlashDecoding kv起始位置 | ||
| 320 | + | ||
| 321 | + uint32_t mBaseSize = 1ULL; | ||
| 322 | + uint32_t s2BaseSize = 1ULL; | ||
| 323 | + | ||
| 324 | + // sparse attr | ||
| 325 | + int64_t sparseBlockSize = 0; | ||
| 326 | + uint32_t sparseBlockCount = 0; | ||
| 327 | + | ||
| 328 | + // cmp attr | ||
| 329 | + int64_t cmpRatio = 0; | ||
| 330 | + | ||
| 331 | + // win | ||
| 332 | + int32_t oriWinRight = 0; | ||
| 333 | + int32_t oriWinLeft = 128; | ||
| 334 | + | ||
| 335 | + bool returnSoftmaxLse = false; | ||
| 336 | +}; | ||
| 337 | + | ||
| 338 | +constexpr uint32_t TQ4_HEAD_DIM = 512U; | ||
| 339 | +constexpr uint32_t TQ4_PACKED_BYTES = 256U; | ||
| 340 | +constexpr uint32_t TQ4_SCALE_BYTES = sizeof(half); | ||
| 341 | +constexpr uint32_t TQ4_SLOT_BYTES = TQ4_PACKED_BYTES + TQ4_SCALE_BYTES; | ||
| 342 | +constexpr uint32_t TQ4_SLOT_ROW_BYTES = (TQ4_SLOT_BYTES + 31U) / 32U * 32U; | ||
| 343 | +constexpr float TQ4_CENTROID_BYTE_STRIDE = 4.0F; | ||
| 344 | +constexpr uint32_t TQ4_CENTROID_INDEX_2 = 2U; | ||
| 345 | +constexpr uint32_t TQ4_CENTROID_INDEX_3 = 3U; | ||
| 346 | +constexpr uint32_t TQ4_CENTROID_INDEX_4 = 4U; | ||
| 347 | +constexpr uint32_t TQ4_CENTROID_INDEX_5 = 5U; | ||
| 348 | +constexpr uint32_t TQ4_CENTROID_INDEX_6 = 6U; | ||
| 349 | +constexpr uint32_t TQ4_CENTROID_INDEX_7 = 7U; | ||
| 350 | +constexpr uint32_t TQ4_CENTROID_INDEX_8 = 8U; | ||
| 351 | +constexpr uint32_t TQ4_CENTROID_INDEX_9 = 9U; | ||
| 352 | +constexpr uint32_t TQ4_CENTROID_INDEX_10 = 10U; | ||
| 353 | +constexpr uint32_t TQ4_CENTROID_INDEX_11 = 11U; | ||
| 354 | +constexpr uint32_t TQ4_CENTROID_INDEX_12 = 12U; | ||
| 355 | +constexpr uint32_t TQ4_CENTROID_INDEX_13 = 13U; | ||
| 356 | +constexpr uint32_t TQ4_CENTROID_INDEX_14 = 14U; | ||
| 357 | +constexpr uint32_t TQ4_CENTROID_INDEX_15 = 15U; | ||
| 358 | + | ||
| 359 | +__aicore__ inline void LoadTq4Centroids(LocalTensor<float> centroids) | ||
| 360 | +{ | ||
| 361 | + centroids.SetValue(0, 0.00547294f); | ||
| 362 | + centroids.SetValue(1, 0.01680406f); | ||
| 363 | + centroids.SetValue(TQ4_CENTROID_INDEX_2, 0.02857605f); | ||
| 364 | + centroids.SetValue(TQ4_CENTROID_INDEX_3, 0.04108622f); | ||
| 365 | + centroids.SetValue(TQ4_CENTROID_INDEX_4, 0.05492980f); | ||
| 366 | + centroids.SetValue(TQ4_CENTROID_INDEX_5, 0.07101817f); | ||
| 367 | + centroids.SetValue(TQ4_CENTROID_INDEX_6, 0.09115373f); | ||
| 368 | + centroids.SetValue(TQ4_CENTROID_INDEX_7, 0.12037795f); | ||
| 369 | + centroids.SetValue(TQ4_CENTROID_INDEX_8, -0.12091285f); | ||
| 370 | + centroids.SetValue(TQ4_CENTROID_INDEX_9, -0.09111122f); | ||
| 371 | + centroids.SetValue(TQ4_CENTROID_INDEX_10, -0.07112455f); | ||
| 372 | + centroids.SetValue(TQ4_CENTROID_INDEX_11, -0.05513602f); | ||
| 373 | + centroids.SetValue(TQ4_CENTROID_INDEX_12, -0.04132067f); | ||
| 374 | + centroids.SetValue(TQ4_CENTROID_INDEX_13, -0.02874970f); | ||
| 375 | + centroids.SetValue(TQ4_CENTROID_INDEX_14, -0.01700489f); | ||
| 376 | + centroids.SetValue(TQ4_CENTROID_INDEX_15, -0.00568677f); | ||
| 377 | + PipeBarrier<PIPE_ALL>(); | ||
| 378 | +} | ||
| 379 | + | ||
| 380 | +struct MSplitInfo { | ||
| 381 | + uint32_t nBufferIdx = 0U; | ||
| 382 | + uint32_t nBufferStartM = 0U; | ||
| 383 | + uint32_t nBufferDealM = 0U; | ||
| 384 | + uint32_t vecStartM = 0U; | ||
| 385 | + uint32_t vecDealM = 0U; | ||
| 386 | +}; | ||
| 387 | +} // namespace SASKernel | ||
| 388 | +#endif // MIXED_QUANT_SPARSE_FLASH_MLA_TQ_COMMON_H | ||
Aattention/mixed_quant_sparse_flash_mla/op_kernel/arch22/mixed_quant_sparse_flash_mla_tq_csa_kernel.h+848-0
Rattention/mixed_quant_sparse_flash_mla/op_kernel/mixed_quant_sparse_flash_mla_common.h→attention/mixed_quant_sparse_flash_mla/op_kernel/arch35/mixed_quant_sparse_flash_mla_common.h+1-1
| @@ -24,7 +24,7 @@ | |||
| 24 | #endif | 24 | #endif |
| 25 | #include "lib/matmul_intf.h" | 25 | #include "lib/matmul_intf.h" |
| 26 | #include "lib/matrix/matmul/tiling.h" | 26 | #include "lib/matrix/matmul/tiling.h" |
| 27 | -#include "mixed_quant_sparse_flash_mla_metadata.h" | 27 | +#include "../mixed_quant_sparse_flash_mla_metadata.h" |
| 28 | 28 | ||
| 29 | using namespace AscendC; | 29 | using namespace AscendC; |
| 30 | 30 | ||
Mattention/mixed_quant_sparse_flash_mla/op_kernel/arch35/mixed_quant_sparse_flash_mla_common_arch35.h+1-1
| @@ -16,7 +16,7 @@ | |||
| 16 | #define MIXED_QUANT_SPARSE_FLASH_MLA_COMMON_ARCH35_H | 16 | #define MIXED_QUANT_SPARSE_FLASH_MLA_COMMON_ARCH35_H |
| 17 | #include <type_traits> | 17 | #include <type_traits> |
| 18 | #include "kernel_tiling/kernel_tiling.h" | 18 | #include "kernel_tiling/kernel_tiling.h" |
| 19 | -#include "../mixed_quant_sparse_flash_mla_common.h" | 19 | +#include "mixed_quant_sparse_flash_mla_common.h" |
| 20 | #include "../../../sparse_flash_mla/op_kernel/arch35/common/static_buffer.h" | 20 | #include "../../../sparse_flash_mla/op_kernel/arch35/common/static_buffer.h" |
| 21 | #include "../../../sparse_flash_mla/op_kernel/arch35/common/smla_common_defs.h" | 21 | #include "../../../sparse_flash_mla/op_kernel/arch35/common/smla_common_defs.h" |
| 22 | 22 | ||
Mattention/mixed_quant_sparse_flash_mla/op_kernel/arch35/mixed_quant_sparse_flash_mla_csa_kernel.h+1-0
| @@ -15,6 +15,7 @@ | |||
| 15 | 15 | ||
| 16 | #ifndef MIXED_QUANT_SPARSE_FLASH_MLA_CSA_KERNEL_H | 16 | #ifndef MIXED_QUANT_SPARSE_FLASH_MLA_CSA_KERNEL_H |
| 17 | #define MIXED_QUANT_SPARSE_FLASH_MLA_CSA_KERNEL_H | 17 | #define MIXED_QUANT_SPARSE_FLASH_MLA_CSA_KERNEL_H |
| 18 | +#include "mixed_quant_sparse_flash_mla_tiling_data_arch35.h" | ||
| 18 | #include "mixed_quant_sparse_flash_mla_common_arch35.h" | 19 | #include "mixed_quant_sparse_flash_mla_common_arch35.h" |
| 19 | #include "mixed_quant_sparse_flash_mla_kvcache.h" | 20 | #include "mixed_quant_sparse_flash_mla_kvcache.h" |
| 20 | #include "mixed_quant_sparse_flash_mla_csa_block_cube.h" | 21 | #include "mixed_quant_sparse_flash_mla_csa_block_cube.h" |
Rattention/mixed_quant_sparse_flash_mla/op_kernel/mixed_quant_sparse_flash_mla_template_tiling_key.h→attention/mixed_quant_sparse_flash_mla/op_kernel/arch35/mixed_quant_sparse_flash_mla_template_tiling_key_arch35.h+12-12
| @@ -1,20 +1,20 @@ | |||
| 1 | /** | 1 | /** |
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | 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 | 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"). | 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. | 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, | 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. | 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. | 8 | + * See LICENSE in the root of the software repository for the full text of the License. |
| 9 | -*/ | 9 | + */ |
| 10 | 10 | ||
| 11 | /*! | 11 | /*! |
| 12 | - * \file mixed_quant_sparse_flash_mla_template_tiling_key.h | 12 | + * \file mixed_quant_sparse_flash_mla_template_tiling_key_arch35.h |
| 13 | * \brief | 13 | * \brief |
| 14 | */ | 14 | */ |
| 15 | 15 | ||
| 16 | -#ifndef MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_H | 16 | +#ifndef MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_ARCH35_H |
| 17 | -#define MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_H | 17 | +#define MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_ARCH35_H |
| 18 | 18 | ||
| 19 | #include "ascendc/host_api/tiling/template_argument.h" | 19 | #include "ascendc/host_api/tiling/template_argument.h" |
| 20 | 20 | ||
| @@ -76,4 +76,4 @@ ASCENDC_TPL_SEL( | |||
| 76 | ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), | 76 | ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), |
| 77 | ASCENDC_TPL_BOOL_SEL(HIGH_PERF, 0, 1), ), ); | 77 | ASCENDC_TPL_BOOL_SEL(HIGH_PERF, 0, 1), ), ); |
| 78 | 78 | ||
| 79 | -#endif // MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_H | 79 | +#endif // MIXED_QUANT_SPARSE_FLASH_MLA_TEMPLATE_TILING_KEY_ARCH35_H |
| @@ -0,0 +1,56 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file mixed_quant_sparse_flash_mla_tiling_data_arch35.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef MIXED_QUANT_SPARSE_FLASH_MLA_ARCH35_TILING_DATA_H | ||
| 17 | +#define MIXED_QUANT_SPARSE_FLASH_MLA_ARCH35_TILING_DATA_H | ||
| 18 | + | ||
| 19 | +#include <cstdint> | ||
| 20 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 21 | + | ||
| 22 | +namespace optiling { | ||
| 23 | +struct MixedQuantSparseFlashMlaBaseParams { | ||
| 24 | + uint32_t batchSize; | ||
| 25 | + uint32_t qSeqSize; | ||
| 26 | + uint32_t kvSeqSize; | ||
| 27 | + uint32_t cmpKvSeqSize; | ||
| 28 | + uint32_t paOriBlockSize; | ||
| 29 | + uint32_t paCmpBlockSize; | ||
| 30 | + uint32_t oriMaxBlockNumPerBatch; | ||
| 31 | + uint32_t cmpMaxBlockNumPerBatch; | ||
| 32 | + uint32_t nNumOfQInOneGroup; | ||
| 33 | + uint32_t oriSparseBlockCount; | ||
| 34 | + uint32_t cmpSparseBlockCount; | ||
| 35 | + float softmaxScale; | ||
| 36 | + int32_t oriKvStride; | ||
| 37 | + int32_t cmpKvStride; | ||
| 38 | + uint32_t tileSize; | ||
| 39 | + uint32_t ropeHeadDim; | ||
| 40 | + uint32_t cmpRatio; | ||
| 41 | + uint32_t oriMaskMode; | ||
| 42 | + uint32_t cmpMaskMode; | ||
| 43 | + int32_t oriWinLeft; | ||
| 44 | + int32_t oriWinRight; | ||
| 45 | + uint32_t sparseBlockSize; | ||
| 46 | + uint32_t dSize; | ||
| 47 | + uint32_t dSizeVInput; | ||
| 48 | + uint32_t returnSoftmaxLse; | ||
| 49 | +}; | ||
| 50 | + | ||
| 51 | +struct MixedQuantSparseFlashMlaTilingData { | ||
| 52 | + MixedQuantSparseFlashMlaBaseParams baseParams; | ||
| 53 | +}; | ||
| 54 | +} // namespace optiling | ||
| 55 | + | ||
| 56 | +#endif // MIXED_QUANT_SPARSE_FLASH_MLA_ARCH35_TILING_DATA_H | ||
| @@ -13,6 +13,7 @@ | |||
| 13 | * \brief | 13 | * \brief |
| 14 | */ | 14 | */ |
| 15 | 15 | ||
| 16 | +#if (__CCE_AICORE__ == 310) | ||
| 16 | #if ASC_DEVKIT_MAJOR >= 9 | 17 | #if ASC_DEVKIT_MAJOR >= 9 |
| 17 | #include "kernel_vec_intf.h" | 18 | #include "kernel_vec_intf.h" |
| 18 | #include "kernel_cube_intf.h" | 19 | #include "kernel_cube_intf.h" |
| @@ -20,12 +21,21 @@ | |||
| 20 | #include "kernel_operator.h" | 21 | #include "kernel_operator.h" |
| 21 | #endif | 22 | #endif |
| 22 | #include "lib/matmul_intf.h" | 23 | #include "lib/matmul_intf.h" |
| 23 | -#include "mixed_quant_sparse_flash_mla_template_tiling_key.h" | 24 | +#include "arch35/mixed_quant_sparse_flash_mla_template_tiling_key_arch35.h" |
| 24 | #include "arch35/mixed_quant_sparse_flash_mla_csa_kernel.h" | 25 | #include "arch35/mixed_quant_sparse_flash_mla_csa_kernel.h" |
| 25 | -#include "mixed_quant_sparse_flash_mla_common.h" | 26 | +#include "arch35/mixed_quant_sparse_flash_mla_common.h" |
| 27 | +#else | ||
| 28 | +#include "kernel_vec_intf.h" | ||
| 29 | +#include "kernel_cube_intf.h" | ||
| 30 | +#include "lib/matmul_intf.h" | ||
| 31 | +#include "arch22/mixed_quant_sparse_flash_mla_template_tiling_key_arch22.h" | ||
| 32 | +#include "arch22/mixed_quant_sparse_flash_mla_tq_csa_kernel.h" | ||
| 33 | +#include "mixed_quant_sparse_flash_mla_metadata.h" | ||
| 34 | +#endif | ||
| 26 | 35 | ||
| 27 | using namespace AscendC; | 36 | using namespace AscendC; |
| 28 | 37 | ||
| 38 | +#if (__CCE_AICORE__ == 310) | ||
| 29 | #define QSMLA_OP_IMPL(templateClass, tilingdataClass, ...) \ | 39 | #define QSMLA_OP_IMPL(templateClass, tilingdataClass, ...) \ |
| 30 | do { \ | 40 | do { \ |
| 31 | using CubeBlockType = \ | 41 | using CubeBlockType = \ |
| @@ -42,6 +52,18 @@ using namespace AscendC; | |||
| 42 | cmpTopkLength, sinks, metadata, attentionOut, softmax_lse, user, tilingData); \ | 52 | cmpTopkLength, sinks, metadata, attentionOut, softmax_lse, user, tilingData); \ |
| 43 | op.Process(); \ | 53 | op.Process(); \ |
| 44 | } while (0) | 54 | } while (0) |
| 55 | +#else | ||
| 56 | +#define QSMLA_TQ_OP_IMPL(templateClass, tilingdataClass, ...) \ | ||
| 57 | + do { \ | ||
| 58 | + templateClass<SASKernel::SASType<__VA_ARGS__>> op; \ | ||
| 59 | + GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tilingDataIn, tiling); \ | ||
| 60 | + const tilingdataClass *__restrict tilingData = &tilingDataIn; \ | ||
| 61 | + op.Init(query, oriKV, cmpKV, oriSparseIndices, cmpSparseIndices, oriBlockTable, cmpBlockTable, cuSeqlensQ, \ | ||
| 62 | + cuSeqlensOriKv, cuSeqlensCmpKv, seqUsedQ, sequsedOriKv, sequsedCmpKv, cmpResidualKv, oriTopkLength, \ | ||
| 63 | + cmpTopkLength, sinks, metadata, attentionOut, softmax_lse, user, tilingData, tiling, &tPipe); \ | ||
| 64 | + op.Process(); \ | ||
| 65 | + } while (0) | ||
| 66 | +#endif | ||
| 45 | 67 | ||
| 46 | template <int FLASH_DECODE, int LAYOUT_T, int KV_LAYOUT_T, int TEMPLATE_MODE, int SPLIT_G, int QUANT_MODE, int KV_DTYPE, | 68 | template <int FLASH_DECODE, int LAYOUT_T, int KV_LAYOUT_T, int TEMPLATE_MODE, int SPLIT_G, int QUANT_MODE, int KV_DTYPE, |
| 47 | int BATCH_CONSISTENCY, int IS_VEC_S2PHYADDR, int HIGH_PERF> | 69 | int BATCH_CONSISTENCY, int IS_VEC_S2PHYADDR, int HIGH_PERF> |
| @@ -53,9 +75,15 @@ __global__ __aicore__ void mixed_quant_sparse_flash_mla( | |||
| 53 | __gm__ uint8_t *oriTopkLength, __gm__ uint8_t *cmpTopkLength, __gm__ uint8_t *sinks, __gm__ uint8_t *metadata, | 75 | __gm__ uint8_t *oriTopkLength, __gm__ uint8_t *cmpTopkLength, __gm__ uint8_t *sinks, __gm__ uint8_t *metadata, |
| 54 | __gm__ uint8_t *attentionOut, __gm__ uint8_t *softmax_lse, __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) | 76 | __gm__ uint8_t *attentionOut, __gm__ uint8_t *softmax_lse, __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) |
| 55 | { | 77 | { |
| 78 | +#if (__CCE_AICORE__ == 310) | ||
| 79 | + REGISTER_TILING_DEFAULT(optiling::MixedQuantSparseFlashMlaTilingData); | ||
| 80 | +#else | ||
| 81 | + REGISTER_TILING_DEFAULT(optiling::MixedQuantSparseFlashMlaTqTilingData); | ||
| 82 | +#endif | ||
| 56 | KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | 83 | KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); |
| 57 | __gm__ uint8_t *user = GetUserWorkspace(workspace); | 84 | __gm__ uint8_t *user = GetUserWorkspace(workspace); |
| 58 | 85 | ||
| 86 | +#if (__CCE_AICORE__ == 310) | ||
| 59 | if constexpr (KV_DTYPE == DTYPE_FP8_E4M3FN) { | 87 | if constexpr (KV_DTYPE == DTYPE_FP8_E4M3FN) { |
| 60 | QSMLA_OP_IMPL(BaseApi::MixedQuantSparseFlashMlaCsa, MixedQuantSparseFlashMlaTilingData, bfloat16_t, | 88 | QSMLA_OP_IMPL(BaseApi::MixedQuantSparseFlashMlaCsa, MixedQuantSparseFlashMlaTilingData, bfloat16_t, |
| 61 | fp8_e4m3fn_t, float, bfloat16_t, FLASH_DECODE, KV_LAYOUT_T == QSMLA_LAYOUT_PA_BBND, | 89 | fp8_e4m3fn_t, float, bfloat16_t, FLASH_DECODE, KV_LAYOUT_T == QSMLA_LAYOUT_PA_BBND, |
| @@ -69,4 +97,23 @@ __global__ __aicore__ void mixed_quant_sparse_flash_mla( | |||
| 69 | static_cast<QSMLATemplateMode>(TEMPLATE_MODE), SPLIT_G, | 97 | static_cast<QSMLATemplateMode>(TEMPLATE_MODE), SPLIT_G, |
| 70 | static_cast<SCALE_CONTIGUOUS_MODE>(QUANT_MODE), BATCH_CONSISTENCY, IS_VEC_S2PHYADDR, HIGH_PERF); | 98 | static_cast<SCALE_CONTIGUOUS_MODE>(QUANT_MODE), BATCH_CONSISTENCY, IS_VEC_S2PHYADDR, HIGH_PERF); |
| 71 | } | 99 | } |
| 100 | +#else | ||
| 101 | + TPipe tPipe; | ||
| 102 | + if constexpr (QUANT_MODE == TURBO_QUANT && TEMPLATE_MODE == CSA_TEMPLATE) { | ||
| 103 | + if constexpr (ORIG_DTYPE_Q == DT_FLOAT16 && ORIG_DTYPE_ORI_KV == DT_FLOAT16 && ORIG_DTYPE_CMP_KV == DT_UINT8 && | ||
| 104 | + ORIG_DTYPE_ATTN_OUT == DT_FLOAT16) { | ||
| 105 | + QSMLA_TQ_OP_IMPL(SASKernel::MixedQuantSparseFlashMlaTqCsaKernel, | ||
| 106 | + optiling::MixedQuantSparseFlashMlaTqTilingData, half, half, half, FLASH_DECODE, | ||
| 107 | + static_cast<SASKernel::SAS_LAYOUT>(LAYOUT_T), | ||
| 108 | + static_cast<SASKernel::SAS_LAYOUT>(KV_LAYOUT_T), CSA_TEMPLATE); | ||
| 109 | + } | ||
| 110 | + if constexpr (ORIG_DTYPE_Q == DT_BF16 && ORIG_DTYPE_ORI_KV == DT_BF16 && ORIG_DTYPE_CMP_KV == DT_UINT8 && | ||
| 111 | + ORIG_DTYPE_ATTN_OUT == DT_BF16) { | ||
| 112 | + QSMLA_TQ_OP_IMPL(SASKernel::MixedQuantSparseFlashMlaTqCsaKernel, | ||
| 113 | + optiling::MixedQuantSparseFlashMlaTqTilingData, bfloat16_t, bfloat16_t, bfloat16_t, | ||
| 114 | + FLASH_DECODE, static_cast<SASKernel::SAS_LAYOUT>(LAYOUT_T), | ||
| 115 | + static_cast<SASKernel::SAS_LAYOUT>(KV_LAYOUT_T), CSA_TEMPLATE); | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | +#endif | ||
| 72 | } | 119 | } |
| @@ -0,0 +1,334 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# -*- coding: UTF-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +import math | ||
| 14 | + | ||
| 15 | +import numpy as np | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +HEAD_DIM = 512 | ||
| 19 | +PACKED_BYTES = HEAD_DIM // 2 | ||
| 20 | +SLOT_BYTES = PACKED_BYTES + 2 | ||
| 21 | +SLOT_ROW_BYTES = 288 | ||
| 22 | +BF16_DEQUANT_BATCH_ROWS = 16 | ||
| 23 | +CENTROIDS = np.array( | ||
| 24 | + [ | ||
| 25 | + 0.00547294, | ||
| 26 | + 0.01680406, | ||
| 27 | + 0.02857605, | ||
| 28 | + 0.04108622, | ||
| 29 | + 0.05492980, | ||
| 30 | + 0.07101817, | ||
| 31 | + 0.09115373, | ||
| 32 | + 0.12037795, | ||
| 33 | + -0.12091285, | ||
| 34 | + -0.09111122, | ||
| 35 | + -0.07112455, | ||
| 36 | + -0.05513602, | ||
| 37 | + -0.04132067, | ||
| 38 | + -0.02874970, | ||
| 39 | + -0.01700489, | ||
| 40 | + -0.00568677, | ||
| 41 | + ], | ||
| 42 | + dtype=np.float32, | ||
| 43 | +) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _float32_to_bf16_bits(values): | ||
| 47 | + values = np.asarray(values, dtype=np.float32) | ||
| 48 | + bits = values.view(np.uint32) | ||
| 49 | + return ( | ||
| 50 | + (bits + np.uint32(0x7FFF) + ((bits >> np.uint32(16)) & np.uint32(1))) | ||
| 51 | + >> np.uint32(16) | ||
| 52 | + ).astype(np.uint16) | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def _bf16_bits_to_float32(values): | ||
| 56 | + bits = np.asarray(values, dtype=np.uint16).astype(np.uint32) << np.uint32(16) | ||
| 57 | + return bits.view(np.float32) | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _make_tq4_byte_lut(): | ||
| 61 | + physical_centroids = CENTROIDS[np.arange(16) ^ 8] | ||
| 62 | + centroid_bits = _float32_to_bf16_bits(physical_centroids).astype(np.uint32) | ||
| 63 | + packed_bytes = np.arange(256, dtype=np.uint32) | ||
| 64 | + low_bits = centroid_bits[packed_bytes & 0xF] | ||
| 65 | + high_bits = centroid_bits[packed_bytes >> 4] | ||
| 66 | + return (high_bits << np.uint32(16)) | low_bits | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def _dequant_byte_lut(slots, scales): | ||
| 70 | + byte_lut = _make_tq4_byte_lut() | ||
| 71 | + packed_pairs = byte_lut[slots[:, :PACKED_BYTES]].view(np.uint16) | ||
| 72 | + centroids = _bf16_bits_to_float32(packed_pairs.reshape(slots.shape[0], HEAD_DIM)) | ||
| 73 | + scaled = ( | ||
| 74 | + centroids * np.asarray(scales, dtype=np.float16).astype(np.float32)[:, None] | ||
| 75 | + ) | ||
| 76 | + return _float32_to_bf16_bits(scaled) | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +def _hadamard(order): | ||
| 80 | + matrix = np.ones((1, 1), dtype=np.float64) | ||
| 81 | + while matrix.shape[0] < order: | ||
| 82 | + matrix = np.block([[matrix, matrix], [matrix, -matrix]]) | ||
| 83 | + return matrix / math.sqrt(order) | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +def test_compact_slot_layout(): | ||
| 87 | + assert PACKED_BYTES == 256 | ||
| 88 | + assert SLOT_BYTES == 258 | ||
| 89 | + assert (1024 - SLOT_BYTES) / 1024 == 0.748046875 | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +def test_signed_nibble_centroid_order(): | ||
| 93 | + physical_codes = np.arange(16, dtype=np.int16) | ||
| 94 | + signed_codes = np.where(physical_codes < 8, physical_codes, physical_codes - 16) | ||
| 95 | + gather_indices = signed_codes + 8 | ||
| 96 | + np.testing.assert_array_equal(gather_indices, np.r_[8:16, 0:8]) | ||
| 97 | + assert np.all(np.diff(CENTROIDS[gather_indices]) > 0) | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def test_byte_lut_exhaustively_matches_two_bf16_centroid_lookups(): | ||
| 101 | + byte_lut = _make_tq4_byte_lut() | ||
| 102 | + packed_bytes = np.arange(256, dtype=np.uint32) | ||
| 103 | + physical_centroid_bits = _float32_to_bf16_bits(CENTROIDS[np.arange(16) ^ 8]) | ||
| 104 | + | ||
| 105 | + np.testing.assert_array_equal( | ||
| 106 | + (byte_lut & np.uint32(0xFFFF)).astype(np.uint16), | ||
| 107 | + physical_centroid_bits[packed_bytes & 0xF], | ||
| 108 | + ) | ||
| 109 | + np.testing.assert_array_equal( | ||
| 110 | + (byte_lut >> np.uint32(16)).astype(np.uint16), | ||
| 111 | + physical_centroid_bits[packed_bytes >> 4], | ||
| 112 | + ) | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +def test_byte_lut_dequant_handles_every_batch_tail(): | ||
| 116 | + rng = np.random.default_rng(6) | ||
| 117 | + for row_count in range(1, BF16_DEQUANT_BATCH_ROWS + 1): | ||
| 118 | + slots = np.zeros((row_count, SLOT_ROW_BYTES), dtype=np.uint8) | ||
| 119 | + slots[:, :PACKED_BYTES] = rng.integers( | ||
| 120 | + 0, 256, size=(row_count, PACKED_BYTES), dtype=np.uint8 | ||
| 121 | + ) | ||
| 122 | + scales = rng.uniform(0.125, 8.0, row_count).astype(np.float16) | ||
| 123 | + actual = _dequant_byte_lut(slots, scales) | ||
| 124 | + | ||
| 125 | + low_codes = slots[:, :PACKED_BYTES] & np.uint8(0xF) | ||
| 126 | + high_codes = slots[:, :PACKED_BYTES] >> np.uint8(4) | ||
| 127 | + codes = np.empty((row_count, HEAD_DIM), dtype=np.uint8) | ||
| 128 | + codes[:, 0::2] = low_codes | ||
| 129 | + codes[:, 1::2] = high_codes | ||
| 130 | + centroid_values = _bf16_bits_to_float32( | ||
| 131 | + _float32_to_bf16_bits(CENTROIDS[codes ^ np.uint8(8)]) | ||
| 132 | + ) | ||
| 133 | + expected = _float32_to_bf16_bits( | ||
| 134 | + centroid_values * scales.astype(np.float32)[:, None] | ||
| 135 | + ) | ||
| 136 | + np.testing.assert_array_equal(actual, expected) | ||
| 137 | + | ||
| 138 | + | ||
| 139 | +def test_byte_lut_scale_rounding_is_within_one_bf16_ulp_of_float_lut(): | ||
| 140 | + finite_fp16 = np.arange(1 << 16, dtype=np.uint16).view(np.float16) | ||
| 141 | + scales = finite_fp16[np.isfinite(finite_fp16)].astype(np.float32) | ||
| 142 | + bf16_centroids = _bf16_bits_to_float32(_float32_to_bf16_bits(CENTROIDS)) | ||
| 143 | + | ||
| 144 | + for centroid, bf16_centroid in zip(CENTROIDS, bf16_centroids): | ||
| 145 | + old_bits = _float32_to_bf16_bits(centroid * scales).astype(np.int32) | ||
| 146 | + optimized_bits = _float32_to_bf16_bits(bf16_centroid * scales).astype(np.int32) | ||
| 147 | + assert np.max(np.abs(old_bits - optimized_bits)) <= 1 | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +def test_corrected_scale_preserves_quantized_row_norm(): | ||
| 151 | + rng = np.random.default_rng(0) | ||
| 152 | + latent = rng.standard_normal(HEAD_DIM).astype(np.float32) | ||
| 153 | + unit = latent / np.linalg.norm(latent) | ||
| 154 | + ascending = np.sort(CENTROIDS) | ||
| 155 | + boundaries = (ascending[:-1] + ascending[1:]) * np.float32(0.5) | ||
| 156 | + ascending_codes = np.sum(unit[:, None] >= boundaries[None, :], axis=1) | ||
| 157 | + selected = ascending[ascending_codes] | ||
| 158 | + corrected_scale = np.linalg.norm(latent) / np.linalg.norm(selected) | ||
| 159 | + reconstructed = selected * corrected_scale | ||
| 160 | + np.testing.assert_allclose( | ||
| 161 | + np.linalg.norm(reconstructed), np.linalg.norm(latent), rtol=2e-7 | ||
| 162 | + ) | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +def test_shared_kv_attention_is_hadamard_basis_invariant(): | ||
| 166 | + rng = np.random.default_rng(1) | ||
| 167 | + transform = _hadamard(HEAD_DIM) | ||
| 168 | + signs = np.where(np.arange(HEAD_DIM) % 3 == 0, -1.0, 1.0) | ||
| 169 | + transform = signs[:, None] * transform | ||
| 170 | + query = rng.standard_normal((3, HEAD_DIM)) | ||
| 171 | + shared_kv = rng.standard_normal((7, HEAD_DIM)) | ||
| 172 | + scale = 1.0 / math.sqrt(HEAD_DIM) | ||
| 173 | + | ||
| 174 | + def attention(q, kv): | ||
| 175 | + scores = q @ kv.T * scale | ||
| 176 | + probabilities = np.exp(scores - scores.max(axis=-1, keepdims=True)) | ||
| 177 | + probabilities /= probabilities.sum(axis=-1, keepdims=True) | ||
| 178 | + return probabilities @ kv | ||
| 179 | + | ||
| 180 | + reference = attention(query, shared_kv) | ||
| 181 | + transformed = attention(query @ transform, shared_kv @ transform) @ transform.T | ||
| 182 | + np.testing.assert_allclose(transformed, reference, rtol=1e-10, atol=1e-10) | ||
| 183 | + | ||
| 184 | + | ||
| 185 | +def _attention_with_sinks(query, key, value, sinks): | ||
| 186 | + scores = query @ key.T / math.sqrt(query.shape[-1]) | ||
| 187 | + max_values = np.maximum(scores.max(axis=-1), sinks) | ||
| 188 | + score_exp = np.exp(scores - max_values[:, None]) | ||
| 189 | + sink_exp = np.exp(sinks - max_values) | ||
| 190 | + denominator = score_exp.sum(axis=-1) + sink_exp | ||
| 191 | + output = score_exp @ value / denominator[:, None] | ||
| 192 | + lse = np.log(denominator) + max_values | ||
| 193 | + return output, lse | ||
| 194 | + | ||
| 195 | + | ||
| 196 | +def _folded_shared_kv_attention(query, centroids, scales, sinks): | ||
| 197 | + scores = (query @ centroids.T) * scales[None, :] / math.sqrt(query.shape[-1]) | ||
| 198 | + max_values = np.maximum(scores.max(axis=-1), sinks) | ||
| 199 | + score_exp = np.exp(scores - max_values[:, None]) | ||
| 200 | + sink_exp = np.exp(sinks - max_values) | ||
| 201 | + denominator = score_exp.sum(axis=-1) + sink_exp | ||
| 202 | + probabilities = score_exp / denominator[:, None] | ||
| 203 | + output = (probabilities * scales[None, :]) @ centroids | ||
| 204 | + lse = np.log(denominator) + max_values | ||
| 205 | + return output, lse | ||
| 206 | + | ||
| 207 | + | ||
| 208 | +def test_attention_fold_is_equivalent_with_reordered_and_duplicate_rows(): | ||
| 209 | + rng = np.random.default_rng(2) | ||
| 210 | + query = rng.standard_normal((11, 32)) | ||
| 211 | + codebook_rows = rng.standard_normal((17, 32)) | ||
| 212 | + selected = np.array([8, 3, 8, 16, 1, 12, 0, 12, 5, 4, 9, 2, 15]) | ||
| 213 | + centroids = codebook_rows[selected] | ||
| 214 | + scales = np.exp(rng.uniform(np.log(2**-8), np.log(2**8), selected.size)) | ||
| 215 | + sinks = rng.standard_normal(query.shape[0]) | ||
| 216 | + | ||
| 217 | + reference = _attention_with_sinks( | ||
| 218 | + query, centroids * scales[:, None], centroids * scales[:, None], sinks | ||
| 219 | + ) | ||
| 220 | + folded = _folded_shared_kv_attention(query, centroids, scales, sinks) | ||
| 221 | + | ||
| 222 | + np.testing.assert_allclose(folded[0], reference[0], rtol=2e-12, atol=2e-12) | ||
| 223 | + np.testing.assert_allclose(folded[1], reference[1], rtol=2e-12, atol=2e-12) | ||
| 224 | + | ||
| 225 | + | ||
| 226 | +def test_attention_fold_preserves_original_and_compressed_regions(): | ||
| 227 | + rng = np.random.default_rng(3) | ||
| 228 | + query = rng.standard_normal((7, 24)) | ||
| 229 | + original = rng.standard_normal((9, 24)) | ||
| 230 | + compressed = rng.standard_normal((15, 24)) | ||
| 231 | + scales = np.exp(rng.uniform(np.log(2**-6), np.log(2**6), compressed.shape[0])) | ||
| 232 | + sinks = rng.standard_normal(query.shape[0]) | ||
| 233 | + | ||
| 234 | + scaled_compressed = compressed * scales[:, None] | ||
| 235 | + reference = _attention_with_sinks( | ||
| 236 | + query, | ||
| 237 | + np.concatenate((original, scaled_compressed)), | ||
| 238 | + np.concatenate((original, scaled_compressed)), | ||
| 239 | + sinks, | ||
| 240 | + ) | ||
| 241 | + | ||
| 242 | + original_scores = query @ original.T / math.sqrt(query.shape[-1]) | ||
| 243 | + compressed_scores = ( | ||
| 244 | + (query @ compressed.T) * scales[None, :] / math.sqrt(query.shape[-1]) | ||
| 245 | + ) | ||
| 246 | + scores = np.concatenate((original_scores, compressed_scores), axis=-1) | ||
| 247 | + max_values = np.maximum(scores.max(axis=-1), sinks) | ||
| 248 | + score_exp = np.exp(scores - max_values[:, None]) | ||
| 249 | + denominator = score_exp.sum(axis=-1) + np.exp(sinks - max_values) | ||
| 250 | + probabilities = score_exp / denominator[:, None] | ||
| 251 | + folded_output = ( | ||
| 252 | + probabilities[:, : original.shape[0]] @ original | ||
| 253 | + + (probabilities[:, original.shape[0] :] * scales[None, :]) @ compressed | ||
| 254 | + ) | ||
| 255 | + folded_lse = np.log(denominator) + max_values | ||
| 256 | + | ||
| 257 | + np.testing.assert_allclose(folded_output, reference[0], rtol=2e-12, atol=2e-12) | ||
| 258 | + np.testing.assert_allclose(folded_lse, reference[1], rtol=2e-12, atol=2e-12) | ||
| 259 | + | ||
| 260 | + | ||
| 261 | +def test_padding_scales_are_neutral_before_masking(): | ||
| 262 | + rng = np.random.default_rng(4) | ||
| 263 | + query = rng.standard_normal((5, 16)) | ||
| 264 | + valid_columns = 19 | ||
| 265 | + padded_columns = 32 | ||
| 266 | + centroids = rng.standard_normal((padded_columns, 16)) | ||
| 267 | + scales = np.ones(padded_columns) | ||
| 268 | + scales[:valid_columns] = np.exp(rng.uniform(-3.0, 3.0, valid_columns)) | ||
| 269 | + | ||
| 270 | + folded_scores = (query @ centroids.T) * scales[None, :] | ||
| 271 | + folded_scores[:, valid_columns:] = -np.inf | ||
| 272 | + reference_scores = ( | ||
| 273 | + query @ (centroids[:valid_columns] * scales[:valid_columns, None]).T | ||
| 274 | + ) | ||
| 275 | + np.testing.assert_allclose( | ||
| 276 | + folded_scores[:, :valid_columns], reference_scores, rtol=2e-12, atol=2e-12 | ||
| 277 | + ) | ||
| 278 | + assert np.all(np.isneginf(folded_scores[:, valid_columns:])) | ||
| 279 | + | ||
| 280 | + | ||
| 281 | +def test_fp16_fold_rounding_remains_numerically_close(): | ||
| 282 | + rng = np.random.default_rng(5) | ||
| 283 | + query = rng.standard_normal((8, 64)).astype(np.float32) | ||
| 284 | + centroids = rng.standard_normal((41, 64)).astype(np.float32) | ||
| 285 | + scales = np.exp( | ||
| 286 | + rng.uniform(np.log(2**-4), np.log(2**4), centroids.shape[0]) | ||
| 287 | + ).astype(np.float16) | ||
| 288 | + sinks = rng.standard_normal(query.shape[0]).astype(np.float32) | ||
| 289 | + | ||
| 290 | + baseline_kv = ( | ||
| 291 | + (centroids * scales.astype(np.float32)[:, None]) | ||
| 292 | + .astype(np.float16) | ||
| 293 | + .astype(np.float32) | ||
| 294 | + ) | ||
| 295 | + folded_kv = centroids.astype(np.float16).astype(np.float32) | ||
| 296 | + reference = _attention_with_sinks(query, baseline_kv, baseline_kv, sinks) | ||
| 297 | + folded = _folded_shared_kv_attention( | ||
| 298 | + query, folded_kv, scales.astype(np.float32), sinks | ||
| 299 | + ) | ||
| 300 | + | ||
| 301 | + output_error = folded[0] - reference[0] | ||
| 302 | + assert np.linalg.norm(output_error) / np.linalg.norm(reference[0]) < 2e-3 | ||
| 303 | + assert np.max(np.abs(output_error)) / np.max(np.abs(reference[0])) < 2e-3 | ||
| 304 | + np.testing.assert_allclose(folded[1], reference[1], rtol=2e-3, atol=2e-3) | ||
| 305 | + | ||
| 306 | + | ||
| 307 | +def test_mtp_tile_mask_matches_per_token_sliding_window(): | ||
| 308 | + query_length = 7 | ||
| 309 | + kv_length = 35 | ||
| 310 | + window_left = 11 | ||
| 311 | + tile_query_start = 1 | ||
| 312 | + tile_query_end = 5 | ||
| 313 | + | ||
| 314 | + tile_left = max(kv_length - query_length + tile_query_start - window_left, 0) | ||
| 315 | + tile_right = kv_length - query_length + tile_query_end | ||
| 316 | + tile_keys = np.arange(tile_left, tile_right + 1) | ||
| 317 | + | ||
| 318 | + tiled_mask = np.empty( | ||
| 319 | + (tile_query_end - tile_query_start + 1, tile_keys.size), dtype=bool | ||
| 320 | + ) | ||
| 321 | + for row, query_pos in enumerate(range(tile_query_start, tile_query_end + 1)): | ||
| 322 | + row_left = max(kv_length - query_length + query_pos - window_left, 0) | ||
| 323 | + row_right = kv_length - query_length + query_pos | ||
| 324 | + tiled_mask[row] = (tile_keys < row_left) | (tile_keys > row_right) | ||
| 325 | + | ||
| 326 | + reference = np.stack( | ||
| 327 | + [ | ||
| 328 | + (tile_keys < max(kv_length - query_length + query_pos - window_left, 0)) | ||
| 329 | + | (tile_keys > kv_length - query_length + query_pos) | ||
| 330 | + for query_pos in range(tile_query_start, tile_query_end + 1) | ||
| 331 | + ] | ||
| 332 | + ) | ||
| 333 | + np.testing.assert_array_equal(tiled_mask, reference) | ||
| 334 | + assert np.any(tiled_mask[0] != tiled_mask[-1]) | ||
Mattention/mixed_quant_sparse_flash_mla/tests/ut/op_host/test_mixed_quant_sparse_flash_mla_tiling.cpp+87-4
| @@ -57,6 +57,7 @@ struct MQSmlaCase { | |||
| 57 | std::vector<int64_t> metadataShape = {1024}; | 57 | std::vector<int64_t> metadataShape = {1024}; |
| 58 | ge::DataType qType = ge::DT_BF16; | 58 | ge::DataType qType = ge::DT_BF16; |
| 59 | ge::DataType kvType = ge::DT_FLOAT8_E4M3FN; | 59 | ge::DataType kvType = ge::DT_FLOAT8_E4M3FN; |
| 60 | + ge::DataType cmpKvType = ge::DT_FLOAT8_E4M3FN; | ||
| 60 | ge::DataType outType = ge::DT_BF16; | 61 | ge::DataType outType = ge::DT_BF16; |
| 61 | std::string layoutQ = "TND"; | 62 | std::string layoutQ = "TND"; |
| 62 | std::string layoutKv = "PA_BBND"; | 63 | std::string layoutKv = "PA_BBND"; |
| @@ -67,6 +68,9 @@ struct MQSmlaCase { | |||
| 67 | int64_t cmpMaskMode = 0; | 68 | int64_t cmpMaskMode = 0; |
| 68 | int64_t oriWinLeft = 127; | 69 | int64_t oriWinLeft = 127; |
| 69 | int64_t oriWinRight = 0; | 70 | int64_t oriWinRight = 0; |
| 71 | + std::string socVersion = "Ascend950"; | ||
| 72 | + uint32_t coreNum = 56; | ||
| 73 | + uint64_t ubSize = 262144; | ||
| 70 | }; | 74 | }; |
| 71 | 75 | ||
| 72 | gert::StorageShape ToStorageShape(const std::vector<int64_t> &dims) | 76 | gert::StorageShape ToStorageShape(const std::vector<int64_t> &dims) |
| @@ -102,7 +106,7 @@ void RunMQSmlaTilingCase(const MQSmlaCase &c, ge::graphStatus expect, uint64_t e | |||
| 102 | static_cast<uint32_t>(kNumHeadsKv)); | 106 | static_cast<uint32_t>(kNumHeadsKv)); |
| 103 | gert::TilingContextPara tilingContextPara( | 107 | gert::TilingContextPara tilingContextPara( |
| 104 | "MixedQuantSparseFlashMla", | 108 | "MixedQuantSparseFlashMla", |
| 105 | - {Desc(c.qShape, c.qType), Desc(c.oriKvShape, c.kvType), Desc(c.cmpKvShape, c.kvType), | 109 | + {Desc(c.qShape, c.qType), Desc(c.oriKvShape, c.kvType), Desc(c.cmpKvShape, c.cmpKvType), |
| 106 | Desc(c.oriSparseIndicesShape, ge::DT_INT32), Desc(c.cmpSparseIndicesShape, ge::DT_INT32), | 110 | Desc(c.oriSparseIndicesShape, ge::DT_INT32), Desc(c.cmpSparseIndicesShape, ge::DT_INT32), |
| 107 | Desc(c.oriBlockTableShape, ge::DT_INT32), Desc(c.cmpBlockTableShape, ge::DT_INT32), | 111 | Desc(c.oriBlockTableShape, ge::DT_INT32), Desc(c.cmpBlockTableShape, ge::DT_INT32), |
| 108 | gert::TilingContextPara::TensorDescription(ToStorageShape(c.cuSeqLensQShape), ge::DT_INT32, ge::FORMAT_ND, | 112 | gert::TilingContextPara::TensorDescription(ToStorageShape(c.cuSeqLensQShape), ge::DT_INT32, ge::FORMAT_ND, |
| @@ -132,7 +136,7 @@ void RunMQSmlaTilingCase(const MQSmlaCase &c, ge::graphStatus expect, uint64_t e | |||
| 132 | {"layout_kv", Ops::Transformer::AnyValue::CreateFrom<std::string>(c.layoutKv)}, | 136 | {"layout_kv", Ops::Transformer::AnyValue::CreateFrom<std::string>(c.layoutKv)}, |
| 133 | {"topk_value_mode", Ops::Transformer::AnyValue::CreateFrom<int64_t>(1)}, | 137 | {"topk_value_mode", Ops::Transformer::AnyValue::CreateFrom<int64_t>(1)}, |
| 134 | {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom<bool>(false)}}, | 138 | {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom<bool>(false)}}, |
| 135 | - &compileInfo, "Ascend950", 56, 262144); | 139 | + &compileInfo, c.socVersion, c.coreNum, c.ubSize); |
| 136 | ExecuteTestCase(tilingContextPara, expect, expectTilingKey); | 140 | ExecuteTestCase(tilingContextPara, expect, expectTilingKey); |
| 137 | } | 141 | } |
| 138 | } // namespace | 142 | } // namespace |
| @@ -201,14 +205,93 @@ TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_swa_bsnd_q_success) | |||
| 201 | RunMQSmlaTilingCase(c, ge::GRAPH_SUCCESS); | 205 | RunMQSmlaTilingCase(c, ge::GRAPH_SUCCESS); |
| 202 | } | 206 | } |
| 203 | 207 | ||
| 204 | -// quant_mode only supports 1 or 2 | 208 | +// arch35 keeps the original quant_mode=1/2 contract and rejects TurboQuant mode 3. |
| 205 | -TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_quant_mode_invalid_failed) | 209 | +TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_arch35_quant_mode3_failed) |
| 206 | { | 210 | { |
| 207 | MQSmlaCase c; | 211 | MQSmlaCase c; |
| 208 | c.quantMode = 3; | 212 | c.quantMode = 3; |
| 209 | RunMQSmlaTilingCase(c, ge::GRAPH_FAILED); | 213 | RunMQSmlaTilingCase(c, ge::GRAPH_FAILED); |
| 210 | } | 214 | } |
| 211 | 215 | ||
| 216 | +// arch22 must not enter the original arch35 quant_mode=1/2 path. | ||
| 217 | +TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_arch22_quant_mode1_failed) | ||
| 218 | +{ | ||
| 219 | + MQSmlaCase c; | ||
| 220 | + c.socVersion = "Ascend910B"; | ||
| 221 | + c.coreNum = 64; | ||
| 222 | + RunMQSmlaTilingCase(c, ge::GRAPH_FAILED); | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +// Empty TND query is allowed only by the TurboQuant contract. | ||
| 226 | +TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_arch35_empty_query_failed) | ||
| 227 | +{ | ||
| 228 | + MQSmlaCase c; | ||
| 229 | + c.qShape = {0, 64, 512}; | ||
| 230 | + RunMQSmlaTilingCase(c, ge::GRAPH_FAILED); | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +// arch22 supports the TurboQuant CSA contract through quant_mode=3. | ||
| 234 | +TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_arch22_turbo_quant_success) | ||
| 235 | +{ | ||
| 236 | + for (ge::DataType dtype : {ge::DT_FLOAT16, ge::DT_BF16}) { | ||
| 237 | + for (int64_t topk : {512, 1024}) { | ||
| 238 | + MQSmlaCase c; | ||
| 239 | + c.oriKvShape = {65, 128, 1, 512}; | ||
| 240 | + c.cmpKvShape = {17, 128, 1, 258}; | ||
| 241 | + c.cmpSparseIndicesShape = {512, 1, topk}; | ||
| 242 | + c.oriBlockTableShape = {4, 65}; | ||
| 243 | + c.cmpBlockTableShape = {4, 17}; | ||
| 244 | + c.qType = dtype; | ||
| 245 | + c.kvType = dtype; | ||
| 246 | + c.cmpKvType = ge::DT_UINT8; | ||
| 247 | + c.outType = dtype; | ||
| 248 | + c.quantMode = 3; | ||
| 249 | + c.cmpRatio = 4; | ||
| 250 | + c.cmpMaskMode = 3; | ||
| 251 | + c.socVersion = "Ascend910B"; | ||
| 252 | + c.coreNum = 64; | ||
| 253 | + RunMQSmlaTilingCase(c, ge::GRAPH_SUCCESS); | ||
| 254 | + } | ||
| 255 | + } | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_arch22_turbo_quant_topk_failed) | ||
| 259 | +{ | ||
| 260 | + MQSmlaCase c; | ||
| 261 | + c.oriKvShape = {65, 128, 1, 512}; | ||
| 262 | + c.cmpKvShape = {17, 128, 1, 258}; | ||
| 263 | + c.cmpSparseIndicesShape = {512, 1, 256}; | ||
| 264 | + c.oriBlockTableShape = {4, 65}; | ||
| 265 | + c.cmpBlockTableShape = {4, 17}; | ||
| 266 | + c.kvType = ge::DT_BF16; | ||
| 267 | + c.cmpKvType = ge::DT_UINT8; | ||
| 268 | + c.quantMode = 3; | ||
| 269 | + c.cmpRatio = 4; | ||
| 270 | + c.cmpMaskMode = 3; | ||
| 271 | + c.socVersion = "Ascend910B"; | ||
| 272 | + c.coreNum = 64; | ||
| 273 | + RunMQSmlaTilingCase(c, ge::GRAPH_FAILED); | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_arch22_turbo_quant_empty_query_success) | ||
| 277 | +{ | ||
| 278 | + MQSmlaCase c; | ||
| 279 | + c.qShape = {0, 64, 512}; | ||
| 280 | + c.oriKvShape = {65, 128, 1, 512}; | ||
| 281 | + c.cmpKvShape = {17, 128, 1, 258}; | ||
| 282 | + c.cmpSparseIndicesShape = {0, 1, 512}; | ||
| 283 | + c.oriBlockTableShape = {4, 65}; | ||
| 284 | + c.cmpBlockTableShape = {4, 17}; | ||
| 285 | + c.kvType = ge::DT_BF16; | ||
| 286 | + c.cmpKvType = ge::DT_UINT8; | ||
| 287 | + c.quantMode = 3; | ||
| 288 | + c.cmpRatio = 4; | ||
| 289 | + c.cmpMaskMode = 3; | ||
| 290 | + c.socVersion = "Ascend910B"; | ||
| 291 | + c.coreNum = 64; | ||
| 292 | + RunMQSmlaTilingCase(c, ge::GRAPH_SUCCESS); | ||
| 293 | +} | ||
| 294 | + | ||
| 212 | // rope_head_dim only supports 64 | 295 | // rope_head_dim only supports 64 |
| 213 | TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_rope_head_dim_failed) | 296 | TEST_F(MixedQuantSparseFlashMlaTiling, test_tiling_rope_head_dim_failed) |
| 214 | { | 297 | { |
| @@ -91,12 +91,13 @@ at::Tensor MixedQuantSparseFlashMlaMetadata( | |||
| 91 | 91 | ||
| 92 | std::tuple<at::Tensor, at::Tensor> ConstructMixedQuantSparseFlashMlaAttenOutTensor( | 92 | std::tuple<at::Tensor, at::Tensor> ConstructMixedQuantSparseFlashMlaAttenOutTensor( |
| 93 | const at::Tensor &q, const at::Tensor &oriKv, std::string layoutQStr, std::string layoutKvStr, | 93 | const at::Tensor &q, const at::Tensor &oriKv, std::string layoutQStr, std::string layoutKvStr, |
| 94 | - const uint64_t &ropeHeadDim, bool returnSoftmaxLse) | 94 | + const uint64_t &ropeHeadDim, bool returnSoftmaxLse, int64_t quantMode) |
| 95 | { | 95 | { |
| 96 | TORCH_CHECK(layoutQStr == "BSND" || layoutQStr == "TND", "The layout of query only support BSND and TND, but got ", | 96 | TORCH_CHECK(layoutQStr == "BSND" || layoutQStr == "TND", "The layout of query only support BSND and TND, but got ", |
| 97 | layoutQStr); | 97 | layoutQStr); |
| 98 | for (auto i = 0; i < q.sizes().size(); i++) { | 98 | for (auto i = 0; i < q.sizes().size(); i++) { |
| 99 | - TORCH_CHECK(q.size(i) > 0, | 99 | + const bool turboQuantEmptyQuery = quantMode == 3 && layoutQStr == "TND" && i == DIM_0 && q.size(i) == 0; |
| 100 | + TORCH_CHECK(q.size(i) > 0 || turboQuantEmptyQuery, | ||
| 100 | "All values within query's shape should be greater " | 101 | "All values within query's shape should be greater " |
| 101 | "than 0, but shape[", | 102 | "than 0, but shape[", |
| 102 | i, "] is ", q.size(i)); | 103 | i, "] is ", q.size(i)); |
| @@ -161,10 +162,10 @@ std::tuple<at::Tensor, at::Tensor> MixedQuantSparseFlashMla( | |||
| 161 | c10::string_view layoutQ, c10::string_view layoutKv, int64_t topkValueMode, bool returnSoftmaxLse, | 162 | c10::string_view layoutQ, c10::string_view layoutKv, int64_t topkValueMode, bool returnSoftmaxLse, |
| 162 | c10::optional<int64_t> keyDtype, c10::optional<int64_t> valueDtype) | 163 | c10::optional<int64_t> keyDtype, c10::optional<int64_t> valueDtype) |
| 163 | { | 164 | { |
| 164 | - TORCH_CHECK(q.numel() > 0, "Tensor query is empty.") | ||
| 165 | - | ||
| 166 | std::string layoutQStr = std::string(layoutQ); | 165 | std::string layoutQStr = std::string(layoutQ); |
| 167 | std::string layoutKvStr = std::string(layoutKv); | 166 | std::string layoutKvStr = std::string(layoutKv); |
| 167 | + const bool turboQuantEmptyQuery = quantMode == 3 && layoutQStr == "TND" && q.dim() == DIM_3 && q.size(DIM_0) == 0; | ||
| 168 | + TORCH_CHECK(q.numel() > 0 || turboQuantEmptyQuery, "Tensor query is empty."); | ||
| 168 | TORCH_CHECK(oriKv.has_value(), "ori_kv must be provided."); | 169 | TORCH_CHECK(oriKv.has_value(), "ori_kv must be provided."); |
| 169 | const at::Tensor &oriKvVal = *oriKv; | 170 | const at::Tensor &oriKvVal = *oriKv; |
| 170 | // convert str | 171 | // convert str |
| @@ -174,15 +175,16 @@ std::tuple<at::Tensor, at::Tensor> MixedQuantSparseFlashMla( | |||
| 174 | // construct the atten_out tensor | 175 | // construct the atten_out tensor |
| 175 | std::tuple<at::Tensor, at::Tensor> mixedQuantSparseFlashMlaAttenOut = | 176 | std::tuple<at::Tensor, at::Tensor> mixedQuantSparseFlashMlaAttenOut = |
| 176 | op_api::ConstructMixedQuantSparseFlashMlaAttenOutTensor(q, oriKvVal, layoutQStr, layoutKvStr, ropeHeadDim, | 177 | op_api::ConstructMixedQuantSparseFlashMlaAttenOutTensor(q, oriKvVal, layoutQStr, layoutKvStr, ropeHeadDim, |
| 177 | - returnSoftmaxLse); | 178 | + returnSoftmaxLse, quantMode); |
| 178 | at::Tensor attenOut = std::get<0>(mixedQuantSparseFlashMlaAttenOut); | 179 | at::Tensor attenOut = std::get<0>(mixedQuantSparseFlashMlaAttenOut); |
| 179 | at::Tensor softmaxLse = std::get<1>(mixedQuantSparseFlashMlaAttenOut); | 180 | at::Tensor softmaxLse = std::get<1>(mixedQuantSparseFlashMlaAttenOut); |
| 180 | 181 | ||
| 181 | at::Tensor nullTensor; | 182 | at::Tensor nullTensor; |
| 182 | auto oriKvValue = oriKv.has_value() ? oriKv.value() : nullTensor; | 183 | auto oriKvValue = oriKv.has_value() ? oriKv.value() : nullTensor; |
| 183 | auto cmpKvValue = cmpKv.has_value() ? cmpKv.value() : nullTensor; | 184 | auto cmpKvValue = cmpKv.has_value() ? cmpKv.value() : nullTensor; |
| 184 | - TensorWrapper oriKvWrapper = MqsmlaMakeWrapper(oriKvValue, ACL_FLOAT8_E4M3FN); | 185 | + const aclDataType tqOriKvType = q.scalar_type() == at::ScalarType::Half ? ACL_FLOAT16 : ACL_BF16; |
| 185 | - TensorWrapper cmpKvWrapper = MqsmlaMakeWrapper(cmpKvValue, ACL_FLOAT8_E4M3FN); | 186 | + TensorWrapper oriKvWrapper = MqsmlaMakeWrapper(oriKvValue, quantMode == 3 ? tqOriKvType : ACL_FLOAT8_E4M3FN); |
| 187 | + TensorWrapper cmpKvWrapper = MqsmlaMakeWrapper(cmpKvValue, quantMode == 3 ? ACL_UINT8 : ACL_FLOAT8_E4M3FN); | ||
| 186 | ACLNN_CMD(aclnnMixedQuantSparseFlashMla, q, oriKvWrapper, cmpKvWrapper, oriSparseIndices, cmpSparseIndices, | 188 | ACLNN_CMD(aclnnMixedQuantSparseFlashMla, q, oriKvWrapper, cmpKvWrapper, oriSparseIndices, cmpSparseIndices, |
| 187 | oriBlockTable, cmpBlockTable, cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, sequsedQ, sequsedOriKv, | 189 | oriBlockTable, cmpBlockTable, cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, sequsedQ, sequsedOriKv, |
| 188 | sequsedCmpKv, cmpResidualKv, oriTopkLength, cmpTopkLength, sinks, metadata, quantMode, ropeHeadDim, | 190 | sequsedCmpKv, cmpResidualKv, oriTopkLength, cmpTopkLength, sinks, metadata, quantMode, ropeHeadDim, |
| @@ -131,7 +131,15 @@ class MixedQuantSparseFlashMlaOpBuilder(OpBuilder): | |||
| 131 | key_dtype=None, | 131 | key_dtype=None, |
| 132 | value_dtype=None, | 132 | value_dtype=None, |
| 133 | ): | 133 | ): |
| 134 | - if q.numel() == 0: | 134 | + turbo_quant_empty_query = ( |
| 135 | + quant_mode == 3 | ||
| 136 | + and layout_q == "TND" | ||
| 137 | + and q.dim() == 3 | ||
| 138 | + and q.shape[0] == 0 | ||
| 139 | + and q.shape[1] > 0 | ||
| 140 | + and q.shape[2] > 0 | ||
| 141 | + ) | ||
| 142 | + if q.numel() == 0 and not turbo_quant_empty_query: | ||
| 135 | raise ValueError("The shape size of q should not be 0") | 143 | raise ValueError("The shape size of q should not be 0") |
| 136 | if ori_kv is not None and ori_kv.numel() == 0: | 144 | if ori_kv is not None and ori_kv.numel() == 0: |
| 137 | raise ValueError("The shape size of ori_kv should not be 0") | 145 | raise ValueError("The shape size of ori_kv should not be 0") |
| @@ -14,4 +14,4 @@ foreach(SUB_DIR ${CURRENT_DIRS}) | |||
| 14 | if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | 14 | if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") |
| 15 | add_subdirectory(${SUB_DIR}) | 15 | add_subdirectory(${SUB_DIR}) |
| 16 | endif() | 16 | endif() |
| 17 | -endforeach() | 17 | +endforeach() |
| @@ -5,8 +5,8 @@ | |||
| 5 | | 产品 | 是否支持 | | 5 | | 产品 | 是否支持 | |
| 6 | | :----------------------------------------------------------- | :------: | | 6 | | :----------------------------------------------------------- | :------: | |
| 7 | |<term>Ascend 950PR&950DT系列产品</term>| √ | | 7 | |<term>Ascend 950PR&950DT系列产品</term>| √ | |
| 8 | -|<term>Atlas A3系列产品</term>| × | | 8 | +|<term>Atlas A3系列产品</term>| √ | |
| 9 | -|<term>Atlas A2系列产品</term>| × | | 9 | +|<term>Atlas A2系列产品</term>| √ | |
| 10 | |<term>Atlas 200I/500 A2推理产品</term>| × | | 10 | |<term>Atlas 200I/500 A2推理产品</term>| × | |
| 11 | |<term>Atlas推理系列产品</term>| × | | 11 | |<term>Atlas推理系列产品</term>| × | |
| 12 | |<term>Atlas训练系列产品</term>| × | | 12 | |<term>Atlas训练系列产品</term>| × | |
| @@ -121,7 +121,7 @@ | |||
| 121 | <tr> | 121 | <tr> |
| 122 | <td>quant_mode</td> | 122 | <td>quant_mode</td> |
| 123 | <td>属性</td> | 123 | <td>属性</td> |
| 124 | - <td>表示量化模式,1表示K、V nope为per-token-group量化,scale类型为bfloat16,2表示K、V nope为per-token-group量化,scale类型为float8_e8m0。</td> | 124 | + <td>表示量化模式。1表示BF16 scale量化布局;2表示FLOAT8_E8M0 scale量化布局;3表示TurboQuant TQ4配套metadata。Metadata接口接受1、2、3,具体平台约束见约束说明。</td> |
| 125 | <td>INT32</td> | 125 | <td>INT32</td> |
| 126 | <td>-</td> | 126 | <td>-</td> |
| 127 | </tr> | 127 | </tr> |
| @@ -249,6 +249,19 @@ | |||
| 249 | 249 | ||
| 250 | ## 约束说明 | 250 | ## 约束说明 |
| 251 | 251 | ||
| 252 | +- `quant_mode`支持1、2、3,具体产品支持的量化模式如下。 | ||
| 253 | + | ||
| 254 | +<!-- npu="950" id1 --> | ||
| 255 | +- <term>Ascend 950PR&950DT系列产品</term>:与`MixedQuantSparseFlashMla`算子配套使用时,仅支持`quant_mode=1/2`。 | ||
| 256 | +<!-- end id1 --> | ||
| 257 | + | ||
| 258 | +<!-- npu="A3" id2 --> | ||
| 259 | +- <term>Atlas A3系列产品</term>:与`MixedQuantSparseFlashMla`算子配套使用时,仅支持`quant_mode=3`。 | ||
| 260 | +<!-- end id2 --> | ||
| 261 | + | ||
| 262 | +<!-- npu="910b" id3 --> | ||
| 263 | +- <term>Atlas A2系列产品</term>:与`MixedQuantSparseFlashMla`算子配套使用时,仅支持`quant_mode=3`。 | ||
| 264 | +<!-- end id3 --> | ||
| 252 | - MixedQuantSparseFlashMlaMetadata算子需要与MixedQuantSparseFlashMla算子配套使用。 | 265 | - MixedQuantSparseFlashMlaMetadata算子需要与MixedQuantSparseFlashMla算子配套使用。 |
| 253 | - B(Batch)表示输入样本批量大小,q、ori_kv、cmp_kv为配套的MixedQuantSparseFlashMla算子的入参,S1表示layout_q=BSND时,q shape中的S轴的大小,T1表示layout_q=TND时,q shape中的T轴的大小,S2表示layout_kv=BSND时,ori_kv shape中的S轴的大小,S3表示layout_kv=BSND时,cmp_kv shape中的S轴的大小,N2表示ori_kv、cmp_kv shape中的N轴的大小。 | 266 | - B(Batch)表示输入样本批量大小,q、ori_kv、cmp_kv为配套的MixedQuantSparseFlashMla算子的入参,S1表示layout_q=BSND时,q shape中的S轴的大小,T1表示layout_q=TND时,q shape中的T轴的大小,S2表示layout_kv=BSND时,ori_kv shape中的S轴的大小,S3表示layout_kv=BSND时,cmp_kv shape中的S轴的大小,N2表示ori_kv、cmp_kv shape中的N轴的大小。 |
| 254 | - 参数cu_seqlens_q、cu_seqlens_ori_kv及cu_seqlens_cmp_kv要求其值为当前Batch与前序Batch有效token数的累加值,第一个元素固定为0,后一个元素的值必须大于等于前一个元素的值。 | 267 | - 参数cu_seqlens_q、cu_seqlens_ori_kv及cu_seqlens_cmp_kv要求其值为当前Batch与前序Batch有效token数的累加值,第一个元素固定为0,后一个元素的值必须大于等于前一个元素的值。 |
| @@ -8,10 +8,10 @@ | |||
| 8 | - <term>Ascend 950PR&950DT系列产品</term>:支持 | 8 | - <term>Ascend 950PR&950DT系列产品</term>:支持 |
| 9 | <!-- end id1 --> | 9 | <!-- end id1 --> |
| 10 | <!-- npu="A3" id2 --> | 10 | <!-- npu="A3" id2 --> |
| 11 | -- <term>Atlas A3系列产品</term>:不支持 | 11 | +- <term>Atlas A3系列产品</term>:支持 |
| 12 | <!-- end id2 --> | 12 | <!-- end id2 --> |
| 13 | <!-- npu="910b" id3 --> | 13 | <!-- npu="910b" id3 --> |
| 14 | -- <term>Atlas A2系列产品</term>:不支持 | 14 | +- <term>Atlas A2系列产品</term>:支持 |
| 15 | <!-- end id3 --> | 15 | <!-- end id3 --> |
| 16 | <!-- npu="310b" id4 --> | 16 | <!-- npu="310b" id4 --> |
| 17 | - <term>Atlas 200I/500 A2推理产品</term>:不支持 | 17 | - <term>Atlas 200I/500 A2推理产品</term>:不支持 |
| @@ -230,7 +230,7 @@ aclnnStatus aclnnMixedQuantSparseFlashMlaMetadata( | |||
| 230 | <td>quantMode(int64_t)</td> | 230 | <td>quantMode(int64_t)</td> |
| 231 | <td>输入</td> | 231 | <td>输入</td> |
| 232 | <td>表示量化模式。</td> | 232 | <td>表示量化模式。</td> |
| 233 | - <td><ul><li>1: Q: nope+rope: 非量化; KV: nope: per-token-group FP8_e4m3。group_size=64; rope: non-quantized and consistent with q; scale: bf16; kv_cache_layout: block_size*(rope[64*2]+nope[448]+scale[448/64*2]+pad[18])</li><li>2: Q: nope+rope: 非量化; KV: nope: per-token-group FP8_e4m3。group_size=64; rope: non-quantized and consistent with q; scale: e8m0; kv_cache_layout: block_size*(nope+rope)+block_size*(scale+pad[1])</li></ul></td> | 233 | + <td><ul><li>1: BF16 scale量化布局。</li><li>2: FLOAT8_E8M0 scale量化布局。</li><li>3: TurboQuant TQ4配套metadata。Metadata接口接受1、2、3,具体平台约束见约束说明。</li></ul></td> |
| 234 | <td>-</td> | 234 | <td>-</td> |
| 235 | <td>-</td> | 235 | <td>-</td> |
| 236 | <td>-</td> | 236 | <td>-</td> |
| @@ -511,6 +511,19 @@ aclnnStatus aclnnMixedQuantSparseFlashMlaMetadata( | |||
| 511 | 511 | ||
| 512 | ## 约束说明 | 512 | ## 约束说明 |
| 513 | 513 | ||
| 514 | + - `quantMode`支持1、2、3,具体产品支持的量化模式如下。 | ||
| 515 | + | ||
| 516 | +<!-- npu="950" id7 --> | ||
| 517 | +- <term>Ascend 950PR&950DT系列产品</term>:与`aclnnMixedQuantSparseFlashMla`算子配套使用时,仅支持`quantMode=1/2`。 | ||
| 518 | +<!-- end id7 --> | ||
| 519 | + | ||
| 520 | +<!-- npu="A3" id8 --> | ||
| 521 | +- <term>Atlas A3系列产品</term>:与`aclnnMixedQuantSparseFlashMla`算子配套使用时,仅支持`quantMode=3`。 | ||
| 522 | +<!-- end id8 --> | ||
| 523 | + | ||
| 524 | +<!-- npu="910b" id9 --> | ||
| 525 | +- <term>Atlas A2系列产品</term>:与`aclnnMixedQuantSparseFlashMla`算子配套使用时,仅支持`quantMode=3`。 | ||
| 526 | +<!-- end id9 --> | ||
| 514 | - aclnnMixedQuantSparseFlashMlaMetadata默认确定性实现。 | 527 | - aclnnMixedQuantSparseFlashMlaMetadata默认确定性实现。 |
| 515 | - B(Batch)表示输入样本批量大小,q、oriKvOptional、cmpKvOptional为配套的aclnnMixedQuantSparseFlashMla算子的入参,S1表示layoutQOptional=BSND时,q shape中的S轴的大小,T1表示layoutQOptional=TND时,q shape中的T轴的大小,S2表示layoutKvOptional=BSND时,oriKvOptional shape中的S轴的大小,S3表示layoutKvOptional=BSND时,cmpKvOptional shape中的S轴的大小,N2表示oriKvOptional、cmpKvOptional shape中的N轴的大小。 | 528 | - B(Batch)表示输入样本批量大小,q、oriKvOptional、cmpKvOptional为配套的aclnnMixedQuantSparseFlashMla算子的入参,S1表示layoutQOptional=BSND时,q shape中的S轴的大小,T1表示layoutQOptional=TND时,q shape中的T轴的大小,S2表示layoutKvOptional=BSND时,oriKvOptional shape中的S轴的大小,S3表示layoutKvOptional=BSND时,cmpKvOptional shape中的S轴的大小,N2表示oriKvOptional、cmpKvOptional shape中的N轴的大小。 |
| 516 | - 参数cuSeqlensQOptional、cuSeqlensOriKvOptional、cuSeqlensCmpKvOptional要求其值为当前Batch与前序Batch有效token数的累加值,第一个元素固定为0,后一个元素的值必须大于等于前一个元素的值。 | 529 | - 参数cuSeqlensQOptional、cuSeqlensOriKvOptional、cuSeqlensCmpKvOptional要求其值为当前Batch与前序Batch有效token数的累加值,第一个元素固定为0,后一个元素的值必须大于等于前一个元素的值。 |
| @@ -16,33 +16,33 @@ import numpy as np | |||
| 16 | import torch.nn as nn | 16 | import torch.nn as nn |
| 17 | 17 | ||
| 18 | metadata = torch.ops.cann_ops_transformer.mixed_quant_sparse_flash_mla_metadata( | 18 | metadata = torch.ops.cann_ops_transformer.mixed_quant_sparse_flash_mla_metadata( |
| 19 | - cu_seqlens_q = torch.tensor([0, 10], dtype=torch.int32).npu(), | 19 | + cu_seqlens_q=torch.tensor([0, 10], dtype=torch.int32).npu(), |
| 20 | - cu_seqlens_ori_kv = None, | 20 | + cu_seqlens_ori_kv=None, |
| 21 | - cu_seqlens_cmp_kv = None, | 21 | + cu_seqlens_cmp_kv=None, |
| 22 | - seqused_q = None, | 22 | + seqused_q=None, |
| 23 | - seqused_ori_kv = torch.tensor([8192], dtype=torch.int32).npu(), | 23 | + seqused_ori_kv=torch.tensor([8192], dtype=torch.int32).npu(), |
| 24 | - seqused_cmp_kv = torch.tensor([64], dtype=torch.int32).npu(), | 24 | + seqused_cmp_kv=torch.tensor([64], dtype=torch.int32).npu(), |
| 25 | - cmp_residual_kv = torch.tensor([1], dtype=torch.int32).npu(), | 25 | + cmp_residual_kv=torch.tensor([1], dtype=torch.int32).npu(), |
| 26 | - ori_topk_length = None, | 26 | + ori_topk_length=None, |
| 27 | - cmp_topk_length = None, | 27 | + cmp_topk_length=None, |
| 28 | - num_heads_q = 128, | 28 | + num_heads_q=128, |
| 29 | - num_heads_kv = 1, | 29 | + num_heads_kv=1, |
| 30 | - head_dim = 512, | 30 | + head_dim=512, |
| 31 | - quant_mode = 1, | 31 | + quant_mode=1, |
| 32 | - batch_size = 1, | 32 | + batch_size=1, |
| 33 | - max_seqlen_q = 1, | 33 | + max_seqlen_q=1, |
| 34 | - max_seqlen_ori_kv = 512, | 34 | + max_seqlen_ori_kv=512, |
| 35 | - max_seqlen_cmp_kv = 32, | 35 | + max_seqlen_cmp_kv=32, |
| 36 | - ori_topk = 0, | 36 | + ori_topk=0, |
| 37 | - cmp_topk = 512, | 37 | + cmp_topk=512, |
| 38 | - rope_head_dim = 64, | 38 | + rope_head_dim=64, |
| 39 | - cmp_ratio = 4, | 39 | + cmp_ratio=4, |
| 40 | - ori_mask_mode = 4, | 40 | + ori_mask_mode=4, |
| 41 | - cmp_mask_mode = 3, | 41 | + cmp_mask_mode=3, |
| 42 | - ori_win_left = 127, | 42 | + ori_win_left=127, |
| 43 | - ori_win_right = 0, | 43 | + ori_win_right=0, |
| 44 | - layout_q = "TND", | 44 | + layout_q="TND", |
| 45 | - layout_kv = "PA_BBND", | 45 | + layout_kv="PA_BBND", |
| 46 | - has_ori_kv = True, | 46 | + has_ori_kv=True, |
| 47 | - has_cmp_kv = True | 47 | + has_cmp_kv=True, |
| 48 | -) | 48 | +) |
| @@ -9,4 +9,4 @@ | |||
| 9 | # ----------------------------------------------------------------------------------------------------------- | 9 | # ----------------------------------------------------------------------------------------------------------- |
| 10 | add_op_to_compiled_list() | 10 | add_op_to_compiled_list() |
| 11 | 11 | ||
| 12 | -add_modules_sources(OPTYPE mixed_quant_sparse_flash_mla_metadata ACLNNTYPE aclnn) | 12 | +add_modules_sources(OPTYPE mixed_quant_sparse_flash_mla_metadata ACLNNTYPE aclnn) |
| @@ -41,7 +41,7 @@ enum class SparseModeMqsmla : uint8_t { | |||
| 41 | }; | 41 | }; |
| 42 | 42 | ||
| 43 | inline constexpr int64_t MQSMLA_QUANT_MODE_LOWER_BOUND = 1; | 43 | inline constexpr int64_t MQSMLA_QUANT_MODE_LOWER_BOUND = 1; |
| 44 | -inline constexpr int64_t MQSMLA_QUANT_MODE_UPPER_BOUND = 2; | 44 | +inline constexpr int64_t MQSMLA_QUANT_MODE_UPPER_BOUND = 3; |
| 45 | inline constexpr int64_t MQSMLA_CMP_RATIO_LOWER_BOUND = 1; | 45 | inline constexpr int64_t MQSMLA_CMP_RATIO_LOWER_BOUND = 1; |
| 46 | inline constexpr int64_t MQSMLA_CMP_RATIO_UPPER_BOUND = 128; | 46 | inline constexpr int64_t MQSMLA_CMP_RATIO_UPPER_BOUND = 128; |
| 47 | inline constexpr int64_t MQSMLA_NUM_HEADS_Q_LOWER_BOUND = 1; | 47 | inline constexpr int64_t MQSMLA_NUM_HEADS_Q_LOWER_BOUND = 1; |
| @@ -28,11 +28,13 @@ __attribute__((visibility("default"))) aclnnStatus aclnnMixedQuantSparseFlashMla | |||
| 28 | const char *layoutQOptional, const char *layoutKvOptional, bool hasOriKv, bool hasCmpKv, const aclTensor *metaData, | 28 | const char *layoutQOptional, const char *layoutKvOptional, bool hasOriKv, bool hasCmpKv, const aclTensor *metaData, |
| 29 | uint64_t *workspaceSize, aclOpExecutor **executor); | 29 | uint64_t *workspaceSize, aclOpExecutor **executor); |
| 30 | 30 | ||
| 31 | -__attribute__((visibility("default"))) aclnnStatus aclnnMixedQuantSparseFlashMlaMetadata( | 31 | +__attribute__((visibility("default"))) aclnnStatus aclnnMixedQuantSparseFlashMlaMetadata(void *workspace, |
| 32 | - void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, aclrtStream stream); | 32 | + uint64_t workspaceSize, |
| 33 | + aclOpExecutor *executor, | ||
| 34 | + aclrtStream stream); | ||
| 33 | 35 | ||
| 34 | #ifdef __cplusplus | 36 | #ifdef __cplusplus |
| 35 | } | 37 | } |
| 36 | #endif | 38 | #endif |
| 37 | 39 | ||
| 38 | -#endif // ACLNN_MIXED_QUANT_SPARSE_FLASH_MLA_METADATA_H | 40 | +#endif // ACLNN_MIXED_QUANT_SPARSE_FLASH_MLA_METADATA_H |
| @@ -1,10 +1,10 @@ | |||
| 1 | # --------------------------------------------------------------------------------------------------------- | 1 | # --------------------------------------------------------------------------------------------------------- |
| 2 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. | 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 | 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"). | 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. | 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, | 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. | 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. | 8 | # See LICENSE in the root of the software repository for the full text of the License. |
| 9 | # --------------------------------------------------------------------------------------------------------- | 9 | # --------------------------------------------------------------------------------------------------------- |
| 10 | 10 | ||
| @@ -29,4 +29,4 @@ endif() | |||
| 29 | 29 | ||
| 30 | if(UT_TEST_ALL OR OP_KERNEL_AICPU_UT) | 30 | if(UT_TEST_ALL OR OP_KERNEL_AICPU_UT) |
| 31 | AddAicpuOpTestCase(mixed_quant_sparse_flash_mla_metadata) | 31 | AddAicpuOpTestCase(mixed_quant_sparse_flash_mla_metadata) |
| 32 | -endif() | 32 | +endif() |
| @@ -62,6 +62,7 @@ bool MixedQuantSparseFlashMlaMetadataCpuKernel::Prepare(CpuKernelContext &ctx) | |||
| 62 | GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); | 62 | GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); |
| 63 | GetAttrValueOpt(ctx, "max_seqlen_ori_kv", maxSeqlenOriKv_); | 63 | GetAttrValueOpt(ctx, "max_seqlen_ori_kv", maxSeqlenOriKv_); |
| 64 | GetAttrValueOpt(ctx, "max_seqlen_cmp_kv", maxSeqlenCmpKv_); | 64 | GetAttrValueOpt(ctx, "max_seqlen_cmp_kv", maxSeqlenCmpKv_); |
| 65 | + GetAttrValueOpt(ctx, "quant_mode", quantMode_); | ||
| 65 | GetAttrValueOpt(ctx, "ori_topk", oriTopK_); | 66 | GetAttrValueOpt(ctx, "ori_topk", oriTopK_); |
| 66 | GetAttrValueOpt(ctx, "cmp_topk", cmpTopK_); | 67 | GetAttrValueOpt(ctx, "cmp_topk", cmpTopK_); |
| 67 | GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); | 68 | GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); |
| @@ -436,7 +437,7 @@ bool MixedQuantSparseFlashMlaMetadataCpuKernel::ParamsInit() | |||
| 436 | s2BaseSize_ = 128U; | 437 | s2BaseSize_ = 128U; |
| 437 | } else { | 438 | } else { |
| 438 | mBaseSize_ = groupSize_; | 439 | mBaseSize_ = groupSize_; |
| 439 | - s2BaseSize_ = 128U; | 440 | + s2BaseSize_ = quantMode_ == 3 ? 512U : 128U; |
| 440 | } | 441 | } |
| 441 | return true; | 442 | return true; |
| 442 | } | 443 | } |
| @@ -340,6 +340,7 @@ private: | |||
| 340 | int32_t maxSeqlenCmpKv_ = 0; | 340 | int32_t maxSeqlenCmpKv_ = 0; |
| 341 | int32_t numHeadsKv_ = 1; | 341 | int32_t numHeadsKv_ = 1; |
| 342 | int32_t headDim_ = 0; | 342 | int32_t headDim_ = 0; |
| 343 | + int32_t quantMode_ = 1; | ||
| 343 | int32_t oriTopK_ = 0; | 344 | int32_t oriTopK_ = 0; |
| 344 | int32_t cmpTopK_ = 0; | 345 | int32_t cmpTopK_ = 0; |
| 345 | int32_t cmpRatio_ = 1; | 346 | int32_t cmpRatio_ = 1; |
| @@ -0,0 +1,46 @@ | |||
| 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 "gtest/gtest.h" | ||
| 12 | +#define private public | ||
| 13 | +#include "../../../op_kernel_aicpu/mixed_quant_sparse_flash_mla_metadata_aicpu.h" | ||
| 14 | +#undef private | ||
| 15 | + | ||
| 16 | +namespace aicpu { | ||
| 17 | +namespace { | ||
| 18 | + | ||
| 19 | +TEST(MixedQuantSparseFlashMlaMetadata, UsesTurboQuantS2BaseSizeOnAscend910) | ||
| 20 | +{ | ||
| 21 | + MixedQuantSparseFlashMlaMetadataCpuKernel kernel; | ||
| 22 | + kernel.numHeadsQ_ = 128; | ||
| 23 | + kernel.numHeadsKv_ = 1; | ||
| 24 | + kernel.quantMode_ = 3; | ||
| 25 | + kernel.socVersion_ = "Ascend910B"; | ||
| 26 | + | ||
| 27 | + ASSERT_TRUE(kernel.ParamsInit()); | ||
| 28 | + EXPECT_EQ(kernel.s2BaseSize_, 512U); | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +TEST(MixedQuantSparseFlashMlaMetadata, PreservesA5S2BaseSize) | ||
| 32 | +{ | ||
| 33 | + for (int32_t quantMode : {1, 2}) { | ||
| 34 | + MixedQuantSparseFlashMlaMetadataCpuKernel kernel; | ||
| 35 | + kernel.numHeadsQ_ = 128; | ||
| 36 | + kernel.numHeadsKv_ = 1; | ||
| 37 | + kernel.quantMode_ = quantMode; | ||
| 38 | + kernel.socVersion_ = "Ascend950"; | ||
| 39 | + | ||
| 40 | + ASSERT_TRUE(kernel.ParamsInit()); | ||
| 41 | + EXPECT_EQ(kernel.s2BaseSize_, 128U); | ||
| 42 | + } | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +} // namespace | ||
| 46 | +} // namespace aicpu | ||
| @@ -15,6 +15,7 @@ | |||
| 15 | #include <vector> | 15 | #include <vector> |
| 16 | #include "tiling/tiling_api.h" | 16 | #include "tiling/tiling_api.h" |
| 17 | #include "exe_graph/runtime/tiling_context.h" | 17 | #include "exe_graph/runtime/tiling_context.h" |
| 18 | +#include "platform/platform_info.h" | ||
| 18 | 19 | ||
| 19 | namespace optiling { | 20 | namespace optiling { |
| 20 | namespace sparse_mla_checker { | 21 | namespace sparse_mla_checker { |
| @@ -40,6 +41,7 @@ struct TensorParam { | |||
| 40 | struct CheckContext { | 41 | struct CheckContext { |
| 41 | const char *opName = nullptr; | 42 | const char *opName = nullptr; |
| 42 | OperatorVariant variant = OperatorVariant::SPARSE; | 43 | OperatorVariant variant = OperatorVariant::SPARSE; |
| 44 | + NpuArch npuArch = NpuArch::DAV_2201; | ||
| 43 | 45 | ||
| 44 | TensorParam q; | 46 | TensorParam q; |
| 45 | TensorParam oriKv; | 47 | TensorParam oriKv; |
| @@ -15,6 +15,7 @@ | |||
| 15 | 15 | ||
| 16 | namespace optiling { | 16 | namespace optiling { |
| 17 | namespace sparse_mla_checker { | 17 | namespace sparse_mla_checker { |
| 18 | +constexpr int64_t TURBO_QUANT_MODE = 3; | ||
| 18 | constexpr uint32_t DIM_IDX_TWO = 2; | 19 | constexpr uint32_t DIM_IDX_TWO = 2; |
| 19 | constexpr uint32_t DIM_IDX_THREE = 3; | 20 | constexpr uint32_t DIM_IDX_THREE = 3; |
| 20 | 21 | ||
| @@ -23,6 +24,13 @@ const char *Op(const CheckContext &context) | |||
| 23 | { | 24 | { |
| 24 | return context.opName == nullptr ? "SparseMla" : context.opName; | 25 | return context.opName == nullptr ? "SparseMla" : context.opName; |
| 25 | } | 26 | } |
| 27 | + | ||
| 28 | +bool IsTurboQuantEmptyTndTensor(const CheckContext &context, const TensorParam ¶m) | ||
| 29 | +{ | ||
| 30 | + return context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE && | ||
| 31 | + context.qLayout == Layout::TND && param.shape != nullptr && param.shape->GetDimNum() > 0 && | ||
| 32 | + param.shape->GetDim(0) == 0; | ||
| 33 | +} | ||
| 26 | } // namespace | 34 | } // namespace |
| 27 | 35 | ||
| 28 | ge::graphStatus CommonChecker::CheckQuery(const CheckContext &context) const | 36 | ge::graphStatus CommonChecker::CheckQuery(const CheckContext &context) const |
| @@ -34,11 +42,14 @@ ge::graphStatus CommonChecker::CheckQuery(const CheckContext &context) const | |||
| 34 | if (context.variant == OperatorVariant::SPARSE) { | 42 | if (context.variant == OperatorVariant::SPARSE) { |
| 35 | status = CheckTensorDesc(context, context.q, "q", {ge::DT_FLOAT16, ge::DT_BF16}); | 43 | status = CheckTensorDesc(context, context.q, "q", {ge::DT_FLOAT16, ge::DT_BF16}); |
| 36 | } else if (context.variant == OperatorVariant::MIXED_QUANT) { | 44 | } else if (context.variant == OperatorVariant::MIXED_QUANT) { |
| 37 | - status = CheckTensorDesc(context, context.q, "q", {ge::DT_BF16}); | 45 | + status = context.quantMode == TURBO_QUANT_MODE ? |
| 46 | + CheckTensorDesc(context, context.q, "q", {ge::DT_FLOAT16, ge::DT_BF16}) : | ||
| 47 | + CheckTensorDesc(context, context.q, "q", {ge::DT_BF16}); | ||
| 38 | } else { | 48 | } else { |
| 39 | status = CheckTensorDesc(context, context.q, "q", {ge::DT_HIFLOAT8}); | 49 | status = CheckTensorDesc(context, context.q, "q", {ge::DT_HIFLOAT8}); |
| 40 | } | 50 | } |
| 41 | - if (status != ge::GRAPH_SUCCESS || CheckNoEmptyDim(context, context.q, "q") != ge::GRAPH_SUCCESS) { | 51 | + if (status != ge::GRAPH_SUCCESS || (!IsTurboQuantEmptyTndTensor(context, context.q) && |
| 52 | + CheckNoEmptyDim(context, context.q, "q") != ge::GRAPH_SUCCESS)) { | ||
| 42 | return ge::GRAPH_FAILED; | 53 | return ge::GRAPH_FAILED; |
| 43 | } | 54 | } |
| 44 | const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; | 55 | const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; |
| @@ -54,7 +65,12 @@ ge::graphStatus CommonChecker::CheckKv(const CheckContext &context, const Tensor | |||
| 54 | if (context.variant == OperatorVariant::SPARSE) { | 65 | if (context.variant == OperatorVariant::SPARSE) { |
| 55 | status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT16, ge::DT_BF16}); | 66 | status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT16, ge::DT_BF16}); |
| 56 | } else if (context.variant == OperatorVariant::MIXED_QUANT) { | 67 | } else if (context.variant == OperatorVariant::MIXED_QUANT) { |
| 57 | - status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT8_E4M3FN}); | 68 | + if (context.quantMode == TURBO_QUANT_MODE) { |
| 69 | + status = std::string(name) == "cmp_kv" ? CheckTensorDesc(context, kv, name, {ge::DT_UINT8}) : | ||
| 70 | + CheckTensorDesc(context, kv, name, {ge::DT_FLOAT16, ge::DT_BF16}); | ||
| 71 | + } else { | ||
| 72 | + status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT8_E4M3FN}); | ||
| 73 | + } | ||
| 58 | } else { | 74 | } else { |
| 59 | status = CheckTensorDesc(context, kv, name, {ge::DT_HIFLOAT8}); | 75 | status = CheckTensorDesc(context, kv, name, {ge::DT_HIFLOAT8}); |
| 60 | } | 76 | } |
| @@ -71,13 +87,15 @@ ge::graphStatus CommonChecker::CheckOutput(const CheckContext &context) const | |||
| 71 | return ge::GRAPH_SUCCESS; | 87 | return ge::GRAPH_SUCCESS; |
| 72 | } | 88 | } |
| 73 | ge::graphStatus status = ge::GRAPH_FAILED; | 89 | ge::graphStatus status = ge::GRAPH_FAILED; |
| 74 | - if (context.variant == OperatorVariant::SPARSE) { | 90 | + if (context.variant == OperatorVariant::SPARSE || |
| 91 | + (context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE)) { | ||
| 75 | status = CheckTensorDesc(context, context.attentionOut, "attention_out", {ge::DT_FLOAT16, ge::DT_BF16}); | 92 | status = CheckTensorDesc(context, context.attentionOut, "attention_out", {ge::DT_FLOAT16, ge::DT_BF16}); |
| 76 | } else { | 93 | } else { |
| 77 | status = CheckTensorDesc(context, context.attentionOut, "attention_out", {ge::DT_BF16}); | 94 | status = CheckTensorDesc(context, context.attentionOut, "attention_out", {ge::DT_BF16}); |
| 78 | } | 95 | } |
| 79 | if (status != ge::GRAPH_SUCCESS || | 96 | if (status != ge::GRAPH_SUCCESS || |
| 80 | - CheckNoEmptyDim(context, context.attentionOut, "attention_out") != ge::GRAPH_SUCCESS) { | 97 | + (!IsTurboQuantEmptyTndTensor(context, context.attentionOut) && |
| 98 | + CheckNoEmptyDim(context, context.attentionOut, "attention_out") != ge::GRAPH_SUCCESS)) { | ||
| 81 | return ge::GRAPH_FAILED; | 99 | return ge::GRAPH_FAILED; |
| 82 | } | 100 | } |
| 83 | const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; | 101 | const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; |
| @@ -152,7 +170,11 @@ ge::graphStatus CommonChecker::CheckQueryAxes(const CheckContext &context) const | |||
| 152 | qHeads = GetDim(context.q, DIM_IDX_TWO); | 170 | qHeads = GetDim(context.q, DIM_IDX_TWO); |
| 153 | qDim = GetDim(context.q, DIM_IDX_THREE); | 171 | qDim = GetDim(context.q, DIM_IDX_THREE); |
| 154 | } else { | 172 | } else { |
| 155 | - OP_CHECK_IF(qSeq <= 0, OP_LOGE_FOR_INVALID_SHAPESIZE(Op(context), "q_t", std::to_string(qSeq).c_str(), "> 0"), | 173 | + const bool turboQuant = |
| 174 | + context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE; | ||
| 175 | + OP_CHECK_IF(qSeq < 0 || (!turboQuant && qSeq == 0), | ||
| 176 | + OP_LOGE_FOR_INVALID_SHAPESIZE(Op(context), "q_t", std::to_string(qSeq).c_str(), | ||
| 177 | + turboQuant ? ">= 0" : "> 0"), | ||
| 156 | return ge::GRAPH_FAILED); | 178 | return ge::GRAPH_FAILED); |
| 157 | qHeads = GetDim(context.q, 1); | 179 | qHeads = GetDim(context.q, 1); |
| 158 | qDim = GetDim(context.q, DIM_IDX_TWO); | 180 | qDim = GetDim(context.q, DIM_IDX_TWO); |
| @@ -186,7 +208,12 @@ ge::graphStatus CommonChecker::CheckKvAxes(const CheckContext &context, const Te | |||
| 186 | return ge::GRAPH_FAILED); | 208 | return ge::GRAPH_FAILED); |
| 187 | int64_t expectedDim = 512; // 512:预期维度大小 | 209 | int64_t expectedDim = 512; // 512:预期维度大小 |
| 188 | if (context.variant == OperatorVariant::MIXED_QUANT) { | 210 | if (context.variant == OperatorVariant::MIXED_QUANT) { |
| 189 | - expectedDim = context.quantMode == 1 ? 608 : 584; // 608,584:混合量化模式下根据量化模式选择不同维度 | 211 | + if (context.quantMode == TURBO_QUANT_MODE) { |
| 212 | + // TurboQuant uses 512 dimensions for ori_kv and 258 bytes for packed cmp_kv. | ||
| 213 | + expectedDim = std::string(name) == "cmp_kv" ? 258 : 512; | ||
| 214 | + } else { | ||
| 215 | + expectedDim = context.quantMode == 1 ? 608 : 584; // 608,584:混合量化模式下根据量化模式选择不同维度 | ||
| 216 | + } | ||
| 190 | } | 217 | } |
| 191 | OP_CHECK_IF(headDim != expectedDim, | 218 | OP_CHECK_IF(headDim != expectedDim, |
| 192 | OP_LOGE_FOR_INVALID_VALUE(Op(context), (std::string(name) + " head dimension").c_str(), | 219 | OP_LOGE_FOR_INVALID_VALUE(Op(context), (std::string(name) + " head dimension").c_str(), |
| @@ -210,7 +237,8 @@ ge::graphStatus CommonChecker::CheckMultiPara(const CheckContext &context) const | |||
| 210 | CheckKvAxes(context, context.cmpKv, "cmp_kv") != ge::GRAPH_SUCCESS) { | 237 | CheckKvAxes(context, context.cmpKv, "cmp_kv") != ge::GRAPH_SUCCESS) { |
| 211 | return ge::GRAPH_FAILED; | 238 | return ge::GRAPH_FAILED; |
| 212 | } | 239 | } |
| 213 | - OP_CHECK_IF(context.variant == OperatorVariant::SPARSE && | 240 | + OP_CHECK_IF((context.variant == OperatorVariant::SPARSE || |
| 241 | + (context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE)) && | ||
| 214 | context.q.desc->GetDataType() != context.attentionOut.desc->GetDataType(), | 242 | context.q.desc->GetDataType() != context.attentionOut.desc->GetDataType(), |
| 215 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | 243 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( |
| 216 | Op(context), "q and attention_out", | 244 | Op(context), "q and attention_out", |
| @@ -219,7 +247,8 @@ ge::graphStatus CommonChecker::CheckMultiPara(const CheckContext &context) const | |||
| 219 | .c_str(), | 247 | .c_str(), |
| 220 | "Q and attention_out dtype must be the same"), | 248 | "Q and attention_out dtype must be the same"), |
| 221 | return ge::GRAPH_FAILED); | 249 | return ge::GRAPH_FAILED); |
| 222 | - if (context.variant == OperatorVariant::SPARSE) { | 250 | + if (context.variant == OperatorVariant::SPARSE || |
| 251 | + (context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE)) { | ||
| 223 | OP_CHECK_IF(context.q.desc->GetDataType() != context.oriKv.desc->GetDataType(), | 252 | OP_CHECK_IF(context.q.desc->GetDataType() != context.oriKv.desc->GetDataType(), |
| 224 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | 253 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( |
| 225 | Op(context), "q and ori_kv", | 254 | Op(context), "q and ori_kv", |
| @@ -228,7 +257,8 @@ ge::graphStatus CommonChecker::CheckMultiPara(const CheckContext &context) const | |||
| 228 | .c_str(), | 257 | .c_str(), |
| 229 | "Q and ori_kv dtype must be the same"), | 258 | "Q and ori_kv dtype must be the same"), |
| 230 | return ge::GRAPH_FAILED); | 259 | return ge::GRAPH_FAILED); |
| 231 | - OP_CHECK_IF(context.cmpKv.present && context.q.desc->GetDataType() != context.cmpKv.desc->GetDataType(), | 260 | + OP_CHECK_IF(context.variant == OperatorVariant::SPARSE && context.cmpKv.present && |
| 261 | + context.q.desc->GetDataType() != context.cmpKv.desc->GetDataType(), | ||
| 232 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | 262 | OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( |
| 233 | Op(context), "q and cmp_kv", | 263 | Op(context), "q and cmp_kv", |
| 234 | (std::to_string(static_cast<int32_t>(context.q.desc->GetDataType())) + " and " + | 264 | (std::to_string(static_cast<int32_t>(context.q.desc->GetDataType())) + " and " + |
| @@ -13,6 +13,7 @@ | |||
| 13 | 13 | ||
| 14 | namespace optiling { | 14 | namespace optiling { |
| 15 | namespace sparse_mla_checker { | 15 | namespace sparse_mla_checker { |
| 16 | +constexpr int64_t TURBO_QUANT_MODE = 3; | ||
| 16 | namespace { | 17 | namespace { |
| 17 | const char *Op(const CheckContext &context) | 18 | const char *Op(const CheckContext &context) |
| 18 | { | 19 | { |
| @@ -45,24 +46,31 @@ ge::graphStatus PagedAttentionChecker::CheckSinglePara(const CheckContext &conte | |||
| 45 | 46 | ||
| 46 | ge::graphStatus PagedAttentionChecker::CheckParaExistence(const CheckContext &context) const | 47 | ge::graphStatus PagedAttentionChecker::CheckParaExistence(const CheckContext &context) const |
| 47 | { | 48 | { |
| 48 | - if (context.kvLayout != Layout::PA_BBND) { | 49 | + if (context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE) { |
| 49 | - OP_CHECK_IF(context.oriBlockTable.present || context.cmpBlockTable.present, | 50 | + OP_CHECK_IF(!context.oriBlockTable.present || !context.cmpBlockTable.present, |
| 50 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 51 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "ori_block_table/cmp_block_table", |
| 51 | - Op(context), "ori_block_table and cmp_block_table", | 52 | + "TurboQuant requires both block tables"), |
| 52 | - "Block tables are only supported when layout_kv is PA_BBND"), | ||
| 53 | return ge::GRAPH_FAILED); | 53 | return ge::GRAPH_FAILED); |
| 54 | return ge::GRAPH_SUCCESS; | 54 | return ge::GRAPH_SUCCESS; |
| 55 | } | 55 | } |
| 56 | + if (context.kvLayout != Layout::PA_BBND) { | ||
| 57 | + OP_CHECK_IF( | ||
| 58 | + context.oriBlockTable.present || context.cmpBlockTable.present, | ||
| 59 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "ori_block_table and cmp_block_table", | ||
| 60 | + "Block tables are only supported when layout_kv is PA_BBND"), | ||
| 61 | + return ge::GRAPH_FAILED); | ||
| 62 | + return ge::GRAPH_SUCCESS; | ||
| 63 | + } | ||
| 56 | 64 | ||
| 57 | OP_CHECK_IF(!context.oriBlockTable.present, | 65 | OP_CHECK_IF(!context.oriBlockTable.present, |
| 58 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 66 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "ori_block_table", |
| 59 | - Op(context), "ori_block_table", "Ori_block_table is required when layout_kv is PA_BBND"), | 67 | + "Ori_block_table is required when layout_kv is PA_BBND"), |
| 60 | - return ge::GRAPH_FAILED); | ||
| 61 | - OP_CHECK_IF(context.cmpKv.present != context.cmpBlockTable.present, | ||
| 62 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | ||
| 63 | - Op(context), "cmp_block_table", | ||
| 64 | - "Cmp_block_table must be present exactly when PA cmp_kv is present"), | ||
| 65 | return ge::GRAPH_FAILED); | 68 | return ge::GRAPH_FAILED); |
| 69 | + OP_CHECK_IF( | ||
| 70 | + context.cmpKv.present != context.cmpBlockTable.present, | ||
| 71 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cmp_block_table", | ||
| 72 | + "Cmp_block_table must be present exactly when PA cmp_kv is present"), | ||
| 73 | + return ge::GRAPH_FAILED); | ||
| 66 | OP_CHECK_IF(context.oriBlockTable.present && !context.sequsedOriKv.present && !CanOmitSequsedOriKv(context), | 74 | OP_CHECK_IF(context.oriBlockTable.present && !context.sequsedOriKv.present && !CanOmitSequsedOriKv(context), |
| 67 | OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 75 | OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( |
| 68 | Op(context), "seqused_ori_kv and ori_topk_length", | 76 | Op(context), "seqused_ori_kv and ori_topk_length", |
| @@ -13,6 +13,7 @@ | |||
| 13 | 13 | ||
| 14 | namespace optiling { | 14 | namespace optiling { |
| 15 | namespace sparse_mla_checker { | 15 | namespace sparse_mla_checker { |
| 16 | +constexpr int64_t TURBO_QUANT_MODE = 3; | ||
| 16 | namespace { | 17 | namespace { |
| 17 | const char *Op(const CheckContext &context) | 18 | const char *Op(const CheckContext &context) |
| 18 | { | 19 | { |
| @@ -50,35 +51,45 @@ ge::graphStatus SeqLenChecker::CheckSinglePara(const CheckContext &context) cons | |||
| 50 | 51 | ||
| 51 | ge::graphStatus SeqLenChecker::CheckParaExistence(const CheckContext &context) const | 52 | ge::graphStatus SeqLenChecker::CheckParaExistence(const CheckContext &context) const |
| 52 | { | 53 | { |
| 54 | + if (context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE) { | ||
| 55 | + OP_CHECK_IF(!context.cuSeqlensQ.present || !context.sequsedOriKv.present, | ||
| 56 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cu_seqlens_q/seqused_ori_kv", | ||
| 57 | + "TurboQuant requires both inputs"), | ||
| 58 | + return ge::GRAPH_FAILED); | ||
| 59 | + OP_CHECK_IF(context.cuSeqlensOriKv.present || context.cuSeqlensCmpKv.present || context.sequsedQ.present || | ||
| 60 | + context.sequsedCmpKv.present || context.cmpResidualKv.present, | ||
| 61 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | ||
| 62 | + Op(context), "sequence inputs", "Unsupported sequence inputs were supplied for TurboQuant"), | ||
| 63 | + return ge::GRAPH_FAILED); | ||
| 64 | + return ge::GRAPH_SUCCESS; | ||
| 65 | + } | ||
| 53 | if (context.qLayout == Layout::TND) { | 66 | if (context.qLayout == Layout::TND) { |
| 54 | OP_CHECK_IF(!context.cuSeqlensQ.present, | 67 | OP_CHECK_IF(!context.cuSeqlensQ.present, |
| 55 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 68 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cu_seqlens_q", |
| 56 | - Op(context), "cu_seqlens_q", "Cu_seqlens_q is required when layout_q is TND"), | 69 | + "Cu_seqlens_q is required when layout_q is TND"), |
| 57 | return ge::GRAPH_FAILED); | 70 | return ge::GRAPH_FAILED); |
| 58 | } else { | 71 | } else { |
| 59 | OP_CHECK_IF(context.cuSeqlensQ.present, | 72 | OP_CHECK_IF(context.cuSeqlensQ.present, |
| 60 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 73 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cu_seqlens_q", |
| 61 | - Op(context), "cu_seqlens_q", "Cu_seqlens_q is only supported when layout_q is TND"), | 74 | + "Cu_seqlens_q is only supported when layout_q is TND"), |
| 62 | return ge::GRAPH_FAILED); | 75 | return ge::GRAPH_FAILED); |
| 63 | } | 76 | } |
| 64 | 77 | ||
| 65 | if (context.kvLayout == Layout::TND) { | 78 | if (context.kvLayout == Layout::TND) { |
| 66 | OP_CHECK_IF(!context.cuSeqlensOriKv.present, | 79 | OP_CHECK_IF(!context.cuSeqlensOriKv.present, |
| 67 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 80 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cu_seqlens_ori_kv", |
| 68 | - Op(context), "cu_seqlens_ori_kv", | 81 | + "Cu_seqlens_ori_kv is required when layout_kv is TND"), |
| 69 | - "Cu_seqlens_ori_kv is required when layout_kv is TND"), | ||
| 70 | return ge::GRAPH_FAILED); | 82 | return ge::GRAPH_FAILED); |
| 71 | OP_CHECK_IF(context.cmpKv.present && !context.cuSeqlensCmpKv.present, | 83 | OP_CHECK_IF(context.cmpKv.present && !context.cuSeqlensCmpKv.present, |
| 72 | OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 84 | OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( |
| 73 | - Op(context), "cu_seqlens_cmp_kv", | 85 | + Op(context), "cu_seqlens_cmp_kv", "Cu_seqlens_cmp_kv is required when TND cmp_kv is present"), |
| 74 | - "Cu_seqlens_cmp_kv is required when TND cmp_kv is present"), | ||
| 75 | return ge::GRAPH_FAILED); | 86 | return ge::GRAPH_FAILED); |
| 76 | } else { | 87 | } else { |
| 77 | - OP_CHECK_IF(context.cuSeqlensOriKv.present || context.cuSeqlensCmpKv.present, | 88 | + OP_CHECK_IF( |
| 78 | - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | 89 | + context.cuSeqlensOriKv.present || context.cuSeqlensCmpKv.present, |
| 79 | - Op(context), "cu_seqlens_ori_kv and cu_seqlens_cmp_kv", | 90 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cu_seqlens_ori_kv and cu_seqlens_cmp_kv", |
| 80 | - "KV cu_seqlens inputs are only supported when layout_kv is TND"), | 91 | + "KV cu_seqlens inputs are only supported when layout_kv is TND"), |
| 81 | - return ge::GRAPH_FAILED); | 92 | + return ge::GRAPH_FAILED); |
| 82 | } | 93 | } |
| 83 | 94 | ||
| 84 | if (context.kvLayout == Layout::PA_BBND) { | 95 | if (context.kvLayout == Layout::PA_BBND) { |
| @@ -105,9 +116,8 @@ ge::graphStatus SeqLenChecker::CheckLength(const CheckContext &context, const Te | |||
| 105 | return ge::GRAPH_SUCCESS; | 116 | return ge::GRAPH_SUCCESS; |
| 106 | } | 117 | } |
| 107 | OP_CHECK_IF(GetDim(param, 0) != expected, | 118 | OP_CHECK_IF(GetDim(param, 0) != expected, |
| 108 | - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( | 119 | + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(Op(context), name, std::to_string(GetDim(param, 0)).c_str(), |
| 109 | - Op(context), name, std::to_string(GetDim(param, 0)).c_str(), | 120 | + ("The length must be " + std::to_string(expected)).c_str()), |
| 110 | - ("The length must be " + std::to_string(expected)).c_str()), | ||
| 111 | return ge::GRAPH_FAILED); | 121 | return ge::GRAPH_FAILED); |
| 112 | return ge::GRAPH_SUCCESS; | 122 | return ge::GRAPH_SUCCESS; |
| 113 | } | 123 | } |
| @@ -13,11 +13,19 @@ | |||
| 13 | 13 | ||
| 14 | namespace optiling { | 14 | namespace optiling { |
| 15 | namespace sparse_mla_checker { | 15 | namespace sparse_mla_checker { |
| 16 | +constexpr int64_t TURBO_QUANT_MODE = 3; | ||
| 16 | namespace { | 17 | namespace { |
| 17 | const char *Op(const CheckContext &context) | 18 | const char *Op(const CheckContext &context) |
| 18 | { | 19 | { |
| 19 | return context.opName == nullptr ? "SparseMla" : context.opName; | 20 | return context.opName == nullptr ? "SparseMla" : context.opName; |
| 20 | } | 21 | } |
| 22 | + | ||
| 23 | +bool IsTurboQuantEmptyTndIndex(const CheckContext &context, const TensorParam ¶m, const char *name) | ||
| 24 | +{ | ||
| 25 | + return context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE && | ||
| 26 | + context.qLayout == Layout::TND && std::string(name) == "cmp_sparse_indices" && param.shape != nullptr && | ||
| 27 | + param.shape->GetDimNum() > 0 && param.shape->GetDim(0) == 0; | ||
| 28 | +} | ||
| 21 | } // namespace | 29 | } // namespace |
| 22 | 30 | ||
| 23 | ge::graphStatus SparseCompressionChecker::CheckIndex(const CheckContext &context, const TensorParam ¶m, | 31 | ge::graphStatus SparseCompressionChecker::CheckIndex(const CheckContext &context, const TensorParam ¶m, |
| @@ -29,7 +37,8 @@ ge::graphStatus SparseCompressionChecker::CheckIndex(const CheckContext &context | |||
| 29 | const size_t dimNum = context.qLayout == Layout::BSND ? 4U : 3U; | 37 | const size_t dimNum = context.qLayout == Layout::BSND ? 4U : 3U; |
| 30 | if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != ge::GRAPH_SUCCESS || | 38 | if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != ge::GRAPH_SUCCESS || |
| 31 | CheckDimNum(context, param, name, {dimNum}) != ge::GRAPH_SUCCESS || | 39 | CheckDimNum(context, param, name, {dimNum}) != ge::GRAPH_SUCCESS || |
| 32 | - CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS) { | 40 | + (!IsTurboQuantEmptyTndIndex(context, param, name) && |
| 41 | + CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS)) { | ||
| 33 | return ge::GRAPH_FAILED; | 42 | return ge::GRAPH_FAILED; |
| 34 | } | 43 | } |
| 35 | return ge::GRAPH_SUCCESS; | 44 | return ge::GRAPH_SUCCESS; |
| @@ -72,6 +81,19 @@ ge::graphStatus SparseCompressionChecker::CheckSinglePara(const CheckContext &co | |||
| 72 | 81 | ||
| 73 | ge::graphStatus SparseCompressionChecker::CheckParaExistence(const CheckContext &context) const | 82 | ge::graphStatus SparseCompressionChecker::CheckParaExistence(const CheckContext &context) const |
| 74 | { | 83 | { |
| 84 | + if (context.variant == OperatorVariant::MIXED_QUANT && context.quantMode == TURBO_QUANT_MODE) { | ||
| 85 | + OP_CHECK_IF(!context.cmpKv.present || !context.cmpSparseIndices.present, | ||
| 86 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cmp_kv/cmp_sparse_indices", | ||
| 87 | + "TurboQuant requires both inputs"), | ||
| 88 | + return ge::GRAPH_FAILED); | ||
| 89 | + OP_CHECK_IF(context.oriSparseIndices.present || context.cmpResidualKv.present || | ||
| 90 | + context.oriTopkLength.present || context.cmpTopkLength.present, | ||
| 91 | + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( | ||
| 92 | + Op(context), "unsupported TurboQuant inputs", | ||
| 93 | + "ori_sparse_indices, cmp_residual_kv and topk length inputs must be absent"), | ||
| 94 | + return ge::GRAPH_FAILED); | ||
| 95 | + return ge::GRAPH_SUCCESS; | ||
| 96 | + } | ||
| 75 | if (!context.cmpKv.present) { | 97 | if (!context.cmpKv.present) { |
| 76 | OP_CHECK_IF(context.cmpSparseIndices.present, | 98 | OP_CHECK_IF(context.cmpSparseIndices.present, |
| 77 | OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cmp_sparse_indices", | 99 | OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Op(context), "cmp_sparse_indices", |