Closed
moe_init_routing_v3(MXFP8 量化、FP8 Group 量化、MXFP8 透传) 性能优化 #3950
cpy_123456Add on  Jul 27Closed at  Jul 28
cpy_123456
cpy_123456Collaborators
Jul 27 Create

moe_init_routing_v3(MXFP8 量化、FP8 Group 量化、MXFP8 透传) 性能优化

概述

本次提交针对 moe_init_routing_v3 算子在 arch35 平台上的三个 Gather 阶段 kernel(MXFP8 量化、FP8 Group 量化、MXFP8 透传)进行了系统性性能优化,涉及 9 个文件,+946/-620 行变更。


优化一:为量化/透传 Kernel 引入 GatherCopy 模式

优化逻辑

背景:原有 MXFP8 量化、FP8 Group 量化、MXFP8 透传三个 kernel 仅支持 Scatter 模式(逐 output row 独立 CopyIn+Compute+CopyOut)。当多个 output row 映射到同一个 source row 时(即 k > 1 且 expert 分布集中),同一行 x 会被重复从 GM 读入多次。

方案:在 Tiling 侧新增 useGatherCopy 字段,当满足 (expertEnd - expertStart) * k__ > expertNum* THREE_NUM 时启用 GatherCopy 模式。GatherCopy 按 source row 遍历,对同一 source row 只执行一次 CopyIn+Compute,然后将结果 CopyOut 到所有对应的 output row。

Tiling 侧决策逻辑:

void ComputeUseGatherCopy()
{
    if (IsOneOf3GatherKernels()) {
        tilingDataPtr_->useGatherCopy = ((expertEnd_ - expertStart_) * 3 > expertNum_) && (k_ > 1);
    } else {
        tilingDataPtr_->useGatherCopy = (rowIdxType_ == ROW_IDX_GATHER);
    }
}

Kernel 侧 sortedRowIdxGm_ 地址切换:GatherCopy 模式下,SCATTER 索引从 workspace 读取(由 RowIdxGather 生成),GATHER 索引直接读 expandedRowIdx;非 GatherCopy 模式则相反。

收益

  • 同一 source row 的 x 数据只从 GM 读入一次,减少 GM 读带宽消耗
  • 量化计算(CopyIn + Compute)只执行一次,减少 Vector 单元重复计算
  • 在 k > 1 且 expert 分布集中的场景下,GM 读带宽可降低至原来的 1/k

核心代码(以 MXFP8 透传为例)

// GatherCopy 模式:按 source row 遍历,一次 CopyIn 多次 CopyOut
for (int64_t row = currentLoopStartRow; row <= currentLoopLastRow; row++) {
    // 跳过所有 output index 为负的 source row(无需 CopyIn)
    bool hasValidOut = false;
    while (curLoopRow < currentLoopRows_ && globalSortIdx / k_ == row) {
        if (indicesLocal.GetValue(curLoopRow) >= 0) {
            hasValidOut = true;
            break;
        }
        curLoopRow++;
        globalSortIdx++;
    }
    if (!hasValidOut) { continue; }

    CopyIn(row, j, loopCols);
    // 对同一 source row 的所有有效 output index 执行 CopyOut
    while (curLoopRow < currentLoopRows_ && globalSortIdx / k_ == row) {
        int32_t outIndex = indicesLocal.GetValue(curLoopRow);
        if (outIndex >= 0) {
            DataCopyPad<uint8_t>(expandedXOutGm_[outIndex * cols_ + ...], outLocal, ...);
        }
        curLoopRow++;
        globalSortIdx++;
    }
}

优化二:FP8 Group 量化计算流水线重构

优化逻辑

背景:原有 ComputeFp8GroupQuantVF 是一个单体 VF 函数,对每个 group(128 元素)串行执行 Amax→Scale→Quantize 全流程。存在两个性能瓶颈:

  1. Scale 计算使用浮点除法 Div(maxReg, fp8MaxReg) 和 Div(1.0f, roundScaleReg),延迟高
  2. 每个 group 独立执行 Amax/Scale/Quantize,无法利用跨 group 的向量化并行

方案:将单体函数拆分为三个独立的流水线阶段:

阶段 函数 功能
1 vfComputeAmax 对所有 group 批量计算 Amax,结果写入 amaxBuffer_
2 vfComputeRoundScale 对所有 group 批量计算 Scale 和 InvScale,使用整数位操作替代浮点除法
3 vfComputeData 对所有 group 批量执行 x * invScale 并 Cast 到 FP8

