Merged
feat: mhc_pre_backward算子新增A2(ascend910b)支持 #10049
feat: mhc_pre_backward算子新增A2(ascend910b)支持 #10049
Merged
renruhaiAdd on Aug 13
Total: 21 files changed+3568-932
@@ -17,7 +17,8 @@
17namespace ops {17namespace ops {
18class MhcPreBackward : public OpDef {18class MhcPreBackward : public OpDef {
19public:19public:
20- explicit MhcPreBackward(const char *name) : OpDef(name)20+ explicit MhcPreBackward(const char *name)
21+ : OpDef(name)
21 {22 {
22 this->Input("x")23 this->Input("x")
23 .ParamType(REQUIRED)24 .ParamType(REQUIRED)
@@ -114,6 +115,16 @@ public:
114 .NeedCheckSupportFlag(false)115 .NeedCheckSupportFlag(false)
115 .ExtendCfgInfo("opFile.value", "mhc_pre_backward_apt");116 .ExtendCfgInfo("opFile.value", "mhc_pre_backward_apt");
116 this->AICore().AddConfig("ascend950", aicConfig);117 this->AICore().AddConfig("ascend950", aicConfig);
118+ OpAICoreConfig aicoreConfig910b;
119+ aicoreConfig910b.DynamicCompileStaticFlag(true)
120+ .DynamicFormatFlag(false)
121+ .DynamicRankSupportFlag(true)
122+ .DynamicShapeSupportFlag(true)
123+ .NeedCheckSupportFlag(false)
124+ .ExtendCfgInfo("aclnnSupport.value", "support_aclnn")
125+ .ExtendCfgInfo("opFile.value", "mhc_pre_backward");
126+ this->AICore().AddConfig("ascend910b", aicoreConfig910b);
127+ this->AICore().AddConfig("ascend910_93", aicoreConfig910b);
117 this->Attr("hc_eps").AttrType(OPTIONAL).Float(1e-6f);128 this->Attr("hc_eps").AttrType(OPTIONAL).Float(1e-6f);
118 }129 }
119};130};
@@ -29,6 +29,7 @@ using namespace ge;
29 29 
30namespace ops {30namespace ops {
31 31 
32+const constexpr int64_t PHI_INDEX = 1;
32const constexpr int64_t GRAD_H_IN_INDEX = 3;33const constexpr int64_t GRAD_H_IN_INDEX = 3;
33const constexpr int64_t GRAD_H_POST_INDEX = 4;34const constexpr int64_t GRAD_H_POST_INDEX = 4;
34const constexpr int64_t GRAD_H_RES_INDEX = 5;35const constexpr int64_t GRAD_H_RES_INDEX = 5;
@@ -69,12 +70,21 @@ ge::graphStatus GetInputShapes(InferShapeContext *context, const gert::Shape *&g
69 70 
70ge::graphStatus ValidateInputDims(int64_t gradHInDimNum, int64_t gradHPostDimNum, int64_t gradHResDimNum)71ge::graphStatus ValidateInputDims(int64_t gradHInDimNum, int64_t gradHPostDimNum, int64_t gradHResDimNum)
71{72{
72- if ((gradHInDimNum != BSD_DIM_NUM && gradHInDimNum != TD_DIM_NUM) ||73+ // Valid combinations:
73- (gradHPostDimNum != BSD_DIM_NUM && gradHPostDimNum != TN_DIM_NUM) ||74+ // BSND: gradHIn=3D, gradHPost=3D, gradHRes=4D(BSNN) or 3D(BSN!)
74- (gradHResDimNum != BSNN_DIM_NUM && gradHResDimNum != TNN_DIM_NUM)) {75+ // TND: gradHIn=2D, gradHPost=2D, gradHRes=3D(TNN) or 2D(TN!)
76+ if (gradHInDimNum != gradHPostDimNum) {
75 return GRAPH_FAILED;77 return GRAPH_FAILED;
76 }78 }
77- if (gradHInDimNum != gradHPostDimNum) {79+ if (gradHInDimNum == BSD_DIM_NUM) {
80+ if (gradHResDimNum != BSNN_DIM_NUM && gradHResDimNum != TNN_DIM_NUM) {
81+ return GRAPH_FAILED;
82+ }
83+ } else if (gradHInDimNum == TD_DIM_NUM) {
84+ if (gradHResDimNum != TNN_DIM_NUM && gradHResDimNum != TN_DIM_NUM) {
85+ return GRAPH_FAILED;
86+ }
87+ } else {
78 return GRAPH_FAILED;88 return GRAPH_FAILED;
79 }89 }
80 return GRAPH_SUCCESS;90 return GRAPH_SUCCESS;
@@ -110,21 +120,19 @@ ge::graphStatus InferTNDFormat(const gert::Shape *gradHInShape, const gert::Shap
110 return GRAPH_SUCCESS;120 return GRAPH_SUCCESS;
111}121}
112 122 
113-ge::graphStatus InferOutputShapes(gert::Shape *gradPhiShape, gert::Shape *gradAlphaShape,123+ge::graphStatus InferOutputShapes(gert::Shape *gradPhiShape, gert::Shape *gradAlphaShape, gert::Shape *gradBiasShape,
114- gert::Shape *gradBiasShape, gert::Shape *gradGammaShape, uint64_t numsResidual,124+ gert::Shape *gradGammaShape, uint64_t numsResidual, uint64_t dimen,
115- uint64_t dimen)125+ uint64_t fusionSize)
116{126{
117- uint64_t n2Plus2n = (2 * numsResidual) + (numsResidual * numsResidual);
118- 
119 gradPhiShape->SetDimNum(2);127 gradPhiShape->SetDimNum(2);
120- gradPhiShape->SetDim(0, n2Plus2n);128+ gradPhiShape->SetDim(0, fusionSize);
121 gradPhiShape->SetDim(1, numsResidual * dimen);129 gradPhiShape->SetDim(1, numsResidual * dimen);
122 130 
123 gradAlphaShape->SetDimNum(1);131 gradAlphaShape->SetDimNum(1);
124 gradAlphaShape->SetDim(0, GRAD_ALPHA_DIM_SIZE);132 gradAlphaShape->SetDim(0, GRAD_ALPHA_DIM_SIZE);
125 133 
126 gradBiasShape->SetDimNum(1);134 gradBiasShape->SetDimNum(1);
127- gradBiasShape->SetDim(0, n2Plus2n);135+ gradBiasShape->SetDim(0, fusionSize);
128 136 
129 if (gradGammaShape != nullptr) {137 if (gradGammaShape != nullptr) {
130 gradGammaShape->SetDimNum(2);138 gradGammaShape->SetDimNum(2);
@@ -175,8 +183,14 @@ static ge::graphStatus InferShape4mHCPreGrad(InferShapeContext *context)
175 return ret;183 return ret;
176 }184 }
177 185 
178- ret = InferOutputShapes(gradPhiShape, gradAlphaShape, gradBiasShape, gradGammaShape,186+ // Derive fusionSize from phi input shape (dim 0), which is platform-dependent:
179- numsResidual, dimen);187+ // A2 (ascend910b): N! + 2N, A3/A5 (ascend950): N^2 + 2N
188+ auto phiShape = context->GetInputShape(PHI_INDEX);
189+ OP_CHECK_NULL_WITH_CONTEXT(context, phiShape);
190+ uint64_t fusionSize = phiShape->GetDim(INDEX_0);
191+ 
192+ ret =
193+ InferOutputShapes(gradPhiShape, gradAlphaShape, gradBiasShape, gradGammaShape, numsResidual, dimen, fusionSize);
180 if (ret != GRAPH_SUCCESS) {194 if (ret != GRAPH_SUCCESS) {
181 return ret;195 return ret;
182 }196 }
@@ -156,9 +156,8 @@ bool MhcGradCheckInputNotNull(const AclnnMhcPreBackwardParams &params)
156 MhcGradCheckInputNotNullImpl(params.gradHIn, "gradHIn") &&156 MhcGradCheckInputNotNullImpl(params.gradHIn, "gradHIn") &&
157 MhcGradCheckInputNotNullImpl(params.gradHPost, "gradHPost") &&157 MhcGradCheckInputNotNullImpl(params.gradHPost, "gradHPost") &&
158 MhcGradCheckInputNotNullImpl(params.gradHRes, "gradHRes") &&158 MhcGradCheckInputNotNullImpl(params.gradHRes, "gradHRes") &&
159- MhcGradCheckInputNotNullImpl(params.invRms, "invRms") &&159+ MhcGradCheckInputNotNullImpl(params.invRms, "invRms") && MhcGradCheckInputNotNullImpl(params.hMix, "hMix") &&
160- MhcGradCheckInputNotNullImpl(params.hMix, "hMix") && MhcGradCheckInputNotNullImpl(params.hPre, "hPre") &&160+ MhcGradCheckInputNotNullImpl(params.hPre, "hPre") && MhcGradCheckInputNotNullImpl(params.hPost, "hPost") &&
161- MhcGradCheckInputNotNullImpl(params.hPost, "hPost") &&
162 (params.gamma == nullptr || MhcGradCheckInputNotNullImpl(params.gamma, "gamma")) &&161 (params.gamma == nullptr || MhcGradCheckInputNotNullImpl(params.gamma, "gamma")) &&
163 (params.gradXPostOptional == nullptr ||162 (params.gradXPostOptional == nullptr ||
164 MhcGradCheckInputNotNullImpl(params.gradXPostOptional, "gradXPostOptional"));163 MhcGradCheckInputNotNullImpl(params.gradXPostOptional, "gradXPostOptional"));
@@ -222,7 +221,8 @@ bool MhcGradCheckInputDims(const AclnnMhcPreBackwardParams &params)
222 (params.gamma == nullptr || CheckDimNum(params.gamma, 2, "gamma")) &&221 (params.gamma == nullptr || CheckDimNum(params.gamma, 2, "gamma")) &&
223 CheckDimNum(params.gradHIn, (params.x)->GetViewShape().GetDimNum() - 1, "gradHIn") &&222 CheckDimNum(params.gradHIn, (params.x)->GetViewShape().GetDimNum() - 1, "gradHIn") &&
224 CheckDimNum(params.gradHPost, (params.x)->GetViewShape().GetDimNum() - 1, "gradHPost") &&223 CheckDimNum(params.gradHPost, (params.x)->GetViewShape().GetDimNum() - 1, "gradHPost") &&
225- CheckDimNum(params.gradHRes, (params.x)->GetViewShape().GetDimNum(), "gradHRes") &&224+ CheckDimNum(params.gradHRes, (params.x)->GetViewShape().GetDimNum(), "gradHRes", true,
225+ (params.x)->GetViewShape().GetDimNum() - 1) &&
226 CheckDimNum(params.invRms, (params.x)->GetViewShape().GetDimNum() - 2, "invRms") &&226 CheckDimNum(params.invRms, (params.x)->GetViewShape().GetDimNum() - 2, "invRms") &&
227 CheckDimNum(params.hMix, (params.x)->GetViewShape().GetDimNum() - 1, "hMix") &&227 CheckDimNum(params.hMix, (params.x)->GetViewShape().GetDimNum() - 1, "hMix") &&
228 CheckDimNum(params.hPre, (params.x)->GetViewShape().GetDimNum() - 1, "hPre") &&228 CheckDimNum(params.hPre, (params.x)->GetViewShape().GetDimNum() - 1, "hPre") &&
@@ -261,12 +261,30 @@ bool CheckShapeDim(const gert::Shape &shape, uint64_t index, uint64_t expected,
261{261{
262 if (shape.GetDim(index) != expected) {262 if (shape.GetDim(index) != expected) {
263 OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s, and dim %lu must be %lu, actual is %ld", msg, index, expected,263 OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s, and dim %lu must be %lu, actual is %ld", msg, index, expected,
264- shape.GetDim(index));264+ shape.GetDim(index));
265 return false;265 return false;
266 }266 }
267 return true;267 return true;
268}268}
269 269 
270+uint64_t Factorial(uint64_t n)
271+{
272+ if (n <= 1) {
273+ return 1;
274+ }
275+ uint64_t result = 1;
276+ for (uint64_t i = 2; i <= n; i++) {
277+ result *= i;
278+ }
279+ return result;
280+}
281+ 
282+bool IsAscend910BPlatform()
283+{
284+ auto socVersion = GetCurrentPlatformInfo().GetSocVersion();
285+ return socVersion == SocVersion::ASCEND910B || socVersion == SocVersion::ASCEND910_93;
286+}
287+ 
270bool MhcGradCheckBSNDShape(const AclnnMhcPreBackwardParams &params, uint64_t batch, uint64_t sequence, uint64_t dimen,288bool MhcGradCheckBSNDShape(const AclnnMhcPreBackwardParams &params, uint64_t batch, uint64_t sequence, uint64_t dimen,
271 uint64_t numsResidual)289 uint64_t numsResidual)
272{290{
@@ -284,11 +302,32 @@ bool MhcGradCheckBSNDShape(const AclnnMhcPreBackwardParams &params, uint64_t bat
284 return false;302 return false;
285 }303 }
286 304 
305+ // 从 phi shape 动态读取 fusionSize, 支持 N!+2N 和 N²+2N
306+ uint64_t fusionSize = params.phi->GetViewShape().GetDim(0);
307+ uint64_t factN = Factorial(numsResidual); // BSN! 形式的 factN = N!
287 auto &gradHResShape = params.gradHRes->GetViewShape();308 auto &gradHResShape = params.gradHRes->GetViewShape();
288- if (!CheckShapeDim(gradHResShape, 0, batch, "gradHRes shape must be [B, S, N, N]") ||309+ if (gradHResShape.GetDimNum() == 4) {
289- !CheckShapeDim(gradHResShape, 1, sequence, "gradHRes shape must be [B, S, N, N]") ||310+ // [B, S, N, N] (BSNN 形式) - 所有平台都支持, factN = N²
290- !CheckShapeDim(gradHResShape, 2, numsResidual, "gradHRes shape must be [B, S, N, N]") ||311+ if (!CheckShapeDim(gradHResShape, 0, batch, "gradHRes shape must be [B, S, N, N]") ||
291- !CheckShapeDim(gradHResShape, 3, numsResidual, "gradHRes shape must be [B, S, N, N]")) {312+ !CheckShapeDim(gradHResShape, 1, sequence, "gradHRes shape must be [B, S, N, N]") ||
313+ !CheckShapeDim(gradHResShape, 2, numsResidual, "gradHRes shape must be [B, S, N, N]") ||
314+ !CheckShapeDim(gradHResShape, 3, numsResidual, "gradHRes shape must be [B, S, N, N]")) {
315+ return false;
316+ }
317+ } else if (gradHResShape.GetDimNum() == 3) {
318+ // [B, S, N!] (BSN! 形式) - 仅 A2 支持, A5 只支持 BSNN
319+ if (!IsAscend910BPlatform()) {
320+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "gradHRes shape [B, S, N!] (BSN!) is only supported on A2 platform");
321+ return false;
322+ }
323+ if (!CheckShapeDim(gradHResShape, 0, batch, "gradHRes shape must be [B, S, N, N] or [B, S, N!]") ||
324+ !CheckShapeDim(gradHResShape, 1, sequence, "gradHRes shape must be [B, S, N, N] or [B, S, N!]") ||
325+ !CheckShapeDim(gradHResShape, 2, factN, "gradHRes shape must be [B, S, N, N] or [B, S, N!]")) {
326+ return false;
327+ }
328+ } else {
329+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "gradHRes shape dim num must be 3 (BSN!) or 4 (BSNN), but got %lu",
330+ gradHResShape.GetDimNum());
292 return false;331 return false;
293 }332 }
294 333 
@@ -298,11 +337,10 @@ bool MhcGradCheckBSNDShape(const AclnnMhcPreBackwardParams &params, uint64_t bat
298 return false;337 return false;
299 }338 }
300 339 
301- uint64_t n2Plus2n = numsResidual * numsResidual + 2 * numsResidual;
302 auto &hMixShape = params.hMix->GetViewShape();340 auto &hMixShape = params.hMix->GetViewShape();
303- if (!CheckShapeDim(hMixShape, 0, batch, "hMix shape must be [B, S, N^2+2N]") ||341+ if (!CheckShapeDim(hMixShape, 0, batch, "hMix shape must be [B, S, fusionSize]") ||
304- !CheckShapeDim(hMixShape, 1, sequence, "hMix shape must be [B, S, N^2+2N]") ||342+ !CheckShapeDim(hMixShape, 1, sequence, "hMix shape must be [B, S, fusionSize]") ||
305- !CheckShapeDim(hMixShape, 2, n2Plus2n, "hMix shape must be [B, S, N^2+2N]")) {343+ !CheckShapeDim(hMixShape, 2, fusionSize, "hMix shape must be [B, S, fusionSize]")) {
306 return false;344 return false;
307 }345 }
308 346 
@@ -354,11 +392,27 @@ bool MhcGradCheckTNDShape(const AclnnMhcPreBackwardParams &params, uint64_t t, u
354 return false;392 return false;
355 }393 }
356 394 
395+ // 从 phi shape 动态读取 fusionSize, 支持 N!+2N 和 N²+2N
396+ uint64_t fusionSize = params.phi->GetViewShape().GetDim(0);
397+ uint64_t factN = Factorial(numsResidual); // BSN! 形式的 factN = N!
357 auto &gradHResShape = params.gradHRes->GetViewShape();398 auto &gradHResShape = params.gradHRes->GetViewShape();
358- if (!CheckShapeDim(gradHResShape, 0, t, "gradHRes shape must be [T, N, N]") ||399+ if (gradHResShape.GetDimNum() == 3) {
359- !CheckShapeDim(gradHResShape, 1, numsResidual, "gradHRes shape must be [T, N, N]") ||400+ // [T, N, N] (BSNN 形式) - 所有平台都支持, factN = N²
360- !CheckShapeDim(gradHResShape, 2, numsResidual, "gradHRes shape must be [T, N, N]")) {401+ if (!CheckShapeDim(gradHResShape, 0, t, "gradHRes shape must be [T, N, N]") ||
361- return false;402+ !CheckShapeDim(gradHResShape, 1, numsResidual, "gradHRes shape must be [T, N, N]") ||
403+ !CheckShapeDim(gradHResShape, 2, numsResidual, "gradHRes shape must be [T, N, N]")) {
404+ return false;
405+ }
406+ } else {
407+ // [T, N!] (BSN! 形式) - 仅 A2 支持, A5 只支持 BSNN
408+ if (!IsAscend910BPlatform()) {
409+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "gradHRes shape [T, N!] (BSN!) is only supported on A2 platform");
410+ return false;
411+ }
412+ if (!CheckShapeDim(gradHResShape, 0, t, "gradHRes shape must be [T, N, N] or [T, N!]") ||
413+ !CheckShapeDim(gradHResShape, 1, factN, "gradHRes shape must be [T, N, N] or [T, N!]")) {
414+ return false;
415+ }
362 }416 }
363 417 
364 auto &invRmsShape = params.invRms->GetViewShape();418 auto &invRmsShape = params.invRms->GetViewShape();
@@ -366,10 +420,9 @@ bool MhcGradCheckTNDShape(const AclnnMhcPreBackwardParams &params, uint64_t t, u
366 return false;420 return false;
367 }421 }
368 422 
369- uint64_t n2Plus2n = numsResidual * numsResidual + 2 * numsResidual;
370 auto &hMixShape = params.hMix->GetViewShape();423 auto &hMixShape = params.hMix->GetViewShape();
371- if (!CheckShapeDim(hMixShape, 0, t, "hMix shape must be [T, N^2+2N]") ||424+ if (!CheckShapeDim(hMixShape, 0, t, "hMix shape must be [T, fusionSize]") ||
372- !CheckShapeDim(hMixShape, 1, n2Plus2n, "hMix shape must be [T, N^2+2N]")) {425+ !CheckShapeDim(hMixShape, 1, fusionSize, "hMix shape must be [T, fusionSize]")) {
373 return false;426 return false;
374 }427 }
375 428 
@@ -411,16 +464,33 @@ bool MhcGradCheckCommonShape(const AclnnMhcPreBackwardParams &params, uint64_t n
411 }464 }
412 465 
413 uint64_t nD = numsResidual * dimen;466 uint64_t nD = numsResidual * dimen;
414- uint64_t n2Plus2n = numsResidual * numsResidual + 2 * numsResidual;467+ 
415 auto &phiShape = params.phi->GetViewShape();468 auto &phiShape = params.phi->GetViewShape();
416- if (!CheckShapeDim(phiShape, 0, n2Plus2n, "phi tensor first dim must be n^2+2n") ||469+ uint64_t fusionSize = phiShape.GetDim(0);
417- !CheckShapeDim(phiShape, 1, nD, "phi tensor second dim must be nD")) {470+ // 校验 phi 第一维: 必须是 N!+2N 或 N²+2N
471+ uint64_t expectedFusionSizeFactN = Factorial(numsResidual) + 2 * numsResidual; // N!+2N
472+ uint64_t expectedFusionSizeNsq = numsResidual * numsResidual + 2 * numsResidual; // N²+2N
473+ if (fusionSize != expectedFusionSizeFactN && fusionSize != expectedFusionSizeNsq) {
474+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "phi tensor first dim must be N!+2N (%lu) or N^2+2N (%lu), but got %lu",
475+ expectedFusionSizeFactN, expectedFusionSizeNsq, fusionSize);
476+ return false;
477+ }
478+ if (!CheckShapeDim(phiShape, 1, nD, "phi tensor second dim must be nD")) {
479+ return false;
480+ }
481+ 
482+ // Verify hMix fusionSize matches phi
483+ auto &hMixShape = params.hMix->GetViewShape();
484+ uint64_t hMixLastDim = hMixShape.GetDim(hMixShape.GetDimNum() - 1);
485+ if (hMixLastDim != fusionSize) {
486+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "hMix last dim must match phi fusionSize %lu, but got %lu", fusionSize,
487+ hMixLastDim);
418 return false;488 return false;
419 }489 }
420 490 
421 auto &gradPhiShape = params.gradPhi->GetViewShape();491 auto &gradPhiShape = params.gradPhi->GetViewShape();
422- if (!CheckShapeDim(gradPhiShape, 0, n2Plus2n, "gradPhi shape must be [2N+N^2, N*D]") ||492+ if (!CheckShapeDim(gradPhiShape, 0, fusionSize, "gradPhi shape first dim must match phi") ||
423- !CheckShapeDim(gradPhiShape, 1, nD, "gradPhi shape must be [2N+N^2, N*D]")) {493+ !CheckShapeDim(gradPhiShape, 1, nD, "gradPhi shape second dim must be nD")) {
424 return false;494 return false;
425 }495 }
426 496 
@@ -430,7 +500,7 @@ bool MhcGradCheckCommonShape(const AclnnMhcPreBackwardParams &params, uint64_t n
430 }500 }
431 501 
432 auto &gradBiasShape = params.gradBias->GetViewShape();502 auto &gradBiasShape = params.gradBias->GetViewShape();
433- if (!CheckShapeDim(gradBiasShape, 0, n2Plus2n, "gradBias shape must be [2N+N^2]")) {503+ if (!CheckShapeDim(gradBiasShape, 0, fusionSize, "gradBias shape must match fusionSize")) {
434 return false;504 return false;
435 }505 }
436 506 
@@ -494,7 +564,7 @@ bool CheckDtype(const aclTensor *tensor, DataType expected, const char *name, bo
494 bool valid = isValidX ? (dtype == DataType::DT_BF16 || dtype == DataType::DT_FLOAT16) : (dtype == expected);564 bool valid = isValidX ? (dtype == DataType::DT_BF16 || dtype == DataType::DT_FLOAT16) : (dtype == expected);
495 if (!valid) {565 if (!valid) {
496 OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s tensor dtype must be %s. actual is [%s].", name,566 OP_LOGE(ACLNN_ERR_PARAM_INVALID, "%s tensor dtype must be %s. actual is [%s].", name,
497- isValidX ? "BF16 or FP16" : op::ToString(expected).GetString(), op::ToString(dtype).GetString());567+ isValidX ? "BF16 or FP16" : op::ToString(expected).GetString(), op::ToString(dtype).GetString());
498 return false;568 return false;
499 }569 }
500 return true;570 return true;
@@ -509,11 +579,10 @@ bool MhcGradCheckInputDtype(const AclnnMhcPreBackwardParams &params)
509 CheckDtype(params.gradHPost, DataType::DT_FLOAT, "gradHPost") &&579 CheckDtype(params.gradHPost, DataType::DT_FLOAT, "gradHPost") &&
510 CheckDtype(params.gradHRes, DataType::DT_FLOAT, "gradHRes") &&580 CheckDtype(params.gradHRes, DataType::DT_FLOAT, "gradHRes") &&
511 CheckDtype(params.invRms, DataType::DT_FLOAT, "invRms") &&581 CheckDtype(params.invRms, DataType::DT_FLOAT, "invRms") &&
512- CheckDtype(params.hMix, DataType::DT_FLOAT, "hMix") &&582+ CheckDtype(params.hMix, DataType::DT_FLOAT, "hMix") && CheckDtype(params.hPre, DataType::DT_FLOAT, "hPre") &&
513- CheckDtype(params.hPre, DataType::DT_FLOAT, "hPre") &&
514 CheckDtype(params.hPost, DataType::DT_FLOAT, "hPost") &&583 CheckDtype(params.hPost, DataType::DT_FLOAT, "hPost") &&
515 (params.gradXPostOptional == nullptr ||584 (params.gradXPostOptional == nullptr ||
516- CheckDtype(params.gradXPostOptional, params.x->GetDataType(), "gradXPostOptional"));585+ CheckDtype(params.gradXPostOptional, params.x->GetDataType(), "gradXPostOptional"));
517}586}
518 587 
519bool MhcGradCheckOutputDtype(const AclnnMhcPreBackwardParams &params)588bool MhcGradCheckOutputDtype(const AclnnMhcPreBackwardParams &params)
@@ -643,17 +712,14 @@ static aclnnStatus mhcPreBackwardCommonProcess(AclnnMhcPreBackwardParams &params
643{712{
644 auto ret = MhcGradCheckParams(params);713 auto ret = MhcGradCheckParams(params);
645 CHECK_RET(ret == ACLNN_SUCCESS, ret);714 CHECK_RET(ret == ACLNN_SUCCESS, ret);
646- 
647 ret = MhcGradCovertDataContiguous(params, executor);715 ret = MhcGradCovertDataContiguous(params, executor);
648 CHECK_RET(ret == ACLNN_SUCCESS, ret);716 CHECK_RET(ret == ACLNN_SUCCESS, ret);
649- 
650 auto outParams =717 auto outParams =
651 l0op::MhcPreBackward(params.xContiguous, params.phiContiguous, params.alphaContiguous, params.gradHInContiguous,718 l0op::MhcPreBackward(params.xContiguous, params.phiContiguous, params.alphaContiguous, params.gradHInContiguous,
652 params.gradHPostContiguous, params.gradHResContiguous, params.invRmsContiguous,719 params.gradHPostContiguous, params.gradHResContiguous, params.invRmsContiguous,
653 params.hMixContiguous, params.hPreContiguous, params.hPostContiguous,720 params.hMixContiguous, params.hPreContiguous, params.hPostContiguous,
654 params.gammaContiguous, params.gradXPostOptionalContiguous, params.hcEps, executor);721 params.gammaContiguous, params.gradXPostOptionalContiguous, params.hcEps, executor);
655 CHECK_RET(outParams != std::tuple(nullptr, nullptr, nullptr, nullptr, nullptr), ACLNN_ERR_INNER_NULLPTR);722 CHECK_RET(outParams != std::tuple(nullptr, nullptr, nullptr, nullptr, nullptr), ACLNN_ERR_INNER_NULLPTR);
656- 
657 CHECK_RET(CopyOutput(std::get<0>(outParams), params.gradX, executor), ACLNN_ERR_INNER_NULLPTR);723 CHECK_RET(CopyOutput(std::get<0>(outParams), params.gradX, executor), ACLNN_ERR_INNER_NULLPTR);
658 CHECK_RET(CopyOutput(std::get<1>(outParams), params.gradPhi, executor), ACLNN_ERR_INNER_NULLPTR);724 CHECK_RET(CopyOutput(std::get<1>(outParams), params.gradPhi, executor), ACLNN_ERR_INNER_NULLPTR);
659 CHECK_RET(CopyOutput(std::get<2>(outParams), params.gradAlpha, executor), ACLNN_ERR_INNER_NULLPTR);725 CHECK_RET(CopyOutput(std::get<2>(outParams), params.gradAlpha, executor), ACLNN_ERR_INNER_NULLPTR);
@@ -672,12 +738,11 @@ aclnnStatus aclnnMhcPreBackwardGetWorkspaceSize(
672 float hcEps, const aclTensor *gradX, const aclTensor *gradPhi, const aclTensor *gradAlpha,738 float hcEps, const aclTensor *gradX, const aclTensor *gradPhi, const aclTensor *gradAlpha,
673 const aclTensor *gradBias, const aclTensor *gradGamma, uint64_t *workspaceSize, aclOpExecutor **executor)739 const aclTensor *gradBias, const aclTensor *gradGamma, uint64_t *workspaceSize, aclOpExecutor **executor)
674{740{
675- L2_DFX_PHASE_1(aclnnMhcPreBackward,741+ L2_DFX_PHASE_1(
676- DFX_IN(x, phi, alpha, gradHIn, gradHPost, gradHRes, invRms, hMix, hPre, hPost, gamma,742+ aclnnMhcPreBackward,
677- gradXPostOptional),743+ DFX_IN(x, phi, alpha, gradHIn, gradHPost, gradHRes, invRms, hMix, hPre, hPost, gamma, gradXPostOptional),
678- DFX_OUT(gradX, gradPhi, gradAlpha, gradBias, gradGamma));744+ DFX_OUT(gradX, gradPhi, gradAlpha, gradBias, gradGamma));
679 auto uniqueExecutor = CREATE_EXECUTOR();745 auto uniqueExecutor = CREATE_EXECUTOR();
680- 
681 AclnnMhcPreBackwardParams params = AclnnMhcPreBackward::Create()746 AclnnMhcPreBackwardParams params = AclnnMhcPreBackward::Create()
682 .SetInput(x, phi, alpha, gamma)747 .SetInput(x, phi, alpha, gamma)
683 .SetGradInput(gradHIn, gradHPost, gradHRes)748 .SetGradInput(gradHIn, gradHPost, gradHRes)
@@ -686,10 +751,8 @@ aclnnStatus aclnnMhcPreBackwardGetWorkspaceSize(
686 .SetAttr(hcEps)751 .SetAttr(hcEps)
687 .SetOutput(gradX, gradPhi, gradAlpha, gradBias, gradGamma)752 .SetOutput(gradX, gradPhi, gradAlpha, gradBias, gradGamma)
688 .Build();753 .Build();
689- 
690 auto ret = mhcPreBackwardCommonProcess(params, uniqueExecutor.get());754 auto ret = mhcPreBackwardCommonProcess(params, uniqueExecutor.get());
691 CHECK_RET(ret == ACLNN_SUCCESS, ret);755 CHECK_RET(ret == ACLNN_SUCCESS, ret);
692- 
693 *workspaceSize = uniqueExecutor->GetWorkspaceSize();756 *workspaceSize = uniqueExecutor->GetWorkspaceSize();
694 uniqueExecutor.ReleaseTo(executor);757 uniqueExecutor.ReleaseTo(executor);
695 return ACLNN_SUCCESS;758 return ACLNN_SUCCESS;
@@ -0,0 +1,546 @@
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_backward_arch22_tiling.cpp
13+ * \brief MhcPreBackward arch22 tiling implementation
14+ */
15+#include "register/op_def_registry.h"
16+#include "tiling/tiling_api.h"
17+#include "tiling/platform/platform_ascendc.h"
18+#include "mhc_pre_backward_arch22_tiling.h"
19+#include "mhc_pre_backward_arch22_tiling_utils.h"
20+#include "log/log.h"
21+#include "mhc/mhc_pre_backward/op_kernel/arch22/mhc_pre_backward_data_arch22.h"
22+#include "mhc/mhc_pre_backward/op_kernel/arch22/mhc_pre_backward_key_arch22.h"
23+ 
24+#define CHECK_NULLPTR(ptr) \
25+ if (ptr == nullptr) { \
26+ return ge::GRAPH_FAILED; \
27+ }
28+ 
29+namespace {
30+constexpr uint8_t INPUT_X_IDX = 0;
31+constexpr uint8_t PHI_IDX = 1;
32+constexpr uint8_t ALPHA_IDX = 2;
33+constexpr uint8_t GRAD_H_IN_IDX = 3;
34+constexpr uint8_t GRAD_H_POST_IDX = 4;
35+constexpr uint8_t GRAD_H_RES_IDX = 5;
36+constexpr uint8_t INV_RMS_IDX = 6;
37+constexpr uint8_t H_MIX_IDX = 7;
38+constexpr uint8_t H_PRE_IDX = 8;
39+constexpr uint8_t GRAD_X_IDX = 0;
40+constexpr uint8_t GRAD_PHI_IDX = 1;
41+constexpr uint8_t GRAD_ALPHA_IDX = 2;
42+constexpr uint8_t GRAD_BIAS_IDX = 3;
43+constexpr float DEFAULT_EPS = 1e-6f;
44+constexpr uint8_t BATCH_SIZE_DIM_IDX = 0;
45+constexpr uint8_t SEQ_LENGTH_DIM_IDX = 1;
46+constexpr uint8_t N_DIM_IDX = 2;
47+constexpr uint8_t C_DIM_IDX = 3;
48+// TND 格式维度索引: x=[T,N,D]
49+constexpr uint8_t TND_T_DIM_IDX = 0;
50+constexpr uint8_t TND_N_DIM_IDX = 1;
51+constexpr uint8_t TND_D_DIM_IDX = 2;
52+constexpr int64_t BSND_X_DIM_NUM = 4; // BSND: x=[B,S,N,D]
53+constexpr int64_t TND_X_DIM_NUM = 3; // TND: x=[T,N,D]
54+constexpr int64_t N_SIZE_4 = 4;
55+constexpr int64_t ALPHA_SIZE_3 = 3;
56+constexpr int64_t DEFAULT_KEY = 0;
57+constexpr int64_t DETERMINISTIC_KEY = 1;
58+constexpr int64_t ELEMENTS_SIZE_PER_BLOCK = 8;
59+ 
60+} // namespace
61+ 
62+using namespace ge;
63+using namespace std;
64+using namespace AscendC;
65+ 
66+namespace optiling {
67+ 
68+ge::graphStatus ShapeVerify(gert::TilingContext *context, int64_t batchSize, int64_t seqLength, int64_t n, int64_t c,
69+ bool isTND)
70+{
71+ auto opName = context->GetNodeName();
72+ // BSND: batchSize=B, seqLength=S, totalLength=B*S
73+ // TND: batchSize=T, seqLength=1, totalLength=T
74+ int64_t totalLength = batchSize * seqLength;
75+ 
76+ // 从 phi shape 动态读取 fusionSize, 校验为 N!+2N 或 N²+2N
77+ auto phiShapePtr = context->GetInputShape(PHI_IDX);
78+ OP_CHECK_IF(phiShapePtr == nullptr, OPS_REPORT_VECTOR_INNER_ERR(opName, "ShapeVerify failed, phi shape is nullptr"),
79+ return ge::GRAPH_FAILED);
80+ auto phiShape = phiShapePtr->GetStorageShape();
81+ OP_CHECK_IF(phiShape.GetDimNum() != 2,
82+ OPS_REPORT_VECTOR_INNER_ERR(opName, "ShapeVerify failed, phi must be 2D, but got %lu dims",
83+ phiShape.GetDimNum()),
84+ return ge::GRAPH_FAILED);
85+ int64_t fusionSize = phiShape.GetDim(0);
86+ int64_t factNFact = Factorial(n); // N!
87+ int64_t factNNsq = n * n; // N²
88+ OP_CHECK_IF(
89+ fusionSize != factNFact + 2 * n && fusionSize != factNNsq + 2 * n,
90+ OPS_REPORT_VECTOR_INNER_ERR(opName, "ShapeVerify failed, phi dim0=%ld must be N!+2N (%ld) or N^2+2N (%ld)",
91+ fusionSize, factNFact + 2 * n, factNNsq + 2 * n),
92+ return ge::GRAPH_FAILED);
93+ 
94+ auto gradHInShapePtr = context->GetInputShape(GRAD_H_IN_IDX);
95+ OP_CHECK_IF(gradHInShapePtr == nullptr,
96+ OPS_REPORT_VECTOR_INNER_ERR(opName, "ShapeVerify failed, gradHIn shape is nullptr"),
97+ return ge::GRAPH_FAILED);
98+ auto gradHInShape = gradHInShapePtr->GetStorageShape();
99+ // BSND: gradHIn=[B,S,D] (3D), TND: gradHIn=[T,D] (2D)
100+ int64_t expectedGradHInDims = isTND ? 2 : 3;
@@ -0,0 +1,28 @@
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_backward_arch22_tiling.h
13+ * \brief MhcPreBackward arch22 tiling declaration
14+ */
15+ 
16+#ifndef MHC_PRE_BACKWARD_ARCH22_TILING_H_
17+#define MHC_PRE_BACKWARD_ARCH22_TILING_H_
18+ 
19+#include "op_host/tiling_base.h"
20+#include "register/tilingdata_base.h"
21+#include "tiling/tiling_api.h"
22+#include "err/ops_err.h"
23+ 
24+namespace optiling {
25+ge::graphStatus TilingMhcPreBackwardArch22(gert::TilingContext *context);
26+}
27+ 
28+#endif // MHC_PRE_BACKWARD_ARCH22_TILING_H_
@@ -0,0 +1,85 @@
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_backward_arch22_tiling_utils.h
13+ * \brief Common utilities for arch22 tiling
14+ */
15+#ifndef MHC_PRE_BACKWARD_OP_HOST_OP_TILING_ARCH22_TILING_UTILS_H
16+#define MHC_PRE_BACKWARD_OP_HOST_OP_TILING_ARCH22_TILING_UTILS_H
17+ 
18+#include "register/op_def_registry.h"
19+#include "tiling/platform/platform_ascendc.h"
20+#include "tiling/tiling_api.h"
21+#include "register/tilingdata_base.h"
22+ 
23+inline std::map<ge::DataType, uint64_t> kDataSizeMap = {
24+ {ge::DT_FLOAT, sizeof(float)}, {ge::DT_INT32, sizeof(int32_t)}, {ge::DT_INT64, sizeof(int64_t)}};
25+ 
26+/**
27+ * if b is 0, return a
28+ */
29+template <typename T>
30+inline T DivCeil(T a, T b)
31+{
32+ if (b == 0) {
33+ return 0;
34+ }
35+ return (a + b - 1) / b;
36+}
37+ 
38+/**
39+ * if b is 0, return 0
40+ */
41+template <typename T>
42+inline T CeilAlign(T a, T b)
43+{
44+ if (b == 0) {
45+ return 0;
46+ }
47+ return DivCeil(a, b) * b;
48+}
49+ 
50+/**
51+ * if b is 0, return a
52+ */
53+template <typename T>
54+inline T DivFloor(T a, T b)
55+{
56+ return b == 0 ? a : a / b;
57+}
58+ 
59+/**
60+ * if b is 0, return 0
61+ */
62+template <typename T>
63+inline T FloorAlign(T a, T b)
64+{
65+ return b == 0 ? 0 : a / b * b;
66+}
67+ 
68+/**
69+ * \brief Compute factorial of n
70+ * \param n input value
71+ * \return n! (factorial of n)
72+ */
73+inline int64_t Factorial(int64_t n)
74+{
75+ if (n <= 1) {
76+ return 1;
77+ }
78+ int64_t result = 1;
79+ for (int64_t i = 2; i <= n; i++) {
80+ result *= i;
81+ }
82+ return result;
83+}
84+ 
85+#endif // MHC_PRE_BACKWARD_OP_HOST_OP_TILING_ARCH22_TILING_UTILS_H
@@ -93,8 +93,8 @@ ge::graphStatus MhcPreBackwardTiling::ValidateInputDims(int64_t gradHInDims, int
93 }93 }
94 if (gradHInDims != gradHPostDims) {94 if (gradHInDims != gradHPostDims) {
95 OP_LOGE(context_->GetNodeName(),95 OP_LOGE(context_->GetNodeName(),
96- "grad_h_in and grad_h_post must have the same dim num, gradHInDims=%ld, gradHPostDims=%ld",96+ "grad_h_in and grad_h_post must have the same dim num, gradHInDims=%ld, gradHPostDims=%ld", gradHInDims,
97- gradHInDims, gradHPostDims);97+ gradHPostDims);
98 return ge::GRAPH_FAILED;98 return ge::GRAPH_FAILED;
99 }99 }
100 if ((gradHInDims == BSD_DIM_NUM && gradHResDims != BSNN_DIM_NUM) ||100 if ((gradHInDims == BSD_DIM_NUM && gradHResDims != BSNN_DIM_NUM) ||
@@ -126,8 +126,7 @@ ge::graphStatus MhcPreBackwardTiling::ParseBSDFormat(const gert::Tensor *gradHIn
126 return ge::GRAPH_FAILED;126 return ge::GRAPH_FAILED;
127 }127 }
128 if (gradHResTensor->GetStorageShape().GetDim(0) != batch ||128 if (gradHResTensor->GetStorageShape().GetDim(0) != batch ||
129- gradHResTensor->GetStorageShape().GetDim(1) != sequence ||129+ gradHResTensor->GetStorageShape().GetDim(1) != sequence || gradHResTensor->GetStorageShape().GetDim(2) != N_ ||
130- gradHResTensor->GetStorageShape().GetDim(2) != N_ ||
131 gradHResTensor->GetStorageShape().GetDim(3) != N_) {130 gradHResTensor->GetStorageShape().GetDim(3) != N_) {
132 OP_LOGE(context_->GetNodeName(),131 OP_LOGE(context_->GetNodeName(),
133 "grad_h_res shape must be [B, S, N, N], actual=[%ld,%ld,%ld,%ld], expected=[%lu,%lu,%lu,%lu]",132 "grad_h_res shape must be [B, S, N, N], actual=[%ld,%ld,%ld,%ld], expected=[%lu,%lu,%lu,%lu]",
@@ -154,8 +153,7 @@ ge::graphStatus MhcPreBackwardTiling::ParseTNDFormat(const gert::Tensor *gradHIn
154 gradHPostTensor->GetStorageShape().GetDim(INDEX_T), t);153 gradHPostTensor->GetStorageShape().GetDim(INDEX_T), t);
155 return ge::GRAPH_FAILED;154 return ge::GRAPH_FAILED;
156 }155 }
157- if (gradHResTensor->GetStorageShape().GetDim(0) != t ||156+ if (gradHResTensor->GetStorageShape().GetDim(0) != t || gradHResTensor->GetStorageShape().GetDim(1) != N_ ||
158- gradHResTensor->GetStorageShape().GetDim(1) != N_ ||
159 gradHResTensor->GetStorageShape().GetDim(2) != N_) {157 gradHResTensor->GetStorageShape().GetDim(2) != N_) {
160 OP_LOGE(context_->GetNodeName(),158 OP_LOGE(context_->GetNodeName(),
161 "grad_h_res shape must be [T, N, N], actual=[%ld,%ld,%ld], expected=[%lu,%lu,%lu]",159 "grad_h_res shape must be [T, N, N], actual=[%ld,%ld,%ld], expected=[%lu,%lu,%lu]",
@@ -249,7 +247,6 @@ ge::graphStatus MhcPreBackwardTiling::ParseInputAndAttr()
249 return ge::GRAPH_SUCCESS;247 return ge::GRAPH_SUCCESS;
250}248}
251 249 
252- 
253void MhcPreBackwardTiling::SetC0TilingParams()250void MhcPreBackwardTiling::SetC0TilingParams()
254{251{
255 tilingData_.matmulTilingC0.set_dbL0C(C0_SET_VALUE);252 tilingData_.matmulTilingC0.set_dbL0C(C0_SET_VALUE);
@@ -297,15 +294,14 @@ void MhcPreBackwardTiling::FillTilingData()
297uint64_t MhcPreBackwardTiling::CalculateWorkspaceSize(uint64_t totalLength, uint64_t fusionSize, uint64_t cubeCoreNum,294uint64_t MhcPreBackwardTiling::CalculateWorkspaceSize(uint64_t totalLength, uint64_t fusionSize, uint64_t cubeCoreNum,
298 uint64_t vecCoreNum, uint64_t elementSize)295 uint64_t vecCoreNum, uint64_t elementSize)
299{296{
300- uint64_t v1Elements = totalLength * fusionSize + // h_mix_grad297+ uint64_t v1Elements = totalLength * fusionSize + // h_mix_grad
301 ALPHA_GRAD_CORE_FACTOR * vecCoreNum + // alpha_grad298 ALPHA_GRAD_CORE_FACTOR * vecCoreNum + // alpha_grad
302 vecCoreNum * fusionSize + // bias_grad299 vecCoreNum * fusionSize + // bias_grad
303- totalLength; // inv_rms_grad300+ totalLength; // inv_rms_grad
304 301 
305- uint64_t v2Elements =302+ uint64_t v2Elements = C0_SET_SHAPE_M * C0_SET_SHAPE_N * cubeCoreNum * BUFFER_NUM + // x_rs_grad_mm
306- C0_SET_SHAPE_M * C0_SET_SHAPE_N * cubeCoreNum * BUFFER_NUM + // x_rs_grad_mm303+ C0_SET_SHAPE_M * C0_SET_SHAPE_N * cubeCoreNum * BUFFER_NUM + // x_rs
307- C0_SET_SHAPE_M * C0_SET_SHAPE_N * cubeCoreNum * BUFFER_NUM + // x_rs304+ EXTRA_BUFFER_SIZE;
308- EXTRA_BUFFER_SIZE;
309 uint64_t totalElements =305 uint64_t totalElements =
310 ((v1Elements + WORKSPACE_ALIGN_SIZE - 1) / WORKSPACE_ALIGN_SIZE * WORKSPACE_ALIGN_SIZE) + v2Elements;306 ((v1Elements + WORKSPACE_ALIGN_SIZE - 1) / WORKSPACE_ALIGN_SIZE * WORKSPACE_ALIGN_SIZE) + v2Elements;
311 return totalElements * elementSize;307 return totalElements * elementSize;
@@ -342,8 +338,7 @@ ge::graphStatus MhcPreBackwardTiling::GetMatmulTiling(matmul_tiling::MatmulApiTi
342 }338 }
343 if (mm.GetTiling(isC0 ? tilingData_.matmulTilingC0 : tilingData_.matmulTilingC1) == -1) {339 if (mm.GetTiling(isC0 ? tilingData_.matmulTilingC0 : tilingData_.matmulTilingC1) == -1) {
344 OP_LOGE(context_->GetNodeName(), "ProcessC%d Get Tiling Failed!, m = %lu, n = %lu, k = %lu", isC0 ? 0 : 1,340 OP_LOGE(context_->GetNodeName(), "ProcessC%d Get Tiling Failed!, m = %lu, n = %lu, k = %lu", isC0 ? 0 : 1,
345- isC0 ? totalLength_ : N_ * N_ + 2 * N_, N_ * D_,341+ isC0 ? totalLength_ : N_ * N_ + 2 * N_, N_ * D_, isC0 ? N_ * N_ + 2 * N_ : totalLength_);
346- isC0 ? N_ * N_ + 2 * N_ : totalLength_);
347 return ge::GRAPH_FAILED;342 return ge::GRAPH_FAILED;
348 }343 }
349 return ge::GRAPH_SUCCESS;344 return ge::GRAPH_SUCCESS;
@@ -378,7 +373,6 @@ ge::graphStatus MhcPreBackwardTiling::TilingProcess()
378 return ge::GRAPH_SUCCESS;373 return ge::GRAPH_SUCCESS;
379}374}
380 375 
381- 
382ge::graphStatus MhcPreBackwardTiling::DoOpTiling()376ge::graphStatus MhcPreBackwardTiling::DoOpTiling()
383{377{
384 auto inputXDesc = context_->GetInputDesc(0);378 auto inputXDesc = context_->GetInputDesc(0);
@@ -436,44 +430,4 @@ ge::graphStatus MhcPreBackwardTiling::PostTiling()
436 return ge::GRAPH_SUCCESS;430 return ge::GRAPH_SUCCESS;
437}431}
438 432 
439-static ge::graphStatus TilingFunc4mHCPreGrad(gert::TilingContext *context)
440-{
441- OP_CHECK_IF(context == nullptr, OPS_REPORT_CUBE_INNER_ERR("[mHCPreBackwardTilingFunc]", " context is null"),
442- return ge::GRAPH_FAILED);
443- 
444- return Ops::Transformer::OpTiling::TilingRegistry::GetInstance().DoTilingImpl(context);
445-}
446- 
447- 
448-static ge::graphStatus TilingPrepare4mHCPreGrad(gert::TilingParseContext *context)
449-{
450- OP_CHECK_IF(context == nullptr, OPS_REPORT_CUBE_INNER_ERR("[TilingPrepare4mHC]", "context is null"),
451- return ge::GRAPH_FAILED);
452- fe::PlatFormInfos *platformInfo = context->GetPlatformInfo();
453- OP_CHECK_IF(platformInfo == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "platformInfoPtr is null"),
454- return ge::GRAPH_FAILED);
455- 
456- auto compileInfoPtr = context->GetCompiledInfo<MhcPreBackwardCompileInfo>();
457- OP_CHECK_IF(compileInfoPtr == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "compileInfoPtr is null"),
458- return ge::GRAPH_FAILED);
459- 
460- auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
461- compileInfoPtr->aicNum = ascendcPlatform.GetCoreNumAic();
462- compileInfoPtr->aivNum = ascendcPlatform.GetCoreNumAiv();
463- 
464- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, compileInfoPtr->ubSize);
465- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, compileInfoPtr->l1Size);
466- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L2, compileInfoPtr->l2Size);
467- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_A, compileInfoPtr->l0ASize);
468- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, compileInfoPtr->l0BSize);
469- ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, compileInfoPtr->l0CSize);
470- 
471- OP_LOGI(context->GetNodeName(), "parse compile info success l1Size:%lu, l2Size:%lu, coreNum:%lu",
472- compileInfoPtr->l1Size, compileInfoPtr->l2Size, compileInfoPtr->aicNum);
473- return ge::GRAPH_SUCCESS;
474-}
475- 
476-IMPL_OP_OPTILING(MhcPreBackward)
477- .Tiling(TilingFunc4mHCPreGrad)
478- .TilingParse<MhcPreBackwardCompileInfo>(TilingPrepare4mHCPreGrad);
479} // namespace optiling433} // namespace optiling
@@ -21,6 +21,7 @@
21#include "err/ops_err.h"21#include "err/ops_err.h"
22#include "platform/platform_infos_def.h"22#include "platform/platform_infos_def.h"
23#include "../../../op_kernel/arch35/mhc_pre_backward_tiling_key.h"23#include "../../../op_kernel/arch35/mhc_pre_backward_tiling_key.h"
24+#include "../mhc_pre_backward_tiling.h"
24 25 
25namespace optiling {26namespace optiling {
26 27 
@@ -39,17 +40,6 @@ END_TILING_DATA_DEF;
39 40 
40REGISTER_TILING_DATA_CLASS(MhcPreBackward, MhcPreBackwardTilingData);41REGISTER_TILING_DATA_CLASS(MhcPreBackward, MhcPreBackwardTilingData);
41 42 
42-struct MhcPreBackwardCompileInfo {
43- uint64_t aicNum{0UL};
44- uint64_t aivNum{0UL};
45- uint64_t ubSize{0UL};
46- uint64_t l1Size{0UL};
47- uint64_t l2Size{0UL};
48- uint64_t l0CSize{0UL};
49- uint64_t l0ASize{0UL};
50- uint64_t l0BSize{0UL};
51-};
52- 
53class MhcPreBackwardTiling : public Ops::Transformer::OpTiling::TilingBaseClass {43class MhcPreBackwardTiling : public Ops::Transformer::OpTiling::TilingBaseClass {
54public:44public:
55 explicit MhcPreBackwardTiling(gert::TilingContext *context)45 explicit MhcPreBackwardTiling(gert::TilingContext *context)
@@ -91,7 +81,7 @@ protected:
91 81 
92 ge::graphStatus GetInputShape();82 ge::graphStatus GetInputShape();
93 ge::graphStatus GetInputTensors(const gert::Tensor *&gradHInTensor, const gert::Tensor *&gradHPostTensor,83 ge::graphStatus GetInputTensors(const gert::Tensor *&gradHInTensor, const gert::Tensor *&gradHPostTensor,
94- const gert::Tensor *&gradHResTensor);84+ const gert::Tensor *&gradHResTensor);
95 ge::graphStatus ValidateInputDims(int64_t gradHInDims, int64_t gradHPostDims, int64_t gradHResDims);85 ge::graphStatus ValidateInputDims(int64_t gradHInDims, int64_t gradHPostDims, int64_t gradHResDims);
96 ge::graphStatus ParseBSDFormat(const gert::Tensor *gradHInTensor, const gert::Tensor *gradHPostTensor,86 ge::graphStatus ParseBSDFormat(const gert::Tensor *gradHInTensor, const gert::Tensor *gradHPostTensor,
97 const gert::Tensor *gradHResTensor);87 const gert::Tensor *gradHResTensor);
@@ -0,0 +1,77 @@
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_backward_tiling.cpp
13+ * \brief MhcPreBackward tiling dispatch entry - routes to arch22 (A2) or arch35 (A3/A5)
14+ */
15+ 
16+#include "register/op_def_registry.h"
17+#include "tiling/tiling_api.h"
18+#include "tiling/platform/platform_ascendc.h"
19+#include "arch22/mhc_pre_backward_arch22_tiling.h"
20+#include "mhc_pre_backward_tiling.h"
21+#include "log/log.h"
22+#include "op_host/tiling_templates_registry.h"
23+#include "op_host/tiling_util.h"
24+#include "err/ops_err.h"
25+ 
26+namespace optiling {
27+ 
28+static ge::graphStatus Tiling4MhcPreBackward(gert::TilingContext *context)
29+{
30+ OP_LOGD(context->GetNodeName(), "MhcPreBackward is running.");
31+ 
32+ auto platformInfo = context->GetPlatformInfo();
33+ OP_CHECK_IF(platformInfo == nullptr, OP_LOGE("TilingForMhcPreBackward", "Tiling platformInfo is null"),
34+ return ge::GRAPH_FAILED);
35+ 
36+ if (Ops::Transformer::OpTiling::IsRegbaseSocVersion(context)) {
37+ OP_LOGD(context->GetNodeName(), "Using arch35 tiling for ASCEND950");
38+ return Ops::Transformer::OpTiling::TilingRegistry::GetInstance().DoTilingImpl(context);
39+ }
40+ 
41+ OP_LOGD(context->GetNodeName(), "Using arch22 tiling for ASCEND910B");
42+ return TilingMhcPreBackwardArch22(context);
43+}
44+ 
45+static ge::graphStatus TilingPrepare4MhcPreBackward(gert::TilingParseContext *context)
46+{
47+ OP_CHECK_IF(context == nullptr, OPS_REPORT_CUBE_INNER_ERR("[TilingPrepare4mHC]", "context is null"),
48+ return ge::GRAPH_FAILED);
49+ fe::PlatFormInfos *platformInfo = context->GetPlatformInfo();
50+ OP_CHECK_IF(platformInfo == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "platformInfoPtr is null"),
51+ return ge::GRAPH_FAILED);
52+ 
53+ auto compileInfoPtr = context->GetCompiledInfo<MhcPreBackwardCompileInfo>();
54+ OP_CHECK_IF(compileInfoPtr == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "compileInfoPtr is null"),
55+ return ge::GRAPH_FAILED);
56+ 
57+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
58+ compileInfoPtr->aicNum = ascendcPlatform.GetCoreNumAic();
59+ compileInfoPtr->aivNum = ascendcPlatform.GetCoreNumAiv();
60+ 
61+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, compileInfoPtr->ubSize);
62+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, compileInfoPtr->l1Size);
63+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L2, compileInfoPtr->l2Size);
64+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_A, compileInfoPtr->l0ASize);
65+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, compileInfoPtr->l0BSize);
66+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, compileInfoPtr->l0CSize);
67+ 
68+ OP_LOGI(context->GetNodeName(), "parse compile info success l1Size:%lu, l2Size:%lu, coreNum:%lu",
69+ compileInfoPtr->l1Size, compileInfoPtr->l2Size, compileInfoPtr->aicNum);
70+ return ge::GRAPH_SUCCESS;
71+}
72+ 
73+// register tiling interface of the MhcPreBackward op.
74+IMPL_OP_OPTILING(MhcPreBackward)
75+ .Tiling(Tiling4MhcPreBackward)
76+ .TilingParse<MhcPreBackwardCompileInfo>(TilingPrepare4MhcPreBackward);
77+} // namespace optiling
@@ -0,0 +1,36 @@
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_backward_tiling.h
13+ * \brief MhcPreBackward tiling header - compile info shared by arch22 and arch35
14+ */
15+ 
16+#ifndef MHC_PRE_BACKWARD_TILING_H_
17+#define MHC_PRE_BACKWARD_TILING_H_
18+ 
19+#include <cstdint>
20+#include <register/tilingdata_base.h>
21+#include <tiling/tiling_api.h>
22+ 
23+namespace optiling {
24+struct MhcPreBackwardCompileInfo {
25+ uint64_t aicNum{0UL};
26+ uint64_t aivNum{0UL};
27+ uint64_t ubSize{0UL};
28+ uint64_t l1Size{0UL};
29+ uint64_t l2Size{0UL};
30+ uint64_t l0CSize{0UL};
31+ uint64_t l0ASize{0UL};
32+ uint64_t l0BSize{0UL};
33+};
34+} // namespace optiling
35+ 
36+#endif // MHC_PRE_BACKWARD_TILING_H_
@@ -0,0 +1,43 @@
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_backward_data_arch22.h
13+ * \brief tiling data struct for arch22 (A2)
14+ */
15+ 
16+#ifndef MHC_PRE_BACKWARD_DATA_ARCH22_H
17+#define MHC_PRE_BACKWARD_DATA_ARCH22_H
18+ 
19+#include <cstdint>
20+ 
21+struct MhcPreBackwardArch22TilingData {
22+ int64_t batchSize = 0;
23+ int64_t seqLength = 0;
24+ int64_t c = 0;
25+ int64_t n = 0;
26+ int64_t fusionSize = 0; // phi 第0维: factN + 2*N (A2: N!+2N, A3: N²+2N)
27+ int64_t isBSNN = 0; // gradHRes 布局: 1=BSNN(B,S,N,N), 0=BSN!(B,S,N!)
28+ int64_t c0 = 0;
29+ int64_t c1 = 0;
30+ int64_t cTail = 0;
31+ int64_t aivNum = 0;
32+ int64_t tileGradY = 0;
33+ int64_t tileHHat2 = 0;
34+ int64_t tileSize = 0;
35+ int64_t ubSize = 0;
36+ int64_t withGamma = 0;
37+ int64_t withGradXPost = 0;
38+ float eps = 0;
39+ TCubeTiling mm1TilingData;
40+ TCubeTiling mm2TilingData;
41+};
42+ 
43+#endif // MHC_PRE_BACKWARD_DATA_ARCH22_H
@@ -0,0 +1,29 @@
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_backward_key_arch22.h
13+ * \brief tiling key template arguments for arch22 (A2)
14+ */
15+ 
16+#ifndef MHC_PRE_BACKWARD_KEY_ARCH22_H
17+#define MHC_PRE_BACKWARD_KEY_ARCH22_H
18+ 
19+#include "ascendc/host_api/tiling/template_argument.h"
20+#include "kernel_tiling/kernel_tiling.h"
21+#include "mhc_pre_backward_data_arch22.h"
22+ 
23+ASCENDC_TPL_ARGS_DECL(MhcPreBackward, ASCENDC_TPL_BOOL_DECL(TILINGKEY, 0, 1), );
24+ 
25+ASCENDC_TPL_SEL(ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_KERNEL_TYPE_SEL(ASCENDC_TPL_MIX_AIC_1_2),
26+ ASCENDC_TPL_BOOL_SEL(TILINGKEY, 0, 1),
27+ ASCENDC_TPL_TILING_STRUCT_SEL(MhcPreBackwardArch22TilingData)), )
28+ 
29+#endif // MHC_PRE_BACKWARD_KEY_ARCH22_H
@@ -0,0 +1,61 @@
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_backward.cpp
13+ * \brief A2 (ascend910b) kernel entry for mhc_pre_backward
14+ */
15+ 
16+#include "kernel_operator.h"
17+#include "lib/matmul_intf.h"
18+#include "arch22/mhc_pre_backward_kernel_arch22.h"
19+#include "arch22/mhc_pre_backward_data_arch22.h"
20+#include "arch22/mhc_pre_backward_key_arch22.h"
21+ 
22+using namespace AscendC;
23+ 
24+template <bool TILINGKEY>
25+__global__ __aicore__ void mhc_pre_backward(GM_ADDR x, GM_ADDR phi, GM_ADDR alpha, GM_ADDR grad_h_in,
26+ GM_ADDR grad_h_post, GM_ADDR grad_h_res, GM_ADDR inv_rms, GM_ADDR h_mix,
27+ GM_ADDR h_pre, GM_ADDR h_post, GM_ADDR gamma, GM_ADDR grad_x_post_optional,
28+ GM_ADDR grad_x, GM_ADDR grad_phi, GM_ADDR grad_alpha, GM_ADDR grad_bias,
29+ GM_ADDR grad_gamma, GM_ADDR workspace, GM_ADDR tiling)
30+{
31+ REGISTER_TILING_DEFAULT(MhcPreBackwardArch22TilingData);
32+ GET_TILING_DATA_WITH_STRUCT(MhcPreBackwardArch22TilingData, tilingData, tiling);
33+ GM_ADDR usrWorkspace = GetUserWorkspace(workspace);
34+ if (usrWorkspace == nullptr) {
35+ return;
36+ }
37+ KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);
38+ 
39+ TPipe pipe;
40+ if constexpr (TILINGKEY) {
41+ MhcPreBackwardKernelArch22<DTYPE_X, DTYPE_PHI, true> op;
42+ op.mm1_.SetSubBlockIdx(0);
43+ op.mm1_.Init(&tilingData.mm1TilingData, &pipe);
44+ op.mm2_.SetSubBlockIdx(0);
45+ op.mm2_.Init(&tilingData.mm2TilingData, &pipe);
46+ 
47+ op.Init(x, phi, h_pre, h_post, grad_h_in, grad_h_post, grad_h_res, alpha, h_mix, inv_rms, grad_x, grad_phi,
48+ grad_alpha, grad_bias, usrWorkspace, &tilingData, &pipe, gamma, grad_x_post_optional, grad_gamma);
49+ op.Process();
50+ } else {
51+ MhcPreBackwardKernelArch22<DTYPE_X, DTYPE_PHI, true> op;
52+ op.mm1_.SetSubBlockIdx(0);
53+ op.mm1_.Init(&tilingData.mm1TilingData, &pipe);
54+ op.mm2_.SetSubBlockIdx(0);
55+ op.mm2_.Init(&tilingData.mm2TilingData, &pipe);
56+ 
57+ op.Init(x, phi, h_pre, h_post, grad_h_in, grad_h_post, grad_h_res, alpha, h_mix, inv_rms, grad_x, grad_phi,
58+ grad_alpha, grad_bias, usrWorkspace, &tilingData, &pipe, gamma, grad_x_post_optional, grad_gamma);
59+ op.Process();
60+ }
61+}
@@ -15,4 +15,4 @@ foreach(SUB_DIR ${CURRENT_DIRS})
15 if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")15 if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
16 add_subdirectory(${SUB_DIR})16 add_subdirectory(${SUB_DIR})
17 endif()17 endif()
18-endforeach()18+endforeach()
@@ -12,4 +12,4 @@ foreach(SUB_DIR ${CURRENT_DIRS})
12 if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")12 if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
13 add_subdirectory(${SUB_DIR})13 add_subdirectory(${SUB_DIR})
14 endif()14 endif()
15-endforeach()15+endforeach()
@@ -10,4 +10,4 @@
10 10 
11if(UT_TEST_ALL OR OP_API_UT)11if(UT_TEST_ALL OR OP_API_UT)
12 add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})12 add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})
13-endif()13+endif()
@@ -21,4 +21,4 @@ foreach(SUB_DIR ${CURRENT_DIRS})
21 if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")21 if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
22 add_subdirectory(${SUB_DIR})22 add_subdirectory(${SUB_DIR})
23 endif()23 endif()
24-endforeach()24+endforeach()
@@ -433,12 +433,121 @@ TEST_F(MhcPreBackwardProto, Ut_Check_Case08_TND_T8192_n4_D2048_FP16)
433 ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);433 ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);
434}434}
435 435 
436+/*
437+ * TND格式测试用例3:T=1024, n=4,D=512, x数据类型bf16
438+ * gradHRes为TN!格式 [T, N!] (2D)
439+ * 预期结果:成功
440+ */
441+TEST_F(MhcPreBackwardProto, Ut_Check_Case09_TND_T1024_n4_D512_BF16_TNFact)
442+{
443+ float alpha[3] = {0.3f, 0.3f, 0.3f};
444+ uint32_t T = 1024;
445+ uint32_t n = 4;
446+ uint32_t D = 512;
447+ uint32_t nD = n * D; // 2048
448+ uint32_t factN = 1; // N! = 24 for n=4
449+ for (uint32_t i = 2; i <= n; i++) {
450+ factN *= i;
451+ } // Factorial(4) = 24
452+ uint32_t fusionSize = factN + 2 * n; // N!+2N = 32
453+ float hcEps = 0.000001f;
454+ 
455+ gert::InfershapeContextPara infershapeContextPara(
456+ "MhcPreBackward",
457+ {
458+ {{{T, n, D}, {T, n, D}}, ge::DT_BF16, ge::FORMAT_ND}, // x (TND format)
459+ {{{fusionSize, nD}, {fusionSize, nD}}, ge::DT_FLOAT, ge::FORMAT_ND}, // phi
460+ {{{3}, {3}}, ge::DT_FLOAT, ge::FORMAT_ND}, // alpha
461+ {{{T, D}, {T, D}}, ge::DT_BF16, ge::FORMAT_ND}, // gradHIn (TD format)
462+ {{{T, n}, {T, n}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradHPost (TN format)
463+ {{{T, factN}, {T, factN}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradHRes (TN! format, 2D)
464+ {{{T}, {T}}, ge::DT_FLOAT, ge::FORMAT_ND}, // invRms (T format)
465+ {{{T, fusionSize}, {T, fusionSize}}, ge::DT_FLOAT, ge::FORMAT_ND}, // hMix
466+ {{{T, n}, {T, n}}, ge::DT_FLOAT, ge::FORMAT_ND}, // hPre
467+ {{{T, n}, {T, n}}, ge::DT_FLOAT, ge::FORMAT_ND}, // hPost
468+ {{{nD}, {nD}}, ge::DT_FLOAT, ge::FORMAT_ND} // gamma (optional)
469+ },
470+ {
471+ {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // gradX
472+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradPhi
473+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradAlpha
474+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradBias
475+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // gradGamma (optional)
476+ },
477+ {{"hc_eps", Ops::Transformer::AnyValue::CreateFrom<float>(hcEps)}});
478+ 
479+ std::vector<std::vector<int64_t>> expectOutputShape = {
480+ {T, n, D}, // gradX: [T, n, D]
481+ {fusionSize, nD}, // gradPhi: [fusionSize, nD]
482+ {3}, // gradAlpha: [3]
483+ {fusionSize}, // gradBias: [fusionSize]
484+ {n, D} // gradGamma: [n, D]
485+ };
486+ 
487+ ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);
488+}
489+ 
490+/*
491+ * BSND格式测试用例4:B=2, S=4096, n=4,D=1536, x数据类型bf16
492+ * gradHRes为BSN!格式 [B, S, N!] (3D)
493+ * 预期结果:成功
494+ */
495+TEST_F(MhcPreBackwardProto, Ut_Check_Case10_B2_S4096_n4_D1536_BF16_BSNFact)
496+{
497+ float alpha[3] = {0.25f, 0.25f, 0.25f};
498+ uint32_t B = 2;
499+ uint32_t S = 4096;
500+ uint32_t n = 4;
501+ uint32_t D = 1536;
502+ uint32_t nD = n * D; // 6144
503+ uint32_t factN = 1; // N! = 24 for n=4
504+ for (uint32_t i = 2; i <= n; i++) {
505+ factN *= i;
506+ } // Factorial(4) = 24
507+ uint32_t fusionSize = factN + 2 * n; // N!+2N = 32
508+ float hcEps = 0.000001f;
509+ 
510+ gert::InfershapeContextPara infershapeContextPara(
511+ "MhcPreBackward",
512+ {
513+ {{{B, S, n, D}, {B, S, n, D}}, ge::DT_BF16, ge::FORMAT_ND}, // x
514+ {{{fusionSize, nD}, {fusionSize, nD}}, ge::DT_FLOAT, ge::FORMAT_ND}, // phi
515+ {{{3}, {3}}, ge::DT_FLOAT, ge::FORMAT_ND}, // alpha
516+ {{{B, S, D}, {B, S, D}}, ge::DT_BF16, ge::FORMAT_ND}, // gradHIn
517+ {{{B, S, n}, {B, S, n}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradHPost
518+ {{{B, S, factN}, {B, S, factN}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradHRes (BSN! format, 3D)
519+ {{{B, S}, {B, S}}, ge::DT_FLOAT, ge::FORMAT_ND}, // invRms
520+ {{{B, S, fusionSize}, {B, S, fusionSize}}, ge::DT_FLOAT, ge::FORMAT_ND}, // hMix
521+ {{{B, S, n}, {B, S, n}}, ge::DT_FLOAT, ge::FORMAT_ND}, // hPre
522+ {{{B, S, n}, {B, S, n}}, ge::DT_FLOAT, ge::FORMAT_ND}, // hPost
523+ {{{nD}, {nD}}, ge::DT_FLOAT, ge::FORMAT_ND} // gamma (optional)
524+ },
525+ {
526+ {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // gradX
527+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradPhi
528+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradAlpha
529+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // gradBias
530+ {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // gradGamma (optional)
531+ },
532+ {{"hc_eps", Ops::Transformer::AnyValue::CreateFrom<float>(hcEps)}});
533+ 
534+ std::vector<std::vector<int64_t>> expectOutputShape = {
535+ {B, S, n, D}, // gradX: [B, S, n, D]
536+ {fusionSize, nD}, // gradPhi: [fusionSize, nD]
537+ {3}, // gradAlpha: [3]
538+ {fusionSize}, // gradBias: [fusionSize]
539+ {n, D} // gradGamma: [n, D]
540+ };
541+ 
542+ ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);
543+}
544+ 
436/*545/*
437 * 边界测试用例1:B=1, S=1, n=4,D=64, x数据类型bf16546 * 边界测试用例1:B=1, S=1, n=4,D=64, x数据类型bf16
438 * 最小尺寸测试547 * 最小尺寸测试
439 * 预期结果:成功548 * 预期结果:成功
440 */549 */
441-TEST_F(MhcPreBackwardProto, Ut_Check_Case09_B1_S1_n4_D1_BF16_Boundary)550+TEST_F(MhcPreBackwardProto, Ut_Check_Case11_B1_S1_n4_D1_BF16_Boundary)
442{551{
443 float alpha[3] = {0.1f, 0.1f, 0.1f}; // alpha = [0.1, 0.1, 0.1]552 float alpha[3] = {0.1f, 0.1f, 0.1f}; // alpha = [0.1, 0.1, 0.1]
444 uint32_t B = 1;553 uint32_t B = 1;
@@ -533,4 +642,4 @@ TEST_F(MhcPreBackwardProto, Ut_Check_Case10_B1_S65535_n8_D8192_FP16_Boundary)
533 };642 };
534 643 
535 ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);644 ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);
536-}645+}