Merged
add hybrid template for dispatch training #9388
add hybrid template for dispatch training #9388
Merged
zhong-zixinAdd on Jul 31
Total: 19 files changed+2935-256
@@ -16,6 +16,11 @@
16 16 
17using namespace op;17using namespace op;
18 18 
19+namespace {
20+constexpr int64_t DIRECT_MODE = 0;
21+constexpr int64_t HYBRID_MODE = 1;
22+} // namespace
23+ 
19static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,24static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,
20 const aclTensor *recvSrcMetadata, const aclTensor *numRecvTokensPerExpert,25 const aclTensor *recvSrcMetadata, const aclTensor *numRecvTokensPerExpert,
21 aclTensor *combinedX)26 aclTensor *combinedX)
@@ -30,15 +35,16 @@ static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *x, co
30}35}
31 36 
32static aclnnStatus CheckParams(int64_t epWorldSize, int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,37static aclnnStatus CheckParams(int64_t epWorldSize, int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,
33- int64_t cclBufferSize, const aclTensor *biasOptional0, const aclTensor *biasOptional1)38+ int64_t cclBufferSize, int64_t topoType, int64_t rankNumPerServer)
34{39{
35 CHECK_RET(epWorldSize > 1, ACLNN_ERR_PARAM_INVALID);40 CHECK_RET(epWorldSize > 1, ACLNN_ERR_PARAM_INVALID);
36 CHECK_RET(epRankId >= 0 && epRankId < epWorldSize, ACLNN_ERR_PARAM_INVALID);41 CHECK_RET(epRankId >= 0 && epRankId < epWorldSize, ACLNN_ERR_PARAM_INVALID);
37 CHECK_RET(numExperts % epWorldSize == 0, ACLNN_ERR_PARAM_INVALID);42 CHECK_RET(numExperts % epWorldSize == 0, ACLNN_ERR_PARAM_INVALID);
38 CHECK_RET(numMaxTokensPerRank > 0, ACLNN_ERR_PARAM_INVALID);43 CHECK_RET(numMaxTokensPerRank > 0, ACLNN_ERR_PARAM_INVALID);
39 CHECK_RET(cclBufferSize > 0, ACLNN_ERR_PARAM_INVALID);44 CHECK_RET(cclBufferSize > 0, ACLNN_ERR_PARAM_INVALID);
40- CHECK_RET(biasOptional0 == nullptr, ACLNN_ERR_PARAM_INVALID);45+ CHECK_RET(topoType == DIRECT_MODE || topoType == HYBRID_MODE, ACLNN_ERR_PARAM_INVALID);
41- CHECK_RET(biasOptional1 == nullptr, ACLNN_ERR_PARAM_INVALID);46+ CHECK_RET(rankNumPerServer > 0, ACLNN_ERR_PARAM_INVALID);
47+ CHECK_RET(epWorldSize % rankNumPerServer == 0, ACLNN_ERR_PARAM_INVALID);
42 return ACLNN_SUCCESS;48 return ACLNN_SUCCESS;
43}49}
44 50 
@@ -53,37 +59,37 @@ enum NnopbaseHcclServerType {
53 59 
54aclnnStatus MoeEpCombineGetWorkspaceSize(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,60aclnnStatus MoeEpCombineGetWorkspaceSize(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,
55 const aclTensor *recvSrcMetadata, const aclTensor *numRecvTokensPerExpert,61 const aclTensor *recvSrcMetadata, const aclTensor *numRecvTokensPerExpert,
56- const aclTensor *topkWeightsOptional, const aclTensor *biasOptional0,62+ const aclTensor *topkWeights, int64_t epWorldSize, int64_t epRankId,
57- const aclTensor *biasOptional1, int64_t epWorldSize, int64_t epRankId,
58 int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize,63 int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize,
59- aclTensor *combinedX, aclTensor *combinedTopkWeightsOptional,64+ int64_t topoType, int64_t rankNumPerServer,
65+ aclTensor *combinedX, aclTensor *combinedTopkWeights,
60 uint64_t *workspaceSize, aclOpExecutor **executor)66 uint64_t *workspaceSize, aclOpExecutor **executor)
61{67{
62 OP_LOGD("MoeEpCombine", "Begin to do MoeEpCombineGetWorkspaceSize");68 OP_LOGD("MoeEpCombine", "Begin to do MoeEpCombineGetWorkspaceSize");
63 auto retNotNull = CheckNotNull(context, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert, combinedX);69 auto retNotNull = CheckNotNull(context, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert, combinedX);
64 CHECK_RET(retNotNull == ACLNN_SUCCESS, retNotNull);70 CHECK_RET(retNotNull == ACLNN_SUCCESS, retNotNull);
65- auto retParams = CheckParams(epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, biasOptional0,71+ auto retParams = CheckParams(epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, topoType,
66- biasOptional1);72+ rankNumPerServer);
67 CHECK_RET(retParams == ACLNN_SUCCESS, retParams);73 CHECK_RET(retParams == ACLNN_SUCCESS, retParams);
68 74 
69 return aclnnInnerMoeEpCombineGetWorkspaceSize(context, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert,75 return aclnnInnerMoeEpCombineGetWorkspaceSize(context, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert,
70- topkWeightsOptional, biasOptional0, biasOptional1, epWorldSize,76+ topkWeights, epWorldSize, epRankId, numExperts, numMaxTokensPerRank,
71- epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, combinedX,77+ cclBufferSize, topoType, rankNumPerServer, combinedX,
72- combinedTopkWeightsOptional, workspaceSize, executor);78+ combinedTopkWeights, workspaceSize, executor);
73}79}
74 80 
75aclnnStatus aclnnMoeEpCombineGetWorkspaceSize(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,81aclnnStatus aclnnMoeEpCombineGetWorkspaceSize(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,
76 const aclTensor *recvSrcMetadata, const aclTensor *numRecvTokensPerExpert,82 const aclTensor *recvSrcMetadata, const aclTensor *numRecvTokensPerExpert,
77- const aclTensor *topkWeightsOptional, const aclTensor *biasOptional0,83+ const aclTensor *topkWeights, int64_t epWorldSize, int64_t epRankId,
78- const aclTensor *biasOptional1, int64_t epWorldSize, int64_t epRankId,
79 int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize,84 int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize,
80- aclTensor *combinedX, aclTensor *combinedTopkWeightsOptional,85+ int64_t topoType, int64_t rankNumPerServer,
86+ aclTensor *combinedX, aclTensor *combinedTopkWeights,
81 uint64_t *workspaceSize, aclOpExecutor **executor)87 uint64_t *workspaceSize, aclOpExecutor **executor)
82{88{
83- return MoeEpCombineGetWorkspaceSize(context, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert,89+ return MoeEpCombineGetWorkspaceSize(context, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert, topkWeights,
84- topkWeightsOptional, biasOptional0, biasOptional1, epWorldSize, epRankId,90+ epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize,
85- numExperts, numMaxTokensPerRank, cclBufferSize, combinedX,91+ topoType, rankNumPerServer, combinedX, combinedTopkWeights, workspaceSize,
86- combinedTopkWeightsOptional, workspaceSize, executor);92+ executor);
87}93}
88 94 
89extern "C" void __attribute__((weak)) NnopbaseSetHcclServerType(void *executor, NnopbaseHcclServerType sType);95extern "C" void __attribute__((weak)) NnopbaseSetHcclServerType(void *executor, NnopbaseHcclServerType sType);
@@ -41,27 +41,17 @@ public:
41 .DataType({ge::DT_INT64})41 .DataType({ge::DT_INT64})
42 .FormatList({ge::FORMAT_ND})42 .FormatList({ge::FORMAT_ND})
43 .AutoContiguous();43 .AutoContiguous();
44- this->Input("topk_weights_optional")44+ this->Input("topk_weights")
45 .ParamType(OPTIONAL)45 .ParamType(OPTIONAL)
46 .DataType({ge::DT_FLOAT})46 .DataType({ge::DT_FLOAT})
47 .FormatList({ge::FORMAT_ND})47 .FormatList({ge::FORMAT_ND})
48 .AutoContiguous();48 .AutoContiguous();
49- this->Input("bias_optional_0")
50- .ParamType(OPTIONAL)
51- .DataType({ge::DT_BF16})
52- .FormatList({ge::FORMAT_ND})
53- .AutoContiguous();
54- this->Input("bias_optional_1")
55- .ParamType(OPTIONAL)
56- .DataType({ge::DT_BF16})
57- .FormatList({ge::FORMAT_ND})
58- .AutoContiguous();
59 49 
60 this->Output("combined_x")50 this->Output("combined_x")
61 .ParamType(REQUIRED)51 .ParamType(REQUIRED)
62 .DataTypeList({ge::DT_BF16, ge::DT_FLOAT16})52 .DataTypeList({ge::DT_BF16, ge::DT_FLOAT16})
63 .Format({ge::FORMAT_ND});53 .Format({ge::FORMAT_ND});
64- this->Output("combined_topk_weights_optional")54+ this->Output("combined_topk_weights")
65 .ParamType(OPTIONAL)55 .ParamType(OPTIONAL)
66 .DataType({ge::DT_FLOAT})56 .DataType({ge::DT_FLOAT})
67 .Format({ge::FORMAT_ND});57 .Format({ge::FORMAT_ND});
@@ -71,6 +61,8 @@ public:
71 this->Attr("num_experts").AttrType(REQUIRED).Int();61 this->Attr("num_experts").AttrType(REQUIRED).Int();
72 this->Attr("num_max_tokens_per_rank").AttrType(REQUIRED).Int();62 this->Attr("num_max_tokens_per_rank").AttrType(REQUIRED).Int();
73 this->Attr("ccl_buffer_size").AttrType(REQUIRED).Int();63 this->Attr("ccl_buffer_size").AttrType(REQUIRED).Int();
64+ this->Attr("topo_type").AttrType(OPTIONAL).Int(0);
65+ this->Attr("rank_num_per_server").AttrType(OPTIONAL).Int(1);
74 66 
75 OpAICoreConfig aicore_config;67 OpAICoreConfig aicore_config;
76 aicore_config.DynamicCompileStaticFlag(true)68 aicore_config.DynamicCompileStaticFlag(true)
@@ -16,8 +16,6 @@
16#include <cmath>16#include <cmath>
17#include <cstdint>17#include <cstdint>
18#include <cstdio>18#include <cstdio>
19-#include <cstdlib>
20-#include <cstring>
21 19 
22#include "mc2_log.h"20#include "mc2_log.h"
23#include "graph/utils/type_utils.h"21#include "graph/utils/type_utils.h"
@@ -40,18 +38,18 @@ constexpr uint32_t TOPK_IDX_INDEX = 2U;
40constexpr uint32_t RECV_SRC_METADATA_INDEX = 3U;38constexpr uint32_t RECV_SRC_METADATA_INDEX = 3U;
41constexpr uint32_t NUM_RECV_PER_EXPERT_INDEX = 4U;39constexpr uint32_t NUM_RECV_PER_EXPERT_INDEX = 4U;
42constexpr uint32_t TOPK_WEIGHTS_INDEX = 5U;40constexpr uint32_t TOPK_WEIGHTS_INDEX = 5U;
43-constexpr uint32_t BIAS_0_INDEX = 6U;
44-constexpr uint32_t BIAS_1_INDEX = 7U;
45 41 
46constexpr uint32_t ATTR_EP_WORLD_SIZE_INDEX = 0;42constexpr uint32_t ATTR_EP_WORLD_SIZE_INDEX = 0;
47constexpr uint32_t ATTR_EP_RANK_ID_INDEX = 1;43constexpr uint32_t ATTR_EP_RANK_ID_INDEX = 1;
48constexpr uint32_t ATTR_NUM_EXPERTS_INDEX = 2;44constexpr uint32_t ATTR_NUM_EXPERTS_INDEX = 2;
49constexpr uint32_t ATTR_NUM_MAX_TPR_INDEX = 3;45constexpr uint32_t ATTR_NUM_MAX_TPR_INDEX = 3;
50constexpr uint32_t ATTR_CCL_BUFFER_SIZE_INDEX = 4;46constexpr uint32_t ATTR_CCL_BUFFER_SIZE_INDEX = 4;
47+constexpr uint32_t ATTR_TOPO_TYPE_INDEX = 5;
48+constexpr uint32_t ATTR_RANK_NUM_PER_SERVER_INDEX = 6;
51 49 
52constexpr uint32_t ONE_DIMS = 1U;50constexpr uint32_t ONE_DIMS = 1U;
53constexpr uint32_t TWO_DIMS = 2U;51constexpr uint32_t TWO_DIMS = 2U;
54-constexpr int64_t MAX_EP_WORLD_SIZE = 128;52+constexpr int64_t MAX_EP_WORLD_SIZE = 1024;
55constexpr int64_t MIN_EP_WORLD_SIZE = 2;53constexpr int64_t MIN_EP_WORLD_SIZE = 2;
56constexpr int64_t MAX_NUM_EXPERTS = 2048;54constexpr int64_t MAX_NUM_EXPERTS = 2048;
57constexpr int64_t MIN_NUM_EXPERTS = 2;55constexpr int64_t MIN_NUM_EXPERTS = 2;
@@ -65,6 +63,8 @@ constexpr int64_t H_MIN = 1;
65constexpr int64_t H_MAX = 8192;63constexpr int64_t H_MAX = 8192;
66constexpr int64_t K_MAX = 32;64constexpr int64_t K_MAX = 32;
67constexpr int64_t META_INNER_DIM = 4;65constexpr int64_t META_INNER_DIM = 4;
66+constexpr uint32_t DIRECT_MODE = 0U;
67+constexpr uint32_t HYBRID_MODE = 1U;
68 68 
69static void PrintTilingDataInfo(const char *nodeName, const MoeEpCombineInfo &info)69static void PrintTilingDataInfo(const char *nodeName, const MoeEpCombineInfo &info)
70{70{
@@ -183,22 +183,6 @@ static ge::graphStatus CheckInputTensorShape(const gert::TilingContext *context,
183 }183 }
184 info.hasTopkWeights = hasTopkWeights ? 1 : 0;184 info.hasTopkWeights = hasTopkWeights ? 1 : 0;
185 185 
186- const gert::StorageShape *bias0Shape = context->GetInputShape(BIAS_0_INDEX);
187- if (bias0Shape != nullptr) {
188- OP_TILING_CHECK(bias0Shape->GetStorageShape().GetDimNum() != TWO_DIMS,
189- OP_LOGE(nodeName, "bias_optional_0 dims must be 2, but got %lu.",
190- bias0Shape->GetStorageShape().GetDimNum()),
191- return ge::GRAPH_FAILED);
192- }
193- 
194- const gert::StorageShape *bias1Shape = context->GetInputShape(BIAS_1_INDEX);
195- if (bias1Shape != nullptr) {
196- OP_TILING_CHECK(bias1Shape->GetStorageShape().GetDimNum() != TWO_DIMS,
197- OP_LOGE(nodeName, "bias_optional_1 dims must be 2, but got %lu.",
198- bias1Shape->GetStorageShape().GetDimNum()),
199- return ge::GRAPH_FAILED);
200- }
201- 
202 return ge::GRAPH_SUCCESS;186 return ge::GRAPH_SUCCESS;
203}187}
204 188 
@@ -247,22 +231,6 @@ static ge::graphStatus CheckInputDataType(const gert::TilingContext *context, co
247 return ge::GRAPH_FAILED);231 return ge::GRAPH_FAILED);
248 }232 }
249 233 
250- auto bias0Desc = context->GetOptionalInputDesc(BIAS_0_INDEX);
251- if (bias0Desc != nullptr) {
252- OP_TILING_CHECK(bias0Desc->GetDataType() != ge::DT_BF16,
253- OP_LOGE(nodeName, "bias_optional_0 dtype must be DT_BF16, but got %s.",
254- ge::TypeUtils::DataTypeToSerialString(bias0Desc->GetDataType()).c_str()),
255- return ge::GRAPH_FAILED);
256- }
257- 
258- auto bias1Desc = context->GetOptionalInputDesc(BIAS_1_INDEX);
259- if (bias1Desc != nullptr) {
260- OP_TILING_CHECK(bias1Desc->GetDataType() != ge::DT_BF16,
261- OP_LOGE(nodeName, "bias_optional_1 dtype must be DT_BF16, but got %s.",
262- ge::TypeUtils::DataTypeToSerialString(bias1Desc->GetDataType()).c_str()),
263- return ge::GRAPH_FAILED);
264- }
265- 
266 return ge::GRAPH_SUCCESS;234 return ge::GRAPH_SUCCESS;
267}235}
268 236 
@@ -276,6 +244,8 @@ static ge::graphStatus CheckAttrParams(const gert::TilingContext *context, const
276 auto numExpertsPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_EXPERTS_INDEX);244 auto numExpertsPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_EXPERTS_INDEX);
277 auto nmtPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_MAX_TPR_INDEX);245 auto nmtPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_MAX_TPR_INDEX);
278 auto cclBufferSizePtr = attrs->GetAttrPointer<int64_t>(ATTR_CCL_BUFFER_SIZE_INDEX);246 auto cclBufferSizePtr = attrs->GetAttrPointer<int64_t>(ATTR_CCL_BUFFER_SIZE_INDEX);
247+ auto topoTypePtr = attrs->GetAttrPointer<int64_t>(ATTR_TOPO_TYPE_INDEX);
248+ auto rankNumPerServerPtr = attrs->GetAttrPointer<int64_t>(ATTR_RANK_NUM_PER_SERVER_INDEX);
279 249 
280 OP_TILING_CHECK(epWorldSizePtr == nullptr, OP_LOGE(nodeName, "epWorldSizePtr is null."), return ge::GRAPH_FAILED);250 OP_TILING_CHECK(epWorldSizePtr == nullptr, OP_LOGE(nodeName, "epWorldSizePtr is null."), return ge::GRAPH_FAILED);
281 OP_TILING_CHECK(epRankIdPtr == nullptr, OP_LOGE(nodeName, "epRankIdPtr is null."), return ge::GRAPH_FAILED);251 OP_TILING_CHECK(epRankIdPtr == nullptr, OP_LOGE(nodeName, "epRankIdPtr is null."), return ge::GRAPH_FAILED);
@@ -283,8 +253,13 @@ static ge::graphStatus CheckAttrParams(const gert::TilingContext *context, const
283 OP_TILING_CHECK(nmtPtr == nullptr, OP_LOGE(nodeName, "nmtPtr is null."), return ge::GRAPH_FAILED);253 OP_TILING_CHECK(nmtPtr == nullptr, OP_LOGE(nodeName, "nmtPtr is null."), return ge::GRAPH_FAILED);
284 OP_TILING_CHECK(cclBufferSizePtr == nullptr, OP_LOGE(nodeName, "cclBufferSizePtr is null."),254 OP_TILING_CHECK(cclBufferSizePtr == nullptr, OP_LOGE(nodeName, "cclBufferSizePtr is null."),
285 return ge::GRAPH_FAILED);255 return ge::GRAPH_FAILED);
256+ OP_TILING_CHECK(topoTypePtr == nullptr, OP_LOGE(nodeName, "topoTypePtr is null."), return ge::GRAPH_FAILED);
257+ OP_TILING_CHECK(rankNumPerServerPtr == nullptr, OP_LOGE(nodeName, "rankNumPerServerPtr is null."),
258+ return ge::GRAPH_FAILED);
286 259 
287 int64_t epWorldSize = *epWorldSizePtr;260 int64_t epWorldSize = *epWorldSizePtr;
261+ int64_t topoType = *topoTypePtr;
262+ int64_t rankNumPerServer = *rankNumPerServerPtr;
288 OP_TILING_CHECK((epWorldSize < MIN_EP_WORLD_SIZE) || (epWorldSize > MAX_EP_WORLD_SIZE),263 OP_TILING_CHECK((epWorldSize < MIN_EP_WORLD_SIZE) || (epWorldSize > MAX_EP_WORLD_SIZE),
289 OP_LOGE(nodeName, "ep_world_size is invalid, should be in [%ld, %ld], but got %ld.",264 OP_LOGE(nodeName, "ep_world_size is invalid, should be in [%ld, %ld], but got %ld.",
290 MIN_EP_WORLD_SIZE, MAX_EP_WORLD_SIZE, epWorldSize),265 MIN_EP_WORLD_SIZE, MAX_EP_WORLD_SIZE, epWorldSize),
@@ -305,12 +280,27 @@ static ge::graphStatus CheckAttrParams(const gert::TilingContext *context, const
305 OP_TILING_CHECK(*cclBufferSizePtr <= 0,280 OP_TILING_CHECK(*cclBufferSizePtr <= 0,
306 OP_LOGE(nodeName, "ccl_buffer_size must be positive, but got %ld.", *cclBufferSizePtr),281 OP_LOGE(nodeName, "ccl_buffer_size must be positive, but got %ld.", *cclBufferSizePtr),
307 return ge::GRAPH_FAILED);282 return ge::GRAPH_FAILED);
283+ OP_TILING_CHECK((topoType != 0) && (topoType != 1),
284+ OP_LOGE(nodeName, "topo_type is invalid, expected 0 or 1, got %ld.", topoType),
285+ return ge::GRAPH_FAILED);
286+ OP_TILING_CHECK(rankNumPerServer <= 0,
287+ OP_LOGE(nodeName, "rank_num_per_server must be positive, got %ld.", rankNumPerServer),
288+ return ge::GRAPH_FAILED);
289+ OP_TILING_CHECK(epWorldSize % rankNumPerServer != 0,
290+ OP_LOGE(nodeName,
291+ "epWorldSize must be divisible by rank_num_per_server, got epWorldSize=%ld, "
292+ "rank_num_per_server=%ld.",
293+ epWorldSize, rankNumPerServer),
294+ return ge::GRAPH_FAILED);
308 295 
309 info.cfg.epWorldSize = static_cast<uint32_t>(epWorldSize);296 info.cfg.epWorldSize = static_cast<uint32_t>(epWorldSize);
310 info.cfg.epRankId = static_cast<uint32_t>(*epRankIdPtr);297 info.cfg.epRankId = static_cast<uint32_t>(*epRankIdPtr);
311 info.cfg.numExperts = static_cast<uint32_t>(*numExpertsPtr);298 info.cfg.numExperts = static_cast<uint32_t>(*numExpertsPtr);
312 info.cfg.numLocalExperts = static_cast<uint32_t>(*numExpertsPtr / epWorldSize);299 info.cfg.numLocalExperts = static_cast<uint32_t>(*numExpertsPtr / epWorldSize);
313 info.cfg.numMaxTokensPerRank = static_cast<uint32_t>(*nmtPtr);300 info.cfg.numMaxTokensPerRank = static_cast<uint32_t>(*nmtPtr);
301+ info.rankSizePerServer = static_cast<uint32_t>(rankNumPerServer);
302+ info.numScaleoutRanks = static_cast<uint32_t>(epWorldSize / rankNumPerServer);
303+ info.networkMode = (topoType == HYBRID_MODE && info.numScaleoutRanks > 1U) ? HYBRID_MODE : DIRECT_MODE;
314 304 
315 return ge::GRAPH_SUCCESS;305 return ge::GRAPH_SUCCESS;
316}306}
@@ -336,19 +326,39 @@ static ge::graphStatus CheckWinSize(const gert::TilingContext *context, MoeEpCom
336 uint64_t hiddenAlign = (info.cfg.hidden * MAX_OUT_DTYPE_SIZE + UB_ALIGN - 1) / UB_ALIGN * UB_ALIGN;326 uint64_t hiddenAlign = (info.cfg.hidden * MAX_OUT_DTYPE_SIZE + UB_ALIGN - 1) / UB_ALIGN * UB_ALIGN;
337 uint64_t topKAlign = (topK * METADATA_DTYPE_SIZE + UB_ALIGN - 1) / UB_ALIGN * UB_ALIGN;327 uint64_t topKAlign = (topK * METADATA_DTYPE_SIZE + UB_ALIGN - 1) / UB_ALIGN * UB_ALIGN;
338 uint64_t dispatchReservedPerSlotBytes = AlignUpWin(hiddenAlign + topKAlign * 2 + UB_ALIGN);328 uint64_t dispatchReservedPerSlotBytes = AlignUpWin(hiddenAlign + topKAlign * 2 + UB_ALIGN);
339- uint64_t dispatchRecvWinDataReservedSize = epWorldSize * nmt * dispatchReservedPerSlotBytes;329+ uint64_t superNodeCount = static_cast<uint64_t>(info.numScaleoutRanks);
330+ uint64_t scaleoutSlotRawBytes = dispatchReservedPerSlotBytes + topK * sizeof(int32_t);
331+ info.scaleoutSlotAlignedBytes = static_cast<uint32_t>(AlignUpWin(scaleoutSlotRawBytes));
340 332 
341- uint64_t stateAndRecvDataWinSize =333+ uint64_t combineDataWinOffset;
342- dispatchWinStateSize + combineWinStateSize + dispatchRecvWinDataReservedSize + combineDataSizePerRank;334+ uint64_t winNeedTotal;
343- uint64_t dispatchSendWinDataReservedSize = dispatchRecvWinDataReservedSize;335+ if (info.networkMode == HYBRID_MODE) {
344- uint64_t winNeedTotal = stateAndRecvDataWinSize + dispatchSendWinDataReservedSize;336+ uint64_t scaleoutRecvDataSize =
337+ superNodeCount * nmt * static_cast<uint64_t>(info.scaleoutSlotAlignedBytes);
338+ uint64_t scaleupFinalRecvDataSize = epWorldSize * nmt * dispatchReservedPerSlotBytes;
339+ uint64_t scaleoutRecvStatusSize = AlignUpWin(superNodeCount * nmt * COMM_ALIGN);
340+ uint64_t scaleoutRecvDataOffset = dispatchWinStateSize + combineWinStateSize;
341+ uint64_t scaleupFinalRecvDataOffset = scaleoutRecvDataOffset + scaleoutRecvDataSize;
342+ uint64_t scaleoutRecvStatusOffset = scaleupFinalRecvDataOffset + scaleupFinalRecvDataSize;
343+ combineDataWinOffset = scaleoutRecvStatusOffset + scaleoutRecvStatusSize;
344+ uint64_t payloadStashWinOffset = combineDataWinOffset + combineDataSizePerRank;
345+ uint64_t payloadStashWinSize = nmt * static_cast<uint64_t>(info.scaleoutSlotAlignedBytes);
346+ winNeedTotal = payloadStashWinOffset + payloadStashWinSize;
347+ } else {
348+ uint64_t dispatchRecvWinDataReservedSize = epWorldSize * nmt * dispatchReservedPerSlotBytes;
349+ uint64_t stateAndRecvDataWinSize =
350+ dispatchWinStateSize + combineWinStateSize + dispatchRecvWinDataReservedSize + combineDataSizePerRank;
351+ uint64_t dispatchSendWinDataReservedSize = dispatchRecvWinDataReservedSize;
352+ combineDataWinOffset = dispatchWinStateSize + combineWinStateSize + dispatchRecvWinDataReservedSize;
353+ winNeedTotal = stateAndRecvDataWinSize + dispatchSendWinDataReservedSize;
354+ }
345 OP_TILING_CHECK(winNeedTotal > maxWindowSize,355 OP_TILING_CHECK(winNeedTotal > maxWindowSize,
346 OP_LOGE(nodeName, "HCCL_BUFFSIZE too small, need %luMB, available %luMB.",356 OP_LOGE(nodeName, "HCCL_BUFFSIZE too small, need %luMB, available %luMB.",
347 (winNeedTotal / MB_SIZE) + 1UL, maxWindowSize / MB_SIZE),357 (winNeedTotal / MB_SIZE) + 1UL, maxWindowSize / MB_SIZE),
348 return ge::GRAPH_FAILED);358 return ge::GRAPH_FAILED);
349 info.totalWinSizeEp = maxWindowSize;359 info.totalWinSizeEp = maxWindowSize;
350 info.combineStateWinOffset = dispatchWinStateSize;360 info.combineStateWinOffset = dispatchWinStateSize;
351- info.combineDataWinOffset = dispatchWinStateSize + combineWinStateSize + dispatchRecvWinDataReservedSize;361+ info.combineDataWinOffset = combineDataWinOffset;
352 info.sendDataWorkspaceSizePerRank = combineDataSizePerRank;362 info.sendDataWorkspaceSizePerRank = combineDataSizePerRank;
353 363 
354 return ge::GRAPH_SUCCESS;364 return ge::GRAPH_SUCCESS;
@@ -30,16 +30,15 @@ using namespace AscendC;
30 30 
31template <uint32_t HasTopkWeight, uint32_t ArchTag>31template <uint32_t HasTopkWeight, uint32_t ArchTag>
32__global__ __aicore__ void moe_ep_combine(GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR recvSrcMetadata,32__global__ __aicore__ void moe_ep_combine(GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR recvSrcMetadata,
33- GM_ADDR numRecvPerExpert, GM_ADDR topkWeights, GM_ADDR bias0, GM_ADDR bias1,33+ GM_ADDR numRecvPerExpert, GM_ADDR topkWeights, GM_ADDR combinedX,
34- GM_ADDR combinedX, GM_ADDR combinedTopkWeightsOptional, GM_ADDR workspace,34+ GM_ADDR combinedTopkWeights, GM_ADDR workspace, GM_ADDR tilingGM)
35- GM_ADDR tilingGM)
36{35{
37 REGISTER_TILING_DEFAULT(MoeEpCombineTilingData);36 REGISTER_TILING_DEFAULT(MoeEpCombineTilingData);
38 REGISTER_TILING_FOR_TILINGKEY("ArchTag == TILINGKEY_TPL_A5", MoeEpCombineTilingData);37 REGISTER_TILING_FOR_TILINGKEY("ArchTag == TILINGKEY_TPL_A5", MoeEpCombineTilingData);
39 TPipe pipe;38 TPipe pipe;
40 GET_TILING_DATA_WITH_STRUCT(MoeEpCombineTilingData, tilingData, tilingGM);39 GET_TILING_DATA_WITH_STRUCT(MoeEpCombineTilingData, tilingData, tilingGM);
41 MoeEpCombine<DTYPE_X, HasTopkWeight> op;40 MoeEpCombine<DTYPE_X, HasTopkWeight> op;
42- op.Init(context, x, topkIdx, recvSrcMetadata, numRecvPerExpert, topkWeights, bias0, bias1, combinedX,41+ op.Init(context, x, topkIdx, recvSrcMetadata, numRecvPerExpert, topkWeights, combinedX, combinedTopkWeights,
43- combinedTopkWeightsOptional, workspace, tilingGM, &pipe, &tilingData.moeEpCombineInfo);42+ workspace, tilingGM, &pipe, &tilingData.moeEpCombineInfo);
44 op.Process();43 op.Process();
45}44}
@@ -66,9 +66,9 @@ public:
66 __aicore__ inline MoeEpCombine(){};66 __aicore__ inline MoeEpCombine(){};
67 67 
68 __aicore__ inline void Init(GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR recvSrcMetadata,68 __aicore__ inline void Init(GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR recvSrcMetadata,
69- GM_ADDR numRecvPerExpert, GM_ADDR topkWeightsOptional, GM_ADDR bias0, GM_ADDR bias1,69+ GM_ADDR numRecvPerExpert, GM_ADDR topkWeights, GM_ADDR combinedX,
70- GM_ADDR combinedX, GM_ADDR combinedTopkWeightsOptional, GM_ADDR workspace,70+ GM_ADDR combinedTopkWeights, GM_ADDR workspace, GM_ADDR tilingGM, TPipe *pipe,
71- GM_ADDR tilingGM, TPipe *pipe, const MoeEpCombineInfo *tilingData);71+ const MoeEpCombineInfo *tilingData);
72 72 
73 __aicore__ inline void Process();73 __aicore__ inline void Process();
74 74 
@@ -152,7 +152,7 @@ private:
152 GlobalTensor<int32_t> topkIdxGm_;152 GlobalTensor<int32_t> topkIdxGm_;
153 GlobalTensor<int32_t> recvSrcMetadataGm_;153 GlobalTensor<int32_t> recvSrcMetadataGm_;
154 GlobalTensor<int64_t> numRecvPerExpertGm_;154 GlobalTensor<int64_t> numRecvPerExpertGm_;
155- GlobalTensor<float> topkWeightsOptionalGm_;155+ GlobalTensor<float> topkWeightsGm_;
156 156 
157 GlobalTensor<XType> combinedXGm_;157 GlobalTensor<XType> combinedXGm_;
158 GlobalTensor<float> combinedTopkWeightsGm_;158 GlobalTensor<float> combinedTopkWeightsGm_;
@@ -196,10 +196,11 @@ private:
196};196};
197 197 
198template <TemplateMoeEpCombineTypeClass>198template <TemplateMoeEpCombineTypeClass>
199-__aicore__ inline void MoeEpCombine<TemplateMoeEpCombineTypeFunc>::Init(199+__aicore__ inline void
200- GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR recvSrcMetadata, GM_ADDR numRecvPerExpert,200+MoeEpCombine<TemplateMoeEpCombineTypeFunc>::Init(GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR recvSrcMetadata,
201- GM_ADDR topkWeightsOptional, GM_ADDR bias0, GM_ADDR bias1, GM_ADDR combinedX, GM_ADDR combinedTopkWeightsOptional,201+ GM_ADDR numRecvPerExpert, GM_ADDR topkWeights, GM_ADDR combinedX,
202- GM_ADDR workspace, GM_ADDR tilingGM, TPipe *pipe, const MoeEpCombineInfo *tilingData)202+ GM_ADDR combinedTopkWeights, GM_ADDR workspace, GM_ADDR tilingGM,
203+ TPipe *pipe, const MoeEpCombineInfo *tilingData)
203{204{
204 tpipe_ = pipe;205 tpipe_ = pipe;
205 tilingData_ = tilingData;206 tilingData_ = tilingData;
@@ -267,8 +268,8 @@ __aicore__ inline void MoeEpCombine<TemplateMoeEpCombineTypeFunc>::Init(
267 XTypeAlign32Size_ = hAlignSize_;268 XTypeAlign32Size_ = hAlignSize_;
268 if constexpr (HasTopkWeight == 1) {269 if constexpr (HasTopkWeight == 1) {
269 XTypeAlign32Size_ = hWeightAlignSize_;270 XTypeAlign32Size_ = hWeightAlignSize_;
270- topkWeightsOptionalGm_.SetGlobalBuffer((__gm__ float *)topkWeightsOptional);271+ topkWeightsGm_.SetGlobalBuffer((__gm__ float *)topkWeights);
271- combinedTopkWeightsGm_.SetGlobalBuffer((__gm__ float *)combinedTopkWeightsOptional);272+ combinedTopkWeightsGm_.SetGlobalBuffer((__gm__ float *)combinedTopkWeights);
272 }273 }
273 tpipe_->InitBuffer(xQueue_, SEND_DOUBLE_BUFFER_NUM, XTypeAlign32Size_);274 tpipe_->InitBuffer(xQueue_, SEND_DOUBLE_BUFFER_NUM, XTypeAlign32Size_);
274 tpipe_->InitBuffer(readStateBuf_, UB_ALIGN); // 32275 tpipe_->InitBuffer(readStateBuf_, UB_ALIGN); // 32
@@ -303,7 +304,7 @@ __aicore__ inline void MoeEpCombine<TemplateMoeEpCombineTypeFunc>::CopyTokenToQu
303 if constexpr (HasTopkWeight == 1) {304 if constexpr (HasTopkWeight == 1) {
304 DataCopyParams weightCopyParams = {1U, static_cast<uint16_t>(sizeof(float)), 0U, 0U};305 DataCopyParams weightCopyParams = {1U, static_cast<uint16_t>(sizeof(float)), 0U, 0U};
305 DataCopyPad(tokenTensor[hAlignSize_ / sizeof(XType)].template ReinterpretCast<float>(),306 DataCopyPad(tokenTensor[hAlignSize_ / sizeof(XType)].template ReinterpretCast<float>(),
306- topkWeightsOptionalGm_[tokenIndex], weightCopyParams, padParams);307+ topkWeightsGm_[tokenIndex], weightCopyParams, padParams);
307 }308 }
308 xQueue_.EnQue(tokenTensor);309 xQueue_.EnQue(tokenTensor);
309}310}
@@ -433,7 +434,9 @@ __aicore__ inline void MoeEpCombine<TemplateMoeEpCombineTypeFunc>::SendPhaseExpe
433 int32_t src_rank = metadataLocal.GetValue(i * RECV_META_FIELDS + 0);434 int32_t src_rank = metadataLocal.GetValue(i * RECV_META_FIELDS + 0);
434 int32_t src_token_idx = metadataLocal.GetValue(i * RECV_META_FIELDS + 1);435 int32_t src_token_idx = metadataLocal.GetValue(i * RECV_META_FIELDS + 1);
435 int32_t src_topK_idx = metadataLocal.GetValue(i * RECV_META_FIELDS + 2);436 int32_t src_topK_idx = metadataLocal.GetValue(i * RECV_META_FIELDS + 2);
436- if (src_rank < 0 || src_rank >= static_cast<int32_t>(epWorldSize_)) {437+ if (src_rank < 0 || src_rank >= static_cast<int32_t>(epWorldSize_) || src_token_idx < 0 ||
438+ src_token_idx >= static_cast<int32_t>(numMaxTokensPerRank_) || src_topK_idx < 0 ||
439+ src_topK_idx >= static_cast<int32_t>(topK_)) {
437 continue;440 continue;
438 }441 }
439 if (splitRankTokens) {442 if (splitRankTokens) {
@@ -34,6 +34,10 @@ struct MoeEpCombineInfo {
34 MoeEpCommonTilingData cfg;34 MoeEpCommonTilingData cfg;
35 uint32_t hasTopkWeights = 0;35 uint32_t hasTopkWeights = 0;
36 uint32_t aivNum = 0;36 uint32_t aivNum = 0;
37+ uint32_t networkMode = 0;
38+ uint32_t rankSizePerServer = 1;
39+ uint32_t numScaleoutRanks = 1;
40+ uint32_t scaleoutSlotAlignedBytes = 0;
37 uint64_t totalWinSizeEp = 0;41 uint64_t totalWinSizeEp = 0;
38 uint64_t totalUbSize = 0;42 uint64_t totalUbSize = 0;
39 uint64_t sendDataWorkspaceSizePerRank = 0; // N * K * actual perSlotBytes43 uint64_t sendDataWorkspaceSizePerRank = 0; // N * K * actual perSlotBytes
@@ -17,9 +17,15 @@
17 17 
18using namespace op;18using namespace op;
19 19 
20+namespace {
21+constexpr int64_t DIRECT_MODE = 0;
22+constexpr int64_t HYBRID_MODE = 1;
23+} // namespace
24+ 
20static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,25static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,
21 aclTensor *numRecvTokensPerRank, aclTensor *numRecvTokensPerExpert,26 aclTensor *numRecvTokensPerRank, aclTensor *numRecvTokensPerExpert,
22- aclTensor *dstBufferSlotIdx)27+ aclTensor *dstBufferSlotIdx, aclTensor *routeCount, aclTensor *routeDstScaleout,
28+ aclTensor *routeScaleoutSlot)
23{29{
24 CHECK_RET(context != nullptr, ACLNN_ERR_PARAM_NULLPTR);30 CHECK_RET(context != nullptr, ACLNN_ERR_PARAM_NULLPTR);
25 CHECK_RET(x != nullptr, ACLNN_ERR_PARAM_NULLPTR);31 CHECK_RET(x != nullptr, ACLNN_ERR_PARAM_NULLPTR);
@@ -27,21 +33,37 @@ static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *x, co
27 CHECK_RET(numRecvTokensPerRank != nullptr, ACLNN_ERR_PARAM_NULLPTR);33 CHECK_RET(numRecvTokensPerRank != nullptr, ACLNN_ERR_PARAM_NULLPTR);
28 CHECK_RET(numRecvTokensPerExpert != nullptr, ACLNN_ERR_PARAM_NULLPTR);34 CHECK_RET(numRecvTokensPerExpert != nullptr, ACLNN_ERR_PARAM_NULLPTR);
29 CHECK_RET(dstBufferSlotIdx != nullptr, ACLNN_ERR_PARAM_NULLPTR);35 CHECK_RET(dstBufferSlotIdx != nullptr, ACLNN_ERR_PARAM_NULLPTR);
36+ CHECK_RET(routeCount != nullptr, ACLNN_ERR_PARAM_NULLPTR);
37+ CHECK_RET(routeDstScaleout != nullptr, ACLNN_ERR_PARAM_NULLPTR);
38+ CHECK_RET(routeScaleoutSlot != nullptr, ACLNN_ERR_PARAM_NULLPTR);
30 return ACLNN_SUCCESS;39 return ACLNN_SUCCESS;
31}40}
32 41 
33static aclnnStatus CheckParams(int64_t epWorldSize, int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,42static aclnnStatus CheckParams(int64_t epWorldSize, int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,
34- int64_t cclBufferSize, int64_t expertAlignment, bool doCpuSync,43+ int64_t cclBufferSize, int64_t expertAlignment, bool doCpuSync, int64_t topoType,
35- const aclTensor *cachedHandleDstBufferSlotIdx)44+ int64_t rankNumPerServer, const aclTensor *cachedDstSlotIdx,
45+ const aclTensor *cachedRouteCount, const aclTensor *cachedRouteDstScaleout,
46+ const aclTensor *cachedRouteScaleoutSlot)
36{47{
37 CHECK_RET(epWorldSize > 1, ACLNN_ERR_PARAM_INVALID);48 CHECK_RET(epWorldSize > 1, ACLNN_ERR_PARAM_INVALID);
38 CHECK_RET(epRankId >= 0 && epRankId < epWorldSize, ACLNN_ERR_PARAM_INVALID);49 CHECK_RET(epRankId >= 0 && epRankId < epWorldSize, ACLNN_ERR_PARAM_INVALID);
39 CHECK_RET(numExperts % epWorldSize == 0, ACLNN_ERR_PARAM_INVALID);50 CHECK_RET(numExperts % epWorldSize == 0, ACLNN_ERR_PARAM_INVALID);
40 CHECK_RET(numMaxTokensPerRank > 0, ACLNN_ERR_PARAM_INVALID);51 CHECK_RET(numMaxTokensPerRank > 0, ACLNN_ERR_PARAM_INVALID);
41 CHECK_RET(cclBufferSize > 0, ACLNN_ERR_PARAM_INVALID);52 CHECK_RET(cclBufferSize > 0, ACLNN_ERR_PARAM_INVALID);
53+ CHECK_RET(topoType == DIRECT_MODE || topoType == HYBRID_MODE, ACLNN_ERR_PARAM_INVALID);
54+ CHECK_RET(rankNumPerServer > 0, ACLNN_ERR_PARAM_INVALID);
55+ CHECK_RET(epWorldSize % rankNumPerServer == 0, ACLNN_ERR_PARAM_INVALID);
42 56 
43- bool cachedMode = (cachedHandleDstBufferSlotIdx != nullptr);57+ bool cachedMode = (cachedDstSlotIdx != nullptr);
44 CHECK_RET(!(cachedMode && doCpuSync), ACLNN_ERR_PARAM_INVALID);58 CHECK_RET(!(cachedMode && doCpuSync), ACLNN_ERR_PARAM_INVALID);
59+ bool anyCachedRoute = cachedRouteCount != nullptr || cachedRouteDstScaleout != nullptr ||
60+ cachedRouteScaleoutSlot != nullptr;
61+ bool allCachedRoute = cachedRouteCount != nullptr && cachedRouteDstScaleout != nullptr &&
62+ cachedRouteScaleoutSlot != nullptr;
63+ CHECK_RET(!anyCachedRoute || allCachedRoute, ACLNN_ERR_PARAM_INVALID);
64+ bool hybridCachedMode =
65+ cachedMode && topoType == HYBRID_MODE && epWorldSize / rankNumPerServer > 1;
66+ CHECK_RET(!hybridCachedMode || allCachedRoute, ACLNN_ERR_PARAM_INVALID);
45 67 
46 return ACLNN_SUCCESS;68 return ACLNN_SUCCESS;
47}69}
@@ -61,26 +83,35 @@ extern "C" void __attribute__((weak)) NnopbaseSetHcclServerType(void *executor,
61 83 
62aclnnStatus aclnnMoeEpDispatchGetWorkspaceSize(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,84aclnnStatus aclnnMoeEpDispatchGetWorkspaceSize(const aclTensor *context, const aclTensor *x, const aclTensor *topkIdx,
63 const aclTensor *topkWeights, const aclTensor *scales,85 const aclTensor *topkWeights, const aclTensor *scales,
64- const aclTensor *cachedHandleDstBufferSlotIdx, int64_t epWorldSize,86+ const aclTensor *cachedDstSlotIdx, const aclTensor *cachedRouteCount,
87+ const aclTensor *cachedRouteDstScaleout,
88+ const aclTensor *cachedRouteScaleoutSlot, int64_t epWorldSize,
65 int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,89 int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,
66 int64_t cclBufferSize, int64_t expertAlignment, bool doCpuSync,90 int64_t cclBufferSize, int64_t expertAlignment, bool doCpuSync,
67- int64_t hostPinnedCounterAddr, aclTensor *numRecvTokensPerRank,91+ int64_t hostPinnedCounterAddr, int64_t topoType,
92+ int64_t rankNumPerServer, aclTensor *numRecvTokensPerRank,
68 aclTensor *numRecvTokensPerExpert, aclTensor *dstBufferSlotIdx,93 aclTensor *numRecvTokensPerExpert, aclTensor *dstBufferSlotIdx,
69- uint64_t *workspaceSize, aclOpExecutor **executor)94+ aclTensor *routeCount, aclTensor *routeDstScaleout,
95+ aclTensor *routeScaleoutSlot, uint64_t *workspaceSize,
96+ aclOpExecutor **executor)
70{97{
71 OP_LOGD("aclnnMoeEpDispatch WorkspaceSize start");98 OP_LOGD("aclnnMoeEpDispatch WorkspaceSize start");
72 99 
73- auto retNotNull = CheckNotNull(context, x, topkIdx, numRecvTokensPerRank, numRecvTokensPerExpert, dstBufferSlotIdx);100+ auto retNotNull = CheckNotNull(context, x, topkIdx, numRecvTokensPerRank, numRecvTokensPerExpert, dstBufferSlotIdx,
101+ routeCount, routeDstScaleout, routeScaleoutSlot);
74 CHECK_RET(retNotNull == ACLNN_SUCCESS, retNotNull);102 CHECK_RET(retNotNull == ACLNN_SUCCESS, retNotNull);
75 103 
76- auto retParams = CheckParams(epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, expertAlignment,104+ auto retParams = CheckParams(epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize,
77- doCpuSync, cachedHandleDstBufferSlotIdx);105+ expertAlignment, doCpuSync, topoType, rankNumPerServer, cachedDstSlotIdx,
106+ cachedRouteCount, cachedRouteDstScaleout, cachedRouteScaleoutSlot);
78 CHECK_RET(retParams == ACLNN_SUCCESS, retParams);107 CHECK_RET(retParams == ACLNN_SUCCESS, retParams);
79 108 
80 aclnnStatus getWorkspaceSizesRes = aclnnInnerMoeEpDispatchGetWorkspaceSize(109 aclnnStatus getWorkspaceSizesRes = aclnnInnerMoeEpDispatchGetWorkspaceSize(
81- context, x, topkIdx, topkWeights, scales, cachedHandleDstBufferSlotIdx, epWorldSize, epRankId, numExperts,110+ context, x, topkIdx, topkWeights, scales, cachedDstSlotIdx, cachedRouteCount, cachedRouteDstScaleout,
82- numMaxTokensPerRank, cclBufferSize, expertAlignment, doCpuSync, hostPinnedCounterAddr, numRecvTokensPerRank,111+ cachedRouteScaleoutSlot, epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize,
83- numRecvTokensPerExpert, dstBufferSlotIdx, workspaceSize, executor);112+ expertAlignment, doCpuSync, hostPinnedCounterAddr, topoType, rankNumPerServer, numRecvTokensPerRank,
113+ numRecvTokensPerExpert, dstBufferSlotIdx, routeCount, routeDstScaleout, routeScaleoutSlot, workspaceSize,
114+ executor);
84 115 
85 return getWorkspaceSizesRes;116 return getWorkspaceSizesRes;
86}117}
@@ -46,7 +46,22 @@ public:
46 .DataTypeList({ge::DT_FLOAT, ge::DT_FLOAT8_E8M0})46 .DataTypeList({ge::DT_FLOAT, ge::DT_FLOAT8_E8M0})
47 .FormatList({ge::FORMAT_ND})47 .FormatList({ge::FORMAT_ND})
48 .AutoContiguous();48 .AutoContiguous();
49- this->Input("cached_handle_dst_buffer_slot_idx")49+ this->Input("cached_dst_slot_idx")
50+ .ParamType(OPTIONAL)
51+ .DataTypeList({ge::DT_INT32})
52+ .FormatList({ge::FORMAT_ND})
53+ .AutoContiguous();
54+ this->Input("cached_route_count")
55+ .ParamType(OPTIONAL)
56+ .DataTypeList({ge::DT_INT32})
57+ .FormatList({ge::FORMAT_ND})
58+ .AutoContiguous();
59+ this->Input("cached_route_dst_scaleout")
60+ .ParamType(OPTIONAL)
61+ .DataTypeList({ge::DT_INT32})
62+ .FormatList({ge::FORMAT_ND})
63+ .AutoContiguous();
64+ this->Input("cached_route_scaleout_slot")
50 .ParamType(OPTIONAL)65 .ParamType(OPTIONAL)
51 .DataTypeList({ge::DT_INT32})66 .DataTypeList({ge::DT_INT32})
52 .FormatList({ge::FORMAT_ND})67 .FormatList({ge::FORMAT_ND})
@@ -64,6 +79,18 @@ public:
64 .ParamType(REQUIRED)79 .ParamType(REQUIRED)
65 .DataTypeList({ge::DT_INT32})80 .DataTypeList({ge::DT_INT32})
66 .FormatList({ge::FORMAT_ND});81 .FormatList({ge::FORMAT_ND});
82+ this->Output("route_count")
83+ .ParamType(REQUIRED)
84+ .DataTypeList({ge::DT_INT32})
85+ .FormatList({ge::FORMAT_ND});
86+ this->Output("route_dst_scaleout")
87+ .ParamType(REQUIRED)
88+ .DataTypeList({ge::DT_INT32})
89+ .FormatList({ge::FORMAT_ND});
90+ this->Output("route_scaleout_slot")
91+ .ParamType(REQUIRED)
92+ .DataTypeList({ge::DT_INT32})
93+ .FormatList({ge::FORMAT_ND});
67 94 
68 this->Attr("ep_world_size").AttrType(REQUIRED).Int();95 this->Attr("ep_world_size").AttrType(REQUIRED).Int();
69 this->Attr("ep_rank_id").AttrType(REQUIRED).Int();96 this->Attr("ep_rank_id").AttrType(REQUIRED).Int();
@@ -73,6 +100,8 @@ public:
73 this->Attr("expert_alignment").AttrType(OPTIONAL).Int(1);100 this->Attr("expert_alignment").AttrType(OPTIONAL).Int(1);
74 this->Attr("do_cpu_sync").AttrType(OPTIONAL).Bool(true);101 this->Attr("do_cpu_sync").AttrType(OPTIONAL).Bool(true);
75 this->Attr("host_pinned_counter_addr").AttrType(OPTIONAL).Int(0);102 this->Attr("host_pinned_counter_addr").AttrType(OPTIONAL).Int(0);
103+ this->Attr("topo_type").AttrType(OPTIONAL).Int(0);
104+ this->Attr("rank_num_per_server").AttrType(OPTIONAL).Int(1);
76 105 
77 OpAICoreConfig aicore_config;106 OpAICoreConfig aicore_config;
78 aicore_config.DynamicCompileStaticFlag(true)107 aicore_config.DynamicCompileStaticFlag(true)
@@ -13,11 +13,10 @@
13 * \brief13 * \brief
14 */14 */
15 15 
16+#include <algorithm>
16#include <cmath>17#include <cmath>
17#include <cstdint>18#include <cstdint>
18#include <cstdio>19#include <cstdio>
19-#include <cstdlib>
20-#include <cstring>
21#include <vector>20#include <vector>
22 21 
23#include "mc2_log.h"22#include "mc2_log.h"
@@ -22,6 +22,7 @@
22#include "moe_ep_dispatch_tiling_key.h"22#include "moe_ep_dispatch_tiling_key.h"
23#include "moe_ep_dispatch_tiling.h"23#include "moe_ep_dispatch_tiling.h"
24#include "moe_ep_dispatch.h"24#include "moe_ep_dispatch.h"
25+#include "moe_ep_dispatch_hybrid.h"
25 26 
26using namespace MoeEpDispatchImpl;27using namespace MoeEpDispatchImpl;
27using namespace Mc2Tiling;28using namespace Mc2Tiling;
@@ -29,9 +30,11 @@ using namespace AscendC;
29 30 
30template <bool DoCpuSync, bool IsCached, bool IsTopkWeights, bool IsMxQuant, uint8_t NetworkMode>31template <bool DoCpuSync, bool IsCached, bool IsTopkWeights, bool IsMxQuant, uint8_t NetworkMode>
31__global__ __aicore__ void moe_ep_dispatch(GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR topkWeights,32__global__ __aicore__ void moe_ep_dispatch(GM_ADDR context, GM_ADDR x, GM_ADDR topkIdx, GM_ADDR topkWeights,
32- GM_ADDR scales, GM_ADDR cachedSlotIdx, GM_ADDR numRecvPerRank,33+ GM_ADDR scales, GM_ADDR cachedSlotIdx, GM_ADDR cachedRouteCount,
33- GM_ADDR numRecvPerExpert, GM_ADDR dstBufferSlotIdx, GM_ADDR workspaceGM,34+ GM_ADDR cachedRouteDstScaleout, GM_ADDR cachedRouteScaleoutSlot,
34- GM_ADDR tilingGM)35+ GM_ADDR numRecvPerRank, GM_ADDR numRecvPerExpert,
36+ GM_ADDR dstBufferSlotIdx, GM_ADDR routeCount, GM_ADDR routeDstScaleout,
37+ GM_ADDR routeScaleoutSlot, GM_ADDR workspaceGM, GM_ADDR tilingGM)
35{38{
36 REGISTER_TILING_DEFAULT(MoeEpDispatchTilingData);39 REGISTER_TILING_DEFAULT(MoeEpDispatchTilingData);
37 40 
@@ -39,8 +42,17 @@ __global__ __aicore__ void moe_ep_dispatch(GM_ADDR context, GM_ADDR x, GM_ADDR t
39 GET_TILING_DATA_WITH_STRUCT(MoeEpDispatchTilingData, tilingData, tilingGM);42 GET_TILING_DATA_WITH_STRUCT(MoeEpDispatchTilingData, tilingData, tilingGM);
40 using ScalesType = typename std::conditional<IsMxQuant, fp8_e8m0_t, float>::type;43 using ScalesType = typename std::conditional<IsMxQuant, fp8_e8m0_t, float>::type;
41 44 
42- MoeEpDispatch<DTYPE_X, ScalesType, DoCpuSync, IsCached, IsTopkWeights, NetworkMode> op;45+ if constexpr (NetworkMode == TILINGKEY_HYBRID) {
43- op.Init(context, x, topkIdx, topkWeights, scales, cachedSlotIdx, numRecvPerRank, numRecvPerExpert, dstBufferSlotIdx,46+ MoeEpDispatchHybridImpl::MoeEpDispatchHybrid<DTYPE_X, ScalesType, DoCpuSync, IsCached, IsTopkWeights,
44- workspaceGM, &pipe, &tilingData);47+ NetworkMode> op;
45- op.Process();48+ op.Init(context, x, topkIdx, topkWeights, scales, cachedSlotIdx, cachedRouteCount, cachedRouteDstScaleout,
49+ cachedRouteScaleoutSlot, numRecvPerRank, numRecvPerExpert, dstBufferSlotIdx, routeCount,
50+ routeDstScaleout, routeScaleoutSlot, workspaceGM, &pipe, &tilingData);
51+ op.Process();
52+ } else {
53+ MoeEpDispatch<DTYPE_X, ScalesType, DoCpuSync, IsCached, IsTopkWeights, NetworkMode> op;
54+ op.Init(context, x, topkIdx, topkWeights, scales, cachedSlotIdx, numRecvPerRank, numRecvPerExpert,
55+ dstBufferSlotIdx, workspaceGM, &pipe, &tilingData);
56+ op.Process();
57+ }
46}58}
@@ -8,19 +8,37 @@
8 * See LICENSE in the root of the software repository for the full text of the License.8 * See LICENSE in the root of the software repository for the full text of the License.
9 */9 */
10 10 
11+/*!
12+ * \file moe_ep_dispatch_base.h
13+ * \brief
14+ */
15+ 
11#ifndef MOE_EP_DISPATCH_BASE_H16#ifndef MOE_EP_DISPATCH_BASE_H
12#define MOE_EP_DISPATCH_BASE_H17#define MOE_EP_DISPATCH_BASE_H
13 18 
14-#if __has_include("../common/mc2_moe_context.h")19+#if ASC_DEVKIT_MAJOR >= 9
15-#include "../common/mc2_moe_context.h"20+#include "basic_api/kernel_basic_intf.h"
16#else21#else
17-#include "../../common/op_kernel/mc2_moe_context.h"22+#include "kernel_operator.h"
18#endif23#endif
19 24 
20-namespace Mc2Kernel {25+#include "adv_api/hcomm/hcomm.h"
26+ 
27+#if __has_include("../common/mc2_moe_context.h")
28+#include "../common/mc2_moe_context.h"
29+#include "../common/mc2_kernel_utils.h"
30+#else
31+#include "../../common/op_kernel/mc2_moe_context.h"
32+#include "../../common/op_kernel/mc2_kernel_utils.h"
33+#endif
34+ 
35+namespace MoeEpDispatchBase {
21 36 
22using namespace AscendC;37using namespace AscendC;
23 38 
39+constexpr uint64_t DISPATCH_CQE_MAX_WRITE_SIZE = 256UL * 1024UL * 1024UL;
40+ 
41+// PerExpertCnt Calculation
24template <Reg::HistogramsType htype, typename T, typename U>42template <Reg::HistogramsType htype, typename T, typename U>
25__simd_vf__ __aicore__ inline void HistogramsVf(__ubuf__ U *dst, __ubuf__ T *src, uint16_t repeatElm,43__simd_vf__ __aicore__ inline void HistogramsVf(__ubuf__ U *dst, __ubuf__ T *src, uint16_t repeatElm,
26 uint16_t halfRepeat, uint32_t totalElm, uint16_t repeatTimes)44 uint16_t halfRepeat, uint32_t totalElm, uint16_t repeatTimes)
@@ -54,15 +72,66 @@ __aicore__ inline void GetExpertFreq(LocalTensor<uint16_t> &dstLocal, LocalTenso
54 PipeBarrier<PIPE_V>();72 PipeBarrier<PIPE_V>();
55}73}
56 74 
57-__aicore__ inline GM_ADDR GetWinAddrByRankId(__gm__ Mc2Aclnn::MoeCommContext *ctx, uint32_t rankId, uint64_t offset)75+__aicore__ inline GM_ADDR GetWindowAddrByRankId(__gm__ Mc2Aclnn::MoeCommContext *context, uint32_t rankId,
76+ uint64_t offset)
58{77{
59- return (GM_ADDR)ctx->epHcclBuffer[rankId] + offset;78+ return (GM_ADDR)context->epHcclBuffer[rankId] + offset;
60}79}
61 80 
62-__aicore__ inline uint64_t GetCommHandle(__gm__ Mc2Aclnn::MoeCommContext *ctx, uint32_t rankId)81+__aicore__ inline uint64_t GetCommHandle(__gm__ Mc2Aclnn::MoeCommContext *context, uint32_t rankId,
82+ uint32_t channelIndex = 0U)
63{83{
64- uint32_t channelsPerRank = ctx->channelsPerRank == 0 ? 1 : ctx->channelsPerRank;84+ uint32_t channelsPerRank = context->channelsPerRank == 0U ? 1U : context->channelsPerRank;
65- return ctx->hcommHandle[rankId * channelsPerRank];85+ return context->hcommHandle[rankId * channelsPerRank + channelIndex];
86+}
87+ 
88+// For Hybrid
89+__aicore__ inline uint32_t GetCurrentServerIndex(uint32_t epRankId, uint32_t rankSizePerServer)
90+{
91+ return rankSizePerServer == 0U ? 0U : epRankId / rankSizePerServer;
92+}
93+ 
94+__aicore__ inline uint32_t GetServerStartRank(uint32_t epRankId, uint32_t rankSizePerServer)
95+{
96+ return GetCurrentServerIndex(epRankId, rankSizePerServer) * rankSizePerServer;
97+}
98+ 
99+__aicore__ inline uint32_t GetServerEndRank(uint32_t epRankId, uint32_t rankSizePerServer, uint32_t epWorldSize)
100+{
101+ uint32_t serverEndRank = GetServerStartRank(epRankId, rankSizePerServer) + rankSizePerServer;
102+ return serverEndRank > epWorldSize ? epWorldSize : serverEndRank;
103+}
104+ 
105+template <typename HcommType>
106+__aicore__ inline void WriteRemoteWindowByChunks(HcommType &hcomm, uint64_t commHandle, GM_ADDR remoteWindowAddr,
107+ GM_ADDR localWorkspaceAddr, uint64_t sendBytes)
108+{
109+ // HCCL单次写有CQE大小限制,保持原分片写逻辑
110+ uint64_t splitCount = (sendBytes + DISPATCH_CQE_MAX_WRITE_SIZE - 1UL) / DISPATCH_CQE_MAX_WRITE_SIZE;
111+ uint64_t dataBytes = DISPATCH_CQE_MAX_WRITE_SIZE;
112+ for (uint64_t splitIndex = 0UL; splitIndex < splitCount; splitIndex++) {
113+ if (splitIndex == splitCount - 1UL) {
114+ dataBytes = sendBytes - splitIndex * DISPATCH_CQE_MAX_WRITE_SIZE;
115+ }
116+ hcomm.WriteNbi(commHandle, remoteWindowAddr, localWorkspaceAddr, dataBytes);
117+ localWorkspaceAddr += dataBytes;
118+ remoteWindowAddr += dataBytes;
119+ }
120+ hcomm.Drain(commHandle);
121+}
122+ 
123+ 
124+} // namespace MoeEpDispatchBase
125+ 
126+namespace Mc2Kernel {
127+ 
128+using MoeEpDispatchBase::GetCommHandle;
129+using MoeEpDispatchBase::GetExpertFreq;
130+ 
131+__aicore__ inline GM_ADDR GetWinAddrByRankId(__gm__ Mc2Aclnn::MoeCommContext *context, uint32_t rankId,
132+ uint64_t offset)
133+{
134+ return MoeEpDispatchBase::GetWindowAddrByRankId(context, rankId, offset);
66}135}
67 136 
68} // namespace Mc2Kernel137} // namespace Mc2Kernel
@@ -19,6 +19,8 @@
19#include <cstdint>19#include <cstdint>
20#include "kernel_tiling/kernel_tiling.h"20#include "kernel_tiling/kernel_tiling.h"
21 21 
22+constexpr uint32_t MOE_EP_SEND_ENTRY_BYTES = 2U * sizeof(uint32_t); // source slot和destination slot
23+ 
22struct MoeEpCommonTilingData {24struct MoeEpCommonTilingData {
23 uint32_t epWorldSize;25 uint32_t epWorldSize;
24 uint32_t epRankId;26 uint32_t epRankId;
@@ -40,16 +42,31 @@ struct MoeEpDispatchInfo {
40 uint32_t isTopkWeights;42 uint32_t isTopkWeights;
41 uint32_t isMxQuant;43 uint32_t isMxQuant;
42 uint32_t networkMode;44 uint32_t networkMode;
45+ uint32_t rankSizePerServer; // 单超节点内rank数
43 uint32_t numScaleupRanks;46 uint32_t numScaleupRanks;
44 uint32_t numScaleoutRanks;47 uint32_t numScaleoutRanks;
45 uint32_t numAivStage1;48 uint32_t numAivStage1;
46 uint32_t numAivStage2;49 uint32_t numAivStage2;
47 uint32_t aivNum;50 uint32_t aivNum;
51+ uint32_t scaleoutSlotAlignedBytes; // scaleout 数据和转发元信息 slot 字节数
52+ uint32_t fanoutCountCoreBytes; // 单个 fanout 生产核的计数区字节数
53+ uint64_t sendEntryTokenRangeBytes; // 单个 token 范围的发送记录字节数
54+ uint64_t fanoutSendEntryCoreBytes; // 单个 fanout 生产核的发送记录字节数
48 uint64_t hostPinnedCounterAddr;55 uint64_t hostPinnedCounterAddr;
56+ uint64_t routeWorkspaceOffset;
57+ uint64_t scaleoutSendEntryOffset;
58+ uint64_t scaleupSendEntryOffset;
59+ uint64_t fanoutSendEntryOffset;
60+ uint64_t fanoutCountOffset;
49 uint64_t cntWinStateOffset;61 uint64_t cntWinStateOffset;
50 uint64_t slotWinStateOffset;62 uint64_t slotWinStateOffset;
51 uint64_t winDataOffset;63 uint64_t winDataOffset;
52 uint64_t dispatchSendWinOffset;64 uint64_t dispatchSendWinOffset;
65+ uint64_t scaleoutRecvDataOffset;
66+ uint64_t scaleupFinalRecvDataOffset;
67+ uint64_t scaleoutRecvStatusOffset;
68+ uint64_t combineDataOffset;
69+ uint64_t payloadStashWinOffset;
53 uint64_t totalWinSizeEp;70 uint64_t totalWinSizeEp;
54 uint64_t totalUbSize;71 uint64_t totalUbSize;
55};72};
@@ -17,9 +17,15 @@
17 17 
18using namespace op;18using namespace op;
19 19 
20+namespace {
21+constexpr int64_t DIRECT_MODE = 0;
22+constexpr int64_t HYBRID_MODE = 1;
23+} // namespace
24+ 
20static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *dstBufferSlotIdx,25static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *dstBufferSlotIdx,
21 const aclTensor *numRecvTokensPerRank, const aclTensor *numRecvTokensPerExpert,26 const aclTensor *numRecvTokensPerRank, const aclTensor *numRecvTokensPerExpert,
22- aclTensor *recvX, aclTensor *recvSrcMetadata)27+ aclTensor *recvX, aclTensor *recvSrcMetadata, aclTensor *recvTopkWeights,
28+ aclTensor *recvScales)
23{29{
24 CHECK_RET(context != nullptr, ACLNN_ERR_PARAM_NULLPTR);30 CHECK_RET(context != nullptr, ACLNN_ERR_PARAM_NULLPTR);
25 CHECK_RET(dstBufferSlotIdx != nullptr, ACLNN_ERR_PARAM_NULLPTR);31 CHECK_RET(dstBufferSlotIdx != nullptr, ACLNN_ERR_PARAM_NULLPTR);
@@ -27,18 +33,22 @@ static aclnnStatus CheckNotNull(const aclTensor *context, const aclTensor *dstBu
27 CHECK_RET(numRecvTokensPerExpert != nullptr, ACLNN_ERR_PARAM_NULLPTR);33 CHECK_RET(numRecvTokensPerExpert != nullptr, ACLNN_ERR_PARAM_NULLPTR);
28 CHECK_RET(recvX != nullptr, ACLNN_ERR_PARAM_NULLPTR);34 CHECK_RET(recvX != nullptr, ACLNN_ERR_PARAM_NULLPTR);
29 CHECK_RET(recvSrcMetadata != nullptr, ACLNN_ERR_PARAM_NULLPTR);35 CHECK_RET(recvSrcMetadata != nullptr, ACLNN_ERR_PARAM_NULLPTR);
36+ CHECK_RET(recvTopkWeights != nullptr, ACLNN_ERR_PARAM_NULLPTR);
37+ CHECK_RET(recvScales != nullptr, ACLNN_ERR_PARAM_NULLPTR);
30 return ACLNN_SUCCESS;38 return ACLNN_SUCCESS;
31}39}
32 40 
33static aclnnStatus CheckParams(int64_t epWorldSize, int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,41static aclnnStatus CheckParams(int64_t epWorldSize, int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,
34- int64_t cclBufferSize, int64_t expertAlignment)42+ int64_t cclBufferSize, int64_t topoType, int64_t rankNumPerServer)
35{43{
36 CHECK_RET(epWorldSize > 1, ACLNN_ERR_PARAM_INVALID);44 CHECK_RET(epWorldSize > 1, ACLNN_ERR_PARAM_INVALID);
37 CHECK_RET(epRankId >= 0 && epRankId < epWorldSize, ACLNN_ERR_PARAM_INVALID);45 CHECK_RET(epRankId >= 0 && epRankId < epWorldSize, ACLNN_ERR_PARAM_INVALID);
38 CHECK_RET(numExperts % epWorldSize == 0, ACLNN_ERR_PARAM_INVALID);46 CHECK_RET(numExperts % epWorldSize == 0, ACLNN_ERR_PARAM_INVALID);
39 CHECK_RET(numMaxTokensPerRank > 0, ACLNN_ERR_PARAM_INVALID);47 CHECK_RET(numMaxTokensPerRank > 0, ACLNN_ERR_PARAM_INVALID);
40 CHECK_RET(cclBufferSize > 0, ACLNN_ERR_PARAM_INVALID);48 CHECK_RET(cclBufferSize > 0, ACLNN_ERR_PARAM_INVALID);
41- CHECK_RET(expertAlignment == 1, ACLNN_ERR_PARAM_INVALID);49+ CHECK_RET(topoType == DIRECT_MODE || topoType == HYBRID_MODE, ACLNN_ERR_PARAM_INVALID);
50+ CHECK_RET(rankNumPerServer > 0, ACLNN_ERR_PARAM_INVALID);
51+ CHECK_RET(epWorldSize % rankNumPerServer == 0, ACLNN_ERR_PARAM_INVALID);
42 return ACLNN_SUCCESS;52 return ACLNN_SUCCESS;
43}53}
44#ifdef __cplusplus54#ifdef __cplusplus
@@ -47,36 +57,39 @@ extern "C" {
47aclnnStatus MoeEpDispatchEpilogueGetWorkspaceSize(57aclnnStatus MoeEpDispatchEpilogueGetWorkspaceSize(
48 const aclTensor *context, const aclTensor *dstBufferSlotIdx, const aclTensor *numRecvTokensPerRank,58 const aclTensor *context, const aclTensor *dstBufferSlotIdx, const aclTensor *numRecvTokensPerRank,
49 const aclTensor *numRecvTokensPerExpert, const aclTensor *cachedRecvSrcMetadata, int64_t epWorldSize,59 const aclTensor *numRecvTokensPerExpert, const aclTensor *cachedRecvSrcMetadata, int64_t epWorldSize,
50- int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize, int64_t expertAlignment,60+ int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize, bool hasTopkWeights,
51- aclTensor *recvX, aclTensor *recvSrcMetadata, aclTensor *recvTopkWeights, aclTensor *recvScales,61+ int64_t topoType, int64_t rankNumPerServer, aclTensor *recvX, aclTensor *recvSrcMetadata,
52- uint64_t *workspaceSize, aclOpExecutor **executor)62+ aclTensor *recvTopkWeights, aclTensor *recvScales, uint64_t *workspaceSize, aclOpExecutor **executor)
53{63{
54 OP_LOGD("MoeEpDispatchEpilogue", "Begin to do MoeEpDispatchEpilogueGetWorkspaceSize");64 OP_LOGD("MoeEpDispatchEpilogue", "Begin to do MoeEpDispatchEpilogueGetWorkspaceSize");
55 auto retNotNull =65 auto retNotNull =
56- CheckNotNull(context, dstBufferSlotIdx, numRecvTokensPerRank, numRecvTokensPerExpert, recvX, recvSrcMetadata);66+ CheckNotNull(context, dstBufferSlotIdx, numRecvTokensPerRank, numRecvTokensPerExpert, recvX, recvSrcMetadata,
67+ recvTopkWeights, recvScales);
57 CHECK_RET(retNotNull == ACLNN_SUCCESS, retNotNull);68 CHECK_RET(retNotNull == ACLNN_SUCCESS, retNotNull);
58 69 
59 auto retParams =70 auto retParams =
60- CheckParams(epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, expertAlignment);71+ CheckParams(epWorldSize, epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, topoType,
72+ rankNumPerServer);
61 CHECK_RET(retParams == ACLNN_SUCCESS, retParams);73 CHECK_RET(retParams == ACLNN_SUCCESS, retParams);
62 74 
63 return aclnnInnerMoeEpDispatchEpilogueGetWorkspaceSize(75 return aclnnInnerMoeEpDispatchEpilogueGetWorkspaceSize(
64 context, dstBufferSlotIdx, numRecvTokensPerRank, numRecvTokensPerExpert, cachedRecvSrcMetadata, epWorldSize,76 context, dstBufferSlotIdx, numRecvTokensPerRank, numRecvTokensPerExpert, cachedRecvSrcMetadata, epWorldSize,
65- epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, expertAlignment, recvX, recvSrcMetadata,77+ epRankId, numExperts, numMaxTokensPerRank, cclBufferSize, hasTopkWeights, topoType, rankNumPerServer, recvX,
66- recvTopkWeights, recvScales, workspaceSize, executor);78+ recvSrcMetadata, recvTopkWeights, recvScales, workspaceSize, executor);
67}79}
68 80 
69aclnnStatus aclnnMoeEpDispatchEpilogueGetWorkspaceSize(81aclnnStatus aclnnMoeEpDispatchEpilogueGetWorkspaceSize(
70 const aclTensor *context, const aclTensor *dstBufferSlotIdx, const aclTensor *numRecvTokensPerRank,82 const aclTensor *context, const aclTensor *dstBufferSlotIdx, const aclTensor *numRecvTokensPerRank,
71 const aclTensor *numRecvTokensPerExpert, const aclTensor *cachedRecvSrcMetadata, int64_t epWorldSize,83 const aclTensor *numRecvTokensPerExpert, const aclTensor *cachedRecvSrcMetadata, int64_t epWorldSize,
72- int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize, int64_t expertAlignment,84+ int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank, int64_t cclBufferSize, bool hasTopkWeights,
73- aclTensor *recvX, aclTensor *recvSrcMetadata, aclTensor *recvTopkWeights, aclTensor *recvScales,85+ int64_t topoType, int64_t rankNumPerServer, aclTensor *recvX, aclTensor *recvSrcMetadata,
74- uint64_t *workspaceSize, aclOpExecutor **executor)86+ aclTensor *recvTopkWeights, aclTensor *recvScales, uint64_t *workspaceSize, aclOpExecutor **executor)
75{87{
76 return MoeEpDispatchEpilogueGetWorkspaceSize(context, dstBufferSlotIdx, numRecvTokensPerRank,88 return MoeEpDispatchEpilogueGetWorkspaceSize(context, dstBufferSlotIdx, numRecvTokensPerRank,
77 numRecvTokensPerExpert, cachedRecvSrcMetadata, epWorldSize, epRankId,89 numRecvTokensPerExpert, cachedRecvSrcMetadata, epWorldSize, epRankId,
78- numExperts, numMaxTokensPerRank, cclBufferSize, expertAlignment, recvX,90+ numExperts, numMaxTokensPerRank, cclBufferSize, hasTopkWeights,
79- recvSrcMetadata, recvTopkWeights, recvScales, workspaceSize, executor);91+ topoType, rankNumPerServer, recvX, recvSrcMetadata, recvTopkWeights,
92+ recvScales, workspaceSize, executor);
80}93}
81 94 
82enum NnopbaseHcclServerType {95enum NnopbaseHcclServerType {
@@ -47,9 +47,9 @@ public:
47 .DataTypeList({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN})47 .DataTypeList({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN})
48 .FormatList({ge::FORMAT_ND});48 .FormatList({ge::FORMAT_ND});
49 this->Output("recv_src_metadata").ParamType(REQUIRED).DataTypeList({ge::DT_INT32}).FormatList({ge::FORMAT_ND});49 this->Output("recv_src_metadata").ParamType(REQUIRED).DataTypeList({ge::DT_INT32}).FormatList({ge::FORMAT_ND});
50- this->Output("recv_topk_weights").ParamType(OPTIONAL).DataTypeList({ge::DT_FLOAT}).FormatList({ge::FORMAT_ND});50+ this->Output("recv_topk_weights").ParamType(REQUIRED).DataTypeList({ge::DT_FLOAT}).FormatList({ge::FORMAT_ND});
51 this->Output("recv_scales")51 this->Output("recv_scales")
52- .ParamType(OPTIONAL)52+ .ParamType(REQUIRED)
53 .DataTypeList({ge::DT_FLOAT, ge::DT_FLOAT8_E8M0})53 .DataTypeList({ge::DT_FLOAT, ge::DT_FLOAT8_E8M0})
54 .FormatList({ge::FORMAT_ND});54 .FormatList({ge::FORMAT_ND});
55 55 
@@ -58,7 +58,9 @@ public:
58 this->Attr("num_experts").AttrType(REQUIRED).Int();58 this->Attr("num_experts").AttrType(REQUIRED).Int();
59 this->Attr("num_max_tokens_per_rank").AttrType(REQUIRED).Int();59 this->Attr("num_max_tokens_per_rank").AttrType(REQUIRED).Int();
60 this->Attr("ccl_buffer_size").AttrType(REQUIRED).Int();60 this->Attr("ccl_buffer_size").AttrType(REQUIRED).Int();
61- this->Attr("expert_alignment").AttrType(OPTIONAL).Int(1);61+ this->Attr("has_topk_weights").AttrType(OPTIONAL).Bool(true);
62+ this->Attr("topo_type").AttrType(OPTIONAL).Int(0);
63+ this->Attr("rank_num_per_server").AttrType(OPTIONAL).Int(1);
62 64 
63 OpAICoreConfig aicore_config;65 OpAICoreConfig aicore_config;
64 aicore_config.DynamicCompileStaticFlag(true)66 aicore_config.DynamicCompileStaticFlag(true)
@@ -17,8 +17,6 @@
17#include <cmath>17#include <cmath>
18#include <cstdint>18#include <cstdint>
19#include <cstdio>19#include <cstdio>
20-#include <cstdlib>
21-#include <cstring>
22 20 
23#include "mc2_log.h"21#include "mc2_log.h"
24#include "graph/utils/type_utils.h"22#include "graph/utils/type_utils.h"
@@ -55,14 +53,16 @@ constexpr uint32_t ATTR_EP_RANK_ID_INDEX = 1;
55constexpr uint32_t ATTR_NUM_EXPERTS_INDEX = 2;53constexpr uint32_t ATTR_NUM_EXPERTS_INDEX = 2;
56constexpr uint32_t ATTR_NUM_MAX_TPR_INDEX = 3;54constexpr uint32_t ATTR_NUM_MAX_TPR_INDEX = 3;
57constexpr uint32_t ATTR_CCL_BUFFER_SIZE_INDEX = 4;55constexpr uint32_t ATTR_CCL_BUFFER_SIZE_INDEX = 4;
58-constexpr uint32_t ATTR_EXPERT_ALIGNMENT_INDEX = 5;56+constexpr uint32_t ATTR_HAS_TOPK_WEIGHTS_INDEX = 5;
57+constexpr uint32_t ATTR_TOPO_TYPE_INDEX = 6;
58+constexpr uint32_t ATTR_RANK_NUM_PER_SERVER_INDEX = 7;
59 59 
60constexpr uint32_t ONE_DIM = 1U;60constexpr uint32_t ONE_DIM = 1U;
61constexpr uint32_t TWO_DIMS = 2U;61constexpr uint32_t TWO_DIMS = 2U;
62constexpr int64_t META_INNER_DIM = 4; // recvSrcMetadata dim(1) = 462constexpr int64_t META_INNER_DIM = 4; // recvSrcMetadata dim(1) = 4
63constexpr uint32_t SYSTEM_NEED_WORKSPACE = 16U * 1024U * 1024U;63constexpr uint32_t SYSTEM_NEED_WORKSPACE = 16U * 1024U * 1024U;
64constexpr uint64_t WIN_ADDR_ALIGN = 512UL;64constexpr uint64_t WIN_ADDR_ALIGN = 512UL;
65-constexpr int64_t MAX_EP_WORLD_SIZE = 128;65+constexpr int64_t MAX_EP_WORLD_SIZE = 1024;
66constexpr int64_t MIN_EP_WORLD_SIZE = 2;66constexpr int64_t MIN_EP_WORLD_SIZE = 2;
67constexpr int64_t MAX_NUM_EXPERTS = 2048;67constexpr int64_t MAX_NUM_EXPERTS = 2048;
68constexpr int64_t MIN_NUM_EXPERTS = 2;68constexpr int64_t MIN_NUM_EXPERTS = 2;
@@ -76,6 +76,8 @@ constexpr uint64_t METADATA_DTYPE_SIZE = 4UL; // sizeof(int32)=sizeof(float)=4
76constexpr int64_t SCALES_GROUP_SIZE_MXFP = 32;76constexpr int64_t SCALES_GROUP_SIZE_MXFP = 32;
77constexpr int64_t SCALES_GROUP_SIZE_PERGROUP = 128;77constexpr int64_t SCALES_GROUP_SIZE_PERGROUP = 128;
78constexpr int64_t SCALES_ALIGN_EVEN = 2; // fp8 align 278constexpr int64_t SCALES_ALIGN_EVEN = 2; // fp8 align 2
79+constexpr uint32_t DIRECT_MODE = 0U;
80+constexpr uint32_t HYBRID_MODE = 1U;
79 81 
80static void PrintTilingDataInfo(const char *nodeName, const MoeEpDispatchEpilogueInfo &info)82static void PrintTilingDataInfo(const char *nodeName, const MoeEpDispatchEpilogueInfo &info)
81{83{
@@ -100,7 +102,8 @@ static ge::graphStatus CheckAttrParams(const gert::TilingContext *context, const
100 auto numExpertsPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_EXPERTS_INDEX);102 auto numExpertsPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_EXPERTS_INDEX);
101 auto nmtPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_MAX_TPR_INDEX);103 auto nmtPtr = attrs->GetAttrPointer<int64_t>(ATTR_NUM_MAX_TPR_INDEX);
102 auto cclBufferSizePtr = attrs->GetAttrPointer<int64_t>(ATTR_CCL_BUFFER_SIZE_INDEX);104 auto cclBufferSizePtr = attrs->GetAttrPointer<int64_t>(ATTR_CCL_BUFFER_SIZE_INDEX);
103- auto expertAlignmentPtr = attrs->GetAttrPointer<int64_t>(ATTR_EXPERT_ALIGNMENT_INDEX);105+ auto topoTypePtr = attrs->GetAttrPointer<int64_t>(ATTR_TOPO_TYPE_INDEX);
106+ auto rankNumPerServerPtr = attrs->GetAttrPointer<int64_t>(ATTR_RANK_NUM_PER_SERVER_INDEX);
104 107 
105 OP_TILING_CHECK(epWorldSizePtr == nullptr, OP_LOGE(nodeName, "epWorldSizePtr is null."), return ge::GRAPH_FAILED);108 OP_TILING_CHECK(epWorldSizePtr == nullptr, OP_LOGE(nodeName, "epWorldSizePtr is null."), return ge::GRAPH_FAILED);
106 OP_TILING_CHECK(epRankIdPtr == nullptr, OP_LOGE(nodeName, "epRankIdPtr is null."), return ge::GRAPH_FAILED);109 OP_TILING_CHECK(epRankIdPtr == nullptr, OP_LOGE(nodeName, "epRankIdPtr is null."), return ge::GRAPH_FAILED);
@@ -108,10 +111,13 @@ static ge::graphStatus CheckAttrParams(const gert::TilingContext *context, const
108 OP_TILING_CHECK(nmtPtr == nullptr, OP_LOGE(nodeName, "nmtPtr is null."), return ge::GRAPH_FAILED);111 OP_TILING_CHECK(nmtPtr == nullptr, OP_LOGE(nodeName, "nmtPtr is null."), return ge::GRAPH_FAILED);
109 OP_TILING_CHECK(cclBufferSizePtr == nullptr, OP_LOGE(nodeName, "cclBufferSizePtr is null."),112 OP_TILING_CHECK(cclBufferSizePtr == nullptr, OP_LOGE(nodeName, "cclBufferSizePtr is null."),
110 return ge::GRAPH_FAILED);113 return ge::GRAPH_FAILED);
111- OP_TILING_CHECK(expertAlignmentPtr == nullptr, OP_LOGE(nodeName, "expertAlignmentPtr is null."),114+ OP_TILING_CHECK(topoTypePtr == nullptr, OP_LOGE(nodeName, "topoTypePtr is null."), return ge::GRAPH_FAILED);
115+ OP_TILING_CHECK(rankNumPerServerPtr == nullptr, OP_LOGE(nodeName, "rankNumPerServerPtr is null."),
112 return ge::GRAPH_FAILED);116 return ge::GRAPH_FAILED);
113 117 
114 int64_t epWorldSize = *epWorldSizePtr;118 int64_t epWorldSize = *epWorldSizePtr;
119+ int64_t topoType = *topoTypePtr;
120+ int64_t rankNumPerServer = *rankNumPerServerPtr;
115 OP_TILING_CHECK((epWorldSize < MIN_EP_WORLD_SIZE) || (epWorldSize > MAX_EP_WORLD_SIZE),121 OP_TILING_CHECK((epWorldSize < MIN_EP_WORLD_SIZE) || (epWorldSize > MAX_EP_WORLD_SIZE),
116 OP_LOGE(nodeName, "ep_world_size is invalid, should be in [%ld, %ld], but got %ld.",122 OP_LOGE(nodeName, "ep_world_size is invalid, should be in [%ld, %ld], but got %ld.",
117 MIN_EP_WORLD_SIZE, MAX_EP_WORLD_SIZE, epWorldSize),123 MIN_EP_WORLD_SIZE, MAX_EP_WORLD_SIZE, epWorldSize),
@@ -132,8 +138,17 @@ static ge::graphStatus CheckAttrParams(const gert::TilingContext *context, const
132 OP_TILING_CHECK(*cclBufferSizePtr <= 0,138 OP_TILING_CHECK(*cclBufferSizePtr <= 0,
133 OP_LOGE(nodeName, "ccl_buffer_size must be positive, but got %ld.", *cclBufferSizePtr),139 OP_LOGE(nodeName, "ccl_buffer_size must be positive, but got %ld.", *cclBufferSizePtr),
134 return ge::GRAPH_FAILED);140 return ge::GRAPH_FAILED);
135- OP_TILING_CHECK(*expertAlignmentPtr != 1,141+ OP_TILING_CHECK((topoType != DIRECT_MODE) && (topoType != HYBRID_MODE),
136- OP_LOGE(nodeName, "expert_alignment must be 1, but got %ld.", *expertAlignmentPtr),142+ OP_LOGE(nodeName, "topo_type is invalid, expected 0 or 1, got %ld.", topoType),
143+ return ge::GRAPH_FAILED);
144+ OP_TILING_CHECK(rankNumPerServer <= 0,
145+ OP_LOGE(nodeName, "rank_num_per_server must be positive, got %ld.", rankNumPerServer),
146+ return ge::GRAPH_FAILED);
147+ OP_TILING_CHECK(epWorldSize % rankNumPerServer != 0,
148+ OP_LOGE(nodeName,
149+ "epWorldSize must be divisible by rank_num_per_server, got epWorldSize=%ld, "
150+ "rank_num_per_server=%ld.",
151+ epWorldSize, rankNumPerServer),
137 return ge::GRAPH_FAILED);152 return ge::GRAPH_FAILED);
138 153 
139 info.cfg.epWorldSize = static_cast<uint32_t>(epWorldSize);154 info.cfg.epWorldSize = static_cast<uint32_t>(epWorldSize);
@@ -141,7 +156,9 @@ static ge::graphStatus CheckAttrParams(const gert::TilingContext *context, const
141 info.cfg.numExperts = static_cast<uint32_t>(*numExpertsPtr);156 info.cfg.numExperts = static_cast<uint32_t>(*numExpertsPtr);
142 info.cfg.numLocalExperts = static_cast<uint32_t>(*numExpertsPtr / epWorldSize);157 info.cfg.numLocalExperts = static_cast<uint32_t>(*numExpertsPtr / epWorldSize);
143 info.cfg.numMaxTokensPerRank = static_cast<uint32_t>(*nmtPtr);158 info.cfg.numMaxTokensPerRank = static_cast<uint32_t>(*nmtPtr);
144- info.cfg.expertAlignment = static_cast<uint32_t>(*expertAlignmentPtr);159+ info.rankSizePerServer = static_cast<uint32_t>(rankNumPerServer);
160+ info.numScaleoutRanks = static_cast<uint32_t>(epWorldSize / rankNumPerServer);
161+ info.networkMode = (topoType == HYBRID_MODE && info.numScaleoutRanks > 1U) ? HYBRID_MODE : DIRECT_MODE;
145 162 
146 return ge::GRAPH_SUCCESS;163 return ge::GRAPH_SUCCESS;
147}164}
@@ -319,7 +336,7 @@ static ge::graphStatus CheckRecvScalesTensor(const gert::TilingContext *context,
319}336}
320 337 
321static ge::graphStatus CheckOutputTensors(const gert::TilingContext *context, const char *nodeName,338static ge::graphStatus CheckOutputTensors(const gert::TilingContext *context, const char *nodeName,
322- MoeEpDispatchEpilogueInfo &info, int64_t topK)339+ MoeEpDispatchEpilogueInfo &info, int64_t topK, bool hasTopkWeights)
323{340{
324 // ---- recvX [A_alloc, hidden] bf16/fp16 ----341 // ---- recvX [A_alloc, hidden] bf16/fp16 ----
325 auto recvXShape = context->GetOutputShape(OUT_RECV_X_INDEX);342 auto recvXShape = context->GetOutputShape(OUT_RECV_X_INDEX);
@@ -356,9 +373,10 @@ static ge::graphStatus CheckOutputTensors(const gert::TilingContext *context, co
356 OP_TILING_CHECK(CheckRecvScalesTensor(context, nodeName, recvXDtype, aAlloc, hidden, info) != ge::GRAPH_SUCCESS,373 OP_TILING_CHECK(CheckRecvScalesTensor(context, nodeName, recvXDtype, aAlloc, hidden, info) != ge::GRAPH_SUCCESS,
357 OP_LOGE(nodeName, "Check recvScales tensor failed."), return ge::GRAPH_FAILED);374 OP_LOGE(nodeName, "Check recvScales tensor failed."), return ge::GRAPH_FAILED);
358 375 
359- // ---- recvTopkWeights [A_alloc] float (OPTIONAL) ----376+ // ---- recvTopkWeights [A_alloc] float when topk weights are enabled ----
360 auto recvTopkWeightsShape = context->GetOutputShape(OUT_RECV_TOPK_WEIGHTS_INDEX);377 auto recvTopkWeightsShape = context->GetOutputShape(OUT_RECV_TOPK_WEIGHTS_INDEX);
361- if (recvTopkWeightsShape != nullptr) {378+ if (hasTopkWeights) {
379+ OP_CHECK_NULL_WITH_CONTEXT(context, recvTopkWeightsShape);
362 OP_TILING_CHECK(recvTopkWeightsShape->GetStorageShape().GetDimNum() != ONE_DIM,380 OP_TILING_CHECK(recvTopkWeightsShape->GetStorageShape().GetDimNum() != ONE_DIM,
363 OP_LOGE(nodeName, "recv_topk_weights dims must be 1, but got %lu.",381 OP_LOGE(nodeName, "recv_topk_weights dims must be 1, but got %lu.",
364 recvTopkWeightsShape->GetStorageShape().GetDimNum()),382 recvTopkWeightsShape->GetStorageShape().GetDimNum()),
@@ -418,31 +436,52 @@ static ge::graphStatus CheckWinSize(const gert::TilingContext *context, const ch
418 uint64_t maxWindowSize = static_cast<uint64_t>(*cclBufferSizePtr);436 uint64_t maxWindowSize = static_cast<uint64_t>(*cclBufferSizePtr);
419 uint64_t epWorldSize = static_cast<uint64_t>(info.cfg.epWorldSize);437 uint64_t epWorldSize = static_cast<uint64_t>(info.cfg.epWorldSize);
420 uint64_t nmt = static_cast<uint64_t>(info.cfg.numMaxTokensPerRank);438 uint64_t nmt = static_cast<uint64_t>(info.cfg.numMaxTokensPerRank);
439+ uint64_t perSlotBytes = static_cast<uint64_t>(info.cfg.perSlotBytes);
421 uint64_t moeExpertNumPerRank = static_cast<uint64_t>(info.cfg.numLocalExperts);440 uint64_t moeExpertNumPerRank = static_cast<uint64_t>(info.cfg.numLocalExperts);
422 uint64_t topK = static_cast<uint64_t>(info.cfg.topK);441 uint64_t topK = static_cast<uint64_t>(info.cfg.topK);
423- 442+ uint64_t superNodeCount = static_cast<uint64_t>(info.numScaleoutRanks);
424 uint64_t cntWinStateSize =443 uint64_t cntWinStateSize =
425 epWorldSize * AlignUpWin(moeExpertNumPerRank * sizeof(int32_t)) + epWorldSize * WIN_ADDR_ALIGN;444 epWorldSize * AlignUpWin(moeExpertNumPerRank * sizeof(int32_t)) + epWorldSize * WIN_ADDR_ALIGN;
426 uint64_t dispatchWinStateSize = cntWinStateSize + epWorldSize * WIN_ADDR_ALIGN;445 uint64_t dispatchWinStateSize = cntWinStateSize + epWorldSize * WIN_ADDR_ALIGN;
427 uint64_t combineWinStateSize = nmt * topK * WIN_ADDR_ALIGN + epWorldSize * WIN_ADDR_ALIGN;446 uint64_t combineWinStateSize = nmt * topK * WIN_ADDR_ALIGN + epWorldSize * WIN_ADDR_ALIGN;
428 uint64_t hiddenAlign = (info.cfg.hidden * MAX_OUT_DTYPE_SIZE + UB_ALIGN - 1) / UB_ALIGN * UB_ALIGN;447 uint64_t hiddenAlign = (info.cfg.hidden * MAX_OUT_DTYPE_SIZE + UB_ALIGN - 1) / UB_ALIGN * UB_ALIGN;
429- uint64_t topKAlign = (topK * METADATA_DTYPE_SIZE + UB_ALIGN - 1) / UB_ALIGN * UB_ALIGN;448+ uint64_t dispatchReservedPerSlotBytes = perSlotBytes;
430- uint64_t dispatchReservedPerSlotBytes = AlignUpWin(hiddenAlign + topKAlign * 2 + UB_ALIGN);449+ uint64_t scaleoutReservedPerSlotBytes =
431- uint64_t dispatchRecvWinDataReservedSize = epWorldSize * nmt * dispatchReservedPerSlotBytes;450+ AlignUpWin(dispatchReservedPerSlotBytes + topK * sizeof(int32_t));
432 uint64_t combineWinDataSize = nmt * topK * AlignUpWin(static_cast<uint64_t>(hiddenAlign + UB_ALIGN));451 uint64_t combineWinDataSize = nmt * topK * AlignUpWin(static_cast<uint64_t>(hiddenAlign + UB_ALIGN));
433 uint64_t totalStateWinSizeEp = dispatchWinStateSize + combineWinStateSize;452 uint64_t totalStateWinSizeEp = dispatchWinStateSize + combineWinStateSize;
434- uint64_t stateAndRecvDataWinSize = dispatchRecvWinDataReservedSize + combineWinDataSize + totalStateWinSizeEp;453+ uint64_t winDataOffset;
435- uint64_t dispatchSendWinDataReservedSize = dispatchRecvWinDataReservedSize;454+ uint64_t winNeed;
436- uint64_t winNeed = stateAndRecvDataWinSize + dispatchSendWinDataReservedSize;455+ if (info.networkMode == HYBRID_MODE) {
437- OP_TILING_CHECK(winNeed > maxWindowSize,456+ uint64_t scaleoutRecvDataSize = superNodeCount * nmt * scaleoutReservedPerSlotBytes;
438- OP_LOGE(nodeName,457+ uint64_t scaleupFinalRecvDataSize = epWorldSize * nmt * dispatchReservedPerSlotBytes;
439- "ccl_buffer_size is not enough, need %lu (ep_world_size=%u, num_max_tokens_per_rank=%u, "458+ uint64_t scaleoutRecvStatusSize = AlignUpWin(superNodeCount * nmt * WIN_ADDR_ALIGN);
440- "per_slot_bytes=%u, dispatch_reserved_per_slot_bytes=%lu), but got ccl_buffer_size=%lu.",459+ uint64_t scaleoutRecvDataOffset = totalStateWinSizeEp;
441- winNeed, info.cfg.epWorldSize, info.cfg.numMaxTokensPerRank, info.cfg.perSlotBytes,460+ uint64_t scaleupFinalRecvDataOffset = scaleoutRecvDataOffset + scaleoutRecvDataSize;
442- dispatchReservedPerSlotBytes, maxWindowSize),461+ uint64_t scaleoutRecvStatusOffset = scaleupFinalRecvDataOffset + scaleupFinalRecvDataSize;
443- return ge::GRAPH_FAILED);462+ uint64_t combineDataOffset = scaleoutRecvStatusOffset + scaleoutRecvStatusSize;
463+ uint64_t payloadStashWinOffset = combineDataOffset + combineWinDataSize;
464+ uint64_t payloadStashWinSize = nmt * scaleoutReservedPerSlotBytes;
465+ winDataOffset = scaleupFinalRecvDataOffset;
466+ winNeed = payloadStashWinOffset + payloadStashWinSize;
467+ } else {
468+ uint64_t dispatchRecvWinDataReservedSize = epWorldSize * nmt * dispatchReservedPerSlotBytes;
469+ uint64_t stateAndRecvDataWinSize =
470+ dispatchRecvWinDataReservedSize + combineWinDataSize + totalStateWinSizeEp;
471+ uint64_t dispatchSendWinDataReservedSize = dispatchRecvWinDataReservedSize;
472+ winDataOffset = totalStateWinSizeEp;
473+ winNeed = stateAndRecvDataWinSize + dispatchSendWinDataReservedSize;
474+ }
475+ OP_TILING_CHECK(
476+ winNeed > maxWindowSize,
477+ OP_LOGE(nodeName,
478+ "ccl_buffer_size is not enough, need %lu (ep_world_size=%u, num_max_tokens_per_rank=%u, "
479+ "per_slot_bytes=%u, dispatch_reserved_per_slot_bytes=%lu), but got ccl_buffer_size=%lu.",
480+ winNeed, info.cfg.epWorldSize, info.cfg.numMaxTokensPerRank, info.cfg.perSlotBytes,
481+ dispatchReservedPerSlotBytes, maxWindowSize),
482+ return ge::GRAPH_FAILED);
444 483 
445- info.winDataOffset = totalStateWinSizeEp;484+ info.winDataOffset = winDataOffset;
446 info.slotWinStateOffset = cntWinStateSize;485 info.slotWinStateOffset = cntWinStateSize;
447 return ge::GRAPH_SUCCESS;486 return ge::GRAPH_SUCCESS;
448}487}
@@ -464,7 +503,12 @@ static ge::graphStatus MoeEpDispatchEpilogueTilingFunc(gert::TilingContext *cont
464 bool cached = (context->GetInputShape(CACHED_RECV_SRC_METADATA_INDEX) != nullptr);503 bool cached = (context->GetInputShape(CACHED_RECV_SRC_METADATA_INDEX) != nullptr);
465 info.cached = cached ? 1U : 0U;504 info.cached = cached ? 1U : 0U;
466 505 
467- bool hasTopkWeights = (context->GetOutputShape(OUT_RECV_TOPK_WEIGHTS_INDEX) != nullptr);506+ auto attrs = context->GetAttrs();
507+ OP_TILING_CHECK(attrs == nullptr, OP_LOGE(nodeName, "attrs is nullptr."), return ge::GRAPH_FAILED);
508+ auto hasTopkWeightsPtr = attrs->GetAttrPointer<bool>(ATTR_HAS_TOPK_WEIGHTS_INDEX);
509+ OP_TILING_CHECK(hasTopkWeightsPtr == nullptr, OP_LOGE(nodeName, "hasTopkWeightsPtr is null."),
510+ return ge::GRAPH_FAILED);
511+ bool hasTopkWeights = *hasTopkWeightsPtr;
468 512 
469 OP_TILING_CHECK(CheckInputDataType(context, nodeName, cached) != ge::GRAPH_SUCCESS,513 OP_TILING_CHECK(CheckInputDataType(context, nodeName, cached) != ge::GRAPH_SUCCESS,
470 OP_LOGE(nodeName, "Check input dtype failed."), return ge::GRAPH_FAILED);514 OP_LOGE(nodeName, "Check input dtype failed."), return ge::GRAPH_FAILED);
@@ -479,7 +523,7 @@ static ge::graphStatus MoeEpDispatchEpilogueTilingFunc(gert::TilingContext *cont
479 info.cfg.topK = static_cast<uint32_t>(dstBufferSlotIdxShape->GetStorageShape().GetDim(1));523 info.cfg.topK = static_cast<uint32_t>(dstBufferSlotIdxShape->GetStorageShape().GetDim(1));
480 const int64_t topK = static_cast<int64_t>(info.cfg.topK);524 const int64_t topK = static_cast<int64_t>(info.cfg.topK);
481 525 
482- OP_TILING_CHECK(CheckOutputTensors(context, nodeName, info, topK) != ge::GRAPH_SUCCESS,526+ OP_TILING_CHECK(CheckOutputTensors(context, nodeName, info, topK, hasTopkWeights) != ge::GRAPH_SUCCESS,
483 OP_LOGE(nodeName, "Check output tensors failed."), return ge::GRAPH_FAILED);527 OP_LOGE(nodeName, "Check output tensors failed."), return ge::GRAPH_FAILED);
484 528 
485 auto recvXShape = context->GetOutputShape(OUT_RECV_X_INDEX);529 auto recvXShape = context->GetOutputShape(OUT_RECV_X_INDEX);
@@ -28,6 +28,9 @@ struct MoeEpCommonTilingData {
28struct MoeEpDispatchEpilogueInfo {28struct MoeEpDispatchEpilogueInfo {
29 MoeEpCommonTilingData cfg;29 MoeEpCommonTilingData cfg;
30 uint32_t aivNum = 0;30 uint32_t aivNum = 0;
31+ uint32_t networkMode = 0;
32+ uint32_t rankSizePerServer = 1;
33+ uint32_t numScaleoutRanks = 1;
31 uint64_t totalUbSize = 0;34 uint64_t totalUbSize = 0;
32 uint64_t winDataOffset = 0; // Win Data Offset35 uint64_t winDataOffset = 0; // Win Data Offset
33 uint64_t slotWinStateOffset = 0; // slot state offset36 uint64_t slotWinStateOffset = 0; // slot state offset
@@ -52,6 +52,8 @@ constexpr uint32_t HCCL_COMM_LAYERS_UB_MEM = 0;
52constexpr uint32_t GET_LOCAL_SERVER_RANK_SIZE_LAYER = 0;52constexpr uint32_t GET_LOCAL_SERVER_RANK_SIZE_LAYER = 0;
53constexpr int COMM_PROTOCOL_UBC_CTP_VALUE = 4;53constexpr int COMM_PROTOCOL_UBC_CTP_VALUE = 4;
54constexpr int COMM_PROTOCOL_UBC_TP_VALUE = 5;54constexpr int COMM_PROTOCOL_UBC_TP_VALUE = 5;
55+constexpr int64_t NETWORK_DIRECT = 0;
56+constexpr int64_t NETWORK_HYBRID = 1;
55constexpr int64_t BUFFER_ALIGNMENT = 2 * 1024 * 1024;57constexpr int64_t BUFFER_ALIGNMENT = 2 * 1024 * 1024;
56constexpr int DIM_TWO = 2;58constexpr int DIM_TWO = 2;
57constexpr uint32_t MOE_CHANNEL_HANDLE_NUM = 72U;59constexpr uint32_t MOE_CHANNEL_HANDLE_NUM = 72U;
@@ -455,7 +457,7 @@ private:
455 457 
456class MoeContextBuilder : public HcclContextBuilderBase {458class MoeContextBuilder : public HcclContextBuilderBase {
457public:459public:
458- at::Tensor Build(const std::string &groupName, int64_t &cclBufferSize)460+ at::Tensor Build(const std::string &groupName, int64_t &cclBufferSize, uint32_t &rankSizePerServer)
459 {461 {
460 InitHcclEngineCtxFunctions();462 InitHcclEngineCtxFunctions();
461 463 
@@ -468,7 +470,9 @@ public:
468 MoeCommContext context;470 MoeCommContext context;
469 BuildContext(hcclComm, groupName, "moe_dispatch_combine_multi_channel", protocol, context, cclBufferSize);471 BuildContext(hcclComm, groupName, "moe_dispatch_combine_multi_channel", protocol, context, cclBufferSize);
470 rankNumPerServer_ = rankNumPerUbDomain_;472 rankNumPerServer_ = rankNumPerUbDomain_;
473+ TORCH_CHECK(rankNumPerServer_ > 0, "rank_num_per_server must be positive after building MoE context");
471 context.rankSizePerServer = rankNumPerServer_;474 context.rankSizePerServer = rankNumPerServer_;
475+ rankSizePerServer = rankNumPerServer_;
472 476 
473 return CreateCommContextTensor(context);477 return CreateCommContextTensor(context);
474 }478 }
@@ -782,7 +786,8 @@ public:
782 static int64_t GetEngramStorageSizeHint(int64_t numEntries, int64_t hiddenSize,786 static int64_t GetEngramStorageSizeHint(int64_t numEntries, int64_t hiddenSize,
783 at::ScalarType dtype = at::kBFloat16);787 at::ScalarType dtype = at::kBFloat16);
784 788 
785- using DispatchTensorList = std::tuple<at::Tensor, at::Tensor, at::Tensor>;789+ using DispatchTensorList =
790+ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor>;
786 using DispatchEpilogueTensorList =791 using DispatchEpilogueTensorList =
787 std::tuple<at::Tensor, at::Tensor, c10::optional<at::Tensor>, c10::optional<at::Tensor>>;792 std::tuple<at::Tensor, at::Tensor, c10::optional<at::Tensor>, c10::optional<at::Tensor>>;
788 using CombineTensorList = std::tuple<at::Tensor, c10::optional<at::Tensor>>;793 using CombineTensorList = std::tuple<at::Tensor, c10::optional<at::Tensor>>;
@@ -790,24 +795,28 @@ public:
790 DispatchTensorList MoeEpDispatch(const at::Tensor &x, const at::Tensor &topkIdx,795 DispatchTensorList MoeEpDispatch(const at::Tensor &x, const at::Tensor &topkIdx,
791 const c10::optional<at::Tensor> &topkWeights,796 const c10::optional<at::Tensor> &topkWeights,
792 const c10::optional<at::Tensor> &scales,797 const c10::optional<at::Tensor> &scales,
793- const c10::optional<at::Tensor> &cachedHandleDstBufferSlotIdx, int64_t epWorldSize,798+ const c10::optional<at::Tensor> &cachedDstSlotIdx,
794- int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank,799+ const c10::optional<at::Tensor> &cachedRouteCount,
795- int64_t expertAlignment, bool doCpuSync, int64_t hostPinnedCounterAddr);800+ const c10::optional<at::Tensor> &cachedRouteDstScaleout,
801+ const c10::optional<at::Tensor> &cachedRouteScaleoutSlot,
802+ int64_t epWorldSize, int64_t epRankId, int64_t numExperts,
803+ int64_t numMaxTokensPerRank, int64_t expertAlignment, bool doCpuSync,
804+ int64_t hostPinnedCounterAddr);
796 DispatchEpilogueTensorList MoeEpDispatchEpilogue(805 DispatchEpilogueTensorList MoeEpDispatchEpilogue(
797 const at::Tensor &dstBufferSlotIdx, const at::Tensor &numRecvPerRank, const at::Tensor &numRecvPerExpert,806 const at::Tensor &dstBufferSlotIdx, const at::Tensor &numRecvPerRank, const at::Tensor &numRecvPerExpert,
798 const c10::optional<at::Tensor> &cachedRecvSrcMetadata, int64_t epWorldSize, int64_t epRankId,807 const c10::optional<at::Tensor> &cachedRecvSrcMetadata, int64_t epWorldSize, int64_t epRankId,
799- int64_t numExperts, int64_t numMaxTokensPerRank, int64_t expertAlignment, at::Tensor &recvX,808+ int64_t numExperts, int64_t numMaxTokensPerRank, at::Tensor &recvX, at::Tensor &recvSrcMetadata,
800- at::Tensor &recvSrcMetadata, const c10::optional<at::Tensor> &recvTopkWeightsOpt,809+ const c10::optional<at::Tensor> &recvTopkWeightsOpt, const c10::optional<at::Tensor> &recvScalesOpt);
801- const c10::optional<at::Tensor> &recvScalesOpt);
802 CombineTensorList MoeEpCombine(const at::Tensor &x, const at::Tensor &topkIdx, const at::Tensor &recvSrcMetadata,810 CombineTensorList MoeEpCombine(const at::Tensor &x, const at::Tensor &topkIdx, const at::Tensor &recvSrcMetadata,
803 const at::Tensor &numRecvTokensPerExpert,811 const at::Tensor &numRecvTokensPerExpert,
804- const c10::optional<at::Tensor> &topkWeights, const c10::optional<at::Tensor> &bias0,812+ const c10::optional<at::Tensor> &topkWeights, int64_t epWorldSize, int64_t epRankId,
805- const c10::optional<at::Tensor> &bias1, int64_t epWorldSize, int64_t epRankId,
806 int64_t numExperts, int64_t numMaxTokensPerRank);813 int64_t numExperts, int64_t numMaxTokensPerRank);
807 814 
808private:815private:
809 void EnsureEngramContext();816 void EnsureEngramContext();
810 void EnsureMoeContext();817 void EnsureMoeContext();
818+ int64_t ResolveRankNumPerServer(int64_t epWorldSize) const;
819+ int64_t ResolveTopoType(int64_t epWorldSize, int64_t rankNumPerServer) const;
811 820 
812 std::string groupName_;821 std::string groupName_;
813 int64_t engramNumCpuBytes_;822 int64_t engramNumCpuBytes_;
@@ -826,6 +835,7 @@ private:
826 835 
827 at::Tensor moeContextTensor_;836 at::Tensor moeContextTensor_;
828 int64_t moeCclBufferSize_ = 0;837 int64_t moeCclBufferSize_ = 0;
838+ uint32_t moeRankSizePerServer_ = 2;
829 bool moeContextInitialized_ = false;839 bool moeContextInitialized_ = false;
830 840 
831 int64_t engramHiddenSize_ = 0;841 int64_t engramHiddenSize_ = 0;
@@ -892,10 +902,24 @@ void ElasticBuffer::EnsureMoeContext()
892 return;902 return;
893 }903 }
894 MoeContextBuilder builder;904 MoeContextBuilder builder;
895- moeContextTensor_ = builder.Build(groupName_, moeCclBufferSize_);905+ moeContextTensor_ = builder.Build(groupName_, moeCclBufferSize_, moeRankSizePerServer_);
896 moeContextInitialized_ = true;906 moeContextInitialized_ = true;
897}907}
898 908 
909+int64_t ElasticBuffer::ResolveRankNumPerServer(int64_t epWorldSize) const
910+{
911+ int64_t rankNumPerServer = static_cast<int64_t>(moeRankSizePerServer_);
912+ TORCH_CHECK(rankNumPerServer > 0, "rank_num_per_server must be positive, got ", rankNumPerServer);
913+ TORCH_CHECK(epWorldSize % rankNumPerServer == 0, "ep_world_size must be divisible by rank_num_per_server, got ",
914+ epWorldSize, " and ", rankNumPerServer);
915+ return rankNumPerServer;
916+}
917+ 
918+int64_t ElasticBuffer::ResolveTopoType(int64_t epWorldSize, int64_t rankNumPerServer) const
919+{
920+ return (epWorldSize / rankNumPerServer > 1) ? NETWORK_HYBRID : NETWORK_DIRECT;
921+}
922+ 
899// EngramWrite - write data with automatic barrier923// EngramWrite - write data with automatic barrier
900void ElasticBuffer::EngramWrite(const at::Tensor &storage)924void ElasticBuffer::EngramWrite(const at::Tensor &storage)
901{925{
@@ -1179,29 +1203,48 @@ private:
1179 1203 
1180Mc2Api::ElasticBuffer::DispatchTensorList Mc2Api::ElasticBuffer::MoeEpDispatch(1204Mc2Api::ElasticBuffer::DispatchTensorList Mc2Api::ElasticBuffer::MoeEpDispatch(
1181 const at::Tensor &x, const at::Tensor &topkIdx, const c10::optional<at::Tensor> &topkWeights,1205 const at::Tensor &x, const at::Tensor &topkIdx, const c10::optional<at::Tensor> &topkWeights,
1182- const c10::optional<at::Tensor> &scales, const c10::optional<at::Tensor> &cachedHandleDstBufferSlotIdx,1206+ const c10::optional<at::Tensor> &scales, const c10::optional<at::Tensor> &cachedDstSlotIdx,
1183- int64_t epWorldSize, int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank, int64_t expertAlignment,1207+ const c10::optional<at::Tensor> &cachedRouteCount, const c10::optional<at::Tensor> &cachedRouteDstScaleout,
1184- bool doCpuSync, int64_t hostPinnedCounterAddr)1208+ const c10::optional<at::Tensor> &cachedRouteScaleoutSlot, int64_t epWorldSize, int64_t epRankId,
1209+ int64_t numExperts, int64_t numMaxTokensPerRank, int64_t expertAlignment, bool doCpuSync,
1210+ int64_t hostPinnedCounterAddr)
1185{1211{
1186 TORCH_CHECK(x.dim() == DIM_TWO, "x dims must be 2, but got ", x.dim());1212 TORCH_CHECK(x.dim() == DIM_TWO, "x dims must be 2, but got ", x.dim());
1187 TORCH_CHECK(topkIdx.dim() == DIM_TWO, "topk_idx dims must be 2, but got ", topkIdx.dim());1213 TORCH_CHECK(topkIdx.dim() == DIM_TWO, "topk_idx dims must be 2, but got ", topkIdx.dim());
1188 EnsureMoeContext();1214 EnsureMoeContext();
1215+ int64_t rankNumPerServer = ResolveRankNumPerServer(epWorldSize);
1216+ int64_t topoType = ResolveTopoType(epWorldSize, rankNumPerServer);
1189 1217 
1190- bool anyCached = cachedHandleDstBufferSlotIdx.has_value();1218+ bool anyCached = cachedDstSlotIdx.has_value();
1191 TORCH_CHECK(!(anyCached && doCpuSync), "cached mode is incompatible with do_cpu_sync=True");1219 TORCH_CHECK(!(anyCached && doCpuSync), "cached mode is incompatible with do_cpu_sync=True");
1220+ bool anyCachedRoute = cachedRouteCount.has_value() || cachedRouteDstScaleout.has_value() ||
1221+ cachedRouteScaleoutSlot.has_value();
1222+ bool allCachedRoute = cachedRouteCount.has_value() && cachedRouteDstScaleout.has_value() &&
1223+ cachedRouteScaleoutSlot.has_value();
1224+ TORCH_CHECK(!anyCachedRoute || allCachedRoute, "cached route tensors must be all present or all absent");
1225+ bool hybridCached = anyCached && topoType == NETWORK_HYBRID;
1226+ TORCH_CHECK(!hybridCached || allCachedRoute, "hybrid cached dispatch requires all cached route tensors");
1192 1227 
1193 auto xSize = x.sizes();1228 auto xSize = x.sizes();
1194 int64_t numTokens = xSize[0];1229 int64_t numTokens = xSize[0];
1195 int64_t topK = topkIdx.size(1);1230 int64_t topK = topkIdx.size(1);
1196 int64_t numLocalExperts = numExperts / epWorldSize;1231 int64_t numLocalExperts = numExperts / epWorldSize;
1232+ int64_t routeCapacity = topK;
1197 1233 
1198 at::Tensor numRecvPerRank = at::empty({epWorldSize}, x.options().dtype(at::kInt));1234 at::Tensor numRecvPerRank = at::empty({epWorldSize}, x.options().dtype(at::kInt));
1199 at::Tensor numRecvPerExpert = at::empty({numLocalExperts}, x.options().dtype(at::kLong));1235 at::Tensor numRecvPerExpert = at::empty({numLocalExperts}, x.options().dtype(at::kLong));
1200 at::Tensor dstSlot = at::empty({numTokens, topK}, x.options().dtype(at::kInt));1236 at::Tensor dstSlot = at::empty({numTokens, topK}, x.options().dtype(at::kInt));
1237+ at::Tensor routeCount = at::zeros({numTokens}, x.options().dtype(at::kInt));
1238+ at::Tensor routeDstScaleout = at::full({numTokens, routeCapacity}, -1, x.options().dtype(at::kInt));
1239+ at::Tensor routeScaleoutSlot = at::full({numTokens, routeCapacity}, -1, x.options().dtype(at::kInt));
1201 1240 
1202 at::Tensor topkWeightsTensor = topkWeights.has_value() ? *topkWeights : at::Tensor();1241 at::Tensor topkWeightsTensor = topkWeights.has_value() ? *topkWeights : at::Tensor();
1203- at::Tensor cachedSlotTensor =1242+ at::Tensor cachedSlotTensor = cachedDstSlotIdx.has_value() ? *cachedDstSlotIdx : at::Tensor();
1204- cachedHandleDstBufferSlotIdx.has_value() ? *cachedHandleDstBufferSlotIdx : at::Tensor();1243+ at::Tensor cachedRouteCountTensor = cachedRouteCount.has_value() ? *cachedRouteCount : at::Tensor();
1244+ at::Tensor cachedRouteDstScaleoutTensor =
1245+ cachedRouteDstScaleout.has_value() ? *cachedRouteDstScaleout : at::Tensor();
1246+ at::Tensor cachedRouteScaleoutSlotTensor =
1247+ cachedRouteScaleoutSlot.has_value() ? *cachedRouteScaleoutSlot : at::Tensor();
1205 1248 
1206 at::Tensor scalesTensor = scales.has_value() ? *scales : at::Tensor();1249 at::Tensor scalesTensor = scales.has_value() ? *scales : at::Tensor();
1207 aclDataType scalesDtype = (scales.has_value() && scalesTensor.scalar_type() == at::kByte) ?1250 aclDataType scalesDtype = (scales.has_value() && scalesTensor.scalar_type() == at::kByte) ?
@@ -1210,34 +1253,44 @@ Mc2Api::ElasticBuffer::DispatchTensorList Mc2Api::ElasticBuffer::MoeEpDispatch(
1210 TensorWrapper scalesWrapper = TensorWrapper{scalesTensor, scalesDtype};1253 TensorWrapper scalesWrapper = TensorWrapper{scalesTensor, scalesDtype};
1211 1254 
1212 ACLNN_CMD(aclnnMoeEpDispatch, moeContextTensor_, x, topkIdx, topkWeightsTensor, scalesWrapper, cachedSlotTensor,1255 ACLNN_CMD(aclnnMoeEpDispatch, moeContextTensor_, x, topkIdx, topkWeightsTensor, scalesWrapper, cachedSlotTensor,
1256+ cachedRouteCountTensor, cachedRouteDstScaleoutTensor, cachedRouteScaleoutSlotTensor,
1213 epWorldSize, epRankId, numExperts, numMaxTokensPerRank, moeCclBufferSize_, expertAlignment, doCpuSync,1257 epWorldSize, epRankId, numExperts, numMaxTokensPerRank, moeCclBufferSize_, expertAlignment, doCpuSync,
1214- hostPinnedCounterAddr, numRecvPerRank, numRecvPerExpert, dstSlot);1258+ hostPinnedCounterAddr, topoType, rankNumPerServer, numRecvPerRank, numRecvPerExpert, dstSlot,
1259+ routeCount, routeDstScaleout, routeScaleoutSlot);
1215 1260 
1216- return std::tie(numRecvPerRank, numRecvPerExpert, dstSlot);1261+ return std::make_tuple(
1262+ numRecvPerRank, numRecvPerExpert, dstSlot, routeCount, routeDstScaleout, routeScaleoutSlot);
1217}1263}
1218 1264 
1219Mc2Api::ElasticBuffer::DispatchEpilogueTensorList Mc2Api::ElasticBuffer::MoeEpDispatchEpilogue(1265Mc2Api::ElasticBuffer::DispatchEpilogueTensorList Mc2Api::ElasticBuffer::MoeEpDispatchEpilogue(
1220 const at::Tensor &dstBufferSlotIdx, const at::Tensor &numRecvPerRank, const at::Tensor &numRecvPerExpert,1266 const at::Tensor &dstBufferSlotIdx, const at::Tensor &numRecvPerRank, const at::Tensor &numRecvPerExpert,
1221 const c10::optional<at::Tensor> &cachedRecvSrcMetadata, int64_t epWorldSize, int64_t epRankId, int64_t numExperts,1267 const c10::optional<at::Tensor> &cachedRecvSrcMetadata, int64_t epWorldSize, int64_t epRankId, int64_t numExperts,
1222- int64_t numMaxTokensPerRank, int64_t expertAlignment, at::Tensor &recvX, at::Tensor &recvSrcMetadata,1268+ int64_t numMaxTokensPerRank, at::Tensor &recvX, at::Tensor &recvSrcMetadata,
1223 const c10::optional<at::Tensor> &recvTopkWeightsOpt, const c10::optional<at::Tensor> &recvScalesOpt)1269 const c10::optional<at::Tensor> &recvTopkWeightsOpt, const c10::optional<at::Tensor> &recvScalesOpt)
1224{1270{
1225 EnsureMoeContext();1271 EnsureMoeContext();
1272+ int64_t rankNumPerServer = ResolveRankNumPerServer(epWorldSize);
1273+ int64_t topoType = ResolveTopoType(epWorldSize, rankNumPerServer);
1226 1274 
1227 at::Tensor cachedRecvSrcMetadataTensor = cachedRecvSrcMetadata.has_value() ? *cachedRecvSrcMetadata : at::Tensor();1275 at::Tensor cachedRecvSrcMetadataTensor = cachedRecvSrcMetadata.has_value() ? *cachedRecvSrcMetadata : at::Tensor();
1228 1276 
1229- at::Tensor recvScalesTensor = recvScalesOpt.has_value() ? *recvScalesOpt : at::Tensor();1277+ aclDataType recvScalesDtype = aclDataType::ACL_FLOAT;
1230- aclDataType recvScalesDtype =1278+ at::Tensor recvScalesTensor =
1231- (recvScalesOpt.has_value() && recvScalesTensor.scalar_type() == at::kByte) ?1279+ recvScalesOpt.has_value() ? *recvScalesOpt : at::empty({1}, recvX.options().dtype(at::kFloat));
1232- aclDataType::ACL_FLOAT8_E8M0 :1280+ if (recvScalesOpt.has_value() && recvScalesTensor.scalar_type() == at::kByte) {
1233- ConvertToAclDataType(recvScalesOpt.has_value() ? recvScalesTensor.scalar_type() : at::kFloat);1281+ recvScalesDtype = aclDataType::ACL_FLOAT8_E8M0;
1282+ }
1283+ 
1234 TensorWrapper recvScalesWrapper = TensorWrapper{recvScalesTensor, recvScalesDtype};1284 TensorWrapper recvScalesWrapper = TensorWrapper{recvScalesTensor, recvScalesDtype};
1235 1285 
1236- at::Tensor recvTopkWeightsTensor = recvTopkWeightsOpt.has_value() ? *recvTopkWeightsOpt : at::Tensor();1286+ at::Tensor recvTopkWeightsTensor =
1287+ recvTopkWeightsOpt.has_value() ? *recvTopkWeightsOpt : at::empty({1}, recvX.options().dtype(at::kFloat));
1288+ bool hasTopkWeights = recvTopkWeightsOpt.has_value();
1237 1289 
1238 ACLNN_CMD(aclnnMoeEpDispatchEpilogue, moeContextTensor_, dstBufferSlotIdx, numRecvPerRank, numRecvPerExpert,1290 ACLNN_CMD(aclnnMoeEpDispatchEpilogue, moeContextTensor_, dstBufferSlotIdx, numRecvPerRank, numRecvPerExpert,
1239 cachedRecvSrcMetadataTensor, epWorldSize, epRankId, numExperts, numMaxTokensPerRank, moeCclBufferSize_,1291 cachedRecvSrcMetadataTensor, epWorldSize, epRankId, numExperts, numMaxTokensPerRank, moeCclBufferSize_,
1240- expertAlignment, recvX, recvSrcMetadata, recvTopkWeightsTensor, recvScalesWrapper);1292+ hasTopkWeights, topoType, rankNumPerServer, recvX, recvSrcMetadata, recvTopkWeightsTensor,
1293+ recvScalesWrapper);
1241 1294 
1242 c10::optional<at::Tensor> recvTopkWeightsOutput;1295 c10::optional<at::Tensor> recvTopkWeightsOutput;
1243 if (recvTopkWeightsOpt.has_value()) {1296 if (recvTopkWeightsOpt.has_value()) {
@@ -1250,15 +1303,17 @@ Mc2Api::ElasticBuffer::DispatchEpilogueTensorList Mc2Api::ElasticBuffer::MoeEpDi
1250 return std::make_tuple(recvX, recvSrcMetadata, recvTopkWeightsOutput, recvScalesOutput);1303 return std::make_tuple(recvX, recvSrcMetadata, recvTopkWeightsOutput, recvScalesOutput);
1251}1304}
1252 1305 
1253-Mc2Api::ElasticBuffer::CombineTensorList Mc2Api::ElasticBuffer::MoeEpCombine(1306+Mc2Api::ElasticBuffer::CombineTensorList
1254- const at::Tensor &x, const at::Tensor &topkIdx, const at::Tensor &recvSrcMetadata,1307+Mc2Api::ElasticBuffer::MoeEpCombine(const at::Tensor &x, const at::Tensor &topkIdx, const at::Tensor &recvSrcMetadata,
1255- const at::Tensor &numRecvTokensPerExpert, const c10::optional<at::Tensor> &topkWeights,1308+ const at::Tensor &numRecvTokensPerExpert,
1256- const c10::optional<at::Tensor> &bias0, const c10::optional<at::Tensor> &bias1, int64_t epWorldSize,1309+ const c10::optional<at::Tensor> &topkWeights, int64_t epWorldSize, int64_t epRankId,
1257- int64_t epRankId, int64_t numExperts, int64_t numMaxTokensPerRank)1310+ int64_t numExperts, int64_t numMaxTokensPerRank)
1258{1311{
1259 TORCH_CHECK(x.dim() == DIM_TWO, "x dims must be 2, but got ", x.dim());1312 TORCH_CHECK(x.dim() == DIM_TWO, "x dims must be 2, but got ", x.dim());
1260 TORCH_CHECK(topkIdx.dim() == DIM_TWO, "topk_idx dims must be 2, but got ", topkIdx.dim());1313 TORCH_CHECK(topkIdx.dim() == DIM_TWO, "topk_idx dims must be 2, but got ", topkIdx.dim());
1261 EnsureMoeContext();1314 EnsureMoeContext();
1315+ int64_t rankNumPerServer = ResolveRankNumPerServer(epWorldSize);
1316+ int64_t topoType = ResolveTopoType(epWorldSize, rankNumPerServer);
1262 1317 
1263 int64_t numTokens = topkIdx.size(0);1318 int64_t numTokens = topkIdx.size(0);
1264 int64_t hidden = x.size(1);1319 int64_t hidden = x.size(1);
@@ -1273,12 +1328,10 @@ Mc2Api::ElasticBuffer::CombineTensorList Mc2Api::ElasticBuffer::MoeEpCombine(
1273 }1328 }
1274 1329 
1275 c10::optional<at::Tensor> topkWeightsOpt = topkWeights;1330 c10::optional<at::Tensor> topkWeightsOpt = topkWeights;
1276- c10::optional<at::Tensor> bias0Opt = c10::optional<at::Tensor>();
1277- c10::optional<at::Tensor> bias1Opt = c10::optional<at::Tensor>();
1278 1331 
1279 ACLNN_CMD(aclnnMoeEpCombine, moeContextTensor_, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert, topkWeightsOpt,1332 ACLNN_CMD(aclnnMoeEpCombine, moeContextTensor_, x, topkIdx, recvSrcMetadata, numRecvTokensPerExpert, topkWeightsOpt,
1280- bias0Opt, bias1Opt, epWorldSize, epRankId, numExperts, numMaxTokensPerRank, moeCclBufferSize_, combinedX,1333+ epWorldSize, epRankId, numExperts, numMaxTokensPerRank, moeCclBufferSize_, topoType, rankNumPerServer,
1281- combinedTopkWeights);1334+ combinedX, combinedTopkWeights);
1282 1335 
1283 c10::optional<at::Tensor> combinedTopkWeightsOpt;1336 c10::optional<at::Tensor> combinedTopkWeightsOpt;
1284 if (topkWeights.has_value()) {1337 if (topkWeights.has_value()) {
@@ -169,13 +169,21 @@ def _inline_align(value: int, base: int) -> int:
169 return (value + base - 1) // base * base169 return (value + base - 1) // base * base
170 170 
171 171 
172-def _get_moe_ep_minimum_window_bytes(172+@dataclass(frozen=True)
173+class _MoeEpWindowLayout:
174+ state_buffer_bytes: int
175+ dispatch_slot_bytes: int
176+ combine_slot_bytes: int
177+ scaleup_receive_buffer_bytes: int
178+ 
179+ 
180+def _get_moe_ep_window_layout(
173 world_size: int,181 world_size: int,
174 num_max_tokens_per_rank: int,182 num_max_tokens_per_rank: int,
175 hidden: int,183 hidden: int,
176 num_experts: int,184 num_experts: int,
177 topk: int,185 topk: int,
178-) -> int:186+) -> _MoeEpWindowLayout:
179 win_addr_align = 512187 win_addr_align = 512
180 ub_align = 32188 ub_align = 32
181 max_out_dtype_size = 2189 max_out_dtype_size = 2
@@ -200,11 +208,30 @@ def _get_moe_ep_minimum_window_bytes(
200 hidden_align + metadata_bytes * 2 + ub_align, win_addr_align208 hidden_align + metadata_bytes * 2 + ub_align, win_addr_align
201 )209 )
202 combine_per_slot_bytes = _inline_align(hidden_align + ub_align, win_addr_align)210 combine_per_slot_bytes = _inline_align(hidden_align + ub_align, win_addr_align)
203- dispatch_buffer_size = (211+ scaleup_receive_buffer_bytes = (
204 world_size * num_max_tokens_per_rank * dispatch_per_slot_bytes212 world_size * num_max_tokens_per_rank * dispatch_per_slot_bytes
205 )213 )
206- combine_recv_buffer_size = num_max_tokens_per_rank * combine_per_slot_bytes * topk214+ return _MoeEpWindowLayout(
207- return state_buffer_size + dispatch_buffer_size * 2 + combine_recv_buffer_size215+ state_buffer_bytes=state_buffer_size,
216+ dispatch_slot_bytes=dispatch_per_slot_bytes,
217+ combine_slot_bytes=combine_per_slot_bytes,
218+ scaleup_receive_buffer_bytes=scaleup_receive_buffer_bytes,
219+ )
220+ 
221+ 
222+def _get_moe_ep_direct_window_bytes(
223+ layout: _MoeEpWindowLayout,
224+ num_max_tokens_per_rank: int,
225+ topk: int,
226+) -> int:
227+ combine_receive_buffer_bytes = (
228+ num_max_tokens_per_rank * layout.combine_slot_bytes * topk
229+ )
230+ return (
231+ layout.state_buffer_bytes
232+ + layout.scaleup_receive_buffer_bytes * 2
233+ + combine_receive_buffer_bytes
234+ )
208 235 
209 236 
210@dataclass237@dataclass
@@ -217,6 +244,9 @@ class EPHandle:
217 expert_alignment: int244 expert_alignment: int
218 num_max_tokens_per_rank: int245 num_max_tokens_per_rank: int
219 topk_idx: torch.Tensor246 topk_idx: torch.Tensor
247+ route_count: Optional[torch.Tensor] = None
248+ route_dst_scaleout: Optional[torch.Tensor] = None
249+ route_scaleout_slot: Optional[torch.Tensor] = None
220 250 
221 @property251 @property
222 def num_recv_tokens(self) -> int:252 def num_recv_tokens(self) -> int:
@@ -228,7 +258,10 @@ class _DispatchArgs:
228 x: torch.Tensor258 x: torch.Tensor
229 scales: Optional[torch.Tensor]259 scales: Optional[torch.Tensor]
230 topk_idx: torch.Tensor260 topk_idx: torch.Tensor
231- cached_dst_slot: Optional[torch.Tensor]261+ cached_dst_slot_idx: Optional[torch.Tensor]
262+ cached_route_count: Optional[torch.Tensor]
263+ cached_route_dst_scaleout: Optional[torch.Tensor]
264+ cached_route_scaleout_slot: Optional[torch.Tensor]
232 cached_recv_src_metadata: Optional[torch.Tensor]265 cached_recv_src_metadata: Optional[torch.Tensor]
233 num_experts: int266 num_experts: int
234 num_max_tokens_per_rank: int267 num_max_tokens_per_rank: int
@@ -355,13 +388,65 @@ class ElasticBuffer:
355 )388 )
356 389 
357 mb_conversion = 1024 * 1024390 mb_conversion = 1024 * 1024
358- minimum_window_bytes = _get_moe_ep_minimum_window_bytes(391+ window_layout = _get_moe_ep_window_layout(
359 world_size,392 world_size,
360 num_max_tokens_per_rank,393 num_max_tokens_per_rank,
361 hidden,394 hidden,
362 num_experts,395 num_experts,
363 topk,396 topk,
364 )397 )
398+ direct_minimum_window_bytes = _get_moe_ep_direct_window_bytes(
399+ window_layout,
400+ num_max_tokens_per_rank,
401+ topk,
402+ )
403+ win_addr_align = 512
404+ state_dtype_size = 4
405+ 
406+ def get_dispatch_buffer_size(rank_num_per_server):
407+ scaleout_rank_count = world_size // rank_num_per_server
408+ scaleout_per_slot_bytes = _inline_align(
409+ window_layout.dispatch_slot_bytes + topk * state_dtype_size,
410+ win_addr_align,
411+ )
412+ scaleout_recv_data_size = (
413+ scaleout_rank_count
414+ * num_max_tokens_per_rank
415+ * scaleout_per_slot_bytes
416+ )
417+ scaleout_recv_status_size = (
418+ scaleout_rank_count * num_max_tokens_per_rank * win_addr_align
419+ )
420+ payload_stash_size = num_max_tokens_per_rank * scaleout_per_slot_bytes
421+ return (
422+ scaleout_recv_data_size
423+ + window_layout.scaleup_receive_buffer_bytes
424+ + scaleout_recv_status_size
425+ + payload_stash_size
426+ )
427+ 
428+ # Context topology is unavailable here, so reserve for the largest valid hybrid layout.
429+ rank_num_per_server_candidates = [
430+ rank_num_per_server
431+ for rank_num_per_server in range(1, world_size + 1)
432+ if world_size % rank_num_per_server == 0
433+ ]
434+ dispatch_buffer_size = max(
435+ get_dispatch_buffer_size(rank_num_per_server)
436+ for rank_num_per_server in rank_num_per_server_candidates
437+ )
438+ combine_buffer_size = (
439+ num_max_tokens_per_rank * window_layout.combine_slot_bytes * topk
440+ )
441+ 
442+ hybrid_minimum_window_bytes = (
443+ window_layout.state_buffer_bytes
444+ + dispatch_buffer_size
445+ + combine_buffer_size
446+ )
447+ minimum_window_bytes = max(
448+ direct_minimum_window_bytes, hybrid_minimum_window_bytes
449+ )
365 return (450 return (
366 _inline_align(451 _inline_align(
367 _inline_align(minimum_window_bytes, mb_conversion) // mb_conversion,452 _inline_align(minimum_window_bytes, mb_conversion) // mb_conversion,
@@ -619,15 +704,36 @@ class ElasticBuffer:
619 expert_alignment,704 expert_alignment,
620 do_cpu_sync,705 do_cpu_sync,
621 )706 )
707+ torch._check(
708+ args.x.shape[1] == self._hidden,
709+ lambda: f"x hidden must equal configured hidden, got {args.x.shape[1]} and {self._hidden}",
710+ )
711+ torch._check(
712+ args.topk_idx.shape[1] == self._num_topk,
713+ lambda: (
714+ "topk_idx topk must equal configured num_topk, "
715+ f"got {args.topk_idx.shape[1]} and {self._num_topk}"
716+ ),
717+ )
622 hp_addr = self._prepare_host_counter(args.do_cpu_sync)718 hp_addr = self._prepare_host_counter(args.do_cpu_sync)
623 719 
624- num_recv_per_rank, num_recv_per_expert, dst_slot = (720+ (
721+ num_recv_per_rank,
722+ num_recv_per_expert,
723+ dst_slot,
724+ route_count,
725+ route_dst_scaleout,
726+ route_scaleout_slot,
727+ ) = (
625 self._runtime.moe_ep_dispatch(728 self._runtime.moe_ep_dispatch(
626 args.x,729 args.x,
627 args.topk_idx,730 args.topk_idx,
628 topk_weights,731 topk_weights,
629 args.scales,732 args.scales,
630- args.cached_dst_slot,733+ args.cached_dst_slot_idx,
734+ args.cached_route_count,
735+ args.cached_route_dst_scaleout,
736+ args.cached_route_scaleout_slot,
631 self._ep_world_size,737 self._ep_world_size,
632 self._rank_id,738 self._rank_id,
633 args.num_experts,739 args.num_experts,
@@ -653,7 +759,6 @@ class ElasticBuffer:
653 self._rank_id,759 self._rank_id,
654 args.num_experts,760 args.num_experts,
655 args.num_max_tokens_per_rank,761 args.num_max_tokens_per_rank,
656- args.expert_alignment,
657 recv_x,762 recv_x,
658 recv_src_meta,763 recv_src_meta,
659 recv_topk_weights,764 recv_topk_weights,
@@ -663,7 +768,14 @@ class ElasticBuffer:
663 768 
664 recv_x = (recv_x, recv_scales) if recv_scales is not None else recv_x769 recv_x = (recv_x, recv_scales) if recv_scales is not None else recv_x
665 new_handle = self._make_dispatch_handle(770 new_handle = self._make_dispatch_handle(
666- args, dst_slot, recv_src_meta, num_recv_per_rank, num_recv_per_expert771+ args,
772+ dst_slot,
773+ recv_src_meta,
774+ num_recv_per_rank,
775+ num_recv_per_expert,
776+ route_count,
777+ route_dst_scaleout,
778+ route_scaleout_slot,
667 )779 )
668 return recv_x, None, recv_topk_weights, new_handle780 return recv_x, None, recv_topk_weights, new_handle
669 781 
@@ -698,18 +810,18 @@ class ElasticBuffer:
698 lambda: ("bias is not supported, please set bias to None."),810 lambda: ("bias is not supported, please set bias to None."),
699 )811 )
700 812 
701- combined_x, combined_topk_weights = self._runtime.moe_ep_combine(813+ combined_x, combined_topk_weights = (
702- x,814+ self._runtime.moe_ep_combine(
703- handle.topk_idx,815+ x,
704- handle.recv_src_metadata,816+ handle.topk_idx,
705- handle.num_recv_tokens_per_expert,817+ handle.recv_src_metadata,
706- topk_weights,818+ handle.num_recv_tokens_per_expert,
707- bias_0,819+ topk_weights,
708- bias_1,820+ self._ep_world_size,
709- self._ep_world_size,821+ self._rank_id,
710- self._rank_id,822+ handle.num_experts,
711- handle.num_experts,823+ handle.num_max_tokens_per_rank,
712- handle.num_max_tokens_per_rank,824+ )
713 )825 )
714 return combined_x, combined_topk_weights826 return combined_x, combined_topk_weights
715 827 
@@ -800,6 +912,9 @@ class ElasticBuffer:
800 scales,912 scales,
801 handle.topk_idx,913 handle.topk_idx,
802 handle.dst_buffer_slot_idx,914 handle.dst_buffer_slot_idx,
915+ handle.route_count,
916+ handle.route_dst_scaleout,
917+ handle.route_scaleout_slot,
803 handle.recv_src_metadata,918 handle.recv_src_metadata,
804 handle.num_experts,919 handle.num_experts,
805 handle.num_max_tokens_per_rank,920 handle.num_max_tokens_per_rank,
@@ -821,6 +936,9 @@ class ElasticBuffer:
821 topk_idx,936 topk_idx,
822 None,937 None,
823 None,938 None,
939+ None,
940+ None,
941+ None,
824 num_experts,942 num_experts,
825 num_max_tokens_per_rank943 num_max_tokens_per_rank
826 if num_max_tokens_per_rank is not None944 if num_max_tokens_per_rank is not None
@@ -882,6 +1000,9 @@ class ElasticBuffer:
882 recv_src_meta: torch.Tensor,1000 recv_src_meta: torch.Tensor,
883 num_recv_per_rank: torch.Tensor,1001 num_recv_per_rank: torch.Tensor,
884 num_recv_per_expert: torch.Tensor,1002 num_recv_per_expert: torch.Tensor,
1003+ route_count: torch.Tensor,
1004+ route_dst_scaleout: torch.Tensor,
1005+ route_scaleout_slot: torch.Tensor,
885 ) -> EPHandle:1006 ) -> EPHandle:
886 topk_idx = (1007 topk_idx = (
887 args.topk_idx1008 args.topk_idx
@@ -897,6 +1018,9 @@ class ElasticBuffer:
897 expert_alignment=args.expert_alignment,1018 expert_alignment=args.expert_alignment,
898 num_max_tokens_per_rank=args.num_max_tokens_per_rank,1019 num_max_tokens_per_rank=args.num_max_tokens_per_rank,
899 topk_idx=topk_idx,1020 topk_idx=topk_idx,
1021+ route_count=route_count,
1022+ route_dst_scaleout=route_dst_scaleout,
1023+ route_scaleout_slot=route_scaleout_slot,
900 )1024 )
901 1025 
902 def _unpack_bias(self, bias):1026 def _unpack_bias(self, bias):