sglang_inc.py 10.7 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
# `dynamo-run out=sglang` runs this script
# Can also be used standalone: `python3 sglang_inc.py` - lots of optional cmd line params
6
7
8

import argparse
import asyncio
9
import json
10
import logging
11
import sys
12
from typing import Optional
13
14
15

import sglang
import uvloop
16
from sglang.srt.entrypoints.engine import EmbeddingReqInput
17
18
19
20
from sglang.srt.server_args import ServerArgs

from dynamo.llm import ModelType, register_llm
from dynamo.runtime import DistributedRuntime, dynamo_worker
21
from dynamo.runtime.logging import configure_dynamo_logging
22

23
# Only used if you run it manually from the command line
24
DEFAULT_ENDPOINT = "dyn://dynamo.backend.generate"
25
DEFAULT_MODEL = "Qwen/Qwen3-0.6B"
26

27
configure_dynamo_logging()
28

29
30
31
32
33
34
35

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

    namespace: str
    component: str
    endpoint: str
36
37
    model_path: str
    model_name: Optional[str]
38
39
    base_gpu_id: int
    tensor_parallel_size: int
40
    kv_block_size: int
41
    context_length: int
42
43
44
    nnodes: int
    node_rank: int
    dist_init_addr: str
45
    migration_limit: int
46
47
48
49
50
51
52
53
54
55
56
57
    extra_engine_args: str


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

    def __init__(self, engine):
        self.engine_client = engine

    async def generate(self, request):
58
        sampling_params = {}
59
60
61
62
63
64
        if request["sampling_options"]["temperature"] is not None:
            sampling_params["temperature"] = request["sampling_options"]["temperature"]
        sampling_params = {
            # sglang defaults this to 128
            "max_new_tokens": request["stop_conditions"]["max_tokens"],
        }
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

        # Check if this is a batch request
        is_batch = "batch_token_ids" in request and request["batch_token_ids"]

        if is_batch:
            # Track tokens separately for each batch item
            num_output_tokens_so_far = {}
            logging.debug("received batch token ids")
            gen = await self.engine_client.async_generate(
                input_ids=request["batch_token_ids"],
                sampling_params=sampling_params,
                stream=True,
            )
        else:
            num_output_tokens_so_far = 0
            logging.debug("received token ids")
            gen = await self.engine_client.async_generate(
                input_ids=request["token_ids"],
                sampling_params=sampling_params,
                stream=True,
            )

87
88
        async for res in gen:
            # res is a dict
89
            logging.debug(f"res: {res}")
90
            finish_reason = res["meta_info"]["finish_reason"]
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

            if is_batch:
                # Handle batch response - get index from SGLang response
                index = res.get("index", 0)
                if index not in num_output_tokens_so_far:
                    num_output_tokens_so_far[index] = 0

                if finish_reason:
                    logging.warning(f"finish_reason: {finish_reason}")
                    # Final response for this batch item
                    out = {
                        "token_ids": [],
                        "finish_reason": finish_reason["type"],
                        "index": index,
                    }
                else:
                    # Streaming response for this batch item
                    next_total_toks = len(res["output_ids"])
                    new_tokens = res["output_ids"][num_output_tokens_so_far[index] :]
                    out = {
                        "token_ids": new_tokens,
                        "index": index,
                    }
                    num_output_tokens_so_far[index] = next_total_toks
115
            else:
116
117
118
119
120
121
122
123
124
125
126
127
128
                if finish_reason:
                    out = {
                        "token_ids": [],
                        "finish_reason": finish_reason["type"],
                    }
                else:
                    next_total_toks = len(res["output_ids"])
                    new_tokens = res["output_ids"][num_output_tokens_so_far:]
                    out = {
                        "token_ids": new_tokens,
                    }
                    num_output_tokens_so_far = next_total_toks

129
130
            yield out

131
132
133
134
    async def encode(self, request):
        obj = EmbeddingReqInput(input_ids=request["token_ids"])
        generator = self.engine_client.tokenizer_manager.generate_request(obj, None)
        engine_results = await anext(generator)
135

136
137
        tokens = 0
        embeddings = []
138
139
140
        for result in engine_results:
            embeddings.append(result["embedding"])
            tokens += result["meta_info"]["prompt_tokens"]
141
142

        out = {
143
144
145
            "embeddings": embeddings,
            "prompt_tokens": tokens,
            "total_tokens": tokens,
146
147
148
149
150
        }

        yield out


151
152
153
154
155
156
157
158
159
160
161
@dynamo_worker(static=False)
async def worker(runtime: DistributedRuntime):
    await init(runtime, cmd_line_args())


