Merged
MoeInitRouting和MoeReRouting算子支持topk_weight重排 #6793
MoeInitRouting和MoeReRouting算子支持topk_weight重排 #6793
Merged
BruceLPAdd on Jun 12
Total: 83 files changed+19127-1616
@@ -166,6 +166,7 @@
166- [aclnnMoeInitRoutingV2](../../moe/moe_init_routing_v2/docs/aclnnMoeInitRoutingV2.md)166- [aclnnMoeInitRoutingV2](../../moe/moe_init_routing_v2/docs/aclnnMoeInitRoutingV2.md)
167- [aclnnMoeInitRoutingV2Grad](../../moe/moe_init_routing_v2_grad/docs/aclnnMoeInitRoutingV2Grad.md)167- [aclnnMoeInitRoutingV2Grad](../../moe/moe_init_routing_v2_grad/docs/aclnnMoeInitRoutingV2Grad.md)
168- [aclnnMoeInitRoutingV3](../../moe/moe_init_routing_v3/docs/aclnnMoeInitRoutingV3.md)168- [aclnnMoeInitRoutingV3](../../moe/moe_init_routing_v3/docs/aclnnMoeInitRoutingV3.md)
169+- [aclnnMoeInitRoutingV4](../../moe/moe_init_routing_v4/docs/aclnnMoeInitRoutingV4.md)
169- [aclnnMoeTokenPermute](../../moe/moe_token_permute/docs/aclnnMoeTokenPermute.md)170- [aclnnMoeTokenPermute](../../moe/moe_token_permute/docs/aclnnMoeTokenPermute.md)
170- [aclnnMoeTokenPermuteGrad](../../moe/moe_token_permute_grad/docs/aclnnMoeTokenPermuteGrad.md)171- [aclnnMoeTokenPermuteGrad](../../moe/moe_token_permute_grad/docs/aclnnMoeTokenPermuteGrad.md)
171- [aclnnMoeTokenPermuteV2](../../moe/moe_token_permute/docs/aclnnMoeTokenPermuteV2.md)172- [aclnnMoeTokenPermuteV2](../../moe/moe_token_permute/docs/aclnnMoeTokenPermuteV2.md)
@@ -20,6 +20,8 @@
20- [mhc_pre_sinkhorn](../../torch_extension/cann_ops_transformer/docs/zh/mhc_pre_sinkhorn.md)20- [mhc_pre_sinkhorn](../../torch_extension/cann_ops_transformer/docs/zh/mhc_pre_sinkhorn.md)
21- [mixed_quant_sparse_flash_mla](../../torch_extension/cann_ops_transformer/docs/zh/mixed_quant_sparse_flash_mla.md)21- [mixed_quant_sparse_flash_mla](../../torch_extension/cann_ops_transformer/docs/zh/mixed_quant_sparse_flash_mla.md)
22- [moe_finalize_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_finalize_routing.md)22- [moe_finalize_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_finalize_routing.md)
23+- [moe_init_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_init_routing.md)
24+- [moe_re_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_re_routing.md)
23- [moe_token_permute](../../torch_extension/cann_ops_transformer/docs/zh/moe_token_permute.md)25- [moe_token_permute](../../torch_extension/cann_ops_transformer/docs/zh/moe_token_permute.md)
24- [qkv_rms_norm_rope_cache_with_k_scale](../../torch_extension/cann_ops_transformer/docs/zh/qkv_rms_norm_rope_cache_with_k_scale.md)26- [qkv_rms_norm_rope_cache_with_k_scale](../../torch_extension/cann_ops_transformer/docs/zh/qkv_rms_norm_rope_cache_with_k_scale.md)
25- [quant_compressor](../../torch_extension/cann_ops_transformer/docs/zh/quant_compressor.md)27- [quant_compressor](../../torch_extension/cann_ops_transformer/docs/zh/quant_compressor.md)
@@ -165,6 +165,7 @@
165|[aclnnMoeInitRouting](../../moe/moe_init_routing/docs/aclnnMoeInitRouting.md)|MoE的routing计算,根据aclnnMoeGatingTopKSoftmax的计算结果做Routing处理。|默认确定性实现| 默认确定性实现 |165|[aclnnMoeInitRouting](../../moe/moe_init_routing/docs/aclnnMoeInitRouting.md)|MoE的routing计算,根据aclnnMoeGatingTopKSoftmax的计算结果做Routing处理。|默认确定性实现| 默认确定性实现 |
166|[aclnnMoeInitRoutingV2](../../moe/moe_init_routing_v2/docs/aclnnMoeInitRoutingV2.md)|该算子对应MoE中的Routing计算,以MoeGatingTopKSoftmax算子的输出x和expert_idx作为输入,并输出Routing矩阵expanded_x等结果供后续计算使用。|默认确定性实现| 默认确定性实现 |166|[aclnnMoeInitRoutingV2](../../moe/moe_init_routing_v2/docs/aclnnMoeInitRoutingV2.md)|该算子对应MoE中的Routing计算,以MoeGatingTopKSoftmax算子的输出x和expert_idx作为输入,并输出Routing矩阵expanded_x等结果供后续计算使用。|默认确定性实现| 默认确定性实现 |
167|[aclnnMoeInitRoutingV3](../../moe/moe_init_routing_v3/docs/aclnnMoeInitRoutingV3.md)|MoE的routing计算,根据[aclnnMoeGatingTopKSoftmaxV2](../../moe/moe_gating_top_k_softmax_v2/docs/aclnnMoeGatingTopKSoftmaxV2.md)的计算结果做routing处理,支持不量化和动态量化模式。|默认确定性实现| 默认确定性实现 |167|[aclnnMoeInitRoutingV3](../../moe/moe_init_routing_v3/docs/aclnnMoeInitRoutingV3.md)|MoE的routing计算,根据[aclnnMoeGatingTopKSoftmaxV2](../../moe/moe_gating_top_k_softmax_v2/docs/aclnnMoeGatingTopKSoftmaxV2.md)的计算结果做routing处理,支持不量化和动态量化模式。|默认确定性实现| 默认确定性实现 |
168+|[aclnnMoeInitRoutingV4](../../moe/moe_init_routing_v4/docs/aclnnMoeInitRoutingV4.md)|MoE的routing计算,根据[aclnnMoeGatingTopKSoftmaxV2](../../moe/moe_gating_top_k_softmax_v2/docs/aclnnMoeGatingTopKSoftmaxV2.md)的计算结果做routing处理,支持非量化、静态量化和动态量化模式。| - | 默认确定性实现 |
168|[aclnnMoeInitRoutingQuant](../../moe/moe_init_routing_quant/docs/aclnnMoeInitRoutingQuant.md)|MoE的Routing计算,根据aclnnMoeGatingTopKSoftmax的计算结果做Routing处理,并对结果进行量化。|默认确定性实现| - |169|[aclnnMoeInitRoutingQuant](../../moe/moe_init_routing_quant/docs/aclnnMoeInitRoutingQuant.md)|MoE的Routing计算,根据aclnnMoeGatingTopKSoftmax的计算结果做Routing处理,并对结果进行量化。|默认确定性实现| - |
169|[aclnnMoeInitRoutingQuantV2](../../moe/moe_init_routing_quant_v2/docs/aclnnMoeInitRoutingQuantV2.md)|MoE的Routing计算,根据aclnnMoeGatingTopKSoftmaxV2的计算结果做Routing处理。|默认确定性实现| 默认确定性实现 |170|[aclnnMoeInitRoutingQuantV2](../../moe/moe_init_routing_quant_v2/docs/aclnnMoeInitRoutingQuantV2.md)|MoE的Routing计算,根据aclnnMoeGatingTopKSoftmaxV2的计算结果做Routing处理。|默认确定性实现| 默认确定性实现 |
170|[aclnnMoeInitRoutingV2Grad](../../moe/moe_init_routing_v2_grad/docs/aclnnMoeInitRoutingV2Grad.md)|[aclnnMoeInitRoutingV2](../../moe/moe_init_routing_v2/docs/aclnnMoeInitRoutingV2.md)的反向传播,完成Tokens的加权求和。|默认确定性实现| 默认确定性实现 |171|[aclnnMoeInitRoutingV2Grad](../../moe/moe_init_routing_v2_grad/docs/aclnnMoeInitRoutingV2Grad.md)|[aclnnMoeInitRoutingV2](../../moe/moe_init_routing_v2/docs/aclnnMoeInitRoutingV2.md)的反向传播,完成Tokens的加权求和。|默认确定性实现| 默认确定性实现 |
@@ -1216,6 +1216,16 @@
1216 <td>AI Core</td>1216 <td>AI Core</td>
1217 <td>MoE的routing计算,根据<a href="../../moe/moe_gating_top_k_softmax_v2/docs/aclnnMoeGatingTopKSoftmaxV2.md">aclnnMoeGatingTopKSoftmaxV2</a>的计算结果做routing处理,支持不量化和动态量化模式。</td>1217 <td>MoE的routing计算,根据<a href="../../moe/moe_gating_top_k_softmax_v2/docs/aclnnMoeGatingTopKSoftmaxV2.md">aclnnMoeGatingTopKSoftmaxV2</a>的计算结果做routing处理,支持不量化和动态量化模式。</td>
1218 </tr>1218 </tr>
1219+ <tr>
1220+ <td>moe</td>
1221+ <td><a href="../../moe/moe_init_routing_v4/README.md">moe_init_routing_v4</a></td>
1222+ <td>✓</td>
1223+ <td>✓</td>
1224+ <td>✓</td>
1225+ <td>✓</td>
1226+ <td>AI Core</td>
1227+ <td>MoE的routing计算,根据<a href="../../moe/moe_gating_top_k_softmax_v2/docs/aclnnMoeGatingTopKSoftmaxV2.md">aclnnMoeGatingTopKSoftmaxV2</a>的计算结果做routing处理,支持非量化、静态量化和动态量化模式。</td>
1228+ </tr>
1219 <tr>1229 <tr>
1220 <td>moe</td>1230 <td>moe</td>
1221 <td><a href="../../moe/moe_re_routing/README.md">moe_re_routing</a></td>1231 <td><a href="../../moe/moe_re_routing/README.md">moe_re_routing</a></td>
@@ -1226,6 +1236,16 @@
1226 <td>AI Core</td>1236 <td>AI Core</td>
1227 <td>MoE网络中,进行AlltoAll操作从其他卡上拿到需要算的token后,将token按照专家顺序重新排列。</td>1237 <td>MoE网络中,进行AlltoAll操作从其他卡上拿到需要算的token后,将token按照专家顺序重新排列。</td>
1228 </tr>1238 </tr>
1239+ <tr>
1240+ <td>moe</td>
1241+ <td><a href="../../moe/moe_re_routing_v2/README.md">moe_re_routing_v2</a></td>
1242+ <td>✓</td>
1243+ <td>✓</td>
1244+ <td>✗</td>
1245+ <td>✓</td>
1246+ <td>AI Core</td>
1247+ <td>MoE网络中,进行AlltoAll操作从其他卡上拿到需要算的token后,将token按照专家顺序重新排列,支持对topkWeight重排。</td>
1248+ </tr>
1229 <tr>1249 <tr>
1230 <td>moe</td>1250 <td>moe</td>
1231 <td><a href="../../moe/moe_token_permute/README.md">moe_token_permute</a></td>1251 <td><a href="../../moe/moe_token_permute/README.md">moe_token_permute</a></td>
@@ -49,6 +49,8 @@
49|[mhc_pre_sinkhorn](../../torch_extension/cann_ops_transformer/docs/zh/mhc_pre_sinkhorn.md)|基于一系列计算得到MHC架构中hidden层的$\mathbf{H}'_{\text{res}}$和$\mathbf{H}_{\text{post}}$投影矩阵以及Attention或MLP层的输入矩阵$\mathbf{h}_{\text{in}}$。对$\mathbf{H}'_{\text{res}}$矩阵执行Sinkhorn迭代归一化变换,最终得到双随机矩阵$\mathbf{H}_{\text{res}}$;支持输出中间计算结果,用于反向梯度计算。|默认确定性实现|默认确定性实现|49|[mhc_pre_sinkhorn](../../torch_extension/cann_ops_transformer/docs/zh/mhc_pre_sinkhorn.md)|基于一系列计算得到MHC架构中hidden层的$\mathbf{H}'_{\text{res}}$和$\mathbf{H}_{\text{post}}$投影矩阵以及Attention或MLP层的输入矩阵$\mathbf{h}_{\text{in}}$。对$\mathbf{H}'_{\text{res}}$矩阵执行Sinkhorn迭代归一化变换,最终得到双随机矩阵$\mathbf{H}_{\text{res}}$;支持输出中间计算结果,用于反向梯度计算。|默认确定性实现|默认确定性实现|
50|[mixed_quant_sparse_flash_mla](../../torch_extension/cann_ops_transformer/docs/zh/mixed_quant_sparse_flash_mla.md)|量化场景下基于共享KV完成MixedQuantSparseFlashMla稀疏注意力计算。需与`mixed_quant_sparse_flash_mla_metadata`配套使用。|默认确定性实现|默认确定性实现|50|[mixed_quant_sparse_flash_mla](../../torch_extension/cann_ops_transformer/docs/zh/mixed_quant_sparse_flash_mla.md)|量化场景下基于共享KV完成MixedQuantSparseFlashMla稀疏注意力计算。需与`mixed_quant_sparse_flash_mla_metadata`配套使用。|默认确定性实现|默认确定性实现|
51|[moe_finalize_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_finalize_routing.md)|将各专家FFN的输出结果按路由权重加权合并,还原为原始token序列。|默认支持确定性计算。|默认支持确定性计算。|51|[moe_finalize_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_finalize_routing.md)|将各专家FFN的输出结果按路由权重加权合并,还原为原始token序列。|默认支持确定性计算。|默认支持确定性计算。|
52+|[moe_init_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_init_routing.md)|MoE的routing计算,根据moe_gating_top_k_softmax的计算结果做routing处理,支持不量化、静态量化和动态量化模式。|默认确定性实现|默认确定性实现|
53+|[moe_re_routing](../../torch_extension/cann_ops_transformer/docs/zh/moe_re_routing.md)|MoE网络中,进行AlltoAll操作从其他卡上拿到需要算的token后,将token按照专家顺序重新排列。支持对topkWeight重排。|默认确定性实现|默认确定性实现|
52|[moe_token_permute](../../torch_extension/cann_ops_transformer/docs/zh/moe_token_permute.md)|根据专家索引扩展并排序token。|默认支持确定性计算。|54|[moe_token_permute](../../torch_extension/cann_ops_transformer/docs/zh/moe_token_permute.md)|根据专家索引扩展并排序token。|默认支持确定性计算。|
53|[qkv_rms_norm_rope_cache_with_k_scale](../../torch_extension/cann_ops_transformer/docs/zh/qkv_rms_norm_rope_cache_with_k_scale.md)|融合Q/K/V拆分、Q/K RMSNorm、RoPE、共享rotation矩阵乘、FP8量化和KV Cache更新,返回更新后的cache副本。|-|默认支持确定性计算。|55|[qkv_rms_norm_rope_cache_with_k_scale](../../torch_extension/cann_ops_transformer/docs/zh/qkv_rms_norm_rope_cache_with_k_scale.md)|融合Q/K/V拆分、Q/K RMSNorm、RoPE、共享rotation矩阵乘、FP8量化和KV Cache更新,返回更新后的cache副本。|-|默认支持确定性计算。|
54|[quant_compressor](../../torch_extension/cann_ops_transformer/docs/zh/quant_compressor.md)|Compressor的量化版本,将每4或128个token的KV cache压缩成一个,然后每个token与这些压缩的KV cache进行DSA计算。|-|默认支持确定性计算|56|[quant_compressor](../../torch_extension/cann_ops_transformer/docs/zh/quant_compressor.md)|Compressor的量化版本,将每4或128个token的KV cache压缩成一个,然后每个token与这些压缩的KV cache进行DSA计算。|-|默认支持确定性计算|
@@ -26,7 +26,7 @@
26#include "array_ops.h"26#include "array_ops.h"
27#include "ge_ir_build.h"27#include "ge_ir_build.h"
28 28 
29-#include "fusion_ops.h"29+#include "../op_graph/moe_init_routing_v3_proto.h"
30#include "nn_other.h"30#include "nn_other.h"
31 31 
32#define FAILED -132#define FAILED -1
@@ -0,0 +1,482 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file moe_init_routing_v3_tiling_arch35.h
13+ * \brief
14+ */
15+ 
16+#ifndef MOE_INIT_ROUTING_V3_TILING_ARCH35_H
17+#define MOE_INIT_ROUTING_V3_TILING_ARCH35_H
18+ 
19+#include <cmath>
20+#include <sstream>
21+#include <string>
22+#include <unordered_set>
23+#include "register/op_def_registry.h"
24+#include "moe_init_routing_v3_tiling.h"
25+#include "../op_kernel/arch35/moe_init_routing_v3_arch35_tiling_def.h"
26+#include "op_host/tiling_util.h"
27+ 
28+#define MIRV3_CHECK_GE_RET(expr) \
29+ if (ge::graphStatus ret = (expr); ret != ge::GRAPH_SUCCESS) { \
30+ return ret; \
31+ }
32+ 
33+namespace optiling {
34+using Ops::Transformer::OpTiling::TilingBaseClass;
35+constexpr int64_t SIMT_DCACHE_SIZE = 64 * 1024LL; // UB要给SIMT预留64k的DCache空间,然后要用SetLocalMemSize()
36+constexpr int64_t SORT_API_MAX_ELEM = 32 * 255LL; // AscendC::Sort全排序模式最多支持一次排序(32*255rep)个元素
37+constexpr int64_t MRG_SORT_API_MAX_ELEM = 1024LL;
38+constexpr int64_t MX_QUANT_BLOCK_SIZE = 32LL;
39+constexpr int64_t MXFPX_SCALE_BLOCK_SIZE = 64LL;
40+constexpr int64_t SCALE_FACTOR_WITH_X = 32LL;
41+constexpr int64_t NUM_THOUSAND = 1000LL;
42+constexpr int64_t FP8_PERBLOCK_BLOCK_SIZE = 128LL;
43+constexpr int64_t FP8_GROUP_SIZE = 128LL;
44+constexpr int64_t DOUBLE_BUFFER = 2LL;
45+ 
46+constexpr int64_t MAX_QUEUE_BUFFER_NUM = 6LL;
47+ 
48+constexpr int64_t NUM_TWO = 2LL;
49+constexpr int64_t NUM_THREE = 3LL;
50+constexpr int64_t NUM_FOUR = 4LL;
51+constexpr int64_t MRG_LIST_NUM = 4LL;
52+constexpr int64_t SORT32_ALIGN_ELEMENT = 32LL;
53+constexpr int64_t UB_BLOCK_SIZE = 32LL;
54+constexpr size_t DIM_ONE = 1ULL;
55+constexpr size_t DIM_TWO = 2ULL;
56+constexpr int32_t SIZE_16 = 16;
57+constexpr int32_t LENGTH_1024 = 1024;
58+constexpr int64_t KV_FACTOR = 2LL;
59+constexpr int64_t ONE_CORE_SORT_BUFFER = 6LL;
60+constexpr int64_t EXPERT_IDX_MAX = 10240LL;
61+constexpr int64_t KV_MODE_EXPERT_IDX_MAX = EXPERT_IDX_MAX / KV_FACTOR;
62+constexpr int64_t RANK_ONE = 1LL;
63+constexpr int64_t RANK_TWO = 2LL;
64+constexpr int64_t RANK_THREE = 3LL;
65+constexpr int64_t BF16_TO_FP32_SIZE_FACTOR = 2LL;
66+ 
67+// 输入输出的位置索引(V3 回归后 topk_weight 相关索引不再使用,V4 子类使用独立索引常量)
68+constexpr int64_t INPUT_X_INDEX = 0LL;
69+constexpr int64_t INPUT_EXPERT_IDX_INDEX = 1LL;
70+constexpr int64_t INPUT_SCALE_INDEX = 2LL;
71+constexpr int64_t INPUT_OFFSET_INDEX = 3LL;
72+constexpr int64_t OUTPUT_EXPANDED_X_INDEX = 0LL;
73+constexpr int64_t OUTPUT_EXPANDED_ROW_IDX_INDEX = 1LL;
74+constexpr int64_t OUTPUT_EXPERT_TOKENS_COUNT_INDEX = 2LL;
75+constexpr int64_t OUTPUT_EXPANDED_SCALE_INDEX = 3LL;
76+constexpr int64_t ATTR_ACTIVE_NUM_INDEX = 0LL;
77+constexpr int64_t ATTR_EXPERT_CAPACITY_INDEX = 1LL;
78+constexpr int64_t ATTR_EXPERT_NUM_INDEX = 2LL;
79+constexpr int64_t ATTR_DROP_PAD_MODE_INDEX = 3LL;
80+constexpr int64_t ATTR_EXPERT_TOKEN_NUM_TYPE_INDEX = 4LL;
81+constexpr int64_t ATTR_EXPERT_TOKEN_NUM_FLAG_INDEX = 5LL;
82+constexpr int64_t ATTR_QUANT_MODE_INDEX = 6LL;
83+constexpr int64_t ATTR_EXPERT_RANGE_INDEX = 7LL;
84+constexpr int64_t ATTR_ROW_IDX_TYPE_INDEX = 8LL;
85+ 
86+constexpr int64_t ACTIVE_NUM_MIN_VALUE = -1LL;
87+constexpr int64_t DYNAMIC_QUANT_COLS_BUFFER = 21LL;
88+constexpr int64_t HIF8_PERTENSOR_QUANT_COLS_BUFFER = 5LL;
89+constexpr int64_t HIF8_PERTOKEN_QUANT_COLS_BUFFER = 5LL;
90+constexpr int64_t STATIC_QUANT_ROW_MULTIPLE = 2LL; // 静态量化行方向Buffer乘数
91+constexpr int64_t STATIC_QUANT_FULLLOAD_COLS_BUFFER = 5LL;
92+constexpr int64_t DYNAMIC_QUANT_FULLLOAD_COLS_BUFFER = 9LL;
93+ 
94+// 输入attrs相关
95+constexpr int64_t ROW_IDX_GATHER = 0LL;
96+constexpr int64_t ROW_IDX_SCATTER = 1LL;
97+constexpr int64_t QUANT_MODE_UNQUANT = -1LL;
98+constexpr int64_t QUANT_MODE_STATIC = 0LL;
99+constexpr int64_t QUANT_MODE_DYNAMIC = 1LL;
100+constexpr int64_t QUANT_MODE_MXFP8_E5M2 = 2LL;
101+constexpr int64_t QUANT_MODE_MXFP8_E4M3FN = 3LL;
102+constexpr int64_t QUANT_MODE_FP8_GROUP_E5M2 = 4LL;
103+constexpr int64_t QUANT_MODE_FP8_GROUP_E4M3FN = 5LL;
104+constexpr int64_t QUANT_MODE_HIF8_CAST = 6LL;
105+constexpr int64_t QUANT_MODE_HIF8_PERTENSOR = 7LL;
106+constexpr int64_t QUANT_MODE_HIF8_PERTOKEN = 8LL;
107+constexpr int64_t QUANT_MODE_MXFP4_E2M1 = 9LL;
108+constexpr int64_t QUANT_MODE_FP8_PERBLOCK_E5M2 = 11LL;
109+constexpr int64_t QUANT_MODE_FP8_PERBLOCK_E4M3FN = 12LL;
110+constexpr int64_t QUANT_MODE_INT4_DYNAMIC = 13LL;
111+constexpr int64_t QUANT_MODE_FP8_GROUP_AMAX_E5M2 = 14LL;
112+constexpr int64_t QUANT_MODE_FP8_GROUP_AMAX_E4M3FN = 15LL;
113+constexpr int64_t QUANT_MODE_MXFP8_ROUNDSCALE_AMAX_E5M2 = 16LL;
114+constexpr int64_t QUANT_MODE_MXFP8_ROUNDSCALE_AMAX_E4M3FN = 17LL;
115+constexpr int64_t EXPERT_TOKENS_TYPE_CUMSUM = 0LL;
116+ 
117+constexpr int64_t EXPERT_TOKENS_TYPE_COUNT = 1LL;
118+constexpr int64_t EXPERT_TOKENS_TYPE_KEY_VALUE = 2LL;
119+constexpr int64_t DROP_PAD_MODE_DROPLESS = 0LL;
120+constexpr int64_t DROP_PAD_MODE_DROPPAD = 1LL;
121+constexpr int64_t EXPERT_CAPACITY_MIN_VALUE = 0LL;
122+constexpr int64_t MAX_COLS_ONE_LOOP = 16376LL; // DropPad Tiling计算使用的最大列数
123+constexpr int64_t REG_SIZE = 256LL;
124+ 
125+constexpr int64_t TILINGKEY_BASE = 10000000LL;
126+constexpr int64_t FULLLOAD_TILINGKEY_BASE = 200000LL; // 全载模版
127+constexpr int64_t SORT_CORE_TILINGKEY_BASE = 1000000LL;
128+constexpr int64_t QUANT_MODE_TILINGKEY_BASE = 10000LL;
129+constexpr int64_t ROWIDX_TYPE_TILINGKEY_BASE = 1000LL;
130+constexpr int64_t DROP_MODE_TILINGKEY_BASE = 100LL;
131+constexpr uint64_t EMPTY_TENSOR_TILINGKEY = 3000000ULL;
132+constexpr int64_t KEY_VALUE_MODE_DIM0_NUM = 2LL;
133+ 
134+inline static int64_t CeilLog4(int64_t x)
135+{
136+ if (x <= 0) {
137+ return 0;
138+ }
139+ return static_cast<int64_t>(std::ceil(std::log(x) / std::log(NUM_FOUR)));
140+}
141+ 
142+inline static int64_t Align(int64_t elementNum, int64_t bytes)
143+{
144+ if (bytes == 0) {
145+ return 0;
146+ }
147+ return (elementNum * bytes + UB_BLOCK_SIZE - 1) / UB_BLOCK_SIZE * UB_BLOCK_SIZE / bytes;
148+}
149+ 
150+inline static int64_t AlignBytes(int64_t elementNum, int64_t bytes)
151+{
152+ if (bytes == 0) {
153+ return 0;
154+ }
155+ return (elementNum * bytes + UB_BLOCK_SIZE - 1) / UB_BLOCK_SIZE * UB_BLOCK_SIZE;
156+}
157+ 
158+struct MultipleParams {
159+ int64_t colMultiple = 0;
160+ int64_t rowMultiple = 0;
161+};
162+ 
163+struct PerLoopParams {
164+ int64_t xCopyInQueueBufferNum = 2;
165+ int64_t perLoopCols = 0;
166+ int64_t perLoopMaxIndicesElements = 0;
167+};
168+ 
169+class MoeInitRoutingV3TilingArch35 : public TilingBaseClass {
170+public:
171+ explicit MoeInitRoutingV3TilingArch35(gert::TilingContext *context)
172+ : TilingBaseClass(context)
173+ {
174+ Reset();
175+ }
176+ ~MoeInitRoutingV3TilingArch35() override = default;
177+ 
178+ void Reset(gert::TilingContext *context) override
179+ {
180+ TilingBaseClass::Reset(context);
181+ Reset();
182+ }
183+ 
184+protected:
185+ // 1、获取INPUT/OUTPUT/ATTR信息:DelayedGetShapeAttrsInfo(),延后到DoOpTiling内执行,以便先检查IsCapable()
186+ ge::graphStatus GetShapeAttrsInfo() override
187+ {
188+ OP_LOGD(context_, "Entered MoeInitRoutingV3TilingArch35::GetShapeAttrsInfo()");
189+ return ge::GRAPH_SUCCESS;
190+ }
191+ // 2、获取平台信息比如CoreNum、UB/L1/L0C资源大小
192+ ge::graphStatus GetPlatformInfo() override;
193+ // 3、判断此Tiling模板是否适配当前SOC
194+ bool IsCapable() override
195+ {
196+ OP_LOGD(context_, "Entered MoeInitRoutingV3TilingArch35::IsCapable()");
197+ return Ops::Transformer::OpTiling::IsRegbaseSocVersion(context_);
198+ }
199+ // 4、计算数据切分TilingData
200+ ge::graphStatus DoOpTiling() override;
201+ // 5、计算高阶API的TilingData
202+ ge::graphStatus DoLibApiTiling() override
203+ {
204+ OP_LOGD(context_, "Entered MoeInitRoutingV3TilingArch35::DoLibApiTiling()");
205+ return ge::GRAPH_SUCCESS;
206+ }
207+ // 6、计算TilingKey
208+ uint64_t GetTilingKey() const override;
209+ // 7、计算Workspace 大小
210+ ge::graphStatus GetWorkspaceSize() override;
211+ // 8、保存Tiling数据
212+ ge::graphStatus PostTiling() override;
213+ 
214+ void Reset()
215+ {
216+ opName = nullptr;
217+ }
218+ 
219+ // DoGetShapeAttrsInfo使用的子函数(V4 需覆盖)
220+ virtual ge::graphStatus GetInputTensorsInfo();
221+ virtual ge::graphStatus GetOutputTensorsInfo();
222+ virtual ge::graphStatus GetInputAttrsInfo();
223+ 
224+ // 辅助工具函数(V4 子类需要使用)
225+ template <bool IS_INPUT_TENSOR = true, bool IS_OPTIONAL_INPUT = false>
226+ ge::graphStatus GetTensorShapeDtype(gert::Shape &shape, ge::DataType &dtype, int64_t index)
227+ {
228+ OP_LOGD(context_, "Entered MoeInitRoutingV3TilingArch35::GetTensorShapeDtype(...)");
229+ const gert::StorageShape *shapePtr{nullptr};
230+ const gert::CompileTimeTensorDesc *descPtr{nullptr};
231+ if constexpr (IS_INPUT_TENSOR) {
232+ if constexpr (IS_OPTIONAL_INPUT) {
233+ shapePtr = context_->GetOptionalInputShape(index);
234+ descPtr = context_->GetOptionalInputDesc(index);
235+ } else {
236+ shapePtr = context_->GetInputShape(index);
237+ descPtr = context_->GetInputDesc(index);
238+ }
239+ } else {
240+ shapePtr = context_->GetOutputShape(index);
241+ descPtr = context_->GetOutputDesc(index);
242+ }
243+ OP_CHECK_NULL_WITH_CONTEXT(context_, shapePtr);
244+ shape = shapePtr->GetStorageShape();
245+ OP_CHECK_NULL_WITH_CONTEXT(context_, descPtr);
246+ dtype = descPtr->GetDataType();
247+ return ge::GRAPH_SUCCESS;
248+ }
249+ 
250+ ge::graphStatus GetOptionalInputShapeDtype(gert::Shape &shape, ge::DataType &dtype, int64_t &marker, int64_t index)
251+ {
252+ OP_LOGD(context_, "Entered MoeInitRoutingV3TilingArch35::GetOptionalInputShapeDtype(...)");
253+ if (context_->GetOptionalInputShape(index) != nullptr) {
254+ marker = 1;
255+ return GetTensorShapeDtype<true, true>(shape, dtype, index);
256+ } else {
257+ // 该Tensor没有输入
258+ marker = 0;
259+ return ge::GRAPH_SUCCESS;
260+ }
261+ }
262+ 
263+ template <typename ATTR_T>
264+ ge::graphStatus GetInputAttr(ATTR_T &attr, const gert::RuntimeAttrs *attrsPtr, int64_t index)
265+ {
266+ OP_LOGD(context_, "Entered MoeInitRoutingV3TilingArch35::GetInputAttr(...)");
267+ const auto *attrPtr = attrsPtr->GetAttrPointer<ATTR_T>(index);
268+ OP_CHECK_NULL_WITH_CONTEXT(context_, attrPtr);
269+ attr = *attrPtr;
270+ return ge::GRAPH_SUCCESS;
271+ }
272+ 
273+ // op variables
274+ const char *opName = "";
275+ MoeInitRoutingV3Arch35TilingData *tilingDataPtr_{nullptr};
276+ 
277+ // platform infos
278+ int64_t aivCoreNum_ = 0LL;
279+ int64_t totalUbSize_ = 0LL;
280+ int64_t availUbSize_ = 0LL;
281+ platform_ascendc::SocVersion socVersion_ = platform_ascendc::SocVersion::ASCEND910B;
282+ 
283+ // important values
284+ int64_t sortLoopMaxElement_ = 0LL;
285+ int64_t totalLength_ = 0LL;
286+ int64_t n_ = 0LL;
287+ int64_t k_ = 0LL;
288+ int64_t cols_ = 0LL;
289+ int64_t inputXDtypeSize_ = 0LL;
290+ int64_t inputScaleDTypeSize_ = 0LL;
291+ int64_t isInputScale_ = 0LL;
292+ int64_t isInputOffset_ = 0LL;
293+ int64_t isInputTopkWeight_ = 0LL;
294+ int64_t isOutputExpandedTopkWeight_ = 0LL;
295+ int64_t sortMode_ = 0LL;
296+ 
297+ // full load flag
298+ bool isFullload_ = false;
299+ bool isEmptyTensor_ = false;
300+ int64_t ep_ = 0LL;
301+ 
302+ // input attrs
303+ int64_t activeNum_ = -1LL;
304+ int64_t expertCapacity_ = -1LL;
305+ int64_t expertNum_ = -1LL;
306+ int64_t dropPadMode_ = -1LL;
307+ int64_t expertTokensNumType_ = -1LL;
308+ bool expertTokensNumFlag_ = false;
309+ int64_t quantMode_ = -1LL;
310+ int64_t expertStart_ = -1LL;
311+ int64_t expertEnd_ = -1LL;
312+ int64_t rowIdxType_ = -1LL;
313+ 
314+ // input tensors shape
315+ gert::Shape xShape_;
316+ gert::Shape expertIdxShape_;
317+ gert::Shape scaleShape_;
318+ gert::Shape offsetShape_;
319+ gert::Shape topkWeightShape_;
320+ // output tensors shape
321+ gert::Shape expandedXShape_;
322+ gert::Shape expandedRowIdxShape_;
323+ gert::Shape expertTokensCountOrCumsumShape_;
324+ gert::Shape expandedScaleShape_;
325+ gert::Shape expandedTopkWeightShape_;
326+ 
327+ // input tensors dtype
328+ ge::DataType xDtype_;
329+ ge::DataType expertIdxDtype_;
330+ ge::DataType scaleDtype_;
331+ ge::DataType offsetDtype_;
332+ ge::DataType topkWeightDtype_;
333+ // output tensors dtype
334+ ge::DataType expandedXDtype_;
335+ ge::DataType expandedRowIdxDtype_;
336+ ge::DataType expertTokensCountOrCumsumDtype_;
337+ ge::DataType expandedScaleDtype_;
338+ ge::DataType expandedTopkWeightDtype_;
339+ 
340+private:
341+ ge::graphStatus CheckSetPlatformInfo();
342+ ge::graphStatus DoGetShapeAttrsInfo();
343+ ge::graphStatus CheckSetAttrs();
344+ ge::graphStatus CheckSetListAttrs();
345+ ge::graphStatus ValidateExpertTokensNumType();
346+ ge::graphStatus ValidateExpertNum();
347+ ge::graphStatus ValidateDropPadMode();
348+ ge::graphStatus ValidateExpertCapacity();
349+ ge::graphStatus ValidateQuantMode();
350+ ge::graphStatus ValidateRowIdxType();
351+ ge::graphStatus CheckSetInputs();
352+ ge::graphStatus CheckSetEmptyTensor();
353+ ge::graphStatus CheckOutputs();
354+ ge::graphStatus GetEmptyTensorWorkspaceSize();
355+ 
356+ // CheckInputShape使用的子函数
357+ ge::graphStatus CheckInputX();
358+ ge::graphStatus CheckInputExpertIdx();
359+ ge::graphStatus CheckInputScale();
360+ ge::graphStatus CheckStaticQuantScale();
361+ struct ScaleShapeCheckInfo {
362+ int64_t rank = -1;
363+ int64_t dim0 = -1;
364+ int64_t dim1 = -1;
365+ int64_t dim2 = -1;
366+ };
367+ ScaleShapeCheckInfo GetExpectedInputScaleShape() const;
368+ ge::graphStatus CheckInputScaleShape(const ScaleShapeCheckInfo &expected);
369+ ge::graphStatus CheckInputScaleDtype();
370+ ge::graphStatus CheckInputOffset();
371+ ge::graphStatus CheckInputTopkWeight();
372+ ge::graphStatus CheckTopkWeightConsistency();
373+ // CheckOutShape使用的子函数
374+ ge::graphStatus CheckOutputExpandedX();
375+ ge::graphStatus CheckOutputExpandedRowIdx();
376+ ge::graphStatus CheckOutputExpertTokensCountOrCumsum();
377+ ge::graphStatus CheckOutputExpandedScale();
378+ ge::graphStatus CheckOutputExpandedTopkWeight();
379+ ge::graphStatus ValidateExpandedXShapeDropPad();
380+ ge::graphStatus ValidateExpandedXShapeDropless();
381+ ge::graphStatus ValidateExpandedXDtype();
382+ void CalculateExpectedScaleShape(int64_t &expectedRank, int64_t &expectedDim0, int64_t &expectedDim1,
383+ int64_t &expectedDim2);
384+ ge::graphStatus ValidateScaleShape(int64_t expectedRank, int64_t expectedDim0, int64_t expectedDim1,
385+ int64_t expectedDim2);
386+ 
387+ // 各阶段TilingData计算函数
388+ MultipleParams GetMultipleParams();
389+ PerLoopParams GetPerLoopParams(MultipleParams &multipleParams, int64_t perCoreIndicesElements);
390+ void AlignInt4DynamicQuantPerLoopCols(PerLoopParams &perLoopParams) const;
391+ void SetPerLoopParams4NoQuantDropPad(const MultipleParams &multipleParams, PerLoopParams &perLoopParams,
392+ const int64_t perCoreIndicesElements);
393+ int64_t GetXBufferNum(const int additionalBufferNum);
394+ void SetPerLoopParams4NoQuantDropLess(PerLoopParams &perLoopParams,
395+ const int64_t perCoreIndicesElements);
396+ void Tiling4GatherOutCompute();
397+ void Tiling4GatherOutMxFP8NoQuantCompute();
398+ void Tiling4GatherOutMxQuant();
399+ void Tiling4GatherOutFP8Quant();
400+ void Tiling4SortOutCompute();
401+ void Tiling4VMSMiddleCompute();
402+ void Tiling4VBSCompute();
403+ void Tiling4ExpertTokensCountCompute();
404+ void Tiling4VBSOneCoreCompute(MoeV3Arch35VBSComputeTilingData *vbsTiling);
405+ void Tiling4VBSMultiCoreCompute(MoeV3Arch35VBSComputeTilingData *vbsTiling);
406+ int64_t CalcMaxRowIdxPerLoopMxQuant(int64_t perLoopCols);
407+ int64_t CalcMaxRowIdxPerLoopFP8Quant(int64_t perLoopCols);
408+ int64_t CalcMaxRowIdxPerLoopFP8GroupQuant(int64_t perLoopCols);
409+ bool IsFullLoad();
410+ bool IsSupportGatherCopyKernels() const;
411+ void ComputeUseGatherCopy();
412+ void Tiling4TopkWeightOut();
413+ void SetIndicesLoopParams4GatherOut(int64_t perLoopMaxIndicesElements, int64_t perCoreIndicesElements,
414+ int64_t lastCoreIndicesElements);
415+ void SetLastCoreIndicesTiling(MoeV3Arch35GatherOutComputeTilingData *gatherOutTiling,
416+ int64_t lastCoreIndicesElements, int64_t perLoopMaxIndicesElements);
417+ 
418+ // DropPad模式Tiling计算函数
419+ void SetCoreSplitParams4SrcToDstDropPad(int64_t &needCoreNum, int64_t &perCoreRows, int64_t &lastCoreRows);
420+ void SetLoopParams4SrcToDstDropPad(int64_t perCoreRows, int64_t lastCoreRows);
421+ void Tiling4SrcToDstDropPadCompute();
422+ void Tiling4GatherOutDropPadCompute();
423+ bool UseCompactGatherOutDropPad(int64_t outputRows) const;
424+ void SetGatherOutDropPadCoreSplitParams(int64_t &needCoreNum, int64_t &perCoreIndicesElements,
425+ int64_t &lastCoreIndicesElements);
426+ void SetGatherOutDropPadLoopParams(int64_t perCoreIndicesElements, int64_t lastCoreIndicesElements);
427+ 
428+ // LogTilingData
429+ void LogBaseTilingData();
430+ void LogVbsTilingData();
431+ void LogVmsMiddleTilingData();
432+ void LogSortOutTilingData();
433+ void LogExpertTokensCountTilingData();
434+ void LogGatherOutTilingData();
435+ 
436+ bool IsMXFPXNoQuantCase(int64_t quantMode, ge::DataType xDtype) const
437+ {
438+ return quantMode == QUANT_MODE_UNQUANT && (xDtype == ge::DataType::DT_FLOAT8_E5M2 ||
439+ xDtype == ge::DataType::DT_FLOAT8_E4M3FN || xDtype == ge::DataType::DT_FLOAT4_E2M1);
440+ }
441+ 
442+ bool IsSupportFullloadQuantMode() const
443+ {
444+ return (quantMode_ == QUANT_MODE_UNQUANT && !IsMXFPXNoQuantCase(quantMode_, xDtype_)) ||
445+ (quantMode_ == QUANT_MODE_STATIC) || IsAnyDynamicQuantCase();
446+ }
447+ 
448+ bool IsMXFP8NoQuantCase(int64_t quantMode, ge::DataType xDtype) const
449+ {
450+ return quantMode == QUANT_MODE_UNQUANT &&
451+ (xDtype == ge::DataType::DT_FLOAT8_E5M2 || xDtype == ge::DataType::DT_FLOAT8_E4M3FN);
452+ }
453+ 
454+ bool IsInt8DynamicQuantCase() const
455+ {
456+ return quantMode_ == QUANT_MODE_DYNAMIC;
457+ }
458+ 
459+ bool IsInt4DynamicQuantCase() const
460+ {
461+ return quantMode_ == QUANT_MODE_INT4_DYNAMIC;
462+ }
463+ 
464+ bool IsAnyDynamicQuantCase() const
465+ {
466+ return IsInt8DynamicQuantCase() || IsInt4DynamicQuantCase();
467+ }
468+ 
469+ bool NeedQuantTempWorkspace() const
470+ {
471+ return (quantMode_ >= QUANT_MODE_DYNAMIC && quantMode_ != QUANT_MODE_HIF8_CAST &&
472+ quantMode_ != QUANT_MODE_HIF8_PERTENSOR && quantMode_ != QUANT_MODE_MXFP8_E5M2 &&
473+ quantMode_ != QUANT_MODE_MXFP8_E4M3FN && quantMode_ != QUANT_MODE_MXFP8_ROUNDSCALE_AMAX_E5M2 &&
474+ quantMode_ != QUANT_MODE_MXFP8_ROUNDSCALE_AMAX_E4M3FN && quantMode_ != QUANT_MODE_FP8_GROUP_E5M2 &&
475+ quantMode_ != QUANT_MODE_FP8_GROUP_E4M3FN && quantMode_ != QUANT_MODE_FP8_GROUP_AMAX_E5M2 &&
476+ quantMode_ != QUANT_MODE_FP8_GROUP_AMAX_E4M3FN);
477+ }
478+};
479+ 
480+} // namespace optiling
481+ 
482+#endif // MOE_INIT_ROUTING_V3_TILING_ARCH35_H
@@ -1,12 +1,12 @@
1/**1/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.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 of3+ * 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").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.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,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.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.8+ * See LICENSE in the root of the software repository for the full text of the License.
9- */9+ */
10 10 
11#include <tuple>11#include <tuple>
12#include "moe_init_routing_v3.h"12#include "moe_init_routing_v3.h"
@@ -24,28 +24,52 @@ using namespace op;
24namespace l0op {24namespace l0op {
25OP_TYPE_REGISTER(MoeInitRoutingV3);25OP_TYPE_REGISTER(MoeInitRoutingV3);
26 26 
27-std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*> MoeInitRoutingV3(const aclTensor *x, const aclTensor *expertIdx, const aclTensor *scale, 27+std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*>
28- const aclTensor *offset, int64_t activeNum, int64_t expertCapacity,28+MoeInitRoutingV3(const aclTensor *x, const aclTensor *expertIdx,
29- int64_t expertNum, int64_t dropPadMode, int64_t expertTokensNumType, 29+ const aclTensor *scale, const aclTensor *offset,
30- bool expertTokensNumFlag, int64_t quantMode, const aclIntArray *activeExpertRange,30+ int64_t activeNum,
31- int64_t rowIdxType, const aclTensor *expandedX, const aclTensor *expandedRowIdx, 31+ int64_t expertCapacity, int64_t expertNum, int64_t dropPadMode,
32- const aclTensor *expertTokensCountOrCumsum, const aclTensor *expandedScale, aclOpExecutor *executor)32+ int64_t expertTokensNumType, bool expertTokensNumFlag,
33+ int64_t quantMode, const aclIntArray *activeExpertRange,
34+ int64_t rowIdxType, const aclTensor *expandedX,
35+ const aclTensor *expandedRowIdx,
36+ const aclTensor *expertTokensCountOrCumsum,
37+ const aclTensor *expandedScale,
38+ aclOpExecutor *executor)
33{39{
34- L0_DFX(MoeInitRoutingV3, x, expertIdx, scale, offset, activeNum, expertCapacity, expertNum, dropPadMode, expertTokensNumType, expertTokensNumFlag,40+ L0_DFX(MoeInitRoutingV3, x, expertIdx, scale, offset,
35- quantMode, activeExpertRange, rowIdxType, expandedX, expandedRowIdx, expertTokensCountOrCumsum, expandedScale);41+ activeNum, expertCapacity, expertNum, dropPadMode,
36- 42+ expertTokensNumType, expertTokensNumFlag, quantMode,
37- auto expandedXOut = executor->AllocTensor(expandedX->GetViewShape(), expandedX->GetDataType(), Format::FORMAT_ND); 43+ activeExpertRange, rowIdxType, expandedX, expandedRowIdx,
38- auto expandedRowIdxOut = executor->AllocTensor(expandedRowIdx->GetViewShape(), expandedRowIdx->GetDataType(), Format::FORMAT_ND);44+ expertTokensCountOrCumsum, expandedScale);
39- auto expertTokensCountOrCumsumOut = executor->AllocTensor(expertTokensCountOrCumsum->GetViewShape(), expertTokensCountOrCumsum->GetDataType(), Format::FORMAT_ND);45+ 
40- auto expandedScaleOut = executor->AllocTensor(expandedScale->GetViewShape(), expandedScale->GetDataType(), Format::FORMAT_ND);46+ auto expandedXOut = executor->AllocTensor(expandedX->GetViewShape(), expandedX->GetDataType(),
41- if (expandedXOut == nullptr || expandedRowIdxOut == nullptr || expertTokensCountOrCumsumOut == nullptr || expandedScaleOut == nullptr) {47+ Format::FORMAT_ND);
42- OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "alloc expandedXOut or expandedRowIdxOut or expertTokensCountOrCumsumOut or expandedScaleOut tensor failed.");48+ auto expandedRowIdxOut = executor->AllocTensor(expandedRowIdx->GetViewShape(), expandedRowIdx->GetDataType(),
43- return std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*>(nullptr, nullptr, nullptr, nullptr);49+ Format::FORMAT_ND);
50+ auto expertTokensCountOrCumsumOut = executor->AllocTensor(expertTokensCountOrCumsum->GetViewShape(),
51+ expertTokensCountOrCumsum->GetDataType(),
52+ Format::FORMAT_ND);
53+ auto expandedScaleOut = executor->AllocTensor(expandedScale->GetViewShape(), expandedScale->GetDataType(),
54+ Format::FORMAT_ND);
55+ if (expandedXOut == nullptr || expandedRowIdxOut == nullptr ||
56+ expertTokensCountOrCumsumOut == nullptr || expandedScaleOut == nullptr) {
57+ OP_LOGE(ACLNN_ERR_INNER_NULLPTR,
58+ "alloc expandedXOut or expandedRowIdxOut or "
59+ "expertTokensCountOrCumsumOut or expandedScaleOut tensor failed.");
60+ return std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*>(
61+ nullptr, nullptr, nullptr, nullptr);
44 }62 }
45 63 
46 ADD_TO_LAUNCHER_LIST_AICORE(64 ADD_TO_LAUNCHER_LIST_AICORE(
47- MoeInitRoutingV3, OP_INPUT(x, expertIdx, scale, offset), OP_OUTPUT(expandedXOut, expandedRowIdxOut, expertTokensCountOrCumsumOut, expandedScaleOut), OP_ATTR(activeNum, expertCapacity, expertNum, dropPadMode, expertTokensNumType, expertTokensNumFlag, quantMode, activeExpertRange, rowIdxType));65+ MoeInitRoutingV3,
48- return std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*>(expandedXOut, expandedRowIdxOut, expertTokensCountOrCumsumOut, expandedScaleOut); //OP_OUTPUT66+ OP_INPUT(x, expertIdx, scale, offset),
67+ OP_OUTPUT(expandedXOut, expandedRowIdxOut, expertTokensCountOrCumsumOut, expandedScaleOut),
68+ OP_ATTR(activeNum, expertCapacity, expertNum, dropPadMode, expertTokensNumType, expertTokensNumFlag,
69+ quantMode, activeExpertRange, rowIdxType));
70+ return std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*>(
71+ expandedXOut, expandedRowIdxOut, expertTokensCountOrCumsumOut,
72+ expandedScaleOut);
49}73}
50 74 
51} // namespace l0op75} // namespace l0op
@@ -15,11 +15,12 @@
15#include "opdev/op_executor.h"15#include "opdev/op_executor.h"
16 16 
17namespace l0op {17namespace l0op {
18-std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*> MoeInitRoutingV3(const aclTensor *x, const aclTensor *expertIdx, const aclTensor *scale, 18+std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*>
19- const aclTensor *offset, int64_t activeNum, int64_t expertCapacity,19+MoeInitRoutingV3(const aclTensor *x, const aclTensor *expertIdx, const aclTensor *scale, const aclTensor *offset,
20- int64_t expertNum, int64_t dropPadMode, int64_t expertTokensNumType, 20+ int64_t activeNum, int64_t expertCapacity, int64_t expertNum, int64_t dropPadMode,
21- bool expertTokensNumFlag, int64_t quantMode, const aclIntArray *activeExpertRange,21+ int64_t expertTokensNumType, bool expertTokensNumFlag, int64_t quantMode,
22- int64_t rowIdxType, const aclTensor *expandedX, const aclTensor *expandedRowIdx, 22+ const aclIntArray *activeExpertRange, int64_t rowIdxType, const aclTensor *expandedX,
23- const aclTensor *expertTokensCountOrCumsum, const aclTensor *expandedScale, aclOpExecutor *executor); 23+ const aclTensor *expandedRowIdx, const aclTensor *expertTokensCountOrCumsum,
24+ const aclTensor *expandedScale, aclOpExecutor *executor);
24} // namespace l0op25} // namespace l0op
25#endif // OP_API_INC_LEVEL0_MOE_INIT_ROUTING_V3_H26#endif // OP_API_INC_LEVEL0_MOE_INIT_ROUTING_V3_H
@@ -111,6 +111,8 @@ struct MoeInitRoutingV3Arch35TilingData {
111 int64_t dropPadMode{0};111 int64_t dropPadMode{0};
112 int64_t smoothType{0}; // 未使用112 int64_t smoothType{0}; // 未使用
113 int64_t expertCapacity{0}; // 新增:DropPad模式下的expert capacity113 int64_t expertCapacity{0}; // 新增:DropPad模式下的expert capacity
114+ int64_t isInputTopkWeight{0}; // 新增:topk_weight输入是否提供
115+ int64_t topkWeightOutPerCorePerLoopElements{0}; // 新增:TopkWeightOut每轮处理的索引元素数
114 MoeV3Arch35VBSComputeTilingData vbsComputeParamsOp;116 MoeV3Arch35VBSComputeTilingData vbsComputeParamsOp;
115 MoeV3Arch35VMSMiddleComputeTilingData vmsMiddleComputeParamsOp;117 MoeV3Arch35VMSMiddleComputeTilingData vmsMiddleComputeParamsOp;
116 MoeV3Arch35SortOutComputeTilingData sortOutComputeParamsOp;118 MoeV3Arch35SortOutComputeTilingData sortOutComputeParamsOp;
@@ -75,12 +75,14 @@ class MoeV3FullLoadBase {
75public:75public:
76 __aicore__ inline MoeV3FullLoadBase(){};76 __aicore__ inline MoeV3FullLoadBase(){};
77 __aicore__ inline void Init(GM_ADDR expertIdx, GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum,77 __aicore__ inline void Init(GM_ADDR expertIdx, GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum,
78- GM_ADDR workspace, const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);78+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight, GM_ADDR workspace,
79+ const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);
79 80 
80protected:81protected:
81 __aicore__ inline void CopyIn();82 __aicore__ inline void CopyIn();
82 __aicore__ inline void InitGlobalBuffers(GM_ADDR expertIdx, GM_ADDR expandedRowIdx,83 __aicore__ inline void InitGlobalBuffers(GM_ADDR expertIdx, GM_ADDR expandedRowIdx,
83- GM_ADDR expertTokensCountOrCumsum, GM_ADDR workspace);84+ GM_ADDR expertTokensCountOrCumsum, GM_ADDR topkWeight,
85+ GM_ADDR expandedTopkWeight, GM_ADDR workspace);
84 __aicore__ inline void InitQueBuffers();86 __aicore__ inline void InitQueBuffers();
85 __aicore__ inline void SortCompute();87 __aicore__ inline void SortCompute();
86 __aicore__ inline void FilterExpertIdx(LocalTensor<int32_t> &expertIdxLocal,88 __aicore__ inline void FilterExpertIdx(LocalTensor<int32_t> &expertIdxLocal,
@@ -91,6 +93,9 @@ protected:
91 __aicore__ inline void ComputeExpertTokenCount();93 __aicore__ inline void ComputeExpertTokenCount();
92 __aicore__ inline void CopyExpertCountToOutput();94 __aicore__ inline void CopyExpertCountToOutput();
93 __aicore__ inline void FreeLocalTensor();95 __aicore__ inline void FreeLocalTensor();
96+ __aicore__ inline void TopkWeightScatterOut();
97+ __aicore__ inline void TopkWeightGatherOut();
98+ __aicore__ inline void TopkWeightZeroOut();
94 99 
95protected:100protected:
96 int64_t sortNum_;101 int64_t sortNum_;
@@ -125,6 +130,7 @@ protected:
125 int64_t endXRow_;130 int64_t endXRow_;
126 int64_t isInputScale_ = 0;131 int64_t isInputScale_ = 0;
127 int64_t epFullload_ = 0;132 int64_t epFullload_ = 0;
133+ int64_t isInputTopkWeight_ = 0;
128 134 
129 static constexpr int64_t DST_BLK_STRIDE = 1;135 static constexpr int64_t DST_BLK_STRIDE = 1;
130 static constexpr int64_t DST_REP_STRIDE = 8;136 static constexpr int64_t DST_REP_STRIDE = 8;
@@ -145,13 +151,18 @@ protected:
145 GlobalTensor<int64_t> expertTokensCountOrCumsumGm_;151 GlobalTensor<int64_t> expertTokensCountOrCumsumGm_;
146 GlobalTensor<int32_t> expertTotalCountGm_;152 GlobalTensor<int32_t> expertTotalCountGm_;
147 153 
154+ GlobalTensor<float> topkWeightGm_;
155+ GlobalTensor<float> expandedTopkWeightGm_;
156+ TBuf<TPosition::VECCALC> topkWeightBuf_;
157+ 
148 TPipe *pipe_;158 TPipe *pipe_;
149};159};
150 160 
151template <typename T>161template <typename T>
152__aicore__ inline void MoeV3FullLoadBase<T>::Init(GM_ADDR expertIdx, GM_ADDR expandedRowIdx,162__aicore__ inline void MoeV3FullLoadBase<T>::Init(GM_ADDR expertIdx, GM_ADDR expandedRowIdx,
153- GM_ADDR expertTokensCountOrCumsum, GM_ADDR workspace,163+ GM_ADDR expertTokensCountOrCumsum,
154- const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe)164+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight, GM_ADDR workspace,
165+ const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe)
155{166{
156 this->gatherOutTilingData_ = &(tilingData->gatherOutComputeParamsOp);167 this->gatherOutTilingData_ = &(tilingData->gatherOutComputeParamsOp);
157 this->blockIdx_ = GetBlockIdx();168 this->blockIdx_ = GetBlockIdx();
@@ -184,6 +195,7 @@ __aicore__ inline void MoeV3FullLoadBase<T>::Init(GM_ADDR expertIdx, GM_ADDR exp
184 this->actualExpertNum_ = tilingData->actualExpertNum;195 this->actualExpertNum_ = tilingData->actualExpertNum;
185 this->epFullload_ = tilingData->epFullload;196 this->epFullload_ = tilingData->epFullload;
186 this->pipe_ = tPipe;197 this->pipe_ = tPipe;
198+ isInputTopkWeight_ = tilingData->isInputTopkWeight;
187 199 
188 if (expertTokensNumType_ == EXERPT_TOKENS_KEY_VALUE) {200 if (expertTokensNumType_ == EXERPT_TOKENS_KEY_VALUE) {
189 expertCountElements_ = ((actualExpertNum_ + 1) < expertNum_) ?201 expertCountElements_ = ((actualExpertNum_ + 1) < expertNum_) ?
@@ -199,13 +211,14 @@ __aicore__ inline void MoeV3FullLoadBase<T>::Init(GM_ADDR expertIdx, GM_ADDR exp
199 startXRow_ = curIndexStart_ / this->k_;211 startXRow_ = curIndexStart_ / this->k_;
200 endXRow_ = (curIndexStart_ + this->coreIndicesElements_ - 1) / this->k_;212 endXRow_ = (curIndexStart_ + this->coreIndicesElements_ - 1) / this->k_;
201 213 
202- InitGlobalBuffers(expertIdx, expandedRowIdx, expertTokensCountOrCumsum, workspace);214+ InitGlobalBuffers(expertIdx, expandedRowIdx, expertTokensCountOrCumsum, topkWeight, expandedTopkWeight, workspace);
203 InitQueBuffers();215 InitQueBuffers();
204}216}
205 217 
206template <typename T>218template <typename T>
207__aicore__ inline void MoeV3FullLoadBase<T>::InitGlobalBuffers(GM_ADDR expertIdx, GM_ADDR expandedRowIdx,219__aicore__ inline void MoeV3FullLoadBase<T>::InitGlobalBuffers(GM_ADDR expertIdx, GM_ADDR expandedRowIdx,
208- GM_ADDR expertTokensCountOrCumsum, GM_ADDR workspace)220+ GM_ADDR expertTokensCountOrCumsum, GM_ADDR topkWeight,
221+ GM_ADDR expandedTopkWeight, GM_ADDR workspace)
209{222{
210 expertIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expertIdx, this->tileLength_);223 expertIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expertIdx, this->tileLength_);
211 expandedRowIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expandedRowIdx, this->tileLength_);224 expandedRowIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expandedRowIdx, this->tileLength_);
@@ -216,6 +229,12 @@ __aicore__ inline void MoeV3FullLoadBase<T>::InitGlobalBuffers(GM_ADDR expertIdx
216 229 
217 expertTotalCountGm_.SetGlobalBuffer((__gm__ int32_t *)workspace + Align(this->totalLength_, sizeof(int32_t)) * 2 +230 expertTotalCountGm_.SetGlobalBuffer((__gm__ int32_t *)workspace + Align(this->totalLength_, sizeof(int32_t)) * 2 +
218 Align(this->actualExpertNum_, sizeof(int32_t)), 1);231 Align(this->actualExpertNum_, sizeof(int32_t)), 1);
232+ 
233+ if (isInputTopkWeight_ == 1) {
234+ topkWeightGm_.SetGlobalBuffer((__gm__ float *)topkWeight, totalLength_);
235+ expandedTopkWeightGm_.SetGlobalBuffer((__gm__ float *)expandedTopkWeight,
236+ (dropPadMode_ == DROP_PAD_MODE) ? outputRows_ : totalLength_);
237+ }
219}238}
220 239 
221template <typename T>240template <typename T>
@@ -230,6 +249,10 @@ __aicore__ inline void MoeV3FullLoadBase<T>::InitQueBuffers()
230 pipe_->InitBuffer(tempBuffer_, buffSize * kvFactor_);249 pipe_->InitBuffer(tempBuffer_, buffSize * kvFactor_);
231 pipe_->InitBuffer(sortedBuffer_, buffSize * kvFactor_);250 pipe_->InitBuffer(sortedBuffer_, buffSize * kvFactor_);
232 pipe_->InitBuffer(expertCountBuf_, AlignBytes(actualExpertNum_, sizeof(int32_t)));251 pipe_->InitBuffer(expertCountBuf_, AlignBytes(actualExpertNum_, sizeof(int32_t)));
252+ 
253+ if (isInputTopkWeight_ == 1) {
254+ pipe_->InitBuffer(topkWeightBuf_, AlignBytes(1, sizeof(float)));
255+ }
233}256}
234 257 
235template <typename T>258template <typename T>
@@ -544,5 +567,85 @@ __aicore__ inline void MoeV3FullLoadBase<T>::FreeLocalTensor()
544 expandedRowIdxQueue_.FreeTensor(expandedRowIdx);567 expandedRowIdxQueue_.FreeTensor(expandedRowIdx);
545}568}
546 569 
570+template <typename T>
571+__aicore__ inline void MoeV3FullLoadBase<T>::TopkWeightScatterOut()
572+{
573+ LocalTensor<int32_t> sortedRowIdx = sortedRowIdxQueue_.DeQue<int32_t>();
574+ LocalTensor<int32_t> sortedExpertIdx = sortedExpertIdxQueue_.DeQue<int32_t>();
575+ SetWaitFlag<HardEvent::MTE2_S>(HardEvent::MTE2_S);
576+ 
577+ DataCopyExtParams copyParams{1, static_cast<uint32_t>(sizeof(float)), 0, 0, 0};
578+ DataCopyPadExtParams<float> padParams{false, 0, 0, 0};
579+ LocalTensor<float> topkWeightLocal = topkWeightBuf_.Get<float>();
580+ 
581+ int64_t startRowIdx = blockIdx_ * perCoreIndicesElements_;
582+ int64_t endRowIdx = Min(startRowIdx + coreIndicesElements_, activeNum_);
583+ 
584+ for (int64_t i = startRowIdx; i < endRowIdx; i++) {
585+ int32_t curExpertId = sortedExpertIdx.GetValue(i);
586+ if (curExpertId < expertStart_) {
587+ continue;
588+ }
589+ if (curExpertId >= expertEnd_) {
590+ break;
591+ }
592+ int64_t srcIdx = sortedRowIdx.GetValue(i);
593+ if (srcIdx >= 0 && srcIdx < totalLength_) {
594+ SetWaitFlag<HardEvent::MTE3_MTE2>(HardEvent::MTE3_MTE2);
595+ DataCopyPad(topkWeightLocal, topkWeightGm_[srcIdx], copyParams, padParams);
596+ SetWaitFlag<HardEvent::MTE2_MTE3>(HardEvent::MTE2_MTE3);
597+ DataCopyPad(expandedTopkWeightGm_[i], topkWeightLocal, copyParams);
598+ }
599+ }
600+ 
601+ sortedRowIdxQueue_.EnQue<int32_t>(sortedRowIdx);
602+ sortedExpertIdxQueue_.EnQue<int32_t>(sortedExpertIdx);
603+}
604+ 
605+template <typename T>
606+__aicore__ inline void MoeV3FullLoadBase<T>::TopkWeightGatherOut()
607+{
608+ LocalTensor<int32_t> expandedRowIdx = expandedRowIdxQueue_.DeQue<int32_t>();
609+ SetWaitFlag<HardEvent::V_S>(HardEvent::V_S);
610+ 
611+ DataCopyExtParams copyParams{1, static_cast<uint32_t>(sizeof(float)), 0, 0, 0};
612+ DataCopyPadExtParams<float> padParams{false, 0, 0, 0};
613+ LocalTensor<float> topkWeightLocal = topkWeightBuf_.Get<float>();
614+ 
615+ int64_t startRowIdx = blockIdx_ * perCoreIndicesElements_;
616+ int64_t endRowIdx = startRowIdx + coreIndicesElements_;
617+ int64_t outputRows = (dropPadMode_ == DROP_PAD_MODE)
618+ ? outputRows_ : Min(actualExpertIdxNum_, activeNum_);
619+ 
620+ for (int64_t curIndex = startRowIdx; curIndex < endRowIdx; curIndex++) {
621+ int32_t outIndex = expandedRowIdx.GetValue(curIndex);
622+ if (outIndex >= 0 && outIndex < outputRows) {
623+ SetWaitFlag<HardEvent::MTE3_MTE2>(HardEvent::MTE3_MTE2);
624+ DataCopyPad(topkWeightLocal, topkWeightGm_[curIndex], copyParams, padParams);
625+ SetWaitFlag<HardEvent::MTE2_MTE3>(HardEvent::MTE2_MTE3);
626+ DataCopyPad(expandedTopkWeightGm_[outIndex], topkWeightLocal, copyParams);
627+ }
628+ }
629+ 
630+ expandedRowIdxQueue_.EnQue<int32_t>(expandedRowIdx);
631+}
632+ 
633+template <typename T>
634+__aicore__ inline void MoeV3FullLoadBase<T>::TopkWeightZeroOut()
635+{
636+ int64_t perCoreRows = Ceil(outputRows_, needCoreNum_);
637+ int64_t startRow = blockIdx_ * perCoreRows;
638+ int64_t endRow = Min(startRow + perCoreRows, outputRows_);
639+ if (startRow >= endRow) {
640+ return;
641+ }
642+ int64_t rowCount = endRow - startRow;
643+ GlobalTensor<float> topkWeightZeroGm;
644+ topkWeightZeroGm.SetGlobalBuffer((__gm__ float *)expandedTopkWeightGm_.GetPhyAddr() + startRow, rowCount);
645+ SetWaitFlag<HardEvent::S_MTE3>(HardEvent::S_MTE3);
646+ InitGlobalMemory(topkWeightZeroGm, rowCount, 0.0f);
647+ SetWaitFlag<HardEvent::MTE3_S>(HardEvent::MTE3_S);
648+}
649+ 
547} // namespace MoeInitRoutingV3650} // namespace MoeInitRoutingV3
548#endif // MOE_V3_FULL_LOAD_BASE_H651#endif // MOE_V3_FULL_LOAD_BASE_H
@@ -31,7 +31,8 @@ class MoeV3FullLoadDynamicQuant : public MoeV3FullLoadBase<T> {
31public:31public:
32 __aicore__ inline MoeV3FullLoadDynamicQuant(){};32 __aicore__ inline MoeV3FullLoadDynamicQuant(){};
33 __aicore__ inline void Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX, GM_ADDR expandedRowIdx,33 __aicore__ inline void Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX, GM_ADDR expandedRowIdx,
34- GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale, GM_ADDR workspace,34+ GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale,
35+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight, GM_ADDR workspace,
35 const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);36 const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);
36 __aicore__ inline void Process();37 __aicore__ inline void Process();
37 38 
@@ -75,11 +76,13 @@ template <typename T, typename QuantT>
75__aicore__ inline void76__aicore__ inline void
76MoeV3FullLoadDynamicQuant<T, QuantT>::Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX,77MoeV3FullLoadDynamicQuant<T, QuantT>::Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX,
77 GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum,78 GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum,
78- GM_ADDR expandedScale, GM_ADDR workspace,79+ GM_ADDR expandedScale,
80+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight, GM_ADDR workspace,
79 const MoeInitRoutingV3Arch35TilingData *tilingData,81 const MoeInitRoutingV3Arch35TilingData *tilingData,
80 TPipe *tPipe)82 TPipe *tPipe)
81{83{
82- MoeV3FullLoadBase<T>::Init(expertIdx, expandedRowIdx, expertTokensCountOrCumsum, workspace, tilingData, tPipe);84+ MoeV3FullLoadBase<T>::Init(expertIdx, expandedRowIdx, expertTokensCountOrCumsum,
85+ topkWeight, expandedTopkWeight, workspace, tilingData, tPipe);
83 86 
84 colsAlign_ = Align(this->cols_, sizeof(T));87 colsAlign_ = Align(this->cols_, sizeof(T));
85 if constexpr (IsSameType<QuantT, int4b_t>::value) {88 if constexpr (IsSameType<QuantT, int4b_t>::value) {
@@ -432,8 +435,14 @@ __aicore__ inline void MoeV3FullLoadDynamicQuant<T, QuantT>::Process()
432 }435 }
433 436 
434 if (this->epFullload_ || this->isInputScale_) {437 if (this->epFullload_ || this->isInputScale_) {
438+ if (this->isInputTopkWeight_) {
439+ this->TopkWeightScatterOut();
440+ }
435 ScatterOutXDynamicQuant();441 ScatterOutXDynamicQuant();
436 } else {442 } else {
443+ if (this->isInputTopkWeight_) {
444+ this->TopkWeightGatherOut();
445+ }
437 GatherOutXDynamicQuant();446 GatherOutXDynamicQuant();
438 }447 }
439 448 
@@ -30,7 +30,8 @@ class MoeV3FullLoadStaticQuant : public MoeV3FullLoadBase<T> {
30public:30public:
31 __aicore__ inline MoeV3FullLoadStaticQuant(){};31 __aicore__ inline MoeV3FullLoadStaticQuant(){};
32 __aicore__ inline void Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX, GM_ADDR expandedRowIdx,32 __aicore__ inline void Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX, GM_ADDR expandedRowIdx,
33- GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale, GM_ADDR workspace,33+ GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale,
34+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight, GM_ADDR workspace,
34 GM_ADDR offset, const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);35 GM_ADDR offset, const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);
35 __aicore__ inline void Process();36 __aicore__ inline void Process();
36 37 
@@ -63,11 +64,14 @@ private:
63template <typename T>64template <typename T>
64__aicore__ inline void MoeV3FullLoadStaticQuant<T>::Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX,65__aicore__ inline void MoeV3FullLoadStaticQuant<T>::Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX,
65 GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum,66 GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum,
66- GM_ADDR expandedScale, GM_ADDR workspace, GM_ADDR offset,67+ GM_ADDR expandedScale,
68+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight,
69+ GM_ADDR workspace, GM_ADDR offset,
67 const MoeInitRoutingV3Arch35TilingData *tilingData,70 const MoeInitRoutingV3Arch35TilingData *tilingData,
68 TPipe *tPipe)71 TPipe *tPipe)
69{72{
70- MoeV3FullLoadBase<T>::Init(expertIdx, expandedRowIdx, expertTokensCountOrCumsum, workspace, tilingData, tPipe);73+ MoeV3FullLoadBase<T>::Init(expertIdx, expandedRowIdx, expertTokensCountOrCumsum,
74+ topkWeight, expandedTopkWeight, workspace, tilingData, tPipe);
71 75 
72 colsAlign_ = Align(this->cols_, sizeof(T));76 colsAlign_ = Align(this->cols_, sizeof(T));
73 inFactor_ = Align(this->cols_, sizeof(int8_t));77 inFactor_ = Align(this->cols_, sizeof(int8_t));
@@ -235,8 +239,14 @@ __aicore__ inline void MoeV3FullLoadStaticQuant<T>::Process()
235 }239 }
236 240 
237 if (this->epFullload_) {241 if (this->epFullload_) {
242+ if (this->isInputTopkWeight_) {
243+ this->TopkWeightScatterOut();
244+ }
238 ScatterOutXStaticQuant();245 ScatterOutXStaticQuant();
239 } else {246 } else {
247+ if (this->isInputTopkWeight_) {
248+ this->TopkWeightGatherOut();
249+ }
240 GatherOutXStaticQuant();250 GatherOutXStaticQuant();
241 }251 }
242 252 
@@ -25,7 +25,8 @@ class MoeV3FullLoadUnquantized : public MoeV3FullLoadBase<T> {
25public:25public:
26 __aicore__ inline MoeV3FullLoadUnquantized(){};26 __aicore__ inline MoeV3FullLoadUnquantized(){};
27 __aicore__ inline void Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX, GM_ADDR expandedRowIdx,27 __aicore__ inline void Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX, GM_ADDR expandedRowIdx,
28- GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale, GM_ADDR workspace,28+ GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale,
29+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight, GM_ADDR workspace,
29 const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);30 const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);
30 __aicore__ inline void Process();31 __aicore__ inline void Process();
31 32 
@@ -56,9 +57,11 @@ template <typename T>
56__aicore__ inline void57__aicore__ inline void
57MoeV3FullLoadUnquantized<T>::Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX,58MoeV3FullLoadUnquantized<T>::Init(GM_ADDR x, GM_ADDR expertIdx, GM_ADDR scale, GM_ADDR expandedX,
58 GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale,59 GM_ADDR expandedRowIdx, GM_ADDR expertTokensCountOrCumsum, GM_ADDR expandedScale,
59- GM_ADDR workspace, const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe)60+ GM_ADDR topkWeight, GM_ADDR expandedTopkWeight, GM_ADDR workspace,
61+ const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe)
60{62{
61- MoeV3FullLoadBase<T>::Init(expertIdx, expandedRowIdx, expertTokensCountOrCumsum, workspace, tilingData, tPipe);63+ MoeV3FullLoadBase<T>::Init(expertIdx, expandedRowIdx, expertTokensCountOrCumsum,
64+ topkWeight, expandedTopkWeight, workspace, tilingData, tPipe);
62 65 
63 if constexpr (IsSameType<T, hifloat8_t>::value) {66 if constexpr (IsSameType<T, hifloat8_t>::value) {
64 xUint8tGm_.SetGlobalBuffer((__gm__ uint8_t *)x);67 xUint8tGm_.SetGlobalBuffer((__gm__ uint8_t *)x);
@@ -113,11 +116,17 @@ __aicore__ inline void MoeV3FullLoadUnquantized<T>::Process()
113 }116 }
114 117 
115 if (this->epFullload_) {118 if (this->epFullload_) {
119+ if (this->isInputTopkWeight_) {
120+ this->TopkWeightScatterOut();
121+ }
116 this->ScatterOutX();122 this->ScatterOutX();
117 if (this->isInputScale_) {123 if (this->isInputScale_) {
118 this->ScatterOutScale();124 this->ScatterOutScale();
119 }125 }
120 } else {126 } else {
127+ if (this->isInputTopkWeight_) {
128+ this->TopkWeightGatherOut();
129+ }
121 this->GatherOutX();130 this->GatherOutX();
122 if (this->isInputScale_) {131 if (this->isInputScale_) {
123 this->GatherOutScale();132 this->GatherOutScale();
@@ -148,11 +157,17 @@ __aicore__ inline void MoeV3FullLoadUnquantized<T>::ProcessDropPadMode()
148 if (this->isInputScale_) {157 if (this->isInputScale_) {
149 this->ZeroOutScale();158 this->ZeroOutScale();
150 }159 }
160+ if (this->isInputTopkWeight_) {
161+ this->TopkWeightZeroOut();
162+ }
151 }163 }
152#ifndef __CCE_KT_TEST__164#ifndef __CCE_KT_TEST__
153 AscendC::SyncAll();165 AscendC::SyncAll();
154#endif166#endif
155 if (this->blockIdx_ < this->needCoreNum_) {167 if (this->blockIdx_ < this->needCoreNum_) {
168+ if (this->isInputTopkWeight_) {
169+ this->TopkWeightGatherOut();
170+ }
156 this->GatherOutX();171 this->GatherOutX();
157 if (this->isInputScale_) {172 if (this->isInputScale_) {
158 this->GatherOutScale();173 this->GatherOutScale();
@@ -0,0 +1,234 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file moe_v3_topk_weight_out.h
13+ * \brief TopkWeight rearrangement for non-FullLoad path (arch35/regbase)
14+ */
15+#ifndef MOE_V3_TOPK_WEIGHT_OUT_H
16+#define MOE_V3_TOPK_WEIGHT_OUT_H
17+ 
18+#include "moe_v3_common.h"
19+ 
20+namespace MoeInitRoutingV3 {
21+using namespace AscendC;
22+ 
23+constexpr int32_t ROW_IDX_QUEUE_DEPTH = 2;
24+constexpr int32_t ROW_IDX_BUFFER_NUM = 2;
25+ 
26+class MoeV3TopkWeightOut {
27+public:
28+ __aicore__ inline MoeV3TopkWeightOut() {}
29+ __aicore__ inline void Init(GM_ADDR topkWeight, GM_ADDR expandedRowIdx, GM_ADDR expandedTopkWeight,
30+ GM_ADDR workspace, const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe);
31+ __aicore__ inline void Process();
32+ 
33+private:
34+ TPipe *pipe_;
35+ TQueBind<QuePosition::VECIN, QuePosition::VECOUT, 1> topkWeightCopyInQueue_;
36+ TQue<QuePosition::VECIN, ROW_IDX_QUEUE_DEPTH> rowIdxCopyInQueue_;
37+ 
38+ GlobalTensor<float> topkWeightGm_;
39+ GlobalTensor<float> expandedTopkWeightGm_;
40+ GlobalTensor<int32_t> expandDstToSrcRowGm_;
41+ GlobalTensor<int32_t> expandedRowIdxGm_;
42+ 
43+ int64_t blockIdx_;
44+ int64_t n_;
45+ int64_t k_;
46+ int64_t totalLength_;
47+ int64_t activeNum_;
48+ int64_t expertTotalCount_;
49+ int64_t rowIdxType_;
50+ int64_t dropPadMode_;
51+ int64_t expertNum_;
52+ int64_t expertCapacity_;
53+ int64_t outputRows_;
54+ int64_t needCoreNum_;
55+ int64_t perCoreElements_;
56+ int64_t coreElements_;
57+ int64_t coreNum_;
58+ int64_t perCorePerLoopElements_;
59+ int64_t indicesLoops_;
60+ 
61+ __aicore__ inline void CopyRowIdxIn(int64_t offset, int64_t curLoopElements);
62+ __aicore__ inline void ProcessDropPadGather(int64_t startIdx);
63+ __aicore__ inline void ProcessDroplessScatter(int64_t startIdx);
64+};
65+ 
66+__aicore__ inline void MoeV3TopkWeightOut::Init(GM_ADDR topkWeight, GM_ADDR expandedRowIdx,
67+ GM_ADDR expandedTopkWeight, GM_ADDR workspace,
68+ const MoeInitRoutingV3Arch35TilingData *tilingData, TPipe *tPipe)
69+{
70+ pipe_ = tPipe;
71+ blockIdx_ = GetBlockIdx();
72+ coreNum_ = tilingData->coreNum;
73+ n_ = tilingData->n;
74+ k_ = tilingData->k;
75+ totalLength_ = n_ * k_;
76+ activeNum_ = tilingData->activeNum;
77+ rowIdxType_ = tilingData->rowIdxType;
78+ dropPadMode_ = tilingData->dropPadMode;
79+ expertNum_ = tilingData->expertNum;
80+ expertCapacity_ = tilingData->expertCapacity;
81+ 
82+ outputRows_ = (dropPadMode_ == DROP_PAD_MODE) ? expertNum_ * expertCapacity_ : activeNum_;
83+ 
84+ topkWeightGm_.SetGlobalBuffer((__gm__ float *)topkWeight, totalLength_);
85+ expandedTopkWeightGm_.SetGlobalBuffer((__gm__ float *)expandedTopkWeight, outputRows_);
86+ 
87+ if (dropPadMode_ != DROP_PAD_MODE) {
88+ GlobalTensor<int32_t> expertTotalCountGm;
89+ expertTotalCountGm.SetGlobalBuffer((__gm__ int32_t *)workspace +
90+ Align(totalLength_, sizeof(int32_t)) * 2 + Align(tilingData->actualExpertNum, sizeof(int32_t)), 1);
91+ AscendC::DataCacheCleanAndInvalid<int32_t, AscendC::CacheLine::SINGLE_CACHE_LINE,
92+ AscendC::DcciDst::CACHELINE_OUT>(expertTotalCountGm);
93+ expertTotalCount_ = expertTotalCountGm.GetValue(0);
94+ 
95+ if (rowIdxType_ == SCATTER) {
96+ expandDstToSrcRowGm_.SetGlobalBuffer((__gm__ int32_t *)expandedRowIdx, totalLength_);
97+ } else {
98+ expandDstToSrcRowGm_.SetGlobalBuffer((__gm__ int32_t *)workspace +
99+ Align(totalLength_, sizeof(int32_t)), Align(totalLength_, sizeof(int32_t)));
100+ }
101+ } else {
102+ expandedRowIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expandedRowIdx, totalLength_);
103+ }
104+ 
105+ int64_t splitBase;
106+ if (dropPadMode_ == DROP_PAD_MODE) {
107+ splitBase = totalLength_;
108+ } else {
109+ splitBase = expertTotalCount_;
110+ }
111+ perCoreElements_ = Ceil(splitBase, coreNum_);
112+ needCoreNum_ = Ceil(splitBase, perCoreElements_);
113+ if (blockIdx_ == needCoreNum_ - 1) {
114+ coreElements_ = splitBase - (needCoreNum_ - 1) * perCoreElements_;
115+ } else {
116+ coreElements_ = perCoreElements_;
117+ }
118+ 
119+ perCorePerLoopElements_ = tilingData->topkWeightOutPerCorePerLoopElements;
120+ indicesLoops_ = Ceil(coreElements_, perCorePerLoopElements_);
121+ 
122+ pipe_->InitBuffer(topkWeightCopyInQueue_, 1, AlignBytes(1, sizeof(float)));
123+ pipe_->InitBuffer(rowIdxCopyInQueue_, ROW_IDX_BUFFER_NUM, AlignBytes(perCorePerLoopElements_, sizeof(int32_t)));
124+}
125+ 
126+__aicore__ inline void MoeV3TopkWeightOut::CopyRowIdxIn(int64_t offset, int64_t curLoopElements)
127+{
128+ LocalTensor<int32_t> rowIdxLocal = rowIdxCopyInQueue_.AllocTensor<int32_t>();
129+ DataCopyExtParams idxCopyParams{1, static_cast<uint32_t>(curLoopElements * sizeof(int32_t)), 0, 0, 0};
130+ DataCopyPadExtParams<int32_t> idxPadParams{false, 0, 0, 0};
131+ if (dropPadMode_ == DROP_PAD_MODE) {
132+ DataCopyPad(rowIdxLocal, expandedRowIdxGm_[offset], idxCopyParams, idxPadParams);
133+ } else {
134+ DataCopyPad(rowIdxLocal, expandDstToSrcRowGm_[offset], idxCopyParams, idxPadParams);
135+ }
136+ rowIdxCopyInQueue_.EnQue(rowIdxLocal);
137+}
138+ 
139+__aicore__ inline void MoeV3TopkWeightOut::ProcessDropPadGather(int64_t startIdx)
140+{
141+ DataCopyExtParams copyParams{static_cast<uint16_t>(1), static_cast<uint32_t>(sizeof(float)), 0, 0, 0};
142+ DataCopyPadExtParams<float> padParams{false, 0, 0, 0};
143+ 
144+ for (int64_t loop = 0; loop < indicesLoops_; loop++) {
145+ int64_t curLoopElements = (loop == indicesLoops_ - 1)
146+ ? coreElements_ - loop * perCorePerLoopElements_
147+ : perCorePerLoopElements_;
148+ int64_t offset = startIdx + loop * perCorePerLoopElements_;
149+ 
150+ CopyRowIdxIn(offset, curLoopElements);
151+ LocalTensor<int32_t> rowIdxLocal = rowIdxCopyInQueue_.DeQue<int32_t>();
152+ SetWaitFlag<HardEvent::MTE2_S>(HardEvent::MTE2_S);
153+ 
154+ for (int64_t i = 0; i < curLoopElements; i++) {
155+ int64_t dstIdx = rowIdxLocal.GetValue(i);
156+ if (dstIdx >= 0 && dstIdx < outputRows_) {
157+ int64_t globalSortIdx = offset + i;
158+ LocalTensor<float> topkWeightLocal = topkWeightCopyInQueue_.AllocTensor<float>();
159+ DataCopyPad(topkWeightLocal, topkWeightGm_[globalSortIdx], copyParams, padParams);
160+ topkWeightCopyInQueue_.EnQue(topkWeightLocal);
161+ topkWeightLocal = topkWeightCopyInQueue_.DeQue<float>();
162+ DataCopyPad(expandedTopkWeightGm_[dstIdx], topkWeightLocal, copyParams);
163+ topkWeightCopyInQueue_.FreeTensor(topkWeightLocal);
164+ }
165+ }
166+ rowIdxCopyInQueue_.FreeTensor(rowIdxLocal);
167+ }
168+}
169+ 
170+__aicore__ inline void MoeV3TopkWeightOut::ProcessDroplessScatter(int64_t startIdx)
171+{
172+ DataCopyExtParams copyParams{static_cast<uint16_t>(1), static_cast<uint32_t>(sizeof(float)), 0, 0, 0};
173+ DataCopyPadExtParams<float> padParams{false, 0, 0, 0};
174+ 
175+ for (int64_t loop = 0; loop < indicesLoops_; loop++) {
176+ int64_t curLoopElements = (loop == indicesLoops_ - 1)
177+ ? coreElements_ - loop * perCorePerLoopElements_
178+ : perCorePerLoopElements_;
179+ int64_t offset = startIdx + loop * perCorePerLoopElements_;
180+ 
181+ CopyRowIdxIn(offset, curLoopElements);
182+ LocalTensor<int32_t> rowIdxLocal = rowIdxCopyInQueue_.DeQue<int32_t>();
183+ SetWaitFlag<HardEvent::MTE2_S>(HardEvent::MTE2_S);
184+ 
185+ for (int64_t i = 0; i < curLoopElements; i++) {
186+ int64_t originalPos = rowIdxLocal.GetValue(i);
187+ if (originalPos >= 0 && originalPos < totalLength_) {
188+ int64_t curIndex = offset + i;
189+ LocalTensor<float> topkWeightLocal = topkWeightCopyInQueue_.AllocTensor<float>();
190+ DataCopyPad(topkWeightLocal, topkWeightGm_[originalPos], copyParams, padParams);
191+ topkWeightCopyInQueue_.EnQue(topkWeightLocal);
192+ topkWeightLocal = topkWeightCopyInQueue_.DeQue<float>();
193+ DataCopyPad(expandedTopkWeightGm_[curIndex], topkWeightLocal, copyParams);
194+ topkWeightCopyInQueue_.FreeTensor(topkWeightLocal);
195+ }
196+ }
197+ rowIdxCopyInQueue_.FreeTensor(rowIdxLocal);
198+ }
199+}
200+ 
201+__aicore__ inline void MoeV3TopkWeightOut::Process()
202+{
203+ int64_t startIdx = blockIdx_ * perCoreElements_;
204+ 
205+ if (dropPadMode_ == DROP_PAD_MODE) {
206+ int64_t perCoreZeroRows = Ceil(outputRows_, coreNum_);
207+ int64_t startRow = blockIdx_ * perCoreZeroRows;
208+ int64_t endRow = Min(startRow + perCoreZeroRows, outputRows_);
209+ if (startRow < endRow) {
210+ GlobalTensor<float> zeroGm;
211+ zeroGm.SetGlobalBuffer(
212+ (__gm__ float *)expandedTopkWeightGm_.GetPhyAddr() + startRow,
213+ endRow - startRow);
214+ SetWaitFlag<HardEvent::S_MTE3>(HardEvent::S_MTE3);
215+ InitGlobalMemory(zeroGm, endRow - startRow, 0.0f);
216+ SetWaitFlag<HardEvent::MTE3_S>(HardEvent::MTE3_S);
217+ }
218+#ifndef __CCE_KT_TEST__
219+ AscendC::SyncAll();
220+#endif
221+ 
222+ if (blockIdx_ < needCoreNum_) {
223+ ProcessDropPadGather(startIdx);
224+ }
225+ return;
226+ }
227+ 
228+ if (blockIdx_ < needCoreNum_) {
229+ ProcessDroplessScatter(startIdx);
230+ }
231+}
232+ 
233+} // namespace MoeInitRoutingV3
234+#endif // MOE_V3_TOPK_WEIGHT_OUT_H
@@ -35,6 +35,7 @@
35#include "arch35/moe_v3_full_load_static_quant.h"35#include "arch35/moe_v3_full_load_static_quant.h"
36#include "arch35/moe_v3_row_idx_gather_droppad.h"36#include "arch35/moe_v3_row_idx_gather_droppad.h"
37#include "arch35/moe_v3_gather_out_droppad.h"37#include "arch35/moe_v3_gather_out_droppad.h"
38+#include "arch35/moe_v3_topk_weight_out.h"
38 39 
39/*40/*
40 * 非量化41 * 非量化
@@ -257,7 +258,7 @@ extern "C" __global__ __aicore__ void moe_init_routing_v3(GM_ADDR x, GM_ADDR exp
257 TPipe fullLoadPipe;258 TPipe fullLoadPipe;
258 MoeV3FullLoadUnquantized<DTYPE_X> fullLoadOp;259 MoeV3FullLoadUnquantized<DTYPE_X> fullLoadOp;
259 fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx, expertTokensCountOrCumsum, expandedScale,260 fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx, expertTokensCountOrCumsum, expandedScale,
260- userWS, t, &fullLoadPipe);261+ nullptr, nullptr, userWS, t, &fullLoadPipe);
261 fullLoadOp.Process();262 fullLoadOp.Process();
262 fullLoadPipe.Destroy();263 fullLoadPipe.Destroy();
263 }264 }
@@ -272,8 +273,10 @@ extern "C" __global__ __aicore__ void moe_init_routing_v3(GM_ADDR x, GM_ADDR exp
272 if (isInt8DynamicQuant) {273 if (isInt8DynamicQuant) {
273 TPipe fullLoadPipe;274 TPipe fullLoadPipe;
274 MoeV3FullLoadDynamicQuant<DTYPE_X> fullLoadOp;275 MoeV3FullLoadDynamicQuant<DTYPE_X> fullLoadOp;
275- fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx, expertTokensCountOrCumsum,276+ fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx,
276- expandedScale, userWS, t, &fullLoadPipe);277+ expertTokensCountOrCumsum, expandedScale,
278+ nullptr, nullptr,
279+ userWS, t, &fullLoadPipe);
277 fullLoadOp.Process();280 fullLoadOp.Process();
278 fullLoadPipe.Destroy();281 fullLoadPipe.Destroy();
279 }282 }
@@ -282,8 +285,10 @@ extern "C" __global__ __aicore__ void moe_init_routing_v3(GM_ADDR x, GM_ADDR exp
282 if (isInt4DynamicQuant) {285 if (isInt4DynamicQuant) {
283 TPipe fullLoadPipe;286 TPipe fullLoadPipe;
284 MoeV3FullLoadDynamicQuant<DTYPE_X, int4b_t> fullLoadOp;287 MoeV3FullLoadDynamicQuant<DTYPE_X, int4b_t> fullLoadOp;
285- fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx, expertTokensCountOrCumsum,288+ fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx,
286- expandedScale, userWS, t, &fullLoadPipe);289+ expertTokensCountOrCumsum, expandedScale,
290+ nullptr, nullptr,
291+ userWS, t, &fullLoadPipe);
287 fullLoadOp.Process();292 fullLoadOp.Process();
288 fullLoadPipe.Destroy();293 fullLoadPipe.Destroy();
289 }294 }
@@ -299,7 +304,7 @@ extern "C" __global__ __aicore__ void moe_init_routing_v3(GM_ADDR x, GM_ADDR exp
299 TPipe fullLoadPipe;304 TPipe fullLoadPipe;
300 MoeV3FullLoadStaticQuant<DTYPE_X> fullLoadOp;305 MoeV3FullLoadStaticQuant<DTYPE_X> fullLoadOp;
301 fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx, expertTokensCountOrCumsum, expandedScale,306 fullLoadOp.Init(x, expertIdx, scale, expandedX, expandedRowIdx, expertTokensCountOrCumsum, expandedScale,
302- userWS, offset, t, &fullLoadPipe);307+ nullptr, nullptr, userWS, offset, t, &fullLoadPipe);
303 fullLoadOp.Process();308 fullLoadOp.Process();
304 fullLoadPipe.Destroy();309 fullLoadPipe.Destroy();
305 }310 }
@@ -445,7 +450,19 @@ extern "C" __global__ __aicore__ void moe_init_routing_v3(GM_ADDR x, GM_ADDR exp
445 }450 }
446 }451 }
447 452 
448- // 4.直接搬运或是搬运的过程中对x进行量化453+ // 4.TopkWeightOut(仅非FullLoad路径)
454+ // V3 regression: isInputTopkWeight 恒为 0,此分支不会执行。
455+ // topkWeight/expandedTopkWeight 传 nullptr 仅为占位,不可在 isInputTopkWeight==1 时执行,
456+ // 否则 Init 内 SetGlobalBuffer 会解引用空指针。V4 通过 tiling 设置 isInputTopkWeight=1 启用此路径。
457+ if (t->isInputTopkWeight == 1) {
458+ TPipe topkWeightPipe;
459+ MoeV3TopkWeightOut topkWeightOp;
460+ topkWeightOp.Init(nullptr, expandedRowIdx, nullptr, userWS, t, &topkWeightPipe);
461+ topkWeightOp.Process();
462+ topkWeightPipe.Destroy();
463+ }
464+ 
465+ // 5.直接搬运或是搬运的过程中对x进行量化
449 if (TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTONECORE_GATHER) ||466 if (TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTONECORE_GATHER) ||
450 TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTONECORE_SCATTER) ||467 TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTONECORE_SCATTER) ||
451 TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTMULTICORE_GATHER) ||468 TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTMULTICORE_GATHER) ||
@@ -471,7 +488,7 @@ extern "C" __global__ __aicore__ void moe_init_routing_v3(GM_ADDR x, GM_ADDR exp
471 gatherOp.Process();488 gatherOp.Process();
472 gatherPipe.Destroy();489 gatherPipe.Destroy();
473 }490 }
474- // 4.直接搬运或是搬运的过程中对x进行量化491+ // 5.直接搬运或是搬运的过程中对x进行量化
475 } else if (TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTONECORE_GATHER_DROP) ||492 } else if (TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTONECORE_GATHER_DROP) ||
476 TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTMULTICORE_GATHER_DROP)) {493 TILING_KEY_IS(MOE_INIT_ROUTING_V3_SORTMULTICORE_GATHER_DROP)) {
477 if constexpr (IsSameType<DTYPE_X, bfloat16_t>::value || IsSameType<DTYPE_X, half>::value ||494 if constexpr (IsSameType<DTYPE_X, bfloat16_t>::value || IsSameType<DTYPE_X, half>::value ||
@@ -18,24 +18,25 @@
18#include "platform/platform_infos_def.h"18#include "platform/platform_infos_def.h"
19#include "op_tiling_parse_context_builder.h"19#include "op_tiling_parse_context_builder.h"
20#include "base/registry/op_impl_space_registry_v2.h"20#include "base/registry/op_impl_space_registry_v2.h"
21-#include <nlohmann/json.hpp>
22 21 
23using namespace std;22using namespace std;
24 23 
25namespace {24namespace {
25+constexpr uint32_t ASCEND910B_CORE_NUM = 64;
26+constexpr uint32_t ASCEND910B_L2_SIZE = 33554432;
27+constexpr uint32_t ASCEND910B_UB_SIZE = 262144;
28+constexpr uint32_t ASCEND910B_L1_SIZE = 524288;
29+ 
26void InitParsePlatformInfo(fe::PlatFormInfos &platformInfo)30void InitParsePlatformInfo(fe::PlatFormInfos &platformInfo)
27{31{
28 platformInfo.Init();32 platformInfo.Init();
29- const char *compileJson =
30- R"({"hardware_info": {"UB_SIZE": 262144, "CORE_NUM": 64, "L2_SIZE": 33554432, "L1_SIZE": 524288, "L0A_SIZE": 65536, "L0B_SIZE": 65536, "L0C_SIZE": 131072, "BT_SIZE": 0, "load3d_constraints": "1", "socVersion":"Ascend910B"}})";
31- nlohmann::json compileInfoJson = nlohmann::json::parse(compileJson);
32 map<string, string> socInfos;33 map<string, string> socInfos;
33 map<string, string> aicoreSpec;34 map<string, string> aicoreSpec;
34- socInfos["ai_core_cnt"] = to_string(compileInfoJson["hardware_info"]["CORE_NUM"].get<uint32_t>());35+ socInfos["ai_core_cnt"] = to_string(ASCEND910B_CORE_NUM);
35- socInfos["l2_size"] = to_string(compileInfoJson["hardware_info"]["L2_SIZE"].get<uint32_t>());36+ socInfos["l2_size"] = to_string(ASCEND910B_L2_SIZE);
36 socInfos["core_type_list"] = "AICore";37 socInfos["core_type_list"] = "AICore";
37- aicoreSpec["ub_size"] = to_string(compileInfoJson["hardware_info"]["UB_SIZE"].get<uint32_t>());38+ aicoreSpec["ub_size"] = to_string(ASCEND910B_UB_SIZE);
38- aicoreSpec["l1_size"] = to_string(compileInfoJson["hardware_info"]["L1_SIZE"].get<uint32_t>());39+ aicoreSpec["l1_size"] = to_string(ASCEND910B_L1_SIZE);
39 map<string, string> versions = {{"NpuArch", "2201"}, {"Short_SoC_version", "Ascend910B"}};40 map<string, string> versions = {{"NpuArch", "2201"}, {"Short_SoC_version", "Ascend910B"}};
40 platformInfo.SetPlatformRes("SoCInfo", socInfos);41 platformInfo.SetPlatformRes("SoCInfo", socInfos);
41 platformInfo.SetPlatformRes("AICoreSpec", aicoreSpec);42 platformInfo.SetPlatformRes("AICoreSpec", aicoreSpec);
@@ -0,0 +1,20 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file in 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+message(STATUS "=== Debug: start ops.moe.moe_init_routing_v4.CMakeLists.txt ")
12+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
13+if(NOT ENABLE_TEST)
14+ list(REMOVE_ITEM CURRENT_DIRS tests)
15+endif()
16+foreach(SUB_DIR ${CURRENT_DIRS})
17+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
18+ add_subdirectory(${SUB_DIR})
19+ endif()
20+endforeach()
@@ -0,0 +1,264 @@
1+# MoeInitRoutingV4
2+ 
3+## 产品支持情况
4+ 
5+| 产品 | 是否支持 |
6+| :----------------------------------------------------------- | :------: |
7+| <term>Ascend 950PR/Ascend 950DT</term> | √ |
8+| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | × |
9+| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | × |
10+| <term>Atlas 200I/500 A2 推理产品</term> | × |
11+| <term>Atlas 推理系列产品</term> | × |
12+| <term>Atlas 训练系列产品</term> | × |
13+ 
14+## 功能说明
15+ 
16+- 算子功能:MoE的routing计算,根据[aclnnMoeGatingTopKSoftmaxV2](../moe_gating_top_k_softmax_v2/docs/aclnnMoeGatingTopKSoftmaxV2.md)的计算结果做routing处理,支持非量化、静态量化和动态量化模式。本接口针对V3接口[aclnnMoeInitRoutingV3](../moe_init_routing_v3/docs/aclnnMoeInitRoutingV3.md)做了如下功能变更,请根据实际情况选择合适的接口:
17+ 
18+ 1.active_num从属性改为可选输入,支持图模式下动态传入active_num值。
19+ 
20+ 2.新增可选输入topkWeight和可选输出expandedTopkWeightOut,支持对topkWeight按排序后的索引进行重排,使得expandedTopkWeightOut与expandedXOut一一对应。topkWeight与expandedTopkWeightOut必须同时传入或同时不传入。
21+ 
22+ 3.仅支持Ascend 950架构。
23+ 
24+- 计算公式:
25+ 
26+ 1.对输入expertIdx做排序,得出排序后的结果sortedExpertIdx和对应的序号sortedRowIdx:
27+ 
28+ $$
29+ sortedExpertIdx, sortedRowIdx=keyValueSort(expertIdx,rowIdx)
30+ $$
31+ 
32+ 2.以sortedRowIdx做位置映射得出expandedRowIdxOut:
33+ - rowIdxType等于1时, 输出scatter索引
34+ 
35+ $$
36+ expandedRowIdxOut[i]=sortedRowIdx[i]
37+ $$
38+ 
39+ - rowIdxType等于0时, 输出gather索引
40+ 
41+ $$
42+ expandedRowIdxOut[sortedRowIdx[i]]=i
43+ $$
44+ 
45+ 3.对sortedExpertIdx的每个专家统计直方图结果,得出expertTokensCountOrCumsumOutOptional:
46+ 
47+ $$
48+ expertTokensCountOrCumsumOutOptional[i]=Histogram(sortedExpertIdx)
49+ $$
50+ 
51+ 4.如果quantMode不等于-1, 计算quant结果:
52+ - 静态quant:
53+ $$
54+ quantResult = round(x * scaleOptional + offsetOptional)
55+ $$
56+ 
57+ - 动态quant:
58+ - 若不输入scale:
59+ $$
60+ dynamicQuantScaleOutOptional = row\_max(abs(x)) / 127
61+ $$
62+ 
63+ $$
64+ quantResult = round(x / dynamicQuantScaleOutOptional)
65+ $$
66+ 
67+ - 若输入scale:
68+ $$
69+ dynamicQuantScaleOutOptional = row\_max(abs(x * scaleOptional)) / 127
70+ $$
71+ 
72+ $$
73+ quantResult = round(x / dynamicQuantScaleOutOptional)
74+ $$
75+ 
76+ - 当quantMode为13时,动态量化使用对称量化范围[-8, 7],scale计算中的分母为7,量化结果沿H维每两个INT4值打包为1个字节。
77+ 
78+ 5.对quantResult取前min(activeNum, NUM_ROWS*K)个sortedRowIdx的对应位置的值,得出expandedXOut:
79+ 
80+ $$
81+ expandedXOut[i]=quantResult[sortedRowIdx[i]/K]
82+ $$
83+ 
84+ 6.如果输入topkWeight,对topkWeight按sortedRowIdx做位置映射,得出expandedTopkWeightOut:
85+ 
86+ $$
87+ expandedTopkWeightOut[i]=topkWeight[sortedRowIdx[i]]
88+ $$
89+ 
90+ 其中i的取值范围为[0, min(activeNum, availableIdxNum))。
91+ 
92+ 7.expandedRowIdxOut的有效元素数量availableIdxNum计算方式为,expertIdx中activeExpertRangeOptional范围内的元素的个数
93+ $$
94+ availableIdxNum = |\{x\in expertIdx| expert\_start \le x<expert\_end \ \}|
95+ $$
96+ 
97+## 参数说明
98+ 
99+ <table style="undefined;table-layout: fixed; width: 1576px"><colgroup>
100+ <col style="width: 170px">
101+ <col style="width: 170px">
102+ <col style="width: 312px">
103+ <col style="width: 213px">
104+ <col style="width: 100px">
105+ </colgroup>
106+ <thead>
107+ <tr>
108+ <th>参数名</th>
109+ <th>输入/输出/属性</th>
110+ <th>描述</th>
111+ <th>数据类型</th>
112+ <th>数据格式</th>
113+ </tr></thead>
114+ <tbody>
115+ <tr>
116+ <td>x</td>
117+ <td>输入</td>
118+ <td>MOE的输入,即token特征输入,对应公式中x。</td>
119+ <td>FLOAT32、FLOAT16、BFLOAT16、INT8、HIFLOAT8、FLOAT4_E2M1、FLOAT8_E4M3FN、FLOAT8_E5M2。</td>
120+ <td>ND</td>
121+ </tr>
122+ <tr>
123+ <td>expertIdx</td>
124+ <td>输入</td>
125+ <td>每一行特征对应的K个处理专家,里面元素专家id不能超过专家数。对应公式中expertIdx。</td>
126+ <td>INT32</td>
127+ <td>ND</td>
128+ </tr>
129+ <tr>
130+ <td>scaleOptional</td>
131+ <td>可选输入</td>
132+ <td>表示用于计算quant结果的参数。如果不输入表示计算时不使用scale,对应公式中scale。<br>• quantMode为1的INT8动态量化场景下,如果输入则要求为2D的Tensor,shape为(expertEnd-expertStart, H)。<br>• quantMode为13的INT4动态量化场景下,如果输入则要求shape为(1, H),表示按H维广播的smooth scale。<br>• 仅quantMode=-1且x的数据类型为FLOAT4_E2M1、FLOAT8_E4M3FN或FLOAT8_E5M2时,scale数据类型支持FLOAT8_E8M0。</td>
133+ <td>FLOAT32、FLOAT8_E8M0</td>
134+ <td>ND</td>
135+ </tr>
136+ <tr>
137+ <td>offsetOptional</td>
138+ <td>可选输入</td>
139+ <td>表示用于计算quant结果的偏移值。在非量化场景下和动态quant场景下不输入,对应公式中offsetOptional。</td>
140+ <td>FLOAT32</td>
141+ <td>ND</td>
142+ </tr>
143+ <tr>
144+ <td>activeNumOptional</td>
145+ <td>可选输入</td>
146+ <td>表示总的最大处理row数,输出expandedXOut只有这么多行是有效的。不输入时activeNum默认为NUM_ROWS*K;输入时为标量Tensor(shape为()或(1,)),数据类型为INT64,值大于等于0,0表示Dropless场景,大于0时表示Active场景,约束所有专家共同处理tokens总量。</td>
147+ <td>INT64</td>
148+ <td>ND</td>
149+ </tr>
150+ <tr>
151+ <td>topkWeightOptional</td>
152+ <td>可选输入</td>
153+ <td>topk专家的路由权重,用于按排序索引重排以与expandedXOut一一对应。输入shape为(NUM_ROWS, K),数据类型仅支持FLOAT32。topkWeight与expandedTopkWeightOut必须同时传入或同时不传入。</td>
154+ <td>FLOAT32</td>
155+ <td>ND</td>
156+ </tr>
157+ <tr>
158+ <td>expertCapacity</td>
159+ <td>属性</td>
160+ <td>表示每个专家能够处理的tokens数,取值范围大于等于0。</td>
161+ <td>INT</td>
162+ <td>-</td>
163+ </tr>
164+ <tr>
165+ <td>expertNum</td>
166+ <td>属性</td>
167+ <td>表示专家数,expertTokensNumType为key\_value模式时,取值范围为[0, 5120],其它模式取值范围[0, 10240]。</td>
168+ <td>INT</td>
169+ <td>-</td>
170+ </tr>
171+ <tr>
172+ <td>dropPadMode</td>
173+ <td>属性</td>
174+ <td>表示是否为DropPad场景,取值为0 和1。<br>• 0:表示Dropless场景,该场景下不校验expertCapacity。<br>• 1:表示DropPad场景。</td>
175+ <td>INT</td>
176+ <td>-</td>
177+ </tr>
178+ <tr>
179+ <td>expertTokensNumType</td>
180+ <td>属性</td>
181+ <td>取值为0、1和2 。<br>• 0:表示comsum模式。<br>• 1:表示count模式,即输出的值为各个专家处理的token数量的累计值。<br>• 2:表示key\_value模式,即输出的值为专家和对应专家处理token数量的累计值。</td>
182+ <td>INT</td>
183+ <td>-</td>
184+ </tr>
185+ <tr>
186+ <td>expertTokensNumFlag</td>
187+ <td>属性</td>
188+ <td>取值为false和true。<br>• false:表示不输出expertTokensCountOrCumsumOut。<br>• true:表示输出expertTokensCountOrCumsumOut。</td>
189+ <td>Bool</td>
190+ <td>-</td>
191+ </tr>
192+ <tr>
193+ <td>quantMode</td>
194+ <td>属性</td>
195+ <td>取值为0、1、-1、2、3、4、5、6、7、8、9、11、12、13、14、15、16、17。<br>• 0:表示静态quant场景。<br>• 1:表示动态quant场景,expandedXOut量化到INT8。<br>• -1:表示非量化场景。<br>• 2:表示MXFP8量化场景,expandedXOut量化到FLOAT8_E5M2。<br>• 3:表示MXFP8量化场景,expandedXOut量化到FLOAT8_E4M3FN。<br>• 4:表示FP8 PerGroup量化场景(GroupSize=128,RoundScale),expandedXOut量化到FLOAT8_E5M2。<br>• 5:表示FP8 PerGroup量化场景(GroupSize=128,RoundScale),expandedXOut量化到FLOAT8_E4M3FN。<br>• 6:表示HIF8直转量化场景下,expandedXOut量化到HIFLOAT8。<br>• 7:表示HIF8 PERTENSOR量化场景,expandedXOut量化到HIFLOAT8。<br>• 8:表示HIF8 PERTOKEN量化场景,expandedXOut量化到HIFLOAT8。<br>• 9:表示MXFP4量化场景,expandedXOut量化到FLOAT4_E2M1。<br>• 11:表示FP8 PerBlock量化场景(BlockSize=128),expandedXOut量化到FLOAT8_E5M2,expandedScaleOut为FLOAT32三维布局。<br>• 12:表示FP8 PerBlock量化场景(BlockSize=128),expandedXOut量化到FLOAT8_E4M3FN,expandedScaleOut为FLOAT32三维布局。<br>• 13:表示INT4动态量化场景,expandedXOut量化到INT4。<br>• 14:表示FP8 PerGroup量化场景(GroupSize=128,RoundScale+Amax),expandedXOut量化到FLOAT8_E5M2。<br>• 15:表示FP8 PerGroup量化场景(GroupSize=128,RoundScale+Amax),expandedXOut量化到FLOAT8_E4M3FN。<br>• 16:表示MXFP8 RoundScale+Amax量化场景,expandedXOut量化到FLOAT8_E5M2。<br>• 17:表示MXFP8 RoundScale+Amax量化场景,expandedXOut量化到FLOAT8_E4M3FN。</td>
196+ <td>INT</td>
197+ <td>-</td>
198+ </tr>
199+ <tr>
200+ <td>activeExpertRangeOptional</td>
201+ <td>可选属性</td>
202+ <td>长度为2,数组内的值为[expertStart, expertEnd],表示活跃的expert范围在expertStart和expertEnd之间,左闭右开。要求值大于等于0,并且expertEnd不大于expertNum。</td>
203+ <td>ListInt</td>
204+ <td>-</td>
205+ </tr>
206+ <tr>
207+ <td>rowIdxType</td>
208+ <td>属性</td>
209+ <td>表示expandedRowIdxOut使用的索引类型,取值为0、1。<br>• 0:表示gather类型的索引。<br>• 1:表示scatter类型的索引。</td>
210+ <td>INT</td>
211+ <td>-</td>
212+ </tr>
213+ <tr>
214+ <td>expandedXOut</td>
215+ <td>输出</td>
216+ <td>根据expertIdx进行扩展过的特征。非量化场景下数据类型同x,量化场景quantMode为0、1时数据类型支持INT8,quantMode为13且x数据类型为FLOAT32或BFLOAT16时数据类型支持INT4,quantMode为2、4、14、16时数据类型支持FLOAT8_E5M2,quantMode为3、5、15、17时数据类型支持FLOAT8_E4M3FN,quantMode为6、7、8时数据类型支持HIFLOAT8,quantMode为9时数据类型支持FLOAT4_E2M1,quantMode为11、12时数据类型分别支持FLOAT8_E5M2、FLOAT8_E4M3FN。
217+ <br>• Dropless场景shape为[NUM_ROWS * K, H]。<br>• Active场景shape为[min(activeNum, NUM_ROWS * K), H]。<br>• DropPad场景下要求是一个3D的Tensor,shape为[expertNum, expertCapacity, H]。</td>
218+ <td>FLOAT32、FLOAT16、BFLOAT16、INT8、INT4、FLOAT8_E5M2、FLOAT8_E4M3FN、HIFLOAT8、FLOAT4_E2M1</td>
219+ <td>ND</td>
220+ </tr>
221+ <tr>
222+ <td>expandedRowIdxOut</td>
223+ <td>输出</td>
224+ <td>expandedXOut和x的索引映射关系,前availableIdxNum\*H个元素为有效数据,其余无效数据,当rowIdxType为0时,无效数据由-1填充;当rowIdxType为1时,无效数据未初始化。</td>
225+ <td>INT32</td>
226+ <td>ND</td>
227+ </tr>
228+ <tr>
229+ <td>expertTokensCountOrCumsumOut</td>
230+ <td>输出</td>
231+ <td>• 在expertTokensNumType为1的场景下,表示activeExpertRangeOptional范围内expert对应的处理token的总数。<br>• 在expertTokensNumType为2的场景下,表示activeExpertRangeOptional范围内token总数为非0的expert,以及对应expert处理token的总数。<br>• expertTokensNumType为0或1时,输出shape为[expertEnd-expertStart];expertTokensNumType为2时,输出shape为[expertNum, 2]。</td>
232+ <td>INT64</td>
233+ <td>ND</td>
234+ </tr>
235+ <tr>
236+ <td>expandedScaleOut</td>
237+ <td>输出</td>
238+ <td>输出量化计算过程中scaleOptional的中间值。<br>• 非量化场景下为可选输入,如果输入则要求为1D的Tensor,类型为FLOAT32。当输入x数据类型为FLOAT4_E2M1、FLOAT8_E4M3FN或FLOAT8_E5M2时,如果输入则要求3D的Tensor,类型为FLOAT8_E8M0。当DropPad场景输出是一个1D的Tensor,shape为[expertNum * expertCapacity],类型为FLOAT32。<br>• quantMode为2、3、9时,数据类型支持FLOAT8_E8M0。<br>• quantMode为16、17时,数据类型支持FLOAT8_E8M0,Shape为[NUM_ROWS*K, M],其中M=CeilAlign(CeilDiv(H,32),2)。<br>• quantMode为4、5、14、15时,数据类型支持FLOAT32,且要求为2D的Tensor,shape为[NUM_ROWS*K, CeilDiv(H, 128)]。<br>• quantMode为11、12时,数据类型支持FLOAT32,且要求为3D的Tensor。<br>• 其余场景数据类型支持FLOAT32。</td>
239+ <td>FLOAT32、FLOAT8_E8M0</td>
240+ <td>ND</td>
241+ </tr>
242+ <tr>
243+ <td>expandedTopkWeightOut</td>
244+ <td>可选输出</td>
245+ <td>按排序索引重排后的路由权重,与expandedXOut一一对应。topkWeight输入时必须同时输出。<br>• Dropless场景下shape为[min(activeNum, NUM_ROWS*K), 1],前effectiveNum个元素为有效数据,其余未初始化,effectiveNum=min(activeNum, availableIdxNum)。<br>• DropPad场景下shape为[expertNum*expertCapacity, 1],已分配容量的位置为有效数据,未分配容量的位置填充为0。</td>
246+ <td>FLOAT32</td>
247+ <td>ND</td>
248+ </tr>
249+ </tbody>
250+ </table>
251+ 
252+## 约束说明
253+ 
254+- activeNum为可选输入,不输入时默认为NUM_ROWS*K;输入时为标量Tensor,数据类型为INT64,值大于等于0。
255+- expertCapacity在Dropless场景下仅校验其值,不使用该参数;在DropPad场景下必须校验且取值范围为(0, NUM_ROWS]。
256+- quantMode支持-1、0、1、2、3、4、5、6、7、8、9、11、12、13、14、15、16、17,分别表示非量化、静态量化、动态量化到INT8、MXFP8量化到FLOAT8_E5M2、MXFP8量化到FLOAT8_E4M3FN、FP8 PerGroup量化到FLOAT8_E5M2、FP8 PerGroup量化到FLOAT8_E4M3FN、按直转方式量化到HIFLOAT8、按PERTENSOR模式量化到HIFLOAT8、按PERTOKEN模式量化到HIFLOAT8,MXFP4量化到FLOAT4_E2M1,FP8 PerBlock量化到FLOAT8_E5M2,FP8 PerBlock量化到FLOAT8_E4M3FN,INT4动态量化,FP8 PerGroup+Amax量化到FLOAT8_E5M2,FP8 PerGroup+Amax量化到FLOAT8_E4M3FN,MXFP8 RoundScale+Amax量化到FLOAT8_E5M2,MXFP8 RoundScale+Amax量化到FLOAT8_E4M3FN。
257+- 支持quantMode为13的INT4动态量化场景,需同时满足:
258+ - x数据类型为FLOAT32或BFLOAT16,expandedXOut数据类型为INT4。
259+ - H为偶数,用于沿H维每两个INT4值打包为1个字节。
260+ - scaleOptional不输入,或输入shape为(1, H)、数据类型为FLOAT32;offsetOptional不输入。
261+- topkWeight与expandedTopkWeightOut必须同时传入或同时不传入。
262+- DropPad模式特殊约束(dropPadMode=1时):
263+ - quantMode仅支持-1(非量化),且数据类型仅支持FLOAT16、BFLOAT16、FLOAT32、INT8、HIFLOAT8。
264+ - expandedXOut必须是3D Tensor,shape为[expertNum, expertCapacity, H]。
@@ -0,0 +1,14 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file in in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS" 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+message(STATUS "=== Debug: start ops.moe.moe_init_routing_v4.op_graph.CMakeLists.txt ")
12+if (BUILD_OPEN_PROJECT)
13+ add_graph_plugin_sources()
14+endif()
@@ -0,0 +1,112 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file moe_init_routing_v4_proto.h
13+ * \brief
14+ */
15+#ifndef OPS_OP_PROTO_INC_MOE_INIT_ROUTING_V4_OPS_H_
16+#define OPS_OP_PROTO_INC_MOE_INIT_ROUTING_V4_OPS_H_
17+ 
18+#include "graph/operator_reg.h"
19+ 
20+namespace ge {
21+/**
22+* @brief compute init routing for moe (v4, ascend950 only).
23+* @par Inputs:
24+* @li x: A 2D tensor. Shape is: (B*S, H). Type is:Int8, BFloat16, Float16, Float32, Hif8, FLOAT8_E5M2, FLOAT8_E4M3FN
25+ or FLOAT4_E2M1. Format support ND.
26+* @li expert_idx: A 2D tensor. Shape is: (B*S, K). Type is:Int32. Expert index. Format support ND.
27+* @li scale: A 1D or 2D tensor. Shape is: (B*S) or (expert_end-expert_start, H) when quant_mode is 1.
28+ When quant_mode is 13, scale can be omitted or shape is (1, H). Type is:Float32 or Float8_E8M0.
29+ Format support ND.
30+* @li offset: A 2D tensor. Shape is: (expert_end - expert_start, 1) or (expert_end - expert_start, H).
31+* Type is:Float32. Format support ND.
32+* @li active_num: A scalar tensor. Type is:Int64. Identify activate scenario. When provided, the value
33+ should equal B*S*K. Default: not provided (equivalent to B*S*K). Format support ND.
34+* @li topk_weight: A 2D tensor. Shape is: (B*S, K). Type is:Float32. TopK routing weights. Format support ND.
35+* @par Outputs:
36+* @li expanded_x: A 2D tensor. Shape is: (B*S*K, H). When quant_mode is -1, type is:Int8, BFloat16, Float16, Float32,
37+ Hif8, FLOAT8_E5M2, FLOAT8_E4M3FN or FLOAT4_E2M1.
38+ The data type must be the same as that of x.
39+ When quant_mode is 0, type is Int8.
40+ When quant_mode is 1, type is Int8.
41+ When quant_mode in [2, 4, 14], type is FLOAT8_E5M2.
42+ When quant_mode in [3, 5, 15], type is FLOAT8_E4M3FN.
43+ When quant_mode in [6, 7, 8], type is Hif8.
44+ When quant_mode is 9, type is FLOAT4_E2M1.
45+ When quant_mode in [11, 12], type is [FLOAT8_E5M2, FLOAT8_E4M3FN].
46+ When quant_mode is 13, type is Int4.
47+ When quant_mode in [16, 17], type is [FLOAT8_E5M2, FLOAT8_E4M3FN].
48+ Format support ND.
49+* @li expanded_row_idx: A 1D tensor. Shape is: (B*S*K). Type is:Int32. Format support ND.
50+* @li expert_tokens_count_or_cumsum: A 1D tensor. represents the number of tokens processed by each expert and the
51+ cumulative value. The value is controlled by expert_tokens_num_flag to output.
52+ Type is:Int64. shape is (expert_end - expert_start, ). Format support ND.
53+* @li expanded_scale: A 1D tensor when quant_mode in [-1, 0, 1, 13]. Shape is: (B*S*K).
54+ Type is:Float32. The data type must be the same as that of scale.
55+ A 2D tensor when quant_mode in [2, 3, 16, 17]. Shape is: (B*S*K, M),
56+ in which M is CeilAlign(CeilDiv(H, 32), 2). Type is: Float8_E8M0.
57+ A 2D tensor when quant_mode in [4, 5, 14, 15]. Shape is: (B*S*K, CeilDiv(H, 128)).
58+ Type is: Float32.
59+ A 3D tensor when quant_mode in [11, 12] (FP8 PerBlock量化,BlockSize=128).
60+ Shape is: (B*S*K, M, 2), in which M is CeilDiv(H, 256).
61+ Type is: Float32 (FP32 Scale).
62+ A 3D tensor when quant_mode is -1 and dtype of input x equals FLOAT4_E2M1 or quant_mode is 9.
63+ Shape is: (B*S*K, M, 2), in which M is CeilAlign(CeilDiv(H, 32), 2).
64+ Type is: Float8_E8M0.
65+ Format support ND.
66+* @li expanded_topk_weight: A 2D tensor. Shape is: (B*S*K, 1) when topk_weight is provided and drop_pad_mode is 0,
67+ or (expert_num*expert_capacity, 1) when drop_pad_mode is 1.
68+ Shape is (0,) when topk_weight is not provided. Type is:Float32. Format support ND.
69+* @par Attributes:
70+* @li expert_capacity: Optional parameter. Type is:Int32. The max tokens count of every expert. Default: -1.
71+* @li expert_num: Optional parameter. Type is:Int32. Number of experts. Default: -1.
72+* @li drop_pad_mode: Optional parameter. Type is:Int32. The value is 0(dropless) or 1(dropPad). Default: 0.
73+* @li expert_tokens_num_type: Optional parameter. Type is:Int32. The value is 0(compute tokens cumsum) or
74+ 1(compute tokens count), which in dropPad scenario. Default: 0.
75+* @li expert_tokens_num_flag: Optional parameter. Type is:Bool. The value is true (compute tokens) or
76+ false(do not compute tokens), which in dropPad scenario. Default: false.
77+* @li quant_mode: Optional parameter. Type is:Int. Valid values: -1(unquant), 0(static), 1(dynamic), 2(fp8_e5m2),
78+ 3(fp8_e4m3fn), 4(fp8_group_e5m2), 5(fp8_group_e4m3fn), 6(hif8 cast), 7(hif8_pertensor),
79+ 8(hif8_pertoken), 9(fp4_e2m1), 11(fp8_perblock_e5m2), 12(fp8_perblock_e4m3fn), 13(int4_dynamic),
80+ 14(fp8_group_amax_e5m2), 15(fp8_group_amax_e4m3fn),
81+ 16(mxfp8_roundscale_amax_e5m2), 17(mxfp8_roundscale_amax_e4m3fn). Default: -1.
82+* @li active_expert_range: Optional parameter. Type is:ListInt. Like [expert_start, expert_end].
83+ expert_start must be greater than or equal to 0, expert_end must be less than or equal to
84+ 10240, expert_start must be less than expert_end. Default: [].
85+* @li row_idx_type: Optional parameter. Type is:Int. The value is 0(gather) or 1(scatter). Default: 0.
86+*/
87+REG_OP(MoeInitRoutingV4)
88+ .INPUT(x, TensorType({DT_INT8, DT_FLOAT16, DT_FLOAT, DT_BF16, DT_HIFLOAT8, DT_FLOAT8_E5M2,
89+ DT_FLOAT8_E4M3FN, DT_FLOAT4_E2M1}))
90+ .INPUT(expert_idx, TensorType({DT_INT32}))
91+ .OPTIONAL_INPUT(scale, TensorType({DT_FLOAT, DT_FLOAT8_E8M0}))
92+ .OPTIONAL_INPUT(offset, TensorType({DT_FLOAT}))
93+ .OPTIONAL_INPUT(active_num, TensorType({DT_INT64}))
94+ .OPTIONAL_INPUT(topk_weight, TensorType({DT_FLOAT}))
95+ .OUTPUT(expanded_x, TensorType({DT_INT8, DT_FLOAT16, DT_FLOAT, DT_BF16, DT_FLOAT8_E5M2,
96+ DT_FLOAT8_E4M3FN, DT_HIFLOAT8, DT_FLOAT4_E2M1, DT_INT4}))
97+ .OUTPUT(expanded_row_idx, TensorType({DT_INT32}))
98+ .OUTPUT(expert_tokens_count_or_cumsum, TensorType({DT_INT64}))
99+ .OUTPUT(expanded_scale, TensorType({DT_FLOAT, DT_FLOAT8_E8M0}))
100+ .OUTPUT(expanded_topk_weight, TensorType({DT_FLOAT}))
101+ .ATTR(expert_capacity, Int, -1)
102+ .ATTR(expert_num, Int, -1)
103+ .ATTR(drop_pad_mode, Int, 0)
104+ .ATTR(expert_tokens_num_type, Int, 0)
105+ .ATTR(expert_tokens_num_flag, Bool, false)
106+ .ATTR(quant_mode, Int, -1)
107+ .ATTR(active_expert_range, ListInt, {})
108+ .ATTR(row_idx_type, Int, 0)
109+ .OP_END_FACTORY_REG(MoeInitRoutingV4)
110+} // namespace ge
111+ 
112+#endif
@@ -0,0 +1,45 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file in 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+message(STATUS "=== Debug: start ops.moe.moe_init_routing_v4.op_host.CMakeLists.txt ")
12+ 
13+set(CONDITION_UNIT ${ASCEND_COMPUTE_UNIT})
14+if (BUILD_OPEN_PROJECT)
15+ message(STATUS "=== Debug: BUILD is BUILD_OPEN_PROJECT")
16+ set(moe_init_routing_v4_depends moe/moe_init_routing_v3
17+ CACHE INTERNAL "Dependencies for moe_init_routing_v4")
18+ set(moe_init_routing_v4_apt_depends moe/moe_init_routing_v3
19+ CACHE INTERNAL "Dependencies for moe_init_routing_v4")
20+ target_sources(op_host_aclnnExc PRIVATE
21+ moe_init_routing_v4_def.cpp
22+ )
23+ if(CONDITION_UNIT STREQUAL "ascend950")
24+ add_ops_compile_options(
25+ OP_NAME MoeInitRoutingV4
26+ OPTIONS --cce-auto-sync=on
27+ -Wno-deprecated-declarations
28+ -Werror
29+ -mllvm
30+ -cce-aicore-dcci-before-kernel-end=false
31+ )
32+ else()
33+ add_ops_compile_options(
34+ OP_NAME MoeInitRoutingV4
35+ OPTIONS --cce-auto-sync=on
36+ -Wno-deprecated-declarations
37+ -Werror
38+ )
39+ endif()
40+endif()
41+ 
42+if(NOT BUILD_OPS_RTY_KERNEL)
43+ message(STATUS "=== Debug: BUILD is NOT BUILD_OPS_RTY_KERNEL")
44+ add_modules_sources(OPTYPE moe_init_routing_v4 ACLNNTYPE aclnn_exclude)
45+endif()
@@ -0,0 +1,13 @@
1+; 该文件主要影响 opc 工具 编译二进制kernel时, --simplified_key_mode 选项中填写的值,格式如下所示:
2+; [某算子]
3+; default=xx
4+; ascendxx=xx
5+; 其中,default为默认mode,ascnedxx为可选mode,如果不同芯片有差异化要求时,需要配置;
6+; 1)如果没有配置:非ascendC算子继续按空处理,即opc编译命令中不添加 --simplified_key_mode 选项,AscendC算子按照 simplified_key_mode=0 处理
7+; 2)如果仅有default配置:各个版本按default配置
8+; 3)如果仅有某些平台的配置,没有default配置:对应平台的按照配置的值传递,非对应平台的:非AscendC算子继续按空处理,AscendC算子按照 simplified_key_mode=0 处理
9+; 4)如果default配置和平台配置都有:对应平台的使用平台的配置,非对应的平台的以default值配置。
10+; 5)对于自定义simplified key的情况,需要在binary_simplified_key_mode.ini 文件中显式配置为None,不传入 --simplified_key_mode 选项,由opc工具和FE框架自行判断使用何种模式
11+; 6)是否是AscendC算子,由 ops/build-in/tbe/op_info_cfg/parser/ascendc_config.json 中配置的算子名字和对于的平台决定
12+[MoeInitRoutingV4]
13+default=0
@@ -0,0 +1,226 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file moe_init_routing_v4_def.cpp
13+ * \brief
14+ */
15+#include "register/op_def_registry.h"
16+ 
17+namespace ops {
18+class MoeInitRoutingV4 : public OpDef {
19+public:
20+ explicit MoeInitRoutingV4(const char *name) : OpDef(name)
21+ {
22+ this->Input("x")
23+ .ParamType(REQUIRED)
24+ .DataType({ge::DT_INT8, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16,
25+ ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_BF16, ge::DT_HIFLOAT8,
26+ ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT16,
27+ ge::DT_BF16, ge::DT_FLOAT4_E2M1, ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16,
28+ ge::DT_FLOAT16, ge::DT_BF16})
29+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
30+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
31+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
32+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
33+ ge::FORMAT_ND})
34+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
35+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
36+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
37+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
38+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
39+ .AutoContiguous();
40+ this->Input("expert_idx")
41+ .ParamType(REQUIRED)
42+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32,
43+ ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32,
44+ ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32,
45+ ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
46+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
47+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
48+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
49+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
50+ ge::FORMAT_ND})
51+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
52+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
53+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
54+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
55+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
56+ .AutoContiguous();
57+ this->Input("scale")
58+ .ParamType(OPTIONAL)
59+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
60+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
61+ ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT8_E8M0,
62+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
63+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
64+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
65+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
66+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
67+ ge::FORMAT_ND})
68+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
69+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
70+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
71+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
72+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
73+ .AutoContiguous();
74+ this->Input("offset")
75+ .ParamType(OPTIONAL)
76+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
77+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
78+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
79+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
80+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
81+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
82+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
83+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
84+ ge::FORMAT_ND})
85+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
86+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
87+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
88+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
89+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
90+ .AutoContiguous();
91+ this->Input("active_num")
92+ .ParamType(OPTIONAL)
93+ .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64,
94+ ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64,
95+ ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64,
96+ ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64})
97+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
98+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
99+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
100+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
101+ ge::FORMAT_ND})
102+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
103+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
104+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
105+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
106+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
107+ .AutoContiguous();
108+ this->Input("topk_weight")
109+ .ParamType(OPTIONAL)
110+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
111+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
112+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
113+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
114+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
115+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
116+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
117+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
118+ ge::FORMAT_ND})
119+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
120+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
121+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
122+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
123+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
124+ .AutoContiguous();
125+ this->Output("expanded_x")
126+ .ParamType(REQUIRED)
127+ .DataType({ge::DT_INT8, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8,
128+ ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8,
129+ ge::DT_HIFLOAT8, ge::DT_HIFLOAT8, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT4_E2M1,
130+ ge::DT_FLOAT4_E2M1, ge::DT_FLOAT4_E2M1, ge::DT_INT4, ge::DT_INT4, ge::DT_FLOAT8_E5M2,
131+ ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN})
132+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
133+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
134+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
135+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
136+ ge::FORMAT_ND})
137+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
138+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
139+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
140+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
141+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
142+ this->Output("expanded_row_idx")
143+ .ParamType(REQUIRED)
144+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32,
145+ ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32,
146+ ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32,
147+ ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
148+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
149+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
150+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
151+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
152+ ge::FORMAT_ND})
153+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
154+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
155+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
156+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
157+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
158+ this->Output("expert_tokens_count_or_cumsum")
159+ .ParamType(REQUIRED)
160+ .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64,
161+ ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64,
162+ ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64,
163+ ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64})
164+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
165+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
166+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
167+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
168+ ge::FORMAT_ND})
169+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
170+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
171+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
172+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
173+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
174+ this->Output("expanded_scale")
175+ .ParamType(REQUIRED)
176+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
177+ ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT,
178+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0,
179+ ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
180+ ge::DT_FLOAT, ge::DT_FLOAT})
181+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
182+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
183+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
184+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
185+ ge::FORMAT_ND})
186+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
187+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
188+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
189+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
190+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
191+ this->Output("expanded_topk_weight")
192+ .ParamType(OPTIONAL)
193+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
194+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
195+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT,
196+ ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
197+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
198+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
199+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
200+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
201+ ge::FORMAT_ND})
202+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
203+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
204+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
205+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND,
206+ ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
207+ this->Attr("expert_capacity").AttrType(OPTIONAL).Int(-1);
208+ this->Attr("expert_num").AttrType(OPTIONAL).Int(-1);
209+ this->Attr("drop_pad_mode").AttrType(OPTIONAL).Int(0);
210+ this->Attr("expert_tokens_num_type").AttrType(OPTIONAL).Int(0);
211+ this->Attr("expert_tokens_num_flag").AttrType(OPTIONAL).Bool(false);
212+ this->Attr("quant_mode").AttrType(OPTIONAL).Int(-1);
213+ this->Attr("active_expert_range").AttrType(OPTIONAL).ListInt({});
214+ this->Attr("row_idx_type").AttrType(OPTIONAL).Int(0);
215+ 
216+ OpAICoreConfig regbaseCfg;
217+ regbaseCfg.DynamicCompileStaticFlag(true)
218+ .DynamicRankSupportFlag(true)
219+ .DynamicShapeSupportFlag(true)
220+ .ExtendCfgInfo("opFile.value", "moe_init_routing_v4_apt");
221+ this->AICore().AddConfig("ascend950", regbaseCfg);
222+ }
223+};
224+ 
225+OP_ADD(MoeInitRoutingV4);
226+} // namespace ops
@@ -0,0 +1,155 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file moe_init_routing_v4_tiling_arch35.cpp
13+ * \brief
14+ */
15+#include "moe_init_routing_v4_tiling_arch35.h"
16+#include "../../moe_init_routing_v3/op_host/moe_init_routing_v3_tiling_arch35.h"
17+#include "../../moe_init_routing_v3/op_kernel/arch35/moe_init_routing_v3_arch35_tiling_def.h"
18+#include "register/op_def_registry.h"
19+#include "log/log.h"
20+ 
21+namespace optiling {
22+using Ops::Transformer::OpTiling::TilingBaseClass;
23+ 
24+class MoeInitRoutingV4TilingArch35 : public MoeInitRoutingV3TilingArch35 {
25+public:
26+ explicit MoeInitRoutingV4TilingArch35(gert::TilingContext *context)
27+ : MoeInitRoutingV3TilingArch35(context)
28+ {
29+ }
30+ ~MoeInitRoutingV4TilingArch35() override = default;
31+ 
32+protected:
33+ bool IsCapable() override
34+ {
35+ // V4 仅在 def.cpp 注册了 ascend950 配置,框架保证只有 950 才会匹配到此算子,无需再校验 SoC 版本。
36+ return true;
37+ }
38+ 
39+ ge::graphStatus GetInputAttrsInfo() override
40+ {
41+ OP_LOGD(context_, "Entered MoeInitRoutingV4TilingArch35::GetInputAttrsInfo()");
42+ 
43+ // 当前阶段不读取 active_num 输入的值,activeNum_ 设为 -1,
44+ // 后续 CheckSetEmptyTensor 会将其归一化为 totalLength_(n*k)。
45+ // 未来动态语义阶段需通过 InputsDataDependency + GetInputTensor 读取实际值。
46+ activeNum_ = -1LL;
47+ 
48+ auto attrsPtr = context_->GetAttrs();
49+ OP_CHECK_NULL_WITH_CONTEXT(context_, attrsPtr);
50+ 
51+ MIRV3_CHECK_GE_RET(GetInputAttr<int64_t>(expertCapacity_, attrsPtr, V4_ATTR_EXPERT_CAPACITY_INDEX));
52+ OP_LOGD(context_, "Get input attr expertCapacity = %ld.", expertCapacity_);
53+ MIRV3_CHECK_GE_RET(GetInputAttr<int64_t>(expertNum_, attrsPtr, V4_ATTR_EXPERT_NUM_INDEX));
54+ OP_LOGD(context_, "Get input attr expertNum = %ld.", expertNum_);
55+ MIRV3_CHECK_GE_RET(GetInputAttr<int64_t>(dropPadMode_, attrsPtr, V4_ATTR_DROP_PAD_MODE_INDEX));
56+ OP_LOGD(context_, "Get input attr dropPadMode = %ld.", dropPadMode_);
57+ MIRV3_CHECK_GE_RET(
58+ GetInputAttr<int64_t>(expertTokensNumType_, attrsPtr, V4_ATTR_EXPERT_TOKEN_NUM_TYPE_INDEX));
59+ OP_LOGD(context_, "Get input attr expertTokensNumType = %ld.", expertTokensNumType_);
60+ MIRV3_CHECK_GE_RET(GetInputAttr<bool>(expertTokensNumFlag_, attrsPtr, V4_ATTR_EXPERT_TOKEN_NUM_FLAG_INDEX));
61+ OP_LOGD(context_, "Get input attr expertTokensNumFlag = %d.", expertTokensNumFlag_);
62+ MIRV3_CHECK_GE_RET(GetInputAttr<int64_t>(quantMode_, attrsPtr, V4_ATTR_QUANT_MODE_INDEX));
63+ OP_LOGD(context_, "Get input attr quantMode = %ld.", quantMode_);
64+ const auto *aerPtr = attrsPtr->GetAttrPointer<gert::ContinuousVector>(V4_ATTR_EXPERT_RANGE_INDEX);
65+ OP_CHECK_NULL_WITH_CONTEXT(context_, aerPtr);
66+ int64_t aerLen = aerPtr->GetSize();
67+ OP_CHECK_IF(aerLen != 2,
68+ OP_LOGE_WITH_INVALID_ATTR_SIZE(context_->GetNodeName(), "active_expert_range",
69+ std::to_string(aerLen), "2"),
70+ return ge::GRAPH_FAILED);
71+ const int64_t *aerList = reinterpret_cast<const int64_t *>(aerPtr->GetData());
72+ expertStart_ = aerList[0];
73+ expertEnd_ = aerList[1];
74+ OP_LOGD(context_, "Extracted input attrs expertStart = %ld, expertEnd = %ld.", expertStart_, expertEnd_);
75+ MIRV3_CHECK_GE_RET(GetInputAttr<int64_t>(rowIdxType_, attrsPtr, V4_ATTR_ROW_IDX_TYPE_INDEX));
76+ OP_LOGD(context_, "Get input attr rowIdxType = %ld.", rowIdxType_);
77+ 
78+ return ge::GRAPH_SUCCESS;
79+ }
80+ 
81+ ge::graphStatus GetInputTensorsInfo() override
82+ {
83+ OP_LOGD(context_, "Entered MoeInitRoutingV4TilingArch35::GetInputTensorsInfo()");
84+ 
85+ MIRV3_CHECK_GE_RET(GetTensorShapeDtype<true>(xShape_, xDtype_, V4_INPUT_X_INDEX));
86+ inputXDtypeSize_ = static_cast<int64_t>(ge::GetSizeByDataType(xDtype_));
87+ inputXDtypeSize_ = (inputXDtypeSize_ > NUM_THOUSAND) ? 1 : inputXDtypeSize_;
88+ MIRV3_CHECK_GE_RET(GetTensorShapeDtype<true>(expertIdxShape_, expertIdxDtype_, V4_INPUT_EXPERT_IDX_INDEX));
89+ MIRV3_CHECK_GE_RET(
90+ GetOptionalInputShapeDtype(scaleShape_, scaleDtype_, isInputScale_, V4_INPUT_SCALE_INDEX));
91+ tilingDataPtr_->isInputScale = isInputScale_;
92+ if (isInputScale_) {
93+ inputScaleDTypeSize_ = static_cast<int64_t>(ge::GetSizeByDataType(scaleDtype_));
94+ }
95+ MIRV3_CHECK_GE_RET(
96+ GetOptionalInputShapeDtype(offsetShape_, offsetDtype_, isInputOffset_, V4_INPUT_OFFSET_INDEX));
97+ tilingDataPtr_->isInputOffset = isInputOffset_;
98+ gert::Shape activeNumShape;
99+ ge::DataType activeNumDtype;
100+ MIRV3_CHECK_GE_RET(
101+ GetOptionalInputShapeDtype(activeNumShape, activeNumDtype, isInputActiveNum_, V4_INPUT_ACTIVE_NUM_INDEX));
102+ if (isInputActiveNum_) {
103+ OP_CHECK_IF(activeNumDtype != ge::DT_INT64,
104+ OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "active_num",
105+ Ops::Base::ToString(activeNumDtype), "DT_INT64"),
106+ return ge::GRAPH_FAILED);
107+ auto activeNumRank = static_cast<int64_t>(activeNumShape.GetDimNum());
108+ OP_CHECK_IF(activeNumRank != 0 && !(activeNumRank == 1 && activeNumShape.GetDim(0) == 1),
109+ OP_LOGE_FOR_INVALID_SHAPE(context_->GetNodeName(), "active_num",
110+ Ops::Base::ToString(activeNumShape), "() or (1,)"),
111+ return ge::GRAPH_FAILED);
112+ }
113+ MIRV3_CHECK_GE_RET(GetOptionalInputShapeDtype(topkWeightShape_, topkWeightDtype_, isInputTopkWeight_,
114+ V4_INPUT_TOPK_WEIGHT_INDEX));
115+ tilingDataPtr_->isInputTopkWeight = isInputTopkWeight_;
116+ OP_LOGD(context_, "Got optional input topk_weight: isInputTopkWeight = %ld.", isInputTopkWeight_);
117+ 
118+ return ge::GRAPH_SUCCESS;
119+ }
120+ 
121+ ge::graphStatus GetOutputTensorsInfo() override
122+ {
123+ OP_LOGD(context_, "Entered MoeInitRoutingV4TilingArch35::GetOutputTensorsInfo()");
124+ 
125+ MIRV3_CHECK_GE_RET(
126+ GetTensorShapeDtype<false>(expandedXShape_, expandedXDtype_, V4_OUTPUT_EXPANDED_X_INDEX));
127+ MIRV3_CHECK_GE_RET(GetTensorShapeDtype<false>(expandedRowIdxShape_, expandedRowIdxDtype_,
128+ V4_OUTPUT_EXPANDED_ROW_IDX_INDEX));
129+ MIRV3_CHECK_GE_RET(GetTensorShapeDtype<false>(expertTokensCountOrCumsumShape_,
130+ expertTokensCountOrCumsumDtype_,
131+ V4_OUTPUT_EXPERT_TOKENS_COUNT_INDEX));
132+ MIRV3_CHECK_GE_RET(
133+ GetTensorShapeDtype<false>(expandedScaleShape_, expandedScaleDtype_, V4_OUTPUT_EXPANDED_SCALE_INDEX));
134+ auto expandedTopkWeightOutShapePtr = context_->GetOutputShape(V4_OUTPUT_EXPANDED_TOPK_WEIGHT_INDEX);
135+ if (expandedTopkWeightOutShapePtr != nullptr &&
136+ expandedTopkWeightOutShapePtr->GetStorageShape().GetShapeSize() > 0) {
137+ isOutputExpandedTopkWeight_ = 1;
138+ MIRV3_CHECK_GE_RET(GetTensorShapeDtype<false>(expandedTopkWeightShape_, expandedTopkWeightDtype_,
139+ V4_OUTPUT_EXPANDED_TOPK_WEIGHT_INDEX));
140+ } else {
141+ isOutputExpandedTopkWeight_ = 0;
142+ }
143+ OP_LOGD(context_, "Got optional output expanded_topk_weight: isOutputExpandedTopkWeight = %ld.",
144+ isOutputExpandedTopkWeight_);
145+ 
146+ return ge::GRAPH_SUCCESS;
147+ }
148+ 
149+private:
150+ int64_t isInputActiveNum_ = 0;
151+};
152+ 
153+REGISTER_OPS_TILING_TEMPLATE(MoeInitRoutingV4, MoeInitRoutingV4TilingArch35, 1000);
154+ 
155+} // namespace optiling
@@ -0,0 +1,44 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file moe_init_routing_v4_tiling_arch35.h
13+ * \brief
14+ */
15+#ifndef MOE_INIT_ROUTING_V4_TILING_ARCH35_H_
16+#define MOE_INIT_ROUTING_V4_TILING_ARCH35_H_
17+ 
18+#include "../../moe_init_routing_v3/op_host/moe_init_routing_v3_tiling_arch35.h"
19+ 
20+namespace optiling {
21+constexpr int64_t V4_INPUT_X_INDEX = 0LL;
22+constexpr int64_t V4_INPUT_EXPERT_IDX_INDEX = 1LL;
23+constexpr int64_t V4_INPUT_SCALE_INDEX = 2LL;
24+constexpr int64_t V4_INPUT_OFFSET_INDEX = 3LL;
25+constexpr int64_t V4_INPUT_ACTIVE_NUM_INDEX = 4LL;
26+constexpr int64_t V4_INPUT_TOPK_WEIGHT_INDEX = 5LL;
27+ 
28+constexpr int64_t V4_ATTR_EXPERT_CAPACITY_INDEX = 0LL;
29+constexpr int64_t V4_ATTR_EXPERT_NUM_INDEX = 1LL;
30+constexpr int64_t V4_ATTR_DROP_PAD_MODE_INDEX = 2LL;
31+constexpr int64_t V4_ATTR_EXPERT_TOKEN_NUM_TYPE_INDEX = 3LL;
32+constexpr int64_t V4_ATTR_EXPERT_TOKEN_NUM_FLAG_INDEX = 4LL;
33+constexpr int64_t V4_ATTR_QUANT_MODE_INDEX = 5LL;
34+constexpr int64_t V4_ATTR_EXPERT_RANGE_INDEX = 6LL;
35+constexpr int64_t V4_ATTR_ROW_IDX_TYPE_INDEX = 7LL;
36+ 
37+constexpr int64_t V4_OUTPUT_EXPANDED_X_INDEX = 0LL;
38+constexpr int64_t V4_OUTPUT_EXPANDED_ROW_IDX_INDEX = 1LL;
39+constexpr int64_t V4_OUTPUT_EXPERT_TOKENS_COUNT_INDEX = 2LL;
40+constexpr int64_t V4_OUTPUT_EXPANDED_SCALE_INDEX = 3LL;
41+constexpr int64_t V4_OUTPUT_EXPANDED_TOPK_WEIGHT_INDEX = 4LL;
42+}
43+ 
44+#endif
@@ -0,0 +1,59 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file moe_init_routing_v4_tiling_base.cpp
13+ * \brief
14+ */
15+#include "moe_init_routing_v4_tiling_arch35.h"
16+#include "register/op_def_registry.h"
17+#include "log/log.h"
18+ 
19+using Ops::Transformer::OpTiling::TilingRegistry;
20+ 
21+namespace optiling {
22+static ge::graphStatus TilingForMoeInitRoutingV4(gert::TilingContext *context)
23+{
24+ return TilingRegistry::GetInstance().DoTilingImpl(context);
25+}
26+ 
27+static ge::graphStatus TilingPrepareForMoeInitRoutingV4(gert::TilingParseContext *context)
28+{
29+ OP_LOGD(context, "TilingPrepareForMoeInitRoutingV4 enter.");
30+ 
31+ auto compileInfo = context->GetCompiledInfo<MoeInitRoutingV3CompileInfo>();
32+ OP_CHECK_NULL_WITH_CONTEXT(context, compileInfo);
33+ auto platformInfo = context->GetPlatformInfo();
34+ OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo);
35+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
36+ compileInfo->aivNum = ascendcPlatform.GetCoreNumAiv();
37+ OP_CHECK_IF((compileInfo->aivNum <= 0),
38+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context->GetNodeName(), "compileInfo->aivNum",
39+ std::to_string(compileInfo->aivNum),
40+ "failed to get core num"),
41+ return ge::GRAPH_FAILED);
42+ 
43+ uint64_t ubSize;
44+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
45+ compileInfo->ubSize = static_cast<int64_t>(ubSize);
46+ compileInfo->socVersion = ascendcPlatform.GetSocVersion();
47+ OP_CHECK_IF((compileInfo->ubSize <= 0),
48+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context->GetNodeName(), "ubSize",
49+ std::to_string(compileInfo->ubSize),
50+ "failed to get ub size"),
51+ return ge::GRAPH_FAILED);
52+ 
53+ return ge::GRAPH_SUCCESS;
54+}
55+ 
56+IMPL_OP_OPTILING(MoeInitRoutingV4)
57+ .Tiling(TilingForMoeInitRoutingV4)
58+ .TilingParse<MoeInitRoutingV3CompileInfo>(TilingPrepareForMoeInitRoutingV4);
59+} // namespace optiling
@@ -0,0 +1,234 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <algorithm>
12+#include <tuple>
13+#include <cstddef>
14+#include "opdev/make_op_executor.h"
15+#include "aclnn_kernels/contiguous.h"
16+#include "opdev/tensor_view_utils.h"
17+#include "aclnn_kernels/common/op_error_check.h"
18+#include "opdev/op_log.h"
19+#include "aclnn_kernels/cast.h"
20+#include "opdev/common_types.h"
21+#include "moe_init_routing_v4.h"
22+#include "aclnn_moe_init_routing_v4.h"
23+#include "aclnn_util.h"
24+ 
25+using namespace op;
26+ 
27+#ifdef __cplusplus
28+extern "C" {
29+#endif
30+ 
31+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_X_REGBASE = {
32+ DataType::DT_FLOAT16, DataType::DT_BF16, DataType::DT_FLOAT, DataType::DT_INT8,
33+ DataType::DT_HIFLOAT8, DataType::DT_FLOAT8_E5M2, DataType::DT_FLOAT8_E4M3FN, DataType::DT_FLOAT4_E2M1};
34+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_EXPERT_IDX = {DataType::DT_INT32};
35+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_SCALE_REGBASE = {DataType::DT_FLOAT,
36+ DataType::DT_FLOAT8_E8M0};
37+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_OFFSET = {DataType::DT_FLOAT};
38+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_ACTIVE_NUM = {DataType::DT_INT64};
39+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_TOPK_WEIGHT = {DataType::DT_FLOAT};
40+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_EXPANDED_X_OUT_REGBASE = {
41+ DataType::DT_FLOAT16, DataType::DT_BF16, DataType::DT_FLOAT,
42+ DataType::DT_INT8, DataType::DT_HIFLOAT8, DataType::DT_FLOAT8_E5M2,
43+ DataType::DT_FLOAT8_E4M3FN, DataType::DT_FLOAT4_E2M1, DataType::DT_INT4};
44+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_EXPANDED_ROW_IDX_OUT = {DataType::DT_INT32};
45+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_EXPERT_TOKENS_COUNT_OR_CUMSUMOUT = {DataType::DT_INT64};
46+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_EXPANDED_SCALE_OUT_REGBASE = {
47+ DataType::DT_FLOAT, DataType::DT_FLOAT8_E8M0};
48+static const std::initializer_list<DataType> DTYPE_SUPPORT_LIST_EXPANDED_TOPK_WEIGHT_OUT = {DataType::DT_FLOAT};
49+ 
50+static inline bool CheckNotNull(const aclTensor *x, const aclTensor *expertIdx, const aclTensor *expandedXOut,
51+ const aclTensor *expandedRowIdxOut, const aclTensor *expertTokensCountOrCumsumOut,
52+ const aclTensor *expandedScaleOut)
53+{
54+ OP_CHECK_NULL(x, return false);
55+ OP_CHECK_NULL(expertIdx, return false);
56+ OP_CHECK_NULL(expandedXOut, return false);
57+ OP_CHECK_NULL(expandedRowIdxOut, return false);
58+ OP_CHECK_NULL(expertTokensCountOrCumsumOut, return false);
59+ OP_CHECK_NULL(expandedScaleOut, return false);
60+ 
61+ return true;
62+}
63+ 
64+static inline bool CheckDtypeValidRegbase(const aclTensor *x, const aclTensor *expertIdx,
65+ const aclTensor *scaleOptional, const aclTensor *offsetOptional,
66+ const aclTensor *activeNumOptional, const aclTensor *topkWeightOptional,
67+ const aclTensor *expandedXOut, const aclTensor *expandedRowIdxOut,
68+ const aclTensor *expertTokensCountOrCumsumOut,
69+ const aclTensor *expandedScaleOut,
70+ const aclTensor *expandedTopkWeightOut)
71+{
72+ if (x != nullptr && x->GetViewShape().GetShapeSize() != 0) {
73+ OP_CHECK_DTYPE_NOT_SUPPORT(x, DTYPE_SUPPORT_LIST_X_REGBASE, return false);
74+ }
75+ if (expertIdx != nullptr && expertIdx->GetViewShape().GetShapeSize() != 0) {
76+ OP_CHECK_DTYPE_NOT_SUPPORT(expertIdx, DTYPE_SUPPORT_LIST_EXPERT_IDX, return false);
77+ }
78+ if (scaleOptional != nullptr && scaleOptional->GetViewShape().GetShapeSize() != 0) {
79+ OP_CHECK_DTYPE_NOT_SUPPORT(scaleOptional, DTYPE_SUPPORT_LIST_SCALE_REGBASE, return false);
80+ }
81+ if (offsetOptional != nullptr && offsetOptional->GetViewShape().GetShapeSize() != 0) {
82+ OP_CHECK_DTYPE_NOT_SUPPORT(offsetOptional, DTYPE_SUPPORT_LIST_OFFSET, return false);
83+ }
84+ if (activeNumOptional != nullptr && activeNumOptional->GetViewShape().GetShapeSize() != 0) {
85+ OP_CHECK_DTYPE_NOT_SUPPORT(activeNumOptional, DTYPE_SUPPORT_LIST_ACTIVE_NUM, return false);
86+ }
87+ if (topkWeightOptional != nullptr && topkWeightOptional->GetViewShape().GetShapeSize() != 0) {
88+ OP_CHECK_DTYPE_NOT_SUPPORT(topkWeightOptional, DTYPE_SUPPORT_LIST_TOPK_WEIGHT, return false);
89+ }
90+ if (expandedXOut != nullptr && expandedXOut->GetViewShape().GetShapeSize() != 0) {
91+ OP_CHECK_DTYPE_NOT_SUPPORT(expandedXOut, DTYPE_SUPPORT_LIST_EXPANDED_X_OUT_REGBASE, return false);
92+ }
93+ if (expandedRowIdxOut != nullptr && expandedRowIdxOut->GetViewShape().GetShapeSize() != 0) {
94+ OP_CHECK_DTYPE_NOT_SUPPORT(expandedRowIdxOut, DTYPE_SUPPORT_LIST_EXPANDED_ROW_IDX_OUT, return false);
95+ }
96+ if (expertTokensCountOrCumsumOut != nullptr && expertTokensCountOrCumsumOut->GetViewShape().GetShapeSize() != 0) {
97+ OP_CHECK_DTYPE_NOT_SUPPORT(expertTokensCountOrCumsumOut, DTYPE_SUPPORT_LIST_EXPERT_TOKENS_COUNT_OR_CUMSUMOUT,
98+ return false);
99+ }
100+ if (expandedScaleOut != nullptr && expandedScaleOut->GetViewShape().GetShapeSize() != 0) {
101+ OP_CHECK_DTYPE_NOT_SUPPORT(expandedScaleOut, DTYPE_SUPPORT_LIST_EXPANDED_SCALE_OUT_REGBASE, return false);
102+ }
103+ if (expandedTopkWeightOut != nullptr && expandedTopkWeightOut->GetViewShape().GetShapeSize() != 0) {
104+ OP_CHECK_DTYPE_NOT_SUPPORT(expandedTopkWeightOut, DTYPE_SUPPORT_LIST_EXPANDED_TOPK_WEIGHT_OUT, return false);
105+ }
106+ return true;
107+}
108+ 
109+ACLNN_API aclnnStatus aclnnMoeInitRoutingV4GetWorkspaceSize(
110+ const aclTensor *x, const aclTensor *expertIdx,
111+ const aclTensor *scaleOptional, const aclTensor *offsetOptional,
112+ const aclTensor *activeNumOptional, const aclTensor *topkWeightOptional,
113+ int64_t expertCapacity, int64_t expertNum, int64_t dropPadMode,
114+ int64_t expertTokensNumType, bool expertTokensNumFlag,
115+ int64_t quantMode, const aclIntArray *activeExpertRangeOptional,
116+ int64_t rowIdxType, const aclTensor *expandedXOut,
117+ const aclTensor *expandedRowIdxOut,
118+ const aclTensor *expertTokensCountOrCumsumOut,
119+ const aclTensor *expandedScaleOut,
120+ const aclTensor *expandedTopkWeightOut,
121+ uint64_t *workspaceSize, aclOpExecutor **executor)
122+{
123+ L2_DFX_PHASE_1(aclnnMoeInitRoutingV4,
124+ DFX_IN(x, expertIdx, scaleOptional, offsetOptional, activeNumOptional,
125+ topkWeightOptional, expertCapacity, expertNum, dropPadMode,
126+ expertTokensNumType, expertTokensNumFlag, quantMode,
127+ activeExpertRangeOptional, rowIdxType),
128+ DFX_OUT(expandedXOut, expandedRowIdxOut,
129+ expertTokensCountOrCumsumOut, expandedScaleOut,
130+ expandedTopkWeightOut));
131+ 
132+ if ((topkWeightOptional != nullptr && expandedTopkWeightOut == nullptr) ||
133+ (topkWeightOptional == nullptr && expandedTopkWeightOut != nullptr)) {
134+ OP_LOGE(ACLNN_ERR_PARAM_INVALID, "topk_weight and expanded_topk_weight must be both present or both absent.");
135+ return ACLNN_ERR_PARAM_INVALID;
136+ }
137+ 
138+ auto ret =
139+ CheckNotNull(x, expertIdx, expandedXOut, expandedRowIdxOut, expertTokensCountOrCumsumOut, expandedScaleOut);
140+ 
141+ CHECK_RET(ret, ACLNN_ERR_PARAM_NULLPTR);
142+ 
143+ auto uniqueExecutor = CREATE_EXECUTOR();
144+ CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
145+ 
146+ CHECK_RET(CheckDtypeValidRegbase(x, expertIdx, scaleOptional, offsetOptional,
147+ activeNumOptional, topkWeightOptional,
148+ expandedXOut, expandedRowIdxOut,
149+ expertTokensCountOrCumsumOut, expandedScaleOut, expandedTopkWeightOut),
150+ ACLNN_ERR_PARAM_INVALID);
151+ 
152+ auto xContiguous = l0op::Contiguous(x, uniqueExecutor.get());
153+ CHECK_RET(xContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
154+ auto expertIdxContiguous = l0op::Contiguous(expertIdx, uniqueExecutor.get());
155+ CHECK_RET(expertIdxContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
156+ 
157+ const aclTensor *scaleContiguous = nullptr;
158+ const aclTensor *offsetContiguous = nullptr;
159+ if (scaleOptional != nullptr) {
160+ scaleContiguous = l0op::Contiguous(scaleOptional, uniqueExecutor.get());
161+ CHECK_RET(scaleContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
162+ }
163+ 
164+ if (offsetOptional != nullptr) {
165+ offsetContiguous = l0op::Contiguous(offsetOptional, uniqueExecutor.get());
166+ CHECK_RET(offsetContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
167+ }
168+ 
169+ const aclTensor *activeNumContiguous = nullptr;
170+ if (activeNumOptional != nullptr) {
171+ activeNumContiguous = l0op::Contiguous(activeNumOptional, uniqueExecutor.get());
172+ CHECK_RET(activeNumContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
173+ }
174+ 
175+ const aclTensor *topkWeightContiguous = nullptr;
176+ if (topkWeightOptional != nullptr) {
177+ topkWeightContiguous = l0op::Contiguous(topkWeightOptional, uniqueExecutor.get());
178+ CHECK_RET(topkWeightContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
179+ }
180+ 
181+ auto routingResult =
182+ std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*, aclTensor*>(
183+ nullptr, nullptr, nullptr, nullptr, nullptr);
184+ routingResult = l0op::MoeInitRoutingV4(
185+ xContiguous, expertIdxContiguous, scaleContiguous, offsetContiguous,
186+ activeNumContiguous, topkWeightContiguous,
187+ expertCapacity, expertNum, dropPadMode,
188+ expertTokensNumType, expertTokensNumFlag,
189+ quantMode, activeExpertRangeOptional, rowIdxType, expandedXOut,
190+ expandedRowIdxOut, expertTokensCountOrCumsumOut, expandedScaleOut,
191+ expandedTopkWeightOut, uniqueExecutor.get());
192+ auto [expandedXOut_, expandedRowIdxOut_, expertTokensCountOrCumsumOut_,
193+ expandedScaleOut_, expandedTopkWeightOut_] = routingResult;
194+ bool hasNullptr = (expandedXOut_ == nullptr) || (expandedRowIdxOut_ == nullptr) ||
195+ (expertTokensCountOrCumsumOut_ == nullptr) || (expandedScaleOut_ == nullptr);
196+ 
197+ CHECK_RET(hasNullptr != true, ACLNN_ERR_INNER_NULLPTR);
198+ 
199+ if (topkWeightOptional != nullptr) {
200+ CHECK_RET(expandedTopkWeightOut_ != nullptr, ACLNN_ERR_INNER_NULLPTR);
201+ }
202+ 
203+ auto viewCopyExpandedXOutResult = l0op::ViewCopy(expandedXOut_, expandedXOut, uniqueExecutor.get());
204+ CHECK_RET(viewCopyExpandedXOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR);
205+ auto viewCopyExpandedRowIdxOutResult = l0op::ViewCopy(expandedRowIdxOut_, expandedRowIdxOut, uniqueExecutor.get());
206+ CHECK_RET(viewCopyExpandedRowIdxOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR);
207+ 
208+ auto viewCopyExpertTokensCountOrCumsumOutResult =
209+ l0op::ViewCopy(expertTokensCountOrCumsumOut_, expertTokensCountOrCumsumOut, uniqueExecutor.get());
210+ CHECK_RET(viewCopyExpertTokensCountOrCumsumOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR);
211+ 
212+ auto viewCopyExpandedScaleOutResult = l0op::ViewCopy(expandedScaleOut_, expandedScaleOut, uniqueExecutor.get());
213+ CHECK_RET(viewCopyExpandedScaleOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR);
214+ 
215+ if (expandedTopkWeightOut != nullptr && expandedTopkWeightOut_ != nullptr) {
216+ auto viewCopyExpandedTopkWeightOutResult =
217+ l0op::ViewCopy(expandedTopkWeightOut_, expandedTopkWeightOut, uniqueExecutor.get());
218+ CHECK_RET(viewCopyExpandedTopkWeightOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR);
219+ }
220+ 
221+ *workspaceSize = uniqueExecutor->GetWorkspaceSize();
222+ uniqueExecutor.ReleaseTo(executor);
223+ return ACLNN_SUCCESS;
224+}
225+ACLNN_API aclnnStatus aclnnMoeInitRoutingV4(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor,
226+ aclrtStream stream)
227+{
228+ L2_DFX_PHASE_2(aclnnMoeInitRoutingV4);
229+ return CommonOpExecutorRun(workspace, workspaceSize, executor, stream);
230+}
231+ 
232+#ifdef __cplusplus
233+}
234+#endif
@@ -0,0 +1,68 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef OP_API_INC_MOE_INIT_ROUTING_V4_H_
12+#define OP_API_INC_MOE_INIT_ROUTING_V4_H_
13+ 
14+#include "aclnn/aclnn_base.h"
15+#include "aclnn_util.h"
16+ 
17+#ifdef __cplusplus
18+extern "C" {
19+#endif
20+ 
21+/**
22+ * @brief aclnnMoeInitRoutingV4的第一段接口,根据具体的计算流程,计算workspace大小。
23+ * @domain aclnn_ops_infer
24+ * @param x,token特征输入,必选参数
25+ * @param expertIdx,每一行特征对应的K个处理专家,必选参数
26+ * @param scaleOptional,用于计算quant结果的scale,可选参数,传nullptr表示不使用scale
27+ * @param offsetOptional,用于计算quant结果的偏移值,可选参数,传nullptr表示不输入
28+ * @param activeNumOptional,表示总的最大处理row数,可选参数,传nullptr表示默认为NUM_ROWS*K
29+ * @param topkWeightOptional,topk专家的路由权重,可选参数,传nullptr表示不输出expandedTopkWeightOut。
30+ * @param expertCapacity,每个专家能够处理的tokens数
31+ * @param expertNum,专家数
32+ * @param dropPadMode,0表示Dropless场景,1表示DropPad场景
33+ * @param expertTokensNumType,0为cumsum模式,1为count模式,2为key_value模式
34+ * @param expertTokensNumFlag,是否输出expertTokensCountOrCumsumOut
35+ * @param quantMode,量化模式
36+ * @param activeExpertRangeOptional,活跃的expert范围[expertStart, expertEnd],左闭右开
37+ * @param rowIdxType,0为gather索引,1为scatter索引
38+ * @param expandedXOut,根据expertIdx进行扩展过的特征,必选参数
39+ * @param expandedRowIdxOut,expandedXOut和x的索引映射关系,必选参数
40+ * @param expertTokensCountOrCumsumOut,每个专家处理的token数量的统计结果,必选参数
41+ * @param expandedScaleOut,量化计算过程中scale的中间值,必选参数
42+ * @param expandedTopkWeightOut,按排序索引重排后的路由权重,可选参数。
43+ * @param workspaceSize,返回需要在Device侧申请的workspace大小
44+ * @param executor,返回op执行器,包含了算子计算流程
45+ * @return ACLNN_SUCCESS表示成功,其他值表示失败
46+ */
47+ACLNN_API aclnnStatus aclnnMoeInitRoutingV4GetWorkspaceSize(
48+ const aclTensor *x, const aclTensor *expertIdx,
49+ const aclTensor *scaleOptional, const aclTensor *offsetOptional,
50+ const aclTensor *activeNumOptional, const aclTensor *topkWeightOptional,
51+ int64_t expertCapacity, int64_t expertNum, int64_t dropPadMode,
52+ int64_t expertTokensNumType, bool expertTokensNumFlag,
53+ int64_t quantMode, const aclIntArray *activeExpertRangeOptional,
54+ int64_t rowIdxType,
55+ const aclTensor *expandedXOut, const aclTensor *expandedRowIdxOut,
56+ const aclTensor *expertTokensCountOrCumsumOut,
57+ const aclTensor *expandedScaleOut, const aclTensor *expandedTopkWeightOut,
58+ uint64_t *workspaceSize, aclOpExecutor **executor);
59+ 
60+/* @brief aclnnMoeInitRoutingV4的第二段接口,用于执行计算。 */
61+ACLNN_API aclnnStatus aclnnMoeInitRoutingV4(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor,
62+ aclrtStream stream);
63+ 
64+#ifdef __cplusplus
65+}
66+#endif
67+ 
68+#endif
@@ -0,0 +1,91 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <tuple>
12+#include "moe_init_routing_v4.h"
13+#include "opdev/make_op_executor.h"
14+#include "opdev/aicpu/aicpu_task.h"
15+#include "opdev/op_def.h"
16+#include "opdev/op_dfx.h"
17+#include "opdev/op_executor.h"
18+#include "opdev/op_log.h"
19+#include "opdev/shape_utils.h"
20+#include "aclnn_kernels/common/op_error_check.h"
21+ 
22+using namespace op;
23+ 
24+namespace l0op {
25+OP_TYPE_REGISTER(MoeInitRoutingV4);
26+ 
27+std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*, aclTensor*>
28+MoeInitRoutingV4(const aclTensor *x, const aclTensor *expertIdx,
29+ const aclTensor *scale, const aclTensor *offset,
30+ const aclTensor *activeNum, const aclTensor *topkWeight,
31+ int64_t expertCapacity, int64_t expertNum, int64_t dropPadMode,
32+ int64_t expertTokensNumType, bool expertTokensNumFlag,
33+ int64_t quantMode, const aclIntArray *activeExpertRange,
34+ int64_t rowIdxType, const aclTensor *expandedX,
35+ const aclTensor *expandedRowIdx,
36+ const aclTensor *expertTokensCountOrCumsum,
37+ const aclTensor *expandedScale,
38+ const aclTensor *expandedTopkWeight,
39+ aclOpExecutor *executor)
40+{
41+ L0_DFX(MoeInitRoutingV4, x, expertIdx, scale, offset, activeNum, topkWeight,
42+ expertCapacity, expertNum, dropPadMode, expertTokensNumType,
43+ expertTokensNumFlag, quantMode, activeExpertRange, rowIdxType,
44+ expandedX, expandedRowIdx, expertTokensCountOrCumsum, expandedScale,
45+ expandedTopkWeight);
46+ 
47+ auto expandedXOut = executor->AllocTensor(expandedX->GetViewShape(), expandedX->GetDataType(),
48+ Format::FORMAT_ND);
49+ auto expandedRowIdxOut = executor->AllocTensor(expandedRowIdx->GetViewShape(), expandedRowIdx->GetDataType(),
50+ Format::FORMAT_ND);
51+ auto expertTokensCountOrCumsumOut = executor->AllocTensor(expertTokensCountOrCumsum->GetViewShape(),
52+ expertTokensCountOrCumsum->GetDataType(),
53+ Format::FORMAT_ND);
54+ auto expandedScaleOut = executor->AllocTensor(expandedScale->GetViewShape(), expandedScale->GetDataType(),
55+ Format::FORMAT_ND);
56+ if (expandedXOut == nullptr || expandedRowIdxOut == nullptr ||
57+ expertTokensCountOrCumsumOut == nullptr || expandedScaleOut == nullptr) {
58+ OP_LOGE(ACLNN_ERR_INNER_NULLPTR,
59+ "alloc expandedXOut or expandedRowIdxOut or "
60+ "expertTokensCountOrCumsumOut or expandedScaleOut tensor failed.");
61+ return std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*, aclTensor*>(
62+ nullptr, nullptr, nullptr, nullptr, nullptr);
63+ }
64+ 
65+ aclTensor* expandedTopkWeightOut = nullptr;
66+ if (expandedTopkWeight != nullptr) {
67+ expandedTopkWeightOut = executor->AllocTensor(expandedTopkWeight->GetViewShape(),
68+ expandedTopkWeight->GetDataType(),
69+ Format::FORMAT_ND);
70+ if (expandedTopkWeightOut == nullptr) {
71+ return std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*, aclTensor*>(
72+ nullptr, nullptr, nullptr, nullptr, nullptr);
73+ }
74+ } else {
75+ op::Shape zeroShape;
76+ zeroShape.AppendDim(0);
77+ expandedTopkWeightOut = executor->AllocTensor(zeroShape, ge::DT_FLOAT, Format::FORMAT_ND);
78+ }
79+ ADD_TO_LAUNCHER_LIST_AICORE(
80+ MoeInitRoutingV4,
81+ OP_INPUT(x, expertIdx, scale, offset, activeNum, topkWeight),
82+ OP_OUTPUT(expandedXOut, expandedRowIdxOut, expertTokensCountOrCumsumOut, expandedScaleOut,
83+ expandedTopkWeightOut),
84+ OP_ATTR(expertCapacity, expertNum, dropPadMode, expertTokensNumType, expertTokensNumFlag,
85+ quantMode, activeExpertRange, rowIdxType));
86+ return std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*, aclTensor*>(
87+ expandedXOut, expandedRowIdxOut, expertTokensCountOrCumsumOut,
88+ expandedScaleOut, expandedTopkWeightOut);
89+}
90+ 
91+} // namespace l0op
@@ -0,0 +1,32 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef OP_API_INC_LEVEL0_MOE_INIT_ROUTING_V4_H
12+#define OP_API_INC_LEVEL0_MOE_INIT_ROUTING_V4_H
13+ 
14+#include <tuple>
15+#include "opdev/op_executor.h"
16+ 
17+namespace l0op {
18+std::tuple<aclTensor*, aclTensor*, aclTensor*, aclTensor*, aclTensor*>
19+MoeInitRoutingV4(const aclTensor *x, const aclTensor *expertIdx,
20+ const aclTensor *scale, const aclTensor *offset,
21+ const aclTensor *activeNum, const aclTensor *topkWeight,
22+ int64_t expertCapacity, int64_t expertNum, int64_t dropPadMode,
23+ int64_t expertTokensNumType, bool expertTokensNumFlag,
24+ int64_t quantMode, const aclIntArray *activeExpertRange,
25+ int64_t rowIdxType, const aclTensor *expandedX,
26+ const aclTensor *expandedRowIdx,
27+ const aclTensor *expertTokensCountOrCumsum,
28+ const aclTensor *expandedScale,
29+ const aclTensor *expandedTopkWeight,
30+ aclOpExecutor *executor);
31+} // namespace l0op
32+#endif // OP_API_INC_LEVEL0_MOE_INIT_ROUTING_V4_H