# PR #41025 完整报告

- 仓库：`vllm-project/vllm`
- 标题：[Feat][CPU] Enable Gated DeltaNet Attention (Qwen 3.5 / 3.6)
- 合并时间：2026-05-07 12:57
- 原文链接：http://prhub.com.cn/vllm-project/vllm/pull/41025

---

# 执行摘要

- 一句话：为 CPU 新增 Gated DeltaNet Attention，支持 Qwen3.5/3.6
- 推荐动作：建议阅读者关注其设计模式：如何在不依赖 Triton 的 CPU 上实现自定义注意力算子，如何利用 `ForwardContext` 和 `GDNAttentionMetadata` 集成到 v1 注意力后端，以及 how to handle hybrid model 的 block size 对齐。该 PR 是 CPU 后端支持现代线性注意力架构的重要一步，值得架构师和 CPU 后端开发者精读。对于急于在 CPU 上运行 Qwen3.5/3.6 的用户，可直接使用；若需要更高性能，可跟踪后续融合优化 PR。

# 功能与动机

根据 PR 标题和描述，目的是在所有 CPU 上启用 Qwen 3.5 和 Qwen 3.6。关联 Issue #35950 报告了在非 GPU 平台运行 Qwen3.5 时出现 `ValueError: too many values to unpack`，本次变更为根本解决。此外，torch.compile 模式还需依赖 PyTorch 修复（PR #40973）才能完整工作。

# 实现拆解

1. **新增 CPU GDN 核心算子**：在 `vllm/model_executor/layers/mamba/ops/cpu/` 下新增 `recurrent_gated_delta_rule.py`（实现 `recurrent_gated_delta_rule`、`chunk_gated_delta_rule`、`gdn_gating`）和 `causal_conv1d.py`（实现 `causal_conv1d_torch` 和 `causal_conv1d_update_torch`），使用纯 PyTorch 实现，避免依赖 Triton。
2. **注册自定义 op**：新增 `gdn_attention.py`，通过 `torch.library` 将 `cpu_gdn_attention_core` 注册为自定义操作，该 op 在 `forward_context` 中查找 `GDNAttentionMetadata` 并根据 prefill/decode 分支调度相应的算子。
3. **修改 `GDNLinearAttention` 层**：在 `gdn_linear_attn.py` 的 `__init__` 中，根据平台（XPU/CPU）选择 forward 方法，新增 `forward_cpu` 方法，调用自定义 op 进行计算。
4. **平台层 block size 对齐**：在 `cpu.py` 中实现 `update_block_size_for_backend`，当模型为 hybrid 时，调用 `_find_non_ssm_backend` 和 `_align_hybrid_block_size` 来协调 MMLU 和注意力后端的页大小。
5. **CI 和文档**：在 ARM CI 脚本中添加 Qwen 3.5 的烟测试，更新 `attention_backends.md` 文档，以及修复 `triton_utils/importing.py` 中缺失的 `cdiv` 以避免 CPU 上导入错误。注意：未添加单元测试，只依赖 CI 烟测试。

