# PR #48247 完整报告

- 仓库：`vllm-project/vllm`
- 标题：[Perf][ROCm] Add AITER custom AG/RS (DP only)
- 合并时间：2026-09-11 13:19
- 原文链接：http://prhub.com.cn/vllm-project/vllm/pull/48247

---

# 执行摘要

- 一句话：ROCm DP 通信接入 AITER 自定义 AG/RS
- 推荐动作：值得精读，尤其是负责 ROCm 分布式与 DP attention 的工程师。重点关注三处设计决策：(1) `_can_use_aiter_ag_rs` 用「DP 组 + sizes 为 None + FULL CUDA graph + uniform batch」四重条件把快路径限制在 uniform decode，混合 batch 与 prefill 自动回退 RCCL，这是正确性优先的取舍；(2) 用 `use_aiter_ag_rs` 角色标志复用同一个 `AiterCustomAllreduce` 实例，并把 AR 的启用条件收紧为 `use_aiter_allreduce`，避免 TP/DP 互相误触发，是本次 review 最有价值的设计收敛；(3) `reduce_scatterv` 中 uniform sizes → None 的归一化虽然是 AITER 路径的前置条件，但顺带影响了 NCCL symm mem 的判定，值得单独回归验证。另外建议后续跟进两点：给 `custom_reduce_scatter` 的返回值语义加一条注释或断言以消除未初始化显存疑虑，以及为 `_can_use_aiter_ag_rs` 的门控条件补一个不依赖 monkeypatch 的单测。

# 功能与动机

Tracking issue #48255（[Tracking][ROCm][Perf]: DP Attention performance）把「AITER Custom AG/RS - PR: https://github.com/vllm-project/vllm/pull/48247」列为提升 MLA 类模型（如 DSv3）DPA 性能的既定工作项，本 PR 即该项落地。PR body 说明：优化只作用于 DP 进程组的 dispatch/combine 通信，不改动 TP/EP 组上的任何 collective，因此在 DP attention + TP experts 场景下默认开启（可用 VLLM_ROCM_USE_AITER_CUSTOM_AR=0 关闭），目标收益是「~3% improved TPOT on 1k/1k」。

# 实现拆解

1. **通信器能力补齐 **（`vllm/distributed/device_communicators/aiter_custom_all_reduce.py`）：在 `AiterCustomAllreduce` 包装类上新增 `should_custom_ag` / `should_custom_rs` / `custom_all_gather` / `custom_reduce_scatter` 四个透传方法，把 AITER 侧原语暴露给 `CudaCommunicator`。由于 AITER 没有 grouped all-gather，AG 在模型侧仍拆成 hidden、topk_weights、topk_ids 三次调用。

2. **DP 组初始化与作用域隔离 **（`cuda_communicator.py`）：`__init__` 中新增分支，仅当 `"dp" in unique_name`、`world_size in (2, 4, 8)`、平台为 ROCm 且 AITER custom AR 打开时构造 `AiterCustomAllreduce`，并新增 `use_aiter_ag_rs` 标志区分用途；同时给 `all_reduce` 与 `_log_all_reduce_backend_selection` 的 AITER 分支补上 `self.use_aiter_allreduce` 前置条件，避免 DP 组误走 custom all-reduce、TP 组误走 AG/RS。

3. **分派门控**：新增 `_can_use_aiter_ag_rs(sizes)`，要求启用标志为真、`sizes is None`、`get_forward_context()` 中 `cudagraph_runtime_mode == CUDAGraphMode.FULL` 且 `batch_descriptor.uniform`；混合 batch 与 prefill 自动回退 RCCL，保证正确性优先。`reduce_scatterv` 里额外把「所有 size 相同」的 `sizes` 归一化为 `None`，让 uniform 语义能被 AITER 路径与既有 NCCL symm mem 路径统一识别。

4. **集合通信接入**：`all_gatherv` 在 pynccl 断言之前插入 AITER AG 分支（同时支持单 Tensor 与 Tensor 列表，失败即回退），`reduce_scatterv` 在 symm mem / pynccl 逻辑之前插入 AITER RS 分支；两条回退路径语义保持不变。

5. **图捕获适配 **（`vllm/distributed/parallel_state.py`）：`GroupCoordinator.graph_capture` 从全局 `rocm_aiter_ops.get_aiter_allreduce()` 改为取本组自身的 `device_communicator.aiter_ar_comm`，避免 TP 与 DP 两个组重复 capture 同一对象；模块级 `graph_capture` 新增 `get_dp_group().graph_capture(context)`，让 DP 组的 AG/RS buffer 也能进入图。

