"docs/pages/components/vscode:/vscode.git/clone" did not exist on "78436fbf7992171f8c3cbb1f3601076e032eb2f2"
vllm_inc.py 11.1 KB
Newer Older
1
2
3
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

4
5
6
7
8
9
10
# `dynamo-run out=vllm` runs this script
# Can also be used standalone: `python3 vllm_inc.py` - lots of optional cmd line params

# Setup checklist:
# - We are in a virtualenv with vllm installed - and patched if using kv routing.
# - `libdynamo_llm_capi.so` is in system lib path or it's containing folder is in LD_LIBRARY_PATH
#   It builds in target/debug/ by default.
11
12
13

import argparse
import asyncio
14
import json
15
import logging
16
import os
17
import sys
18
19
import uuid
from typing import Optional
20
21
22
23
24
25
26
27
28

import uvloop
from vllm import SamplingParams
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.entrypoints.openai.api_server import (
    build_async_engine_client_from_engine_args,
)
from vllm.inputs import TokensPrompt

29
30
31
32
33
34
35
36
from dynamo.llm import (
    ForwardPassMetrics,
    KvStats,
    ModelType,
    WorkerMetricsPublisher,
    WorkerStats,
    register_llm,
)
37
from dynamo.runtime import DistributedRuntime, dynamo_worker
38
from dynamo.runtime.logging import configure_dynamo_logging
39
from dynamo.sdk.lib.utils import get_capi_library_path
40

41
# Only used if you run it manually from the command line
42
DEFAULT_ENDPOINT = "dyn://dynamo.backend.generate"
43
DEFAULT_MODEL = "Qwen/Qwen3-0.6B"
44

45
configure_dynamo_logging()
46
47
48
49
50
51
52
53


class Config:
    """Command line parameters or defaults"""

    namespace: str
    component: str
    endpoint: str
54
55
    model_path: str
    model_name: Optional[str]
56
    tensor_parallel_size: int
57
    kv_block_size: int
58
    context_length: int
59
    migration_limit: int
60
61
62
63
64
65
66
67
    extra_engine_args: str


class RequestHandler:
    """
    Request handler for the generate endpoint
    """

68
69
    def __init__(self, component, engine, default_sampling_params):
        self.component = component
70
        self.engine_client = engine
71
        self.default_sampling_params = default_sampling_params
72
        self.metrics_publisher = WorkerMetricsPublisher()
73
74
75
76
77
78
79
80
81

    def setup_kv_metrics(self):
        if not hasattr(self.engine_client, "set_metrics_publisher"):
            logging.debug("VLLM version does not support KV metrics")
            return

        self.engine_client.set_metrics_publisher(self.metrics_publisher)
        # Initially send dummy metrics to kick start,
        # vLLM will not update stat until forward pass is triggered
82
83
84
85
86
87
88
89
90
91
92
93
94
95

        # Create the structured metrics objects
        worker_stats = WorkerStats(
            request_active_slots=0,
            request_total_slots=1024,
            num_requests_waiting=0,
            data_parallel_rank=None,
        )

        kv_stats = KvStats(
            kv_active_blocks=0,
            kv_total_blocks=1024,
            gpu_cache_usage_perc=0.0,
            gpu_prefix_cache_hit_rate=0.0,
96
        )
97
98
99
100
101
102
103
104

        metrics = ForwardPassMetrics(
            worker_stats=worker_stats, kv_stats=kv_stats, spec_decode_stats=None
        )

        # Publish the metrics as a single object
        self.metrics_publisher.publish(metrics)

105
106
107
108
109
110
111
112
        task = asyncio.create_task(self.create_metrics_publisher_endpoint())
        task.add_done_callback(
            lambda _: logging.debug("metrics publisher endpoint created")
        )

    async def create_metrics_publisher_endpoint(self):
        logging.debug("Creating metrics publisher endpoint")
        await self.metrics_publisher.create_endpoint(self.component)
113
114

    async def generate(self, request):
115
116
        # logging.debug(f"Received request: {request}")
        request_id = str(uuid.uuid4().hex)
