config.py 30.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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.

16
import json
17
import logging
18
import re
19
import shlex
20
from typing import Literal, Optional, Protocol
21

22
from pydantic import BaseModel
23

24
25
26
27
from benchmarks.profiler.utils.defaults import (
    DEFAULT_MODEL_NAME,
    DYNAMO_RUN_DEFAULT_PORT,
)
28
29
30
31
32
33
34
35
36
37
38
39
40
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)


41
class Container(BaseModel):
42
43
    args: Optional[list[str]] = None
    model_config = {"extra": "allow"}
44
45
46


class PodSpec(BaseModel):
47
48
    mainContainer: Optional[Container] = None
    model_config = {"extra": "allow"}
49
50
51


class ServiceResources(BaseModel):
52
    requests: Optional[dict[str, str]] = None
53
54
55
56
    limits: Optional[dict[str, str]] = None


class Service(BaseModel):
57
58
59
60
    replicas: Optional[int] = None
    resources: Optional[ServiceResources] = None
    extraPodSpec: Optional[PodSpec] = None
    model_config = {"extra": "allow"}
61
62
63
64


class Services(BaseModel):
    Frontend: Service
65
    model_config = {"extra": "allow"}
66
67
68
69
70
71
72
73
74
75
76
77
78


class Spec(BaseModel):
    services: dict[str, Service]


class Metadata(BaseModel):
    name: str


class Config(BaseModel):
    metadata: Metadata
    spec: Spec
79
    model_config = {"extra": "allow"}
80
81


82
83
84
85
def break_arguments(args: list[str] | None) -> list[str]:
    ans: list[str] = []
    if args is None:
        return ans
86
    if isinstance(args, str):
87
88
        # Use shlex.split to properly handle quoted arguments and JSON values
        ans = shlex.split(args)
89
90
    else:
        for arg in args:
91
            if arg is not None:
92
93
                # Use shlex.split to properly handle quoted arguments
                ans.extend(shlex.split(arg))
94
    return ans
95
96


97
98
99
100
101
102
103
104
105
106
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


107
def join_arguments(args: list[str]) -> list[str]:
108
109
    # Use shlex.join to properly quote arguments that contain spaces or special characters
    return [shlex.join(args)]
110
111


112
113
114
115
116
117
118
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
119
120


121
122
123
def find_arg_index(args: list[str]) -> int:
    # find the correct index to insert an argument
    idx = len(args)
124

125
126
127
128
129
    try:
        new_idx = args.index("|")
        idx = min(idx, new_idx)
    except ValueError:
        pass
130

131
132
133
134
135
    try:
        new_idx = args.index("2>&1")
        idx = min(idx, new_idx)
    except ValueError:
        pass
136

137
    return idx
138
139


140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def parse_override_engine_args(args: list[str]) -> tuple[dict, list[str]]:
    """
    Parse and extract --override-engine-args from argument list.

    Returns:
        tuple: (override_dict, modified_args) where override_dict is the parsed JSON
               and modified_args is the args list with --override-engine-args removed
    """
    override_dict = {}
    try:
        idx = args.index("--override-engine-args")
        if idx + 1 < len(args):
            # Parse existing override
            override_dict = json.loads(args[idx + 1])
            # Remove the old override args
            del args[idx : idx + 2]
    except (ValueError, json.JSONDecodeError):
        pass  # No existing override or invalid JSON

    return override_dict, args


162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
class ConfigModifierProtocol(Protocol):
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
        ...

    @classmethod
    def set_config_tp_size(cls, config: dict, tp_size: int) -> dict:
        ...

    @classmethod
    def get_model_name(cls, config: dict) -> str:
        ...

    @classmethod
    def get_port(cls, config: dict) -> int:
        ...

    @classmethod
    def get_kv_cache_size_from_dynamo_log(cls, dynamo_log_fn: str) -> int:
        ...


184
185
186
class VllmV1ConfigModifier:
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
187
        cfg = Config.model_validate(config)
