config.py 14.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
17
import re
18
from copy import deepcopy
19
20
from typing import Literal

21
22
from utils.defaults import DEFAULT_MODEL_NAME, DYNAMO_RUN_DEFAULT_PORT

23
24
25
26
27
28
29
30
31
32
33
34
35
from dynamo.planner.defaults import WORKER_COMPONENT_NAMES

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)


36
37
38
def break_arguments(args: list[str]) -> list[str]:
    ans = []
    if isinstance(args, str):
39
        ans = re.split(r"[ =]", args)
40
41
42
43
    else:
        for arg in args:
            ans.extend(arg.split(" "))
    return ans
44
45


46
47
48
49
50
51
52
53
54
55
def remove_valued_arguments(args: list[str], key: str) -> list[str]:
    """Remove a valued argument (e.g., --key value) from the arguments list if exists."""
    if key in args:
        idx = args.index(key)
        if idx + 1 < len(args):
            del args[idx : idx + 2]

    return args


56
57
def join_arguments(args: list[str]) -> list[str]:
    return [" ".join(args)]
58
59


60
61
62
63
64
65
66
def append_argument(args: list[str], to_append) -> list[str]:
    idx = find_arg_index(args)
    if isinstance(to_append, list):
        args[idx:idx] = to_append
    else:
        args.insert(idx, to_append)
    return args
67
68


69
70
71
def find_arg_index(args: list[str]) -> int:
    # find the correct index to insert an argument
    idx = len(args)
72

73
74
75
76
77
    try:
        new_idx = args.index("|")
        idx = min(idx, new_idx)
    except ValueError:
        pass
78

79
80
81
82
83
    try:
        new_idx = args.index("2>&1")
        idx = min(idx, new_idx)
    except ValueError:
        pass
84

85
    return idx
86
87
88
89
90


class VllmV1ConfigModifier:
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
91
        config = deepcopy(config)
92

93
        # set metadata name
94
        config["metadata"]["name"] = "vllm-agg"
95

96
97
98
        # disable planner
        if "Planner" in config["spec"]["services"]:
            del config["spec"]["services"]["Planner"]
99
100

        if target == "prefill":
101
102
            # convert prefill worker into decode worker
            config["spec"]["services"][
103
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
104
            ] = config["spec"]["services"][
105
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
106
107
            ]
            del config["spec"]["services"][
108
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
109
110
111
            ]

            args = config["spec"]["services"][
112
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
113
114
115
116
117
118
119
120
121
122
123
124
125
            ]["extraPodSpec"]["mainContainer"]["args"]

            args = break_arguments(args)

            # remove --is-prefill-worker flag
            args.remove("--is-prefill-worker")

            # disable prefix caching
            if "--enable-prefix-caching" in args:
                args.remove("--enable-prefix-caching")
            if "--no-enable-prefix-caching" not in args:
                args = append_argument(args, "--no-enable-prefix-caching")

126
127
128
            config["spec"]["services"][
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
            ]["extraPodSpec"]["mainContainer"]["args"] = join_arguments(args)
129

130
        elif target == "decode":
131
132
            # delete prefill worker
            del config["spec"]["services"][
133
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
134
135
136
            ]

            args = config["spec"]["services"][
137
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
138
139
140
            ]["extraPodSpec"]["mainContainer"]["args"]

            args = break_arguments(args)
141

142
143
144
145
146
147
            # enable prefix caching
            if "--enable-prefix-caching" not in args:
                args = append_argument(args, "--enable-prefix-caching")
            if "--no-enable-prefix-caching" in args:
                args.remove("--no-enable-prefix-caching")

148
149
150
            config["spec"]["services"][
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
            ]["extraPodSpec"]["mainContainer"]["args"] = join_arguments(args)
151
152

        # set num workers to 1
153
        decode_worker_config = config["spec"]["services"][
154
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
155
156
        ]
        decode_worker_config["replicas"] = 1
157
158
159
160
161

        return config

    @classmethod
    def set_config_tp_size(cls, config: dict, tp_size: int):
162
163
        config = deepcopy(config)

164
165
166
        config["spec"]["services"][
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
        ]["resources"]["requests"]["gpu"] = str(tp_size)
167
168
169
170
171
172
173
174
175
        if (
            "limits"
            in config["spec"]["services"][
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
            ]["resources"]
        ):
            config["spec"]["services"][
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
            ]["resources"]["limits"]["gpu"] = str(tp_size)
176

177
178
179
        args = config["spec"]["services"][
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
        ]["extraPodSpec"]["mainContainer"]["args"]
180
181
182
183
184
185
186
187
188

        args = break_arguments(args)

        try:
            idx = args.index("--tensor-parallel-size")
            args[idx + 1] = str(tp_size)
        except ValueError:
            args = append_argument(args, ["--tensor-parallel-size", str(tp_size)])

189
190
191
        config["spec"]["services"][
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
        ]["extraPodSpec"]["mainContainer"]["args"] = join_arguments(args)
192

193
194
195
196
        return config

    @classmethod
    def get_model_name(cls, config: dict) -> str:
197
        worker_name = WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
