CANN ops-transformer 的 moe_token_permute 算子:基于 torch_npu 的 MoE Token 重排与 MX 量化实现

发布时间:2026/9/21 2:32:15
CANN ops-transformer 的 moe_token_permute 算子:基于 torch_npu 的 MoE Token 重排与 MX 量化实现
CANN ops-transformer 的 moe_token_permute 算子基于 torch_npu 的 MoE Token 重排与 MX 量化实现【免费下载链接】ops-transformer本项目是CANN提供的transformer类大模型算子库实现网络在NPU上加速计算。项目地址: https://gitcode.com/cann/ops-transformer导读moe_token_permute是 CANN ops-transformer 算子库中面向 MoEMixture of Experts训练/推理场景的核心前置算子它以torch_npu扩展接口的形式提供根据专家索引indices将输入tokens按专家排序并返回排序后的 token 与原始 token 的行映射关系。本文以 moe_token_permute 官方 Torch API 文档 为主体结合 Python 封装层、C 接入层、算子定义与 Kernel 实现完整讲解函数原型、参数语义、返回值 shape 推导、MXFP8/MXFP4 量化模式以及源码级实现原理帮助读者在 NPU 上正确、高效地使用该接口完成 MoE 路由后的 token 重排。功能说明MoE 中 Token 重排的语义在 MoE 模型中Router门控网络会为每个 token 产生一个或多个专家索引随后需要把属于同一专家的 token 聚合到一起才能送入对应的专家网络计算。moe_token_permute正是完成这一步重排的高效算子根据indices将输入tokens扩展每个 token 可按K个索引重复并按照专家索引排序返回排序后的 tokenpermuted_tokens及其与原始 token 的映射关系sorted_indices。算子仓库 READMEmoe_token_permute/README.md中给出了精确的计算公式paddedModefalse时sortedIndicesFirst argSort(indices) sortedIndicesOut argSort(sortedIndicesFirst) permuteTokens[sortedIndicesFirst[i]] tokens[i // topK]即先对展平后的indices做一次稳定的argSort得到按专家分组的行顺序再取该顺序的逆映射作为sorted_indices输出最终按sortedIndicesFirst[i] // topK从原始 token 中取值填入输出。仓库测试资产的 golden 参考实现golden.py用 PyTorch 原语还原了这一过程torch.argsort(expert_idx.reshape(-1), stableTrue)得到排序后的行号expanded_row_idx[sorted_row_idx] torch.arange(...)构造逆映射再通过input_x[selected_indices]完成 token 收集可作为理解算子行为的最小可读参考。值得一提的是indices可以是一维[N]每个 token 对应 1 个专家即 topK1也可以是二维[N, K]每个 token 对应 K 个专家。当K 1时token 会按索引重复最终输出行数等于indices.numel()。产品支持情况根据官方文档该接口在不同产品上的支持情况如下产品是否支持Ascend 950PR / Ascend 950DT支持额外支持 MXFP8/MXFP4 量化输出Atlas A3 训练系列产品 / Atlas A3 推理系列产品支持不支持量化模式Atlas A2 训练系列产品 / Atlas A2 推理系列产品支持不支持量化模式Atlas 200I/500 A2 推理产品不支持Atlas 推理系列产品不支持Atlas 训练系列产品不支持从算子注册配置moe_token_permute_def.cpp可以看到AICore 侧仅注册了ascend910b与ascend910_93两个 AI Core 配置与文档所述 Atlas A2/A3 及 Ascend 950 系列支持范围一致。函数原型与 Python 侧注册接口的完整函数原型如下cann_ops_transformer.ops.moe_token_permute( tokens, indices, num_out_tokensNone, padded_modeFalse, quant_mode-1, ) - (Tensor, Tensor, Tensor)在 Python 侧moe_token_permute.py该接口通过torch.ops.cann_ops_transformer.moe_token_permute分发其自定义算子 schema 为moe_token_permute(Tensor tokens, Tensor indices, int? num_out_tokensNone, bool padded_modeFalse, int quant_mode-1) - (Tensor, Tensor, Tensor)底层 C 封装csrc/moe_token_permute.cpp会完成输入合法性检查、num_out_tokens归一化、量化模式解析非 Ascend 950 一律强制quant_mode-1最终调用aclnnMoeTokenPermuteV2执行。该接口属于cann_ops_transformer扩展包使用前需要安装该包并导入torch_npu。参数说明参数名参数类型可选/必选描述数据类型维度(shape)tokensTensor必选输入 token 特征记 shape 为[N, H]。量化模式仅支持 float16 和 bfloat16。非量化float16、bfloat16、float32Ascend 950 非量化额外支持 int8量化float16、bfloat16[N, H]indicesTensor必选token 对应的专家索引。可以是一维索引也可以表示每个 token 对应 K 个专家。元素个数记为F。int32、int64[N]或[N, K]num_out_tokensint可选控制permuted_tokens的有效输出行数。None或0表示保留全部正数表示最多保留指定行数负数表示从完整结果尾部删除对应行数。默认值为None。int64-padded_modebool可选是否使用 padded 模式。当前仅支持False。默认值为False。bool-quant_modeint可选量化模式-1表示不量化2表示 MXFP8 E5M23表示 MXFP8 E4M3FN9表示 MXFP4 E2M1。默认值为-1。int64-参数细节与产品差异Atlas A3 训练系列产品 / Atlas A3 推理系列产品、Atlas A2 训练系列产品 / Atlas A2 推理系列产品quant_mode仅支持-1即按非量化路径执行。Ascend 950PR / Ascend 950DTquant_mode支持-1 / 2 / 3 / 9取值为9MXFP4时隐藏维H必须为偶数取值为2 / 3 / 9时不支持 autograd即输入tokens不能带有requires_gradTrue。这一差异在 C 侧有明确对应实现csrc/moe_token_permute.cppResolveQuantMode首先通过aclrtGetSocName判断是否 Ascend 950非 950 平台强制回退为-1并检查tokens.requires_grad()与量化模式互斥。num_out_tokens的语义与 Python 封装中的_actual_num_out_tokensmoe_token_permute.py以及 C 侧GetActualNumOutTokenscsrc/moe_token_permute.cpp完全一致num_out_tokens 为 None 或 0有效输出行数 F num_out_tokens 0 有效输出行数 min(num_out_tokens, F) num_out_tokens 0 有效输出行数 max(F num_out_tokens, 0)返回值说明接口固定返回三个 Tensorpermuted_tokens, sorted_indices, expanded_scale记F indices.numel()、H tokens.shape[1]则各量化模式的输出规格如下quant_modepermuted_tokenssorted_indicesexpanded_scale-1shape 为[M, H]dtype 与tokens相同shape 为[F]dtype 为 int32shape 为[0]的空 Tensordtype 为 float322shape 为[M, H]dtype 为 float8_e5m2shape 为[F]dtype 为 int32shape 为[M, AlignUp(CeilDiv(H, 32), 2)]dtype 为 float8_e8m03shape 为[M, H]dtype 为 float8_e4m3fnshape 为[F]dtype 为 int32shape 为[M, AlignUp(CeilDiv(H, 32), 2)]dtype 为 float8_e8m09PyTorch 物理 shape 为[M, H / 2]dtype 为 uint8shape 为[F]dtype 为 int32PyTorch 物理 shape 为[M, CeilDiv(H, 64), 2]dtype 为 uint8其中CeilDiv(a, b) (a b - 1) // b AlignUp(a, b) CeilDiv(a, b) * b各输出含义permuted_tokens根据indices扩展并按专家索引排序后的 token仅该输出与expanded_scale的第一维受num_out_tokens影响。sorted_indicespermuted_tokens与原始tokens的行映射关系长度始终为indices.numel()即不受num_out_tokens截断影响dtype 固定为 int32。expanded_scale量化输出对应的 per-token 分块 scale非量化模式返回空 Tensor。[!NOTE] MXFP4 类型当前通过 uint8 Tensor 承载物理存储。调用 aclnn 接口时permuted_tokens会被解释为ACL_FLOAT4_E2M1expanded_scale会被解释为ACL_FLOAT8_E8M0。因此表中的 uint8 表示 PyTorch 侧的物理存储类型不表示量化数据的逻辑类型。上述 shape 计算逻辑在 Python 侧的 Meta 函数moe_token_permute_metamoe_token_permute.py中有逐字对应的实现例如 MXFP8 的 scale 列数计算为_align_up(_ceil_div(H, 32), 2)MXFP4 的 scale 物理 shape 为(M, _ceil_div(H, 64), 2)与文档表格完全一致可作为 shape 推导的权威参考。约束说明indices元素个数必须小于16777215元素值必须大于等于0且小于16777215。这一上限在 tiling 侧同样存在moe_token_permute_tiling.cpp 中的SORT_LIMIT_LENGTH 16777215超出范围时排序结果不正确。MXFP8 的每 32 个量化值共享一个 E8M0 scalescale 数量向 2 对齐即AlignUp(CeilDiv(H, 32), 2)。MXFP4 的两个 4 bit 值打包在一个 uint8 中因此permuted_tokens的 PyTorch 物理隐藏维为H / 2。padded_mode当前仅支持False。在 Atlas A2 / A3 系列上topK 需小于等于 512来自 README.md 约束说明与 tiling 中MAX_INDICES_NUM 512、SPLIT_K_THRESHOLD 512相印证。输入 shape 约束tokens必须为 2Dindices必须为 1D 或 2Dcsrc/moe_token_permute.cpp 与 Meta 函数中均有检查。确定性计算该接口默认支持确定性计算即在相同输入下多次调用会得到一致的输出顺序排序使用稳定排序语义golden 实现中亦使用stableTrue的argsort。这在分布式训练中有利于保证梯度与调试结果的可复现性。调用示例非量化调用import torch import torch_npu from cann_ops_transformer.ops import moe_token_permute tokens torch.randn(4, 128, dtypetorch.float16, devicenpu) indices torch.tensor( [[1, 0], [0, 1], [1, 0], [0, 1]], dtypetorch.int32, devicenpu, ) permuted_tokens, sorted_indices, expanded_scale moe_token_permute( tokens, indices, num_out_tokens6, ) print(permuted_tokens.shape) # torch.Size([6, 128]) print(sorted_indices.shape) # torch.Size([8]) print(expanded_scale.shape) # torch.Size([0])该示例中indices为[4, 2]即F 8topK2每个 token 会按两个专家索引重复参与排序num_out_tokens6对permuted_tokens第一维截断至 6而sorted_indices仍保留全部 8 个元素。Ascend 950 MXFP8 调用Ascend 950PR / Ascend 950DTpermuted_tokens, sorted_indices, expanded_scale moe_token_permute( tokens, indices, quant_mode2, ) print(permuted_tokens.shape) # torch.Size([8, 128]) print(expanded_scale.shape) # torch.Size([8, 4])这里H 128MXFP8 E5M2 模式下的 scale 列数为AlignUp(CeilDiv(128, 32), 2) AlignUp(4, 2) 4故expanded_scale形状为[8, 4]且未指定num_out_tokens时M F 8。如需 MXFP4quant_mode9调用请确保H为偶数。源码级实现解析算子定义与 shape 推导算子注册moe_token_permute_def.cpp明确了输入输出 dtype 组合tokens支持 bf16 / fp16 / fp32 / int8indices支持 int64 / int32sorted_indices固定 int32属性num_out_tokens默认 0与padded_mode默认 False均为可选。infershape 逻辑moe_token_permute_infershape.cpp展示了如何从indices的[N]/[N, K]形状推导输出长度sortedIndicesLen topK * N再结合numOutTokens按与文档一致的规则裁剪第一维。NPU Kernel排序 索引拷贝的两段式流水Kernel 入口moe_token_permute.cpp体现了算子内部的计算拆解通过TILING_KEY在单核/多核排序与是否按隐藏维拆分SpiltD之间选择不同执行路径核心流程为第一趟排序对indices使用MoeSortOneCore/MoeSortMultiCore实现见 moe_sort_one_core_token_permute.h 与 moe_sort_multi_core_token_permute.h按专家索引稳定排序第二趟排序对第一趟结果再做一次排序得到逆映射sortedIndices索引拷贝通过MoeindexCopyOp/MoeindexCopySpiltDOpmoe_index_copy.h按映射关系把tokens收集到permuted_tokens输出。tiling 侧moe_token_permute_tiling.cpp负责根据 token 数量、隐藏维、topK 等参数决策排序模式与切分策略并在对应单测 test_moe_token_permute_tiling.cpp 中验证。与 aclnn 接口的关系该 Torch API 在底层转发至aclnnMoeTokenPermuteV2aclnn_moe_token_permute_v2.h。而根据 README.md 的说明在 Ascend 950 上框架内部会进一步转调aclnnMoeInitRoutingV2/aclnnMoeInitRoutingV3接口见 aclnn_moe_token_permute.cpp参数映射关系如下遇到参数错误提示时可据此排查tokens输入 对应MoeInitRoutingV2的x输入indices输入 对应expertIdx输入numOutTokens输入 对应activeNum输入paddedMode输入 对应dropPadMode输入permuteTokensOut输出 对应expandedXOut输出sortedIndicesOut输出 对应expandedRowIdxOut输出。总结与使用建议moe_token_permute是 CANN ops-transformer 中实现 MoE 路由后 token 重排的标准接口具有以下使用要点先确认平台Atlas A2/A3 系列仅支持非量化路径quant_mode-1MXFP8/MXFP4 量化仅适用于 Ascend 950PR / 950DT且量化模式不支持 autograd善用num_out_tokens可通过正数截断或负数尾部裁剪来控制有效输出行数且它只影响permuted_tokens与expanded_scale的第一维不影响sorted_indices长度理解量化布局MXFP8 每 32 个值共享一个 E8M0 scale 且列数向 2 对齐MXFP4 以 uint8 物理承载、隐藏维减半配合expanded_scale即可在 permute 阶段直接产出可用于 MX 量化的输出减少后续二次量化开销。相关源码与测试可继续在仓库中查阅Torch API 文档、aclnn 接口文档、aclnnMoeTokenPermuteV2 文档、C 语言调用示例、kernel 单测 与 ST 执行器。【免费下载链接】ops-transformer本项目是CANN提供的transformer类大模型算子库实现网络在NPU上加速计算。项目地址: https://gitcode.com/cann/ops-transformer创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考