sglang.py 13.8 KB
Newer Older
1
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
# SPDX-License-Identifier: Apache-2.0

import logging
import re
6
from typing import Tuple
7

8
9
import yaml

10
11
12
13
14
15
16
17
18
from benchmarks.profiler.utils.config import (
    Config,
    append_argument,
    break_arguments,
    get_service_name_by_type,
    get_worker_service_from_config,
    remove_valued_arguments,
    set_argument_value,
    setup_worker_service_resources,
19
    update_image,
20
21
    validate_and_get_worker_args,
)
22
from benchmarks.profiler.utils.config_modifiers.protocol import BaseConfigModifier
23
24
25
from benchmarks.profiler.utils.defaults import (
    DEFAULT_MODEL_NAME,
    DYNAMO_RUN_DEFAULT_PORT,
26
    EngineType,
27
28
29
30
31
32
33
34
35
36
37
38
39
40
)
from dynamo.planner.defaults import SubComponentType

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S"
)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)


41
DEFAULT_SGLANG_CONFIG_PATH = "examples/backends/sglang/deploy/disagg.yaml"
42
43


44
45
46
class SGLangConfigModifier(BaseConfigModifier):
    BACKEND = "sglang"

47
48
49
50
51
    @classmethod
    def load_default_config(cls) -> dict:
        with open(DEFAULT_SGLANG_CONFIG_PATH, "r") as f:
            return yaml.safe_load(f)

52
53
54
55
56
    @classmethod
    def update_image(cls, config, image: str) -> dict:
        """Update container image for all DGD services (frontend, planner, workers)."""
        return update_image(config, image)

57
58
59
60
    @classmethod
    def convert_config(
        cls,
        config: dict,
61
        target: EngineType,
62
63
64
65
66
67
68
69
70
71
72
        is_moe_model: bool = False,
    ) -> dict:
        cfg = Config.model_validate(config)

        # set metadata name
        cfg.metadata.name = "sglang-agg"

        # disable planner
        if "Planner" in cfg.spec.services:
            del cfg.spec.services["Planner"]

73
        if target == EngineType.PREFILL:
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
            # Get service names by inferring from subComponentType first
            prefill_service_name = get_service_name_by_type(
                cfg, "sglang", SubComponentType.PREFILL
            )
            decode_service_name = get_service_name_by_type(
                cfg, "sglang", SubComponentType.DECODE
            )

            # convert prefill worker into decode worker
            cfg.spec.services[decode_service_name] = cfg.spec.services[
                prefill_service_name
            ]
            del cfg.spec.services[prefill_service_name]

            # Set subComponentType for aggregated mode (using decode worker for prefill-only)
            cfg.spec.services[decode_service_name].subComponentType = "decode"

            worker_service = get_worker_service_from_config(
                cfg,
                backend="sglang",
                sub_component_type=SubComponentType.DECODE,
            )
            args = validate_and_get_worker_args(worker_service, backend="sglang")
            args = break_arguments(args)

            # remove disagg flags
            args = remove_valued_arguments(args, "--disaggregation-mode")
            args = remove_valued_arguments(args, "--disaggregation-transfer-backend")
            args = remove_valued_arguments(args, "--disaggregation-bootstrap-port")

            # disable prefix caching
            if "--disable-radix-cache" not in args:
                args = append_argument(args, "--disable-radix-cache")

            worker_service.extraPodSpec.mainContainer.args = args

