"lib/vscode:/vscode.git/clone" did not exist on "c7f6f6d98038ebf496a9e1d45c24ed269491d756"
worker.py 12.4 KB
Newer Older
1
2
3
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

4
import asyncio
5
import logging
6
import random
7
import signal
8
import socket
9
10
import sys
from typing import Any, Dict, Optional, Union
11
12

import sglang as sgl
13
14
import uvloop
from sglang.srt.server_args import ServerArgs
15
from sglang.srt.utils import get_ip
16
17
from utils.protocol import DisaggPreprocessedRequest
from utils.sgl_utils import parse_sglang_args_inc
18

19
from dynamo.llm import (
20
21
    ForwardPassMetrics,
    KvStats,
22
23
    ModelType,
    WorkerMetricsPublisher,
24
    WorkerStats,
25
26
27
28
    ZmqKvEventPublisher,
    ZmqKvEventPublisherConfig,
    register_llm,
)
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from dynamo.runtime import DistributedRuntime, dynamo_worker
from dynamo.runtime.logging import configure_dynamo_logging

configure_dynamo_logging()


class RequestHandler:
    def __init__(
        self,
        engine: sgl.Engine,
        server_args: ServerArgs,
        component,
        decode_client: Optional[Any] = None,
    ):
        self.engine = engine
        self.server_args = server_args
        self.component = component
        self.metrics_publisher = WorkerMetricsPublisher()
47

48
49
50
51
52
53
54
55
56
57
        if server_args.disaggregation_mode != "null":
            self.bootstrap_host, self.bootstrap_port = self._get_bootstrap_info()
            if decode_client is None:
                raise ValueError(
                    "decode_client must be provided when disaggregation_mode is not 'null'"
                )
            self.decode_client = decode_client
            logging.info(
                f"Disaggregation enabled - bootstrap host: {self.bootstrap_host}, bootstrap port: {self.bootstrap_port}"
            )
58

59
        logging.info("Request handler initialized")
60

61
62
    def setup_metrics(self):
        """Set up metrics publisher - call this after handler creation"""
63
        worker_stats = WorkerStats(
64
65
            request_active_slots=0,
            request_total_slots=1024,
66
67
68
69
70
            num_requests_waiting=0,
            data_parallel_rank=None,
        )

        kv_stats = KvStats(
71
72
73
74
75
            kv_active_blocks=0,
            kv_total_blocks=1024,
            gpu_cache_usage_perc=0.0,
            gpu_prefix_cache_hit_rate=0.0,
        )
76
77
78
79
80
81
82

        metrics = ForwardPassMetrics(
            worker_stats=worker_stats,
            kv_stats=kv_stats,
            spec_decode_stats=None,
        )
        self.metrics_publisher.publish(metrics)
83
84
85
86
        task = asyncio.create_task(self.create_metrics_publisher_endpoint())
        task.add_done_callback(
            lambda _: logging.debug("metrics publisher endpoint created")
        )
87

88
89
90
    async def create_metrics_publisher_endpoint(self):
        logging.debug("Creating metrics publisher endpoint")
        await self.metrics_publisher.create_endpoint(self.component)
91
92
93
94
95

    def _update_metrics(self):
        """Update metrics with current engine state"""
        # TODO: remove this once the following upstream changes are merged:
        #   • sgl-project/sglang#6721 – "Expose runtime KV-cache & request metrics"
96
        logging.warning(
97
98
            "Publishing placeholder metrics in SGLangWorker; these are NOT real engine metrics yet and will be replaced once upstream support lands."
        )
99
100
101
102
103
104
105
106
107

        worker_stats = WorkerStats(
            request_active_slots=0,
            request_total_slots=1024,
            num_requests_waiting=0,
            data_parallel_rank=None,
        )

        kv_stats = KvStats(
108
109
110
111
112
113
            kv_active_blocks=random.randint(0, 500),
            kv_total_blocks=1000,
            gpu_cache_usage_perc=random.uniform(0.1, 0.8),
            gpu_prefix_cache_hit_rate=random.uniform(0.0, 0.5),
        )

114
115
116
117
118
119
120
121
122
123
        # TODO: get spec_dec_stats from sglang once real engine metrics are available
        spec_dec_stats = None

        metrics = ForwardPassMetrics(
            worker_stats=worker_stats,
            kv_stats=kv_stats,
            spec_decode_stats=spec_dec_stats,
        )
        self.metrics_publisher.publish(metrics)

