Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions tests/models/transformers/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,3 +769,22 @@ class Attention(nn.Module):

with pytest.raises(ValueError, match="Cannot resolve attention scaling expression"):
fuser.scale(Attention())


class _ImageOnlyMRoPEModel:
"""`get_rope_index` without `video_grid_thw` or `**kwargs` (e.g. HunYuanVL)."""

def get_rope_index(self, input_ids, image_grid_thw):
seq_len = input_ids.shape[-1]
positions = torch.arange(seq_len).view(1, 1, -1).expand(4, 1, -1)
return positions, torch.tensor([0])


def test_get_mrope_input_positions_omits_unsupported_grid_kwargs():
"""Optional grids the model can't accept must not be passed when empty."""
mixin = SimpleNamespace(model=_ImageOnlyMRoPEModel())

positions, delta = MultiModalMixin.get_mrope_input_positions(mixin, [1, 2, 3], [])

assert positions.shape == (4, 3)
assert delta == 0
48 changes: 48 additions & 0 deletions tests/transformers_utils/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
from vllm.transformers_utils import config as config_module
from vllm.transformers_utils.config import (
get_safetensors_params_metadata,
mrope_num_dims,
patch_legacy_rope_type,
try_get_generation_config,
uses_mrope,
)
from vllm.transformers_utils.configs.glm5_next import (
Glm5NextConfig,
Expand Down Expand Up @@ -176,3 +178,49 @@ def test_safetensors_metadata_of_repo_without_safetensors():
assert get_safetensors_params_metadata("some/pytorch-only-model") == {}

get_safetensors_metadata.assert_called_once()


@pytest.mark.parametrize(
("section_key", "mrope_section", "expected_num_dims"),
[
("mrope_section", [16, 24, 24], 3),
("mrope_section", [16, 16, 16, 16], 4),
# Interleaved M-RoPE takes 2 sections but still consumes 3D positions
("mrope_section", [32, 32], 3),
# HunYuan-VL checkpoints ship the section under its legacy name
("xdrope_section", [16, 16, 16, 16], 4),
],
)
def test_mrope_num_dims(section_key, mrope_section, expected_num_dims):
config = PretrainedConfig()
config.rope_parameters = {"rope_type": "default", section_key: mrope_section}

assert uses_mrope(config)
assert mrope_num_dims(config) == expected_num_dims


@pytest.mark.parametrize("section_name", ["mrope_section", "xdrope_section"])
def test_mrope_num_dims_from_config_attribute(section_name):
"""Some configs expose the section as an attribute rather than under
`rope_parameters`."""
config = PretrainedConfig()
setattr(config, section_name, [16, 16, 16, 16])

assert uses_mrope(config)
assert mrope_num_dims(config) == 4


def test_mrope_num_dims_from_nested_rope_parameters():
"""Sections nested by layer type must be found, not silently defaulted."""
config = PretrainedConfig()
config.rope_parameters = {
"full_attention": {"mrope_section": [16, 16, 16, 16]},
"linear_attention": {"rope_type": "default"},
}

assert uses_mrope(config)
assert mrope_num_dims(config) == 4


def test_mrope_num_dims_without_mrope():
assert mrope_num_dims(PretrainedConfig()) == 0
18 changes: 0 additions & 18 deletions tests/v1/core/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,24 +105,6 @@ def _mm_feature_mixed(offset: int, length: int) -> MultiModalFeatureSpec:
)


def test_strip_covered_mm_data_xdrope() -> None:
"""XD-RoPE models (e.g. HunyuanOCR) compute positions the same way, so a
covered item must keep its grid dims: stripping them made the worker index
an empty ``image_grid_thw`` and crash the engine on the second request with
an identical prompt."""
covered = _mm_feature_mixed(offset=0, length=100)
uncovered = _mm_feature_mixed(offset=300, length=100)

stripped = strip_covered_mm_data(
[covered, uncovered], num_computed_tokens=250, uses_xdrope=True
)

assert stripped[0].data is not None
assert list(stripped[0].data.keys()) == ["image_grid_thw"]
assert stripped[1].data is not None
assert set(stripped[1].data.keys()) == {"pixel_values", "image_grid_thw"}


