Merged
新增sparse_flash_mla_softmax_l1_norm算子 #8956
新增sparse_flash_mla_softmax_l1_norm算子 #8956
Merged
dai-yuwenAdd on Jul 21
Total: 32 files changed+6206-0
@@ -0,0 +1,19 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+if(NOT ENABLE_TEST AND NOT BENCHMARK)
13+ list(REMOVE_ITEM CURRENT_DIRS tests)
14+endif()
15+foreach(SUB_DIR ${CURRENT_DIRS})
16+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
17+ add_subdirectory(${SUB_DIR})
18+ endif()
19+endforeach()
@@ -0,0 +1,93 @@
1+# SparseFlashMlaSoftmaxL1Norm
2+ 
3+## 产品支持情况
4+ 
5+| 产品 | 是否支持 |
6+| ------------------------------------------------------------ | :------: |
7+| <term>Ascend 950PR/Ascend 950DT</term> | √ |
8+| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | × |
9+| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | × |
10+| <term>Atlas 200I/500 A2 推理产品</term> | × |
11+| <term>Atlas 推理系列产品</term> | × |
12+| <term>Atlas 训练系列产品</term> | × |
13+ 
14+## 功能说明
15+ 
16+- 算子功能:计算`SparseFlashMla`注意力的Softmax L1Norm结果,支持Compressed Attention以及Sparse Compressed Attention场景。该算子为`aclnnDenseLightningIndexerKLLossGrad`反向算子的配套正向接口,输出可用于反向梯度计算。调用过程中,需先调用`SparseFlashMlaSoftmaxL1NormMetadata`算子完成负载均衡计算,再调用本算子完成计算过程。
17+ 
18+- 计算公式:
19+ 
20+ 阶段一:根据是否为sparse场景,对输入key进行选择
21+ 
22+ * 当为sparse时:
23+ 
24+ $$
25+ selectedKv = Gather(K, sparseIndices[i]),\ 0 <= i < selectBlockCount
26+ $$
27+ 
28+ * else:
29+ 
30+ $$
31+ selectedKv = K
32+ $$
33+ 
34+ 阶段二:计算P(SimpleSoftmax)
35+ 
36+ $$
37+ P = SimpleSoftmax(Mask(Q @ selectedKv^{T} \cdot scale), softmaxLse)
38+ $$
39+ 
40+ 阶段三:计算Softmax L1Norm
41+ 
42+ $$
43+ softmaxL1Norm = \frac{ReduceSum(P, dim=G)}{G}
44+ $$
45+ 
46+ 其中,$G$ 为group数($G = N1 / N2$)。
47+ 
48+## 参数说明
49+ 
50+| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 |
51+| ------ | -------------- | ---- | -------- | -------- |
52+| q | 输入 | attention结构的输入Q。 | FLOAT16、BFLOAT16 | ND |
53+| k | 输入 | attention结构的输入K(V)。 | FLOAT16、BFLOAT16 | ND |
54+| softmax_lse | 输入 | 注意力正向计算的输出softmaxLse,计算公式详见sparse_flash_mla文档。 | FLOAT32 | ND |
55+| sparse_indices | 可选输入 | 稀疏场景下选择的k中权重较高的注意力索引。 | INT32 | ND |
56+| cu_seqlens_q | 可选输入 | 每个Batch中Query的有效token数的累加和形式。layout为TND时该参数必传。 | INT32 | ND |
57+| cu_seqlens_k | 可选输入 | 每个Batch中Key的有效token数的累加和形式。layout为TND时该参数必传。 | INT32 | ND |
58+| seqused_q | 可选输入 | 表示不同batch中q实际参与运算的token数。 | INT32 | ND |
59+| seqused_k | 可选输入 | 表示不同batch中k实际参与运算的token数。 | INT32 | ND |
60+| cmp_residual_k | 可选输入 | 表示每个batch S2 // cmpRatio后的余数。当k不为空且mask_mode=3时必须传入。 | INT32 | ND |
61+| topk_length | 可选输入 | 表示每行q对应的k实际可选的topk长度。mask_mode=0且存在稀疏索引时需要传。 | INT32 | ND |
62+| metadata | 可选输入 | 表示tiling下沉的aicpu算子输出结果,由`SparseFlashMlaSoftmaxL1NormMetadata`算子生成。 | INT32 | ND |
63+| softmax_scale | 可选属性 | 缩放系数,默认值为1.0。推荐值:sqrt(head_dim)的倒数。 | FLOAT32 | - |
64+| max_seqlen_k | 可选属性 | 表示k的最大序列长度,TND dense场景用于输出shape推导,默认值为0。 | INT64 | - |
65+| cmp_ratio | 可选属性 | 表示对k的压缩率,取值范围1~128,默认值为1。 | INT64 | - |
66+| mask_mode | 可选属性 | 表示q和k计算的mask模式。0:No mask;3:rightDownCausal模式。默认值为0。 | INT64 | - |
67+| layout_q | 可选属性 | 表示输入q的数据排布格式,支持"BSND"、"TND",默认值为"BSND"。 | STRING | - |
68+| layout_k | 可选属性 | 表示输入k的数据排布格式,支持"BSND"、"TND",默认值为"BSND"。 | STRING | - |
69+| softmax_l1_norm | 输出 | 表示q与k计算得出的softmax L1Norm结果,公式为reduceG(softmax)/G。若存在sparse_indices则该输出不为空,其他场景下输出为空。 | FLOAT32 | ND |
70+ 
71+## 约束说明
72+ 
73+- 确定性说明:aclnnSparseFlashMlaSoftmaxL1Norm默认确定性实现。
74+- 仅支持BSND或TND layout,且layout_q与layout_k必须保持一致。
75+- 关于数据shape的约束:
76+ - B:泛化支持。
77+ - S1、S2:泛化支持,支持S1、S2不等长。
78+ - N1:支持1~128,且num_heads_q必须能被num_heads_k整除。
79+ - N2:仅支持1。
80+ - D:仅支持512。
81+- mask_mode支持:
82+ - 0:不做mask操作。
83+ - 3:rightDownCausal模式的mask,对应以右顶点为划分的下三角场景。
84+- cmp_ratio取值范围:1~128。
85+- TND场景:必传cu_seqlens_q和cu_seqlens_k参数。
86+- metadata必须传入,由`SparseFlashMlaSoftmaxL1NormMetadata`算子生成。
87+ 
88+## 调用说明
89+ 
90+| 调用方式 | 调用样例 | 说明 |
91+| -------- | -------- | ---- |
92+| aclnn API | [test_aclnn_sparse_flash_mla_softmax_l1_norm](examples/test_aclnn_sparse_flash_mla_softmax_l1_norm.cpp) | 通过[aclnnSparseFlashMlaSoftmaxL1Norm](docs/aclnnSparseFlashMlaSoftmaxL1Norm.md)接口方式调用算子。 |
93+| PyTorch API | - | 通过[sparse_flash_mla_softmax_l1_norm](../../torch_extension/cann_ops_transformer/docs/zh/sparse_flash_mla_softmax_l1_norm.md)接口调用算子。 |
@@ -0,0 +1,219 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <iostream>
12+#include <vector>
13+#include "acl/acl.h"
14+#include "aclnnop/aclnn_sparse_flash_mla_softmax_l1_norm.h"
15+#include "aclnnop/aclnn_sparse_flash_mla_softmax_l1_norm_metadata.h"
16+ 
17+#define CHECK_RET(cond, return_expr) \
18+ do { \
19+ if (!(cond)) { \
20+ return_expr; \
21+ } \
22+ } while (0)
23+ 
24+#define LOG_PRINT(message, ...) \
25+ do { \
26+ printf(message, ##__VA_ARGS__); \
27+ } while (0)
28+ 
29+int64_t GetShapeSize(const std::vector<int64_t> &shape)
30+{
31+ int64_t shapeSize = 1;
32+ for (auto i : shape) {
33+ shapeSize *= i;
34+ }
35+ return shapeSize;
36+}
37+ 
38+int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream)
39+{
40+ auto ret = aclInit(nullptr);
41+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
42+ ret = aclrtSetDevice(deviceId);
43+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
44+ ret = aclrtCreateContext(context, deviceId);
45+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
46+ ret = aclrtSetCurrentContext(*context);
47+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret); return ret);
48+ ret = aclrtCreateStream(stream);
49+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
50+ return 0;
51+}
52+ 
53+template <typename T>
54+int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
55+ aclDataType dataType, aclTensor **tensor)
56+{
57+ auto size = GetShapeSize(shape) * sizeof(T);
58+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
59+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
60+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
61+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
62+ std::vector<int64_t> strides(shape.size(), 1);
63+ for (int64_t i = shape.size() - 2; i >= 0; i--) {
64+ strides[i] = shape[i + 1] * strides[i + 1];
65+ }
66+ *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
67+ shape.data(), shape.size(), *deviceAddr);
68+ return 0;
69+}
70+ 
71+int main()
72+{
73+ int32_t deviceId = 0;
74+ aclrtContext context;
75+ aclrtStream stream;
76+ auto ret = Init(deviceId, &context, &stream);
77+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
78+ 
79+ // TND layout: qShape=(T1,N1,D), kShape=(T2,N2,D), softmaxLseShape=(N2,T1,G)
80+ std::vector<int64_t> qShape = {16, 128, 512};
81+ std::vector<int64_t> kShape = {2048, 1, 512};
82+ std::vector<int64_t> softmaxLseShape = {1, 16, 128};
83+ std::vector<int64_t> cuSeqQLenshape = {2};
84+ std::vector<int64_t> cuSeqKLenshape = {2};
85+ std::vector<int64_t> cmpResidualKShape = {1};
86+ std::vector<int64_t> softmaxL1NormShape = {16, 1, 2048};
87+ std::vector<int64_t> metadataShape = {64};
88+ 
89+ void *qDeviceAddr = nullptr;
90+ void *kDeviceAddr = nullptr;
91+ void *softmaxLseDeviceAddr = nullptr;
92+ void *cuSeqQLenDeviceAddr = nullptr;
93+ void *cuSeqKLenDeviceAddr = nullptr;
94+ void *cmpResidualKDeviceAddr = nullptr;
95+ void *softmaxL1NormDeviceAddr = nullptr;
96+ void *metadataDeviceAddr = nullptr;
97+ 
98+ aclTensor *q = nullptr;
99+ aclTensor *k = nullptr;
100+ aclTensor *softmaxLse = nullptr;
101+ aclTensor *cuSeqQLen = nullptr;
102+ aclTensor *cuSeqKLen = nullptr;
103+ aclTensor *cmpResidualK = nullptr;
104+ aclTensor *softmaxL1Norm = nullptr;
105+ aclTensor *metadata = nullptr;
106+ 
107+ std::vector<short> qHostData(16 * 128 * 512, 1.0);
108+ std::vector<short> kHostData(2048 * 1 * 512, 1.0);
109+ std::vector<float> softmaxLseHostData(1 * 16 * 128, 3.0);
110+ std::vector<int32_t> cuSeqQLenHostData = {0, 16};
111+ std::vector<int32_t> cuSeqKLenHostData = {0, 2048};
112+ std::vector<int32_t> cmpResidualKHostData = {0};
113+ std::vector<float> softmaxL1NormHostData(16 * 1 * 2048, 0);
114+ std::vector<int32_t> metadataHostData(64, 0);
115+ 
116+ ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
117+ CHECK_RET(ret == ACL_SUCCESS, return ret);
118+ ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
119+ CHECK_RET(ret == ACL_SUCCESS, return ret);
120+ ret = CreateAclTensor(softmaxLseHostData, softmaxLseShape, &softmaxLseDeviceAddr, aclDataType::ACL_FLOAT,
121+ &softmaxLse);
122+ CHECK_RET(ret == ACL_SUCCESS, return ret);
123+ ret = CreateAclTensor(cuSeqQLenHostData, cuSeqQLenshape, &cuSeqQLenDeviceAddr, aclDataType::ACL_INT32, &cuSeqQLen);
124+ CHECK_RET(ret == ACL_SUCCESS, return ret);
125+ ret = CreateAclTensor(cuSeqKLenHostData, cuSeqKLenshape, &cuSeqKLenDeviceAddr, aclDataType::ACL_INT32, &cuSeqKLen);
126+ CHECK_RET(ret == ACL_SUCCESS, return ret);
127+ ret = CreateAclTensor(cmpResidualKHostData, cmpResidualKShape, &cmpResidualKDeviceAddr, aclDataType::ACL_INT32,
128+ &cmpResidualK);
129+ CHECK_RET(ret == ACL_SUCCESS, return ret);
130+ ret = CreateAclTensor(softmaxL1NormHostData, softmaxL1NormShape, &softmaxL1NormDeviceAddr, aclDataType::ACL_FLOAT,
131+ &softmaxL1Norm);
132+ CHECK_RET(ret == ACL_SUCCESS, return ret);
133+ ret = CreateAclTensor(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
134+ CHECK_RET(ret == ACL_SUCCESS, return ret);
135+ 
136+ double softmaxScale = 0.088388;
137+ int64_t maxSeqlenK = 2048;
138+ int64_t cmpRatio = 128;
139+ int64_t maskMode = 3;
140+ char layoutQ[4] = {'T', 'N', 'D', 0};
141+ char layoutK[4] = {'T', 'N', 'D', 0};
142+ 
143+ // 1. 调用 metadata 前置算子
144+ uint64_t metadataWorkspaceSize = 0;
145+ aclOpExecutor *metadataExecutor = nullptr;
146+ ret = aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize(
147+ cuSeqQLen, cuSeqKLen, nullptr, nullptr, cmpResidualK, nullptr, 0, 16, 2048, 128, 1, 512, 0, cmpRatio, maskMode,
148+ layoutQ, layoutK, metadata, &metadataWorkspaceSize, &metadataExecutor);
149+ CHECK_RET(ret == ACL_SUCCESS,
150+ LOG_PRINT("aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
151+ return ret);
152+ void *metadataWorkspaceAddr = nullptr;
153+ if (metadataWorkspaceSize > 0) {
154+ ret = aclrtMalloc(&metadataWorkspaceAddr, metadataWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
155+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
156+ }
157+ ret = aclnnSparseFlashMlaSoftmaxL1NormMetadata(metadataWorkspaceAddr, metadataWorkspaceSize, metadataExecutor,
158+ stream);
159+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashMlaSoftmaxL1NormMetadata failed. ERROR: %d\n", ret);
160+ return ret);
161+ ret = aclrtSynchronizeStream(stream);
162+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
163+ 
164+ // 2. 调用主算子
165+ uint64_t workspaceSize = 0;
166+ aclOpExecutor *executor = nullptr;
167+ ret = aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize(
168+ q, k, softmaxLse, nullptr, cuSeqQLen, cuSeqKLen, nullptr, nullptr, cmpResidualK, nullptr, metadata,
169+ softmaxScale, maxSeqlenK, cmpRatio, maskMode, layoutQ, layoutK, softmaxL1Norm, &workspaceSize, &executor);
170+ CHECK_RET(ret == ACL_SUCCESS,
171+ LOG_PRINT("aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize failed. ERROR: %d\n", ret);
172+ return ret);
173+ 
174+ void *workspaceAddr = nullptr;
175+ if (workspaceSize > 0) {
176+ ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
177+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
178+ }
179+ 
180+ try {
181+ ret = aclnnSparseFlashMlaSoftmaxL1Norm(workspaceAddr, workspaceSize, executor, stream);
182+ if (ret != ACL_SUCCESS) {
183+ LOG_PRINT("Expected kernel failure (skeleton stage): ERROR: %d\n", ret);
184+ } else {
185+ ret = aclrtSynchronizeStream(stream);
186+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
187+ }
188+ } catch (const std::exception &e) {
189+ LOG_PRINT("Expected kernel failure (skeleton stage): %s\n", e.what());
190+ }
191+ 
192+ aclDestroyTensor(q);
193+ aclDestroyTensor(k);
194+ aclDestroyTensor(softmaxLse);
195+ aclDestroyTensor(cuSeqQLen);
196+ aclDestroyTensor(cuSeqKLen);
197+ aclDestroyTensor(cmpResidualK);
198+ aclDestroyTensor(softmaxL1Norm);
199+ aclDestroyTensor(metadata);
200+ aclrtFree(qDeviceAddr);
201+ aclrtFree(kDeviceAddr);
202+ aclrtFree(softmaxLseDeviceAddr);
203+ aclrtFree(cuSeqQLenDeviceAddr);
204+ aclrtFree(cuSeqKLenDeviceAddr);
205+ aclrtFree(cmpResidualKDeviceAddr);
206+ aclrtFree(softmaxL1NormDeviceAddr);
207+ aclrtFree(metadataDeviceAddr);
208+ if (workspaceSize > 0) {
209+ aclrtFree(workspaceAddr);
210+ }
211+ if (metadataWorkspaceSize > 0) {
212+ aclrtFree(metadataWorkspaceAddr);
213+ }
214+ aclrtDestroyStream(stream);
215+ aclrtDestroyContext(context);
216+ aclrtResetDevice(deviceId);
217+ aclFinalize();
218+ return 0;
219+}
@@ -0,0 +1,54 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, 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+require_pypto_pro(sparse_flash_mla_softmax_l1_norm)
11+add_op_to_compiled_list()
12+ 
13+if (BUILD_OPEN_PROJECT)
14+ target_sources(op_host_aclnn PRIVATE
15+ sparse_flash_mla_softmax_l1_norm_def.cpp
16+ )
17+ add_modules_sources(OPTYPE sparse_flash_mla_softmax_l1_norm ACLNNTYPE aclnn)
18+ enable_pypto_kernel(sparse_flash_mla_softmax_l1_norm)
19+endif()
20+ 
21+# ascend950 条件编译——缺少此项会导致 kernel binary 未编译
22+set(CONDITION_UNIT ${ASCEND_COMPUTE_UNIT})
23+if("${CONDITION_UNIT}" STREQUAL "ascend950")
24+ # PyPTO kernel: runs codegen at configure time and exposes PYPTO_GEN_DIR for the host tiling -I below.
25+ # Must be called BEFORE add_modules_sources(...) (which reads PYPTO_GEN_DIR).
26+ add_ops_compile_options(
27+ OP_NAME SparseFlashMlaSoftmaxL1Norm
28+ COMPUTE_UNIT Ascend950PR_9599
29+ OPTIONS -DENABLE_CV_COMM_VIA_SSBUF=true
30+ )
31+endif()
32+ 
33+if (BUILD_OPS_RTY_KERNEL)
34+ add_ops_compile_options(
35+ OP_NAME SparseFlashMlaSoftmaxL1Norm
36+ OPTIONS --cce-auto-sync=off
37+ -Wno-deprecated-declarations
38+ -Werror
39+ )
40+else()
41+ add_ops_compile_options(
42+ OP_NAME SparseFlashMlaSoftmaxL1Norm
43+ OPTIONS --cce-auto-sync=off
44+ -Wno-deprecated-declarations
45+ )
46+endif()
47+ 
48+if(NOT BUILD_OPS_RTY_KERNEL)
49+ add_modules_sources(OPTYPE sparse_flash_mla_softmax_l1_norm ACLNNTYPE aclnn)
50+endif()
51+ 
52+if(NOT BUILD_OPS_RTY_KERNEL)
53+ add_tiling_modules()
54+endif()
@@ -0,0 +1,337 @@
1+{
2+ "op_type": "SparseFlashMlaSoftmaxL1Norm",
3+ "op_list": [
4+ {
5+ "bin_filename": "SparseFlashMlaSoftmaxL1Norm_0e2106133132dc56a5e028c3ab148b85",
6+ "inputs": [
7+ {
8+ "name": "q",
9+ "index": 0,
10+ "dtype": "bfloat16",
11+ "format": "ND",
12+ "paramType": "required",
13+ "shape": [
14+ -2
15+ ],
16+ "format_match_mode": "FormatAgnostic"
17+ },
18+ {
19+ "name": "k",
20+ "index": 1,
21+ "dtype": "bfloat16",
22+ "format": "ND",
23+ "paramType": "required",
24+ "shape": [
25+ -2
26+ ],
27+ "format_match_mode": "FormatAgnostic"
28+ },
29+ {
30+ "name": "softmax_lse",
31+ "index": 2,
32+ "dtype": "float32",
33+ "format": "ND",
34+ "paramType": "required",
35+ "shape": [
36+ -2
37+ ],
38+ "format_match_mode": "FormatAgnostic"
39+ },
40+ {
41+ "name": "sparse_indices",
42+ "index": 3,
43+ "dtype": "int32",
44+ "format": "ND",
45+ "paramType": "optional",
46+ "shape": [
47+ -2
48+ ],
49+ "format_match_mode": "FormatAgnostic"
50+ },
51+ {
52+ "name": "cu_seqlens_q",
53+ "index": 4,
54+ "dtype": "int32",
55+ "format": "ND",
56+ "paramType": "optional",
57+ "shape": [
58+ -2
59+ ],
60+ "format_match_mode": "FormatAgnostic"
61+ },
62+ {
63+ "name": "cu_seqlens_k",
64+ "index": 5,
65+ "dtype": "int32",
66+ "format": "ND",
67+ "paramType": "optional",
68+ "shape": [
69+ -2
70+ ],
71+ "format_match_mode": "FormatAgnostic"
72+ },
73+ {
74+ "name": "seqused_q",
75+ "index": 6,
76+ "dtype": "int32",
77+ "format": "ND",
78+ "paramType": "optional",
79+ "shape": [
80+ -2
81+ ],
82+ "format_match_mode": "FormatAgnostic"
83+ },
84+ {
85+ "name": "seqused_k",
86+ "index": 7,
87+ "dtype": "int32",
88+ "format": "ND",
89+ "paramType": "optional",
90+ "shape": [
91+ -2
92+ ],
93+ "format_match_mode": "FormatAgnostic"
94+ },
95+ {
96+ "name": "cmp_residual_k",
97+ "index": 8,
98+ "dtype": "int32",
99+ "format": "ND",
100+ "paramType": "optional",
101+ "shape": [
102+ -2
103+ ],
104+ "format_match_mode": "FormatAgnostic"
105+ },
106+ {
107+ "name": "topk_length",
108+ "index": 9,
109+ "dtype": "int32",
110+ "format": "ND",
111+ "paramType": "optional",
112+ "shape": [
113+ -2
114+ ],
115+ "format_match_mode": "FormatAgnostic"
116+ },
117+ {
118+ "name": "metadata",
119+ "index": 10,
120+ "dtype": "int32",
121+ "format": "ND",
122+ "paramType": "optional",
123+ "shape": [
124+ -2
125+ ],
126+ "format_match_mode": "FormatAgnostic"
127+ }
128+ ],
129+ "outputs": [
130+ {
131+ "name": "softmax_l1_norm",
132+ "index": 0,
133+ "dtype": "float32",
134+ "format": "ND",
135+ "paramType": "required",
136+ "shape": [
137+ -2
138+ ],
139+ "format_match_mode": "FormatAgnostic"
140+ }
141+ ],
142+ "attrs": [
143+ {
144+ "name": "softmax_scale",
145+ "dtype": "float",
146+ "value": 0.0
147+ },
148+ {
149+ "name": "cmp_ratio",
150+ "dtype": "int",
151+ "value": 0
152+ },
153+ {
154+ "name": "mask_mode",
155+ "dtype": "int",
156+ "value": 0
157+ },
158+ {
159+ "name": "layout_q",
160+ "dtype": "str",
161+ "value": ""
162+ },
163+ {
164+ "name": "layout_k",
165+ "dtype": "str",
166+ "value": ""
167+ }
168+ ]
169+ },
170+ {
171+ "bin_filename": "SparseFlashMlaSoftmaxL1Norm_441d95d84e65204b07cca4bc7c37ef36",
172+ "inputs": [
173+ {
174+ "name": "q",
175+ "index": 0,
176+ "dtype": "float16",
177+ "format": "ND",
178+ "paramType": "required",
179+ "shape": [
180+ -2
181+ ],
182+ "format_match_mode": "FormatAgnostic"
183+ },
184+ {
185+ "name": "k",
186+ "index": 1,
187+ "dtype": "float16",
188+ "format": "ND",
189+ "paramType": "required",
190+ "shape": [
191+ -2
192+ ],
193+ "format_match_mode": "FormatAgnostic"
194+ },
195+ {
196+ "name": "softmax_lse",
197+ "index": 2,
198+ "dtype": "float32",
199+ "format": "ND",
200+ "paramType": "required",
201+ "shape": [
202+ -2
203+ ],
204+ "format_match_mode": "FormatAgnostic"
205+ },
206+ {
207+ "name": "sparse_indices",
208+ "index": 3,
209+ "dtype": "int32",
210+ "format": "ND",
211+ "paramType": "optional",
212+ "shape": [
213+ -2
214+ ],
215+ "format_match_mode": "FormatAgnostic"
216+ },
217+ {
218+ "name": "cu_seqlens_q",
219+ "index": 4,
220+ "dtype": "int32",
221+ "format": "ND",
222+ "paramType": "optional",
223+ "shape": [
224+ -2
225+ ],
226+ "format_match_mode": "FormatAgnostic"
227+ },
228+ {
229+ "name": "cu_seqlens_k",
230+ "index": 5,
231+ "dtype": "int32",
232+ "format": "ND",
233+ "paramType": "optional",
234+ "shape": [
235+ -2
236+ ],
237+ "format_match_mode": "FormatAgnostic"
238+ },
239+ {
240+ "name": "seqused_q",
241+ "index": 6,
242+ "dtype": "int32",
243+ "format": "ND",
244+ "paramType": "optional",
245+ "shape": [
246+ -2
247+ ],
248+ "format_match_mode": "FormatAgnostic"
249+ },
250+ {
251+ "name": "seqused_k",
252+ "index": 7,
253+ "dtype": "int32",
254+ "format": "ND",
255+ "paramType": "optional",
256+ "shape": [
257+ -2
258+ ],
259+ "format_match_mode": "FormatAgnostic"
260+ },
261+ {
262+ "name": "cmp_residual_k",
263+ "index": 8,
264+ "dtype": "int32",
265+ "format": "ND",
266+ "paramType": "optional",
267+ "shape": [
268+ -2
269+ ],
270+ "format_match_mode": "FormatAgnostic"
271+ },
272+ {
273+ "name": "topk_length",
274+ "index": 9,
275+ "dtype": "int32",
276+ "format": "ND",
277+ "paramType": "optional",
278+ "shape": [
279+ -2
280+ ],
281+ "format_match_mode": "FormatAgnostic"
282+ },
283+ {
284+ "name": "metadata",
285+ "index": 10,
286+ "dtype": "int32",
287+ "format": "ND",
288+ "paramType": "optional",
289+ "shape": [
290+ -2
291+ ],
292+ "format_match_mode": "FormatAgnostic"
293+ }
294+ ],
295+ "outputs": [
296+ {
297+ "name": "softmax_l1_norm",
298+ "index": 0,
299+ "dtype": "float32",
300+ "format": "ND",
301+ "paramType": "required",
302+ "shape": [
303+ -2
304+ ],
305+ "format_match_mode": "FormatAgnostic"
306+ }
307+ ],
308+ "attrs": [
309+ {
310+ "name": "scale_value",
311+ "dtype": "float",
312+ "value": 0.0
313+ },
314+ {
315+ "name": "cmp_ratio",
316+ "dtype": "int",
317+ "value": 0
318+ },
319+ {
320+ "name": "mask_mode",
321+ "dtype": "int",
322+ "value": 0
323+ },
324+ {
325+ "name": "layout_q",
326+ "dtype": "str",
327+ "value": ""
328+ },
329+ {
330+ "name": "layout_k",
331+ "dtype": "str",
332+ "value": ""
333+ }
334+ ]
335+ }
336+ ]
337+}
@@ -0,0 +1,13 @@
1+; 该文件主要影响 opc 工具 编译二进制kernel时, --simplified_key_mode 选项中填写的值,格式如下所示:
2+; [某算子]
3+; default=xx
4+; ascendxx=xx
5+; 其中,default为默认mode,ascnedxx为可选mode,如果不同芯片有差异化要求时,需要配置;
6+; 1)如果没有配置:非ascendC算子继续按空处理,即opc编译命令中不添加 --simplified_key_mode 选项,AscendC算子按照 simplified_key_mode=0 处理
7+; 2)如果仅有default配置:各个版本按default配置
8+; 3)如果仅有某些平台的配置,没有default配置:对应平台的按照配置的值传递,非对应平台的:非AscendC算子继续按空处理,AscendC算子按照 simplified_key_mode=0 处理
9+; 4)如果default配置和平台配置都有:对应平台的使用平台的配置,非对应的平台的以default值配置。
10+; 5)对于自定义simplified key的情况,需要在binary_simplified_key_mode.ini 文件中显式配置为None,不传入 --simplified_key_mode 选项,由opc工具和FE框架自行判断使用何种模式
11+; 6)是否是AscendC算子,由 ops/build-in/tbe/op_info_cfg/parser/ascendc_config.json 中配置的算子名字和对于的平台决定
12+[SparseFlashMlaSoftmaxL1Norm]
13+default=0
@@ -0,0 +1,101 @@
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 sparse_flash_mla_softmax_l1_norm_def.cpp
13+ * \brief
14+ */
15+#include "register/op_def_registry.h"
16+ 
17+namespace ops {
18+class SparseFlashMlaSoftmaxL1Norm : public OpDef {
19+public:
20+ explicit SparseFlashMlaSoftmaxL1Norm(const char *name) : OpDef(name)
21+ {
22+ this->Input("q")
23+ .ParamType(REQUIRED)
24+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
25+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
26+ .AutoContiguous();
27+ this->Input("k")
28+ .ParamType(REQUIRED)
29+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
30+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
31+ .AutoContiguous();
32+ this->Input("softmax_lse")
33+ .ParamType(REQUIRED)
34+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT})
35+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
36+ .AutoContiguous();
37+ this->Input("sparse_indices")
38+ .ParamType(OPTIONAL)
39+ .DataType({ge::DT_INT32, ge::DT_INT32})
40+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
41+ .AutoContiguous();
42+ this->Input("cu_seqlens_q")
43+ .ParamType(OPTIONAL)
44+ .DataType({ge::DT_INT32, ge::DT_INT32})
45+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
46+ .AutoContiguous();
47+ this->Input("cu_seqlens_k")
48+ .ParamType(OPTIONAL)
49+ .DataType({ge::DT_INT32, ge::DT_INT32})
50+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
51+ .AutoContiguous();
52+ this->Input("seqused_q")
53+ .ParamType(OPTIONAL)
54+ .DataType({ge::DT_INT32, ge::DT_INT32})
55+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
56+ .AutoContiguous();
57+ this->Input("seqused_k")
58+ .ParamType(OPTIONAL)
59+ .DataType({ge::DT_INT32, ge::DT_INT32})
60+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
61+ .AutoContiguous();
62+ this->Input("cmp_residual_k")
63+ .ParamType(OPTIONAL)
64+ .DataType({ge::DT_INT32, ge::DT_INT32})
65+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
66+ .AutoContiguous();
67+ this->Input("topk_length")
68+ .ParamType(OPTIONAL)
69+ .DataType({ge::DT_INT32, ge::DT_INT32})
70+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
71+ .AutoContiguous();
72+ this->Input("metadata")
73+ .ParamType(OPTIONAL)
74+ .DataType({ge::DT_INT32, ge::DT_INT32})
75+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
76+ .AutoContiguous();
77+ this->Output("softmax_l1_norm")
78+ .ParamType(REQUIRED)
79+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT})
80+ .Format({ge::FORMAT_ND, ge::FORMAT_ND});
81+ this->Attr("softmax_scale").AttrType(OPTIONAL).Float(1.0);
82+ this->Attr("max_seqlen_k").AttrType(OPTIONAL).Int(0);
83+ this->Attr("cmp_ratio").AttrType(OPTIONAL).Int(1);
84+ this->Attr("mask_mode").AttrType(OPTIONAL).Int(0);
85+ this->Attr("layout_q").AttrType(OPTIONAL).String("BSND");
86+ this->Attr("layout_k").AttrType(OPTIONAL).String("BSND");
87+ 
88+ OpAICoreConfig aicore_config;
89+ aicore_config.DynamicCompileStaticFlag(true)
90+ .DynamicFormatFlag(true)
91+ .DynamicRankSupportFlag(true)
92+ .DynamicShapeSupportFlag(true)
93+ .NeedCheckSupportFlag(false)
94+ .PrecisionReduceFlag(true)
95+ .ExtendCfgInfo("opFile.value", "sparse_flash_mla_softmax_l1_norm")
96+ .ExtendCfgInfo("aclnnSupport.value", "support_aclnn");
97+ this->AICore().AddConfig("ascend950", aicore_config);
98+ }
99+};
100+OP_ADD(SparseFlashMlaSoftmaxL1Norm);
101+} // namespace ops
@@ -0,0 +1,105 @@
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 sparse_flash_mla_softmax_l1_norm_infershape.cpp
13+ * \brief
14+ */
15+#include <graph/utils/type_utils.h>
16+#include <register/op_impl_registry.h>
17+#include "err/ops_err.h"
18+ 
19+using namespace ge;
20+ 
21+namespace ops {
22+constexpr uint32_t QUERY_INDEX = 0;
23+constexpr uint32_t KEY_INDEX = 1;
24+constexpr uint32_t SPARSE_INDICES_INDEX = 3;
25+constexpr uint32_t SOFTMAX_L1_NORM_INDEX = 0;
26+constexpr uint32_t ATTR_MAX_SEQLEN_K_INDEX = 4;
27+constexpr uint32_t ATTR_LAYOUT_Q_INDEX = 4;
28+ 
29+static ge::graphStatus InferShapeSparseFlashMlaSoftmaxL1Norm(gert::InferShapeContext *context)
30+{
31+ OP_CHECK_IF(context == nullptr, OP_LOGE("SparseFlashMlaSoftmaxL1Norm", "InferShapeContext is nullptr!"),
32+ return ge::GRAPH_FAILED);
33+ OP_LOGD(context->GetNodeName(), "Enter SparseFlashMlaSoftmaxL1Norm InferShape impl.");
34+ const gert::Shape *queryShape = context->GetInputShape(QUERY_INDEX);
35+ OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);
36+ const gert::Shape *keyShape = context->GetInputShape(KEY_INDEX);
37+ OP_CHECK_NULL_WITH_CONTEXT(context, keyShape);
38+ 
39+ auto attrs = context->GetAttrs();
40+ OP_CHECK_NULL_WITH_CONTEXT(context, attrs);
41+ const char *layoutQPtr = attrs->GetAttrPointer<char>(ATTR_LAYOUT_Q_INDEX);
42+ OP_CHECK_NULL_WITH_CONTEXT(context, layoutQPtr);
43+ std::string layoutQStr(layoutQPtr);
44+ OP_CHECK_IF(layoutQStr != "BSND" && layoutQStr != "TND",
45+ OP_LOGE(context, "layout_q only supports BSND or TND, but got %s.", layoutQStr.c_str()),
46+ return ge::GRAPH_FAILED);
47+ const int64_t *maxSeqlenKPtr = attrs->GetAttrPointer<int64_t>(ATTR_MAX_SEQLEN_K_INDEX);
48+ int64_t maxSeqlenK = (maxSeqlenKPtr != nullptr) ? *maxSeqlenKPtr : 0;
49+ 
50+ gert::Shape *outShape = context->GetOutputShape(SOFTMAX_L1_NORM_INDEX);
51+ OP_CHECK_NULL_WITH_CONTEXT(context, outShape);
52+ 
53+ const gert::Shape *sparseIndiceShape = context->GetOptionalInputShape(static_cast<size_t>(SPARSE_INDICES_INDEX));
54+ if (layoutQStr == "BSND") {
55+ OP_CHECK_IF(queryShape->GetDimNum() != 4,
56+ OP_LOGE(context, "BSND layout, query dim num (%zu) must be 4!", queryShape->GetDimNum()),
57+ return ge::GRAPH_FAILED);
58+ OP_CHECK_IF(keyShape->GetDimNum() != 4,
59+ OP_LOGE(context, "BSND layout, key dim num (%zu) must be 4!", keyShape->GetDimNum()),
60+ return ge::GRAPH_FAILED);
61+ outShape->SetDimNum(4);
62+ outShape->SetDim(0, queryShape->GetDim(0)); // B
63+ outShape->SetDim(1, queryShape->GetDim(1)); // S1
64+ outShape->SetDim(2, keyShape->GetDim(2)); // N2
65+ 
66+ if (sparseIndiceShape != nullptr && sparseIndiceShape->GetShapeSize() != 0) {
67+ outShape->SetDim(3, sparseIndiceShape->GetDim(3)); // K
68+ } else {
69+ outShape->SetDim(3, keyShape->GetDim(1)); // S2
70+ }
71+ } else { // TND
72+ OP_CHECK_IF(queryShape->GetDimNum() != 3,
73+ OP_LOGE(context, "TND layout, query dim num (%zu) must be 3!", queryShape->GetDimNum()),
74+ return ge::GRAPH_FAILED);
75+ OP_CHECK_IF(keyShape->GetDimNum() != 3,
76+ OP_LOGE(context, "TND layout, key dim num (%zu) must be 3!", keyShape->GetDimNum()),
77+ return ge::GRAPH_FAILED);
78+ outShape->SetDimNum(3);
79+ outShape->SetDim(0, queryShape->GetDim(0)); // T1
80+ outShape->SetDim(1, keyShape->GetDim(0)); // T2
81+ if (sparseIndiceShape != nullptr && sparseIndiceShape->GetShapeSize() != 0) {
82+ outShape->SetDim(2, sparseIndiceShape->GetDim(2)); // K
83+ } else {
84+ outShape->SetDim(2, maxSeqlenK); // S2
85+ }
86+ }
87+ 
88+ OP_LOGD(context->GetNodeName(), "SparseFlashMlaSoftmaxL1Norm InferShape end.");
89+ return GRAPH_SUCCESS;
90+}
91+ 
92+static ge::graphStatus InferDataTypeSparseFlashMlaSoftmaxL1Norm(gert::InferDataTypeContext *context)
93+{
94+ OP_CHECK_IF(context == nullptr, OP_LOGE("SparseFlashMlaSoftmaxL1Norm", "InferDataTypeContext is nullptr!"),
95+ return ge::GRAPH_FAILED);
96+ OP_LOGD(context->GetNodeName(), "Enter SparseFlashMlaSoftmaxL1Norm InferDataType impl.");
97+ context->SetOutputDataType(SOFTMAX_L1_NORM_INDEX, ge::DT_FLOAT);
98+ OP_LOGD(context->GetNodeName(), "SparseFlashMlaSoftmaxL1Norm InferDataType end.");
99+ return GRAPH_SUCCESS;
100+}
101+ 
102+IMPL_OP_INFERSHAPE(SparseFlashMlaSoftmaxL1Norm)
103+ .InferShape(InferShapeSparseFlashMlaSoftmaxL1Norm)
104+ .InferDataType(InferDataTypeSparseFlashMlaSoftmaxL1Norm);
105+} // namespace ops
@@ -0,0 +1,627 @@
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 sparse_flash_mla_softmax_l1_norm_tiling.cpp
13+ * \brief 补充完整的参数校验,支持 BSND 和 TND 布局
14+ */
15+#include <string>
16+#include <set>
17+#include "sparse_flash_mla_softmax_l1_norm_tiling.h"
18+#include "log/log.h"
19+#include "err/ops_err.h"
20+ 
21+using namespace ge;
22+using namespace std;
23+ 
24+namespace optiling {
25+namespace smlasoftmaxl1norm {
26+ 
27+constexpr int64_t QUERY_IDX = 0;
28+constexpr int64_t KEY_IDX = 1;
29+constexpr int64_t LSE_IDX = 2;
30+constexpr int64_t SPARSE_INDICES_IDX = 3;
31+constexpr int64_t CU_SEQLENS_Q_IDX = 4;
32+constexpr int64_t CU_SEQLENS_K_IDX = 5;
33+constexpr int64_t SEQUSED_Q_IDX = 6;
34+constexpr int64_t SEQUSED_K_IDX = 7;
35+constexpr int64_t CMP_RESIDUAL_K_IDX = 8;
36+constexpr int64_t TOPK_LENGTH_IDX = 9;
37+constexpr int64_t METADATA_IDX = 10;
38+constexpr int64_t SOFTMAX_L1_NORM_IDX = 0;
39+ 
40+constexpr int64_t DIM_LIMIT = 512;
41+constexpr int64_t N1_MIN = 1;
42+constexpr int64_t N1_MAX = 128;
43+constexpr int64_t N2_VALUE = 1;
44+constexpr int64_t CMP_RATIO_MIN = 1;
45+constexpr int64_t CMP_RATIO_MAX = 128;
46+constexpr int64_t DIM_NUM_THREE = 3;
47+constexpr int64_t DIM_NUM_FOUR = 4;
48+constexpr int64_t DIM_NUM_ONE = 1;
49+constexpr int64_t DIM_NUM_TWO = 2;
50+constexpr int64_t B_ADD_ONE = 1;
51+constexpr int64_t SCALE_VALUE_ATTR_IDX = 0;
52+constexpr int64_t MAX_SEQLEN_K_ATTR_IDX = 1;
53+constexpr int64_t CMP_RATIO_ATTR_IDX = 2;
54+constexpr int64_t MASK_MODE_ATTR_IDX = 3;
55+constexpr int64_t LAYOUT_Q_ATTR_IDX = 4;
56+constexpr int64_t LAYOUT_K_ATTR_IDX = 5;
57+ 
58+struct TilingShapeInfo {
59+ int64_t bSize = 0;
60+ int64_t sqSize = 0;
61+ int64_t skSize = 0;
62+ int64_t gSize = 0;
63+ int64_t dSize = 0;
64+ int64_t t1 = 0;
65+ int64_t t2 = 0;
66+};
67+ 
68+static string DataTypeToStr(ge::DataType dtype)
69+{
70+ switch (dtype) {
71+ case ge::DT_FLOAT16:
72+ return "FLOAT16";
73+ case ge::DT_BF16:
74+ return "BFLOAT16";
75+ case ge::DT_FLOAT:
76+ return "FLOAT32";
77+ case ge::DT_INT32:
78+ return "INT32";
79+ case ge::DT_INT64:
80+ return "INT64";
81+ default:
82+ return "UNKNOWN(" + to_string(static_cast<int>(dtype)) + ")";
83+ }
84+}
85+ 
86+static int64_t AlignData(const int64_t a, const int64_t b)
87+{
88+ if (b == 0U) {
89+ return a;
90+ }
91+ return (a + b - 1U) / b * b;
92+}
93+ 
94+static ge::graphStatus ParseAttrs(gert::TilingContext *context, float &scaleValue, int64_t &maxSeqlenK,
95+ int64_t &cmpRatio, int64_t &maskMode, string &layoutQ, string &layoutK)
96+{
97+ auto attrs = context->GetAttrs();
98+ OP_CHECK_NULL_WITH_CONTEXT(context, attrs);
99+ 
100+ const float *scaleValuePtr = attrs->GetAttrPointer<float>(SCALE_VALUE_ATTR_IDX);
@@ -0,0 +1,71 @@
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 sparse_flash_mla_softmax_l1_norm_tiling.h
13+ * \brief
14+ */
15+#ifndef SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_TILING_H_
16+#define SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_TILING_H_
17+ 
18+#include "exe_graph/runtime/tiling_context.h"
19+#include "tiling/platform/platform_ascendc.h"
20+#include "register/op_def_registry.h"
21+#include "register/tilingdata_base.h"
22+#include "tiling/tiling_api.h"
23+ 
24+namespace optiling {
25+namespace smlasoftmaxl1norm {
26+ 
27+BEGIN_TILING_DATA_DEF(SmlaSoftmaxL1NormTilingData)
28+TILING_DATA_FIELD_DEF(int64_t, b)
29+TILING_DATA_FIELD_DEF(int64_t, sq)
30+TILING_DATA_FIELD_DEF(int64_t, sk)
31+TILING_DATA_FIELD_DEF(int64_t, g)
32+TILING_DATA_FIELD_DEF(int64_t, d)
33+TILING_DATA_FIELD_DEF(int64_t, t1)
34+TILING_DATA_FIELD_DEF(int64_t, t2)
35+TILING_DATA_FIELD_DEF(int64_t, max_seqlen_k)
36+TILING_DATA_FIELD_DEF(int64_t, k_length)
37+TILING_DATA_FIELD_DEF(int64_t, cmp_ratio)
38+TILING_DATA_FIELD_DEF(int64_t, init_per_core_num)
39+TILING_DATA_FIELD_DEF(int64_t, init_total_num)
40+TILING_DATA_FIELD_DEF(float, softmax_scale)
41+TILING_DATA_FIELD_DEF(bool, has_seqused_q)
42+TILING_DATA_FIELD_DEF(bool, has_seqused_k)
43+TILING_DATA_FIELD_DEF(bool, has_topk_length)
44+END_TILING_DATA_DEF
45+REGISTER_TILING_DATA_CLASS(SparseFlashMlaSoftmaxL1Norm, SmlaSoftmaxL1NormTilingData)
46+ 
47+struct SparseFlashMlaSoftmaxL1NormCompileInfo {
48+ uint32_t aivNum;
49+ uint32_t aicNum;
50+ uint64_t ubSize;
51+ uint64_t l1Size;
52+ uint64_t l0aSize;
53+ uint64_t l0bSize;
54+ uint64_t l0cSize;
55+ uint64_t l2CacheSize;
56+ int64_t coreNum;
57+};
58+ 
59+struct AiCoreParams {
60+ uint64_t ubSize = 0;
61+ uint64_t numBlocks = 0;
62+ uint64_t aicNum = 0;
63+ uint64_t l1Size = 0;
64+ uint64_t l0aSize = 0;
65+ uint64_t l0bSize = 0;
66+ uint64_t l0cSize = 0;
67+};
68+} // namespace smlasoftmaxl1norm
69+} // namespace optiling
70+ 
71+#endif // SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_TILING_H_
@@ -0,0 +1,41 @@
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 sparse_flash_mla_softmax_l1_norm_metadata.h
13+ * \brief Runtime metadata consumed by sparse_flash_mla_softmax_l1_norm.
14+ */
15+#ifndef SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
16+#define SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
17+ 
18+#include <cstdint>
19+ 
20+namespace optiling {
21+ 
22+using SMLA_METADATA_T = int32_t;
23+ 
24+constexpr uint32_t SMLA_METADATA_MAX_CORE_NUM = 36;
25+constexpr uint32_t SMLA_METADATA_SIZE = 64;
26+ 
27+namespace detail {
28+struct SmlaSoftmaxL1NormMetaData {
29+ int32_t totalNum;
30+ int32_t formerCoreProcessNum;
31+ int32_t remainCoreProcessNum;
32+ int32_t remainCoreNum;
33+ int32_t totalCoreNum;
34+};
35+} // namespace detail
36+ 
37+static_assert(SMLA_METADATA_SIZE * sizeof(SMLA_METADATA_T) >= sizeof(detail::SmlaSoftmaxL1NormMetaData));
38+ 
39+} // namespace optiling
40+ 
41+#endif // SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
@@ -0,0 +1,17 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+list(REMOVE_ITEM CURRENT_DIRS tests)
13+foreach(SUB_DIR ${CURRENT_DIRS})
14+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
15+ add_subdirectory(${SUB_DIR})
16+ endif()
17+endforeach()
@@ -0,0 +1,79 @@
1+# SparseFlashMlaSoftmaxL1NormMetadata
2+ 
3+## 产品支持情况
4+ 
5+| 产品 | 是否支持 |
6+| ------------------------------------------------------------ | :------: |
7+| <term>Ascend 950PR/Ascend 950DT</term> | √ |
8+| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | × |
9+| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | × |
10+| <term>Atlas 200I/500 A2 推理产品</term> | × |
11+| <term>Atlas 推理系列产品</term> | × |
12+| <term>Atlas 训练系列产品</term> | × |
13+ 
14+## 功能说明
15+ 
16+- 算子功能:该算子为AICPU算子,是`SparseFlashMlaSoftmaxL1Norm`算子的前置算子。根据`SparseFlashMlaSoftmaxL1Norm`算子的输入shape、layout、mask和压缩比例信息,计算并输出分核切分metadata,减少主算子tiling阶段对host array的访问。
17+ 
18+ **该算子不建议单独使用,建议与`SparseFlashMlaSoftmaxL1Norm`算子配合使用,形成完整的工作流。**
19+ 
20+ 计算流程:
21+ 1. 接收主算子的shape信息,包括batchSize、maxSeqLenQ、maxSeqLenK、numHeadsQ、numHeadsK、headDim、topk、layout和mask信息。
22+ 2. 根据layout和可选输入seqUsedQOptional计算参与负载均衡的seq总数,采用strided方式将任务均衡切分到可用AIC核上。
23+ 3. 输出metadata,作为`SparseFlashMlaSoftmaxL1Norm`算子的metadataOptional输入使用。
24+ 
25+## 参数说明
26+ 
27+| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 |
28+| ------ | -------------- | ---- | -------- | -------- |
29+| cu_seqlens_q | 可选输入 | 表示每个Batch中Query的有效token数的累加和形式。TND场景下必传,第一个值固定为0。 | INT32 | ND |
30+| cu_seqlens_k | 可选输入 | 表示每个Batch中Key的有效token数的累加和形式。TND场景下必传,第一个值固定为0。 | INT32 | ND |
31+| seqused_q | 可选输入 | 表示不同batch中q实际参与运算的token数。当该入参存在时,seq总数按每个batch实际用到的seq累加计算。 | INT32 | ND |
32+| seqused_k | 可选输入 | 预留接口参数,表示不同batch中k实际参与运算的token数。当前kernel路径暂不使用。 | INT32 | ND |
33+| cmp_residual_k | 可选输入 | 预留接口参数,表示不同batch中key的sequence length与cmpRatio相关的残差。当前kernel路径暂不使用。 | INT32 | ND |
34+| topk_length | 可选输入 | 表示每行q对应的k实际可选的topk长度。maskMode=0且存在稀疏索引时需要传。 | INT32 | ND |
35+| batch_size | 可选属性 | 表示batch数量,支持非负数。TND场景可填0并通过cu_seqlens_q推导,默认值为0。 | INT64 | - |
36+| max_seqlen_q | 可选属性 | 表示q的最大序列长度,支持非负数。BSND场景必须为正数,默认值为0。 | INT64 | - |
37+| max_seqlen_k | 可选属性 | 表示k的最大序列长度,支持非负数。BSND场景必须为正数,默认值为0。 | INT64 | - |
38+| num_heads_q | 必选属性 | 表示q的head个数,必须为正数且能被num_heads_k整除。 | INT64 | - |
39+| num_heads_k | 必选属性 | 表示k的head个数,必须为正数。 | INT64 | - |
40+| head_dim | 必选属性 | 表示q/k的head dimension,必须为正数。 | INT64 | - |
41+| topk | 可选属性 | 表示从k中筛选出的关键token个数,支持非负数。0表示无稀疏,默认值为0。 | INT64 | - |
42+| cmp_ratio | 可选属性 | 表示k的压缩率,取值范围[1, 128],默认值为1。 | INT64 | - |
43+| mask_mode | 可选属性 | 表示sparse mask模式。0:No mask;3:rightDownCausal模式。默认值为0。 | INT64 | - |
44+| layout_q | 可选属性 | 表示q侧的数据排布格式,支持BSND/TND,默认值为"BSND"。 | STRING | - |
45+| layout_k | 可选属性 | 表示k侧的数据排布格式,支持BSND/TND,默认值为"BSND"。 | STRING | - |
46+| metadata | 输出 | 表示负载均衡结果输出,shape固定为(64,),输出结果作为`SparseFlashMlaSoftmaxL1Norm`的metadataOptional输入。 | INT32 | ND |
47+ 
48+## 约束说明
49+ 
50+- 确定性说明:aclnnSparseFlashMlaSoftmaxL1NormMetadata默认确定性实现。
51+- BSND场景:必传batch_size、max_seqlen_q和max_seqlen_k参数以获取shape信息。
52+- TND场景:必传cu_seqlens_q和cu_seqlens_k参数以获取正确shape信息。当batch_size为0时,通过cu_seqlens_q的shape推导batch。
53+- layout约束:layout_q必须为BSND或TND,layout_k支持BSND和TND,layout_k需与layout_q保持一致。
54+- head约束:num_heads_q、num_heads_k必须为正数,且num_heads_q必须能被num_heads_k整除, head_dim只支持512。
55+- 负载均衡约束:
56+ - topk支持非负数,0表示无稀疏。
57+ - cmp_ratio取值范围为[1, 128]。
58+ - mask_mode当前仅支持0和3。
59+ 
60+## Metadata输出布局
61+ 
62+metadata输出为INT32 Tensor,shape固定为(64,),字段布局如下:
63+ 
64+| 字段 | index | 说明 |
65+| ---- | ----- | ---- |
66+| totalNum | 0 | 参与负载均衡的seq总数。TND场景为各batch的seqQ累加值;BSND场景为B×S;当seqused_q存在时,按每个batch实际用到的seq累加。 |
67+| formerCoreProcessNum | 1 | 常规核处理的seq数,即ceil(totalNum / totalCoreNum)。 |
68+| remainCoreProcessNum | 2 | 尾核处理的seq数,即floor(totalNum / totalCoreNum)。 |
69+| remainCoreNum | 3 | 尾核数目。当totalNum能被totalCoreNum整除时为0,否则为totalCoreNum - (totalNum % totalCoreNum)。 |
70+| totalCoreNum | 4 | 实际使用的AIC核数,取min(totalNum, aicCoreNum, 36)。 |
71+ 
72+采用strided切分方式,每个核处理的seq索引按核间步进totalCoreNum排列。
73+ 
74+## 调用说明
75+ 
76+| 调用方式 | 调用样例 | 说明 |
77+| -------- | -------- | ---- |
78+| aclnn API | - | 通过[aclnnSparseFlashMlaSoftmaxL1NormMetadata](docs/aclnnSparseFlashMlaSoftmaxL1NormMetadata.md)接口方式调用算子,输出metadata供`SparseFlashMlaSoftmaxL1Norm`使用。 |
79+| PyTorch API | - | 通过[sparse_flash_mla_softmax_l1_norm_metadata](../../torch_extension/cann_ops_transformer/docs/zh/sparse_flash_mla_softmax_l1_norm.md)(内置在主算子接口中)调用算子。 |
@@ -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+/*!
12+ * \file sparse_flash_mla_softmax_l1_norm_metadata_proto.h
13+ * \brief
14+ */
15+#ifndef SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_PROTO_H
16+#define SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_PROTO_H
17+ 
18+#include "graph/operator_reg.h"
19+#include "graph/types.h"
20+ 
21+namespace ge {
22+ 
23+REG_OP(SparseFlashMlaSoftmaxL1NormMetadata)
24+ .OPTIONAL_INPUT(cu_seqlens_q, TensorType({DT_INT32}))
25+ .OPTIONAL_INPUT(cu_seqlens_k, TensorType({DT_INT32}))
26+ .OPTIONAL_INPUT(seqused_q, TensorType({DT_INT32}))
27+ .OPTIONAL_INPUT(seqused_k, TensorType({DT_INT32}))
28+ .OPTIONAL_INPUT(cmp_residual_k, TensorType({DT_INT32}))
29+ .OPTIONAL_INPUT(topk_length, TensorType({DT_INT32}))
30+ .OUTPUT(metadata, TensorType({DT_INT32}))
31+ .ATTR(batch_size, Int, 0)
32+ .ATTR(max_seqlen_q, Int, 0)
33+ .ATTR(max_seqlen_k, Int, 0)
34+ .REQUIRED_ATTR(num_heads_q, Int)
35+ .REQUIRED_ATTR(num_heads_k, Int)
36+ .REQUIRED_ATTR(head_dim, Int)
37+ .ATTR(topk, Int, 0)
38+ .ATTR(cmp_ratio, Int, 1)
39+ .ATTR(mask_mode, Int, 0)
40+ .ATTR(layout_q, String, "BSND")
41+ .ATTR(layout_k, String, "BSND")
42+ .OP_END_FACTORY_REG(SparseFlashMlaSoftmaxL1NormMetadata)
43+ 
44+} // namespace ge
45+ 
46+#endif // SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_PROTO_H
@@ -0,0 +1,12 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+add_op_to_compiled_list()
11+ 
12+add_modules_sources(OPTYPE sparse_flash_mla_softmax_l1_norm_metadata ACLNNTYPE aclnn)
@@ -0,0 +1,113 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file aclnn_sparse_flash_mla_softmax_l1_norm_metadata.cpp
13+ * \brief
14+ */
15+ 
16+#include "aclnn_sparse_flash_mla_softmax_l1_norm_metadata.h"
17+#include "l0_sparse_flash_mla_softmax_l1_norm_metadata.h"
18+#include "aclnn_kernels/contiguous.h"
19+#include "aclnn/aclnn_base.h"
20+#include "aclnn_kernels/common/op_error_check.h"
21+#include "opdev/make_op_executor.h"
22+#include "opdev/op_dfx.h"
23+#include "opdev/op_executor.h"
24+#include "opdev/platform.h"
25+ 
26+#ifdef __cplusplus
27+extern "C" {
28+#endif
29+ 
30+static aclnnStatus ParamsCheck(const aclTensor *metadata)
31+{
32+ CHECK_RET(metadata != nullptr, ACLNN_ERR_PARAM_NULLPTR);
33+ return ACLNN_SUCCESS;
34+}
35+ 
36+aclnnStatus aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize(
37+ const aclTensor *cuSeqLensQOptional, const aclTensor *cuSeqLensKOptional, const aclTensor *seqUsedQOptional,
38+ const aclTensor *seqUsedKOptional, const aclTensor *cmpResidualKOptional, const aclTensor *topkLengthOptional,
39+ int64_t batchSize, int64_t maxSeqLenQ, int64_t maxSeqLenK, int64_t numHeadsQ, int64_t numHeadsK, int64_t headDim,
40+ int64_t topk, int64_t cmpRatio, int64_t maskMode, char *layoutQ, char *layoutK, const aclTensor *metadata,
41+ uint64_t *workspaceSize, aclOpExecutor **executor)
42+{
43+ L2_DFX_PHASE_1(aclnnSparseFlashMlaSoftmaxL1NormMetadata,
44+ DFX_IN(cuSeqLensQOptional, cuSeqLensKOptional, seqUsedQOptional, seqUsedKOptional,
45+ cmpResidualKOptional, topkLengthOptional, batchSize, maxSeqLenQ, maxSeqLenK, numHeadsQ,
46+ numHeadsK, headDim, topk, cmpRatio, maskMode, layoutQ, layoutK),
47+ DFX_OUT(metadata));
48+ 
49+ auto uniqueExecutor = CREATE_EXECUTOR();
50+ CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
51+ 
52+ auto ret = ParamsCheck(metadata);
53+ CHECK_RET(ret == ACLNN_SUCCESS, ret);
54+ 
55+ const op::PlatformInfo &npuInfo = op::GetCurrentPlatformInfo();
56+ uint32_t aicCoreNum = npuInfo.GetCubeCoreNum();
57+ std::string socVersionStr = npuInfo.GetSocLongVersion();
58+ const char *socVersion = socVersionStr.c_str();
59+ 
60+ const aclTensor *cuSeqLensQContiguous = nullptr;
61+ if (cuSeqLensQOptional != nullptr) {
62+ cuSeqLensQContiguous = l0op::Contiguous(cuSeqLensQOptional, uniqueExecutor.get());
63+ CHECK_RET(cuSeqLensQContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR);
64+ }
65+ const aclTensor *cuSeqLensKContiguous = nullptr;
66+ if (cuSeqLensKOptional != nullptr) {
67+ cuSeqLensKContiguous = l0op::Contiguous(cuSeqLensKOptional, uniqueExecutor.get());
68+ CHECK_RET(cuSeqLensKContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR);
69+ }
70+ const aclTensor *seqUsedQContiguous = nullptr;
71+ if (seqUsedQOptional != nullptr) {
72+ seqUsedQContiguous = l0op::Contiguous(seqUsedQOptional, uniqueExecutor.get());
73+ CHECK_RET(seqUsedQContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR);
74+ }
75+ const aclTensor *seqUsedKContiguous = nullptr;
76+ if (seqUsedKOptional != nullptr) {
77+ seqUsedKContiguous = l0op::Contiguous(seqUsedKOptional, uniqueExecutor.get());
78+ CHECK_RET(seqUsedKContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR);
79+ }
80+ const aclTensor *cmpResidualKContiguous = nullptr;
81+ if (cmpResidualKOptional != nullptr) {
82+ cmpResidualKContiguous = l0op::Contiguous(cmpResidualKOptional, uniqueExecutor.get());
83+ CHECK_RET(cmpResidualKContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR);
84+ }
85+ const aclTensor *topkLengthContiguous = nullptr;
86+ if (topkLengthOptional != nullptr) {
87+ topkLengthContiguous = l0op::Contiguous(topkLengthOptional, uniqueExecutor.get());
88+ CHECK_RET(topkLengthContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR);
89+ }
90+ 
91+ auto output = l0op::SparseFlashMlaSoftmaxL1NormMetadata(
92+ cuSeqLensQContiguous, cuSeqLensKContiguous, seqUsedQContiguous, seqUsedKContiguous, cmpResidualKContiguous,
93+ topkLengthContiguous, batchSize, maxSeqLenQ, maxSeqLenK, numHeadsQ, numHeadsK, headDim, topk, cmpRatio,
94+ maskMode, layoutQ, layoutK, socVersion, aicCoreNum, metadata, uniqueExecutor.get());
95+ CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR);
96+ 
97+ *workspaceSize = 0;
98+ uniqueExecutor.ReleaseTo(executor);
99+ return ACLNN_SUCCESS;
100+}
101+ 
102+__attribute__((visibility("default"))) aclnnStatus aclnnSparseFlashMlaSoftmaxL1NormMetadata(void *workspace,
103+ uint64_t workspaceSize,
104+ aclOpExecutor *executor,
105+ aclrtStream stream)
106+{
107+ L2_DFX_PHASE_2(aclnnSparseFlashMlaSoftmaxL1NormMetadata);
108+ return CommonOpExecutorRun(workspace, workspaceSize, executor, stream);
109+}
110+ 
111+#ifdef __cplusplus
112+}
113+#endif
@@ -0,0 +1,41 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file aclnn_sparse_flash_mla_softmax_l1_norm_metadata.h
13+ * \brief
14+ */
15+#ifndef ACLNN_SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
16+#define ACLNN_SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
17+ 
18+#include <string>
19+#include "aclnn/aclnn_base.h"
20+ 
21+#ifdef __cplusplus
22+extern "C" {
23+#endif
24+ 
25+__attribute__((visibility("default"))) aclnnStatus aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize(
26+ const aclTensor *cuSeqLensQOptional, const aclTensor *cuSeqLensKOptional, const aclTensor *seqUsedQOptional,
27+ const aclTensor *seqUsedKOptional, const aclTensor *cmpResidualKOptional, const aclTensor *topkLengthOptional,
28+ int64_t batchSize, int64_t maxSeqLenQ, int64_t maxSeqLenK, int64_t numHeadsQ, int64_t numHeadsK, int64_t headDim,
29+ int64_t topk, int64_t cmpRatio, int64_t maskMode, char *layoutQ, char *layoutK, const aclTensor *metadata,
30+ uint64_t *workspaceSize, aclOpExecutor **executor);
31+ 
32+__attribute__((visibility("default"))) aclnnStatus aclnnSparseFlashMlaSoftmaxL1NormMetadata(void *workspace,
33+ uint64_t workspaceSize,
34+ aclOpExecutor *executor,
35+ aclrtStream stream);
36+ 
37+#ifdef __cplusplus
38+}
39+#endif
40+ 
41+#endif // ACLNN_SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_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 l0_sparse_flash_mla_softmax_l1_norm_metadata.cpp
13+ * \brief
14+ */
15+ 
16+#include "l0_sparse_flash_mla_softmax_l1_norm_metadata.h"
17+#include "opdev/aicpu/aicpu_task.h"
18+#include "opdev/make_op_executor.h"
19+#include "opdev/op_def.h"
20+#include "opdev/op_dfx.h"
21+#include "opdev/op_executor.h"
22+#include "opdev/op_log.h"
23+ 
24+using namespace op;
25+ 
26+namespace l0op {
27+OP_TYPE_REGISTER(SparseFlashMlaSoftmaxL1NormMetadata);
28+ 
29+const aclTensor *SparseFlashMlaSoftmaxL1NormMetadata(
30+ const aclTensor *cuSeqLensQOptional, const aclTensor *cuSeqLensKOptional, const aclTensor *seqUsedQOptional,
31+ const aclTensor *seqUsedKOptional, const aclTensor *cmpResidualKOptional, const aclTensor *topkLengthOptional,
32+ int64_t batchSize, int64_t maxSeqLenQ, int64_t maxSeqLenK, int64_t numHeadsQ, int64_t numHeadsK, int64_t headDim,
33+ int64_t topk, int64_t cmpRatio, int64_t maskMode, char *layoutQ, char *layoutK, const char *socVersion,
34+ int64_t aicCoreNum, const aclTensor *metadata, aclOpExecutor *executor)
35+{
36+ L0_DFX(SparseFlashMlaSoftmaxL1NormMetadata, cuSeqLensQOptional, cuSeqLensKOptional, seqUsedQOptional,
37+ seqUsedKOptional, cmpResidualKOptional, topkLengthOptional, batchSize, maxSeqLenQ, maxSeqLenK, numHeadsQ,
38+ numHeadsK, headDim, topk, cmpRatio, maskMode, layoutQ, layoutK, socVersion, aicCoreNum, metadata);
39+ 
40+ static internal::AicpuTaskSpace space("SparseFlashMlaSoftmaxL1NormMetadata");
41+ 
42+ auto ret = ADD_TO_LAUNCHER_LIST_AICPU(
43+ SparseFlashMlaSoftmaxL1NormMetadata,
44+ OP_ATTR_NAMES({"batch_size", "max_seqlen_q", "max_seqlen_k", "num_heads_q", "num_heads_k", "head_dim", "topk",
45+ "cmp_ratio", "mask_mode", "layout_q", "layout_k", "soc_version", "aic_core_num"}),
46+ OP_INPUT(cuSeqLensQOptional, cuSeqLensKOptional, seqUsedQOptional, seqUsedKOptional, cmpResidualKOptional,
47+ topkLengthOptional),
48+ OP_OUTPUT(metadata),
49+ OP_ATTR(batchSize, maxSeqLenQ, maxSeqLenK, numHeadsQ, numHeadsK, headDim, topk, cmpRatio, maskMode, layoutQ,
50+ layoutK, socVersion, aicCoreNum));
51+ OP_CHECK(ret == ACL_SUCCESS,
52+ OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "SparseFlashMlaSoftmaxL1NormMetadata ADD_TO_LAUNCHER_LIST_AICPU failed."),
53+ return nullptr);
54+ return metadata;
55+}
56+} // namespace l0op
@@ -0,0 +1,31 @@
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 l0_sparse_flash_mla_softmax_l1_norm_metadata.h
13+ * \brief
14+ */
15+#ifndef L0_SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
16+#define L0_SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
17+ 
18+#include <cstdint>
19+#include <string>
20+#include "opdev/op_executor.h"
21+ 
22+namespace l0op {
23+const aclTensor *SparseFlashMlaSoftmaxL1NormMetadata(
24+ const aclTensor *cuSeqLensQOptional, const aclTensor *cuSeqLensKOptional, const aclTensor *seqUsedQOptional,
25+ const aclTensor *seqUsedKOptional, const aclTensor *cmpResidualKOptional, const aclTensor *topkLengthOptional,
26+ int64_t batchSize, int64_t maxSeqLenQ, int64_t maxSeqLenK, int64_t numHeadsQ, int64_t numHeadsK, int64_t headDim,
27+ int64_t topk, int64_t cmpRatio, int64_t maskMode, char *layoutQ, char *layoutK, const char *socVersion,
28+ int64_t aicCoreNum, const aclTensor *metadata, aclOpExecutor *executor);
29+} // namespace l0op
30+ 
31+#endif // L0_SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_H
@@ -0,0 +1,38 @@
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 sparse_flash_mla_softmax_l1_norm_metadata_infershape.cpp
13+ * \brief
14+ */
15+#include "register/op_impl_registry.h"
16+#include "../../sparse_flash_mla_softmax_l1_norm/op_kernel/sparse_flash_mla_softmax_l1_norm_metadata.h"
17+ 
18+using namespace ge;
19+ 
20+namespace ops {
21+static ge::graphStatus InferShapeSparseFlashMlaSoftmaxL1NormMetadata(gert::InferShapeContext *context)
22+{
23+ gert::Shape *oShape = context->GetOutputShape(0);
24+ oShape->SetDimNum(1);
25+ oShape->SetDim(0, optiling::SMLA_METADATA_SIZE);
26+ return GRAPH_SUCCESS;
27+}
28+ 
29+static ge::graphStatus InferDtypeSparseFlashMlaSoftmaxL1NormMetadata(gert::InferDataTypeContext *context)
30+{
31+ context->SetOutputDataType(0, DT_INT32);
32+ return GRAPH_SUCCESS;
33+}
34+ 
35+IMPL_OP_INFERSHAPE(SparseFlashMlaSoftmaxL1NormMetadata)
36+ .InferShape(InferShapeSparseFlashMlaSoftmaxL1NormMetadata)
37+ .InferDataType(InferDtypeSparseFlashMlaSoftmaxL1NormMetadata);
38+} // namespace ops
@@ -0,0 +1,30 @@
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+if (BUILD_WITH_INSTALLED_DEPENDENCY_CANN_PKG)
12+ if (NOT (UT_TEST_ALL OR OP_KERNEL_AICPU_UT))
13+ add_definitions(-D_GLIBCXX_USE_CXX11_ABI=1)
14+ set(CMAKE_CXX_COMPILER ${ASCEND_DIR}/toolkit/toolchain/hcc/bin/aarch64-target-linux-gnu-g++)
15+ endif()
16+ 
17+ file(GLOB_RECURSE JSON_FILE ${CMAKE_CURRENT_SOURCE_DIR}/*.json)
18+ set_property(GLOBAL APPEND PROPERTY AICPU_JSON_FILES ${JSON_FILE})
19+ 
20+ file(GLOB AICPU_SRC ${CMAKE_CURRENT_SOURCE_DIR}/*_aicpu*.cpp)
21+ message(STATUS "[sparse_flash_mla_softmax_l1_norm_metadata] Found aicpu sources: ${AICPU_SRC}")
22+ 
23+ set(OBJ_NAME sparse_flash_mla_softmax_l1_norm_metadata_cust_obj)
24+ add_aicpu_cust_kernel_modules(${OBJ_NAME})
25+ target_sources(${OBJ_NAME} PRIVATE ${AICPU_SRC})
26+endif()
27+ 
28+if(UT_TEST_ALL OR OP_KERNEL_AICPU_UT)
29+ AddAicpuOpTestCase(sparse_flash_mla_softmax_l1_norm_metadata)
30+endif()
@@ -0,0 +1,80 @@
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 sparse_flash_mla_softmax_l1_norm_metadata_aicpu_arch35.h
13+ * \brief arch35 (Ascend950) specific implementations for AICPU metadata kernel.
14+ */
15+#ifndef SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_AICPU_ARCH35_H
16+#define SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_AICPU_ARCH35_H
17+ 
18+#include "../sparse_flash_mla_softmax_l1_norm_metadata_aicpu.h"
19+#include "../../../sparse_flash_mla_softmax_l1_norm/op_kernel/sparse_flash_mla_softmax_l1_norm_metadata.h"
20+ 
21+#include <algorithm>
22+ 
23+using namespace optiling;
24+ 
25+namespace aicpu {
26+ 
27+template <typename T>
28+inline T CeilDiv(T x, T y)
29+{
30+ if (y == 0) {
31+ return 0;
32+ }
33+ return (x + y - 1) / y;
34+}
35+ 
36+inline int64_t SparseFlashMlaSoftmaxL1NormMetadataCpuKernel::CalcTotalSize() const
37+{
38+ if (IsTensorValid(seqUsedQuery_)) {
39+ auto *data = reinterpret_cast<const int32_t *>(seqUsedQuery_->GetData());
40+ int64_t total = 0;
41+ for (int64_t i = 0; i < bSize_; ++i) {
42+ total += static_cast<int64_t>(data[i]);
43+ }
44+ return total;
45+ }
46+ if (layoutType_ == SmlaLayout::TND && IsTensorValid(cuSeqLensQuery_)) {
47+ auto *data = reinterpret_cast<const int32_t *>(cuSeqLensQuery_->GetData());
48+ return static_cast<int64_t>(data[bSize_]);
49+ }
50+ return bSize_ * s1Size_;
51+}
52+ 
53+inline bool SparseFlashMlaSoftmaxL1NormMetadataCpuKernel::BuildMetadata()
54+{
55+ int64_t totalNum = CalcTotalSize();
56+ if (totalNum <= 0) {
57+ KERNEL_LOG_ERROR("totalNum should be larger than 0, but got %ld", totalNum);
58+ return false;
59+ }
60+ 
61+ int64_t totalCoreNum = std::min<int64_t>(std::min(totalNum, aicCoreNum_), SMLA_METADATA_MAX_CORE_NUM);
62+ int64_t formerCoreProcessNum = CeilDiv(totalNum, totalCoreNum);
63+ int64_t remainCoreProcessNum = totalNum / totalCoreNum;
64+ int64_t remainder = totalNum % totalCoreNum;
65+ int64_t remainCoreNum = (remainder == 0) ? 0 : (totalCoreNum - remainder);
66+ 
67+ auto *metadataData = reinterpret_cast<SMLA_METADATA_T *>(metadata_->GetData());
68+ std::fill_n(metadataData, SMLA_METADATA_SIZE, static_cast<SMLA_METADATA_T>(0));
69+ auto *metadata = reinterpret_cast<detail::SmlaSoftmaxL1NormMetaData *>(metadataData);
70+ metadata->totalNum = static_cast<int32_t>(totalNum);
71+ metadata->formerCoreProcessNum = static_cast<int32_t>(formerCoreProcessNum);
72+ metadata->remainCoreProcessNum = static_cast<int32_t>(remainCoreProcessNum);
73+ metadata->remainCoreNum = static_cast<int32_t>(remainCoreNum);
74+ metadata->totalCoreNum = static_cast<int32_t>(totalCoreNum);
75+ return true;
76+}
77+ 
78+} // namespace aicpu
79+ 
80+#endif // SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_AICPU_ARCH35_H
@@ -0,0 +1,180 @@
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 sparse_flash_mla_softmax_l1_norm_metadata_aicpu.cpp
13+ * \brief
14+ */
15+ 
16+#include "log.h"
17+#include "status.h"
18+#include "cust_op/cust_cpu_utils.h"
19+#include "../../sparse_flash_mla_softmax_l1_norm/op_kernel/sparse_flash_mla_softmax_l1_norm_metadata.h"
20+#include "sparse_flash_mla_softmax_l1_norm_metadata_aicpu.h"
21+#include "arch35/sparse_flash_mla_softmax_l1_norm_metadata_aicpu_arch35.h"
22+ 
23+using namespace optiling;
24+ 
25+namespace aicpu {
26+ 
27+uint32_t SparseFlashMlaSoftmaxL1NormMetadataCpuKernel::Compute(CpuKernelContext &ctx)
28+{
29+ if (!Prepare(ctx)) {
30+ return KERNEL_STATUS_PARAM_INVALID;
31+ }
32+ ValidSocVersion socVersion = ProcessSocVersion();
33+ if (socVersion == ValidSocVersion::ASCEND950) {
34+ return BuildMetadata() ? KERNEL_STATUS_OK : KERNEL_STATUS_PARAM_INVALID;
35+ }
36+ KERNEL_LOG_ERROR("Unsupported soc version: %s", socVersion_.c_str());
37+ return KERNEL_STATUS_PARAM_INVALID;
38+}
39+ 
40+bool SparseFlashMlaSoftmaxL1NormMetadataCpuKernel::Prepare(CpuKernelContext &ctx)
41+{
42+ cuSeqLensQuery_ = ctx.Input(0);
43+ cuSeqLensKey_ = ctx.Input(1);
44+ seqUsedQuery_ = ctx.Input(2);
45+ seqUsedKey_ = ctx.Input(3);
46+ cmpResidualKey_ = ctx.Input(4);
47+ topkLength_ = ctx.Input(5);
48+ metadata_ = ctx.Output(0);
49+ 
50+ bool requiredAttrs = GetAttrValue(ctx, "num_heads_q", numHeadsQ_) && GetAttrValue(ctx, "num_heads_k", numHeadsK_) &&
51+ GetAttrValue(ctx, "head_dim", headDim_);
52+ if (!requiredAttrs) {
53+ return false;
54+ }
55+ 
56+ GetAttrValueOpt(ctx, "batch_size", bSize_);
57+ GetAttrValueOpt(ctx, "max_seqlen_q", s1Size_);
58+ GetAttrValueOpt(ctx, "max_seqlen_k", s2Size_);
59+ GetAttrValueOpt(ctx, "topk", topk_);
60+ GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_);
61+ GetAttrValueOpt(ctx, "mask_mode", maskMode_);
62+ GetAttrValueOpt(ctx, "layout_q", layout_);
63+ GetAttrValueOpt(ctx, "layout_k", layoutK_);
64+ GetAttrValueOpt(ctx, "soc_version", socVersion_);
65+ GetAttrValueOpt(ctx, "aic_core_num", aicCoreNum_);
66+ 
67+ if (layout_ == "BSND") {
68+ layoutType_ = SmlaLayout::BSND;
69+ } else if (layout_ == "TND") {
70+ layoutType_ = SmlaLayout::TND;
71+ } else {
72+ KERNEL_LOG_ERROR("layout_q must be BSND or TND, but got %s", layout_.c_str());
73+ return false;
74+ }
75+ 
76+ if (bSize_ <= 0) {
77+ if (IsTensorValid(seqUsedQuery_)) {
78+ bSize_ = seqUsedQuery_->GetTensorShape()->GetDimSize(0);
79+ } else if (layoutType_ == SmlaLayout::TND && IsTensorValid(cuSeqLensQuery_)) {
80+ bSize_ = cuSeqLensQuery_->GetTensorShape()->GetDimSize(0) - 1;
81+ }
82+ }
83+ 
84+ return ParamsCheck();
85+}
86+ 
87+ValidSocVersion SparseFlashMlaSoftmaxL1NormMetadataCpuKernel::ProcessSocVersion()
88+{
89+ const std::string ascend950 = "Ascend950";
90+ if (socVersion_.find(ascend950) != std::string::npos) {
91+ return ValidSocVersion::ASCEND950;
92+ }
93+ return ValidSocVersion::ASCEND910;
94+}
95+ 
96+bool SparseFlashMlaSoftmaxL1NormMetadataCpuKernel::ParamsCheck()
97+{
98+ KERNEL_CHECK_NULLPTR(metadata_, false, "metadata output is null");
99+ KERNEL_CHECK_NULLPTR(metadata_->GetData(), false, "metadata data is null");
100+ KERNEL_CHECK_NULLPTR(metadata_->GetTensorShape(), false, "metadata shape is null");
101+ 
102+ if (aicCoreNum_ <= 0) {
103+ KERNEL_LOG_ERROR("aic_core_num must be positive, but got %ld", aicCoreNum_);
104+ return false;
105+ }
106+ if (numHeadsQ_ <= 0 || numHeadsK_ <= 0 || headDim_ <= 0) {
107+ KERNEL_LOG_ERROR("num_heads_q/num_heads_k/head_dim must be positive, but got nq=%ld nk=%ld d=%ld", numHeadsQ_,
108+ numHeadsK_, headDim_);
109+ return false;
110+ }
111+ if (numHeadsQ_ % numHeadsK_ != 0) {
112+ KERNEL_LOG_ERROR("num_heads_q must be divisible by num_heads_k, but got nq=%ld nk=%ld", numHeadsQ_, numHeadsK_);
113+ return false;
114+ }
115+ if (bSize_ <= 0) {
116+ KERNEL_LOG_ERROR("batch_size must be positive, but got %ld", bSize_);
117+ return false;
118+ }
119+ if (layoutType_ == SmlaLayout::BSND && s1Size_ <= 0) {
120+ KERNEL_LOG_ERROR("max_seqlen_q must be positive for BSND, but got %ld", s1Size_);
121+ return false;
122+ }
123+ if (s1Size_ < 0 || s2Size_ < 0) {
124+ KERNEL_LOG_ERROR("max_seqlen_q/max_seqlen_k must be non-negative, but got q=%ld k=%ld", s1Size_, s2Size_);
125+ return false;
126+ }
127+ if (maskMode_ != static_cast<int64_t>(SmlaSparseMode::NO_MASK) &&
128+ maskMode_ != static_cast<int64_t>(SmlaSparseMode::RIGHT_DOWN_CAUSAL)) {
129+ KERNEL_LOG_ERROR("mask_mode only supports 0 or 3, but got %ld", maskMode_);
130+ return false;
131+ }
132+ if (cmpRatio_ < 1 || cmpRatio_ > 128) {
133+ KERNEL_LOG_ERROR("cmp_ratio must be in [1, 128], but got %ld", cmpRatio_);
134+ return false;
135+ }
136+ if (layoutType_ == SmlaLayout::TND && !IsTensorValid(cuSeqLensQuery_)) {
137+ KERNEL_LOG_ERROR("cu_seqlens_q must be provided for TND layout.");
138+ return false;
139+ }
140+ if (layoutType_ == SmlaLayout::TND && !IsTensorValid(cuSeqLensKey_)) {
141+ KERNEL_LOG_ERROR("cu_seqlens_k must be provided for TND layout.");
142+ return false;
143+ }
144+ if (IsTensorValid(cuSeqLensQuery_) && cuSeqLensQuery_->GetTensorShape()->GetDimSize(0) != bSize_ + 1) {
145+ KERNEL_LOG_ERROR("cu_seqlens_q length must be batch_size + 1, but got %ld and batch_size=%ld.",
146+ cuSeqLensQuery_->GetTensorShape()->GetDimSize(0), bSize_);
147+ return false;
148+ }
149+ if (IsTensorValid(cuSeqLensKey_) && cuSeqLensKey_->GetTensorShape()->GetDimSize(0) != bSize_ + 1) {
150+ KERNEL_LOG_ERROR("cu_seqlens_k length must be batch_size + 1, but got %ld and batch_size=%ld.",
151+ cuSeqLensKey_->GetTensorShape()->GetDimSize(0), bSize_);
152+ return false;
153+ }
154+ if (IsTensorValid(seqUsedQuery_) && seqUsedQuery_->GetTensorShape()->GetDimSize(0) != bSize_) {
155+ KERNEL_LOG_ERROR("seqused_q length must be batch_size, but got %ld and batch_size=%ld.",
156+ seqUsedQuery_->GetTensorShape()->GetDimSize(0), bSize_);
157+ return false;
158+ }
159+ if (IsTensorValid(seqUsedKey_) && seqUsedKey_->GetTensorShape()->GetDimSize(0) != bSize_) {
160+ KERNEL_LOG_ERROR("seqused_k length must be batch_size, but got %ld and batch_size=%ld.",
161+ seqUsedKey_->GetTensorShape()->GetDimSize(0), bSize_);
162+ return false;
163+ }
164+ if (IsTensorValid(cmpResidualKey_) && cmpResidualKey_->GetTensorShape()->GetDimSize(0) != bSize_) {
165+ KERNEL_LOG_ERROR("cmp_residual_k length must be batch_size, but got %ld and batch_size=%ld.",
166+ cmpResidualKey_->GetTensorShape()->GetDimSize(0), bSize_);
167+ return false;
168+ }
169+ if (IsTensorValid(topkLength_) && topkLength_->GetTensorShape()->GetDims() < 1) {
170+ KERNEL_LOG_ERROR("topk_length must be at least 1-dimensional.");
171+ return false;
172+ }
173+ return true;
174+}
175+ 
176+namespace {
177+static const char *kernelType = "SparseFlashMlaSoftmaxL1NormMetadata";
178+REGISTER_CPU_KERNEL(kernelType, SparseFlashMlaSoftmaxL1NormMetadataCpuKernel);
179+} // namespace
180+} // namespace aicpu
@@ -0,0 +1,125 @@
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 sparse_flash_mla_softmax_l1_norm_metadata_aicpu.h
13+ * \brief
14+ */
15+#ifndef SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_AICPU_H
16+#define SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_AICPU_H
17+ 
18+#include <cstdint>
19+#include <string>
20+#include <type_traits>
21+#include "cpu_context.h"
22+#include "cpu_kernel.h"
23+#include "cpu_tensor.h"
24+ 
25+namespace aicpu {
26+ 
27+enum class SmlaSparseMode : int32_t {
28+ NO_MASK = 0,
29+ RIGHT_DOWN_CAUSAL = 3,
30+};
31+ 
32+enum class SmlaLayout {
33+ BSND = 0,
34+ TND = 1,
35+};
36+ 
37+enum class ValidSocVersion { ASCEND910 = 0, ASCEND950 };
38+ 
39+inline bool IsTensorValid(Tensor *tensor)
40+{
41+ return tensor != nullptr && tensor->GetData() != nullptr && tensor->GetTensorShape() != nullptr;
42+}
43+ 
44+template <typename T>
45+inline typename std::enable_if<std::is_integral_v<T>, bool>::type GetAttrValue(CpuKernelContext &ctx,
46+ const std::string &name, T &value)
47+{
48+ auto attr = ctx.GetAttr(name);
49+ if (attr == nullptr) {
50+ KERNEL_LOG_ERROR("attr is null: %s", name.c_str());
51+ return false;
52+ }
53+ value = static_cast<T>(attr->GetInt());
54+ return true;
55+}
56+ 
57+inline bool GetAttrValue(CpuKernelContext &ctx, const std::string &name, std::string &value)
58+{
59+ auto attr = ctx.GetAttr(name);
60+ if (attr == nullptr) {
61+ KERNEL_LOG_ERROR("attr is null: %s", name.c_str());
62+ return false;
63+ }
64+ value = attr->GetString();
65+ return true;
66+}
67+ 
68+template <typename T>
69+inline typename std::enable_if<std::is_integral_v<T>, void>::type GetAttrValueOpt(CpuKernelContext &ctx,
70+ const std::string &name, T &value)
71+{
72+ auto attr = ctx.GetAttr(name);
73+ if (attr != nullptr) {
74+ value = static_cast<T>(attr->GetInt());
75+ }
76+}
77+ 
78+inline void GetAttrValueOpt(CpuKernelContext &ctx, const std::string &name, std::string &value)
79+{
80+ auto attr = ctx.GetAttr(name);
81+ if (attr != nullptr) {
82+ value = attr->GetString();
83+ }
84+}
85+ 
86+class SparseFlashMlaSoftmaxL1NormMetadataCpuKernel : public CpuKernel {
87+public:
88+ SparseFlashMlaSoftmaxL1NormMetadataCpuKernel() = default;
89+ ~SparseFlashMlaSoftmaxL1NormMetadataCpuKernel() override = default;
90+ uint32_t Compute(CpuKernelContext &ctx) override;
91+ 
92+private:
93+ bool Prepare(CpuKernelContext &ctx);
94+ bool ParamsCheck();
95+ ValidSocVersion ProcessSocVersion();
96+ bool BuildMetadata();
97+ int64_t CalcTotalSize() const;
98+ 
99+ Tensor *cuSeqLensQuery_ = nullptr;
100+ Tensor *cuSeqLensKey_ = nullptr;
101+ Tensor *seqUsedQuery_ = nullptr;
102+ Tensor *seqUsedKey_ = nullptr;
103+ Tensor *cmpResidualKey_ = nullptr;
104+ Tensor *topkLength_ = nullptr;
105+ Tensor *metadata_ = nullptr;
106+ 
107+ int64_t bSize_ = 0;
108+ int64_t s1Size_ = 0;
109+ int64_t s2Size_ = 0;
110+ int64_t numHeadsQ_ = 0;
111+ int64_t numHeadsK_ = 0;
112+ int64_t headDim_ = 0;
113+ int64_t topk_ = 0;
114+ int64_t maskMode_ = 0;
115+ int64_t cmpRatio_ = 1;
116+ int64_t aicCoreNum_ = 36;
117+ std::string socVersion_;
118+ std::string layout_ = "BSND";
119+ std::string layoutK_ = "BSND";
120+ SmlaLayout layoutType_ = SmlaLayout::BSND;
121+};
122+ 
123+} // namespace aicpu
124+ 
125+#endif // SPARSE_FLASH_MLA_SOFTMAX_L1_NORM_METADATA_AICPU_H
@@ -0,0 +1,15 @@
1+{
2+ "SparseFlashMlaSoftmaxL1NormMetadata":{
3+ "opInfo":{
4+ "computeCost":"100",
5+ "engine":"DNN_VM_AICPU",
6+ "flagAsync":"False",
7+ "flagPartial":"False",
8+ "functionName":"RunCpuKernel",
9+ "kernelSo":"libtransformer_aicpu_kernels.so",
10+ "opKernelLib":"CUSTAICPUKernel",
11+ "userDefined":"True",
12+ "workspaceSize":"100"
13+ }
14+ }
15+}
@@ -0,0 +1,386 @@
1+# sparse_flash_mla_softmax_l1_norm
2+ 
3+## 产品支持情况
4+ 
5+<!-- npu="950" id1 -->
6+- <term>Ascend 950PR/Ascend 950DT</term>:支持
7+<!-- end id1 -->
8+<!-- npu="A3" id2 -->
9+- <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:不支持
10+<!-- end id2 -->
11+<!-- npu="910b" id3 -->
12+- <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:不支持
13+<!-- end id3 -->
14+<!-- npu="310b" id4 -->
15+- <term>Atlas 200I/500 A2 推理产品</term>:不支持
16+<!-- end id4 -->
17+<!-- npu="310p" id5 -->
18+- <term>Atlas 推理系列产品</term>:不支持
19+<!-- end id5 -->
20+<!-- npu="910" id6 -->
21+- <term>Atlas 训练系列产品</term>:不支持
22+<!-- end id6 -->
23+ 
24+## 功能说明
25+ 
26+- 接口功能:计算`SparseFlashMla`注意力的Softmax L1Norm结果,支持Compressed Attention以及Sparse Compressed Attention场景。该接口为`dense_lightning_indexer_kl_loss_grad`反向算子的配套接口,输出可用于反向梯度计算。调用过程中,需先调用`sparse_flash_mla_softmax_l1_norm_metadata`接口完成负载均衡计算,再调用`sparse_flash_mla_softmax_l1_norm`接口完成算子计算过程。
27+ - `sparse_flash_mla_softmax_l1_norm_metadata`接口:根据主算子的shape、layout、mask等信息,采用strided方式将任务均衡切分到可用AIC核上,输出metadata供主算子使用。
28+ - `sparse_flash_mla_softmax_l1_norm`接口:根据metadata中的分核信息,对Q和K计算Softmax L1Norm。
29+ 
30+- 计算公式:
31+ 
32+ 阶段一:根据是否为sparse场景,对输入key进行选择
33+ 
34+ * 当为sparse时:
35+ 
36+ $$
37+ selectedKv\text{ }=\text{ }Gather \left( K, sparseIndices \left[ i \left] \left) ,\text{ }0\text{ } < =i < \text{ }selectBlockCount\right. \right. \right. \right.
38+ $$
39+ 
40+ * else:
41+ 
42+ $$
43+ selectedKv\text{ }=\text{ }K
44+ $$
45+ 
46+ 阶段二:计算P(SimpleSoftmax)
47+ 
48+ $$
49+ P = SimpleSoftmax(Mask(Q \text{ }@\text{ } selectedKv^{{T}} \cdot \text{ } scale), lse)
50+ $$
51+ 
52+ 阶段三:计算Softmax L1Norm
53+ 
54+ $$
55+ softmaxL1Norm = \frac{ReduceSum(P, dim=G)}{G}
56+ $$
57+ 
58+ 其中,$G$ 为group数($G = N1 / N2$),$ReduceSum$ 在G维度(query head group维度)上对softmax概率$P$求和后取平均。
59+ 
60+## 函数原型
61+ 
62+调用`sparse_flash_mla_softmax_l1_norm`接口之前,先调用前置接口`sparse_flash_mla_softmax_l1_norm_metadata`,完成负载均衡的计算。
63+ 
64+```python
65+cann_ops_transformer.sparse_flash_mla_softmax_l1_norm_metadata(
66+ num_heads_q,
67+ num_heads_k,
68+ head_dim,
69+ *,
70+ cu_seqlens_q=None,
71+ cu_seqlens_k=None,
72+ seqused_q=None,
73+ seqused_k=None,
74+ cmp_residual_k=None,
75+ topk_length=None,
76+ batch_size=None,
77+ max_seqlen_q=None,
78+ max_seqlen_k=None,
79+ topk=None,
80+ layout_q=None,
81+ layout_k=None,
82+ mask_mode=None,
83+ cmp_ratio=None
84+) -> Tensor
85+```
86+ 
87+```python
88+cann_ops_transformer.sparse_flash_mla_softmax_l1_norm(
89+ q,
90+ k,
91+ softmax_lse,
92+ *,
93+ sparse_indices=None,
94+ cu_seqlens_q=None,
95+ cu_seqlens_k=None,
96+ seqused_q=None,
97+ seqused_k=None,
98+ cmp_residual_k=None,
99+ topk_length=None,
100+ metadata=None,
101+ softmax_scale=1.0,
102+ max_seqlen_k=0,
103+ cmp_ratio=1,
104+ mask_mode=0,
105+ layout_q="BSND",
106+ layout_k="BSND"
107+) -> Tensor
108+```
109+ 
110+## 参数说明
111+ 
112+### sparse_flash_mla_softmax_l1_norm
113+ 
114+| 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) |
115+|--------|----------|-----------|------|----------|-------------|
116+| q | Tensor | 必选 | attention结构的输入Q,对应公式中的$Q$。`layout_q`="BSND"时shape为(B,S1,N1,D);`layout_q`="TND"时shape为(T1,N1,D)。 | float16、bfloat16 | (B,S1,N1,D)、(T1,N1,D) |
117+| k | Tensor | 必选 | attention结构的输入K,对应公式中的$K$。与q的B保持一致,S2支持泛化,N2=1。 | float16、bfloat16 | (B,S2,N2,D)、(T2,N2,D) |
118+| softmax_lse | Tensor | 必选 | 注意力正向计算的输出softmax_lse。与q的B保持一致,N2=1,S1与q的S1保持一致,G=N1/N2。 | float32 | (B,N2,S1,G)、(N2,T1,G) |
119+| sparse_indices | Tensor | 可选 | 稀疏场景下选择的k中权重较高的注意力索引。与q的B/S1保持一致,N2=1,K支持泛化。 | int32 | (B,S1,N2,K)、(T1,N2,K) |
120+| cu_seqlens_q | Tensor | 可选 | 每个Batch中q的有效token数的累加和形式。`layout_q`为TND时该参数必传,长度与B+1保持一致,累加和与T1保持一致。 | int32 | (B+1,) |
121+| cu_seqlens_k | Tensor | 可选 | 每个Batch中k的有效token数的累加和形式。`layout_k`为TND时该参数必传,长度与B+1保持一致,累加和与T2保持一致。 | int32 | (B+1,) |
122+| seqused_q | Tensor | 可选 | 表示不同batch中q实际参与运算的token数。 | int32 | (B,) |
123+| seqused_k | Tensor | 可选 | 表示不同batch中k实际参与运算的token数。 | int32 | (B,) |
124+| cmp_residual_k | Tensor | 可选 | 表示每个batch S2 // cmpRatio后的余数。当k不为空且mask_mode=3时必须传入。 | int32 | (B,) |
125+| topk_length | Tensor | 可选 | 表示每行q对应的k实际可选的topk长度。mask_mode=0且sparse_indices不为空时需要传,且必须为准确值。 | int32 | (B,S1,N2)、(T1,N2) |
126+| metadata | Tensor | 必选 | 表示tiling下沉的aicpu算子输出结果,由`sparse_flash_mla_softmax_l1_norm_metadata`算子生成。 | int32 | (x) |
127+| softmax_scale | float | 可选 | 表示缩放系数,默认值为1.0。推荐值:sqrt(head_dim)的倒数。 | float32 | - |
128+| max_seqlen_k | int | 可选 | 表示k的最大序列长度,TND dense场景用于输出shape推导,默认值为0。 | int | - |
129+| cmp_ratio | int | 可选 | 表示对k的压缩率,取值范围1~128,默认值为1。 | int | - |
130+| mask_mode | int | 可选 | 表示q和k计算的mask模式。0:No mask;3:rightDownCausal模式。默认值为0。 | int | - |
131+| layout_q | str | 可选 | 表示输入q的数据排布格式,支持"BSND"、"TND",默认值为"BSND"。需与layout_k保持一致。 | string | - |
132+| layout_k | str | 可选 | 表示输入k的数据排布格式,支持"BSND"、"TND",默认值为"BSND"。需与layout_q保持一致。 | string | - |
133+ 
134+### sparse_flash_mla_softmax_l1_norm_metadata
135+ 
136+| 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) |
137+|--------|----------|-----------|------|----------|-------------|
138+| num_heads_q | int | 必选 | 表示公式中$Q$的头数(即N1),当前支持1~128。 | int | - |
139+| num_heads_k | int | 必选 | 表示公式中$key$的头数(即N2),当前仅支持1。 | int | - |
140+| head_dim | int | 必选 | 表示头的维度(即D),当前仅支持512。 | int | - |
141+| cu_seqlens_q | Tensor | 可选 | 表示每个Batch中q的有效token数的累加和形式,当`layout_q`为TND时该参数必传,累加和与T1保持一致。 | int32 | (B+1,) |
142+| cu_seqlens_k | Tensor | 可选 | 表示每个Batch中k的有效token数的累加和形式,当`layout_k`为TND时该参数必传,累加和与T2保持一致。 | int32 | (B+1,) |
143+| seqused_q | Tensor | 可选 | 表示不同batch中q实际参与运算的token数。 | int32 | (B,) |
144+| seqused_k | Tensor | 可选 | 预留接口参数,表示不同batch中k实际参与运算的token数,当前kernel路径暂不使用。 | int32 | (B,) |
145+| cmp_residual_k | Tensor | 可选 | 预留接口参数,表示不同batch中k的sequence length与cmpRatio相关的残差,当前kernel路径暂不使用。 | int32 | (B,) |
146+| topk_length | Tensor | 可选 | 表示每行q对应的k实际可选的topk长度。 | int32 | (B,S1,N2)、(T1,N2) |
147+| batch_size | int | 可选 | 表示输入样本批量大小(即B),默认值为None(BSND场景需传正数,TND场景可为None自动推导)。 | int | - |
148+| max_seqlen_q | int | 可选 | 表示q的最大序列长度,默认值为None。BSND场景必须为正数。 | int | - |
149+| max_seqlen_k | int | 可选 | 表示k的最大序列长度,默认值为None。BSND场景必须为正数。 | int | - |
150+| topk | int | 可选 | 表示从k中筛选出的关键token个数,0表示无稀疏,默认值为None。 | int | - |
151+| layout_q | str | 可选 | 表示q的数据排布格式,支持"BSND"、"TND",默认值为None(内部转为"BSND")。 | string | - |
152+| layout_k | str | 可选 | 表示k的数据排布格式,支持"BSND"、"TND",默认值为None(内部转为"BSND")。 | string | - |
153+| mask_mode | int | 可选 | 表示q和k计算的mask模式,0表示No mask,3表示rightDownCausal模式,默认值为None(内部转为0)。 | int | - |
154+| cmp_ratio | int | 可选 | 表示对k的压缩率,取值范围1~128,默认值为None(内部转为1)。 | int | - |
155+ 
156+## 返回值说明
157+ 
158+### sparse_flash_mla_softmax_l1_norm
159+ 
160+| 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) |
161+|--------|----------|-----------|------|----------|-------------|
162+| softmax_l1_norm | Tensor | 必选 | q与k计算得出的softmax L1Norm结果,公式为reduceG(softmax)/G。若存在sparse_indices则该输出不为空,其他场景下输出为空。 | float32 | (B,S1,N2,S2)、(T1,N2,T2) |
163+ 
164+### sparse_flash_mla_softmax_l1_norm_metadata
165+ 
166+| 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) |
167+|--------|----------|-----------|------|----------|-------------|
168+| metadata | Tensor | 必选 | 负载均衡结果输出,采用strided切分方式,每个核处理的seq索引按核间步进排列。 | int32 | (64,) |
169+ 
170+Metadata字段布局:
171+ 
172+| 字段 | index | 说明 |
173+|:---|:---|:---|
174+| totalNum | 0 | 参与负载均衡的seq总数。 |
175+| formerCoreProcessNum | 1 | 常规核处理的seq数,即ceil(totalNum / totalCoreNum)。 |
176+| remainCoreProcessNum | 2 | 尾核处理的seq数,即floor(totalNum / totalCoreNum)。 |
177+| remainCoreNum | 3 | 尾核数目。 |
178+| totalCoreNum | 4 | 实际使用的AIC核数,取min(totalNum, aicCoreNum, 36)。 |
179+ 
180+## 约束说明
181+ 
182+- 该接口支持训练场景下使用。
183+- 该接口支持单算子模式和TorchAir图模式调用。
184+- 参数q、k的数据类型必须保持一致。
185+- 入参为空处理:q为空Tensor时直接返回。
186+ 
187+- Mask模式支持:
188+ 
189+ | 模式 | 含义 | 备注 |
190+ | :--- | :--- | :--- |
191+ | 0 | 不做mask操作 | 支持 |
192+ | 3 | rightDownCausal | 支持 |
193+ 
194+- 规格约束:
195+ 
196+ | 规格项 | 规格 | 规格说明 |
197+ | :--- | :--- | :--- |
198+ | B | 支持泛化 | - |
199+ | S1、S2 | 支持泛化 | 支持S1、S2不等长。 |
200+ | N1 | 1~128 | num_heads_q必须能被num_heads_k整除。 |
201+ | N2 | 1 | 当前仅支持N2=1。 |
202+ | D | 512 | q、k最后一维需保持一致。 |
203+ | layout_q/k | BSND / TND,必须一致 | - |
204+ | cmp_ratio | 1~128 | - |
205+ 
206+ - BSND场景:必传batch_size、max_seqlen_q和max_seqlen_k参数。
207+ - TND场景:必传cu_seqlens_q和cu_seqlens_k参数,batch_size可为None(通过cu_seqlens_q推导)。
208+ - metadata必须传入,由`sparse_flash_mla_softmax_l1_norm_metadata`算子生成。
209+ 
210+## 确定性计算
211+ 
212+默认支持确定性计算。
213+ 
214+## 调用说明
215+ 
216+- 单算子模式调用:
217+ 
218+ ```python
219+ import math
220+ import torch
221+ import torch_npu
222+ import cann_ops_transformer
223+ 
224+ torch_npu.npu.set_device(0)
225+ 
226+ S1 = 16
227+ S2 = 2048
228+ cmp_ratio = 128
229+ actual_seq_q = [S1]
230+ actual_seq_k = [S2]
231+ 
232+ T1 = sum(actual_seq_q)
233+ T2 = sum(actual_seq_k)
234+ 
235+ B = 1
236+ N1 = 128
237+ N2 = 1
238+ D = 512
239+ scale_value = 1.0 / math.sqrt(D)
240+ dtype = torch.float16
241+ input_layout = "TND"
242+ 
243+ q_shape = (T1, N1, D)
244+ k_shape = (T2, N2, D)
245+ softmax_lse_shape = (N2, T1, N1 // N2)
246+ softmax_l1_norm_shape = (T1, N2, T2)
247+ 
248+ cu_seq_qlen = [0] + [sum(actual_seq_q[:x+1]) for x in range(len(actual_seq_q))]
249+ cu_seq_klen = [0] + [sum(actual_seq_k[:x+1]) for x in range(len(actual_seq_k))]
250+ 
251+ q = (torch.rand(q_shape).to(dtype)) * 2
252+ k = (torch.rand(k_shape).to(dtype)) * 2
253+ softmax_lse = (torch.rand(softmax_lse_shape).to(torch.float32))
254+ 
255+ cu_seq_qlen_tensor = torch.tensor(cu_seq_qlen).to(torch.int32).npu()
256+ cu_seq_klen_tensor = torch.tensor(cu_seq_klen).to(torch.int32).npu()
257+ 
258+ cmp_residual_k = torch.zeros(B, dtype=torch.int32, device="npu")
259+ 
260+ # 调用sparse_flash_mla_softmax_l1_norm_metadata完成负载均衡计算
261+ metadata = cann_ops_transformer.sparse_flash_mla_softmax_l1_norm_metadata(
262+ N1, N2, D,
263+ cu_seqlens_q=cu_seq_qlen_tensor,
264+ cu_seqlens_k=cu_seq_klen_tensor,
265+ cmp_residual_k=cmp_residual_k,
266+ max_seqlen_q=S1,
267+ max_seqlen_k=S2,
268+ topk=0,
269+ cmp_ratio=cmp_ratio,
270+ mask_mode=3,
271+ layout_q=input_layout,
272+ layout_k=input_layout,
273+ )
274+ 
275+ # 调用sparse_flash_mla_softmax_l1_norm执行算子计算
276+ softmax_l1_norm = cann_ops_transformer.sparse_flash_mla_softmax_l1_norm(
277+ q.npu(),
278+ k.npu(),
279+ softmax_lse.npu(),
280+ cu_seqlens_q=cu_seq_qlen_tensor,
281+ cu_seqlens_k=cu_seq_klen_tensor,
282+ cmp_residual_k=cmp_residual_k,
283+ metadata=metadata,
284+ softmax_scale=scale_value,
285+ max_seqlen_k=S2,
286+ cmp_ratio=cmp_ratio,
287+ mask_mode=3,
288+ layout_q=input_layout,
289+ layout_k=input_layout,
290+ )
291+ 
292+ torch_npu.npu.synchronize()
293+ assert softmax_l1_norm.shape == softmax_l1_norm_shape
294+ assert softmax_l1_norm.dtype == torch.float32
295+ assert torch.isfinite(softmax_l1_norm.float()).all().item()
296+ ```
297+ 
298+- TorchAir图模式调用:
299+ 
300+ ```python
301+ import math
302+ import torch
303+ import torch_npu
304+ import torchair
305+ import cann_ops_transformer
306+ 
307+ 
308+ class SparseFlashMlaSoftmaxL1NormModel(torch.nn.Module):
309+ def __init__(self):
310+ super().__init__()
311+ 
312+ def forward(self, q, k, softmax_lse, cu_seq_qlen_tensor, cu_seq_klen_tensor,
313+ cmp_residual_k, max_seqlen_k, cmp_ratio, mask_mode, layout_q, layout_k):
314+ # 调用sparse_flash_mla_softmax_l1_norm_metadata完成负载均衡计算
315+ metadata = cann_ops_transformer.sparse_flash_mla_softmax_l1_norm_metadata(
316+ N1, N2, D,
317+ cu_seqlens_q=cu_seq_qlen_tensor,
318+ cu_seqlens_k=cu_seq_klen_tensor,
319+ cmp_residual_k=cmp_residual_k,
320+ max_seqlen_q=S1,
321+ max_seqlen_k=max_seqlen_k,
322+ topk=0,
323+ cmp_ratio=cmp_ratio,
324+ mask_mode=mask_mode,
325+ layout_q=layout_q,
326+ layout_k=layout_k,
327+ )
328+ # 调用sparse_flash_mla_softmax_l1_norm执行算子计算
329+ return cann_ops_transformer.sparse_flash_mla_softmax_l1_norm(
330+ q, k, softmax_lse,
331+ cu_seqlens_q=cu_seq_qlen_tensor,
332+ cu_seqlens_k=cu_seq_klen_tensor,
333+ cmp_residual_k=cmp_residual_k,
334+ metadata=metadata,
335+ softmax_scale=scale_value,
336+ max_seqlen_k=max_seqlen_k,
337+ cmp_ratio=cmp_ratio,
338+ mask_mode=mask_mode,
339+ layout_q=layout_q,
340+ layout_k=layout_k,
341+ )
342+ 
343+ 
344+ torch_npu.npu.set_device(0)
345+ 
346+ S1 = 16
347+ S2 = 2048
348+ cmp_ratio = 128
349+ actual_seq_q = [S1]
350+ actual_seq_k = [S2]
351+ 
352+ T1 = sum(actual_seq_q)
353+ T2 = sum(actual_seq_k)
354+ 
355+ B = 1
356+ N1 = 128
357+ N2 = 1
358+ D = 512
359+ scale_value = 1.0 / math.sqrt(D)
360+ dtype = torch.float16
361+ input_layout = "TND"
362+ 
363+ q_shape = (T1, N1, D)
364+ k_shape = (T2, N2, D)
365+ softmax_lse_shape = (N2, T1, N1 // N2)
366+ 
367+ cu_seq_qlen = [0] + [sum(actual_seq_q[:x+1]) for x in range(len(actual_seq_q))]
368+ cu_seq_klen = [0] + [sum(actual_seq_k[:x+1]) for x in range(len(actual_seq_k))]
369+ 
370+ q = (torch.rand(q_shape).to(dtype)) * 2
371+ k = (torch.rand(k_shape).to(dtype)) * 2
372+ softmax_lse = (torch.rand(softmax_lse_shape).to(torch.float32))
373+ 
374+ cu_seq_qlen_tensor = torch.tensor(cu_seq_qlen).to(torch.int32).npu()
375+ cu_seq_klen_tensor = torch.tensor(cu_seq_klen).to(torch.int32).npu()
376+ 
377+ cmp_residual_k = torch.zeros(B, dtype=torch.int32, device="npu")
378+ 
379+ model = SparseFlashMlaSoftmaxL1NormModel()
380+ config = torchair.CompilerConfig()
381+ # 获取图模式后端
382+ npu_backend = torchair.get_npu_backend(compiler_config=config)
383+ model = torch.compile(model, backend=npu_backend, dynamic=True)
384+ softmax_l1_norm = model(q, k, softmax_lse, cu_seq_qlen_tensor, cu_seq_klen_tensor,
385+ cmp_residual_k, S2, cmp_ratio, 3, input_layout, input_layout)
386+ ```
@@ -23,6 +23,10 @@ from .quant_sparse_flash_mla import (
23)23)
24from .scatter_pa_kv_cache_with_k_scale import scatter_pa_kv_cache_with_k_scale24from .scatter_pa_kv_cache_with_k_scale import scatter_pa_kv_cache_with_k_scale
25from .sparse_flash_mla import sparse_flash_mla, sparse_flash_mla_metadata25from .sparse_flash_mla import sparse_flash_mla, sparse_flash_mla_metadata
26+from .sparse_flash_mla_softmax_l1_norm import (
27+ sparse_flash_mla_softmax_l1_norm,
28+ sparse_flash_mla_softmax_l1_norm_metadata,
29+)
26from .sparse_lightning_indexer_kl_loss_grad import (30from .sparse_lightning_indexer_kl_loss_grad import (
27 sparse_lightning_indexer_kl_loss_grad,31 sparse_lightning_indexer_kl_loss_grad,
28 sparse_lightning_indexer_kl_loss_grad_metadata,32 sparse_lightning_indexer_kl_loss_grad_metadata,