188

189
        # set metadata name
190
        cfg.metadata.name = "vllm-agg"
191

192
        # disable planner
193
194
        if "Planner" in cfg.spec.services:
            del cfg.spec.services["Planner"]
195
196

        if target == "prefill":
197
            # convert prefill worker into decode worker
198
            cfg.spec.services[
199
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
200
            ] = cfg.spec.services[
201
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
202
            ]
203
            del cfg.spec.services[
204
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
205
206
            ]

207
            worker_service = cfg.spec.services[
208
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
209
210
211
212
213
214
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
215
                    f"Missing extraPodSpec or mainContainer in VLLM decode worker service '{WORKER_COMPONENT_NAMES['vllm'].decode_worker_k8s_name}'"
216
217
                )
            args = worker_service.extraPodSpec.mainContainer.args
218
219
220
221
222
223
224
225
226
227
228
229

            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")

230
            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
231

232
        elif target == "decode":
233
            # delete prefill worker
234
            del cfg.spec.services[
235
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
236
237
            ]

238
            worker_service = cfg.spec.services[
239
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
240
241
242
243
244
245
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
246
                    f"Missing extraPodSpec or mainContainer in VLLM decode worker service '{WORKER_COMPONENT_NAMES['vllm'].decode_worker_k8s_name}'"
247
248
                )
            args = worker_service.extraPodSpec.mainContainer.args
249
250

            args = break_arguments(args)
251

252
253
254
255
256
257
            # 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")

258
            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
259
260

        # set num workers to 1
261
        decode_worker_config = cfg.spec.services[
262
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
263
        ]
264
        decode_worker_config.replicas = 1
265

266
        return cfg.model_dump()
267
268
269

    @classmethod
    def set_config_tp_size(cls, config: dict, tp_size: int):
270
        cfg = Config.model_validate(config)
271

272
        worker_service = cfg.spec.services[
273
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
        ]

        # Ensure resources exists
        if worker_service.resources is None:
            worker_service.resources = ServiceResources()

        # Ensure requests exists
        if worker_service.resources.requests is None:
            worker_service.resources.requests = {}

        worker_service.resources.requests["gpu"] = str(tp_size)

        # Update limits if they exist
        if worker_service.resources.limits is not None:
            worker_service.resources.limits["gpu"] = str(tp_size)

290
        if (
291
292
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
293
        ):
294
295
296
            raise ValueError(
                f"Missing extraPodSpec or mainContainer in VLLM decode worker service '{WORKER_COMPONENT_NAMES['vllm'].decode_worker_k8s_name}'"
            )
297
        args = worker_service.extraPodSpec.mainContainer.args
298
299
300
301
302
303
304
305
306

        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)])

307
        worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
308

309
        return cfg.model_dump()
310
311
312

    @classmethod
    def get_model_name(cls, config: dict) -> str:
313
        cfg = Config.model_validate(config)
314
        worker_name = WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
315
316
317
318
319
320
321
322
323
324
        worker_service = cfg.spec.services[worker_name]
        if (
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
        ):
            logger.warning(
                f"Worker service missing extraPodSpec or mainContainer, using default model name: {DEFAULT_MODEL_NAME}"
            )
            return DEFAULT_MODEL_NAME
        args = worker_service.extraPodSpec.mainContainer.args
325
326
327
328
329
330
331
332
333
334

        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
335
336
337

    @classmethod
    def get_port(cls, config: dict) -> int:
338
        cfg = Config.model_validate(config)
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
        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

357
358
359
360
        args = break_arguments(args)
        try:
            idx = args.index("--http-port")
            return int(args[idx + 1])
361
        except (ValueError, IndexError):
362
363
364
365
            logger.warning(
                f"Port not found in configuration args, using default port: {DYNAMO_RUN_DEFAULT_PORT}"
            )
            return DYNAMO_RUN_DEFAULT_PORT
