Merged
【feat】mega_moe 弹性扩缩容 #9368
【feat】mega_moe 弹性扩缩容 #9368
Merged
Simple_Bright&ManAdd on Jul 30
Total: 15 files changed+604-168
@@ -108,10 +108,13 @@ static void CopyContextToTensor(const CommContext &context, at::Tensor &tensor)
108// ======================== KFC Mode ========================108// ======================== KFC Mode ========================
109class KfcContextBuilder {109class KfcContextBuilder {
110public:110public:
111- void Build(const std::string &group, int64_t worldSize, int64_t &cclBufferSize, at::Tensor &contextTensor)111+ void Build(const std::string &group, int64_t worldSize, int64_t &cclBufferSize, at::Tensor &contextTensor,
112+ void **localDeviceBuffer)
112 {113 {
113 CommContext mc2ContextHost;114 CommContext mc2ContextHost;
114 GetMc2Context(mc2ContextHost, worldSize, cclBufferSize, group.c_str());115 GetMc2Context(mc2ContextHost, worldSize, cclBufferSize, group.c_str());
116+ TORCH_CHECK(mc2ContextHost.epRankId < HCCL_MAX_RANK_SIZE, "Invalid local rank id: ", mc2ContextHost.epRankId);
117+ *localDeviceBuffer = reinterpret_cast<void *>(mc2ContextHost.epHcclBuffer_[mc2ContextHost.epRankId]);
115 118 
116 CopyContextToTensor(mc2ContextHost, contextTensor);119 CopyContextToTensor(mc2ContextHost, contextTensor);
117 }120 }
@@ -603,8 +606,14 @@ public:
603 static_cast<int>(protocol));606 static_cast<int>(protocol));
604 }607 }
605 608 
606- TopoType GetTopoType() const { return topoType_; }609+ TopoType GetTopoType() const
607- int64_t GetRankNumPerServer() const { return rankNumPerServer_; }610+ {
611+ return topoType_;
612+ }
613+ int64_t GetRankNumPerServer() const
614+ {
615+ return rankNumPerServer_;
616+ }
608 617 
609 // 记录本卡与其他卡的通信层数,key为其他卡的rankId,value为通信层数618 // 记录本卡与其他卡的通信层数,key为其他卡的rankId,value为通信层数
610 std::unordered_map<uint32_t, uint32_t> layerMap_;619 std::unordered_map<uint32_t, uint32_t> layerMap_;
@@ -677,14 +686,45 @@ public:
677 TORCH_CHECK(aclRet == ACL_SUCCESS, "aclrtFree(customDeviceBuffer_) failed, ret=", aclRet);686 TORCH_CHECK(aclRet == ACL_SUCCESS, "aclrtFree(customDeviceBuffer_) failed, ret=", aclRet);
678 customDeviceBuffer_ = nullptr;687 customDeviceBuffer_ = nullptr;
679 }688 }
689+ localDeviceBuffer_ = nullptr;
680 }690 }
681 691 
682- int64_t CclBufferSize() const { return cclBufferSize_; }692+ int64_t CclBufferSize() const
683- int64_t GetTopoType() const { return static_cast<int64_t>(topoType_); }693+ {
684- int64_t GetRankNumPerServer() const { return static_cast<int64_t>(rankNumPerServer_); }694+ return cclBufferSize_;
695+ }
696+ int64_t GetTopoType() const
697+ {
698+ return static_cast<int64_t>(topoType_);
699+ }
700+ int64_t GetRankNumPerServer() const
701+ {
702+ return static_cast<int64_t>(rankNumPerServer_);
703+ }
704+ 
705+ at::Tensor GetLocalBufferTensor(const py::object &dtype, int64_t offset) const
706+ {
707+ TORCH_CHECK(localDeviceBuffer_ != nullptr, "Local CCL buffer is not initialized.");
708+ TORCH_CHECK(offset >= 0, "offset must be non-negative, got ", offset, ".");
709+ torch::ScalarType scalarType = torch::python::detail::py_object_to_dtype(dtype);
710+ int64_t elementBytes = static_cast<int64_t>(c10::elementSize(scalarType));
711+ TORCH_CHECK(elementBytes > 0, "Invalid element size for requested dtype.");
712+ int64_t totalElements = cclBufferSize_ / elementBytes;
713+ TORCH_CHECK(offset <= totalElements, "offset must be in [0, ", totalElements, "], got ", offset, ".");
714+ 
715+ void *data = static_cast<void *>(static_cast<uint8_t *>(localDeviceBuffer_) + offset * elementBytes);
716+ auto options = at::TensorOptions()
717+ .dtype(scalarType)
718+ .device(c10::DeviceType::PrivateUse1)
719+ .memory_format(c10::MemoryFormat::Contiguous);
720+ return at::from_blob(data, {totalElements - offset}, options);
721+ }
685 722 
686private:723private:
687- static int64_t ContextTensorSize() { return (sizeof(CommContext) + sizeof(int32_t) - 1) / sizeof(int32_t); }724+ static int64_t ContextTensorSize()
725+ {
726+ return (sizeof(CommContext) + sizeof(int32_t) - 1) / sizeof(int32_t);
727+ }
688 728 
689 void EnsureResolved()729 void EnsureResolved()
690 {730 {
@@ -698,13 +738,14 @@ private:
698 switch (mode_) {738 switch (mode_) {
699 case BackendMode::KFC: {739 case BackendMode::KFC: {
700 KfcContextBuilder builder;740 KfcContextBuilder builder;
701- builder.Build(group_, worldSize_, cclBufferSize_, tensor);741+ builder.Build(group_, worldSize_, cclBufferSize_, tensor, &localDeviceBuffer_);
702 return;742 return;
703 }743 }
704 case BackendMode::CHANNEL: {744 case BackendMode::CHANNEL: {
705 HcclChannelContextBuilder builder;745 HcclChannelContextBuilder builder;
706 builder.Build(group_, worldSize_, cclBufferSize_, tensor, commAlg_, opName_, customCclBufferSize_,746 builder.Build(group_, worldSize_, cclBufferSize_, tensor, commAlg_, opName_, customCclBufferSize_,
707 &customDeviceBuffer_, &customMemHandle_);747 &customDeviceBuffer_, &customMemHandle_);
748+ localDeviceBuffer_ = customDeviceBuffer_;
708 topoType_ = builder.GetTopoType();749 topoType_ = builder.GetTopoType();
709 rankNumPerServer_ = builder.GetRankNumPerServer();750 rankNumPerServer_ = builder.GetRankNumPerServer();
710 return;751 return;
@@ -725,6 +766,7 @@ private:
725 int64_t rankNumPerServer_ = DEFAULT_RANK_NUM_PER_SERVER;766 int64_t rankNumPerServer_ = DEFAULT_RANK_NUM_PER_SERVER;
726 int64_t customCclBufferSize_ = 0;767 int64_t customCclBufferSize_ = 0;
727 void *customDeviceBuffer_ = nullptr;768 void *customDeviceBuffer_ = nullptr;
769+ void *localDeviceBuffer_ = nullptr;
728 HcclMemHandle customMemHandle_ = nullptr;770 HcclMemHandle customMemHandle_ = nullptr;
729};771};
730 772 
@@ -740,6 +782,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
740 .def("create_context", &CommContextManager::CreateContext)782 .def("create_context", &CommContextManager::CreateContext)
741 .def("update_group", &CommContextManager::UpdateGroup, py::arg("group"), py::arg("contextTensor").noconvert())783 .def("update_group", &CommContextManager::UpdateGroup, py::arg("group"), py::arg("contextTensor").noconvert())
742 .def("destroy", &CommContextManager::Destroy)784 .def("destroy", &CommContextManager::Destroy)
785+ .def("get_local_buffer_tensor", &CommContextManager::GetLocalBufferTensor, py::arg("dtype"),
786+ py::arg("offset") = 0)
743 .def_property_readonly("ccl_buffer_size", &CommContextManager::CclBufferSize)787 .def_property_readonly("ccl_buffer_size", &CommContextManager::CclBufferSize)
744 .def_property_readonly("topo_type", &CommContextManager::GetTopoType)788 .def_property_readonly("topo_type", &CommContextManager::GetTopoType)
745 .def_property_readonly("rank_num_per_server", &CommContextManager::GetRankNumPerServer);789 .def_property_readonly("rank_num_per_server", &CommContextManager::GetRankNumPerServer);
@@ -102,11 +102,12 @@ aclnnStatus aclnnMegaMoeGetWorkspaceSize(
102 const aclTensor *xActiveMaskOptional, const aclTensorList *sharedWeight1Optional,102 const aclTensor *xActiveMaskOptional, const aclTensorList *sharedWeight1Optional,
103 const aclTensorList *sharedWeight2Optional, const aclTensorList *sharedWeightScales1Optional,103 const aclTensorList *sharedWeight2Optional, const aclTensorList *sharedWeightScales1Optional,
104 const aclTensorList *sharedWeightScales2Optional, const aclTensorList *sharedBias1Optional,104 const aclTensorList *sharedWeightScales2Optional, const aclTensorList *sharedBias1Optional,
105- const aclTensorList *sharedBias2Optional, int64_t moeExpertNum, int64_t epWorldSize, int64_t cclBufferSize,105+ const aclTensorList *sharedBias2Optional, const aclTensor *maskBufferOptional, int64_t moeExpertNum,
106- int64_t maxRecvTokenNum, int64_t dispatchQuantMode, int64_t dispatchQuantOutDtype, int64_t combineQuantMode,106+ int64_t epWorldSize, int64_t cclBufferSize, int64_t maxRecvTokenNum, int64_t dispatchQuantMode,
107- const char *commAlg, int64_t numMaxTokensPerRank, const char *activation, const aclFloatArray *activationParams,107+ int64_t dispatchQuantOutDtype, int64_t combineQuantMode, const char *commAlg, int64_t numMaxTokensPerRank,
108- int64_t topoType, int64_t rankNumPerServer, int64_t topkWeightsType, aclTensor *yOut, aclTensor *expertTokenNumsOut,108+ const char *activation, const aclFloatArray *activationParams, int64_t topoType, int64_t rankNumPerServer,
109- uint64_t *workspaceSize, aclOpExecutor **executor)109+ int64_t topkWeightsType, aclTensor *yOut, aclTensor *expertTokenNumsOut, uint64_t *workspaceSize,
110+ aclOpExecutor **executor)
110{111{
111 OP_LOGD("aclnn_mega_moe WorkspaceSize start");112 OP_LOGD("aclnn_mega_moe WorkspaceSize start");
112 113 
@@ -191,10 +192,10 @@ aclnnStatus aclnnMegaMoeGetWorkspaceSize(
191 context, x, topkIds, topkWeights, weight1, weight2, weightScales1Optional, weightScales2Optional, bias1Optional,192 context, x, topkIds, topkWeights, weight1, weight2, weightScales1Optional, weightScales2Optional, bias1Optional,
192 bias2Optional, xActiveMaskOptional, nullptr, sharedWeight1Optional, sharedWeight2Optional,193 bias2Optional, xActiveMaskOptional, nullptr, sharedWeight1Optional, sharedWeight2Optional,
193 sharedWeightScales1Optional, sharedWeightScales2Optional, sharedBias1Optional, sharedBias2Optional,194 sharedWeightScales1Optional, sharedWeightScales2Optional, sharedBias1Optional, sharedBias2Optional,
194- moeExpertNum, epWorldSize, cclBufferSize, maxRecvTokenNum, dispatchQuantMode, dispatchQuantOutDtype,195+ maskBufferOptional, moeExpertNum, epWorldSize, cclBufferSize, maxRecvTokenNum, dispatchQuantMode,
195- combineQuantMode, const_cast<char *>(commAlg), numMaxTokensPerRank, const_cast<char *>(activation),196+ dispatchQuantOutDtype, combineQuantMode, const_cast<char *>(commAlg), numMaxTokensPerRank,
196- activationParams, ge::DT_UNDEFINED, false, false, 0, topoType, rankNumPerServer, topkWeightsType, yOut,197+ const_cast<char *>(activation), activationParams, ge::DT_UNDEFINED, false, false, 0, topoType, rankNumPerServer,
197- expertTokenNumsOut, workspaceSize, executor);198+ topkWeightsType, yOut, expertTokenNumsOut, workspaceSize, executor);
198 199 
199 return getWorkspaceSizesRes;200 return getWorkspaceSizesRes;
200}201}
@@ -155,6 +155,11 @@ public:
155 .DataTypeList({ge::DT_FLOAT})155 .DataTypeList({ge::DT_FLOAT})
156 .FormatList({ge::FORMAT_ND})156 .FormatList({ge::FORMAT_ND})
157 .AutoContiguous();157 .AutoContiguous();
158+ this->Input("mask_buffer")
159+ .ParamType(OPTIONAL)
160+ .DataTypeList({ge::DT_INT32})
161+ .FormatList({ge::FORMAT_ND})
162+ .AutoContiguous();
158 163 
159 this->Output("y").ParamType(REQUIRED).DataTypeList({ge::DT_BF16}).FormatList({ge::FORMAT_ND});164 this->Output("y").ParamType(REQUIRED).DataTypeList({ge::DT_BF16}).FormatList({ge::FORMAT_ND});
160 this->Output("expert_token_nums").ParamType(REQUIRED).DataTypeList({ge::DT_INT32}).FormatList({ge::FORMAT_ND});165 this->Output("expert_token_nums").ParamType(REQUIRED).DataTypeList({ge::DT_INT32}).FormatList({ge::FORMAT_ND});
@@ -177,7 +182,6 @@ public:
177 this->Attr("topo_type").AttrType(OPTIONAL).Int(0);182 this->Attr("topo_type").AttrType(OPTIONAL).Int(0);
178 this->Attr("rank_num_per_server").AttrType(OPTIONAL).Int(2); // 最少2个rank183 this->Attr("rank_num_per_server").AttrType(OPTIONAL).Int(2); // 最少2个rank
179 this->Attr("topk_weights_type").AttrType(OPTIONAL).Int(0);184 this->Attr("topk_weights_type").AttrType(OPTIONAL).Int(0);
180- 
181 OpAICoreConfig aicore_config;185 OpAICoreConfig aicore_config;
182 aicore_config.DynamicCompileStaticFlag(true)186 aicore_config.DynamicCompileStaticFlag(true)
183 .DynamicFormatFlag(true)187 .DynamicFormatFlag(true)
@@ -308,6 +312,11 @@ public:
308 .DataTypeList({ge::DT_FLOAT})312 .DataTypeList({ge::DT_FLOAT})
309 .FormatList({ge::FORMAT_ND})313 .FormatList({ge::FORMAT_ND})
310 .AutoContiguous();314 .AutoContiguous();
315+ aicore_config_arch22.Input("mask_buffer")
316+ .ParamType(OPTIONAL)
317+ .DataTypeList({ge::DT_INT32})
318+ .FormatList({ge::FORMAT_ND})
319+ .AutoContiguous();
311 320 
312 aicore_config_arch22.Output("y")321 aicore_config_arch22.Output("y")
313 .ParamType(REQUIRED)322 .ParamType(REQUIRED)
@@ -78,6 +78,7 @@ constexpr uint32_t BIAS1_INDEX = 8; // GMM1 的 bias(OPTIONAL)
78constexpr uint32_t BIAS2_INDEX = 9; // GMM2 的 bias(OPTIONAL)78constexpr uint32_t BIAS2_INDEX = 9; // GMM2 的 bias(OPTIONAL)
79constexpr uint32_t X_ACTIVE_MASK_INDEX = 10; // token 活跃掩码(OPTIONAL)79constexpr uint32_t X_ACTIVE_MASK_INDEX = 10; // token 活跃掩码(OPTIONAL)
80constexpr uint32_t SCALES_INDEX = 11; // 额外 scale(OPTIONAL)80constexpr uint32_t SCALES_INDEX = 11; // 额外 scale(OPTIONAL)
81+constexpr uint32_t MASK_BUFFER_INDEX = 18; // rank 通信掩码(OPTIONAL)
81 82 
82// 输出 tensor 索引83// 输出 tensor 索引
83constexpr uint32_t OUTPUT_Y_INDEX = 0; // 输出 y,shape = [M, K]84constexpr uint32_t OUTPUT_Y_INDEX = 0; // 输出 y,shape = [M, K]
@@ -306,11 +307,20 @@ static ge::graphStatus CheckActivationAttr(const char *ptr, uint32_t &activation
306 return ge::GRAPH_SUCCESS;307 return ge::GRAPH_SUCCESS;
307}308}
308 309 
309-static bool IsValidActivationClamp(float value) { return value >= 0.0f && !std::isnan(value); }310+static bool IsValidActivationClamp(float value)
311+{
312+ return value >= 0.0f && !std::isnan(value);
313+}
310 314 
311-static bool IsFiniteActivationParam(float value) { return std::isfinite(value); }315+static bool IsFiniteActivationParam(float value)
316+{
317+ return std::isfinite(value);
318+}
312 319 
313-static bool IsValidSituScale(float value) { return std::isfinite(value) && value != 0.0f; }320+static bool IsValidSituScale(float value)
321+{
322+ return std::isfinite(value) && value != 0.0f;
323+}
314 324 
315static ge::graphStatus CheckActivationParamCount(uint32_t activationCode, size_t actualCount, size_t minCount,325static ge::graphStatus CheckActivationParamCount(uint32_t activationCode, size_t actualCount, size_t minCount,
316 size_t maxCount)326 size_t maxCount)
@@ -518,6 +528,22 @@ static ge::graphStatus MegaMoeA2A3CheckAttrAndSetTiling(gert::TilingContext *con
518 OP_LOGE_WITHOUT_REPORT(K_INNER_DEBUG, "CheckNumMaxTokensPerRankAttr failed."), return GRAPH_FAILED);528 OP_LOGE_WITHOUT_REPORT(K_INNER_DEBUG, "CheckNumMaxTokensPerRankAttr failed."), return GRAPH_FAILED);
519 info.numMaxTokensPerRank = static_cast<uint32_t>(*numMaxTokensPerRankPtr);529 info.numMaxTokensPerRank = static_cast<uint32_t>(*numMaxTokensPerRankPtr);
520 530 
531+ // Rank mask is an A3-only capability.
532+ std::string socVersion = mc2tiling::GetSocVersion(context);
533+ auto maskBuffer = context->GetOptionalInputTensor(MASK_BUFFER_INDEX);
534+ OP_TILING_CHECK(socVersion != "Ascend910_93" && maskBuffer != nullptr,
535+ OP_LOGE(K_INNER_DEBUG, "mask_buffer is supported on A3 only."), return GRAPH_FAILED);
536+ if (maskBuffer != nullptr) {
537+ auto maskShape = context->GetOptionalInputShape(MASK_BUFFER_INDEX);
538+ auto maskDesc = context->GetOptionalInputDesc(MASK_BUFFER_INDEX);
539+ OP_TILING_CHECK(maskShape == nullptr || maskDesc == nullptr,
540+ OP_LOGE(K_INNER_DEBUG, "mask_buffer shape/desc is null."), return GRAPH_FAILED);
541+ OP_TILING_CHECK(maskShape->GetStorageShape().GetDimNum() != ONE_DIM ||
542+ maskShape->GetStorageShape().GetDim(0) != static_cast<int64_t>(info.epWorldSize),
543+ OP_LOGE(K_INNER_DEBUG, "mask_buffer shape must be [ep_world_size]."), return GRAPH_FAILED);
544+ OP_TILING_CHECK(maskDesc->GetDataType() != ge::DT_INT32,
545+ OP_LOGE(K_INNER_DEBUG, "mask_buffer dtype must be int32."), return GRAPH_FAILED);
546+ }
521 // 9. activation547 // 9. activation
522 OP_TILING_CHECK(CheckActivationAttr(activationPtr, info.activationCode) != ge::GRAPH_SUCCESS,548 OP_TILING_CHECK(CheckActivationAttr(activationPtr, info.activationCode) != ge::GRAPH_SUCCESS,
523 OP_LOGE_WITHOUT_REPORT(K_INNER_DEBUG, "CheckActivationAttr failed."), return GRAPH_FAILED);549 OP_LOGE_WITHOUT_REPORT(K_INNER_DEBUG, "CheckActivationAttr failed."), return GRAPH_FAILED);
@@ -43,6 +43,7 @@ struct MegaMoeConfig {
43 uint32_t sharedWeightScales2Index = 15U;43 uint32_t sharedWeightScales2Index = 15U;
44 uint32_t sharedBias1Index = 16U;44 uint32_t sharedBias1Index = 16U;
45 uint32_t sharedBias2Index = 17U;45 uint32_t sharedBias2Index = 17U;
46+ uint32_t maskBufferIndex = 18U;
46 uint32_t yIndex = 0U;47 uint32_t yIndex = 0U;
47 uint32_t expertTokenNumsIndex = 1U;48 uint32_t expertTokenNumsIndex = 1U;
48 uint32_t attrMoeExpertNumIndex = 0U;49 uint32_t attrMoeExpertNumIndex = 0U;
@@ -35,7 +35,7 @@ __global__ __aicore__ void mega_moe(GM_ADDR context, GM_ADDR x, GM_ADDR topkIds,
35 GM_ADDR weight2, GM_ADDR weightScales1, GM_ADDR weightScales2, GM_ADDR bias1,35 GM_ADDR weight2, GM_ADDR weightScales1, GM_ADDR weightScales2, GM_ADDR bias1,
36 GM_ADDR bias2, GM_ADDR xActiveMask, GM_ADDR scales, GM_ADDR sharedWeight1,36 GM_ADDR bias2, GM_ADDR xActiveMask, GM_ADDR scales, GM_ADDR sharedWeight1,
37 GM_ADDR sharedWeight2, GM_ADDR sharedWeightScales1, GM_ADDR sharedWeightScales2,37 GM_ADDR sharedWeight2, GM_ADDR sharedWeightScales1, GM_ADDR sharedWeightScales2,
38- GM_ADDR sharedBias1, GM_ADDR sharedBias2, GM_ADDR yOut,38+ GM_ADDR sharedBias1, GM_ADDR sharedBias2, GM_ADDR maskBuffer, GM_ADDR yOut,
39 GM_ADDR expertTokenNumsOut, GM_ADDR workspaceGM, GM_ADDR tilingGM)39 GM_ADDR expertTokenNumsOut, GM_ADDR workspaceGM, GM_ADDR tilingGM)
40{40{
41 KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);41 KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);
@@ -67,14 +67,14 @@ __global__ __aicore__ void mega_moe(GM_ADDR context, GM_ADDR x, GM_ADDR topkIds,
67 GET_TILING_DATA_WITH_STRUCT(MegaMoeTilingDataQuant, tilingData, tilingGM);67 GET_TILING_DATA_WITH_STRUCT(MegaMoeTilingDataQuant, tilingData, tilingGM);
68 MegaMoe<DTYPE_X, DTYPE_WEIGHT1, DTYPE_Y, TPL_IS_TRANSPOSE_W1, TPL_IS_TRANSPOSE_W2, isNz, false> op;68 MegaMoe<DTYPE_X, DTYPE_WEIGHT1, DTYPE_Y, TPL_IS_TRANSPOSE_W1, TPL_IS_TRANSPOSE_W2, isNz, false> op;
69 op.Init(context, x, topkIds, topkWeights, weight1, weight2, weightScales1, weightScales2, bias1, bias2,69 op.Init(context, x, topkIds, topkWeights, weight1, weight2, weightScales1, weightScales2, bias1, bias2,
70- xActiveMask, scales, yOut, expertTokenNumsOut, workspaceGM, tilingGM);70+ xActiveMask, scales, maskBuffer, yOut, expertTokenNumsOut, workspaceGM, tilingGM);
71 op.Process();71 op.Process();
72 } else {72 } else {
73 GET_TILING_DATA_WITH_STRUCT(MegaMoeTilingDataNonQuant, tilingData, tilingGM);73 GET_TILING_DATA_WITH_STRUCT(MegaMoeTilingDataNonQuant, tilingData, tilingGM);
74 74 
75 MegaMoe<DTYPE_X, DTYPE_WEIGHT1, DTYPE_Y, TPL_IS_TRANSPOSE_W1, TPL_IS_TRANSPOSE_W2, isNz, false> op;75 MegaMoe<DTYPE_X, DTYPE_WEIGHT1, DTYPE_Y, TPL_IS_TRANSPOSE_W1, TPL_IS_TRANSPOSE_W2, isNz, false> op;
76 op.Init(context, x, topkIds, topkWeights, weight1, weight2, weightScales1, weightScales2, bias1, bias2,76 op.Init(context, x, topkIds, topkWeights, weight1, weight2, weightScales1, weightScales2, bias1, bias2,
77- xActiveMask, scales, yOut, expertTokenNumsOut, workspaceGM, tilingGM);77+ xActiveMask, scales, maskBuffer, yOut, expertTokenNumsOut, workspaceGM, tilingGM);
78 op.Process();78 op.Process();
79 }79 }
80 }80 }
@@ -89,8 +89,9 @@ public:
89 __aicore__ inline MegaMoe(){};89 __aicore__ inline MegaMoe(){};
90 __aicore__ inline void Init(GM_ADDR contextGM, GM_ADDR xGM, GM_ADDR topkIdsGM, GM_ADDR topkWeightsGM,90 __aicore__ inline void Init(GM_ADDR contextGM, GM_ADDR xGM, GM_ADDR topkIdsGM, GM_ADDR topkWeightsGM,
91 GM_ADDR weight1GM, GM_ADDR weight2GM, GM_ADDR weightScales1GM, GM_ADDR weightScales2GM,91 GM_ADDR weight1GM, GM_ADDR weight2GM, GM_ADDR weightScales1GM, GM_ADDR weightScales2GM,
92- GM_ADDR bias1GM, GM_ADDR bias2GM, GM_ADDR xActiveMaskGM, GM_ADDR scalesGM, GM_ADDR yGM,92+ GM_ADDR bias1GM, GM_ADDR bias2GM, GM_ADDR xActiveMaskGM, GM_ADDR scalesGM,
93- GM_ADDR expertTokenNumsGM, GM_ADDR workspaceGM, GM_ADDR tilingGM);93+ GM_ADDR maskBufferGM, GM_ADDR yGM, GM_ADDR expertTokenNumsGM, GM_ADDR workspaceGM,
94+ GM_ADDR tilingGM);
94 __aicore__ inline void Process();95 __aicore__ inline void Process();
95 96 
96private:97private:
@@ -106,6 +107,7 @@ private:
106 GM_ADDR bias2GM_;107 GM_ADDR bias2GM_;
107 GM_ADDR xActiveMaskGM_;108 GM_ADDR xActiveMaskGM_;
108 GM_ADDR scalesGM_;109 GM_ADDR scalesGM_;
110+ GM_ADDR maskBufferGM_;
109 GM_ADDR yGM_;111 GM_ADDR yGM_;
110 GM_ADDR gmExpertTokenNums_;112 GM_ADDR gmExpertTokenNums_;
111 GM_ADDR workspaceGM_;113 GM_ADDR workspaceGM_;
@@ -139,13 +141,13 @@ private:
139 uint64_t initRoutingQuantTilingKey;141 uint64_t initRoutingQuantTilingKey;
140};142};
141 143 
142- 
143template <MegaMoeClass>144template <MegaMoeClass>
144__aicore__ inline void MegaMoe<MegaMoeFunc>::Init(GM_ADDR contextGM, GM_ADDR xGM, GM_ADDR topkIdsGM,145__aicore__ inline void MegaMoe<MegaMoeFunc>::Init(GM_ADDR contextGM, GM_ADDR xGM, GM_ADDR topkIdsGM,
145 GM_ADDR topkWeightsGM, GM_ADDR weight1GM, GM_ADDR weight2GM,146 GM_ADDR topkWeightsGM, GM_ADDR weight1GM, GM_ADDR weight2GM,
146 GM_ADDR weightScales1GM, GM_ADDR weightScales2GM, GM_ADDR bias1GM,147 GM_ADDR weightScales1GM, GM_ADDR weightScales2GM, GM_ADDR bias1GM,
147- GM_ADDR bias2GM, GM_ADDR xActiveMaskGM, GM_ADDR scalesGM, GM_ADDR yGM,148+ GM_ADDR bias2GM, GM_ADDR xActiveMaskGM, GM_ADDR scalesGM,
148- GM_ADDR expertTokenNumsGM, GM_ADDR workspaceGM, GM_ADDR tilingGM)149+ GM_ADDR maskBufferGM, GM_ADDR yGM, GM_ADDR expertTokenNumsGM,
150+ GM_ADDR workspaceGM, GM_ADDR tilingGM)
149{151{
150 constexpr bool kRoutingIsQuant =152 constexpr bool kRoutingIsQuant =
151 std::is_same_v<BType_, AscendC::int4b_t> || std::is_same_v<BType_, int32_t> || std::is_same_v<BType_, int8_t>;153 std::is_same_v<BType_, AscendC::int4b_t> || std::is_same_v<BType_, int32_t> || std::is_same_v<BType_, int8_t>;
@@ -162,6 +164,7 @@ __aicore__ inline void MegaMoe<MegaMoeFunc>::Init(GM_ADDR contextGM, GM_ADDR xGM
162 bias2GM_ = bias2GM;164 bias2GM_ = bias2GM;
163 xActiveMaskGM_ = xActiveMaskGM;165 xActiveMaskGM_ = xActiveMaskGM;
164 scalesGM_ = scalesGM;166 scalesGM_ = scalesGM;
167+ maskBufferGM_ = maskBufferGM;
165 yGM_ = yGM;168 yGM_ = yGM;
166 gmExpertTokenNums_ = expertTokenNumsGM;169 gmExpertTokenNums_ = expertTokenNumsGM;
167 workspaceGM_ = workspaceGM;170 workspaceGM_ = workspaceGM;
@@ -371,7 +374,8 @@ __aicore__ inline void MegaMoe<MegaMoeFunc>::Process()
371 activationCode_,374 activationCode_,
372 activationParams1_,375 activationParams1_,
373 activationParams2_,376 activationParams2_,
374- tilingGM_};377+ tilingGM_,
378+ maskBufferGM_};
375 } else {379 } else {
376 params = typename MatmulKernel::Params{problemShape,380 params = typename MatmulKernel::Params{problemShape,
377 static_cast<uint32_t>(epWorldSize_),381 static_cast<uint32_t>(epWorldSize_),
@@ -413,7 +417,8 @@ __aicore__ inline void MegaMoe<MegaMoeFunc>::Process()
413 activationCode_,417 activationCode_,
414 activationParams1_,418 activationParams1_,
415 activationParams2_,419 activationParams2_,
416- tilingGM_};420+ tilingGM_,
421+ maskBufferGM_};
417 }422 }
418 423 
419 MatmulKernel kernel(params);424 MatmulKernel kernel(params);
@@ -158,6 +158,7 @@ public:
158 GM_ADDR contextGM{nullptr};158 GM_ADDR contextGM{nullptr};
159 // 算子tiling数据地址(GM),ADump启动时由0核dump到Tiling段159 // 算子tiling数据地址(GM),ADump启动时由0核dump到Tiling段
160 GM_ADDR tilingGM{nullptr};160 GM_ADDR tilingGM{nullptr};
161+ GM_ADDR ptrMaskBuffer{nullptr};
161 union {162 union {
162 MoeInitRoutingQuantV2TilingData moeInitRoutingQuantV2TilingData;163 MoeInitRoutingQuantV2TilingData moeInitRoutingQuantV2TilingData;
163 MoeInitRoutingV2TilingData moeInitRoutingV2TilingData;164 MoeInitRoutingV2TilingData moeInitRoutingV2TilingData;
@@ -166,9 +167,7 @@ public:
166 167 
167 // Methods168 // Methods
168 CATLASS_HOST_DEVICE169 CATLASS_HOST_DEVICE
169- Params()170+ Params() {}
170- {
171- }
172 171 
173 CATLASS_HOST_DEVICE172 CATLASS_HOST_DEVICE
174 Params(GemmCoord problemShape_, uint32_t EP_, uint32_t listLen_, uint32_t expertPerRank_,173 Params(GemmCoord problemShape_, uint32_t EP_, uint32_t listLen_, uint32_t expertPerRank_,
@@ -183,24 +182,49 @@ public:
183 MoeInitRoutingQuantV2TilingData moeInitRoutingQuantV2TilingData_, uint32_t epilogueGranularity_ = 0,182 MoeInitRoutingQuantV2TilingData moeInitRoutingQuantV2TilingData_, uint32_t epilogueGranularity_ = 0,
184 float swigluLimit_ = std::numeric_limits<float>::infinity(), uint32_t activationCode_ = 0,183 float swigluLimit_ = std::numeric_limits<float>::infinity(), uint32_t activationCode_ = 0,
185 float activationParams1_ = Epilogue::SwigluOaiActivation::DEFAULT_ALPHA,184 float activationParams1_ = Epilogue::SwigluOaiActivation::DEFAULT_ALPHA,
186- float activationParams2_ = Epilogue::SituActivation::DEFAULT_BETA, GM_ADDR tilingGM_ = nullptr)185+ float activationParams2_ = Epilogue::SituActivation::DEFAULT_BETA, GM_ADDR tilingGM_ = nullptr,
187- : problemShape(problemShape_), EP(EP_), listLen(listLen_), expertPerRank(expertPerRank_),186+ GM_ADDR ptrMaskBuffer_ = nullptr)
188- maxOutputSize(maxOutputSize_), topK(topK_), initRoutingQuantTilingKey(initRoutingQuantTilingKey_),187+ : problemShape(problemShape_),
189- epilogueCoreNum(epilogueCoreNum_), epilogueGranularity(epilogueGranularity_), swigluLimit(swigluLimit_),188+ EP(EP_),
190- activationCode(activationCode_), activationParams1(activationParams1_),189+ listLen(listLen_),
190+ expertPerRank(expertPerRank_),
191+ maxOutputSize(maxOutputSize_),
192+ topK(topK_),
193+ initRoutingQuantTilingKey(initRoutingQuantTilingKey_),
194+ epilogueCoreNum(epilogueCoreNum_),
195+ epilogueGranularity(epilogueGranularity_),
196+ swigluLimit(swigluLimit_),
197+ activationCode(activationCode_),
198+ activationParams1(activationParams1_),
191 activationParams2(activationParams2_),199 activationParams2(activationParams2_),
192- contextGM(contextGM_), tilingGM(tilingGM_), ptrA(reinterpret_cast<__gm__ ElementABefore *>(ptrA_)),200+ contextGM(contextGM_),
193- layoutA(layoutA_), layoutA2(layoutA2_), ptrB1(reinterpret_cast<__gm__ ElementB *>(ptrB1_)),201+ tilingGM(tilingGM_),
194- layoutB1(layoutB1_), ptrBias1(reinterpret_cast<__gm__ float *>(ptrBias1_)),202+ ptrMaskBuffer(ptrMaskBuffer_),
195- ptrB2(reinterpret_cast<__gm__ ElementB *>(ptrB2_)), layoutB2(layoutB2_),203+ ptrA(reinterpret_cast<__gm__ ElementABefore *>(ptrA_)),
204+ layoutA(layoutA_),
205+ layoutA2(layoutA2_),
206+ ptrB1(reinterpret_cast<__gm__ ElementB *>(ptrB1_)),
207+ layoutB1(layoutB1_),
208+ ptrBias1(reinterpret_cast<__gm__ float *>(ptrBias1_)),
209+ ptrB2(reinterpret_cast<__gm__ ElementB *>(ptrB2_)),
210+ layoutB2(layoutB2_),
196 ptrBias2(reinterpret_cast<__gm__ float *>(ptrBias2_)),211 ptrBias2(reinterpret_cast<__gm__ float *>(ptrBias2_)),
197- ptrScale1(reinterpret_cast<__gm__ ElementScale *>(ptrScale1_)), layoutScale1(layoutScale1_),212+ ptrScale1(reinterpret_cast<__gm__ ElementScale *>(ptrScale1_)),
198- ptrScale2(reinterpret_cast<__gm__ ElementScale *>(ptrScale2_)), layoutScale2(layoutScale2_),213+ layoutScale1(layoutScale1_),
199- ptrOutput(reinterpret_cast<__gm__ ElementD2 *>(ptrOutput_)), layoutD1(layoutD1_), layoutD2(layoutD2_),214+ ptrScale2(reinterpret_cast<__gm__ ElementScale *>(ptrScale2_)),
200- expertIdx(expertIdx_), moeInitRoutingQuantV2Scale(moeInitRoutingQuantV2Scale_),215+ layoutScale2(layoutScale2_),
216+ ptrOutput(reinterpret_cast<__gm__ ElementD2 *>(ptrOutput_)),
217+ layoutD1(layoutD1_),
218+ layoutD2(layoutD2_),
219+ expertIdx(expertIdx_),
220+ moeInitRoutingQuantV2Scale(moeInitRoutingQuantV2Scale_),
201 moeInitRoutingQuantV2Offset(moeInitRoutingQuantV2Offset_),221 moeInitRoutingQuantV2Offset(moeInitRoutingQuantV2Offset_),
202- expertTokensBeforeCapacity(expertTokensBeforeCapacity_), probs(probs_), ptrXActiveMask(ptrXActiveMask_),222+ expertTokensBeforeCapacity(expertTokensBeforeCapacity_),
203- ptrScales(ptrScales_), ptrWorkspace(ptrWorkspace_), ptrExpertTokenNums(gmExpertTokenNums_),223+ probs(probs_),
224+ ptrXActiveMask(ptrXActiveMask_),
225+ ptrScales(ptrScales_),
226+ ptrWorkspace(ptrWorkspace_),
227+ ptrExpertTokenNums(gmExpertTokenNums_),
204 moeInitRoutingQuantV2TilingData(moeInitRoutingQuantV2TilingData_)228 moeInitRoutingQuantV2TilingData(moeInitRoutingQuantV2TilingData_)
205 {229 {
206 moeInitRoutingQuantV2TilingData.vbsComputeParamsOp = moeInitRoutingQuantV2TilingData_.vbsComputeParamsOp;230 moeInitRoutingQuantV2TilingData.vbsComputeParamsOp = moeInitRoutingQuantV2TilingData_.vbsComputeParamsOp;
@@ -230,26 +254,50 @@ public:
230 GM_ADDR expertTokensBeforeCapacity_, GM_ADDR probs_, GM_ADDR ptrWorkspace_, GM_ADDR gmExpertTokenNums_,254 GM_ADDR expertTokensBeforeCapacity_, GM_ADDR probs_, GM_ADDR ptrWorkspace_, GM_ADDR gmExpertTokenNums_,
231 GM_ADDR ptrXActiveMask_, GM_ADDR ptrScales_, MoeInitRoutingV2TilingData moeInitRoutingV2TilingData_,255 GM_ADDR ptrXActiveMask_, GM_ADDR ptrScales_, MoeInitRoutingV2TilingData moeInitRoutingV2TilingData_,
232 uint32_t epilogueGranularity_ = 0, float swigluLimit_ = std::numeric_limits<float>::infinity(),256 uint32_t epilogueGranularity_ = 0, float swigluLimit_ = std::numeric_limits<float>::infinity(),
233- uint32_t activationCode_ = 0,257+ uint32_t activationCode_ = 0, float activationParams1_ = Epilogue::SwigluOaiActivation::DEFAULT_ALPHA,
234- float activationParams1_ = Epilogue::SwigluOaiActivation::DEFAULT_ALPHA,258+ float activationParams2_ = Epilogue::SituActivation::DEFAULT_BETA, GM_ADDR tilingGM_ = nullptr,
235- float activationParams2_ = Epilogue::SituActivation::DEFAULT_BETA, GM_ADDR tilingGM_ = nullptr)259+ GM_ADDR ptrMaskBuffer_ = nullptr)
236- : problemShape(problemShape_), EP(EP_), listLen(listLen_), expertPerRank(expertPerRank_),260+ : problemShape(problemShape_),
237- maxOutputSize(maxOutputSize_), topK(topK_), initRoutingQuantTilingKey(initRoutingQuantTilingKey_),261+ EP(EP_),
238- epilogueCoreNum(epilogueCoreNum_), epilogueGranularity(epilogueGranularity_), swigluLimit(swigluLimit_),262+ listLen(listLen_),
239- activationCode(activationCode_), activationParams1(activationParams1_),263+ expertPerRank(expertPerRank_),
264+ maxOutputSize(maxOutputSize_),
265+ topK(topK_),
266+ initRoutingQuantTilingKey(initRoutingQuantTilingKey_),
267+ epilogueCoreNum(epilogueCoreNum_),
268+ epilogueGranularity(epilogueGranularity_),
269+ swigluLimit(swigluLimit_),
270+ activationCode(activationCode_),
271+ activationParams1(activationParams1_),
240 activationParams2(activationParams2_),272 activationParams2(activationParams2_),
241- contextGM(contextGM_), tilingGM(tilingGM_), ptrA(reinterpret_cast<__gm__ ElementABefore *>(ptrA_)),273+ contextGM(contextGM_),
242- layoutA(layoutA_), layoutA2(layoutA2_), ptrB1(reinterpret_cast<__gm__ ElementB *>(ptrB1_)),274+ tilingGM(tilingGM_),
243- layoutB1(layoutB1_), ptrBias1(reinterpret_cast<__gm__ float *>(ptrBias1_)),275+ ptrMaskBuffer(ptrMaskBuffer_),
244- ptrB2(reinterpret_cast<__gm__ ElementB *>(ptrB2_)), layoutB2(layoutB2_),276+ ptrA(reinterpret_cast<__gm__ ElementABefore *>(ptrA_)),
277+ layoutA(layoutA_),
278+ layoutA2(layoutA2_),
279+ ptrB1(reinterpret_cast<__gm__ ElementB *>(ptrB1_)),
280+ layoutB1(layoutB1_),
281+ ptrBias1(reinterpret_cast<__gm__ float *>(ptrBias1_)),
282+ ptrB2(reinterpret_cast<__gm__ ElementB *>(ptrB2_)),
283+ layoutB2(layoutB2_),
245 ptrBias2(reinterpret_cast<__gm__ float *>(ptrBias2_)),284 ptrBias2(reinterpret_cast<__gm__ float *>(ptrBias2_)),
246- ptrScale1(reinterpret_cast<__gm__ ElementScale *>(ptrScale1_)), layoutScale1(layoutScale1_),285+ ptrScale1(reinterpret_cast<__gm__ ElementScale *>(ptrScale1_)),
247- ptrScale2(reinterpret_cast<__gm__ ElementScale *>(ptrScale2_)), layoutScale2(layoutScale2_),286+ layoutScale1(layoutScale1_),
248- ptrOutput(reinterpret_cast<__gm__ ElementD2 *>(ptrOutput_)), layoutD1(layoutD1_), layoutD2(layoutD2_),287+ ptrScale2(reinterpret_cast<__gm__ ElementScale *>(ptrScale2_)),
249- expertIdx(expertIdx_), moeInitRoutingQuantV2Scale(moeInitRoutingQuantV2Scale_),288+ layoutScale2(layoutScale2_),
289+ ptrOutput(reinterpret_cast<__gm__ ElementD2 *>(ptrOutput_)),
290+ layoutD1(layoutD1_),
291+ layoutD2(layoutD2_),
292+ expertIdx(expertIdx_),
293+ moeInitRoutingQuantV2Scale(moeInitRoutingQuantV2Scale_),
250 moeInitRoutingQuantV2Offset(moeInitRoutingQuantV2Offset_),294 moeInitRoutingQuantV2Offset(moeInitRoutingQuantV2Offset_),
251- expertTokensBeforeCapacity(expertTokensBeforeCapacity_), probs(probs_), ptrXActiveMask(ptrXActiveMask_),295+ expertTokensBeforeCapacity(expertTokensBeforeCapacity_),
252- ptrScales(ptrScales_), ptrWorkspace(ptrWorkspace_), ptrExpertTokenNums(gmExpertTokenNums_),296+ probs(probs_),
297+ ptrXActiveMask(ptrXActiveMask_),
298+ ptrScales(ptrScales_),
299+ ptrWorkspace(ptrWorkspace_),
300+ ptrExpertTokenNums(gmExpertTokenNums_),
253 moeInitRoutingV2TilingData(moeInitRoutingV2TilingData_)301 moeInitRoutingV2TilingData(moeInitRoutingV2TilingData_)
254 {302 {
255 gmmOutPreRowStride = problemShape.n() > problemShape.k() ? problemShape.n() : problemShape.k();303 gmmOutPreRowStride = problemShape.n() > problemShape.k() ? problemShape.n() : problemShape.k();
@@ -276,9 +324,7 @@ public:
276 }324 }
277 325 
278 CATLASS_DEVICE326 CATLASS_DEVICE
279- ~MegaMoeKernel()327+ ~MegaMoeKernel() {}
280- {
281- }
282 328 
283 template <int32_t CORE_TYPE = g_coreType>329 template <int32_t CORE_TYPE = g_coreType>
284 CATLASS_DEVICE void operator()(Params const &params);330 CATLASS_DEVICE void operator()(Params const &params);
@@ -286,6 +332,9 @@ public:
286 template <>332 template <>
287 CATLASS_DEVICE void operator()<AscendC::AIC>(Params const &params)333 CATLASS_DEVICE void operator()<AscendC::AIC>(Params const &params)
288 {334 {
335+ if (IsRankMasked(RuntimeRank(params))) {
336+ return;
337+ }
289 if constexpr (!std::is_same_v<ElementB, AscendC::int4b_t>) {338 if constexpr (!std::is_same_v<ElementB, AscendC::int4b_t>) {
290 GMM1(params);339 GMM1(params);
291 AscendC::CrossCoreWaitFlag<0x2>(SYNCFLAGV2C);340 AscendC::CrossCoreWaitFlag<0x2>(SYNCFLAGV2C);
@@ -299,6 +348,9 @@ public:
299 template <>348 template <>
300 CATLASS_DEVICE void operator()<AscendC::AIV>(Params const &params)349 CATLASS_DEVICE void operator()<AscendC::AIV>(Params const &params)
301 {350 {
351+ if (IsRankMasked(RuntimeRank(params))) {
352+ return;
353+ }
302 DispatchAndCombine(params);354 DispatchAndCombine(params);
303 }355 }
304 356 
@@ -350,6 +402,14 @@ private:
350 tokenPerExpertLayout = Layout3D(paddedExpertNumAligned, params.expertPerRank);402 tokenPerExpertLayout = Layout3D(paddedExpertNumAligned, params.expertPerRank);
351 preSumBeforeRank.SetGlobalBuffer(reinterpret_cast<__gm__ int32_t *>(workspaceInfo.ptrSumBeforeRank));403 preSumBeforeRank.SetGlobalBuffer(reinterpret_cast<__gm__ int32_t *>(workspaceInfo.ptrSumBeforeRank));
352 gmXActiveMask.SetGlobalBuffer(reinterpret_cast<__gm__ bool *>(params.ptrXActiveMask));404 gmXActiveMask.SetGlobalBuffer(reinterpret_cast<__gm__ bool *>(params.ptrXActiveMask));
405+ maskBufferAddr = params.ptrMaskBuffer;
406+ if (maskBufferAddr != nullptr) {
407+ uint32_t rankMaskBytes = AlignUp(params.EP * sizeof(int32_t), BYTE_PER_BLK);
408+ uint32_t rankMaskUbOffset = ArchTag::UB_SIZE - rankMaskBytes;
409+ rankMaskLocal = resource.ubBuf.template GetBufferByByte<int32_t>(rankMaskUbOffset);
410+ rankMaskLocal.SetSize(rankMaskBytes / sizeof(int32_t));
411+ CopyRankMaskToLocal(params);
412+ }
353 413 
354 isCombineV1 = false;414 isCombineV1 = false;
355 if constexpr (std::is_same_v<ElementB, int8_t>) {415 if constexpr (std::is_same_v<ElementB, int8_t>) {
@@ -360,6 +420,29 @@ private:
360 }420 }
361 }421 }
362 422 
423+ CATLASS_DEVICE
424+ void CopyRankMaskToLocal(Params const &params)
425+ {
426+ if (maskBufferAddr == nullptr) {
427+ return;
428+ }
429+ AscendC::GlobalTensor<int32_t> rankMaskGm;
430+ rankMaskGm.SetGlobalBuffer(reinterpret_cast<__gm__ int32_t *>(maskBufferAddr));
431+ AscendC::DataCopyPad(rankMaskLocal, rankMaskGm, {1, static_cast<uint16_t>(params.EP * sizeof(int32_t)), 0, 0},
432+ {});
433+ AscendC::SetFlag<AscendC::HardEvent::MTE2_S>(EVENT_ID0);
434+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_S>(EVENT_ID0);
435+ }
436+ 
437+ CATLASS_DEVICE
438+ bool IsRankMasked(int32_t rank)
439+ {
440+ if (maskBufferAddr == nullptr) {
441+ return false;
442+ }
443+ return rankMaskLocal.GetValue(rank) != 0;
444+ }
445+ 
363 template <typename T>446 template <typename T>
364 CATLASS_DEVICE void CopyGMToGM(AscendC::GlobalTensor<T> dst, AscendC::GlobalTensor<T> src, int32_t elemNum,447 CATLASS_DEVICE void CopyGMToGM(AscendC::GlobalTensor<T> dst, AscendC::GlobalTensor<T> src, int32_t elemNum,
365 int32_t ubMoveNum)448 int32_t ubMoveNum)
@@ -917,7 +1000,7 @@ private:
917 1000 
918 int32_t runtimeRank = RuntimeRank(params);1001 int32_t runtimeRank = RuntimeRank(params);
919 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {1002 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {
920- if (dstEpIdx == runtimeRank) {1003+ if (dstEpIdx == runtimeRank || IsRankMasked(dstEpIdx)) {
921 continue;1004 continue;
922 }1005 }
923 AscendC::GlobalTensor<int32_t> srcAddress;1006 AscendC::GlobalTensor<int32_t> srcAddress;
@@ -947,18 +1030,27 @@ private:
947 AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0);1030 AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0);
948 }1031 }
949 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {1032 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {
1033+ bool rankAvailable = !IsRankMasked(dstEpIdx);
950 if (dstEpIdx != runtimeRank) {1034 if (dstEpIdx != runtimeRank) {
951 int32_t intPer512 = CACHE_LINE / sizeof(int);1035 int32_t intPer512 = CACHE_LINE / sizeof(int);
952 for (int32_t checkIdx = 0; checkIdx < paddedExpertNumAligned; checkIdx += intPer512) {1036 for (int32_t checkIdx = 0; checkIdx < paddedExpertNumAligned; checkIdx += intPer512) {
953 __gm__ int32_t *sync_check =1037 __gm__ int32_t *sync_check =
954 reinterpret_cast<__gm__ int32_t *>(shmem() + peermemInfo.offsetPeerTokenPerExpert) +1038 reinterpret_cast<__gm__ int32_t *>(shmem() + peermemInfo.offsetPeerTokenPerExpert) +
955 tokenPerExpertLayout(dstEpIdx, 0, checkIdx);1039 tokenPerExpertLayout(dstEpIdx, 0, checkIdx);
1040+ if (!rankAvailable) {
1041+ break;
1042+ }
956 gm_signal_wait_until_ne(sync_check, 0);1043 gm_signal_wait_until_ne(sync_check, 0);
957 }1044 }
958- AscendC::DataCopy(tmpBuffer, tokenPerExpert[tokenPerExpertLayout(dstEpIdx, 0, 0)], numPerCore);1045+ if (rankAvailable) {
959- AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);1046+ AscendC::DataCopy(tmpBuffer, tokenPerExpert[tokenPerExpertLayout(dstEpIdx, 0, 0)], numPerCore);
960- AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);1047+ AscendC::SetFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
961- AscendC::Adds(tmpBuffer, tmpBuffer, -0x800000, numPerCore);1048+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_V>(EVENT_ID0);
1049+ AscendC::Adds(tmpBuffer, tmpBuffer, -0x800000, numPerCore);
1050+ } else {
1051+ AscendC::Duplicate(tmpBuffer, 0, numPerCore);
1052+ }
1053+ 
962 AscendC::PipeBarrier<PIPE_V>();1054 AscendC::PipeBarrier<PIPE_V>();
963 AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);1055 AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
964 AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);1056 AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
@@ -1140,6 +1232,7 @@ private:
1140 }1232 }
1141 1233 
1142 AscendC::SyncAll<true>();1234 AscendC::SyncAll<true>();
1235+ CopyRankMaskToLocal(params);
1143 1236 
1144 exceptionDump_.UpdateStage(MC2MegaMoeAdump::Stage::ALLGATHER_TOKEN_PER_EXPERT);1237 exceptionDump_.UpdateStage(MC2MegaMoeAdump::Stage::ALLGATHER_TOKEN_PER_EXPERT);
1145 CrossRankSyncAndlocalTokenPerExpertAllGatherAndGetSumPreRankV2(params, localTokenPerExpertOffset);1238 CrossRankSyncAndlocalTokenPerExpertAllGatherAndGetSumPreRankV2(params, localTokenPerExpertOffset);
@@ -1182,6 +1275,9 @@ private:
1182 // ----------------------------------------------------------1275 // ----------------------------------------------------------
1183 uint32_t currentM = cumsumMM((params.EP - 1) * params.expertPerRank + groupIdx);1276 uint32_t currentM = cumsumMM((params.EP - 1) * params.expertPerRank + groupIdx);
1184 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {1277 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {
1278+ if (IsRankMasked(dstEpIdx)) {
1279+ continue;
1280+ }
1185 uint32_t rowStartInGroup =1281 uint32_t rowStartInGroup =
1186 dstEpIdx == 0 ? 0 : cumsumMM((dstEpIdx - 1) * params.expertPerRank + groupIdx);1282 dstEpIdx == 0 ? 0 : cumsumMM((dstEpIdx - 1) * params.expertPerRank + groupIdx);
1187 uint32_t rowStart = rowStartInGroup + prevGroupSum1;1283 uint32_t rowStart = rowStartInGroup + prevGroupSum1;
@@ -1301,8 +1397,7 @@ private:
1301 rowStartThisCore, gmPerTokenScale2[rowStartThisCore], params.expertPerRank,1397 rowStartThisCore, gmPerTokenScale2[rowStartThisCore], params.expertPerRank,
1302 params.EP, runtimeRank, params.listLen, resource, params.epilogueCoreNum,1398 params.EP, runtimeRank, params.listLen, resource, params.epilogueCoreNum,
1303 params.swigluLimit, params.activationCode, params.activationParams1,1399 params.swigluLimit, params.activationCode, params.activationParams1,
1304- params.activationParams2,1400+ params.activationParams2, params.gmmOutPreRowStride);
1305- params.gmmOutPreRowStride);
1306 }1401 }
1307 AscendC::SyncAll<true>();1402 AscendC::SyncAll<true>();
1308 AscendC::CrossCoreSetFlag<0x2, PIPE_MTE3>(SYNCFLAGV2C);1403 AscendC::CrossCoreSetFlag<0x2, PIPE_MTE3>(SYNCFLAGV2C);
@@ -1326,8 +1421,7 @@ private:
1326 } else {1421 } else {
1327 blockEpilogue1(gmC[gmOffsetC], shapeC, gmPermutedToken[gmOffsetD], resource, params.epilogueCoreNum,1422 blockEpilogue1(gmC[gmOffsetC], shapeC, gmPermutedToken[gmOffsetD], resource, params.epilogueCoreNum,
1328 params.swigluLimit, params.activationCode, params.activationParams1,1423 params.swigluLimit, params.activationCode, params.activationParams1,
1329- params.activationParams2,1424+ params.activationParams2, params.gmmOutPreRowStride);
1330- params.gmmOutPreRowStride);
1331 }1425 }
1332 }1426 }
1333 AscendC::SyncAll<true>();1427 AscendC::SyncAll<true>();
@@ -1353,8 +1447,7 @@ private:
1353 } else {1447 } else {
1354 blockEpilogue1(gmC[gmOffsetC], shapeC, gmPermutedToken[gmOffsetD], resource, coreNum,1448 blockEpilogue1(gmC[gmOffsetC], shapeC, gmPermutedToken[gmOffsetD], resource, coreNum,
1355 params.swigluLimit, params.activationCode, params.activationParams1,1449 params.swigluLimit, params.activationCode, params.activationParams1,
1356- params.activationParams2,1450+ params.activationParams2, params.gmmOutPreRowStride);
1357- params.gmmOutPreRowStride);
1358 }1451 }
1359 }1452 }
1360 AscendC::SyncAll<true>();1453 AscendC::SyncAll<true>();
@@ -1383,7 +1476,11 @@ private:
1383 shmem.InitStatusTargetSum();1476 shmem.InitStatusTargetSum();
1384 if (get_subblockid() == 0) {1477 if (get_subblockid() == 0) {
1385 AscendC::LocalTensor<int32_t> ctrBuffer = resource.ubBuf.template GetBufferByByte<int32_t>(0);1478 AscendC::LocalTensor<int32_t> ctrBuffer = resource.ubBuf.template GetBufferByByte<int32_t>(0);
1386- shmem.CrossRankSyncV2Set(ctrBuffer);1479+ if (maskBufferAddr == nullptr) {
1480+ shmem.CrossRankSyncV2Set(ctrBuffer);
1481+ } else {
1482+ shmem.CrossRankSyncV2SetWithMask(ctrBuffer, rankMaskLocal);
1483+ }
1387 } else {1484 } else {
1388 uint32_t uboffset = 0;1485 uint32_t uboffset = 0;
1389 uint32_t aicCoreNum = coreNum / 2;1486 uint32_t aicCoreNum = coreNum / 2;
@@ -1404,7 +1501,11 @@ private:
1404 AscendC::LocalTensor<float> statusSumOutTensor =1501 AscendC::LocalTensor<float> statusSumOutTensor =
1405 resource.ubBuf.template GetBufferByByte<float>(uboffset);1502 resource.ubBuf.template GetBufferByByte<float>(uboffset);
1406 uboffset += AlignUp(sizeof(float), 32);1503 uboffset += AlignUp(sizeof(float), 32);
1407- shmem.CrossRankSyncV2Wait(statusTensor, gatherMaskOutTensor, gatherTmpTensor, statusSumOutTensor);1504+ if (maskBufferAddr == nullptr) {
1505+ shmem.CrossRankSyncV2Wait(statusTensor, gatherMaskOutTensor, gatherTmpTensor, statusSumOutTensor);
1506+ } else {
1507+ shmem.CrossRankSyncV2WaitWithMask(rankMaskLocal);
1508+ }
1408 1509 
1409 exceptionDump_.UpdateStage(MC2MegaMoeAdump::Stage::UNPERMUTE);1510 exceptionDump_.UpdateStage(MC2MegaMoeAdump::Stage::UNPERMUTE);
1410 MoeTokenUnpermuteTilingData tilingData;1511 MoeTokenUnpermuteTilingData tilingData;
@@ -1416,7 +1517,11 @@ private:
1416 kernelMoeTokenUnpermuteOp.Process();1517 kernelMoeTokenUnpermuteOp.Process();
1417 }1518 }
1418 } else {1519 } else {
1419- shmem.CrossRankSync();1520+ if (maskBufferAddr == nullptr) {
1521+ shmem.CrossRankSync();
1522+ } else {
1523+ shmem.CrossRankSyncWithMask(rankMaskLocal);
1524+ }
1420 1525 
1421 exceptionDump_.UpdateStage(MC2MegaMoeAdump::Stage::UNPERMUTE);1526 exceptionDump_.UpdateStage(MC2MegaMoeAdump::Stage::UNPERMUTE);
1422 MoeTokenUnpermuteTilingData tilingData;1527 MoeTokenUnpermuteTilingData tilingData;
@@ -1445,6 +1550,9 @@ private:
1445 uint32_t groupIdx = t_groupIdx;1550 uint32_t groupIdx = t_groupIdx;
1446 1551 
1447 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {1552 for (int32_t dstEpIdx = coreIdx; dstEpIdx < params.EP; dstEpIdx += coreNum) {
1553+ if (IsRankMasked(dstEpIdx)) {
1554+ continue;
1555+ }
1448 __gm__ void *dstPeermemPtr = shmem(peermemInfo.offsetD, dstEpIdx);1556 __gm__ void *dstPeermemPtr = shmem(peermemInfo.offsetD, dstEpIdx);
1449 AscendC::GlobalTensor<ElementD2> gmRemotePeer;1557 AscendC::GlobalTensor<ElementD2> gmRemotePeer;
1450 gmRemotePeer.SetGlobalBuffer(reinterpret_cast<__gm__ ElementD2 *>(dstPeermemPtr));1558 gmRemotePeer.SetGlobalBuffer(reinterpret_cast<__gm__ ElementD2 *>(dstPeermemPtr));
@@ -1589,9 +1697,7 @@ private:
1589 __gm__ float *ptrSoftFlagBase;1697 __gm__ float *ptrSoftFlagBase;
1590 1698 
1591 CATLASS_DEVICE1699 CATLASS_DEVICE
1592- WorkspaceInfo()1700+ WorkspaceInfo() {}
1593- {
1594- }
1595 1701 
1596 CATLASS_DEVICE1702 CATLASS_DEVICE
1597 WorkspaceInfo(const Params &params)1703 WorkspaceInfo(const Params &params)
@@ -1654,9 +1760,7 @@ private:
1654 int64_t offsetD;1760 int64_t offsetD;
1655 1761 
1656 CATLASS_DEVICE1762 CATLASS_DEVICE
1657- PeermemInfo()1763+ PeermemInfo() {}
1658- {
1659- }
1660 1764 
1661 CATLASS_DEVICE1765 CATLASS_DEVICE
1662 PeermemInfo(const Params &params, const HcclShmem<false> &shmem)1766 PeermemInfo(const Params &params, const HcclShmem<false> &shmem)
@@ -1675,8 +1779,8 @@ private:
1675 1779 
1676 // 尾部:CrossRankSync + tokenPerExpert1780 // 尾部:CrossRankSync + tokenPerExpert
1677 int64_t tailSyncSize = static_cast<int64_t>(shmem.TailReservedSize());1781 int64_t tailSyncSize = static_cast<int64_t>(shmem.TailReservedSize());
1678- int64_t tokenPerExpertSize = EP * AlignUp(EP * MAX_EXPERTS_PER_RANK + 1, ALIGN_128) *1782+ int64_t tokenPerExpertSize =
1679- static_cast<int64_t>(sizeof(int32_t));1783+ EP * AlignUp(EP * MAX_EXPERTS_PER_RANK + 1, ALIGN_128) * static_cast<int64_t>(sizeof(int32_t));
1680 1784 
1681 // A: dispatch 数据区(量化时含行内 scale)1785 // A: dispatch 数据区(量化时含行内 scale)
1682 int64_t offsetASize = bs * topK * (RoutingIsQuant ? (h + ALIGN_512) : h * sizeof(int16_t));1786 int64_t offsetASize = bs * topK * (RoutingIsQuant ? (h + ALIGN_512) : h * sizeof(int16_t));
@@ -1727,6 +1831,8 @@ private:
1727 HcclShmem<false> shmem;1831 HcclShmem<false> shmem;
1728 int32_t paddedExpertNumAligned;1832 int32_t paddedExpertNumAligned;
1729 bool isCombineV1;1833 bool isCombineV1;
1834+ GM_ADDR maskBufferAddr{nullptr};
1835+ AscendC::LocalTensor<int32_t> rankMaskLocal;
1730 // ExceptionDump引擎:记录执行阶段时间戳,并提供Dump接口由host侧dump指定GM地址内容。1836 // ExceptionDump引擎:记录执行阶段时间戳,并提供Dump接口由host侧dump指定GM地址内容。
1731 // 基址取通信域首地址(shmem()()),根据kRoutingIsQuant选择对应tiling结构体的Policy,1837 // 基址取通信域首地址(shmem()()),根据kRoutingIsQuant选择对应tiling结构体的Policy,
1732 // ArchTag传入Policy供架构差异扩展。1838 // ArchTag传入Policy供架构差异扩展。
@@ -21,7 +21,6 @@
21#ifndef HCCL_SHMEM_HPP21#ifndef HCCL_SHMEM_HPP
22#define HCCL_SHMEM_HPP22#define HCCL_SHMEM_HPP
23 23 
24- 
25#include "kernel_operator.h"24#include "kernel_operator.h"
26#include "const_args.hpp"25#include "const_args.hpp"
27#include "mc2_moe_context.h"26#include "mc2_moe_context.h"
@@ -198,9 +197,7 @@ public:
198 std::conditional_t<IS_A2, __gm__ HcclA2CombineOpParam *, __gm__ HcclOpResParam *> WinContext_{nullptr};197 std::conditional_t<IS_A2, __gm__ HcclA2CombineOpParam *, __gm__ HcclOpResParam *> WinContext_{nullptr};
199 AscendC::LocalTensor<int32_t> ub;198 AscendC::LocalTensor<int32_t> ub;
200 FORCE_INLINE_AICORE199 FORCE_INLINE_AICORE
201- HcclShmem()200+ HcclShmem() {}
202- {
203- }
204 FORCE_INLINE_AICORE201 FORCE_INLINE_AICORE
205 void initShmem(__gm__ Mc2Aclnn::Mc2MoeContext *mc2Context)202 void initShmem(__gm__ Mc2Aclnn::Mc2MoeContext *mc2Context)
206 {203 {
@@ -370,9 +367,7 @@ public:
370 }367 }
371 368 
372 FORCE_INLINE_AICORE369 FORCE_INLINE_AICORE
373- ~HcclShmem()370+ ~HcclShmem() {}
374- {
375- }
376 371 
377 FORCE_INLINE_AICORE372 FORCE_INLINE_AICORE
378 void CrossRankSync()373 void CrossRankSync()
@@ -395,6 +390,35 @@ public:
395 gm_store(sync_base, count);390 gm_store(sync_base, count);
396 }391 }
397 392 
393+ FORCE_INLINE_AICORE
394+ void CrossRankSyncWithMask(AscendC::LocalTensor<int32_t> rankMask)
395+ {
396+ uint64_t flag_offset = (m_segmentSize - m_tailReservedSize) / sizeof(int64_t);
397+ __gm__ int64_t *sync_counter = (__gm__ int64_t *)(*this)() + flag_offset;
398+ __gm__ int64_t *sync_base = (__gm__ int64_t *)(*this)() + flag_offset + m_rankSize * 8;
399+ int64_t count = gm_load(sync_base) + 1;
400+ int vec_id = AscendC::GetBlockIdx();
401+ int vec_size = AscendC::GetBlockNum() * AscendC::GetTaskRation();
402+ // 完成所有发送,再进入等待,不要因为一个rank没有等待到阻塞后续发送
403+ for (int i = vec_id; i < m_rankSize; i += vec_size) {
404+ if (rankMask.GetValue(i) != 0) { // masked rank不再等待
405+ continue;
406+ }
407+ __gm__ int64_t *sync_remote = (__gm__ int64_t *)((*this)(i)) + flag_offset + m_rank * 8;
408+ gm_store(sync_remote, count);
409+ gm_dcci((__gm__ uint8_t *)sync_remote);
410+ }
411+ for (int i = vec_id; i < m_rankSize; i += vec_size) {
412+ if (rankMask.GetValue(i) != 0) { // masked rank不再等待
413+ continue;
414+ }
415+ auto sync_check = sync_counter + i * 8;
416+ gm_signal_wait_until_eq_for_barrier(sync_check, count);
417+ }
418+ AscendC::SyncAll<true>();
419+ gm_store(sync_base, count);
420+ }
421+ 
398 // Cross-server-capable overload of CrossRankSync.422 // Cross-server-capable overload of CrossRankSync.
399 // Same counter-based barrier protocol as the no-arg version, but routes the423 // Same counter-based barrier protocol as the no-arg version, but routes the
400 // remote write through RDMA when the destination rank lives on another server.424 // remote write through RDMA when the destination rank lives on another server.
@@ -558,6 +582,30 @@ public:
558 AscendC::CrossCoreWaitFlag(RECV_SYNC_EVENT_ID);582 AscendC::CrossCoreWaitFlag(RECV_SYNC_EVENT_ID);
559 }583 }
560 584 
585+ FORCE_INLINE_AICORE
586+ void CrossRankSyncV2SetWithMask(AscendC::LocalTensor<int32_t> ctrBuffer, AscendC::LocalTensor<int32_t> rankMask)
587+ {
588+ uint64_t flag_offset = (m_segmentSize - m_tailReservedSize) + m_rank * STATE_OFFSET;
589+ int vec_size = get_block_num();
590+ int vec_id = get_block_idx();
591+ AscendC::CrossCoreSetFlag<0x0, PIPE_MTE3>(RECV_SYNC_EVENT_ID);
592+ AscendC::CrossCoreSetFlag<0x0, PIPE_MTE3>(SEND_SYNC_EVENT_ID);
593+ AscendC::CrossCoreWaitFlag(SEND_SYNC_EVENT_ID);
594+ pipe_barrier(PIPE_ALL);
595+ ctrBuffer.SetValue(0, epStateValue_);
596+ AscendC::SetFlag<AscendC::HardEvent::S_MTE3>(EVENT_ID0);
597+ AscendC::WaitFlag<AscendC::HardEvent::S_MTE3>(EVENT_ID0);
598+ for (uint32_t dstEpIdx = vec_id; dstEpIdx < m_rankSize; dstEpIdx += vec_size) {
599+ if (rankMask.GetValue(dstEpIdx) != 0) {
600+ continue;
601+ }
602+ AscendC::GlobalTensor<int32_t> gmDstStates;
603+ gmDstStates.SetGlobalBuffer((__gm__ int32_t *)((*this)(flag_offset, dstEpIdx)));
604+ AscendC::DataCopy(gmDstStates, ctrBuffer, 8);
605+ }
606+ AscendC::CrossCoreWaitFlag(RECV_SYNC_EVENT_ID);
607+ }
608+ 
561 FORCE_INLINE_AICORE609 FORCE_INLINE_AICORE
562 void CrossRankSyncV2Wait(AscendC::LocalTensor<float> statusTensor, AscendC::LocalTensor<float> gatherMaskOutTensor,610 void CrossRankSyncV2Wait(AscendC::LocalTensor<float> statusTensor, AscendC::LocalTensor<float> gatherMaskOutTensor,
563 AscendC::LocalTensor<uint32_t> gatherTmpTensor,611 AscendC::LocalTensor<uint32_t> gatherTmpTensor,
@@ -622,6 +670,27 @@ public:
622 AscendC::CrossCoreWaitFlag(SEND_SYNC_EVENT_ID);670 AscendC::CrossCoreWaitFlag(SEND_SYNC_EVENT_ID);
623 }671 }
624 672 
673+ FORCE_INLINE_AICORE
674+ void CrossRankSyncV2WaitWithMask(AscendC::LocalTensor<int32_t> rankMask)
675+ {
676+ uint64_t flag_offset = m_segmentSize - m_tailReservedSize;
677+ int vec_size = get_block_num();
678+ int vec_id = get_block_idx();
679+ AscendC::CrossCoreSetFlag<0x0, PIPE_MTE3>(SEND_SYNC_EVENT_ID);
680+ for (int rank = vec_id; rank < m_rankSize; rank += vec_size) {
681+ if (rankMask.GetValue(rank) != 0) {
682+ continue;
683+ }
684+ __gm__ int32_t *status = reinterpret_cast<__gm__ int32_t *>((*this)() + flag_offset + rank * STATE_OFFSET);
685+ do {
686+ gm_dcci(reinterpret_cast<__gm__ uint8_t *>(status));
687+ } while (gm_load(status) != epStateValue_);
688+ }
689+ AscendC::CrossCoreSetFlag<0x0, PIPE_MTE3>(RECV_SYNC_EVENT_ID);
690+ AscendC::CrossCoreWaitFlag(RECV_SYNC_EVENT_ID);
691+ AscendC::CrossCoreWaitFlag(SEND_SYNC_EVENT_ID);
692+ }
693+ 
625 FORCE_INLINE_AICORE694 FORCE_INLINE_AICORE
626 __gm__ int32_t *SyncBaseAddr()695 __gm__ int32_t *SyncBaseAddr()
627 {696 {
@@ -94,8 +94,8 @@ __global__ __aicore__ void mega_moe(GM_ADDR context, GM_ADDR x, GM_ADDR topkIds,
94 GM_ADDR weight2, GM_ADDR weightScales1, GM_ADDR weightScales2, GM_ADDR bias1,94 GM_ADDR weight2, GM_ADDR weightScales1, GM_ADDR weightScales2, GM_ADDR bias1,
95 GM_ADDR bias2, GM_ADDR xActiveMask, GM_ADDR scales, GM_ADDR sharedWeight1,95 GM_ADDR bias2, GM_ADDR xActiveMask, GM_ADDR scales, GM_ADDR sharedWeight1,
96 GM_ADDR sharedWeight2, GM_ADDR sharedWeightScales1, GM_ADDR sharedWeightScales2,96 GM_ADDR sharedWeight2, GM_ADDR sharedWeightScales1, GM_ADDR sharedWeightScales2,
97- GM_ADDR sharedBias1, GM_ADDR sharedBias2, GM_ADDR yOut, GM_ADDR expertTokenNumsOut,97+ GM_ADDR sharedBias1, GM_ADDR sharedBias2, GM_ADDR maskBuffer, GM_ADDR yOut,
98- GM_ADDR workspaceGM, GM_ADDR tilingGM)98+ GM_ADDR expertTokenNumsOut, GM_ADDR workspaceGM, GM_ADDR tilingGM)
99{99{
100 InitSocState();100 InitSocState();
101 KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);101 KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);
@@ -81,11 +81,12 @@ ACLNN_API aclnnStatus aclnnMegaMoeGetWorkspaceSize(
81 const aclTensor *xActiveMaskOptional, const aclTensorList *sharedWeight1Optional,81 const aclTensor *xActiveMaskOptional, const aclTensorList *sharedWeight1Optional,
82 const aclTensorList *sharedWeight2Optional, const aclTensorList *sharedWeightScales1Optional,82 const aclTensorList *sharedWeight2Optional, const aclTensorList *sharedWeightScales1Optional,
83 const aclTensorList *sharedWeightScales2Optional, const aclTensorList *sharedBias1Optional,83 const aclTensorList *sharedWeightScales2Optional, const aclTensorList *sharedBias1Optional,
84- const aclTensorList *sharedBias2Optional, int64_t moeExpertNum, int64_t epWorldSize, int64_t cclBufferSize,84+ const aclTensorList *sharedBias2Optional, const aclTensor *maskBufferOptional, int64_t moeExpertNum,
85- int64_t maxRecvTokenNum, int64_t dispatchQuantMode, int64_t dispatchQuantOutDtype, int64_t combineQuantMode,85+ int64_t epWorldSize, int64_t cclBufferSize, int64_t maxRecvTokenNum, int64_t dispatchQuantMode,
86- const char *commAlg, int64_t numMaxTokensPerRank, const char *activation, const aclFloatArray *activationParams,86+ int64_t dispatchQuantOutDtype, int64_t combineQuantMode, const char *commAlg, int64_t numMaxTokensPerRank,
87- int64_t topoType, int64_t rankNumPerServer, int64_t topkWeightsType, aclTensor *yOut, aclTensor *expertTokenNumsOut,87+ const char *activation, const aclFloatArray *activationParams, int64_t topoType, int64_t rankNumPerServer,
88- uint64_t *workspaceSize, aclOpExecutor **executor);88+ int64_t topkWeightsType, aclTensor *yOut, aclTensor *expertTokenNumsOut, uint64_t *workspaceSize,
89+ aclOpExecutor **executor);
89 90 
90/**91/**
91 * @brief aclnnMegaMoe的第二段接口,用于执行计算。92 * @brief aclnnMegaMoe的第二段接口,用于执行计算。
@@ -47,12 +47,12 @@ static aclnnStatus RunActivationParamCase(const char *activation, const std::vec
47 auto expertTokenNumsDesc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);47 auto expertTokenNumsDesc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
48 auto activationParamsDesc = FloatArrayDesc(activationParams);48 auto activationParamsDesc = FloatArrayDesc(activationParams);
49 49 
50- auto ut = OP_API_UT(aclnnMegaMoe,50+ auto ut = OP_API_UT(
51- INPUT(contextDesc, xDesc, topkIdsDesc, topkWeightsDesc, weight1Descs, weight2Descs,51+ aclnnMegaMoe,
52- weightScales1Descs, weightScales2Descs, nullptr, nullptr, nullptr, nullptr, nullptr,52+ INPUT(contextDesc, xDesc, topkIdsDesc, topkWeightsDesc, weight1Descs, weight2Descs, weightScales1Descs,
53- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, activation,53+ weightScales2Descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
54- activationParamsDesc, 0, 2, 0),54+ nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, activation, activationParamsDesc, 0, 2, 0),
55- OUTPUT(yDesc, expertTokenNumsDesc));55+ OUTPUT(yDesc, expertTokenNumsDesc));
56 56 
57 uint64_t workspaceSize = 0;57 uint64_t workspaceSize = 0;
58 return ut.TestGetWorkspaceSize(&workspaceSize);58 return ut.TestGetWorkspaceSize(&workspaceSize);
@@ -88,12 +88,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_context)
88 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);88 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
89 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});89 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
90 90 
91- auto ut = OP_API_UT(aclnnMegaMoe,91+ auto ut = OP_API_UT(
92- INPUT(nullptr, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs,92+ aclnnMegaMoe,
93- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,93+ INPUT(nullptr, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs, weight_scales1_descs,
94- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",94+ weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
95- activation_params_desc, 0, 2, 0),95+ nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
96- OUTPUT(y_desc, expert_token_nums_desc));96+ OUTPUT(y_desc, expert_token_nums_desc));
97 97 
98 uint64_t workspace_size = 0;98 uint64_t workspace_size = 0;
99 aclOpExecutor *executor = nullptr;99 aclOpExecutor *executor = nullptr;
@@ -116,12 +116,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_x)
116 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);116 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
117 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});117 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
118 118 
119- auto ut = OP_API_UT(aclnnMegaMoe,119+ auto ut = OP_API_UT(
120- INPUT(context_desc, nullptr, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs,120+ aclnnMegaMoe,
121- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,121+ INPUT(context_desc, nullptr, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs,
122- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",122+ weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
123- activation_params_desc, 0, 2, 0),123+ nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
124- OUTPUT(y_desc, expert_token_nums_desc));124+ OUTPUT(y_desc, expert_token_nums_desc));
125 125 
126 uint64_t workspace_size = 0;126 uint64_t workspace_size = 0;
127 aclOpExecutor *executor = nullptr;127 aclOpExecutor *executor = nullptr;
@@ -144,12 +144,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_topk_ids)
144 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);144 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
145 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});145 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
146 146 
147- auto ut = OP_API_UT(aclnnMegaMoe,147+ auto ut = OP_API_UT(
148- INPUT(context_desc, x_desc, nullptr, topk_weights_desc, weight1_descs, weight2_descs,148+ aclnnMegaMoe,
149- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,149+ INPUT(context_desc, x_desc, nullptr, topk_weights_desc, weight1_descs, weight2_descs, weight_scales1_descs,
150- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",150+ weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
151- activation_params_desc, 0, 2, 0),151+ nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
152- OUTPUT(y_desc, expert_token_nums_desc));152+ OUTPUT(y_desc, expert_token_nums_desc));
153 153 
154 uint64_t workspace_size = 0;154 uint64_t workspace_size = 0;
155 aclOpExecutor *executor = nullptr;155 aclOpExecutor *executor = nullptr;
@@ -172,12 +172,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_topk_weights)
172 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);172 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
173 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});173 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
174 174 
175- auto ut = OP_API_UT(aclnnMegaMoe,175+ auto ut = OP_API_UT(
176- INPUT(context_desc, x_desc, topk_ids_desc, nullptr, weight1_descs, weight2_descs,176+ aclnnMegaMoe,
177- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,177+ INPUT(context_desc, x_desc, topk_ids_desc, nullptr, weight1_descs, weight2_descs, weight_scales1_descs,
178- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",178+ weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
179- activation_params_desc, 0, 2, 0),179+ nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
180- OUTPUT(y_desc, expert_token_nums_desc));180+ OUTPUT(y_desc, expert_token_nums_desc));
181 181 
182 uint64_t workspace_size = 0;182 uint64_t workspace_size = 0;
183 aclOpExecutor *executor = nullptr;183 aclOpExecutor *executor = nullptr;
@@ -200,12 +200,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_weight1)
200 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);200 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
201 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});201 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
202 202 
203- auto ut = OP_API_UT(aclnnMegaMoe,203+ auto ut = OP_API_UT(
204- INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, nullptr, weight2_descs,204+ aclnnMegaMoe,
205- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,205+ INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, nullptr, weight2_descs, weight_scales1_descs,
206- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",206+ weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
207- activation_params_desc, 0, 2, 0),207+ nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
208- OUTPUT(y_desc, expert_token_nums_desc));208+ OUTPUT(y_desc, expert_token_nums_desc));
209 209 
210 uint64_t workspace_size = 0;210 uint64_t workspace_size = 0;
211 aclOpExecutor *executor = nullptr;211 aclOpExecutor *executor = nullptr;
@@ -228,12 +228,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_weight2)
228 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);228 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
229 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});229 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
230 230 
231- auto ut = OP_API_UT(aclnnMegaMoe,231+ auto ut = OP_API_UT(
232- INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, nullptr,232+ aclnnMegaMoe,
233- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,233+ INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, nullptr, weight_scales1_descs,
234- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",234+ weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
235- activation_params_desc, 0, 2, 0),235+ nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
236- OUTPUT(y_desc, expert_token_nums_desc));236+ OUTPUT(y_desc, expert_token_nums_desc));
237 237 
238 uint64_t workspace_size = 0;238 uint64_t workspace_size = 0;
239 aclOpExecutor *executor = nullptr;239 aclOpExecutor *executor = nullptr;
@@ -256,12 +256,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_y_out)
256 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);256 auto expert_token_nums_desc = TensorDesc({4}, ACL_INT32, ACL_FORMAT_ND);
257 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});257 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
258 258 
259- auto ut = OP_API_UT(aclnnMegaMoe,259+ auto ut = OP_API_UT(
260- INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs,260+ aclnnMegaMoe,
261- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,261+ INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs,
262- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",262+ weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
263- activation_params_desc, 0, 2, 0),263+ nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
264- OUTPUT(nullptr, expert_token_nums_desc));264+ OUTPUT(nullptr, expert_token_nums_desc));
265 265 
266 uint64_t workspace_size = 0;266 uint64_t workspace_size = 0;
267 aclOpExecutor *executor = nullptr;267 aclOpExecutor *executor = nullptr;
@@ -284,12 +284,12 @@ TEST_F(AclnnMegaMoeTest, ascend950_nullptr_expert_token_nums_out)
284 auto y_desc = TensorDesc({128, 4096}, ACL_BF16, ACL_FORMAT_ND);284 auto y_desc = TensorDesc({128, 4096}, ACL_BF16, ACL_FORMAT_ND);
285 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});285 auto activation_params_desc = FloatArrayDesc(std::vector<float>{std::numeric_limits<float>::max()});
286 286 
287- auto ut = OP_API_UT(aclnnMegaMoe,287+ auto ut = OP_API_UT(
288- INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs,288+ aclnnMegaMoe,
289- weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr,289+ INPUT(context_desc, x_desc, topk_ids_desc, topk_weights_desc, weight1_descs, weight2_descs,
290- nullptr, nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu",290+ weight_scales1_descs, weight_scales2_descs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
291- activation_params_desc, 0, 2, 0),291+ nullptr, nullptr, nullptr, 16, 4, 2097152, 0, 0, 0, 0, "", 0, "swiglu", activation_params_desc, 0, 2, 0),
292- OUTPUT(y_desc, nullptr));292+ OUTPUT(y_desc, nullptr));
293 293 
294 uint64_t workspace_size = 0;294 uint64_t workspace_size = 0;
295 aclOpExecutor *executor = nullptr;295 aclOpExecutor *executor = nullptr;
@@ -27,17 +27,25 @@ std::tuple<at::Tensor, at::Tensor> NpuMegaMoe(
27 const c10::optional<std::vector<at::Tensor>> &sharedWeightScales1,27 const c10::optional<std::vector<at::Tensor>> &sharedWeightScales1,
28 const c10::optional<std::vector<at::Tensor>> &sharedWeightScales2,28 const c10::optional<std::vector<at::Tensor>> &sharedWeightScales2,
29 const c10::optional<std::vector<at::Tensor>> &sharedBias1,29 const c10::optional<std::vector<at::Tensor>> &sharedBias1,
30- const c10::optional<std::vector<at::Tensor>> &sharedBias2, int64_t maxRecvTokenNum, int64_t dispatchQuantMode,30+ const c10::optional<std::vector<at::Tensor>> &sharedBias2, const c10::optional<at::Tensor> &maskBuffer,
31- int64_t combineQuantMode, std::string commAlg, int64_t numMaxTokensPerRank, std::string activation,31+ int64_t maxRecvTokenNum, int64_t dispatchQuantMode, int64_t combineQuantMode, std::string commAlg,
32- std::vector<float> activationParams, c10::optional<int64_t> dispatchQuantOutDtype,32+ int64_t numMaxTokensPerRank, std::string activation, std::vector<float> activationParams,
33- c10::optional<int64_t> weight1Type, c10::optional<int64_t> weight2Type, c10::optional<int64_t> topoType,33+ c10::optional<int64_t> dispatchQuantOutDtype, c10::optional<int64_t> weight1Type,
34- c10::optional<int64_t> rankNumPerServer, int64_t topkWeightsType)34+ c10::optional<int64_t> weight2Type, c10::optional<int64_t> topoType, c10::optional<int64_t> rankNumPerServer,
35+ int64_t topkWeightsType)
35{36{
36 TORCH_CHECK((epWorldSize > 0), "The ep_world_sizes should be greater than 0, current is: ", epWorldSize);37 TORCH_CHECK((epWorldSize > 0), "The ep_world_sizes should be greater than 0, current is: ", epWorldSize);
37 TORCH_CHECK((x.dim() == DIM_TWO) && (topkIds.dim() == DIM_TWO), "The x and topk_ids should be 2D");38 TORCH_CHECK((x.dim() == DIM_TWO) && (topkIds.dim() == DIM_TWO), "The x and topk_ids should be 2D");
38 TORCH_CHECK(39 TORCH_CHECK(
39 ((x.scalar_type() == at::kBFloat16) || (x.scalar_type() == at::kHalf)) && (topkIds.scalar_type() == at::kInt),40 ((x.scalar_type() == at::kBFloat16) || (x.scalar_type() == at::kHalf)) && (topkIds.scalar_type() == at::kInt),
40 "dtype of x should be bfloat16, float16, dtype of topk_ids should be int.");41 "dtype of x should be bfloat16, float16, dtype of topk_ids should be int.");
42+ if (maskBuffer.has_value()) {
43+ const at::Tensor &mask = maskBuffer.value();
44+ TORCH_CHECK(mask.scalar_type() == at::kInt, "mask_buffer dtype must be int32.");
45+ TORCH_CHECK(mask.dim() == 1 && mask.numel() == epWorldSize, "mask_buffer shape must be [ep_world_size].");
46+ TORCH_CHECK(mask.device() == x.device(), "mask_buffer must be on the same device as x.");
47+ TORCH_CHECK(mask.is_contiguous(), "mask_buffer must be contiguous.");
48+ }
41 49 
42 at::TensorList weight1Ref = weight1;50 at::TensorList weight1Ref = weight1;
43 at::TensorList weight2Ref = weight2;51 at::TensorList weight2Ref = weight2;
@@ -127,9 +135,9 @@ std::tuple<at::Tensor, at::Tensor> NpuMegaMoe(
127 ACLNN_CMD(aclnnMegaMoe, context, x, topkIds, topkWeights, weight1Wrapper, weight2Wrapper, weightScales1Wrapper,135 ACLNN_CMD(aclnnMegaMoe, context, x, topkIds, topkWeights, weight1Wrapper, weight2Wrapper, weightScales1Wrapper,
128 weightScales2Wrapper, bias1Wrapper, bias2Wrapper, xActiveMask, sharedWeight1Wrapper, sharedWeight2Wrapper,136 weightScales2Wrapper, bias1Wrapper, bias2Wrapper, xActiveMask, sharedWeight1Wrapper, sharedWeight2Wrapper,
129 sharedWeightScales1Wrapper, sharedWeightScales2Wrapper, sharedBias1Wrapper, sharedBias2Wrapper,137 sharedWeightScales1Wrapper, sharedWeightScales2Wrapper, sharedBias1Wrapper, sharedBias2Wrapper,
130- moeExpertNum, epWorldSize, cclBufferSize, maxRecvTokenNum, dispatchQuantMode, dispatchQuantResultType,138+ maskBuffer, moeExpertNum, epWorldSize, cclBufferSize, maxRecvTokenNum, dispatchQuantMode,
131- combineQuantMode, commAlgPtr, numMaxTokensPerRank, activationPtr, activationParams, topoTypeValue,139+ dispatchQuantResultType, combineQuantMode, commAlgPtr, numMaxTokensPerRank, activationPtr,
132- rankNumPerServerValue, topkWeightsType, y, expertTokenNums);140+ activationParams, topoTypeValue, rankNumPerServerValue, topkWeightsType, y, expertTokenNums);
133 141 
134 return std::tie(y, expertTokenNums);142 return std::tie(y, expertTokenNums);
135}143}
@@ -142,7 +150,10 @@ constexpr int64_t RESERVED_SPACE_SIZE = 10LL * 1024 * 1024;
142constexpr int64_t MAX_EXPERTS_PER_RANK_A2A3 = 128LL;150constexpr int64_t MAX_EXPERTS_PER_RANK_A2A3 = 128LL;
143constexpr int64_t SYNC_STATE_RESERVED_SIZE = 512LL * 1024;151constexpr int64_t SYNC_STATE_RESERVED_SIZE = 512LL * 1024;
144 152 
145-int64_t CeilAlign(int64_t val, int64_t align) { return (val + align - 1) / align * align; }153+int64_t CeilAlign(int64_t val, int64_t align)
154+{
155+ return (val + align - 1) / align * align;
156+}
146 157 
147// A2 minimum buffer size (MB).158// A2 minimum buffer size (MB).
148// Matches tiling_arch22.cpp CalcLeastCclBufferSize with isA3=false.159// Matches tiling_arch22.cpp CalcLeastCclBufferSize with isA3=false.
@@ -82,6 +82,7 @@ class _MegaMoeOpBuilder(OpBuilder):
82 "Tensor[]? shared_weight1=None, Tensor[]? shared_weight2=None, "82 "Tensor[]? shared_weight1=None, Tensor[]? shared_weight2=None, "
83 "Tensor[]? shared_weight_scales1=None, Tensor[]? shared_weight_scales2=None, "83 "Tensor[]? shared_weight_scales1=None, Tensor[]? shared_weight_scales2=None, "
84 "Tensor[]? shared_bias1=None, Tensor[]? shared_bias2=None, "84 "Tensor[]? shared_bias1=None, Tensor[]? shared_bias2=None, "
85+ "Tensor? mask_buffer=None, "
85 "int max_recv_token_num=0, "86 "int max_recv_token_num=0, "
86 "int dispatch_quant_mode=0, int combine_quant_mode=0, "87 "int dispatch_quant_mode=0, int combine_quant_mode=0, "
87 'str comm_alg="", int num_max_tokens_per_rank=0, str activation="swiglu", '88 'str comm_alg="", int num_max_tokens_per_rank=0, str activation="swiglu", '
@@ -114,6 +115,7 @@ class _MegaMoeOpBuilder(OpBuilder):
114 shared_weight_scales2=None,115 shared_weight_scales2=None,
115 shared_bias1=None,116 shared_bias1=None,
116 shared_bias2=None,117 shared_bias2=None,
118+ mask_buffer=None,
117 max_recv_token_num=0,119 max_recv_token_num=0,
118 dispatch_quant_mode=0,120 dispatch_quant_mode=0,
119 combine_quant_mode=0,121 combine_quant_mode=0,
@@ -167,6 +169,7 @@ def _npu_mega_moe(
167 shared_weight_scales2=None,169 shared_weight_scales2=None,
168 shared_bias1=None,170 shared_bias1=None,
169 shared_bias2=None,171 shared_bias2=None,
172+ mask_buffer=None,
170 max_recv_token_num=0,173 max_recv_token_num=0,
171 dispatch_quant_mode=0,174 dispatch_quant_mode=0,
172 combine_quant_mode=0,175 combine_quant_mode=0,
@@ -207,6 +210,7 @@ def _npu_mega_moe(
207 shared_weight_scales2,210 shared_weight_scales2,
208 shared_bias1,211 shared_bias1,
209 shared_bias2,212 shared_bias2,
213+ mask_buffer,
210 max_recv_token_num,214 max_recv_token_num,
211 dispatch_quant_mode,215 dispatch_quant_mode,
212 combine_quant_mode,216 combine_quant_mode,
@@ -284,10 +288,142 @@ class SymmBuffer:
284 self.topk_weights_type = topk_weights_type288 self.topk_weights_type = topk_weights_type
285 self.topo_type = self._ctx_manager.topo_type289 self.topo_type = self._ctx_manager.topo_type
286 self.rank_num_per_server = self._ctx_manager.rank_num_per_server290 self.rank_num_per_server = self._ctx_manager.rank_num_per_server
291+ self.mask_buffer = None
292+ 
293+ def _create_mask_buffer(self, ep_world_size: int) -> torch.Tensor:
294+ return torch.zeros(ep_world_size, dtype=torch.int32, device=self.context.device)
295+ 
296+ def _check_mask_buffer_supported(self) -> None:
297+ if "Ascend910_93" not in torch.npu.get_device_name():
298+ raise RuntimeError("mask_buffer is supported on Atlas A3 only.")
287 299 
288 def destroy(self):300 def destroy(self):
289 self._ctx_manager.destroy()301 self._ctx_manager.destroy()
290 302 
303+ def query_mask_buffer(self, mask_status: torch.Tensor) -> None:
304+ """Copy the current rank mask to a caller-provided NPU tensor."""
305+ self._check_mask_buffer_supported()
306+ if self.mask_buffer is None:
307+ self.mask_buffer = self._create_mask_buffer(self.ep_world_size)
308+ if not isinstance(mask_status, torch.Tensor):
309+ raise TypeError(f"mask_status must be a Tensor, got {type(mask_status)}.")
310+ if mask_status.dtype != torch.int32:
311+ raise TypeError(
312+ f"mask_status dtype must be torch.int32, got {mask_status.dtype}."
313+ )
314+ if mask_status.device.type != "npu":
315+ raise ValueError(f"mask_status must be on NPU, got {mask_status.device}.")
316+ if mask_status.device != self.mask_buffer.device:
317+ raise ValueError(
318+ "mask_status must be on the same NPU device as mask_buffer."
319+ )
320+ if mask_status.shape != self.mask_buffer.shape:
321+ raise ValueError(
322+ "mask_status shape must match mask_buffer shape "
323+ f"{tuple(self.mask_buffer.shape)}, got {tuple(mask_status.shape)}."
324+ )
325+ if not mask_status.is_contiguous():
326+ raise ValueError("mask_status must be contiguous.")
327+ mask_status.copy_(self.mask_buffer, non_blocking=True)
328+ 
329+ def update_mask_buffer(self, rank: int, masked: bool) -> None:
330+ self._check_mask_buffer_supported()
331+ if (
332+ isinstance(rank, bool)
333+ or not isinstance(rank, int)
334+ or not 0 <= rank < self.ep_world_size
335+ ):
336+ raise IndexError(f"rank must be in [0, {self.ep_world_size}), got {rank}.")
337+ if not isinstance(masked, bool):
338+ raise TypeError(f"masked must be bool, got {type(masked)}.")
339+ 
340+ if self.mask_buffer is None:
341+ self.mask_buffer = self._create_mask_buffer(self.ep_world_size)
342+ 
343+ self.mask_buffer[rank] = int(masked)
344+ 
345+ def clean_mask_buffer(self) -> None:
346+ """Set every rank mask entry to zero on the current NPU stream."""
347+ self._check_mask_buffer_supported()
348+ if self.mask_buffer is None:
349+ self.mask_buffer = self._create_mask_buffer(self.ep_world_size)
350+ return
351+ self.mask_buffer.zero_()
352+ 
353+ def get_local_buffer_tensor(
354+ self,
355+ dtype: torch.dtype,
356+ size: Optional[torch.Size] = None,
357+ offset: int = 0,
358+ ) -> torch.Tensor:
359+ """Return a zero-copy tensor view of the local CCL buffer."""
360+ self._check_mask_buffer_supported()
361+ if not isinstance(dtype, torch.dtype):
362+ raise TypeError(f"dtype must be torch.dtype, got {type(dtype)}.")
363+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
364+ raise ValueError(f"offset must be a non-negative int, got {offset}.")
365+ 
366+ tensor = self._ctx_manager.get_local_buffer_tensor(dtype, offset)
367+ if size is None:
368+ return tensor
369+ if not isinstance(size, torch.Size):
370+ raise TypeError(f"size must be torch.Size or None, got {type(size)}.")
371+ if tensor.numel() < size.numel():
372+ raise ValueError(
373+ f"requested size contains {size.numel()} elements, but only "
374+ f"{tensor.numel()} elements remain after offset {offset}."
375+ )
376+ return tensor[: size.numel()].view(size)
377+ 
378+ def update_group(self, group) -> None:
379+ """Destroy the old links after a replacement context has been created."""
380+ self._check_mask_buffer_supported()
381+ rank_id = torch.distributed.get_rank(group)
382+ group_name = group._get_backend(torch.device("npu")).get_hccl_comm_name(
383+ rank_id, init_comm=True
384+ )
385+ ep_world_size = torch.distributed.get_world_size(group)
386+ required_ccl_buffer_size = _get_mega_moe_ccl_buffer_size(
387+ ep_world_size,
388+ self.num_experts,
389+ self.num_max_tokens_per_rank,
390+ self.num_topk,
391+ self.hidden,
392+ self.max_recv_token_num,
393+ self.dispatch_quant_mode,
394+ self.dispatch_quant_out_dtype,
395+ self.combine_quant_mode,
396+ self.comm_alg,
397+ self.topk_weights_type,
398+ )
399+ new_manager = CommContextManager(
400+ group_name,
401+ ep_world_size,
402+ backend={
403+ "Ascend910B": "kfc",
404+ "Ascend910_93": "kfc",
405+ "Ascend950": "channel",
406+ },
407+ customCclBufferSize=required_ccl_buffer_size,
408+ )
409+ try:
410+ new_context = new_manager.create_context()
411+ except Exception:
412+ new_manager.destroy()
413+ raise
414+ 
415+ old_manager = self._ctx_manager
416+ self.group = group
417+ self.rank_id = rank_id
418+ self.group_name = group_name
419+ self.ep_world_size = ep_world_size
420+ self._ctx_manager = new_manager
421+ self.context = new_context
422+ self.ccl_buffer_size = new_manager.ccl_buffer_size
423+ self.topo_type = new_manager.topo_type
424+ self.rank_num_per_server = new_manager.rank_num_per_server
425+ old_manager.destroy()
426+ 
291 427 
292_TORCH_DTYPE_TO_INT = { # torch枚举428_TORCH_DTYPE_TO_INT = { # torch枚举
293 torch.float8_e5m2: 23,429 torch.float8_e5m2: 23,
@@ -417,6 +553,7 @@ def mega_moe(
417 shared_weight_scales2=shared_l2_weights_sf,553 shared_weight_scales2=shared_l2_weights_sf,
418 shared_bias1=shared_l1_bias,554 shared_bias1=shared_l1_bias,
419 shared_bias2=shared_l2_bias,555 shared_bias2=shared_l2_bias,
556+ mask_buffer=sym_buffer.mask_buffer,
420 max_recv_token_num=sym_buffer.max_recv_token_num,557 max_recv_token_num=sym_buffer.max_recv_token_num,
421 dispatch_quant_mode=sym_buffer.dispatch_quant_mode,558 dispatch_quant_mode=sym_buffer.dispatch_quant_mode,
422 combine_quant_mode=sym_buffer.combine_quant_mode,559 combine_quant_mode=sym_buffer.combine_quant_mode,
@@ -630,6 +630,32 @@ get_symm_buffer_for_mega_moe(group, num_experts, num_max_tokens_per_rank, num_to
630mega_moe(x, topk_ids, topk_weights, l1_weights, l2_weights, sym_buffer, *, l1_weights_sf=None, l2_weights_sf=None, l1_bias=None, l2_bias=None, x_active_mask=None, activation="swiglu", activation_clamp=None, activation_params=None, weight1_type=None, weight2_type=None, shared_l1_weights=None, shared_l2_weights=None, shared_l1_weights_sf=None, shared_l2_weights_sf=None, shared_l1_bias=None, shared_l2_bias=None) -> (Tensor, Tensor)630mega_moe(x, topk_ids, topk_weights, l1_weights, l2_weights, sym_buffer, *, l1_weights_sf=None, l2_weights_sf=None, l1_bias=None, l2_bias=None, x_active_mask=None, activation="swiglu", activation_clamp=None, activation_params=None, weight1_type=None, weight2_type=None, shared_l1_weights=None, shared_l2_weights=None, shared_l1_weights_sf=None, shared_l2_weights_sf=None, shared_l1_bias=None, shared_l2_bias=None) -> (Tensor, Tensor)
631```631```
632 632 
633+### 弹性扩缩容接口
634+ 
635+```python
636+sym_buffer.query_mask_buffer(mask_status) -> None
637+sym_buffer.update_mask_buffer(rank, masked) -> None
638+sym_buffer.clean_mask_buffer() -> None
639+sym_buffer.get_local_buffer_tensor(dtype, size=None, offset=0) -> Tensor
640+sym_buffer.update_group(group) -> None
641+```
642+ 
643+`mask_buffer` 及以上五个 `SymmBuffer` 弹性扩缩容接口当前仅支持 <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>。`SymmBuffer` 默认不创建 `mask_buffer`,因此各代际默认均不会向算子传入该参数。第一次调用 `query_mask_buffer`、`update_mask_buffer` 或 `clean_mask_buffer` 时,才会在 NPU 上创建 shape 为 `[ep_world_size]` 的全 0 int32 掩码;0 表示正常 rank,1 表示失能 rank,失能 rank 会在后续计算和卡间通信中被跳过。
644+ 
645+- `query_mask_buffer` 接收调用者预先创建的 `mask_status`,其 dtype 必须为 `torch.int32`,shape、所在 NPU 必须与内部 `mask_buffer` 一致。接口通过 D2D 拷贝将当前掩码写入 `mask_status`,不返回 Tensor。
646+- `update_mask_buffer` 只更新当前进程中的本地掩码,各 rank 的掩码一致性由调用者保证。当恢复 rank,即 `masked` 输入为 `False` 时,必须调用 `get_local_buffer_tensor` 清空算子现存通信缓存区标志位。样例如下:
647+ 
648+ ```python
649+ symm_buffer.update_mask_buffer(0, False) # 恢复 rank 0 通信
650+ symm_buffer.update_mask_buffer(1, False) # 恢复 rank 1 通信
651+ local_buffer = symm_buffer.get_local_buffer_tensor(torch.uint8)
652+ local_buffer.zero_()
653+ ```
654+ 
655+- `clean_mask_buffer` 在当前 NPU stream 上将本地掩码的所有元素清零;各 rank 需要分别调用,跨 rank 的一致性仍由调用者保证。掩码尚未创建时,接口会创建全 0 掩码。
656+- `get_local_buffer_tensor` 将当前 Rank 的本地 CCL Buffer 零拷贝包装为 NPU Tensor。`offset` 以 `dtype` 元素为单位,`size` 为 `None` 时返回从 `offset` 到 Buffer 末尾的一维视图,否则返回指定 shape。返回 Tensor 不持有底层内存,其生命周期不得超过 `SymmBuffer`;调用 `update_group` 后旧视图失效,必须重新获取。调用者写入原始通信 Buffer 前必须保证相关算子已经执行完成,并确保写入范围正确。
657+- `update_group` 使用新 group 完整重建通信链路;旧通信链路的算子执行完成以及新 group 与现有 mask shape 的一致性需要调用者保证。如需清除失能状态,应显式调用 `clean_mask_buffer`。
658+ 
633## 参数说明659## 参数说明
634 660 
635### get_symm_buffer_for_mega_moe661### get_symm_buffer_for_mega_moe