async def init(runtime: DistributedRuntime, config: Config):
    """
    Instantiate and serve
    """

    arg_map = {
162
        "model_path": config.model_path,
163
164
165
166
        "skip_tokenizer_init": True,
        "tp_size": config.tensor_parallel_size,
        "base_gpu_id": config.base_gpu_id,
    }
167
168
169
170

    if config.kv_block_size:
        arg_map["page_size"] = config.kv_block_size

171
172
173
    if config.context_length:
        arg_map["context_length"] = config.context_length

174
175
176
177
178
179
180
    if config.dist_init_addr != "":
        arg_map["trust_remote_code"] = True
        arg_map["nnodes"] = config.nnodes
        arg_map["dist_init_addr"] = config.dist_init_addr
        # In practice this is always 0 because Dynamo only manages the leader
        arg_map["node_rank"] = config.node_rank

181
182
183
184
185
186
187
188
189
190
191
192
193
    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

194
195
    # TODO fetch default SamplingParams from generation_config.json

196
197
198
    engine_args = ServerArgs(**arg_map)
    engine_client = sglang.Engine(server_args=engine_args)

199
200
201
202
    component = runtime.namespace(config.namespace).component(config.component)
    await component.create_service()

    endpoint = component.endpoint(config.endpoint)
203
204
    model_type = (
        ModelType.Backend if not engine_args.is_embedding else ModelType.Embedding
205
    )
206
207
208
209
210
211
212
    await register_llm(
        model_type,
        endpoint,
        config.model_path,
        config.model_name,
        migration_limit=config.migration_limit,
    )
213

214
215
    # the server will gracefully shutdown (i.e., keep opened TCP streams finishes)
    # after the lease is revoked
216
217
218
219
220
    handler = RequestHandler(engine_client)
    if engine_args.is_embedding:
        await endpoint.serve_endpoint(handler.encode)
    else:
        await endpoint.serve_endpoint(handler.generate)
221
222
223
224
225
226
227
228
229
230
231
232
233


def cmd_line_args():
    parser = argparse.ArgumentParser(
        description="SGLang 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(
234
        "--model-path",
235
236
237
238
        type=str,
        default=DEFAULT_MODEL,
        help=f"Path to disk model or HuggingFace model identifier to load. Default: {DEFAULT_MODEL}",
    )
239
240
241
242
243
244
    parser.add_argument(
        "--model-name",
        type=str,
        default="",
        help="Name to serve the model under. Defaults to deriving it from model path.",
    )
245
246
247
248
249
250
251
252
253
    parser.add_argument(
        "--base-gpu-id",
        type=int,
        default=0,
        help="The base GPU ID to start allocating GPUs from. Useful when running multiple instances on the same machine.",
    )
    parser.add_argument(
        "--tensor-parallel-size", type=int, default=1, help="Number of GPUs to use."
    )
254
255
256
    parser.add_argument(
        "--kv-block-size", type=int, default=16, help="Size of a KV cache block."
    )
257
258
259
260
261
262
    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.",
    )
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    parser.add_argument(
        "--nnodes", type=int, default=1, help="The number of machines SGLang will use"
    )
    parser.add_argument(
        "--node-rank",
        type=int,
        default=0,
        help="Unique number for each node. 0 for the leader.",
    )
    parser.add_argument(
        "--dist-init-addr",
        type=str,
        default="",
        help="Host address (e.g., `192.168.0.2:25000`) of the node with rank 0",
    )
278
279
280
281
282
283
    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.",
    )
284
285
286
287
288
289
290
291
292
    parser.add_argument(
        "--extra-engine-args",
        type=str,
        default="",
        help="Path to a JSON file containing additional keyword arguments to pass to the SGLang Engine.",
    )
    args = parser.parse_args()

    config = Config()
293
294
295
296
297
298
    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
299
300
301
302

    endpoint_str = args.endpoint.replace("dyn://", "", 1)
    endpoint_parts = endpoint_str.split(".")
    if len(endpoint_parts) != 3:
303
        logging.error(
304
305
306
307
308
309
310
311
312
313
314
            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.base_gpu_id = args.base_gpu_id
    config.tensor_parallel_size = args.tensor_parallel_size
315
    config.kv_block_size = args.kv_block_size
316
    config.context_length = args.context_length
317
318
319
    config.nnodes = args.nnodes
    config.node_rank = args.node_rank
    config.dist_init_addr = args.dist_init_addr
320
    config.migration_limit = args.migration_limit
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())