366
367
368

    @classmethod
    def get_kv_cache_size_from_dynamo_log(cls, dynamo_log_fn: str) -> int:
369
        # TODO
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
        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


391
392
393
class SGLangConfigModifier:
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
394
        cfg = Config.model_validate(config)
395
396

        # set metadata name
397
        cfg.metadata.name = "sglang-agg"
398
399

        # disable planner
400
401
        if "Planner" in cfg.spec.services:
            del cfg.spec.services["Planner"]
402
403
404

        if target == "prefill":
            # convert prefill worker into decode worker
405
            cfg.spec.services[
406
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
407
            ] = cfg.spec.services[
408
409
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]
410
            del cfg.spec.services[
411
412
413
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]

414
            worker_service = cfg.spec.services[
415
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
416
417
418
419
420
421
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
422
                    f"Missing extraPodSpec or mainContainer in SGLang decode worker service '{WORKER_COMPONENT_NAMES['sglang'].decode_worker_k8s_name}'"
423
424
                )
            args = worker_service.extraPodSpec.mainContainer.args
425
426
427
428
429
430
431
432
433
434
435

            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")

436
            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
437
438
439

        elif target == "decode":
            # delete prefill worker
440
            del cfg.spec.services[
441
442
443
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]

444
            worker_service = cfg.spec.services[
445
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
446
447
448
449
450
451
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
452
                    f"Missing extraPodSpec or mainContainer in SGLang decode worker service '{WORKER_COMPONENT_NAMES['sglang'].decode_worker_k8s_name}'"
453
454
                )
            args = worker_service.extraPodSpec.mainContainer.args
455
456
457
458
459
460
461
462
463
464
465

            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")

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

466
            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
467
468
469
470
471
472
473
474
475
476
477

        # 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):
478
        cfg = Config.model_validate(config)
479

480
        worker_service = cfg.spec.services[
481
            WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
        ]

        # Ensure resources exists
        if worker_service.resources is None:
            worker_service.resources = ServiceResources()

        # Ensure requests exists
        if worker_service.resources.requests is None:
            worker_service.resources.requests = {}

        worker_service.resources.requests["gpu"] = str(tp_size)

        # Update limits if they exist
        if worker_service.resources.limits is not None:
            worker_service.resources.limits["gpu"] = str(tp_size)

498
        if (
499
500
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
501
        ):
502
503
504
            raise ValueError(
                f"Missing extraPodSpec or mainContainer in SGLang decode worker service '{WORKER_COMPONENT_NAMES['sglang'].decode_worker_k8s_name}'"
            )
505
        args = worker_service.extraPodSpec.mainContainer.args
506
507
508
509
510
511
512
513
514

        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)])

515
        worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
516

517
        return cfg.model_dump()
518
519
520

    @classmethod
    def get_model_name(cls, config: dict) -> str:
521
        cfg = Config.model_validate(config)
522
        worker_name = WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
523
524
525
526
527
528
529
530
531
532
        worker_service = cfg.spec.services[worker_name]
        if (
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
        ):
            logger.warning(
                f"Worker service missing extraPodSpec or mainContainer, using default model name: {DEFAULT_MODEL_NAME}"
            )
            return DEFAULT_MODEL_NAME
        args = worker_service.extraPodSpec.mainContainer.args
533
534
535
536
537
538
539
540
541
542
543
544
545

        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:
546
        cfg = Config.model_validate(config)
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
        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

565
566
567
568
        args = break_arguments(args)
        try:
            idx = args.index("--http-port")
            return int(args[idx + 1])
569
        except (ValueError, IndexError):
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
            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


