Skip to content

Commit a7b7b2a

Browse files
committed
[None][feat] Refuse modeling_v2 step targets for engine features they do not declare
A modeling_v2 core hands each step to one of its step targets: steps with context rows to PrefillTarget, steps without to DecodeTarget. A deployment class whose step targets declare features names them in step_targets (a class without it is its own step target), and step targets declare the engine features they serve with the feature's class decorator. modeling_v2_resolve refuses a deployment when a feature it turns on changes steps that one of its step targets runs without declaring the feature, or whose condition fails: auto falls back to the built-in implementation, require raises naming the step target and feature. A feature is a class in _features.py whose from_args reads the facts that decide support from the engine arguments (None while the feature is off) and whose steps say which kinds of step it changes. The first feature is PrefillCudaGraph: breakable changes the context steps only, so a DecodeTarget never has to declare it; piecewise also runs the decode steps through torch.compile unless compile_only_piecewise_graphs is set. Declared support: - qwen4_exp default PrefillTarget: breakable under attention TP (the two refusals check_deployment made move here) - minimax_m3 sm107 tp2 PrefillTarget, kimi_k3_vl tp16 (both, no step targets): breakable - glm_moe_dsa sm103 tp8 and sm107 low_latency PrefillTarget and DecodeTarget: breakable and piecewise The other targets declare nothing and are refused when a prefill CUDA graph is on. Signed-off-by: Fred Wei <20514172+WeiHaocheng@users.noreply.github.com>
1 parent 8abe3d8 commit a7b7b2a

11 files changed

Lines changed: 276 additions & 18 deletions

File tree

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
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

‎tensorrt_llm/_torch/_experimental/modeling_v2/_router_index.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@
4646

4747
from tensorrt_llm.logger import logger
4848

49+
from ._features import feature_refusal
50+
4951
if TYPE_CHECKING:
5052
from tensorrt_llm._torch.model_config import ModelConfig
5153
from tensorrt_llm.llmapi.llm_args import TorchLlmArgs
@@ -220,7 +222,9 @@ def modeling_v2_resolve(config: "ModelConfig", llm_args: "TorchLlmArgs") -> Opti
220222
221223
Returns the target class, or None for the built-in implementation:
222224
when ``llm_args.modeling_v2`` is ``off``, when no ``route`` is registered
223-
for the architecture, or when that ``route`` raises ``NoTarget``.
225+
for the architecture, when that ``route`` raises ``NoTarget``, or when the
226+
deployment turns on a feature that a step target of the returned class does
227+
not declare for the steps it runs (``_features``).
224228
In ``require`` every one of those but ``off`` raises ``ValueError`` instead.
225229
It also returns None for a ``@disable_v2_by_default`` target when
226230
``modeling_v2`` was left at its default.
@@ -241,6 +245,9 @@ def modeling_v2_resolve(config: "ModelConfig", llm_args: "TorchLlmArgs") -> Opti
241245
known = ", ".join(sorted(registered_routes())) or "(none)"
242246
raise NoTarget(f"no route for this architecture; routed architectures: {known}")
243247
target = route(config, llm_args, _device_compute_capability())
248+
refusal = feature_refusal(target, config, llm_args)
249+
if refusal is not None:
250+
raise NoTarget(refusal)
244251
except NoTarget as why:
245252
if mode is ModelingV2Mode.REQUIRE:
246253
raise ValueError(f"modeling_v2='require', but no target fits {arch!r}: {why}") from None

‎tensorrt_llm/_torch/_experimental/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tp8/modeling.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252

5353
import torch
5454

55+
from tensorrt_llm._torch._experimental.modeling_v2._features import PrefillCudaGraph, Step
5556
from tensorrt_llm._torch._experimental.modeling_v2._router_index import resolved_mode
5657
from tensorrt_llm._torch.attention.attention import maybe_allgather_for_helix_cp
5758
from tensorrt_llm._torch.attention.backends import AttentionMetadata
@@ -151,6 +152,7 @@ def forward(
151152
)
152153

153154

