Skip to content

Commit cd222a8

Browse files
authored
fix: restore native LMCache integration (#1804)
Signed-off-by: AlpinDale <alpindale@gmail.com>
1 parent 3a05f89 commit cd222a8

16 files changed

Lines changed: 362 additions & 3488 deletions

File tree

‎docs/src/content/docs/deployment/production.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,46 @@ and the
217217
Sonar's local code and examples define the supported configuration for your
218218
installed Sonar commit.
219219

220+
## Reuse an external KV cache
221+
222+
Install the optional dependencies with `tools/install_kv_connectors.sh` from
223+
the source checkout.
224+
225+
### LMCache
226+
227+
For CPU offloading within each engine:
228+
229+
```bash
230+
PYTHONHASHSEED=0 \
231+
LMCACHE_CHUNK_SIZE=256 \
232+
LMCACHE_LOCAL_CPU=True \
233+
LMCACHE_MAX_LOCAL_CPU_SIZE=5 \
234+
sonar serve Qwen/Qwen3-0.6B \
235+
--kv-transfer-config '{"kv_connector":"LMCacheConnectorV1","kv_role":"kv_both"}'
236+
```
237+
238+
For a separate cache process, start the server and select `LMCacheMPConnector`:
239+
240+
```bash
241+
lmcache server --l1-size-gb 5 --l1-init-size-gb 5 --eviction-policy LRU
242+
```
243+
244+
Set `lmcache.mp.host` and `lmcache.mp.port` in `kv_connector_extra_config`
245+
when the server is not at `tcp://localhost:5555`.
246+
247+
Use the same LMCache version for the engine and cache server.
248+
249+
### Mooncake
250+
251+
Select `MooncakeConnector` for prefill/decode transfers or
252+
`MooncakeStoreConnector` for a shared Mooncake Store. The Store connector reads
253+
its configuration from `MOONCAKE_CONFIG_PATH`. Start a Mooncake master before
254+
the engine.
255+
256+
For TCP-only transfers, set `MC_FORCE_TCP=1` in addition to
257+
`"mooncake_protocol": "tcp"` in the transfer connector's extra configuration,
258+
or `"protocol": "tcp"` in the Store configuration.
259+
220260
## Configure the proxy
221261

222262
Permit streaming responses and disable response buffering. Set the upstream

‎examples/disaggregated_prefill/lmcache/cpu_offload_lmcache.py‎

Lines changed: 24 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -1,152 +1,62 @@
11
# SPDX-License-Identifier: Apache-2.0
22
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3-
"""
4-
This file demonstrates the example usage of cpu offloading
5-
with LMCache in Sonar v1 or v0.
6-
7-
Usage:
8-
9-
Specify Sonar version
10-
11-
-v v0 : Use LMCacheConnector
12-
model = mistralai/Mistral-7B-Instruct-v0.2
13-
(Includes enable_chunked_prefill = True)
14-
15-
-v v1 : Use LMCacheConnectorV1 (default)
16-
model = meta-llama/Meta-Llama-3.1-8B-Instruct
17-
(Without enable_chunked_prefill)
3+
"""Offload KV cache to CPU with LMCache and reuse a shared prompt prefix.
184
19-
Note that `lmcache` is needed to run this example.
20-
Requirements:
21-
https://docs.lmcache.ai/getting_started/installation.html#prerequisites
22-
Learn more about LMCache environment setup, please refer to:
23-
https://docs.lmcache.ai/getting_started/installation.html
5+
Install dependencies with tools/install_kv_connectors.sh, then run with
6+
PYTHONHASHSEED=0.
247
"""
258

269
import argparse
2710
import contextlib
2811
import os
2912
import time
30-
from dataclasses import asdict
31-
32-
from lmcache.v1.cache_engine import LMCacheEngineBuilder
3313

3414
from sonar import LLM, SamplingParams
3515
from sonar.config import KVTransferConfig
36-
from sonar.distributed.kv_transfer.kv_connector.v1.lmcache_integration.sonar_v1_adapter import ENGINE_NAME
37-
from sonar.engine.arg_utils import EngineArgs
3816

3917

40-
def setup_environment_variables(sonar_version: str):
41-
# LMCache-related environment variables
42-
# Use experimental features in LMCache
43-
os.environ["LMCACHE_USE_EXPERIMENTAL"] = "True"
44-
# LMCache is set to use 256 tokens per chunk
18+
def setup_environment_variables():
4519
os.environ["LMCACHE_CHUNK_SIZE"] = "256"
46-
# Enable local CPU backend in LMCache
4720
os.environ["LMCACHE_LOCAL_CPU"] = "True"
48-
# Set local CPU memory limit to 5.0 GB
4921
os.environ["LMCACHE_MAX_LOCAL_CPU_SIZE"] = "5.0"
50-
if sonar_version == "v0":
51-
os.environ["SONAR_USE_V1"] = "0"
5222

5323

5424
@contextlib.contextmanager
55-
def build_llm_with_lmcache(lmcache_connector: str, model: str, sonar_version: str):
56-
ktc = KVTransferConfig(
57-
kv_connector=lmcache_connector,
58-
kv_role="kv_both",
25+
def build_llm_with_lmcache(model: str):
26+
llm = LLM(
27+
model=model,
28+
kv_transfer_config=KVTransferConfig(kv_connector="LMCacheConnectorV1", kv_role="kv_both"),
29+
max_model_len=8000,
30+
gpu_memory_utilization=0.8,
31+
# Attribute reuse to LMCache rather than Sonar's local prefix cache.
32+
enable_prefix_caching=False,
5933
)
60-
# Set GPU memory utilization to 0.8 for an A40 GPU with 40GB
61-
# memory. Reduce the value if your GPU has less memory.
62-
# Note: LMCache supports chunked prefill (see Sonar#14505, LMCache#392).
63-
if sonar_version == "v0":
64-
llm_args = EngineArgs(
65-
model=model,
66-
kv_transfer_config=ktc,
67-
max_model_len=8000,
68-
gpu_memory_utilization=0.8,
69-
enable_chunked_prefill=True, # Only in v0
70-
)
71-
else:
72-
llm_args = EngineArgs(
73-
model=model,
74-
kv_transfer_config=ktc,
75-
max_model_len=8000,
76-
gpu_memory_utilization=0.8,
77-
)
78-
79-
llm = LLM(**asdict(llm_args))
8034
try:
8135
yield llm
8236
finally:
83-
# Clean up lmcache backend
84-
LMCacheEngineBuilder.destroy(ENGINE_NAME)
37+
llm.llm_engine.engine_core.shutdown()
8538

8639

87-
def print_output(
88-
llm: LLM,
89-
prompt: list[str],
90-
sampling_params: SamplingParams,
91-
req_str: str,
92-
):
93-
# Should be able to see logs like the following:
94-
# `LMCache INFO: Storing KV cache for 6006 out of 6006 tokens for request 0`
95-
# This indicates that the KV cache has been stored in LMCache.
40+
def print_output(llm: LLM, prompt: list[str], sampling_params: SamplingParams, req_str: str):
9641
start = time.time()
9742
outputs = llm.generate(prompt, sampling_params)
98-
print("-" * 50)
9943
for output in outputs:
100-
generated_text = output.outputs[0].text
101-
print(f"Generated text: {generated_text!r}")
44+
print(f"Generated text: {output.outputs[0].text!r}")
45+
print(f"Cached prompt tokens: {output.num_cached_tokens}")
10246
print(f"Generation took {time.time() - start:.2f} seconds, {req_str} request done.")
103-
print("-" * 50)
104-
105-
106-
def parse_args():
107-
parser = argparse.ArgumentParser()
108-
parser.add_argument(
109-
"-v",
110-
"--version",
111-
choices=["v0", "v1"],
112-
default="v1",
113-
help="Specify Sonar version (default: v1)",
114-
)
115-
return parser.parse_args()
11647

11748

11849
def main():
119-
args = parse_args()
120-
121-
if args.version == "v0":
122-
lmcache_connector = "LMCacheConnector"
123-
model = "mistralai/Mistral-7B-Instruct-v0.2"
124-
else:
125-
lmcache_connector = "LMCacheConnectorV1"
126-
model = "meta-llama/Meta-Llama-3.1-8B-Instruct"
127-
128-
setup_environment_variables(args.version)
50+
parser = argparse.ArgumentParser()
51+
parser.add_argument("--model", default="Qwen/Qwen3-0.6B")
52+
args = parser.parse_args()
53+
setup_environment_variables()
12954

130-
with build_llm_with_lmcache(lmcache_connector, model, args.version) as llm:
131-
# This example script runs two requests with a shared prefix.
132-
# Define the shared prompt and specific prompts
55+
with build_llm_with_lmcache(args.model) as llm:
13356
shared_prompt = "Hello, how are you?" * 1000
134-
first_prompt = [
135-
shared_prompt + "Hello, my name is",
136-
]
137-
second_prompt = [
138-
shared_prompt + "Tell me a very long story",
139-
]
140-
141-
sampling_params = SamplingParams(temperature=0, top_p=0.95, max_tokens=10)
142-
143-
# Print the first output
144-
print_output(llm, first_prompt, sampling_params, "first")
145-
146-
time.sleep(1)
147-
148-
# print the second output
149-
print_output(llm, second_prompt, sampling_params, "second")
57+
sampling_params = SamplingParams(temperature=0, max_tokens=10)
58+
print_output(llm, [shared_prompt + "Hello, my name is"], sampling_params, "first")
59+
print_output(llm, [shared_prompt + "Tell me a very long story"], sampling_params, "second")
15060

15161

15262
if __name__ == "__main__":

examples/disaggregated_prefill/lmcache/disagg_prefill_lmcache_v0.py renamed to examples/disaggregated_prefill/lmcache/disagg_prefill_lmcache.py

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -14,31 +14,16 @@
1414

1515
import os
1616
import subprocess
17+
import sys
1718
import time
1819
from multiprocessing import Event, Process
1920

20-
from lmcache.experimental.cache_engine import LMCacheEngineBuilder
21-
2221
from sonar import LLM, SamplingParams
2322
from sonar.config import KVTransferConfig
24-
from sonar.distributed.kv_transfer.kv_connector.v1.lmcache_integration.sonar_v1_adapter import ENGINE_NAME
2523

2624
# LMCache-related environment variables
2725
# The port to start LMCache server
2826
port = 8100
29-
# Use experimental features in LMCache
30-
os.environ["LMCACHE_USE_EXPERIMENTAL"] = "True"
31-
# LMCache is set to use 256 tokens per chunk
32-
os.environ["LMCACHE_CHUNK_SIZE"] = "256"
33-
# Disable local CPU backend in LMCache
34-
os.environ["LMCACHE_LOCAL_CPU"] = "False"
35-
# Set local CPU memory buffer limit to 5.0 GB
36-
os.environ["LMCACHE_MAX_LOCAL_CPU_SIZE"] = "5.0"
37-
# Set the remote URL for LMCache server
38-
os.environ["LMCACHE_REMOTE_URL"] = f"lm://localhost:{port}"
39-
# Set the serializer/deserializer between sonar and LMCache server
40-
# `naive` indicates using raw bytes of the tensor without any compression
41-
os.environ["LMCACHE_REMOTE_SERDE"] = "naive"
4227

4328
prompts = [
4429
"Hello, how are you?" * 1000,
@@ -52,10 +37,9 @@ def run_prefill(prefill_done, prompts):
5237
sampling_params = SamplingParams(temperature=0, top_p=0.95, max_tokens=1)
5338

5439
ktc = KVTransferConfig(
55-
kv_connector="LMCacheConnector",
40+
kv_connector="LMCacheMPConnector",
5641
kv_role="kv_producer",
57-
kv_rank=0,
58-
kv_parallel_size=2,
42+
kv_connector_extra_config={"lmcache.mp.port": port},
5943
)
6044
# Set GPU memory utilization to 0.8 for an A40 GPU with 40GB
6145
# memory. Reduce the value if your GPU has less memory.
@@ -75,8 +59,7 @@ def run_prefill(prefill_done, prompts):
7559
print("Prefill node is finished.")
7660
prefill_done.set()
7761

78-
# Clean up lmcache backend
79-
LMCacheEngineBuilder.destroy(ENGINE_NAME)
62+
llm.llm_engine.engine_core.shutdown()
8063

8164

8265
def run_decode(prefill_done, prompts, timeout=1):
@@ -86,10 +69,9 @@ def run_decode(prefill_done, prompts, timeout=1):
8669
sampling_params = SamplingParams(temperature=0, top_p=0.95, max_tokens=10)
8770

8871
ktc = KVTransferConfig(
89-
kv_connector="LMCacheConnector",
72+
kv_connector="LMCacheMPConnector",
9073
kv_role="kv_consumer",
91-
kv_rank=1,
92-
kv_parallel_size=2,
74+
kv_connector_extra_config={"lmcache.mp.port": port},
9375
)
9476
# Set GPU memory utilization to 0.8 for an A40 GPU with 40GB
9577
# of memory. Reduce the value if your GPU has less memory.
@@ -110,13 +92,28 @@ def run_decode(prefill_done, prompts, timeout=1):
11092
generated_text = output.outputs[0].text
11193
print(f"Generated text: {generated_text!r}")
11294

113-
# Clean up lmcache backend
114-
LMCacheEngineBuilder.destroy(ENGINE_NAME)
95+
llm.llm_engine.engine_core.shutdown()
11596

11697

11798
def run_lmcache_server(port):
118-
server_proc = subprocess.Popen(["python", "-m", "lmcache.experimental.server", "localhost", str(port)])
119-
return server_proc
99+
return subprocess.Popen(
100+
[
101+
sys.executable,
102+
"-m",
103+
"lmcache.cli.main",
104+
"server",
105+
"--host",
106+
"localhost",
107+
"--port",
108+
str(port),
109+
"--l1-size-gb",
110+
"5",
111+
"--l1-init-size-gb",
112+
"5",
113+
"--eviction-policy",
114+
"LRU",
115+
]
116+
)
120117

121118

122119
def main():

0 commit comments

Comments
 (0)