压缩和解压缩 KV Cache#

compress 接口定义如下:

compress(instance_id: str, method: str, location: str, tokens: list[int]) -> event_id: str, num_tokens: int
decompress(instance_id: str, method: str, location: str, tokens: list[int]) -> event_id: str, num_tokens: int

这两个函数使用存储位置中的给定方法对由 tokens 指定的 KV Cache 块进行压缩/解压缩。控制器返回一个 event_id 和计划进行压缩或解压缩的令牌数量。

示例用法:#

首先,我们需要一个 yaml 文件 example.yaml 来正确配置 lmcache 实例:

chunk_size: 256
local_cpu: True
max_local_cpu_size: 5

# cache controller configurations
enable_controller: True
lmcache_instance_id: "lmcache_default_instance"
controller_pull_url: "localhost:9001"
lmcache_worker_ports: 8001

# Peer identifiers
p2p_host: "localhost"
p2p_init_ports: 8200

第二,我们需要在 8000 端口启动 vllm/lmcache 实例:

CUDA_VISIBLE_DEVICES=0 LMCACHE_CONFIG_FILE=example.yaml vllm serve meta-llama/Llama-3.1-8B-Instruct --max-model-len 4096  --gpu-memory-utilization 0.8 --port 8000 --kv-transfer-config '{"kv_connector":"LMCacheConnectorV1", "kv_role":"kv_both"}'

第三,我们需要在 9000 端口启动 lmcache 控制器,在 9001 端口启动监控器:

lmcache_controller --host localhost --port 9000 --monitor-port 9001

然后我们可以向 vllm 发送请求,以查看它是否正常工作:

curl -X POST http://localhost:8000/v1/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "meta-llama/Llama-3.1-8B-Instruct",
    "prompt": "Explain the significance of KV cache in language models.",
    "max_tokens": 10
  }'

现在我们发送请求以对提示进行标记:

curl -X POST http://localhost:8000/tokenize \
  -H "Content-Type: application/json" \
  -d '{
    "model": "meta-llama/Llama-3.1-8B-Instruct",
    "prompt": "Explain the significance of KV cache in language models."
  }'

我们应该能够在响应中看到令牌 ID:

{"count":12,"max_model_len":4096,"tokens":[128000,849,21435,279,26431,315,85748,6636,304,4221,4211,13],"token_strs":null}

毕竟,我们发出了一个 compress 请求:

curl -X POST http://localhost:9000/compress \
  -H "Content-Type: application/json" \
  -d '{
      "instance_id": "lmcache_default_instance",
      "method": "cachegen",
      "location": "LocalCPUBackend",
      "tokens": [128000, 849, 21435, 279, 26431, 315, 85748, 6636, 304, 4221, 4211, 13]
  }'

控制器的响应消息类似于:

{"event_id": "xxx", "num_tokens": 12}

这表明正在压缩 12 个 token。event_id 可用于查询操作的状态。

一旦 KV Cache 被压缩,我们可以使用 cachegen 进行解压。

curl -X POST http://localhost:9000/decompress \
  -H "Content-Type: application/json" \
  -d '{
      "instance_id": "lmcache_default_instance",
      "method": "cachegen",
      "location": "LocalCPUBackend",
      "tokens": [128000, 849, 21435, 279, 26431, 315, 85748, 6636, 304, 4221, 4211, 13]
  }'

控制器的响应消息类似于:

{"event_id": "xxx", "num_tokens": 12}

这表示正在解压缩 12 个令牌。event_id 可用于查询操作的状态。