config.py 30.8 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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


def deep_update(target: dict, source: dict) -> None:
    """
    Recursively update nested dictionaries.

    Args:
        target: Dictionary to update
        source: Dictionary with new values
    """
    for key, value in source.items():
        if isinstance(value, dict) and key in target and isinstance(target[key], dict):
            deep_update(target[key], value)
        else:
            target[key] = value


177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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:
        ...


199
200
201
class VllmV1ConfigModifier:
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
202
        cfg = Config.model_validate(config)
203

204
        # set metadata name
205
        cfg.metadata.name = "vllm-agg"
206

207
        # disable planner
208
209
        if "Planner" in cfg.spec.services:
            del cfg.spec.services["Planner"]
210
211

        if target == "prefill":
212
            # convert prefill worker into decode worker
213
            cfg.spec.services[
214
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
215
            ] = cfg.spec.services[
216
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
217
            ]
218
            del cfg.spec.services[
219
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
220
221
            ]

222
            worker_service = cfg.spec.services[
223
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
224
225
226
227
228
229
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
230
                    f"Missing extraPodSpec or mainContainer in VLLM decode worker service '{WORKER_COMPONENT_NAMES['vllm'].decode_worker_k8s_name}'"
231
232
                )
            args = worker_service.extraPodSpec.mainContainer.args
233
234
235
236
237
238
239
240
241
242
243
244

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

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

247
        elif target == "decode":
248
            # delete prefill worker
249
            del cfg.spec.services[
250
                WORKER_COMPONENT_NAMES["vllm"].prefill_worker_k8s_name
251
252
            ]

253
            worker_service = cfg.spec.services[
254
                WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
255
256
257
258
259
260
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
261
                    f"Missing extraPodSpec or mainContainer in VLLM decode worker service '{WORKER_COMPONENT_NAMES['vllm'].decode_worker_k8s_name}'"
262
263
                )
            args = worker_service.extraPodSpec.mainContainer.args
264
265

            args = break_arguments(args)
266

267
268
269
270
271
272
            # 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")

273
            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
274
275

        # set num workers to 1
276
        decode_worker_config = cfg.spec.services[
277
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
278
        ]
279
        decode_worker_config.replicas = 1
280

281
        return cfg.model_dump()
282
283
284

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

287
        worker_service = cfg.spec.services[
288
            WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        ]

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

305
        if (
306
307
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
308
        ):
309
310
311
            raise ValueError(
                f"Missing extraPodSpec or mainContainer in VLLM decode worker service '{WORKER_COMPONENT_NAMES['vllm'].decode_worker_k8s_name}'"
            )
312
        args = worker_service.extraPodSpec.mainContainer.args
313
314
315
316
317
318
319
320
321

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

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

324
        return cfg.model_dump()
325
326
327

    @classmethod
    def get_model_name(cls, config: dict) -> str:
328
        cfg = Config.model_validate(config)
329
        worker_name = WORKER_COMPONENT_NAMES["vllm"].decode_worker_k8s_name
330
331
332
333
334
335
336
337
338
339
        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
340
341
342
343
344
345
346
347
348
349

        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
350
351
352

    @classmethod
    def get_port(cls, config: dict) -> int:
353
        cfg = Config.model_validate(config)
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
        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

372
373
374
375
        args = break_arguments(args)
        try:
            idx = args.index("--http-port")
            return int(args[idx + 1])
376
        except (ValueError, IndexError):
377
378
379
380
            logger.warning(
                f"Port not found in configuration args, using default port: {DYNAMO_RUN_DEFAULT_PORT}"
            )
            return DYNAMO_RUN_DEFAULT_PORT
381
382
383

    @classmethod
    def get_kv_cache_size_from_dynamo_log(cls, dynamo_log_fn: str) -> int:
384
        # TODO
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
        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


406
407
408
class SGLangConfigModifier:
    @classmethod
    def convert_config(cls, config: dict, target: Literal["prefill", "decode"]) -> dict:
409
        cfg = Config.model_validate(config)
410
411

        # set metadata name
412
        cfg.metadata.name = "sglang-agg"
413
414

        # disable planner
415
416
        if "Planner" in cfg.spec.services:
            del cfg.spec.services["Planner"]
417
418
419

        if target == "prefill":
            # convert prefill worker into decode worker
420
            cfg.spec.services[
421
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
422
            ] = cfg.spec.services[
423
424
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]
425
            del cfg.spec.services[
426
427
428
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]

429
            worker_service = cfg.spec.services[
430
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
431
432
433
434
435
436
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
437
                    f"Missing extraPodSpec or mainContainer in SGLang decode worker service '{WORKER_COMPONENT_NAMES['sglang'].decode_worker_k8s_name}'"
438
439
                )
            args = worker_service.extraPodSpec.mainContainer.args
440
441
442
443
444
445
446
447
448
449
450

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

451
            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
452
453
454

        elif target == "decode":
            # delete prefill worker
455
            del cfg.spec.services[
456
457
458
                WORKER_COMPONENT_NAMES["sglang"].prefill_worker_k8s_name
            ]

459
            worker_service = cfg.spec.services[
460
                WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
461
462
463
464
465
466
            ]
            if (
                not worker_service.extraPodSpec
                or not worker_service.extraPodSpec.mainContainer
            ):
                raise ValueError(
467
                    f"Missing extraPodSpec or mainContainer in SGLang decode worker service '{WORKER_COMPONENT_NAMES['sglang'].decode_worker_k8s_name}'"
468
469
                )
            args = worker_service.extraPodSpec.mainContainer.args
470
471
472
473
474
475
476
477
478
479
480

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

481
            worker_service.extraPodSpec.mainContainer.args = join_arguments(args)
482
483
484
485
486
487
488
489
490
491
492

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

495
        worker_service = cfg.spec.services[
496
            WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
        ]

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

513
        if (
514
515
            not worker_service.extraPodSpec
            or not worker_service.extraPodSpec.mainContainer
516
        ):
517
518
519
            raise ValueError(
                f"Missing extraPodSpec or mainContainer in SGLang decode worker service '{WORKER_COMPONENT_NAMES['sglang'].decode_worker_k8s_name}'"
            )
520
        args = worker_service.extraPodSpec.mainContainer.args
521
522
523
524
525
526
527
528
529

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

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

532
        return cfg.model_dump()
533
534
535

    @classmethod
    def get_model_name(cls, config: dict) -> str:
536
        cfg = Config.model_validate(config)
537
        worker_name = WORKER_COMPONENT_NAMES["sglang"].decode_worker_k8s_name
538
539
540
541
542
543
544
545
546
547
        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
548
549
550
551
552
553
554
555
556
557
558
559
560

        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:
561
        cfg = Config.model_validate(config)
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
        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

580
581
582
583
        args = break_arguments(args)
        try:
            idx = args.index("--http-port")
            return int(args[idx + 1])
584
        except (ValueError, IndexError):
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
            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


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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
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


857
CONFIG_MODIFIERS: dict[str, type[ConfigModifierProtocol]] = {
858
    "vllm": VllmV1ConfigModifier,
859
    "sglang": SGLangConfigModifier,
860
    "trtllm": TrtllmConfigModifier,
861
}
862
863
864

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