6. **配置与开关 **（`vllm/envs.py`）：经 review 决定不新增 env var，复用 `VLLM_ROCM_USE_AITER_CUSTOM_AR`（默认 True），只更新注释说明它同时启用 DP AG/RS。

7. **测试与基准配套**：`tests/utils.py` 的 `init_test_distributed_environment` / `multi_process_parallel` 增加 `data_parallel_size` 与 DP master port 支持（构造带 `_data_parallel_master_port_list` 的 `ParallelConfig`）；`tests/distributed/test_rocm_aiter_custom_ar.py` 新增 `test_rocm_aiter_custom_ag_rs`，含 eager 与 CUDA graph 两个执行体；`tests/distributed/test_comm_ops.py` 新增 `test_aiter_all_gather_precedes_pynccl`；`benchmarks/kernels/benchmark_device_communicators.py` 新增 `benchmark_ag_rs` 与按 collective 分组的 `COMM_COLLECTIVE` / `COLLECTIVE_BASELINE` 打分逻辑，使 AG/RS 各自与同类 NCCL baseline 对比而不是跨 collective 比较。

关键文件：
- `vllm/distributed/device_communicators/cuda_communicator.py`（模块 设备通信；类别 source；类型 core-logic；符号 _can_use_aiter_ag_rs, all_gatherv, reduce_scatterv, all_reduce）: 本 PR 的核心：DP 组 AITER 通信器初始化、`use_aiter_ag_rs` 作用域隔离、`_can_use_aiter_ag_rs` 门控，以及 `all_gatherv` / `reduce_scatterv` 中 AITER 快路径的插入与回退。
- `vllm/distributed/device_communicators/aiter_custom_all_reduce.py`（模块 集合通信；类别 source；类型 core-logic；符号 should_custom_ag, should_custom_rs, custom_all_gather, custom_reduce_scatter）: 对 AITER CustomAllreduce 的薄封装，本 PR 新增 4 个 AG/RS 透传方法，是 vLLM 侧调用 AITER 新原语的唯一入口。
- `vllm/distributed/parallel_state.py`（模块 并行状态；类别 source；类型 dependency-wiring；符号 GroupCoordinator.graph_capture, graph_capture）: `graph_capture` 从全局 AITER 查询改为按组取各自的 `aiter_ar_comm`，并把 DP 组纳入模块级 capture 范围，保证 DP AG/RS 能进入 FULL CUDA graph。
- `tests/distributed/test_rocm_aiter_custom_ar.py`（模块 通信测试；类别 test；类型 test-coverage；符号 _get_aiter_ag_rs_comm, _assert_aiter_handles_ag, _assert_aiter_handles_rs, eager_ag_rs）: 新增 `test_rocm_aiter_custom_ag_rs`，覆盖 eager 与 CUDA graph 两种执行方式下的 AG/RS 正确性，是新路径的主要回归保障。
- `benchmarks/kernels/benchmark_device_communicators.py`（模块 基准测试；类别 source；类型 benchmark；符号 benchmark_ag_rs, _calculate_speedup_info, COMM_COLLECTIVE, COLLECTIVE_BASELINE）: 新增 `benchmark_ag_rs` 并把结果按 collective 分组、各自对比同类 NCCL baseline，是验证 AG/RS 收益的基准工具。
- `tests/utils.py`（模块 测试工具；类别 test；类型 test-coverage；符号 init_test_distributed_environment, multi_process_parallel）: 测试脚手架新增 DP 支持（data_parallel_size、DP master port 与 ParallelConfig 构造），是新单测能够拉起 DP 组的前提。
- `vllm/envs.py`（模块 环境变量；类别 source；类型 configuration；符号 VLLM_ROCM_USE_AITER_CUSTOM_AR）: review 结论的落点：不新增 `VLLM_ROCM_USE_AITER_AG_RS`，复用 `VLLM_ROCM_USE_AITER_CUSTOM_AR`，只更新注释说明其额外语义。
- `tests/distributed/test_comm_ops.py`（模块 通信测试；类别 test；类型 test-coverage；符号 test_aiter_all_gather_precedes_pynccl）: 新增 `test_aiter_all_gather_precedes_pynccl`，锁定「AITER AG 优先于 pynccl 且不要求 pynccl 可用」这一分派顺序。