110
        elif target == EngineType.DECODE:
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
            # Get service names by inferring from subComponentType first
            prefill_service_name = get_service_name_by_type(
                cfg, "sglang", SubComponentType.PREFILL
            )
            decode_service_name = get_service_name_by_type(
                cfg, "sglang", SubComponentType.DECODE
            )

            # delete prefill worker
            del cfg.spec.services[prefill_service_name]

            # Set subComponentType for aggregated decode-only mode
            cfg.spec.services[decode_service_name].subComponentType = "decode"

            worker_service = get_worker_service_from_config(
                cfg,
                backend="sglang",
                sub_component_type=SubComponentType.DECODE,
            )
            args = validate_and_get_worker_args(worker_service, backend="sglang")
            args = break_arguments(args)

            # remove disagg flags
            args = remove_valued_arguments(args, "--disaggregation-mode")
            args = remove_valued_arguments(args, "--disaggregation-transfer-backend")
            args = remove_valued_arguments(args, "--disaggregation-bootstrap-port")

            # enable prefix caching
            if "--disable-radix-cache" in args:
                args.remove("--disable-radix-cache")

            if is_moe_model:
                # need to use round_robin dp attention routing for MoE models to ensure kv reuse can skip prefill
                if "--load-balance-method" in args:
                    idx = args.index("--load-balance-method")
                    args[idx + 1] = "round_robin"
                else:
                    args = append_argument(
                        args, ["--load-balance-method", "round_robin"]
                    )

            worker_service.extraPodSpec.mainContainer.args = args

        # set num workers to 1
        # Use the inferred decode service name
        final_decode_service_name = get_service_name_by_type(
            cfg, "sglang", SubComponentType.DECODE
        )
        decode_worker_config = cfg.spec.services[final_decode_service_name]
        decode_worker_config.replicas = 1

        return cfg.model_dump()

    @classmethod
    def set_config_tp_size(
        cls,
        config: dict,
        tp_size: int,
        component_type: SubComponentType = SubComponentType.DECODE,
    ):
        cfg = Config.model_validate(config)
        worker_service = get_worker_service_from_config(
            cfg, backend="sglang", sub_component_type=component_type
        )

        # Set up resources
        setup_worker_service_resources(worker_service, tp_size)

        # Get and validate args
        args = validate_and_get_worker_args(worker_service, backend="sglang")

        # Set --tp argument
        args = set_argument_value(args, "--tp", str(tp_size))
184
185
186
187
188
189
190
191
192
193
194
195
        args = remove_valued_arguments(args, "--tp-size")
        args = remove_valued_arguments(args, "--tensor-parallel-size")

        # Remove --ep if present
        args = remove_valued_arguments(args, "--ep")
        args = remove_valued_arguments(args, "--ep-size")
        args = remove_valued_arguments(args, "--expert-parallel-size")

        # remove --dp if present
        args = remove_valued_arguments(args, "--dp")
        args = remove_valued_arguments(args, "--dp-size")
        args = remove_valued_arguments(args, "--data-parallel-size")
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220

        worker_service.extraPodSpec.mainContainer.args = args
        return cfg.model_dump()

    @classmethod
    def set_config_tep_size(
        cls,
        config: dict,
        tep_size: int,
        num_gpus_per_node: int,
        component_type: SubComponentType = SubComponentType.DECODE,
    ):
        cfg = Config.model_validate(config)
        worker_service = get_worker_service_from_config(
            cfg, backend="sglang", sub_component_type=component_type
        )

        # Set up resources with multinode configuration
        setup_worker_service_resources(worker_service, tep_size, num_gpus_per_node)

        # Get and validate args
        args = validate_and_get_worker_args(worker_service, backend="sglang")

        # 1. Set --tp=tep_size, if not present add it
        args = set_argument_value(args, "--tp", str(tep_size))
221
222
        args = remove_valued_arguments(args, "--tp-size")
        args = remove_valued_arguments(args, "--tensor-parallel-size")
223

224
225
226
227
        # 2. Set --ep=tep_size, if not present add it
        args = set_argument_value(args, "--ep", str(tep_size))
        args = remove_valued_arguments(args, "--ep-size")
        args = remove_valued_arguments(args, "--expert-parallel-size")
228
229
230

        # 3. Remove --dp if present
        args = remove_valued_arguments(args, "--dp")
231
232
        args = remove_valued_arguments(args, "--dp-size")
        args = remove_valued_arguments(args, "--data-parallel-size")
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261

        # 4. Remove --enable-dp-attention if present
        if "--enable-dp-attention" in args:
            args.remove("--enable-dp-attention")

        worker_service.extraPodSpec.mainContainer.args = args
        return cfg.model_dump()

    @classmethod
    def set_config_dep_size(
        cls,
        config: dict,
        dep_size: int,
        num_gpus_per_node: int,
        component_type: SubComponentType = SubComponentType.DECODE,
    ):
        cfg = Config.model_validate(config)
        worker_service = get_worker_service_from_config(
            cfg, backend="sglang", sub_component_type=component_type
        )

        # Set up resources with multinode configuration
        setup_worker_service_resources(worker_service, dep_size, num_gpus_per_node)

        # Get and validate args
        args = validate_and_get_worker_args(worker_service, backend="sglang")

        # 1. Set --tp=dep_size
        args = set_argument_value(args, "--tp", str(dep_size))
262
263
        args = remove_valued_arguments(args, "--tp-size")
        args = remove_valued_arguments(args, "--tensor-parallel-size")
264
265
266

        # 2. Set --dp=dep_size (data parallelism across experts)
        args = set_argument_value(args, "--dp", str(dep_size))
