Merged
Add mhcPre for A2、A3 #10035
Add mhcPre for A2、A3 #10035
Merged
liuyun_njAdd on Aug 13
Total: 11 files changed+2718-130
@@ -17,7 +17,8 @@
17namespace ops {17namespace ops {
18class MhcPre : public OpDef {18class MhcPre : public OpDef {
19public:19public:
20- explicit MhcPre(const char* name) : OpDef(name)20+ explicit MhcPre(const char *name)
21+ : OpDef(name)
21 {22 {
22 this->Input("x")23 this->Input("x")
23 .ParamType(REQUIRED)24 .ParamType(REQUIRED)
@@ -77,14 +78,17 @@ public:
77 .Format({ge::FORMAT_ND, ge::FORMAT_ND})78 .Format({ge::FORMAT_ND, ge::FORMAT_ND})
78 .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});79 .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
79 80 
81+ this->AICore().AddConfig("ascend910b");
82+ this->AICore().AddConfig("ascend910_93");
83+ 
80 OpAICoreConfig aicConfig;84 OpAICoreConfig aicConfig;
81 aicConfig.DynamicCompileStaticFlag(true)85 aicConfig.DynamicCompileStaticFlag(true)
82- .DynamicFormatFlag(false)86+ .DynamicFormatFlag(false)
83- .DynamicRankSupportFlag(true)87+ .DynamicRankSupportFlag(true)
84- .DynamicShapeSupportFlag(true)88+ .DynamicShapeSupportFlag(true)
85- .NeedCheckSupportFlag(false)89+ .NeedCheckSupportFlag(false)
86- .ExtendCfgInfo("aclnnSupport.value", "support_aclnn")90+ .ExtendCfgInfo("aclnnSupport.value", "support_aclnn")
87- .ExtendCfgInfo("opFile.value", "mhc_pre_apt");91+ .ExtendCfgInfo("opFile.value", "mhc_pre_apt");
88 this->AICore().AddConfig("ascend950", aicConfig);92 this->AICore().AddConfig("ascend950", aicConfig);
89 93 
90 this->Attr("out_flag").AttrType(OPTIONAL).Int(0);94 this->Attr("out_flag").AttrType(OPTIONAL).Int(0);
@@ -96,4 +100,4 @@ public:
96 100 
97OP_ADD(MhcPre);101OP_ADD(MhcPre);
98 102 
99-}103+} // namespace ops
@@ -85,6 +85,15 @@ static void SetShapeFromX(gert::Shape *dst, const gert::Shape *src)
85 }85 }
86}86}
87 87 
88+static uint64_t Factorial(uint64_t n)
89+{
90+ uint64_t r = 1;
91+ for (uint64_t i = 2; i <= n; ++i) {
92+ r *= i;
93+ }
94+ return r;
95+}
96+ 
88static ge::graphStatus InferShape4MhcPre(InferShapeContext *context)97static ge::graphStatus InferShape4MhcPre(InferShapeContext *context)
89{98{
90 OP_LOGD(context->GetNodeName(), "Begin to do InferShape MhcPre");99 OP_LOGD(context->GetNodeName(), "Begin to do InferShape MhcPre");
@@ -97,40 +106,74 @@ static ge::graphStatus InferShape4MhcPre(InferShapeContext *context)
97 106 
98 int64_t phiDim = phiShape->GetDimNum();107 int64_t phiDim = phiShape->GetDimNum();
99 int64_t xDim = xShape->GetDimNum();108 int64_t xDim = xShape->GetDimNum();
100- OP_CHECK_IF(109+ OP_CHECK_IF(phiDim != 2,
101- phiDim != 2,110+ OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "phi", std::to_string(phiDim).c_str(), "2"),
102- OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "phi", std::to_string(phiDim).c_str(), "2"),111+ return GRAPH_FAILED);
103- return GRAPH_FAILED);112+ OP_CHECK_IF(xDim != BSND_DIM_NUM && xDim != TND_DIM_NUM,
104- OP_CHECK_IF(113+ OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "x", std::to_string(xDim).c_str(), "3 or 4"),
105- xDim != BSND_DIM_NUM && xDim != TND_DIM_NUM,114+ return GRAPH_FAILED);
106- OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "x", std::to_string(xDim).c_str(), "3 or 4"),
107- return GRAPH_FAILED);
108 115 
109 int64_t alphaDim = alphaShape->GetDimNum();116 int64_t alphaDim = alphaShape->GetDimNum();
110- OP_CHECK_IF(117+ OP_CHECK_IF(alphaDim != 1,
111- alphaDim != 1,118+ OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "alpha", std::to_string(alphaDim).c_str(), "1"),
112- OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "alpha", std::to_string(alphaDim).c_str(), "1"),119+ return GRAPH_FAILED);
113- return GRAPH_FAILED);
114 120 
115 int64_t alphaDimSize = alphaShape->GetDim(0);121 int64_t alphaDimSize = alphaShape->GetDim(0);
116 OP_CHECK_IF(alphaDimSize != 2 && alphaDimSize != 3,122 OP_CHECK_IF(alphaDimSize != 2 && alphaDimSize != 3,
117- OP_LOGE_FOR_INVALID_SHAPE(context->GetNodeName(), "alpha",123+ OP_LOGE_FOR_INVALID_SHAPE(context->GetNodeName(), "alpha", Ops::Base::ToString(*alphaShape).c_str(),
118- Ops::Base::ToString(*alphaShape).c_str(), "[2] or [3]"),124+ "[2] or [3]"),
119 return GRAPH_FAILED);125 return GRAPH_FAILED);
120 // has residual126 // has residual
121 bool hasResi = (alphaDimSize == 3);127 bool hasResi = (alphaDimSize == 3);
122 128 
123- gert::Shape *outShapes[6] = {context->GetOutputShape(OUT_H_IN_INDEX), context->GetOutputShape(OUT_H_POST_INDEX),129+ gert::Shape *outShapes[6] = {context->GetOutputShape(OUT_H_IN_INDEX), context->GetOutputShape(OUT_H_POST_INDEX),
124 context->GetOutputShape(OUT_H_RES_INDEX), context->GetOutputShape(OUT_INV_RMS_INDEX),130 context->GetOutputShape(OUT_H_RES_INDEX), context->GetOutputShape(OUT_INV_RMS_INDEX),
125 context->GetOutputShape(OUT_H_MIX_INDEX), context->GetOutputShape(OUT_H_PRE_INDEX)};131 context->GetOutputShape(OUT_H_MIX_INDEX), context->GetOutputShape(OUT_H_PRE_INDEX)};
132+ 
133+ uint64_t phiDim0 = phiShape->GetDim(0);
134+ uint64_t n = 0;
135+ uint64_t d = 0;
136+ uint64_t nn = 0;
137+ bool isFac = false;
138+ if (xDim == BSND_DIM_NUM) {
139+ n = xShape->GetDim(2);
140+ d = xShape->GetDim(3);
141+ } else {
142+ n = xShape->GetDim(1);
143+ d = xShape->GetDim(2);
144+ }
145+ 
146+ uint64_t nn_fac = Factorial(n);
147+ uint64_t nn_pow = n * n;
148+ uint64_t doubleN = 2 * n;
149+ OP_CHECK_IF(
150+ !hasResi && phiDim0 != doubleN,
151+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context->GetNodeName(), "phi", Ops::Base::ToString(*phiShape).c_str(),
152+ "alpha shape [2] requires phi shape [2n, nD]"),
153+ return GRAPH_FAILED);
154+ OP_CHECK_IF(
155+ hasResi && phiDim0 != nn_fac + doubleN && phiDim0 != nn_pow + doubleN,
156+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context->GetNodeName(), "phi", Ops::Base::ToString(*phiShape).c_str(),
157+ "alpha shape [3] requires phi to contain the residual branch"),
158+ return GRAPH_FAILED);
159+ if (phiDim0 == (nn_fac + doubleN)) {
160+ nn = nn_fac;
161+ isFac = true;
162+ } else {
163+ nn = nn_pow;
164+ }
165+ 
126 if (xDim == BSND_DIM_NUM) {166 if (xDim == BSND_DIM_NUM) {
127 // b,s,n,d167 // b,s,n,d
128- uint64_t b = xShape->GetDim(0), s = xShape->GetDim(1), n = xShape->GetDim(2), d = xShape->GetDim(3);168+ uint64_t b = xShape->GetDim(0);
169+ uint64_t s = xShape->GetDim(1);
129 // dim of phi,bias170 // dim of phi,bias
130- uint64_t matN = hasResi ? (n * n + 2 * n) : (2 * n);171+ uint64_t matN = hasResi ? (nn + 2 * n) : (2 * n);
131 SetShape3D(outShapes[OUT_H_IN_INDEX], b, s, d);172 SetShape3D(outShapes[OUT_H_IN_INDEX], b, s, d);
132 SetShape3D(outShapes[OUT_H_POST_INDEX], b, s, n);173 SetShape3D(outShapes[OUT_H_POST_INDEX], b, s, n);
133- if (hasResi) {174+ if (hasResi && isFac) {
175+ SetShape3D(outShapes[OUT_H_RES_INDEX], b, s, nn);
176+ } else if (hasResi) {
134 SetShape4D(outShapes[OUT_H_RES_INDEX], b, s, n, n);177 SetShape4D(outShapes[OUT_H_RES_INDEX], b, s, n, n);
135 } else {178 } else {
136 SetShape1D(outShapes[OUT_H_RES_INDEX], 0);179 SetShape1D(outShapes[OUT_H_RES_INDEX], 0);
@@ -140,12 +183,14 @@ static ge::graphStatus InferShape4MhcPre(InferShapeContext *context)
140 SetShape3D(outShapes[OUT_H_PRE_INDEX], b, s, n);183 SetShape3D(outShapes[OUT_H_PRE_INDEX], b, s, n);
141 } else {184 } else {
142 // t,n,d185 // t,n,d
143- uint64_t t = xShape->GetDim(0), n = xShape->GetDim(1), d = xShape->GetDim(2);186+ uint64_t t = xShape->GetDim(0);
144 // dim of phi,bias187 // dim of phi,bias
145- uint64_t matN = hasResi ? (n * n + 2 * n) : (2 * n);188+ uint64_t matN = hasResi ? (nn + 2 * n) : (2 * n);
146 SetShape2D(outShapes[OUT_H_IN_INDEX], t, d);189 SetShape2D(outShapes[OUT_H_IN_INDEX], t, d);
147 SetShape2D(outShapes[OUT_H_POST_INDEX], t, n);190 SetShape2D(outShapes[OUT_H_POST_INDEX], t, n);
148- if (hasResi) {191+ if (hasResi && isFac) {
192+ SetShape2D(outShapes[OUT_H_RES_INDEX], t, nn);
193+ } else if (hasResi) {
149 SetShape3D(outShapes[OUT_H_RES_INDEX], t, n, n);194 SetShape3D(outShapes[OUT_H_RES_INDEX], t, n, n);
150 } else {195 } else {
151 SetShape1D(outShapes[OUT_H_RES_INDEX], 0);196 SetShape1D(outShapes[OUT_H_RES_INDEX], 0);
@@ -51,15 +51,27 @@ constexpr int64_t DIM_IDX_2 = 2;
51constexpr int64_t DIM_IDX_3 = 3;51constexpr int64_t DIM_IDX_3 = 3;
52 52 
53constexpr int64_t N_VALID_VALUES[] = {4, 6, 8};53constexpr int64_t N_VALID_VALUES[] = {4, 6, 8};
54+constexpr int64_t N_VALID_VALUE_A2 = 4;
54constexpr int64_t D_ALIGNMENT = 16;55constexpr int64_t D_ALIGNMENT = 16;
56+constexpr int64_t D_ALIGNMENT_A2 = 128;
55constexpr int64_t ALPHA_DIM_SIZE_3 = 3;57constexpr int64_t ALPHA_DIM_SIZE_3 = 3;
56constexpr int64_t ALPHA_DIM_SIZE_2 = 2;58constexpr int64_t ALPHA_DIM_SIZE_2 = 2;
57constexpr int64_t PHI_DIM_OFFSET = 2;59constexpr int64_t PHI_DIM_OFFSET = 2;
58constexpr int64_t MHC_PRE_USE_FP32 = 0;60constexpr int64_t MHC_PRE_USE_FP32 = 0;
59constexpr int64_t MHC_PRE_USE_HF32 = 1;61constexpr int64_t MHC_PRE_USE_HF32 = 1;
60 62 
63+static int64_t Factorial(int64_t n)
64+{
65+ int64_t r = 1;
66+ for (int64_t i = 2; i <= n; ++i) {
67+ r *= i;
68+ }
69+ return r;
70+}
71+ 
61static bool CheckAlphaShape(const aclTensor *alphaTensor);72static bool CheckAlphaShape(const aclTensor *alphaTensor);
62static bool ValidateNDParams(int64_t n, int64_t d);73static bool ValidateNDParams(int64_t n, int64_t d);
74+static bool ValidateNDParamsA2(int64_t n, int64_t d);
63static bool CheckTensorShape(const aclTensor *tensor, std::initializer_list<int64_t> expectedShape, const char *name);75static bool CheckTensorShape(const aclTensor *tensor, std::initializer_list<int64_t> expectedShape, const char *name);
64 76 
65static std::string TensorShapeToString(const aclTensor *tensor)77static std::string TensorShapeToString(const aclTensor *tensor)
@@ -23,17 +23,19 @@ extern "C" {
23 * @domain aclnn_ops_infer23 * @domain aclnn_ops_infer
24 * 算子功能:MhcPre正向算子24 * 算子功能:MhcPre正向算子
25 * @param [in] x: 输入tensor,shape为[B,S,N,D]或[T,N,D],数据类型支持:BF16/FP16。25 * @param [in] x: 输入tensor,shape为[B,S,N,D]或[T,N,D],数据类型支持:BF16/FP16。
26- * @param [in] phi: 输入tensor,shape为[n^2+2n, nD]或[2n, nD](alpha维度决定),数据类型支持:FP32。26+ * @param [in] phi: 输入tensor,shape为[n!+2n, nD]或[n^2+2n, nD]或[2n, nD](alpha维度决定),数据类型支持:FP32。
27 * @param [in] alpha: 输入tensor,shape为[3]或[2],数据类型支持:FP32。alpha=[3]时有hRes输出,alpha=[2]时无hRes输出。27 * @param [in] alpha: 输入tensor,shape为[3]或[2],数据类型支持:FP32。alpha=[3]时有hRes输出,alpha=[2]时无hRes输出。
28- * @param [in] bias: 输入tensor,shape为[2N]或[n^2+2n](alpha维度决定),数据类型支持:FP32。28+ * @param [in] bias: 输入tensor,shape为[2N]或[n^2+2n]或[n!+2n](alpha维度决定),数据类型支持:FP32。
29 * @param [in] gammaOptional: 可选输入tensor,shape为[n, D],数据类型支持:FP32。29 * @param [in] gammaOptional: 可选输入tensor,shape为[n, D],数据类型支持:FP32。
30 * @param [in] normEps: 归一化epsilon参数。30 * @param [in] normEps: 归一化epsilon参数。
31 * @param [in] hcEps: hyper connection epsilon参数。31 * @param [in] hcEps: hyper connection epsilon参数。
32 * @param [out] hIn: 输出tensor,shape为[B,S,D]或[T,D],数据类型:BF16/FP16。32 * @param [out] hIn: 输出tensor,shape为[B,S,D]或[T,D],数据类型:BF16/FP16。
33 * @param [out] hPost: 输出tensor,shape为[B,S,N]或[T,N],数据类型:FP32。33 * @param [out] hPost: 输出tensor,shape为[B,S,N]或[T,N],数据类型:FP32。
34- * @param [out] hRes: 可选输出tensor,alpha=[3]时shape为[B,S,N,N]或[T,N,N],alpha=[2]时为0,数据类型:FP32。34+ * @param [out] hRes:
35+ * 可选输出tensor,alpha=[3]时shape为[B,S,N!]或[B,S,N,N]或[T,N!]或[T,N,N],alpha=[2]时为0,数据类型:FP32。
35 * @param [out] invRmsOptional: 可选输出tensor,shape为[B,S]或[T],数据类型:FP32。36 * @param [out] invRmsOptional: 可选输出tensor,shape为[B,S]或[T],数据类型:FP32。
36- * @param [out] hMixOptional: 可选输出tensor,shape为[B,S,N^2+2N]或[B,S,2N](alpha维度决定),数据类型:FP32。37+ * @param [out] hMixOptional:
38+ * 可选输出tensor,shape为[B,S,N!+2N]或[B,S,N^2+2N]或[B,S,2N](alpha维度决定),数据类型:FP32。
37 * @param [out] hPreOptional: 可选输出tensor,shape为[B,S,N]或[T,N],数据类型:FP32。39 * @param [out] hPreOptional: 可选输出tensor,shape为[B,S,N]或[T,N],数据类型:FP32。
38 * @param [out] workspaceSize: 返回需要在npu device侧申请的workspace大小。40 * @param [out] workspaceSize: 返回需要在npu device侧申请的workspace大小。
39 * @param [out] executor: 返回op执行器,包含了算子计算流程。41 * @param [out] executor: 返回op执行器,包含了算子计算流程。
@@ -665,8 +665,8 @@ ge::graphStatus MhcPreBaseTiling::CalculateBsTiling()
665 tilingData_.set_kL1Size(BASIC_API_K_L1_SIZE);665 tilingData_.set_kL1Size(BASIC_API_K_L1_SIZE);
666 tilingData_.set_fusionAlign(fusionAlign);666 tilingData_.set_fusionAlign(fusionAlign);
667 667 
668- chunkTSize_ = (((totalLength_ + blockDim_ - 1U) / blockDim_) + CHUNK_T_CALC_FACTOR - 1U) /668+ chunkTSize_ = (((totalLength_ + blockDim_ - 1U) / blockDim_) + CHUNK_T_CALC_FACTOR - 1U) / CHUNK_T_CALC_FACTOR *
jiang-lirui

这个文件与op_tiling目录下的文件名相同

likedislike
669- CHUNK_T_CALC_FACTOR * CHUNK_T_CALC_FACTOR;669+ CHUNK_T_CALC_FACTOR;
670 chunkTSize_ = std::min(chunkTSize_, CHUNK_T_MAX);670 chunkTSize_ = std::min(chunkTSize_, CHUNK_T_MAX);
671 v1ChunkDSize_ = V1_CHUNK_D_SIZE;671 v1ChunkDSize_ = V1_CHUNK_D_SIZE;
672 672 
@@ -676,8 +676,7 @@ ge::graphStatus MhcPreBaseTiling::CalculateBsTiling()
676 // SYSTEM_WORKSPACE follows the user workspace and is reserved for the runtime.676 // SYSTEM_WORKSPACE follows the user workspace and is reserved for the runtime.
677 size_t xStageWorkspaceSize = static_cast<size_t>(chunkTSize_) * BASIC_API_K_UB_SIZE *677 size_t xStageWorkspaceSize = static_cast<size_t>(chunkTSize_) * BASIC_API_K_UB_SIZE *
678 BASIC_API_X_STAGE_BUFFER_COUNT * sizeof(float) * blockDim_;678 BASIC_API_X_STAGE_BUFFER_COUNT * sizeof(float) * blockDim_;
679- size_t hMixWorkspaceSize =679+ size_t hMixWorkspaceSize = outFlag_ ? 0U : static_cast<size_t>(matM_) * static_cast<size_t>(matN_) * sizeof(float);
680- outFlag_ ? 0U : static_cast<size_t>(matM_) * static_cast<size_t>(matN_) * sizeof(float);
681 workspaceSize_ = xStageWorkspaceSize + hMixWorkspaceSize + SYSTEM_WORKSPACE;680 workspaceSize_ = xStageWorkspaceSize + hMixWorkspaceSize + SYSTEM_WORKSPACE;
682 return CheckUbBufferSize();681 return CheckUbBufferSize();
683}682}
@@ -755,8 +754,8 @@ ge::graphStatus MhcPreBaseTiling::CalculateMkTiling()
755 v1ChunkDSize_ = V1_CHUNK_D_SIZE;754 v1ChunkDSize_ = V1_CHUNK_D_SIZE;
756 size_t xStageBytes = mkStage == M_K_USE_L1_STAGE ?755 size_t xStageBytes = mkStage == M_K_USE_L1_STAGE ?
757 0U :756 0U :
758- static_cast<size_t>(mDim) * actualKBlockNum * BASIC_API_X_STAGE_BUFFER_COUNT *757+ static_cast<size_t>(mDim) * actualKBlockNum * BASIC_API_X_STAGE_BUFFER_COUNT * mL1Size *
759- mL1Size * kL1Size * sizeof(float);758+ kL1Size * sizeof(float);
760 workspaceSize_ = finalOffset + xStageBytes + SYSTEM_WORKSPACE;759 workspaceSize_ = finalOffset + xStageBytes + SYSTEM_WORKSPACE;
761 return CheckUbBufferSize();760 return CheckUbBufferSize();
762}761}
@@ -778,8 +777,8 @@ ge::graphStatus MhcPreBaseTiling::CalculateNdTiling()
778 (xFloatWorkspaceSizeRaw + DECODE_WORKSPACE_ALIGN - 1U) / DECODE_WORKSPACE_ALIGN * DECODE_WORKSPACE_ALIGN;777 (xFloatWorkspaceSizeRaw + DECODE_WORKSPACE_ALIGN - 1U) / DECODE_WORKSPACE_ALIGN * DECODE_WORKSPACE_ALIGN;
779 uint64_t chunkNd = (matK_ + blockDim_ - 1U) / blockDim_;778 uint64_t chunkNd = (matK_ + blockDim_ - 1U) / blockDim_;
780 uint64_t mmResBlockNum = (matK_ + chunkNd - 1U) / chunkNd;779 uint64_t mmResBlockNum = (matK_ + chunkNd - 1U) / chunkNd;
781- size_t mmResWorkspaceSize = static_cast<size_t>(mmResBlockNum) * static_cast<size_t>(matM_) *780+ size_t mmResWorkspaceSize =
782- static_cast<size_t>(matN_) * sizeof(float);781+ static_cast<size_t>(mmResBlockNum) * static_cast<size_t>(matM_) * static_cast<size_t>(matN_) * sizeof(float);
783 workspaceSize_ = xFloatWorkspaceSize + mmResWorkspaceSize + SYSTEM_WORKSPACE;782 workspaceSize_ = xFloatWorkspaceSize + mmResWorkspaceSize + SYSTEM_WORKSPACE;
784 return CheckUbBufferSize();783 return CheckUbBufferSize();
785}784}
@@ -932,43 +931,4 @@ ge::graphStatus MhcPreBaseTiling::PostTiling()
932 workspaces[0] = workspaceSize_;931 workspaces[0] = workspaceSize_;
933 return ge::GRAPH_SUCCESS;932 return ge::GRAPH_SUCCESS;
934}933}
935- 
936-static ge::graphStatus TilingFunc4mHCPre(gert::TilingContext *context)
937-{
938- OP_CHECK_IF(context == nullptr, OPS_REPORT_CUBE_INNER_ERR("[mHCPreTilingTilingFunc]", "Context is null"),
939- return ge::GRAPH_FAILED);
940- 
941- return Ops::Transformer::OpTiling::TilingRegistry::GetInstance().DoTilingImpl(context);
942-}
943- 
944-static ge::graphStatus TilingPrepare4mHCPre(gert::TilingParseContext *context)
945-{
946- OP_CHECK_IF(context == nullptr, OPS_REPORT_CUBE_INNER_ERR("[TilingPrepare4mHC]", "Context is null"),
947- return ge::GRAPH_FAILED);
948- fe::PlatFormInfos *platformInfo = context->GetPlatformInfo();
949- OP_CHECK_IF(platformInfo == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "PlatformInfoPtr is null"),
950- return ge::GRAPH_FAILED);
951- 
952- auto compileInfoPtr = context->GetCompiledInfo<MhcPreCompileInfo>();
953- OP_CHECK_IF(compileInfoPtr == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "CompileInfoPtr is null"),
954- return ge::GRAPH_FAILED);
955- 
956- auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
957- 
958- compileInfoPtr->aicNum = ascendcPlatform.GetCoreNumAic();
959- compileInfoPtr->aivNum = ascendcPlatform.GetCoreNumAiv();
960- 
961- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, compileInfoPtr->ubSize);
962- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, compileInfoPtr->l1Size);
963- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L2, compileInfoPtr->l2Size);
964- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_A, compileInfoPtr->l0ASize);
965- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, compileInfoPtr->l0BSize);
966- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, compileInfoPtr->l0CSize);
967- 
968- OP_LOGI(context->GetNodeName(), "ParseCompileInfo success, L1Size: %lu, L2Size: %lu, CoreNum: %lu",
969- compileInfoPtr->l1Size, compileInfoPtr->l2Size, compileInfoPtr->aicNum);
970- return ge::GRAPH_SUCCESS;
971-}
972- 
973-IMPL_OP_OPTILING(MhcPre).Tiling(TilingFunc4mHCPre).TilingParse<MhcPreCompileInfo>(TilingPrepare4mHCPre);
974} // namespace optiling934} // namespace optiling
@@ -0,0 +1,574 @@
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 mhc_pre_membase_tiling.cpp
13+ * \brief MhcPre tiling implementation
14+ */
15+ 
16+#include <sstream>
17+#include "mhc_pre_membase_tiling.h"
18+#include "op_host/tiling_templates_registry.h"
19+#include "op_host/tiling_util.h"
20+ 
21+using namespace ge;
22+namespace optiling {
23+namespace {
24+constexpr uint64_t WORKSPACE_SIZE = 32;
25+int64_t CeilDiv(int64_t x, int64_t y)
26+{
27+ if (y != 0) {
28+ return (x + y - 1) / y;
29+ }
30+ return x;
31+}
32+int64_t DownAlign(int64_t x, int64_t y)
33+{
34+ if (y == 0) {
35+ return x;
36+ }
37+ return (x / y) * y;
38+}
39+int64_t RoundUp(int64_t x, int64_t y)
40+{
41+ return CeilDiv(x, y) * y;
42+}
43+int64_t Factorial(int64_t n)
44+{
45+ int64_t r = 1;
46+ for (int64_t i = 2; i <= n; ++i) {
47+ r *= i;
48+ }
49+ return r;
50+}
51+ 
52+constexpr int64_t BLOCK_SIZE = 32;
53+constexpr int64_t REPEAT_SIZE = 256;
54+constexpr int64_t UB_RESEVED_SIZE = 8192;
55+constexpr int64_t DOUBLE_BUFFER = 2;
56+constexpr uint64_t M_L1_MAX_SIZE = 256;
57+constexpr uint64_t K_MULIT_CORE_SPLIT_BASE_SIZE = 256;
58+constexpr uint64_t A_L1_SIZE = 128 * 256;
59+constexpr uint64_t K_L1_MAX_SIZE = 1024;
60+constexpr int64_t OUT_FLAG_ATTR_IDX = 0;
61+constexpr int64_t NORM_EPS_ATTR_IDX = 1;
62+constexpr int64_t HC_EPS_ATTR_IDX = 2;
63+constexpr int64_t BS_SPLIT_THRESHOLD = 128;
64+constexpr int64_t MAX_BS_PER_LOOP = 32;
65+constexpr int64_t MAX_REDUCE_SIZE = 256;
66+} // namespace
67+ 
68+int8_t CheckOptionalParamsExisting(const gert::StorageShape *checkShape)
69+{
70+ OP_CHECK_IF(nullptr == checkShape, OP_LOGD("CheckOptionalParamsExisting", "Get nullptr checkShape"), return 0);
71+ int64_t checkShapeSize = checkShape->GetOriginShape().GetShapeSize();
72+ OP_CHECK_IF((checkShapeSize <= 0), OP_LOGD("CheckOptionalParamsExisting", "Get empty checkShapeSize"), return 0);
73+ return 1;
74+}
75+ 
76+ge::graphStatus MhcPreTiling::GetPlatformInfo()
77+{
78+ auto platformInfo = context_->GetPlatformInfo();
79+ if (platformInfo == nullptr) {
80+ auto compileInfoPtr = context_->GetCompileInfo<MhcPreMembaseCompileInfo>();
81+ OP_CHECK_IF(compileInfoPtr == nullptr, OP_LOGE(context_, "compile info is null"), return ge::GRAPH_FAILED);
82+ aivCoreNum_ = compileInfoPtr->coreNum;
83+ ubSize_ = compileInfoPtr->ubSize;
84+ } else {
85+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
86+ aivCoreNum_ = ascendcPlatform.GetCoreNumAiv();
87+ aicCoreNum_ = ascendcPlatform.GetCoreNumAic();
88+ 
89+ uint64_t ubSizePlatForm;
90+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm);
91+ ubSize_ = ubSizePlatForm;
92+ socVersion_ = ascendcPlatform.GetSocVersion();
93+ }
94+ return ge::GRAPH_SUCCESS;
95+}
96+ 
97+ge::graphStatus MhcPreTiling::GetAttr()
98+{
99+ auto *attrs = context_->GetAttrs();
100+ OP_CHECK_NULL_WITH_CONTEXT(context_, attrs);
@@ -0,0 +1,169 @@
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 mhc_pre_membase_tiling.h
13+ * \brief MhcPre tiling
14+ */
15+ 
16+#ifndef MHC_PRE_MEMBASE_TILING_H
17+#define MHC_PRE_MEMBASE_TILING_H
18+ 
19+#include <vector>
20+#include <iostream>
21+#include "log/log.h"
22+#include "register/op_impl_registry.h"
23+#include "platform/platform_infos_def.h"
24+#include "exe_graph/runtime/tiling_context.h"
25+#include "tiling/platform/platform_ascendc.h"
26+#include "register/op_def_registry.h"
27+#include "register/tilingdata_base.h"
28+#include "tiling/tiling_api.h"
29+#include "platform/platform_info.h"
30+ 
31+namespace optiling {
32+ 
33+struct TilingRequiredParaInfo {
34+ const gert::CompileTimeTensorDesc *desc;
35+ const gert::StorageShape *shape;
36+};
37+ 
38+struct TilingOptionalParaInfo {
39+ const gert::CompileTimeTensorDesc *desc;
40+ const gert::Tensor *tensor;
41+};
42+ 
43+BEGIN_TILING_DATA_DEF(MhcPreMembaseTilingData)
44+TILING_DATA_FIELD_DEF(int64_t, bs); // batch size
45+TILING_DATA_FIELD_DEF(int64_t, hcMix); // hcMult * hcMult + 2 * hcMult
46+TILING_DATA_FIELD_DEF(int64_t, hcMult); // n维度大小
47+TILING_DATA_FIELD_DEF(int64_t, d); // 特征维度大小
48+TILING_DATA_FIELD_DEF(int64_t, hcMultAlign); // 对齐后的hcMult
49+TILING_DATA_FIELD_DEF(int64_t, rowOfFormerBlock); // 前核处理BS总数
50+TILING_DATA_FIELD_DEF(int64_t, rowLoopOfFormerBlock); // 前核处理行循环次数
51+TILING_DATA_FIELD_DEF(int64_t, rowLoopOfTailBlock); // 尾核处理行循环次数
52+TILING_DATA_FIELD_DEF(int64_t, tailRowFactorOfFormerBlock); // 前核尾次处理的行数
53+TILING_DATA_FIELD_DEF(int64_t, tailRowFactorOfTailBlock); // 尾核尾次处理的行数
54+TILING_DATA_FIELD_DEF(int64_t, dLoop); // d维度循环次数
55+TILING_DATA_FIELD_DEF(int64_t, dFactor); // 每次处理的d维度大小
56+TILING_DATA_FIELD_DEF(int64_t, tailDFactor); // 尾次处理的d维度大小
57+TILING_DATA_FIELD_DEF(float, hcEps); // Sinkhorn算法的epsilon参数
58+TILING_DATA_FIELD_DEF(float, normEps); // 归一化的epsilon参数
59+TILING_DATA_FIELD_DEF(int64_t, stage2RowFactor); // 阶段2每次处理的行数
60+// 预留参数,切K优化使用
61+TILING_DATA_FIELD_DEF(int64_t, mL1Size); // M维度L1缓冲大小
62+TILING_DATA_FIELD_DEF(int64_t, cubeBlockDimK); // Cube核K维度切分数量
63+TILING_DATA_FIELD_DEF(int64_t, cvLoopKSize); // CV循环K维度大小
64+ 
65+TILING_DATA_FIELD_DEF(int64_t, secondUsedCoreNum); // 阶段2使用的核心数
66+ 
67+TILING_DATA_FIELD_DEF(int64_t, cubeCoreNum); // Cube核心数
68+ 
69+TILING_DATA_FIELD_DEF(int64_t, needGrad); // 是否需要梯度
70+TILING_DATA_FIELD_DEF(int64_t, hasGamma); // 是否有gamma输入
71+ 
72+// 预留参数,切K优化情况 尾批次专用参数 (tailBs != BS_SPLIT_THRESHOLD 时使用)
73+TILING_DATA_FIELD_DEF(int64_t, tailBsRowOfFormerBlock); // 尾批次前核处理BS总数
74+TILING_DATA_FIELD_DEF(int64_t, tailBsRowLoopOfFormerBlock); // 尾批次前核处理行循环次数
75+TILING_DATA_FIELD_DEF(int64_t, tailBsRowLoopOfTailBlock); // 尾批次尾核处理行循环次数
76+TILING_DATA_FIELD_DEF(int64_t, tailBsUsedCoreNum); // 尾批次使用的核心数
77+TILING_DATA_FIELD_DEF(int64_t, tailBsRowFactor); // 尾批次每次处理的行数
78+TILING_DATA_FIELD_DEF(int64_t, tailBsTailRowFactorOfFormerBlock); // 尾批次前核尾次处理的行数
79+TILING_DATA_FIELD_DEF(int64_t, tailBsTailRowFactorOfTailBlock); // 尾批次尾核尾次处理的行数
80+TILING_DATA_FIELD_DEF(int64_t, tailBsML1Size); // 尾批次M维度L1缓冲大小
81+ 
82+// 阶段1专用 Tiling 字段
83+TILING_DATA_FIELD_DEF(int64_t, stage1VecCoreNum); // 阶段1使用的 Vector Core 数量
84+TILING_DATA_FIELD_DEF(int64_t, stage1CubeCoreNum); // 阶段1使用的 Cube Core 数量
85+TILING_DATA_FIELD_DEF(int64_t, stage1BsFactor); // 每轮 BS 数
86+TILING_DATA_FIELD_DEF(int64_t, stage1NcLoop); // n*c 切分段数
87+TILING_DATA_FIELD_DEF(int64_t, stage1NcFactor); // 每段大小
88+TILING_DATA_FIELD_DEF(int64_t, stage1TailNcFactor); // 尾段大小
89+TILING_DATA_FIELD_DEF(int64_t, stage1XCastWsSize); // X_cast workspace 大小
90+TILING_DATA_FIELD_DEF_STRUCT(TCubeTiling, mm1TilingData)
91+END_TILING_DATA_DEF;
92+ 
93+REGISTER_TILING_DATA_CLASS(MhcPre_0, MhcPreMembaseTilingData)
94+REGISTER_TILING_DATA_CLASS(MhcPre_1, MhcPreMembaseTilingData)
95+REGISTER_TILING_DATA_CLASS(MhcPre_10, MhcPreMembaseTilingData)
96+REGISTER_TILING_DATA_CLASS(MhcPre_11, MhcPreMembaseTilingData)
97+ 
98+struct MhcPreMembaseCompileInfo {
99+ uint64_t coreNum = 0;
100+ uint64_t ubSize = 0;
101+};
102+ 
103+class MhcPreTiling {
104+public:
105+ explicit MhcPreTiling(gert::TilingContext *tilingContext)
106+ : context_(tilingContext)
107+ {}
108+ ~MhcPreTiling() = default;
109+ 
110+ ge::graphStatus GetPlatformInfo();
111+ ge::graphStatus DoOpTiling();
112+ ge::graphStatus GetWorkspaceSize();
113+ ge::graphStatus PostTiling();
114+ ge::graphStatus GetAttr();
115+ ge::graphStatus GetShapeAttrsInfoInner(int8_t &gammaExist);
116+ ge::graphStatus CalcOpTiling();
117+ ge::graphStatus CalcMembaseOpTiling();
118+ ge::graphStatus CalcMKSplitCoreMembasePart2Tiling();
119+ ge::graphStatus CalcBsSplit();
120+ ge::graphStatus CalcTailBsTiling();
121+ ge::graphStatus CalcStage1Tiling();
122+ 
123+private:
124+ gert::TilingContext *context_ = nullptr;
125+ uint64_t tilingKey_ = 0;
126+ MhcPreMembaseTilingData tilingData_;
127+ uint64_t aivCoreNum_ = 0;
128+ uint64_t aicCoreNum_ = 0;
129+ uint64_t workspaceSize_ = 0;
130+ uint64_t usedAivCoreNums_ = 0;
131+ uint64_t ubSize_ = 0;
132+ int64_t bs_ = 0;
133+ int64_t hcMix_ = 0;
134+ int64_t hcMult_ = 0;
135+ int64_t d_ = 0;
136+ int64_t hcMultAlign_ = 0;
137+ int64_t rowOfFormerBlock_ = 0;
138+ int64_t rowOfTailBlock_ = 0;
139+ int64_t rowLoopOfFormerBlock_ = 0;
140+ int64_t rowLoopOfTailBlock_ = 0;
141+ int64_t rowFactor_ = 0;
142+ int64_t tailRowFactorOfFormerBlock_ = 0;
143+ int64_t tailRowFactorOfTailBlock_ = 0;
144+ int64_t dLoop_ = 0;
145+ int64_t dFactor_ = 0;
146+ int64_t tailDFactor_ = 0;
147+ float hcEps_ = 0.0;
148+ float normEps_ = 0.0;
149+ bool needGrad_ = true;
150+ int64_t tailBs_ = 0;
151+ // 尾批次专用参数
152+ int64_t tailBsRowOfFormerBlock_ = 0;
153+ int64_t tailBsRowOfTailBlock_ = 0;
154+ int64_t tailBsRowLoopOfFormerBlock_ = 0;
155+ int64_t tailBsRowLoopOfTailBlock_ = 0;
156+ int64_t tailBsUsedCoreNum_ = 0;
157+ int64_t tailBsRowFactor_ = 0;
158+ int64_t tailBsTailRowFactorOfFormerBlock_ = 0;
159+ int64_t tailBsTailRowFactorOfTailBlock_ = 0;
160+ int64_t tailBsML1Size_ = 0;
161+ bool isFac = false;
162+ bool hasResi = true;
163+ int64_t nn_fac = 0;
164+ int64_t nn_pow = 0;
165+ platform_ascendc::SocVersion socVersion_ = platform_ascendc::SocVersion::ASCEND910B;
166+};
167+ 
168+} // namespace optiling
169+#endif // MHC_PRE_MEMBASE_TILING_H
@@ -0,0 +1,92 @@
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 mhc_pre.cpp
13+ * \brief
14+ */
15+ 
16+#if !defined(__CCE_AICORE__) || __CCE_AICORE__ != 310
17+ 
18+#include "kernel_operator.h"
19+#include "kernel_operator_intf.h"
20+#include "lib/matmul_intf.h"
21+#include "mhc_pre_m_split_core.h"
22+#include "mhc_pre_base.h"
23+using namespace MhcPre;
24+ 
25+using namespace AscendC;
26+ 
27+extern "C" __global__ __aicore__ void mhc_pre(GM_ADDR x, GM_ADDR phi, GM_ADDR alpha, GM_ADDR bias, GM_ADDR gamma,
28+ GM_ADDR hin, GM_ADDR hPost, GM_ADDR hRes, GM_ADDR invRms, GM_ADDR hMix,
29+ GM_ADDR hPre, GM_ADDR workspace, GM_ADDR tiling)
30+{
31+ KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);
32+ if (workspace == nullptr) {
33+ return;
34+ }
35+ 
36+ GM_ADDR userWs = GetUserWorkspace(workspace);
37+ if (userWs == nullptr) {
38+ return;
39+ }
40+ 
41+ GET_TILING_DATA_WITH_STRUCT(MhcPreMembaseTilingData, tiling_data_in, tiling);
42+ const MhcPreMembaseTilingData *__restrict tilingData = &tiling_data_in;
43+ 
44+ if (TILING_KEY_IS(0)) {
45+ // -----------power + res--------------
46+ TPipe pipe;
47+ MhcPre::MhcPreStage1<DTYPE_X, true, true> op1;
48+ op1.cubeCompute_.mm1_.Init(&tilingData->mm1TilingData, &pipe);
49+ op1.cubeCompute_.mm1_.SetSubBlockIdx(0);
50+ op1.Init(x, phi, gamma, invRms, hMix, userWs, tilingData, &pipe);
51+ op1.Process();
52+ pipe.Destroy();
53+ 
54+ TPipe pipeStage2;
55+ MhcPre::MhcPreStage2<DTYPE_X, true, true> op2;
56+ op2.Init(x, alpha, bias, hin, hPost, hRes, hPre, hMix, invRms, userWs, tilingData, &pipeStage2);
57+ op2.Process(false);
58+ pipeStage2.Destroy();
59+ } else if (TILING_KEY_IS(10)) {
60+ // -----------factorial + res--------------
61+ TPipe pipe;
62+ MhcPre::MhcPreStage1<DTYPE_X, false, true> opStage1;
63+ opStage1.cubeCompute_.mm1_.Init(&tilingData->mm1TilingData, &pipe);
64+ opStage1.cubeCompute_.mm1_.SetSubBlockIdx(0);
65+ opStage1.Init(x, phi, gamma, invRms, hMix, userWs, tilingData, &pipe);
66+ opStage1.Process();
67+ pipe.Destroy();
68+ 
69+ TPipe pipeStage2;
70+ MhcPre::MhcPreStage2<DTYPE_X, false, true> opStage2;
71+ opStage2.Init(x, alpha, bias, hin, hPost, hRes, hPre, hMix, invRms, userWs, tilingData, &pipeStage2);
72+ opStage2.Process(false);
73+ pipeStage2.Destroy();
74+ } else if (TILING_KEY_IS(11)) {
75+ // -----------factorial no res--------------
76+ TPipe pipe;
77+ MhcPre::MhcPreStage1<DTYPE_X, false, false> opStage1;
78+ opStage1.cubeCompute_.mm1_.Init(&tilingData->mm1TilingData, &pipe);
79+ opStage1.cubeCompute_.mm1_.SetSubBlockIdx(0);
80+ opStage1.Init(x, phi, gamma, invRms, hMix, userWs, tilingData, &pipe);
81+ opStage1.Process();
82+ pipe.Destroy();
83+ 
84+ TPipe pipeStage2;
85+ MhcPre::MhcPreStage2<DTYPE_X, false, false> opStage2;
86+ opStage2.Init(x, alpha, bias, hin, hPost, hRes, hPre, hMix, invRms, userWs, tilingData, &pipeStage2);
87+ opStage2.Process(false);
88+ pipeStage2.Destroy();
89+ }
90+ // #endif
91+}
92+#endif
@@ -0,0 +1,682 @@
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 mhc_pre_base.h
13+ * \brief
14+ */
15+ 
16+#ifndef MHC_PRE_VECTOR_BASE_H
17+#define MHC_PRE_VECTOR_BASE_H
18+ 
19+#include "kernel_operator.h"
20+#include <cstdint>
21+ 
22+namespace MhcPre {
23+using namespace AscendC;
24+constexpr int32_t BLOCK_SIZE = 32;
25+constexpr int32_t DEFAULT_BLOCK_STRIDE = 1;
26+constexpr int32_t DEFAULT_REPEAT_STRIDE = 8;
27+constexpr int32_t ONE_REPEAT_BLOCK_NUMS = 8;
28+constexpr int32_t REPEAT_SIZE = 256;
29+constexpr int32_t MAX_REPEAT_STRIDE = 255;
30+constexpr int32_t WORKSPACE_ALIGN_SIZE = 512;
31+constexpr uint32_t ONE = 1;
32+constexpr uint32_t SHIFT_COEFF = 17;
33+constexpr int32_t DOUBLE_BUFFER = 2;
34+constexpr int32_t CV_RATIO = 2;
35+constexpr uint64_t N_SIZE = 24;
36+constexpr uint64_t NUM_TWO = 2;
37+constexpr uint64_t NUM_EIGHT = 8;
38+constexpr uint64_t NUM_SIXTEEN = 16;
39+constexpr uint64_t SQUARE_SUM_SIZE = 16;
40+constexpr uint64_t MM_CACHE_LINE_BYTES = 512;
41+constexpr uint64_t MAX_BS_PER_LOOP = 32;
42+constexpr uint64_t ELEMENTS_SIZE_PER_BLOCK = BLOCK_SIZE / sizeof(float);
43+ 
44+__aicore__ inline int32_t CeilDiv(int32_t a, int32_t b)
45+{
46+ if (b == 0) {
47+ return a;
48+ }
49+ return (a + b - 1) / b;
50+}
51+ 
52+__aicore__ inline int32_t CeilAlign(int32_t a, int32_t b)
53+{
54+ return CeilDiv(a, b) * b;
55+}
56+ 
57+template <typename T>
58+__aicore__ inline int32_t RoundUp(int32_t num)
59+{
60+ int32_t elemNum = BLOCK_SIZE / sizeof(T);
61+ return CeilAlign(num, elemNum);
62+}
63+ 
64+__aicore__ inline void SetGatherMaskPattern(const LocalTensor<uint32_t> &maskPattern)
65+{
66+ uint32_t base = ONE;
67+ int32_t length = 8;
68+ for (uint32_t i = 0; i < NUM_SIXTEEN; i++) {
69+ Duplicate(maskPattern[i * length], base, length);
70+ base = (base << 1);
71+ }
72+ PipeBarrier<PIPE_V>();
73+}
74+ 
75+__aicore__ inline void GatherMaskByDiagonal(const LocalTensor<float> &output, const LocalTensor<float> &input,
76+ const LocalTensor<uint32_t> maskPattern, uint16_t dim0)
77+{
78+ uint32_t totalCount = 16 * 16;
79+ uint32_t maskCount = 16;
80+ uint16_t src0StriRepeat = 2; // 16/8(block)=2
81+ uint32_t remainCount = (dim0 % 16) * 16;
82+ uint32_t loopCount = dim0 / 16;
83+ uint64_t rsvdCnt = 0;
84+ for (uint32_t loopIdx = 0; loopIdx < loopCount; loopIdx++) {
85+ GatherMask(output[loopIdx * maskCount], input[loopIdx * totalCount], maskPattern, true, totalCount,
86+ {1, 1, 0, 0}, rsvdCnt);
87+ }
88+ GatherMask(output[loopCount * maskCount], input[loopCount * totalCount], maskPattern, true, maskCount,
89+ {1, dim0, src0StriRepeat, 1}, rsvdCnt);
90+ PipeBarrier<PIPE_V>();
91+}
92+ 
93+__aicore__ inline uint64_t Factorial(uint64_t n)
94+{
95+ uint64_t r = 1;
96+ for (uint64_t i = 2; i <= n; ++i) {
97+ r *= i;
98+ }
99+ return r;
100+}
@@ -0,0 +1,108 @@
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 mhc_pre_cube_compute.h
13+ * \brief
14+ */
15+#ifndef MHC_PRE_CUBE_COMPUTE_H
16+#define MHC_PRE_CUBE_COMPUTE_H
17+ 
18+#include "kernel_operator.h"
19+#include "kernel_operator_intf.h"
20+#include "mhc_pre_base.h"
21+#include "lib/matmul_intf.h"
22+#include <cstdint>
23+ 
24+using AscendC::GlobalTensor;
25+using AscendC::TPosition;
26+using namespace AscendC;
27+ 
28+namespace MhcPre {
29+ 
30+constexpr MatmulConfig MHC_PRE_GRAD_MM1_CFG = GetMDLConfig(true, false, 0, false, false, false, true);
31+ 
32+#define MHC_PRE_CUBE_COMPUTE_TEMPLATE_PARAM template <typename T, bool isFac, bool hasResi>
33+#define MHC_PRE_CUBE_COMPUTE_TEMPLATE_CLASS MhcPreCubeCompute<T, isFac, hasResi>
34+ 
35+// 不切K使用的矩阵乘实现
36+MHC_PRE_CUBE_COMPUTE_TEMPLATE_PARAM
37+class MhcPreCubeCompute {
38+public:
39+ __aicore__ inline MhcPreCubeCompute(){};
40+ __aicore__ inline void Init(const GlobalTensor<float> &xGm, const GlobalTensor<float> &phiGm,
41+ const GlobalTensor<float> &workspaceGlobalAB, int64_t bs, int64_t n, int64_t c,
42+ int64_t vecCoreNum);
43+ __aicore__ inline void ProcessMatmulXPhi(const int32_t taskOffset, const int32_t mm1M);
44+ 
45+public:
46+ GlobalTensor<float> xGm_;
47+ GlobalTensor<float> phiGm_;
48+ GlobalTensor<float> workspaceGlobalAB_;
49+ using AType = matmul::MatmulType<TPosition::GM, CubeFormat::ND, T>;
50+ using BType = matmul::MatmulType<TPosition::GM, CubeFormat::ND, T, true>;
51+ using CType = matmul::MatmulType<TPosition::GM, CubeFormat::ND, T>;
52+ 
53+ matmul::MatmulImpl<AType, BType, CType, CType, MHC_PRE_GRAD_MM1_CFG> mm1_;
54+ 
55+ int64_t n_, c_, curBs_;
56+ int64_t mm1K_, mm1M_, mm1N_;
57+ int64_t ping4Cub = 1;
58+ uint64_t vecCoreNum_ = 0;
59+ uint64_t blockIdx_ = 0;
60+};
61+ 
62+MHC_PRE_CUBE_COMPUTE_TEMPLATE_PARAM
63+__aicore__ inline void MHC_PRE_CUBE_COMPUTE_TEMPLATE_CLASS::Init(const GlobalTensor<float> &xGm,
64+ const GlobalTensor<float> &phiGm,
65+ const GlobalTensor<float> &workspaceGlobalAB,
66+ int64_t bs, int64_t n, int64_t c, int64_t vecCoreNum)
67+{
68+ blockIdx_ = GetBlockIdx();
69+ xGm_ = xGm;
70+ phiGm_ = phiGm;
71+ workspaceGlobalAB_ = workspaceGlobalAB;
72+ vecCoreNum_ = vecCoreNum;
73+ n_ = n;
74+ c_ = c;
75+ curBs_ = bs;
76+ 
77+ if constexpr (hasResi) {
78+ if constexpr (isFac) {
79+ mm1N_ = Factorial(n_) + 2 * n_;
80+ } else {
81+ mm1N_ = n_ * n_ + 2 * n_;
82+ }
83+ } else {
84+ mm1N_ = 2 * n_;
85+ }
86+ 
87+ mm1K_ = n_ * c_;
88+}
89+ 
90+MHC_PRE_CUBE_COMPUTE_TEMPLATE_PARAM
91+__aicore__ inline void MHC_PRE_CUBE_COMPUTE_TEMPLATE_CLASS::ProcessMatmulXPhi(const int32_t taskOffset,
92+ const int32_t mm1M)
93+{
94+ if (mm1M <= 0)
95+ return;
96+ uint64_t xxoffset = blockIdx_ * curBs_ * 2 * mm1K_ + ping4Cub * vecCoreNum_ * curBs_ * mm1K_;
97+ mm1_.SetTensorA(xGm_[blockIdx_ * curBs_ * 2 * mm1K_ + ping4Cub * vecCoreNum_ * curBs_ * mm1K_]);
98+ mm1_.SetTensorB(phiGm_, true);
99+ // mm1_.SetHF32(true, 1);
100+ mm1_.SetOrgShape(mm1M, mm1N_, mm1K_);
101+ mm1_.SetSingleShape(mm1M, mm1N_, mm1K_);
102+ mm1_.template IterateAll<false>(workspaceGlobalAB_[taskOffset * mm1N_]);
103+ mm1_.End();
104+ ping4Cub = 1 - ping4Cub;
105+}
106+} // namespace MhcPre
107+ 
108+#endif // MHC_PRE_CUBE_COMPUTE_H
@@ -0,0 +1,622 @@
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 mhc_pre_m_split_core.h
13+ * \brief
14+ */
15+ 
16+#ifndef MHC_PRE_M_SPLIT_A3_CORE_H
17+#define MHC_PRE_M_SPLIT_A3_CORE_H
18+ 
19+#include "kernel_operator.h"
20+#include "mhc_pre_base.h"
21+#include "mhc_pre_cube_compute.h"
22+ 
23+namespace MhcPre {
24+using namespace AscendC;
25+template <typename T, bool isFac, bool hasResi>
26+class MhcPreStage1 {
27+public:
28+ __aicore__ inline MhcPreStage1() {}
29+ 
30+ __aicore__ inline void Init(GM_ADDR x, GM_ADDR phi, GM_ADDR gamma, GM_ADDR invRms, GM_ADDR hcBeforeNorm,
31+ GM_ADDR workspace, const MhcPreMembaseTilingData *tilingDataPtr, TPipe *pipePtr)
32+ {
33+ pipe = pipePtr;
34+ InitTilingParams(tilingDataPtr);
35+ hasGamma_ = (tilingData->hasGamma != 0);
36+ 
37+ // 获取当前核心 ID
38+ uint64_t blockIdx = GetBlockIdx();
39+ uint64_t cubeCoreId = blockIdx;
40+ uint64_t vecCoreId = blockIdx;
41+ 
42+ // 计算 workspace 偏移
43+ int64_t ncSize = hcMult * d;
44+ 
45+ // 计算 Cube Core ID(Vector Core ID / 2)
46+ if ASCEND_IS_AIV {
47+ cubeCoreId = blockIdx / CV_RATIO;
48+ int64_t maxBsPerLoop = 32;
49+ int64_t xQueSize = maxBsPerLoop * stage1NcFactor;
50+ pipe->InitBuffer(xQue, NUM_TWO, xQueSize * sizeof(T));
51+ pipe->InitBuffer(xCastQue, NUM_TWO, xQueSize * sizeof(float));
52+ pipe->InitBuffer(tmpQue, maxBsPerLoop * stage1NcFactor * sizeof(float));
53+ pipe->InitBuffer(sumQue, maxBsPerLoop * sizeof(float));
54+ LocalTensor<float> sumLocal = sumQue.Get<float>();
55+ pipe->InitBuffer(invRmsQue, NUM_TWO, maxBsPerLoop * sizeof(float));
56+ if (hasGamma_) {
57+ pipe->InitBuffer(gammaQue, 1, stage1NcFactor * sizeof(float));
58+ }
59+ }
60+ 
61+ // 设置 GM 地址
62+ xGm.SetGlobalBuffer((__gm__ T *)x);
63+ phiGm.SetGlobalBuffer((__gm__ float *)phi);
64+ if (hasGamma_) {
65+ gammaGm.SetGlobalBuffer((__gm__ float *)gamma);
66+ }
67+ xCastWsGm.SetGlobalBuffer((__gm__ float *)workspace);
68+ 
69+ // 设置额外的 workspace 地址(needGrad=false 时使用)
70+ if (needGrad_) {
71+ invRmsGm.SetGlobalBuffer((__gm__ float *)invRms);
72+ hcBeforeNormGm.SetGlobalBuffer((__gm__ float *)hcBeforeNorm);
73+ } else {
74+ int64_t xCastWsTotalSize = stage1XCastWsSize / sizeof(float);
75+ invRmsWsGm.SetGlobalBuffer((__gm__ float *)workspace + xCastWsTotalSize);
76+ int64_t invRmsWsTotalSize = bs * sizeof(float) / sizeof(float);
77+ hcBeforeNormWsGm.SetGlobalBuffer((__gm__ float *)workspace + xCastWsTotalSize + invRmsWsTotalSize);
78+ }
79+ 
80+ // 初始化 Cube Compute
81+ if ASCEND_IS_AIC {
82+ // 根据 needGrad 决定输出地址
83+ if (needGrad_) {
84+ cubeCompute_.Init(xCastWsGm, phiGm, hcBeforeNormGm, stage1BsFactor, hcMult, d, stage1VecCoreNum);
85+ } else {
86+ cubeCompute_.Init(xCastWsGm, phiGm, hcBeforeNormWsGm, stage1BsFactor, hcMult, d, stage1VecCoreNum);
87+ }
88+ return;
89+ }
90+ }
91+ 
92+ __aicore__ inline void InitTilingParams(const MhcPreMembaseTilingData *tilingDataPtr)
93+ {
94+ tilingData = tilingDataPtr;
95+ needGrad_ = tilingData->needGrad;
96+ hcMult = tilingData->hcMult;
97+ stage1XCastWsSize = tilingData->stage1XCastWsSize;
98+ bs = tilingData->bs;
99+ d = tilingData->d;
100+ stage1NcFactor = tilingData->stage1NcFactor;