124
    def _get_bootstrap_info(self):
125
        """Bootstrap info from tokenizer manager"""
126
127
128
129
130
131
132
133
134
135
136
        inner_tm = self.engine.tokenizer_manager
        bootstrap_port = inner_tm.server_args.disaggregation_bootstrap_port

        if inner_tm.server_args.dist_init_addr:
            bootstrap_host = socket.gethostbyname(
                inner_tm.server_args.dist_init_addr.split(":")[0]
            )
        else:
            bootstrap_host = get_ip()

        return bootstrap_host, bootstrap_port
137

138
    def _build_sampling_params(self, request: dict) -> dict:
139
        sampling_params = {}
140
141
142
143
144
145
146
147
148
        if request["sampling_options"]["temperature"]:
            sampling_params["temperature"] = request["sampling_options"]["temperature"]
        if request["sampling_options"]["top_p"]:
            sampling_params["top_p"] = request["sampling_options"]["top_p"]
        if request["sampling_options"]["top_k"]:
            sampling_params["top_k"] = request["sampling_options"]["top_k"]
        sampling_params["max_new_tokens"] = request["stop_conditions"]["max_tokens"]
        if request["stop_conditions"]["ignore_eos"]:
            sampling_params["ignore_eos"] = request["stop_conditions"]["ignore_eos"]
149
150
        return sampling_params

151
    def _get_request_batch_size(self, request: dict):
152
        """Get batch size from request, returns None for single requests"""
153
154
        if request["batch_token_ids"] is not None:
            return len(request["batch_token_ids"])
155
156
        return None

157
    def _is_batch_request(self, request: dict):
158
        """Check if request is in batch mode"""
159
160
161
162
        return request["batch_token_ids"] is not None

    def _generate_bootstrap_room(self):
        return random.randint(0, 2**63 - 1)
163

164
    async def generate(self, request: dict):
165
166
167
        is_batch = self._is_batch_request(request)
        batch_size = self._get_request_batch_size(request)

168
169
        # TODO: maintain a mapping from SGLang's Ouput struct to LLMEngineOuput
        sampling_params = self._build_sampling_params(request)
170

171
        if self.server_args.disaggregation_mode != "null":
172
173
174
175
176
177
178
179
180
181
            if is_batch:
                bootstrap_room = [
                    self._generate_bootstrap_room() for _ in range(batch_size)
                ]
                bootstrap_host = [self.bootstrap_host] * batch_size
                bootstrap_port = [self.bootstrap_port] * batch_size
            else:
                bootstrap_host = self.bootstrap_host
                bootstrap_port = self.bootstrap_port
                bootstrap_room = self._generate_bootstrap_room()
182
183
184
185
186

            # decode worker request
            disagg_request = DisaggPreprocessedRequest(
                request=request,
                sampling_params=sampling_params,
187
188
                bootstrap_host=bootstrap_host,
                bootstrap_port=bootstrap_port,
189
190
191
192
193
                bootstrap_room=bootstrap_room,
            )

            # prefill response is not used
            prefill = await self.engine.async_generate(
194
                input_ids=request["token_ids"]
195
                if not is_batch
196
                else request["batch_token_ids"],
197
198
                sampling_params=sampling_params,
                stream=True,
199
200
                bootstrap_host=bootstrap_host,
                bootstrap_port=bootstrap_port,
201
202
203
204
205
206
                bootstrap_room=bootstrap_room,
            )
            prefill_task = asyncio.create_task(self._prefill_generator(prefill))

            decode = await self.decode_client.generate(disagg_request.model_dump_json())

207
208
209
            async for out in self._process_stream(
                decode, unpack=True, is_batch=is_batch
            ):
210
211
212
213
214
                yield out

            await prefill_task
        else:
            g = await self.engine.async_generate(
215
                input_ids=request["token_ids"]
216
                if not is_batch
217
                else request["batch_token_ids"],
218
219
220
221
                sampling_params=sampling_params,
                stream=True,
            )

222
            async for out in self._process_stream(g, unpack=False, is_batch=is_batch):
223
224
                yield out