155+
@PrefillCudaGraph.supported()
154156
class PrefillTarget:
155157
"""The general case: context rows, and possibly generation rows beside them.
156158
@@ -182,6 +184,7 @@ def forward(
182184
)
183185

184186

187+
@PrefillCudaGraph.supported()
185188
class DecodeTarget:
186189
"""The specialization: routed to only when there are no context rows.
187190
@@ -248,6 +251,9 @@ def forward(
248251
class ModelingV2Glm52Nvfp4Sm103Tp8(GlmMoeDsaForCausalLM):
249252
"""GLM-5.2-NVFP4 on sm_103: the built-in causal LM with this target's core and dispatch."""
250253

254+
#: The step target ``_select_target`` hands each kind of step to.
255+
step_targets = {Step.CONTEXT: PrefillTarget, Step.DECODE: DecodeTarget}
256+
251257
def __init__(self, model_config: ModelConfig):
252258
world_size = model_config.mapping.world_size
253259
mode = resolved_mode(type(self))

‎tensorrt_llm/_torch/_experimental/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_107__low_latency/modeling.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import torch
2323
from transformers import PretrainedConfig
2424

25+
from tensorrt_llm._torch._experimental.modeling_v2._features import PrefillCudaGraph, Step
2526
from tensorrt_llm._torch.attention.backends.interface import (
2627
AttentionForwardArgs,
2728
AttentionInputType,
@@ -130,6 +131,7 @@
130131
_LOGITS_EXCHANGE_BYTES = 16 << 20
131132

132133

134+
@PrefillCudaGraph.supported()
133135
class PrefillTarget:
134136
"""Forwards that carry context rows: the decoder stack the context server runs."""
135137

@@ -202,6 +204,7 @@ class _DraftState:
202204
half_done: torch.cuda.Event
203205

204206

207+
@PrefillCudaGraph.supported()
205208
class DecodeTarget:
206209
"""Generation kernels selected from the actual row count and TP mapping.
207210
@@ -1749,6 +1752,9 @@ class ModelingV2Glm52Nvfp4Sm107LowLatency(
17491752
):
17501753
"""GLM-5.2-NVFP4 on Rubin, with tensor-parallel attention and experts."""
17511754

1755+
#: The step target ``_select_target`` hands each kind of step to.
1756+
step_targets = {Step.CONTEXT: PrefillTarget, Step.DECODE: DecodeTarget}
1757+
17521758
@classmethod
17531759
def get_preferred_kv_cache_manager_version(cls, pretrained_config: Any = None) -> Literal["V2"]:
17541760
"""The KV cache manager the context server's built-in implementation prefers."""

‎tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp16ep1/modeling.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
import torch
9191
from torch import nn
9292

93+
from tensorrt_llm._torch._experimental.modeling_v2._features import PrefillCudaGraph
9394
from tensorrt_llm._torch._experimental.modeling_v2._native import load_family_ops
9495
from tensorrt_llm._torch._experimental.modeling_v2.models.kimi_k3_vl.kernels.k3_mla.decode_view import (
9596
k3_mla_decode_view,
@@ -143,6 +144,7 @@
143144
from tensorrt_llm._torch.pyexecutor.config_utils import is_mla
144145
from tensorrt_llm._torch.utils import AuxStreamType
145146
from tensorrt_llm.functional import AllReduceStrategy
147+
from tensorrt_llm.llmapi.llm_args import PrefillCudaGraphBackend
146148
from tensorrt_llm.logger import logger
147149
from tensorrt_llm.mapping import Mapping
148150
from tensorrt_llm.models.modeling_utils import QuantAlgo, QuantConfig
@@ -3199,6 +3201,15 @@ def _check_construction(model_config: ModelConfig) -> None:
31993201
)
32003202

32013203

3204+
def _breakable_prefill_cuda_graph(feature: PrefillCudaGraph) -> bool:
3205+
"""The breakable prefill graph, whose segments the KDA core runs eagerly between.
3206+
3207+
Nothing in the target is written for torch.compile, which the piecewise graph needs.
3208+
"""
3209+
return feature.backend == PrefillCudaGraphBackend.BREAKABLE
3210+
3211+
3212+
@PrefillCudaGraph.supported(when=_breakable_prefill_cuda_graph)
32023213
class ModelingV2KimiK3Mxfp4Sm100Tp16Moetp16ep1(KimiLinearForCausalLM):
32033214
"""The class ``route`` returns: this target's text model (`KimiLinearModel` above) behind its checks.
32043215

‎tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp4ep4/modeling.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
import torch
9494
from torch import nn
9595

96+
from tensorrt_llm._torch._experimental.modeling_v2._features import PrefillCudaGraph
9697
from tensorrt_llm._torch._experimental.modeling_v2._native import load_family_ops
9798
from tensorrt_llm._torch._experimental.modeling_v2.models.kimi_k3_vl.kernels.k3_mla.decode_view import (
9899
k3_mla_decode_view,
@@ -146,6 +147,7 @@
146147
from tensorrt_llm._torch.pyexecutor.config_utils import is_mla
147148
from tensorrt_llm._torch.utils import AuxStreamType
148149
from tensorrt_llm.functional import AllReduceStrategy
150+
from tensorrt_llm.llmapi.llm_args import PrefillCudaGraphBackend
149151
from tensorrt_llm.logger import logger
150152
from tensorrt_llm.mapping import Mapping
151153
from tensorrt_llm.models.modeling_utils import QuantAlgo, QuantConfig
@@ -3308,6 +3310,15 @@ def _check_construction(model_config: ModelConfig) -> None:
33083310
)
33093311

33103312

3313+
def _breakable_prefill_cuda_graph(feature: PrefillCudaGraph) -> bool:
3314+
"""The breakable prefill graph, whose segments the KDA core runs eagerly between.
3315+
3316+
Nothing in the target is written for torch.compile, which the piecewise graph needs.
3317+
"""
3318+
return feature.backend == PrefillCudaGraphBackend.BREAKABLE
3319+
3320+
3321+
@PrefillCudaGraph.supported(when=_breakable_prefill_cuda_graph)
33113322
class ModelingV2KimiK3Mxfp4Sm100Tp16Moetp4ep4(KimiLinearForCausalLM):
33123323
"""The class ``route`` returns: this target's text model (`KimiLinearModel` above) behind its checks.
33133324

‎tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
from torch import nn
8989
from transformers import PretrainedConfig
9090

91+
from tensorrt_llm._torch._experimental.modeling_v2._features import PrefillCudaGraph, Step
9192
from tensorrt_llm._torch._experimental.modeling_v2._router_index import (
9293
ModelingV2Mode,
9394
resolved_mode,
@@ -262,6 +263,7 @@
262263
from tensorrt_llm._torch.utils import ActType_TrtllmGen, get_model_extra_attrs
263264
from tensorrt_llm._utils import mpi_rank, prefer_pinned
264265
from tensorrt_llm.functional import PositionEmbeddingType
266+
from tensorrt_llm.llmapi.llm_args import PrefillCudaGraphBackend
265267
from tensorrt_llm.logger import logger
266268
from tensorrt_llm.quantization.mode import QuantAlgo
267269

@@ -2935,6 +2937,12 @@ def _draft_attention_boundary(qkv, output, draft_key: str) -> None:
29352937
_draft_attention_eager = eager_on_graph(_draft_attention_boundary)
29362938

29372939

2940+
def _breakable_prefill_cuda_graph(feature: PrefillCudaGraph) -> bool:
2941+
"""The breakable prefill graph (`PrefillTarget`); the target does not run under torch.compile."""
2942+
return feature.backend == PrefillCudaGraphBackend.BREAKABLE
2943+
2944+
2945+
@PrefillCudaGraph.supported(when=_breakable_prefill_cuda_graph)
29382946
class PrefillTarget:
29392947
"""A step with context rows: prefill chunks, and the mixed steps that carry generation rows beside them. Every
29402948
layer runs in its generic form; the attention core is the MSA backend's for every row.
@@ -6100,6 +6108,9 @@ class ModelingV2MiniMaxM3Nvfp4Sm107Tp2(
61006108
``load_draft_weights``) and the worker (``M3Eagle3Worker``) that verifies and drafts each step.
61016109
"""
61026110

6111+
#: The step target ``_select_target`` hands each kind of step to.
6112+
step_targets = {Step.CONTEXT: PrefillTarget, Step.DECODE: DecodeTarget}
6113+
61036114
def __init__(self, model_config: ModelConfig[PretrainedConfig]) -> None:
61046115
assert torch.cuda.get_device_capability() == _SM, (
61056116
f"this target is built for sm_{_SM[0]}{_SM[1]}, the device is sm_"

0 commit comments

Comments
 (0)