|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +"""Engine features a step target must declare before a deployment that turns them on can build it. |
| 4 | +
|
| 5 | +A deployment's core hands each step to one of its step targets (``_select_target``): every |
| 6 | +step with context rows to ``PrefillTarget``, every step without to ``DecodeTarget``. A |
| 7 | +deployment class whose step targets declare features names them in ``step_targets``; a |
| 8 | +deployment class without it stands for all of its steps and is its own step target. |
| 9 | +
|
| 10 | +A :class:`Feature` changes some kinds of step (:attr:`Feature.steps`, which may depend on how |
| 11 | +the deployment sets it), and every step target that runs those steps has to serve it. Each |
| 12 | +feature is a class whose instance holds the facts that decide support, read from the engine |
| 13 | +arguments by :meth:`Feature.from_args`, which returns None while the feature is off. A step |
| 14 | +target declares support with the feature's class decorator:: |
| 15 | +
|
| 16 | + @PrefillCudaGraph.supported(when=_prefill_cuda_graph_supported) |
| 17 | + class PrefillTarget: ... |
| 18 | +
|
| 19 | +``when`` sees only the feature instance and returns whether the target serves it; without |
| 20 | +``when`` the target serves every setting of the feature. A step target that does not declare |
| 21 | +a feature does not serve it: ``modeling_v2_resolve`` refuses every deployment one of whose |
| 22 | +step targets runs a step the feature changes without serving it, so a feature added here is |
| 23 | +refused everywhere until step targets declare it. A step target that never runs those steps |
| 24 | +need not declare it: a breakable prefill CUDA graph changes only the steps with context |
| 25 | +rows, so a ``DecodeTarget`` never has to serve one. |
| 26 | +
|
| 27 | +Picking a different step target when a feature is on is the core's decision, made with an |
| 28 | +ordinary branch on ``Feature.from_args`` in ``_select_target``. |
| 29 | +""" |
| 30 | + |
| 31 | +from __future__ import annotations |
| 32 | + |
| 33 | +import enum |
| 34 | +from dataclasses import dataclass |
| 35 | +from typing import TYPE_CHECKING, Callable, ClassVar, Dict, FrozenSet, List, Optional, Type |
| 36 | + |
| 37 | +if TYPE_CHECKING: |
| 38 | + from tensorrt_llm._torch.model_config import ModelConfig |
| 39 | + from tensorrt_llm.llmapi.llm_args import PrefillCudaGraphBackend, TorchLlmArgs |
| 40 | + |
| 41 | + |
| 42 | +class Step(enum.Enum): |
| 43 | + """The kinds of step a core hands to its step targets.""" |
| 44 | + |
| 45 | + #: A step with context rows, possibly with generation rows beside them. |
| 46 | + CONTEXT = "context" |
| 47 | + #: A step with generation rows only. |
| 48 | + DECODE = "decode" |
| 49 | + |
| 50 | + |
| 51 | +def step_targets(deployment: type) -> Dict[Step, type]: |
| 52 | + """The step target that runs each kind of step of ``deployment``.""" |
| 53 | + return getattr(deployment, "step_targets", None) or {step: deployment for step in Step} |
| 54 | + |
| 55 | + |
| 56 | +# Every feature class, filled as each is defined. |
| 57 | +_FEATURES: List[Type["Feature"]] = [] |
| 58 | + |
| 59 | + |
| 60 | +class Feature: |
| 61 | + """An engine feature a step target serves only once it declares it.""" |
| 62 | + |
| 63 | + # step target class -> its ``when``, or None for every setting; one dict per feature class. |
| 64 | + _supported_by: ClassVar[Dict[type, Optional[Callable[["Feature"], bool]]]] |
| 65 | + |
| 66 | + def __init_subclass__(cls, **kwargs): |
| 67 | + super().__init_subclass__(**kwargs) |
| 68 | + cls._supported_by = {} |
| 69 | + _FEATURES.append(cls) |
| 70 | + |
| 71 | + @classmethod |
| 72 | + def from_args( |
| 73 | + cls, model_config: "ModelConfig", llm_args: "TorchLlmArgs" |
| 74 | + ) -> Optional["Feature"]: |
| 75 | + """The feature as this deployment sets it, or None when the deployment leaves it off.""" |
| 76 | + raise NotImplementedError |
| 77 | + |
| 78 | + @property |
| 79 | + def steps(self) -> FrozenSet[Step]: |
| 80 | + """The kinds of step the feature, as set, changes.""" |
| 81 | + return frozenset(Step) |
| 82 | + |
| 83 | + @classmethod |
| 84 | + def supported(cls, when: Optional[Callable[["Feature"], bool]] = None): |
| 85 | + """Declare that the decorated step target serves this feature, where ``when`` holds if given.""" |
| 86 | + |
| 87 | + def declare(target: type) -> type: |
| 88 | + cls._supported_by[target] = when |
| 89 | + return target |
| 90 | + |
| 91 | + return declare |
| 92 | + |
| 93 | + @classmethod |
| 94 | + def refusal( |
| 95 | + cls, deployment: type, model_config: "ModelConfig", llm_args: "TorchLlmArgs" |
| 96 | + ) -> Optional[str]: |
| 97 | + """Why ``deployment`` cannot serve this feature as the deployment sets it, or None.""" |
| 98 | + feature = cls.from_args(model_config, llm_args) |
| 99 | + if feature is None: |
| 100 | + return None |
| 101 | + targets = step_targets(deployment) |
| 102 | + for target in dict.fromkeys(targets[step] for step in Step if step in feature.steps): |
| 103 | + if target in cls._supported_by: |
| 104 | + when = cls._supported_by[target] |
| 105 | + if when is None or when(feature): |
| 106 | + continue |
| 107 | + name = deployment.__name__ |
| 108 | + if target is not deployment: |
| 109 | + name = f"{name}'s {target.__name__}" |
| 110 | + return f"{name} does not support {feature}" |
| 111 | + return None |
| 112 | + |
| 113 | + |
| 114 | +def feature_refusal( |
| 115 | + deployment: type, model_config: "ModelConfig", llm_args: "TorchLlmArgs" |
| 116 | +) -> Optional[str]: |
| 117 | + """Why ``deployment`` cannot serve the features this deployment turns on, or None.""" |
| 118 | + refusals = [ |
| 119 | + why for feature in _FEATURES if (why := feature.refusal(deployment, model_config, llm_args)) |
| 120 | + ] |
| 121 | + return "; ".join(refusals) or None |
| 122 | + |
| 123 | + |
| 124 | +@dataclass(frozen=True) |
| 125 | +class PrefillCudaGraph(Feature): |
| 126 | + """A prefill CUDA graph (``prefill_cuda_graph_backend`` other than ``disabled``). |
| 127 | +
|
| 128 | + The engine captures and replays it for steps with context rows only, but ``piecewise`` |
| 129 | + builds it from a torch.compile of the model, which also runs the steps without context |
| 130 | + rows unless ``torch_compile_config.compile_only_piecewise_graphs`` limits it to the |
| 131 | + graphed ones. |
| 132 | + """ |
| 133 | + |
| 134 | + backend: "PrefillCudaGraphBackend" |
| 135 | + attention_dp: bool |
| 136 | + #: Whether the torch.compile that ``piecewise`` needs also runs the decode steps. |
| 137 | + compiles_decode: bool |
| 138 | + |
| 139 | + @classmethod |
| 140 | + def from_args(cls, model_config, llm_args) -> Optional["PrefillCudaGraph"]: |
| 141 | + backend = llm_args.prefill_cuda_graph_backend |
| 142 | + if backend == "disabled": |
| 143 | + return None |
| 144 | + compile_config = llm_args.torch_compile_config |
| 145 | + compiles_decode = backend == "piecewise" and not ( |
| 146 | + compile_config is not None and compile_config.compile_only_piecewise_graphs |
| 147 | + ) |
| 148 | + return cls(backend, model_config.mapping.enable_attention_dp, compiles_decode) |
| 149 | + |
| 150 | + @property |
| 151 | + def steps(self) -> FrozenSet[Step]: |
| 152 | + return frozenset(Step) if self.compiles_decode else frozenset({Step.CONTEXT}) |
| 153 | + |
| 154 | + def __str__(self) -> str: |
| 155 | + words = f"prefill_cuda_graph_backend='{self.backend.value}'" |
| 156 | + return f"{words} with attention DP" if self.attention_dp else words |
0 commit comments