Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-27 18:25:21 +09:00
1165 changed files with 51759 additions and 14579 deletions
+23
View File
@@ -17,6 +17,26 @@ EPS = 1e-5
attn_res_module = importlib.import_module("vllm.models.kimi_k3.nvidia.ops.attn_res")
def _on_rocm_below_10() -> bool:
if not current_platform.is_rocm():
return False
from vllm.platforms.rocm import get_rocm_version
return (get_rocm_version() or (0,)) < (10,)
# The Triton bundled with ROCm < 10 (3.7.x) crashes in the AMD
# CanonicalizePointers pass on the kernel's tl.where over pointer tensors. Only
# the num_blocks > 0 loop contains it. ROCm serves AttnRes from
# vllm/models/kimi_k3/amd/ops/attn_res.py instead, so nothing real is lost.
_OLD_ROCM = _on_rocm_below_10()
def _skip_on_old_rocm(num_blocks: int) -> None:
if _OLD_ROCM and num_blocks > 0:
pytest.skip("Triton on ROCm < 10 cannot compile this kernel's pointer select")
def _randn_with_row_padding(*shape: int, padding: int = 0) -> torch.Tensor:
storage = torch.randn(
*shape[:-1],
@@ -79,6 +99,7 @@ def test_attn_res(
):
if backend == "nvidia" and not current_platform.is_device_capability_family(100):
pytest.skip("NVIDIA AttnRes requires the SM100 family")
_skip_on_old_rocm(num_blocks)
prefix = _randn_with_row_padding(num_tokens, HIDDEN_SIZE, padding=row_padding)
delta = (
@@ -133,6 +154,7 @@ def test_attn_res(
@pytest.mark.parametrize("num_blocks", range(MAX_BLOCKS + 1))
def test_attn_res_block_counts(num_blocks: int):
_skip_on_old_rocm(num_blocks)
prefix = torch.randn(1, HIDDEN_SIZE, device="cuda", dtype=torch.bfloat16)
blocks = torch.randn(
1, MAX_BLOCKS, HIDDEN_SIZE, device="cuda", dtype=torch.bfloat16
@@ -169,6 +191,7 @@ def test_attn_res_block_counts(num_blocks: int):
def test_attn_res_without_output_norm():
_skip_on_old_rocm(MAX_BLOCKS)
prefix = torch.randn(7, HIDDEN_SIZE, device="cuda", dtype=torch.bfloat16)
delta = torch.randn_like(prefix)
blocks = torch.randn(
+56 -9
View File
@@ -22,6 +22,9 @@ from vllm.model_executor.layers.mamba.ops.causal_conv1d import causal_conv1d_upd
from vllm.model_executor.layers.mamba.ops.gather_initial_states import (
gather_initial_states,
)
from vllm.models.kimi_k3.amd.ops.third_party.kda import (
fused_recurrent_kda as fused_recurrent_kda_amd,
)
from vllm.models.kimi_k3.amd.ops.third_party.kda import (
fused_recurrent_kda_packed_decode as fused_recurrent_kda_packed_decode_amd,
)
@@ -44,10 +47,12 @@ from vllm.models.kimi_k3.nvidia.ops.third_party.kda import (
chunk_kda,
chunk_kda_with_fused_gate,
fused_kda_gate,
fused_recurrent_kda,
fused_recurrent_kda_fwd,
fused_recurrent_kda_packed_decode,
)
from vllm.models.kimi_k3.nvidia.ops.third_party.kda import (
fused_recurrent_kda as fused_recurrent_kda_nvidia,
)
from vllm.platforms import current_platform
from vllm.third_party.flash_linear_attention.ops.l2norm import l2norm_fwd
from vllm.utils.flashinfer import flashinfer_fused_kda_decode
@@ -66,6 +71,10 @@ PACKED_DECODE_IMPLS = {
"nvidia": fused_recurrent_kda_packed_decode,
"amd": fused_recurrent_kda_packed_decode_amd,
}
SPEC_DECODE_IMPLS = {
"nvidia": fused_recurrent_kda_nvidia,
"amd": fused_recurrent_kda_amd,
}
def test_kda_warmup_skips_missing_metadata(monkeypatch):
@@ -468,17 +477,51 @@ def test_packed_kda_decode_correctness(
@pytest.mark.parametrize(
("H", "fuse_gate"),
[(12, True), (12, False), (12, None), (96, None)],
("impl", "H", "fuse_gate", "num_seqs", "query_len"),
[
*[
pytest.param(
impl,
H,
fuse_gate,
3,
3,
id=f"{impl}-H{H}-fuse-{fuse_gate}",
)
for impl in SPEC_DECODE_IMPLS
for H, fuse_gate in [
(12, True),
(12, False),
(12, None),
(96, None),
]
],
pytest.param("amd", 12, True, 1, 1, id="amd-single-token"),
pytest.param("amd", 12, True, 1, 8, id="amd-single-sequence-short"),
pytest.param(
"amd",
96,
None,
1,
8,
id="amd-single-sequence-many-heads",
),
pytest.param("amd", 12, True, 2, 4, id="amd-uniform-two-sequences"),
pytest.param("amd", 12, True, 4, 4, id="amd-uniform-four-sequences"),
pytest.param("amd", 12, True, 8, 7, id="amd-uniform-eight-sequences"),
],
)
@pytest.mark.parametrize("lower_bound", [-5.0, None])
@torch.inference_mode()
def test_kda_spec_decode_correctness(
H: int,
fuse_gate: bool | None,
num_seqs: int,
query_len: int,
lower_bound: float | None,
impl: str,
):
num_seqs, query_len, D = 3, 3, 128
D = 128
T = num_seqs * query_len
torch.manual_seed(1234)
@@ -522,10 +565,8 @@ def test_kda_spec_decode_correctness(
dtype=torch.int32,
device=DEVICE,
).view(num_seqs, query_len)
num_accepted_tokens = torch.tensor(
[1, 2, 3],
dtype=torch.int32,
device=DEVICE,
num_accepted_tokens = (
torch.arange(num_seqs, dtype=torch.int32, device=DEVICE) % query_len + 1
)
state_storage = 0.01 * torch.randn(
T + 1,
@@ -578,7 +619,12 @@ def test_kda_spec_decode_correctness(
expected = torch.cat(expected_outputs, dim=1)
actual_state = state.clone()
actual, _ = fused_recurrent_kda(
extra_args = (
{"uniform_sequence_length": query_len}
if impl == "amd" and num_seqs in (2, 4, 8)
else {}
)
actual, _ = SPEC_DECODE_IMPLS[impl](
q=q,
k=k,
v=v,
@@ -593,6 +639,7 @@ def test_kda_spec_decode_correctness(
num_accepted_tokens=num_accepted_tokens,
out=output,
fuse_gate=fuse_gate,
**extra_args,
)
assert actual.data_ptr() == output.data_ptr()
+19
View File
@@ -49,6 +49,7 @@ PRUNED_METADATA_FIELDS = {
"prefill_state_indices",
"prefill_has_initial_state",
"spec_sequence_masks",
"uniform_spec_sequence_length",
"flashinfer_prefill_query_start_loc",
"flashinfer_prefill_seq_order",
}
@@ -409,6 +410,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
"num_speculative_tokens",
"full_cuda_graph",
"is_prefilling",
"expected_uniform_spec_sequence_length",
),
[
pytest.param(
@@ -417,6 +419,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
2,
False,
[False, False],
3,
id="pure-spec-decode",
),
pytest.param(
@@ -425,6 +428,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
2,
False,
[True, False, False],
3,
id="mixed-prefill-and-spec-decode",
),
pytest.param(
@@ -433,6 +437,7 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
0,
False,
[False, False],
None,
id="regular-decode",
),
pytest.param(
@@ -441,8 +446,18 @@ def test_internal_checkpoint_metadata_skips_unaligned_offset():
2,
False,
[False, False],
None,
id="no-scheduled-draft-tokens",
),
pytest.param(
BatchSpec(seq_lens=[50, 30], query_lens=[3, 2]),
[2, 1],
2,
False,
[False, False],
None,
id="ragged-spec-decode",
),
],
)
def test_kimi_k3_kda_metadata_matches_shared_gdn(
@@ -451,6 +466,7 @@ def test_kimi_k3_kda_metadata_matches_shared_gdn(
num_speculative_tokens: int,
full_cuda_graph: bool,
is_prefilling: list[bool],
expected_uniform_spec_sequence_length: int | None,
):
kwargs: dict[str, torch.Tensor] = {}
if num_decode_draft_tokens is not None:
@@ -483,6 +499,9 @@ def test_kimi_k3_kda_metadata_matches_shared_gdn(
assert isinstance(actual, KimiK3KDAMetadata)
_assert_matches_shared_gdn(reference, actual)
assert (
reference.uniform_spec_sequence_length == expected_uniform_spec_sequence_length
)
def test_mixed_regular_and_spec_decode_uses_packed_decode_metadata():
+6 -6
View File
@@ -15,6 +15,7 @@ from tests.utils import (
multi_process_parallel,
)
from vllm.distributed import get_tp_group
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
from vllm.model_executor.layers.fused_moe.experts.trtllm_mxfp4_moe import (
TrtLlmMxfp4ExpertsMonolithic,
)
@@ -43,12 +44,11 @@ def test_deferred_finalize_enabled_before_moe_kernel_setup(
hidden_dim = LATENT_SIZE
hidden_dim_unpadded = LATENT_SIZE
experts_per_token = 16
defer_moe_finalize = False
_defer_moe_finalize = False
defer_moe_finalize_max_num_tokens = -1
@property
def use_deferred_moe_finalize(self) -> bool:
return self.defer_moe_finalize
defer_moe_finalize = FusedMoEConfig.defer_moe_finalize
limit_deferred_moe_finalize = FusedMoEConfig.limit_deferred_moe_finalize
use_deferred_moe_finalize = FusedMoEConfig.use_deferred_moe_finalize
moe_config = FakeMoEConfig()
quant_method = SimpleNamespace(
@@ -99,7 +99,7 @@ def test_deferred_finalize_enabled_before_moe_kernel_setup(
latent_moe_runner.LatentMoERunner()
assert moe_config.defer_moe_finalize
assert moe_config.use_deferred_moe_finalize
assert moe_config.defer_moe_finalize_max_num_tokens == 128
assert initialized_with["experts_per_token"] == 16
+67 -2
View File
@@ -7,7 +7,8 @@ import numpy as np
import pytest
import torch
from vllm.config import VllmConfig
from vllm.config import CompilationConfig, VllmConfig
from vllm.config.compilation import CompilationMode
from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
from vllm.model_executor.models import gemma
from vllm.model_executor.models.gemma3n import (
@@ -18,10 +19,72 @@ from vllm.model_executor.models.gemma4 import (
Gemma4ForCausalLM,
_gemma4_layer_weights_mapper,
)
from vllm.model_executor.models.gemma4_dspark import (
Gemma4DSparkForCausalLM,
Gemma4DSparkModel,
)
MODELS = ["google/gemma-2b", "google/gemma-2-2b", "google/gemma-3-4b-it"]
@pytest.mark.usefixtures("dist_init")
@pytest.mark.parametrize(
"enabled,has_weights,with_markov",
[
pytest.param(True, True, False, id="hidden-only"),
pytest.param(True, True, True, id="with-markov"),
pytest.param(True, False, True, id="missing-weights"),
pytest.param(False, True, True, id="disabled-head"),
],
)
def test_gemma4_dspark_loads_confidence_head(
monkeypatch, enabled, has_weights, with_markov
) -> None:
"""Use checkpoint confidence parameters, or disable an unavailable head."""
config = SimpleNamespace(
vocab_size=64,
hidden_size=8,
target_layer_ids=[0, 1],
num_hidden_layers=0,
rms_norm_eps=1e-6,
markov_rank=4,
enable_confidence_head=enabled,
confidence_head_with_markov=with_markov,
)
vllm_config = SimpleNamespace(
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
model_config=SimpleNamespace(dtype=torch.bfloat16),
speculative_config=SimpleNamespace(
draft_model_config=SimpleNamespace(hf_config=config),
),
)
monkeypatch.setattr(Gemma4DSparkModel, "_build_fused_kv_buffers", lambda _: None)
model = Gemma4DSparkForCausalLM(vllm_config=cast(VllmConfig, vllm_config))
width = config.hidden_size + (config.markov_rank if with_markov else 0)
weight = torch.arange(width, dtype=torch.bfloat16).reshape(1, -1) / 16
bias = torch.tensor([-0.5], dtype=torch.bfloat16)
loaded = model.load_weights(
[("confidence_head.proj.weight", weight), ("confidence_head.proj.bias", bias)]
if has_weights
else []
)
if not (enabled and has_weights):
assert model.model.confidence_head is None
assert not loaded
return
assert loaded == {
"model.confidence_head.proj.weight",
"model.confidence_head.proj.bias",
}
assert model.model.confidence_head.proj.weight.dtype == torch.float32
hidden = torch.full((3, config.hidden_size), 0.25, dtype=torch.bfloat16)
markov = torch.full((3, config.markov_rank), -0.5, dtype=torch.bfloat16)
inputs = torch.cat([hidden, markov], dim=-1) if with_markov else hidden
expected = (inputs.float() @ weight.float().T + bias.float()).sigmoid().squeeze(-1)
torch.testing.assert_close(model.compute_confidence(hidden, markov), expected)
@pytest.mark.cpu_test
@pytest.mark.usefixtures("dist_init")
def test_checkpoint_lm_head_can_override_tied_config(monkeypatch) -> None:
@@ -164,7 +227,9 @@ def test_dummy_loader(vllm_runner, monkeypatch, model: str) -> None:
) as llm:
if model == "google/gemma-3-4b-it":
normalizers = llm.llm.collective_rpc(
lambda self: self.model_runner.model.language_model.model.normalizer.cpu().item() # noqa: E501
lambda self: (
self.model_runner.model.language_model.model.normalizer.cpu().item()
) # noqa: E501
)
config = llm.llm.llm_engine.model_config.hf_config.text_config
else:
@@ -73,6 +73,7 @@ def _set_conv_state_layout(monkeypatch, layout: str) -> None:
def test_models(
hf_runner,
vllm_runner,
gpu_memory_cleared,
example_prompts,
monkeypatch,
model: str,
@@ -14,7 +14,7 @@ from types import SimpleNamespace
from typing import cast
import pytest
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config import ModelConfig
from vllm.model_executor.models.config import (
@@ -23,7 +23,7 @@ from vllm.model_executor.models.config import (
)
def _model_config(hf_config: PretrainedConfig) -> ModelConfig:
def _model_config(hf_config: PreTrainedConfig) -> ModelConfig:
"""Minimal stand-in for ModelConfig; only hf_config is read."""
return cast(ModelConfig, SimpleNamespace(hf_config=hf_config))
@@ -42,7 +42,7 @@ def test_encoder_backbone_enables_bidirectional_attention():
EncoderOnlyAttention; JinaEmbeddingsV5Model then dispatches to the encoder
implementation.
"""
hf_config = PretrainedConfig(is_decoder=False)
hf_config = PreTrainedConfig(is_decoder=False)
JinaEmbeddingsV5ModelConfig.verify_and_update_model_config(_model_config(hf_config))
@@ -55,13 +55,13 @@ def test_supported_decoder_backbone_is_accepted():
`-small` omits `is_decoder` entirely, so an absent attribute has to be
treated as a decoder. The first assertion pins that assumption: if
PretrainedConfig ever gains an `is_decoder=False` default, this fails here
PreTrainedConfig ever gains an `is_decoder=False` default, this fails here
rather than silently rejecting a supported checkpoint.
"""
absent = PretrainedConfig()
absent = PreTrainedConfig()
assert not hasattr(absent, "is_decoder")
JinaEmbeddingsV5ModelConfig.verify_and_update_model_config(_model_config(absent))
JinaEmbeddingsV5ModelConfig.verify_and_update_model_config(
_model_config(PretrainedConfig(is_decoder=True))
_model_config(PreTrainedConfig(is_decoder=True))
)
@@ -6,15 +6,8 @@ from typing import TYPE_CHECKING, Any
import pytest
import torch
from mistral_common.multimodal import download_image
from mistral_common.protocol.instruct.chunk import ImageURLChunk
from mistral_common.protocol.instruct.request import ChatCompletionRequest
from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
from mistral_common.tokens.tokenizers.multimodal import image_from_chunk
from transformers import AutoProcessor
from vllm import SamplingParams, TextPrompt, TokensPrompt
from vllm.inputs import MultiModalDataBuiltins
from vllm import SamplingParams
from vllm.logprobs import Logprob, SampleLogprobs
from vllm.model_executor.models.pixtral import _make_packed_sequence_metadata
from vllm.platforms import current_platform
@@ -56,59 +49,6 @@ def _create_msg_format(urls: list[str]) -> list[dict[str, Any]]:
]
def _create_msg_format_hf(urls: list[str]) -> list[dict[str, Any]]:
return [
{
"role": "user",
"content": [
{
"type": "text",
"content": PROMPT,
},
*({"type": "image", "image": download_image(url)} for url in urls),
],
}
]
def _create_engine_inputs(urls: list[str]) -> TokensPrompt:
msg = _create_msg_format(urls)
tokenizer = MistralTokenizer.from_model("pixtral")
request = ChatCompletionRequest(messages=msg) # type: ignore[type-var]
tokenized = tokenizer.encode_chat_completion(request)
engine_inputs = TokensPrompt(prompt_token_ids=tokenized.tokens)
images = []
for chunk in request.messages[0].content:
if isinstance(chunk, ImageURLChunk):
images.append(image_from_chunk(chunk))
mm_data = MultiModalDataBuiltins(image=images)
engine_inputs["multi_modal_data"] = mm_data
return engine_inputs
def _create_engine_inputs_hf(urls: list[str]) -> TextPrompt:
msg = _create_msg_format_hf(urls)
tokenizer = AutoProcessor.from_pretrained("mistral-community/pixtral-12b")
prompt = tokenizer.apply_chat_template(msg)
images = []
for chunk in msg[0]["content"]:
if chunk["type"] == "image":
images.append(chunk["image"])
mm_data = MultiModalDataBuiltins(image=images)
engine_inputs = TextPrompt(prompt=prompt, multi_modal_data=mm_data)
return engine_inputs
SAMPLING_PARAMS = SamplingParams(max_tokens=512, temperature=0.0, logprobs=5)
LIMIT_MM_PER_PROMPT = dict(image=4)
@@ -6,7 +6,6 @@ typically specific to a small subset of models.
"""
import types
from pathlib import PosixPath
import numpy as np
import numpy.typing as npt
@@ -29,7 +28,7 @@ from vllm.logprobs import SampleLogprobs
from vllm.platforms import current_platform
from vllm.utils.collection_utils import is_list_of
from .....conftest import HfRunner, ImageAsset, ImageTestAssets
from .....conftest import HfRunner, ImageTestAssets
from .types import RunnerOutput
@@ -48,17 +47,6 @@ def blip2_vllm_to_hf_output(vllm_output: RunnerOutput, model: str) -> RunnerOutp
return hf_output_ids, hf_output_str, out_logprobs
def qwen_vllm_to_hf_output(
vllm_output: RunnerOutput, model: str
) -> tuple[list[int], str, SampleLogprobs | None]:
"""Sanitize vllm output [qwen models] to be comparable with hf output."""
output_ids, output_str, out_logprobs = vllm_output
hf_output_str = output_str + "<|endoftext|>"
return output_ids, hf_output_str, out_logprobs
def qwen2_vllm_to_hf_output(
vllm_output: RunnerOutput, model: str
) -> tuple[list[int], str, SampleLogprobs | None]:
@@ -239,37 +227,6 @@ def get_llava_embeddings(image_assets: ImageTestAssets):
return [asset.image_embeds for asset in image_assets]
####### Prompt path encoders for models that need models on disk
def qwen_prompt_path_encoder(
tmp_path: PosixPath, prompt: str, assets: list[ImageAsset] | ImageTestAssets
) -> str:
"""Given a temporary dir path, export one or more image assets into the
tempdir & replace its contents with the local path to the string so that
the HF version of Qwen-VL can resolve the path and load the image in its
forward() call.
Args:
tmp_path: Tempdir for test under consideration.
prompt: Prompt with image placeholders.
assets: list of image assets whose len equals the num placeholders.
"""
# Ensure that the number of placeholders matches the number of assets;
# If this is not true, the test is probably written incorrectly.
assert prompt.count("<img></img>") == len(assets)
# Replace the placeholders with local paths to the exported assets
for asset in assets:
image_tmp_path = tmp_path / f"{asset.name}.jpg"
asset.pil_image.save(image_tmp_path)
prompt = prompt.replace(
"<img></img>",
f"<img>{image_tmp_path}</img>",
1,
)
return prompt
####### Model-specific HuggingFace runner patchers
def deepseekvl2_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
"""Patches and returns an instance of the HfRunner to use for GLM4."""
@@ -14,11 +14,6 @@ from vllm.entrypoints.pooling.scoring.typing import ScoreMultiModalParam
from ....conftest import HfRunner, VllmRunner
pytestmark = pytest.mark.skip(
reason="jinaai/jina-reranker-m0 custom code is incompatible with "
"transformers v5 (missing all_tied_weights_keys)"
)
MODELS = ["jinaai/jina-reranker-m0"]
MM_PROCESSOR_KWARGS = {
@@ -29,8 +24,8 @@ MM_PROCESSOR_KWARGS = {
LIMIT_MM_PER_PROMPT = {"image": 2}
CHECKPOINT_TO_HF_MAPPER = {
"visual.": "model.visual.",
"model.": "model.language_model.",
r"^visual\.": "model.visual.",
r"^model\.(?!language_model\.|visual\.)": "model.language_model.",
}
HANDELSBLATT_IMAGE_URL = (
@@ -22,19 +22,19 @@ from unittest.mock import MagicMock
import numpy as np
import pytest
import torch
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from tests.models.registry import HF_EXAMPLE_MODELS
from vllm.config.multimodal import MultiModalDummyOptions
class MockAudioFlamingo3Config(PretrainedConfig):
class MockAudioFlamingo3Config(PreTrainedConfig):
model_type = "audioflamingo3"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.audio_config = PretrainedConfig()
self.text_config = PretrainedConfig()
self.audio_config = PreTrainedConfig()
self.text_config = PreTrainedConfig()
class MockAudioFlamingo3Processor:
@@ -8,7 +8,7 @@ import pytest
import torch
from PIL import Image
from tokenizers import Tokenizer, decoders, models, pre_tokenizers
from transformers import PreTrainedTokenizerFast
from transformers import TokenizersBackend
from vllm.model_executor.models.bailing_moe_v3_vl import (
IMAGE_PLACEHOLDER,
@@ -34,7 +34,7 @@ def processor():
add_prefix_space=False, use_regex=False
)
backend.decoder = decoders.ByteLevel()
tokenizer = PreTrainedTokenizerFast(
tokenizer = TokenizersBackend(
tokenizer_object=backend,
additional_special_tokens=[
"<|vision_start|>",
@@ -1,13 +1,16 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
from collections.abc import Set as AbstractSet
from functools import partial
import numpy as np
import pytest
import torch
from PIL import Image
from tests.models.utils import build_model_context
from vllm.config import ModelConfig
from vllm.config.multimodal import (
AudioDummyOptions,
@@ -16,10 +19,15 @@ from vllm.config.multimodal import (
MultiModalDummyOptions,
VideoDummyOptions,
)
from vllm.distributed.ec_transfer.ec_connector.utils import (
PlaceholderMetadataResolver,
collect_ec_item_metadata,
)
from vllm.entrypoints.chat_utils import _get_embeds_data
from vllm.inputs import MultiModalDataDict, MultiModalInput
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.cache import MultiModalProcessorOnlyCache
from vllm.multimodal.inputs import batched_tensors_equal
from vllm.multimodal.inputs import MultiModalFeatureSpec, batched_tensors_equal
from vllm.multimodal.processing import BaseMultiModalProcessor, InputProcessingContext
from vllm.platforms import current_platform
from vllm.tokenizers import TokenizerLike, cached_tokenizer_from_config
@@ -193,6 +201,79 @@ def get_token_prompt(
return inputs.prompt
@pytest.mark.parametrize(
"model_id,durations",
[
("Qwen/Qwen2-Audio-7B-Instruct", [1.0, 2.3]),
("nvidia/audio-flamingo-3-hf", [31.0]),
("fixie-ai/ultravox-v0_5-llama-3_2-1b", [1.0, 31.0]),
("Qwen/Qwen2.5-Omni-3B", [1.0, 2.3]),
("Qwen/Qwen3-Omni-30B-A3B-Instruct", [1.0, 2.3]),
],
)
def test_audio_metadata_only_roundtrip(model_id, durations, monkeypatch):
"""EC metadata preserves the raw-audio prompt without running the HF processor."""
ctx = build_model_context(model_id, limit_mm_per_prompt={"audio": len(durations)})
mm_config = ctx.model_config.multimodal_config
mm_config.enable_mm_embeds = True
mm_config.allow_missing_mm_embeddings = True
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
sample_rate = processor.info.get_feature_extractor().sampling_rate
audios = [
np.zeros(int(duration * sample_rate), dtype=np.float32)
for duration in durations
]
prompt = processor.dummy_inputs.get_dummy_text({"audio": len(audios)})
raw = processor(
prompt,
mm_items=processor.info.parse_mm_data({"audio": audios}),
hf_processor_mm_kwargs={},
)
features = [
MultiModalFeatureSpec(
data=item,
modality="audio",
identifier=str(index),
mm_position=position,
)
for index, (item, position) in enumerate(
zip(raw["mm_kwargs"]["audio"], raw["mm_placeholders"]["audio"])
)
]
published = collect_ec_item_metadata(
features, PlaceholderMetadataResolver(ctx.model_config)
)
metadata = json.loads(
json.dumps([entry["metadata"] for entry in published.values()])
)
assert len(metadata) == len(audios)
assert all(metadata)
audio_data = _get_embeds_data("audio", metadata, processor)
def unexpected_preprocessing(*args, **kwargs):
pytest.fail("The EC consumer must not preprocess audio")
monkeypatch.setattr(processor, "_call_hf_processor", unexpected_preprocessing)
remote = processor(
prompt,
mm_items=processor.info.parse_mm_data({"audio": audio_data}),
hf_processor_mm_kwargs={},
)
assert remote["prompt_token_ids"] == raw["prompt_token_ids"]
assert remote["mm_placeholders"] == raw["mm_placeholders"]
# Omni also consumes these lengths when constructing M-RoPE positions.
if "audio_feature_lengths" in audio_data:
assert torch.equal(
remote["mm_kwargs"].get_data()["audio_feature_lengths"],
raw["mm_kwargs"].get_data()["audio_feature_lengths"],
)
mm_config.allow_missing_mm_embeddings = False
ordinary_processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
with pytest.raises(ValueError, match="should contain the fields"):
ordinary_processor.info.parse_mm_data({"audio": audio_data})
def random_vision_chunk(
rng: np.random.RandomState,
min_wh: int,
@@ -6,7 +6,7 @@ from collections.abc import Mapping
import pytest
from PIL import Image
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.image import rescale_image_size
@@ -17,7 +17,7 @@ from ...utils import build_model_context
def _get_expected_num_patches(
config: PretrainedConfig,
config: PreTrainedConfig,
image: Image.Image,
num_imgs: int,
min_num: int,
@@ -6,7 +6,7 @@ from collections.abc import Mapping
import pytest
from PIL import Image
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.image import rescale_image_size
@@ -17,7 +17,7 @@ from ...utils import build_model_context
def _get_expected_num_patches(
config: PretrainedConfig,
config: PreTrainedConfig,
image: Image.Image,
num_imgs: int,
min_num: int,
@@ -6,7 +6,7 @@ from collections.abc import Mapping
import pytest
from PIL import Image
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.image import rescale_image_size
@@ -17,7 +17,7 @@ from ...utils import build_model_context
def _get_expected_num_patches(
config: PretrainedConfig,
config: PreTrainedConfig,
image: Image.Image,
num_imgs: int,
min_num: int,
@@ -8,10 +8,11 @@ import pytest
import torch
from PIL import Image
from vllm.model_executor.models.vision import FusedInputNorm
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.cache import MultiModalProcessorOnlyCache
from vllm.multimodal.inputs import batched_tensors_equal
from vllm.platforms import current_platform
from ....conftest import ImageTestAssets
from ...utils import build_model_context
@@ -65,45 +66,6 @@ def test_jina_vl_processing_order() -> None:
]
@pytest.mark.parametrize(
("image_mean", "image_std", "rescale_factor", "is_identity"),
[
([0.0, 0.0, 0.0], [1.0, 1.0, 1.0], 1.0, True),
([0.5, 0.5, 0.5], [0.25, 0.25, 0.25], 1 / 255, False),
],
)
def test_fused_input_norm_initialization_on_device(
monkeypatch: pytest.MonkeyPatch,
image_mean: list[float],
image_std: list[float],
rescale_factor: float,
is_identity: bool,
):
"""Identity detection must not synchronize the default device."""
original_allclose = torch.allclose
def cpu_allclose(input: torch.Tensor, other: torch.Tensor, *args, **kwargs):
assert input.device.type == "cpu"
assert other.device.type == "cpu"
return original_allclose(input, other, *args, **kwargs)
monkeypatch.setattr(torch, "allclose", cpu_allclose)
# Exercise the real accelerator when available. The meta device gives the
# CPU-only test shard the same non-CPU default-device semantics without
# requiring a CUDA-enabled PyTorch build.
default_device = "cuda" if torch.cuda.is_available() else "meta"
with torch.device(default_device):
input_norm = FusedInputNorm(image_mean, image_std, rescale_factor)
assert input_norm.is_identity is is_identity
if is_identity:
assert input_norm.weight is None
assert input_norm.bias is None
else:
assert input_norm.weight.device.type == default_device
assert input_norm.bias.device.type == default_device
@pytest.mark.parametrize("model_id", ["Qwen/Qwen2-VL-2B-Instruct"])
@pytest.mark.parametrize(
("mm_processor_kwargs", "expected_toks_per_img", "expected_pixels_shape"),
@@ -240,16 +202,20 @@ def test_qwen2_5_vl_video_fps_to_second_per_grid_ts(model_id: str) -> None:
assert float(spg) == pytest.approx(temporal_patch_size / fps, rel=2e-2)
@pytest.mark.usefixtures("default_vllm_config")
@pytest.mark.parametrize(
"model_id", ["Qwen/Qwen2-VL-2B-Instruct", "Qwen/Qwen2.5-VL-3B-Instruct"]
)
@pytest.mark.parametrize("num_imgs", [1, 2])
def test_mm_device_do_normalize(
image_assets: ImageTestAssets,
model_id: str,
num_imgs: int,
):
"""Ensure that enable mm_device_do_normalize yields the correct result."""
image_assets: ImageTestAssets, model_id: str, num_imgs: int
) -> None:
"""Device-side normalisation must reproduce the on-CPU processor result.
Runs on any platform: the CPU platform exercises the ``forward_native``
fallback, accelerators exercise the fused kernel.
"""
device = current_platform.device_type
ctx = build_model_context(
model_id,
limit_mm_per_prompt={"image": num_imgs},
@@ -280,9 +246,15 @@ def test_mm_device_do_normalize(
].get_data()["pixel_values"]
ctx.model_config.multimodal_config.mm_device_do_normalize = True
input_norm = FusedInputNorm.from_model_config(ctx.model_config)
input_norm = build_mm_input_norm(ctx.model_config).to(device)
# With normalisation disabled, the processor emits raw uint8 pixels,
# matching the production mm_device_do_normalize path.
assert pixel_values_without_normalize.dtype == torch.uint8
pixel_values_do_input_norm = input_norm(
pixel_values_without_normalize.to(dtype), dtype
pixel_values_without_normalize.to(device), dtype
)
torch.testing.assert_close(pixel_values_with_normalize, pixel_values_do_input_norm)
torch.testing.assert_close(
pixel_values_with_normalize.to(device), pixel_values_do_input_norm
)
@@ -17,6 +17,7 @@ from ...utils import build_model_context
[
({"max_image_size": {"longest_edge": 384}}, 1377),
({"max_image_size": {"longest_edge": 768}}, 405),
({"do_image_splitting": False}, 81),
],
)
@pytest.mark.parametrize("num_imgs", [1, 2])
@@ -63,6 +64,14 @@ def test_processor_override(
# Ensure the placeholders format are correct
hf_processor = processor.info.get_hf_processor(**hf_processor_mm_kwargs)
num_patches = processor.info.get_num_patches(
image_width=dummy_image.width,
image_height=dummy_image.height,
processor=hf_processor,
mm_kwargs=hf_processor_mm_kwargs,
)
assert num_patches == expected_toks_per_img // hf_processor.image_seq_len
hf_processed_inputs = hf_processor(
text=prompt,
images=mm_data["image"],
+41
View File
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared BF16 baselines for the quantization comparison tests.
Several tests here quantize the same model and compare against an
unquantized run of it. Computing that reference once per session avoids
booting an identical engine for every quantization scheme under test.
Only the outputs are cached; each engine is still torn down as usual, so
tests keep the isolation ``VllmRunner.__exit__`` provides.
"""
import pytest
@pytest.fixture(scope="session")
def quant_baseline_logprobs(vllm_runner):
"""Greedy logprobs for an unquantized model, computed once per config."""
cache: dict = {}
def baseline(
model: str,
prompts: list[str],
*,
max_model_len: int,
max_tokens: int,
num_logprobs: int,
):
key = (model, max_model_len, max_tokens, num_logprobs, tuple(prompts))
if key not in cache:
with vllm_runner(
model,
max_model_len=max_model_len,
enforce_eager=True,
) as vllm_model:
cache[key] = vllm_model.generate_greedy_logprobs(
prompts, max_tokens, num_logprobs
)
return cache[key]
return baseline
@@ -37,6 +37,7 @@ NUM_LOG_PROBS = 8
@pytest.mark.parametrize("model", [DENSE_MODEL, MOE_MODEL], ids=["dense", "moe"])
def test_fp8_per_channel_logprobs(
vllm_runner,
quant_baseline_logprobs,
example_prompts,
model: str,
monkeypatch: pytest.MonkeyPatch,
@@ -52,14 +53,13 @@ def test_fp8_per_channel_logprobs(
with monkeypatch.context() as m:
m.setenv("TOKENIZERS_PARALLELISM", "true")
with vllm_runner(
baseline_outputs = quant_baseline_logprobs(
model,
example_prompts,
max_model_len=MAX_MODEL_LEN,
enforce_eager=True,
) as vllm_model:
baseline_outputs = vllm_model.generate_greedy_logprobs(
example_prompts, MAX_TOKENS, NUM_LOG_PROBS
)
max_tokens=MAX_TOKENS,
num_logprobs=NUM_LOG_PROBS,
)
with vllm_runner(
model,
+6 -6
View File
@@ -42,6 +42,7 @@ NUM_LOG_PROBS = 8
@pytest.mark.parametrize("model", [DENSE_MODEL, MOE_MODEL], ids=["dense", "moe"])
def test_mxfp8_logprobs(
vllm_runner,
quant_baseline_logprobs,
example_prompts,
model: str,
monkeypatch: pytest.MonkeyPatch,
@@ -56,14 +57,13 @@ def test_mxfp8_logprobs(
with monkeypatch.context() as m:
m.setenv("TOKENIZERS_PARALLELISM", "true")
with vllm_runner(
baseline_outputs = quant_baseline_logprobs(
model,
example_prompts,
max_model_len=MAX_MODEL_LEN,
enforce_eager=True,
) as vllm_model:
baseline_outputs = vllm_model.generate_greedy_logprobs(
example_prompts, MAX_TOKENS, NUM_LOG_PROBS
)
max_tokens=MAX_TOKENS,
num_logprobs=NUM_LOG_PROBS,
)
with vllm_runner(
model,
+255 -7
View File
@@ -13,17 +13,24 @@ from torch.nn import functional as F
import vllm.model_executor.layers.vocab_parallel_embedding as embedding_module
import vllm.model_executor.parameter as parameter_module
import vllm.models.qwen4_exp.nvidia.ngram_embedding as ngram_embedding_module
import vllm.models.qwen4_exp.common.ngram_embedding as ngram_embedding_module
from vllm.config.quantization import QuantizationConfigArgs
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptMixedPrecisionConfig,
ModelOptNvFp4Config,
)
from vllm.model_executor.layers.quantization.online.base import OnlineQuantizationConfig
from vllm.models.qwen4_exp.amd import ple_layer as amd_ple_layer
from vllm.models.qwen4_exp.amd.ple_layer import (
Qwen4ExpPLELayer as Qwen4ExpPLELayerAMD,
)
from vllm.models.qwen4_exp.common.ple import (
PLEShardOverlap,
compute_ple_shard_overlap,
copy_ple_embedding_shard_,
)
from vllm.models.qwen4_exp.config import Qwen4ExpTextConfig
from vllm.models.qwen4_exp.nvidia.ngram_embedding import (
Qwen4ExpNGramEmbedding,
Qwen4ExpPLEDeviceEmbedding,
@@ -33,6 +40,7 @@ from vllm.models.qwen4_exp.nvidia.ngram_embedding import (
Qwen4ExpPLEUnquantizedEmbeddingMethod,
)
from vllm.models.qwen4_exp.nvidia.ple_layer import Qwen4ExpPLELayer
from vllm.utils.torch_utils import weak_ref_tensor
from vllm.v1.attention.backends.short_conv_attn import (
PleShortConvAttentionMetadata,
)
@@ -396,7 +404,6 @@ def test_ple_fp8_embedding_uses_int8_for_parallel_reduce(monkeypatch) -> None:
def test_ple_fp8_embedding_respects_checkpoint_shard_exclusions() -> None:
prefix = "model.layers.1.ple.ple_embedding.ngram_embedding"
quant_config = Fp8Config(
is_checkpoint_fp8_serialized=True,
ignored_layers=[],
weight_block_size=[128, 128],
)
@@ -422,12 +429,11 @@ def test_ple_embedding_rejects_unsupported_quantization_configs() -> None:
with pytest.raises(NotImplementedError, match="ModelOptNvFp4Config"):
Qwen4ExpPLEEmbeddingMethod.from_quant_config(nvfp4_config, prefix)
dynamic_fp8_config = Fp8Config(
is_checkpoint_fp8_serialized=False,
ignored_layers=[],
online_fp8_config = OnlineQuantizationConfig(
QuantizationConfigArgs(linear="fp8_per_tensor")
)
with pytest.raises(NotImplementedError, match="serialized FP8"):
Qwen4ExpPLEEmbeddingMethod.from_quant_config(dynamic_fp8_config, prefix)
with pytest.raises(NotImplementedError, match="OnlineQuantizationConfig"):
Qwen4ExpPLEEmbeddingMethod.from_quant_config(online_fp8_config, prefix)
def test_ple_embedding_respects_modelopt_exclusion() -> None:
@@ -885,6 +891,40 @@ def test_fused_ngram_ids_correctness(
assert torch.all((actual >= offsets) & (actual < offsets + sizes))
@pytest.mark.skipif(not torch.cuda.is_available(), reason="fused PLE needs CUDA")
def test_ngram_prefetch_ids_outlive_start_prefetch() -> None:
"""Eager breaks hand the side-stream lookup weak refs, so the ids must stay
valid after start_prefetch returns rather than be reused from the pool."""
device = torch.device("cuda")
query_start_loc = torch.tensor([0, 3, 5], dtype=torch.int32, device=device)
input_ids = torch.arange(20, 25, dtype=torch.int32, device=device)
ngram_context = torch.tensor([[11, 12], [13, 14]], dtype=torch.int32, device=device)
params = _ngram_hash_params(device, ngram_context.shape[1])
module = Qwen4ExpNGramEmbedding.__new__(Qwen4ExpNGramEmbedding)
nn.Module.__init__(module)
for name in ("layer_multipliers", "ngram_heads_vocab_sizes", "ngram_heads_offsets"):
module.register_buffer(name, params[name])
module.eos_token_id = params["eos_token_id"]
module.heads_per_ngram = params["heads_per_ngram"]
num_heads = params["ngram_heads_vocab_sizes"].numel()
module._prefetch_ids = torch.empty(8, num_heads, dtype=torch.long, device=device)
prefetched: list[torch.Tensor] = []
module.ngram_embedding = SimpleNamespace(
supports_prefetch=True,
start_prefetch=lambda _, ids: prefetched.append(weak_ref_tensor(ids)),
)
expected = _reference_ngram_ids(input_ids, query_start_loc, ngram_context, **params)
# A fresh pool makes the next same-size allocation reuse any freed ids,
# like a later CUDA graph segment would.
pool = torch.cuda.MemPool()
with torch.cuda.use_mem_pool(pool):
module.start_prefetch(None, input_ids, query_start_loc, ngram_context)
torch.full_like(expected, -1)
assert torch.equal(prefetched[0], expected)
def _short_conv_dilated_decode_pytorch(
x_d: torch.Tensor,
conv_state: torch.Tensor,
@@ -1715,3 +1755,211 @@ def test_fused_gate_correctness(num_tokens: int, strided_kv: bool) -> None:
expected_normed = grouped_norm(expected_gated, norm_conv)
assert torch.equal(gated, expected_gated)
torch.testing.assert_close(normed, expected_normed, atol=1e-2, rtol=1e-2)
def _build_amd_ngram_embedding(
monkeypatch: pytest.MonkeyPatch,
*,
device: str,
cpu_offload: bool,
fp8_checkpoint: bool,
) -> tuple[amd_ple_layer.Qwen4ExpNGramEmbedding, torch.Tensor]:
"""Construct and load a small AMD embedding through its checkpoint loader."""
_mock_etp_group(monkeypatch)
monkeypatch.setattr(embedding_module, "get_tensor_model_parallel_rank", lambda: 0)
monkeypatch.setattr(
embedding_module, "get_tensor_model_parallel_world_size", lambda: 1
)
monkeypatch.setattr(parameter_module, "get_tensor_model_parallel_rank", lambda: 0)
monkeypatch.setattr(
parameter_module, "get_tensor_model_parallel_world_size", lambda: 1
)
monkeypatch.setattr(
amd_ple_layer,
"get_current_vllm_config",
lambda: SimpleNamespace(engram_config=SimpleNamespace(cpu_offload=cpu_offload)),
)
config = Qwen4ExpTextConfig(
ngram_size=3,
heads_per_ngram=1,
ngram_vocab_size_base=5,
make_ngram_vocab_size_divisible_by=8,
split_ngram_parts=2,
ple_embed_dim=6,
eos_token_id=0,
vocab_size=64,
)
with torch.device(device):
module = amd_ple_layer.Qwen4ExpNGramEmbedding(
config,
embedding_dim=config.ple_embed_dim,
ple_dense_layer_id=0,
max_total_tokens=4,
max_num_reqs=2,
prefix="test.ple_embedding",
layer_name="test.ple",
quant_config=(
Fp8Config(is_checkpoint_fp8_serialized=True) if fp8_checkpoint else None
),
params_dtype=torch.bfloat16,
)
# Only the outer owner is a stub; the embedding constructor and loader run.
layer = Qwen4ExpPLELayerAMD.__new__(Qwen4ExpPLELayerAMD)
nn.Module.__init__(layer)
layer.ple_embedding = module
monkeypatch.setattr(
amd_ple_layer,
"get_forward_context",
lambda: SimpleNamespace(no_compile_layers={module.layer_name: layer}),
)
embedding = module.ngram_embedding
loaded_weight = (
torch.arange(embedding.org_vocab_size * embedding.embedding_dim)
.reshape(embedding.org_vocab_size, embedding.embedding_dim)
.to(embedding.weight.dtype)
)
shard_size = (embedding.org_vocab_size + 1) // 2
weights = [
(f"ngram_embedding.shard_{i}.weight", shard)
for i, shard in enumerate(loaded_weight.split(shard_size))
]
expected_loaded = {"ngram_embedding.weight"}
if fp8_checkpoint:
weights.append(("ngram_embedding.weight_scale", torch.tensor([0.25])))
expected_loaded.add("ngram_embedding.weight_scale")
assert module.load_weights(weights) == expected_loaded
embedding.quant_method.process_weights_after_loading(embedding)
return module, loaded_weight
@pytest.mark.parametrize(
"device,cpu_offload",
[
pytest.param("cpu", False, id="cpu-resident"),
pytest.param(
"cuda:0",
False,
id="gpu-resident",
marks=pytest.mark.skipif(
not torch.cuda.is_available(), reason="requires CUDA or ROCm"
),
),
pytest.param(
"cuda:0",
True,
id="gpu-offloaded",
marks=pytest.mark.skipif(
not torch.cuda.is_available(), reason="requires CUDA or ROCm"
),
),
],
)
def test_amd_fp8_embedding_loads_checkpoint_shards_and_global_scale(
monkeypatch: pytest.MonkeyPatch,
device: str,
cpu_offload: bool,
) -> None:
"""AMD checkpoint loading must accept and apply the global FP8 scale."""
module, loaded_weight = _build_amd_ngram_embedding(
monkeypatch, device=device, cpu_offload=cpu_offload, fp8_checkpoint=True
)
embedding = module.ngram_embedding
assert embedding.weight.dtype == torch.float8_e4m3fn
assert embedding.weight.device == torch.device("cpu" if cpu_offload else device)
if cpu_offload:
assert embedding.weight.is_pinned()
assert embedding.weight_scale.device == torch.device(device)
torch.testing.assert_close(embedding.weight.float().cpu(), loaded_weight.float())
dequantized = embedding.dequantize(embedding.weight.to(device), torch.bfloat16)
torch.testing.assert_close(
dequantized.cpu(), loaded_weight.to(torch.bfloat16) * 0.25, rtol=0, atol=0
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA or ROCm")
@pytest.mark.parametrize("fp8_checkpoint", [False, True], ids=["bf16", "fp8"])
def test_amd_pinned_embedding_output_written_under_compile(
monkeypatch: pytest.MonkeyPatch,
fp8_checkpoint: bool,
) -> None:
"""The AMD pinned lookup op must survive aot_autograd/Inductor.
The op writes via the declared-mutated ``output``. Without
``mutates_args=["output"]`` the call is dead-code-eliminated, the UVA lookup
never runs, and the returned ``output`` stays untouched.
"""
module, loaded_weight = _build_amd_ngram_embedding(
monkeypatch, device="cuda:0", cpu_offload=True, fp8_checkpoint=fp8_checkpoint
)
ngram_ids = torch.tensor([[3, 0], [1, 2]], device="cuda:0")
output = torch.zeros(
ngram_ids.shape[0],
module.embedding_dim,
dtype=module.ngram_embedding.weight.dtype,
device="cuda:0",
)
def lookup(ids: torch.Tensor, out: torch.Tensor) -> torch.Tensor:
torch.ops.vllm.qwen4_exp_amd_ple_ngram_embedding_pinned(
ids, out, module.layer_name
)
return out
torch.compile(lookup, fullgraph=True)(ngram_ids, output)
torch.cuda.current_stream().synchronize()
expected = loaded_weight[ngram_ids.cpu()].to(device="cuda:0").flatten(-2)
torch.testing.assert_close(output.float(), expected.float(), rtol=0, atol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA or ROCm")
@pytest.mark.parametrize("fp8_checkpoint", [False, True], ids=["bf16", "fp8"])
def test_amd_pinned_embedding_output_written_under_cudagraph_capture(
monkeypatch: pytest.MonkeyPatch,
fp8_checkpoint: bool,
) -> None:
"""The AMD pinned lookup op must be capture-safe.
It launches a single kernel on the current stream, so a cudagraph capture
reproduces the lookup into ``output`` without cross-stream work.
"""
module, loaded_weight = _build_amd_ngram_embedding(
monkeypatch, device="cuda:0", cpu_offload=True, fp8_checkpoint=fp8_checkpoint
)
ngram_ids = torch.tensor([[3, 0], [1, 2]], device="cuda:0")
output = torch.zeros(
ngram_ids.shape[0],
module.embedding_dim,
dtype=module.ngram_embedding.weight.dtype,
device="cuda:0",
)
def lookup(ids: torch.Tensor, out: torch.Tensor) -> torch.Tensor:
torch.ops.vllm.qwen4_exp_amd_ple_ngram_embedding_pinned(
ids, out, module.layer_name
)
return out
graph = torch.cuda.CUDAGraph()
warmup_stream = torch.cuda.Stream(device="cuda:0")
warmup_stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(warmup_stream):
for _ in range(3):
lookup(ngram_ids, output)
torch.cuda.current_stream().wait_stream(warmup_stream)
with torch.cuda.graph(graph):
lookup(ngram_ids, output)
for _ in range(2):
ngram_ids.copy_(ngram_ids.flip(-1) + 3)
output.fill_(float("nan"))
graph.replay()
torch.cuda.current_stream().synchronize()
expected = loaded_weight[ngram_ids.cpu()].to(device="cuda:0").flatten(-2)
torch.testing.assert_close(output.float(), expected.float(), rtol=0, atol=0)
+9 -2
View File
@@ -7,7 +7,7 @@ from typing import Any, Literal
import pytest
from packaging.version import Version
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from transformers import __version__ as TRANSFORMERS_VERSION
from vllm.config.model import ModelDType, TokenizerMode
@@ -1233,7 +1233,7 @@ _MULTIMODAL_EXAMPLE_MODELS = {
# NemotronH layers are constructed via `hybrid_override_pattern`
use_original_num_layers=True,
hf_overrides={
"vision_config": PretrainedConfig(
"vision_config": PreTrainedConfig(
args={
"min_num_patches": 1,
"max_num_patches": 12,
@@ -1502,6 +1502,13 @@ _SPECULATIVE_DECODING_EXAMPLE_MODELS = {
max_model_len=8192, # Reduce max len to ensure test runs in low-VRAM CI env
max_num_seqs=32,
),
# LiLiCorr checkpoints are not published yet.
"LiLiCorrDraftModel": _HfExamplesInfo(
"Qwen/Qwen3-8B",
speculative_model="LiLiCorrDraftModel",
is_available_online=False,
use_original_num_layers=True,
),
"DFlash2DraftModel": _HfExamplesInfo(
"Qwen/Qwen3.8-27B",
speculative_model="z-lab/Qwen3.8-27B-DFlash2",
+3 -3
View File
@@ -4,7 +4,7 @@
import pytest
import torch
from transformers import Gemma3Config, PretrainedConfig, Qwen2Config
from transformers import Gemma3Config, PreTrainedConfig, Qwen2Config
from vllm.model_executor.models.adapters import (
_create_pooling_model_cls,
@@ -266,14 +266,14 @@ def test_resolve_num_labels_defaults_when_undeclared():
config = _composite_config()
assert (
_resolve_num_labels(config, config.get_text_config())
== PretrainedConfig().num_labels
== PreTrainedConfig().num_labels
)
def test_resolve_num_labels_declared_on_outer_config():
"""Multimodal checkpoints keep id2label/problem_type on the top-level config."""
config = _composite_config(outer_labels=20)
assert config.get_text_config().num_labels == PretrainedConfig().num_labels
assert config.get_text_config().num_labels == PreTrainedConfig().num_labels
assert _resolve_num_labels(config, config.get_text_config()) == 20
+126
View File
@@ -16,6 +16,132 @@ pytestmark = pytest.mark.skipif(
)
@pytest.mark.parametrize("hash_routing", [False, True], ids=["regular", "hash"])
@pytest.mark.parametrize("vision", [False, True], ids=["text", "vision"])
@torch.inference_mode()
def test_rocm_moe_routing_and_shared_experts_match_reference(
hash_routing, vision, monkeypatch, default_vllm_config, dist_init
) -> None:
"""AMD V4 routing, clamped experts and shared output agree with PyTorch."""
from vllm.forward_context import set_forward_context
from vllm.models.deepseek_v4.amd.model import DeepseekV4MoE
from vllm.models.deepseek_v4.common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
from vllm.utils.torch_utils import set_default_torch_dtype
from vllm.v1.worker.workspace import (
init_workspace_manager,
is_workspace_manager_initialized,
)
monkeypatch.setenv("VLLM_ROCM_USE_AITER_MOE", "0")
monkeypatch.setenv("VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS", "0")
default_vllm_config.kernel_config.moe_backend = "triton"
config = SimpleNamespace(
hidden_size=512,
n_routed_experts=8,
num_experts_per_tok=2,
moe_intermediate_size=512,
swiglu_limit=0.05,
norm_topk_prob=True,
scoring_func="sqrtsoftplus",
routed_scaling_factor=1.5,
num_hash_layers=int(hash_routing),
vocab_size=IMAGE_SENTINEL_BASE_ID + 8,
topk_method="noaux_tc",
vision_n_layers=int(vision),
n_shared_experts=1,
hidden_act="silu",
)
torch.manual_seed(42)
with torch.device("cuda"), set_default_torch_dtype(torch.bfloat16):
moe = DeepseekV4MoE(
SimpleNamespace(
model_config=SimpleNamespace(hf_config=config),
quant_config=None,
parallel_config=ParallelConfig(),
),
prefix="model.layers.0.ffn",
)
for parameter in moe.parameters():
if parameter.is_floating_point():
parameter.normal_(std=0.04)
hidden = torch.randn(17, config.hidden_size) * 0.1
input_ids = torch.arange(17, dtype=torch.int32)
if vision:
# Include both ends of the five-token sentinel interval and the
# first ordinary token above it.
input_ids[1:4] = torch.tensor(
[
IMAGE_SENTINEL_BASE_ID,
IMAGE_SENTINEL_BASE_ID + 4,
IMAGE_SENTINEL_BASE_ID + 5,
],
dtype=torch.int32,
)
if moe.gate.tid2eid is not None:
rows = torch.arange(config.vocab_size)
moe.gate.tid2eid.copy_(torch.stack((rows % 8, (rows + 3) % 8), dim=1))
if moe.gate.e_score_correction_bias is not None:
moe.gate.e_score_correction_bias.copy_(torch.arange(8) * 0.1)
if moe.gate.bias_vl is not None:
moe.gate.bias_vl.copy_(torch.arange(8) * -0.1)
scores = torch.nn.functional.softplus(
hidden.float() @ moe.gate.weight.float().T
).sqrt()
bias = moe.gate.e_score_correction_bias
selection_scores = scores if bias is None else scores + bias
expected_ids = selection_scores.topk(2, dim=-1).indices
if hash_routing:
expected_ids = moe.gate.tid2eid[input_ids.long()].long()
if vision:
image_mask = (input_ids >= IMAGE_SENTINEL_BASE_ID) & (
input_ids < IMAGE_SENTINEL_BASE_ID + 5
)
expected_ids[image_mask] = (
(scores + moe.gate.bias_vl).topk(2, dim=-1).indices[image_mask]
)
expected_weights = scores.gather(1, expected_ids)
expected_weights *= config.routed_scaling_factor / expected_weights.sum(
dim=-1, keepdim=True
)
router_logits, _ = moe.gate(hidden)
weights, ids = moe.experts.router.select_experts(
hidden, router_logits, topk_indices_dtype=torch.int32, input_ids=input_ids
)
torch.testing.assert_close(ids.long(), expected_ids)
torch.testing.assert_close(weights, expected_weights, rtol=1e-5, atol=1e-6)
def expert_reference(x, gate_up_weight, down_weight):
gate, up = (
torch.nn.functional.linear(x, gate_up_weight).float().chunk(2, dim=-1)
)
gate = gate.clamp(max=config.swiglu_limit)
up = up.clamp(-config.swiglu_limit, config.swiglu_limit)
activated = (torch.nn.functional.silu(gate) * up).to(x.dtype)
return torch.nn.functional.linear(activated, down_weight).float()
routed = moe.experts.routed_experts
expected = torch.zeros_like(hidden, dtype=torch.float32)
for expert_id in range(config.n_routed_experts):
token, slot = torch.where(expected_ids == expert_id)
expected[token] += (
expert_reference(
hidden[token], routed.w13_weight[expert_id], routed.w2_weight[expert_id]
)
* expected_weights[token, slot, None]
)
shared = moe.shared_experts
expected += expert_reference(
hidden, shared.gate_up_proj.weight, shared.down_proj.weight
)
moe.experts._quant_method.process_weights_after_loading(routed)
if not is_workspace_manager_initialized():
init_workspace_manager(torch.device("cuda:0"))
with set_forward_context(None, default_vllm_config, num_tokens=hidden.shape[0]):
actual = moe(hidden, input_ids)
torch.testing.assert_close(actual.float(), expected, rtol=0.02, atol=5e-5)
def test_rocm_packed_kv_cache_auto_uses_ds_mla_layout() -> None:
from vllm.config import CacheConfig
from vllm.models.deepseek_v4.attention import _resolve_dsv4_kv_cache_dtype
+5 -5
View File
@@ -5,7 +5,7 @@
from typing import Any
import pytest
from transformers import AutoConfig, PretrainedConfig
from transformers import AutoConfig, PreTrainedConfig
from vllm.config.speculative import SpeculativeConfig
@@ -15,19 +15,19 @@ _CHECKPOINTS = {
}
def _mtp_config(model_type: str) -> PretrainedConfig:
def _mtp_config(model_type: str) -> PreTrainedConfig:
"""Create a top-level MTP configuration with mtp_num_hidden_layers."""
kwargs: dict[str, Any] = {
"model_type": model_type,
"architectures": ["SomeArch"],
"mtp_num_hidden_layers": 1,
}
return PretrainedConfig(**kwargs)
return PreTrainedConfig(**kwargs)
def _multimodal_wrapper_mtp_config(
model_type: str, mtp_layers: int = 1
) -> PretrainedConfig:
) -> PreTrainedConfig:
"""Download a multimodal wrapper config via AutoConfig.from_pretrained
and configure mtp_num_hidden_layers in text_config.
@@ -36,7 +36,7 @@ def _multimodal_wrapper_mtp_config(
- MoE (qwen3_5_moe): Qwen/Qwen3.6-35B-A3B
"""
repo = _CHECKPOINTS[model_type]
config: PretrainedConfig = AutoConfig.from_pretrained(repo)
config: PreTrainedConfig = AutoConfig.from_pretrained(repo)
text_config = config.get_text_config()
text_config.mtp_num_hidden_layers = mtp_layers
return config
+38 -40
View File
@@ -88,70 +88,68 @@ def test_registry_imports(model_arch):
assert supports_multimodal(model_cls)
@create_new_process_for_each_test()
@pytest.mark.parametrize(
"model_arch,is_mm,init_cuda,score_type",
"model_arch,is_mm,score_type",
[
("LlamaForCausalLM", False, False, "bi-encoder"),
("LlavaForConditionalGeneration", True, True, "bi-encoder"),
("DeepseekV41ForCausalLM", True, False, "bi-encoder"),
("BertForSequenceClassification", False, False, "cross-encoder"),
("RobertaForSequenceClassification", False, False, "cross-encoder"),
("XLMRobertaForSequenceClassification", False, False, "cross-encoder"),
("GteNewModel", False, False, "bi-encoder"),
("GteNewForSequenceClassification", False, False, "cross-encoder"),
("HF_ColBERT", False, False, "late-interaction"),
("LlamaForCausalLM", False, "bi-encoder"),
("LlavaForConditionalGeneration", True, "bi-encoder"),
("DeepseekV41ForCausalLM", True, "bi-encoder"),
("BertForSequenceClassification", False, "cross-encoder"),
("RobertaForSequenceClassification", False, "cross-encoder"),
("XLMRobertaForSequenceClassification", False, "cross-encoder"),
("GteNewModel", False, "bi-encoder"),
("GteNewForSequenceClassification", False, "cross-encoder"),
("HF_ColBERT", False, "late-interaction"),
],
)
def test_registry_model_property(model_arch, is_mm, init_cuda, score_type):
def test_registry_model_property(model_arch, is_mm, score_type):
model_info = ModelRegistry._try_inspect_model_cls(model_arch)
assert model_info is not None
assert model_info.supports_multimodal is is_mm
assert model_info.score_type == score_type
if init_cuda and current_platform.is_cuda_alike():
assert not torch.cuda.is_initialized()
ModelRegistry._try_load_model_cls(model_arch)
if not torch.cuda.is_initialized():
warnings.warn(
"This model no longer initializes CUDA on import. "
"Please test using a different one.",
stacklevel=2,
)
@create_new_process_for_each_test()
@pytest.mark.parametrize(
"model_arch,is_pp,init_cuda",
"model_arch,is_pp",
[
# TODO(woosuk): Re-enable this once the MLP Speculator is supported
# in V1.
# ("MLPSpeculatorPreTrainedModel", False, False),
("DeepseekV2ForCausalLM", True, False),
("Qwen2VLForConditionalGeneration", True, True),
# ("MLPSpeculatorPreTrainedModel", False),
("DeepseekV2ForCausalLM", True),
("Qwen2VLForConditionalGeneration", True),
],
)
def test_registry_is_pp(model_arch, is_pp, init_cuda):
def test_registry_is_pp(model_arch, is_pp):
model_info = ModelRegistry._try_inspect_model_cls(model_arch)
assert model_info is not None
assert model_info.supports_pp is is_pp
if init_cuda and current_platform.is_cuda_alike():
assert not torch.cuda.is_initialized()
ModelRegistry._try_load_model_cls(model_arch)
if not torch.cuda.is_initialized():
warnings.warn(
"This model no longer initializes CUDA on import. "
"Please test using a different one.",
stacklevel=2,
)
@create_new_process_for_each_test()
@pytest.mark.parametrize(
"model_arch",
["LlavaForConditionalGeneration", "Qwen2VLForConditionalGeneration"],
)
def test_registry_inspect_does_not_init_cuda(model_arch):
"""Inspecting a model must not import it: these architectures initialize
CUDA at import time, so the inspection path has to stay out-of-process."""
if not current_platform.is_cuda_alike():
pytest.skip("Requires a CUDA-like platform")
assert ModelRegistry._try_inspect_model_cls(model_arch) is not None
assert not torch.cuda.is_initialized()
ModelRegistry._try_load_model_cls(model_arch)
if not torch.cuda.is_initialized():
warnings.warn(
"This model no longer initializes CUDA on import. "
"Please test using a different one.",
stacklevel=2,
)
@pytest.mark.parametrize(
"model_arch,supported",
[
-60
View File
@@ -13,7 +13,6 @@ from vllm.distributed.parallel_state import (
initialize_model_parallel,
)
from vllm.model_executor.models.vision import (
FusedInputNorm,
get_load_balance_assignment,
resolve_visual_encoder_outputs,
run_dp_sharded_mrope_vision_model,
@@ -488,62 +487,3 @@ def test_simple_mrope_vision_model_spatial_merge(spatial_merge_size: int):
assert output.shape[0] == expected_output_patches
assert output.shape[1] == vision_model.out_hidden_size
def _reference_input_norm(
pixel_values: torch.Tensor,
image_mean: list[float],
image_std: list[float],
rescale_factor: float,
channel: int,
out_dtype: torch.dtype,
) -> torch.Tensor:
"""Straightforward per-channel affine: (x * rescale - mean) / std."""
patches, size = pixel_values.shape
patch_size = size // channel
mean = torch.tensor(image_mean, dtype=torch.float32).view(1, channel, 1)
std = torch.tensor(image_std, dtype=torch.float32).view(1, channel, 1)
x = pixel_values.to(torch.float32).view(patches, channel, patch_size)
x = (x * rescale_factor - mean) / std
return x.view(patches, size).to(out_dtype)
@pytest.mark.parametrize("num_patches", [1, 37, 70000])
def test_fused_input_norm_matches_reference(num_patches: int):
"""FusedInputNorm must equal the plain affine, including for num_patches
above the cuDNN batch-norm grid limit (~65535) that previously raised
CUDNN_STATUS_INTERNAL_ERROR (issue #51717)."""
channel = 3
patch_size = 14 * 14
image_mean = [0.48145466, 0.4578275, 0.40821073]
image_std = [0.26862954, 0.26130258, 0.27577711]
rescale_factor = 1.0 / 255.0
set_random_seed(0)
pixel_values = torch.randint(
0, 256, (num_patches, channel * patch_size), dtype=torch.float32
)
norm = FusedInputNorm(
image_mean=image_mean,
image_std=image_std,
rescale_factor=rescale_factor,
channel=channel,
)
assert not norm.is_identity
out = norm(pixel_values, visual_dtype=torch.float32)
expected = _reference_input_norm(
pixel_values, image_mean, image_std, rescale_factor, channel, torch.float32
)
torch.testing.assert_close(out, expected)
def test_fused_input_norm_identity_passthrough():
"""The identity configuration returns the input unchanged (cast only)."""
norm = FusedInputNorm.identity()
assert norm.is_identity
pixel_values = torch.randn(8, 3 * 196, dtype=torch.float32)
out = norm(pixel_values, visual_dtype=torch.bfloat16)
torch.testing.assert_close(out, pixel_values.to(torch.bfloat16))
@@ -50,6 +50,55 @@ class WeightlessRMSNorm(RMSNorm):
return self._rms(x.to(torch.float32)).to(x.dtype)
class Gemma4RMSNorm(RMSNorm):
"""`pow(v, -0.5)` where the others write `rsqrt(v)` (HF `Gemma4RMSNorm._norm`).
Gemma 4 spells the reciprocal square root as `torch.pow(..., -0.5)` to keep
Torch and JAX in agreement, and -- unlike Gemma 1-3 -- its weight is *not*
zero-centered, so this fuses to a plain `RMSNorm`.
"""
def _rms(self, x):
mean_squared = x.pow(2).mean(-1, keepdim=True) + self.variance_epsilon
return x * torch.pow(mean_squared, -0.5)
def forward(self, x):
return (self._rms(x.float()) * self.weight.float()).type_as(x)
class PowOperatorRMSNorm(Gemma4RMSNorm):
"""The `v ** -0.5` operator spelling of the same reciprocal square root."""
def _rms(self, x):
return x * (x.pow(2).mean(-1, keepdim=True) + self.variance_epsilon) ** -0.5
class KwargPowRMSNorm(Gemma4RMSNorm):
"""The keyword spelling `torch.pow(v, exponent=-0.5)` of the same rsqrt."""
def _rms(self, x):
mean_squared = x.pow(2).mean(-1, keepdim=True) + self.variance_epsilon
return x * torch.pow(mean_squared, exponent=-0.5)
class KwargBasePowRMSNorm(Gemma4RMSNorm):
"""The fully functional spelling `torch.pow(input=v, exponent=-0.5)`."""
def _rms(self, x):
mean_squared = x.pow(2).mean(-1, keepdim=True) + self.variance_epsilon
return x * torch.pow(input=mean_squared, exponent=-0.5)
class WeightlessGemma4RMSNorm(Gemma4RMSNorm):
"""Gemma 4 with `with_scale=False`: the `pow` spelling and no scale parameter."""
def __init__(self, hidden: int = 16, eps: float = 1e-6):
super().__init__(hidden, eps, weight=False)
def forward(self, x):
return self._rms(x.float()).type_as(x)
class LayerNorm(RMSNorm):
"""An RMSNorm not named `*RMSNorm`, keeping the input dtype (no upcast)."""
@@ -156,6 +205,11 @@ class UntraceableGatedRMSNorm(RMSNorm):
(RMSNorm, 1e-5, False),
(GemmaRMSNorm, 1e-6, True),
(WeightlessRMSNorm, 1e-6, False),
(Gemma4RMSNorm, 1e-6, False),
(PowOperatorRMSNorm, 1e-6, False),
(KwargPowRMSNorm, 1e-6, False),
(KwargBasePowRMSNorm, 1e-6, False),
(WeightlessGemma4RMSNorm, 1e-6, False),
(LayerNorm, 1e-6, False),
(torch.nn.RMSNorm, 1e-5, False), # fused `F.rms_norm` op
],
@@ -188,6 +242,10 @@ def test_gated_rms_norm_is_not_fused(cls):
(RMSNorm, "RMSNorm", False),
(GemmaRMSNorm, "GemmaRMSNorm", True),
(WeightlessRMSNorm, "RMSNorm", False),
(Gemma4RMSNorm, "RMSNorm", False),
(KwargPowRMSNorm, "RMSNorm", False),
(KwargBasePowRMSNorm, "RMSNorm", False),
(WeightlessGemma4RMSNorm, "RMSNorm", False),
],
)
def test_rms_norm_builds_vllm_class(cls, expected, zero_centered, default_vllm_config):
@@ -213,6 +271,25 @@ def test_rms_norm_builds_vllm_class(cls, expected, zero_centered, default_vllm_c
assert built.weight.shape[0] == (weight.size(0) if weight is not None else 0)
@pytest.mark.parametrize(
"cls", [Gemma4RMSNorm, PowOperatorRMSNorm, KwargPowRMSNorm, KwargBasePowRMSNorm]
)
def test_pow_spelled_norm_fuses_to_equivalent_math(cls, default_vllm_config):
"""Matching `pow(v, -0.5)` is only sound if it really is the reciprocal square
root: the fused norm must reproduce the unfused forward, not just replace it.
`pow` and `rsqrt` take different paths to the same value, so compare at float32
tolerance rather than bit-for-bit."""
torch.manual_seed(0)
module = cls(16)
with torch.no_grad():
module.weight.copy_(torch.randn(16))
built = get_fuser(module, RMSNormFuser).fuse(module, "norm", default_vllm_config)
with torch.no_grad():
built.weight.copy_(module.weight)
x = torch.randn(4, 16)
torch.testing.assert_close(built(x), module(x), rtol=1e-5, atol=1e-6)
def test_weightless_norm_has_no_hidden_size(default_vllm_config):
"""A weightless norm states no hidden size, and the model's (LM) hidden size
would be wrong for one on a sub-dimension: Llama 4's `qk_norm` normalizes
+2 -2
View File
@@ -13,7 +13,7 @@ from typing import Any
import pytest
import torch
import torch.nn as nn
from transformers import AutoConfig, AutoModel, PretrainedConfig
from transformers import AutoConfig, AutoModel, PreTrainedConfig
from vllm.config import ModelConfig, VllmConfig
from vllm.model_executor.models.interfaces import SupportsMultiModal
@@ -524,7 +524,7 @@ def replace_vocab_embeddings(model, **config_kwargs):
stub = nn.Module()
stub.model = model
stub.config = PretrainedConfig(
stub.config = PreTrainedConfig(
vocab_size=VOCAB_SIZE, num_positions=NUM_POSITIONS, **config_kwargs
)
embeddings = Base._vocab_embeddings(stub)
+3 -3
View File
@@ -8,7 +8,7 @@ from typing import Any
import torch
import torch.nn.functional as F
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config.model import AttnTypeStr, ModelConfig, ModelDType, RunnerOption
from vllm.config.pooler import SequencePoolingType, TokenPoolingType
@@ -446,12 +446,12 @@ def get_vllm_extra_kwargs(model_info: ModelInfo, vllm_extra_kwargs):
def dummy_hf_overrides(
hf_config: PretrainedConfig,
hf_config: PreTrainedConfig,
*,
model_arch: str = "",
exist_overrides: dict[str, Any] | None = None,
use_original_num_layers: bool = False,
) -> PretrainedConfig:
) -> PreTrainedConfig:
"""Dummy HF overrides function used to create dummy model
with only minimum nums of layer.
"""