117
118

        prompt = TokensPrompt(prompt_token_ids=request["token_ids"])
119
120

        sampling_params = SamplingParams(**self.default_sampling_params)
121
122
123
124
125
126
127
128
129
        for key, value in request["sampling_options"].items():
            if not value:
                continue
            if hasattr(sampling_params, key):
                setattr(sampling_params, key, value)

        max_tokens = request["stop_conditions"]["max_tokens"]
        if max_tokens:
            sampling_params.max_tokens = max_tokens
130

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
        num_output_tokens_so_far = 0
        gen = self.engine_client.generate(prompt, sampling_params, request_id)
        async for res in gen:
            # res is vllm's RequestOutput

            # This is the expected way for a request to end.
            # The new token ID will be eos, don't forward it.
            if res.finished:
                yield {"finish_reason": "stop", "token_ids": []}
                break

            if not res.outputs:
                yield {"finish_reason": "error", "token_ids": []}
                break

            output = res.outputs[0]
            next_total_toks = len(output.token_ids)
            out = {"token_ids": output.token_ids[num_output_tokens_so_far:]}
            if output.finish_reason:
                out["finish_reason"] = output.finish_reason
            if output.stop_reason:
                out["stop_reason"] = output.stop_reason
            yield out
            num_output_tokens_so_far = next_total_toks


@dynamo_worker(static=False)
async def worker(runtime: DistributedRuntime):
    await init(runtime, cmd_line_args())


162
163
164
165
166
167
168
169
def _check_and_set_env_value(key, expected, allow_override=False):
    if not allow_override and key in os.environ and os.environ[key] != expected:
        raise ValueError(
            f"{key} is set and doesn't equal expected {expected}. Please unset variable before launch."
        )
    os.environ.setdefault(key, expected)


170
171
172
173
174
175
async def init(runtime: DistributedRuntime, config: Config):
    """
    Instantiate and serve
    """

    arg_map = {
176
        "model": config.model_path,
177
178
179
        "task": "generate",
        "tensor_parallel_size": config.tensor_parallel_size,
        "skip_tokenizer_init": True,
180
        "disable_log_requests": True,
181
        "enable_prefix_caching": True,
182
183
        # KV routing relies on logging KV metrics
        "disable_log_stats": False,
184
    }
185
186
    assert config.kv_block_size > 0, "Must use non-negative integer for KV Block Size"
    arg_map["block_size"] = config.kv_block_size
187

188
189
190
191
    if config.context_length:
        # Usually we want it to default to the max (from tokenizer_config.json)
        arg_map["max_model_len"] = config.context_length

192
193
194
195
196
197
198
199
200
201
202
203
204
    if config.extra_engine_args != "":
        json_map = {}
        # extra_engine_args is a filename
        try:
            with open(config.extra_engine_args) as f:
                json_map = json.load(f)
        except FileNotFoundError:
            logging.error(f"File {config.extra_engine_args} not found.")
        except json.JSONDecodeError as e:
            logging.error(f"Invalid JSON in {config.extra_engine_args}: {e}")
        logging.debug(f"Adding extra engine arguments: {json_map}")
        arg_map = {**arg_map, **json_map}  # json_map gets precedence

205
    # Patch won't start KVCacheEventManager unless these four are set
206
207
208
209
210
211
212

    component = runtime.namespace(config.namespace).component(config.component)
    await component.create_service()
    endpoint = component.endpoint(config.endpoint)

    _check_and_set_env_value("VLLM_WORKER_ID", str(endpoint.lease_id()))
    _check_and_set_env_value(
213
        "VLLM_KV_CAPI_PATH", get_capi_library_path(), allow_override=True
214
215
216
217
218
219
    )
    _check_and_set_env_value("VLLM_KV_NAMESPACE", config.namespace)
    _check_and_set_env_value("VLLM_KV_COMPONENT", config.component)
    _check_and_set_env_value(
        "VLLM_NO_USAGE_STATS", "1", allow_override=True
    )  # Avoid internal HTTP requests
220
    engine_args = AsyncEngineArgs(**arg_map)
