# PR #40264 完整报告

- 仓库：`vllm-project/vllm`
- 标题：[ROCm] Profiler api support for ROCm MORI toy proxy server in PD Disaggregation
- 合并时间：2026-05-07 16:58
- 原文链接：http://prhub.com.cn/vllm-project/vllm/pull/40264

---

# 执行摘要

- 一句话：为 MORI 代理服务器添加 profiler API 支持
- 推荐动作：该 PR 变更清晰，适合想了解 PD 分离和 KV Connector profiling 的开发者快速阅读。设计上使用 asyncio 并发发送请求，并正确使用锁机制处理竞态条件，值得借鉴。

# 功能与动机

在 ROCm MORI KV Connector 的 PD 分离部署中，用户需要通过代理服务器统一管理 prefill 和 decode 实例。现有代理服务器缺乏性能分析接口，无法远程控制 torch profiler。此 PR 通过在代理服务器上暴露 /start_profile 和 /stop_profile 端点，使得用户可以通过统一的 API 启动和停止所有 decode 服务器的 profiler，并收集 trace 文件用于性能分析。

# 实现拆解

1. 新增依赖与命令行参数：在文件头部添加 `argparse` 和 `urlparse` 导入，并在 `__main__` 块中使用 `argparse` 解析 `--port` 参数，替换原先硬编码的端口号。
2. 实现 `send_profile_cmd` 核心函数：异步函数接收 `req_data` 和 `profiler_cmd`（仅允许 `"start"` 或 `"stop"`）。通过 `_list_lock` 获取 `prefill_instances` 和 `decode_instances` 的本地副本，避免多线程竞态条件。若没有已注册的实例，则直接抛出 `RuntimeError`。随后使用 `aiohttp` 并发地向所有实例发送 POST 请求，URL 格式为 `http://hostname:port/{cmd}_profile`。所有请求通过 `asyncio.gather` 并发执行，并统一处理异常和 HTTP 错误状态码。最后返回第一个成功响应的 JSON。
3. 添加 `/start_profile` 和 `/stop_profile` 端点：使用 Quart 的 `@app.post` 装饰器注册两个路由，分别解析请求 JSON 并调用 `send_profile_cmd`，遇到异常时记录日志并返回 500 错误。
4. 主入口配置调整：将 `app.run(port=10001)` 替换为 `app.run(port=args.port)`，使端口可通过 `--port` 参数指定。
本次变更为纯新增功能，未引入测试文件，但 PR body 中提供了详细的部署和验证步骤，证明变更可正常工作。

关键文件：
- `examples/disaggregated/disaggregated_serving/moriio_toy_proxy_server.py`（模块 代理服务器；类别 source；类型 dependency-wiring；符号 send_profile_cmd, start_profile, stop_profile）: 添加了 profiler API 支持，包括 send_profile_cmd 函数和 /start_profile、/stop_profile 端点，以及端口参数配置。

关键符号：send_profile_cmd, start_profile, stop_profile

## 关键源码片段

### `examples/disaggregated/disaggregated_serving/moriio_toy_proxy_server.py`

添加了 profiler API 支持，包括 send_profile_cmd 函数和 /start_profile、/stop_profile 端点，以及端口参数配置。

```python
async def send_profile_cmd(req_data: dict, profiler_cmd: str):
    # profiler_cmd 必须是 "start" 或 "stop"
    assert profiler_cmd in {"start", "stop"}

    # 加锁获取实例列表的本地副本，避免竞态条件
    with _list_lock:
        p_instances = list(prefill_instances)
        d_instances = list(decode_instances)

    if not p_instances and not d_instances:
        raise RuntimeError(
            "Service Unavailable: No prefill or decode instances are registered."
        )

    headers = {
        "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}",
    }

    tasks = []

    # 使用 aiohttp 并发地向所有 prefill 和 decode 实例发送 profiler 请求
    async with aiohttp.ClientSession(
        timeout=aiohttp.ClientTimeout(total=60)
    ) as session:
        for instances in (p_instances, d_instances):
            for inst in instances:
                _p = urlparse(inst["request_address"])
                url = f"http://{_p.hostname}:{_p.port}/{profiler_cmd}_profile"

                tasks.append(
                    session.post(
                        url,
                        json=req_data,
                        headers=headers,
                    )
                )

        responses = await asyncio.gather(*tasks, return_exceptions=True)

        for r in responses:
            if isinstance(r, Exception):
                raise r
            if r.status >= 400:
                msg = await r.text()
                raise RuntimeError(f"{profiler_cmd}_profile failed: {r.status}, {msg}")

        return await responses[0].json()


@app.post("/start_profile")
async def start_profile():
    try:
        req_data = await request.get_json()
        return await send_profile_cmd(req_data, "start")
    except Exception as e:
        logger.exception("start_profile failed: %s", e)
        return await make_response((str(e), 500))


@app.post("/stop_profile")
async def stop_profile():
    try:
        req_data = await request.get_json()
        return await send_profile_cmd(req_data, "stop")
    except Exception as e:
        logger.exception("stop_profile failed: %s", e)
        return await make_response((str(e), 500))

```

# 评论区精华

在代码审查中，gemini-code-assist[bot] 指出了 `send_profile_cmd` 函数中的竞态条件：直接访问全局 `prefill_instances` 和 `decode_instances` 列表而未加锁，可能导致迭代时列表被后台线程修改而抛出 `RuntimeError`。建议使用已有的 `_list_lock` 创建本地副本。该建议被采纳，提交者在后续版本中修复了该问题。此次讨论体现了对并发安全性的重视，即使是在示例脚本中。

- send_profile_cmd 中访问全局列表的竞态条件 (correctness): 采纳建议，在函数开头用 with _list_lock 创建本地副本 p_instances 和 d_instances。

# 风险与影响

- 风险：变更为示例脚本，不涉及任何生产代码，风险极低。唯一的风险是如果代理服务器与实例之间网络不通，profiler 请求会超时并返回错误，但属于预期行为。此外，send_profile_cmd 中已使用 _list_lock 保护全局列表，竞态条件已修复。
- 影响：对用户：为使用 MORI KV Connector 的 PD 分离部署用户提供了便捷的性能分析接口。对系统：仅影响 MORI 代理服务器，不影响 vLLM 核心组件。对团队：降低了在 ROCm 平台上调试和性能分析的门槛。
- 风险标记：无显著风险，仅示例变更

# 关联脉络

- PR #40549 [ROCm] Enable SimpleCPUOffloadConnector on ROCm: 同为 ROCm KV Connector 相关 PR，增强了 ROCm 上的 KV 卸载能力，与 MORI 代理的 profiler API 互补。
- PR #40731 nixl refactor: new transfer design: KV Connector 传输层重构，与 MORI 代理同属 KV Connector 生态。
- PR #41795 [KV Offload] Return None from lookup() for in-flight blocks: 修复 KV offload 中 lookup 的 in-flight 块处理，提升 ROCm KV Connector 稳定性。