Skip to content

Commit e045dcc

Browse files
[None][fix] Address encoder backend review comments
Problem: trtllm-bench sets disable_mm_encoder for text-only runs, so a serving config with encoder_attention_backend failed at startup. Under modeling_v2 auto or require, the Qwen4-Exp target built its own vision tower and ignored the selection. The Nemotron-H RADIO vision default was FLASHINFER, whose plan build for a new image shape can stall during CUDA graph replay. Backend names were repeated outside the config Literal, and this PR also carried a MiniCPM-V 4.6 fix owned by another change. Solution: Skip the encoder-presence check with one info log when the encoder is disabled; model support checks still run. Decline the Qwen4-Exp target when an encoder backend is selected, so auto uses the built-in model and require names the setting. Default RADIO vision to TRTLLM; VANILLA and FLASHINFER stay selectable. Read backend names from a named Literal and document the ModelConfig helpers. Drop the MiniCPM-V 4.6 max_seq_len change and a test that restated model declarations. Validation: CPU suites of the PR and touched files match the previous head apart from the changed tests, which pass; applicable pre-commit hooks pass and the serve schemas are unchanged. Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>
1 parent 501d70e commit e045dcc

8 files changed

Lines changed: 140 additions & 73 deletions

File tree

‎docs/source/features/multi-modality.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,9 @@ The table covers every registered multimodal model implementation; model aliases
9191
| `WhisperForConditionalGeneration` | `audio` | Not supported |
9292
<!-- encoder-attention-backends:end -->
9393

94-
For MiniCPM-V 4.6, the selection applies to its TensorRT-LLM attention layers; its fixed window-merger attention is unchanged.
94+
For MiniCPM-V 4.6, the selection applies to its TensorRT-LLM attention layers; its fixed window-merger attention is unchanged. The Nemotron-H RADIO vision encoder defaults to `TRTLLM`, and `VANILLA` and `FLASHINFER` remain selectable.
9595

96-
Supported entries use TensorRT-LLM's `Attention` and apply encoder overrides explicitly. Other encoders keep their fixed implementation, including Hugging Face attention, direct SDPA, and custom attention paths. Overrides for entries marked "Not supported" fail during initialization, even if the requested value is `VANILLA`. Unknown encoder names and unsupported backends also fail during initialization; Hugging Face `attn_implementation` names are not accepted.
96+
Supported entries use TensorRT-LLM's `Attention` and apply encoder overrides explicitly. Other encoders keep their fixed implementation, including Hugging Face attention, direct SDPA, and custom attention paths. Overrides for entries marked "Not supported" fail during initialization, even if the requested value is `VANILLA`. Unknown encoder names and unsupported backends also fail during initialization; Hugging Face `attn_implementation` names are not accepted. With `disable_mm_encoder=True`, encoders that the model skips do not use the setting, so text-only runs can reuse a serving configuration.
9797

9898
## Model Support Matrix
9999

‎tensorrt_llm/_torch/_experimental/modeling_v2/models/qwen4_exp/routing.py‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
from __future__ import annotations
1414

15-
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Tuple
15+
from typing import TYPE_CHECKING, Any, Dict, NamedTuple, Optional, Tuple
1616

1717
import torch
1818

@@ -57,6 +57,7 @@ class EngineChoices(NamedTuple):
5757
mamba_ssm_cache_dtype: torch.dtype # the recurrent-state cache's dtype
5858
gdn_replay: bool # TRTLLM_USE_GDN_REPLAY, which the engine reads for eligible MTP workloads
5959
prefill_cuda_graph_backend: str # `prefill_cuda_graph_backend`: disabled, piecewise, breakable
60+
encoder_attention_backend: Optional[Dict[str, str]] # `multimodal_config` encoder backends
6061

6162

6263
def engine_choices(model_config: ModelConfig, llm_args: TorchLlmArgs) -> EngineChoices:
@@ -65,6 +66,7 @@ def engine_choices(model_config: ModelConfig, llm_args: TorchLlmArgs) -> EngineC
6566
from tensorrt_llm._torch.utils import is_gdn_replay_enabled
6667

6768
kv_cache_config = llm_args.kv_cache_config
69+
mm_config = llm_args.multimodal_config
6870
return EngineChoices(
6971
torch_dtype=model_config.torch_dtype,
7072
moe_backend=model_config.moe_backend_requested,
@@ -73,16 +75,20 @@ def engine_choices(model_config: ModelConfig, llm_args: TorchLlmArgs) -> EngineC
7375
),
7476
gdn_replay=is_gdn_replay_enabled(),
7577
prefill_cuda_graph_backend=str(llm_args.prefill_cuda_graph_backend.value),
78+
encoder_attention_backend=(
79+
mm_config.encoder_attention_backend if mm_config is not None else None
80+
),
7681
)
7782