221
222
223
    model_config = engine_args.create_model_config()
    # Load default sampling params from `generation_config.json`
    default_sampling_params = model_config.get_diff_sampling_param()
224
225
226
227

    engine_context = build_async_engine_client_from_engine_args(engine_args)
    engine_client = await engine_context.__aenter__()

228
    await register_llm(
229
230
231
232
233
234
235
236
        ModelType.Backend,
        endpoint,
        config.model_path,
        config.model_name,
        context_length=arg_map.get(
            "max_model_len", None
        ),  # if None, takes length from tokenizer
        kv_cache_block_size=arg_map["block_size"],
237
        migration_limit=config.migration_limit,
238
    )
239
240
241
    handler = RequestHandler(component, engine_client, default_sampling_params)
    handler.setup_kv_metrics()

242
243
    # the server will gracefully shutdown (i.e., keep opened TCP streams finishes)
    # after the lease is revoked
244
    await endpoint.serve_endpoint(handler.generate)
245
246
247
248
249
250
251
252
253
254
255
256
257


def cmd_line_args():
    parser = argparse.ArgumentParser(
        description="vLLM server integrated with Dynamo LLM."
    )
    parser.add_argument(
        "--endpoint",
        type=str,
        default=DEFAULT_ENDPOINT,
        help=f"Dynamo endpoint string in 'dyn://namespace.component.endpoint' format. Default: {DEFAULT_ENDPOINT}",
    )
    parser.add_argument(
258
        "--model-path",
259
260
261
262
        type=str,
        default=DEFAULT_MODEL,
        help=f"Path to disk model or HuggingFace model identifier to load. Default: {DEFAULT_MODEL}",
    )
263
264
265
266
267
268
    parser.add_argument(
        "--model-name",
        type=str,
        default="",
        help="Name to serve the model under. Defaults to deriving it from model path.",
    )
269
270
271
    parser.add_argument(
        "--tensor-parallel-size", type=int, default=1, help="Number of GPUs to use."
    )
272
273
274
    parser.add_argument(
        "--kv-block-size", type=int, default=16, help="Size of a KV cache block."
    )
275
276
277
278
279
280
    parser.add_argument(
        "--context-length",
        type=int,
        default=None,
        help="Max model context length. Defaults to models max, usually model_max_length from tokenizer_config.json. Reducing this reduces VRAM requirements.",
    )
281
282
283
284
285
286
    parser.add_argument(
        "--migration-limit",
        type=int,
        default=0,
        help="Maximum number of times a request may be migrated to a different engine worker. The number may be overridden by the engine.",
    )
287
288
289
290
291
292
293
294
295
    parser.add_argument(
        "--extra-engine-args",
        type=str,
        default="",
        help="Path to a JSON file containing additional keyword arguments to pass to the vLLM AsyncLLMEngine.",
    )
    args = parser.parse_args()

    config = Config()
296
297
298
299
300
301
    config.model_path = args.model_path
    if args.model_name:
        config.model_name = args.model_name
    else:
        # This becomes an `Option` on the Rust side
        config.model_name = None
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

    endpoint_str = args.endpoint.replace("dyn://", "", 1)
    endpoint_parts = endpoint_str.split(".")
    if len(endpoint_parts) != 3:
        logging.error(
            f"Invalid endpoint format: '{args.endpoint}'. Expected 'dyn://namespace.component.endpoint' or 'namespace.component.endpoint'."
        )
        sys.exit(1)

    parsed_namespace, parsed_component_name, parsed_endpoint_name = endpoint_parts

    config.namespace = parsed_namespace
    config.component = parsed_component_name
    config.endpoint = parsed_endpoint_name
    config.tensor_parallel_size = args.tensor_parallel_size
317
    config.kv_block_size = args.kv_block_size
318
    config.context_length = args.context_length
319
    config.migration_limit = args.migration_limit
320
321
322
323
324
325
326
327
    config.extra_engine_args = args.extra_engine_args

    return config


if __name__ == "__main__":
    uvloop.install()
    asyncio.run(worker())