跳转至

KV缓存CPU卸载指南

概述

KV缓存CPU卸载功能可将非活跃的KV缓存块从NPU内存卸载至CPU内存,使vLLM在NPU内存受限时能够处理更长的上下文或更多并发请求。当NPU上发生前缀缓存未命中但数据存在于CPU内存时,KV缓存会异步加载回NPU,从而降低重计算延迟。

此功能基于 vLLM 的 OffloadingConnector 框架构建。上游的 CPUOffloadingSpec 和 TieringOffloadingSpec 名称已注册到 Ascend NPU 实现中,这些实现使用专用的 NPU 流在 NPU 和 CPU 之间进行高效的异步数据传输。

核心概念

  • CPU 块池:预分配的 CPU 内存块池。仅 CPU 的 spec 在可用时使用固定张量;多层级 spec 使用共享的 mmap 区域,以便调度器和次级层级可以访问相同的字节。
  • 异步传输:NPU 到 CPU(D2H)和 CPU 到 NPU(H2D)的传输在单独的 NPU 流上执行,与计算重叠以最小化延迟影响。
  • LRU 淘汰:CPU 侧块池使用 LRU(最近最少使用)淘汰策略来高效管理有限的 CPU 内存。
  • 多层级卸载:TieringOffloadingSpec 复用 vLLM 的层级管理器,并支持 CPU 主层级以及可选的次级层级(如文件系统存储)。

使用方法

Python API

from vllm import LLM, SamplingParams
from vllm.config import KVTransferConfig

kv_transfer_config = KVTransferConfig(
    kv_connector="OffloadingConnector",
    kv_role="kv_both",
    kv_connector_extra_config={
        "cpu_bytes_to_use": 8 * (1 << 30),
        "blocks_per_chunk": 8,
        "spec_name": "CPUOffloadingSpec",
    },
)

llm = LLM(
    model="Qwen/Qwen3-0.6B",
    gpu_memory_utilization=0.5,
    kv_transfer_config=kv_transfer_config,
)

sampling_params = SamplingParams(max_tokens=100, temperature=0.0)
outputs = llm.generate(["Hello, my name is"], sampling_params)
for output in outputs:
    print(f"Prompt: {output.prompt!r}")
    print(f"Generated: {output.outputs[0].text!r}")

在线服务

vllm serve Qwen/Qwen3-0.6B \
    --gpu-memory-utilization 0.5 \
    --kv-transfer-config '{
        "kv_connector": "OffloadingConnector",
        "kv_role": "kv_both",
        "kv_connector_extra_config": {
            "cpu_bytes_to_use": 8589934592,
            "blocks_per_chunk": 8,
            "spec_name": "CPUOffloadingSpec"
        }
    }'

多层级卸载

kv_transfer_config = KVTransferConfig(
    kv_connector="OffloadingConnector",
    kv_role="kv_both",
    kv_connector_extra_config={
        "cpu_bytes_to_use": 8 * (1 << 30),
        "blocks_per_chunk": 8,
        "spec_name": "TieringOffloadingSpec",
        "pin_shared_mmap": True,
        "secondary_tiers": [
            {
                "type": "fs",
                "root_dir": "/tmp/vllm_kv_offload",
            }
        ],
    },
)

配置参数

  • kv_connector: Must be set to "OffloadingConnector".
  • kv_role: Set to "kv_both" to enable both storing and loading of KV cache.
  • cpu_bytes_to_use: Total bytes reserved for the CPU tier across all workers. This is required by the vLLM offloading specs.
  • blocks_per_chunk: Number of NPU KV-cache blocks in one offloaded chunk. It must be greater than zero. Alternatively, block_size can specify the chunk size in tokens when all KV-cache groups use the same block size; the two options are mutually exclusive.
  • spec_name: Use the upstream names "CPUOffloadingSpec" for CPU-only offload or "TieringOffloadingSpec" for multi-tier offload. vLLM Ascend transparently maps them to the NPU implementations.
  • pin_shared_mmap: Boolean, defaults to false. Applies to TieringOffloadingSpec; set to true to register its shared CPU mapping as pinned host memory.
  • secondary_tiers: Optional list of vLLM tiering backends used by TieringOffloadingSpec. Each entry is a dict; common keys:
    • type: Backend type. Use "fs" for filesystem storage.
    • root_dir: Directory the tier writes block files into.
    • n_read_threads / n_write_threads: Thread-pool sizes for the tier's I/O. For high-bandwidth backends (e.g. 3FS over RDMA) increasing these helps saturate parallel bandwidth.