关键文件：
- `vllm/model_executor/layers/mamba/ops/cpu/recurrent_gated_delta_rule.py`（模块 GDN 算子；类别 source；类型 core-logic；符号 l2norm, recurrent_gated_delta_rule, gdn_gating, chunk_gated_delta_rule）: CPU GDN 核心算法的纯 PyTorch 实现，包括循环和分块两种变体，是功能使能的关键。
- `vllm/model_executor/layers/mamba/ops/cpu/gdn_attention.py`（模块 GDN 注意力；类别 source；类型 core-logic；符号 cpu_gdn_attention_core, cpu_gdn_attention_core_fake, register_cpu_gdn_attention_ops）: 注册 CPU 自定义 op `cpu_gdn_attention_core`，作为算子和 vLLM 注意力机制之间的桥梁，负责解析 attention metadata 并调度 conv1d 和 delta rule。
- `vllm/model_executor/layers/mamba/gdn_linear_attn.py`（模块 GDN 层；类别 source；类型 core-logic；符号 forward_cpu）: 修改了 GDNLinearAttention 层的初始化流程，新增 forward_cpu 方法，是 CPU 后端的入口点。
- `vllm/model_executor/layers/mamba/ops/cpu/causal_conv1d.py`（模块 因果卷积；类别 source；类型 core-logic；符号 causal_conv1d_torch, causal_conv1d_update_torch）: 纯 PyTorch 实现的因果卷积，支持 prefill 和 decode 两种模式，是 GDN 的前置步骤。
- `vllm/platforms/cpu.py`（模块 平台配置；类别 source；类型 core-logic）: 实现 update_block_size_for_backend 以支持 hybrid 模型的 block size 对齐。
- `vllm/v1/attention/backends/cpu_attn.py`（模块 注意力后端；类别 source；类型 core-logic；符号 get_supported_kernel_block_sizes）: 添加 get_supported_kernel_block_sizes 方法，返回 [MultipleOf(16)]，告知平台 CPU 注意力后端支持的块大小。
- `vllm/model_executor/layers/linear.py`（模块 线性层；类别 source；类型 bugfix）: 在 process_weights_after_loading 中添加保护，避免非 2D 权重触发 dispatch_cpu_unquantized_gemm。
- `vllm/triton_utils/importing.py`（模块 Triton 兼容；类别 source；类型 dependency-wiring）: 在 Triton 不存在时，将 cdiv 添加到 dummy 装饰器，避免 CPU 等平台因导入 triton 相关模块而报错。
- `.buildkite/scripts/hardware_ci/run-cpu-test-arm.sh`（模块 CI 脚本；类别 infra；类型 configuration）: 添加 Qwen 3.5 在 ARM CPU 上的烟测试，确保基本功能通过。
- `docs/design/attention_backends.md`（模块 设计文档；类别 docs；类型 documentation）: 更新注意力后端设计文档，反映 CPU 后端的变化。
- `vllm/model_executor/layers/mamba/ops/cpu/__init__.py`（模块 包定义；类别 infra；类型 infrastructure）: 空文件，使 cpu 目录成为 Python 包。

关键符号：l2norm, recurrent_gated_delta_rule, gdn_gating, chunk_gated_delta_rule, cpu_gdn_attention_core, cpu_gdn_attention_core_fake, register_cpu_gdn_attention_ops, forward_cpu, causal_conv1d_torch, causal_conv1d_update_torch, get_supported_kernel_block_sizes

## 关键源码片段

### `vllm/model_executor/layers/mamba/ops/cpu/recurrent_gated_delta_rule.py`

CPU GDN 核心算法的纯 PyTorch 实现，包括循环和分块两种变体，是功能使能的关键。

```python
# SPDX-License-Identifier: Apache-2.0
import torch
import torch.nn.functional as F


def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6) -> torch.Tensor:
    # 计算 L2 归一化，保持与 HuggingFace 参考实现一致
    inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
    return x * inv_norm


def recurrent_gated_delta_rule(
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    g: torch.Tensor,
    beta: torch.Tensor,
    initial_state: torch.Tensor,
    scale: float | None = None,
    use_qk_l2norm_in_kernel: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
    # 循环变体的 Gated Delta Rule，逐个 token 更新隐状态
    if use_qk_l2norm_in_kernel:
        query = l2norm(query, dim=-1)
        key = l2norm(key, dim=-1)
    # 转置并转为 float32 以保证数值稳定性
    query, key, value, beta, g = [
        x.transpose(1, 2).contiguous().to(torch.float32)
        for x in (query, key, value, beta, g)
    ]
    batch_size, num_heads, seq_len, _ = key.shape
    if scale is None:
        scale = 1 / (query.shape[-1] ** 0.5)
    query = query * scale
    core_attn_out = torch.empty(batch_size, num_heads, seq_len, value.shape[-1])
    last_state = initial_state
    for t in range(seq_len):
        q_t = query[:, :, t]
        k_t = key[:, :, t]
        v_t = value[:, :, t]
        g_t = g[:, :, t].exp().unsqueeze(-1).unsqueeze(-1)  # 门控衰减
        beta_t = beta[:, :, t].unsqueeze(-1)
        last_state = last_state * g_t
        kv_mem = (last_state * k_t.unsqueeze(-2)).sum(dim=-1)
        delta = (v_t - kv_mem) * beta_t
        last_state = last_state + delta.unsqueeze(-1) * k_t.unsqueeze(-2)
        core_attn_out[:, :, t] = (last_state * q_t.unsqueeze(-2)).sum(dim=-1)
    return core_attn_out.transpose(1, 2).contiguous().to(query.dtype)


def gdn_gating(A_log, a, b, dt_bias, beta=1.0, threshold=20.0):
    # 使用 softplus 计算门控值，sigmoid 输出
    softplus_x = F.softplus(a.float() + dt_bias.float(), beta=beta, threshold=threshold)
    g = -torch.exp(A_log.float()) * softplus_x
    beta_output = torch.sigmoid(b.float()).to(dtype=b.dtype)
    return g, beta_output

```