关键符号：_can_use_aiter_ag_rs, all_gatherv, reduce_scatterv, should_custom_ag, should_custom_rs, custom_all_gather, custom_reduce_scatter, GroupCoordinator.graph_capture, benchmark_ag_rs, eager_ag_rs, graph_ag_rs, test_rocm_aiter_custom_ag_rs, test_aiter_all_gather_precedes_pynccl, multi_process_parallel

## 关键源码片段

### `vllm/distributed/device_communicators/aiter_custom_all_reduce.py`

对 AITER CustomAllreduce 的薄封装，本 PR 新增 4 个 AG/RS 透传方法，是 vLLM 侧调用 AITER 新原语的唯一入口。

**`AiterCustomAllreduce`：新增 AG/RS 透传接口**

```python
class AiterCustomAllreduce:
    """对 AITER CustomAllreduce 的薄封装，统一暴露 AR / AG / RS 三类原语。"""

    def __init__(self, group, device, max_size=None):
        from aiter.dist.device_communicators.custom_all_reduce import (
            CustomAllreduce as _AiterCustomAllreduce,
        )
        if max_size is None:
            max_size = self.MAX_SIZE
        self._impl = _AiterCustomAllreduce(group, device, max_size=max_size)

    # ---- all-reduce：TP 组沿用，本 PR 未改变其行为 ----
    def should_custom_ar(self, inp: torch.Tensor) -> bool:
        return self._impl.should_custom_ar(inp)

    def custom_all_reduce(self, inp: torch.Tensor) -> torch.Tensor | None:
        return self._impl.custom_all_reduce(inp)

    # ---- 本 PR 新增：DP attention dispatch / combine 使用的 AG/RS ----
    def should_custom_ag(self, inp: torch.Tensor) -> bool:
        # 由 AITER 判断 shape / dtype / 对齐是否落在 kernel 支持范围内，
        # 不满足时 CudaCommunicator 会静默回退到 RCCL。
        return self._impl.should_custom_ag(inp)

    def should_custom_rs(self, inp: torch.Tensor, dim: int) -> bool:
        # 调用侧已把待切分维度 movedim 到 0，因此 dim 恒为 0
        return self._impl.should_custom_rs(inp, dim)

    def custom_all_gather(self, inp: torch.Tensor, dim: int = 0) -> torch.Tensor | None:
        return self._impl.custom_all_gather(inp, dim=dim)

    def custom_reduce_scatter(
        self, inp: torch.Tensor, out: torch.Tensor, dim: int = 0
    ) -> torch.Tensor | None:
        # 注意：AITER 实现为就地写入 out、成功时返回 None，
        # 其上游类型标注 Tensor | None 与实现不一致（PR 讨论中已确认）。
        return self._impl.custom_reduce_scatter(inp, out, dim=dim)

```

### `vllm/distributed/parallel_state.py`

`graph_capture` 从全局 AITER 查询改为按组取各自的 `aiter_ar_comm`，并把 DP 组纳入模块级 capture 范围，保证 DP AG/RS 能进入 FULL CUDA graph。

**`parallel_state.py`：按组捕获 AITER 通信器并把 DP 组纳入 capture**

```python
@contextmanager
def graph_capture(device, graph_capture_context=None):
    """全局 graph capture 上下文：现在把 DP 组也纳入 capture 范围。"""
    context = graph_capture_context or GraphCaptureContext(
        torch.cuda.Stream(device=device)
    )
    with (
        get_tp_group().graph_capture(context),
        get_pp_group().graph_capture(context),
        # 新增：DP 组的 AITER AG/RS 也需要在 capture 上下文中注册 buffer，
        # 否则 FULL CUDA graph 的 decode 无法把 AG/RS 收进图内。
        get_dp_group().graph_capture(context),
    ):
        yield context


class GroupCoordinator:
    @contextmanager
    def graph_capture(self, graph_capture_context=None):
        ...
        maybe_aiter_ar_context = nullcontext()
        ...
        if self.device_communicator is not None:
            ...
            # 只 capture 本组自己的 AITER 通信器：
            # 旧实现用全局 rocm_aiter_ops.get_aiter_allreduce()，TP 与 DP
            # 两个组会重复 capture 同一个对象（见 commit a634d16 的注释）。
            aiter_ar_comm = getattr(self.device_communicator, "aiter_ar_comm", None)
            if aiter_ar_comm is not None:
                maybe_aiter_ar_context = aiter_ar_comm.capture()
        ...
        with (
            torch.cuda.stream(stream),
            maybe_ca_context,
            maybe_fi_pcie_ipc_context,
            maybe_aiter_ar_context,
        ):
            yield graph_capture_context

```

# 评论区精华