Pinning the shared CPU tier

pin_shared_mmap defaults to false for TieringOffloadingSpec. To enable registration on supported Ascend runtimes, set pin_shared_mmap to true in kv_connector_extra_config. This registers the existing shared CPU mapping as page-locked host memory for direct batched NPU transfers:

{
    "kv_connector": "OffloadingConnector",
    "kv_role": "kv_both",
    "kv_connector_extra_config": {
        "spec_name": "TieringOffloadingSpec",
        "cpu_bytes_to_use": 8589934592,
        "blocks_per_chunk": 8,
        "pin_shared_mmap": true,
        "secondary_tiers": [
            {"type": "fs", "root_dir": "/tmp/vllm_kv_offload"}
        ]
    }
}

Registration scope follows the cache layout automatically: replicated MLA workers register the whole shared region; other layouts register each worker's page-aligned slots when the upstream vLLM range API is available, otherwise the whole region is registered.

If the Ascend extension lacks the required host-registration/batched-copy APIs, or registration fails, the worker rolls back completed registrations and falls back to pageable mmap with a warning. Startup logs report the registered bytes and range count when registration succeeds.

Larger shared CPU regions require more pages to be populated (pre-faulted), so increasing cpu_bytes_to_use increases startup population time. On supported vLLM versions, segmented mappings and disjoint MLA population shards reduce this cost. Population is required even when pin_shared_mmap is false; benchmark startup time separately from KV-transfer bandwidth.

CPUOffloadingSpec uses PyTorch's pinned tensor allocator and does not use this option.

调优文件系统(SSD / 3FS)次级层级

fs 层级复用了 vLLM 的批处理文件系统实现。它在启动时探测 O_DIRECT,当文件系统拒绝直接 I/O 时自动回退到缓冲 I/O。要获得最佳的磁盘/3FS 卸载吞吐量:

  • 增加 blocks_per_chunk 以传输更大的块并减少元数据开销,同时考虑由此产生的更粗粒度的缓存命中粒度。
  • 提高 n_read_threads / n_write_threads 以匹配后端的并行度(基于 RDMA 的 3FS 比本地 SSD 受益于更高的并发性)。
  • 保持 CPU 主层级(cpu_bytes_to_use)足够大,以便较慢的磁盘层级仅用于真正冷的数据——只有当工作集超过 CPU 容量时,次级层级才能提高性能。
  • 文件系统(SSD / 3FS)次级层级的 kvcache 淘汰策略仍在开发中,将在未来版本中支持。

工作原理

  1. 正常推理:KV缓存块照常在NPU上计算并存储。
  2. 卸载至CPU:当NPU内存已满且需要新块时,非活跃的KV缓存块通过专用D2H NPU流异步复制到CPU内存。
  3. 前缀缓存命中(CPU):当请求与之前计算的数据共享前缀,且NPU上未找到前缀缓存但CPU内存中存在时,KV缓存块通过专用H2D NPU流从CPU异步加载回NPU。
  4. LRU管理:当CPU内存已满时,CPU块池使用LRU淘汰策略丢弃最近最少使用的块。

可选:KV缓存事件

您可以启用KV缓存事件发布以进行监控或调试:

from vllm.config import KVEventsConfig

kv_events_config = KVEventsConfig(
    enable_kv_cache_events=True,
    publisher="zmq",
    endpoint="tcp://*:5555",
    topic="kv_events",
)

llm = LLM(
    model="Qwen/Qwen3-0.6B",
    gpu_memory_utilization=0.5,
    kv_transfer_config=kv_transfer_config,
    kv_events_config=kv_events_config,
)

注意事项

  • This feature requires vLLM v1 engine.
  • Adjust cpu_bytes_to_use based on available CPU memory. Reserving too much may cause out-of-memory errors on the host.
  • CPUOffloadingSpec uses pinned (page-locked) tensors when available. TieringOffloadingSpec uses a shared mmap primary tier and attempts host registration when pin_shared_mmap is enabled. Benchmark offload bandwidth on the target host and CANN version.
  • The gpu_memory_utilization parameter controls how much NPU memory is reserved for KV cache. Lower values leave less NPU memory for KV cache, making offloading more active.
  • For production workloads, benchmark with realistic request patterns to find the optimal cpu_bytes_to_use and blocks_per_chunk settings.