### `vllm/model_executor/layers/mamba/ops/cpu/gdn_attention.py`

注册 CPU 自定义 op `cpu_gdn_attention_core`，作为算子和 vLLM 注意力机制之间的桥梁，负责解析 attention metadata 并调度 conv1d 和 delta rule。

```python
# 注册 CPU GDN 注意力自定义 op
import torch
from vllm.forward_context import get_forward_context
from vllm.model_executor.layers.mamba.ops.cpu.causal_conv1d import causal_conv1d_torch, causal_conv1d_update_torch
from vllm.model_executor.layers.mamba.ops.cpu.recurrent_gated_delta_rule import chunk_gated_delta_rule, gdn_gating, recurrent_gated_delta_rule
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadata


def cpu_gdn_attention_core(mixed_qkv, b, a, core_attn_out, layer_name):
    # 从 forward context 获取 attention metadata
    forward_context = get_forward_context()
    layer = forward_context.no_compile_layers[_resolve_layer_name(layer_name)]
    attn_metadata = forward_context.attn_metadata
    if attn_metadata is None:
        return
    assert isinstance(attn_metadata, dict)
    attn_metadata_i = attn_metadata[layer.prefix]
    # 解码分支：用 update 模式
    if num_decodes > 0:
        decode_input = mixed_qkv[:num_decode_tokens]
        indices = state_indices_tensor[:num_decodes]
        conv_state = conv_state[indices].contiguous()
        decode_out = causal_conv1d_update_torch(
            x=decode_input.unsqueeze(-1),
            conv_state=conv_state,
            weight=conv_weights,
            bias=layer.conv1d.bias,
        )
        # 省略：门控计算 + recurrent_gated_delta_rule
    # 预填分支：用 prefill 模式
    if num_prefills > 0:
        prefill_out = causal_conv1d_torch(
            x=mixed_qkv[num_decode_tokens:],
            weight=conv_weights,
            bias=layer.conv1d.bias,
            conv_states=conv_state,
            query_start_loc=query_start_loc[num_decodes:],
            cache_indices=cache_indices[num_decodes:],
            has_initial_state=has_initial_state[num_decodes:],
        )
        # 省略：门控 + chunk_gated_delta_rule


def register_cpu_gdn_attention_ops():
    # 将自定义 op 注册到 torch.library
    torch.library.define(
        "vllm::cpu_gdn_attention_core",
        "(Tensor mixed_qkv, Tensor b, Tensor a, Tensor core_attn_out, str layer_name) -> ()",
    )
    torch.library.impl("vllm::cpu_gdn_attention_core", "CPU")(cpu_gdn_attention_core)

```

### `vllm/model_executor/layers/mamba/gdn_linear_attn.py`

修改了 GDNLinearAttention 层的初始化流程，新增 forward_cpu 方法，是 CPU 后端的入口点。

```python
class GDNLinearAttention(torch.nn.Module):
    def __init__(self, ..., vllm_config, prefix):
        # ... 其他初始化 ...
        # 根据平台选择 forward 方法
        self._forward_method = self.forward_cuda
        if current_platform.is_xpu():
            self._forward_method = self.forward_xpu
        elif current_platform.is_cpu():
            # 注册 CPU 自定义 op
            from vllm.model_executor.layers.mamba.ops.cpu.gdn_attention import register_cpu_gdn_attention_ops
            register_cpu_gdn_attention_ops()
            self._forward_method = self.forward_cpu
        # ...

    def forward_cpu(self, hidden_states, output):
        # CPU 前向：拆分 QKV、门控、调用 custom op
        mixed_qkvz, _ = self.in_proj_qkvz(hidden_states)
        ba, _ = self.in_proj_ba(hidden_states)
        if self.gqa_interleaved_layout:
            # Qwen3-Next layout: 需要重排
            query, key, value, z, b, a = self.fix_query_key_value_ordering(mixed_qkvz, ba)
            query, key, value = map(lambda x: rearrange(x, "l p d -> l (p d)"), (query, key, value))
            mixed_qkv = torch.cat((query, key, value), dim=-1)
        else:
            # Qwen3.5 layout: 直接切分
            qkv_size = (self.key_dim * 2 + self.value_dim) // self.tp_size
            z_size = self.value_dim // self.tp_size
            mixed_qkv, z = mixed_qkvz.split([qkv_size, z_size], dim=-1)
            z = z.reshape(z.size(0), -1, self.head_v_dim)
            b, a = ba.chunk(2, dim=-1)
        core_attn_out = torch.zeros((num_tokens, self.num_v_heads//self.tp_size, self.head_v_dim), dtype=hidden_states.dtype)
        torch.ops.vllm.cpu_gdn_attention_core(mixed_qkv, b, a, core_attn_out, _encode_layer_name(self.prefix))
        # 输出归一化并投影
        core_attn_out = self.norm(core_attn_out.reshape(-1, core_attn_out.shape[-1]), z.reshape(-1, z.shape[-1]))
        core_attn_out = rearrange(core_attn_out, "... h d -> ... (h d)")
        output[:num_tokens], _ = self.out_proj(core_attn_out)

```