关键优化点 — 消除浮点除法:

旧方案:

Div(rawScaleReg, maxReg, fp8MaxReg, maskAll);       // amax / fp8Max (浮点除法)
Div(invScaleReg, 1.0f, roundScaleReg, maskAll);      // 1.0 / scale (浮点除法)

新方案(整数位操作):

// 直接从 amax 的 FP32 指数位提取,减去 fp8Emax 得到 roundedScale 的指数
ShiftRights(expBitsReg, (RegTensor<uint32_t> &)maxReg, FP32_EXPONENT_SHIFT, maskAllUint);
Sub<uint32_t>(roundedExpBitsReg, expBitsReg, fp8EmaxReg, maskAllUint);
// invScale 的指数 = 2*BIAS - roundedExpBits
Sub<uint32_t>(invExpBitsReg, invExpSubReg, roundedExpBitsReg, maskAllUint);

收益

  • 消除 2 次浮点除法/组:用整数移位+减法替代,单条指令延迟从 ~20 cycles 降至 ~1 cycle
  • 跨 group 向量化:vfComputeRoundScale 一次处理 vfLen(16 个 float)个 group 的 scale,充分利用向量寄存器宽度
  • 流水线并行:三个阶段在 UB 内通过 TBuf 传递中间数据,减少 Queue 的 Alloc/Free 开销

核心代码

// 阶段2:批量计算 RoundScale 和 InvScale(整数位操作,无浮点除法)
template <bool CLAMP_AMAX>
__simd_vf__ inline void vfComputeRoundScale(__ubuf__ float *amaxInAddr,
    __ubuf__ float *scaleOutAddr, __ubuf__ float *invScaleOutAddr,
    uint16_t groupNum, uint32_t fp8EmaxValue)
{
    for (uint16_t i = 0; i < vfLoopNum; i++) {
        DataCopy<float, PostLiteral::POST_MODE_UPDATE>(maxReg, amaxInAddr, vfLen);
        // 提取指数位
        ShiftRights(expBitsReg, (RegTensor<uint32_t> &)maxReg, FP32_EXPONENT_SHIFT, maskAllUint);
        // 尾数进位判断
        Compare<uint32_t, CMPMODE::GT>(maskMantHigh, mantBitsReg, fp8MantReg, maskAllUint);
        // roundedExpBits = expBits - fp8Emax + mantAdd
        Sub<uint32_t>(roundedExpBitsReg, expBitsReg, fp8EmaxReg, maskAllUint);
        Add<uint32_t>(roundedExpBitsReg, roundedExpBitsReg, mantAddReg, maskAllUint);
        // scale = roundedExpBits << 23 (构造 FP32)
        ShiftLefts((RegTensor<float> &)roundScaleReg, roundedExpBitsReg, FP32_EXPONENT_SHIFT, maskAllUint);
        // invScale = (2*BIAS - roundedExpBits) << 23
        Sub<uint32_t>(invExpBitsReg, invExpSubReg, roundedExpBitsReg, maskAllUint);
        ShiftLefts((RegTensor<float> &)invScaleReg, invExpBitsReg, FP32_EXPONENT_SHIFT, maskAllUint);
    }
}

优化三:GatherCopy 模式下的 hasValidOut 提前跳过

优化逻辑

在 GatherCopy 模式中,部分 source row 的所有 output index 可能为负值(即该行没有被任何 expert 选中)。新增 hasValidOut 预扫描:在 CopyIn 之前先遍历当前 source row 的所有 index,若全部为负则直接 continue,跳过 CopyIn + Compute + CopyOut 全流程。

收益

  • 避免对无效 source row 执行 GM 读入(CopyIn)和向量计算(Compute)
  • 在 expert 分布稀疏(大量 token 未被路由到当前 expert 范围)时效果显著

核心代码

bool hasValidOut = false;
while (curLoopRow < currentLoopRows_ && globalSortIdx / k_ == row) {
    if (indicesLocal.GetValue(curLoopRow) >= 0) {
        hasValidOut = true;
        break;
    }
    curLoopRow++;
    globalSortIdx++;
}
if (!hasValidOut) { continue; }

优化四:Tiling 侧 UB 预算与 Workspace 修正

4.1 MXFP8 量化 UB 预算修正

CalcMaxRowIdxPerLoopMxQuant 中 xInSize 多算了 AlignBytes(perLoopCols, sizeof(int8_t)):