7883

7984
def _check_engine(
8085
spec_config: Optional[Any], kv_cache_quant_algo: Optional[Any], engine: EngineChoices
8186
) -> None:
82-
"""Decline what the target's constructor or first forward would refuse.
87+
"""Decline what the target's constructor or first forward would refuse or ignore.
8388
84-
Without this ``auto`` claims the deployment and then fails mid-build instead of
85-
falling back to the built-in implementation.
89+
Without this ``auto`` claims the deployment and then fails mid-build, or runs
90+
without a requested setting, instead of falling back to the built-in
91+
implementation.
8692
"""
8793
if spec_config is not None and (
8894
getattr(spec_config, "draft_len_schedule", None) is not None
@@ -116,6 +122,11 @@ def _check_engine(
116122
"which the target does not implement; 'breakable' runs the prefill step as a "
117123
"breakable CUDA graph"
118124
)
125+
if engine.encoder_attention_backend:
126+
raise NoTarget(
127+
f"multimodal_config.encoder_attention_backend={engine.encoder_attention_backend}; "
128+
"the target's vision tower runs its own attention and does not apply it"
129+
)
119130
if spec_config is None:
120131
return
121132
draft = spec_config.max_draft_len

‎tensorrt_llm/_torch/model_config.py‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from dataclasses import dataclass, field
2424
from pathlib import Path
2525
from typing import (TYPE_CHECKING, Any, Dict, Generic, Iterator, List, Optional,
26-
Sequence, Tuple, TypeVar)
26+
Sequence, Tuple, TypeVar, get_args)
2727

2828
import filelock
2929
import torch
@@ -40,14 +40,17 @@
4040
torch_dtype_to_binding)
4141
from tensorrt_llm.bindings import LayerType as LayerTypeCpp
4242
from tensorrt_llm.functional import AllReduceStrategy
43+
# yapf: disable
4344
# Callers import MoeLoadBalancerConfig from this module.
4445
from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig # noqa: F401
4546
from tensorrt_llm.llmapi.llm_args import (CSA2SparseAttentionConfig,
4647
DeepSeekSparseAttentionConfig,
4748
DeepSeekV4SparseAttentionConfig,
49+
EncoderAttentionBackend,
4850
KvCacheConfig,
4951
MoeLoadBalancerConfigType,
5052
MultimodalConfig)
53+
# yapf: enable
5154
from tensorrt_llm.logger import logger
5255
from tensorrt_llm.mapping import Mapping
5356
from tensorrt_llm.models.modeling_utils import QuantConfig
@@ -371,23 +374,48 @@ class ModelConfig(Generic[TConfig]):
371374
modeling_v2_target: Optional[type] = None
372375

373376
def get_encoder_attention_backend(self, encoder: str, default: str) -> str:
374-
"""Select a logical encoder's backend, preserving its existing default."""
377+
"""Return the attention backend selected for a logical encoder.
378+
379+
Args:
380+
encoder: Logical encoder name, such as ``"vision"`` or ``"audio"``.
381+
default: Backend the model uses for this encoder when
382+
``multimodal_config.encoder_attention_backend`` omits it.
383+
384+
Returns:
385+
The backend from ``multimodal_config.encoder_attention_backend``,
386+
or ``default`` when the encoder has no entry.
387+
388+
Raises:
389+
ValueError: If the selected backend is not a public encoder backend.
390+
"""
375391
overrides = (self.multimodal_config.encoder_attention_backend
376392
if self.multimodal_config is not None else None)
377393
if not overrides or encoder not in overrides:
378394
return default
379395
backend = overrides[encoder]
380-
if backend not in ("VANILLA", "TRTLLM", "FLASHINFER"):
396+
backends = get_args(EncoderAttentionBackend)
397+
if backend not in backends:
381398
raise ValueError(
382399
f"Invalid attention backend {backend!r} for the {encoder} encoder; "
383-
"expected VANILLA, TRTLLM, or FLASHINFER")
400+
f"expected one of {', '.join(backends)}")
384401
return backend
385402

