Prhub

#22933 [CPU] expand the interface of shared_expert without scaling factor

原始 PR 作者 mingfeima 合并时间 2026-04-21 20:03 文件变更 9 提交数 6 评论 2 代码增减 +313 / -623

执行摘要

扩展 CPU 平台的 shared_expert 内核以支持无缩放因子,并提取公共向量化存根简化 MoE 代码。

根据PR body,动机是“expand shared_expert kernel when scaling factor is None, which maps exactly the behavior of MoE when expert equals to one”,同时“Also simplifies moe kernel source codes by extracting common vectorized stubs into moe.h”。

值得精读,特别是学习如何通过提取公共存根来简化内核代码的设计模式,以及接口扩展时保持向后兼容的实践。重点关注 moe.h 中的向量化实现和测试更新策略。

讨论亮点

本次PR没有review评论,变更主要由作者自行推进和合并,未产生技术讨论或争议。

实现拆解

  1. 新增公共头文件:创建 sgl-kernel/csrc/cpu/moe.h,定义 fill_stub、copy_stub、copy_mul_stub、sum_stub、add_mul_stub 等模板函数,实现向量化操作以优化CPU计算。
    - 涉及文件:sgl-kernel/csrc/cpu/moe.h。
    - 关键符号:add_mul_stub 等存根函数。
    - 变更原因:统一存根逻辑,消除重复代码,便于维护。
    - 影响:所有MoE相关内核文件可复用这些存根,提高代码一致性。

  2. 重构内核文件:修改 moe.cpp、moe_int4.cpp、moe_fp8.cpp、moe_int8.cpp,移除各自内部的存根实现,改为 #include "moe.h"。
    - 涉及文件:sgl-kernel/csrc/cpu/moe.cpp 等。
    - 关键符号:删除了重复的 copy_stub 等函数。
    - 变更原因:简化代码结构,减少冗余。
    - 影响:内核逻辑不变,但依赖关系更清晰,降低维护成本。

  3. 扩展接口参数:在提交历史中,将 fused_experts_out 和 routed_scaling_factor 设为可选,允许 scaling_factor 为 None。
    - 涉及文件:sgl-kernel/csrc/cpu/torch_extension_cpu.cpp 及内核实现。
    - 关键符号:shared_expert_cpu 函数参数调整。
    - 变更原因:使 shared_expert 行为与单专家MoE一致,增加灵活性。
    - 影响:调用方可以省略缩放因子,简化使用场景。

  4. 更新测试配套:修改 test/srt/cpu/test_shared_expert.py 和 test/srt/cpu/utils.py,添加对无缩放因子情况的测试覆盖。
    - 涉及文件:test/srt/cpu/test_shared_expert.py、test/srt/cpu/utils.py。
    - 关键符号:_bf16_shared_expert、_int8_shared_expert、_fp8_shared_expert 测试函数。
    - 变更原因:确保新接口的正确性,防止回归。
    - 影响:测试覆盖更全面,保障代码质量。

文件 模块 状态 重要度
sgl-kernel/csrc/cpu/moe.h MoE 内核 added 7.85
sgl-kernel/csrc/cpu/moe.cpp MoE 内核 modified 7.27
test/srt/cpu/test_shared_expert.py 测试套件 modified 6.74

关键符号

fill_stub copy_stub copy_mul_stub sum_stub add_mul_stub shared_expert_cpu

关键源码片段

sgl-kernel/csrc/cpu/moe.h dependency-wiring

新增公共头文件,统一管理向量化存根,是重构的核心,消除了多个内核文件的代码重复。

// add_mul_stub: 实现 out = input + input2 * scale,支持 input2 为 nullptr 的情况(即无缩放因子)
template <typename scalar_t, typename input_t>
inline void add_mul_stub(
    scalar_t* __restrict__ out,
    const input_t* __restrict__ input,
    const scalar_t* __restrict__ input2,
    float scale,
    int64_t size) {
  // 静态断言确保输入类型为 float 或 scalar_t,保证类型安全
  static_assert(
      std::is_same_v<input_t, float> || std::is_same_v<input_t, scalar_t>,
      "add_mul_stub only supports input_t == float or input_t == scalar_t");
​
  // 处理 input2 为空指针的情况:直接复制输入,忽略缩放因子
  if (input2 == nullptr) {
    copy_stub(out, input, size);
    return;
  }
​
  using bVec = at::vec::Vectorized<scalar_t>;
  using fVec = at::vec::Vectorized<float>;
  constexpr int kVecSize = bVec::size();
  const fVec s_vec = fVec(scale); // 向量化缩放因子
  int64_t d;
​
  // 向量化循环:处理主体部分,使用 GCC unroll 优化
#pragma GCC unroll 4
  for (d = 0; d <= size - kVecSize; d += kVecSize) {
    auto [x0, x1] = load_float_vec2(input + d); // 加载输入到两个浮点向量
​
    bVec y_bvec = bVec::loadu(input2 + d); // 加载 input2 数据
    fVec y0, y1;
    std::tie(y0, y1) = at::vec::convert_to_float(y_bvec); // 转换为浮点
​
    x0 = x0 + y0 * s_vec; // 执行加法和缩放
    x1 = x1 + y1 * s_vec;
    bVec out_vec = convert_from_float_ext<scalar_t>(x0, x1); // 转换回原始类型
    out_vec.store(out + d); // 存储结果
  }
​
  // 处理剩余元素:标量回退
  for (; d < size; ++d) {
    out[d] = static_cast<scalar_t>(input[d] + float(input2[d]) * scale);
  }
}
sgl-kernel/csrc/cpu/moe.cpp core-logic