# 评论区精华

Review 中的核心讨论包括：
- **l2norm 数值稳定性**：gemini-code-assist 建议在 float32 中计算平方和以避免 float16 溢出，但作者选择与 HuggingFace 参考实现保持一致，未修改。
- **自定义 op 注册方式**：vadiklyutiy 指出在 `__init__` 中导入并调用 `register_cpu_gdn_attention_ops` 显得不直观，作者后来改为在导入时通过模块级调用来显式注册，参考了 `pynccl.py` 的模式。
- **causal_conv1d 命名**：bigPYJ1151 建议添加 `_torch` 后缀以区别于可能的高性能版本，作者采纳。
- **update_block_size_for_backend 的合理性**：bigPYJ1151 认为 CPUAttentionBackend 应重写 `get_supported_kernel_block_sizes`，作者已添加该方法（返回 `MultipleOf(16)`），并解释了当前逻辑的效果。
- **triton.cdiv 缺失问题**：vadiklyutiy 询问 `cdiv` 引入的原因，作者解释是为了防止 CPU 上无 Triton 时 `index.py` 报错。

 - l2norm 数值稳定性 (correctness): 作者拒绝，选择与 HuggingFace 参考实现保持一致。
- 自定义 op 注册方式 (design): 作者随后改为在导入时通过模块级调用来显式注册，参考 `pynccl.py` 模式。
- causal_conv1d 命名约定 (style): 作者接受，函数重命名为 `causal_conv1d_torch` 和 `causal_conv1d_update_torch`。
- hybrid 模型 block size 对齐 (design): 作者已添加 `get_supported_kernel_block_sizes` 返回 `MultipleOf(16)`，并解释当前逻辑影响不大。
- triton.cdiv 缺失问题 (question): 作者解释是为了避免 CPU 上无 Triton 时 `index.py` 导入失败。

# 风险与影响

- 风险：技术风险分析：
 - **数值精度风险**：`l2norm` 对 float16 输入可能在极端值下溢出，但与 HF 参考实现一致，风险可控。
 - **性能风险**：当前所有 CPU GDN 算子均为纯 PyTorch 实现（循环或逐序列操作），在大 batch 或长序列下性能不如融合 kernel，PR 描述中提到后续会通过融合 /varlen kernel 优化。
 - **缺少单元测试**：未为新算子添加直接单元测试，仅依赖 CI 烟测试，未来回归风险增加。
 - **torch.compile 兼容性风险**：默认 torch.compile 模式下，Qwen3.5/3.6 会因 PyTorch Inductor 代码生成错误而失败，需要等 PyTorch 官方修复或合入 #40973 的补丁才能支持。PR 已注明当前在 compile 模式下会失败。
 - **Hybrid 模型 block size 对齐**：新增逻辑依赖 backend 的 `get_supported_kernel_block_sizes`，若后端未实现则跳过，不会崩溃，但可能使用次优配置。
- 影响：影响评估：
 - **用户影响**：使 Qwen 3.5 和 Qwen 3.6 能够在所有 CPU 上运行（包括 ARM 和 x86），扩大了模型覆盖范围；精度与 HF 一致，可投入生产验证。
 - **系统影响**：新增了 `torch.ops.vllm.cpu_gdn_attention_core` 自定义 op，在 CPU 上注册了 GDN 注意力后端；修改了 CPU 平台层的 block size 分配策略（仅 hybrid 模型）。
 - **团队影响**：为后续 CPU 性能优化（融合 kernel）奠定了基础，但当前实现需要额外的工程投入来达到最佳性能。ARM CI 增加了测试资源消耗。
 - 风险标记：缺少测试覆盖 , 核心路径变更 , 依赖 torch.compile 补丁 , 数值精度风险（l2norm）

# 关联脉络

- PR #41314 [CPU] Add FP8 W8A16 MoE support: 同为 CPU 后端特性，共享类似的 ops 注册与测试模式，且都扩展了 CPU 可运行模型范围。