386403
def with_encoder_attention_backend(self,
387404
encoder: str,
388405
default: str | None = None
389406
) -> "ModelConfig":
390-
"""Apply an encoder selection to a shallow copy without changing the decoder."""
407+
"""Return a config whose ``attn_backend`` is the encoder's backend.
408+
409+
Args:
410+
encoder: Logical encoder name, such as ``"vision"`` or ``"audio"``.
411+
default: Backend the model uses for this encoder when no override
412+
is set. ``None`` means the decoder's ``attn_backend``.
413+
414+
Returns:
415+
``self`` when the selected backend equals ``attn_backend``;
416+
otherwise a shallow copy with only ``attn_backend`` changed, so the
417+
decoder config is never modified.
418+
"""
391419
backend = self.get_encoder_attention_backend(
392420
encoder, self.attn_backend if default is None else default)
393421
if backend == self.attn_backend:

‎tensorrt_llm/_torch/models/modeling_nemotron_h_multimodal.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -667,7 +667,9 @@ def __init__(self, model_config: ModelConfig[transformers.PretrainedConfig]):
667667
self.vision_model = RADIOVisionModel(
668668
vision_model_config,
669669
disable_quantization=True,
670-
vision_attn_backend=model_config.get_encoder_attention_backend("vision", "FLASHINFER"),
670+
# FlashInfer's cuDNN ragged-prefill plan build for a new image shape can stall
671+
# indefinitely while the language model replays CUDA graphs, freezing the server.
672+
vision_attn_backend=model_config.get_encoder_attention_backend("vision", "TRTLLM"),
671673
encoder_cuda_graph_config=encoder_cuda_graph_config,
672674
)
673675