198
199
200
201
202
203
204
205
206
207
208
209
210
        args = config["spec"]["services"][worker_name]["extraPodSpec"]["mainContainer"][
            "args"
        ]

        args = break_arguments(args)
        for i, arg in enumerate(args):
            if arg == "--model" and i + 1 < len(args):
                return args[i + 1]

        logger.warning(
            f"Model name not found in configuration args, using default model name: {DEFAULT_MODEL_NAME}"
        )
        return DEFAULT_MODEL_NAME
211
212
213

    @classmethod
    def get_port(cls, config: dict) -> int:
214
215
216
217
218
219
220
221
222
223
224
225
        args = config["spec"]["services"]["Frontend"]["extraPodSpec"]["mainContainer"][
            "args"
        ]
        args = break_arguments(args)
        try:
            idx = args.index("--http-port")
            return int(args[idx + 1])
        except ValueError:
            logger.warning(
                f"Port not found in configuration args, using default port: {DYNAMO_RUN_DEFAULT_PORT}"
            )
            return DYNAMO_RUN_DEFAULT_PORT
226
227
228

    @classmethod
    def get_kv_cache_size_from_dynamo_log(cls, dynamo_log_fn: str) -> int:
229
        # TODO
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
        try:
            with open(dynamo_log_fn, "r") as f:
                for line in f:
                    if "Maximum concurrency for" in line:
                        line = line.strip().split("Maximum concurrency for ")[1]
                        token_count = int(
                            line.split(" tokens per request: ")[0].replace(",", "")
                        )
                        concurrency = float(line.split(" tokens per request: ")[1][:-1])

                        logger.info(
                            f"Found KV cache info: {token_count} x {concurrency} = {int(token_count * concurrency)}"
                        )
                        return int(token_count * concurrency)
        except Exception as e:
            logger.warning(
                f"Failed to parse KV cache size from line: {line}. Error: {e}"
            )
        return 0


251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
class SGLangConfigModifier:
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
        config = deepcopy(config)

        # set metadata name
        config["metadata"]["name"] = "sglang-agg"

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

        if target == "prefill":
            # convert prefill worker into decode worker
            config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
            ] = config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]
            del config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]

            args = config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
            ]["extraPodSpec"]["mainContainer"]["args"]

            args = break_arguments(args)

            # remove `--disaggregation-mode` and `--disaggregation-transfer-backend`
            args = remove_valued_arguments(args, "--disaggregation-mode")
            args = remove_valued_arguments(args, "--disaggregation-transfer-backend")

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

            config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
            ]["extraPodSpec"]["mainContainer"]["args"] = join_arguments(args)

        elif target == "decode":
            # delete prefill worker
            del config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]

            args = config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
            ]["extraPodSpec"]["mainContainer"]["args"]

            args = break_arguments(args)

            # call `dynamo.sglang.worker` instead of `dynamo.sglang.decode_worker`
            idx = args.index("dynamo.sglang.decode_worker")
            args[idx] = "dynamo.sglang.worker"

            # remove `--disaggregation-mode` and `--disaggregation-transfer-backend`
            args = remove_valued_arguments(args, "--disaggregation-mode")
            args = remove_valued_arguments(args, "--disaggregation-transfer-backend")

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

            config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
            ]["extraPodSpec"]["mainContainer"]["args"] = join_arguments(args)

        # set num workers to 1
        decode_worker_config = config["spec"]["services"][
            WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
        ]
        decode_worker_config["replicas"] = 1

        return config

    @classmethod
    def set_config_tp_size(cls, config: dict, tp_size: int):
        config = deepcopy(config)

        config["spec"]["services"][
            WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
        ]["resources"]["requests"]["gpu"] = str(tp_size)
        if (
            "limits"
            in config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
            ]["resources"]
        ):
            config["spec"]["services"][
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
            ]["resources"]["limits"]["gpu"] = str(tp_size)

        args = config["spec"]["services"][
            WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
        ]["extraPodSpec"]["mainContainer"]["args"]

        args = break_arguments(args)

        try:
            idx = args.index("--tp")
            args[idx + 1] = str(tp_size)
        except ValueError:
            args = append_argument(args, ["--tp", str(tp_size)])

        config["spec"]["services"][
            WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
        ]["extraPodSpec"]["mainContainer"]["args"] = join_arguments(args)

        return config

    @classmethod
    def get_model_name(cls, config: dict) -> str:
        worker_name = WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
        args = config["spec"]["services"][worker_name]["extraPodSpec"]["mainContainer"][
            "args"
        ]

        args = break_arguments(args)
        for i, arg in enumerate(args):
            if arg == "--served-model-name" and i + 1 < len(args):
                return args[i + 1]

        logger.warning(
            f"Model name not found in configuration args, using default model name: {DEFAULT_MODEL_NAME}"
        )
        return DEFAULT_MODEL_NAME

    @classmethod
    def get_port(cls, config: dict) -> int:
        args = config["spec"]["services"]["Frontend"]["extraPodSpec"]["mainContainer"][
            "args"
        ]
        args = break_arguments(args)
        try:
            idx = args.index("--http-port")
            return int(args[idx + 1])
        except ValueError:
            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) -> int:
        # TODO
        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))
        except Exception as e:
            logger.warning(f"Failed to parse KV cache size from log file. Error: {e}")
        return 0


411
CONFIG_MODIFIERS = {
412
    "vllm": VllmV1ConfigModifier,
413
    "sglang": SGLangConfigModifier,
414
}