# PR #47641 完整报告

- 仓库：`vllm-project/vllm`
- 标题：[Hardware][CPU] Enable granite-4 model on cpu
- 合并时间：2026-07-20 14:15
- 原文链接：http://prhub.com.cn/vllm-project/vllm/pull/47641

---

# PR 分析报告 : 在 CPU 上启用 Granite-4 模型

## 1. 执行摘要
本 PR 为 IBM Granite 4.0 系列 Mamba 模型在 CPU 平台上新增推理能力，核心工作是编写 C++ 向量化内核（causal_conv1d_update、selective_state_update、mamba_chunk_scan）并建立 CPU 后端分发机制，避免对 Triton 的依赖。改动涉及 21 个文件，包括新增内核代码、Python 绑定、后端注册和测试，是一个跨平台适配的重要里程碑。

## 2. 功能与动机
根据关联 Issue #27971，granite-4.0-h-tiny 在 CPU 上推理时因缺少 Mamba 算子而失败。IBM 的 Granite 4.0 模型大量使用 Mamba2 结构，其热点操作（causal conv1d 状态更新、SSM 单步递归、chunk 扫描前向）在 CPU 上之前仅能通过 Triton JIT（不稳定）或纯 PyTorch（低效）运行。本 PR 的目标是提供高性能且稳定的 CPU 原生实现，使整个模型家族能在 ppc64le/Power10、x86 等平台上正确运行。

## 3. 实现拆解

1. **C++ 内核开发 **（csrc/cpu/mamba_kernels.hpp, csrc/cpu/mamba_cpu.cpp）
 - 实现 `causal_conv1d_update_kernel`：支持非连续 paged state，通过显式 stride 直接写入，避免全量拷贝（原瓶颈 34-41% direct_copy_kernel）。采用 OpenMP 并行，state 移位提供 memmove 和元素循环两种路径。
 - 实现 `selective_state_update_kernel`：接受 float32 参数（A, D, dt_bias），避免逐次类型转换，且输入 dt 为标量 per-head，无需预先扩展。
 - 实现 `mamba_chunk_scan_fwd_cpu` 内核：处理 prefill 阶段的长序列扫描。
2. **Python 绑定 **（vllm/_custom_ops.py）
 - 新增 `causal_conv1d_update_cpu_vec`、`selective_state_update_cpu`、`mamba_chunk_scan_fwd_cpu` 三个函数，直接转发到 `torch.ops._C`。
3. **后端分发与适配 **（ssu_dispatch.py, short_conv.py, cpu/causal_conv1d.py）
 - 新增 `CPUSSUBackend` 类，在 `initialize_mamba_ssu_backend` 中检测 CPU 平台后自动选用，避免 Triton JIT 问题。
 - 修改 `short_conv.py` 的 `forward_native`：对 ARM 架构保留原有 PyTorch 实现（`causal_conv1d_update_torch`），其他架构使用新 C++ 内核。
 - 将 CPU 相关函数从杂乱的目录迁移至 `mamba/ops/cpu/` 下，清理原 Triton 文件中的 CPU 侵入。
4. **CMake 与构建配置 **（csrc/cpu/torch_bindings.cpp）
 - 注册三个新的 torch 自定义 op，并保留既有 AMX 加速的 `causal_conv1d_update_cpu`（通过 `is_vnni` 参数切换）。
5. **测试与 CI**（tests/kernels/mamba/test_mamba_ssm.py, .buildkite/hardware_tests/cpu.yaml）
 - 激活 Mamba SSM 和 causal_conv1d 的 CPU 测试，使能 x86/power CI 路径。

### `csrc/cpu/mamba_kernels.hpp`

新增 CPU Mamba 解码步核心向量内核头文件，包含 causal_conv1d_update 和 selective_state_update 的模板实现，支持非连续状态 stride 寻址，这是性能关键。

```cpp
// causal_conv1d_update_kernel — 模板化，支持 native BF16/FP32
// state_ptr 可能指向非连续的 paged KV cache 张量。
// 通过显式 stride 直接在正确内存位置写入，避免整个 paged tensor 的连续拷贝。
template <typename scalar_t>
inline void causal_conv1d_update_kernel(
    const scalar_t* __restrict__ x_ptr, scalar_t* __restrict__ state_ptr,
    int64_t stride_s_slot, int64_t stride_s_dim, int64_t stride_s_state,
    const scalar_t* __restrict__ weight_ptr, const float* __restrict__ bias_ptr,
    scalar_t* __restrict__ out_ptr, const int32_t* __restrict__ cache_idxs,
    int32_t pad_slot_id, int64_t batch, int64_t dim, int64_t seqlen,
    int64_t width, int64_t state_len, bool do_silu) {
#pragma omp parallel for
  for (int64_t b = 0; b < batch; ++b) {
    int64_t cache_idx = (cache_idxs != nullptr) ? cache_idxs[b] : b;
    if (cache_idx == pad_slot_id) continue;

    for (int64_t t = 0; t < seqlen; ++t) {
      const scalar_t* x_b = x_ptr + (b * dim * seqlen + t);
      scalar_t* out_b = out_ptr + (b * dim * seqlen + t);
      scalar_t* s_base = state_ptr + cache_idx * stride_s_slot;  // slot 起始

      for (int64_t d = 0; d < dim; ++d) {
        float x_val = static_cast<float>(x_b[d * seqlen]);
        scalar_t* sd = s_base + d * stride_s_dim;               // 当前 dim 的状态
        const scalar_t* w = weight_ptr + d * width;

        float acc = (bias_ptr != nullptr) ? bias_ptr[d] : 0.0f;
        for (int64_t k = 0; k < state_len; ++k) {
          acc += static_cast<float>(w[k]) *
                 static_cast<float>(sd[k * stride_s_state]);
        }
        acc += static_cast<float>(w[state_len]) * x_val;

        // 状态左移，新输入追加在末尾
        if (stride_s_state == 1) {
          // 连续时用 memmove 快速路径
          if (state_len > 1)
            std::memmove(sd, sd + 1, (state_len - 1) * sizeof(scalar_t));
          if (state_len > 0) sd[state_len - 1] = static_cast<scalar_t>(x_val);
        } else {
          // 非连续时逐元素移位
          for (int64_t k = 0; k < state_len - 1; ++k)
            sd[k * stride_s_state] = sd[(k + 1) * stride_s_state];
          if (state_len > 0)
            sd[(state_len - 1) * stride_s_state] = static_cast<scalar_t>(x_val);
        }

        // SiLU 激活（gate 分支使用）
        if (do_silu) {
          float sigmoid = (acc >= 0) ? 1.0f / (1.0f + std::exp(-acc))
                                     : std::exp(acc) / (1.0f + std::exp(acc));
          acc *= sigmoid;
        }
        out_b[d * seqlen] = static_cast<scalar_t>(acc);
      }
    }
  }
}

```

