LLM推理服务中,(Time-To-First-Token) 一直是个核心指标。用户发起请求到看见第一个token输出,这段时间越短体验越好,但实际部署中往往存在各种问题。
LMCache针对TTFT提出了一套KV缓存持久化与复用的方案。项目开源,目前已经和vLLM深度集成。
原理
大模型推理有个特点:每次处理输入文本都要重新计算KV缓存。KV缓存可以理解为模型"阅读"文本时产生的中间状态,类似于做的笔记。
问题在于传统方案不复用这些"笔记"。同样的文本再来一遍,整个KV缓存从头算。
LMCache的做法是把KV缓存存下来——不光存GPU显存里,还能存到CPU内存、磁盘上。下次遇到相同文本(注意不只是前缀匹配,是任意位置的文本复用),直接取缓存,省掉重复计算。
实测效果:搭配vLLM,在多轮对话、RAG这类场景下,响应速度能快3到10倍。
伪代码大概是这样:
# Old way: Slow as molasses
def get_answer(prompt):
memory = build_memory_from_zero(prompt) # GPU cries
return model.answer(memory)
# With LMCache: Zippy and clever
import lmcache
def get_answer(prompt):
if lmcache.knows_this(prompt): # Seen it before?
memory = lmcache.grab_memory(prompt) # Snag it fast
else:
memory = build_memory_from_zero(prompt)
lmcache.save_memory(prompt, memory) # Keep it for later
return model.answer(memory)

几个特性
缓存读取速度比原生方案快7倍左右,吞吐量也有提升。文本不管在prompt的什么位置,只要重复出现就能命中缓存。
存储层面支持多级——GPU显存、CPU内存、磁盘都行,甚至可以接NIXL这种分布式存储,GPU压力能减轻不少。
LMCache和vLLM v1集成得比较深,支持跨设备共享KV缓存、跨节点传递等特性。生产环境里可以配合llm-d、KServe这些工具用。
做聊天机器人或者RAG应用的话,这东西能在不升级硬件的情况下把延迟压下来一部分。
安装
LMCache目前主要支持Linux,Windows上得走WSL或者社区的适配方案。
基本要求:Python 3.9+,NVIDIA GPU(V100、H100这类),CUDA 12.8以上。装好之后离线也能跑。
pip直接装:
pip install lmcache
自带PyTorch依赖。遇到奇怪报错的话,建议换源码编译。
想尝鲜可以装TestPyPI上的预发布版:
pip install --index-url https://pypi.org/simple --extra-index-url https://test.pypi.org/simple lmcache==0.3.4.dev61
验证一下版本:
importlmcache
fromimportlib.metadataimportversion
print(version("lmcache")) # Should be 0.3.4.dev61 or newer
具体版本号去GitHub看最新的。
源码编译
喜欢折腾的可以clone下来自己编:
git clone https://github.com/LMCache/LMCache.git
cd LMCache
pip install -r requirements/build.txt
# Pick one:
# A: Choose your Torch
pip install torch==2.7.1 # Good for vLLM 0.10.0
# B: Get vLLM with Torch included
pip install vllm==0.10.0
pip install -e . --no-build-isolation
跑个验证:
python3 -c"import lmcache.c_ops"
不报错就行。
用uv的话会快一些:
git clone https://github.com/LMCache/LMCache.git
cd LMCache
uv venv --python3.12
source .venv/bin/activate
uv pip install -r requirements/build.txt
# Same Torch/vLLM choices
uv pip install -e . --no-build-isolation
Docker部署
如果嫌麻烦直接拉镜像:
# Stable
docker pull lmcache/vllm-openai
# Nightly
docker pull lmcache/vllm-openai:latest-nightly
AMD GPU(比如MI300X)需要从vLLM基础镜像开始,加上ROCm编译参数:
PYTORCH_ROCM_ARCH="gfx942" \
TORCH_DONT_CHECK_COMPILER_ABI=1 \
CXX=hipcc \
BUILD_WITH_HIP=1 \
python3 -m pip install --no-build-isolation -e .
小结
KV缓存复用这个思路已经是基本操作了,但LMCache把它做得比较完整:多级存储、任意位置匹配、和vLLM的原生集成,这些组合起来确实能解决实际问题。对于多轮对话、RAG这类prompt重复率高的场景,3-10倍的TTFT优化是实打实的。
LMCache目前主要绑定vLLM生态,Linux优先,AMD GPU支持还在完善中。但作为一个开源方案,值得关注。
项目地址:https://github.com/LMCache/LMCache
作者:Algo Insights