执行摘要
- 一句话:启用 SimpleCPUOffloadConnector 的 ROCm 后端支持
- 推荐动作:值得精读,尤其是
cuda_mem_ops.py 中平台抽象与函数动态解析的模式,以及 cache_kernels.cu 中条件编译与 fallback 的设计。这些做法可复用至其他需要跨平台加速器内存操作的场景。
功能与动机
根据 Issue #40397,SimpleCPUOffloadConnector 原先仅支持 CUDA,AMD GPU 用户无法使用该功能。本 PR 填补了 ROCm 支持的空白,使 vLLM 在 AMD 平台上也能基于 CPU 卸载 KV 缓存。
实现拆解
-
平台探测与库加载:在 vllm/v1/simple_kv_offload/cuda_mem_ops.py 中新增 from vllm.platforms import current_platform,利用 current_platform.is_rocm() 判断平台,并通过 ctypes.CDLL 加载 libamdhip64.so 获取 hipMemcpyBatchAsync 符号。
-
ROCm 批处理拷贝函数封装:在 _resolve_batch_memcpy() 中为 ROCm 分支设置函数签名与参数类型,并以 numAttrs=0 调用(因为 ROCm 7.2.1/7.2.2 中 numAttrs>0 返回 hipErrorNotSupported)。CUDA 路径保持不变。
-
C++ 内核侧对应修改:在 csrc/cache_kernels.cu 的 swap_blocks_batch 函数中增加 ROCm 条件编译分支(USE_ROCM && HIP_VERSION >= 70100000),调用 hipMemcpyBatchAsync,并统一 fallback 为逐 hipMemcpyAsync 的循环。
-
测试平台兼容性放宽:将 tests/v1/simple_kv_offload/test_integration.py 中的 current_platform.is_cuda() 改为 current_platform.is_cuda_alike(),使测试在 ROCm 上可被识别(但因无实际 GPU 仍会跳过)。
-
调度测试边界修复:在 tests/v1/simple_kv_offload/test_scheduler.py 的 make_request 中将 num_tokens 从 num_blocks * BLOCK_SIZE 改为 num_blocks * BLOCK_SIZE + 1,避免前缀缓存因对齐问题截断最后一个块。
关键文件:
vllm/v1/simple_kv_offload/cuda_mem_ops.py(模块 核心卸载;类别 source;类型 dependency-wiring;符号 _resolve_batch_memcpy, _batch_memcpy_fn, build_params, copy_blocks): 核心修改文件:新增 ROCm 批处理内存拷贝动态解析与调用逻辑,是功能启用的关键。
csrc/cache_kernels.cu(模块 调度器;类别 other;类型 core-logic;符号 swap_blocks_batch): C++ 侧添加 ROCm 批处理拷贝分支与 fallback,确保内核级兼容性。
tests/v1/simple_kv_offload/test_integration.py(模块 测试;类别 test;类型 test-coverage): 修改平台判别条件,使集成测试可在 ROCm 上识别并执行(当前因无 GPU 仍跳过)。
tests/v1/simple_kv_offload/test_scheduler.py(模块 测试;类别 test;类型 test-coverage;符号 make_request): 修复 token 数量边界问题,避免前缀缓存截断,属于测试质量改进。
关键符号:_resolve_batch_memcpy, build_params, copy_blocks, swap_blocks_batch, make_request
关键源码片段
vllm/v1/simple_kv_offload/cuda_mem_ops.py
核心修改文件:新增 ROCm 批处理内存拷贝动态解析与调用逻辑,是功能启用的关键。
# vllm/v1/simple_kv_offload/cuda_mem_ops.py
import ctypes
from typing import Any, NamedTuple
import numpy as np
import torch
from vllm.logger import init_logger
from vllm.platforms import current_platform
logger = init_logger(__name__)
# ... (pin_tensor, _CUmemLocation, _CUmemcpyAttributes 等保持不变 )
_BATCH_MEMCPY_FUNC_TYPE = ctypes.CFUNCTYPE(
ctypes.c_uint, # CUresult / hipError_t
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p,
ctypes.c_void_p,
)
_batch_memcpy_fn: Any = None
def _resolve_batch_memcpy():
"""Resolve the platform batch-memcpy entry point (one-time).
* CUDA: ``cuMemcpyBatchAsync`` via ``cuGetProcAddress`` (uses
srcAccessOrder=STREAM via one attributes entry).
* ROCm: ``hipMemcpyBatchAsync`` from libamdhip64 (ROCm 7.1+). ROCm
7.2.1 or 7.2.2 rejects any call with ``numAttrs > 0``
(see ROCm/clr @ rocm-7.2.1 hipamd/src/hip_memory.cpp:2819-2822), so
we call with ``numAttrs=0``.
Raises ``RuntimeError`` if the symbol is unavailable (older CUDA
driver, ROCm < 7.1, unusual install). The connector requires the
batch API.
"""
if current_platform.is_rocm():
try:
lib = ctypes.CDLL("libamdhip64.so", mode=ctypes.RTLD_GLOBAL)
fn = lib.hipMemcpyBatchAsync
except (OSError, AttributeError) as e:
raise RuntimeError(
"hipMemcpyBatchAsync is unavailable in this ROCm install; "
"SimpleCPUOffloadConnector requires ROCm 7.1+."
) from e
fn.restype = ctypes.c_uint
fn.argtypes = [
ctypes.c_void_p, # dsts
ctypes.c_void_p, # srcs
ctypes.c_void_p, # sizes
ctypes.c_size_t, # count
ctypes.c_void_p, # attrs
ctypes.c_void_p, # attrIdxs
ctypes.c_size_t, # numAttrs
ctypes.c_void_p, # failIdx
ctypes.c_void_p, # stream
]
return fn
from cuda.bindings import driver as drv
err, ptr, _ = drv.cuGetProcAddress(b"cuMemcpyBatchAsync", 12080, 0)
if err != drv.CUresult.CUDA_SUCCESS:
raise RuntimeError(f"cuGetProcAddress(cuMemcpyBatchAsync) failed: {err}")
return _BATCH_MEMCPY_FUNC_TYPE(ptr)
csrc/cache_kernels.cu
C++ 侧添加 ROCm 批处理拷贝分支与 fallback,确保内核级兼容性。
// csrc/cache_kernels.cu (swap_blocks_batch 片段 )
#if !defined(USE_ROCM) && defined(CUDA_VERSION) && CUDA_VERSION >= 12080
static_assert(sizeof(CUdeviceptr) == sizeof(int64_t));
// CUDA 12.8+: 使用 cuMemcpyBatchAsync ( 略 )
// ...
return;
#elif defined(USE_ROCM) && defined(HIP_VERSION) && HIP_VERSION >= 70100000
{
// ROCm 7.1+ 使用 hipMemcpyBatchAsync。
// ROCm 7.2.1/7.2.2 中 numAttrs>0 会返回 hipErrorNotSupported,
// 因此调用时设置 numAttrs=0。
hipMemcpyAttributes attr = {};
size_t attrs_idx = 0;
size_t fail_idx = 0;
hipError_t result = hipMemcpyBatchAsync(
reinterpret_cast<void**>(dst_data),
reinterpret_cast<void**>(src_data),
reinterpret_cast<size_t*>(size_data),
static_cast<size_t>(n),
&attr, &attrs_idx,
0, // numAttrs = 0,避免版本兼容问题
&fail_idx,
static_cast<hipStream_t>(stream));
TORCH_CHECK(result == hipSuccess,
"hipMemcpyBatchAsync failed at index ", fail_idx,
" with error ", result);
return;
}
#endif
// 通用 fallback: 逐元素异步拷贝
for (int64_t i = 0; i < n; i++) {
cudaMemcpyAsync(reinterpret_cast<void*>(dst_data[i]),
reinterpret_cast<void*>(src_data[i]),
reinterpret_cast<size_t*>(size_data)[i],
cudaMemcpyDefault,
stream);
}
评论区精华
-
错误处理健壮性(gemini-code-assist[bot]): 指出若 libamdhip64.so 加载失败或符号不存在时引擎会崩溃,建议返回 None 并触发 fallback。作者后来回复“this review comment is obsolete”,暗示后续提交已解决。
-
注释冗余性(tjtanaa): 认为对 CUmemcpyAttributes 和 hipMemcpyAttributes 兼容性的注释过于冗长,建议简化。作者表示同意并已调整。
-
后续优化方向(mawong-amd): 提及 PR #41386 升级 ROCm 基础镜像到 7.2.2 后,未来可使用统一的 numAttrs > 0 调用;PR #41474 因本 PR 在 ROCm 上更具相关性。这些为后续改进提供了线索。
- 运行时解析失败时的降级处理 (correctness): 评论被标注为过时,但 Python 侧未实现降级;C++ 侧已有循环 fallback。风险仍存在。
- 注释冗长性 (style): 作者同意并删除了多余的注释块。
- 后续 ROCm 版本统一化 (design): 未在本次 PR 中解决,留作后续优化。
风险与影响
- 风险:
- ROCm 版本兼容:当前代码针对 ROCm 7.1+ 并特殊处理 7.2.1/7.2.2,若未来版本修复
numAttrs>0 问题,需调整条件逻辑,否则会错过性能优化。
- 符号解析失败降级:虽然 C++ 侧已有 fallback 循环,但 Python 侧的
_resolve_batch_memcpy 若失败会直接抛出 RuntimeError,没有继续降级,可能导致引擎在低版本 ROCm 上无法启动。
- 回归风险:对
test_scheduler.py 中 token 数量的调整可能影响其他依赖测试;但改动很小,风险较低。
- 影响:用户:AMD GPU 用户现在可以使用 VLLM_USE_SIMPLE_KV_OFFLOAD=1 在 CPU 上卸载 KV 缓存,从而在显存不足时扩展模型容量,精度与 CUDA 基线一致(lm-eval 测试通过)。
系统:SimpleCPUOffloadConnector 路径新增 ROCm 分支,增加了约 90 行代码,但整体架构清晰,未影响 CUDA 路径。
团队:为后续统一批处理拷贝接口(如 #39306)奠定了基础,但需关注 ROCm 版本演进带来的条件分化。
- 风险标记:ROCm 版本兼容分化, Python 侧无符号解析降级, cache_kernels.cu 条件编译复杂度增加
关联脉络
- PR #40397 Add ROCm support for simple offload connector: 本 PR 直接解决的 Issue,描述了需求与原始报错堆栈。
- PR #41386 [ROCm] Bump base image to ROCm 7.2.2: 评论提及合并后可能允许统一 numAttrs>0 调用。
- PR #41474 [ROCm] Enable random-access batched copy for kv offload: 本 PR 后该特性在 ROCm 上更具相关性。
- PR #39306 [RFC] Refactor batch memcpy to use unified numAttrs>0: 评论提及与未来统一调用接口相关。
参与讨论