267
268
        args = remove_valued_arguments(args, "--dp-size")
        args = remove_valued_arguments(args, "--data-parallel-size")
269
270

        # 3. Enable --enable-dp-attention
271
272
        if "--enable-dp-attention" not in args:
            args = append_argument(args, "--enable-dp-attention")
273

274
275
276
277
        # 4. Set --ep=dep_size (expert parallelism size)
        args = set_argument_value(args, "--ep", str(dep_size))
        args = remove_valued_arguments(args, "--ep-size")
        args = remove_valued_arguments(args, "--expert-parallel-size")
278
279
280
281
282

        worker_service.extraPodSpec.mainContainer.args = args
        return cfg.model_dump()

    @classmethod
283
    def get_model_name(cls, config: dict) -> Tuple[str, str]:
284
285
286
287
288
289
290
291
        cfg = Config.model_validate(config)
        try:
            worker_service = get_worker_service_from_config(cfg, backend="sglang")
            args = validate_and_get_worker_args(worker_service, backend="sglang")
        except (ValueError, KeyError):
            logger.warning(
                f"Worker service missing or invalid, using default model name: {DEFAULT_MODEL_NAME}"
            )
292
            return DEFAULT_MODEL_NAME, DEFAULT_MODEL_NAME
293
294

        args = break_arguments(args)
295
        return cls._get_model_name_and_path_from_args(args, DEFAULT_MODEL_NAME, logger)
296
297
298
299
300
301
302
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

    @classmethod
    def get_port(cls, config: dict) -> int:
        cfg = Config.model_validate(config)
        frontend_service = cfg.spec.services.get("Frontend")
        if (
            not frontend_service
            or not frontend_service.extraPodSpec
            or not frontend_service.extraPodSpec.mainContainer
        ):
            logger.warning(
                f"Frontend service or container not found, using default port: {DYNAMO_RUN_DEFAULT_PORT}"
            )
            return DYNAMO_RUN_DEFAULT_PORT

        args = frontend_service.extraPodSpec.mainContainer.args
        if not args:
            logger.warning(
                f"No args found in Frontend configuration, using default port: {DYNAMO_RUN_DEFAULT_PORT}"
            )
            return DYNAMO_RUN_DEFAULT_PORT

        args = break_arguments(args)
        try:
            idx = args.index("--http-port")
            return int(args[idx + 1])
        except (ValueError, IndexError):
            logger.warning(
                f"Port not found in configuration args, using default port: {DYNAMO_RUN_DEFAULT_PORT}"
            )
            return DYNAMO_RUN_DEFAULT_PORT

    @classmethod
    def get_kv_cache_size_from_dynamo_log(
        cls, dynamo_log_fn: str, attention_dp_size: int = 1
    ) -> int:
        try:
            with open(dynamo_log_fn, "r") as f:
                for line in f:
                    if "KV Cache is allocated" in line and "#tokens:" in line:
                        # Extract the number after "#tokens:"
                        match = re.search(r"#tokens:\s*(\d+)", line)
                        if match:
                            return int(match.group(1)) * attention_dp_size
        except Exception as e:
            logger.warning(f"Failed to parse KV cache size from log file. Error: {e}")
        return 0
343
344
345

    @classmethod
    def set_prefill_config(
346
347
348
349
350
        cls,
        config: dict,
        max_batch_size: int,
        max_num_tokens: int,
        component_type: SubComponentType = SubComponentType.DECODE,
351
352
353
354
355
356
357
358
    ) -> dict:
        """
        Configure prefill-related limits for aggregated prefill runs.
        - Batch size is applied as server concurrency.
        - Max tokens is applied as a total token cap to avoid chunked prefill.
        """
        cfg = Config.model_validate(config)
        worker_service = get_worker_service_from_config(
359
            cfg, backend="sglang", sub_component_type=component_type
360
361
362
363
364
365
366
367
368
369
        )
        args = validate_and_get_worker_args(worker_service, backend="sglang")
        args = break_arguments(args)

        # Set max concurrency to control effective batch size
        args = set_argument_value(args, "--max-running-requests", str(max_batch_size))

        # Cap total tokens processed in a batch to avoid chunked prefill
        args = set_argument_value(args, "--chunked-prefill-size", str(max_num_tokens))

370
371
        args = append_argument(args, "--enable-dp-lm-head")

372
373
        worker_service.extraPodSpec.mainContainer.args = args
        return cfg.model_dump()