核心 MoE 内核文件,移除重复存根代码并导入 moe.h,体现重构效果和接口扩展。

#include "moe.h"  // 新增:导入公共头文件,统一使用向量化存根
#include "common.h"
#include "gemm.h"
​
namespace {
  // [NOTE]: Fused MoE kernel with AMX
  // 原有内核实现保持不变,但依赖 moe.h 中的存根函数
  // 例如,在 fused_moe 函数中使用 add_mul_stub 处理缩放因子
  template <typename scalar_t>
  void fused_moe(
      scalar_t* __restrict__ output,
      scalar_t* __restrict__ input,
      const scalar_t* __restrict__ packed_w1,
      const scalar_t* __restrict__ packed_w2,
      const scalar_t* __restrict__ fused_experts_out, // 可能为 nullptr
      float routed_scaling_factor, // 可能为 None
      int64_t M,
      int64_t N,
      int64_t K) {
    // ...
    // 在循环中调用 add_mul_stub,fused_experts_out 可为空以支持无缩放因子
    add_mul_stub(out + m * K, C + m * BLOCK_N, fused_out_row, routed_scaling_factor, n_size);
    // ...
  }
} // anonymous namespace
test/srt/cpu/test_shared_expert.py test-coverage

关键测试文件,更新以覆盖无缩放因子情况,确保接口扩展正确性和回归测试。

def _bf16_shared_expert(self, m, n, k, routed_scaling_factor, apply_scaling_factor):
    dtype = torch.bfloat16
    hidden_states = torch.randn(m, k, dtype=dtype) / k
    w1 = torch.randn(2 * n, k, dtype=dtype)
    w2 = torch.randn(k, n, dtype=dtype)
    # 根据 apply_scaling_factor 决定是否提供 fused_output 和 routed_scaling_factor
    fused_output = (
        torch.randn(m, k, dtype=dtype) / k if apply_scaling_factor else None
    )
    routed_scaling_factor = routed_scaling_factor if apply_scaling_factor else None
​
    # 参考实现:使用 torch_naive_moe 计算期望结果
    ref = torch_naive_moe(
        hidden_states.float(), w1.float(), w2.float(),
        fused_output.float() if apply_scaling_factor else None,
        routed_scaling_factor
    ).to(dtype=dtype)
​
    # 调用扩展后的内核:shared_expert_cpu 现在支持 fused_output 和 routed_scaling_factor 为 None
    out = torch.ops.sgl_kernel.shared_expert_cpu(
        hidden_states, w1, w2, fused_output, routed_scaling_factor,
        True, False, False, None, None, output_dtype=dtype
    )
    # 断言结果一致
    torch.testing.assert_close(ref, out, atol=atol, rtol=rtol)

评论区精华

没有提炼出高价值讨论线程

当前评论区没有形成足够清晰的争议点或结论,后续有更多讨论时会体现在这里。

风险与影响

主要风险在于代码重构可能引入回归错误:公共存根函数 add_mul_stub 等如果实现有误,会影响所有依赖的MoE内核(如moe.cpp、moe_int4.cpp等),导致计算错误。性能风险较低,因为向量化存根优化了计算,但需确保新老接口性能一致。兼容性风险:接口扩展可能破坏现有调用,但测试更新覆盖了新老情况,降低了风险。安全风险不明显,未涉及敏感数据。

对用户:使shared_expert内核更灵活,支持无缩放因子场景,便于集成到MoE流程中,简化模型配置。对系统:代码简化提高可维护性,向量化存根可能轻微提升CPU性能,减少代码重复。对团队:减少维护负担,为未来内核扩展提供模板,促进代码复用。

公共存根错误 接口兼容性 回归测试覆盖

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论