refactor: reduce copied vLLM 0.29 compatibility code

Reuse upstream weight mapping and multimodal processing, consolidate Omni processor bridges, and trim unused Hunyuan internals. Route no-media kwargs through the active renderer and preserve GLM generation prompt formatting.

Validation: 453 CPU tests passed, 7 skipped; processor imports, Ruff, and diff checks passed. GPU and end-to-end CI not rerun.
Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
This commit is contained in:
tzhouam committed 2026-09-10 00:41:53 +08:00
1 parent eef8e2bb94
commit efda9369a8
37 files changed
+448 -1506

No files matched your search

@@ -1593,73 +1593,42 @@ def test_model_path_resolver_is_generic_and_model_owned(tmp_path):
assert "model_path_resolver" not in engine_args
def test_build_stage0_input_processor_uses_omni_input_preprocessor(monkeypatch):
def test_build_stage0_input_processor_wraps_active_renderer(monkeypatch):
import vllm_omni.engine.stage_init_utils as init_mod
from vllm_omni.inputs.preprocess import OmniRenderer
original = object()
class DummyInputProcessor:
def __init__(self, vllm_config, renderer=None):
self.vllm_config = vllm_config
self.renderer = renderer or object()
self.input_preprocessor = None
class DummyOmniInputPreprocessor:
def __init__(self, vllm_config, renderer=None):
self.vllm_config = vllm_config
self.renderer = renderer
self.renderer = renderer or original
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
monkeypatch.setattr(init_mod, "OmniInputPreprocessor", DummyOmniInputPreprocessor)
input_processor = build_stage0_input_processor(
processor = build_stage0_input_processor(
types.SimpleNamespace(model_config=types.SimpleNamespace(try_get_generation_config=lambda: {}))
)
assert isinstance(input_processor.input_preprocessor, DummyOmniInputPreprocessor)
assert input_processor.input_preprocessor.renderer is input_processor.renderer
assert isinstance(processor.renderer, OmniRenderer)
assert processor.renderer._renderer is original
assert not hasattr(processor, "input_preprocessor")
def test_build_stage0_input_processor_does_not_resolve_tokenizer_when_skipped(
monkeypatch,
):
def test_build_stage0_input_processor_does_not_resolve_tokenizer_when_skipped(monkeypatch):
import vllm_omni.engine.stage_init_utils as init_mod
token_only_renderer = object()
seen = {}
original = object()
class DummyInputProcessor:
def __init__(self, vllm_config, renderer=None):
if renderer is None:
raise AssertionError("skip_tokenizer_init must supply a renderer")
seen["renderer"] = renderer
assert renderer is original
self.renderer = renderer
self.input_preprocessor = None
class DummyOmniInputPreprocessor:
def __init__(self, vllm_config, renderer=None):
seen["preprocessor_renderer"] = renderer
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
monkeypatch.setattr(
init_mod,
"_build_token_only_renderer",
lambda _config: token_only_renderer,
)
monkeypatch.setattr(
init_mod,
"OmniInputPreprocessor",
DummyOmniInputPreprocessor,
)
monkeypatch.setattr(init_mod, "_build_token_only_renderer", lambda _: original)
config = types.SimpleNamespace(
model_config=types.SimpleNamespace(
skip_tokenizer_init=True,
try_get_generation_config=lambda: {},
)
model_config=types.SimpleNamespace(skip_tokenizer_init=True, try_get_generation_config=lambda: {})
)
build_stage0_input_processor(config)
assert seen["renderer"] is token_only_renderer
assert seen["preprocessor_renderer"] is token_only_renderer
processor = build_stage0_input_processor(config)
assert processor.renderer._renderer is original
def test_inject_kv_stage_info_infers_sender_tp_topology():
+44
View File
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from transformers import BatchFeature
from vllm_omni.inputs.mm_processor import OmniMultiModalProcessor
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.mark.parametrize("counts", [{}, {"audio": 1, "image": 0}])
@pytest.mark.parametrize("original_text", [None, "", "voice cloning text"])
def test_custom_processor_bridge_preserves_prompt_kwargs_and_passthrough(counts, original_text):
class Processor(OmniMultiModalProcessor):
def _get_mm_fields_config(self, *args):
return {}
def _get_prompt_updates(self, *args):
return []
processor = object.__new__(Processor)
processor.dummy_inputs = SimpleNamespace(get_dummy_text=Mock(return_value="dummy"))
processor._get_hf_mm_data = Mock(return_value=({"audios": ["wave"]}, {"embedding": "preserve"}))
processor._call_hf_processor = Mock(return_value=BatchFeature({"features": "processed"}))
items = Mock()
items.get_all_counts.return_value = counts
kwargs = {"sampling_rate": 16000}
if original_text is not None:
kwargs[processor._OMNI_PROMPT_TEXT_KEY] = original_text
before = dict(kwargs)
result = processor._apply_hf_processor_main(items, kwargs)
items.select.assert_called_once_with({k for k, v in counts.items() if v > 0})
processor._call_hf_processor.assert_called_once_with(
"dummy" if original_text is None else original_text,
{"audios": ["wave"]},
{"sampling_rate": 16000},
{},
)
assert dict(result) == {"features": "processed", "embedding": "preserve"}
assert kwargs == before
+88 -24
View File
@@ -1,35 +1,99 @@
# SPDX-License-Identifier: Apache-2.0
"""Unit tests for OmniInputPreprocessor._process_text routing."""
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Exercise Omni routing through the active upstream rendering pipeline."""
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
from pytest_mock import MockerFixture
import torch
from vllm.inputs import tokens_input
from vllm.pooling_params import PoolingParams
from vllm.renderers import BaseRenderer
from vllm.renderers.params import TokenizeParams
from vllm.v1.engine.input_processor import InputProcessor
from vllm_omni.inputs.preprocess import OmniRenderer
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class TestProcessTextMmProcessorKwargsRouting:
"""Presence-based routing: an explicit empty ``mm_processor_kwargs`` dict
on the prompt still routes through ``_process_multimodal``. Required for
AR-based image generation (e.g. GLM-Image t2i) where the HF processor
supplies the image-generation scaffold from its own defaults and no extra
kwargs are needed from the caller.
"""
class _Renderer(BaseRenderer):
def __init__(self):
self.model_config = SimpleNamespace(is_encoder_decoder=False, enable_prompt_embeds=True)
self.tokenizer = None
self.default_cmpl_tok_params = TokenizeParams(max_total_tokens=128)
self._tokenize_prompt = lambda prompt, params: {**prompt, "prompt_token_ids": [1, 2, 3]}
self._tokenize_prompt_async = AsyncMock(side_effect=self._tokenize_prompt)
self._process_multimodal = Mock(return_value=tokens_input([1, 2, 3, 99]))
self._process_multimodal_async = AsyncMock(side_effect=self._process_multimodal)
@pytest.fixture
def preprocessor(self, mocker: MockerFixture):
from vllm_omni.inputs.preprocess import OmniInputPreprocessor
def render_messages(self, messages, params):
return messages, {"prompt": "hello"}
instance = object.__new__(OmniInputPreprocessor)
instance._process_multimodal = mocker.MagicMock(return_value={})
instance._tokenize_prompt = mocker.MagicMock(return_value=[1, 2, 3])
return instance
def test_empty_mm_processor_kwargs_routes_to_multimodal(self, preprocessor):
preprocessor._process_text({"prompt": "hello", "mm_processor_kwargs": {}})
assert preprocessor._process_multimodal.called
assert not preprocessor._tokenize_prompt.called
@pytest.fixture
def renderer():
return OmniRenderer(_Renderer())
def test_missing_mm_processor_kwargs_routes_to_tokenize(self, preprocessor):
preprocessor._process_text({"prompt": "hello"})
assert preprocessor._tokenize_prompt.called
assert not preprocessor._process_multimodal.called
@pytest.mark.parametrize("kwargs", [{}, {"target_h": 512, "target_w": 768}])
@pytest.mark.parametrize("tokenized", [False, True])
def test_process_inputs_routes_no_media_processor_kwargs(renderer, kwargs, tokenized):
# Keep real process_inputs/render_cmpl; stub unrelated config validation.
processor = object.__new__(InputProcessor)
processor.renderer = renderer
processor.model_config = renderer.model_config
processor.vllm_config = SimpleNamespace(
parallel_config=SimpleNamespace(
data_parallel_size=1,
data_parallel_size_local=1,
local_engines_only=False,
)
)
processor._validate_params = Mock()
processor._validate_lora = Mock()
processor._validate_model_inputs = Mock()
prompt = {"prompt_token_ids": [1, 2, 3]} if tokenized else {"prompt": "hello"}
prompt.update(mm_processor_kwargs=kwargs, cache_salt="salt")
request = processor.process_inputs("image-request", prompt, PoolingParams(), ("embed",))
assert request.prompt_token_ids == [1, 2, 3, 99]
assert request.cache_salt == "salt"
renderer._renderer._process_multimodal.assert_called_once_with(
[1, 2, 3],
{},
mm_processor_kwargs=kwargs,
mm_uuids=None,
skip_mm_cache=False,
)
@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize("kind", ["text", "tokens", "media", "kwargs", "embeds"])
def test_renderer_preserves_routes_extras_and_cache_policy(renderer, async_mode, kind):
prompt = {"prompt": "hello", "additional_information": {"speaker": 1}, "model_intermediate_buffer": {"x": 2}}
if kind == "tokens":
prompt["prompt_token_ids"] = [1, 2, 3]
elif kind == "media":
prompt["multi_modal_data"] = {"image": "image"}
elif kind == "kwargs":
prompt["mm_processor_kwargs"] = {}
elif kind == "embeds":
prompt["prompt_embeds"] = torch.ones(3, 4)
if async_mode:
(result,) = asyncio.run(renderer.render_cmpl_async([prompt], skip_mm_cache=True))
else:
(result,) = renderer.render_cmpl([prompt], skip_mm_cache=True)
assert result["additional_information"] == {"speaker": 1}
assert result["model_intermediate_buffer"] == {"x": 2}
assert result["prompt"] == "hello"
if kind in ("media", "kwargs"):
assert result["prompt_token_ids"] == [1, 2, 3, 99]
assert renderer._renderer._process_multimodal.call_args.kwargs["skip_mm_cache"] is True
else:
renderer._renderer._process_multimodal.assert_not_called()
if kind == "embeds":
torch.testing.assert_close(result["prompt_embeds"], prompt["prompt_embeds"])
else:
assert result["prompt_token_ids"] == [1, 2, 3]
@@ -91,6 +91,44 @@ GlmImageRotaryEmbedding = _ar_mod.GlmImageRotaryEmbedding
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.mark.parametrize("num_images", [0, 1, 2])
@pytest.mark.parametrize("preformatted", [False, True])
def test_generation_prompt_ids_preserve_hf_target_scaffold(num_images, preformatted):
from functools import partial
from types import SimpleNamespace
from transformers.models.glm_image.processing_glm_image import GlmImageProcessor
from vllm.multimodal.parse import MultiModalDataItems
from vllm.multimodal.processing import BaseMultiModalProcessor, ProcessorInputs
processor = object.__new__(GlmImageMultiModalProcessor)
symbols = SimpleNamespace(grid_bos_token="<sop>", grid_eos_token="<eop>", bos_token="<image_start>")
hf_processor = SimpleNamespace(
_build_prompt_with_target_shape=partial(GlmImageProcessor._build_prompt_with_target_shape, symbols)
)
tokenizer = SimpleNamespace(encode=lambda text, **kwargs: list(text.encode()))
processor.info = SimpleNamespace(
get_tokenizer=lambda: tokenizer,
get_hf_processor=lambda: hf_processor,
get_hf_config=lambda: _make_hf_config(),
)
items = MagicMock(spec=MultiModalDataItems)
items.get_all_counts.return_value = {"image": num_images}
suffix = "<sop>16 24<eop>" + ("<sop>13 19<eop>" if not num_images else "") + "<image_start>"
text_ids = list(b"a red bird")
expected = [167855] * num_images + text_ids + list(suffix.encode())
inputs = ProcessorInputs(
prompt=expected if preformatted else text_ids,
mm_data_items=items,
hf_processor_mm_kwargs={"target_h": 512, "target_w": 768},
)
with patch.object(BaseMultiModalProcessor, "apply", side_effect=lambda inputs, timing: inputs) as upstream:
result = processor.apply(inputs, MagicMock())
assert result.prompt == expected
assert inputs.prompt == (expected if preformatted else text_ids)
upstream.assert_called_once()
def test_glm_image_ar_omits_hidden_pooler_payload():
assert GlmImageForConditionalGeneration.omni_pooler_payload_include_hidden is False
@@ -43,6 +43,34 @@ _FEAT_DIM = 128
_CHUNK_FRAMES = 3000
@pytest.mark.parametrize("version", [(2, 5), (4, 5)])
def test_prompt_batching_delegates_upstream_without_tts_kwargs(version):
from unittest.mock import MagicMock
info = SimpleNamespace(
get_model_version=lambda: version,
get_hf_processor=MagicMock(return_value=object()),
ctx=SimpleNamespace(call_hf_processor=MagicMock()),
)
info.ctx.call_hf_processor.side_effect = (
[{"features": [1]}, {"features": [2]}] if version == (2, 5) else [{"features": [1, 2]}]
)
kwargs = {"use_tts": True, "sampling_rate": 16000}
result = MiniCPMO45OmniLLMMultiModalProcessor._call_hf_processor_on_prompts(
SimpleNamespace(info=info), ["one", "two"], {"audios": [10, 20]}, kwargs, out_keys={"features"}
)
assert result == {"features": [1, 2]}
assert kwargs == {"use_tts": True, "sampling_rate": 16000}
for call in info.ctx.call_hf_processor.call_args_list:
assert call.args[2] == {"sampling_rate": 16000}
payloads = [call.args[1] for call in info.ctx.call_hf_processor.call_args_list]
assert payloads == (
[{"text": "one", "audios": 10}, {"text": "two", "audios": 20}]
if version == (2, 5)
else [{"text": ["one", "two"], "audios": [10, 20]}]
)
class TestMiniCPMOFieldConfig:
def test_short_audios_stay_batched(self) -> None:
# two <=30s audios: one feature entry + one 1-element lens per audio
@@ -620,10 +620,17 @@ def test_derive_audio_from_video_placeholders_only_pairs_true_videos():
def test_qwen3_processor_inherits_vllm_omni_per_video_helpers():
from vllm.model_executor.models.qwen3_omni_moe_thinker import (
Qwen3OmniMoeThinkerMultiModalProcessor as UpstreamQwen3Processor,
)
assert issubclass(
Qwen3OmniMoeThinkerMultiModalProcessor,
Qwen2_5OmniThinkerMultiModalProcessor,
)
assert Qwen3OmniMoeThinkerMultiModalProcessor._get_hf_mm_data is UpstreamQwen3Processor._get_hf_mm_data
mro = Qwen3OmniMoeThinkerMultiModalProcessor.__mro__
assert mro.index(Qwen2_5OmniThinkerMultiModalProcessor) < mro.index(UpstreamQwen3Processor)
def test_qwen3_prompt_updates_prefer_hf_second_per_grid_ts_from_outputs():
@@ -113,7 +113,9 @@ def _save_peft_adapter(tmp_path: Path) -> Path:
return adapter_dir
def test_peft_expert_lora_loads_into_thinker(tmp_path: Path):
def test_peft_expert_lora_loads_into_thinker(tmp_path: Path, monkeypatch):
# This CPU harness tests weight mapping, not CUDA pinned-memory allocation.
monkeypatch.setattr("vllm.lora.lora_model.PIN_MEMORY", False)
adapter_dir = _save_peft_adapter(tmp_path)
peft_helper = PEFTHelper.from_local_dir(str(adapter_dir), max_position_embeddings=128)
lora_model = LoRAModel.from_local_checkpoint(
@@ -4,9 +4,7 @@
import pytest
import torch
from torch import nn
from vllm.model_executor.models.utils import WeightsMapper
from vllm_omni.model_executor.models.weight_loader import AutoWeightsLoader
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -20,21 +18,18 @@ class _TinyModel(nn.Module):
self.rotary_embed.register_parameter("inv_freq", nn.Parameter(torch.zeros(1)))
def test_auto_weights_loader_preserves_removed_skip_arguments() -> None:
def test_upstream_mapper_preserves_stage_exclusions_after_renaming() -> None:
model = _TinyModel()
model.skipped.weight.data.zero_()
loaded = AutoWeightsLoader(
model,
skip_prefixes=["skipped."],
skip_substrs=["rotary_embed.inv_freq"],
).load_weights(
loaded = AutoWeightsLoader(model).load_weights(
[
("checkpoint.kept.weight", torch.ones(1, 1)),
("skipped.weight", torch.full((1, 1), 2.0)),
("checkpoint.skipped.weight", torch.full((1, 1), 2.0)),
("rotary_embed.inv_freq", torch.ones(1)),
],
mapper=WeightsMapper(orig_to_new_prefix={"checkpoint.": ""}),
mapper=WeightsMapper(orig_to_new_prefix={"checkpoint.": ""})
| WeightsMapper(orig_to_new_prefix={"skipped.": None}, orig_to_new_substr={"rotary_embed.inv_freq": None}),
)
assert loaded == {"kept.weight"}