// 修正前(多算了 int8 buffer)
int64_t xInSize = AlignBytes(perLoopCols, inputXDtypeSize_) + AlignBytes(perLoopCols, sizeof(int8_t));

// 修正后
int64_t xInSize = AlignBytes(perLoopCols, inputXDtypeSize_);

收益:释放了被多算的 UB 空间,允许更多的 perLoopMaxIndicesElements(每循环处理的行数),减少循环次数。

4.2 FP8 Group 量化独立 UB 预算函数

新增 CalcMaxRowIdxPerLoopFP8GroupQuant,精确覆盖 kernel 中 amaxBuffer_ 和 invScaleBuffer_ 两个 TBuf 的 UB 开销:

int64_t CalcMaxRowIdxPerLoopFP8GroupQuant(int64_t perLoopCols)
{
    int64_t xInSize = AlignBytes(perLoopCols, inputXDtypeSize_);
    int64_t xOutSize = AlignBytes(perLoopCols, sizeof(uint8_t));
    int64_t scaleSize = AlignBytes(CeilDiv(perLoopCols, FP8_GROUP_SIZE), sizeof(float));
    int64_t tmpBufSize = std::max(scaleSize, REG_SIZE);  // amaxBuffer_ / invScaleBuffer_
    return (availUbSize_ / 2 - (xInSize + xOutSize + scaleSize + tmpBufSize * 2)) / sizeof(int32_t);
}

4.3 Workspace 精简

新增 NeedQuantTempWorkspace() 函数,MXFP8/FP8 Group 量化模式不再分配 quantTempWorkspace(这些 kernel 不使用 quantTempGm_):

bool NeedQuantTempWorkspace() const
{
    return (quantMode_ >= QUANT_MODE_DYNAMIC && quantMode_ != QUANT_MODE_HIF8_CAST &&
        quantMode_ != QUANT_MODE_HIF8_PERTENSOR && quantMode_ != QUANT_MODE_MXFP8_E5M2 &&
        quantMode_ != QUANT_MODE_MXFP8_E4M3FN && ...);
}

收益:减少 aivCoreNum * cols * sizeof(float) 字节的 workspace 分配(对于典型场景如 64 核 × 7168 列 = 1.75MB)。


优化五:RowIdxGather 与 ExpertTokensCount 适配

RowIdxGather 简化

  • 移除 TPipe 依赖(不再需要 Queue buffer),直接使用 SIMT VF 计算
  • 支持 useGatherCopy 模式下 SCATTER 索引的反向映射(从 expandedRowIdx 读到 workspace)
  • 精简 Init 逻辑,移除冗余的循环拆分计算

ExpertTokensCount 适配

  • useGatherCopy && SCATTER 模式下,在 Init 阶段将 workspace 中的 gather row index 区域初始化为 -1
  • 确保 GatherCopy kernel 读取到未写入的 index 时能正确跳过

涉及文件汇总

文件 变更类型
moe_init_routing_v3_tiling_arch35.cpp Tiling 逻辑:新增 useGatherCopy 决策、UB 预算修正、Workspace 精简
moe_init_routing_v3_arch35_tiling_def.h Tiling 数据结构:新增 useGatherCopy 字段
moe_v3_gather_mxfp8_quant.h MXFP8 量化 kernel:新增 GatherCopy 模式 + hasValidOut 跳过
moe_v3_gather_fp8_group_quant.h FP8 Group 量化 kernel:计算流水线重构 + GatherCopy 模式
moe_v3_gather_out_mxfp8.h MXFP8 透传 kernel:新增 GatherCopy 模式 + hasValidOut 跳过
moe_v3_row_idx_gather.h RowIdxGather:移除 TPipe、支持 useGatherCopy 反向映射
moe_v3_expert_tokens_count.h ExpertTokensCount:适配 useGatherCopy 的 workspace 初始化
moe_init_routing_v3_apt.cpp Kernel 调度:适配 RowIdxGather 新接口、SCATTER 模式支持
test_moe_init_routing_v3_arch35_tiling.cpp 单测适配
likedislike
cpy_123456
cpy_123456Collaborators
Jul 27 Comments:

/assign

likedislike
CANN-robotCANN-robotCollaborators
Jul 27 Assign cpy_123456 as responsible person
cpy_123456cpy_123456Collaborators
Jul 27 Modify description of issue
CANN-robotCANN-robotCollaborators
Jul 28 Close issue
CANN-robotCANN-robotCollaborators
Jul 28 Added label: resolved