### `csrc/cpu/mamba_cpu.cpp`

C++ 包装器，将 at::Tensor 参数适配到内核模板，包含 stride 提取、数据类型转换和条件写入，是内部实现入口。

```cpp
// causal_conv1d_update 的 CPU at::Tensor wrapper
// 关键设计：仅在类型不匹配时复制 conv_state，布局非连续通过 strides 传递，避免全量拷贝。
at::Tensor causal_conv1d_update_cpu_impl(
    at::Tensor& x, at::Tensor& conv_state, const at::Tensor& weight,
    const c10::optional<at::Tensor>& bias,
    const c10::optional<std::string>& activation,
    const c10::optional<at::Tensor>& conv_state_indices,
    const c10::optional<at::Tensor>& query_start_loc, int64_t pad_slot_id) {
  // ... dtype 判断、contiguous 保证、stride 提取 ...
  // 关键：提取 stride_s_slot, stride_s_dim, stride_s_state
  int64_t stride_s_slot = state_c.stride(0);
  int64_t stride_s_dim = state_c.stride(1);
  int64_t stride_s_state = state_c.stride(2);

  at::Tensor out = x_c.clone();  // 输出分配在 native dtype

  // ... 选择性类型转换、缓存索引处理 ...

  VLLM_DISPATCH_FLOATING_TYPES(dtype, "causal_conv1d_update", [&] {
    mamba_cpu::causal_conv1d_update_kernel<scalar_t>(
        x_c.data_ptr<scalar_t>(), state_c.data_ptr<scalar_t>(),
        stride_s_slot, stride_s_dim, stride_s_state,
        w_c.data_ptr<scalar_t>(),
        bias_f32.defined() ? bias_f32.data_ptr<float>() : nullptr,
        out.data_ptr<scalar_t>(), cache_idx_ptr,
        static_cast<int32_t>(pad_slot_id),
        batch, dim, seqlen, width, state_len, do_silu);
  });

  // 仅当类型转换时才写回 conv_state
  if (!state_type_ok) conv_state.copy_(state_c);
  return out;
}

```

## 5. 评论区精华
- **bigPYJ1151 与 fadara01 关于内核命名**：bigPYJ1151 提出用 `_vec` 后缀区分 AMX 实现，fadara01 指出该内核实际为标量。作者解释命名来自维护者建议，并承诺后续可向量化。
- **fadara01 要求 ARM 保持旧路径**：ARM 上的 causal_conv1d 由 oneDNN 加速，不应替换。最终通过 `CpuArchEnum.ARM` 分支实现。
- **bigPYJ1151 提议移除 torch fallback**：新 C++ 内核已通用，无需维护纯 PyTorch 回退，已执行。
- **depthfirst 静态分析**：指出 state_len/width 未校验、memmove 越界、dim-3 非连续假设等问题，至合并时未完全修复，需后续跟进。

## 6. 风险与影响
- **内存安全**：内核中若干校验缺失，可能在异常 shape 下导致 OOB 读写（depthfirst 报告）。建议后续增加 TORCH_CHECK 断言。
- **ARM 性能**：旧 PyTorch 路径在 ARM 上已优化，但可能不如新内核在其他架构上的收益。可通过 benchmark 验证。
- **平台兼容**：使用 VSX/AVX 内联函数，若编译环境缺少相关指令集则报错。当前仅打算支持 ppc64le 和 x86_64。
- **影响范围**：仅限于 CPU 后端，GPU 用户无影响。新增 21 个文件，共 1283 行代码，引入了一定的维护成本。

## 7. 关联脉络
本 PR 与 Issue #27971（CPU 推理失败）直接关联，是 vLLM CPU 后端的又一块拼图。此前已有 ROCm 上的 Mamba 性能优化（#46832）和 MoE 适配，本 PR 补齐了 Mamba CPU 算子栈。后续可能为其他 Mamba 模型（如 Jamba、Mamba2）提供通用 CPU 支持，并为 ARM 上的向量化 kernel 改进奠定基础。