591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
class TrtllmConfigModifier:
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
        cfg = Config.model_validate(config)

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

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

        if target == "prefill":
            # Convert to prefill-only aggregated setup
            # Merge prefill worker config into a single worker
            if "TRTLLMPrefillWorker" in cfg.spec.services:
                # Rename prefill worker to generic worker
                cfg.spec.services["TRTLLMWorker"] = cfg.spec.services[
                    "TRTLLMPrefillWorker"
                ]
                del cfg.spec.services["TRTLLMPrefillWorker"]

            # Remove decode worker
            del cfg.spec.services["TRTLLMDecodeWorker"]

            worker_service = cfg.spec.services["TRTLLMWorker"]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
                    "Missing extraPodSpec or mainContainer in TRTLLM worker service 'TRTLLMWorker'"
                )
            args = worker_service.extraPodSpec.mainContainer.args

            args = break_arguments(args)

            # Remove disaggregation args
            args = remove_valued_arguments(args, "--disaggregation-mode")
            args = remove_valued_arguments(args, "--disaggregation-strategy")

            # Keep the original extra-engine-args (prefill.yaml) which may contain user settings
            # Check if user already has override-engine-args and merge with our changes
            override_dict, args = parse_override_engine_args(args)

            # Merge our overrides for converting prefill-only disagg to aggregated:
            # - Disable enable_block_reuse (no KV reuse for prefill-only)
            # - Enable overlap scheduler (disabled in prefill.yaml but needed for agg)
            # - Remove cache_transceiver_config (not needed in agg mode)
            if "kv_cache_config" not in override_dict:
                override_dict["kv_cache_config"] = {}
            override_dict["kv_cache_config"]["enable_block_reuse"] = False
            override_dict[
                "disable_overlap_scheduler"
            ] = False  # Enable overlap scheduler for agg
            override_dict[
                "cache_transceiver_config"
            ] = None  # Remove cache transceiver for agg

            override_str = json.dumps(override_dict)
            args = append_argument(args, ["--override-engine-args", override_str])

            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)

        elif target == "decode":
            # Convert to decode-only aggregated setup
            # Use decode worker as the main worker
            if "TRTLLMDecodeWorker" in cfg.spec.services:
                # Rename decode worker to generic worker
                cfg.spec.services["TRTLLMWorker"] = cfg.spec.services[
                    "TRTLLMDecodeWorker"
                ]
                del cfg.spec.services["TRTLLMDecodeWorker"]

            # Remove prefill worker if exists
            if "TRTLLMPrefillWorker" in cfg.spec.services:
                del cfg.spec.services["TRTLLMPrefillWorker"]

            worker_service = cfg.spec.services["TRTLLMWorker"]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
                    "Missing extraPodSpec or mainContainer in TRTLLM worker service 'TRTLLMWorker'"
                )
            args = worker_service.extraPodSpec.mainContainer.args

            args = break_arguments(args)

            # Remove disaggregation args
            args = remove_valued_arguments(args, "--disaggregation-mode")
            args = remove_valued_arguments(args, "--disaggregation-strategy")

            # Keep the original extra-engine-args (decode.yaml) which may contain user settings
            # Check if user already has override-engine-args and merge with our changes
            override_dict, args = parse_override_engine_args(args)

            # Merge our overrides for converting decode-only disagg to aggregated:
            # - Enable enable_block_reuse (to skip prefill in decode-only)
            # - Remove cache_transceiver_config (not needed in agg mode)
            if "kv_cache_config" not in override_dict:
                override_dict["kv_cache_config"] = {}
            override_dict["kv_cache_config"]["enable_block_reuse"] = True
            override_dict[
                "cache_transceiver_config"
            ] = None  # Remove cache transceiver for agg

            override_str = json.dumps(override_dict)
            args = append_argument(args, ["--override-engine-args", override_str])

            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)

        # Set num workers to 1
        worker_config = cfg.spec.services["TRTLLMWorker"]
        worker_config.replicas = 1

        return cfg.model_dump()

    @classmethod
    def set_config_tp_size(cls, config: dict, tp_size: int):
        cfg = Config.model_validate(config)

        worker_service = cfg.spec.services["TRTLLMWorker"]

        # Ensure resources exists
        if worker_service.resources is None:
            worker_service.resources = ServiceResources()

        # Ensure requests exists
        if worker_service.resources.requests is None:
            worker_service.resources.requests = {}

        worker_service.resources.requests["gpu"] = str(tp_size)

        # Update limits if they exist
        if worker_service.resources.limits is not None:
            worker_service.resources.limits["gpu"] = str(tp_size)

        if (
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
        ):
            raise ValueError(
                "Missing extraPodSpec or mainContainer in TRTLLM worker service 'TRTLLMWorker'"
            )
        args = worker_service.extraPodSpec.mainContainer.args

        # Break arguments to handle both joined strings and lists
        args = break_arguments(args)

        # For TRT-LLM, we need to update the override-engine-args
        # to set the tensor_parallel_size
        override_dict, args = parse_override_engine_args(args)

        # Add/update tensor_parallel_size in the override
        override_dict["tensor_parallel_size"] = tp_size
        override_str = json.dumps(override_dict)
        args = append_argument(args, ["--override-engine-args", override_str])

        worker_service.extraPodSpec.mainContainer.args = join_arguments(args)

        return cfg.model_dump()

    @classmethod
    def get_model_name(cls, config: dict) -> str:
        cfg = Config.model_validate(config)
        worker_name = "TRTLLMWorker"
        worker_service = cfg.spec.services.get(worker_name)

        # Also check for disagg worker names
        if not worker_service:
            worker_name = "TRTLLMPrefillWorker"
            worker_service = cfg.spec.services.get(worker_name)
        if not worker_service:
            worker_name = "TRTLLMDecodeWorker"
            worker_service = cfg.spec.services.get(worker_name)

        if not worker_service:
            logger.warning(
                f"Worker service not found, using default model name: {DEFAULT_MODEL_NAME}"
            )
            return DEFAULT_MODEL_NAME

        if (
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
        ):
            logger.warning(
                f"Worker service missing extraPodSpec or mainContainer, using default model name: {DEFAULT_MODEL_NAME}"
            )
            return DEFAULT_MODEL_NAME
        args = worker_service.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:
        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

        # TRT-LLM frontend doesn't have args, it uses the default port
        return DYNAMO_RUN_DEFAULT_PORT

    @classmethod
    def get_kv_cache_size_from_dynamo_log(cls, dynamo_log_fn: str) -> int:
        # TRT-LLM log parsing for KV cache size
        # Format: [TensorRT-LLM][INFO] [MemUsageChange] Allocated XX GiB for max tokens in paged KV cache (XXXXXX).
        try:
            with open(dynamo_log_fn, "r") as f:
                for line in f:
                    # Look for the specific TRT-LLM KV cache allocation log
                    if (
                        "Allocated" in line
                        and "for max tokens in paged KV cache" in line
                    ):
                        # Extract the number in parentheses at the end
                        match = re.search(r"paged KV cache \((\d+)\)", line)
                        if match:
                            max_tokens = int(match.group(1))
                            logger.info(
                                f"Found TRT-LLM KV cache max tokens: {max_tokens}"
                            )
                            return max_tokens
        except Exception as e:
            logger.warning(f"Failed to parse KV cache size from log file. Error: {e}")

        # Return a reasonable default if we couldn't find the KV cache size in logs
        logger.warning(
            "Could not find KV cache size in TRT-LLM logs, using default value of 100000"
        )
        return 100000  # Default fallback value for TRT-LLM


842
CONFIG_MODIFIERS: dict[str, type[ConfigModifierProtocol]] = {
843
    "vllm": VllmV1ConfigModifier,
844
    "sglang": SGLangConfigModifier,
845
    "trtllm": TrtllmConfigModifier,
846
}
847
848
849

# Re-export WORKER_COMPONENT_NAMES for profile_sla.py
__all__ = ["CONFIG_MODIFIERS", "WORKER_COMPONENT_NAMES"]