Merged
refactor(distributed): Disable dispatch/combine large-kernel execution version #4262
luoxinhuiAdd on Jun 24
refactor(distributed): Disable dispatch/combine large-kernel execution version #4262
Merged
luoxinhuiAdd on Jun 24
Total: 26 files changed+20-3240
@@ -619,19 +619,6 @@ enum class DistReduceType {
619 619 
620enum class AtomicType { SET, ADD };620enum class AtomicType { SET, ADD };
621 621 
622-struct MoeConfig {
623- int32_t routedExpertNum{0};
624- int32_t expertNumPerRank{0};
625- int32_t rankNum{0};
626-};
627-void MoeDistributedDispatch(
628- const Tensor& tokenTensor, const Tensor& tokenExpertTable, Tensor& expandX, Tensor& validCnt, Tensor& combineInfo,
629- const char* group, const MoeConfig& moeConfig);
630-void MoeDistributedCombine(
631- const Tensor& expandX, const Tensor& assistInfoForCombine, const Tensor& recvCounts, const Tensor& expertScales,
632- const char* group, uint32_t epWorldSize, uint32_t moeExpertNum, uint32_t sharedExpertNum,
633- uint32_t sharedExpertRankNum, Tensor& out);
634- 
635struct ShmemTensor {622struct ShmemTensor {
636 std::string group;623 std::string group;
637 int64_t worldSize{0};624 int64_t worldSize{0};
@@ -681,15 +668,6 @@ void ReduceScatter(
681void OneShotAllReduce(const Tensor& predToken, const Tensor& in, ShmemTensor& shmemTensor, Tensor& out);668void OneShotAllReduce(const Tensor& predToken, const Tensor& in, ShmemTensor& shmemTensor, Tensor& out);
682void TwoShotAllReduce(const Tensor& predToken, const Tensor& in, ShmemTensor& shmemTensor, Tensor& out);669void TwoShotAllReduce(const Tensor& predToken, const Tensor& in, ShmemTensor& shmemTensor, Tensor& out);
683 670 
684-void MoeDistributedDispatchV2(
685- const Tensor& x, const Tensor& expertIds, const char* group, uint32_t epWorldSize, uint32_t moeExpertNum,
686- uint32_t sharedExpertNum, uint32_t sharedExpertRankNum, Tensor& expandX, Tensor& assistInfoForCombine,
687- Tensor& expertTokenNums, Tensor& recvCounts);
688-void MoeDistributedCombineV2(
689- const Tensor& expandX, const Tensor& assistInfoForCombine, const Tensor& recvCounts, const Tensor& expertScales,
690- const char* group, uint32_t epWorldSize, uint32_t moeExpertNum, uint32_t sharedExpertNum,
691- uint32_t sharedExpertRankNum, Tensor& out);
692- 
693} // namespace Distributed671} // namespace Distributed
694std::tuple<Tensor, Tensor> TopKSort(const Tensor& x, int idxStart);672std::tuple<Tensor, Tensor> TopKSort(const Tensor& x, int idxStart);
695std::tuple<Tensor, Tensor> TopKSort(const Tensor& x, const SymbolicScalar& idxStart);673std::tuple<Tensor, Tensor> TopKSort(const Tensor& x, const SymbolicScalar& idxStart);
@@ -27,24 +27,13 @@ using AtomicType = Distributed::AtomicType;
27std::string CodeGenOpNPU::GetTemplateDType() const27std::string CodeGenOpNPU::GetTemplateDType() const
28{28{
29 static const std::unordered_map<Opcode, int32_t> dTypeOperandIndexMap = {29 static const std::unordered_map<Opcode, int32_t> dTypeOperandIndexMap = {
30- {Opcode::OP_FFN_BATCHING, 0},
31- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE, 0},
32- {Opcode::OP_COPY_TO_LOCAL_EXPERT, 0},
33- {Opcode::OP_SEND_TO_ROUTING_EXPERT, 1},
34- {Opcode::OP_SEND_TO_SHARED_EXPERT, 1},
35- {Opcode::OP_FFN_SCHED, 1},
36- {Opcode::OP_FFN_BATCHING, 1},
37- {Opcode::OP_FFN_VALIDCNT, 1},
38 {Opcode::OP_SHMEM_PUT, 1},30 {Opcode::OP_SHMEM_PUT, 1},
39 {Opcode::OP_SHMEM_STORE, 1},31 {Opcode::OP_SHMEM_STORE, 1},
40 {Opcode::OP_SHMEM_SIGNAL, 1},32 {Opcode::OP_SHMEM_SIGNAL, 1},
41 {Opcode::OP_SHMEM_WAIT_UNTIL, 1},33 {Opcode::OP_SHMEM_WAIT_UNTIL, 1},
42 {Opcode::OP_SHMEM_GET, 1},34 {Opcode::OP_SHMEM_GET, 1},
43 {Opcode::OP_SHMEM_LOAD, 0},35 {Opcode::OP_SHMEM_LOAD, 0},
44- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND, 1},
45- {Opcode::OP_FFN_COMBINEINFO, 2},
46 {Opcode::OP_SHMEM_SET, 3},36 {Opcode::OP_SHMEM_SET, 3},
47- {Opcode::OP_DISPATCH_SET_FLAG, 4},
48 };37 };
49 auto it = dTypeOperandIndexMap.find(opCode);38 auto it = dTypeOperandIndexMap.find(opCode);
50 ASSERT(GenCodeErr::OP_CODE_UNSUPPORTED, it != dTypeOperandIndexMap.end())39 ASSERT(GenCodeErr::OP_CODE_UNSUPPORTED, it != dTypeOperandIndexMap.end())
@@ -53,22 +42,6 @@ std::string CodeGenOpNPU::GetTemplateDType() const
53 return DataType2CCEStr(operandDtype[operandIndex]);42 return DataType2CCEStr(operandDtype[operandIndex]);
54}43}
55 44 
56-std::string CodeGenOpNPU::GenExtraTemplateParamsForMoeDistributedCombine(int32_t operandIndex) const
57-{
58- Distributed::MoeCombineAttr distOpAttr =
59- AnyCast<Distributed::MoeCombineAttr>(opAttrs.at(OpAttributeKey::distOpAttr));
60- int64_t secondToLastIndex = 2;
61- int64_t rowShape = shape[operandIndex][shape[operandIndex].size() - secondToLastIndex];
62- if (distOpAttr.rowShape != -1) {
63- rowShape = distOpAttr.rowShape;
64- }
65- int64_t colShape = shape[operandIndex][shape[operandIndex].size() - 1];
66- std::ostringstream oss;
67- oss << "<" << GetTemplateDType() << ", " << distOpAttr.topK << ", " << rowShape << ", " << colShape << ", "
68- << distOpAttr.paddedColShape << ">";
69- return oss.str();
70-}
71- 
72std::string CodeGenOpNPU::GenTemplateParamsForPutAndGet() const45std::string CodeGenOpNPU::GenTemplateParamsForPutAndGet() const
73{46{
74 std::ostringstream oss;47 std::ostringstream oss;
@@ -169,22 +142,6 @@ std::string CodeGenOpNPU::GenTemplateParamsForSignal() const
169 return oss.str();142 return oss.str();
170}143}
171 144 
172-std::string CodeGenOpNPU::GenTemplateParamsForMoeDistributedCombineSend() const
173-{
174- std::ostringstream oss;
175- int32_t expandXIndex = 4;
176- oss << GenExtraTemplateParamsForMoeDistributedCombine(expandXIndex);
177- return oss.str();
178-}
179- 
180-std::string CodeGenOpNPU::GenTemplateParamsForMoeDistributedCombineReceive() const
181-{
182- std::ostringstream oss;
183- int32_t outIndex = 0;
184- oss << GenExtraTemplateParamsForMoeDistributedCombine(outIndex);
185- return oss.str();
186-}
187- 
188std::string CodeGenOpNPU::GenTemplateParamsForSet() const145std::string CodeGenOpNPU::GenTemplateParamsForSet() const
189{146{
190 std::ostringstream oss;147 std::ostringstream oss;
@@ -206,15 +163,7 @@ std::string CodeGenOpNPU::GenTemplateParamsForSet() const
206std::string CodeGenOpNPU::GenTemplateParamsDefault() const163std::string CodeGenOpNPU::GenTemplateParamsDefault() const
207{164{
208 std::ostringstream oss;165 std::ostringstream oss;
209- Distributed::MoeDispatchAttr distOpAttr;166+ oss << "<" << GetTemplateDType() << ">";
210- if (opAttrs.count(OpAttributeKey::distOpAttr) != 0) {
211- distOpAttr = AnyCast<Distributed::MoeDispatchAttr>(opAttrs.at(OpAttributeKey::distOpAttr));
212- }
213- if (distOpAttr.extraTemplateParam.empty()) {
214- oss << "<" << GetTemplateDType() << ">";
215- } else {
216- oss << "<" << GetTemplateDType() << ", " << distOpAttr.extraTemplateParam << ">";
217- }
218 return oss.str();167 return oss.str();
219}168}
220 169 
@@ -226,10 +175,6 @@ std::string CodeGenOpNPU::GenTemplateParams() const
226 {Opcode::OP_SHMEM_STORE, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForStore(); }},175 {Opcode::OP_SHMEM_STORE, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForStore(); }},
227 {Opcode::OP_SHMEM_LOAD, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForLoad(); }},176 {Opcode::OP_SHMEM_LOAD, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForLoad(); }},
228 {Opcode::OP_SHMEM_SIGNAL, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForSignal(); }},177 {Opcode::OP_SHMEM_SIGNAL, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForSignal(); }},
229- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND,
230- [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForMoeDistributedCombineSend(); }},
231- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE,
232- [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForMoeDistributedCombineReceive(); }},
233 {Opcode::OP_SHMEM_SET, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForSet(); }}};178 {Opcode::OP_SHMEM_SET, [](const CodeGenOpNPU* self) { return self->GenTemplateParamsForSet(); }}};
234 179 
235 auto handler = templateParamHandlers.find(opCode);180 auto handler = templateParamHandlers.find(opCode);
@@ -355,74 +300,6 @@ std::string CodeGenOpNPU::GenOffsetsAndRawShapesForShmemSignal() const
355 return oss.str();300 return oss.str();
356}301}
357 302 
358-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForMoeDistributedCombineSend() const
359-{
360- std::ostringstream oss;
361- int32_t expandXIndex = 4;
362- oss << ", " << GenOffsets(expandXIndex);
363- return oss.str();
364-}
365- 
366-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForMoeDistributedCombineReceive() const
367-{
368- std::ostringstream oss;
369- int32_t shmemDataIndex = 6;
370- Distributed::MoeCombineAttr distOpAttr =
371- AnyCast<Distributed::MoeCombineAttr>(opAttrs.at(OpAttributeKey::distOpAttr));
372- oss << ", " << GenOffsets(shmemDataIndex) << ", " << distOpAttr.rowOffset;
373- return oss.str();
374-}
375- 
376-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForSendToRoutingExpert() const
377-{
378- std::ostringstream oss;
379- int32_t expertTableIndex = 6;
380- int32_t shmemDataIndex = 5;
381- oss << ", " << GenOffsetsAndRawShapes(expertTableIndex) << ", " << GenOffsetsAndRawShapes(shmemDataIndex);
382- return oss.str();
383-}
384- 
385-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForSendToSharedExpert() const
386-{
387- std::ostringstream oss;
388- int32_t tokenIndex = 2;
389- int32_t shmemDataIndex = 3;
390- oss << ", " << GenOffsetsAndRawShapes(tokenIndex) << ", " << GenOffsetsAndRawShapes(shmemDataIndex);
391- return oss.str();
392-}
393- 
394-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForCopyToLocalExpert() const
395-{
396- std::ostringstream oss;
397- int32_t tokenIndex = 3;
398- oss << ", " << GenOffsetsAndRawShapes(tokenIndex);
399- return oss.str();
400-}
401- 
402-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForDispatchSetFlag() const
403-{
404- std::ostringstream oss;
405- int32_t shmemFlagIndex = 5;
406- oss << ", " << GenOffsetsAndRawShapes(shmemFlagIndex);
407- return oss.str();
408-}
409- 
410-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForFfnOperations() const
411-{
412- std::ostringstream oss;
413- int32_t shmemIndex = 3;
414- oss << ", " << GenOffsetsAndRawShapes(shmemIndex);
415- return oss.str();
416-}
417- 
418-std::string CodeGenOpNPU::GenOffsetsAndRawShapesForFfnCombineInfo() const
419-{
420- std::ostringstream oss;
421- int32_t shmemIndex = 2;
422- oss << ", " << GenOffsetsAndRawShapes(shmemIndex);
423- return oss.str();
424-}
425- 
426std::string CodeGenOpNPU::GenOffsetsAndRawShapesForShmemSet() const303std::string CodeGenOpNPU::GenOffsetsAndRawShapesForShmemSet() const
427{304{
428 std::ostringstream oss;305 std::ostringstream oss;
@@ -451,26 +328,6 @@ std::string CodeGenOpNPU::GenExtraParamsStr() const
451 [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForShmemLoad(); }},328 [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForShmemLoad(); }},
452 {Opcode::OP_SHMEM_SIGNAL,329 {Opcode::OP_SHMEM_SIGNAL,
453 [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForShmemSignal(); }},330 [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForShmemSignal(); }},
454- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND,
455- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForMoeDistributedCombineSend(); }},
456- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE,
457- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForMoeDistributedCombineReceive(); }},
458- {Opcode::OP_SEND_TO_ROUTING_EXPERT,
459- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForSendToRoutingExpert(); }},
460- {Opcode::OP_SEND_TO_SHARED_EXPERT,
461- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForSendToSharedExpert(); }},
462- {Opcode::OP_COPY_TO_LOCAL_EXPERT,
463- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForCopyToLocalExpert(); }},
464- {Opcode::OP_DISPATCH_SET_FLAG,
465- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForDispatchSetFlag(); }},
466- {Opcode::OP_FFN_SCHED,
467- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForFfnOperations(); }},
468- {Opcode::OP_FFN_BATCHING,
469- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForFfnOperations(); }},
470- {Opcode::OP_FFN_VALIDCNT,
471- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForFfnOperations(); }},
472- {Opcode::OP_FFN_COMBINEINFO,
473- [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForFfnCombineInfo(); }},
474 {Opcode::OP_SHMEM_SET, [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForShmemSet(); }}};331 {Opcode::OP_SHMEM_SET, [](const CodeGenOpNPU* self) { return self->GenOffsetsAndRawShapesForShmemSet(); }}};
475 332 
476 auto handler = offsetsAndRawShapesHandlers.find(opCode);333 auto handler = offsetsAndRawShapesHandlers.find(opCode);
@@ -499,10 +356,10 @@ std::string CodeGenOpNPU::GenDistOp() const
499 std::ostringstream oss;356 std::ostringstream oss;
500 std::unordered_set<int32_t> skipOperands = {};357 std::unordered_set<int32_t> skipOperands = {};
501 static const std::unordered_map<Opcode, std::unordered_set<int32_t>> skipIndexMap = {358 static const std::unordered_map<Opcode, std::unordered_set<int32_t>> skipIndexMap = {
502- {Opcode::OP_SHMEM_PUT, {0, 2, 3, 4}}, {Opcode::OP_SHMEM_GET, {0, 2, 3}},359+ {Opcode::OP_SHMEM_PUT, {0, 2, 3, 4}}, {Opcode::OP_SHMEM_GET, {0, 2, 3}},
503- {Opcode::OP_SHMEM_STORE, {0, 1, 2, 3}}, {Opcode::OP_SHMEM_LOAD, {0, 1, 2}},360+ {Opcode::OP_SHMEM_STORE, {0, 1, 2, 3}}, {Opcode::OP_SHMEM_LOAD, {0, 1, 2}},
504- {Opcode::OP_SHMEM_SIGNAL, {0, 2, 3}}, {Opcode::OP_SHMEM_SET, {0, 2, 3}},361+ {Opcode::OP_SHMEM_SIGNAL, {0, 2, 3}}, {Opcode::OP_SHMEM_SET, {0, 2, 3}},
505- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND, {0}}, {Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE, {4}},362+ 
506 }; // 跳过部分操作数索引,对于 shmem api 只需要获得 ub 地址信息363 }; // 跳过部分操作数索引,对于 shmem api 只需要获得 ub 地址信息
507 auto it = skipIndexMap.find(opCode);364 auto it = skipIndexMap.find(opCode);
508 if (it != skipIndexMap.end()) {365 if (it != skipIndexMap.end()) {
@@ -311,22 +311,12 @@ CodeGenOpNPU::CodeGenOpNPU(const CodeGenOpNPUCtx& ctx)
311 }),311 }),
312 distributeOps_({312 distributeOps_({
313 // distribute op313 // distribute op
314- {Opcode::OP_FFN_SCHED, [this]() { return GenDistOp(); }},
315- {Opcode::OP_FFN_BATCHING, [this]() { return GenDistOp(); }},
316- {Opcode::OP_FFN_COMBINEINFO, [this]() { return GenDistOp(); }},
317- {Opcode::OP_FFN_VALIDCNT, [this]() { return GenDistOp(); }},
318- {Opcode::OP_SEND_TO_ROUTING_EXPERT, [this]() { return GenDistOp(); }},
319- {Opcode::OP_SEND_TO_SHARED_EXPERT, [this]() { return GenDistOp(); }},
320- {Opcode::OP_DISPATCH_SET_FLAG, [this]() { return GenDistOp(); }},
321- {Opcode::OP_COPY_TO_LOCAL_EXPERT, [this]() { return GenDistOp(); }},
322 {Opcode::OP_SHMEM_SET, [this]() { return GenDistOp(); }},314 {Opcode::OP_SHMEM_SET, [this]() { return GenDistOp(); }},
323 {Opcode::OP_SHMEM_PUT, [this]() { return GenDistOp(); }},315 {Opcode::OP_SHMEM_PUT, [this]() { return GenDistOp(); }},
324 {Opcode::OP_SHMEM_STORE, [this]() { return GenDistOp(); }},316 {Opcode::OP_SHMEM_STORE, [this]() { return GenDistOp(); }},
325 {Opcode::OP_SHMEM_SIGNAL, [this]() { return GenDistOp(); }},317 {Opcode::OP_SHMEM_SIGNAL, [this]() { return GenDistOp(); }},
326 {Opcode::OP_SHMEM_GET, [this]() { return GenDistOp(); }},318 {Opcode::OP_SHMEM_GET, [this]() { return GenDistOp(); }},
327 {Opcode::OP_SHMEM_LOAD, [this]() { return GenDistOp(); }},319 {Opcode::OP_SHMEM_LOAD, [this]() { return GenDistOp(); }},
328- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND, [this]() { return GenDistOp(); }},
329- {Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE, [this]() { return GenDistOp(); }},
330 }),320 }),
331 gatherScatterOps_({321 gatherScatterOps_({
332 // gather/scatter op322 // gather/scatter op
@@ -163,7 +163,6 @@ public:
163 std::string GenDistOp() const;163 std::string GenDistOp() const;
164 std::string GetTemplateDType() const;164 std::string GetTemplateDType() const;
165 std::string GenTemplateParams() const;165 std::string GenTemplateParams() const;
166- std::string GenExtraTemplateParamsForMoeDistributedCombine(int32_t operandIndex) const;
167 std::string GenOffsets(int32_t operandIndex) const;166 std::string GenOffsets(int32_t operandIndex) const;
168 std::string GenShapes(int32_t operandIndex) const;167 std::string GenShapes(int32_t operandIndex) const;
169 std::string GenRawShapes(int32_t operandIndex) const;168 std::string GenRawShapes(int32_t operandIndex) const;
@@ -220,8 +219,6 @@ protected:
220 std::string GenTemplateParamsForLoad() const;219 std::string GenTemplateParamsForLoad() const;
221 std::string GenTemplateParamsForStore() const;220 std::string GenTemplateParamsForStore() const;
222 std::string GenTemplateParamsForSignal() const;221 std::string GenTemplateParamsForSignal() const;
223- std::string GenTemplateParamsForMoeDistributedCombineSend() const;
224- std::string GenTemplateParamsForMoeDistributedCombineReceive() const;
225 std::string GenTemplateParamsForSet() const;222 std::string GenTemplateParamsForSet() const;
226 std::string GenTemplateParamsDefault() const;223 std::string GenTemplateParamsDefault() const;
227 224 
@@ -230,14 +227,6 @@ protected:
230 std::string GenOffsetsAndRawShapesForShmemStore() const;227 std::string GenOffsetsAndRawShapesForShmemStore() const;
231 std::string GenOffsetsAndRawShapesForShmemLoad() const;228 std::string GenOffsetsAndRawShapesForShmemLoad() const;
232 std::string GenOffsetsAndRawShapesForShmemSignal() const;229 std::string GenOffsetsAndRawShapesForShmemSignal() const;
233- std::string GenOffsetsAndRawShapesForMoeDistributedCombineSend() const;
234- std::string GenOffsetsAndRawShapesForMoeDistributedCombineReceive() const;
235- std::string GenOffsetsAndRawShapesForSendToRoutingExpert() const;
236- std::string GenOffsetsAndRawShapesForSendToSharedExpert() const;
237- std::string GenOffsetsAndRawShapesForCopyToLocalExpert() const;
238- std::string GenOffsetsAndRawShapesForDispatchSetFlag() const;
239- std::string GenOffsetsAndRawShapesForFfnOperations() const;
240- std::string GenOffsetsAndRawShapesForFfnCombineInfo() const;
241 std::string GenOffsetsAndRawShapesForShmemSet() const;230 std::string GenOffsetsAndRawShapesForShmemSet() const;
242 std::string GenOffsetsAndRawShapesDefault() const;231 std::string GenOffsetsAndRawShapesDefault() const;
243 std::string GenTargetRankStr() const;232 std::string GenTargetRankStr() const;
@@ -306,14 +306,6 @@ const std::map<std::string, CorePipeType> SCHED_CORE_PIPE_TYPE{
306 {"REMOTE_REDUCE", CorePipeType::PIPE_MTE_OUT},306 {"REMOTE_REDUCE", CorePipeType::PIPE_MTE_OUT},
307 {"COMM_WAIT_FLAG", CorePipeType::PIPE_S},307 {"COMM_WAIT_FLAG", CorePipeType::PIPE_S},
308 {"DEPEND_ON", CorePipeType::PIPE_S},308 {"DEPEND_ON", CorePipeType::PIPE_S},
309- {"SEND_TO_ROUTING_EXPERT", CorePipeType::PIPE_MTE_OUT},
310- {"SEND_TO_SHARED_EXPERT", CorePipeType::PIPE_MTE_OUT},
311- {"COPY_TO_LOCAL_EXPERT", CorePipeType::PIPE_MTE_OUT},
312- {"DISPATCH_SET_FLAG", CorePipeType::PIPE_S},
313- {"FFN_SCHED", CorePipeType::PIPE_S},
314- {"FFN_BATCHING", CorePipeType::PIPE_S},
315- {"FFN_COMBINEINFO", CorePipeType::PIPE_S},
316- {"FFN_VALIDCNT", CorePipeType::PIPE_S},
317 {"SHMEM_SET", CorePipeType::PIPE_S},309 {"SHMEM_SET", CorePipeType::PIPE_S},
318 {"SHMEM_PUT", CorePipeType::PIPE_MTE_OUT},310 {"SHMEM_PUT", CorePipeType::PIPE_MTE_OUT},
319 {"SHMEM_PUT_UB2GM", CorePipeType::PIPE_MTE_OUT},311 {"SHMEM_PUT_UB2GM", CorePipeType::PIPE_MTE_OUT},
@@ -322,8 +314,6 @@ const std::map<std::string, CorePipeType> SCHED_CORE_PIPE_TYPE{
322 {"SHMEM_GET", CorePipeType::PIPE_MTE_IN},314 {"SHMEM_GET", CorePipeType::PIPE_MTE_IN},
323 {"SHMEM_GET_GM2UB", CorePipeType::PIPE_MTE_IN},315 {"SHMEM_GET_GM2UB", CorePipeType::PIPE_MTE_IN},
324 {"BIND_TENSOR", CorePipeType::PIPE_S},316 {"BIND_TENSOR", CorePipeType::PIPE_S},
325- {"MOE_DISTRIBUTED_COMBINE_SEND", CorePipeType::PIPE_MTE_OUT},
326- {"MOE_DISTRIBUTED_COMBINE_RECEIVE", CorePipeType::PIPE_MTE_IN},
327 // TOPK and ArgSort317 // TOPK and ArgSort
328 {"TOPK", CorePipeType::PIPE_VECTOR_ALU},318 {"TOPK", CorePipeType::PIPE_VECTOR_ALU},
329 {"TILEDMRGSORT", CorePipeType::PIPE_VECTOR_ALU},319 {"TILEDMRGSORT", CorePipeType::PIPE_VECTOR_ALU},
@@ -196,21 +196,6 @@ struct ShmemSetAttr {
196 SymbolicScalar ownerRank;196 SymbolicScalar ownerRank;
197};197};
198 198 
199-struct MoeDispatchAttr {
200- std::string extraTemplateParam{};
201- int64_t topK = 0;
202- SymbolicScalar ownerRank;
203-};
204- 
205-struct MoeCombineAttr {
206- int64_t setType = 0;
207- int64_t topK = 0;
208- int64_t paddedColShape{0};
209- int64_t rowOffset{-1};
210- int64_t rowShape{-1};
211- SymbolicScalar ownerRank;
212-};
213- 
214inline int GetTotalTileNum(const std::array<int, MAX_DIST_DIM_SIZE>& tile)199inline int GetTotalTileNum(const std::array<int, MAX_DIST_DIM_SIZE>& tile)
215{200{
216 return tile[static_cast<size_t>(TileIndex::HEAD_NUM)] +201 return tile[static_cast<size_t>(TileIndex::HEAD_NUM)] +
@@ -51,39 +51,6 @@ inline void CreateTileOp(
51 }51 }
52}52}
53 53 
54-Tensor SendToRoutingExpert(
55- const Tensor& shmemData, const Tensor& tokenTensor, const Tensor& tokenExpertTable, const char* group,
56- const MoeConfig& moeConfig);
57-void SendToSharedExpert(
58- const Tensor& shmemData, const Tensor& tokenTensor, const Tensor& syncTensor, const char* group);
59-Tensor CopyToLocalExpert(const Tensor& tokenTensor, const Tensor& syncTensor);
60-Tensor DispatchSetFlag(
61- Tensor& shmemFlag, const Tensor& tokenExpertTable, const Tensor& syncTensor, const char* group,
62- const MoeConfig& moeConfig);
63-void TiledSendToRoutingExpert(
64- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
65- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
66-void TiledSendToSharedExpert(
67- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
68- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
69-void TiledCopyToLocalExpert(
70- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
71- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
72-void TiledDispatchSetFlag(
73- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
74- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
75-void TiledDispatchFFNSched(
76- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
77- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
78-void TiledDispatchFFNBatching(
79- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
80- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
81-void TiledDispatchFFNCombineInfo(
82- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
83- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
84-void TiledDispatchFFNValidCnt(
85- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
86- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
87void TiledShmemPut(54void TiledShmemPut(
88 Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,55 Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
89 const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);56 const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
@@ -108,12 +75,6 @@ void TiledShmemSet(
108void TiledShmemBindTensor(75void TiledShmemBindTensor(
109 Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,76 Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
110 const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);77 const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
111-void TiledMoeDistributedCombineSend(
112- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
113- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
114-void TiledMoeDistributedCombineReceive(
115- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
116- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
117 78 
118} // namespace Distributed79} // namespace Distributed
119} // namespace npu::tile_fwk80} // namespace npu::tile_fwk
@@ -1,473 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file moe_distributed_combine.cpp
13- * \brief
14- */
15- 
16-#include "distributed_common.h"
17-#include "interface/function/function.h"
18-#include "interface/inner/tilefwk.h"
19-#include "interface/operation/operation.h"
20-#include "interface/program/program.h"
21-#include "interface/tensor/logical_tensor.h"
22-#include "interface/utils/common.h"
23-#include "tilefwk/error_code.h"
24-#include "tilefwk/data_type.h"
25-#include "tilefwk/symbolic_distributed.h"
26-#include "tilefwk/tensor.h"
27-#include "tilefwk/tilefwk.h"
28- 
29-namespace npu::tile_fwk::Distributed {
30-void MoeDistributedCombineValidateExpandX(
31- const Tensor& expandX, const Tensor& expertScales, int32_t epWorldSize, int32_t moeExpertNum)
32-{
33- uint32_t supportedDim = 2;
34- ASSERT(DistributedErrorCode::INVALID_TENSOR_DIM, expandX.GetShape().size() == supportedDim)
35- << "The dim of \"expandX\" only supports " << supportedDim << ", but got " << expandX.GetShape().size();
36- 
37- int32_t expandXRow = expandX.GetShape(0);
38- int32_t topK = expertScales.GetShape(1);
39- int32_t batchSize = expertScales.GetShape(0);
40- int32_t expectedRow = std::min(topK * batchSize * epWorldSize, batchSize * moeExpertNum);
41- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, expandXRow == expectedRow)
42- << "The first axis of \"expandX\" must be the smaller value between topK (the "
43- << "second axis of \"expertScales\") * batchSize (the first axis of \"expertScales\") * epWorldSize and "
44- << "batchSize * moeExpertNum, topK=" << topK << ", batchSize=" << batchSize << ", epWorldSize=" << epWorldSize
45- << ", moeExpertNum=" << moeExpertNum << ", the expected first axis of \"expandX\" should be " << expectedRow
46- << " but got " << expandXRow;
47- 
48- int32_t expandXCol = expandX.GetShape(1);
49- int32_t supportedHiddenSize = 5120;
50- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, expandXCol == supportedHiddenSize)
51- << "The second axis of \"expandX\" only supports " << supportedHiddenSize << ", but got " << expandXCol;
52- 
53- ASSERT(DistributedErrorCode::INVALID_TENSOR_DTYPE, expandX.GetDataType() == DT_BF16)
54- << "The data type of \"expandX\" only supports DT_BF16, but got " << DataType2String(expandX.GetDataType());
55- 
56- ASSERT(DistributedErrorCode::INVALID_TENSOR_FORMAT, expandX.Format() == npu::tile_fwk::TileOpFormat::TILEOP_ND)
57- << "The format of \"expandX\" only supports ND, but got NZ";
58-}
59- 
60-void MoeDistributedCombineValidateAssistInfoForCombine(const Tensor& assistInfoForCombine, const Tensor& expandX)
61-{
62- uint32_t supportedDim = 2;
63- ASSERT(DistributedErrorCode::INVALID_TENSOR_DIM, assistInfoForCombine.GetShape().size() == supportedDim)
64- << "The dim of \"assistInfoForCombine\" only "
65- << "supports " << supportedDim << ", but got " << assistInfoForCombine.GetShape().size();
66- 
67- int32_t assistInfoForCombineRow = assistInfoForCombine.GetShape(0);
68- int32_t expandXRow = expandX.GetShape(0);
69- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, assistInfoForCombineRow == expandXRow)
70- << "The first axis of \"assistInfoForCombine\" must be consistent "
71- << "with that of \"expandX\", but expandXRow=" << expandXRow
72- << ", assistInfoForCombineRow=" << assistInfoForCombineRow;
73- 
74- int32_t assistInfoForCombineCol = assistInfoForCombine.GetShape(1);
75- int32_t supportedAssistInfoForCombineCol = 3;
76- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, assistInfoForCombineCol == supportedAssistInfoForCombineCol)
77- << "The second axis of "
78- << "\"assistInfoForCombine\" must be " << supportedAssistInfoForCombineCol << ", but got "
79- << assistInfoForCombineCol;
80- 
81- ASSERT(DistributedErrorCode::INVALID_TENSOR_DTYPE, assistInfoForCombine.GetDataType() == DT_INT32)
82- << "The data type of \"assistInfoForCombine\" only supports "
83- << "DT_INT32, but got " << DataType2String(assistInfoForCombine.GetDataType());
84- 
85- ASSERT(
86- DistributedErrorCode::INVALID_TENSOR_FORMAT,
87- assistInfoForCombine.Format() == npu::tile_fwk::TileOpFormat::TILEOP_ND)
88- << "The format of "
89- << "\"assistInfoForCombine\" only supports ND, but got NZ";
90-}
91- 
92-void MoeDistributedCombineValidateRecvCounts(const Tensor& recvCounts)
93-{
94- ASSERT(DistributedErrorCode::INVALID_TENSOR_DIM, recvCounts.GetShape().size() == 1)
95- << "The dim of \"recvCounts\" only supports 1, but got " << recvCounts.GetShape().size();
96- 
97- int32_t recvCountsSize = recvCounts.GetShape(0);
98- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, recvCountsSize == 1)
99- << "The size of \"recvCounts\" must be 1, but recvCountsSize=" << recvCountsSize;
100- 
101- ASSERT(DistributedErrorCode::INVALID_TENSOR_DTYPE, recvCounts.GetDataType() == DT_INT32)
102- << "The data type of \"recvCounts\" only supports DT_INT32, but got "
103- << DataType2String(recvCounts.GetDataType());
104- 
105- ASSERT(DistributedErrorCode::INVALID_TENSOR_FORMAT, recvCounts.Format() == npu::tile_fwk::TileOpFormat::TILEOP_ND)
106- << "The format of \"recvCounts\" only "
107- << "supports ND, but got NZ";
108-}
109- 
110-void MoeDistributedCombineValidateExpertScales(const Tensor& expertScales)
111-{
112- uint32_t supportedDim = 2;
113- ASSERT(DistributedErrorCode::INVALID_TENSOR_DIM, expertScales.GetShape().size() == supportedDim)
114- << "The dim of \"expertScales\" only supports " << supportedDim << ", but got "
115- << expertScales.GetShape().size();
116- 
117- int32_t expertScalesRow = expertScales.GetShape(0);
118- int32_t supportedExpertScalesRow1 = 8;
119- int32_t supportedExpertScalesRow2 = 256;
120- ASSERT(
121- DistributedErrorCode::INVALID_TENSOR_SHAPE,
122- (expertScalesRow == supportedExpertScalesRow1) || (expertScalesRow == supportedExpertScalesRow2))
123- << "The "
124- << "first axis of \"expertScales\" only supports " << supportedExpertScalesRow1 << " or "
125- << supportedExpertScalesRow2 << ", but got " << expertScalesRow;
126- 
127- int32_t expertScalesCol = expertScales.GetShape(1);
128- int32_t supportedExpertScalesCol = 8;
129- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, expertScalesCol == supportedExpertScalesCol)
130- << "The second axis of \"expertScales\" only supports " << supportedExpertScalesCol << ", but got "
131- << expertScalesCol;
132- 
133- ASSERT(DistributedErrorCode::INVALID_TENSOR_DTYPE, expertScales.GetDataType() == DT_FP32)
134- << "The data type of \"expertScales\" only supports DT_FP32, but got "
135- << DataType2String(expertScales.GetDataType());
136- 
137- ASSERT(DistributedErrorCode::INVALID_TENSOR_FORMAT, expertScales.Format() == npu::tile_fwk::TileOpFormat::TILEOP_ND)
138- << "The format of \"expertScales\" only "
139- << "supports ND, but got NZ";
140-}
141- 
142-void MoeDistributedCombineValidateOut(const Tensor& out, const Tensor& expertScales, const Tensor& expandX)
143-{
144- uint32_t supportedDim = 2;
145- ASSERT(DistributedErrorCode::INVALID_TENSOR_DIM, out.GetShape().size() == supportedDim)
146- << "The dim of \"out\" only supports " << supportedDim << ", but got " << out.GetShape().size();
147- 
148- int32_t outRow = out.GetShape(0);
149- int32_t expertScalesRow = expertScales.GetShape(0);
150- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, outRow == expertScalesRow)
151- << "The first axis of \"out\" must be consistent with that of \"expertScales\", "
152- << "but expertScalesRow=" << expertScalesRow << ", outRow=" << outRow;
153- 
154- int32_t outCol = out.GetShape(1);
155- int32_t expandXCol = expandX.GetShape(1);
156- ASSERT(DistributedErrorCode::INVALID_TENSOR_SHAPE, outCol == expandXCol)
157- << "The second axis of \"out\" must be consistent with that of \"expandX\", but "
158- << "expandXCol=" << expandXCol << ", outCol=" << outCol;
159- 
160- ASSERT(DistributedErrorCode::INVALID_TENSOR_DTYPE, out.GetDataType() == expandX.GetDataType())
161- << "The data type of \"out\" must be consistent with that of "
162- << "\"expandX\", but data type of \"expandX\" is " << DataType2String(expandX.GetDataType()) << " and the "
163- << "data type of \"out\" is " << DataType2String(out.GetDataType());
164- 
165- ASSERT(DistributedErrorCode::INVALID_TENSOR_FORMAT, out.Format() == npu::tile_fwk::TileOpFormat::TILEOP_ND)
166- << "The format of \"out\" only supports ND, but got "
167- << "NZ";
168-}
169- 
170-void MoeDistributedCombineValidateGroup(const char* group)
171-{
172- ASSERT(DistributedErrorCode::NULLPTR, group != nullptr) << "\"group\" cannot be nullptr";
173- int32_t groupLen = std::strlen(group);
174- int32_t maxGroupLen = 128;
175- ASSERT(DistributedErrorCode::INVALID_GROUP_NAME, (groupLen >= 1) && (groupLen < maxGroupLen))
176- << "The length of \"group\" only supports [1, " << maxGroupLen << "), but got " << groupLen;
177-}
178- 
179-void MoeDistributedCombineValidateMoeEpWorldSize(int32_t epWorldSize)
180-{
181- int32_t supportedEpWorldSize1 = 4;
182- int32_t supportedEpWorldSize2 = 8;
183- ASSERT(
184- DistributedErrorCode::INVALID_WORLD_SIZE,
185- (epWorldSize == supportedEpWorldSize1) || (epWorldSize == supportedEpWorldSize2))
186- << "epWorldSize only "
187- << "supports " << supportedEpWorldSize1 << " or " << supportedEpWorldSize2 << ", but got " << epWorldSize;
188-}
189- 
190-void MoeDistributedCombineValidateMoeExpertNum(int32_t moeExpertNum)
191-{
192- int32_t supportedMoeExpertNum = 160;
193- ASSERT(DistributedErrorCode::INVALID_MOE_EXPERT_NUM, moeExpertNum == supportedMoeExpertNum)
194- << "moeExpertNum only supports " << supportedMoeExpertNum << ", but "
195- << "got " << moeExpertNum;
196-}
197- 
198-void TiledMoeDistributedCombineSend(
199- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
200- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op)
201-{
202- ASSERT(DistributedErrorCode::INVALID_OPERAND_NUM, iOperand.size() == 5UL)
203- << "TiledMoeDistributedCombineSend iOperand size is not equal to 5";
204- ASSERT(DistributedErrorCode::INVALID_OPERAND_NUM, oOperand.size() == 1UL)
205- << "TiledMoeDistributedCombineSend oOperand size is not equal to 1";
206- auto expandX = iOperand[0];
207- auto assistInfoForCombine = iOperand[1];
208- auto recvCounts = iOperand[2];
209- auto shmemData = iOperand[3];
210- auto shmemSignal = iOperand[4];
211- auto out = oOperand[0];
212- int64_t hiddenSize = expandX->shape[1];
213- 
214- int64_t dataByteSize = BytesOf(expandX->Datatype());
215- ASSERT(DistributedErrorCode::DIVISION_BY_ZERO, dataByteSize != 0) << "iOperand expandX dType size cannot be zero";
216- int64_t paddedColShape = AlignUp(dataByteSize * hiddenSize, COPY_BLOCK_BYTE_SIZE) / dataByteSize;
217- Shape assistInfoForCombineShape =
218- Shape{static_cast<int64_t>(COPY_BLOCK_BYTE_SIZE) / static_cast<int64_t>(BytesOf(DT_INT32))};
219- Shape signalShape = Shape{static_cast<int64_t>(REPEAT_BYTE) / static_cast<int64_t>(BytesOf(DT_INT32))};
220- 
221- MoeCombineAttr distOpAttr;
222- op.GetAttr(OpAttributeKey::distOpAttr, distOpAttr);
223- 
224- CreateTileOp(
225- tileShape, [&](int32_t tileIndex, int32_t rowOffset, int32_t colOffset, int32_t rowShape, int32_t colShape) {
226- (void)tileIndex;
227- 
228- auto expandXTile = expandX->View(function, {rowShape, colShape}, {rowOffset, colOffset});
229- auto dataBuffer = std::make_shared<LogicalTensor>(function, expandX->Datatype(), Shape{hiddenSize});
230- auto assistInfoForCombineBuffer =
231- std::make_shared<LogicalTensor>(function, DT_INT32, assistInfoForCombineShape);
232- auto signalBuffer = std::make_shared<LogicalTensor>(function, DT_INT32, signalShape);
233- 
234- auto& tileOp = function.AddOperation(
235- Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND,
236- {expandXTile, assistInfoForCombine, recvCounts, shmemData, shmemSignal},
237- {out, dataBuffer, assistInfoForCombineBuffer, signalBuffer});
238- 
239- distOpAttr.paddedColShape = paddedColShape;
240- tileOp.SetAttr(OpAttributeKey::distOpAttr, distOpAttr);
241- tileOp.SetAttr(OpAttributeKey::dontTouch, true);
242- });
243-}
244- 
245-void TiledMoeDistributedCombineReceive(
246- Function& function, const TileShape& tileShape, const std::vector<std::shared_ptr<LogicalTensor>>& iOperand,
247- const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op)
248-{
249- (void)op;
250- 
251- ASSERT(DistributedErrorCode::INVALID_OPERAND_NUM, iOperand.size() == 4UL)
252- << "TiledMoeDistributedCombineReceive iOperand size is not equal to 4";
253- ASSERT(DistributedErrorCode::INVALID_OPERAND_NUM, oOperand.size() == 1UL)
254- << "TiledMoeDistributedCombineReceive oOperand size is not equal to 1";
255- auto predToken = iOperand[0];
256- auto expertScales = iOperand[1];
257- auto shmemDataThisRank = iOperand[2];
258- auto shmemSignalThisRank = iOperand[3];
259- auto out = oOperand[0];
260- int64_t topK = expertScales->shape[1];
261- int64_t hiddenSize = out->shape[1];
262- 
263- int64_t dataByteSize = BytesOf(out->Datatype());
264- ASSERT(DistributedErrorCode::DIVISION_BY_ZERO, dataByteSize != 0) << "oOperand out dType size cannot be zero";
265- int64_t paddedColShape = AlignUp(dataByteSize * hiddenSize, COPY_BLOCK_BYTE_SIZE) / dataByteSize;
266- int64_t floatByteSize = BytesOf(DataType::DT_FP32);
267- ASSERT(DistributedErrorCode::DIVISION_BY_ZERO, floatByteSize != 0) << "floatByteSize cannot be zero";
268- int64_t floatEleNum = AlignUp(floatByteSize * paddedColShape, REPEAT_BYTE) / floatByteSize;
269- 
270- MoeCombineAttr distOpAttr;
271- distOpAttr.topK = topK;
272- 
273- CreateTileOp(
274- tileShape, [&](int32_t tileIndex, int32_t rowOffset, int32_t colOffset, int32_t rowShape, int32_t colShape) {
275- (void)tileIndex;
276- 
277- auto shmemDataTile = shmemDataThisRank->View(
278- function, {1, 1, topK * rowShape, colShape}, {0, 0, topK * rowOffset, colOffset});
279- auto outTile = out->View(function, {rowShape, colShape}, {rowOffset, colOffset});
280- auto mulFp32Buffer = std::make_shared<LogicalTensor>(function, DT_FP32, Shape{floatEleNum});
281- auto sumFp32Buffer = std::make_shared<LogicalTensor>(function, DT_FP32, Shape{floatEleNum});
282- auto outBuffer = std::make_shared<LogicalTensor>(function, out->Datatype(), Shape{hiddenSize});
283- 
284- auto& tileOp = function.AddOperation(
285- Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE,
286- {predToken, expertScales, shmemDataTile, shmemSignalThisRank},
287- {outTile, mulFp32Buffer, sumFp32Buffer, outBuffer});
288- 
289- distOpAttr.paddedColShape = paddedColShape;
290- distOpAttr.rowOffset = rowOffset;
291- distOpAttr.rowShape = rowShape;
292- tileOp.SetAttr(OpAttributeKey::distOpAttr, distOpAttr);
293- });
294-}
295- 
296-void CreateShmemTensor(
297- Tensor& shmemTensor, int32_t rankSize, int32_t hcclGroupIndex, DataType dataType, const Shape& shape,
298- uint64_t memType = 0)
299-{
300- auto& function = *Program::GetInstance().GetCurrentFunction();
301- Shape shmemShape{rankSize};
302- shmemShape.insert(shmemShape.end(), shape.begin(), shape.end());
303- auto shmemTensorInner = std::make_shared<LogicalTensor>(function, dataType, shmemShape);
304- shmemTensor = shmemTensorInner;
305- Program::GetInstance().GetTensorSlotManager()->TensorWrite(shmemTensor, SlotProperty::SHMEM_TENSOR);
306- auto& op = function.AddOperation(Opcode::OP_BIND_TENSOR, {}, {shmemTensorInner});
307- op.SetAttribute(
308- OpAttributeKey::bindTensor,
309- BindTensor(
310- hcclGroupIndex, memType,
311- BytesOf(dataType) * std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int64_t>())));
312-}
313- 
314-Tensor MoeDistributedCombineSend(
315- const Tensor& in, const Tensor& assistInfoForCombine, const Tensor& recvCounts, const Tensor& shmemData,
316- const Tensor& shmemSignal, int32_t topK)
317-{
318- auto& function = *Program::GetInstance().GetCurrentFunction();
319- auto out = std::make_shared<LogicalTensor>(function, DT_INT32, Shape{1});
320- auto& op = function.AddOperation(
321- Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND,
322- {in.GetStorage(), assistInfoForCombine.GetStorage(), recvCounts.GetStorage(), shmemData.GetStorage(),
323- shmemSignal.GetStorage()},
324- {out});
325- MoeCombineAttr distOpAttr;
326- distOpAttr.topK = topK;
327- op.SetAttr(OpAttributeKey::distOpAttr, distOpAttr);
328- return out;
329-}
330- 
331-Tensor MoeDistributedCombineReceive(
332- const Tensor& predToken, const Tensor& expertScales, const Tensor& shmemData, const Tensor& shmemSignal)
333-{
334- auto& function = *Program::GetInstance().GetCurrentFunction();
335- int32_t batchSize = expertScales.GetShape(0);
336- int32_t hiddenSize = shmemData.GetShape(3);
337- auto out = std::make_shared<LogicalTensor>(function, shmemData.GetDataType(), Shape{batchSize, hiddenSize});
338- function.AddOperation(
339- Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE,
340- {predToken.GetStorage(), expertScales.GetStorage(), shmemData.GetStorage(), shmemSignal.GetStorage()}, {out});
341- return out;
342-}
343- 
344-void MoeDistributedCombineValidate(
345- const Tensor& expandX, const Tensor& assistInfoForCombine, const Tensor& recvCounts, const Tensor& expertScales,
346- const char* group, uint32_t epWorldSize, uint32_t moeExpertNum, uint32_t sharedExpertNum,
347- uint32_t sharedExpertRankNum, Tensor& out)
348-{
349- (void)sharedExpertNum;
350- (void)sharedExpertRankNum;
351- 
352- MoeDistributedCombineValidateExpandX(expandX, expertScales, epWorldSize, moeExpertNum);
353- MoeDistributedCombineValidateAssistInfoForCombine(assistInfoForCombine, expandX);
354- MoeDistributedCombineValidateRecvCounts(recvCounts);
355- MoeDistributedCombineValidateExpertScales(expertScales);
356- MoeDistributedCombineValidateOut(out, expertScales, expandX);
357- MoeDistributedCombineValidateGroup(group);
358- MoeDistributedCombineValidateMoeEpWorldSize(epWorldSize);
359- MoeDistributedCombineValidateMoeExpertNum(moeExpertNum);
360-}
361- 
362-void MoeDistributedCombine(
363- const Tensor& expandX, const Tensor& assistInfoForCombine, const Tensor& recvCounts, const Tensor& expertScales,
364- const char* group, uint32_t epWorldSize, uint32_t moeExpertNum, uint32_t sharedExpertNum,
365- uint32_t sharedExpertRankNum, Tensor& out)
366-{
367- MoeDistributedCombineValidate(
368- expandX, assistInfoForCombine, recvCounts, expertScales, group, epWorldSize, moeExpertNum, sharedExpertNum,
369- sharedExpertRankNum, out);
370- 
371- int32_t batchSize = expertScales.GetShape(0);
372- int32_t topK = expertScales.GetShape(1);
373- int32_t hiddenSize = expandX.GetShape(1);
374- 
375- int32_t shmemDataRow = topK * batchSize;
376- Shape shmemDataShape = {1, shmemDataRow, hiddenSize};
377- int32_t shmemSignalCol = SAME_ADDR_BYTE_SIZE / BytesOf(DataType::DT_FP32);
378- Shape shmemSignalShape = {batchSize, shmemSignalCol};
379- 
380- Tensor shmemData;
381- Tensor shmemSignal;
382- int32_t hcclGroupIndex = static_cast<int>(CommGroupRecorder::GetInstance().Input(std::string(group)));
383- LOOP("CreateShmemTensor", FunctionType::DYNAMIC_LOOP, index, LoopRange(1))
384- {
385- (void)index;
386- CreateShmemTensor(shmemData, epWorldSize, hcclGroupIndex, expandX.GetDataType(), shmemDataShape);
387- CreateShmemTensor(shmemSignal, epWorldSize, hcclGroupIndex, DT_INT32, shmemSignalShape);
388- }
389- LOOP("MoeDistributedCombine", FunctionType::DYNAMIC_LOOP, index, LoopRange(1))
390- {
391- (void)index;
392- 
393- int32_t expandXRow = expandX.GetShape(0);
394- int32_t aivNum = 40;
395- TileShape::Current().SetDistTile(
396- {expandXRow / aivNum, aivNum, expandXRow % aivNum}, {hiddenSize, 1, 0}, {0, 0, 0});
397- auto sendOut =
398- MoeDistributedCombineSend(expandX, assistInfoForCombine, recvCounts, shmemData, shmemSignal, topK);
399- 
400- SymbolicScalar thisRank = GetHcclRankId(group);
401- auto shmemDataThisRank =
402- View(shmemData, {1, 1, shmemDataRow, hiddenSize}, std::vector<SymbolicScalar>{thisRank, 0, 0, 0});
403- auto shmemSignalThisRank =
404- View(shmemSignal, {1, batchSize, shmemSignalCol}, std::vector<SymbolicScalar>{thisRank, 0, 0});
405- TileShape::Current().SetDistTile({1, batchSize, 0}, {hiddenSize, 1, 0}, {0, 0, 0});
406- out = MoeDistributedCombineReceive(sendOut, expertScales, shmemDataThisRank, shmemSignalThisRank);
407- }
408-}
409- 
410-void MoeDistributedCombineV2(
411- const Tensor& expandX, const Tensor& assistInfoForCombine, const Tensor& recvCounts, const Tensor& expertScales,
412- const char* group, uint32_t epWorldSize, uint32_t moeExpertNum, uint32_t sharedExpertNum,
413- uint32_t sharedExpertRankNum, Tensor& out)
414-{
415- MoeDistributedCombineValidate(
416- expandX, assistInfoForCombine, recvCounts, expertScales, group, epWorldSize, moeExpertNum, sharedExpertNum,
417- sharedExpertRankNum, out);
418- 
419- int32_t batchSize = expertScales.GetShape(0);
420- int32_t topK = expertScales.GetShape(1);
421- int32_t hiddenSize = expandX.GetShape(1);
422- 
423- auto shmemTensor = CreateShmemTensor(group, epWorldSize, expandX.GetDataType(), {batchSize * topK, hiddenSize});
424- 
425- SymbolicScalar recvCountsScalar = GetTensorData(recvCounts, {0});
426- std::set<int> unrollList = {64, 32, 16, 8, 4, 2, 1};
427- LOOP("MoeDistributedCombineSend", FunctionType::DYNAMIC_LOOP, rowIndex, LoopRange(recvCountsScalar), unrollList)
428- {
429- SymbolicScalar rankId = GetTensorData(assistInfoForCombine, {rowIndex, 0});
430- SymbolicScalar tokenId = GetTensorData(assistInfoForCombine, {rowIndex, 1});
431- SymbolicScalar kOffset = GetTensorData(assistInfoForCombine, {rowIndex, 2});
432- 
433- Tensor expandXTile = View(expandX, {1, hiddenSize}, {rowIndex, 0});
434- auto shmemDataTile = ShmemView(shmemTensor, {1, hiddenSize}, {topK * tokenId + kOffset, 0});
435- TileShape::Current().SetVecTile({1, hiddenSize});
436- Tensor predToken(DT_INT32, {1, 1}, "sendPredToken");
437- Tensor shmemPutOut = ShmemPut(expandXTile, shmemDataTile, rankId, AtomicType::SET, predToken);
438- 
439- auto shmemSignalTile = ShmemView(shmemTensor, {1, hiddenSize}, {tokenId, 0});
440- ShmemSignal(shmemSignalTile, rankId, rankId, 1, AtomicType::ADD, shmemPutOut);
441- }
442- 
443- SymbolicScalar thisRank = GetHcclRankId(group);
444- LOOP("MoeDistributedCombineReceive", FunctionType::DYNAMIC_LOOP, tokenId, LoopRange(batchSize))
445- {
446- auto shmemSignalTile = ShmemView(shmemTensor, {1, hiddenSize}, {tokenId, 0});
447- TileShape::Current().SetVecTile({1, hiddenSize});
448- Tensor predToken(DT_INT32, {1, 1}, "receivePredToken");
449- Tensor waitUntilOut = ShmemWaitUntil(shmemSignalTile, thisRank, OpType::EQ, topK, true, predToken);
450- 
451- TileShape::Current().SetVecTile({topK, hiddenSize});
452- auto shmemDataTile = ShmemView(shmemTensor, {topK, hiddenSize}, {topK * tokenId, 0});
453- Tensor shmemGetOutFp16 = ShmemGet(shmemDataTile, thisRank, waitUntilOut);
454- 
455- TileShape::Current().SetVecTile({topK / 2, hiddenSize});
456- Tensor shmemGetOutFp32 = npu::tile_fwk::Cast(shmemGetOutFp16, DT_FP32);
457- 
458- Tensor expertScalesTile = View(expertScales, {1, topK}, {tokenId, 0});
459- int64_t kTileShape = AlignUp(topK, 16);
460- int64_t l0bSize = 65536;
461- ASSERT(DistributedErrorCode::DIVISION_BY_ZERO, (BytesOf(DT_FP32) != 0) && (kTileShape != 0))
462- << "Divisor kTileShape cannot be zero";
463- int64_t nTileShape = l0bSize / BytesOf(DT_FP32) / kTileShape;
464- TileShape::Current().SetCubeTile({1, 1}, {kTileShape, kTileShape}, {nTileShape, nTileShape});
465- Tensor matmulOutFp32 = Matrix::Matmul(DT_FP32, expertScalesTile, shmemGetOutFp32);
466- 
467- Tensor matmulOutFp16 = npu::tile_fwk::Cast(matmulOutFp32, DT_BF16);
468- 
469- Assemble(matmulOutFp16, {tokenId, 0}, out);
470- }
471-}
472- 
473-} // namespace npu::tile_fwk::Distributed
@@ -1241,19 +1241,6 @@ void OpcodeManager::RegisterDistribute()
1241 Opcode::OP_BIND_TENSOR, OpCoreType::ANY, "BIND_TENSOR", {}, {MemoryType::MEM_DEVICE_DDR},1241 Opcode::OP_BIND_TENSOR, OpCoreType::ANY, "BIND_TENSOR", {}, {MemoryType::MEM_DEVICE_DDR},
1242 {"TileOp::Distributed::ShmemGet", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,1242 {"TileOp::Distributed::ShmemGet", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1243 {OP_ATTR_PREFIX + "BindTensor"});1243 {OP_ATTR_PREFIX + "BindTensor"});
1244- RegisterInfo(
1245- Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND, OpCoreType::ANY, "MOE_DISTRIBUTED_COMBINE_SEND",
1246- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_DEVICE_DDR,
1247- MemoryType::MEM_DEVICE_DDR},
1248- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_UB, MemoryType::MEM_UB},
1249- {"TileOp::Distributed::MoeDistributedCombineSend", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1250- {OpAttributeKey::requiresBoundaryCopy});
1251- RegisterInfo(
1252- Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE, OpCoreType::ANY, "MOE_DISTRIBUTED_COMBINE_RECEIVE",
1253- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},
1254- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_UB, MemoryType::MEM_UB},
1255- {"TileOp::Distributed::MoeDistributedCombineReceive", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1256- {OpAttributeKey::requiresBoundaryCopy});
1257}1244}
1258 1245 
1259void OpcodeManager::RegisterCommon()1246void OpcodeManager::RegisterCommon()
@@ -1342,50 +1329,6 @@ void OpcodeManager::RegisterCommon()
1342 RegisterInfo(1329 RegisterInfo(
1343 Opcode::OP_BAR_ALL, OpCoreType::ANY, "BAR.ALL", {}, {}, {"BAR.ALL", PIPE_S, PIPE_S, CoreType::AIC},1330 Opcode::OP_BAR_ALL, OpCoreType::ANY, "BAR.ALL", {}, {}, {"BAR.ALL", PIPE_S, PIPE_S, CoreType::AIC},
1344 OpCalcType::SYNC);1331 OpCalcType::SYNC);
1345- RegisterInfo(
1346- Opcode::OP_SEND_TO_ROUTING_EXPERT, OpCoreType::ANY, "SEND_TO_ROUTING_EXPERT",
1347- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},
1348- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_UB, MemoryType::MEM_UB},
1349- {"TileOp::Distributed::SendToRoutingExpert", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1350- {OP_ATTR_PREFIX + "distributed"});
1351- RegisterInfo(
1352- Opcode::OP_SEND_TO_SHARED_EXPERT, OpCoreType::ANY, "SEND_TO_SHARED_EXPERT",
1353- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR}, {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB},
1354- {"TileOp::Distributed::SendToSharedExpert", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1355- {OpAttributeKey::requiresBoundaryCopy});
1356- RegisterInfo(
1357- Opcode::OP_COPY_TO_LOCAL_EXPERT, OpCoreType::ANY, "COPY_TO_LOCAL_EXPERT", {MemoryType::MEM_DEVICE_DDR},
1358- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB},
1359- {"TileOp::Distributed::CopyToLocalExpert", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1360- {OpAttributeKey::requiresBoundaryCopy});
1361- RegisterInfo(
1362- Opcode::OP_DISPATCH_SET_FLAG, OpCoreType::ANY, "DISPATCH_SET_FLAG",
1363- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},
1364- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB, MemoryType::MEM_UB, MemoryType::MEM_UB},
1365- {"TileOp::Distributed::DispatchSetFlag", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1366- {OpAttributeKey::requiresBoundaryCopy});
1367- RegisterInfo(
1368- Opcode::OP_FFN_SCHED, OpCoreType::ANY, "FFN_SCHED", {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},
1369- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB},
1370- {"TileOp::Distributed::FFNSched", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1371- {OpAttributeKey::requiresBoundaryCopy});
1372- RegisterInfo(
1373- Opcode::OP_FFN_BATCHING, OpCoreType::ANY, "FFN_BATCHING",
1374- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},
1375- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB},
1376- {"TileOp::Distributed::FFNBatching", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1377- {OpAttributeKey::requiresBoundaryCopy});
1378- RegisterInfo(
1379- Opcode::OP_FFN_COMBINEINFO, OpCoreType::ANY, "FFN_COMBINEINFO",
1380- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR},
1381- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB},
1382- {"TileOp::Distributed::FFNCombineInfo", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1383- {OpAttributeKey::requiresBoundaryCopy});
1384- RegisterInfo(
1385- Opcode::OP_FFN_VALIDCNT, OpCoreType::ANY, "FFN_VALIDCNT",
1386- {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_DEVICE_DDR}, {MemoryType::MEM_DEVICE_DDR, MemoryType::MEM_UB},
1387- {"TileOp::Distributed::FFNValidCnt", PIPE_S, PIPE_S, CoreType::AIV}, OpCalcType::DISTRIBUTED,
1388- {OpAttributeKey::requiresBoundaryCopy});
1389 RegisterInfo(1332 RegisterInfo(
1390 Opcode::OP_AICPU_CALL_AIC, OpCoreType::ANY, "AICPU_CALL_AIC", {}, {},1333 Opcode::OP_AICPU_CALL_AIC, OpCoreType::ANY, "AICPU_CALL_AIC", {}, {},
1391 {"TileOp::AicpuCall", PIPE_S, PIPE_S, CoreType::AIC}, OpCalcType::SYS);1334 {"TileOp::AicpuCall", PIPE_S, PIPE_S, CoreType::AIC}, OpCalcType::SYS);
@@ -307,14 +307,6 @@ enum class Opcode {
307 OP_BAR_ALL,307 OP_BAR_ALL,
308 308 
309 // Distributed309 // Distributed
310- OP_SEND_TO_ROUTING_EXPERT,
311- OP_SEND_TO_SHARED_EXPERT,
312- OP_COPY_TO_LOCAL_EXPERT,
313- OP_DISPATCH_SET_FLAG,
314- OP_FFN_SCHED,
315- OP_FFN_BATCHING,
316- OP_FFN_COMBINEINFO,
317- OP_FFN_VALIDCNT,
318 OP_SHMEM_SET,310 OP_SHMEM_SET,
319 OP_SHMEM_PUT,311 OP_SHMEM_PUT,
320 OP_SHMEM_STORE,312 OP_SHMEM_STORE,
@@ -323,8 +315,6 @@ enum class Opcode {
323 OP_SHMEM_GET,315 OP_SHMEM_GET,
324 OP_SHMEM_LOAD,316 OP_SHMEM_LOAD,
325 OP_BIND_TENSOR,317 OP_BIND_TENSOR,
326- OP_MOE_DISTRIBUTED_COMBINE_SEND,
327- OP_MOE_DISTRIBUTED_COMBINE_RECEIVE,
328 318 
329 // Quantization319 // Quantization
330 OP_QUANTIZE_SYM, // Symmetric quantization: FP32 -> INT8320 OP_QUANTIZE_SYM, // Symmetric quantization: FP32 -> INT8
@@ -551,19 +541,16 @@ public:
551 541 
552 inline bool IsCopyOut(Opcode opCode) const542 inline bool IsCopyOut(Opcode opCode) const
553 {543 {
554- return opCode == Opcode::OP_COPY_OUT || opCode == Opcode::OP_UB_COPY_OUT || opCode == Opcode::OP_L0C_COPY_OUT ||544+ return opCode == Opcode::OP_COPY_OUT || opCode == Opcode::OP_UB_COPY_OUT ||
555- opCode == Opcode::OP_L1_COPY_OUT || opCode == Opcode::OP_TRANSPOSE_MOVEOUT ||545+ opCode == Opcode::OP_L0C_COPY_OUT || opCode == Opcode::OP_L1_COPY_OUT ||
556- opCode == Opcode::OP_INDEX_OUTCAST || opCode == Opcode::OP_INDEX_PUT || opCode == Opcode::OP_FFN_SCHED ||546+ opCode == Opcode::OP_TRANSPOSE_MOVEOUT || opCode == Opcode::OP_INDEX_OUTCAST ||
557- opCode == Opcode::OP_FFN_BATCHING || opCode == Opcode::OP_FFN_COMBINEINFO ||547+ opCode == Opcode::OP_INDEX_PUT || opCode == Opcode::OP_INDEX_ADD ||
558- opCode == Opcode::OP_INDEX_ADD || opCode == Opcode::OP_FFN_VALIDCNT ||
559 opCode == Opcode::OP_NCHW2NC1HWC0 || opCode == Opcode::OP_NCHW2Fractal_Z ||548 opCode == Opcode::OP_NCHW2NC1HWC0 || opCode == Opcode::OP_NCHW2Fractal_Z ||
560 opCode == Opcode::OP_NC1HWC02NCHW || opCode == Opcode::OP_NCDHW2NDC1HWC0 ||549 opCode == Opcode::OP_NC1HWC02NCHW || opCode == Opcode::OP_NCDHW2NDC1HWC0 ||
561 opCode == Opcode::OP_NCDHW2FRACTAL_Z_3D || opCode == Opcode::OP_NDC1HWC02NCDHW ||550 opCode == Opcode::OP_NCDHW2FRACTAL_Z_3D || opCode == Opcode::OP_NDC1HWC02NCDHW ||
562- opCode == Opcode::OP_COPY_TO_LOCAL_EXPERT || opCode == Opcode::OP_SHMEM_PUT ||551+ opCode == Opcode::OP_SHMEM_PUT || opCode == Opcode::OP_SHMEM_SIGNAL ||
563- opCode == Opcode::OP_SHMEM_SIGNAL || opCode == Opcode::OP_SHMEM_GET ||552+ opCode == Opcode::OP_SHMEM_GET || opCode == Opcode::OP_SHMEM_STORE ||
564- opCode == Opcode::OP_SHMEM_STORE || opCode == Opcode::OP_RESHAPE_COPY_OUT ||553+ opCode == Opcode::OP_RESHAPE_COPY_OUT || opCode == Opcode::OP_L0C_COPY_OUT_CONV ||
565- opCode == Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND ||
566- opCode == Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE || opCode == Opcode::OP_L0C_COPY_OUT_CONV ||
567 opCode == Opcode::OP_L0C_RESHAPE_COPY_OUT;554 opCode == Opcode::OP_L0C_RESHAPE_COPY_OUT;
568 }555 }
569 556 
@@ -575,13 +562,8 @@ public:
575 {562 {
576 return opCode == Opcode::OP_SHMEM_WAIT_UNTIL || opCode == Opcode::OP_SHMEM_PUT ||563 return opCode == Opcode::OP_SHMEM_WAIT_UNTIL || opCode == Opcode::OP_SHMEM_PUT ||
577 opCode == Opcode::OP_SHMEM_SIGNAL || opCode == Opcode::OP_SHMEM_GET ||564 opCode == Opcode::OP_SHMEM_SIGNAL || opCode == Opcode::OP_SHMEM_GET ||
578- opCode == Opcode::OP_FFN_VALIDCNT || opCode == Opcode::OP_SHMEM_SET ||565+ opCode == Opcode::OP_SHMEM_SET || opCode == Opcode::OP_SHMEM_STORE ||
579- opCode == Opcode::OP_SHMEM_STORE || opCode == Opcode::OP_SHMEM_LOAD ||566+ opCode == Opcode::OP_SHMEM_LOAD;
580- opCode == Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND ||
581- opCode == Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE || opCode == Opcode::OP_FFN_BATCHING ||
582- opCode == Opcode::OP_SEND_TO_ROUTING_EXPERT || opCode == Opcode::OP_COPY_TO_LOCAL_EXPERT ||
583- opCode == Opcode::OP_DISPATCH_SET_FLAG || opCode == Opcode::OP_FFN_SCHED ||
584- opCode == Opcode::OP_FFN_COMBINEINFO;
585 }567 }
586 568 
587private:569private:
@@ -1055,23 +1037,13 @@ const std::unordered_set<Opcode> LOGICALNOT_OPS{Opcode::OP_LOGICALNOT};
1055const std::unordered_set<Opcode> LOGICALAND_OPS{Opcode::OP_LOGICALAND};1037const std::unordered_set<Opcode> LOGICALAND_OPS{Opcode::OP_LOGICALAND};
1056 1038 
1057const std::unordered_set<Opcode> DISTRIBUTED_OPS{1039const std::unordered_set<Opcode> DISTRIBUTED_OPS{
1058- Opcode::OP_SEND_TO_ROUTING_EXPERT,
1059- Opcode::OP_SEND_TO_SHARED_EXPERT,
1060- Opcode::OP_COPY_TO_LOCAL_EXPERT,
1061- Opcode::OP_DISPATCH_SET_FLAG,
1062- Opcode::OP_FFN_SCHED,
1063- Opcode::OP_FFN_BATCHING,
1064- Opcode::OP_FFN_COMBINEINFO,
1065- Opcode::OP_FFN_VALIDCNT,
1066 Opcode::OP_SHMEM_PUT,1040 Opcode::OP_SHMEM_PUT,
1067 Opcode::OP_SHMEM_SIGNAL,1041 Opcode::OP_SHMEM_SIGNAL,
1068 Opcode::OP_SHMEM_GET,1042 Opcode::OP_SHMEM_GET,
1069- Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE,
1070 Opcode::OP_BIND_TENSOR,1043 Opcode::OP_BIND_TENSOR,
1071 Opcode::OP_SHMEM_STORE,1044 Opcode::OP_SHMEM_STORE,
1072 Opcode::OP_SHMEM_LOAD,1045 Opcode::OP_SHMEM_LOAD,
1073- Opcode::OP_SHMEM_SET,1046+ Opcode::OP_SHMEM_SET};
1074- Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND};
1075 1047 
1076const std::unordered_set<Opcode> LASTUSE_OPS{1048const std::unordered_set<Opcode> LASTUSE_OPS{
1077 Opcode::OP_ADD, Opcode::OP_SUB, Opcode::OP_MUL, Opcode::OP_DIV,1049 Opcode::OP_ADD, Opcode::OP_SUB, Opcode::OP_MUL, Opcode::OP_DIV,
@@ -1101,14 +1073,11 @@ inline bool IsCopyOut(const Opcode& op)
1101{1073{
1102 return (1074 return (
1103 op == Opcode::OP_COPY_OUT || op == Opcode::OP_L0C_COPY_OUT || op == Opcode::OP_TRANSPOSE_MOVEOUT ||1075 op == Opcode::OP_COPY_OUT || op == Opcode::OP_L0C_COPY_OUT || op == Opcode::OP_TRANSPOSE_MOVEOUT ||
1104- op == Opcode::OP_INDEX_OUTCAST || op == Opcode::OP_FFN_SCHED || op == Opcode::OP_FFN_BATCHING ||1076+ op == Opcode::OP_INDEX_OUTCAST || op == Opcode::OP_INDEX_PUT || op == Opcode::OP_SHMEM_PUT ||
1105- op == Opcode::OP_INDEX_PUT || op == Opcode::OP_FFN_COMBINEINFO || op == Opcode::OP_FFN_VALIDCNT ||1077+ op == Opcode::OP_SHMEM_SIGNAL || op == Opcode::OP_SHMEM_GET || op == Opcode::OP_SHMEM_SET ||
1106- op == Opcode::OP_COPY_TO_LOCAL_EXPERT || op == Opcode::OP_SHMEM_PUT || op == Opcode::OP_SHMEM_SIGNAL ||1078+ op == Opcode::OP_RESHAPE_COPY_OUT || op == Opcode::OP_SHMEM_STORE || op == Opcode::OP_NCHW2NC1HWC0 ||
1107- op == Opcode::OP_SHMEM_GET || op == Opcode::OP_SHMEM_SET || op == Opcode::OP_RESHAPE_COPY_OUT ||1079+ op == Opcode::OP_NCHW2Fractal_Z || op == Opcode::OP_NC1HWC02NCHW || op == Opcode::OP_NDC1HWC02NCDHW ||
1108- op == Opcode::OP_SHMEM_STORE || op == Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE ||1080+ op == Opcode::OP_NCDHW2NDC1HWC0 || op == Opcode::OP_NCDHW2FRACTAL_Z_3D || op == Opcode::OP_INDEX_ADD ||
1109- op == Opcode::OP_NCHW2NC1HWC0 || op == Opcode::OP_NCHW2Fractal_Z || op == Opcode::OP_NC1HWC02NCHW ||
1110- op == Opcode::OP_NDC1HWC02NCDHW || op == Opcode::OP_NCDHW2NDC1HWC0 || op == Opcode::OP_NCDHW2FRACTAL_Z_3D ||
1111- op == Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND || op == Opcode::OP_INDEX_ADD ||
1112 op == Opcode::OP_L0C_COPY_OUT_CONV || op == Opcode::OP_L0C_RESHAPE_COPY_OUT);1081 op == Opcode::OP_L0C_COPY_OUT_CONV || op == Opcode::OP_L0C_RESHAPE_COPY_OUT);
1113}1082}
1114 1083 
@@ -528,20 +528,13 @@ public:
528 Opcode::OP_NCDHW2NDC1HWC0,528 Opcode::OP_NCDHW2NDC1HWC0,
529 Opcode::OP_NCDHW2FRACTAL_Z_3D,529 Opcode::OP_NCDHW2FRACTAL_Z_3D,
530 Opcode::OP_NDC1HWC02NCDHW,530 Opcode::OP_NDC1HWC02NCDHW,
531- Opcode::OP_FFN_SCHED,
532- Opcode::OP_FFN_BATCHING,
533- Opcode::OP_FFN_COMBINEINFO,
534- Opcode::OP_FFN_VALIDCNT,
535 Opcode::OP_SHMEM_PUT,531 Opcode::OP_SHMEM_PUT,
536 Opcode::OP_SHMEM_STORE,532 Opcode::OP_SHMEM_STORE,
537 Opcode::OP_SHMEM_SIGNAL,533 Opcode::OP_SHMEM_SIGNAL,
538 Opcode::OP_SHMEM_GET,534 Opcode::OP_SHMEM_GET,
539 Opcode::OP_SHMEM_LOAD,535 Opcode::OP_SHMEM_LOAD,
540 Opcode::OP_SHMEM_SET,536 Opcode::OP_SHMEM_SET,
541- Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND,
542- Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE,
543 Opcode::OP_GATHER_IN_UB,537 Opcode::OP_GATHER_IN_UB,
544- Opcode::OP_COPY_TO_LOCAL_EXPERT,
545 Opcode::OP_L1_COPY_IN_A_SCALE,538 Opcode::OP_L1_COPY_IN_A_SCALE,
546 Opcode::OP_L1_COPY_IN_B_SCALE,539 Opcode::OP_L1_COPY_IN_B_SCALE,
547 Opcode::OP_L1_TO_L0A_SCALE,540 Opcode::OP_L1_TO_L0A_SCALE,
@@ -1988,38 +1988,6 @@ void ExpandOperationInto(
1988 TiledMaxpool(function, tileShape, iOperand[0], oOperand[0], op);1988 TiledMaxpool(function, tileShape, iOperand[0], oOperand[0], op);
1989 break;1989 break;
1990 }1990 }
1991- case Opcode::OP_SEND_TO_ROUTING_EXPERT: {
1992- npu::tile_fwk::Distributed::TiledSendToRoutingExpert(function, tileShape, iOperand, oOperand, op);
1993- break;
1994- }
1995- case Opcode::OP_SEND_TO_SHARED_EXPERT: {
1996- npu::tile_fwk::Distributed::TiledSendToSharedExpert(function, tileShape, iOperand, oOperand, op);
1997- break;
1998- }
1999- case Opcode::OP_COPY_TO_LOCAL_EXPERT: {
2000- npu::tile_fwk::Distributed::TiledCopyToLocalExpert(function, tileShape, iOperand, oOperand, op);
2001- break;
2002- }
2003- case Opcode::OP_DISPATCH_SET_FLAG: {
2004- npu::tile_fwk::Distributed::TiledDispatchSetFlag(function, tileShape, iOperand, oOperand, op);
2005- break;
2006- }
2007- case Opcode::OP_FFN_SCHED: {
2008- npu::tile_fwk::Distributed::TiledDispatchFFNSched(function, tileShape, iOperand, oOperand, op);
2009- break;
2010- }
2011- case Opcode::OP_FFN_BATCHING: {
2012- npu::tile_fwk::Distributed::TiledDispatchFFNBatching(function, tileShape, iOperand, oOperand, op);
2013- break;
2014- }
2015- case Opcode::OP_FFN_COMBINEINFO: {
2016- npu::tile_fwk::Distributed::TiledDispatchFFNCombineInfo(function, tileShape, iOperand, oOperand, op);
2017- break;
2018- }
2019- case Opcode::OP_FFN_VALIDCNT: {
2020- npu::tile_fwk::Distributed::TiledDispatchFFNValidCnt(function, tileShape, iOperand, oOperand, op);
2021- break;
2022- }
2023 case Opcode::OP_SHMEM_PUT: {1991 case Opcode::OP_SHMEM_PUT: {
2024 npu::tile_fwk::Distributed::TiledShmemPut(function, tileShape, iOperand, oOperand, op);1992 npu::tile_fwk::Distributed::TiledShmemPut(function, tileShape, iOperand, oOperand, op);
2025 break;1993 break;
@@ -2052,14 +2020,6 @@ void ExpandOperationInto(
2052 npu::tile_fwk::Distributed::TiledShmemSet(function, tileShape, iOperand, oOperand, op);2020 npu::tile_fwk::Distributed::TiledShmemSet(function, tileShape, iOperand, oOperand, op);
2053 break;2021 break;
2054 }2022 }
2055- case Opcode::OP_MOE_DISTRIBUTED_COMBINE_SEND: {
2056- npu::tile_fwk::Distributed::TiledMoeDistributedCombineSend(function, tileShape, iOperand, oOperand, op);
2057- break;
2058- }
2059- case Opcode::OP_MOE_DISTRIBUTED_COMBINE_RECEIVE: {
2060- npu::tile_fwk::Distributed::TiledMoeDistributedCombineReceive(function, tileShape, iOperand, oOperand, op);
2061- break;
2062- }
2063 case Opcode::OP_VIEW_TYPE: {2023 case Opcode::OP_VIEW_TYPE: {
2064 TiledViewTypeOperation(function, tileShape, iOperand[0], oOperand[0]);2024 TiledViewTypeOperation(function, tileShape, iOperand[0], oOperand[0]);
2065 break;2025 break;
@@ -26,8 +26,6 @@
26#include "dynamic/cube_dyn.h"26#include "dynamic/cube_dyn.h"
27#include "fixpipe.h"27#include "fixpipe.h"
28#include "distributed/common.h"28#include "distributed/common.h"
29-#include "distributed/moe_dispatch.h"
30-#include "distributed/moe_combine.h"
31#include "dynamic/aicpu_call.h"29#include "dynamic/aicpu_call.h"
32#endif30#endif
33 31 
@@ -1,131 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file moe_combine.h
13- * \brief
14- */
15- 
16-#ifndef __DISTRIBUTED_COMBINE__
17-#define __DISTRIBUTED_COMBINE__
18- 
19-#include "common.h"
20-#include <type_traits>
21- 
22-namespace TileOp::Distributed {
23-template <typename T, uint32_t topK, uint16_t rowShape, uint16_t colShape, uint16_t paddedColShape>
24-TILEOP void MoeDistributedCombineSend(
25- CoreFuncParam* param, __ubuf__ T* dataBuffer, __ubuf__ int32_t* assistInfoForCombineBuffer,
26- __ubuf__ int32_t* signalBuffer, __gm__ T* expandX, __gm__ int32_t* assistInfoForCombine,
27- __ubuf__ int32_t* recvCounts, __gm__ T* shmemDataBaseAddr, __gm__ int32_t* shmemSignalBaseAddr,
28- uint64_t expandXOffset0, uint64_t expandXOffset1, __gm__ int64_t* hcclContext)
29-{
30- signalBuffer[0] = 1;
31- uint64_t maxRow = ((expandXOffset0 + rowShape) < recvCounts[0]) ? (expandXOffset0 + rowShape) : recvCounts[0];
32- for (uint64_t row = expandXOffset0; row < maxRow; row++) {
33- set_flag(PIPE_MTE3, PIPE_MTE2, EVENT_ID0);
34- wait_flag(PIPE_MTE3, PIPE_MTE2, EVENT_ID0);
35- TileOp::UBCopyIn<int32_t, 1, 3, 8, 3>(
36- assistInfoForCombineBuffer, assistInfoForCombine + MOE_COMBINE_INFO_NUM * row);
37- 
38- set_flag(PIPE_MTE2, PIPE_S, EVENT_ID0);
39- wait_flag(PIPE_MTE2, PIPE_S, EVENT_ID0);
40- int32_t rankId = assistInfoForCombineBuffer[0];
41- int32_t tokenId = assistInfoForCombineBuffer[1];
42- int32_t kOffset = assistInfoForCombineBuffer[2];
43- 
44- TileOp::UBCopyIn<T, 1, colShape, paddedColShape, colShape>(dataBuffer, expandX + colShape * row);
45- 
46- __gm__ T* winDataAddr =
47- MapVirtualAddr<T>(hcclContext, shmemDataBaseAddr, rankId) + colShape * (topK * tokenId + kOffset);
48- set_flag(PIPE_MTE2, PIPE_MTE3, EVENT_ID0);
49- wait_flag(PIPE_MTE2, PIPE_MTE3, EVENT_ID0);
50- TileOp::UBCopyOut<T, 1, colShape, colShape, paddedColShape>(winDataAddr, dataBuffer);
51- 
52- __gm__ int32_t* winSignalAddr =
53- MapVirtualAddr<int32_t>(hcclContext, shmemSignalBaseAddr, rankId) + MOE_COMBINE_SIGNAL_OFFSET * tokenId;
54- set_atomic_add();
55- set_atomic_s32();
56- pipe_barrier(PIPE_MTE3);
57- copy_ubuf_to_gm(winSignalAddr, signalBuffer, 0, 1, 1, 0, 0);
58- set_atomic_none();
59- }
60-}
61- 
62-TILEOP void MoeDistributedCombineWaitSignal(
63- __gm__ int32_t* winSignalAddr, __ubuf__ int32_t* signalBuffer, int32_t expectedValue)
64-{
65- set_flag(PIPE_MTE3, PIPE_MTE2, EVENT_ID0);
66- wait_flag(PIPE_MTE3, PIPE_MTE2, EVENT_ID0);
67- do {
68- copy_gm_to_ubuf(signalBuffer, winSignalAddr, 0, 1, 1, 0, 0);
69- set_flag(PIPE_MTE2, PIPE_S, EVENT_ID0);
70- wait_flag(PIPE_MTE2, PIPE_S, EVENT_ID0);
71- } while (signalBuffer[0] != expectedValue);
72-}
73- 
74-template <typename T, uint32_t topK, uint16_t colShape, uint16_t paddedColShape>
75-TILEOP void MoeDistributedCombineCompute(
76- __ubuf__ T* out, __ubuf__ float* mulFp32Buffer, __ubuf__ float* sumFp32Buffer, __ubuf__ float* expertScales,
77- __gm__ T* winDataAddr)
78-{
79- uint8_t repeat = static_cast<uint8_t>(
80- AlignUp<uint16_t>(sizeof(float) * paddedColShape, VECTOR_INSTRUCTION_BYTE_SIZE) / VECTOR_INSTRUCTION_BYTE_SIZE);
81- 
82- vector_dup(sumFp32Buffer, 0.0f, repeat, 1, 1, 8, 8);
83- 
84- for (int kOffset = 0; kOffset < topK; kOffset++) {
85- set_flag(PIPE_V, PIPE_MTE2, EVENT_ID0);
86- wait_flag(PIPE_V, PIPE_MTE2, EVENT_ID0);
87- TileOp::UBCopyIn<T, 1, colShape, paddedColShape, colShape>(out, winDataAddr);
88- set_flag(PIPE_MTE2, PIPE_V, EVENT_ID0);
89- wait_flag(PIPE_MTE2, PIPE_V, EVENT_ID0);
90- vconv_bf162f32(mulFp32Buffer, out, repeat, 1, 1, 8, 4);
91- pipe_barrier(PIPE_V);
92- vmuls(mulFp32Buffer, mulFp32Buffer, static_cast<float>(expertScales[kOffset]), repeat, 1, 1, 8, 8);
93- pipe_barrier(PIPE_V);
94- vadd(sumFp32Buffer, mulFp32Buffer, sumFp32Buffer, repeat, 1, 1, 1, 8, 8, 8);
95- winDataAddr += colShape;
96- }
97- 
98- pipe_barrier(PIPE_V);
99- vconv_f322bf16a(out, sumFp32Buffer, repeat, 1, 1, 4, 8);
100-}
101- 
102-template <typename T, uint32_t topK, uint16_t rowShape, uint16_t colShape, uint16_t paddedColShape>
103-TILEOP void MoeDistributedCombineReceive(
104- CoreFuncParam* param, __gm__ T* out, __ubuf__ float* mulFp32Buffer, __ubuf__ float* sumFp32Buffer,
105- __ubuf__ T* outBuffer, __ubuf__ float* expertScales, __gm__ T* shmemDataBaseAddr,
106- __gm__ int32_t* shmemSignalBaseAddr, uint64_t shmemDataOffset0, uint64_t shmemDataOffset1,
107- uint64_t shmemDataOffset2, uint64_t shmemDataOffset3, int64_t rowOffset, __gm__ int64_t* hcclContext)
108-{
109- uint64_t thisRankId = shmemDataOffset0;
110- 
111- for (uint64_t tokenId = rowOffset; tokenId < rowOffset + rowShape; tokenId++) {
112- __gm__ int32_t* winSignalAddr =
113- MapVirtualAddr<int32_t>(hcclContext, shmemSignalBaseAddr, thisRankId) + MOE_COMBINE_SIGNAL_OFFSET * tokenId;
114- __ubuf__ int32_t* signalBuffer = reinterpret_cast<__ubuf__ int32_t*>(outBuffer);
115- MoeDistributedCombineWaitSignal(winSignalAddr, signalBuffer, topK);
116- 
117- constexpr uint32_t expertScalesColShape =
118- AlignUp<uint32_t>(sizeof(float) * topK, COPY_BLOCK_BYTE_SIZE) / sizeof(float);
119- __gm__ T* winDataAddr =
120- MapVirtualAddr<T>(hcclContext, shmemDataBaseAddr, thisRankId) + colShape * topK * tokenId;
121- MoeDistributedCombineCompute<T, topK, colShape, paddedColShape>(
122- outBuffer, mulFp32Buffer, sumFp32Buffer, expertScales + expertScalesColShape * tokenId, winDataAddr);
123- 
124- set_flag(PIPE_V, PIPE_MTE3, EVENT_ID0);
125- wait_flag(PIPE_V, PIPE_MTE3, EVENT_ID0);
126- TileOp::UBCopyOut<T, 1, colShape, colShape, paddedColShape>(out + colShape * tokenId, outBuffer);
127- }
128-}
129-} // namespace TileOp::Distributed
130- 
131-#endif
@@ -1,575 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file moe_dispatch.h
13- * \brief
14- */
15- 
16-#ifndef __DISTRIBUTED_DISPATCH__
17-#define __DISTRIBUTED_DISPATCH__
18- 
19-#include "common.h"
20-#include <type_traits>
21- 
22-namespace TileOp::Distributed {
23-template <
24- typename T, int32_t axisH, int32_t tRowOffset, int32_t tColOffset, int32_t tRowShape, int32_t tColShape,
25- int32_t groupIndex>
26-TILEOP void SendToRoutingExpert(
27- CoreFuncParam* param, __gm__ int32_t* syncTensor, __ubuf__ T* tokenBuffer, __ubuf__ int32_t* expertTableUb,
28- __ubuf__ int32_t* expertBuffer, __gm__ T* token, __gm__ T* shmemDataBaseAddr, __gm__ int32_t* expertTable,
29- uint32_t tableOffset0, uint32_t tableOffset1, uint32_t tableRawShape0, uint32_t tableRawShape1,
30- uint32_t shmemDataOffset0, uint32_t shmemDataOffset1, uint32_t shmemDataOffset2, uint32_t shmemDataOffset3,
31- uint32_t shmemDataRawShape0, uint32_t shmemDataRawShape1, uint32_t shmemDataRawShape2, uint32_t shmemDataRawShape3,
32- __gm__ int64_t* hcclContext)
33-{
34- int32_t topK = static_cast<int32_t>(tableRawShape1);
35- int32_t expertTblSize = static_cast<int32_t>(tableRawShape0) * static_cast<int32_t>(tableRawShape1);
36- int32_t lenBurst = AlignUp<int32_t>(expertTblSize * sizeof(int32_t), 32) / 32;
37- copy_gm_to_ubuf(expertTableUb, expertTable, 0, 1, lenBurst, 0, 0);
38- PIPE_SYNC_EVENT(PIPE_MTE2, PIPE_S, EVENT_ID0);
39- __gm__ CommContext* winContext = (__gm__ CommContext*)(hcclContext[groupIndex]);
40- uint64_t localUsrRankId = static_cast<uint64_t>(winContext->rankId);
41- const int32_t hOutSize = axisH * sizeof(T); // 如有量化,需要量化后通信
42- int32_t shmemDataLength = AlignUp<int32_t>(axisH, 512) + 512; // 512对齐,预留512三元组存储
43- const int32_t tokenQuantAlign32 = AlignUp<int32_t>(hOutSize, 32) / sizeof(int32_t);
44- __ubuf__ int32_t* tmpTokenBuffer = reinterpret_cast<__ubuf__ int32_t*>(tokenBuffer);
45- int32_t combineInfoOffset = 32;
46- for (int32_t row = tRowOffset; row < tRowOffset + tRowShape; ++row) {
47- copy_gm_to_ubuf(tokenBuffer, token + row * axisH, 0, 1, hOutSize / 32, 0, 0);
48- PIPE_SYNC_EVENT(PIPE_MTE2, PIPE_S, EVENT_ID0);
49- for (int32_t col = tColOffset; col < tColOffset + tColShape; ++col) {
50- tmpTokenBuffer[tokenQuantAlign32 + combineInfoOffset] = static_cast<int32_t>(localUsrRankId);
51- tmpTokenBuffer[tokenQuantAlign32 + (combineInfoOffset + 1)] = row;
52- tmpTokenBuffer[tokenQuantAlign32 + (combineInfoOffset + 2)] = col;
53- int32_t tableIndex = row * topK + col;
54- int32_t remoteExpertId = expertTableUb[tableIndex];
55- int32_t remoteRankId = remoteExpertId / static_cast<int32_t>(shmemDataRawShape2);
56- int32_t remoteExpertOffset = remoteExpertId % static_cast<int32_t>(shmemDataRawShape2);
57- int32_t tokenOffset = CalcOccurrencesVector(expertTableUb, remoteExpertId, tableIndex, expertBuffer);
58- __gm__ T* remoteShmemBaseAddr =
59- MapVirtualAddr<T>(hcclContext, shmemDataBaseAddr, static_cast<uint32_t>(remoteRankId));
60- __gm__ T* remoteShmemDataAddr =
61- remoteShmemBaseAddr +
62- static_cast<uint64_t>(
63- localUsrRankId * static_cast<uint64_t>(shmemDataRawShape2) *
64- static_cast<uint64_t>(shmemDataRawShape3) +
65- static_cast<uint64_t>(remoteExpertOffset) * static_cast<uint64_t>(shmemDataRawShape3) +
66- static_cast<uint64_t>(tokenOffset) * static_cast<uint64_t>(shmemDataLength));
67- PIPE_SYNC_EVENT(PIPE_S, PIPE_MTE3, EVENT_ID0);
68- copy_ubuf_to_gm(remoteShmemDataAddr, tokenBuffer, 0, 1, shmemDataLength * sizeof(T) / 32, 0, 0);
69- PIPE_SYNC_EVENT(PIPE_MTE3, PIPE_S, EVENT_ID0);
70- }
71- PIPE_SYNC_EVENT(PIPE_MTE3, PIPE_MTE2, EVENT_ID0);
72- }
73-}
74- 
75-template <typename T, int32_t bs, int32_t axisH, int32_t tileRowShape, int32_t groupIndex>
76-TILEOP void SendToSharedExpert(
77- CoreFuncParam* param, __gm__ int32_t* syncTensor, __ubuf__ T* tokenBuffer, __gm__ T* token,
78- __gm__ T* shmemDataBaseAddr, uint32_t tokenOffset0, uint32_t tokenOffset1, uint32_t tokenShape0,
79- uint32_t tokenShape1, uint32_t shmemDataOffset0, uint32_t shmemDataOffset1, uint32_t shmemDataOffset2,
80- uint32_t shmemDataOffset3, uint32_t shmemDataRawShape0, uint32_t shmemDataRawShape1, uint32_t shmemDataRawShape2,
81- uint32_t shmemDataRawShape3, __gm__ int64_t* hcclContext)
82-{
83- __gm__ CommContext* winContext = (__gm__ CommContext*)(hcclContext[groupIndex]);
84- int32_t localUsrRankId = static_cast<int32_t>(winContext->rankId);
85- int32_t rankSize = static_cast<int32_t>(winContext->rankNum);
86- 
87- constexpr int32_t hOutSize = axisH * sizeof(T);
88- constexpr int32_t tokenQuantAlign32 = AlignUp<int32_t>(hOutSize, 32) / sizeof(int32_t);
89- int32_t shareRankSize = 1; // 在前端赋值 shareRankCnt
90- int32_t moeRankSize = rankSize - shareRankSize;
91- int32_t shareOpProcessRankSize = moeRankSize / shareRankSize;
92- 
93- __ubuf__ int32_t* tmpTokenBuffer = reinterpret_cast<__ubuf__ int32_t*>(tokenBuffer); // 类型转换使用
94- for (int32_t row = tokenOffset0; row < tokenOffset0 + tileRowShape; ++row) {
95- copy_gm_to_ubuf(tokenBuffer, token + row * axisH, 0, 1, hOutSize / 32, 0, 0);
96- PIPE_SYNC_EVENT(PIPE_MTE2, PIPE_S, EVENT_ID0);
97- tmpTokenBuffer[tokenQuantAlign32] =
98- localUsrRankId; // 暂时先不考虑 A3 数组,前端大小可以暂时用 token[1],暂不修改
99- tmpTokenBuffer[tokenQuantAlign32 + 1] = row;
100- tmpTokenBuffer[tokenQuantAlign32 + 2] = 1;
@@ -27,8 +27,6 @@ struct OpTestParam {
27 int worldRankId;27 int worldRankId;
28};28};
29 29 
30-template <typename T>
31-void TestMoeDistributedCombine(OpTestParam& testParam, std::string& goldenDir);
32void TestAllGatherAttentionPostReducescatter(OpTestParam& testParam, std::string& goldenDir);30void TestAllGatherAttentionPostReducescatter(OpTestParam& testParam, std::string& goldenDir);
33template <typename T>31template <typename T>
34void TestAllGather(OpTestParam& testParam, std::string& goldenDir);32void TestAllGather(OpTestParam& testParam, std::string& goldenDir);
@@ -37,8 +35,6 @@ void TestReduceScatter(OpTestParam& testParam, std::string& goldenDir);
37template <typename T>35template <typename T>
38void TestAllReduce(OpTestParam& testParam, std::string& goldenDir);36void TestAllReduce(OpTestParam& testParam, std::string& goldenDir);
39template <typename T>37template <typename T>
40-void TestShmemMoeDispatch(OpTestParam& testParam, std::string& goldenDir);
41-template <typename T>
42void TestAllReduceAddAllReduce(OpTestParam& testParam, std::string& goldenDir);38void TestAllReduceAddAllReduce(OpTestParam& testParam, std::string& goldenDir);
43template <typename T>39template <typename T>
44void Test2GroupsAllGather(OpTestParam& testParam, std::string& goldenDir);40void Test2GroupsAllGather(OpTestParam& testParam, std::string& goldenDir);
@@ -80,22 +80,6 @@ class GenTensorCase:
80 value_range: ValueRange80 value_range: ValueRange
81 81 
82 82 
83-@dataclasses.dataclass
84-class MoeCase:
85- dtype: torch.dtype
86- batch_size: int
87- hidden_size: int
88- shared_expert_num: int
89- routed_expert_num: int
90- top_k: int
91- world_size: int
92- value_range: ValueRange
93- 
94- def __post_init__(self):
95- if self.top_k > self.routed_expert_num:
96- raise ValueError(f'top_k ({self.top_k}) cannot exceed routed_expert_num ({self.routed_expert_num})')
97- 
98- 
99@dataclasses.dataclass83@dataclasses.dataclass
100class AllGatherAttnPostReducescatterCase:84class AllGatherAttnPostReducescatterCase:
101 dtype: torch.dtype85 dtype: torch.dtype
@@ -109,25 +93,6 @@ class AllGatherAttnPostReducescatterCase:
109 value_range: ValueRange93 value_range: ValueRange
110 94 
111 95 
112-@dataclasses.dataclass
113-class SendToRoutedExpertsArgs:
114- case: MoeCase
115- x_list: List[torch.Tensor]
116- routed_expert_ids_list: List[torch.Tensor]
117- y_list: List[List[List[torch.Tensor]]]
118- combine_info_list: List[List[List[torch.Tensor]]]
119- 
120- 
121-@dataclasses.dataclass
122-class GetRoutedOutAndSaveArgs:
123- case: MoeCase
124- expand_x_list: List[torch.Tensor]
125- assist_info_for_combine: List[torch.Tensor]
126- expert_scales_list: List[torch.Tensor]
127- recv_counts_list: List[torch.Tensor]
128- save_dir: Path
129- 
130- 
131@dataclasses.dataclass96@dataclasses.dataclass
132class DistributedOpAndSaveArgs:97class DistributedOpAndSaveArgs:
133 inputs: List[torch.Tensor]98 inputs: List[torch.Tensor]
@@ -280,267 +245,6 @@ def all_reduce_and_save(args: DistributedOpAndSaveArgs) -> torch.Tensor:
280 return outputs245 return outputs
281 246 
282 247 
283-def parse_moe_case(config: dict) -> MoeCase:
284- params = config['params']
285- input_tensor = config['input_tensors'][0]
286- dtype = get_dtype(input_tensor['dtype'])
287- batch_size = params['batch_size']
288- hidden_size = params['hidden_size']
289- shared_expert_num = params['shared_expert_num']
290- routed_expert_num = params['routed_expert_num']
291- top_k = params['top_k']
292- world_size = params['world_size']
293- min_val, max_val = input_tensor['data_range']['min'], input_tensor['data_range']['max']
294- value_range = ValueRange(min_val=min_val, max_val=max_val)
295- case = MoeCase(dtype=dtype, batch_size=batch_size, hidden_size=hidden_size, shared_expert_num=shared_expert_num,
296- routed_expert_num=routed_expert_num, top_k=top_k, world_size=world_size, value_range=value_range)
297- return case
298- 
299- 
300-def generate_moe_dispatch_input_data(case: MoeCase, save_dir: Path) \
301- -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
302- gen_tensor_case = GenTensorCase(
303- dtype=case.dtype, shape=(case.batch_size, case.hidden_size),
304- world_size=case.world_size, value_range=case.value_range
305- )
306- x_list = generate_random_tensor_list_and_save(gen_tensor_case, save_dir, 'x',)
307- gen_tensor_case = GenTensorCase(
308- dtype=torch.float32, shape=(case.batch_size, case.routed_expert_num),
309- world_size=case.world_size, value_range=case.value_range
310- )
311- scores_list = generate_random_tensor_list(gen_tensor_case)
312- scores_list = [scores.sigmoid() for scores in scores_list]
313- 
314- routed_expert_ids_list = []
315- for rank in range(case.world_size):
316- scores = scores_list[rank]
317- _, routed_expert_ids = torch.topk(scores, k=case.top_k)
318- 
319- scales = scores.gather(1, routed_expert_ids)
320- save_tensor(scales, save_dir / f'scale_rank_{rank}.bin')
321- 
322- routed_expert_ids += case.shared_expert_num
323- routed_expert_ids_list.append(routed_expert_ids)
324- routed_expert_ids = routed_expert_ids.to(dtype=torch.int32)
325- save_tensor(routed_expert_ids, save_dir / f'expert_ids_rank_{rank}.bin')
326- 
327- return x_list, routed_expert_ids_list
328- 
329- 
330-def generate_combine_info_tensor(rank_id: int, token_id: int, k_offset: int) -> torch.Tensor:
331- return torch.tensor([rank_id, token_id, k_offset], dtype=torch.int32).unsqueeze(0)
332- 
333- 
334-def get_shared_expert_rank_id(case: MoeCase, rank_id: int) -> int:
335- if rank_id < case.shared_expert_num:
336- return rank_id
337- shared_expert_capacity = case.routed_expert_num // case.shared_expert_num
338- return (rank_id - case.shared_expert_num) // shared_expert_capacity
339- 
340- 
341-def send_to_shared_experts(
342- case: MoeCase,
343- x_list: List[torch.Tensor],
344- y_list: List[List[List[torch.Tensor]]],
345- combine_info_list: List[List[List[torch.Tensor]]],
346-) -> None:
347- expert_offset = 0
348- for rank_id in range(case.world_size):
349- x = x_list[rank_id]
350- target_shared_expert_rank_id = get_shared_expert_rank_id(case, rank_id)
351- for token_id in range(case.batch_size):
352- token = x[token_id].unsqueeze(0)
353- y_list[target_shared_expert_rank_id][expert_offset].append(token)
354- combine_info_list[target_shared_expert_rank_id][expert_offset].append(
355- generate_combine_info_tensor(rank_id, token_id, case.top_k),
356- )
357- 
358- 
359-def get_routed_expert_capacity(case: MoeCase) -> int:
360- if case.shared_expert_num > 0:
361- return 1
362- return math.ceil(case.routed_expert_num / case.world_size)
363- 
364- 
365-def get_routed_expert_rank_id_and_expert_offset(case: MoeCase, expert_id: int) -> Tuple[int, int]:
366- if case.shared_expert_num > 0:
367- return expert_id, 0
368- routed_expert_capacity = get_routed_expert_capacity(case)
369- return divmod(expert_id, routed_expert_capacity)
370- 
371- 
372-def send_to_routed_experts(args: SendToRoutedExpertsArgs) -> None:
373- case = args.case
374- x_list = args.x_list
375- routed_expert_ids_list = args.routed_expert_ids_list
376- y_list = args.y_list
377- combine_info_list = args.combine_info_list
378- for source_rank_id in range(case.world_size):
379- x = x_list[source_rank_id]
380- routed_expert_ids = routed_expert_ids_list[source_rank_id]
381- for token_id in range(case.batch_size):
382- token = x[token_id].unsqueeze(0)
383- for k_offset in range(case.top_k):
384- target_routed_expert_id = routed_expert_ids[token_id][k_offset].item()
385- target_routed_expert_rank_id, expert_offset = \
386- get_routed_expert_rank_id_and_expert_offset(case, target_routed_expert_id)
387- y_list[target_routed_expert_rank_id][expert_offset].append(token)
388- combine_info_list[target_routed_expert_rank_id][expert_offset].append(
389- generate_combine_info_tensor(source_rank_id, token_id, k_offset),
390- )
391- 
392- 
393-def get_dispatch_output_row(case: MoeCase) -> int:
394- if case.shared_expert_num > 0:
395- return case.batch_size * case.world_size
396- else:
397- max_send_token_num = case.batch_size * case.top_k * case.world_size
398- max_receive_token_num = case.batch_size * case.routed_expert_num
399- return min(max_send_token_num, max_receive_token_num)
400- 
401- 
402-def collect_and_save(
403- case: MoeCase,
404- y_list: List[List[List[torch.Tensor]]],
405- combine_info_list: List[List[List[torch.Tensor]]],
406- save_dir: Path,
407-) -> None:
408- row = get_dispatch_output_row(case)
409- routed_expert_capacity = get_routed_expert_capacity(case)
410- for rank_id in range(case.world_size):
411- fixed_shape_y = torch.zeros((row, case.hidden_size), dtype=case.dtype)
412- fixed_shape_combine_info = torch.zeros((row, 3), dtype=torch.int32)
413- valid_count = torch.zeros([routed_expert_capacity], dtype=torch.int32)
414- y_offset, combine_info_offset = 0, 0
415- for expert_offset in range(routed_expert_capacity):
416- if y_list[rank_id][expert_offset]:
417- actual_y = torch.cat(y_list[rank_id][expert_offset], dim=0)
418- fixed_shape_y[y_offset:y_offset + actual_y.size(0)] = actual_y
419- y_offset += actual_y.size(0)
420- actual_combine_info = torch.cat(combine_info_list[rank_id][expert_offset], dim=0)
421- fixed_shape_combine_info[combine_info_offset:combine_info_offset + actual_combine_info.size(0)] \
422- = actual_combine_info
423- combine_info_offset += actual_combine_info.size(0)
424- valid_count[expert_offset] = actual_y.size(0)
425- save_tensor(fixed_shape_y, save_dir / f'y_rank_{rank_id}.bin')
426- save_tensor(fixed_shape_combine_info, save_dir / f'combine_info_rank_{rank_id}.bin')
427- save_tensor(valid_count, save_dir / f'valid_count_rank_{rank_id}.bin')
428- recv_counts = torch.sum(valid_count).item()
429- recv_counts_tensor = torch.tensor(recv_counts, dtype=torch.int32)
430- save_tensor(recv_counts_tensor, save_dir / f'recv_counts_rank_{rank_id}.bin')
431- 
432- 
433-def generate_moe_dispatch_case(case: MoeCase, save_dir: Path) -> None:
434- params = (case.batch_size, case.hidden_size, case.routed_expert_num, case.top_k, get_dtype_num(case.dtype))
435- save_params(params, save_dir)
436- 
437- x_list, routed_expert_ids_list = generate_moe_dispatch_input_data(case, save_dir)
438- 
439- routed_expert_capacity = get_routed_expert_capacity(case)
440- y_list = [[[] for _ in range(routed_expert_capacity)] for _ in range(case.world_size)]
441- combine_info_list = [[[] for _ in range(routed_expert_capacity)] for _ in range(case.world_size)]
442- if case.shared_expert_num > 0:
443- send_to_shared_experts(case, x_list, y_list, combine_info_list)
444- args = SendToRoutedExpertsArgs(case=case, x_list=x_list, routed_expert_ids_list=routed_expert_ids_list,
445- y_list=y_list, combine_info_list=combine_info_list)
446- send_to_routed_experts(args)
447- collect_and_save(case, y_list, combine_info_list, save_dir)
448- 
449- 
450-def get_moe_distributed_combine_input_data(dispatch_save_dir: Path, case: MoeCase) \
451- -> Tuple[List[torch.Tensor], List[torch.Tensor], List[torch.Tensor]]:
452- expand_x_list = []
453- assist_info_for_combine_list = []
454- expert_scales_list = []
455- recv_counts_list = []
456- row = get_dispatch_output_row(case)
457- for rank in range(case.world_size):
458- expand_x = torch.from_numpy(np.fromfile(dispatch_save_dir / f'y_rank_{rank}.bin'))
459- expand_x = expand_x.view(dtype=case.dtype).view([row, case.hidden_size])
460- expand_x_list.append(expand_x)
461- 
462- assist_info_for_combine = torch.from_numpy(
463- np.fromfile(dispatch_save_dir / f'combine_info_rank_{rank}.bin', dtype=np.int32),
464- )
465- assist_info_for_combine = assist_info_for_combine.view([row, 3])
466- assist_info_for_combine_list.append(assist_info_for_combine)
467- 
468- expert_scales = torch.from_numpy(np.fromfile(dispatch_save_dir / f'scale_rank_{rank}.bin', dtype=np.float32))
469- expert_scales = expert_scales.view([case.batch_size, case.top_k, 1])
470- expert_scales_list.append(expert_scales)
471- 
472- recvcounts = torch.from_numpy(np.fromfile(dispatch_save_dir / f'recv_counts_rank_{rank}.bin', dtype=np.int32))
473- recv_counts_list.append(recvcounts)
474- return expand_x_list, assist_info_for_combine_list, expert_scales_list, recv_counts_list
475- 
476- 
477-def get_shared_out_and_save(
478- case: MoeCase,
479- expand_x_list: List[torch.Tensor],
480- assist_info_for_combine_list: List[torch.Tensor],
481- save_dir: Path,
482-) -> List[torch.Tensor]:
483- shared_out_list = []
484- for rank_id in range(case.world_size):
485- source_shared_expert_rank_id = get_shared_expert_rank_id(case, rank_id)
486- expand_x = expand_x_list[source_shared_expert_rank_id]
487- assist_info_for_combine = assist_info_for_combine_list[source_shared_expert_rank_id]
488- mask = assist_info_for_combine[:, 0] == rank_id
489- shared_out = expand_x[mask]
490- shared_out_list.append(shared_out)
491- save_tensor(shared_out, save_dir / f'share_y_rank_{rank_id}.bin')
492- return shared_out_list
493- 
494- 
495-def get_routed_out_and_save(args: GetRoutedOutAndSaveArgs) -> List[torch.Tensor]:
496- case = args.case
497- expand_x_list = args.expand_x_list
498- assist_info_for_combine_list = args.assist_info_for_combine
499- expert_scales_list = args.expert_scales_list
500- recv_counts_list = args.recv_counts_list
501- save_dir = args.save_dir
502- routed_out_list = [
503- torch.zeros([case.batch_size, case.top_k, case.hidden_size], dtype=case.dtype)
504- for _ in range(case.world_size)
505- ]
506- for source_rank_id in range(case.shared_expert_num, case.world_size):
507- expand_x = expand_x_list[source_rank_id]
508- assist_info_for_combine = assist_info_for_combine_list[source_rank_id]
509- valid_row_shape = recv_counts_list[source_rank_id]
510- for i, (token, (target_rank_id, token_id, k_offset)) in enumerate(zip(expand_x, assist_info_for_combine)):
511- if i < valid_row_shape:
512- routed_out_list[target_rank_id][token_id, k_offset] = token
513- for source_rank_id in range(case.world_size):
514- routed_out = routed_out_list[source_rank_id]
515- save_tensor(routed_out, save_dir / f'moe_y_rank_{source_rank_id}.bin')
516- expert_scales = expert_scales_list[source_rank_id]
517- routed_out = routed_out.to(dtype=torch.float32)
518- routed_out = routed_out * expert_scales
519- save_tensor(routed_out, save_dir / f'scaled_moe_y_rank_{source_rank_id}.bin')
520- routed_out_list[source_rank_id] = torch.sum(routed_out, dim=1)
521- return routed_out_list
522- 
523- 
524-def generate_moe_distributed_combine_case(case: MoeCase, save_dir: Path, dispatch_save_dir: Path) \
525- -> None:
526- expand_x_list, assist_info_for_combine_list, expert_scales_list, recv_counts_list \
527- = get_moe_distributed_combine_input_data(dispatch_save_dir, case)
528- 
529- if case.shared_expert_num > 0:
530- shared_out_list = get_shared_out_and_save(case, expand_x_list, assist_info_for_combine_list, save_dir)
531- args = GetRoutedOutAndSaveArgs(case=case, expand_x_list=expand_x_list,
532- assist_info_for_combine=assist_info_for_combine_list,
533- expert_scales_list=expert_scales_list, recv_counts_list=recv_counts_list, save_dir=save_dir)
534- routed_out_list = get_routed_out_and_save(args)
535- 
536- for rank_id in range(case.world_size):
537- routed_out = routed_out_list[rank_id]
538- out = routed_out.to(dtype=torch.float32)
539- if case.shared_expert_num > 0:
540- out += shared_out_list[rank_id]
541- save_tensor(out.to(dtype=case.dtype), save_dir / f'out_rank_{rank_id}.bin')
542- 
543- 
544def generate_allgather_attn_post_reducescatter_case(config: dict) -> AllGatherAttnPostReducescatterCase:248def generate_allgather_attn_post_reducescatter_case(config: dict) -> AllGatherAttnPostReducescatterCase:
545 params = config['params']249 params = config['params']
546 input_tensor = config['input_tensors'][0]250 input_tensor = config['input_tensors'][0]
@@ -703,26 +407,6 @@ def generate_allreduce_add_allreduce_golden(config: dict, output: Path) -> bool:
703 return True407 return True
704 408 
705 409 
706-def generate_moe_dispatch_golden(config: dict, output: Path) -> bool:
707- case = parse_moe_case(config)
708- generate_moe_dispatch_case(case, output)
709- return True
710- 
711- 
712-def generate_moe_distributed_combine_golden(config: dict, output: Path) -> bool:
713- case = parse_moe_case(config)
714- params = config['params'] # 整理一下
715- use_v2 = params['use_v2']
716- params = (case.batch_size, case.hidden_size, case.routed_expert_num, case.top_k, get_dtype_num(case.dtype),
717- use_v2)
718- save_params(params, output)
719- dispatch_save_dir = output / 'dispatch'
720- dispatch_save_dir.mkdir(parents=True, exist_ok=True)
721- generate_moe_dispatch_case(case, dispatch_save_dir)
722- generate_moe_distributed_combine_case(case, output, dispatch_save_dir)
723- return True
724- 
725- 
726def prepare_attention_input(case, output: Path):410def prepare_attention_input(case, output: Path):
727 all_gather_input_shape = (411 all_gather_input_shape = (
728 case.batch_size * case.seq_len * case.num_heads // case.world_size,412 case.batch_size * case.seq_len * case.num_heads // case.world_size,
@@ -825,8 +509,6 @@ OPERATOR_DISPATCHERS = {
825 'AllGather': generate_all_gather_golden,509 'AllGather': generate_all_gather_golden,
826 'ReduceScatter': generate_reduce_scatter_golden,510 'ReduceScatter': generate_reduce_scatter_golden,
827 'AllReduce': generate_all_reduce_golden,511 'AllReduce': generate_all_reduce_golden,
828- 'MoeDispatch': generate_moe_dispatch_golden,
829- 'MoeDistributedCombine': generate_moe_distributed_combine_golden,
830 'AllReduceAddAllReduce': generate_allreduce_add_allreduce_golden,512 'AllReduceAddAllReduce': generate_allreduce_add_allreduce_golden,
831 'AllGatherAttnPostReduceScatter': gen_allgather_attnpost_reducescatter_case,513 'AllGatherAttnPostReduceScatter': gen_allgather_attnpost_reducescatter_case,
832 'MultiCommGroupsOp': gen_2_groups_allgather_golden,514 'MultiCommGroupsOp': gen_2_groups_allgather_golden,
@@ -1,85 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_moe_dispatch.cpp
13- * \brief
14- */
15- 
16-#include "distributed_op_test_common.h"
17-#include "tilefwk/tilefwk.h"
18-#include "interface/inner/tilefwk.h"
19-#include "interface/configs/config_manager.h"
20-#include "tilefwk/data_type.h"
21-#include "test_dev_func_runner.h"
22- 
23-namespace npu::tile_fwk::Distributed {
24-template <typename T>
25-void TestShmemMoeDispatch(OpTestParam& testParam, std::string& goldenDir)
26-{
27- constexpr size_t paramsSize = 5;
28- auto [batchSize, hiddenSize, routedNum, topK, typeNum] = GetParams<paramsSize>(goldenDir + "/params.bin");
29- DataType dType = GetDataTypeNum(typeNum);
30- int32_t expertNumPerRank = routedNum / testParam.rankSize;
31- Shape tokenTensorShape{batchSize, hiddenSize};
32- Shape tokenExpertTableShape{batchSize, topK};
33- int32_t expandXRowShape = std::min(
34- static_cast<int32_t>(batchSize) * static_cast<int32_t>(topK) * testParam.rankSize,
35- static_cast<int32_t>(batchSize) * routedNum);
36- Shape expandXShape{expandXRowShape, hiddenSize};
37- Shape combineInfoShape{expandXRowShape, 3};
38- Tensor tokenTensor(dType, tokenTensorShape, "tokenTensor");
39- Tensor tokenExpertTable(DataType::DT_INT32, tokenExpertTableShape, "tokenExpertTable");
40- Tensor expertTokenNums(DataType::DT_INT32, {expertNumPerRank}, "expertTokenNums");
41- Tensor expandX(dType, expandXShape, "expandX");
42- Tensor combineInfo(DataType::DT_INT32, combineInfoShape, "combineInfo");
43- std::string xPath = goldenDir + "/x_rank_" + std::to_string(testParam.rankId) + ".bin";
44- std::vector<T> tokenTensorPtr = ReadToVector<T>(xPath, tokenTensorShape);
45- std::string expertIdsPath = goldenDir + "/expert_ids_rank_" + std::to_string(testParam.rankId) + ".bin";
46- std::vector<int32_t> tokenExpertTablePtr = ReadToVector<int32_t>(expertIdsPath, tokenExpertTableShape);
47- MoeConfig moeConfig{routedNum, expertNumPerRank, static_cast<int32_t>(testParam.rankSize)};
48- FUNCTION("MoeDispatch", {tokenTensor, tokenExpertTable}, {expandX, expertTokenNums, combineInfo})
49- {
50- Distributed::MoeDistributedDispatch(tokenTensor, tokenExpertTable, expandX, expertTokenNums, combineInfo,
51- testParam.group, moeConfig);
52- }
53- ProgramData::GetInstance().AppendInputs({
54- RawTensorData::CreateTensor<T>(tokenTensor, tokenTensorPtr),
55- RawTensorData::CreateTensor<int32_t>(tokenExpertTable, tokenExpertTablePtr),
56- });
57- ProgramData::GetInstance().AppendOutputs({
58- RawTensorData::CreateTensorZero(expandX),
59- RawTensorData::CreateTensorZero(expertTokenNums),
60- RawTensorData::CreateTensorZero(combineInfo),
61- });
62- DeviceLauncherConfig config;
63- config.runModel = false;
64- DevFuncRunner::Run(Program::GetInstance().GetLastFunction(), config);
65- int64_t expandXEleNum = expandXShape[0] * expandXShape[1];
66- auto expandXOutPut = ProgramData::GetInstance().GetOutputData(0);
67- EXPECT_TRUE(CompareWithGolden<uint8_t*>(
68- dType, goldenDir + "/y_rank_", expandXEleNum, expandXOutPut->GetDevPtr(), testParam));
69- auto expertTokenNumsOutPut = ProgramData::GetInstance().GetOutputData(1);
70- EXPECT_TRUE(CompareWithGolden<uint8_t*>(
71- DataType::DT_INT32, goldenDir + "/valid_count_rank_", expertNumPerRank, expertTokenNumsOutPut->GetDevPtr(),
72- testParam));
73- int64_t combineInfoEleNum = combineInfoShape[0] * combineInfoShape[1];
74- auto combineInfoOutPut = ProgramData::GetInstance().GetOutputData(2);
75- EXPECT_TRUE(CompareWithGolden<uint8_t*>(
76- DataType::DT_INT32, goldenDir + "/combine_info_rank_", combineInfoEleNum, combineInfoOutPut->GetDevPtr(),
77- testParam));
78-}
79- 
80-template void TestShmemMoeDispatch<int32_t>(OpTestParam& testParam, std::string& goldenDir);
81-template void TestShmemMoeDispatch<float>(OpTestParam& testParam, std::string& goldenDir);
82-template void TestShmemMoeDispatch<float16>(OpTestParam& testParam, std::string& goldenDir);
83-template void TestShmemMoeDispatch<bfloat16>(OpTestParam& testParam, std::string& goldenDir);
84- 
85-} // namespace npu::tile_fwk::Distributed
@@ -1,91 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_moe_combine.cpp
13- * \brief
14- */
15- 
16-#include "distributed_op_test_common.h"
17-#include "tilefwk/tilefwk.h"
18-#include "interface/inner/tilefwk.h"
19-#include "interface/configs/config_manager.h"
20-#include "tilefwk/data_type.h"
21-#include "test_dev_func_runner.h"
22- 
23-namespace npu::tile_fwk::Distributed {
24- 
25-template <typename T>
26-void TestMoeDistributedCombine(OpTestParam& testParam, std::string& goldenDir)
27-{
28- constexpr size_t paramsSize = 6;
29- auto [batchSize, hiddenSize, moeExpertNum, topK, dtype_num, useV2] =
30- GetParams<paramsSize>(goldenDir + "/params.bin");
31- 
32- DataType dType = GetDataTypeNum(dtype_num);
33- 
34- int64_t row = std::min(topK * batchSize * testParam.rankSize, batchSize * moeExpertNum);
35- Shape inShape{row, hiddenSize};
36- Shape combineInfoShape{row, 3};
37- Shape recvCountsShape{1};
38- Shape scaleShape{batchSize, topK};
39- Shape outShape{batchSize, hiddenSize};
40- 
41- Tensor expandX(dType, inShape, "expandX");
42- Tensor assistInfoForCombine(DataType::DT_INT32, combineInfoShape, "assistInfoForCombine");
43- Tensor recvCounts(DataType::DT_INT32, recvCountsShape, "recvCounts");
44- Tensor expertScales(DataType::DT_FP32, scaleShape, "expertScales");
45- Tensor out(dType, outShape, "out");
46- 
47- std::string dispatchPath = goldenDir + "/dispatch";
48- std::vector<T> expandXPtr =
49- ReadToVector<T>(dispatchPath + "/y_rank_" + std::to_string(testParam.rankId) + ".bin", inShape);
50- std::vector<int32_t> assistInfoForCombinePtr = ReadToVector<int32_t>(
51- dispatchPath + "/combine_info_rank_" + std::to_string(testParam.rankId) + ".bin", combineInfoShape);
52- std::vector<int32_t> recvCountsPtr = ReadToVector<int32_t>(
53- dispatchPath + "/recv_counts_rank_" + std::to_string(testParam.rankId) + ".bin", recvCountsShape);
54- std::vector<float> expertScalesPtr =
55- ReadToVector<float>(dispatchPath + "/scale_rank_" + std::to_string(testParam.rankId) + ".bin", scaleShape);
56- 
57- using CombineFunc = std::function<void(
58- const Tensor&, const Tensor&, const Tensor&, const Tensor&, const char*, uint32_t, uint32_t, uint32_t, uint32_t,
59- Tensor&)>;
60- CombineFunc func = (useV2 == 1) ? MoeDistributedCombineV2 : MoeDistributedCombine;
61- 
62- FUNCTION("MoeDistributedCombineMain", {expandX, assistInfoForCombine, recvCounts, expertScales}, {out})
63- {
64- func(
65- expandX, assistInfoForCombine, recvCounts, expertScales, testParam.group, testParam.rankSize, moeExpertNum,
66- 0, 0, out);
67- }
68- 
69- ProgramData::GetInstance().AppendInputs(
70- {RawTensorData::CreateTensor<T>(expandX, expandXPtr),
71- RawTensorData::CreateTensor<int32_t>(assistInfoForCombine, assistInfoForCombinePtr),
72- RawTensorData::CreateTensor<int32_t>(recvCounts, recvCountsPtr),
73- RawTensorData::CreateTensor<float>(expertScales, expertScalesPtr)});
74- ProgramData::GetInstance().AppendOutputs({RawTensorData::CreateTensorZero(out)});
75- 
76- DeviceLauncherConfig config;
77- config.runModel = false;
78- DevFuncRunner::Run(Program::GetInstance().GetLastFunction(), config);
79- 
80- int64_t outEleNum = outShape[0] * outShape[1];
81- auto outPtr = ProgramData::GetInstance().GetOutputData(0)->GetDevPtr();
82- 
83- EXPECT_TRUE(CompareWithGolden<uint8_t*>(dType, goldenDir + "/out_rank_", outEleNum, outPtr, testParam));
84-}
85- 
86-template void TestMoeDistributedCombine<int32_t>(OpTestParam& testParam, std::string& goldenDir);
87-template void TestMoeDistributedCombine<float>(OpTestParam& testParam, std::string& goldenDir);
88-template void TestMoeDistributedCombine<float16>(OpTestParam& testParam, std::string& goldenDir);
89-template void TestMoeDistributedCombine<bfloat16>(OpTestParam& testParam, std::string& goldenDir);
90- 
91-} // namespace npu::tile_fwk::Distributed
@@ -1,2 +0,0 @@
1-operation,case_name,input_shape,input_dtype,input_format,input_datarange,output_shape,output_dtype,output_format,view_shape,tile_shape,batch_size,hidden_size,shared_expert_num,routed_expert_num,top_k,world_size
2-MoeDispatch,MoeDispatch_test_1,"[]","bfloat16","ND","[,]","[]","bfloat16","ND","[,]","[]",8,5120,0,160,8,4
@@ -1,53 +0,0 @@
1-{
2- "test_cases": [
3- {
4- "case_index": 0,
5- "case_name": "MoeDispatch_test_1",
6- "operation": "MoeDispatch",
7- "input_tensors": [
8- {
9- "name": "input0",
10- "shape": [
11- ""
12- ],
13- "dtype": "bfloat16",
14- "format": "ND",
15- "need_trans": false,
16- "data_range": {
17- "min": "",
18- "max": ""
19- }
20- }
21- ],
22- "output_tensors": [
23- {
24- "name": "output0",
25- "shape": [
26- ""
27- ],
28- "dtype": "bfloat16",
29- "format": "ND",
30- "need_trans": false
31- }
32- ],
33- "view_shape": [
34- "",
35- ""
36- ],
37- "tile_shape": [
38- ""
39- ],
40- "params": {
41- "batch_size": 8,
42- "hidden_size": 5120,
43- "shared_expert_num": 0,
44- "routed_expert_num": 160,
45- "top_k": 8,
46- "world_size": 4,
47- "on_board": true,
48- "func_id": -1
49- },
50- "index": 5
51- }
52- ]
53-}
@@ -1,3 +0,0 @@
1-operation,case_name,input_shape,input_dtype,input_format,input_datarange,output_shape,output_dtype,output_format,view_shape,tile_shape,batch_size,hidden_size,shared_expert_num,routed_expert_num,top_k,world_size,use_v2
2-MoeDistributedCombine,MoeDistributedCombine_test_1,"[]","bfloat16","ND","[,]","[]","bfloat16","ND","[]","[]",8,5120,0,160,8,4,1
3-MoeDistributedCombine,MoeDistributedCombine_test_2,"[]","bfloat16","ND","[,]","[]","bfloat16","ND","[]","[]",8,5120,0,160,8,4,0
@@ -1,53 +0,0 @@
1-{
2- "test_cases": [
3- {
4- "case_index": 0,
5- "case_name": "MoeDistributedCombine_test_1",
6- "operation": "MoeDistributedCombine",
7- "input_tensors": [
8- {
9- "name": "input0",
10- "shape": [
11- ""
12- ],
13- "dtype": "bfloat16",
14- "format": "ND",
15- "need_trans": false,
16- "data_range": {
17- "min": "",
18- "max": ""
19- }
20- }
21- ],
22- "output_tensors": [
23- {
24- "name": "output0",
25- "shape": [
26- ""
27- ],
28- "dtype": "bfloat16",
29- "format": "ND",
30- "need_trans": false
31- }
32- ],
33- "view_shape": [
34- ""
35- ],
36- "tile_shape": [
37- ""
38- ],
39- "params": {
40- "batch_size": 8,
41- "hidden_size": 5120,
42- "shared_expert_num": 0,
43- "routed_expert_num": 160,
44- "top_k": 8,
45- "world_size": 4,
46- "use_v2": 0,
47- "on_board": true,
48- "func_id": -1
49- },
50- "index": 6
51- }
52- ]
53-}
@@ -102,12 +102,6 @@ void GegisterOps()
102 reg.RegisterOp("AllReduceAddAllReduce", []<typename T>(OpTestParam& testParam, std::string& goldenDir) {102 reg.RegisterOp("AllReduceAddAllReduce", []<typename T>(OpTestParam& testParam, std::string& goldenDir) {
103 Distributed::TestAllReduceAddAllReduce<T>(testParam, goldenDir);103 Distributed::TestAllReduceAddAllReduce<T>(testParam, goldenDir);
104 });104 });
105- reg.RegisterOp("MoeDistributedCombine", []<typename T>(OpTestParam& testParam, std::string& goldenDir) {
106- Distributed::TestMoeDistributedCombine<T>(testParam, goldenDir);
107- });
108- reg.RegisterOp("MoeDispatch", []<typename T>(OpTestParam& testParam, std::string& goldenDir) {
109- Distributed::TestShmemMoeDispatch<T>(testParam, goldenDir);
110- });
111 reg.disRegisterMap["AllGatherAttnPostReduceScatter"] = [](OpTestParam& testParam, const std::string&,105 reg.disRegisterMap["AllGatherAttnPostReduceScatter"] = [](OpTestParam& testParam, const std::string&,
112 std::string& goldenDir) {106 std::string& goldenDir) {
113 Distributed::TestAllGatherAttentionPostReducescatter(testParam, goldenDir);107 Distributed::TestAllGatherAttentionPostReducescatter(testParam, goldenDir);
@@ -1,167 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_codegen_dispatch.cpp
13- * \brief Unit test for codegen.
14- */
15- 
16-#include <gtest/gtest.h>
17-#include "interface/function/function.h"
18-#include "tilefwk/tilefwk.h"
19-#include "interface/inner/tilefwk.h"
20-#include "interface/configs/config_manager.h"
21-#include "codegen/npu/cloudnpu/codegen_cloudnpu.h"
22-#include "test_codegen_common.h"
23-#include "test_codegen_utils.h"
24-#include "interface/operation/distributed/distributed_common.h"
25-#include <vector>
26-#include <string>
27- 
28-namespace npu::tile_fwk::Distributed {
29-class TestMoeDistributed : public CodegenTestBase {
30-public:
31- TestMoeDistributed() : CodegenTestBase({.compileStage = CS_EXECUTE_GRAPH}) {}
32- 
33-protected:
34- bool oriEnableAihacBackend = false;
35-};
36- 
37-std::string MoeDistributedGetFunctionRawName(const std::string& functionName)
38-{
39- std::string functionRawName = FUNCTION_PREFIX + functionName + SUB_FUNC_SUFFIX;
40-#if ENABLE_HIDDENLOOP
41- functionRawName += HIDDEN_FUNC_SUFFIX;
42-#endif
43- return functionRawName;
44-}
45- 
46-TEST_F(TestMoeDistributed, MoeDistributedDispatchV2)
47-{
48- const char* groupName = "hcom123";
49- DataType dType = DT_BF16;
50- int routingExpertNum = 4;
51- int topK = 4;
52- int batchSize = 2;
53- int hiddenSize = 5120;
54- int rankSize = 2;
55- 
56- int32_t expandXRowShape = topK * rankSize < routingExpertNum ?
57- static_cast<int32_t>(batchSize) * static_cast<int32_t>(topK) * rankSize :
58- static_cast<int32_t>(batchSize) * routingExpertNum;
59- 
60- Shape xShape{batchSize, hiddenSize};
61- Shape expertIdsShape{batchSize, topK};
62- Shape expandXShape{expandXRowShape, hiddenSize};
63- Shape recvCountsShape{1};
64- Shape assistInfoForCombineShape{expandXRowShape, 3};
65- Shape expertTokenNumsShape{routingExpertNum / rankSize};
66- 
67- Tensor x(dType, xShape, "x");
68- Tensor expertIds(DataType::DT_INT32, expertIdsShape, "expertIds");
69- Tensor expertTokenNums(DataType::DT_INT32, expertTokenNumsShape, "expertTokenNums");
70- Tensor expandX(dType, expandXShape, "expandX");
71- Tensor assistInfoForCombine(DataType::DT_INT32, assistInfoForCombineShape, "assistInfoForCombine");
72- Tensor recvCounts(DataType::DT_INT32, recvCountsShape, "recvCounts");
73- 
74- FUNCTION("DISPATCH_F", {x, expertIds}, {expandX, assistInfoForCombine, expertTokenNums, recvCounts})
75- {
76- Distributed::MoeDistributedDispatchV2(
77- x, expertIds, groupName, rankSize, routingExpertNum, 0, 0, expandX, assistInfoForCombine, expertTokenNums,
78- recvCounts);
79- }
80- 
81- auto functionRawName = MoeDistributedGetFunctionRawName("MoeDistributedDispatchPrepare");
82- auto function = Program::GetInstance().GetFunctionByRawName(functionRawName);
83- (void)GenCodeByFunction(*function);
84-}
85- 
86-TEST_F(TestMoeDistributed, MoeDistributedDispatch)
87-{
88- const char* group = "hcom123";
89- DataType dType = DT_BF16;
90- int routingExpertNum = 4;
91- int topK = 4;
92- int bs = 2;
93- int hiddenSize = 5120;
94- int rankSize = 4;
95- 
96- int32_t expandXRowShape = topK * rankSize < routingExpertNum ?
97- static_cast<int32_t>(bs) * static_cast<int32_t>(topK) * rankSize :
98- static_cast<int32_t>(bs) * routingExpertNum;
99- 
100- Shape tokenTensorShape{bs, hiddenSize};
101- Shape tokenExpertTableShape{bs, topK};
102- Shape expandXShape{expandXRowShape, hiddenSize};
103- Shape validCntShape{routingExpertNum / rankSize};
104- Shape combineInfoShape{expandXRowShape, 3};
105- 
106- Tensor tokenTensor(dType, tokenTensorShape, "tokenTensor");
107- Tensor tokenExpertTable(DataType::DT_INT32, tokenExpertTableShape, "tokenExpertTable");
108- Tensor validCnt(DataType::DT_INT32, validCntShape, "validCnt");
109- Tensor expandX(dType, expandXShape, "expandX");
110- Tensor combineInfo(DataType::DT_INT32, combineInfoShape, "combineInfo");
111- 
112- MoeConfig moeConfig{routingExpertNum, routingExpertNum / rankSize, rankSize};
113- 
114- FUNCTION("DISPATCH_F", {tokenTensor, tokenExpertTable}, {expandX, validCnt, combineInfo})
115- {
116- Distributed::MoeDistributedDispatch(
117- tokenTensor, tokenExpertTable, expandX, validCnt, combineInfo, group, moeConfig);
118- }
119- 
120- auto functionRawName = MoeDistributedGetFunctionRawName("L0");
121- auto function = Program::GetInstance().GetFunctionByRawName(functionRawName);
122- (void)GenCodeByFunction(*function);
123-}
124- 
125-void TestMoeDistributedCombineFunc(
126- std::function<void(
127- const Tensor&, const Tensor&, const Tensor&, const Tensor&, const char*, uint32_t, uint32_t, uint32_t, uint32_t,
128- Tensor&)>
129- func,
130- std::string loopName)
131-{
132- const char* group = "hcom123";
133- int32_t batchSize = 8;
134- int32_t hiddenSize = 5120;
135- int32_t moeExpertNum = 160;
136- int32_t topK = 8;
137- int32_t epWorldSize = 4;
138- int32_t row = std::min(topK * batchSize * epWorldSize, batchSize * moeExpertNum);
139- DataType dType = DT_BF16;
140- 
141- Tensor expandX(dType, {row, hiddenSize}, "expandX");
142- Tensor assistInfoForCombine(DT_INT32, {row, 3}, "assistInfoForCombine");
143- Tensor recvCounts(DataType::DT_INT32, {1}, "recvCounts");
144- Tensor expertScales(DT_FP32, {batchSize, topK}, "expertScales");
145- Tensor out(dType, {batchSize, hiddenSize}, "out");
146- 
147- FUNCTION("MoeDistributedCombineMain", {expandX, assistInfoForCombine, recvCounts, expertScales}, {out})
148- {
149- func(expandX, assistInfoForCombine, recvCounts, expertScales, group, epWorldSize, moeExpertNum, 0, 0, out);
150- }
151- 
152- auto functionRawName = MoeDistributedGetFunctionRawName(loopName);
153- auto function = Program::GetInstance().GetFunctionByRawName(functionRawName);
154- (void)GenCodeByFunction(*function);
155-}
156- 
157-TEST_F(TestMoeDistributed, TestMoeDistributedCombine)
158-{
159- TestMoeDistributedCombineFunc(Distributed::MoeDistributedCombine, "MoeDistributedCombine");
160-}
161- 
162-TEST_F(TestMoeDistributed, TestMoeDistributedCombineV2)
163-{
164- TestMoeDistributedCombineFunc(Distributed::MoeDistributedCombineV2, "MoeDistributedCombineSend");
165-}
166- 
167-} // namespace npu::tile_fwk::Distributed