def test_strip_covered_mm_data_mrope() -> None:
"""For M-RoPE models, covered items keep their keep_on_cpu metadata fields
(the worker needs them to compute positions); payload fields are dropped."""
Expand Down
10 changes: 3 additions & 7 deletions vllm/config/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@
get_sentence_transformer_tokenizer_config,
is_encoder_decoder,
is_rope_parameters_nested,
mrope_num_dims,
try_get_dense_modules,
try_get_generation_config,
try_get_tokenizer_config,
uses_mrope,
uses_xdrope_dim,
)
from vllm.transformers_utils.model_arch_config_convertor import (
MODEL_ARCH_CONFIG_CONVERTORS,
Expand Down Expand Up @@ -1850,12 +1850,8 @@ def uses_mrope(self) -> bool:
return uses_mrope(self.hf_config)

@property
def uses_xdrope_dim(self) -> int:
return uses_xdrope_dim(self.hf_config)

@property
def uses_xdrope(self) -> bool:
return self.uses_xdrope_dim > 0
def mrope_num_dims(self) -> int:
return mrope_num_dims(self.hf_config)

@property
def is_multimodal_model(self) -> bool:
Expand Down
52 changes: 2 additions & 50 deletions vllm/model_executor/models/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -1783,7 +1783,8 @@ def get_mrope_input_positions(

Returns:
Tuple of `(llm_positions, mrope_position_delta)`
- llm_positions: Tensor of shape `[3, num_tokens]` with T/H/W positions
- llm_positions: Tensor of shape `[num_dims, num_tokens]`, one row
per M-RoPE position channel (e.g. T/H/W)
- mrope_position_delta: Delta for position calculations
"""
...
Expand All @@ -1803,55 +1804,6 @@ def supports_mrope(
return isinstance(model, SupportsMRoPE)


@runtime_checkable
class SupportsXDRoPE(Protocol):
"""The interface required for all models that support XD-RoPE."""

supports_xdrope: ClassVar[Literal[True]] = True
"""
A flag that indicates this model supports XD-RoPE.

Note:
There is no need to redefine this flag if this class is in the
XDRope of your model class.
"""

def get_xdrope_input_positions(
self,
input_tokens: list[int],
mm_features: list["MultiModalFeatureSpec"],
) -> torch.Tensor:
"""
Get XD-RoPE input positions and delta value for this specific model.

This method should be implemented by each model that supports XD-RoPE
to provide model-specific logic for computing input positions.

Args:
input_tokens: List of input token IDs
mm_features: Information about each multi-modal data item

Returns:
llm_positions: Tensor of shape `[xdrope_dim, num_tokens]` with
4D(P/W/H/T) or 3D(W/H/T) positions.
"""
...


@overload
def supports_xdrope(model: type[object]) -> TypeIs[type[SupportsXDRoPE]]: ...


@overload
def supports_xdrope(model: object) -> TypeIs[SupportsXDRoPE]: ...


def supports_xdrope(
model: type[object] | object,
) -> TypeIs[type[SupportsXDRoPE]] | TypeIs[SupportsXDRoPE]:
return isinstance(model, SupportsXDRoPE)


@runtime_checkable
class SupportsEncoderCudaGraph(Protocol):
"""Interface for models whose vision encoder supports CUDA graph
Expand Down
32 changes: 22 additions & 10 deletions vllm/model_executor/models/transformers/multimodal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1236,17 +1236,31 @@ def get_mrope_input_positions(
video_grid_thw = torch.stack(video_grid_thw) if video_grid_thw else None

# `get_rope_index` doesn't always accept arbitrary `kwargs`
kwargs = {}
if not hasattr(self, "_get_rope_index_accepts_mm_token_type_ids"):
if not hasattr(self, "_get_rope_index_kwarg_names"):
import inspect

sig = inspect.signature(self.model.get_rope_index)
params = sig.parameters
self._get_rope_index_accepts_mm_token_type_ids = (
"mm_token_type_ids" in params
or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
params = inspect.signature(self.model.get_rope_index).parameters
self._get_rope_index_kwarg_names = (
None
if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
else frozenset(params)
)
if self._get_rope_index_accepts_mm_token_type_ids:

kwarg_names = self._get_rope_index_kwarg_names

def accepts_kwarg(name: str) -> bool:
return kwarg_names is None or name in kwarg_names

# Drop a grid the model can't accept only when there is nothing to pass.
kwargs = {
name: value
for name, value in (
("image_grid_thw", image_grid_thw),
("video_grid_thw", video_grid_thw),
)
if value is not None or accepts_kwarg(name)
}
if accepts_kwarg("mm_token_type_ids"):
mm_token_type_ids = torch.zeros(len(input_tokens), dtype=torch.int)
for feature in mm_features:
position = feature.mm_position
Expand All @@ -1257,8 +1271,6 @@ def get_mrope_input_positions(

mrope_positions, mrope_position_delta = self.model.get_rope_index(
input_ids=torch.tensor(input_tokens).unsqueeze(0),
image_grid_thw=image_grid_thw,
video_grid_thw=video_grid_thw,
**kwargs,
)

Expand Down
7 changes: 3 additions & 4 deletions vllm/multimodal/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,11 @@ def strip_covered_mm_data(
mm_features: list[MultiModalFeatureSpec],
num_computed_tokens: int,
uses_mrope: bool = False,
uses_xdrope: bool = False,
) -> list[MultiModalFeatureSpec]:
"""Drop the tensor data of mm items whose placeholder span is fully inside
a prefix-cache-covered region: no encoder run can be scheduled for them,
so the workers never consume the payload fields. M-RoPE and XD-RoPE models
keep CPU-side metadata fields used to compute positions. SHM address items
so the workers never consume the payload fields. M-RoPE models keep
CPU-side metadata fields used to compute positions. SHM address items
are also kept so workers can balance the sender's reference count. The
scheduler-side ``Request`` keeps the full features."""
if not mm_features or num_computed_tokens == 0:
Expand All @@ -239,7 +238,7 @@ def maybe_strip(f: MultiModalFeatureSpec) -> MultiModalFeatureSpec:
return f

data = None
if uses_mrope or uses_xdrope:
if uses_mrope:
data = MultiModalKwargsItem(
{k: elem for k, elem in f.data.items() if elem.field.keep_on_cpu}
)
Expand Down
74 changes: 54 additions & 20 deletions vllm/transformers_utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import os
from collections.abc import Callable, Iterator
from collections.abc import Callable, Iterator, Sequence
from contextlib import contextmanager
from dataclasses import asdict
from functools import cache, partial, wraps
Expand Down Expand Up @@ -569,15 +569,47 @@ def patch_rope_parameters(config: PretrainedConfig) -> None:
config.validate_rope()


def _uses_mrope(config: PretrainedConfig) -> bool:
def _iter_rope_parameters(config: PretrainedConfig) -> Iterator[dict[str, Any]]:
"""Yield a config's rope parameters, one dict per layer type if nested."""
rope_parameters = getattr(config, "rope_parameters", None)
if rope_parameters is None:
return False
if not isinstance(rope_parameters, dict):
return

return "mrope_section" in rope_parameters or any(
isinstance(params, dict) and "mrope_section" in params
for params in rope_parameters.values()
)
if is_rope_parameters_nested(rope_parameters):
yield from (p for p in rope_parameters.values() if isinstance(p, dict))
else:
yield rope_parameters


def _mrope_section(config: PretrainedConfig) -> Sequence[int] | None:
"""Return the M-RoPE section this config declares, if any.

`xdrope_section` is the legacy name HunYuan-VL checkpoints use for the same
field; upstream Transformers normalises it to `mrope_section`.
"""
from vllm.config.utils import getattr_iter

names = ("mrope_section", "xdrope_section")

for params in _iter_rope_parameters(config):
for i, name in enumerate(names):
section = params.get(name)
if isinstance(section, (list, tuple)):
if i > 0:
logger.warning_once(
"rope_parameters contains a deprecated key '%s'. "
"Please use the preferred key '%s' instead.",
name,
names[0],
)
return section

section = getattr_iter(config, names, None, warn=True)
return section if isinstance(section, (list, tuple)) else None


def _uses_mrope(config: PretrainedConfig) -> bool:
return _mrope_section(config) is not None


def uses_mrope(config: PretrainedConfig) -> bool:
Expand All @@ -602,21 +634,23 @@ def thinker_uses_mrope(config: PretrainedConfig) -> bool:
return uses_mrope(thinker_text_config)


def uses_xdrope_dim(config: PretrainedConfig) -> int:
"""Detect if the model with this config uses XD-ROPE."""
xdrope_section = getattr(config, "xdrope_section", None)
if xdrope_section is not None and isinstance(xdrope_section, list):
return len(xdrope_section)
rope_scaling = getattr(config, "rope_scaling", None)
if rope_scaling is None:
def mrope_num_dims(config: PretrainedConfig) -> int:
"""Number of M-RoPE position channels the model consumes.

Each section entry sizes one channel, so the section length is the channel
count. Interleaved M-RoPE also accepts a 2 section variant whose positions
are still 3D, so never return fewer than 3.
"""
if not uses_mrope(config):
return 0

if isinstance(rope_scaling, dict) and "xdrope_section" in rope_scaling:
xdrope_section = rope_scaling["xdrope_section"]
if xdrope_section is not None and isinstance(xdrope_section, list):
return len(xdrope_section)
for candidate in (config.get_text_config(), config):
mrope_section = _mrope_section(candidate)
if mrope_section is not None:
return max(len(mrope_section), 3)

return 0
# Custom configs may declare M-RoPE without exposing the sections.
return 3


def is_encoder_decoder(config: PretrainedConfig) -> bool:
Expand Down
2 changes: 0 additions & 2 deletions vllm/v1/core/sched/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ def from_request(
block_ids: tuple[list[int], ...],
prefill_token_ids: list[int] | None = None,
uses_mrope: bool = False,
uses_xdrope: bool = False,
) -> "NewRequestData":
return cls(
req_id=request.request_id,
Expand All @@ -65,7 +64,6 @@ def from_request(
request.mm_features,
request.num_computed_tokens,
uses_mrope=uses_mrope,
uses_xdrope=uses_xdrope,
),
sampling_params=request.sampling_params,
pooling_params=request.pooling_params,
Expand Down
Loading
Loading