Merged
chunk_gated_delta_rule support FP32 state #8738
chunk_gated_delta_rule support FP32 state #8738
Merged
赵志勇Add on Jul 15
Total: 14 files changed+511-219
@@ -44,11 +44,11 @@ REG_OP(ChunkGatedDeltaRule)
44 .INPUT(key, TensorType({DT_BF16}))44 .INPUT(key, TensorType({DT_BF16}))
45 .INPUT(value, TensorType({DT_BF16}))45 .INPUT(value, TensorType({DT_BF16}))
46 .INPUT(beta, TensorType({DT_BF16}))46 .INPUT(beta, TensorType({DT_BF16}))
47- .INPUT(initial_state, TensorType({DT_BF16}))47+ .INPUT(initial_state, TensorType({DT_BF16, DT_FLOAT}))
48 .INPUT(actual_seq_lengths, TensorType({DT_INT32}))48 .INPUT(actual_seq_lengths, TensorType({DT_INT32}))
49 .OPTIONAL_INPUT(g, TensorType({DT_FLOAT}))49 .OPTIONAL_INPUT(g, TensorType({DT_FLOAT}))
50 .OUTPUT(out, TensorType({DT_BF16}))50 .OUTPUT(out, TensorType({DT_BF16}))
51- .OUTPUT(final_state, TensorType({DT_BF16}))51+ .OUTPUT(final_state, TensorType({DT_BF16, DT_FLOAT}))
52 .ATTR(scale_value, Float, 1.0)52 .ATTR(scale_value, Float, 1.0)
53 .OP_END_FACTORY_REG(ChunkGatedDeltaRule)53 .OP_END_FACTORY_REG(ChunkGatedDeltaRule)
54 54 
@@ -42,7 +42,7 @@ public:
42 .UnknownShapeFormat({ge::FORMAT_ND});42 .UnknownShapeFormat({ge::FORMAT_ND});
43 this->Input("initial_state")43 this->Input("initial_state")
44 .ParamType(REQUIRED)44 .ParamType(REQUIRED)
45- .DataType({ge::DT_BF16})45+ .DataTypeList({ge::DT_BF16, ge::DT_FLOAT})
46 .Format({ge::FORMAT_ND})46 .Format({ge::FORMAT_ND})
47 .UnknownShapeFormat({ge::FORMAT_ND});47 .UnknownShapeFormat({ge::FORMAT_ND});
48 this->Input("actual_seq_lengths")48 this->Input("actual_seq_lengths")
@@ -64,10 +64,10 @@ public:
64 .AutoContiguous();64 .AutoContiguous();
65 this->Output("final_state")65 this->Output("final_state")
66 .ParamType(REQUIRED)66 .ParamType(REQUIRED)
67- .DataType({ge::DT_BF16})67+ .DataTypeList({ge::DT_BF16, ge::DT_FLOAT})
68 .Format({ge::FORMAT_ND})68 .Format({ge::FORMAT_ND})
69 .UnknownShapeFormat({ge::FORMAT_ND});69 .UnknownShapeFormat({ge::FORMAT_ND});
70- 70+ 
71 this->Attr("scale_value").AttrType(OPTIONAL).Float(1.0);71 this->Attr("scale_value").AttrType(OPTIONAL).Float(1.0);
72 72 
73 OpAICoreConfig aicoreConfig;73 OpAICoreConfig aicoreConfig;
@@ -98,10 +98,11 @@ static ge::graphStatus InferDataTypeChunkGatedDeltaRule(gert::InferDataTypeConte
98 OP_LOGE("ChunkGatedDeltaRule", "inference context is null");98 OP_LOGE("ChunkGatedDeltaRule", "inference context is null");
99 return ge::GRAPH_FAILED;99 return ge::GRAPH_FAILED;
100 }100 }
101- // 根据 query 的输入 dtype 推导两个输出的 dtype101+ // 根据 query 的输入 dtype 推导 out 的 dtype, finalState 跟随 initialState
102 auto queryDtype = context->GetInputDataType(QUERY_INDEX);102 auto queryDtype = context->GetInputDataType(QUERY_INDEX);
103+ auto stateDtype = context->GetInputDataType(STATE_INDEX);
103 context->SetOutputDataType(OUTPUT_OUT_IDX, queryDtype);104 context->SetOutputDataType(OUTPUT_OUT_IDX, queryDtype);
104- context->SetOutputDataType(OUTPUT_FINAL_STATE_IDX, queryDtype);105+ context->SetOutputDataType(OUTPUT_FINAL_STATE_IDX, stateDtype);
105 return ge::GRAPH_SUCCESS;106 return ge::GRAPH_SUCCESS;
106}107}
107 108 
@@ -20,6 +20,7 @@
20#include "err/ops_err.h"20#include "err/ops_err.h"
21#include "log/log.h"21#include "log/log.h"
22#include "tiling/platform/platform_ascendc.h"22#include "tiling/platform/platform_ascendc.h"
23+#include "../op_kernel/chunk_gated_delta_rule_tiling_key.h"
23 24 
24namespace optiling {25namespace optiling {
25REGISTER_OPS_TILING_TEMPLATE(ChunkGatedDeltaRule, ChunkGatedDeltaRuleTiling, 0);26REGISTER_OPS_TILING_TEMPLATE(ChunkGatedDeltaRule, ChunkGatedDeltaRuleTiling, 0);
@@ -72,6 +73,7 @@ void ChunkGatedDeltaRuleTiling::InitCompileInfo()
72 ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, compileInfo_.ubSize);73 ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, compileInfo_.ubSize);
73 compileInfo_.aivNum = ascendcPlatform.GetCoreNumAiv();74 compileInfo_.aivNum = ascendcPlatform.GetCoreNumAiv();
74 compileInfo_.aicNum = ascendcPlatform.GetCoreNumAic();75 compileInfo_.aicNum = ascendcPlatform.GetCoreNumAic();
76+ socVersion_ = ascendcPlatform.GetSocVersion();
75 77 
76 if (compileInfo_.aivNum <= 0 || compileInfo_.aicNum <= 0) {78 if (compileInfo_.aivNum <= 0 || compileInfo_.aicNum <= 0) {
77 OP_LOGE(context_->GetNodeName(), "aivNum <= 0 or aicNum <= 0");79 OP_LOGE(context_->GetNodeName(), "aivNum <= 0 or aicNum <= 0");
@@ -122,24 +124,33 @@ ge::graphStatus ChunkGatedDeltaRuleTiling::DoOpTiling()
122 124 
123 tilingData_.interWorkspaceSz = 0;125 tilingData_.interWorkspaceSz = 0;
124 int64_t sizeHigh = ge::GetSizeByDataType(ge::DT_FLOAT);126 int64_t sizeHigh = ge::GetSizeByDataType(ge::DT_FLOAT);
127+ int64_t sizeLow = ge::GetSizeByDataType(ge::DT_BF16);
125 int64_t nv = tilingData_.nv;128 int64_t nv = tilingData_.nv;
126 int64_t dv = tilingData_.dv;129 int64_t dv = tilingData_.dv;
127 int64_t dk = tilingData_.dk;130 int64_t dk = tilingData_.dk;
128 int64_t s = tilingData_.maxGroupLength;131 int64_t s = tilingData_.maxGroupLength;
129- int64_t b = tilingData_.b;132+ tilingData_.interWorkspaceSz += sizeHigh * nv * s; // gCumExp (FP32)
130- tilingData_.interWorkspaceSz += sizeHigh * nv * s; // gCumExp133+ tilingData_.interWorkspaceSz += sizeLow * nv * s * dk; // kCumDecay (BF16)
131- tilingData_.interWorkspaceSz += sizeHigh * nv * s * dk; // kCumDecay134+ if (tilingData_.stateIsFp32) {
132- tilingData_.interWorkspaceSz += sizeHigh * nv * s * dv; // vInner135+ tilingData_.interWorkspaceSz += sizeHigh * nv * s * dv; // vInner (FP32)
133- tilingData_.interWorkspaceSz += sizeHigh * nv * s * dk; // qPrime136+ tilingData_.interWorkspaceSz += sizeLow * nv * s * dv; // vInnerBf16 (BF16, for stage3)
134- tilingData_.interWorkspaceSz += sizeHigh * nv * s * dv; // attnInter137+ } else {
135- tilingData_.interWorkspaceSz += sizeHigh * nv * s * dk; // kg138+ tilingData_.interWorkspaceSz += sizeLow * nv * s * dv; // vInner (BF16)
136- tilingData_.interWorkspaceSz += sizeHigh * nv * s * c; // qkt139+ }
137- tilingData_.interWorkspaceSz += sizeHigh * b * nv * dv * dk; // highState140+ tilingData_.interWorkspaceSz += sizeLow * nv * s * dk; // qPrime (BF16)
138- tilingData_.interWorkspaceSz += sizeHigh * c * c * tilingData_.aiCoreNum * MASK_NUM; // mask141+ tilingData_.interWorkspaceSz += sizeLow * nv * s * dv; // attnInter (BF16, arch22 compat)
142+ tilingData_.interWorkspaceSz += sizeLow * nv * s * dk; // kg (BF16)
143+ tilingData_.interWorkspaceSz += sizeLow * nv * s * c; // qkt (BF16)
144+ if (tilingData_.stateIsFp32) {
145+ tilingData_.interWorkspaceSz += sizeLow * nv * dv * dk; // stateBf16Wk (BF16, arch35)
146+ } else if (socVersion_ != platform_ascendc::SocVersion::ASCEND950) {
147+ tilingData_.interWorkspaceSz += sizeHigh * tilingData_.b * nv * dv * dk; // highState_ (arch22: kernel unconditionally advances offset)
148+ }
149+ tilingData_.interWorkspaceSz += sizeHigh * c * c * tilingData_.aiCoreNum * MASK_NUM; // mask (FP32)
139 150 
140 // stage1 临时变量空间151 // stage1 临时变量空间
141 tilingData_.stageWorkspaceSz =152 tilingData_.stageWorkspaceSz =
142- sizeHigh * c * (STAGE_ONE_TWO * c + STAGE_ONE_THREE * dk + dv) * tilingData_.stageOneParaNum;153+ sizeLow * c * (STAGE_ONE_TWO * c + STAGE_ONE_THREE * dk + dv) * tilingData_.stageOneParaNum;
143 tilingData_.stageWorkspaceSz *= tilingData_.aiCoreNum;154 tilingData_.stageWorkspaceSz *= tilingData_.aiCoreNum;
144 155 
145 PrintTilingData();156 PrintTilingData();
@@ -186,12 +197,40 @@ ge::graphStatus ChunkGatedDeltaRuleTiling::DoMatmulTiling()
186 tilingData_.matmulTilingFp32.depthB1 = 1;197 tilingData_.matmulTilingFp32.depthB1 = 1;
187 tilingData_.matmulTilingFp32.stepM = 1;198 tilingData_.matmulTilingFp32.stepM = 1;
188 tilingData_.matmulTilingFp32.stepN = 1;199 tilingData_.matmulTilingFp32.stepN = 1;
200+ 
201+ // ========== MT_FP32C: BF16 -> BF16 -> FP32 (for FP32 state path) ==========
202+ if (tilingData_.stateIsFp32) {
203+ matmul_tiling::MultiCoreMatmulTiling mmFp32C;
204+ mmFp32C.SetBufferSpace(l1Size, l0CSize, ubSize);
205+ mmFp32C.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND,
206+ matmul_tiling::DataType::DT_BFLOAT16, true);
207+ mmFp32C.SetBType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND,
208+ matmul_tiling::DataType::DT_BFLOAT16, true);
209+ mmFp32C.SetCType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND,
210+ matmul_tiling::DataType::DT_FLOAT);
211+ mmFp32C.SetBias(false);
212+ mmFp32C.SetDim(1);
213+ mmFp32C.SetShape(baseM, baseN, baseK);
214+ mmFp32C.SetOrgShape(baseM, baseN, baseK);
215+ mmFp32C.SetFixSplit(baseM, baseN, baseK);
216+ if (mmFp32C.GetTiling(tilingData_.matmulTilingFp32C) == -1) {
217+ OP_LOGE(context_->GetNodeName(), "CGDR: Get Tiling Fp32C Failed!");
218+ return ge::GRAPH_FAILED;
219+ }
220+ tilingData_.matmulTilingFp32C.dbL0C = 1;
221+ tilingData_.matmulTilingFp32C.stepKa = 1;
222+ tilingData_.matmulTilingFp32C.stepKb = 1;
223+ tilingData_.matmulTilingFp32C.depthA1 = 1;
224+ tilingData_.matmulTilingFp32C.depthB1 = 1;
225+ tilingData_.matmulTilingFp32C.stepM = 1;
226+ tilingData_.matmulTilingFp32C.stepN = 1;
227+ }
189 return ge::GRAPH_SUCCESS;228 return ge::GRAPH_SUCCESS;
190}229}
191 230 
192ge::graphStatus ChunkGatedDeltaRuleTiling::DoLibApiTiling()231ge::graphStatus ChunkGatedDeltaRuleTiling::DoLibApiTiling()
193{232{
194- tilingKey_ = 0;233+ tilingKey_ = tilingData_.stateIsFp32 ? TILING_KEY_CGDR_FP32_STATE : TILING_KEY_CGDR_BF16_STATE;
195 234 
196 // 执行 matmul tiling235 // 执行 matmul tiling
197 if (DoMatmulTiling() != ge::GRAPH_SUCCESS) {236 if (DoMatmulTiling() != ge::GRAPH_SUCCESS) {
@@ -313,9 +352,17 @@ ge::graphStatus ChunkGatedDeltaRuleTiling::AnalyzeDtype()
313 352 
314 auto betaDtype = context_->GetInputDesc(BETA_INDEX)->GetDataType();353 auto betaDtype = context_->GetInputDesc(BETA_INDEX)->GetDataType();
315 auto stateDtype = context_->GetInputDesc(STATE_INDEX)->GetDataType();354 auto stateDtype = context_->GetInputDesc(STATE_INDEX)->GetDataType();
316- OP_CHECK_IF(betaDtype != ge::DT_BF16 || stateDtype != ge::DT_BF16,355+ OP_CHECK_IF(betaDtype != ge::DT_BF16,
317- OP_LOGE(context_->GetNodeName(), "beta dtype and state dtype should be bfloat16"),356+ OP_LOGE(context_->GetNodeName(), "beta dtype should be bfloat16"),
318 return ge::GRAPH_FAILED);357 return ge::GRAPH_FAILED);
358+ OP_CHECK_IF(stateDtype != ge::DT_BF16 && stateDtype != ge::DT_FLOAT,
359+ OP_LOGE(context_->GetNodeName(), "state dtype should be bfloat16 or float32"),
360+ return ge::GRAPH_FAILED);
361+ if (stateDtype == ge::DT_FLOAT && socVersion_ != platform_ascendc::SocVersion::ASCEND950) {
362+ OP_LOGE(context_->GetNodeName(), "FP32 state is only supported on Ascend950");
363+ return ge::GRAPH_FAILED;
364+ }
365+ tilingData_.stateIsFp32 = (stateDtype == ge::DT_FLOAT) ? 1 : 0;
319 366 
320 auto actualSeqLengthsDtype = context_->GetInputDesc(ACTUAL_SEQ_LENGTHS_INDEX)->GetDataType();367 auto actualSeqLengthsDtype = context_->GetInputDesc(ACTUAL_SEQ_LENGTHS_INDEX)->GetDataType();
321 OP_CHECK_IF(actualSeqLengthsDtype != ge::DT_INT32,368 OP_CHECK_IF(actualSeqLengthsDtype != ge::DT_INT32,
@@ -331,8 +378,13 @@ ge::graphStatus ChunkGatedDeltaRuleTiling::AnalyzeDtype()
331 auto finalStateDtype = context_->GetOutputDesc(OUTPUT_FINAL_STATE_IDX)->GetDataType();378 auto finalStateDtype = context_->GetOutputDesc(OUTPUT_FINAL_STATE_IDX)->GetDataType();
332 OP_CHECK_IF(outDtype != ge::DT_BF16, OP_LOGE(context_->GetNodeName(), "output dtype should be bfloat16"),379 OP_CHECK_IF(outDtype != ge::DT_BF16, OP_LOGE(context_->GetNodeName(), "output dtype should be bfloat16"),
333 return ge::GRAPH_FAILED);380 return ge::GRAPH_FAILED);
334- OP_CHECK_IF(finalStateDtype != ge::DT_BF16,381+ OP_CHECK_IF(finalStateDtype != ge::DT_BF16 && finalStateDtype != ge::DT_FLOAT,
335- OP_LOGE(context_->GetNodeName(), "final_state dtype should be bfloat16"), return ge::GRAPH_FAILED);382+ OP_LOGE(context_->GetNodeName(), "final_state dtype should be bfloat16 or float32"), return ge::GRAPH_FAILED);
383+ OP_CHECK_IF(stateDtype != finalStateDtype,
384+ OP_LOGE(context_->GetNodeName(),
385+ "initial_state and final_state must have the same dtype, got initial_state=%d, final_state=%d",
386+ static_cast<int>(stateDtype), static_cast<int>(finalStateDtype)),
387+ return ge::GRAPH_FAILED);
336 388 
337 return ge::GRAPH_SUCCESS;389 return ge::GRAPH_SUCCESS;
338}390}
@@ -551,6 +603,7 @@ void ChunkGatedDeltaRuleTiling::PrintTilingData()
551 OP_LOGD(context_->GetNodeName(), "stateStride0: [%ld]", tilingData_.stateStride0);603 OP_LOGD(context_->GetNodeName(), "stateStride0: [%ld]", tilingData_.stateStride0);
552 OP_LOGD(context_->GetNodeName(), "stateStride1: [%ld]", tilingData_.stateStride1);604 OP_LOGD(context_->GetNodeName(), "stateStride1: [%ld]", tilingData_.stateStride1);
553 OP_LOGD(context_->GetNodeName(), "scale: [%f]", tilingData_.scale);605 OP_LOGD(context_->GetNodeName(), "scale: [%f]", tilingData_.scale);
606+ OP_LOGD(context_->GetNodeName(), "stateIsFp32: [%ld]", tilingData_.stateIsFp32);
554}607}
555 608 
556// tiling 调度入口609// tiling 调度入口
@@ -95,6 +95,7 @@ protected:
95 ChunkGatedDeltaRuleCompileInfo compileInfo_;95 ChunkGatedDeltaRuleCompileInfo compileInfo_;
96 ChunkGatedDeltaRule::ChunkGatedDeltaRuleTilingData tilingData_;96 ChunkGatedDeltaRule::ChunkGatedDeltaRuleTilingData tilingData_;
97 ChunkGatedDeltaRuleInfo inputParams_;97 ChunkGatedDeltaRuleInfo inputParams_;
98+ platform_ascendc::SocVersion socVersion_;
98};99};
99 100 
100} // namespace optiling101} // namespace optiling
@@ -53,7 +53,7 @@ struct ChunkGatedDeltaRuleParams {
53 53 
54// 校验相关:支持的数据类型54// 校验相关:支持的数据类型
55static const std::initializer_list<op::DataType> QKV_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16};55static const std::initializer_list<op::DataType> QKV_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16};
56-static const std::initializer_list<op::DataType> STATE_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16};56+static const std::initializer_list<op::DataType> STATE_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16, op::DataType::DT_FLOAT};
57static const std::initializer_list<op::DataType> BETA_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16};57static const std::initializer_list<op::DataType> BETA_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16};
58static const std::initializer_list<op::DataType> SEQ_LENS_TYPE_SUPPORT_LIST = {op::DataType::DT_INT32};58static const std::initializer_list<op::DataType> SEQ_LENS_TYPE_SUPPORT_LIST = {op::DataType::DT_INT32};
59static const std::initializer_list<op::DataType> G_TYPE_SUPPORT_LIST = {op::DataType::DT_FLOAT};59static const std::initializer_list<op::DataType> G_TYPE_SUPPORT_LIST = {op::DataType::DT_FLOAT};
@@ -35,9 +35,10 @@ ChunkGatedDeltaRule(const aclTensor *query, const aclTensor *key, const aclTenso
35 L0_DFX(ChunkGatedDeltaRule, query, key, value, beta, initialState, actualSeqLengths, gOptional, scaleValue);35 L0_DFX(ChunkGatedDeltaRule, query, key, value, beta, initialState, actualSeqLengths, gOptional, scaleValue);
36 36 
37 DataType outType = value->GetDataType();37 DataType outType = value->GetDataType();
38+ DataType stateType = initialState->GetDataType();
38 Format format = Format::FORMAT_ND;39 Format format = Format::FORMAT_ND;
39 auto out = executor->AllocTensor(outType, format, format);40 auto out = executor->AllocTensor(outType, format, format);
40- auto finalState = executor->AllocTensor(outType, format, format);41+ auto finalState = executor->AllocTensor(stateType, format, format);
41 42 
42 auto ret =43 auto ret =
43 INFER_SHAPE(ChunkGatedDeltaRule, OP_INPUT(query, key, value, beta, initialState, actualSeqLengths, gOptional),44 INFER_SHAPE(ChunkGatedDeltaRule, OP_INPUT(query, key, value, beta, initialState, actualSeqLengths, gOptional),
@@ -40,60 +40,15 @@ struct CGDRInitParams {
40 GM_ADDR finalState;40 GM_ADDR finalState;
41};41};
42 42 
43-template <typename srcType, typename dstType>
44-__aicore__ inline void CopyCast(
45- const GlobalTensor<srcType>& src,
46- const GlobalTensor<dstType>& dst,
47- TPipe* pipe,
48- const int64_t totalDataCount,
49- const RoundMode& roundMode)
50-{
51- if ASCEND_IS_AIV {
52- int64_t blkNum = GetBlockNum();
53- int64_t blkId = GetBlockIdx();
54- int64_t dataPerCore = (totalDataCount + blkNum - 1) / blkNum;
55- int64_t startPos = dataPerCore * blkId;
56- int64_t endPos = startPos + dataPerCore;
57- if (startPos >= totalDataCount) {
58- return;
59- }
60- if (endPos > totalDataCount) {
61- endPos = totalDataCount;
62- }
63- TQue<QuePosition::VECIN, TQUE_DEPTH_TWO> inQueue;
64- TQue<QuePosition::VECOUT, TQUE_DEPTH_TWO> outQueue;
65- pipe->InitBuffer(inQueue, BUFFER_NUM_TWO, TILE_LEN * sizeof(srcType)); // use 2 buffer
66- pipe->InitBuffer(outQueue, BUFFER_NUM_TWO, TILE_LEN * sizeof(dstType)); // use 2 buffer
67- for (int64_t i = startPos; i < endPos; i += TILE_LEN) {
68- uint32_t blockLen = i + TILE_LEN > endPos ? endPos - i : TILE_LEN;
69- // copy in
70- DataCopyExtParams inParams{1, static_cast<uint32_t>(blockLen * sizeof(srcType)), 0, 0, 0};
71- DataCopyPadExtParams<srcType> inPadParams{false, 0, 0, 0};
72- auto inLocal = inQueue.AllocTensor<srcType>();
73- DataCopyPad(inLocal, src[i], inParams, inPadParams);
74- inQueue.EnQue(inLocal);
75- // cast
76- auto stateIn = inQueue.DeQue<srcType>();
77- auto stateOut = outQueue.AllocTensor<dstType>();
78- Cast(stateOut, stateIn, roundMode, blockLen);
79- outQueue.EnQue(stateOut);
80- inQueue.FreeTensor(stateIn);
81- // copy out
82- auto outLocal = outQueue.DeQue<dstType>();
83- DataCopyExtParams outParams{1, static_cast<uint32_t>(blockLen * sizeof(dstType)), 0, 0, 0};
84- DataCopyPad(dst[i], outLocal, outParams);
85- outQueue.FreeTensor(outLocal);
86- }
87- PipeBarrier<PIPE_V>();
88- }
89-}
90 43 
91- 44+template <typename lowType, typename highType, typename stateType = lowType>
92-template <typename lowType, typename highType>
93class CGDR {45class CGDR {
94public:46public:
47+ static constexpr bool kStateIsFp32 = std::is_same_v<stateType, float>;
48+ using vInnerType = std::conditional_t<kStateIsFp32, float, lowType>;
49+ using StageOneMmVInner = StageOneMTT<vInnerType>;
95 __aicore__ inline CGDR(TPipe *pipe, const ChunkGatedDeltaRuleTilingData *tilingData)50 __aicore__ inline CGDR(TPipe *pipe, const ChunkGatedDeltaRuleTilingData *tilingData)
96- : stageOneOp_(stage1MT_)51+ : stageOneOp_(stage1MmBf16_, stage1MmVInner_)
97 {52 {
98 pipe_ = pipe;53 pipe_ = pipe;
99 tiling_ = tilingData;54 tiling_ = tilingData;
@@ -102,10 +57,17 @@ public:
102 __aicore__ inline void InitMatmul()57 __aicore__ inline void InitMatmul()
103 {58 {
104 if ASCEND_IS_AIC {59 if ASCEND_IS_AIC {
105- // 使用 tiling 中的 matmul tiling 数据初始化60+ stage1MmBf16_.Init(&tiling_->matmulTilingFp32, pipe_);
106- stage1MT_.Init(&tiling_->matmulTilingFp32, pipe_);61+ if constexpr (kStateIsFp32) {
107- stage2MT_.Init(&tiling_->matmulTilingFp32, pipe_);62+ stage1MmVInner_.Init(&tiling_->matmulTilingFp32C, pipe_);
108- stage3MT_.Init(&tiling_->matmulTilingFp32, pipe_);63+ } else {
64+ stage1MmVInner_.Init(&tiling_->matmulTilingFp32, pipe_);
65+ }
66+ stage2MmBf16_.Init(&tiling_->matmulTilingFp32, pipe_);
67+ if constexpr (kStateIsFp32) {
68+ stage2MmFp32_.Init(&tiling_->matmulTilingFp32C, pipe_);
69+ }
70+ stage3Mm_.Init(&tiling_->matmulTilingFp32, pipe_);
109 }71 }
110 }72 }
111 73 
@@ -161,8 +123,8 @@ public:
161 }123 }
162 124 
163 dataSize = tiling_->b * tiling_->nv * tiling_->dv * tiling_->dk;125 dataSize = tiling_->b * tiling_->nv * tiling_->dv * tiling_->dk;
164- initState_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(initParams.initState), dataSize);126+ initState_.SetGlobalBuffer(reinterpret_cast<__gm__ stateType *>(initParams.initState), dataSize);
165- finalState_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(initParams.finalState), dataSize);127+ finalState_.SetGlobalBuffer(reinterpret_cast<__gm__ stateType *>(initParams.finalState), dataSize);
166 128 
167 actualSeqLens_.SetGlobalBuffer(reinterpret_cast<__gm__ int32_t *>(initParams.seqlens), tiling_->b);129 actualSeqLens_.SetGlobalBuffer(reinterpret_cast<__gm__ int32_t *>(initParams.seqlens), tiling_->b);
168 130 
@@ -173,8 +135,13 @@ public:
173 kCumDecay_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));135 kCumDecay_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));
174 offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->dk;136 offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->dk;
175 137 
176- vInner_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));138+ vInner_.SetGlobalBuffer(reinterpret_cast<__gm__ vInnerType *>(user + offset));
177- offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->dv;139+ offset += sizeof(vInnerType) * tiling_->nv * tiling_->maxGroupLength * tiling_->dv;
140+ 
141+ if constexpr (kStateIsFp32) {
142+ vInnerBf16_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));
143+ offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->dv;
144+ }
178 145 
179 qPrime_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));146 qPrime_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));
180 offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->dk;147 offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->dk;
@@ -188,8 +155,11 @@ public:
188 qkt_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));155 qkt_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset));
189 offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->chunkSize;156 offset += sizeof(lowType) * tiling_->nv * tiling_->maxGroupLength * tiling_->chunkSize;
190 157 
191- highState_.SetGlobalBuffer(reinterpret_cast<__gm__ highType *>(user + offset));158+ if constexpr (kStateIsFp32) {
192- offset += sizeof(highType) * tiling_->b * tiling_->nv * tiling_->dv * tiling_->dk;159+ uint64_t stateWkElemCnt = tiling_->nv * tiling_->dv * tiling_->dk;
160+ curStateBf16_.SetGlobalBuffer(reinterpret_cast<__gm__ lowType *>(user + offset), stateWkElemCnt);
161+ offset += sizeof(lowType) * stateWkElemCnt;
162+ }
193 163 
194 stageOneMask_.SetGlobalBuffer(reinterpret_cast<__gm__ highType *>(user + offset));164 stageOneMask_.SetGlobalBuffer(reinterpret_cast<__gm__ highType *>(user + offset));
195 offset += sizeof(highType) * tiling_->chunkSize * tiling_->chunkSize * tiling_->aiCoreNum * TASK_RATIO;165 offset += sizeof(highType) * tiling_->chunkSize * tiling_->chunkSize * tiling_->aiCoreNum * TASK_RATIO;
@@ -214,8 +184,8 @@ public:
214 int32_t length = actualSeqLens_.GetValue(bid);184 int32_t length = actualSeqLens_.GetValue(bid);
215 seqStart = seqEnd;185 seqStart = seqEnd;
216 seqEnd = seqStart + (int64_t)length;186 seqEnd = seqStart + (int64_t)length;
187+ 
217 for (int64_t pos = seqStart; pos < seqEnd; pos += tiling_->maxGroupLength) {188 for (int64_t pos = seqStart; pos < seqEnd; pos += tiling_->maxGroupLength) {
218- // set chunk group
219 cg.startPos = pos;189 cg.startPos = pos;
220 if (pos + tiling_->maxGroupLength > seqEnd) {190 if (pos + tiling_->maxGroupLength > seqEnd) {
221 cg.length = seqEnd - pos;191 cg.length = seqEnd - pos;
@@ -243,7 +213,7 @@ public:
243private:213private:
244 __aicore__ inline void RunStage1(const ChunkGroup& cg)214 __aicore__ inline void RunStage1(const ChunkGroup& cg)
245 {215 {
246- GDRStageOneInitParams initStageOneParams {query_, key_, value_, beta_, g_,216+ GDRStageOneInitParams<vInnerType> initStageOneParams {query_, key_, value_, beta_, g_,
247 gCum_, kCumDecay_, vInner_, qPrime_, kg_, qkt_,217 gCum_, kCumDecay_, vInner_, qPrime_, kg_, qkt_,
248 stageWsAddr_, stageOneMask_, cg, gFlag_};218 stageWsAddr_, stageOneMask_, cg, gFlag_};
249 stageOneOp_.Init(initStageOneParams, pipe_, tiling_);219 stageOneOp_.Init(initStageOneParams, pipe_, tiling_);
@@ -251,14 +221,41 @@ private:
251 pipe_->Reset();221 pipe_->Reset();
252 }222 }
253 223 
254- __aicore__ inline void RunStage2(ChunkGroup& cg, GlobalTensor<lowType> stateIn,224+ template <typename sType>
255- GlobalTensor<lowType> stateOut, bool useInitialState)225+ __aicore__ inline void RunStage2(ChunkGroup& cg, GlobalTensor<sType> stateIn,
226+ GlobalTensor<sType> stateOut, bool isFirstGroup)
256 {227 {
257- Stage2 stageTwoOp;228+ Stage2<sType> stageTwoOp;
258- StageTwoParams initStageTwoParams{229+ StageTwoParams<sType> initStageTwoParams;
259- qPrime_, vInner_, gCum_, kCumDecay_, stateIn, stateOut, kg_,230+ initStageTwoParams.qPrime = qPrime_;
260- out_[cg.startPos * tiling_->nv * tiling_->dv], stageWsAddr_, &stage2MT_, pipe_, &cg,231+ initStageTwoParams.vInner = vInner_;
261- tiling_->nv, tiling_->nk, tiling_->dv, tiling_->dk, tiling_->stateStride1, useInitialState, gFlag_};232+ if constexpr (std::is_same_v<sType, float>) {
233+ initStageTwoParams.vInnerBf16 = vInnerBf16_;
234+ }
235+ initStageTwoParams.gCum = gCum_;
236+ initStageTwoParams.kCumdecay = kCumDecay_;
237+ initStageTwoParams.kg = kg_;
238+ initStageTwoParams.out = out_[cg.startPos * tiling_->nv * tiling_->dv];
239+ initStageTwoParams.ws = stageWsAddr_;
240+ initStageTwoParams.mm1Bf16 = &stage2MmBf16_;
241+ initStageTwoParams.mm1Fp32 = &stage2MmFp32_;
242+ initStageTwoParams.pipe = pipe_;
243+ initStageTwoParams.cg = &cg;
244+ initStageTwoParams.Nv = tiling_->nv;
245+ initStageTwoParams.Nk = tiling_->nk;
246+ initStageTwoParams.Dv = tiling_->dv;
247+ initStageTwoParams.Dk = tiling_->dk;
248+ initStageTwoParams.stateStride1 = tiling_->stateStride1;
249+ initStageTwoParams.useInitialState = isFirstGroup;
250+ initStageTwoParams.gOptional = gFlag_;
251+ initStageTwoParams.isFirstGroup = isFirstGroup;
252+ initStageTwoParams.stateIn = stateIn;
253+ initStageTwoParams.stateOut = stateOut;
254+ if constexpr (std::is_same_v<sType, float>) {
255+ initStageTwoParams.curStateBf16 = curStateBf16_;
256+ } else {
257+ initStageTwoParams.curStateBf16 = stateIn;
258+ }
262 stageTwoOp.Init(&initStageTwoParams, tiling_->aiCoreNum);259 stageTwoOp.Init(&initStageTwoParams, tiling_->aiCoreNum);
263 stageTwoOp.Process();260 stageTwoOp.Process();
264 pipe_->Reset();261 pipe_->Reset();
@@ -266,12 +263,21 @@ private:
266 263 
267 __aicore__ inline void RunStage3(ChunkGroup& cg)264 __aicore__ inline void RunStage3(ChunkGroup& cg)
268 {265 {
266+ if ASCEND_IS_AIC {
267+ stage3Mm_.Init(&tiling_->matmulTilingFp32, pipe_);
268+ }
269+ GlobalTensor<lowType> vInnerBf16;
270+ if constexpr (kStateIsFp32) {
271+ vInnerBf16 = vInnerBf16_;
272+ } else {
273+ vInnerBf16 = vInner_;
274+ }
269 Stage3 stageThreeOp;275 Stage3 stageThreeOp;
270 StageThreeParams initStageThreeParams{276 StageThreeParams initStageThreeParams{
271- qkt_, gCum_, vInner_,277+ qkt_, gCum_, vInnerBf16,
272 stageThreeMask_[int(GetBlockIdx() / 2) * tiling_->chunkSize * tiling_->chunkSize],278 stageThreeMask_[int(GetBlockIdx() / 2) * tiling_->chunkSize * tiling_->chunkSize],
273 stageWsAddr_, out_[cg.startPos * tiling_->nv * tiling_->dv],279 stageWsAddr_, out_[cg.startPos * tiling_->nv * tiling_->dv],
274- &stage3MT_, pipe_, &cg, tiling_->scale,280+ &stage3Mm_, pipe_, &cg, tiling_->scale,
275 tiling_->nv, tiling_->nk, tiling_->dv, tiling_->dk, gFlag_};281 tiling_->nv, tiling_->nk, tiling_->dv, tiling_->dk, gFlag_};
276 stageThreeOp.Init(&initStageThreeParams, tiling_->aiCoreNum);282 stageThreeOp.Init(&initStageThreeParams, tiling_->aiCoreNum);
277 stageThreeOp.Process();283 stageThreeOp.Process();
@@ -288,18 +294,20 @@ private:
288 GlobalTensor<highType> g_;294 GlobalTensor<highType> g_;
289 GlobalTensor<lowType> out_;295 GlobalTensor<lowType> out_;
290 float scale_;296 float scale_;
291- GlobalTensor<lowType> finalState_;297+ GlobalTensor<stateType> finalState_;
292- GlobalTensor<lowType> initState_;298+ GlobalTensor<stateType> initState_;
293 GlobalTensor<int32_t> actualSeqLens_;299 GlobalTensor<int32_t> actualSeqLens_;
294 300 
301+ GlobalTensor<lowType> curStateBf16_;
302+ GlobalTensor<lowType> vInnerBf16_; // (Nv, maxGroupLength, Dv) BF16 vInner for stage3 (FP32 path only)
303+ 
295 GlobalTensor<highType> gCum_; // (Nv, maxGroupLength)304 GlobalTensor<highType> gCum_; // (Nv, maxGroupLength)
296 GlobalTensor<lowType> kCumDecay_; // (Nv, maxGroupLength, Dk)305 GlobalTensor<lowType> kCumDecay_; // (Nv, maxGroupLength, Dk)
297- GlobalTensor<lowType> vInner_; // (Nv, maxGroupLength, Dv)306+ GlobalTensor<vInnerType> vInner_; // (Nv, maxGroupLength, Dv) primary vInner
298 GlobalTensor<lowType> qPrime_; // (Nv, maxGroupLength, Dk)307 GlobalTensor<lowType> qPrime_; // (Nv, maxGroupLength, Dk)
299 GlobalTensor<lowType> attnInter_; // (Nv, maxGroupLength, Dv)308 GlobalTensor<lowType> attnInter_; // (Nv, maxGroupLength, Dv)
300 GlobalTensor<lowType> kg_; // (Nv, maxGroupLength, Dk)309 GlobalTensor<lowType> kg_; // (Nv, maxGroupLength, Dk)
301 GlobalTensor<lowType> qkt_; // (Nv, maxGroupLength, C)310 GlobalTensor<lowType> qkt_; // (Nv, maxGroupLength, C)
302- GlobalTensor<highType> highState_;
303 // mask矩阵311 // mask矩阵
304 GlobalTensor<highType> stageOneMask_; // (Nv, maxGroupLength, C)312 GlobalTensor<highType> stageOneMask_; // (Nv, maxGroupLength, C)
305 GlobalTensor<highType> stageThreeMask_; // (Nv, maxGroupLength, C)313 GlobalTensor<highType> stageThreeMask_; // (Nv, maxGroupLength, C)
@@ -308,12 +316,14 @@ private:
308 TBuf<TPosition::VECCALC> tmpBuff_; // 构造mask矩阵316 TBuf<TPosition::VECCALC> tmpBuff_; // 构造mask矩阵
309 317 
310 // Matmul objects318 // Matmul objects
311- StageOneMT stage1MT_;319+ StageOneMTT<bfloat16_t> stage1MmBf16_;
312- StageTwoMT stage2MT_;320+ StageOneMmVInner stage1MmVInner_;
313- StageThreeMT stage3MT_;321+ StageTwoMT stage2MmBf16_;
322+ StageTwoMTFp32C stage2MmFp32_;
323+ StageThreeMT stage3Mm_;
314 324 
315 // Stage operators325 // Stage operators
316- Stage1 stageOneOp_;326+ Stage1<kStateIsFp32> stageOneOp_;
317 bool gFlag_ = false;327 bool gFlag_ = false;
318};328};
319 329 
@@ -25,8 +25,8 @@ using namespace matmul;
25 25 
26using aT1 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t>;26using aT1 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t>;
27using bT1 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t>;27using bT1 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t>;
28-using cT1 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t>;28+template <typename cType>
29-using StageOneMT = matmul::MatmulImpl<aT1, bT1, cT1>;29+using StageOneMTT = matmul::MatmulImpl<aT1, bT1, MatmulType<TPosition::GM, CubeFormat::ND, cType>>;
30 30 
31constexpr uint64_t UB_REST_BYTES = 140 * 1024; // 140KB31constexpr uint64_t UB_REST_BYTES = 140 * 1024; // 140KB
32constexpr uint64_t INVERSE_SHAPE = 32; // 对角块边长32constexpr uint64_t INVERSE_SHAPE = 32; // 对角块边长
@@ -45,6 +45,7 @@ struct MatmulShapeParams {
45 uint64_t sk; // 单次计算 K 维度45 uint64_t sk; // 单次计算 K 维度
46};46};
47 47 
48+template <typename vInnerType>
48struct GDRStageOneInitParams {49struct GDRStageOneInitParams {
49 // input50 // input
50 GlobalTensor<bfloat16_t> query; // (T, Nk, Dk)51 GlobalTensor<bfloat16_t> query; // (T, Nk, Dk)
@@ -55,7 +56,7 @@ struct GDRStageOneInitParams {
55 // ouput56 // ouput
56 GlobalTensor<float> gCumExp; // (Nv, cg_len)57 GlobalTensor<float> gCumExp; // (Nv, cg_len)
57 GlobalTensor<bfloat16_t> kCumdecay; // (Nv, cg_len, Dk)58 GlobalTensor<bfloat16_t> kCumdecay; // (Nv, cg_len, Dk)
58- GlobalTensor<bfloat16_t> vInner; // (Nv, cg_len, Dv)59+ GlobalTensor<vInnerType> vInner; // (Nv, cg_len, Dv)
59 GlobalTensor<bfloat16_t> qPrime; // (Nv, cg_len, Dk)60 GlobalTensor<bfloat16_t> qPrime; // (Nv, cg_len, Dk)
60 GlobalTensor<bfloat16_t> kG; // (Nv, cg_len, Dk)61 GlobalTensor<bfloat16_t> kG; // (Nv, cg_len, Dk)
61 GlobalTensor<bfloat16_t> qK; // (Nv, cg_len, C)62 GlobalTensor<bfloat16_t> qK; // (Nv, cg_len, C)
@@ -66,10 +67,14 @@ struct GDRStageOneInitParams {
66 bool gOptional;67 bool gOptional;
67};68};
68 69 
70+template <bool kStateIsFp32 = false>
69class Stage1 {71class Stage1 {
70public:72public:
71- __aicore__ inline Stage1(StageOneMT &mm) : mm(mm) {}73+ using vInnerType = std::conditional_t<kStateIsFp32, float, bfloat16_t>;
72- __aicore__ inline void SetGlobalTensors(const GDRStageOneInitParams &initParams)74+ using MMBf16 = StageOneMTT<bfloat16_t>;
75+ using MMVInner = StageOneMTT<vInnerType>;
76+ __aicore__ inline Stage1(MMBf16 &mmBf16, MMVInner &mmVInner) : mmBf16_(mmBf16), mmVInner_(mmVInner) {}
77+ __aicore__ inline void SetGlobalTensors(const GDRStageOneInitParams<vInnerType> &initParams)
73 {78 {
74 queryGm_ = initParams.query;79 queryGm_ = initParams.query;
75 keyGm_ = initParams.key;80 keyGm_ = initParams.key;
@@ -193,7 +198,7 @@ public:
193 WaitFlag<HardEvent::S_V>(eventID);198 WaitFlag<HardEvent::S_V>(eventID);
194 }199 }
195 200 
196- __aicore__ inline void Init(const GDRStageOneInitParams &initParams, TPipe *pipe,201+ __aicore__ inline void Init(const GDRStageOneInitParams<vInnerType> &initParams, TPipe *pipe,
197 const ChunkGatedDeltaRuleTilingData *tilingData)202 const ChunkGatedDeltaRuleTilingData *tilingData)
198 {203 {
199 pipe_ = pipe;204 pipe_ = pipe;
@@ -298,14 +303,14 @@ private:
298 AscendC::CrossCoreWaitFlag(0x9); // 同步0303 AscendC::CrossCoreWaitFlag(0x9); // 同步0
299 // key @ key.transpose(-1,-2)304 // key @ key.transpose(-1,-2)
300 for (uint32_t i = 0; i < curParaNum; ++i) {305 for (uint32_t i = 0; i < curParaNum; ++i) {
301- AICProcess(keyConGm_[i * ckOffset_], keyConGm_[i * ckOffset_], kkWsGm_[i * ccOffset_],306+ AICProcess(mmBf16_, keyConGm_[i * ckOffset_], keyConGm_[i * ckOffset_], kkWsGm_[i * ccOffset_],
302 {chunkSize_, chunkSize_, dk_, chunkSize_, chunkSize_, dk_}, true);307 {chunkSize_, chunkSize_, dk_, chunkSize_, chunkSize_, dk_}, true);
303 }308 }
304 AscendC::CrossCoreSetFlag<0x2, PIPE_FIX>(0x8); // 同步1309 AscendC::CrossCoreSetFlag<0x2, PIPE_FIX>(0x8); // 同步1
305 310 
306 // query @ key.transpose(-1,-2) stage1 out311 // query @ key.transpose(-1,-2) stage1 out
307 for (uint32_t i = 0; i < curParaNum; ++i) {312 for (uint32_t i = 0; i < curParaNum; ++i) {
308- AICProcess(queryConGm_[i * ckOffset_], keyConGm_[i * ckOffset_], outQkGm_[chunkRowBase_[i] * chunkSize_],313+ AICProcess(mmBf16_, queryConGm_[i * ckOffset_], keyConGm_[i * ckOffset_], outQkGm_[chunkRowBase_[i] * chunkSize_],
309 {validLenBatch_[i], validLenBatch_[i], dk_, validLenBatch_[i], validLenBatch_[i], dk_},314 {validLenBatch_[i], validLenBatch_[i], dk_, validLenBatch_[i], validLenBatch_[i], dk_},
310 true);315 true);
311 }316 }
@@ -320,14 +325,15 @@ private:
320 325 
321 // attn @ k_cumdecay326 // attn @ k_cumdecay
322 for (uint32_t i = 0; i < curParaNum; ++i) {327 for (uint32_t i = 0; i < curParaNum; ++i) {
323- AICProcess(attnWsGm_[i * ccOffset_], gBKWsGm_[i * ckOffset_], outKCumdecayGm_[chunkRowBase_[i] * dk_],328+ AICProcess(mmBf16_, attnWsGm_[i * ccOffset_], gBKWsGm_[i * ckOffset_], outKCumdecayGm_[chunkRowBase_[i] * dk_],
324 {chunkSize_, dk_, chunkSize_, chunkSize_, dk_, chunkSize_});329 {chunkSize_, dk_, chunkSize_, chunkSize_, dk_, chunkSize_});
325 }330 }
326 AscendC::CrossCoreWaitFlag(0x5); // 同步4331 AscendC::CrossCoreWaitFlag(0x5); // 同步4
327 332 
328 // attn @ v_beta stage1 out333 // attn @ v_beta stage1 out
329 for (uint32_t i = 0; i < curParaNum; ++i) {334 for (uint32_t i = 0; i < curParaNum; ++i) {
330- AICProcess(attnWsGm_[i * ccOffset_], vBetaWsGm_[i * cvOffset_], outVInnerGm_[chunkRowBase_[i] * dv_],335+ AICProcess(mmVInner_, attnWsGm_[i * ccOffset_], vBetaWsGm_[i * cvOffset_],
336+ outVInnerGm_[chunkRowBase_[i] * dv_],
331 {chunkSize_, dv_, chunkSize_, chunkSize_, dv_, chunkSize_});337 {chunkSize_, dv_, chunkSize_, chunkSize_, dv_, chunkSize_});
332 }338 }
333 }339 }
@@ -794,41 +800,34 @@ private:
794 uint64_t leftDown = offset + chunkSize_ * INVERSE_SHAPE;800 uint64_t leftDown = offset + chunkSize_ * INVERSE_SHAPE;
795 uint64_t rightDown = leftDown + INVERSE_SHAPE;801 uint64_t rightDown = leftDown + INVERSE_SHAPE;
796 // 右矩阵左下角 @ 右矩阵左上角 -> 右矩阵左下角802 // 右矩阵左下角 @ 右矩阵左上角 -> 右矩阵左下角
797- InverseAICProcess(attnWsGm_[leftDown], attnWsGm_[offset], attnWsGm_[leftDown]);803+ AICProcess(mmBf16_, attnWsGm_[leftDown], attnWsGm_[offset], attnWsGm_[leftDown],
804+ {chunkSize_, chunkSize_, chunkSize_, INVERSE_SHAPE, INVERSE_SHAPE, INVERSE_SHAPE});
798 int32_t eventID = static_cast<int32_t>(pipe_->FetchEventID(HardEvent::FIX_MTE2));805 int32_t eventID = static_cast<int32_t>(pipe_->FetchEventID(HardEvent::FIX_MTE2));
799 SetFlag<HardEvent::FIX_MTE2>(eventID);806 SetFlag<HardEvent::FIX_MTE2>(eventID);
800 WaitFlag<HardEvent::FIX_MTE2>(eventID);807 WaitFlag<HardEvent::FIX_MTE2>(eventID);
801 // 右矩阵右下角 @ 右矩阵左下角 -> 右矩阵左下角808 // 右矩阵右下角 @ 右矩阵左下角 -> 右矩阵左下角
802- InverseAICProcess(attnWsGm_[rightDown], attnWsGm_[leftDown], attnWsGm_[leftDown]);809+ AICProcess(mmBf16_, attnWsGm_[rightDown], attnWsGm_[leftDown], attnWsGm_[leftDown],
810+ {chunkSize_, chunkSize_, chunkSize_, INVERSE_SHAPE, INVERSE_SHAPE, INVERSE_SHAPE});
803 eventID = static_cast<int32_t>(pipe_->FetchEventID(HardEvent::FIX_MTE2));811 eventID = static_cast<int32_t>(pipe_->FetchEventID(HardEvent::FIX_MTE2));
804 SetFlag<HardEvent::FIX_MTE2>(eventID);812 SetFlag<HardEvent::FIX_MTE2>(eventID);
805 WaitFlag<HardEvent::FIX_MTE2>(eventID);813 WaitFlag<HardEvent::FIX_MTE2>(eventID);
806 }814 }
807 815 
808- __aicore__ inline void AICProcess(GlobalTensor<bfloat16_t> x, GlobalTensor<bfloat16_t> y,816+ template <typename MMType, typename CType>
809- GlobalTensor<bfloat16_t> z, const MatmulShapeParams &shape, bool transB = false)817+ __aicore__ inline void AICProcess(MMType &mmRef, GlobalTensor<bfloat16_t> x, GlobalTensor<bfloat16_t> y,
818+ GlobalTensor<CType> z, const MatmulShapeParams &shape, bool transB = false)
810 {819 {
811- mm.SetOrgShape(shape.m, shape.n, shape.k);820+ mmRef.SetOrgShape(shape.m, shape.n, shape.k);
812- mm.SetSingleShape(shape.sm, shape.sn, shape.sk);821+ mmRef.SetSingleShape(shape.sm, shape.sn, shape.sk);
813- mm.SetTensorA(x);822+ mmRef.SetTensorA(x);
814- mm.SetTensorB(y, transB);823+ mmRef.SetTensorB(y, transB);
815- mm.IterateAll(z);824+ mmRef.IterateAll(z);
816- mm.End();825+ mmRef.End();
817- }
818- 
819- __aicore__ inline void InverseAICProcess(GlobalTensor<bfloat16_t> x, GlobalTensor<bfloat16_t> y,
820- GlobalTensor<bfloat16_t> z)
821- {
822- mm.SetOrgShape(chunkSize_, chunkSize_, chunkSize_);
823- mm.SetSingleShape(INVERSE_SHAPE, INVERSE_SHAPE, INVERSE_SHAPE);
824- mm.SetTensorA(x);
825- mm.SetTensorB(y);
826- mm.IterateAll(z);
827- mm.End();
828 }826 }
829 827
830 TPipe *pipe_;828 TPipe *pipe_;
831- StageOneMT &mm;829+ MMBf16 &mmBf16_;
830+ MMVInner &mmVInner_;
832 const ChunkGatedDeltaRuleTilingData *tiling_;831 const ChunkGatedDeltaRuleTilingData *tiling_;
833 ChunkGroup cg_;832 ChunkGroup cg_;
834 uint32_t nk_;833 uint32_t nk_;
@@ -867,7 +866,7 @@ private:
867 GlobalTensor<float> gGm_;866 GlobalTensor<float> gGm_;
868 GlobalTensor<float> outGCumExpGm_;867 GlobalTensor<float> outGCumExpGm_;
869 GlobalTensor<bfloat16_t> outKCumdecayGm_;868 GlobalTensor<bfloat16_t> outKCumdecayGm_;
870- GlobalTensor<bfloat16_t> outVInnerGm_;869+ GlobalTensor<vInnerType> outVInnerGm_;
871 GlobalTensor<bfloat16_t> outQPrimeGm_;870 GlobalTensor<bfloat16_t> outQPrimeGm_;
872 GlobalTensor<bfloat16_t> outKgBaseGm_;871 GlobalTensor<bfloat16_t> outKgBaseGm_;
873 GlobalTensor<bfloat16_t> outKgGm_;872 GlobalTensor<bfloat16_t> outKgGm_;
@@ -25,20 +25,26 @@ using namespace matmul;
25 25 
26using aT2 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t, true>;26using aT2 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t, true>;
27using bT2 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t, true>;27using bT2 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t, true>;
28-using cT2 = MatmulType<TPosition::GM, CubeFormat::ND, bfloat16_t>;28+template <typename cType>
29-using StageTwoMT = matmul::MatmulImpl<aT2, bT2, cT2>;29+using StageTwoMTT = matmul::MatmulImpl<aT2, bT2, MatmulType<TPosition::GM, CubeFormat::ND, cType>>;
30+using StageTwoMT = StageTwoMTT<bfloat16_t>;
31+using StageTwoMTFp32C = StageTwoMTT<float>;
30 32 
33+template <typename stateType>
31struct StageTwoParams {34struct StageTwoParams {
32- GlobalTensor<bfloat16_t> qPrime; // (Nv, Sp, Dk)35+ GlobalTensor<bfloat16_t> qPrime; // (Nv, Sp, Dk)
33- GlobalTensor<bfloat16_t> vInner; // (Nv, Sp, Dv)36+ GlobalTensor<stateType> vInner; // (Nv, Sp, Dv)
34- GlobalTensor<float> gCum; // (Nv, Sp)37+ GlobalTensor<bfloat16_t> vInnerBf16; // (Nv, Sp, Dv) BF16 vInner for stage3/CalStateNew (FP32 path)
35- GlobalTensor<bfloat16_t> kCumdecay; // (Nv, Sp, Dk)38+ GlobalTensor<float> gCum; // (Nv, Sp)
36- GlobalTensor<bfloat16_t> curState; // (Nv, Dv, Dk)39+ GlobalTensor<bfloat16_t> kCumdecay; // (Nv, Sp, Dk)
37- GlobalTensor<bfloat16_t> finalState; // (Nv, Dv, Dk)40+ GlobalTensor<bfloat16_t> curStateBf16; // (Nv, Dv, Dk) BF16 state for AIC
41+ GlobalTensor<stateType> stateIn; // (Nv, Dv, Dk) state input
42+ GlobalTensor<stateType> stateOut; // (Nv, Dv, Dk) state output
38 GlobalTensor<bfloat16_t> kg;43 GlobalTensor<bfloat16_t> kg;
39 GlobalTensor<bfloat16_t> out;44 GlobalTensor<bfloat16_t> out;
40 GM_ADDR ws;45 GM_ADDR ws;
41- StageTwoMT *mm1;46+ StageTwoMT *mm1Bf16;
47+ StageTwoMTFp32C *mm1Fp32;
42 TPipe *pipe;48 TPipe *pipe;
43 ChunkGroup *cg;49 ChunkGroup *cg;
44 int64_t Nv;50 int64_t Nv;
@@ -48,11 +54,15 @@ struct StageTwoParams {
48 int64_t stateStride1;54 int64_t stateStride1;
49 bool useInitialState;55 bool useInitialState;
50 bool gOptional;56 bool gOptional;
57+ bool isFirstGroup;
51};58};
52 59 
60+template <typename stateType = bfloat16_t>
53class Stage2 {61class Stage2 {
54public:62public:
55- __aicore__ inline void Init(StageTwoParams *initParams, int32_t coreNum)63+ static constexpr bool kIsFp32 = std::is_same_v<stateType, float>;
64+ 
65+ __aicore__ inline void Init(StageTwoParams<stateType> *initParams, int32_t coreNum)
56 {66 {
57 sTP_ = initParams;67 sTP_ = initParams;
58 pipe_ = sTP_->pipe;68 pipe_ = sTP_->pipe;
@@ -70,6 +80,7 @@ public:
70 useInitialState_ = sTP_->useInitialState;80 useInitialState_ = sTP_->useInitialState;
71 stateStride1_ = (useInitialState_) ? sTP_->stateStride1 : Dv_ * Dk_;81 stateStride1_ = (useInitialState_) ? sTP_->stateStride1 : Dv_ * Dk_;
72 gOptional_ = sTP_->gOptional;82 gOptional_ = sTP_->gOptional;
83+ isFirstGroup_ = sTP_->isFirstGroup;
73 InitLocalBuffers();84 InitLocalBuffers();
74 }85 }
75 86 
@@ -78,18 +89,31 @@ public:
78 if ASCEND_IS_AIC {89 if ASCEND_IS_AIC {
79 return;90 return;
80 }91 }
81- pipe_->InitBuffer(inQueue_, BUFFER_NUM_ONE, Std::max((uint64_t)chunkSize_,92+ if constexpr (kIsFp32) {
82- (uint64_t)Dv_) * curDk_ * sizeof(bfloat16_t));93+ uint64_t inSize = Std::max((uint64_t)chunkSize_, (uint64_t)Dv_) * curDk_ * sizeof(float);
83- uint64_t outQueueSize = Std::max((uint64_t)chunkSize_ * chunkSize_ * sizeof(bfloat16_t),94+ uint64_t vInnerCastInSize = chunkSize_ * Dv_ * sizeof(float);
84- (uint64_t)Dv_ * curDk_ * sizeof(bfloat16_t));95+ uint64_t vInnerCastOutSize = chunkSize_ * Dv_ * sizeof(bfloat16_t);
85- pipe_->InitBuffer(outQueue_, BUFFER_NUM_ONE, outQueueSize);96+ pipe_->InitBuffer(inQueue_, BUFFER_NUM_ONE, Std::max(inSize, vInnerCastInSize));
86- pipe_->InitBuffer(tmpBuff_, (Std::max((uint64_t)chunkSize_, (uint64_t)Dv_) * curDk_ +97+ uint64_t outSize = Std::max(inSize, vInnerCastOutSize);
87- BLOCK_FLOAT_NUM) *sizeof(float));98+ pipe_->InitBuffer(outQueue_, BUFFER_NUM_ONE, outSize);
88- uint32_t buffOffset = 0;99+ pipe_->InitBuffer(tmpBuff_, (Dv_ * curDk_ + BLOCK_FLOAT_NUM) * sizeof(float));
89- tmpBuffer1_ = tmpBuff_.GetWithOffset<float>(static_cast<uint32_t>(Dv_ * curDk_), buffOffset);100+ uint32_t buffOffset = 0;
90- buffOffset += Ceil(Dv_ * curDk_ * sizeof(float), BLOCK_SIZE) * BLOCK_SIZE;101+ stateFp32Ub_ = tmpBuff_.GetWithOffset<float>(static_cast<uint32_t>(Dv_ * curDk_), buffOffset);
91- // 暂存所取的最后一位数102+ buffOffset += Ceil(Dv_ * curDk_ * sizeof(float), BLOCK_SIZE) * BLOCK_SIZE;
92- lastGCum_ = tmpBuff_.GetWithOffset<float>(static_cast<uint32_t>(NUM_ONE), buffOffset);103+ lastGCum_ = tmpBuff_.GetWithOffset<float>(static_cast<uint32_t>(NUM_ONE), buffOffset);
104+ } else {
105+ pipe_->InitBuffer(inQueue_, BUFFER_NUM_ONE, Std::max((uint64_t)chunkSize_,
106+ (uint64_t)Dv_) * curDk_ * sizeof(bfloat16_t));
107+ uint64_t outQueueSize = Std::max((uint64_t)chunkSize_ * chunkSize_ * sizeof(bfloat16_t),
108+ (uint64_t)Dv_ * curDk_ * sizeof(bfloat16_t));
109+ pipe_->InitBuffer(outQueue_, BUFFER_NUM_ONE, outQueueSize);
110+ pipe_->InitBuffer(tmpBuff_, (Std::max((uint64_t)chunkSize_, (uint64_t)Dv_) * curDk_ +
111+ BLOCK_FLOAT_NUM) *sizeof(float));
112+ uint32_t buffOffset = 0;
113+ tmpBuffer1_ = tmpBuff_.GetWithOffset<float>(static_cast<uint32_t>(Dv_ * curDk_), buffOffset);
114+ buffOffset += Ceil(Dv_ * curDk_ * sizeof(float), BLOCK_SIZE) * BLOCK_SIZE;
115+ lastGCum_ = tmpBuff_.GetWithOffset<float>(static_cast<uint32_t>(NUM_ONE), buffOffset);
116+ }
93 }117 }
94 118 
95 __aicore__ inline void Process()119 __aicore__ inline void Process()
@@ -106,45 +130,132 @@ public:
106 for (int64_t nvId = nvStart; nvId < nvEnd; nvId++) {130 for (int64_t nvId = nvStart; nvId < nvEnd; nvId++) {
107 curChunkSize_ = chunkSize_;131 curChunkSize_ = chunkSize_;
108 for (int64_t cId = 0; cId < chunkNum_; cId++) {132 for (int64_t cId = 0; cId < chunkNum_; cId++) {
109- auto curState = (cId == 0) ? sTP_->curState[nvId * stateStride1_] : sTP_->finalState[nvId * Dv_ * Dk_];
110- auto finalState = sTP_->finalState[nvId * Dv_ * Dk_];
111 int64_t length = cId * chunkSize_;133 int64_t length = cId * chunkSize_;
112 if (cId == chunkNum_ - 1) {134 if (cId == chunkNum_ - 1) {
113 curChunkSize_ = lastChunkSize;135 curChunkSize_ = lastChunkSize;
114 }136 }
115 if ASCEND_IS_AIV {137 if ASCEND_IS_AIV {
116- if (GetSubBlockIdx() == 0) {138+ if constexpr (kIsFp32) {
117- CopyIn(curState, Dv_, Dk_);139+ ProcessAivFp32(nvId, cId, length);
118- CalGCumExp(sTP_->gCum[nvId * Sp_ + length]);140+ } else {
141+ ProcessAivBf16(nvId, cId, length);
119 }142 }
120- CrossCoreWaitFlag(0x2);
121- if (GetSubBlockIdx() == 0) {
122- CopyOutState(finalState);
123- }
124- CrossCoreSetFlag<0x2, PIPE_MTE3>(0x5);
125- CrossCoreWaitFlag(0x4);
126 }143 }
127 if ASCEND_IS_AIC {144 if ASCEND_IS_AIC {
128- uint64_t mm_offset0 = nvId * Sp_ * Dk_ + length * Dk_;145+ ProcessAic(nvId, cId, length);
129- uint64_t mm_offset1 = nvId * Sp_ * Dv_ + length * Dv_;
130- CalVPrime(sTP_->kCumdecay[mm_offset0], curState, sTP_->vInner[mm_offset1]);
131- CalAttnInter(sTP_->qPrime[mm_offset0], curState,
132- sTP_->out[nvId * Dv_ + cId * chunkSize_ * Nv_ * Dv_]);
133- CrossCoreSetFlag<0x2, PIPE_FIX>(0x2); // 读完之前AIV不能写
134- CrossCoreWaitFlag(0x5);
135- CalStateNew(sTP_->vInner[mm_offset1], sTP_->kg[mm_offset0], finalState);
136- SetFlag<HardEvent::FIX_MTE2>(FIX_MTE2_EVENT);
137- WaitFlag<HardEvent::FIX_MTE2>(FIX_MTE2_EVENT);
138- CrossCoreSetFlag<0x2, PIPE_FIX>(0x4);
139 }146 }
140 }147 }
141 }148 }
142 }149 }
143 150 
144- __aicore__ inline void CalGCumExp(GlobalTensor<float> gCum)151+ __aicore__ inline void ProcessAivFp32(int64_t nvId, int64_t cId, int64_t length)
152+ {
153+ if (GetSubBlockIdx() == 0) {
154+ if (isFirstGroup_ && cId == 0) {
155+ CopyIn<float>(sTP_->stateIn[nvId * stateStride1_], Dv_, Dk_);
156+ } else {
157+ CopyIn<float>(sTP_->stateOut[nvId * Dv_ * Dk_], Dv_, Dk_);
158+ }
159+ auto stateIn = inQueue_.DeQue<float>();
160+ DataCopy(stateFp32Ub_, stateIn, Dv_ * curDk_);
161+ inQueue_.FreeTensor(stateIn);
162+ SetFlag<HardEvent::MTE2_V>(MTE2_V_EVENT);
163+ WaitFlag<HardEvent::MTE2_V>(MTE2_V_EVENT);
164+ auto bf16State = outQueue_.AllocTensor<bfloat16_t>();
165+ Cast(bf16State, stateFp32Ub_, RoundMode::CAST_RINT, Dv_ * curDk_);
166+ outQueue_.EnQue(bf16State);
167+ CopyOut<bfloat16_t>(sTP_->curStateBf16[nvId * Dv_ * Dk_], Dv_, Dk_, false, curDk_);
168+ CalGCumExpFp32(sTP_->gCum[nvId * Sp_ + length]);
169+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
170+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
171+ PipeBarrier<PIPE_MTE3>();
172+ auto fp32Local = outQueue_.AllocTensor<float>();
173+ DataCopy(fp32Local, stateFp32Ub_, Dv_ * curDk_);
174+ outQueue_.EnQue(fp32Local);
175+ CopyOut<float>(sTP_->stateOut[nvId * Dv_ * Dk_], Dv_, Dk_, false, curDk_);
176+ }
177+ CrossCoreSetFlag<0x2, PIPE_MTE3>(0x3);
178+ CrossCoreWaitFlag(0x2);
179+ if (GetSubBlockIdx() == 0) {
180+ PipeBarrier<PIPE_MTE3>();
181+ uint64_t mm_offset1 = nvId * Sp_ * Dv_ + length * Dv_;
182+ CastGmToGm<float, bfloat16_t>(sTP_->vInner[mm_offset1],
183+ sTP_->vInnerBf16[mm_offset1],
184+ curChunkSize_ * Dv_);
185+ }
186+ CrossCoreSetFlag<0x2, PIPE_MTE3>(0x5);
187+ CrossCoreWaitFlag(0x4);
188+ }
189+ 
190+ __aicore__ inline void ProcessAivBf16(int64_t nvId, int64_t cId, int64_t length)
191+ {
192+ auto curState = (cId == 0) ? sTP_->curStateBf16[nvId * stateStride1_]
193+ : sTP_->stateOut[nvId * Dv_ * Dk_];
194+ auto finalState = sTP_->stateOut[nvId * Dv_ * Dk_];
195+ if (GetSubBlockIdx() == 0) {
196+ CopyIn(curState, Dv_, Dk_);
197+ CalGCumExpBf16(sTP_->gCum[nvId * Sp_ + length]);
198+ }
199+ CrossCoreWaitFlag(0x2);
200+ if (GetSubBlockIdx() == 0) {
201+ CopyOutState(finalState);
202+ }
203+ CrossCoreSetFlag<0x2, PIPE_MTE3>(0x5);
204+ CrossCoreWaitFlag(0x4);
205+ }
206+ 
207+ __aicore__ inline void ProcessAic(int64_t nvId, int64_t cId, int64_t length)
208+ {
209+ uint64_t mm_offset0 = nvId * Sp_ * Dk_ + length * Dk_;
210+ uint64_t mm_offset1 = nvId * Sp_ * Dv_ + length * Dv_;
211+ auto stateOut = sTP_->stateOut[nvId * Dv_ * Dk_];
212+ GlobalTensor<bfloat16_t> stateForAic;
213+ if constexpr (kIsFp32) {
214+ CrossCoreWaitFlag(0x3);
215+ stateForAic = sTP_->curStateBf16[nvId * Dv_ * Dk_];
216+ } else {
217+ stateForAic = (cId == 0) ? sTP_->curStateBf16[nvId * stateStride1_]
218+ : sTP_->stateOut[nvId * Dv_ * Dk_];
219+ }
220+ CalVPrime(sTP_->kCumdecay[mm_offset0], stateForAic, sTP_->vInner[mm_offset1]);
221+ CalAttnInter(sTP_->qPrime[mm_offset0], stateForAic,
222+ sTP_->out[nvId * Dv_ + cId * chunkSize_ * Nv_ * Dv_]);
223+ CrossCoreSetFlag<0x2, PIPE_FIX>(0x2);
224+ CrossCoreWaitFlag(0x5);
225+ if constexpr (kIsFp32) {
226+ CalStateNew(sTP_->vInnerBf16[mm_offset1],
227+ sTP_->kg[mm_offset0], stateOut);
228+ } else {
229+ CalStateNew(sTP_->vInner[mm_offset1], sTP_->kg[mm_offset0], stateOut);
230+ }
231+ SetFlag<HardEvent::FIX_MTE2>(FIX_MTE2_EVENT);
232+ WaitFlag<HardEvent::FIX_MTE2>(FIX_MTE2_EVENT);
233+ CrossCoreSetFlag<0x2, PIPE_FIX>(0x4);
234+ }
235+ 
236+ __aicore__ inline void CalGCumExpFp32(GlobalTensor<float> gCum)
237+ {
238+ if (!gOptional_) {
239+ return;
240+ }
241+ DataCacheCleanAndInvalid<float,
242+ CacheLine::SINGLE_CACHE_LINE,
243+ DcciDst::CACHELINE_OUT>(gCum[curChunkSize_ - 1]);
244+ float gVal = gCum.GetValue(curChunkSize_ - 1);
245+ lastGCum_.SetValue(0, gVal);
246+ SetFlag<HardEvent::S_V>(S_V_EVENT);
247+ WaitFlag<HardEvent::S_V>(S_V_EVENT);
248+ Exp<float, 0, true>(lastGCum_, lastGCum_, 1);
249+ float tmpFloat = lastGCum_.GetValue(0);
250+ SetFlag<HardEvent::S_V>(S_V_EVENT);
251+ WaitFlag<HardEvent::S_V>(S_V_EVENT);
252+ Muls(stateFp32Ub_, stateFp32Ub_, tmpFloat, Dv_ * curDk_);
253+ PipeBarrier<PIPE_V>();
254+ }
255+ 
256+ __aicore__ inline void CalGCumExpBf16(GlobalTensor<float> gCum)
145 {257 {
146 if (gOptional_) {258 if (gOptional_) {
147- // 刷新cache
148 DataCacheCleanAndInvalid<float,259 DataCacheCleanAndInvalid<float,
149 CacheLine::SINGLE_CACHE_LINE,260 CacheLine::SINGLE_CACHE_LINE,
150 DcciDst::CACHELINE_OUT>(gCum[curChunkSize_ - 1]);261 DcciDst::CACHELINE_OUT>(gCum[curChunkSize_ - 1]);
@@ -172,54 +283,126 @@ public:
172 inQueue_.FreeTensor(stateIn);283 inQueue_.FreeTensor(stateIn);
173 }284 }
174 285 
286+ template <typename MMType, typename AT, typename BT, typename CT>
287+ __aicore__ inline void RunMatmul(MMType *mm, GlobalTensor<AT> a, bool transA,
288+ GlobalTensor<BT> b, bool transB,
289+ GlobalTensor<CT> c, int64_t M, int64_t N, int64_t K, int32_t accum)
290+ {
291+ mm->SetOrgShape(M, N, K);
292+ mm->SetSingleShape(M, N, K);
293+ mm->SetTensorA(a, transA);
294+ mm->SetTensorB(b, transB);
295+ mm->IterateAll(c, accum);
296+ mm->End();
297+ }
298+ 
299+ template <typename MMType, typename AT, typename BT, typename CT>
300+ __aicore__ inline void RunMatmul(MMType *mm, GlobalTensor<AT> a, bool transA,
301+ GlobalTensor<BT> b, bool transB,
302+ GlobalTensor<CT> c, int64_t M, int64_t N, int64_t K,
303+ int64_t Ka, int64_t Kb, int32_t accum = 0)
304+ {
305+ mm->SetOrgShape(M, N, K, Ka, Kb);
306+ mm->SetSingleShape(M, N, K);
307+ mm->SetTensorA(a, transA);
308+ mm->SetTensorB(b, transB);
309+ mm->IterateAll(c, accum);
310+ mm->End();
311+ }
312+ 
175 __aicore__ inline void CalAttnInter(GlobalTensor<bfloat16_t> qPrime,313 __aicore__ inline void CalAttnInter(GlobalTensor<bfloat16_t> qPrime,
176 GlobalTensor<bfloat16_t> state,314 GlobalTensor<bfloat16_t> state,
177 GlobalTensor<bfloat16_t> out)315 GlobalTensor<bfloat16_t> out)
178 {316 {
179- // q_prime @ state.transpose(0, 1)317+ RunMatmul(sTP_->mm1Bf16, qPrime, false, state, true, out,
180- sTP_->mm1->SetOrgShape(curChunkSize_, Dv_, Dk_, Dk_, Nv_ * Dv_); // MNKaKbN318+ curChunkSize_, Dv_, Dk_, Dk_, Nv_ * Dv_);
181- sTP_->mm1->SetSingleShape(curChunkSize_, Dv_, Dk_); // SingleCoreMNK
182- sTP_->mm1->SetTensorA(qPrime, false);
183- sTP_->mm1->SetTensorB(state, true);
184- sTP_->mm1->IterateAll(out);
185- sTP_->mm1->End();
186 }319 }
187 320 
321+ template <typename vInnerType>
188 __aicore__ inline void CalVPrime(GlobalTensor<bfloat16_t> kCumdecay,322 __aicore__ inline void CalVPrime(GlobalTensor<bfloat16_t> kCumdecay,
189 GlobalTensor<bfloat16_t> state,323 GlobalTensor<bfloat16_t> state,
190- GlobalTensor<bfloat16_t> vPrime)324+ GlobalTensor<vInnerType> vPrime)
191 {325 {
192- // v_inner += k_cumdecay @ state.transpose(0, 1)326+ if constexpr (kIsFp32) {
193- sTP_->mm1->SetOrgShape(curChunkSize_, Dv_, Dk_); // MNK327+ RunMatmul(sTP_->mm1Fp32, kCumdecay, false, state, true, vPrime,
194- sTP_->mm1->SetSingleShape(curChunkSize_, Dv_, Dk_); // SingleCoreMNK328+ curChunkSize_, Dv_, Dk_, 1);
195- sTP_->mm1->SetTensorA(kCumdecay, false);329+ } else {
196- sTP_->mm1->SetTensorB(state, true);330+ RunMatmul(sTP_->mm1Bf16, kCumdecay, false, state, true, vPrime,
197- sTP_->mm1->IterateAll(vPrime, 1);331+ curChunkSize_, Dv_, Dk_, 1);
198- sTP_->mm1->End();332+ }
199 }333 }
200 334 
335+ template <typename stateOutType>
201 __aicore__ inline void CalStateNew(GlobalTensor<bfloat16_t> vInner,336 __aicore__ inline void CalStateNew(GlobalTensor<bfloat16_t> vInner,
202 GlobalTensor<bfloat16_t> kg,337 GlobalTensor<bfloat16_t> kg,
203- GlobalTensor<bfloat16_t> state)338+ GlobalTensor<stateOutType> state)
204 {339 {
205- // state_out = v_new.transpose(0, 1) @ kg340+ if constexpr (kIsFp32) {
206- sTP_->mm1->SetOrgShape(Dv_, Dk_, curChunkSize_); // MNK341+ RunMatmul(sTP_->mm1Fp32, vInner, true, kg, false, state,
207- sTP_->mm1->SetSingleShape(Dv_, Dk_, curChunkSize_); // SingleCoreMNK342+ Dv_, Dk_, curChunkSize_, 1);
208- sTP_->mm1->SetTensorA(vInner, true);343+ } else {
209- sTP_->mm1->SetTensorB(kg, false);344+ RunMatmul(sTP_->mm1Bf16, vInner, true, kg, false, state,
210- sTP_->mm1->IterateAll(state, 1);345+ Dv_, Dk_, curChunkSize_, 1);
211- sTP_->mm1->End();346+ }
347+ }
348+ 
349+ template <typename srcType, typename dstType>
350+ __aicore__ inline void CastGmToGm(GlobalTensor<srcType> srcGm, GlobalTensor<dstType> dstGm,
351+ int32_t count)
352+ {
353+ int32_t paddedCount = Ceil(count, BLOCK_SIZE / sizeof(dstType)) * (BLOCK_SIZE / sizeof(dstType));
354+ int32_t srcAlign = BLOCK_SIZE / sizeof(srcType);
355+ int32_t srcPadded = Ceil(count, srcAlign) * srcAlign;
356+ int32_t padding = srcPadded - count;
357+ 
358+ auto srcLocal = inQueue_.AllocTensor<srcType>();
359+ if (paddedCount > srcPadded) {
360+ Duplicate<srcType>(srcLocal, static_cast<srcType>(0), paddedCount);
361+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
362+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
363+ }
364+ DataCopyExtParams inParams{1, static_cast<uint32_t>(count * sizeof(srcType)), 0, 0, 0};
365+ DataCopyPadExtParams<srcType> inPadParams{true, 0, static_cast<uint8_t>(padding), 0};
366+ DataCopyPad(srcLocal, srcGm, inParams, inPadParams);
367+ inQueue_.EnQue(srcLocal);
368+ 
369+ srcLocal = inQueue_.DeQue<srcType>();
370+ auto dstLocal = outQueue_.AllocTensor<dstType>();
371+ Cast(dstLocal, srcLocal, RoundMode::CAST_RINT, paddedCount);
372+ inQueue_.FreeTensor(srcLocal);
373+ outQueue_.EnQue(dstLocal);
374+ 
375+ dstLocal = outQueue_.DeQue<dstType>();
376+ DataCopyExtParams outParams{1, static_cast<uint32_t>(count * sizeof(dstType)), 0, 0, 0};
377+ DataCopyPadExtParams<dstType> outPadParams{false, 0, 0, 0};
378+ DataCopyPad(dstGm, dstLocal, outParams);
379+ outQueue_.FreeTensor(dstLocal);
212 }380 }
213 381 
214 template <typename inType>382 template <typename inType>
215 __aicore__ inline void CopyIn(GlobalTensor<inType> tmpGM, int32_t row, int32_t col)383 __aicore__ inline void CopyIn(GlobalTensor<inType> tmpGM, int32_t row, int32_t col)
216 {384 {
217 LocalTensor<inType> inLocal = inQueue_.AllocTensor<inType>();385 LocalTensor<inType> inLocal = inQueue_.AllocTensor<inType>();
386+ int padding;
387+ uint32_t dstStride = 0;
388+ if constexpr (kIsFp32 && std::is_same_v<inType, float>) {
389+ int32_t floatAligned = Ceil(col, BLOCK_FLOAT_NUM) * BLOCK_FLOAT_NUM;
390+ padding = floatAligned - col;
391+ if (floatAligned < curDk_) {
392+ uint32_t dataBlocks = static_cast<uint32_t>(floatAligned * sizeof(float) / BLOCK_SIZE);
393+ uint32_t rowBlocks = static_cast<uint32_t>(curDk_ * sizeof(float) / BLOCK_SIZE);
394+ dstStride = rowBlocks - dataBlocks;
395+ Duplicate<inType>(inLocal, static_cast<inType>(0), row * curDk_);
396+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
397+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
398+ }
399+ } else {
400+ padding = Ceil(col, BLOCK_SIZE / sizeof(inType)) * (BLOCK_SIZE / sizeof(inType)) - col;
401+ }
218 DataCopyExtParams inParams{static_cast<uint16_t>(row),402 DataCopyExtParams inParams{static_cast<uint16_t>(row),
219- static_cast<uint32_t>(col * sizeof(inType)), // 非对齐情况需要补0403+ static_cast<uint32_t>(col * sizeof(inType)),
220 static_cast<uint32_t>(0),404 static_cast<uint32_t>(0),
221- 0, 0};405+ dstStride, 0};
222- int padding = Ceil(col, BLOCK_SIZE / sizeof(inType)) * (BLOCK_SIZE / sizeof(inType)) - col;
223 DataCopyPadExtParams<inType> copyPadParams{true, 0, static_cast<uint8_t>(padding), 0};406 DataCopyPadExtParams<inType> copyPadParams{true, 0, static_cast<uint8_t>(padding), 0};
224 DataCopyPad(inLocal, tmpGM, inParams, copyPadParams);407 DataCopyPad(inLocal, tmpGM, inParams, copyPadParams);
225 inQueue_.EnQue(inLocal);408 inQueue_.EnQue(inLocal);
@@ -231,13 +414,24 @@ public:
231 }414 }
232 415 
233 template <typename outType>416 template <typename outType>
234- __aicore__ inline void CopyOut(GlobalTensor<outType> tmpGM, int32_t row, int32_t col, bool setAtomic = false)417+ __aicore__ inline void CopyOut(GlobalTensor<outType> tmpGM, int32_t row, int32_t col,
418+ bool setAtomic = false, int32_t srcCol = 0)
235 {419 {
236 auto outLocal = outQueue_.DeQue<outType>();420 auto outLocal = outQueue_.DeQue<outType>();
237 DataCopyExtParams copyParams;421 DataCopyExtParams copyParams;
238 copyParams.blockCount = static_cast<uint16_t>(row);422 copyParams.blockCount = static_cast<uint16_t>(row);
239 copyParams.blockLen = static_cast<uint32_t>(col * sizeof(outType));423 copyParams.blockLen = static_cast<uint32_t>(col * sizeof(outType));
240- copyParams.srcStride = static_cast<uint32_t>(0);424+ if (srcCol > col) {
425+ uint32_t actualReadBytes = Ceil(col * sizeof(outType), BLOCK_SIZE) * BLOCK_SIZE;
426+ uint32_t srcRowBytes = srcCol * sizeof(outType);
427+ if (srcRowBytes >= actualReadBytes && (srcRowBytes - actualReadBytes) % BLOCK_SIZE == 0) {
428+ copyParams.srcStride = (srcRowBytes - actualReadBytes) / BLOCK_SIZE;
429+ } else {
430+ copyParams.srcStride = 0;
431+ }
432+ } else {
433+ copyParams.srcStride = static_cast<uint32_t>(0);
434+ }
241 copyParams.dstStride = static_cast<uint32_t>(0);435 copyParams.dstStride = static_cast<uint32_t>(0);
242 if (setAtomic) {436 if (setAtomic) {
243 SetAtomicAdd<outType>();437 SetAtomicAdd<outType>();
@@ -250,13 +444,14 @@ public:
250 }444 }
251 445 
252private:446private:
253- StageTwoParams *sTP_;447+ StageTwoParams<stateType> *sTP_;
254 TPipe *pipe_;448 TPipe *pipe_;
255 TQue<QuePosition::VECIN, BUFFER_NUM_ONE> inQueue_;449 TQue<QuePosition::VECIN, BUFFER_NUM_ONE> inQueue_;
256 TQue<QuePosition::VECOUT, BUFFER_NUM_ONE> outQueue_;450 TQue<QuePosition::VECOUT, BUFFER_NUM_ONE> outQueue_;
257 TBuf<TPosition::VECCALC> tmpBuff_;451 TBuf<TPosition::VECCALC> tmpBuff_;
258 LocalTensor<float> tmpBuffer1_;452 LocalTensor<float> tmpBuffer1_;
259 LocalTensor<float> lastGCum_;453 LocalTensor<float> lastGCum_;
454+ LocalTensor<float> stateFp32Ub_;
260 int64_t Nk_;455 int64_t Nk_;
261 int64_t Nv_;456 int64_t Nv_;
262 int64_t Dk_;457 int64_t Dk_;
@@ -271,6 +466,7 @@ private:
271 int64_t stateStride1_;466 int64_t stateStride1_;
272 bool useInitialState_;467 bool useInitialState_;
273 bool gOptional_;468 bool gOptional_;
469+ bool isFirstGroup_;
274};470};
275} // namespace ChunkGatedDeltaRule471} // namespace ChunkGatedDeltaRule
276-#endif // CHUNK_GATED_DELTA_RULE_STAGE2_H472+#endif // CHUNK_GATED_DELTA_RULE_STAGE2_H
@@ -31,6 +31,7 @@ namespace ChunkGatedDeltaRule {
31 constexpr uint64_t MTE3_S_EVENT = 5;31 constexpr uint64_t MTE3_S_EVENT = 5;
32 constexpr uint64_t FIX_MTE2_EVENT = 6;32 constexpr uint64_t FIX_MTE2_EVENT = 6;
33 constexpr uint64_t S_MTE3_EVENT = 6;33 constexpr uint64_t S_MTE3_EVENT = 6;
34+ constexpr uint64_t V_MTE2_EVENT = 7;
34 35 
35 constexpr uint64_t NUM_ONE = 1;36 constexpr uint64_t NUM_ONE = 1;
36 constexpr uint64_t BUFFER_NUM_ONE = 1;37 constexpr uint64_t BUFFER_NUM_ONE = 1;
@@ -15,6 +15,7 @@
15 15 
16#include "arch35/chunk_gated_delta_rule.h"16#include "arch35/chunk_gated_delta_rule.h"
17#include "chunk_gated_delta_rule_tiling_data.h"17#include "chunk_gated_delta_rule_tiling_data.h"
18+#include "chunk_gated_delta_rule_tiling_key.h"
18 19 
19using namespace AscendC;20using namespace AscendC;
20using namespace matmul;21using namespace matmul;
@@ -30,11 +31,16 @@ extern "C" __global__ __aicore__ void chunk_gated_delta_rule(
30 TPipe pipe;31 TPipe pipe;
31 32 
32 __gm__ uint8_t *user = GetUserWorkspace(workspaceGM);33 __gm__ uint8_t *user = GetUserWorkspace(workspaceGM);
33-
34- CGDR<bfloat16_t, float> op(&pipe, &tilingData);
35 CGDRInitParams initParams{34 CGDRInitParams initParams{
36 query, key, value, beta, initialState, seqlens, gOptional,35 query, key, value, beta, initialState, seqlens, gOptional,
37 out, finalState};36 out, finalState};
38- op.Init(initParams, user);37+ if (TILING_KEY_IS(TILING_KEY_CGDR_FP32_STATE)) {
39- op.Process();38+ CGDR<bfloat16_t, float, float> op(&pipe, &tilingData);
39+ op.Init(initParams, user);
40+ op.Process();
41+ } else if (TILING_KEY_IS(TILING_KEY_CGDR_BF16_STATE)) {
42+ CGDR<bfloat16_t, float, bfloat16_t> op(&pipe, &tilingData);
43+ op.Init(initParams, user);
44+ op.Process();
45+ }
40}46}
@@ -35,10 +35,12 @@ namespace ChunkGatedDeltaRule {
35 int64_t interWorkspaceSz;35 int64_t interWorkspaceSz;
36 int64_t stageWorkspaceSz;36 int64_t stageWorkspaceSz;
37 int64_t stageOneParaNum;37 int64_t stageOneParaNum;
38+ float scale;
39+ AscendC::tiling::TCubeTiling matmulTilingFp32; // BF16 C matmul tiling
40+ AscendC::tiling::TCubeTiling matmulTilingFp32C; // FP32 C matmul tiling (for FP32 state path)
41+ int64_t stateIsFp32;
38 int64_t stateStride0;42 int64_t stateStride0;
39 int64_t stateStride1;43 int64_t stateStride1;
40- float scale;
41- AscendC::tiling::TCubeTiling matmulTilingFp32; // for MT_FP32: fp32 -> fp32
42 };44 };
atomgit-bot

🟠 High Priority

在 chunk_gated_delta_rule_tiling_data.h 中,新增的 int64_t stateIsFp32 字段被插入在 stateStride1 和 scale 之间(结构体中部),而非追加在末尾。这导致 scale、matmulTilingFp32 等所有后续字段的偏移量均向后平移 8 字节。

BF16 路径的 TilingKey 保持为 0UL(TILING_KEY_CGDR_BF16_STATE),与旧版 tilingKey_ = 0 相同。若存在旧版缓存的调优数据(key=0),新版代码按新布局解析时会将 stateIsFp32(8 字节)所在位置误读为旧版的 scale/matmulTilingFp32 起始位置,导致:

  • scale 读到错误值
  • matmulTilingFp32 的数据损坏
  • 可能引发 kernel 精度异常或运行错误

违反项目规则:"TilingID / TilingKey 新增字段只能追加在原有字段末尾,绝不能修改历史字段顺序,否则缓存的调优数据语义失效。"

修复方向:将 stateIsFp32 移到结构体末尾(matmulTilingFp32C 之后),确保 BF16 TilingKey=0 的已有字段偏移不变。

Suggestions
44
+ struct alignas(STRUCT_ALIGNAS) ChunkGatedDeltaRuleTilingData {
45
+ int64_t aiCoreNum;
46
+ int64_t t;
47
+ int64_t nk;
48
+ int64_t dk;
49
+ int64_t nv;
50
+ int64_t dv;
51
+ int64_t b;
52
+ int64_t hasGamma;
53
+ int64_t chunkSize;
54
+ int64_t maxGroupLength; // maxGroupLength = p * chunkSize
55
+ int64_t interWorkspaceSz;
56
+ int64_t stageWorkspaceSz;
57
+ int64_t stageOneParaNum;
58
+ int64_t stateStride0;
59
+ int64_t stateStride1;
60
+ float scale;
61
+ AscendC::tiling::TCubeTiling matmulTilingFp32; // BF16 C matmul tiling
62
+ AscendC::tiling::TCubeTiling matmulTilingFp32C; // FP32 C matmul tiling (for FP32 state path)
63
+ int64_t stateIsFp32;
44
64
  };
Apply suggestion
likedislike
Incorrect?
43 #pragma pack(pop)45 #pragma pack(pop)
44 46 
@@ -0,0 +1,22 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file chunk_gated_delta_rule_tiling_key.h
13+ * \brief chunk_gated_delta_rule tiling key definitions
14+ */
15+ 
16+#ifndef CHUNK_GATED_DELTA_RULE_TILING_KEY_H
17+#define CHUNK_GATED_DELTA_RULE_TILING_KEY_H
18+ 
19+#define TILING_KEY_CGDR_BF16_STATE 0UL
20+#define TILING_KEY_CGDR_FP32_STATE 1UL
21+ 
22+#endif // CHUNK_GATED_DELTA_RULE_TILING_KEY_H