- **开关设计**：Rohan138 在 `vllm/envs.py` 上提出不必新增 `VLLM_ROCM_USE_AITER_AG_RS`，「I wonder if we need a new env var or we can just keep AG/RS enabled by default with `VLLM_ROCM_USE_AITER_CUSTOM_AR`?」并引用 PR#46065 已把 AITER AR 移入 `CudaCommunicator`；tjtanaa 回复「Yes. Let's reuse the variable name.」，作者在 commit `fe4d78b6` 中删除新 env var。
- **通信器复用**：tjtanaa 要求复用 `self.aiter_ar_comm`、删除 `self.aiter_ag_rs_comm`，并去掉 `_aiter_ops.py` 中新增的 `is_custom_all_gather_enabled`；作者回复「I added a new attribute `use_aiter_ag_rs` to keep track of which mode (TP/DP) it's for」，靠角色标志而不是两个对象来隔离。
- **返回值丢弃争议**：depthfirst-app[bot] 给 `custom_reduce_scatter` 返回值被丢弃打了 MEDIUM，「If the operation fails and returns `None`, the `output` buffer—allocated with `torch.empty()`... could leak hidden states or tokens from other users' requests」；作者解释该接口是就地写、成功恒返回 None，AITER 自身类型标注有误，因此「ignoring for now」。
- **pynccl 前置断言**：coderabbitai 指出 `all_gatherv` 在 AITER 分支之前就断言 pynccl 可用，`VLLM_DISABLE_PYNCCL=1` 时会把本可走的 AITER AG 变成 `AssertionError`；作者在 commit `afb4886` 修复并补了 `test_aiter_all_gather_precedes_pynccl`。
- **与 SP/DCP/ 融合算子的关系**：Rohan138 追问 AR+RMSNorm 融合（#36066 / #36851）与 SP/DCP 的交互，作者回答 SP 的 RS/AG 都在 TP 组、DCP 有自己的 `"dcp"` 组，新路径只在 DP 组生效，并称「Probably not a blocker for this particular PR」。
- **流程层面**：mergify 多次提示 merge conflict，tjtanaa 要求「rebase then reevaluate the rebase code integrity」，AndreasKaratzas 因队列拥堵主动取消过一次 CI；最终 Rohan138 与 tjtanaa 均 APPROVED。

 - DP AG/RS 与 TP AR 是否共用同一个 AITER 通信器 (design): 采纳共享通信器方案，新增 `use_aiter_ag_rs` 角色标志区分 TP/DP 用途，并在 `all_reduce` 与后端日志中补上 `self.use_aiter_allreduce` 前置条件。
 - 是否新增 VLLM_ROCM_USE_AITER_AG_RS 环境变量 (design): 删除新 env var，复用 `VLLM_ROCM_USE_AITER_CUSTOM_AR`（默认 True），commit `fe4d78b6` 落地，`envs.py` 仅保留注释更新。
 - custom_reduce_scatter 返回值被丢弃可能返回未初始化显存 (correctness): 按 AITER 实际行为接受该风险，未加断言或回退；属于被显式记录的残余风险。
 - all_gatherv 在 AITER 分支前断言 pynccl 可用 (correctness): 已修复：把 AITER 分支移到 pynccl 断言之前，只在实际回退路径断言；commit `afb4886` 并补 `test_aiter_all_gather_precedes_pynccl`。
 - 与 AR+RMSNorm 融合、SP / DCP 的作用域边界 (design): 确认作用域互不重叠，不作为阻塞项；但作者也承认对 SP/DCP 实现不熟，属于基于组归属的推断。
 - 注释措辞与 rebase/CI 流程 (style): 注释已改为 cuda/rocm；PR 经多轮 rebase 后通过 AMD CI（剩余失败用例与 nightly 一致），Rohan138 与 tjtanaa 最终 APPROVED。

# 风险与影响

