Merged
A5 QSMLA 支持N泛化和LSE #9167
A5 QSMLA 支持N泛化和LSE #9167
Merged
CccccccAdd on Jul 25
Total: 21 files changed+2373-1540
@@ -42,6 +42,7 @@ const std::string CMP_KV_NAME = "cmp_kv";
42const std::string ORI_SPARSE_INDICES_NAME = "ori_sparse_indices";42const std::string ORI_SPARSE_INDICES_NAME = "ori_sparse_indices";
43const std::string CMP_SPARSE_INDICES_NAME = "cmp_sparse_indices";43const std::string CMP_SPARSE_INDICES_NAME = "cmp_sparse_indices";
44const std::string ATTEN_OUT_NAME = "attention_out";44const std::string ATTEN_OUT_NAME = "attention_out";
45+const std::string SOFTMAX_LSE_NAME = "softmax_lse";
45 46 
46const std::string CU_SEQLENS_Q_NAME = "cu_seqlens_q";47const std::string CU_SEQLENS_Q_NAME = "cu_seqlens_q";
47const std::string CU_SEQLENS_ORI_KV_NAME = "cu_seqlens_ori_kv";48const std::string CU_SEQLENS_ORI_KV_NAME = "cu_seqlens_ori_kv";
@@ -76,10 +77,10 @@ enum class QSMLAAxis : uint32_t {
76 S = 1,77 S = 1,
77 N = 2,78 N = 2,
78 D = 3,79 D = 3,
79- K = 3, // sparse_indices的K和key的D枚举值相同,表达相同位置, 最后一维80+ K = 3, // sparse_indices的K和key的D枚举值相同,表达相同位置, 最后一维
80 T = 5,81 T = 5,
81 Bn = 6, // block number82 Bn = 6, // block number
82- Bs = 7 // block size83+ Bs = 7 // block size
83};84};
84 85 
85enum class QSMLATemplateMode : uint32_t {86enum class QSMLATemplateMode : uint32_t {
@@ -146,6 +147,7 @@ constexpr uint32_t ATTR_TOPK_VALUE_MODE_INDEX = 9;
146constexpr uint32_t ATTR_RETURN_SOFTMAX_LSE_INDEX = 10;147constexpr uint32_t ATTR_RETURN_SOFTMAX_LSE_INDEX = 10;
147 148 
148// Dim Index149// Dim Index
150+constexpr uint32_t DIM_IDX_ZERO = 0;
149constexpr uint32_t DIM_IDX_ONE = 1;151constexpr uint32_t DIM_IDX_ONE = 1;
150constexpr uint32_t DIM_IDX_TWO = 2;152constexpr uint32_t DIM_IDX_TWO = 2;
151constexpr uint32_t DIM_IDX_THREE = 3;153constexpr uint32_t DIM_IDX_THREE = 3;
@@ -259,6 +261,7 @@ struct QSMLAParaInfo {
259 const char *layoutQ = nullptr;261 const char *layoutQ = nullptr;
260 const char *layoutKv = nullptr;262 const char *layoutKv = nullptr;
261 const int64_t *topkValueMode = nullptr;263 const int64_t *topkValueMode = nullptr;
264+ const bool *returnSoftmaxLse = nullptr;
262};265};
263 266 
264// -----------算子Tiling入参信息类---------------267// -----------算子Tiling入参信息类---------------
@@ -327,19 +330,23 @@ public:
327 QSMLALayout qLayout = QSMLALayout::BSND;330 QSMLALayout qLayout = QSMLALayout::BSND;
328 QSMLALayout kvLayout = QSMLALayout::PA_BBND;331 QSMLALayout kvLayout = QSMLALayout::PA_BBND;
329 QSMLALayout outLayout = QSMLALayout::BSND;332 QSMLALayout outLayout = QSMLALayout::BSND;
333+ 
334+ bool returnSoftmaxLse = false;
330};335};
331 336 
332class QSMLAInfoParser {337class QSMLAInfoParser {
333public:338public:
334- explicit QSMLAInfoParser(gert::TilingContext *context) : context_(context) {}339+ explicit QSMLAInfoParser(gert::TilingContext *context) : context_(context)
340+ {
341+ }
335 ~QSMLAInfoParser() = default;342 ~QSMLAInfoParser() = default;
336 343 
337 ge::graphStatus CheckRequiredInOutExistence() const;344 ge::graphStatus CheckRequiredInOutExistence() const;
338 ge::graphStatus CheckRequiredAttrExistence() const;345 ge::graphStatus CheckRequiredAttrExistence() const;
339 ge::graphStatus CheckRequiredParaExistence() const;346 ge::graphStatus CheckRequiredParaExistence() const;
340 347 
341- ge::graphStatus GetActualSeqLenSize(uint32_t &size, const gert::Tensor *tensor,348+ ge::graphStatus GetActualSeqLenSize(uint32_t &size, const gert::Tensor *tensor, QSMLALayout &layout,
342- QSMLALayout &layout, const std::string &name) const;349+ const std::string &name) const;
343 ge::graphStatus GetActualSeqLenQSize(uint32_t &size);350 ge::graphStatus GetActualSeqLenQSize(uint32_t &size);
344 ge::graphStatus GetOpName();351 ge::graphStatus GetOpName();
345 ge::graphStatus GetNpuInfo();352 ge::graphStatus GetNpuInfo();
@@ -447,26 +454,27 @@ private:
447 uint32_t GetAxisNum(const gert::Shape &shape, const QSMLAAxis &axis, const QSMLALayout &layout) const;454 uint32_t GetAxisNum(const gert::Shape &shape, const QSMLAAxis &axis, const QSMLALayout &layout) const;
448 static constexpr int64_t invalidDimValue_ = std::numeric_limits<int64_t>::min();455 static constexpr int64_t invalidDimValue_ = std::numeric_limits<int64_t>::min();
449 456 
450- void LogErrorDtypeSupport(const std::vector<ge::DataType> &expectDtypeList,457+ void LogErrorDtypeSupport(const std::vector<ge::DataType> &expectDtypeList, const ge::DataType &actualDtype,
451- const ge::DataType &actualDtype, const std::string &name) const;458+ const std::string &name) const;
452- ge::graphStatus CheckDtypeSupport(const gert::CompileTimeTensorDesc *desc,459+ ge::graphStatus CheckDtypeSupport(const gert::CompileTimeTensorDesc *desc, const std::string &name) const;
453- const std::string &name) const;460+ template <typename T>
454- template <typename T> void LogErrorNumberSupport(const std::vector<T> &expectNumberList,461+ void LogErrorNumberSupport(const std::vector<T> &expectNumberList, const T &actualValue, const std::string &name,
455- const T &actualValue, const std::string &name, const std::string subName) const;462+ const std::string subName) const;
456- template <typename T> void LogErrorDimNumSupport(const std::vector<T> &expectNumberList,463+ template <typename T>
457- const T &actualValue, const std::string &name) const;464+ void LogErrorDimNumSupport(const std::vector<T> &expectNumberList, const T &actualValue,
458- ge::graphStatus CheckDimNumSupport(const gert::StorageShape *shape,465+ const std::string &name) const;
459- const std::vector<size_t> &expectDimNumList, const std::string &name) const;466+ ge::graphStatus CheckDimNumSupport(const gert::StorageShape *shape, const std::vector<size_t> &expectDimNumList,
467+ const std::string &name) const;
460 ge::graphStatus CheckShapeNumSupport(const gert::StorageShape *shape,468 ge::graphStatus CheckShapeNumSupport(const gert::StorageShape *shape,
461- const std::vector<int64_t> &expectShapeNumList, const std::string &name) const;469+ const std::vector<int64_t> &expectShapeNumList, const std::string &name) const;
462- ge::graphStatus CheckDimNumInLayoutSupport(const QSMLALayout &layout,470+ ge::graphStatus CheckDimNumInLayoutSupport(const QSMLALayout &layout, const gert::StorageShape *shape,
463- const gert::StorageShape *shape, const std::string &name) const;471+ const std::string &name) const;
464- void LogErrorLayoutSupport(const std::vector<QSMLALayout> &expectLayoutList,472+ void LogErrorLayoutSupport(const std::vector<QSMLALayout> &expectLayoutList, const QSMLALayout &actualLayout,
465- const QSMLALayout &actualLayout, const std::string &name) const;473+ const std::string &name) const;
466- ge::graphStatus GetExpectedShape(gert::Shape &shapeExpected,474+ ge::graphStatus GetExpectedShape(gert::Shape &shapeExpected, const QSMLATilingShapeCompareParam &param,
467- const QSMLATilingShapeCompareParam &param, const QSMLALayout &layout) const;475+ const QSMLALayout &layout) const;
468- ge::graphStatus CompareShape(QSMLATilingShapeCompareParam &param,476+ ge::graphStatus CompareShape(QSMLATilingShapeCompareParam &param, const gert::Shape &shape,
469- const gert::Shape &shape, const QSMLALayout &layout, const std::string &name) const;477+ const QSMLALayout &layout, const std::string &name) const;
470 ge::graphStatus CheckLayoutSupport(const QSMLALayout &actualLayout, const std::string &name) const;478 ge::graphStatus CheckLayoutSupport(const QSMLALayout &actualLayout, const std::string &name) const;
471 ge::graphStatus CheckSingleParaQuery() const;479 ge::graphStatus CheckSingleParaQuery() const;
472 ge::graphStatus CheckSingleParaKey() const;480 ge::graphStatus CheckSingleParaKey() const;
@@ -495,8 +503,8 @@ private:
495 ge::graphStatus CheckCmpSparseIndicesExistence();503 ge::graphStatus CheckCmpSparseIndicesExistence();
496 ge::graphStatus CheckParaExistence();504 ge::graphStatus CheckParaExistence();
497 ge::graphStatus CheckCmpRatioExistence();505 ge::graphStatus CheckCmpRatioExistence();
498- ge::graphStatus GetActualSeqLenSize(uint32_t &size, const gert::Tensor *tensor,506+ ge::graphStatus GetActualSeqLenSize(uint32_t &size, const gert::Tensor *tensor, const QSMLALayout &layout,
499- const QSMLALayout &layout, const std::string &name) const;507+ const std::string &name) const;
500 ge::graphStatus CheckSWAExistence();508 ge::graphStatus CheckSWAExistence();
501 ge::graphStatus CheckHCAExistence();509 ge::graphStatus CheckHCAExistence();
502 ge::graphStatus CheckCSAExistence();510 ge::graphStatus CheckCSAExistence();
@@ -510,8 +518,8 @@ private:
510 ge::graphStatus CheckTopK();518 ge::graphStatus CheckTopK();
511 ge::graphStatus CheckTopkShape();519 ge::graphStatus CheckTopkShape();
512 ge::graphStatus CheckBlockTable() const;520 ge::graphStatus CheckBlockTable() const;
513- ge::graphStatus CheckDTypeConsistency(const ge::DataType &actualDtype,521+ ge::graphStatus CheckDTypeConsistency(const ge::DataType &actualDtype, const ge::DataType &expectDtype,
514- const ge::DataType &expectDtype, const std::string &name) const;522+ const std::string &name) const;
515 523 
516 ge::graphStatus CheckAttenOut();524 ge::graphStatus CheckAttenOut();
517 ge::graphStatus CheckAttenOutShape();525 ge::graphStatus CheckAttenOutShape();
@@ -555,7 +563,7 @@ private:
555 int64_t cmpS2Size_ = 0;563 int64_t cmpS2Size_ = 0;
556 uint32_t qkHeadDim_ = 0;564 uint32_t qkHeadDim_ = 0;
557 uint32_t vHeadDim_ = 0;565 uint32_t vHeadDim_ = 0;
558- uint32_t qTSize_ = 0; // 仅TND时生效566+ uint32_t qTSize_ = 0; // 仅TND时生效
559 uint32_t kvTSize_ = 0; // 仅TND时生效567 uint32_t kvTSize_ = 0; // 仅TND时生效
560 KvStorageMode kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS;568 KvStorageMode kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS;
561 uint32_t sparseBlockCount_ = 0;569 uint32_t sparseBlockCount_ = 0;
@@ -619,4 +627,4 @@ private:
619 gert::Shape attenOutShapeCmp_{};627 gert::Shape attenOutShapeCmp_{};
620};628};
621} // namespace optiling629} // namespace optiling
622-#endif // QUANT_SPARSE_FLASH_MLA_CHECK_H630+#endif // QUANT_SPARSE_FLASH_MLA_CHECK_H
@@ -15,20 +15,21 @@
15 15 
16#include <graph/utils/type_utils.h>16#include <graph/utils/type_utils.h>
17#include <register/op_impl_registry.h>17#include <register/op_impl_registry.h>
18-#include "log/log.h"18+#include "err/ops_err.h"
19+#include "quant_sparse_flash_mla_check.h"
19 20 
21+using namespace optiling;
20using namespace ge;22using namespace ge;
21 23 
22namespace ops {24namespace ops {
23constexpr uint32_t QUERY_INPUT_INDEX = 0;25constexpr uint32_t QUERY_INPUT_INDEX = 0;
24-constexpr uint32_t RETURN_SOFTMAX_LSE_INDEX = 10;
25 26 
26ge::graphStatus InferShapeQuantSparseFlashMla(gert::InferShapeContext *context)27ge::graphStatus InferShapeQuantSparseFlashMla(gert::InferShapeContext *context)
27{28{
28- if (context == nullptr) {29+ OP_CHECK_IF(context == nullptr,
29- OP_LOGE("QuantSparseFlashMla", "context is nullptr!");30+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("QuantSparseFlashMla", "InferShapeContext",
30- return ge::GRAPH_FAILED;31+ "InferShapeContext is nullptr"),
31- }32+ return ge::GRAPH_FAILED);
32 const gert::Shape *queryShape = context->GetInputShape(QUERY_INPUT_INDEX);33 const gert::Shape *queryShape = context->GetInputShape(QUERY_INPUT_INDEX);
33 OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);34 OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);
34 gert::Shape *attentionOutShape = context->GetOutputShape(0);35 gert::Shape *attentionOutShape = context->GetOutputShape(0);
@@ -38,30 +39,49 @@ ge::graphStatus InferShapeQuantSparseFlashMla(gert::InferShapeContext *context)
38 gert::Shape *softmaxLseShape = context->GetOutputShape(1);39 gert::Shape *softmaxLseShape = context->GetOutputShape(1);
39 OP_CHECK_NULL_WITH_CONTEXT(context, softmaxLseShape);40 OP_CHECK_NULL_WITH_CONTEXT(context, softmaxLseShape);
40 auto attr = context->GetAttrs();41 auto attr = context->GetAttrs();
41- const bool *returnSoftmaxLsePtr = attr->GetAttrPointer<bool>(RETURN_SOFTMAX_LSE_INDEX);42+ OP_CHECK_NULL_WITH_CONTEXT(context, attr);
43+ const bool *returnSoftmaxLsePtr = attr->GetAttrPointer<bool>(ATTR_RETURN_SOFTMAX_LSE_INDEX);
42 bool returnSoftmaxLse = (returnSoftmaxLsePtr != nullptr) ? *returnSoftmaxLsePtr : false;44 bool returnSoftmaxLse = (returnSoftmaxLsePtr != nullptr) ? *returnSoftmaxLsePtr : false;
45+ 
46+ const gert::Shape *kvShape = context->GetInputShape(ORI_KV_INDEX);
47+ OP_CHECK_NULL_WITH_CONTEXT(context, kvShape);
48+ const char *layoutQ = attr->GetStr(ATTR_LAYOUT_Q_INDEX);
49+ const char *layoutKv = attr->GetStr(ATTR_LAYOUT_KV_INDEX);
50+ std::string layoutQStr = (layoutQ != nullptr) ? std::string(layoutQ) : "BSND";
51+ std::string layoutKvStr = (layoutKv != nullptr) ? std::string(layoutKv) : "BSND";
43 if (returnSoftmaxLse) {52 if (returnSoftmaxLse) {
44- *softmaxLseShape = *queryShape;53+ if (layoutQStr == "TND") {
45- auto lastDimIdx = softmaxLseShape->GetDimNum() - 1;54+ int64_t kvHeadNum;
46- softmaxLseShape->SetDim(lastDimIdx, 1);55+ if (layoutKvStr == "PA_BBND") {
56+ kvHeadNum = kvShape->GetDim(DIM_IDX_TWO);
57+ } else {
58+ kvHeadNum = kvShape->GetDim(DIM_IDX_ONE);
59+ }
60+ softmaxLseShape->SetDimNum(DIM_NUM_THREE);
61+ softmaxLseShape->SetDim(DIM_IDX_ZERO, kvHeadNum);
62+ softmaxLseShape->SetDim(DIM_IDX_ONE, queryShape->GetDim(DIM_IDX_ZERO));
63+ softmaxLseShape->SetDim(DIM_IDX_TWO, queryShape->GetDim(DIM_IDX_ONE) / kvHeadNum);
64+ } else {
65+ int64_t kvHeadNum = kvShape->GetDim(DIM_IDX_TWO);
66+ softmaxLseShape->SetDimNum(DIM_NUM_FOUR);
67+ softmaxLseShape->SetDim(DIM_IDX_ZERO, queryShape->GetDim(DIM_IDX_ZERO));
68+ softmaxLseShape->SetDim(DIM_IDX_ONE, kvHeadNum);
69+ softmaxLseShape->SetDim(DIM_IDX_TWO, queryShape->GetDim(DIM_IDX_ONE));
70+ softmaxLseShape->SetDim(DIM_IDX_THREE, queryShape->GetDim(DIM_IDX_TWO) / kvHeadNum);
71+ }
47 } else {72 } else {
48- softmaxLseShape->SetDimNum(1);73+ softmaxLseShape->SetDimNum(DIM_NUM_ONE);
49- softmaxLseShape->SetDim(0, 0);74+ softmaxLseShape->SetDim(DIM_IDX_ZERO, 0);
50 }75 }
51 return GRAPH_SUCCESS;76 return GRAPH_SUCCESS;
52}77}
53 78 
54ge::graphStatus InferDataTypeQuantSparseFlashMla(gert::InferDataTypeContext *context)79ge::graphStatus InferDataTypeQuantSparseFlashMla(gert::InferDataTypeContext *context)
55{80{
56- if (context == nullptr) {
57- OP_LOGE("QuantSparseFlashMla", "context is nullptr!");
58- return ge::GRAPH_FAILED;
59- }
60 context->SetOutputDataType(0, ge::DT_BF16); // 目前仅支持BF1681 context->SetOutputDataType(0, ge::DT_BF16); // 目前仅支持BF16
82+ context->SetOutputDataType(SOFTMAX_LSE_INDEX, ge::DT_FLOAT);
61 return ge::GRAPH_SUCCESS;83 return ge::GRAPH_SUCCESS;
62}84}
63 85 
64-IMPL_OP(QuantSparseFlashMla)86+IMPL_OP(QuantSparseFlashMla).InferShape(InferShapeQuantSparseFlashMla).InferDataType(InferDataTypeQuantSparseFlashMla);
65- .InferShape(InferShapeQuantSparseFlashMla)
66- .InferDataType(InferDataTypeQuantSparseFlashMla);
67} // namespace ops87} // namespace ops
@@ -20,8 +20,8 @@
20using namespace ge;20using namespace ge;
21using namespace AscendC;21using namespace AscendC;
22using std::map;22using std::map;
23-using std::string;
24using std::pair;23using std::pair;
24+using std::string;
25namespace optiling {25namespace optiling {
26 26 
27struct QSMLACompileInfo {27struct QSMLACompileInfo {
@@ -44,8 +44,7 @@ ge::graphStatus QSMLAInfoParser::CheckRequiredAttrExistence() const
44 44 
45ge::graphStatus QSMLAInfoParser::CheckRequiredParaExistence() const45ge::graphStatus QSMLAInfoParser::CheckRequiredParaExistence() const
46{46{
47- if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS ||47+ if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) {
48- CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) {
49 return ge::GRAPH_FAILED;48 return ge::GRAPH_FAILED;
50 }49 }
51 50 
@@ -137,7 +136,7 @@ ge::graphStatus QSMLAInfoParser::GetAttrParaInfo()
137{136{
138 auto attrs = context_->GetAttrs();137 auto attrs = context_->GetAttrs();
139 OP_CHECK_IF(attrs == nullptr, OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), "attrs got from ge is nullptr"),138 OP_CHECK_IF(attrs == nullptr, OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), "attrs got from ge is nullptr"),
140- return ge::GRAPH_FAILED);139+ return ge::GRAPH_FAILED);
141 140 
142 OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo start");141 OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo start");
143 opParamInfo_.quantMode = attrs->GetAttrPointer<int64_t>(ATTR_QUANT_MODE_INDEX);142 opParamInfo_.quantMode = attrs->GetAttrPointer<int64_t>(ATTR_QUANT_MODE_INDEX);
@@ -150,7 +149,7 @@ ge::graphStatus QSMLAInfoParser::GetAttrParaInfo()
150 opParamInfo_.layoutQ = attrs->GetStr(ATTR_LAYOUT_Q_INDEX);149 opParamInfo_.layoutQ = attrs->GetStr(ATTR_LAYOUT_Q_INDEX);
151 opParamInfo_.layoutKv = attrs->GetStr(ATTR_LAYOUT_KV_INDEX);150 opParamInfo_.layoutKv = attrs->GetStr(ATTR_LAYOUT_KV_INDEX);
152 opParamInfo_.topkValueMode = attrs->GetAttrPointer<int64_t>(ATTR_TOPK_VALUE_MODE_INDEX);151 opParamInfo_.topkValueMode = attrs->GetAttrPointer<int64_t>(ATTR_TOPK_VALUE_MODE_INDEX);
153- 152+ opParamInfo_.returnSoftmaxLse = attrs->GetAttrPointer<bool>(ATTR_RETURN_SOFTMAX_LSE_INDEX);
154 OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo end");153 OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo end");
155 154 
156 return ge::GRAPH_SUCCESS;155 return ge::GRAPH_SUCCESS;
@@ -184,8 +183,8 @@ ge::graphStatus QSMLAInfoParser::GetQueryAndOutLayout()
184 // 获取q和attnOut的Layout基准值183 // 获取q和attnOut的Layout基准值
185 // layoutQuery: {qLayout, outLayout}184 // layoutQuery: {qLayout, outLayout}
186 const map<string, pair<QSMLALayout, QSMLALayout>> layoutMap = {185 const map<string, pair<QSMLALayout, QSMLALayout>> layoutMap = {
187- {"BSND", {QSMLALayout::BSND, QSMLALayout::BSND}},186+ {"BSND", {QSMLALayout::BSND, QSMLALayout::BSND}},
188- {"TND", {QSMLALayout::TND, QSMLALayout::TND }},187+ {"TND", {QSMLALayout::TND, QSMLALayout::TND}},
189 };188 };
190 189 
191 std::string layout(opParamInfo_.layoutQ);190 std::string layout(opParamInfo_.layoutQ);
@@ -203,9 +202,9 @@ ge::graphStatus QSMLAInfoParser::GetQueryAndOutLayout()
203ge::graphStatus QSMLAInfoParser::GetKvLayout()202ge::graphStatus QSMLAInfoParser::GetKvLayout()
204{203{
205 const map<string, QSMLALayout> layoutKVMap = {204 const map<string, QSMLALayout> layoutKVMap = {
206- {"PA_BBND", QSMLALayout::PA_BBND},205+ {"PA_BBND", QSMLALayout::PA_BBND},
207- {"TND", QSMLALayout::TND},206+ {"TND", QSMLALayout::TND},
208- {"BSND", QSMLALayout::BSND},207+ {"BSND", QSMLALayout::BSND},
209 };208 };
210 209 
211 std::string layout(opParamInfo_.layoutKv);210 std::string layout(opParamInfo_.layoutKv);
@@ -223,17 +222,17 @@ ge::graphStatus QSMLAInfoParser::GetKvLayout()
223 222 
224bool QSMLAInfoParser::HasAxis(const QSMLAAxis &axis, const QSMLALayout &layout, const gert::Shape &shape) const223bool QSMLAInfoParser::HasAxis(const QSMLAAxis &axis, const QSMLALayout &layout, const gert::Shape &shape) const
225{224{
226- const auto& layoutIt = QSMLA_LAYOUT_AXIS_MAP.find(layout);225+ const auto &layoutIt = QSMLA_LAYOUT_AXIS_MAP.find(layout);
227 if (layoutIt == QSMLA_LAYOUT_AXIS_MAP.end()) {226 if (layoutIt == QSMLA_LAYOUT_AXIS_MAP.end()) {
228 return false;227 return false;
229 }228 }
230 229 
231- const std::vector<QSMLAAxis>& axes = layoutIt->second;230+ const std::vector<QSMLAAxis> &axes = layoutIt->second;
232- const auto& axisIt = std::find(axes.begin(), axes.end(), axis);231+ const auto &axisIt = std::find(axes.begin(), axes.end(), axis);
233 if (axisIt == axes.end()) {232 if (axisIt == axes.end()) {
234 return false;233 return false;
235 }234 }
236- const auto& dimIt = QSMLA_LAYOUT_DIM_MAP.find(layout);235+ const auto &dimIt = QSMLA_LAYOUT_DIM_MAP.find(layout);
237 if (dimIt == QSMLA_LAYOUT_DIM_MAP.end() || dimIt->second != shape.GetDimNum()) {236 if (dimIt == QSMLA_LAYOUT_DIM_MAP.end() || dimIt->second != shape.GetDimNum()) {
238 return false;237 return false;
239 }238 }
@@ -242,8 +241,8 @@ bool QSMLAInfoParser::HasAxis(const QSMLAAxis &axis, const QSMLALayout &layout,
242 241 
243size_t QSMLAInfoParser::GetAxisIdx(const QSMLAAxis &axis, const QSMLALayout &layout) const242size_t QSMLAInfoParser::GetAxisIdx(const QSMLAAxis &axis, const QSMLALayout &layout) const
244{243{
245- const std::vector<QSMLAAxis>& axes = QSMLA_LAYOUT_AXIS_MAP.find(layout)->second;244+ const std::vector<QSMLAAxis> &axes = QSMLA_LAYOUT_AXIS_MAP.find(layout)->second;
246- const auto& axisIt = std::find(axes.begin(), axes.end(), axis);245+ const auto &axisIt = std::find(axes.begin(), axes.end(), axis);
247 return std::distance(axes.begin(), axisIt);246 return std::distance(axes.begin(), axisIt);
248}247}
249 248 
@@ -290,18 +289,17 @@ ge::graphStatus QSMLAInfoParser::GetGSize()
290 return ge::GRAPH_SUCCESS;289 return ge::GRAPH_SUCCESS;
291}290}
292 291 
293-ge::graphStatus QSMLAInfoParser::GetActualSeqLenSize(uint32_t &size, const gert::Tensor *tensor,292+ge::graphStatus QSMLAInfoParser::GetActualSeqLenSize(uint32_t &size, const gert::Tensor *tensor, QSMLALayout &layout,
294- QSMLALayout &layout, const std::string &name) const293+ const std::string &name) const
295{294{
296 if ((tensor == nullptr)) {295 if ((tensor == nullptr)) {
297- OP_LOGE(opName_, "when layout of q is %s, %s must be provided.",296+ OP_LOGE(opName_, "when layout of q is %s, %s must be provided.", QSMLALayoutToSerialString(layout).c_str(),
298- QSMLALayoutToSerialString(layout).c_str(), name.c_str());297+ name.c_str());
299 return ge::GRAPH_FAILED;298 return ge::GRAPH_FAILED;
300 }299 }
301 int64_t shapeSize = tensor->GetShapeSize();300 int64_t shapeSize = tensor->GetShapeSize();
302 if (shapeSize <= 0) {301 if (shapeSize <= 0) {
303- OP_LOGE(opName_, "the shape size of %s is %ld, it should be greater than 0.",302+ OP_LOGE(opName_, "the shape size of %s is %ld, it should be greater than 0.", name.c_str(), shapeSize);
304- name.c_str(), shapeSize);
305 return ge::GRAPH_FAILED;303 return ge::GRAPH_FAILED;
306 }304 }
307 size = static_cast<uint32_t>(shapeSize);305 size = static_cast<uint32_t>(shapeSize);
@@ -356,17 +354,18 @@ ge::graphStatus QSMLAInfoParser::GetMaxBlockNumPerBatch()
356 }354 }
357 if (opParamInfo_.oriBlockTable.tensor == nullptr) {355 if (opParamInfo_.oriBlockTable.tensor == nullptr) {
358 OP_LOGE(opName_, "the layout_kv is %s, blockTable must be provided.",356 OP_LOGE(opName_, "the layout_kv is %s, blockTable must be provided.",
359- QSMLALayoutToSerialString(kvLayout_).c_str());357+ QSMLALayoutToSerialString(kvLayout_).c_str());
360 return ge::GRAPH_FAILED;358 return ge::GRAPH_FAILED;
361 }359 }
362 uint32_t oriDimNum = opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDimNum();360 uint32_t oriDimNum = opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDimNum();
363 if (oriDimNum != DIM_NUM_TWO) {361 if (oriDimNum != DIM_NUM_TWO) {
364- OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, "ori_block_table",362+ OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, "ori_block_table", std::to_string(oriDimNum).c_str(),
365- std::to_string(oriDimNum).c_str(), std::to_string(DIM_NUM_TWO).c_str());363+ std::to_string(DIM_NUM_TWO).c_str());
366 return ge::GRAPH_FAILED;364 return ge::GRAPH_FAILED;
367 }365 }
368 if (opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1) <= 0) {366 if (opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1) <= 0) {
369- OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, ORI_BLOCK_TABLE_NAME.c_str(),367+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(
368+ opName_, ORI_BLOCK_TABLE_NAME.c_str(),
370 Ops::Base::ToString(opParamInfo_.oriBlockTable.tensor->GetStorageShape()).c_str(),369 Ops::Base::ToString(opParamInfo_.oriBlockTable.tensor->GetStorageShape()).c_str(),
371 ORI_BLOCK_TABLE_NAME + "'s second dimension should be greater than 0");370 ORI_BLOCK_TABLE_NAME + "'s second dimension should be greater than 0");
372 return ge::GRAPH_FAILED;371 return ge::GRAPH_FAILED;
@@ -376,12 +375,13 @@ ge::graphStatus QSMLAInfoParser::GetMaxBlockNumPerBatch()
376 if (opParamInfo_.cmpBlockTable.tensor != nullptr) {375 if (opParamInfo_.cmpBlockTable.tensor != nullptr) {
377 uint32_t cmpDimNum = opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDimNum();376 uint32_t cmpDimNum = opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDimNum();
378 if (cmpDimNum != DIM_NUM_TWO) {377 if (cmpDimNum != DIM_NUM_TWO) {
379- OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, "cmp_block_table",378+ OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, "cmp_block_table", std::to_string(cmpDimNum).c_str(),
380- std::to_string(cmpDimNum).c_str(), std::to_string(DIM_NUM_TWO).c_str());379+ std::to_string(DIM_NUM_TWO).c_str());
381 return ge::GRAPH_FAILED;380 return ge::GRAPH_FAILED;
382 }381 }
383 if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1) <= 0) {382 if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1) <= 0) {
384- OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, CMP_BLOCK_TABLE_NAME.c_str(),383+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(
384+ opName_, CMP_BLOCK_TABLE_NAME.c_str(),
385 Ops::Base::ToString(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()).c_str(),385 Ops::Base::ToString(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()).c_str(),
386 CMP_BLOCK_TABLE_NAME + "'s second dimension should be greater than 0");386 CMP_BLOCK_TABLE_NAME + "'s second dimension should be greater than 0");
387 return ge::GRAPH_FAILED;387 return ge::GRAPH_FAILED;
@@ -513,8 +513,8 @@ void QSMLAInfoParser::GenerateInfo(QSMLATilingInfo &qsmlaInfo)
513 qsmlaInfo.dSizeV = 512;513 qsmlaInfo.dSizeV = 512;
514 qsmlaInfo.dSizeVInput = dSizeKV_;514 qsmlaInfo.dSizeVInput = dSizeKV_;
515 515 
516- qsmlaInfo.totalBlockNum = (opParamInfo_.oriKv.tensor != nullptr) ?516+ qsmlaInfo.totalBlockNum =
517- opParamInfo_.oriKv.tensor->GetStorageShape().GetDim(0) : 0;517+ (opParamInfo_.oriKv.tensor != nullptr) ? opParamInfo_.oriKv.tensor->GetStorageShape().GetDim(0) : 0;
518 qsmlaInfo.sparseBlockSize = 1; // 写死为1518 qsmlaInfo.sparseBlockSize = 1; // 写死为1
519 qsmlaInfo.oriBlockSize = oriBlockSize_;519 qsmlaInfo.oriBlockSize = oriBlockSize_;
520 qsmlaInfo.cmpBlockSize = cmpBlockSize_;520 qsmlaInfo.cmpBlockSize = cmpBlockSize_;
@@ -542,6 +542,7 @@ void QSMLAInfoParser::GenerateInfo(QSMLATilingInfo &qsmlaInfo)
542 qsmlaInfo.qLayout = qLayout_;542 qsmlaInfo.qLayout = qLayout_;
543 qsmlaInfo.kvLayout = kvLayout_;543 qsmlaInfo.kvLayout = kvLayout_;
544 qsmlaInfo.outLayout = outLayout_;544 qsmlaInfo.outLayout = outLayout_;
545+ qsmlaInfo.returnSoftmaxLse = (opParamInfo_.returnSoftmaxLse != nullptr) ? *opParamInfo_.returnSoftmaxLse : false;
545}546}
546 547 
547ge::graphStatus QSMLAInfoParser::Parse(QSMLATilingInfo &qsmlaInfo)548ge::graphStatus QSMLAInfoParser::Parse(QSMLATilingInfo &qsmlaInfo)
@@ -551,33 +552,22 @@ ge::graphStatus QSMLAInfoParser::Parse(QSMLATilingInfo &qsmlaInfo)
551 return ge::GRAPH_FAILED;552 return ge::GRAPH_FAILED;
552 }553 }
553 554 
554- if (ge::GRAPH_SUCCESS != GetOpName() ||555+ if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() || ge::GRAPH_SUCCESS != GetOpParaInfo() ||
555- ge::GRAPH_SUCCESS != GetNpuInfo() ||
556- ge::GRAPH_SUCCESS != GetOpParaInfo() ||
557 ge::GRAPH_SUCCESS != CheckRequiredParaExistence()) {556 ge::GRAPH_SUCCESS != CheckRequiredParaExistence()) {
558 return ge::GRAPH_FAILED;557 return ge::GRAPH_FAILED;
559 }558 }
560 559 
561- if (ge::GRAPH_SUCCESS != GetInOutDataType() ||560+ if (ge::GRAPH_SUCCESS != GetInOutDataType() || ge::GRAPH_SUCCESS != GetQueryAndOutLayout() ||
562- ge::GRAPH_SUCCESS != GetQueryAndOutLayout() ||
563 ge::GRAPH_SUCCESS != GetKvLayout()) {561 ge::GRAPH_SUCCESS != GetKvLayout()) {
564 return ge::GRAPH_FAILED;562 return ge::GRAPH_FAILED;
565 }563 }
566 564 
567 SetQSMLAShape();565 SetQSMLAShape();
568- if (566+ if (ge::GRAPH_SUCCESS != GetN1Size() || ge::GRAPH_SUCCESS != GetN2Size() || ge::GRAPH_SUCCESS != GetGSize() ||
569- ge::GRAPH_SUCCESS != GetN1Size() ||567+ ge::GRAPH_SUCCESS != GetBatchSize() || ge::GRAPH_SUCCESS != GetQTSize() || ge::GRAPH_SUCCESS != GetS1Size() ||
570- ge::GRAPH_SUCCESS != GetN2Size() ||568+ ge::GRAPH_SUCCESS != GetS2Size() || ge::GRAPH_SUCCESS != GetQkHeadDim() ||
571- ge::GRAPH_SUCCESS != GetGSize() ||569+ ge::GRAPH_SUCCESS != GetSparseBlockCount() || ge::GRAPH_SUCCESS != GetDSizeQ() ||
572- ge::GRAPH_SUCCESS != GetBatchSize() ||570+ ge::GRAPH_SUCCESS != GetKvstride() || ge::GRAPH_SUCCESS != GetDSizeKV()) {
573- ge::GRAPH_SUCCESS != GetQTSize() ||
574- ge::GRAPH_SUCCESS != GetS1Size() ||
575- ge::GRAPH_SUCCESS != GetS2Size() ||
576- ge::GRAPH_SUCCESS != GetQkHeadDim() ||
577- ge::GRAPH_SUCCESS != GetSparseBlockCount() ||
578- ge::GRAPH_SUCCESS != GetDSizeQ() ||
579- ge::GRAPH_SUCCESS != GetKvstride() ||
580- ge::GRAPH_SUCCESS != GetDSizeKV()) {
581 return ge::GRAPH_FAILED;571 return ge::GRAPH_FAILED;
582 }572 }
583 573 
@@ -600,8 +590,8 @@ ge::graphStatus QuantSparseFlashMlaTiling::DoOpTiling(QSMLATilingInfo *tilingInf
600{590{
601 if (tilingInfo->opParamInfo.cmpKv.tensor == nullptr) {591 if (tilingInfo->opParamInfo.cmpKv.tensor == nullptr) {
602 OP_CHECK_IF(tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr,592 OP_CHECK_IF(tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr,
603- OP_LOGE("QuantSparseFlashMla", "cmpSparseIndices must be empty when cmpKv is not provided."),593+ OP_LOGE("QuantSparseFlashMla", "cmpSparseIndices must be empty when cmpKv is not provided."),
604- return ge::GRAPH_FAILED);594+ return ge::GRAPH_FAILED);
605 perfMode_ = QSMLATemplateMode::SWA_TEMPLATE_MODE;595 perfMode_ = QSMLATemplateMode::SWA_TEMPLATE_MODE;
606 } else if (tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr) {596 } else if (tilingInfo->opParamInfo.cmpSparseIndices.tensor != nullptr) {
607 perfMode_ = QSMLATemplateMode::CSA_TEMPLATE_MODE;597 perfMode_ = QSMLATemplateMode::CSA_TEMPLATE_MODE;
@@ -618,21 +608,22 @@ ge::graphStatus QuantSparseFlashMlaTiling::DoOpTiling(QSMLATilingInfo *tilingInf
618 608 
619 // -------------set workspacesize-----------------609 // -------------set workspacesize-----------------
620 constexpr uint32_t TRIPLE_BUFFER_NUM = 3;610 constexpr uint32_t TRIPLE_BUFFER_NUM = 3;
621- constexpr uint32_t M_BASE_SIZE = 64; // m轴基本块大小611+ constexpr uint32_t M_BASE_SIZE = 64; // m轴基本块大小
622- constexpr uint32_t S2_BASE_SIZE = 128; // S2轴基本块大小612+ constexpr uint32_t S2_BASE_SIZE = 128; // S2轴基本块大小
623 constexpr uint32_t D_SIZE = 512;613 constexpr uint32_t D_SIZE = 512;
624 constexpr uint32_t VEC_RES_ELEM_SIZE = 2; // 2: fp16/bf16614 constexpr uint32_t VEC_RES_ELEM_SIZE = 2; // 2: fp16/bf16
625- constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数615+ constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数
626- constexpr uint32_t UB_SIZE = 248 * 1024; // UB大小共256KB,预留8k616+ constexpr uint32_t UB_SIZE = 248 * 1024; // UB大小共256KB,预留8k
627- constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128; // VF向量化处理的元素对齐粒度617+ constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128; // VF向量化处理的元素对齐粒度
628- uint32_t alignedSparseBlockCount = (tilingInfo->sparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) /618+ uint32_t alignedSparseBlockCount =
629- SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM;619+ (tilingInfo->sparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM;
630- uint32_t totalBS1 = (tilingInfo->qLayout == QSMLALayout::TND) ?620+ uint32_t totalBS1 =
631- tilingInfo->s1Size : (tilingInfo->bSize * tilingInfo->s1Size);621+ (tilingInfo->qLayout == QSMLALayout::TND) ? tilingInfo->s1Size : (tilingInfo->bSize * tilingInfo->s1Size);
632- uint32_t blocksizeFlag = static_cast<uint32_t>((tilingInfo->cmpBlockSize &622+ uint32_t blocksizeFlag = static_cast<uint32_t>((tilingInfo->cmpBlockSize & (tilingInfo->cmpBlockSize - 1)) ==
633- (tilingInfo->cmpBlockSize - 1)) == 0); // blockSize2是否为2的幂次623+ 0); // blockSize2是否为2的幂次
634 624 
635- uint64_t vectorizeUbSize = static_cast<uint64_t>(tilingInfo->cmpMaxBlockNumPerBatch) * sizeof(int32_t) +625+ uint64_t vectorizeUbSize =
626+ static_cast<uint64_t>(tilingInfo->cmpMaxBlockNumPerBatch) * sizeof(int32_t) +
636 static_cast<uint64_t>(alignedSparseBlockCount) * sizeof(int32_t) +627 static_cast<uint64_t>(alignedSparseBlockCount) * sizeof(int32_t) +
637 static_cast<uint64_t>(alignedSparseBlockCount) * sizeof(int64_t); // 物理地址计算向量化所需ub大小628 static_cast<uint64_t>(alignedSparseBlockCount) * sizeof(int64_t); // 物理地址计算向量化所需ub大小
638 uint32_t vectorizeFlag =629 uint32_t vectorizeFlag =
@@ -674,6 +665,7 @@ ge::graphStatus QuantSparseFlashMlaTiling::DoOpTiling(QSMLATilingInfo *tilingInf
674 tilingData_.baseParams.set_sparseBlockSize(tilingInfo->sparseBlockSize);665 tilingData_.baseParams.set_sparseBlockSize(tilingInfo->sparseBlockSize);
675 tilingData_.baseParams.set_dSize(tilingInfo->dSize);666 tilingData_.baseParams.set_dSize(tilingInfo->dSize);
676 tilingData_.baseParams.set_dSizeVInput(tilingInfo->dSizeVInput);667 tilingData_.baseParams.set_dSizeVInput(tilingInfo->dSizeVInput);
668+ tilingData_.baseParams.set_returnSoftmaxLse(tilingInfo->returnSoftmaxLse);
677 669 
678 tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity());670 tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity());
679 context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize());671 context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize());
@@ -685,9 +677,8 @@ ge::graphStatus QuantSparseFlashMlaTiling::DoOpTiling(QSMLATilingInfo *tilingInf
685 uint32_t outputType = static_cast<uint32_t>(tilingInfo->outputType);677 uint32_t outputType = static_cast<uint32_t>(tilingInfo->outputType);
686 uint32_t qLayout = static_cast<uint32_t>(tilingInfo->qLayout);678 uint32_t qLayout = static_cast<uint32_t>(tilingInfo->qLayout);
687 uint32_t inputKvLayout = static_cast<uint32_t>(tilingInfo->kvLayout);679 uint32_t inputKvLayout = static_cast<uint32_t>(tilingInfo->kvLayout);
688- uint32_t tilingKey =680+ uint32_t tilingKey = GET_TPL_TILING_KEY(0U, qLayout, inputKvLayout, static_cast<uint32_t>(perfMode_),
689- GET_TPL_TILING_KEY(0U, qLayout, inputKvLayout, static_cast<uint32_t>(perfMode_),681+ static_cast<uint32_t>(tilingInfo->gSize > 64), DTYPE_HIF8, vectorizeFlag);
690- static_cast<uint32_t>(tilingInfo->gSize > 64), DTYPE_HIF8, vectorizeFlag);
691 context_->SetTilingKey(tilingKey);682 context_->SetTilingKey(tilingKey);
692 context_->SetScheduleMode(1);683 context_->SetScheduleMode(1);
693 684 
@@ -698,7 +689,7 @@ ge::graphStatus QuantSparseFlashMlaTiling::DoOpTiling(QSMLATilingInfo *tilingInf
698ge::graphStatus TilingQuantSparseFlashMla(gert::TilingContext *context)689ge::graphStatus TilingQuantSparseFlashMla(gert::TilingContext *context)
699{690{
700 OP_CHECK_IF(context == nullptr, OPS_REPORT_VECTOR_INNER_ERR("QuantSparseFlashMla", "Tiling context is null."),691 OP_CHECK_IF(context == nullptr, OPS_REPORT_VECTOR_INNER_ERR("QuantSparseFlashMla", "Tiling context is null."),
701- return ge::GRAPH_FAILED);692+ return ge::GRAPH_FAILED);
702 QSMLATilingInfo qsmlaInfo;693 QSMLATilingInfo qsmlaInfo;
703 QSMLAInfoParser qsmlaInfoParser(context);694 QSMLAInfoParser qsmlaInfoParser(context);
704 if (qsmlaInfoParser.Parse(qsmlaInfo) != ge::GRAPH_SUCCESS) {695 if (qsmlaInfoParser.Parse(qsmlaInfo) != ge::GRAPH_SUCCESS) {
@@ -54,6 +54,7 @@ TILING_DATA_FIELD_DEF(int32_t, oriWinRight)
54TILING_DATA_FIELD_DEF(uint32_t, sparseBlockSize)54TILING_DATA_FIELD_DEF(uint32_t, sparseBlockSize)
55TILING_DATA_FIELD_DEF(uint32_t, dSize)55TILING_DATA_FIELD_DEF(uint32_t, dSize)
56TILING_DATA_FIELD_DEF(uint32_t, dSizeVInput)56TILING_DATA_FIELD_DEF(uint32_t, dSizeVInput)
57+TILING_DATA_FIELD_DEF(uint32_t, returnSoftmaxLse)
57END_TILING_DATA_DEF58END_TILING_DATA_DEF
58REGISTER_TILING_DATA_CLASS(QuantSparseFlashMlaBaseParamsOp, QuantSparseFlashMlaBaseParams)59REGISTER_TILING_DATA_CLASS(QuantSparseFlashMlaBaseParamsOp, QuantSparseFlashMlaBaseParams)
59 60 
@@ -80,5 +81,5 @@ private:
80 QSMLATilingInfo *qsmlaInfo_ = nullptr;81 QSMLATilingInfo *qsmlaInfo_ = nullptr;
81};82};
82 83 
83-}84+} // namespace optiling
84-#endif85+#endif
@@ -62,32 +62,36 @@ template <typename CubeBlockType, typename VecBlockType>
62class QuantSparseFlashMlaCsa {62class QuantSparseFlashMlaCsa {
63public:63public:
64 ARGS_TRAITS;64 ARGS_TRAITS;
65- __aicore__ inline QuantSparseFlashMlaCsa() {};65+ __aicore__ inline QuantSparseFlashMlaCsa(){};
66 66 
67- __aicore__ inline void Init(__gm__ uint8_t *query, __gm__ uint8_t *oriKV, __gm__ uint8_t *cmpKV,67+ __aicore__ inline void
68- __gm__ uint8_t *qDescale, __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale,68+ Init(__gm__ uint8_t *query, __gm__ uint8_t *oriKV, __gm__ uint8_t *cmpKV, __gm__ uint8_t *qDescale,
69- __gm__ uint8_t *oriSparseIndices, __gm__ uint8_t *cmpSparseIndices, __gm__ uint8_t *oriBlockTable,69+ __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale, __gm__ uint8_t *oriSparseIndices,
70- __gm__ uint8_t *cmpBlockTable, __gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *cuSeqlensOriKv,70+ __gm__ uint8_t *cmpSparseIndices, __gm__ uint8_t *oriBlockTable, __gm__ uint8_t *cmpBlockTable,
71- __gm__ uint8_t *cuSeqlensCmpKv, __gm__ uint8_t *sequsedQ, __gm__ uint8_t *seqUsedOriKV,71+ __gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *cuSeqlensCmpKv,
72- __gm__ uint8_t *seqUsedCmpKV, __gm__ uint8_t *cmpResidualKv, __gm__ uint8_t *oriTopkLength,72+ __gm__ uint8_t *sequsedQ, __gm__ uint8_t *seqUsedOriKV, __gm__ uint8_t *seqUsedCmpKV,
73- __gm__ uint8_t *cmpTopkLength, __gm__ uint8_t *sinks, __gm__ uint8_t *metadata,73+ __gm__ uint8_t *cmpResidualKv, __gm__ uint8_t *oriTopkLength, __gm__ uint8_t *cmpTopkLength,
74- __gm__ uint8_t *attentionOut, __gm__ uint8_t *workspace,74+ __gm__ uint8_t *sinks, __gm__ uint8_t *metadata, __gm__ uint8_t *attentionOut, __gm__ uint8_t *softmaxLse,
75- const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe);75+ __gm__ uint8_t *workspace, const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe);
76 __aicore__ inline void Process();76 __aicore__ inline void Process();
77+ 
77private:78private:
78 __aicore__ inline void ProcessMainLoop();79 __aicore__ inline void ProcessMainLoop();
79 __aicore__ inline int64_t GetSeqLen(int32_t bIdx, bool hasActualSeq, bool hasCuSeqlens,80 __aicore__ inline int64_t GetSeqLen(int32_t bIdx, bool hasActualSeq, bool hasCuSeqlens,
80- GlobalTensor<int32_t>& actualSeqGm, GlobalTensor<int32_t>& cuSeqlensGm, int64_t defaultSize);81+ GlobalTensor<int32_t> &actualSeqGm, GlobalTensor<int32_t> &cuSeqlensGm,
82+ int64_t defaultSize);
81 __aicore__ inline void ParseTilingData(__gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *sequsedQ,83 __aicore__ inline void ParseTilingData(__gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *sequsedQ,
82- __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *sequsedOriKv,84+ __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *sequsedOriKv,
83- __gm__ uint8_t *cuSeqlensCmpKv, __gm__ uint8_t *sequsedCmpKv, __gm__ uint8_t *cmpResidualKv);85+ __gm__ uint8_t *cuSeqlensCmpKv, __gm__ uint8_t *sequsedCmpKv,
84- __aicore__ inline void InitGlobalBuffer(__gm__ uint8_t *query, __gm__ uint8_t *oriKV, __gm__ uint8_t *cmpKV,86+ __gm__ uint8_t *cmpResidualKv);
85- __gm__ uint8_t *qDescale, __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale,87+ __aicore__ inline void
86- __gm__ uint8_t *cmpSparseIndices, __gm__ uint8_t *oriBlockTable, __gm__ uint8_t *cmpBlockTable,88+ InitGlobalBuffer(__gm__ uint8_t *query, __gm__ uint8_t *oriKV, __gm__ uint8_t *cmpKV, __gm__ uint8_t *qDescale,
87- __gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *cuSeqlensCmpKv,89+ __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale, __gm__ uint8_t *cmpSparseIndices,
88- __gm__ uint8_t *sequsedQ, __gm__ uint8_t *sequsedOriKv,90+ __gm__ uint8_t *oriBlockTable, __gm__ uint8_t *cmpBlockTable, __gm__ uint8_t *cuSeqlensQ,
89- __gm__ uint8_t *sequsedCmpKv, __gm__ uint8_t *cmpResidualKv, __gm__ uint8_t *sinks, __gm__ uint8_t *workspace,91+ __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *cuSeqlensCmpKv, __gm__ uint8_t *sequsedQ,
90- const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe);92+ __gm__ uint8_t *sequsedOriKv, __gm__ uint8_t *sequsedCmpKv, __gm__ uint8_t *cmpResidualKv,
93+ __gm__ uint8_t *sinks, __gm__ uint8_t *workspace,
94+ const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe);
91 __aicore__ inline void InitLocalBuffer();95 __aicore__ inline void InitLocalBuffer();
92 __aicore__ inline void InitMMResBuf(__gm__ uint8_t *workspace);96 __aicore__ inline void InitMMResBuf(__gm__ uint8_t *workspace);
93 __aicore__ inline void ComputeConstexpr();97 __aicore__ inline void ComputeConstexpr();
@@ -157,9 +161,9 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Init
157 __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale, __gm__ uint8_t *oriSparseIndices,161 __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale, __gm__ uint8_t *oriSparseIndices,
158 __gm__ uint8_t *cmpSparseIndices, __gm__ uint8_t *oriBlockTable, __gm__ uint8_t *cmpBlockTable,162 __gm__ uint8_t *cmpSparseIndices, __gm__ uint8_t *oriBlockTable, __gm__ uint8_t *cmpBlockTable,
159 __gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *cuSeqlensCmpKv,163 __gm__ uint8_t *cuSeqlensQ, __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *cuSeqlensCmpKv,
160- __gm__ uint8_t *sequsedQ, __gm__ uint8_t *seqUsedOriKV, __gm__ uint8_t *seqUsedCmpKV,164+ __gm__ uint8_t *sequsedQ, __gm__ uint8_t *seqUsedOriKV, __gm__ uint8_t *seqUsedCmpKV, __gm__ uint8_t *cmpResidualKv,
161- __gm__ uint8_t *cmpResidualKv, __gm__ uint8_t *oriTopkLength, __gm__ uint8_t *cmpTopkLength,165+ __gm__ uint8_t *oriTopkLength, __gm__ uint8_t *cmpTopkLength, __gm__ uint8_t *sinks, __gm__ uint8_t *metadata,
162- __gm__ uint8_t *sinks, __gm__ uint8_t *metadata, __gm__ uint8_t *attentionOut, __gm__ uint8_t *workspace,166+ __gm__ uint8_t *attentionOut, __gm__ uint8_t *softmaxLse, __gm__ uint8_t *workspace,
163 const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe)167 const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe)
164{168{
165 __gm__ uint8_t *sequsedOriKv = seqUsedOriKV;169 __gm__ uint8_t *sequsedOriKv = seqUsedOriKV;
@@ -198,12 +202,12 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Init
198 202 
199 this->pipe = tPipe;203 this->pipe = tPipe;
200 this->ParseTilingData(cuSeqlensQ, sequsedQ, cuSeqlensOriKv, sequsedOriKv, cuSeqlensCmpKv, sequsedCmpKv,204 this->ParseTilingData(cuSeqlensQ, sequsedQ, cuSeqlensOriKv, sequsedOriKv, cuSeqlensCmpKv, sequsedCmpKv,
201- cmpResidualKv);205+ cmpResidualKv);
202 this->InitGlobalBuffer(query, oriKV, cmpKV, qDescale, oriKVDescale, cmpKVDescale, cmpSparseIndices, oriBlockTable,206 this->InitGlobalBuffer(query, oriKV, cmpKV, qDescale, oriKVDescale, cmpKVDescale, cmpSparseIndices, oriBlockTable,
203- cmpBlockTable, cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, sequsedQ, sequsedOriKv, sequsedCmpKv, cmpResidualKv,207+ cmpBlockTable, cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, sequsedQ, sequsedOriKv,
204- sinks, workspace, tiling, tPipe); // gm设置208+ sequsedCmpKv, cmpResidualKv, sinks, workspace, tiling, tPipe); // gm设置
205 vecBlock.InitVecBlock(tPipe, cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, sequsedOriKv, sequsedCmpKv, cmpResidualKv);209 vecBlock.InitVecBlock(tPipe, cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, sequsedOriKv, sequsedCmpKv, cmpResidualKv);
206- vecBlock.CleanOutput(attentionOut, constInfo);210+ vecBlock.CleanOutput(attentionOut, softmaxLse, constInfo);
207 if ASCEND_IS_AIV {211 if ASCEND_IS_AIV {
208 if constexpr (TEMPLATE_MODE == QSMLATemplateMode::CSA_TEMPLATE_MODE && IS_VEC_S2PHYADDR) {212 if constexpr (TEMPLATE_MODE == QSMLATemplateMode::CSA_TEMPLATE_MODE && IS_VEC_S2PHYADDR) {
209 this->vecBlock.GetKVPhyAddr(hasLoad, bN2StartIdx, bN2EndIdx, gS1StartIdx, nextGs1Idx, hasActualSeqQlen,213 this->vecBlock.GetKVPhyAddr(hasLoad, bN2StartIdx, bN2EndIdx, gS1StartIdx, nextGs1Idx, hasActualSeqQlen,
@@ -220,9 +224,10 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Init
220}224}
221 225 
222template <typename CubeBlockType, typename VecBlockType>226template <typename CubeBlockType, typename VecBlockType>
223-__aicore__ inline int64_t QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::GetSeqLen(227+__aicore__ inline int64_t
224- int32_t bIdx, bool hasActualSeq, bool hasCuSeqlens,228+QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::GetSeqLen(int32_t bIdx, bool hasActualSeq, bool hasCuSeqlens,
225- GlobalTensor<int32_t>& actualSeqGm, GlobalTensor<int32_t>& cuSeqlensGm, int64_t defaultSize)229+ GlobalTensor<int32_t> &actualSeqGm,
230+ GlobalTensor<int32_t> &cuSeqlensGm, int64_t defaultSize)
226{231{
227 if (hasActualSeq) {232 if (hasActualSeq) {
228 return actualSeqGm.GetValue(bIdx);233 return actualSeqGm.GetValue(bIdx);
@@ -247,8 +252,8 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Pars
247 constInfo.cmpS2Size = quantSparseFlashMlaBaseParams.cmpKvSeqSize;252 constInfo.cmpS2Size = quantSparseFlashMlaBaseParams.cmpKvSeqSize;
248 constInfo.sparseBlockCount = quantSparseFlashMlaBaseParams.sparseBlockCount;253 constInfo.sparseBlockCount = quantSparseFlashMlaBaseParams.sparseBlockCount;
249 constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128;254 constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128;
250- constInfo.alignedSparseBlockCount = (constInfo.sparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) /255+ constInfo.alignedSparseBlockCount =
251- SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM;256+ (constInfo.sparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM;
252 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {257 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {
253 constInfo.cmpRatio = quantSparseFlashMlaBaseParams.cmpRatio;258 constInfo.cmpRatio = quantSparseFlashMlaBaseParams.cmpRatio;
254 }259 }
@@ -262,6 +267,7 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Pars
262 constInfo.dSize = quantSparseFlashMlaBaseParams.dSize;267 constInfo.dSize = quantSparseFlashMlaBaseParams.dSize;
263 constInfo.dSizeV = constInfo.dSize;268 constInfo.dSizeV = constInfo.dSize;
264 constInfo.dSizeVInput = quantSparseFlashMlaBaseParams.dSizeVInput;269 constInfo.dSizeVInput = quantSparseFlashMlaBaseParams.dSizeVInput;
270+ constInfo.isSoftmaxLseEnable = quantSparseFlashMlaBaseParams.returnSoftmaxLse;
265 constInfo.sparseBlockSize = 1;271 constInfo.sparseBlockSize = 1;
266 constInfo.actualSeqLenSize = constInfo.bSize + 1;272 constInfo.actualSeqLenSize = constInfo.bSize + 1;
267 273 
@@ -308,14 +314,13 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Pars
308 314 
309 constInfo.needInit = 0;315 constInfo.needInit = 0;
310 for (uint32_t bIdx = 0; bIdx < constInfo.bSize; bIdx++) {316 for (uint32_t bIdx = 0; bIdx < constInfo.bSize; bIdx++) {
311- int64_t s2Size = GetSeqLen(bIdx, hasActualSeqOriKvlen, hasCuSeqlensOriKv,317+ int64_t s2Size = GetSeqLen(bIdx, hasActualSeqOriKvlen, hasCuSeqlensOriKv, actualSeqOriKvlenGm, cuSeqlensOriKvGm,
312- actualSeqOriKvlenGm, cuSeqlensOriKvGm, constInfo.s2Size);318+ constInfo.s2Size);
313- int64_t s1Size = GetSeqLen(bIdx, hasActualSeqQlen, hasCuSeqlensQ,319+ int64_t s1Size =
314- actualSeqQlenGm, cuSeqlensQGm, constInfo.s1Size);320+ GetSeqLen(bIdx, hasActualSeqQlen, hasCuSeqlensQ, actualSeqQlenGm, cuSeqlensQGm, constInfo.s1Size);
315 int64_t expectQs;321 int64_t expectQs;
316 if constexpr (LAYOUT_T == QSMLA_LAYOUT::TND) {322 if constexpr (LAYOUT_T == QSMLA_LAYOUT::TND) {
317- expectQs = GetSeqLen(bIdx, false, hasCuSeqlensQ,323+ expectQs = GetSeqLen(bIdx, false, hasCuSeqlensQ, actualSeqQlenGm, cuSeqlensQGm, constInfo.s1Size);
318- actualSeqQlenGm, cuSeqlensQGm, constInfo.s1Size);
319 } else {324 } else {
320 expectQs = constInfo.s1Size;325 expectQs = constInfo.s1Size;
321 }326 }
@@ -329,21 +334,19 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Pars
329template <typename CubeBlockType, typename VecBlockType>334template <typename CubeBlockType, typename VecBlockType>
330__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::InitGlobalBuffer(335__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::InitGlobalBuffer(
331 __gm__ uint8_t *query, __gm__ uint8_t *oriKV, __gm__ uint8_t *cmpKV, __gm__ uint8_t *qDescale,336 __gm__ uint8_t *query, __gm__ uint8_t *oriKV, __gm__ uint8_t *cmpKV, __gm__ uint8_t *qDescale,
332- __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale, __gm__ uint8_t *cmpSparseIndices,337+ __gm__ uint8_t *oriKVDescale, __gm__ uint8_t *cmpKVDescale, __gm__ uint8_t *cmpSparseIndices,
333 __gm__ uint8_t *oriBlockTable, __gm__ uint8_t *cmpBlockTable, __gm__ uint8_t *cuSeqlensQ,338 __gm__ uint8_t *oriBlockTable, __gm__ uint8_t *cmpBlockTable, __gm__ uint8_t *cuSeqlensQ,
334 __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *cuSeqlensCmpKv, __gm__ uint8_t *sequsedQ,339 __gm__ uint8_t *cuSeqlensOriKv, __gm__ uint8_t *cuSeqlensCmpKv, __gm__ uint8_t *sequsedQ,
335- __gm__ uint8_t *sequsedOriKv, __gm__ uint8_t *sequsedCmpKv, __gm__ uint8_t *cmpResidualKv,340+ __gm__ uint8_t *sequsedOriKv, __gm__ uint8_t *sequsedCmpKv, __gm__ uint8_t *cmpResidualKv, __gm__ uint8_t *sinks,
336- __gm__ uint8_t *sinks, __gm__ uint8_t *workspace,341+ __gm__ uint8_t *workspace, const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe)
337- const QuantSparseFlashMlaTilingData *__restrict tiling, TPipe *tPipe)
338{342{
339 vecBlock.InitGlobalBuffer(oriKV, cmpKV, qDescale, oriKVDescale, cmpKVDescale, cmpSparseIndices, oriBlockTable,343 vecBlock.InitGlobalBuffer(oriKV, cmpKV, qDescale, oriKVDescale, cmpKVDescale, cmpSparseIndices, oriBlockTable,
340- cmpBlockTable, sequsedQ, sinks, sequsedOriKv, sequsedCmpKv, cmpResidualKv);344+ cmpBlockTable, sequsedQ, sinks, sequsedOriKv, sequsedCmpKv, cmpResidualKv);
341 cubeBlock.InitCubeInput(cuSeqlensQ, sequsedQ, constInfo);345 cubeBlock.InitCubeInput(cuSeqlensQ, sequsedQ, constInfo);
342}346}
343 347 
344template <typename CubeBlockType, typename VecBlockType>348template <typename CubeBlockType, typename VecBlockType>
345-__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::InitMMResBuf(349+__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::InitMMResBuf(__gm__ uint8_t *workspace)
346- __gm__ uint8_t *workspace)
347{350{
348 uint32_t mm1ResultSize = constInfo.s1BaseSize / CV_RATIO * constInfo.s2BaseSize * sizeof(T);351 uint32_t mm1ResultSize = constInfo.s1BaseSize / CV_RATIO * constInfo.s2BaseSize * sizeof(T);
349 uint32_t mm2ResultSize = constInfo.s1BaseSize / CV_RATIO * 512 * sizeof(T);352 uint32_t mm2ResultSize = constInfo.s1BaseSize / CV_RATIO * 512 * sizeof(T);
@@ -483,11 +486,11 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Proc
483 bool lastBN = (bnIdx == bN2EndIdx - 1);486 bool lastBN = (bnIdx == bN2EndIdx - 1);
484 runParam.boIdx = bnIdx;487 runParam.boIdx = bnIdx;
485 runParam.n2oIdx = 0;488 runParam.n2oIdx = 0;
486- ComputeParamBatch<TEMPLATE_INTF_ARGS>(runParam, this->constInfo,489+ ComputeParamBatch<TEMPLATE_INTF_ARGS>(runParam, this->constInfo, this->cuSeqlensQGm, this->cuSeqlensOriKvGm,
487- this->cuSeqlensQGm, this->cuSeqlensOriKvGm, this->cuSeqlensCmpKvGm, this->actualSeqQlenGm,490+ this->cuSeqlensCmpKvGm, this->actualSeqQlenGm, this->actualSeqOriKvlenGm,
488- this->actualSeqOriKvlenGm, this->actualSeqCmpKvlenGm, this->cmpResidualKvGm,491+ this->actualSeqCmpKvlenGm, this->cmpResidualKvGm, this->hasCuSeqlensOriKv,
489- this->hasCuSeqlensOriKv, this->hasCuSeqlensCmpKv,492+ this->hasCuSeqlensCmpKv, this->hasActualSeqQlen,
490- this->hasActualSeqQlen, this->hasActualSeqOriKvlen, this->hasActualSeqCmpKvlen);493+ this->hasActualSeqOriKvlen, this->hasActualSeqCmpKvlen);
491 ComputeS1LoopInfo<TEMPLATE_INTF_ARGS>(runParam, this->constInfo, lastBN, nextGs1Idx, gS1StartIdx);494 ComputeS1LoopInfo<TEMPLATE_INTF_ARGS>(runParam, this->constInfo, lastBN, nextGs1Idx, gS1StartIdx);
492 495 
493 int64_t gS1LoopEnd = lastBN ? (runParam.gs1LoopEndIdx + PRELOAD_NUM) : runParam.gs1LoopEndIdx;496 int64_t gS1LoopEnd = lastBN ? (runParam.gs1LoopEndIdx + PRELOAD_NUM) : runParam.gs1LoopEndIdx;
@@ -514,10 +517,9 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Proc
514 }517 }
515 if (notLastThreeLoop) {518 if (notLastThreeLoop) {
516 this->ComputeAxisIdxByBnAndGs1(bnIdx, gS1Index, runParam);519 this->ComputeAxisIdxByBnAndGs1(bnIdx, gS1Index, runParam);
517- bool s1NoNeedCalc = ComputeParamS1<TEMPLATE_INTF_ARGS>(520+ bool s1NoNeedCalc =
518- runParam, this->constInfo, gS1Index, this->cuSeqlensQGm);521+ ComputeParamS1<TEMPLATE_INTF_ARGS>(runParam, this->constInfo, gS1Index, this->cuSeqlensQGm);
519- bool s2NoNeedCalc =522+ bool s2NoNeedCalc = ComputeS2LoopInfo<TEMPLATE_INTF_ARGS>(runParam, this->constInfo);
520- ComputeS2LoopInfo<TEMPLATE_INTF_ARGS>(runParam, this->constInfo);
521 // s1和s2有任意一个不需要算, 则continue, 如果是当前核最后一次循环,则补充计算taskIdx+2的部分523 // s1和s2有任意一个不需要算, 则continue, 如果是当前核最后一次循环,则补充计算taskIdx+2的部分
522 if (s1NoNeedCalc || s2NoNeedCalc) {524 if (s1NoNeedCalc || s2NoNeedCalc) {
523 continue;525 continue;
@@ -537,13 +539,13 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Proc
537 if ASCEND_IS_AIV {539 if ASCEND_IS_AIV {
538 if (notLastThreeLoop) {540 if (notLastThreeLoop) {
539 RunInfo &runInfo1 = runInfo[taskId % 4];541 RunInfo &runInfo1 = runInfo[taskId % 4];
540- this->vecBlock.ProcessVec0(this->l1RightBuffers.Get(runInfo1.taskIdMod3), \542+ this->vecBlock.ProcessVec0(this->l1RightBuffers.Get(runInfo1.taskIdMod3),
541- v0ResGmBuffers.Get(runInfo1.taskIdMod3), runInfo1, this->constInfo);543+ v0ResGmBuffers.Get(runInfo1.taskIdMod3), runInfo1, this->constInfo);
542 }544 }
543 if (taskId > 1 && notLast) {545 if (taskId > 1 && notLast) {
544 auto &runInfo2 = runInfo[(taskId + 2) % 4];546 auto &runInfo2 = runInfo[(taskId + 2) % 4];
545 this->vecBlock.ProcessVec1(this->l1PBuffers.Get(), this->bmm1Buffers.Get(), runInfo2,547 this->vecBlock.ProcessVec1(this->l1PBuffers.Get(), this->bmm1Buffers.Get(), runInfo2,
546- this->constInfo);548+ this->constInfo);
547 }549 }
548 if (taskId > 2) {550 if (taskId > 2) {
549 RunInfo &runInfo3 = runInfo[(taskId + 1) % 4];551 RunInfo &runInfo3 = runInfo[(taskId + 1) % 4];
@@ -553,7 +555,8 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Proc
553 if (taskId > 0 && notLastTwoLoop) {555 if (taskId > 0 && notLastTwoLoop) {
554 RunInfo &runInfo1 = runInfo[(taskId + 3) % 4];556 RunInfo &runInfo1 = runInfo[(taskId + 3) % 4];
555 this->cubeBlock.IterateLoadQK(this->l1RightBuffers.Get(runInfo1.taskIdMod3),557 this->cubeBlock.IterateLoadQK(this->l1RightBuffers.Get(runInfo1.taskIdMod3),
556- v0ResGmBuffers.Get(runInfo1.taskIdMod3), runInfo1, this->constInfo, isFirstLoop);558+ v0ResGmBuffers.Get(runInfo1.taskIdMod3), runInfo1,
559+ this->constInfo, isFirstLoop);
557 isFirstLoop = false;560 isFirstLoop = false;
558 } else {561 } else {
559 if constexpr (IS_SPLIT_G) {562 if constexpr (IS_SPLIT_G) {
@@ -567,15 +570,16 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Proc
567 if (taskId > 1 && notLast) {570 if (taskId > 1 && notLast) {
568 auto &runInfo2 = runInfo[(taskId + 2) % 4];571 auto &runInfo2 = runInfo[(taskId + 2) % 4];
569 RunInfo &runInfoNext = runInfo[(taskId + 3) % 4];572 RunInfo &runInfoNext = runInfo[(taskId + 3) % 4];
570- this->cubeBlock.IterateBmm1(573+ this->cubeBlock.IterateBmm1(this->bmm1Buffers.Get(),
571- this->bmm1Buffers.Get(), this->l1RightBuffers.Get(runInfo2.taskIdMod3),574+ this->l1RightBuffers.Get(runInfo2.taskIdMod3),
572- v0ResGmBuffers.Get(runInfo2.taskIdMod3),575+ v0ResGmBuffers.Get(runInfo2.taskIdMod3), notLastTwoLoop,
573- notLastTwoLoop, runInfoNext, runInfo2, this->constInfo);576+ runInfoNext, runInfo2, this->constInfo);
574 }577 }
575 if (taskId > 2) {578 if (taskId > 2) {
576 RunInfo &runInfo3 = runInfo[(taskId + 1) % 4];579 RunInfo &runInfo3 = runInfo[(taskId + 1) % 4];
577 this->cubeBlock.IterateBmm2(this->bmm2Buffers.Get(), this->l1PBuffers,580 this->cubeBlock.IterateBmm2(this->bmm2Buffers.Get(), this->l1PBuffers,
578- this->l1RightBuffers.Get(runInfo3.taskIdMod3), runInfo3, this->constInfo);581+ this->l1RightBuffers.Get(runInfo3.taskIdMod3), runInfo3,
582+ this->constInfo);
579 }583 }
580 }584 }
581 ++taskId;585 ++taskId;
@@ -595,22 +599,27 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Proc
595}599}
596 600 
597template <typename CubeBlockType, typename VecBlockType>601template <typename CubeBlockType, typename VecBlockType>
598-__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::ComputeAxisIdxByBnAndGs1(602+__aicore__ inline void
599- int64_t bnIndex, int64_t gS1Index, RunParamStr &runParam)603+QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::ComputeAxisIdxByBnAndGs1(int64_t bnIndex, int64_t gS1Index,
604+ RunParamStr &runParam)
600{605{
601 // GS1合轴, 不切G, 只切S1606 // GS1合轴, 不切G, 只切S1
602 runParam.s1oIdx = gS1Index * runParam.qSNumInOneBlock;607 runParam.s1oIdx = gS1Index * runParam.qSNumInOneBlock;
603 if constexpr (IS_SPLIT_G) {608 if constexpr (IS_SPLIT_G) {
604- runParam.goIdx = (aicIdx % 2 == 0) ? 0 : 64;609+ int64_t halfG = (constInfo.gSize + 1) / 2; // ceil(gSize/2), 第一个AIC多处理一行
610+ runParam.goIdx = (aicIdx % 2 == 0) ? 0 : halfG;
611+ runParam.gSplitSize = (aicIdx % 2 == 0) ? halfG : (constInfo.gSize - halfG);
605 } else {612 } else {
606 runParam.goIdx = 0;613 runParam.goIdx = 0;
614+ runParam.gSplitSize = constInfo.gSize;
607 }615 }
608}616}
609 617 
610template <typename CubeBlockType, typename VecBlockType>618template <typename CubeBlockType, typename VecBlockType>
611-__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::SetRunInfo(619+__aicore__ inline void
612- RunInfo &runInfo, RunParamStr &runParam, int64_t taskId, int64_t s2LoopCount,620+QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::SetRunInfo(RunInfo &runInfo, RunParamStr &runParam, int64_t taskId,
613- int64_t s2LoopLimit, int64_t multiCoreInnerIdx)621+ int64_t s2LoopCount, int64_t s2LoopLimit,
622+ int64_t multiCoreInnerIdx)
614{623{
615 if (s2LoopCount < runParam.oriKvLoopEndIdx) {624 if (s2LoopCount < runParam.oriKvLoopEndIdx) {
616 runInfo.s2StartIdx = runParam.s2LineStartIdx;625 runInfo.s2StartIdx = runParam.s2LineStartIdx;
@@ -645,15 +654,14 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::SetR
645 654 
646template <typename CubeBlockType, typename VecBlockType>655template <typename CubeBlockType, typename VecBlockType>
647__aicore__ inline void656__aicore__ inline void
648-QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::InitUniqueRunInfo(657+QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::InitUniqueRunInfo(const RunParamStr &runParam, RunInfo &runInfo)
649- const RunParamStr &runParam, RunInfo &runInfo)
650{658{
651 InitTaskParamByRun<TEMPLATE_INTF_ARGS>(runParam, runInfo);659 InitTaskParamByRun<TEMPLATE_INTF_ARGS>(runParam, runInfo);
652}660}
653 661 
654template <typename CubeBlockType, typename VecBlockType>662template <typename CubeBlockType, typename VecBlockType>
655-__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::ComputeBmm1Tail(663+__aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::ComputeBmm1Tail(RunInfo &runInfo,
656- RunInfo &runInfo, RunParamStr &runParam)664+ RunParamStr &runParam)
657{665{
658 // ------------------------S1 Base Related---------------------------666 // ------------------------S1 Base Related---------------------------
659 runInfo.s1RealSize = runParam.s1RealSize;667 runInfo.s1RealSize = runParam.s1RealSize;
@@ -663,14 +671,15 @@ __aicore__ inline void QuantSparseFlashMlaCsa<CubeBlockType, VecBlockType>::Comp
663 runInfo.halfMRealSize = runParam.halfMRealSize;671 runInfo.halfMRealSize = runParam.halfMRealSize;
664 runInfo.firstHalfMRealSize = runParam.firstHalfMRealSize;672 runInfo.firstHalfMRealSize = runParam.firstHalfMRealSize;
665 673 
666- runInfo.vec2S1BaseSize = runInfo.halfS1RealSize; // D>128 这里需要适配674+ runInfo.vec2S1BaseSize = runInfo.halfS1RealSize; // D>128 这里需要适配
667 runInfo.vec2MBaseSize = runInfo.halfMRealSize;675 runInfo.vec2MBaseSize = runInfo.halfMRealSize;
668 676 
669 // ------------------------S2 Base Related----------------------------677 // ------------------------S2 Base Related----------------------------
670 runInfo.s2RealSize = constInfo.s2BaseSize;678 runInfo.s2RealSize = constInfo.s2BaseSize;
671 runInfo.s2AlignedSize = runInfo.s2RealSize;679 runInfo.s2AlignedSize = runInfo.s2RealSize;
672 int64_t curS2LoopCnt = (runInfo.s2LoopCount >= runParam.oriKvLoopEndIdx) ?680 int64_t curS2LoopCnt = (runInfo.s2LoopCount >= runParam.oriKvLoopEndIdx) ?
673- (runInfo.s2LoopCount - runParam.oriKvLoopEndIdx) : runInfo.s2LoopCount;681+ (runInfo.s2LoopCount - runParam.oriKvLoopEndIdx) :
682+ runInfo.s2LoopCount;
674 if (runInfo.s2StartIdx + (curS2LoopCnt + 1) * runInfo.s2RealSize > runInfo.s2EndIdx) {683 if (runInfo.s2StartIdx + (curS2LoopCnt + 1) * runInfo.s2RealSize > runInfo.s2EndIdx) {
675 runInfo.s2RealSize = runInfo.s2EndIdx - curS2LoopCnt * runInfo.s2RealSize - runInfo.s2StartIdx;684 runInfo.s2RealSize = runInfo.s2EndIdx - curS2LoopCnt * runInfo.s2RealSize - runInfo.s2StartIdx;
676 runInfo.s2AlignedSize = Align(runInfo.s2RealSize);685 runInfo.s2AlignedSize = Align(runInfo.s2RealSize);
@@ -31,12 +31,13 @@ using namespace AscendC;
31using namespace AscendC::Impl::Detail;31using namespace AscendC::Impl::Detail;
32 32 
33TEMPLATE_INTF33TEMPLATE_INTF
34-__aicore__ inline void GetSingleCoreParam(RunParamStr& runParam, const ConstInfo &constInfo,34+__aicore__ inline void
35- GlobalTensor<int32_t>& cuSeqlensQGm, GlobalTensor<int32_t>& cuSeqlensOriKvGm,35+GetSingleCoreParam(RunParamStr &runParam, const ConstInfo &constInfo, GlobalTensor<int32_t> &cuSeqlensQGm,
36- GlobalTensor<int32_t>& cuSeqlensCmpKvGm, GlobalTensor<int32_t>& actualSeqQlenGm,36+ GlobalTensor<int32_t> &cuSeqlensOriKvGm, GlobalTensor<int32_t> &cuSeqlensCmpKvGm,
37- GlobalTensor<int32_t>& actualSeqOriKvlenGm, GlobalTensor<int32_t>& actualSeqCmpKvlenGm,37+ GlobalTensor<int32_t> &actualSeqQlenGm, GlobalTensor<int32_t> &actualSeqOriKvlenGm,
38- GlobalTensor<int32_t>& cmpResidualKvGm, bool hasCuSeqlensOriKv,38+ GlobalTensor<int32_t> &actualSeqCmpKvlenGm, GlobalTensor<int32_t> &cmpResidualKvGm,
39- bool hasCuSeqlensCmpKv, bool hasActualSeqQlen, bool hasActualSeqOriKvlen, bool hasActualSeqCmpKvlen)39+ bool hasCuSeqlensOriKv, bool hasCuSeqlensCmpKv, bool hasActualSeqQlen, bool hasActualSeqOriKvlen,
40+ bool hasActualSeqCmpKvlen)
40{41{
41 int32_t actualS1Size = 0;42 int32_t actualS1Size = 0;
42 int32_t actualS2OriSize = 0;43 int32_t actualS2OriSize = 0;
@@ -44,10 +45,9 @@ __aicore__ inline void GetSingleCoreParam(RunParamStr& runParam, const ConstInfo
44 int32_t bIdx = runParam.boIdx;45 int32_t bIdx = runParam.boIdx;
45 if constexpr (LAYOUT_T == QSMLA_LAYOUT::TND) {46 if constexpr (LAYOUT_T == QSMLA_LAYOUT::TND) {
46 actualS1Size = (!hasActualSeqQlen) ? (cuSeqlensQGm.GetValue(bIdx + 1) - cuSeqlensQGm.GetValue(bIdx)) :47 actualS1Size = (!hasActualSeqQlen) ? (cuSeqlensQGm.GetValue(bIdx + 1) - cuSeqlensQGm.GetValue(bIdx)) :
47- actualSeqQlenGm.GetValue(bIdx);48+ actualSeqQlenGm.GetValue(bIdx);
48 } else {49 } else {
49- actualS1Size = (!hasActualSeqQlen) ? constInfo.s1Size :50+ actualS1Size = (!hasActualSeqQlen) ? constInfo.s1Size : actualSeqQlenGm.GetValue(bIdx);
50- actualSeqQlenGm.GetValue(bIdx);
51 }51 }
52 52 
53 if constexpr (KV_LAYOUT_T == QSMLA_LAYOUT::TND) {53 if constexpr (KV_LAYOUT_T == QSMLA_LAYOUT::TND) {
@@ -57,8 +57,7 @@ __aicore__ inline void GetSingleCoreParam(RunParamStr& runParam, const ConstInfo
57 actualS2OriSize = cuSeqlensOriKvGm.GetValue(bIdx + 1) - cuSeqlensOriKvGm.GetValue(bIdx);57 actualS2OriSize = cuSeqlensOriKvGm.GetValue(bIdx + 1) - cuSeqlensOriKvGm.GetValue(bIdx);
58 }58 }
59 } else {59 } else {
60- actualS2OriSize = (!hasActualSeqOriKvlen) ? constInfo.s2Size :60+ actualS2OriSize = (!hasActualSeqOriKvlen) ? constInfo.s2Size : actualSeqOriKvlenGm.GetValue(bIdx);
61- actualSeqOriKvlenGm.GetValue(bIdx);
62 }61 }
63 62 
64 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {63 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {
@@ -71,8 +70,8 @@ __aicore__ inline void GetSingleCoreParam(RunParamStr& runParam, const ConstInfo
71 actualS2CmpSize = actualS2OriSize / constInfo.cmpRatio;70 actualS2CmpSize = actualS2OriSize / constInfo.cmpRatio;
72 }71 }
73 } else {72 } else {
74- actualS2CmpSize = (!hasActualSeqCmpKvlen) ? (actualS2OriSize / constInfo.cmpRatio) :73+ actualS2CmpSize =
75- actualSeqCmpKvlenGm.GetValue(bIdx);74+ (!hasActualSeqCmpKvlen) ? (actualS2OriSize / constInfo.cmpRatio) : actualSeqCmpKvlenGm.GetValue(bIdx);
76 }75 }
77 }76 }
78 77 
@@ -81,8 +80,8 @@ __aicore__ inline void GetSingleCoreParam(RunParamStr& runParam, const ConstInfo
81 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {80 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {
82 runParam.actualS2CmpSize = actualS2CmpSize;81 runParam.actualS2CmpSize = actualS2CmpSize;
83 runParam.cmpResidual = cmpResidualKvGm.GetValue(bIdx);82 runParam.cmpResidual = cmpResidualKvGm.GetValue(bIdx);
84- runParam.nextTokensPerBatchCmp = (int64_t)runParam.actualS2CmpSize * constInfo.cmpRatio +83+ runParam.nextTokensPerBatchCmp =
85- runParam.cmpResidual - runParam.actualS1Size;84+ (int64_t)runParam.actualS2CmpSize * constInfo.cmpRatio + runParam.cmpResidual - runParam.actualS1Size;
86 }85 }
87 runParam.nextTokensPerBatchOri = runParam.actualS2OriSize - runParam.actualS1Size;86 runParam.nextTokensPerBatchOri = runParam.actualS2OriSize - runParam.actualS1Size;
88 if (constInfo.oriWinLeft == -1) {87 if (constInfo.oriWinLeft == -1) {
@@ -94,29 +93,30 @@ __aicore__ inline void GetSingleCoreParam(RunParamStr& runParam, const ConstInfo
94}93}
95 94 
96TEMPLATE_INTF95TEMPLATE_INTF
97-__aicore__ inline void ComputeParamBatch(RunParamStr& runParam, const ConstInfo &constInfo,96+__aicore__ inline void
98- GlobalTensor<int32_t>& cuSeqlensQGm, GlobalTensor<int32_t>& cuSeqlensOriKvGm,97+ComputeParamBatch(RunParamStr &runParam, const ConstInfo &constInfo, GlobalTensor<int32_t> &cuSeqlensQGm,
99- GlobalTensor<int32_t>& cuSeqlensCmpKvGm, GlobalTensor<int32_t>& actualSeqQlenGm,98+ GlobalTensor<int32_t> &cuSeqlensOriKvGm, GlobalTensor<int32_t> &cuSeqlensCmpKvGm,
100- GlobalTensor<int32_t>& actualSeqOriKvlenGm, GlobalTensor<int32_t>& actualSeqCmpKvlenGm,99+ GlobalTensor<int32_t> &actualSeqQlenGm, GlobalTensor<int32_t> &actualSeqOriKvlenGm,
101- GlobalTensor<int32_t>& cmpResidualKvGm, bool hasCuSeqlensOriKv,100+ GlobalTensor<int32_t> &actualSeqCmpKvlenGm, GlobalTensor<int32_t> &cmpResidualKvGm,
102- bool hasCuSeqlensCmpKv, bool hasActualSeqQlen, bool hasActualSeqOriKvlen, bool hasActualSeqCmpKvlen)101+ bool hasCuSeqlensOriKv, bool hasCuSeqlensCmpKv, bool hasActualSeqQlen, bool hasActualSeqOriKvlen,
102+ bool hasActualSeqCmpKvlen)
103{103{
104- GetSingleCoreParam<TEMPLATE_INTF_ARGS>(runParam, constInfo, cuSeqlensQGm, cuSeqlensOriKvGm,104+ GetSingleCoreParam<TEMPLATE_INTF_ARGS>(runParam, constInfo, cuSeqlensQGm, cuSeqlensOriKvGm, cuSeqlensCmpKvGm,
105- cuSeqlensCmpKvGm, actualSeqQlenGm, actualSeqOriKvlenGm, actualSeqCmpKvlenGm,105+ actualSeqQlenGm, actualSeqOriKvlenGm, actualSeqCmpKvlenGm, cmpResidualKvGm,
106- cmpResidualKvGm, hasCuSeqlensOriKv, hasCuSeqlensCmpKv,106+ hasCuSeqlensOriKv, hasCuSeqlensCmpKv, hasActualSeqQlen, hasActualSeqOriKvlen,
107- hasActualSeqQlen, hasActualSeqOriKvlen, hasActualSeqCmpKvlen);107+ hasActualSeqCmpKvlen);
108}108}
109 109 
110TEMPLATE_INTF110TEMPLATE_INTF
111-__aicore__ inline void ComputeS1LoopInfo(RunParamStr& runParam, const ConstInfo &constInfo, bool lastBN,111+__aicore__ inline void ComputeS1LoopInfo(RunParamStr &runParam, const ConstInfo &constInfo, bool lastBN,
112- int64_t nextGs1Idx, int64_t gS1StartIdx)112+ int64_t nextGs1Idx, int64_t gS1StartIdx)
113{113{
114 // 计算每个基本块可以拷贝多少行s114 // 计算每个基本块可以拷贝多少行s
115 runParam.qSNumInOneBlock = 1;115 runParam.qSNumInOneBlock = 1;
116 runParam.gs1LoopStartIdx = gS1StartIdx;116 runParam.gs1LoopStartIdx = gS1StartIdx;
117 if (runParam.nextTokensPerBatchOri < 0) {117 if (runParam.nextTokensPerBatchOri < 0) {
118- int64_t gs1LoopStartIdx = runParam.nextTokensPerBatchOri * (-1) / runParam.qSNumInOneBlock *118+ int64_t gs1LoopStartIdx =
119- runParam.qSNumInOneBlock;119+ runParam.nextTokensPerBatchOri * (-1) / runParam.qSNumInOneBlock * runParam.qSNumInOneBlock;
120 if (gs1LoopStartIdx > gS1StartIdx) {120 if (gs1LoopStartIdx > gS1StartIdx) {
121 runParam.gs1LoopStartIdx = gs1LoopStartIdx;121 runParam.gs1LoopStartIdx = gs1LoopStartIdx;
122 }122 }
@@ -125,7 +125,7 @@ __aicore__ inline void ComputeS1LoopInfo(RunParamStr& runParam, const ConstInfo
125 int32_t gs1LoopEndIdx = 0;125 int32_t gs1LoopEndIdx = 0;
126 if constexpr (TEMPLATE_MODE == QSMLATemplateMode::CSA_TEMPLATE_MODE) {126 if constexpr (TEMPLATE_MODE == QSMLATemplateMode::CSA_TEMPLATE_MODE) {
127 gs1LoopEndIdx = runParam.actualS1Size; // 对于CSA, 不切G轴, 每次拷贝一行的topk,只算一行的qs127 gs1LoopEndIdx = runParam.actualS1Size; // 对于CSA, 不切G轴, 每次拷贝一行的topk,只算一行的qs
128- } else { // SWA/HCA128+ } else { // SWA/HCA
129 // 不需要取topk, 每次计算gSize行, 循环qs次129 // 不需要取topk, 每次计算gSize行, 循环qs次
130 gs1LoopEndIdx = (runParam.actualS1Size + runParam.qSNumInOneBlock - 1) / runParam.qSNumInOneBlock;130 gs1LoopEndIdx = (runParam.actualS1Size + runParam.qSNumInOneBlock - 1) / runParam.qSNumInOneBlock;
131 }131 }
@@ -142,8 +142,7 @@ __aicore__ inline void ComputeS1LoopInfo(RunParamStr& runParam, const ConstInfo
142}142}
143 143 
144TEMPLATE_INTF144TEMPLATE_INTF
145-__aicore__ inline void ComputeSouterParam(RunParamStr& runParam, const ConstInfo &constInfo,145+__aicore__ inline void ComputeSouterParam(RunParamStr &runParam, const ConstInfo &constInfo, uint32_t sOuterLoopIdx)
146- uint32_t sOuterLoopIdx)
147{146{
148 int64_t cubeSOuterOffset = sOuterLoopIdx * runParam.qSNumInOneBlock;147 int64_t cubeSOuterOffset = sOuterLoopIdx * runParam.qSNumInOneBlock;
149 if (runParam.actualS1Size == 0) {148 if (runParam.actualS1Size == 0) {
@@ -153,7 +152,7 @@ __aicore__ inline void ComputeSouterParam(RunParamStr& runParam, const ConstInfo
153 runParam.s1RealSize = Min(runParam.qSNumInOneBlock, runParam.actualS1Size - cubeSOuterOffset);152 runParam.s1RealSize = Min(runParam.qSNumInOneBlock, runParam.actualS1Size - cubeSOuterOffset);
154 runParam.mRealSize = runParam.s1RealSize * constInfo.gSize;153 runParam.mRealSize = runParam.s1RealSize * constInfo.gSize;
155 if constexpr (IS_SPLIT_G) {154 if constexpr (IS_SPLIT_G) {
156- runParam.mRealSize = runParam.mRealSize >> 1;155+ runParam.mRealSize = runParam.s1RealSize * runParam.gSplitSize;
157 }156 }
158 }157 }
159 158 
@@ -171,7 +170,7 @@ __aicore__ inline void ComputeSouterParam(RunParamStr& runParam, const ConstInfo
171 runParam.firstHalfS1RealSize = runParam.halfS1RealSize;170 runParam.firstHalfS1RealSize = runParam.halfS1RealSize;
172 if (constInfo.subBlockIdx == 1) {171 if (constInfo.subBlockIdx == 1) {
173 runParam.halfS1RealSize = runParam.s1RealSize - runParam.halfS1RealSize;172 runParam.halfS1RealSize = runParam.s1RealSize - runParam.halfS1RealSize;
174- runParam.sOuterOffset = cubeSOuterOffset + runParam.halfMRealSize / constInfo.gSize;173+ runParam.sOuterOffset = cubeSOuterOffset + runParam.firstHalfMRealSize / constInfo.gSize;
175 } else {174 } else {
176 runParam.sOuterOffset = cubeSOuterOffset;175 runParam.sOuterOffset = cubeSOuterOffset;
177 }176 }
@@ -179,8 +178,8 @@ __aicore__ inline void ComputeSouterParam(RunParamStr& runParam, const ConstInfo
179}178}
180 179 
181TEMPLATE_INTF180TEMPLATE_INTF
182-__aicore__ inline void LoopSOuterOffsetInit(RunParamStr& runParam, const ConstInfo &constInfo,181+__aicore__ inline void LoopSOuterOffsetInit(RunParamStr &runParam, const ConstInfo &constInfo, int32_t sIdx,
183- int32_t sIdx, GlobalTensor<int32_t>& cuSeqlensQGm)182+ GlobalTensor<int32_t> &cuSeqlensQGm)
184{183{
185 if ASCEND_IS_AIV {184 if ASCEND_IS_AIV {
186 int64_t seqOffset = 0;185 int64_t seqOffset = 0;
@@ -192,23 +191,43 @@ __aicore__ inline void LoopSOuterOffsetInit(RunParamStr& runParam, const ConstIn
192 191 
193 int64_t attentionOutSeqOffset = seqOffset * constInfo.n2GDv;192 int64_t attentionOutSeqOffset = seqOffset * constInfo.n2GDv;
194 if constexpr (LAYOUT_T == QSMLA_LAYOUT::BSND || LAYOUT_T == QSMLA_LAYOUT::TND) {193 if constexpr (LAYOUT_T == QSMLA_LAYOUT::BSND || LAYOUT_T == QSMLA_LAYOUT::TND) {
195- runParam.attentionOutOffset = attentionOutSeqOffset +194+ runParam.attentionOutOffset = attentionOutSeqOffset + runParam.sOuterOffset * constInfo.n2GDv +
196- runParam.sOuterOffset * constInfo.n2GDv + runParam.n2oIdx * constInfo.gDv +195+ runParam.n2oIdx * constInfo.gDv + runParam.goIdx * constInfo.dSizeV;
197- runParam.goIdx * constInfo.dSizeV;
198 }196 }
199 if (constInfo.subBlockIdx == 1) {197 if (constInfo.subBlockIdx == 1) {
200- runParam.attentionOutOffset += runParam.halfMRealSize * constInfo.dSizeV;198+ runParam.attentionOutOffset += runParam.firstHalfMRealSize * constInfo.dSizeV;
199+ }
200+ if (constInfo.isSoftmaxLseEnable) {
201+ if constexpr (LAYOUT_T == QSMLA_LAYOUT::TND) {
202+ // [N2, T, G] (TND)
203+ runParam.softmaxLseOffset = runParam.n2oIdx * constInfo.s1Size * constInfo.gSize +
204+ (seqOffset + runParam.sOuterOffset) * constInfo.gSize;
205+ } else {
206+ // [B, N2, S1, G] (BSND)
207+ runParam.softmaxLseOffset = sIdx * constInfo.n2Size * constInfo.s1Size * constInfo.gSize +
208+ runParam.n2oIdx * constInfo.s1Size * constInfo.gSize +
209+ runParam.sOuterOffset * constInfo.gSize;
210+ }
211+ if constexpr (IS_SPLIT_G) {
212+ uint32_t aicIdxLocal = constInfo.aivIdx >> 1U;
213+ if (aicIdxLocal % 2U != 0) {
214+ runParam.softmaxLseOffset += constInfo.gSize >> 1U;
215+ }
216+ }
217+ if (constInfo.subBlockIdx == 1) {
218+ runParam.softmaxLseOffset += runParam.firstHalfMRealSize;
219+ }
201 }220 }
202 }221 }
203}222}
204 223 
205TEMPLATE_INTF224TEMPLATE_INTF
206-__aicore__ inline bool ComputeParamS1(RunParamStr& runParam, const ConstInfo &constInfo,225+__aicore__ inline bool ComputeParamS1(RunParamStr &runParam, const ConstInfo &constInfo, uint32_t sOuterLoopIdx,
207- uint32_t sOuterLoopIdx, GlobalTensor<int32_t>& cuSeqlensQGm)226+ GlobalTensor<int32_t> &cuSeqlensQGm)
208{227{
209 if (runParam.nextTokensPerBatchOri < 0) {228 if (runParam.nextTokensPerBatchOri < 0) {
210- if (runParam.s1oIdx < (runParam.nextTokensPerBatchOri * (-1)) /229+ if (runParam.s1oIdx <
211- runParam.qSNumInOneBlock * runParam.qSNumInOneBlock) {230+ (runParam.nextTokensPerBatchOri * (-1)) / runParam.qSNumInOneBlock * runParam.qSNumInOneBlock) {
212 return true;231 return true;
213 }232 }
214 }233 }
@@ -220,7 +239,7 @@ __aicore__ inline bool ComputeParamS1(RunParamStr& runParam, const ConstInfo &co
220}239}
221 240 
222TEMPLATE_INTF241TEMPLATE_INTF
223-__aicore__ inline bool ComputeLastBN(RunParamStr& runParam, GlobalTensor<int32_t>& cuSeqlensQGm)242+__aicore__ inline bool ComputeLastBN(RunParamStr &runParam, GlobalTensor<int32_t> &cuSeqlensQGm)
224{243{
225 if constexpr (LAYOUT_T == QSMLA_LAYOUT::TND) {244 if constexpr (LAYOUT_T == QSMLA_LAYOUT::TND) {
226 if (runParam.boIdx > 0 &&245 if (runParam.boIdx > 0 &&
@@ -240,7 +259,7 @@ __aicore__ inline int64_t ClipSInnerTokenCube(int64_t sInnerToken, int64_t minVa
240}259}
241 260 
242TEMPLATE_INTF261TEMPLATE_INTF
243-__aicore__ inline bool ComputeS2LoopInfo(RunParamStr& runParam, const ConstInfo &constInfo)262+__aicore__ inline bool ComputeS2LoopInfo(RunParamStr &runParam, const ConstInfo &constInfo)
244{263{
245 if (runParam.actualS2OriSize == 0) {264 if (runParam.actualS2OriSize == 0) {
246 runParam.oriKvLoopEndIdx = 0;265 runParam.oriKvLoopEndIdx = 0;
@@ -258,8 +277,8 @@ __aicore__ inline bool ComputeS2LoopInfo(RunParamStr& runParam, const ConstInfo
258 277 
259 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {278 if constexpr (TEMPLATE_MODE != QSMLATemplateMode::SWA_TEMPLATE_MODE) {
260 runParam.s2LineCmpEndIdx = ClipSInnerTokenCube<TEMPLATE_INTF_ARGS>(279 runParam.s2LineCmpEndIdx = ClipSInnerTokenCube<TEMPLATE_INTF_ARGS>(
261- (runParam.cubeSOuterOffset + runParam.s1RealSize + runParam.nextTokensPerBatchCmp) / constInfo.cmpRatio,280+ (runParam.cubeSOuterOffset + runParam.s1RealSize + runParam.nextTokensPerBatchCmp) / constInfo.cmpRatio, 0,
262- 0, runParam.actualS2CmpSize);281+ runParam.actualS2CmpSize);
263 if constexpr (TEMPLATE_MODE == QSMLATemplateMode::HCA_TEMPLATE_MODE) {282 if constexpr (TEMPLATE_MODE == QSMLATemplateMode::HCA_TEMPLATE_MODE) {
264 runParam.s2CmpLineEndIdx = Min(runParam.s2LineCmpEndIdx, runParam.actualS2CmpSize);283 runParam.s2CmpLineEndIdx = Min(runParam.s2LineCmpEndIdx, runParam.actualS2CmpSize);
265 runParam.cmpKvLoopEndIdx = (runParam.s2CmpLineEndIdx + s2BaseSize - 1) / s2BaseSize;284 runParam.cmpKvLoopEndIdx = (runParam.s2CmpLineEndIdx + s2BaseSize - 1) / s2BaseSize;
@@ -277,7 +296,7 @@ __aicore__ inline bool ComputeS2LoopInfo(RunParamStr& runParam, const ConstInfo
277}296}
278 297 
279TEMPLATE_INTF298TEMPLATE_INTF
280-__aicore__ inline void InitTaskParamByRun(const RunParamStr& runParam, RunInfo &runInfo)299+__aicore__ inline void InitTaskParamByRun(const RunParamStr &runParam, RunInfo &runInfo)
281{300{
282 runInfo.boIdx = runParam.boIdx;301 runInfo.boIdx = runParam.boIdx;
283 runInfo.preTokensPerBatch = runParam.preTokensPerBatch;302 runInfo.preTokensPerBatch = runParam.preTokensPerBatch;
@@ -295,4 +314,4 @@ __aicore__ inline void InitTaskParamByRun(const RunParamStr& runParam, RunInfo &
295 runInfo.isCmp = runInfo.s2LoopCount >= runInfo.oriKvLoopEndIdx;314 runInfo.isCmp = runInfo.s2LoopCount >= runInfo.oriKvLoopEndIdx;
296}315}
297 316 
298-#endif // QUANT_SPARSE_FLASH_MLA_KVCACHE_H317+#endif // QUANT_SPARSE_FLASH_MLA_KVCACHE_H
@@ -18,98 +18,106 @@
18 18 
19#include "util.h"19#include "util.h"
20 20 
21-using AscendC::TQue;
22using AscendC::QuePosition;21using AscendC::QuePosition;
22+using AscendC::TQue;
23 23 
24namespace regbaseutil {24namespace regbaseutil {
25constexpr int64_t MAX_PRE_NEXT_TOKENS = 0x7FFFFFFF;25constexpr int64_t MAX_PRE_NEXT_TOKENS = 0x7FFFFFFF;
26-enum class VselrIndexEnum {GT_64_AND_LTE_128_INDEX = 0, GT_0_AND_LTE_64_INDEX = 1};26+enum class VselrIndexEnum {
27-#define COMMON_RUN_PARAM \27+ GT_64_AND_LTE_128_INDEX = 0,
28- int64_t boIdx; \28+ GT_0_AND_LTE_64_INDEX = 1
29- int64_t s1oIdx; \29+};
30- int64_t n2oIdx; \30+#define COMMON_RUN_PARAM \
31- int64_t goIdx; \31+ int64_t boIdx; \
32- int64_t s2LoopEndIdx; /* S2方向的循环控制信息 souter层确定 */ \32+ int64_t s1oIdx; \
33- int64_t s2LineStartIdx = 0; /* S2方向按行的起始位置 */ \33+ int64_t n2oIdx; \
34- int64_t s2LineOriEndIdx; /* S2方向按行的结束位置 */ \34+ int64_t goIdx; \
35- int64_t s2CmpLineEndIdx; \35+ int64_t gSplitSize; /* split-G模式下当前AIC处理的G轴行数 */ \
36- int64_t s2LineCmpEndIdx; \36+ int64_t s2LoopEndIdx; /* S2方向的循环控制信息 souter层确定 */ \
37- /* cube视角的sOuter,在SAMEAB场景中cubeSOuterSize为两倍的 halfS1RealSize souter层确定 */ \37+ int64_t s2LineStartIdx = 0; /* S2方向按行的起始位置 */ \
38- uint32_t s1RealSize; \38+ int64_t s2LineOriEndIdx; /* S2方向按行的结束位置 */ \
39- uint32_t halfS1RealSize; \39+ int64_t s2CmpLineEndIdx; \
40- uint32_t firstHalfS1RealSize; \40+ int64_t s2LineCmpEndIdx; \
41- uint32_t mRealSize; \41+ /* cube视角的sOuter,在SAMEAB场景中cubeSOuterSize为两倍的 halfS1RealSize souter层确定 */ \
42- uint32_t halfMRealSize; \42+ uint32_t s1RealSize; \
43- uint32_t firstHalfMRealSize; \43+ uint32_t halfS1RealSize; \
44- int64_t attentionOutOffset; /* attentionOut的offset souter层确定 */ \44+ uint32_t firstHalfS1RealSize; \
45- int32_t actualS1Size; /* Q的actualSeqLength */ \45+ uint32_t mRealSize; \
46- int32_t actualS2OriSize; /* ori_kv的真实使用长度 */ \46+ uint32_t halfMRealSize; \
47- int32_t actualS2CmpSize; /* cmp_kv的真实使用长度 */ \47+ uint32_t firstHalfMRealSize; \
48- int32_t cmpResidual /* cmp的余数,用于mask计算 */ \48+ int64_t attentionOutOffset; /* attentionOut的offset souter层确定 */ \
49+ int32_t actualS1Size; /* Q的actualSeqLength */ \
50+ int32_t actualS2OriSize; /* ori_kv的真实使用长度 */ \
51+ int32_t actualS2CmpSize; /* cmp_kv的真实使用长度 */ \
52+ int32_t cmpResidual /* cmp的余数,用于mask计算 */
49 53 
50-struct RunParamStr { // 分核与切块需要使用到参数54+struct RunParamStr { // 分核与切块需要使用到参数
51 COMMON_RUN_PARAM;55 COMMON_RUN_PARAM;
52 /* 推理新增 */56 /* 推理新增 */
53 int64_t gs1LoopStartIdx;57 int64_t gs1LoopStartIdx;
54 int64_t gs1LoopEndIdx;58 int64_t gs1LoopEndIdx;
55 // BN循环生产的数据59 // BN循环生产的数据
56- int64_t preTokensPerBatch = MAX_PRE_NEXT_TOKENS; // 左上顶点的pretoken60+ int64_t preTokensPerBatch = MAX_PRE_NEXT_TOKENS; // 左上顶点的pretoken
57 int64_t nextTokensPerBatchOri = MAX_PRE_NEXT_TOKENS; // ori 左上顶点的nexttoken61 int64_t nextTokensPerBatchOri = MAX_PRE_NEXT_TOKENS; // ori 左上顶点的nexttoken
58 int64_t nextTokensPerBatchCmp = MAX_PRE_NEXT_TOKENS; // cmp 左上顶点的nexttoken62 int64_t nextTokensPerBatchCmp = MAX_PRE_NEXT_TOKENS; // cmp 左上顶点的nexttoken
59 63 
60 // NBS1循环生产的数据64 // NBS1循环生产的数据
61- int64_t sOuterOffset; // 单个S内 souter的 souterIdx * halfS1RealSize souter层确定65+ int64_t sOuterOffset; // 单个S内 souter的 souterIdx * halfS1RealSize souter层确定
62- int64_t cubeSOuterOffset; // 单个S内 souter的 souterIdx * halfS1RealSize souter层确定66+ int64_t cubeSOuterOffset; // 单个S内 souter的 souterIdx * halfS1RealSize souter层确定
63 int64_t mOuterOffset;67 int64_t mOuterOffset;
64 int64_t cubeMOuterOffset;68 int64_t cubeMOuterOffset;
65 69 
66 // lse 输出offset70 // lse 输出offset
67- int64_t softmaxLseOffset; // souter层确定71+ int64_t softmaxLseOffset; // souter层确定
68 72 
69 int64_t qSNumInOneBlock;73 int64_t qSNumInOneBlock;
70 int64_t oriKvLoopEndIdx;74 int64_t oriKvLoopEndIdx;
71 int64_t cmpKvLoopEndIdx;75 int64_t cmpKvLoopEndIdx;
72};76};
73 77 
74-#define COMMON_RUN_INFO \78+#define COMMON_RUN_INFO \
75- uint64_t s2StartIdx; /* s2的起始位置,sparse场景下可能不是0 */ \79+ uint64_t s2StartIdx; /* s2的起始位置,sparse场景下可能不是0 */ \
76- int64_t s2EndIdx; \80+ int64_t s2EndIdx; \
77- int64_t s2LoopCount; /* s2循环当前的循环index */ \81+ int64_t s2LoopCount; /* s2循环当前的循环index */ \
78- int64_t s2LoopLimit; \82+ int64_t s2LoopLimit; \
79- int64_t s1oIdx = 0; /* s1轴的index */ \83+ int64_t s1oIdx = 0; /* s1轴的index */ \
80- int64_t loop = 0; /* for v0 perload loop */ \84+ int64_t loop = 0; /* for v0 perload loop */ \
81- int64_t boIdx = 0; /* b轴的index */ \85+ int64_t boIdx = 0; /* b轴的index */ \
82- int64_t n2oIdx = 0; /* n2轴的index */ \86+ int64_t n2oIdx = 0; /* n2轴的index */ \
83- int64_t goIdx = 0; /* g轴的index */ \87+ int64_t goIdx = 0; /* g轴的index */ \
84- int32_t s1RealSize; \88+ int32_t s1RealSize; \
85- int32_t halfS1RealSize; /* vector侧实际的s1基本块大小,如果Cube基本块=128,那么halfS1RealSize=64 */ \89+ int32_t halfS1RealSize; /* vector侧实际的s1基本块大小,如果Cube基本块=128,那么halfS1RealSize=64 */ \
86- int32_t firstHalfS1RealSize; /* 当s1RealSize不是2的整数倍时,v0比v1少计算一行,计算subblock偏移的时候需要使用v0的s1 size */ \90+ int32_t \
87- int32_t mRealSize; \91+ firstHalfS1RealSize; /* 当s1RealSize不是2的整数倍时,v0比v1少计算一行,计算subblock偏移的时候需要使用v0的s1 \
88- int32_t halfMRealSize; \92+ size */ \
89- int32_t firstHalfMRealSize; \93+ int32_t mRealSize; \
90- int32_t s2RealSize; /* s2方向基本块的真实长度 */ \94+ int32_t halfMRealSize; \
91- int64_t s2AlignedSize; /* s2方向基本块对齐到16之后的长度 */ \95+ int32_t firstHalfMRealSize; \
92- int32_t vec2S1BaseSize; /* vector2侧开循环之后,经过切分的S1大小,例如把64切分成两份32 */ \96+ int32_t s2RealSize; /* s2方向基本块的真实长度 */ \
93- int32_t vec2S1RealSize; /* vector2侧开循环之后,经过切分的S1的尾块大小,例如把63切分成两份32和31,第二份的实际大小是31 */ \97+ int64_t s2AlignedSize; /* s2方向基本块对齐到16之后的长度 */ \
94- int32_t vec2MBaseSize; \98+ int32_t vec2S1BaseSize; /* vector2侧开循环之后,经过切分的S1大小,例如把64切分成两份32 */ \
95- int32_t vec2MRealSize; \99+ int32_t \
96- int64_t taskId; \100+ vec2S1RealSize; /* vector2侧开循环之后,经过切分的S1的尾块大小,例如把63切分成两份32和31,第二份的实际大小是31 \
97- int64_t multiCoreInnerIdx = 0; \101+ */ \
98- int64_t attentionOutOffset; \102+ int32_t vec2MBaseSize; \
99- int32_t actualS1Size; /* 非TND场景=总s1Size, Tnd场景下当前batch对应的s1 */ \103+ int32_t vec2MRealSize; \
100- int32_t actualS2OriSize; /* ori_kv的真实使用长度 */ \104+ int64_t taskId; \
101- int32_t actualS2CmpSize; /* cmp_kv的真实使用长度 */ \105+ int64_t multiCoreInnerIdx = 0; \
102- int32_t cmpResidual; /* cmp的余数,用于mask计算 */ \106+ int64_t attentionOutOffset; \
103- int64_t preTokensPerBatch; /* vector2 左上顶点的pretoken */ \107+ int32_t actualS1Size; /* 非TND场景=总s1Size, Tnd场景下当前batch对应的s1 */ \
104- int64_t nextTokensPerBatchOri; /* vector2 ori 左上顶点的nexttoken */ \108+ int32_t actualS2OriSize; /* ori_kv的真实使用长度 */ \
105- int64_t nextTokensPerBatchCmp; /* vector2 cmp 左上顶点的nexttoken */ \109+ int32_t actualS2CmpSize; /* cmp_kv的真实使用长度 */ \
106- uint8_t taskIdMod2; \110+ int32_t cmpResidual; /* cmp的余数,用于mask计算 */ \
107- uint8_t taskIdMod3; \111+ int64_t preTokensPerBatch; /* vector2 左上顶点的pretoken */ \
108- uint8_t multiCoreIdxMod2 = 0; \112+ int64_t nextTokensPerBatchOri; /* vector2 ori 左上顶点的nexttoken */ \
109- uint8_t multiCoreIdxMod3 = 0; \113+ int64_t nextTokensPerBatchCmp; /* vector2 cmp 左上顶点的nexttoken */ \
110- int64_t sOuterOffset; \114+ uint8_t taskIdMod2; \
111- int64_t mOuterOffset; \115+ uint8_t taskIdMod3; \
112- bool isCmp; \116+ uint8_t multiCoreIdxMod2 = 0; \
117+ uint8_t multiCoreIdxMod3 = 0; \
118+ int64_t sOuterOffset; \
119+ int64_t mOuterOffset; \
120+ bool isCmp;
113 121 
114struct RunInfo {122struct RunInfo {
115 COMMON_RUN_INFO;123 COMMON_RUN_INFO;
@@ -122,100 +130,100 @@ struct RunInfo {
122 int64_t cmpKvLoopEndIdx;130 int64_t cmpKvLoopEndIdx;
123};131};
124 132 
125-#define COMMON_CONST_INFO \133+#define COMMON_CONST_INFO \
126- /* 全局的基本块信息 */ \134+ /* 全局的基本块信息 */ \
127- uint32_t bSize; \135+ uint32_t bSize; \
128- uint32_t needInit; \136+ uint32_t needInit; \
129- uint32_t s1BaseSize; \137+ uint32_t s1BaseSize; \
130- uint32_t s2BaseSize; \138+ uint32_t s2BaseSize; \
131- int64_t dSize; /* query d 512 */ \139+ int64_t dSize; /* query d 512 */ \
132- int64_t dSizeV; /* key d 512 */ \140+ int64_t dSizeV; /* key d 512 */ \
133- int64_t dSizeVInput; /* key inpue d 512 */ \141+ int64_t dSizeVInput; /* key inpue d 512 */ \
134- int64_t sparseMode = 3; \142+ int64_t sparseMode = 3; \
135- int64_t gSize; /* g轴的大小 */ \143+ int64_t gSize; /* g轴的大小 */ \
136- int64_t n2Size; \144+ int64_t n2Size; \
137- int64_t s1Size; /* s1总大小 */ \145+ int64_t s1Size; /* s1总大小 */ \
138- int64_t s2Size; /* s2总大小 */ \146+ int64_t s2Size; /* s2总大小 */ \
139- int64_t cmpS2Size; \147+ int64_t cmpS2Size; \
140- /* 轴的乘积 */ \148+ /* 轴的乘积 */ \
141- int64_t s1D; \149+ int64_t s1D; \
142- int64_t gS1D; \150+ int64_t gS1D; \
143- int64_t n2GS1D; \151+ int64_t n2GS1D; \
144- int64_t s2D; \152+ int64_t s2D; \
145- int64_t n2S2D; \153+ int64_t n2S2D; \
146- int64_t s1Dv; \154+ int64_t s1Dv; \
147- int64_t gS1Dv; \155+ int64_t gS1Dv; \
148- int64_t n2GS1Dv; \156+ int64_t n2GS1Dv; \
149- int64_t s2Dv; \157+ int64_t s2Dv; \
150- int64_t n2S2Dv; \158+ int64_t n2S2Dv; \
151- int64_t s1S2; \159+ int64_t s1S2; \
152- int64_t gS1; \160+ int64_t gS1; \
153- int64_t gD; \161+ int64_t gD; \
154- int64_t n2D; \162+ int64_t n2D; \
155- int64_t bN2D; \163+ int64_t bN2D; \
156- int64_t gDv; \164+ int64_t gDv; \
157- int64_t n2Dv; \165+ int64_t n2Dv; \
158- int64_t bN2Dv; \166+ int64_t bN2Dv; \
159- int64_t n2G; \167+ int64_t n2G; \
160- int64_t n2GD; \168+ int64_t n2GD; \
161- int64_t bN2GD; \169+ int64_t bN2GD; \
162- int64_t n2GDv; \170+ int64_t n2GDv; \
163- int64_t bN2GDv; \171+ int64_t bN2GDv; \
164- int64_t gS2; \172+ int64_t gS2; \
165- int64_t s1Dr; \173+ int64_t s1Dr; \
166- int64_t gS1Dr; \174+ int64_t gS1Dr; \
167- int64_t n2GS1Dr; \175+ int64_t n2GS1Dr; \
168- int64_t s2Dr; \176+ int64_t s2Dr; \
169- int64_t n2S2Dr; \177+ int64_t n2S2Dr; \
170- int64_t gDr; \178+ int64_t gDr; \
171- int64_t n2Dr; \179+ int64_t n2Dr; \
172- int64_t bN2Dr; \180+ int64_t bN2Dr; \
173- int64_t n2GDr; \181+ int64_t n2GDr; \
174- int64_t bN2GDr; \182+ int64_t bN2GDr; \
175- int32_t s2BaseN2D; \183+ int32_t s2BaseN2D; \
176- int32_t s1BaseN2GD; \184+ int32_t s1BaseN2GD; \
177- int64_t s2BaseBN2D; \185+ int64_t s2BaseBN2D; \
178- int64_t s1BaseBN2GD; \186+ int64_t s1BaseBN2GD; \
179- int32_t s1BaseD; \187+ int32_t s1BaseD; \
180- int32_t s2BaseD; \188+ int32_t s2BaseD; \
181- int64_t s2BaseN2Dv; \189+ int64_t s2BaseN2Dv; \
182- int64_t s2BaseBN2Dv; \190+ int64_t s2BaseBN2Dv; \
183- int64_t s1BaseN2GDv; \191+ int64_t s1BaseN2GDv; \
184- int64_t s1BaseBN2GDv; \192+ int64_t s1BaseBN2GDv; \
185- int32_t s1BaseDv; \193+ int32_t s1BaseDv; \
186- int32_t s2BaseDv; \194+ int32_t s2BaseDv; \
187- /* matmul跳读参数 */ \195+ /* matmul跳读参数 */ \
188- int64_t mm1Ka; \196+ int64_t mm1Ka; \
189- /* dq 或者attentionOut的Stride */ \197+ /* dq 或者attentionOut的Stride */ \
190- int64_t attentionOutStride; \198+ int64_t attentionOutStride; \
191- uint32_t aivIdx; \199+ uint32_t aivIdx; \
192- uint8_t subBlockIdx;\200+ uint8_t subBlockIdx;
193 201 
194-#define INFER_CONST_INFO \202+#define INFER_CONST_INFO \
195- /* 推理 */ \203+ /* 推理 */ \
196- bool isActualLenDimsNull; /* 判断是否有actualseq */ \204+ bool isActualLenDimsNull; /* 判断是否有actualseq */ \
197- bool isSoftmaxLseEnable; \205+ bool isSoftmaxLseEnable; \
198- uint32_t sparseBlockCount; \206+ uint32_t sparseBlockCount; \
199 uint32_t alignedSparseBlockCount; /* 按128对齐后的sparseBlockCount,用于kvPhyAddrGm的UB/GM buffer分配与寻址 */ \207 uint32_t alignedSparseBlockCount; /* 按128对齐后的sparseBlockCount,用于kvPhyAddrGm的UB/GM buffer分配与寻址 */ \
200- uint32_t actualSeqLenSize; /* 用户输入的actualseq的长度 */ \208+ uint32_t actualSeqLenSize; /* 用户输入的actualseq的长度 */ \
201- /* service mm1 mm2 pageAttention */ \209+ /* service mm1 mm2 pageAttention */ \
202- uint32_t oriBlockSize; \210+ uint32_t oriBlockSize; \
203- uint32_t cmpBlockSize; \211+ uint32_t cmpBlockSize; \
204- uint32_t paLayoutType; \212+ uint32_t paLayoutType; \
205- uint32_t oriMaxBlockNumPerBatch; \213+ uint32_t oriMaxBlockNumPerBatch; \
206- uint32_t cmpMaxBlockNumPerBatch; \214+ uint32_t cmpMaxBlockNumPerBatch; \
207- int32_t oriWinLeft; \215+ int32_t oriWinLeft; \
208- int32_t oriWinRight; \216+ int32_t oriWinRight; \
209- uint32_t sparseBlockSize; \217+ uint32_t sparseBlockSize; \
210- uint32_t cmpRatio; \218+ uint32_t cmpRatio; \
211- float softmaxScale; \219+ float softmaxScale; \
212- uint32_t oriKvStride; \220+ uint32_t oriKvStride; \
213- uint32_t cmpKvStride; \221+ uint32_t cmpKvStride;
214 222 
215-struct ConstInfo{223+struct ConstInfo {
216 COMMON_CONST_INFO;224 COMMON_CONST_INFO;
217 INFER_CONST_INFO;225 INFER_CONST_INFO;
218};226};
219-}227+} // namespace regbaseutil
220 228 
221#endif // QSMLA_UTIL_REGBASE_H229#endif // QSMLA_UTIL_REGBASE_H
@@ -8,7 +8,7 @@
8 * See LICENSE in the root of the software repository for the full text of the License.8 * See LICENSE in the root of the software repository for the full text of the License.
9*/9*/
10 10 
11- /*!11+/*!
12 * \file quant_sparse_flash_mla.cpp12 * \file quant_sparse_flash_mla.cpp
13 * \brief13 * \brief
14 */14 */
@@ -26,20 +26,22 @@
26 26 
27using namespace AscendC;27using namespace AscendC;
28 28 
29-#define QSMLA_OP_IMPL(templateClass, tilingdataClass, ...) \29+#define QSMLA_OP_IMPL(templateClass, tilingdataClass, ...) \
30- do { \30+ do { \
31- using CubeBlockType = typename std::conditional<g_coreType == AscendC::AIC, \31+ using CubeBlockType = \
32- BaseApi::CSABlockCube<__VA_ARGS__>, BaseApi::CSABlockCubeDummy<__VA_ARGS__>>::type; \32+ typename std::conditional<g_coreType == AscendC::AIC, BaseApi::CSABlockCube<__VA_ARGS__>, \
33- using VecBlockType = typename std::conditional<g_coreType == AscendC::AIC, \33+ BaseApi::CSABlockCubeDummy<__VA_ARGS__>>::type; \
34- BaseApi::CSABlockVecDummy<__VA_ARGS__>, BaseApi::CSABlockVec<__VA_ARGS__>>::type; \34+ using VecBlockType = \
35- templateClass<CubeBlockType, VecBlockType> op; \35+ typename std::conditional<g_coreType == AscendC::AIC, BaseApi::CSABlockVecDummy<__VA_ARGS__>, \
36- GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tilingDataIn, tiling); \36+ BaseApi::CSABlockVec<__VA_ARGS__>>::type; \
37- const tilingdataClass *__restrict tilingData = &tilingDataIn; \37+ templateClass<CubeBlockType, VecBlockType> op; \
38- op.Init(query, oriKV, cmpKV, qDescale, oriKVDescale, cmpKVDescale, oriSparseIndices, \38+ GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tilingDataIn, tiling); \
39- cmpSparseIndices, oriBlockTable, cmpBlockTable, cuSeqlensQ, cuSeqlensOriKv, \39+ const tilingdataClass *__restrict tilingData = &tilingDataIn; \
40- cuSeqlensCmpKv, seqUsedQ, seqUsedOriKV, seqUsedCmpKV, cmpResidualKv, oriTopkLength, \40+ op.Init(query, oriKV, cmpKV, qDescale, oriKVDescale, cmpKVDescale, oriSparseIndices, cmpSparseIndices, \
41- cmpTopkLength, sinks, metadata, attentionOut, user, tilingData, &tPipe); \41+ oriBlockTable, cmpBlockTable, cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, seqUsedQ, seqUsedOriKV, \
42- op.Process(); \42+ seqUsedCmpKV, cmpResidualKv, oriTopkLength, cmpTopkLength, sinks, metadata, attentionOut, softmax_lse, \
43+ user, tilingData, &tPipe); \
44+ op.Process(); \
43 } while (0)45 } while (0)
44 46 
45template <int FLASH_DECODE, int LAYOUT_T, int KV_LAYOUT_T, int TEMPLATE_MODE, int SPLIT_G, int KV_DTYPE,47template <int FLASH_DECODE, int LAYOUT_T, int KV_LAYOUT_T, int TEMPLATE_MODE, int SPLIT_G, int KV_DTYPE,
@@ -58,9 +60,9 @@ quant_sparse_flash_mla(__gm__ uint8_t *query, __gm__ uint8_t *oriKV, __gm__ uint
58 TPipe tPipe;60 TPipe tPipe;
59 __gm__ uint8_t *user = GetUserWorkspace(workspace);61 __gm__ uint8_t *user = GetUserWorkspace(workspace);
60 if constexpr (ORIG_DTYPE_Q == DT_HIFLOAT8 && ORIG_DTYPE_ORI_KV == DT_HIFLOAT8) {62 if constexpr (ORIG_DTYPE_Q == DT_HIFLOAT8 && ORIG_DTYPE_ORI_KV == DT_HIFLOAT8) {
61- QSMLA_OP_IMPL(BaseApi::QuantSparseFlashMlaCsa, QuantSparseFlashMlaTilingData, hifloat8_t,63+ QSMLA_OP_IMPL(BaseApi::QuantSparseFlashMlaCsa, QuantSparseFlashMlaTilingData, hifloat8_t, hifloat8_t, float,
62- hifloat8_t, float, bfloat16_t, FLASH_DECODE, KV_LAYOUT_T == QSMLA_LAYOUT_PA_BBND,64+ bfloat16_t, FLASH_DECODE, KV_LAYOUT_T == QSMLA_LAYOUT_PA_BBND,
63- static_cast<QSMLA_LAYOUT>(LAYOUT_T), static_cast<QSMLA_LAYOUT>(KV_LAYOUT_T),65+ static_cast<QSMLA_LAYOUT>(LAYOUT_T), static_cast<QSMLA_LAYOUT>(KV_LAYOUT_T),
64- static_cast<QSMLATemplateMode>(TEMPLATE_MODE), SPLIT_G, IS_VEC_S2PHYADDR);66+ static_cast<QSMLATemplateMode>(TEMPLATE_MODE), SPLIT_G, IS_VEC_S2PHYADDR);
65 }67 }
66}68}
@@ -10,236 +10,353 @@
10# See LICENSE in the root of the software repository for the full text of the License.10# See LICENSE in the root of the software repository for the full text of the License.
11# -----------------------------------------------------------------------------------------------------------11# -----------------------------------------------------------------------------------------------------------
12 12 
13-import os
14import torch13import torch
15import torch_npu14import torch_npu
16-import check_valid_param
17-import pytest
18-import random
19-import numpy as np
20-import math
21-import cann_ops_transformer
22import torchair15import torchair
23from torchair.configs.compiler_config import CompilerConfig16from torchair.configs.compiler_config import CompilerConfig
24import logging17import logging
25 18 
19+ 
26class Network(torch.nn.Module):20class Network(torch.nn.Module):
27 def __init__(self):21 def __init__(self):
28 super(Network, self).__init__()22 super(Network, self).__init__()
29 23 
30- def forward(self, q, ori_kv, cmp_kv, q_descale, ori_kv_descale, cmp_kv_descale, ori_sparse_indices,24+ def forward(
31- cmp_sparse_indices, ori_block_table, cmp_block_table, cu_seqlens_q, cu_seqlens_ori_kv,25+ self,
32- cu_seqlens_cmp_kv, seqused_q, seqused_ori_kv, seqused_cmp_kv, cmp_residual_kv, ori_topk_length,26+ q,
33- cmp_topk_length, sinks, metadata, quant_mode, softmax_scale, cmp_ratio, ori_mask_mode,27+ ori_kv,
34- cmp_mask_mode, ori_win_left, ori_win_right, layout_q, layout_kv, topk_value_mode, return_softmax_lse):28+ cmp_kv,
35- npu_result, _ = torch.ops.cann_ops_transformer.quant_sparse_flash_mla(29+ q_descale,
36- q=q,30+ ori_kv_descale,
37- ori_kv=ori_kv,31+ cmp_kv_descale,
38- cmp_kv=cmp_kv,32+ ori_sparse_indices,
39- q_descale=q_descale,33+ cmp_sparse_indices,
40- ori_kv_descale=ori_kv_descale,34+ ori_block_table,
41- cmp_kv_descale=cmp_kv_descale,35+ cmp_block_table,
42- ori_sparse_indices=ori_sparse_indices,36+ cu_seqlens_q,
43- cmp_sparse_indices=cmp_sparse_indices,37+ cu_seqlens_ori_kv,
44- ori_block_table=ori_block_table,38+ cu_seqlens_cmp_kv,
45- cmp_block_table=cmp_block_table,39+ seqused_q,
46- cu_seqlens_q=cu_seqlens_q,40+ seqused_ori_kv,
47- cu_seqlens_ori_kv=cu_seqlens_ori_kv,41+ seqused_cmp_kv,
48- cu_seqlens_cmp_kv=cu_seqlens_cmp_kv,42+ cmp_residual_kv,
49- seqused_q=seqused_q,43+ ori_topk_length,
50- seqused_ori_kv=seqused_ori_kv,44+ cmp_topk_length,
51- seqused_cmp_kv=seqused_cmp_kv,45+ sinks,
52- cmp_residual_kv=cmp_residual_kv,46+ metadata,
53- ori_topk_length=ori_topk_length,47+ quant_mode,
54- cmp_topk_length=cmp_topk_length,48+ softmax_scale,
55- sinks=sinks,49+ cmp_ratio,
56- metadata=metadata,50+ ori_mask_mode,
57- quant_mode=quant_mode,51+ cmp_mask_mode,
58- softmax_scale=softmax_scale,52+ ori_win_left,
59- cmp_ratio=cmp_ratio,53+ ori_win_right,
60- ori_mask_mode=ori_mask_mode,54+ layout_q,
61- cmp_mask_mode=cmp_mask_mode,55+ layout_kv,
62- ori_win_left=ori_win_left,56+ topk_value_mode,
63- ori_win_right=ori_win_right,57+ return_softmax_lse,
64- layout_q=layout_q,58+ ):
65- layout_kv=layout_kv,59+ npu_result, npu_lse = torch.ops.cann_ops_transformer.quant_sparse_flash_mla(
66- topk_value_mode=topk_value_mode,60+ q=q,
67- return_softmax_lse=return_softmax_lse)61+ ori_kv=ori_kv,
68- return npu_result62+ cmp_kv=cmp_kv,
63+ q_descale=q_descale,
64+ ori_kv_descale=ori_kv_descale,
65+ cmp_kv_descale=cmp_kv_descale,
66+ ori_sparse_indices=ori_sparse_indices,
67+ cmp_sparse_indices=cmp_sparse_indices,
68+ ori_block_table=ori_block_table,
69+ cmp_block_table=cmp_block_table,
70+ cu_seqlens_q=cu_seqlens_q,
71+ cu_seqlens_ori_kv=cu_seqlens_ori_kv,
72+ cu_seqlens_cmp_kv=cu_seqlens_cmp_kv,
73+ seqused_q=seqused_q,
74+ seqused_ori_kv=seqused_ori_kv,
75+ seqused_cmp_kv=seqused_cmp_kv,
76+ cmp_residual_kv=cmp_residual_kv,
77+ ori_topk_length=ori_topk_length,
78+ cmp_topk_length=cmp_topk_length,
79+ sinks=sinks,
80+ metadata=metadata,
81+ quant_mode=quant_mode,
82+ softmax_scale=softmax_scale,
83+ cmp_ratio=cmp_ratio,
84+ ori_mask_mode=ori_mask_mode,
85+ cmp_mask_mode=cmp_mask_mode,
86+ ori_win_left=ori_win_left,
87+ ori_win_right=ori_win_right,
88+ layout_q=layout_q,
89+ layout_kv=layout_kv,
90+ topk_value_mode=topk_value_mode,
91+ return_softmax_lse=return_softmax_lse,
92+ )
93+ return npu_result, npu_lse
69 94 
70 95 
71def test_qsmla_quant_process_graph(test_data, device_id=0):96def test_qsmla_quant_process_graph(test_data, device_id=0):
72- global npu_model, is_compiled97+ params = test_data["params"]
73- params = test_data['params']98+ metadata_input = test_data["metadata_input"]
74- metadata_input = test_data['metadata_input']99+ op_input = test_data["op_input"]
75- op_input = test_data['op_input']100+ cpu_output = test_data["cpu_output"]
76- cpu_output = test_data['cpu_output']101+ cpu_lse = test_data.get("cpu_lse")
77 torch_npu.npu.set_device(device_id)102 torch_npu.npu.set_device(device_id)
@@ -30,11 +30,11 @@ param_combinations = []
30for _, params in enumerate(ENABLED_PARAMS):30for _, params in enumerate(ENABLED_PARAMS):
31 normalized_params = {}31 normalized_params = {}
32 for key, value in params.items():32 for key, value in params.items():
33- if value == 'torch.bfloat16':33+ if value == "torch.bfloat16":
34 value = torch.bfloat1634 value = torch.bfloat16
35- elif value == 'torch.float8_e4m3fn':35+ elif value == "torch.float8_e4m3fn":
36 value = torch.float8_e4m3fn36 value = torch.float8_e4m3fn
37- elif value == 'torch.uint8':37+ elif value == "torch.uint8":
38 value = torch.uint838 value = torch.uint8
39 elif value == "FALSE":39 elif value == "FALSE":
40 value = False40 value = False
@@ -47,20 +47,56 @@ for _, params in enumerate(ENABLED_PARAMS):
47 if isinstance(isSink_raw, str):47 if isinstance(isSink_raw, str):
48 isSink_raw = isSink_raw.upper() == "TRUE"48 isSink_raw = isSink_raw.upper() == "TRUE"
49 normalized_params["isSink"] = bool(isSink_raw)49 normalized_params["isSink"] = bool(isSink_raw)
50- for key in ["seqused_q", "cu_seqlens_q", "seqused_ori_kv", "seqused_cmp_kv",50+ for key in [
51- "cu_seqlens_ori_kv", "cu_seqlens_cmp_kv", "cmp_residual_kv"]:51+ "seqused_q",
52+ "cu_seqlens_q",
53+ "seqused_ori_kv",
54+ "seqused_cmp_kv",
55+ "cu_seqlens_ori_kv",
56+ "cu_seqlens_cmp_kv",
57+ "cmp_residual_kv",
58+ ]:
52 normalized_params[key] = utils.parse_list_param(params.get(key))59 normalized_params[key] = utils.parse_list_param(params.get(key))
53 template_run_mode = normalized_params["template_run_mode"]60 template_run_mode = normalized_params["template_run_mode"]
54 if isinstance(template_run_mode, list):61 if isinstance(template_run_mode, list):
55 template_run_mode = template_run_mode[0]62 template_run_mode = template_run_mode[0]
56 63 
57 param_names = [64 param_names = [
58- "Testcase_Name", "layout_q", "layout_kv", "q_type", "ori_kv_type", "cmp_kv_type", "B", "S1", "S2", "N1", \65+ "Testcase_Name",
59- "N2", "D", "K", "block_size1", "block_size2", "softmax_scale", "cmp_ratio", "ori_mask_mode", "cmp_mask_mode", \66+ "layout_q",
60- "ori_win_left", "ori_win_right", "quant_mode", "template_run_mode", \67+ "layout_kv",
61- "actlen_mode", "S1EQS2", "topk_value_mode", "return_softmax_lse", "isSink", \68+ "q_type",
62- "seqused_q", "cu_seqlens_q", "seqused_ori_kv", "seqused_cmp_kv", \69+ "ori_kv_type",
63- "cu_seqlens_ori_kv", "cu_seqlens_cmp_kv", "cmp_residual_kv"70+ "cmp_kv_type",
71+ "B",
72+ "S1",
73+ "S2",
74+ "N1",
75+ "N2",
76+ "D",
77+ "K",
78+ "block_size1",
79+ "block_size2",
80+ "softmax_scale",
81+ "cmp_ratio",
82+ "ori_mask_mode",
83+ "cmp_mask_mode",
84+ "ori_win_left",
85+ "ori_win_right",
86+ "quant_mode",
87+ "template_run_mode",
88+ "actlen_mode",
89+ "S1EQS2",
90+ "topk_value_mode",
91+ "return_softmax_lse",
92+ "isSink",
93+ "seqused_q",
94+ "cu_seqlens_q",
95+ "seqused_ori_kv",
96+ "seqused_cmp_kv",
97+ "cu_seqlens_ori_kv",
98+ "cu_seqlens_cmp_kv",
99+ "cmp_residual_kv",
64 ]100 ]
65 101 
66 param_values = [102 param_values = [
@@ -108,17 +144,19 @@ for _, params in enumerate(ENABLED_PARAMS):
108 logging.info(param_combinations)144 logging.info(param_combinations)
109 145 
110case_id = 0146case_id = 0
147+ 
148+ 
111def qsmla(param_combinations):149def qsmla(param_combinations):
112 global case_id150 global case_id
113 params = utils.fill_none_params(param_combinations)151 params = utils.fill_none_params(param_combinations)
114 152 
115- Testcase_Name = params['Testcase_Name']153+ Testcase_Name = params["Testcase_Name"]
116 if Testcase_Name is None:154 if Testcase_Name is None:
117- ops_mode = 'prefill' if params['S1'] > 4 else "decode"155+ ops_mode = "prefill" if params["S1"] > 4 else "decode"
118- q_type_str = "BF16" if params['q_type'] == torch.bfloat16 else "FP16"156+ q_type_str = "BF16" if params["q_type"] == torch.bfloat16 else "FP16"
119- kv_type_str = "HIF8" if params['ori_kv_type'] == torch.uint8 else "FP8_E4M3FN"157+ kv_type_str = "HIF8" if params["ori_kv_type"] == torch.uint8 else "FP8_E4M3FN"
120 Testcase_Name = f"quantSparseFlashMla_{params['template_run_mode']}_{ops_mode}_{params['layout_q']}_{q_type_str}_{params['layout_kv']}_{kv_type_str}_{params['B']}_{params['N1']}_{params['N2']}_{params['S1']}_{params['S2']}_{params['D']}_{params['K']}_{case_id:06d}"158 Testcase_Name = f"quantSparseFlashMla_{params['template_run_mode']}_{ops_mode}_{params['layout_q']}_{q_type_str}_{params['layout_kv']}_{kv_type_str}_{params['B']}_{params['N1']}_{params['N2']}_{params['S1']}_{params['S2']}_{params['D']}_{params['K']}_{case_id:06d}"
121- params['Testcase_Name'] = Testcase_Name159+ params["Testcase_Name"] = Testcase_Name
122 logging.info(f"input_params: {params}")160 logging.info(f"input_params: {params}")
123 161 
124 # 输入参数的合法性校验162 # 输入参数的合法性校验
@@ -128,18 +166,21 @@ def qsmla(param_combinations):
128 pytest.skip(f"输入参数校验失败:{e}")166 pytest.skip(f"输入参数校验失败:{e}")
129 167 
130 # 生成测试数据168 # 生成测试数据
131- input_data = quant_sparse_flash_mla_golden.generate_and_save_testdata(params, save_pt=True, save_path=save_path)169+ quant_sparse_flash_mla_golden.generate_and_save_testdata(
170+ params, save_pt=True, save_path=save_path
171+ )
132 case_id += 1172 case_id += 1
133 173 
174+ 
134@pytest.mark.ci175@pytest.mark.ci
135@pytest.mark.parametrize("param_combinations", param_combinations)176@pytest.mark.parametrize("param_combinations", param_combinations)
136-def test_quant_sparse_flash_mla(param_combinations): # 初始化参数和tensor177+def test_quant_sparse_flash_mla(param_combinations): # 初始化参数和tensor
137 # 线程池178 # 线程池
138 with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:179 with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
139 futures = executor.submit(qsmla, param_combinations)180 futures = executor.submit(qsmla, param_combinations)
140 # 等待并获取结果181 # 等待并获取结果
141 for future in concurrent.futures.as_completed([futures]):182 for future in concurrent.futures.as_completed([futures]):
142 try:183 try:
143- result = future.result()184+ future.result()
144- except Exception as e:185+ except Exception:
145- pytest.fail(f"当前用例线程执行失败")186+ pytest.fail("当前用例线程执行失败")
@@ -14,53 +14,70 @@ import logging
14import math14import math
15import torch15import torch
16 16 
17-logging.basicConfig(level=logging.INFO, format='%(message)s', force=True)17+logging.basicConfig(level=logging.INFO, format="%(message)s", force=True)
18logger = logging.getLogger(__name__)18logger = logging.getLogger(__name__)
19 19 
20+ 
20def check_valid_param(params):21def check_valid_param(params):
21- if params.get('q_type') not in [torch.uint8]:22+ if params.get("q_type") not in [torch.uint8]:
22 raise ValueError("q_type should be: uint8")23 raise ValueError("q_type should be: uint8")
23 24 
24- if params.get('layout_q') not in ["BSND", "TND"]:25+ if params.get("layout_q") not in ["BSND", "TND"]:
25 raise ValueError(f"不支持的Q shape: {params.get('layout_q')}")26 raise ValueError(f"不支持的Q shape: {params.get('layout_q')}")
26 27 
27- if params.get('layout_kv') not in ["BSND", "PA_BBND", "TND"]:28+ if params.get("layout_kv") not in ["BSND", "PA_BBND", "TND"]:
28 raise ValueError(f"不支持的KV shape: {params.get('layout_kv')}")29 raise ValueError(f"不支持的KV shape: {params.get('layout_kv')}")
29 30 
30- if params.get('template_run_mode') not in ["CSA", "HCA", "SWA"]:31+ if params.get("template_run_mode") not in ["CSA", "HCA", "SWA"]:
31- raise ValueError(f"不支持的template_run_mode: {params.get('template_run_mode')}")32+ raise ValueError(
33+ f"不支持的template_run_mode: {params.get('template_run_mode')}"
34+ )
32 35 
33- B = params.get('B')36+ B = params.get("B")
34- cmp_ratio = params.get('cmp_ratio')37+ cmp_ratio = params.get("cmp_ratio")
35 38 
36- if params.get('layout_q') == "TND":39+ if params.get("layout_q") == "TND":
37- cu_seqlens_q = params.get('cu_seqlens_q')40+ cu_seqlens_q = params.get("cu_seqlens_q")
38- T1 = params.get('T1')41+ T1 = params.get("T1")
39 if cu_seqlens_q is None or T1 is None:42 if cu_seqlens_q is None or T1 is None:
40 raise ValueError("layout_q为TND时,cu_seqlens_q和T1不能为None")43 raise ValueError("layout_q为TND时,cu_seqlens_q和T1不能为None")
41 if cu_seqlens_q[-1] != T1:44 if cu_seqlens_q[-1] != T1:
42- raise ValueError(f"cu_seqlens_q最后一维({cu_seqlens_q[-1]})与T1({T1})不一致")45+ raise ValueError(
46+ f"cu_seqlens_q最后一维({cu_seqlens_q[-1]})与T1({T1})不一致"
47+ )
43 if len(cu_seqlens_q) != B + 1:48 if len(cu_seqlens_q) != B + 1:
44 raise ValueError(f"cu_seqlens_q长度({len(cu_seqlens_q)})应等于B+1({B + 1})")49 raise ValueError(f"cu_seqlens_q长度({len(cu_seqlens_q)})应等于B+1({B + 1})")
45 50 
46- if params.get('layout_kv') == "TND":51+ if params.get("layout_kv") == "TND":
47- cu_seqlens_ori_kv = params.get('cu_seqlens_ori_kv')52+ cu_seqlens_ori_kv = params.get("cu_seqlens_ori_kv")
48 if cu_seqlens_ori_kv is None:53 if cu_seqlens_ori_kv is None:
49 raise ValueError("layout_kv为TND时,cu_seqlens_ori_kv不能为None")54 raise ValueError("layout_kv为TND时,cu_seqlens_ori_kv不能为None")
50 T2 = cu_seqlens_ori_kv[-1]55 T2 = cu_seqlens_ori_kv[-1]
51 if len(cu_seqlens_ori_kv) != B + 1:56 if len(cu_seqlens_ori_kv) != B + 1:
52- raise ValueError(f"cu_seqlens_ori_kv长度({len(cu_seqlens_ori_kv)})应等于B+1({B + 1})")57+ raise ValueError(
53- if not all(cu_seqlens_ori_kv[i] <= cu_seqlens_ori_kv[i + 1] for i in range(len(cu_seqlens_ori_kv) - 1)):58+ f"cu_seqlens_ori_kv长度({len(cu_seqlens_ori_kv)})应等于B+1({B + 1})"
59+ )
60+ if not all(
61+ cu_seqlens_ori_kv[i] <= cu_seqlens_ori_kv[i + 1]
62+ for i in range(len(cu_seqlens_ori_kv) - 1)
63+ ):
54 raise ValueError(f"cu_seqlens_ori_kv必须单调递增: {cu_seqlens_ori_kv}")64 raise ValueError(f"cu_seqlens_ori_kv必须单调递增: {cu_seqlens_ori_kv}")
55 65 
56- cu_seqlens_cmp_kv = params.get('cu_seqlens_cmp_kv')66+ cu_seqlens_cmp_kv = params.get("cu_seqlens_cmp_kv")
57 if cu_seqlens_cmp_kv is not None:67 if cu_seqlens_cmp_kv is not None:
58 T3 = cu_seqlens_cmp_kv[-1]68 T3 = cu_seqlens_cmp_kv[-1]
59 if len(cu_seqlens_cmp_kv) != B + 1:69 if len(cu_seqlens_cmp_kv) != B + 1:
60- raise ValueError(f"cu_seqlens_cmp_kv长度({len(cu_seqlens_cmp_kv)})应等于B+1({B + 1})")70+ raise ValueError(
61- if not all(cu_seqlens_cmp_kv[i] <= cu_seqlens_cmp_kv[i + 1] for i in range(len(cu_seqlens_cmp_kv) - 1)):71+ f"cu_seqlens_cmp_kv长度({len(cu_seqlens_cmp_kv)})应等于B+1({B + 1})"
72+ )
73+ if not all(
74+ cu_seqlens_cmp_kv[i] <= cu_seqlens_cmp_kv[i + 1]
75+ for i in range(len(cu_seqlens_cmp_kv) - 1)
76+ ):
62 raise ValueError(f"cu_seqlens_cmp_kv必须单调递增: {cu_seqlens_cmp_kv}")77 raise ValueError(f"cu_seqlens_cmp_kv必须单调递增: {cu_seqlens_cmp_kv}")
63 if cmp_ratio is not None and cmp_ratio != 1:78 if cmp_ratio is not None and cmp_ratio != 1:
64 expected_T3 = math.floor(T2 / cmp_ratio)79 expected_T3 = math.floor(T2 / cmp_ratio)
65 if T3 != expected_T3:80 if T3 != expected_T3:
66- raise ValueError(f"cu_seqlens_cmp_kv最后一维({T3})与预期T3({expected_T3})不一致, T2={T2}, cmp_ratio={cmp_ratio}")81+ raise ValueError(
82+ f"cu_seqlens_cmp_kv最后一维({T3})与预期T3({expected_T3})不一致, T2={T2}, cmp_ratio={cmp_ratio}"
83+ )
@@ -14,11 +14,11 @@ import os
14import glob14import glob
15import pandas as pd15import pandas as pd
16from pathlib import Path16from pathlib import Path
17-import numpy as np
18import argparse17import argparse
19import shutil18import shutil
20import logging19import logging
21 20 
21+ 
22def process_profiler_data(args):22def process_profiler_data(args):
23 """23 """
24 读取性能数据写入test result表格24 读取性能数据写入test result表格
@@ -26,7 +26,9 @@ def process_profiler_data(args):
26 logging.info("=============开始处理性能分析数据=============")26 logging.info("=============开始处理性能分析数据=============")
27 27 
28 # 检查是否存在PROF开头的文件夹28 # 检查是否存在PROF开头的文件夹
29- prof_folders = [f for f in os.listdir() if os.path.isdir(f) and f.startswith('PROF')]29+ prof_folders = [
30+ f for f in os.listdir() if os.path.isdir(f) and f.startswith("PROF")
31+ ]
30 32 
31 if not prof_folders:33 if not prof_folders:
32 logging.warning("PROF文件夹不存在")34 logging.warning("PROF文件夹不存在")
@@ -36,18 +38,22 @@ def process_profiler_data(args):
36 logging.info(f"PROF path: {prof_folder}")38 logging.info(f"PROF path: {prof_folder}")
37 39 
38 profiler_output_path = os.path.join(prof_folder, "mindstudio_profiler_output")40 profiler_output_path = os.path.join(prof_folder, "mindstudio_profiler_output")
39- if not os.path.exists(profiler_output_path) or not os.path.isdir(profiler_output_path):41+ if not os.path.exists(profiler_output_path) or not os.path.isdir(
42+ profiler_output_path
43+ ):
40 logging.warning(f"在 {prof_folder} 中不存在mindstudio_profiler_output文件夹")44 logging.warning(f"在 {prof_folder} 中不存在mindstudio_profiler_output文件夹")
41 return45 return
42 46 
43 # 检查是否存在op_summary开头的表格47 # 检查是否存在op_summary开头的表格
44 op_summary_files = []48 op_summary_files = []
45- for ext in ['.csv']:49+ for ext in [".csv"]:
46 pattern = os.path.join(profiler_output_path, f"op_summary*{ext}")50 pattern = os.path.join(profiler_output_path, f"op_summary*{ext}")
47 op_summary_files.extend(glob.glob(pattern))51 op_summary_files.extend(glob.glob(pattern))
48 52 
49 if not op_summary_files:53 if not op_summary_files:
50- logging.warning(f"在 {profiler_output_path} 中未找到 op_summary 开头的表格文件,直接返回")54+ logging.warning(
55+ f"在 {profiler_output_path} 中未找到 op_summary 开头的表格文件,直接返回"
56+ )
51 return57 return
52 58 
53 op_summary_file = op_summary_files[0]59 op_summary_file = op_summary_files[0]
@@ -55,7 +61,7 @@ def process_profiler_data(args):
55 61 
56 # 读取表格A (op_summary)62 # 读取表格A (op_summary)
57 try:63 try:
58- if op_summary_file.endswith('.csv'):64+ if op_summary_file.endswith(".csv"):
59 df_a = pd.read_csv(op_summary_file)65 df_a = pd.read_csv(op_summary_file)
60 66 
61 except Exception as e:67 except Exception as e:
@@ -92,10 +98,10 @@ def process_profiler_data(args):
92 df_b["perf_result"] = ""98 df_b["perf_result"] = ""
93 99 
94 for i in range(df_b.shape[0]):100 for i in range(df_b.shape[0]):
95- a_row1_idx = 2 * row_idx # 当前case metadata性能数据101+ a_row1_idx = 2 * row_idx # 当前case metadata性能数据
96- a_row2_idx = 2 * row_idx + 1 # 当前case qsmla性能数据102+ a_row2_idx = 2 * row_idx + 1 # 当前case qsmla性能数据
97 103 
98- if df_b.iloc[i]["result"] != "NPU ERROR": # NPU ERROR时跳过104+ if df_b.iloc[i]["result"] != "NPU ERROR": # NPU ERROR时跳过
99 cur_metadata_perf = df_a.iloc[a_row1_idx][task_duration_col]105 cur_metadata_perf = df_a.iloc[a_row1_idx][task_duration_col]
100 df_b.at[i, "metadata_duration"] = cur_metadata_perf106 df_b.at[i, "metadata_duration"] = cur_metadata_perf
101 cur_qsmla_perf = df_a.iloc[a_row2_idx][task_duration_col]107 cur_qsmla_perf = df_a.iloc[a_row2_idx][task_duration_col]
@@ -121,11 +127,14 @@ def process_profiler_data(args):
121 if i % 10 == 0:127 if i % 10 == 0:
122 logging.info(f"已处理 {i}/{df_b.shape[0]} 行")128 logging.info(f"已处理 {i}/{df_b.shape[0]} 行")
123 129 
124- logging.info(f"数据合并完成,为表格B添加了 {df_b.shape[0]} 行的 metadata_duration 和 qsmla_duration 数据")130+ logging.info(
131+ f"数据合并完成,为表格B添加了 {df_b.shape[0]} 行的 metadata_duration 和 qsmla_duration 数据"
132+ )
125 133 
126 except Exception as e:134 except Exception as e:
127 logging.warning(f"数据合并过程中出错: {e}")135 logging.warning(f"数据合并过程中出错: {e}")
128 import traceback136 import traceback
137+ 
129 traceback.print_exc()138 traceback.print_exc()
130 return139 return
131 140 
@@ -134,7 +143,7 @@ def process_profiler_data(args):
134 if os.path.exists(new_result_path):143 if os.path.exists(new_result_path):
135 try:144 try:
136 os.remove(new_result_path)145 os.remove(new_result_path)
137- logging.info(f"发现历史result_perf文件,删除成功")146+ logging.info("发现历史result_perf文件,删除成功")
138 except Exception as e:147 except Exception as e:
139 logging.warning(f"历史result_perf文件删除失败: {e}")148 logging.warning(f"历史result_perf文件删除失败: {e}")
140 try:149 try:
@@ -145,7 +154,9 @@ def process_profiler_data(args):
145 logging.warning(f"保存文件失败: {e}")154 logging.warning(f"保存文件失败: {e}")
146 return155 return
147 156 
148- logging.info("=================处理完成!性能失败用例如下=================\n", perf_fail_list)157+ logging.info(
158+ "=================处理完成!性能失败用例如下=================\n", perf_fail_list
159+ )
149 160 
150 prof_folder = Path(prof_folder)161 prof_folder = Path(prof_folder)
151 if args.delete_perf_file and prof_folder.exists() and prof_folder.is_dir():162 if args.delete_perf_file and prof_folder.exists() and prof_folder.is_dir():
@@ -157,16 +168,42 @@ def process_profiler_data(args):
157 168 
158 return new_result_path169 return new_result_path
159 170 
171+ 
160# 命令行接口172# 命令行接口
161def main():173def main():
162- parser = argparse.ArgumentParser(description='处理性能数据')174+ parser = argparse.ArgumentParser(description="处理性能数据")
163- parser.add_argument('--test_result_path', type=str, default="result.xlsx", help='结果表格路径', required=False)175+ parser.add_argument(
164- parser.add_argument('--is_compare', type=bool, default=False, help='是否与基线表格对比', required=False)176+ "--test_result_path",
165- parser.add_argument('--perf_golden_path', type=str, default="perf_golden.xlsx", help='性能基线数据表格路径', required=False)177+ type=str,
166- parser.add_argument('--delete_perf_file', type=bool, default=False, help='是否删除PROF文件夹内容', required=False)178+ default="result.xlsx",
179+ help="结果表格路径",
180+ required=False,
181+ )
182+ parser.add_argument(
183+ "--is_compare",
184+ type=bool,
185+ default=False,
186+ help="是否与基线表格对比",
187+ required=False,
188+ )
189+ parser.add_argument(
190+ "--perf_golden_path",
191+ type=str,
192+ default="perf_golden.xlsx",
193+ help="性能基线数据表格路径",
194+ required=False,
195+ )
196+ parser.add_argument(
197+ "--delete_perf_file",
198+ type=bool,
199+ default=False,
200+ help="是否删除PROF文件夹内容",
201+ required=False,
202+ )
167 args = parser.parse_args()203 args = parser.parse_args()
168 204 
169 process_profiler_data(args)205 process_profiler_data(args)
170 206 
207+ 
171if __name__ == "__main__":208if __name__ == "__main__":
172- main()209+ main()
@@ -12,9 +12,6 @@
12 12 
13import os13import os
14import torch14import torch
15-import torch_npu
16-import check_valid_param
17-import pytest
18import random15import random
19import numpy as np16import numpy as np
20import math17import math
@@ -31,6 +28,7 @@ DATA_RANGE_RIGHT = 2
31quant_param_range_left = DATA_RANGE_LEFT / -1 # = 2.028quant_param_range_left = DATA_RANGE_LEFT / -1 # = 2.0
32quant_param_range_right = DATA_RANGE_RIGHT / 1 # = 2.029quant_param_range_right = DATA_RANGE_RIGHT / 1 # = 2.0
33 30 
31+ 
34class GeneralizedSFAQuant:32class GeneralizedSFAQuant:
35 def __init__(33 def __init__(
36 self,34 self,
@@ -113,8 +111,20 @@ class GeneralizedSFAQuant:
113 seqused_cmp_kv,111 seqused_cmp_kv,
114 cmp_residual_kv,112 cmp_residual_kv,
115 sinks,113 sinks,
114+ return_softmax_lse=False,
116 ):115 ):
117 attn_out = torch.zeros(q_bnsd.shape, dtype=q_bnsd.dtype)116 attn_out = torch.zeros(q_bnsd.shape, dtype=q_bnsd.dtype)
117+ softmax_lse = None
118+ if return_softmax_lse:
119+ softmax_lse = torch.zeros(
120+ (
121+ q_bnsd.shape[0],
122+ ori_k_bnsd.shape[1],
123+ q_bnsd.shape[2],
124+ q_bnsd.shape[1] // ori_k_bnsd.shape[1],
125+ ),
126+ dtype=torch.float32,
127+ )
118 B = q_bnsd.shape[0]128 B = q_bnsd.shape[0]
119 act_q = self.seqused_q129 act_q = self.seqused_q
120 G = int(self.N1 / self.N2)130 G = int(self.N1 / self.N2)
@@ -125,12 +135,16 @@ class GeneralizedSFAQuant:
125 cur_act_q = act_q[i_B]135 cur_act_q = act_q[i_B]
126 cur_ori_act_kv = seqused_ori_kv[i_B]136 cur_ori_act_kv = seqused_ori_kv[i_B]
127 cur_cmp_act_kv = seqused_cmp_kv[i_B] if seqused_cmp_kv is not None else 0137 cur_cmp_act_kv = seqused_cmp_kv[i_B] if seqused_cmp_kv is not None else 0
128- cur_cmp_residual = cmp_residual_kv[i_B] if cmp_residual_kv is not None else 0138+ cur_cmp_residual = (
139+ cmp_residual_kv[i_B] if cmp_residual_kv is not None else 0
140+ )
129 cur_cmp_restored = cur_cmp_act_kv * self.cmp_ratio + cur_cmp_residual141 cur_cmp_restored = cur_cmp_act_kv * self.cmp_ratio + cur_cmp_residual
130 142 
131 for i_N2 in range(self.N2):143 for i_N2 in range(self.N2):
132 logging.info(f" i_N2 = {i_N2}/{self.N2}")144 logging.info(f" i_N2 = {i_N2}/{self.N2}")
133- cur_sinks = sinks[i_N2 * G : (i_N2 + 1) * G] if sinks is not None else None145+ cur_sinks = (
146+ sinks[i_N2 * G : (i_N2 + 1) * G] if sinks is not None else None
147+ )
134 for i_S1 in range(cur_act_q):148 for i_S1 in range(cur_act_q):
135 milestones = [149 milestones = [
136 int(cur_act_q * pct / 100) for pct in range(10, 101, 10)150 int(cur_act_q * pct / 100) for pct in range(10, 101, 10)
@@ -164,7 +178,7 @@ class GeneralizedSFAQuant:
164 and cmp_sparse_indices_bnsd is not None178 and cmp_sparse_indices_bnsd is not None
165 ):179 ):
166 topk_id = cmp_sparse_indices_bnsd[i_B, i_N2, i_S1, :]180 topk_id = cmp_sparse_indices_bnsd[i_B, i_N2, i_S1, :]
167- empty_flag, cur_cmp_k = self.gather_cmp_kv(181+ _, cur_cmp_k = self.gather_cmp_kv(
168 cmp_k_bnsd,182 cmp_k_bnsd,
169 topk_id,183 topk_id,
170 i_B,184 i_B,
@@ -174,11 +188,10 @@ class GeneralizedSFAQuant:
174 cur_act_q,188 cur_act_q,
175 )189 )
176 elif self.template_run_mode == "HCA":190 elif self.template_run_mode == "HCA":
177- empty_flag, cur_cmp_k = self.mask_cmp_kv(191+ _, cur_cmp_k = self.mask_cmp_kv(
178 cmp_k_bnsd, i_B, i_N2, i_S1, cur_cmp_restored, cur_act_q192 cmp_k_bnsd, i_B, i_N2, i_S1, cur_cmp_restored, cur_act_q
179 )193 )
180 else:194 else:
181- empty_flag = True
182 cur_cmp_k = []195 cur_cmp_k = []
183 if cur_cmp_k == []:196 if cur_cmp_k == []:
184 cmp_s2_loop_time = 0197 cmp_s2_loop_time = 0
@@ -195,7 +208,11 @@ class GeneralizedSFAQuant:
195 # hifp8FullQuant: online softmax with hif8 quantized attention scores208 # hifp8FullQuant: online softmax with hif8 quantized attention scores
196 hifp8_scale_value = 16.0209 hifp8_scale_value = 16.0
197 score_max_pre = torch.ones((G,)).to(torch.float) * (-torch.inf)210 score_max_pre = torch.ones((G,)).to(torch.float) * (-torch.inf)
198- score_max = cur_sinks.clone() if cur_sinks is not None else torch.ones((G,)).to(torch.float) * (-torch.inf)211+ score_max = (
212+ cur_sinks.clone()
213+ if cur_sinks is not None
214+ else torch.ones((G,)).to(torch.float) * (-torch.inf)
215+ )
199 acc_o = torch.zeros((G, self.D)).to(torch.float32)216 acc_o = torch.zeros((G, self.D)).to(torch.float32)
200 sumexp = torch.ones((G,)).to(torch.float32)217 sumexp = torch.ones((G,)).to(torch.float32)
201 218 
@@ -210,8 +227,9 @@ class GeneralizedSFAQuant:
210 else: # cmp_kv227 else: # cmp_kv
211 if i_S2 < total_s2_loop_time - 1:228 if i_S2 < total_s2_loop_time - 1:
212 k_tile = cur_cmp_k_fp32[229 k_tile = cur_cmp_k_fp32[
213- (i_S2 - ori_s2_loop_time)230+ (i_S2 - ori_s2_loop_time) * s2_base_size : (
214- * s2_base_size : (i_S2 - ori_s2_loop_time + 1)231+ i_S2 - ori_s2_loop_time + 1
232+ )
215 * s2_base_size,233 * s2_base_size,
216 :,234 :,
217 ]235 ]
@@ -223,12 +241,20 @@ class GeneralizedSFAQuant:
223 # MM1241 # MM1
224 mm1_res = torch.matmul(q_curr_fp32, k_tile.T)242 mm1_res = torch.matmul(q_curr_fp32, k_tile.T)
225 # scale过程与NPU一致 保证精度统一243 # scale过程与NPU一致 保证精度统一
226- is_cmp_tile = (i_S2 >= ori_s2_loop_time)244+ is_cmp_tile = i_S2 >= ori_s2_loop_time
227 if is_cmp_tile:245 if is_cmp_tile:
228- combined_scale = self.softmax_scale * self.q_descale_val * self.cmp_kv_descale_val246+ combined_scale = (
247+ self.softmax_scale
248+ * self.q_descale_val
249+ * self.cmp_kv_descale_val
250+ )
229 cur_v_descale = self.cmp_kv_descale_val251 cur_v_descale = self.cmp_kv_descale_val
230 else:252 else:
231- combined_scale = self.softmax_scale * self.q_descale_val * self.ori_kv_descale_val253+ combined_scale = (
254+ self.softmax_scale
255+ * self.q_descale_val
256+ * self.ori_kv_descale_val
257+ )
232 cur_v_descale = self.ori_kv_descale_val258 cur_v_descale = self.ori_kv_descale_val
233 scale_res = mm1_res * combined_scale259 scale_res = mm1_res * combined_scale
234 260 
@@ -255,8 +281,14 @@ class GeneralizedSFAQuant:
255 281 
256 acc_o = torch.div(acc_o, sumexp.unsqueeze(1))282 acc_o = torch.div(acc_o, sumexp.unsqueeze(1))
257 acc_o = acc_o / hifp8_scale_value283 acc_o = acc_o / hifp8_scale_value
258- attn_out[i_B, i_N2 * G : (i_N2 + 1) * G, i_S1, :] = acc_o.to(torch.bfloat16)284+ attn_out[i_B, i_N2 * G : (i_N2 + 1) * G, i_S1, :] = acc_o.to(
259- return attn_out285+ torch.bfloat16
286+ )
287+ if return_softmax_lse:
288+ softmax_lse[i_B, i_N2, i_S1, :] = score_max + torch.log(
289+ sumexp + 1e-10
290+ )
291+ return attn_out, softmax_lse
260 292 
261 def gather_cmp_kv(293 def gather_cmp_kv(
262 self,294 self,
@@ -323,7 +355,6 @@ class GeneralizedSFAQuant:
323 tensor = tensor.permute(0, 2, 1, 3)355 tensor = tensor.permute(0, 2, 1, 3)
324 return tensor, [B, N, S, D]356 return tensor, [B, N, S, D]
325 elif layout in ["TND"]:357 elif layout in ["TND"]:
326- T = shape[0]
327 N = shape[1]358 N = shape[1]
328 D = shape[2]359 D = shape[2]
329 B = len(cu_seqlens_q) - 1360 B = len(cu_seqlens_q) - 1
@@ -377,6 +408,34 @@ class GeneralizedSFAQuant:
377 else:408 else:
378 return tensor409 return tensor
379 410 
411+ def lse_trans_bnsd_to_target_layout(self, tensor, layout, act_seq=None):
412+ if layout in ["BSND"]: # B N S G
413+ return tensor
414+ elif layout in ["TND"]: # B N2 S1 G --> T1 N2 G --> N2 T1 G
415+ T = act_seq[-1]
416+ B = tensor.shape[0]
417+ N2 = tensor.shape[1]
418+ G = tensor.shape[3]
419+ output = torch.zeros((N2, T, G), dtype=torch.float)
420+ t_start = 0
421+ act_seq_per_batch = prefix_sum_to_original(
422+ act_seq
423+ ) # prefix_sum_to_original 还原成每个batch的真实长度
424+ for b_index in range(B):
425+ cur_act_seq = act_seq_per_batch[b_index]
426+ t_end = t_start + cur_act_seq
427+ if cur_act_seq == 0:
428+ continue
429+ for n_index in range(N2):
430+ output[n_index, t_start:t_end, :] = tensor[
431+ b_index, n_index, :cur_act_seq, :
432+ ]
433+ t_start += cur_act_seq
434+ output = output.transpose(0, 1).contiguous()
435+ return output
436+ else:
437+ return tensor
438+ 
380 def forward(439 def forward(
381 self,440 self,
382 q,441 q,
@@ -388,6 +447,7 @@ class GeneralizedSFAQuant:
388 seqused_cmp_kv,447 seqused_cmp_kv,
389 cmp_residual_kv,448 cmp_residual_kv,
390 sinks,449 sinks,
450+ return_softmax_lse,
391 ):451 ):
392 logging.info("cpu执行中...")452 logging.info("cpu执行中...")
393 logging.info(f"template_run_mode = {self.template_run_mode}")453 logging.info(f"template_run_mode = {self.template_run_mode}")
@@ -408,7 +468,7 @@ class GeneralizedSFAQuant:
408 )468 )
409 )469 )
410 470 
411- attn_out = self.calculate_by_bnsd(471+ attn_out, softmax_lse = self.calculate_by_bnsd(
412 q_bnsd,472 q_bnsd,
413 ori_k_bnsd,473 ori_k_bnsd,
414 cmp_k_bnsd,474 cmp_k_bnsd,
@@ -418,12 +478,17 @@ class GeneralizedSFAQuant:
418 seqused_cmp_kv,478 seqused_cmp_kv,
419 cmp_residual_kv,479 cmp_residual_kv,
420 sinks,480 sinks,
481+ return_softmax_lse,
421 )482 )
422 483 
423 attn_out = self.trans_bnsd_to_target_layout(484 attn_out = self.trans_bnsd_to_target_layout(
424 attn_out, self.layout_q, cu_seqlens_q, self.seqused_q485 attn_out, self.layout_q, cu_seqlens_q, self.seqused_q
425 )486 )
426- return attn_out487+ if return_softmax_lse:
488+ softmax_lse = self.lse_trans_bnsd_to_target_layout(
489+ softmax_lse, self.layout_q, cu_seqlens_q
490+ )
491+ return attn_out, softmax_lse
427 492 
428 493 
429def prefix_sum_to_original(cu_seqlens_q):494def prefix_sum_to_original(cu_seqlens_q):
@@ -489,7 +554,9 @@ def get_max_adjacent_diff(cu_seqlens_q):
489 return max_diff554 return max_diff
490 555 
491 556 
492-def gen_cmp_sparse_indices_bsnd(cmp_ratio, B, S1, N2, K, cmp_restored_len, seqused_q, cmp_mask_mode):557+def gen_cmp_sparse_indices_bsnd(
558+ cmp_ratio, B, S1, N2, K, cmp_restored_len, seqused_q, cmp_mask_mode
559+):
493 # 有效索引在叠加了causal后有效tokens中选取,不足sparse_block_count,尾部填充-1560 # 有效索引在叠加了causal后有效tokens中选取,不足sparse_block_count,尾部填充-1
494 cmp_sparse_indices = torch.full((B, S1, N2, K), fill_value=-1, dtype=torch.int32)561 cmp_sparse_indices = torch.full((B, S1, N2, K), fill_value=-1, dtype=torch.int32)
495 for i_B in range(B):562 for i_B in range(B):
@@ -736,7 +803,9 @@ def gen_cmp_kv(
736 # generate cmp_sparse_indices803 # generate cmp_sparse_indices
737 cmp_sparse_indices = None804 cmp_sparse_indices = None
738 if template_run_mode == "CSA" and cmp_max_s2 != 0:805 if template_run_mode == "CSA" and cmp_max_s2 != 0:
739- cmp_restored_len = [seqused_cmp_kv[i] * cmp_ratio + cmp_residual_kv[i] for i in range(B)]806+ cmp_restored_len = [
807+ seqused_cmp_kv[i] * cmp_ratio + cmp_residual_kv[i] for i in range(B)
808+ ]
740 if layout_q == "BSND":809 if layout_q == "BSND":
741 cmp_sparse_indices = gen_cmp_sparse_indices_bsnd(810 cmp_sparse_indices = gen_cmp_sparse_indices_bsnd(
742 cmp_ratio, B, S1, N2, K, cmp_restored_len, seqused_q, cmp_mask_mode811 cmp_ratio, B, S1, N2, K, cmp_restored_len, seqused_q, cmp_mask_mode
@@ -824,7 +893,7 @@ def generate_and_save_testdata(params, save_pt=False, save_path=""):
824 return_softmax_lse = params.get("return_softmax_lse", False)893 return_softmax_lse = params.get("return_softmax_lse", False)
825 quant_mode = params.get("quant_mode", False)894 quant_mode = params.get("quant_mode", False)
826 isSink = params.get("isSink", True)895 isSink = params.get("isSink", True)
827- 896+ return_softmax_lse = params.get("return_softmax_lse", False)
828 cu_seqlens_q = torch.tensor(cu_seqlens_q).to(torch.int32)897 cu_seqlens_q = torch.tensor(cu_seqlens_q).to(torch.int32)
829 seqused_q = torch.tensor(seqused_q).to(torch.int32)898 seqused_q = torch.tensor(seqused_q).to(torch.int32)
830 seqused_ori_kv = torch.tensor(seqused_ori_kv).to(torch.int32)899 seqused_ori_kv = torch.tensor(seqused_ori_kv).to(torch.int32)
@@ -927,11 +996,13 @@ def generate_and_save_testdata(params, save_pt=False, save_path=""):
927 cmp_k_bnsd = None996 cmp_k_bnsd = None
928 cmp_kv_descale = None997 cmp_kv_descale = None
929 998 
930- if cmp_k_bnsd is None: # 如果cmp_k_bnsd为None999+ if cmp_k_bnsd is None: # 如果cmp_k_bnsd为None
931- cmp_mask_mode = 0 # cmp_mask_mode 设置为0,防止拦截1000+ cmp_mask_mode = 0 # cmp_mask_mode 设置为0,防止拦截
932- if layout_kv == "PA_BBND" and (1001+ if (
933- template_run_mode == "HCA" or template_run_mode == "CSA"1002+ layout_kv == "PA_BBND"
934- ) and cmp_k_in_pa_shape is not None:1003+ and (template_run_mode == "HCA" or template_run_mode == "CSA")
1004+ and cmp_k_in_pa_shape is not None
1005+ ):
935 total_block = block_size1 + block_size21006 total_block = block_size1 + block_size2
936 fusion_base = torch.zeros((block_num, total_block, N2, D), dtype=ori_kv_type)1007 fusion_base = torch.zeros((block_num, total_block, N2, D), dtype=ori_kv_type)
937 fusion_base[:, :block_size1, :, :] = ori_k_in_pa_shape1008 fusion_base[:, :block_size1, :, :] = ori_k_in_pa_shape
@@ -941,14 +1012,16 @@ def generate_and_save_testdata(params, save_pt=False, save_path=""):
941 stride_n2 = D1012 stride_n2 = D
942 stride_d = 11013 stride_d = 1
943 ori_k_in_pa_shape = torch.as_strided(1014 ori_k_in_pa_shape = torch.as_strided(
944- fusion_base,1015+ fusion_base,
945- size=[block_num, block_size1, N2, D],1016+ size=[block_num, block_size1, N2, D],
946- stride=[stride_n, stride_bs, stride_n2, stride_d])1017+ stride=[stride_n, stride_bs, stride_n2, stride_d],
1018+ )
947 cmp_k_in_pa_shape = torch.as_strided(1019 cmp_k_in_pa_shape = torch.as_strided(
948- fusion_base,1020+ fusion_base,
949- size=[block_num, block_size2, N2, D],1021+ size=[block_num, block_size2, N2, D],
950- stride=[stride_n, stride_bs, stride_n2, stride_d],1022+ stride=[stride_n, stride_bs, stride_n2, stride_d],
951- storage_offset=block_size1 * N2 * D)1023+ storage_offset=block_size1 * N2 * D,
1024+ )
952 1025 
953 test_qsmla = GeneralizedSFAQuant(1026 test_qsmla = GeneralizedSFAQuant(
954 layout_q,1027 layout_q,
@@ -983,9 +1056,11 @@ def generate_and_save_testdata(params, save_pt=False, save_path=""):
983 template_run_mode,1056 template_run_mode,
984 q_descale_val=q_descale.item(),1057 q_descale_val=q_descale.item(),
985 ori_kv_descale_val=ori_kv_descale.item(),1058 ori_kv_descale_val=ori_kv_descale.item(),
986- cmp_kv_descale_val=cmp_kv_descale.item() if cmp_kv_descale is not None else None,1059+ cmp_kv_descale_val=cmp_kv_descale.item()
1060+ if cmp_kv_descale is not None
1061+ else None,
987 )1062 )
988- cpu_result = test_qsmla.forward(1063+ cpu_result, cpu_lse = test_qsmla.forward(
989 q,1064 q,
990 ori_k_bnsd,1065 ori_k_bnsd,
991 cmp_k_bnsd,1066 cmp_k_bnsd,
@@ -995,6 +1070,7 @@ def generate_and_save_testdata(params, save_pt=False, save_path=""):
995 seqused_cmp_kv,1070 seqused_cmp_kv,
996 cmp_residual_kv,1071 cmp_residual_kv,
997 sinks,1072 sinks,
1073+ return_softmax_lse,
998 )1074 )
999 1075 
1000 logging.info("mode:%s\n", template_run_mode)1076 logging.info("mode:%s\n", template_run_mode)
@@ -1058,7 +1134,9 @@ def generate_and_save_testdata(params, save_pt=False, save_path=""):
1058 "layout_q": layout_q,1134 "layout_q": layout_q,
1059 "layout_kv": layout_kv,1135 "layout_kv": layout_kv,
1060 "has_ori_kv": True,1136 "has_ori_kv": True,
1061- "has_cmp_kv": False if (template_run_mode == "SWA" or cmp_k_in_pa_shape is None) else True,1137+ "has_cmp_kv": False
1138+ if (template_run_mode == "SWA" or cmp_k_in_pa_shape is None)
1139+ else True,
1062 },1140 },
1063 "op_input": {1141 "op_input": {
1064 "q": q_npu,1142 "q": q_npu,
@@ -1091,6 +1169,7 @@ def generate_and_save_testdata(params, save_pt=False, save_path=""):
1091 "return_softmax_lse": return_softmax_lse,1169 "return_softmax_lse": return_softmax_lse,
1092 },1170 },
1093 "cpu_output": cpu_result,1171 "cpu_output": cpu_result,
1172+ "cpu_lse": cpu_lse if return_softmax_lse else None,
1094 }1173 }
1095 1174 
1096 if save_pt:1175 if save_pt:
@@ -2,7 +2,7 @@
2# -*- coding: utf-8 -*-2# -*- coding: utf-8 -*-
3# -----------------------------------------------------------------------------------------------------------3# -----------------------------------------------------------------------------------------------------------
4# Copyright (c) 2026 Huawei Technologies Co., Ltd.4# Copyright (c) 2026 Huawei Technologies Co., Ltd.
5-# This program is free software, you can redistribute it and/or it under the terms and conditions of5+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6# CANN Open Software License Agreement Version 2.0 (the "License").6# CANN Open Software License Agreement Version 2.0 (the "License").
7# Please refer to the License for details. You may not use this file except in compliance with the License.7# Please refer to the License for details. You may not use this file except in compliance with the License.
8# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,8# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
@@ -13,7 +13,7 @@
13import torch13import torch
14 14 
15TEST_PARAMS = {15TEST_PARAMS = {
16- "decode_first":{16+ "decode_first": {
17 "Testcase_Name": [None],17 "Testcase_Name": [None],
18 "layout_q": ["TND"],18 "layout_q": ["TND"],
19 "layout_kv": ["PA_BBND"],19 "layout_kv": ["PA_BBND"],
@@ -37,7 +37,11 @@ TEST_PARAMS = {
37 "seqused_cmp_kv": [None],37 "seqused_cmp_kv": [None],
38 "cu_seqlens_ori_kv": [None],38 "cu_seqlens_ori_kv": [None],
39 "cu_seqlens_cmp_kv": [None],39 "cu_seqlens_cmp_kv": [None],
40- "cmp_residual_kv": [[0,]],40+ "cmp_residual_kv": [
41+ [
42+ 0,
43+ ]
44+ ],
41 "softmax_scale": [0.04419417],45 "softmax_scale": [0.04419417],
42 "cmp_ratio": [4],46 "cmp_ratio": [4],
43 "ori_mask_mode": [4],47 "ori_mask_mode": [4],
@@ -46,12 +50,12 @@ TEST_PARAMS = {
46 "ori_win_right": [0],50 "ori_win_right": [0],
47 "quant_mode": [1],51 "quant_mode": [1],
48 "template_run_mode": ["CSA"],52 "template_run_mode": ["CSA"],
49- "actlen_mode":["full"],53+ "actlen_mode": ["full"],
50- "S1EQS2":[False],54+ "S1EQS2": [False],
51- "isSink":[True],55+ "isSink": [True],
56+ "return_softmax_lse": [True],
52 },57 },
53- 58+ "prefill_first": {
54- "prefill_first":{
55 "Testcase_Name": [None],59 "Testcase_Name": [None],
56 "layout_q": ["TND"],60 "layout_q": ["TND"],
57 "layout_kv": ["PA_BBND"],61 "layout_kv": ["PA_BBND"],
@@ -84,11 +88,12 @@ TEST_PARAMS = {
84 "ori_win_right": [0],88 "ori_win_right": [0],
85 "quant_mode": [1],89 "quant_mode": [1],
86 "template_run_mode": ["CSA"],90 "template_run_mode": ["CSA"],
87- "actlen_mode":["full"],91+ "actlen_mode": ["full"],
88- "S1EQS2":[False],92+ "S1EQS2": [False],
89- "isSink":[True],93+ "isSink": [True],
94+ "return_softmax_lse": [True],
90 },95 },
91- "csa_small_prefill":{96+ "csa_small_prefill": {
92 "Testcase_Name": [None],97 "Testcase_Name": [None],
93 "layout_q": ["TND"],98 "layout_q": ["TND"],
94 "layout_kv": ["PA_BBND"],99 "layout_kv": ["PA_BBND"],
@@ -121,11 +126,12 @@ TEST_PARAMS = {
121 "ori_win_right": [0],126 "ori_win_right": [0],
122 "quant_mode": [1],127 "quant_mode": [1],
123 "template_run_mode": ["CSA"],128 "template_run_mode": ["CSA"],
124- "actlen_mode":["full"],129+ "actlen_mode": ["full"],
125- "S1EQS2":[False],130+ "S1EQS2": [False],
126- "isSink":[True],131+ "isSink": [True],
127- }132+ "return_softmax_lse": [True],
133+ },
128}134}
129 135 
130ENABLED_PARAMS = [TEST_PARAMS["decode_first"]]136ENABLED_PARAMS = [TEST_PARAMS["decode_first"]]
131-#ENABLED_PARAMS = [TEST_PARAMS[key] for key in TEST_PARAMS.keys()]137+# ENABLED_PARAMS = [TEST_PARAMS[key] for key in TEST_PARAMS.keys()]
@@ -10,8 +10,6 @@
10# See LICENSE in the root of the software repository for the full text of the License.10# See LICENSE in the root of the software repository for the full text of the License.
11# -----------------------------------------------------------------------------------------------------------11# -----------------------------------------------------------------------------------------------------------
12 12 
13-import math
14-import random
15import logging13import logging
16import torch14import torch
17import datetime15import datetime
@@ -19,47 +17,86 @@ import os
19import sys17import sys
20import numpy as np18import numpy as np
21 19 
22-logging.basicConfig(level=logging.INFO, format='%(message)s', force=True)20+logging.basicConfig(level=logging.INFO, format="%(message)s", force=True)
23logger = logging.getLogger(__name__)21logger = logging.getLogger(__name__)
24 22 
25-def cal_relative_diff_np_isclose(real_data, expect_data, type_str='fp16'):23+ 
24+def cal_relative_diff_np_isclose(real_data, expect_data, type_str="fp16"):
26 diff = abs(float(real_data) - float(expect_data))25 diff = abs(float(real_data) - float(expect_data))
27 result = diff / (np.abs(expect_data) + 10e-10)26 result = diff / (np.abs(expect_data) + 10e-10)
28 return result27 return result
29 28 
30-def display_output_np_isclose(real_data, expect_data, start, end, expect_fp32_data=None):29+ 
30+def display_output_np_isclose(
31+ real_data, expect_data, start, end, expect_fp32_data=None
32+):
31 def display_inner(idx):33 def display_inner(idx):
32 j = idx + start34 j = idx + start
33- diff_rate = cal_relative_diff_np_isclose(35+ diff_rate = cal_relative_diff_np_isclose(real_data[j], expect_data[j])
34- real_data[j], expect_data[j])
35 36 
36 if "inf" in str(expect_data[j]) or "nan" in str(expect_data[j]):37 if "inf" in str(expect_data[j]) or "nan" in str(expect_data[j]):
37 diff_abs = "inf" if "inf" in str(expect_data[j]) else "nan"38 diff_abs = "inf" if "inf" in str(expect_data[j]) else "nan"
38 if expect_fp32_data is not None:39 if expect_fp32_data is not None:
39- print_log('%08d \t %-7s \t %-7s \t %-7s \t %-7s \t %-7s' % (40+ print_log(
40- start + idx + 1, expect_fp32_data[j], expect_data[j], real_data[j], diff_abs, diff_rate))41+ "%08d \t %-7s \t %-7s \t %-7s \t %-7s \t %-7s"
42+ % (
43+ start + idx + 1,
44+ expect_fp32_data[j],
45+ expect_data[j],
46+ real_data[j],
47+ diff_abs,
48+ diff_rate,
49+ )
50+ )
41 else:51 else:
42- print_log('%08d \t %-7s \t %-7s \t %-7s \t %-7s' % (52+ print_log(
43- start + idx + 1, expect_data[j], real_data[j], diff_abs, diff_rate))53+ "%08d \t %-7s \t %-7s \t %-7s \t %-7s"
54+ % (
55+ start + idx + 1,
56+ expect_data[j],
57+ real_data[j],
58+ diff_abs,
59+ diff_rate,
60+ )
61+ )
44 else:62 else:
45- diff_abs = abs(np.float64(63+ diff_abs = abs(np.float64(expect_data[j]) - np.float64(real_data[j]))
46- expect_data[j]) - np.float64(real_data[j]))
47 if expect_fp32_data is not None:64 if expect_fp32_data is not None:
48- print_log('%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f \t %0.7f' % (65+ print_log(
49- start + idx + 1, expect_fp32_data[j], expect_data[j], real_data[j], diff_abs, diff_rate))66+ "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f \t %0.7f"
67+ % (
68+ start + idx + 1,
69+ expect_fp32_data[j],
70+ expect_data[j],
71+ real_data[j],
72+ diff_abs,
73+ diff_rate,
74+ )
75+ )
50 else:76 else:
51- print_log('%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f' % (77+ print_log(
52- start + idx + 1, expect_data[j], real_data[j], diff_abs, diff_rate))78+ "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f"
79+ % (
80+ start + idx + 1,
81+ expect_data[j],
82+ real_data[j],
83+ diff_abs,
84+ diff_rate,
85+ )
86+ )
53 87 
54 print_log(88 print_log(
55- '---------------------------------------------------------------------------------------')89+ "---------------------------------------------------------------------------------------"
90+ )
56 if expect_fp32_data is not None:91 if expect_fp32_data is not None:
57 print_log(92 print_log(
58- 'Loop \t ExpFP32Out \t ExpFP16Out \t NPUOut \tFpDiff(min) \t RateDiff')93+ "Loop \t ExpFP32Out \t ExpFP16Out \t NPUOut \tFpDiff(min) \t RateDiff"
94+ )
59 else:95 else:
60- print_log('Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff')96+ print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff")
61 print_log(97 print_log(
62- '---------------------------------------------------------------------------------------')98+ "---------------------------------------------------------------------------------------"
99+ )
63 split_count = int(end - start)100 split_count = int(end - start)
64 if split_count <= 20:101 if split_count <= 20:
65 for i in range(split_count + 1):102 for i in range(split_count + 1):
@@ -67,60 +104,88 @@ def display_output_np_isclose(real_data, expect_data, start, end, expect_fp32_da
67 else:104 else:
68 for i in range(10):105 for i in range(10):
69 display_inner(i)106 display_inner(i)
70- print_log('... \t ... \t ... \t ... \t ...')107+ print_log("... \t ... \t ... \t ... \t ...")
71 for i in range(split_count - 10 + 1, split_count + 1):108 for i in range(split_count - 10 + 1, split_count + 1):
72 display_inner(i)109 display_inner(i)
73 110 
74-def print_log(data=None, level='INFO'):111+ 
75- print("[%s] [%s]-%s:%s - %s" % (datetime.datetime.now().strftime(112+def print_log(data=None, level="INFO"):
76- "%Y/%m/%d %H:%M:%S"), level, os.path.basename(sys._getframe().f_back.f_code.co_filename),113+ print(
77- str(sys._getframe().f_back.f_lineno).zfill(4), data))114+ "[%s] [%s]-%s:%s - %s"
115+ % (
116+ datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"),
117+ level,
118+ os.path.basename(sys._getframe().f_back.f_code.co_filename),
119+ str(sys._getframe().f_back.f_lineno).zfill(4),
120+ data,
121+ )
122+ )
123+ 
78 124 
79def display_error_output(real_data, expect_data, err_idx, relative_diff):125def display_error_output(real_data, expect_data, err_idx, relative_diff):
80 print_log(126 print_log(
81- 'Error Line-----------------------------------------------------------------------------')127+ "Error Line-----------------------------------------------------------------------------"
82- print_log('Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff')128+ )
129+ print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff")
83 print_log(130 print_log(
84- '---------------------------------------------------------------------------------------')131+ "---------------------------------------------------------------------------------------"
132+ )
85 count = 0133 count = 0
86 len_err = len(err_idx)134 len_err = len(err_idx)
87 for i in err_idx:135 for i in err_idx:
88 count += 1136 count += 1
89 if count < 10 or (90 < count < 100):137 if count < 10 or (90 < count < 100):
90- print_log('%08d \t %.7f \t %.7f \t %.7f \t %.7f' % (138+ print_log(
91- i, expect_data[i], real_data[i], abs(np.float64(139+ "%08d \t %.7f \t %.7f \t %.7f \t %.7f"
92- expect_data[i]) - np.float64(real_data[i])),140+ % (
93- relative_diff[count - 1]))141+ i,
142+ expect_data[i],
143+ real_data[i],
144+ abs(np.float64(expect_data[i]) - np.float64(real_data[i])),
145+ relative_diff[count - 1],
146+ )
147+ )
94 elif count == 10 or (count == 100 and len_err > 100):148 elif count == 10 or (count == 100 and len_err > 100):
95- dot_3 = '...'149+ dot_3 = "..."
96- print_log('%08s \t %07s \t %07s \t %07s \t %07s' %150+ print_log(
97- (dot_3, dot_3, dot_3, dot_3, dot_3))151+ "%08s \t %07s \t %07s \t %07s \t %07s"
152+ % (dot_3, dot_3, dot_3, dot_3, dot_3)
153+ )
98 elif count > 100:154 elif count > 100:
99 break155 break
100 156 
101 print_log(157 print_log(
102- 'Max-RE line:---------------------------------------------------------------------------')158+ "Max-RE line:---------------------------------------------------------------------------"
159+ )
103 max_error = max(relative_diff)160 max_error = max(relative_diff)
104 m_idx_list = err_idx[np.where(relative_diff == max_error)]161 m_idx_list = err_idx[np.where(relative_diff == max_error)]
105 m_count = 0162 m_count = 0
106 for m_idx in m_idx_list:163 for m_idx in m_idx_list:
107 m_count += 1164 m_count += 1
108 if m_count < 4:165 if m_count < 4:
109- print_log('%08d \t %.7f \t %.7f \t %.7f \t %.7f' % (166+ print_log(
110- m_idx, expect_data[m_idx], real_data[m_idx],167+ "%08d \t %.7f \t %.7f \t %.7f \t %.7f"
111- abs(np.float64(expect_data[m_idx]) -168+ % (
112- np.float64(real_data[m_idx])),169+ m_idx,
113- max_error))170+ expect_data[m_idx],
171+ real_data[m_idx],
172+ abs(np.float64(expect_data[m_idx]) - np.float64(real_data[m_idx])),
173+ max_error,
174+ )
175+ )
114 else:176 else:
115 break177 break
116 print_log(178 print_log(
117- '---------------------------------------------------------------------------------------')179+ "---------------------------------------------------------------------------------------"
180+ )
181+ 
182+ 
118def check_result(expect, npu_result):183def check_result(expect, npu_result):
119- diff_thd=0.005184+ diff_thd = 0.005
120- pct_thd=0.005185+ pct_thd = 0.005
121- max_diff_hd=10186+ max_diff_hd = 10
122- rtol=0.005187+ rtol = 0.005
123- atol=0.000025188+ atol = 0.000025
124 max_error_idx = 10000000189 max_error_idx = 10000000
125 190 
126 real_data = npu_result.cpu().to(torch.float).numpy()191 real_data = npu_result.cpu().to(torch.float).numpy()
@@ -129,7 +194,8 @@ def check_result(expect, npu_result):
129 data_compe = data_compe.flatten()194 data_compe = data_compe.flatten()
130 if real_data.size == 0 and real_data.size == data_compe.size:195 if real_data.size == 0 and real_data.size == data_compe.size:
131 print_log(196 print_log(
132- 'The npu_output is [],and it is same as bm_output, the result of data_compare is \"Pass\"')197+ 'The npu_output is [],and it is same as bm_output, the result of data_compare is "Pass"'
198+ )
133 return "Pass", 100.0, 0199 return "Pass", 100.0, 0
134 start = 0200 start = 0
135 end = real_data.size - 1201 end = real_data.size - 1
@@ -140,30 +206,38 @@ def check_result(expect, npu_result):
140 206 
141 if real_data.size != data_compe.size:207 if real_data.size != data_compe.size:
142 print_log(208 print_log(
143- 'Error,the size of npu output[%s] and benchmark[%s] is not equal.' % (real_data.size, data_compe.size))209+ "Error,the size of npu output[%s] and benchmark[%s] is not equal."
210+ % (real_data.size, data_compe.size)
211+ )
144 return result, 0.0, max_error212 return result, 0.0, max_error
145- overflows_count = data_compe[np.isinf(data_compe)].size + data_compe[np.isnan(data_compe)].size213+ overflows_count = (
146- 214+ data_compe[np.isinf(data_compe)].size + data_compe[np.isnan(data_compe)].size
215+ )
147 216 
148 if overflows_count > 0:217 if overflows_count > 0:
149- print_log('Overflow,size:%s,benchmark_output:%s, %s' % (218+ print_log(
150- overflows_count, data_compe[np.isinf(data_compe)][0:10], data_compe[np.isnan(data_compe)][0:10]))219+ "Overflow,size:%s,benchmark_output:%s, %s"
151- 220+ % (
221+ overflows_count,
222+ data_compe[np.isinf(data_compe)][0:10],
223+ data_compe[np.isnan(data_compe)][0:10],
224+ )
225+ )
152 226 
153 split_count = int(end - start + 1) if end != start else 1227 split_count = int(end - start + 1) if end != start else 1
154- print_log('split_count:%s; max_diff_hd:%s;' %228+ print_log("split_count:%s; max_diff_hd:%s;" % (float(split_count), max_diff_hd))
155- (float(split_count), max_diff_hd))
156- 
157- has_nan_inf = False
158- if 'nan' in str(real_data) or 'inf' in str(real_data) or 'nan' in str(data_compe) or 'inf' in str(data_compe):
159- has_nan_inf = True
160 229 
161 if npu_result.dtype == torch.bfloat16:230 if npu_result.dtype == torch.bfloat16:
162- rtol=0.0078125231+ rtol = 0.0078125
163- atol=0.0001232+ atol = 0.0001
164- diff_result = np.isclose(real_data.astype(np.float32), data_compe.astype(np.float32), rtol=rtol, atol=atol,233+ diff_result = np.isclose(
165- equal_nan=True)234+ real_data.astype(np.float32),
166- elif npu_result.dtype == 'float8_e4m3fn':235+ data_compe.astype(np.float32),
236+ rtol=rtol,
237+ atol=atol,
238+ equal_nan=True,
239+ )
240+ elif npu_result.dtype == "float8_e4m3fn":
167 nan_mask = np.isnan(real_data)241 nan_mask = np.isnan(real_data)
168 real_data[nan_mask] = 0242 real_data[nan_mask] = 0
169 arr_string = real_data.tobytes()243 arr_string = real_data.tobytes()
@@ -172,8 +246,10 @@ def check_result(expect, npu_result):
172 data_compe[nan_mask] = 0246 data_compe[nan_mask] = 0
173 arr_string = data_compe.tobytes()247 arr_string = data_compe.tobytes()
174 data_compe = np.frombuffer(arr_string, dtype="uint8")248 data_compe = np.frombuffer(arr_string, dtype="uint8")
175- diff_result = np.isclose(real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True)249+ diff_result = np.isclose(
176- elif npu_result.dtype == 'float8_e5m2':250+ real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True
251+ )
252+ elif npu_result.dtype == "float8_e5m2":
177 nan_mask = np.isnan(real_data)253 nan_mask = np.isnan(real_data)
178 real_data[nan_mask] = 0254 real_data[nan_mask] = 0
179 nan_pos_inf = np.isposinf(real_data)255 nan_pos_inf = np.isposinf(real_data)
@@ -192,12 +268,16 @@ def check_result(expect, npu_result):
192 268 
193 arr_string = data_compe.tobytes()269 arr_string = data_compe.tobytes()
194 data_compe = np.frombuffer(arr_string, dtype="uint8")270 data_compe = np.frombuffer(arr_string, dtype="uint8")
195- diff_result = np.isclose(real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True)271+ diff_result = np.isclose(
272+ real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True
273+ )
196 else:274 else:
197- diff_result = np.isclose(real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True)275+ diff_result = np.isclose(
276+ real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True
277+ )
198 err_idx = np.where(diff_result != np.array((True,)))[0]278 err_idx = np.where(diff_result != np.array((True,)))[0]
199 279 
200- if str(data_compe.dtype) == 'bool':280+ if str(data_compe.dtype) == "bool":
201 data_compe = data_compe.astype(np.int8)281 data_compe = data_compe.astype(np.int8)
202 real_data = real_data.astype(np.int8)282 real_data = real_data.astype(np.int8)
203 diff_abs = abs(data_compe - real_data)283 diff_abs = abs(data_compe - real_data)
@@ -208,8 +288,7 @@ def check_result(expect, npu_result):
208 err_diff = diff_abs / (b + eps)288 err_diff = diff_abs / (b + eps)
209 err_diff = err_diff[err_idx]289 err_diff = err_diff[err_idx]
210 290 
211- fulfill_percent = float(split_count - err_idx.size) / \291+ fulfill_percent = float(split_count - err_idx.size) / float(split_count) * 100.0
212- float(split_count) * 100.0
213 292 
214 display_output_np_isclose(real_data, data_compe, start, end)293 display_output_np_isclose(real_data, data_compe, start, end)
215 pct_thd = (1 - pct_thd) * 100.0294 pct_thd = (1 - pct_thd) * 100.0
@@ -219,16 +298,20 @@ def check_result(expect, npu_result):
219 if max_error >= max_diff_hd:298 if max_error >= max_diff_hd:
220 result = "Failed"299 result = "Failed"
221 print_log(300 print_log(
222- '---------------------------------------------------------------------------------------')301+ "---------------------------------------------------------------------------------------"
223- print_log('Rtol \t Atol \t PctThd \t PctRlt \t Result')302+ )
303+ print_log("Rtol \t Atol \t PctThd \t PctRlt \t Result")
224 print_log(304 print_log(
225- '---------------------------------------------------------------------------------------')305+ "---------------------------------------------------------------------------------------"
226- print_log('%.4f \t %.6f \t %.2f%% \t %.6f%% \t %s' %306+ )
227- (rtol, atol, pct_thd, fulfill_percent, result))307+ print_log(
308+ "%.4f \t %.6f \t %.2f%% \t %.6f%% \t %s"
309+ % (rtol, atol, pct_thd, fulfill_percent, result)
310+ )
228 if len(err_diff) > 0:311 if len(err_diff) > 0:
229- print_log('Max-RelativeError is: %s. Threshold is: %s.' %312+ print_log(
230- (max_error, max_diff_hd))313+ "Max-RelativeError is: %s. Threshold is: %s." % (max_error, max_diff_hd)
314+ )
231 if result == "Failed":315 if result == "Failed":
232- display_error_output(real_data, data_compe,316+ display_error_output(real_data, data_compe, err_idx, err_diff[0:max_error_idx])
233- err_idx, err_diff[0:max_error_idx])317+ return result, fulfill_percent
234- return result, fulfill_percent
@@ -10,39 +10,31 @@
10# See LICENSE in the root of the software repository for the full text of the License.10# See LICENSE in the root of the software repository for the full text of the License.
11# -----------------------------------------------------------------------------------------------------------11# -----------------------------------------------------------------------------------------------------------
12 12 
13-import itertools
14import torch13import torch
15import pytest14import pytest
16-import random
17-import pandas as pd
18from pathlib import Path15from pathlib import Path
19-import numpy as np
20-import math
21import os16import os
22-import multiprocessing as mp
23-import concurrent.futures
24import result_compare_method17import result_compare_method
25-import check_valid_param
26from batch import quant_sparse_flash_mla_process18from batch import quant_sparse_flash_mla_process
27import utils19import utils
28import logging20import logging
29 21 
30testcase_path = os.environ.get("QSMLA_PT_DIR", "qsmla_testcase")22testcase_path = os.environ.get("QSMLA_PT_DIR", "qsmla_testcase")
31is_run_graph = os.environ.get("RUN_GRAPH", "0") == "1"23is_run_graph = os.environ.get("RUN_GRAPH", "0") == "1"
32-result_path = Path('result.xlsx')24+result_path = Path("result.xlsx")
33-device_id=025+device_id = 0
34 26 
35# 日志配置27# 日志配置
36logging.basicConfig(28logging.basicConfig(
37 level=logging.INFO,29 level=logging.INFO,
38 format="%(asctime)s [%(levelname)-5s] %(filename)s:%(lineno)d %(message)s",30 format="%(asctime)s [%(levelname)-5s] %(filename)s:%(lineno)d %(message)s",
39 datefmt="%Y-%m-%d %H:%M:%S",31 datefmt="%Y-%m-%d %H:%M:%S",
40- force=True32+ force=True,
41)33)
42 34 
43testcase_files = []35testcase_files = []
44if os.path.isdir(testcase_path):36if os.path.isdir(testcase_path):
45- pt_files = [f for f in os.listdir(testcase_path) if f.endswith('.pt')]37+ pt_files = [f for f in os.listdir(testcase_path) if f.endswith(".pt")]
46 if not pt_files:38 if not pt_files:
47 logging.warning(f"错误: 目录中没有找到.pt文件: {testcase_path}")39 logging.warning(f"错误: 目录中没有找到.pt文件: {testcase_path}")
48 else:40 else:
@@ -53,28 +45,67 @@ if os.path.isdir(testcase_path):
53else:45else:
54 logging.warning(f"错误: 输出目录不存在: {testcase_path}")46 logging.warning(f"错误: 输出目录不存在: {testcase_path}")
55 47 
48+ 
56def qsmla(testcase_files):49def qsmla(testcase_files):
57 test_data = torch.load(testcase_files, map_location="cpu")50 test_data = torch.load(testcase_files, map_location="cpu")
58 try:51 try:
59 if is_run_graph:52 if is_run_graph:
60- npu_result, cpu_quant_result = quant_sparse_flash_mla_process.test_qsmla_quant_process_graph(53+ npu_result, cpu_quant_result, cpu_lse, npu_lse = (
61- test_data, device_id=device_id)54+ quant_sparse_flash_mla_process.test_qsmla_quant_process_graph(
55+ test_data, device_id=device_id
56+ )
57+ )
62 else:58 else:
63- npu_result, cpu_quant_result = quant_sparse_flash_mla_process.test_qsmla_quant_process_ci(59+ npu_result, cpu_quant_result, cpu_lse, npu_lse = (
64- test_data, device_id=device_id)60+ quant_sparse_flash_mla_process.test_qsmla_quant_process_ci(
65- result, fulfill_percent = result_compare_method.check_result(cpu_quant_result, npu_result)61+ test_data, device_id=device_id
62+ )
63+ )
64+ 
65+ # 分别校验主输出与LSE,分开保存结果
66+ main_res, main_pct = result_compare_method.check_result(
67+ cpu_quant_result, npu_result
68+ )
69+ lse_res, lse_pct = None, None
70+ fail_info = []
71+ min_fulfill = main_pct
72+ 
73+ if test_data["params"].get("return_softmax_lse"):
74+ print("return_softmax_lse is true!!!")
75+ lse_res, lse_pct = result_compare_method.check_result(cpu_lse, npu_lse)
76+ 
77+ # 主输出失败记录
78+ if main_res != "PASS":
79+ fail_info.append(f"MAIN_FAILED:{main_res}")
80+ # LSE失败记录
81+ if lse_res is not None and lse_res != "PASS":
82+ fail_info.append(f"LSE_FAILED:{lse_res}")
83+ min_fulfill = min(min_fulfill, lse_pct)
84+ 
85+ # 整合最终结果
86+ if fail_info:
87+ result = "; ".join(fail_info)
88+ fulfill_percent = min_fulfill
89+ else:
90+ result = "PASS"
91+ fulfill_percent = min_fulfill
92+ 
66 except Exception as e:93 except Exception as e:
67 logging.exception(e)94 logging.exception(e)
68 result = "NPU ERROR"95 result = "NPU ERROR"
69 fulfill_percent = 096 fulfill_percent = 0
70 97 
71- utils.save_result(test_data['params'], result, fulfill_percent, result_path)98+ utils.save_result(test_data["params"], result, fulfill_percent, result_path)
72 99 
73 if result in ("NPU ERROR", "Failed"):100 if result in ("NPU ERROR", "Failed"):
74- pytest.fail(f"用例执行失败:{test_data['Testcase_Name']} 精度:{fulfill_percent:.2f}%")101+ pytest.fail(
102+ f"用例执行失败:{test_data['Testcase_Name']} 精度:{fulfill_percent:.2f}%"
103+ )
104+ 
75 105 
76testcase_ids = [os.path.splitext(os.path.basename(f))[0] for f in testcase_files]106testcase_ids = [os.path.splitext(os.path.basename(f))[0] for f in testcase_files]
77 107 
108+ 
78@pytest.mark.ci109@pytest.mark.ci
79@pytest.mark.parametrize("testcase_files", testcase_files, ids=testcase_ids)110@pytest.mark.parametrize("testcase_files", testcase_files, ids=testcase_ids)
80def test_quant_sparse_flash_mla(testcase_files):111def test_quant_sparse_flash_mla(testcase_files):
@@ -19,7 +19,6 @@ import quant_sparse_flash_mla_golden
19from batch import quant_sparse_flash_mla_process19from batch import quant_sparse_flash_mla_process
20import pytest20import pytest
21from pathlib import Path21from pathlib import Path
22-import multiprocessing as mp
23import utils22import utils
24import logging23import logging
25import os24import os
@@ -27,7 +26,7 @@ import os
27pt_save_path = "qsmla_testcase"26pt_save_path = "qsmla_testcase"
28device_id = 027device_id = 0
29save_pt = False28save_pt = False
30-result_path = Path('result.xlsx')29+result_path = Path("result.xlsx")
31is_run_graph = os.environ.get("RUN_GRAPH", "0") == "1"30is_run_graph = os.environ.get("RUN_GRAPH", "0") == "1"
32 31 
33# 日志配置32# 日志配置
@@ -35,7 +34,7 @@ logging.basicConfig(
35 level=logging.INFO,34 level=logging.INFO,
36 format="%(asctime)s [%(levelname)-5s] %(filename)s:%(lineno)d %(message)s",35 format="%(asctime)s [%(levelname)-5s] %(filename)s:%(lineno)d %(message)s",
37 datefmt="%Y-%m-%d %H:%M:%S",36 datefmt="%Y-%m-%d %H:%M:%S",
38- force=True37+ force=True,
39)38)
40 39 
41param_combinations = []40param_combinations = []
@@ -76,6 +75,7 @@ for params in ENABLED_PARAMS:
76 "actlen_mode": params.get("actlen_mode"),75 "actlen_mode": params.get("actlen_mode"),
77 "S1EQS2": params.get("S1EQS2", [False]),76 "S1EQS2": params.get("S1EQS2", [False]),
78 "isSink": params.get("isSink", [True]),77 "isSink": params.get("isSink", [True]),
78+ "return_softmax_lse": params.get("return_softmax_lse", [False]),
79 }79 }
80 80 
81 param_names = list(param_values.keys())81 param_names = list(param_values.keys())
@@ -86,6 +86,8 @@ for params in ENABLED_PARAMS:
86 param_combinations.append(combination)86 param_combinations.append(combination)
87 87 
88case_id = 088case_id = 0
89+ 
90+ 
89def qsmla(param_combinations):91def qsmla(param_combinations):
90 global case_id92 global case_id
91 93 
@@ -93,32 +95,68 @@ def qsmla(param_combinations):
93 params = utils.fill_none_params(param_combinations)95 params = utils.fill_none_params(param_combinations)
94 96 
95 # 生成测试用例名称97 # 生成测试用例名称
96- Testcase_Name = params['Testcase_Name']98+ Testcase_Name = params["Testcase_Name"]
97 if Testcase_Name is None:99 if Testcase_Name is None:
98- ops_mode = 'prefill' if params['S1'] > 4 else "decode"100+ ops_mode = "prefill" if params["S1"] > 4 else "decode"
99- q_type_str = "BF16" if params['q_type'] == torch.bfloat16 else "FP16"101+ q_type_str = "BF16" if params["q_type"] == torch.bfloat16 else "FP16"
100- kv_type_str = "HIF8" if params['ori_kv_type'] == torch.uint8 else "FP8_E4M3FN"102+ kv_type_str = "HIF8" if params["ori_kv_type"] == torch.uint8 else "FP8_E4M3FN"
101 Testcase_Name = f"quantSparseFlashMla_{params['template_run_mode']}_{ops_mode}_{params['layout_q']}_{q_type_str}_{params['layout_kv']}_{kv_type_str}_{params['B']}_{params['N1']}_{params['N2']}_{params['S1']}_{params['S2']}_{params['D']}_{params['K']}_{case_id:06d}"103 Testcase_Name = f"quantSparseFlashMla_{params['template_run_mode']}_{ops_mode}_{params['layout_q']}_{q_type_str}_{params['layout_kv']}_{kv_type_str}_{params['B']}_{params['N1']}_{params['N2']}_{params['S1']}_{params['S2']}_{params['D']}_{params['K']}_{case_id:06d}"
102- params['Testcase_Name'] = Testcase_Name104+ params["Testcase_Name"] = Testcase_Name
103 105 
104 # 输入参数的合法性校验106 # 输入参数的合法性校验
105 try:107 try:
106 check_valid_param.check_valid_param(params)108 check_valid_param.check_valid_param(params)
107 except ValueError as e:109 except ValueError as e:
108- pytest.skip(f"输入参数校验失败:{e}")110+ pytest.skip(f"输入参数校验失败:{e}")
109 111 
110 # 生成测试数据及golden112 # 生成测试数据及golden
111- test_data = quant_sparse_flash_mla_golden.generate_and_save_testdata(params, save_pt=save_pt, save_path=pt_save_path)113+ test_data = quant_sparse_flash_mla_golden.generate_and_save_testdata(
114+ params, save_pt=save_pt, save_path=pt_save_path
115+ )
112 116 
113 # 获得cpu结果(真值)和算子结果(测试值)117 # 获得cpu结果(真值)和算子结果(测试值)
114 try:118 try:
115 if is_run_graph:119 if is_run_graph:
116- npu_result, cpu_quant_result = quant_sparse_flash_mla_process.test_qsmla_quant_process_graph(120+ npu_result, cpu_quant_result, cpu_lse, npu_lse = (
117- test_data, device_id=device_id)121+ quant_sparse_flash_mla_process.test_qsmla_quant_process_graph(
122+ test_data, device_id=device_id
123+ )
124+ )
118 else:125 else:
119- npu_result, cpu_quant_result = quant_sparse_flash_mla_process.test_qsmla_quant_process_ci(126+ npu_result, cpu_quant_result, cpu_lse, npu_lse = (
120- test_data, device_id=device_id)127+ quant_sparse_flash_mla_process.test_qsmla_quant_process_ci(
121- result, fulfill_percent = result_compare_method.check_result(cpu_quant_result, npu_result)128+ test_data, device_id=device_id
129+ )
130+ )
131+ 
132+ # 分别校验主输出与LSE,分开保存结果
133+ main_res, main_pct = result_compare_method.check_result(
134+ cpu_quant_result, npu_result
135+ )
136+ lse_res, lse_pct = None, None
137+ fail_info = []
138+ min_fulfill = main_pct
139+ 
140+ if test_data["params"].get("return_softmax_lse"):
141+ print("return_softmax_lse is true!!!")
142+ lse_res, lse_pct = result_compare_method.check_result(cpu_lse, npu_lse)
143+ 
144+ # 主输出失败记录
145+ if main_res != "PASS":
146+ fail_info.append(f"MAIN_FAILED:{main_res}")
147+ # LSE失败记录
148+ if lse_res is not None and lse_res != "PASS":
149+ fail_info.append(f"LSE_FAILED:{lse_res}")
150+ min_fulfill = min(min_fulfill, lse_pct)
151+ 
152+ # 整合最终结果
153+ if fail_info:
154+ result = "; ".join(fail_info)
155+ fulfill_percent = min_fulfill
156+ else:
157+ result = "PASS"
158+ fulfill_percent = min_fulfill
159+ 
122 except Exception as e:160 except Exception as e:
123 logging.exception(e)161 logging.exception(e)
124 result = "NPU ERROR"162 result = "NPU ERROR"
@@ -126,22 +164,27 @@ def qsmla(param_combinations):
126 164 
127 case_id += 1165 case_id += 1
128 166 
129- utils.save_result(test_data['params'], result, fulfill_percent, result_path)167+ utils.save_result(test_data["params"], result, fulfill_percent, result_path)
130 168 
131 if result in ("NPU ERROR", "Failed"):169 if result in ("NPU ERROR", "Failed"):
132- pytest.fail(f"用例执行失败:{test_data['Testcase_Name']} 精度:{fulfill_percent:.2f}%")170+ pytest.fail(
171+ f"用例执行失败:{test_data['Testcase_Name']} 精度:{fulfill_percent:.2f}%"
172+ )
173+ 
133 174 
134def _gen_testcase_id(params, idx):175def _gen_testcase_id(params, idx):
135- name = params.get('Testcase_Name')176+ name = params.get("Testcase_Name")
136 if name is not None:177 if name is not None:
137 return name178 return name
138- ops_mode = 'prefill' if params['S1'] > 4 else "decode"179+ ops_mode = "prefill" if params["S1"] > 4 else "decode"
139- q_type_str = "HIF8" if params['q_type'] == torch.bfloat16 else "FP16"180+ q_type_str = "HIF8" if params["q_type"] == torch.bfloat16 else "FP16"
140- kv_type_str = "HIF8" if params['ori_kv_type'] == torch.uint8 else "FP8_E4M3FN"181+ kv_type_str = "HIF8" if params["ori_kv_type"] == torch.uint8 else "FP8_E4M3FN"
141 return f"{params['template_run_mode']}_{ops_mode}_{params['layout_q']}_{q_type_str}_{params['layout_kv']}_{kv_type_str}_B{params['B']}_S1{params['S1']}_S2{params['S2']}_D{params['D']}_K{params['K']}_{idx:06d}"182 return f"{params['template_run_mode']}_{ops_mode}_{params['layout_q']}_{q_type_str}_{params['layout_kv']}_{kv_type_str}_B{params['B']}_S1{params['S1']}_S2{params['S2']}_D{params['D']}_K{params['K']}_{idx:06d}"
142 183 
184+ 
143testcase_ids = [_gen_testcase_id(p, i) for i, p in enumerate(param_combinations)]185testcase_ids = [_gen_testcase_id(p, i) for i, p in enumerate(param_combinations)]
144 186 
187+ 
145@pytest.mark.ci188@pytest.mark.ci
146@pytest.mark.parametrize("param_combinations", param_combinations, ids=testcase_ids)189@pytest.mark.parametrize("param_combinations", param_combinations, ids=testcase_ids)
147def test_quant_sparse_flash_mla(param_combinations):190def test_quant_sparse_flash_mla(param_combinations):
@@ -18,7 +18,17 @@ import os
18import math18import math
19import logging19import logging
20 20 
21-def infer_template_run_mode(K, cmp_ratio, ori_kv_type, cmp_kv_type, cmp_mask_mode, block_size1, block_size2, block_num2):21+ 
22+def infer_template_run_mode(
23+ K,
24+ cmp_ratio,
25+ ori_kv_type,
26+ cmp_kv_type,
27+ cmp_mask_mode,
28+ block_size1,
29+ block_size2,
30+ block_num2,
31+):
22 """32 """
23 根据K和cmp_ratio推断template_run_mode并设置默认值33 根据K和cmp_ratio推断template_run_mode并设置默认值
24 34 
@@ -37,8 +47,8 @@ def infer_template_run_mode(K, cmp_ratio, ori_kv_type, cmp_kv_type, cmp_mask_mod
37 """47 """
38 template_run_mode = "SWA"48 template_run_mode = "SWA"
39 49 
40- if K is None or K == ['None'] or K == 0:50+ if K is None or K == ["None"] or K == 0:
41- if cmp_ratio is None or cmp_ratio == ['None']:51+ if cmp_ratio is None or cmp_ratio == ["None"]:
42 template_run_mode = "SWA"52 template_run_mode = "SWA"
43 cmp_ratio = 153 cmp_ratio = 1
44 cmp_kv_type = ori_kv_type54 cmp_kv_type = ori_kv_type
@@ -64,17 +74,16 @@ def infer_template_run_mode(K, cmp_ratio, ori_kv_type, cmp_kv_type, cmp_mask_mod
64 block_num2 = block_num2 # 后续计算74 block_num2 = block_num2 # 后续计算
65 75 
66 return {76 return {
67- 'template_run_mode': template_run_mode,77+ "template_run_mode": template_run_mode,
68- 'K': K,78+ "K": K,
69- 'cmp_ratio': cmp_ratio,79+ "cmp_ratio": cmp_ratio,
70- 'cmp_kv_type': cmp_kv_type,80+ "cmp_kv_type": cmp_kv_type,
71- 'cmp_mask_mode': cmp_mask_mode,81+ "cmp_mask_mode": cmp_mask_mode,
72- 'block_size2': block_size2,82+ "block_size2": block_size2,
73- 'block_num2': block_num2,83+ "block_num2": block_num2,
74 }84 }
75 85 
76 86 
77- 
78def gen_seqused_cmp_kv(seqused_ori_kv, cmp_ratio):87def gen_seqused_cmp_kv(seqused_ori_kv, cmp_ratio):
79 """88 """
80 生成seqused_cmp_kv89 生成seqused_cmp_kv
@@ -88,6 +97,7 @@ def gen_seqused_cmp_kv(seqused_ori_kv, cmp_ratio):
88 """97 """
89 return [math.floor(s / cmp_ratio) for s in seqused_ori_kv]98 return [math.floor(s / cmp_ratio) for s in seqused_ori_kv]
90 99 
100+ 
91def parse_list_param(value):101def parse_list_param(value):
92 if value is None or (isinstance(value, float) and pd.isna(value)):102 if value is None or (isinstance(value, float) and pd.isna(value)):
93 return None103 return None
@@ -95,18 +105,17 @@ def parse_list_param(value):
95 return value105 return value
96 if isinstance(value, str):106 if isinstance(value, str):
97 s = value.strip()107 s = value.strip()
98- if s.lower() == 'none' or s == '':108+ if s.lower() == "none" or s == "":
99 return None109 return None
100- if s.startswith('[') and s.endswith(']'):110+ if s.startswith("[") and s.endswith("]"):
101 s = s[1:-1]111 s = s[1:-1]
102 try:112 try:
103- return [int(x.strip()) for x in s.split(',') if x.strip() != '']113+ return [int(x.strip()) for x in s.split(",") if x.strip() != ""]
104 except ValueError:114 except ValueError:
105 return None115 return None
106 return None116 return None
107 117 
108 118 
109- 
110def gen_cu_seqlens_from_seqused(seqused):119def gen_cu_seqlens_from_seqused(seqused):
111 """120 """
112 从seqused生成cu_seqlens累加和121 从seqused生成cu_seqlens累加和
@@ -122,6 +131,7 @@ def gen_cu_seqlens_from_seqused(seqused):
122 cu_seqlens.append(cu_seqlens[-1] + s)131 cu_seqlens.append(cu_seqlens[-1] + s)
123 return cu_seqlens132 return cu_seqlens
124 133 
134+ 
125def calc_block_num(seqused_ori_kv, seqused_cmp_kv, block_size1, block_size2, cmp_ratio):135def calc_block_num(seqused_ori_kv, seqused_cmp_kv, block_size1, block_size2, cmp_ratio):
126 """136 """
127 计算block_num1和block_num2137 计算block_num1和block_num2
@@ -149,6 +159,7 @@ def calc_block_num(seqused_ori_kv, seqused_cmp_kv, block_size1, block_size2, cmp
149 159 
150 return ori_block_num_sum, cmp_block_num_sum160 return ori_block_num_sum, cmp_block_num_sum
151 161 
162+ 
152def fill_none_params(params_dict):163def fill_none_params(params_dict):
153 """164 """
154 填充None参数的默认值(完整封装)165 填充None参数的默认值(完整封装)
@@ -159,45 +170,45 @@ def fill_none_params(params_dict):
159 返回:170 返回:
160 dict: 填充后的完整参数字典171 dict: 填充后的完整参数字典
161 """172 """
162- layout_q = params_dict['layout_q']173+ layout_q = params_dict["layout_q"]
163- B = params_dict['B']174+ B = params_dict["B"]
164- S1 = params_dict['S1']175+ S1 = params_dict["S1"]
165- S2 = params_dict['S2']176+ S2 = params_dict["S2"]
166- ori_kv_type = params_dict['ori_kv_type']177+ ori_kv_type = params_dict["ori_kv_type"]
167- block_size1 = params_dict['block_size1']178+ block_size1 = params_dict["block_size1"]
168- actlen_mode = params_dict.get('actlen_mode', 'full')179+ actlen_mode = params_dict.get("actlen_mode", "full")
169- S1EQS2 = params_dict.get('S1EQS2', False)180+ S1EQS2 = params_dict.get("S1EQS2", False)
170 181 
171 # 1. 获取template_run_mode(优先从params_dict获取)182 # 1. 获取template_run_mode(优先从params_dict获取)
172- template_run_mode = params_dict.get('template_run_mode')183+ template_run_mode = params_dict.get("template_run_mode")
173 184 
174 if template_run_mode is None:185 if template_run_mode is None:
175 # 如果未提供template_run_mode,则推断(向后兼容)186 # 如果未提供template_run_mode,则推断(向后兼容)
176 infer_result = infer_template_run_mode(187 infer_result = infer_template_run_mode(
177- params_dict.get('K'),188+ params_dict.get("K"),
178- params_dict.get('cmp_ratio'),189+ params_dict.get("cmp_ratio"),
179 ori_kv_type,190 ori_kv_type,
180- params_dict.get('cmp_kv_type'),191+ params_dict.get("cmp_kv_type"),
181- params_dict.get('cmp_mask_mode'),192+ params_dict.get("cmp_mask_mode"),
182 block_size1,193 block_size1,
183- params_dict.get('block_size2'),194+ params_dict.get("block_size2"),
184- params_dict.get('block_num2')195+ params_dict.get("block_num2"),
185 )196 )
186- K = infer_result['K']197+ K = infer_result["K"]
187- cmp_ratio = infer_result['cmp_ratio']198+ cmp_ratio = infer_result["cmp_ratio"]
188- cmp_kv_type = infer_result['cmp_kv_type']199+ cmp_kv_type = infer_result["cmp_kv_type"]
189- cmp_mask_mode = infer_result['cmp_mask_mode']200+ cmp_mask_mode = infer_result["cmp_mask_mode"]
190- block_size2 = infer_result['block_size2']201+ block_size2 = infer_result["block_size2"]
191- block_num2 = infer_result['block_num2']202+ block_num2 = infer_result["block_num2"]
192- template_run_mode = infer_result['template_run_mode']203+ template_run_mode = infer_result["template_run_mode"]
193 else:204 else:
194 # 如果提供了template_run_mode,直接使用params_dict中的参数205 # 如果提供了template_run_mode,直接使用params_dict中的参数
195- K = params_dict.get('K')206+ K = params_dict.get("K")
196- cmp_ratio = params_dict.get('cmp_ratio')207+ cmp_ratio = params_dict.get("cmp_ratio")
197- cmp_kv_type = params_dict.get('cmp_kv_type')208+ cmp_kv_type = params_dict.get("cmp_kv_type")
198- cmp_mask_mode = params_dict.get('cmp_mask_mode')209+ cmp_mask_mode = params_dict.get("cmp_mask_mode")
199- block_size2 = params_dict.get('block_size2')210+ block_size2 = params_dict.get("block_size2")
200- block_num2 = params_dict.get('block_num2')211+ block_num2 = params_dict.get("block_num2")
201 212 
202 # 处理None参数的默认值(保持一致性)213 # 处理None参数的默认值(保持一致性)
203 if cmp_ratio is None:214 if cmp_ratio is None:
@@ -212,14 +223,13 @@ def fill_none_params(params_dict):
212 K = 0223 K = 0
213 224 
214 # 2. 获取需要填充的参数225 # 2. 获取需要填充的参数
215- seqused_q = params_dict.get('seqused_q')226+ seqused_q = params_dict.get("seqused_q")
216- cu_seqlens_q = params_dict.get('cu_seqlens_q')227+ cu_seqlens_q = params_dict.get("cu_seqlens_q")
217- seqused_ori_kv = params_dict.get('seqused_ori_kv')228+ seqused_ori_kv = params_dict.get("seqused_ori_kv")
218- cu_seqlens_ori_kv = params_dict.get('cu_seqlens_ori_kv')229+ cu_seqlens_ori_kv = params_dict.get("cu_seqlens_ori_kv")
219- seqused_cmp_kv = params_dict.get('seqused_cmp_kv')230+ seqused_cmp_kv = params_dict.get("seqused_cmp_kv")
220- cu_seqlens_cmp_kv = params_dict.get('cu_seqlens_cmp_kv')231+ cu_seqlens_cmp_kv = params_dict.get("cu_seqlens_cmp_kv")
221- cmp_residual_kv = params_dict.get('cmp_residual_kv')232+ cmp_residual_kv = params_dict.get("cmp_residual_kv")
222- 
223 if seqused_q is not None and len(seqused_q) == 1:233 if seqused_q is not None and len(seqused_q) == 1:
224 seqused_q = seqused_q * B234 seqused_q = seqused_q * B
225 if seqused_ori_kv is not None and len(seqused_ori_kv) == 1:235 if seqused_ori_kv is not None and len(seqused_ori_kv) == 1:
@@ -229,14 +239,22 @@ def fill_none_params(params_dict):
229 if cmp_residual_kv is not None and len(cmp_residual_kv) == 1:239 if cmp_residual_kv is not None and len(cmp_residual_kv) == 1:
230 cmp_residual_kv = cmp_residual_kv * B240 cmp_residual_kv = cmp_residual_kv * B
231 241 
232- need_fill_q_ori = any(v is None for v in [seqused_q, cu_seqlens_q, seqused_ori_kv, cu_seqlens_ori_kv])242+ need_fill_q_ori = any(
243+ v is None for v in [seqused_q, cu_seqlens_q, seqused_ori_kv, cu_seqlens_ori_kv]
244+ )
233 245 
234 if need_fill_q_ori:246 if need_fill_q_ori:
235 # 从cu推导seqused247 # 从cu推导seqused
236 if seqused_q is None and cu_seqlens_q is not None:248 if seqused_q is None and cu_seqlens_q is not None:
237- seqused_q = [cu_seqlens_q[i + 1] - cu_seqlens_q[i] for i in range(len(cu_seqlens_q) - 1)]249+ seqused_q = [
250+ cu_seqlens_q[i + 1] - cu_seqlens_q[i]
251+ for i in range(len(cu_seqlens_q) - 1)
252+ ]
238 if seqused_ori_kv is None and cu_seqlens_ori_kv is not None:253 if seqused_ori_kv is None and cu_seqlens_ori_kv is not None:
239- seqused_ori_kv = [cu_seqlens_ori_kv[i + 1] - cu_seqlens_ori_kv[i] for i in range(len(cu_seqlens_ori_kv) - 1)]254+ seqused_ori_kv = [
255+ cu_seqlens_ori_kv[i + 1] - cu_seqlens_ori_kv[i]
256+ for i in range(len(cu_seqlens_ori_kv) - 1)
257+ ]
240 258 
241 # S1EQS2联动: seqused_q与seqused_ori_kv259 # S1EQS2联动: seqused_q与seqused_ori_kv
242 if S1EQS2:260 if S1EQS2:
@@ -283,12 +301,16 @@ def fill_none_params(params_dict):
283 for i in range(B):301 for i in range(B):
284 slot_len = cu_seqlens_q[i + 1] - cu_seqlens_q[i]302 slot_len = cu_seqlens_q[i + 1] - cu_seqlens_q[i]
285 if slot_len < seqused_q[i]:303 if slot_len < seqused_q[i]:
286- raise ValueError(f"cu_seqlens_q slot ({slot_len}) at batch {i} must >= seqused_q ({seqused_q[i]})")304+ raise ValueError(
305+ f"cu_seqlens_q slot ({slot_len}) at batch {i} must >= seqused_q ({seqused_q[i]})"
306+ )
287 307 
288 for i in range(B):308 for i in range(B):
289 slot_len = cu_seqlens_ori_kv[i + 1] - cu_seqlens_ori_kv[i]309 slot_len = cu_seqlens_ori_kv[i + 1] - cu_seqlens_ori_kv[i]
290 if slot_len < seqused_ori_kv[i]:310 if slot_len < seqused_ori_kv[i]:
291- raise ValueError(f"cu_seqlens_ori_kv slot ({slot_len}) at batch {i} must >= seqused_ori_kv ({seqused_ori_kv[i]})")311+ raise ValueError(
312+ f"cu_seqlens_ori_kv slot ({slot_len}) at batch {i} must >= seqused_ori_kv ({seqused_ori_kv[i]})"
313+ )
292 314 
293 # 3. 填充cmp参数 (SWA场景为None, 非SWA场景自动生成)315 # 3. 填充cmp参数 (SWA场景为None, 非SWA场景自动生成)
294 if template_run_mode == "SWA":316 if template_run_mode == "SWA":
@@ -305,16 +327,21 @@ def fill_none_params(params_dict):
305 for i in range(B):327 for i in range(B):
306 slot_len = cu_seqlens_cmp_kv[i + 1] - cu_seqlens_cmp_kv[i]328 slot_len = cu_seqlens_cmp_kv[i + 1] - cu_seqlens_cmp_kv[i]
307 if slot_len < seqused_cmp_kv[i]:329 if slot_len < seqused_cmp_kv[i]:
308- raise ValueError(f"cu_seqlens_cmp_kv slot ({slot_len}) at batch {i} must >= seqused_cmp_kv ({seqused_cmp_kv[i]})")330+ raise ValueError(
331+ f"cu_seqlens_cmp_kv slot ({slot_len}) at batch {i} must >= seqused_cmp_kv ({seqused_cmp_kv[i]})"
332+ )
309 333 
310 # 6. 计算block_num334 # 6. 计算block_num
311- block_num1 = params_dict.get('block_num1')335+ block_num1 = params_dict.get("block_num1")
312- block_num2 = params_dict.get('block_num2')336+ block_num2 = params_dict.get("block_num2")
313 337 
314 if block_num1 is None:338 if block_num1 is None:
315 ori_block_num, _ = calc_block_num(339 ori_block_num, _ = calc_block_num(
316- seqused_ori_kv, seqused_cmp_kv if seqused_cmp_kv is not None else [0] * B,340+ seqused_ori_kv,
317- block_size1, block_size2, cmp_ratio341+ seqused_cmp_kv if seqused_cmp_kv is not None else [0] * B,
342+ block_size1,
343+ block_size2,
344+ cmp_ratio,
318 )345 )
319 block_num1 = ori_block_num346 block_num1 = ori_block_num
320 if block_num2 is None:347 if block_num2 is None:
@@ -329,50 +356,51 @@ def fill_none_params(params_dict):
329 # 7. 计算T1356 # 7. 计算T1
330 T1 = cu_seqlens_q[-1] if layout_q == "TND" else None357 T1 = cu_seqlens_q[-1] if layout_q == "TND" else None
331 358 
332- quant_mode = params_dict.get('quant_mode')359+ quant_mode = params_dict.get("quant_mode")
333 360 
334 # 构建完整参数字典361 # 构建完整参数字典
335 filled_params = {362 filled_params = {
336- 'Testcase_Name': params_dict.get('Testcase_Name'),363+ "Testcase_Name": params_dict.get("Testcase_Name"),
337- 'layout_q': layout_q,364+ "layout_q": layout_q,
338- 'layout_kv': params_dict['layout_kv'],365+ "layout_kv": params_dict["layout_kv"],
339- 'q_type': params_dict['q_type'],366+ "q_type": params_dict["q_type"],
340- 'ori_kv_type': ori_kv_type,367+ "ori_kv_type": ori_kv_type,
341- 'cmp_kv_type': cmp_kv_type,368+ "cmp_kv_type": cmp_kv_type,
342- 'B': B,369+ "B": B,
343- 'S1': S1,370+ "S1": S1,
344- 'S2': S2,371+ "S2": S2,
345- 'T1': T1,372+ "T1": T1,
346- 'N1': params_dict['N1'],373+ "N1": params_dict["N1"],
347- 'N2': params_dict['N2'],374+ "N2": params_dict["N2"],
348- 'D': params_dict['D'],375+ "D": params_dict["D"],
349- 'K': K,376+ "K": K,
350- 'block_num1': block_num1,377+ "block_num1": block_num1,
351- 'block_num2': block_num2,378+ "block_num2": block_num2,
352- 'block_size1': block_size1,379+ "block_size1": block_size1,
353- 'block_size2': block_size2,380+ "block_size2": block_size2,
354- 'seqused_q': seqused_q,381+ "seqused_q": seqused_q,
355- 'cu_seqlens_q': cu_seqlens_q,382+ "cu_seqlens_q": cu_seqlens_q,
356- 'seqused_ori_kv': seqused_ori_kv,383+ "seqused_ori_kv": seqused_ori_kv,
357- 'seqused_cmp_kv': seqused_cmp_kv,384+ "seqused_cmp_kv": seqused_cmp_kv,
358- 'cu_seqlens_ori_kv': cu_seqlens_ori_kv,385+ "cu_seqlens_ori_kv": cu_seqlens_ori_kv,
359- 'cu_seqlens_cmp_kv': cu_seqlens_cmp_kv,386+ "cu_seqlens_cmp_kv": cu_seqlens_cmp_kv,
360- 'cmp_residual_kv': cmp_residual_kv,387+ "cmp_residual_kv": cmp_residual_kv,
361- 'softmax_scale': params_dict['softmax_scale'],388+ "softmax_scale": params_dict["softmax_scale"],
362- 'cmp_ratio': cmp_ratio,389+ "cmp_ratio": cmp_ratio,
363- 'ori_mask_mode': params_dict['ori_mask_mode'],390+ "ori_mask_mode": params_dict["ori_mask_mode"],
364- 'cmp_mask_mode': cmp_mask_mode,391+ "cmp_mask_mode": cmp_mask_mode,
365- 'ori_win_left': params_dict['ori_win_left'],392+ "ori_win_left": params_dict["ori_win_left"],
366- 'ori_win_right': params_dict['ori_win_right'],393+ "ori_win_right": params_dict["ori_win_right"],
367- 'quant_mode': quant_mode,394+ "quant_mode": quant_mode,
368- 'template_run_mode': template_run_mode,395+ "template_run_mode": template_run_mode,
369- 'topk_value_mode': params_dict.get('topk_value_mode', 1),396+ "topk_value_mode": params_dict.get("topk_value_mode", 1),
370- 'return_softmax_lse': params_dict.get('return_softmax_lse', False),397+ "return_softmax_lse": params_dict.get("return_softmax_lse", False),
371- 'isSink': params_dict.get('isSink', True),398+ "isSink": params_dict.get("isSink", True),
372 }399 }
373 400 
374 return filled_params401 return filled_params
375 402 
403+ 
376def load_excel_test_cases(excel_file_path: str, sheetname: str):404def load_excel_test_cases(excel_file_path: str, sheetname: str):
377 """405 """
378 从 Excel 文件加载测试用例。406 从 Excel 文件加载测试用例。
@@ -385,7 +413,7 @@ def load_excel_test_cases(excel_file_path: str, sheetname: str):
385 list[]: 测试用例字典列表413 list[]: 测试用例字典列表
386 """414 """
387 if sheetname is None:415 if sheetname is None:
388- sheetname = 'Sheet1'416+ sheetname = "Sheet1"
389 417 
390 # 检查文件是否存在418 # 检查文件是否存在
391 if not os.path.exists(excel_file_path):419 if not os.path.exists(excel_file_path):
@@ -398,20 +426,50 @@ def load_excel_test_cases(excel_file_path: str, sheetname: str):
398 426 
399 # 定义必需的列名427 # 定义必需的列名
400 required_columns = [428 required_columns = [
401- "layout_q", "layout_kv", "q_type", "ori_kv_type", "cmp_kv_type", "B", "S1", "S2", "N1",429+ "layout_q",
402- "N2", "D", "K", "block_size1", "block_size2", "softmax_scale", "cmp_ratio",430+ "layout_kv",
403- "ori_mask_mode", "cmp_mask_mode", "ori_win_left", "ori_win_right", "quant_mode",431+ "q_type",
404- "template_run_mode", "actlen_mode", "S1EQS2",432+ "ori_kv_type",
405- "topk_value_mode", "return_softmax_lse",433+ "cmp_kv_type",
434+ "B",
435+ "S1",
436+ "S2",
437+ "N1",
438+ "N2",
439+ "D",
440+ "K",
441+ "block_size1",
442+ "block_size2",
443+ "softmax_scale",
444+ "cmp_ratio",
445+ "ori_mask_mode",
446+ "cmp_mask_mode",
447+ "ori_win_left",
448+ "ori_win_right",
449+ "quant_mode",
450+ "template_run_mode",
451+ "actlen_mode",
452+ "S1EQS2",
453+ "topk_value_mode",
454+ "return_softmax_lse",
406 ]455 ]
407 optional_columns = [456 optional_columns = [
408- "Testcase_Name", "seqused_q", "cu_seqlens_q", "seqused_ori_kv", "seqused_cmp_kv",457+ "Testcase_Name",
409- "cu_seqlens_ori_kv", "cu_seqlens_cmp_kv", "cmp_residual_kv",458+ "seqused_q",
459+ "cu_seqlens_q",
460+ "seqused_ori_kv",
461+ "seqused_cmp_kv",
462+ "cu_seqlens_ori_kv",
463+ "cu_seqlens_cmp_kv",
464+ "cmp_residual_kv",
410 ]465 ]
411 # 检查是否缺少必要列466 # 检查是否缺少必要列
412 missing_cols = [col for col in required_columns if col not in df.columns]467 missing_cols = [col for col in required_columns if col not in df.columns]
413 if missing_cols:468 if missing_cols:
414- pytest.skip(f"Missing required columns in Excel: {missing_cols}", allow_module_level=True)469+ pytest.skip(
470+ f"Missing required columns in Excel: {missing_cols}",
471+ allow_module_level=True,
472+ )
415 473 
416 # 构建测试用例列表474 # 构建测试用例列表
417 test_cases = []475 test_cases = []
@@ -432,44 +490,45 @@ def load_excel_test_cases(excel_file_path: str, sheetname: str):
432 pytest.skip(f"Failed to read Excel file: {e}", allow_module_level=True)490 pytest.skip(f"Failed to read Excel file: {e}", allow_module_level=True)
433 return None491 return None
434 492 
493+ 
435def save_result(params, result, fulfill_percent, result_path):494def save_result(params, result, fulfill_percent, result_path):
436 """495 """
437 存储测试结果到表格496 存储测试结果到表格
438 """497 """
439 row_data = {498 row_data = {
440- "case_name": params.get('Testcase_Name'),499+ "case_name": params.get("Testcase_Name"),
441- "layout_q": params.get('layout_q'),500+ "layout_q": params.get("layout_q"),
442- "layout_kv": params.get('layout_kv'),501+ "layout_kv": params.get("layout_kv"),
443- "q_type": params.get('q_type'),502+ "q_type": params.get("q_type"),
444- "ori_kv_type": params.get('ori_kv_type'),503+ "ori_kv_type": params.get("ori_kv_type"),
445- "cmp_kv_type": params.get('cmp_kv_type'),504+ "cmp_kv_type": params.get("cmp_kv_type"),
446- "B": params.get('B'),505+ "B": params.get("B"),
447- "S1": params.get('S1'),506+ "S1": params.get("S1"),
448- "T1": params.get('T1'),507+ "T1": params.get("T1"),
449- "N1": params.get('N1'),508+ "N1": params.get("N1"),
450- "N2": params.get('N2'),509+ "N2": params.get("N2"),
451- "D": params.get('D'),510+ "D": params.get("D"),
452- "K": params.get('K'),511+ "K": params.get("K"),
453- "block_num1": params.get('block_num1'),512+ "block_num1": params.get("block_num1"),
454- "block_num2": params.get('block_num2'),513+ "block_num2": params.get("block_num2"),
455- "block_size1": params.get('block_size1'),514+ "block_size1": params.get("block_size1"),
456- "block_size2": params.get('block_size2'),515+ "block_size2": params.get("block_size2"),
457- "seqused_q": params.get('seqused_q'),516+ "seqused_q": params.get("seqused_q"),
458- "cu_seqlens_q": params.get('cu_seqlens_q'),517+ "cu_seqlens_q": params.get("cu_seqlens_q"),
459- "seqused_ori_kv": params.get('seqused_ori_kv'),518+ "seqused_ori_kv": params.get("seqused_ori_kv"),
460- "seqused_cmp_kv": params.get('seqused_cmp_kv'),519+ "seqused_cmp_kv": params.get("seqused_cmp_kv"),
461- "cu_seqlens_ori_kv": params.get('cu_seqlens_ori_kv'),520+ "cu_seqlens_ori_kv": params.get("cu_seqlens_ori_kv"),
462- "cu_seqlens_cmp_kv": params.get('cu_seqlens_cmp_kv'),521+ "cu_seqlens_cmp_kv": params.get("cu_seqlens_cmp_kv"),
463- "cmp_residual_kv": params.get('cmp_residual_kv'),522+ "cmp_residual_kv": params.get("cmp_residual_kv"),
464- "softmax_scale": params.get('softmax_scale'),523+ "softmax_scale": params.get("softmax_scale"),
465- "cmp_ratio": params.get('cmp_ratio'),524+ "cmp_ratio": params.get("cmp_ratio"),
466- "ori_mask_mode": params.get('ori_mask_mode'),525+ "ori_mask_mode": params.get("ori_mask_mode"),
467- "cmp_mask_mode": params.get('cmp_mask_mode'),526+ "cmp_mask_mode": params.get("cmp_mask_mode"),
468- "ori_win_left": params.get('ori_win_left'),527+ "ori_win_left": params.get("ori_win_left"),
469- "ori_win_right": params.get('ori_win_right'),528+ "ori_win_right": params.get("ori_win_right"),
470- "quant_mode": params.get('quant_mode'),529+ "quant_mode": params.get("quant_mode"),
471- "topk_value_mode": params.get('topk_value_mode'),530+ "topk_value_mode": params.get("topk_value_mode"),
472- "return_softmax_lse": params.get('return_softmax_lse'),531+ "return_softmax_lse": params.get("return_softmax_lse"),
473 "result": result,532 "result": result,
474 "fulfill_percent": fulfill_percent,533 "fulfill_percent": fulfill_percent,
475 }534 }
@@ -7,7 +7,7 @@
7 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.7 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 * See LICENSE in the root of the software repository for the full text of the License.8 * See LICENSE in the root of the software repository for the full text of the License.
9 */9 */
10- 10+ 
11/*!11/*!
12 * \file quant_sparse_flash_mla_metadata_aicpu.cpp12 * \file quant_sparse_flash_mla_metadata_aicpu.cpp
13 * \brief13 * \brief