225
226
227
228
229
230
231
232
    async def _process_stream(self, stream_source, unpack: bool, is_batch: bool):
        # Initialize based on batch mode
        num_output_tokens_so_far: Union[Dict[int, int], int]
        if is_batch:
            num_output_tokens_so_far = {}
        else:
            num_output_tokens_so_far = 0

233
234
235
        async for res in stream_source:
            data = res.data() if unpack else res
            finish_reason = data["meta_info"]["finish_reason"]
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

            if is_batch:
                # Handle batch response
                assert isinstance(num_output_tokens_so_far, dict)
                index = data.get("index", 0)
                if index not in num_output_tokens_so_far:
                    num_output_tokens_so_far[index] = 0

                if finish_reason:
                    out = {
                        "token_ids": [],
                        "finish_reason": finish_reason["type"],
                        "index": index,
                    }
                else:
                    next_total_toks = len(data["output_ids"])
                    new_tokens = data["output_ids"][num_output_tokens_so_far[index] :]
                    out = {
                        "token_ids": new_tokens,
                        "index": index,
                    }
                    num_output_tokens_so_far[index] = next_total_toks
258
            else:
259
260
261
262
263
264
265
266
267
                # Handle single response
                assert isinstance(num_output_tokens_so_far, int)
                if finish_reason:
                    out = {"token_ids": [], "finish_reason": finish_reason["type"]}
                else:
                    next_total_toks = len(data["output_ids"])
                    out = {"token_ids": data["output_ids"][num_output_tokens_so_far:]}
                    num_output_tokens_so_far = next_total_toks

268
            yield out
269
270
271
272

    async def _prefill_generator(self, prefill):
        async for _ in prefill:
            pass
273

274
275
276
277
278
279
280
281
    async def flush_cache(self, request: dict):
        _ = request
        asyncio.create_task(self.engine.tokenizer_manager.flush_cache())
        yield {
            "status": "success",
            "message": "Cache flush initiated. Check backend logs for status",
        }

282

283
284
285
286
287
288
async def graceful_shutdown(runtime):
    logging.info("Received shutdown signal, shutting down DistributedRuntime")
    runtime.shutdown()
    logging.info("DistributedRuntime shutdown complete")


289
290
@dynamo_worker(static=False)
async def worker(runtime: DistributedRuntime):
291
292
293
294
295
296
297
298
299
300
301
302
    # Set up signal handler for graceful shutdown
    loop = asyncio.get_running_loop()

    def signal_handler():
        # Schedule the shutdown coroutine instead of calling it directly
        asyncio.create_task(graceful_shutdown(runtime))

    for sig in (signal.SIGTERM, signal.SIGINT):
        loop.add_signal_handler(sig, signal_handler)

    logging.info("Signal handlers set up for graceful shutdown")

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
    server_args = parse_sglang_args_inc(sys.argv[1:])
    await init(runtime, server_args)


async def init(runtime: DistributedRuntime, server_args: ServerArgs):
    """Initialize worker (either prefill or aggregated)"""

    engine = sgl.Engine(server_args=server_args)

    component = runtime.namespace("dynamo").component("worker")
    await component.create_service()

    endpoint = component.endpoint("generate")
    await register_llm(
        ModelType.Backend,
        endpoint,
        server_args.model_path,
        server_args.served_model_name,
        kv_cache_block_size=server_args.page_size,
    )

    if server_args.disaggregation_mode != "null":
        decode_client = (
            await runtime.namespace("dynamo")
            .component("decode")
            .endpoint("generate")
            .client()
        )
        handler = RequestHandler(engine, server_args, component, decode_client)
    else:
        handler = RequestHandler(engine, server_args, component)

    # Set up metrics in background
    handler.setup_metrics()

    # Set up ZMQ kv event publisher
    zmq_config = ZmqKvEventPublisherConfig(
        worker_id=endpoint.lease_id(),
        kv_block_size=server_args.page_size,
    )
    _ = ZmqKvEventPublisher(component=component, config=zmq_config)

345
346
347
348
349
350
    tasks = [endpoint.serve_endpoint(handler.generate)]

    flush_endpoint = component.endpoint("flush_cache")
    tasks.append(flush_endpoint.serve_endpoint(handler.flush_cache))

    await asyncio.gather(*tasks)
351
352
353
354
355


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