- 风险：
 1. **`reduce_scatterv` 归一化带来的跨路径副作用**：`sizes` 全相同时被改写为 `None`，会让既有 `use_symm_mem = sizes is None and should_nccl_symm_mem_ag_rs()` 以及 `_can_use_aiter_ag_rs` 的分支条件发生变化——此前传 uniform sizes 列表的调用方一定不走 symm mem，现在可能走。这是本 PR 中唯一改动到非 AITER 路径的逻辑，需要针对 SP / DCP / chunked prefill 场景做回归确认。
 2. **未初始化显存返回风险**：`custom_reduce_scatter(input_tensor, output, dim=0)` 的返回值被丢弃后直接 `return output.movedim(...)`，若 AITER 未真正写入，多用户服务场景下 `torch.empty` 的内容可能泄漏给调用方；作者已确认 AITER 实现为就地写且恒返回 None，但该结论依赖外部库版本行为，属于被接受的残余风险。
 3. **默认开启的行为变更**：ROCm + DP attention + TP experts 的部署在 AITER custom AR 打开时（默认 True）会自动切换 DP 通信实现，唯一回退手段是 `VLLM_ROCM_USE_AITER_CUSTOM_AR=0`，这同时会关掉 TP 组的 AITER AR，粒度较粗。
 4. **与 AITER 版本的耦合**：`should_custom_ag` / `should_custom_rs` / `custom_all_gather` 直接透传到 `_impl`，老版本 AITER 缺少这些方法时会在运行期抛 `AttributeError`，代码中没有 `hasattr` 保护或降级日志。
 5. **图捕获路径扩大**：模块级 `graph_capture` 现在无条件调用 `get_dp_group()`，若某些调用场景下 DP 组未初始化（`get_dp_group` 内部为 assert）会直接失败；同时每次 capture 都会额外进入 DP 组的 capture 上下文。
 6. **收益不稳定且未完全解释**：作者数据中 1k/1k 在 conc 16/32 出现 −5.37% / −2.57% 的 TPOT 回退，8k/1k 在 conc 2、32 出现 −11.53% / −7.02%，PR 未给出解释，无法区分噪声与门控回退带来的额外开销。
 7. **门控逻辑缺少直测**：`test_aiter_all_gather_precedes_pynccl` 直接 `monkeypatch` 掉 `_can_use_aiter_ag_rs` 返回 True，真正决定「uniform + FULL graph」的门控条件没有独立单测覆盖。
 - 影响：**对用户**：ROCm（MI300 系列）+ DP attention 部署默认获得 DP 通信加速，1k/1k 低并发 TPOT 提升 3%~17%，中高并发约 2%~3%；gsm8k 精度 0.9469 对 nightly 0.9484，在 stderr 范围内无回退。接口与配置未变，无需改启动参数，仅需在异常时用 `VLLM_ROCM_USE_AITER_CUSTOM_AR=0` 关闭。**对系统**：DP 组的 collective 分派顺序、`graph_capture` 覆盖范围（新增 DP 组）、以及 `reduce_scatterv` 对 uniform sizes 的处理语义都发生了改变，属于分布式核心路径变更，但都由 `_can_use_aiter_ag_rs` 的门控和既有回退分支兜底，TP/EP/SP/DCP 组的 collectives 不受影响。**对团队**：新增了一条 ROCm 专有的通信快路径，后续 AITER 与 vLLM 需要在 `should_custom_*` 契约上同步演进；同时引入了 DP 组级别的测试脚手架（`data_parallel_size` 支持），对后续 DP 相关 PR 有复用价值。
 - 风险标记：核心通信路径变更 , 默认开启行为变更 , symm mem 路径受牵连 , 未初始化显存风险 , AITER 版本耦合 , 收益波动未解释 , 门控逻辑缺直测

# 关联脉络

- PR #51692 [ROCm][Perf] Add bpreshuffled blockscaled fp8 GEMM: 与 #48247 同属 tracking issue #48255 的 ROCm DPA 性能工作项，都是把 AITER 内核接入 vLLM 的注意力 / 通信执行路径。
- PR #56098 [ROCm][Bugfix][Perf] Tune multi-stream shared experts use; wvSplitKrc fixes: 同样修改 `vllm/distributed/parallel_state.py`，且聚焦 ROCm 通信 / 多流重叠的执行路径，与本 PR 的 graph capture 改动存在协同关系。
- PR #54889 [DCP][Kernel][Perf] Fuse the empty-shard LSE mask into the A2A pack kernel: 本 PR review 中 Rohan138 专门追问 DCP 组与新分派逻辑的关系；该 PR 属 DCP 集合通信 / 内核优化线，与本 PR「按通信组限定快路径」的思路同源。
- PR #53695 [ROCm][Feature] Support KV connectors with ROCM_AITER_UNIFIED_ATTN: 同为 ROCm AITER 后端能力接通（attention + 通信），说明 AITER 在 vLLM ROCm 栈中的接入面在持续扩大。
- PR #55531 [KV Connector] Support symmetric DCP disagg for hybrid mamba models: 涉及 `vllm/config/parallel.py` 与 DCP/DP 并行组语义，与本 PR 新增的 DP 组 graph capture、uniform 分片判定存在概念交集。