‎tensorrt_llm/_torch/pyexecutor/model_loader.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,16 @@ def _validate_encoder_attention_backend_enabled(
172172
"""Reject selections for encoders that the effective model config omits."""
173173
if mm_config is None or not mm_config.encoder_attention_backend:
174174
return
175+
if disable_mm_encoder:
176+
# Text-only runs, such as trtllm-bench without --modality, reuse
177+
# serving configs. A skipped encoder never applies the selection, and
178+
# models that ignore disable_mm_encoder still build it with the setting.
179+
logger.info(
180+
"multimodal_config.encoder_attention_backend is not applied "
181+
"to encoders skipped by disable_mm_encoder=True")
182+
return
175183
for encoder in mm_config.encoder_attention_backend:
176-
if disable_mm_encoder or getattr(pretrained_config, f"{encoder}_config",
177-
None) is None:
184+
if getattr(pretrained_config, f"{encoder}_config", None) is None:
178185
raise ValueError(
179186
f"The {encoder} encoder is not enabled in the model config")
180187

‎tensorrt_llm/llmapi/llm_args.py‎

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -811,23 +811,26 @@ class MultimodalEncoderSchedulingPolicy(StrEnum):
811811
LLM capacity filtering (``MultimodalEagerEncoderScheduler``)."""
812812

813813

814+
# Public attention backends a multimodal encoder can select.
815+
EncoderAttentionBackend = Literal["VANILLA", "TRTLLM", "FLASHINFER"]
816+
817+
814818
class MultimodalConfig(StrictBaseModel):
815819
"""Multimodal model configuration."""
816820

817-
encoder_attention_backend: dict[str, Literal[
818-
"VANILLA", "TRTLLM", "FLASHINFER"]] | None = Field(
819-
default=None,
820-
description=
821-
("TensorRT-LLM attention backend for each logical multimodal encoder, "
822-
"for example {'vision': 'FLASHINFER'}. Public values are VANILLA, TRTLLM, "
823-
"and FLASHINFER. Image and video share the vision encoder. Only encoders "
824-
"using TensorRT-LLM Attention support this option; encoders using fixed "
825-
"attention reject overrides at initialization. Omitted entries retain "
826-
"their model-specific defaults and the language model's attn_backend "
827-
"is unchanged. Unsupported encoders or backends raise an error."),
828-
status="prototype",
829-
telemetry=False,
830-
)
821+
encoder_attention_backend: dict[str, EncoderAttentionBackend] | None = Field(
822+
default=None,
823+
description=
824+
("TensorRT-LLM attention backend for each logical multimodal encoder, "
825+
"for example {'vision': 'FLASHINFER'}. Public values are VANILLA, TRTLLM, "
826+
"and FLASHINFER. Image and video share the vision encoder. Only encoders "
827+
"using TensorRT-LLM Attention support this option; encoders using fixed "
828+
"attention reject overrides at initialization. Omitted entries retain "
829+
"their model-specific defaults and the language model's attn_backend "
830+
"is unchanged. Unsupported encoders or backends raise an error."),
831+
status="prototype",
832+
telemetry=False,
833+
)
831834

832835
encoder_cuda_graph: dict[str, MultimodalEncoderCudaGraphConfig] | None = Field(
833836
default=None,

‎tests/unittest/_torch/modeling_v2/test_modeling_v2_routing.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
CacheTransceiverConfig,
5050
KvCacheConfig,
5151
MTPDecodingConfig,
52+
MultimodalConfig,
5253
NGramDecodingConfig,
5354
TorchLlmArgs,
5455
)
@@ -1185,6 +1186,15 @@ def test_qwen4_exp_piecewise_prefill_cuda_graph_falls_back():
11851186
_declined(config, dict(prefill_cuda_graph_backend="piecewise"), match="piecewise")
11861187

11871188

1189+
@pytest.mark.usefixtures("_qwen4_exp_sm")
1190+
def test_qwen4_exp_encoder_attention_backend_falls_back():
1191+
"""The target's own vision tower would ignore it; the built-in model applies it."""
1192+
config = _model_config(_qwen4_exp_config())
1193+
selected = MultimodalConfig(encoder_attention_backend={"vision": "TRTLLM"})
1194+
_declined(config, dict(multimodal_config=selected), match="encoder_attention_backend")
1195+
_claimed(config, dict(multimodal_config=MultimodalConfig(encoder_attention_backend={})))
1196+
1197+
11881198
@pytest.mark.usefixtures("_qwen4_exp_sm")
11891199
@pytest.mark.parametrize("backend", ["disabled", "breakable"])
11901200
def test_qwen4_exp_matches_without_or_with_the_breakable_prefill_cuda_graph(backend):

‎tests/unittest/_torch/multimodal/test_encoder_attention_backend.py‎

Lines changed: 51 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -216,42 +216,6 @@ def test_loader_keeps_omitted_settings_unchanged(
216216
)
217217

218218

219-
@pytest.mark.parametrize(
220-
("module", "model", "expected"),
221-
[
222-
(
223-
"gemma4mm",
224-
"Gemma4ForConditionalGeneration",
225-
{"vision": _PUBLIC_BACKENDS, "audio": frozenset()},
226-
),
227-
("gemma4_unified", "Gemma4UnifiedForConditionalGeneration", {}),
228-
(
229-
"nemotron_h_multimodal",
230-
"NemotronHMultimodalModel",
231-
{"vision": _PUBLIC_BACKENDS, "audio": frozenset()},
232-
),
233-
("glm5_next_vision", "Glm5NextVLM", {"vision": frozenset({"TRTLLM"})}),
234-
("kimi_k25", "KimiK25ForConditionalGeneration", {"vision": _PUBLIC_BACKENDS}),
235-
("kimi_k3_vl", "KimiK3ForConditionalGeneration", {"vision": _PUBLIC_BACKENDS}),
236-
("step3p7vl", "Step3p7VLForConditionalGeneration", {"vision": _PUBLIC_BACKENDS}),
237-
("minicpmv4_6", "MiniCPMV4_6Model", {"vision": _PUBLIC_BACKENDS}),
238-
("mistral", "Mistral3VLM", {"vision": _PUBLIC_BACKENDS}),
239-
("deepseekv41_multimodal", "DeepseekV41ForConditionalGeneration", {"vision": frozenset()}),
240-
("minimaxm3", "MiniMaxM3VLForConditionalGeneration", {"vision": frozenset()}),
241-
],
242-
)
243-
def test_model_encoder_backend_declarations(module: str, model: str, expected: dict) -> None:
244-
model_cls = getattr(import_module(f"tensorrt_llm._torch.models.modeling_{module}"), model)
245-
assert model_cls.supported_encoder_attention_backends == expected
246-
for encoder, backends in expected.items():
247-
assert backends <= _PUBLIC_BACKENDS
248-
if not backends:
249-
with pytest.raises(ValueError, match=f"{encoder}.*cannot be changed"):
250-
_validate_encoder_attention_backend_support(
251-
model_cls, MultimodalConfig(encoder_attention_backend={encoder: "VANILLA"})
252-
)
253-
254-
255219
@pytest.mark.parametrize(
256220
("module", "model", "encoder"),
257221
[
@@ -268,14 +232,11 @@ def test_hf_encoders_reject_backend_overrides(module: str, model: str, encoder:
268232
)
269233

270234

271-
@pytest.mark.parametrize("disabled", [False, True])
272-
def test_loader_rejects_absent_or_disabled_encoder(disabled: bool) -> None:
273-
config = SimpleNamespace(vision_config=object() if disabled else None)
235+
def test_loader_rejects_absent_encoder() -> None:
274236
with pytest.raises(ValueError, match="vision.*not enabled"):
275237
_validate_encoder_attention_backend_enabled(
276238
MultimodalConfig(encoder_attention_backend={"vision": "VANILLA"}),
277-
config,
278-
disable_mm_encoder=disabled,
239+
SimpleNamespace(vision_config=None),
279240
)
280241

281242

@@ -318,6 +279,50 @@ def load_config(**kwargs):
318279
)
319280

320281

282+
def test_loader_skips_encoder_check_when_encoder_is_disabled(
283+
monkeypatch: pytest.MonkeyPatch,
284+
) -> None:
285+
"""A text-only run, such as trtllm-bench without --modality, reuses a serving config."""
286+
from unittest.mock import MagicMock
287+
288+
from tensorrt_llm._torch.pyexecutor import model_loader
289+
from tensorrt_llm.llmapi.llm_args import TorchLlmArgs
290+
291+
class ReachedTargetResolution(Exception):
292+
pass
293+
294+
def resolve_target(*args, **kwargs):
295+
raise ReachedTargetResolution
296+
297+
llm_args = TorchLlmArgs(
298+
model="/tmp/dummy_model",
299+
disable_mm_encoder=True,
300+
multimodal_config=MultimodalConfig(encoder_attention_backend={"vision": "VANILLA"}),
301+
)
302+
messages = []
303+
monkeypatch.setattr(model_loader.logger, "info", messages.append)
304+
monkeypatch.setattr(model_loader, "modeling_v2_resolve_on_all_ranks", resolve_target)
305+
loader = model_loader.ModelLoader(
306+
llm_args=llm_args,
307+
mapping=MagicMock(),
308+
spec_config=None,
309+
sparse_attention_config=None,
310+
max_num_tokens=128,
311+
max_seq_len=128,
312+
)
313+
checkpoint_loader = SimpleNamespace(
314+
load_config=lambda **kwargs: SimpleNamespace(pretrained_config=SimpleNamespace())
315+
)
316+
317+
# The check passes without an error and loading continues to target resolution.
318+
with pytest.raises(ReachedTargetResolution):
319+
loader._load_and_validate_config("/tmp/dummy_model", checkpoint_loader)
320+
assert [message for message in messages if "encoder_attention_backend" in message] == [
321+
"multimodal_config.encoder_attention_backend is not applied "
322+
"to encoders skipped by disable_mm_encoder=True"
323+
]
324+
325+
321326
def test_loader_validates_registered_model_class(monkeypatch: pytest.MonkeyPatch) -> None:
322327
from tensorrt_llm._torch.pyexecutor import model_loader
323328
from tensorrt_llm.llmapi.llm_args import TorchLlmArgs
@@ -407,7 +412,7 @@ def test_pixtral_encoder_backend_keeps_decoder(
407412
assert config.attn_backend == "FLASHINFER"
408413

409414

410-
@pytest.mark.parametrize("override", [None, "VANILLA"])
415+
@pytest.mark.parametrize("override", [None, "VANILLA", "FLASHINFER"])
411416
def test_radio_encoder_backend_keeps_decoder(
412417
override: str | None, monkeypatch: pytest.MonkeyPatch
413418
) -> None:
@@ -432,14 +437,15 @@ def test_radio_encoder_backend_keeps_decoder(
432437
pretrained_config.torch_dtype = torch.float32
433438
config = ModelConfig(
434439
pretrained_config=pretrained_config,
435-
attn_backend="TRTLLM",
440+
attn_backend="FLASHINFER",
436441
multimodal_config=_multimodal_config(override),
437442
)
438443

439444
modeling_nemotron_h_multimodal.NemotronHVisionEncoder(config)
440445

441-
assert built["vision"][1]["vision_attn_backend"] == (override or "FLASHINFER")
442-
assert config.attn_backend == "TRTLLM"
446+
# The RADIO default is TRTLLM regardless of the decoder backend.
447+
assert built["vision"][1]["vision_attn_backend"] == (override or "TRTLLM")
448+
assert config.attn_backend == "FLASHINFER"
443449

444450

445451
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)