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

Both sides edited the same import block in the Qwen4Exp NVIDIA and AMD
models and nothing else collided. This branch adds
`from ..common.mtp import make_mtp_hidden_buffer`, the helper the MTP
buffer extraction calls; upstream ec4a3a5370 widened the `..config`
import to `ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig` for the
layer-type constants it introduced. The two changes are independent, so
the resolution keeps both lines. Every symbol still has a use outside the
import in both files.

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-17 08:16:59 +09:00
1729 changed files with 15443 additions and 16090 deletions
+88
View File
@@ -934,3 +934,91 @@ def test_aligned_block_table_matches_shared_gdn():
)
torch.testing.assert_close(actual, expected)
def _build_non_spec(batch, is_prefilling, full_cuda_graph=False):
common_attn_metadata = create_common_attn_metadata(
batch, BLOCK_SIZE, DEVICE
).replace(
is_prefilling=None
if is_prefilling is None
else torch.tensor(is_prefilling, dtype=torch.bool)
)
builder = _make_builder(
KimiK3KDAMetadataBuilder,
num_speculative_tokens=0,
full_cuda_graph=full_cuda_graph,
)
return builder, common_attn_metadata, builder.build(0, common_attn_metadata)
def test_one_token_first_chunk_excludes_padding():
"""Neither padding requests nor padding tokens count as prefill work."""
common = create_common_attn_metadata(
BatchSpec(seq_lens=[100, 1, 0, 0], query_lens=[1, 1, 0, 0]),
BLOCK_SIZE,
DEVICE,
).replace(
is_prefilling=torch.tensor([False, True, False, False], dtype=torch.bool),
num_actual_tokens=4,
)
builder = _make_builder(
KimiK3KDAMetadataBuilder, num_speculative_tokens=0, full_cuda_graph=False
)
actual = builder.build(0, common)
assert actual.num_decodes == 1
assert actual.num_prefills == 1
assert actual.num_decode_tokens == 1
assert actual.num_prefill_tokens == 1
@pytest.mark.parametrize(
("seq_len", "query_len", "is_prefilling", "num_prefills"),
[
pytest.param(1, 1, True, 1, id="first-chunk"),
pytest.param(65, 1, True, 0, id="resumed-chunk"),
pytest.param(0, 0, True, 0, id="padding"),
pytest.param(1, 1, None, 0, id="missing-prefill-flag"),
],
)
def test_one_token_chunk_classification(
seq_len, query_len, is_prefilling, num_prefills
):
"""Only a real first chunk with a prefill flag needs state initialization."""
_, _, actual = _build_non_spec(
BatchSpec(seq_lens=[100, seq_len], query_lens=[1, query_len]),
is_prefilling=None if is_prefilling is None else [False, is_prefilling],
)
assert actual.num_prefills == num_prefills
assert actual.num_decodes == 2 - num_prefills
assert actual.num_prefill_tokens == num_prefills
assert actual.num_decode_tokens == 1 + query_len - num_prefills
if num_prefills:
assert actual.has_initial_state is not None
assert actual.has_initial_state.tolist() == [True, False]
else:
assert actual.has_initial_state is None
def test_cudagraph_capture_batch_stays_decode_only():
"""Capture rows have no history, but must still select decode kernels."""
batch = BatchSpec(seq_lens=[1] * 4, query_lens=[1] * 4)
common_attn_metadata = create_common_attn_metadata(
batch, BLOCK_SIZE, DEVICE
).replace(is_prefilling=torch.zeros(4, dtype=torch.bool))
builder = _make_builder(
KimiK3KDAMetadataBuilder,
num_speculative_tokens=0,
full_cuda_graph=True,
)
actual = builder.build_for_cudagraph_capture(common_attn_metadata)
assert actual.num_prefills == 0
assert actual.num_decodes == 4
assert actual.has_initial_state is None
staged = actual.non_spec_state_indices_tensor
assert staged is not None
assert staged.data_ptr() == builder.non_spec_state_indices_tensor.data_ptr()
torch.testing.assert_close(staged, common_attn_metadata.block_table_tensor[:, 0])
@@ -164,8 +164,7 @@ def test_chunked_prefill_with_parallel_sampling(
max_tokens: int,
conv_state_layout: str,
) -> None:
"""
Tests chunked prefill in conjunction with n > 1.
"""Tests chunked prefill in conjunction with n > 1.
In this case, prefill is populated with decoding tokens and
we test that it doesn't fail.
@@ -199,8 +198,7 @@ def test_mamba_cache_cg_padding(
max_tokens: int,
conv_state_layout: str,
) -> None:
"""
This test is for verifying that mamba cache is padded to CG captured
"""This test is for verifying that mamba cache is padded to CG captured
batch size. If it's not, a torch RuntimeError will be raised because
tensor dimensions aren't compatible.
"""
@@ -236,8 +234,7 @@ def test_fail_upon_inc_requests_and_finished_requests_lt_available_blocks(
example_prompts,
model: str,
) -> None:
"""
This test is for verifying that the hybrid inner state management doesn't
"""This test is for verifying that the hybrid inner state management doesn't
collapse in case where the number of incoming requests and
finished_requests_ids is larger than the maximum mamba block capacity.
@@ -263,8 +260,7 @@ def test_state_cleanup(
example_prompts,
model: str,
) -> None:
"""
This test is for verifying that the Hybrid state is cleaned up between
"""This test is for verifying that the Hybrid state is cleaned up between
steps.
If it's not cleaned, an error would be expected.
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Tests for max_tokens_per_doc and max_tokens_per_query.
"""
"""Tests for max_tokens_per_doc and max_tokens_per_query."""
import json
import os
@@ -23,11 +23,9 @@ NONINTERLEAVED_PROMPT = base_prompt("<image><image><video>\n")
@pytest.mark.parametrize("dtype", ["float16"])
@pytest.mark.parametrize("max_tokens", [128])
def test_models(vllm_runner, model, dtype: str, max_tokens: int) -> None:
"""
This is a simple test to check if interleaved and non-interleaved prompts
"""This is a simple test to check if interleaved and non-interleaved prompts
give the same result.
"""
image_cherry = convert_image_mode(ImageAsset("cherry_blossom").pil_image, "RGB")
image_stop = convert_image_mode(ImageAsset("stop_sign").pil_image, "RGB")
images = [image_cherry, image_stop]
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Create a reduced-layer version of the Maverick model for testing purposes.
"""Create a reduced-layer version of the Maverick model for testing purposes.
This script creates a new model with fewer layers by:
1. Loading the original Maverick model configuration
@@ -39,7 +38,6 @@ def run_maverick_serving(model: str):
"""Test Llama-4-Maverick model with vLLM LLM class using CLI equivalent
options with reduced layers.
"""
try:
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
@@ -71,8 +69,7 @@ def run_maverick_serving(model: str):
def get_rope_layers_config(model_path: str) -> list[int]:
"""
Get the interleaved RoPE configuration from HuggingFace config
"""Get the interleaved RoPE configuration from HuggingFace config.
Args:
model_path: Path to the local directory containing the reduced
@@ -81,6 +78,7 @@ def get_rope_layers_config(model_path: str) -> list[int]:
Returns:
List of 0 or 1 indicating whether each layer uses RoPE and local attn
0 indicates that RoPE is not used while 1 indicates that RoPE is used.
"""
config_path = Path(model_path) / "config.json"
model_config = json.loads(config_path.read_text())
@@ -98,8 +96,7 @@ def create_reduced_maverick_model(
vision_layers: int = 2,
force_recreate: bool = False,
) -> str:
"""
Create a reduced-layer version of the Maverick model.
"""Create a reduced-layer version of the Maverick model.
Args:
original_model_name: Name of the original Maverick model
@@ -111,8 +108,8 @@ def create_reduced_maverick_model(
Returns:
Path to the created reduced model directory
"""
"""
print(
f"Creating reduced Maverick model with {text_layers} text layers and "
f"{vision_layers} vision layers..."
@@ -178,7 +175,6 @@ def create_reduced_config(
original_config: Any, text_layers: int, num_experts: int, vision_layers: int
) -> dict[str, Any]:
"""Create a reduced configuration based on the original."""
# Convert config to dictionary
config_dict = original_config.to_dict()
@@ -220,7 +216,6 @@ def create_reduced_config(
def copy_tokenizer_files(original_model_name: str, output_path: Path) -> None:
"""Copy tokenizer files from the original model."""
try:
tokenizer = AutoTokenizer.from_pretrained(
original_model_name, trust_remote_code=True
@@ -233,7 +228,6 @@ def copy_tokenizer_files(original_model_name: str, output_path: Path) -> None:
def create_preprocessor_config(original_config: Any, output_path: Path) -> None:
"""Create preprocessor_config.json for multimodal model."""
# Try to load the original preprocessor config
try:
processor = AutoProcessor.from_pretrained(
@@ -253,7 +247,6 @@ def create_reduced_safetensors(
original_config: Any, reduced_config: dict[str, Any], output_path: Path
) -> None:
"""Create safetensors files with weights for the reduced model."""
print("Generating synthetic weights for reduced model...")
text_config = reduced_config["text_config"]
@@ -276,7 +269,6 @@ def create_reduced_safetensors(
def create_text_model_weights(text_config: dict[str, Any]) -> dict[str, torch.Tensor]:
"""Create synthetic weights for the text model with MoE structure."""
weights = {}
vocab_size = text_config["vocab_size"]
@@ -405,7 +397,6 @@ def create_vision_model_weights(
vision_config: dict[str, Any],
) -> dict[str, torch.Tensor]:
"""Create synthetic weights for the vision model."""
weights = {}
hidden_size = vision_config["hidden_size"]
@@ -473,8 +464,7 @@ def create_vision_model_weights(
def create_shared_weights(
text_config: dict[str, Any], vision_config: dict[str, Any]
) -> dict[str, torch.Tensor]:
"""Create weights for shared components (vision-language connector)"""
"""Create weights for shared components (vision-language connector)."""
weights = {}
text_hidden_size = text_config["hidden_size"]
@@ -492,7 +482,6 @@ def save_weights_to_safetensors(
weights: dict[str, torch.Tensor], output_path: Path
) -> None:
"""Save weights to safetensors files and create index."""
# Determine how to shard the weights
max_shard_size = 5 * 1024 * 1024 * 1024 # 5GB per shard
@@ -655,7 +644,6 @@ def test_dummy_maverick(
def main():
"""Main function to create and test the reduced model."""
import argparse
parser = argparse.ArgumentParser(
@@ -31,8 +31,7 @@ def mask_bbox_tokens(
output: tuple[list[int], str, SampleLogprobs],
tokenizer: TokenizerLike,
) -> tuple[list[int], str, SampleLogprobs]:
"""
Always pass check_logprobs_close check for bounding box tokens
"""Always pass check_logprobs_close check for bounding box tokens
because it is reasonable for them to differ slightly.
"""
ignore_pattern = r"<[xy]_[\d.]+>"
@@ -97,7 +97,7 @@ def batch_make_image_embeddings(
processor,
llm: VllmRunner,
) -> list[Qwen2VLPromptImageEmbeddingInput]:
"""batched image embeddings for Qwen2-VL
"""Batched image embeddings for Qwen2-VL.
This will infer all images' embeddings in a single batch,
and split the result according to input batches.
@@ -108,7 +108,6 @@ def batch_make_image_embeddings(
returns: `list[Qwen2VLPromptImageEmbeddingInput]`
"""
image_batches_: list[Any] = image_batches[:]
# convert single-image batches to multiple-image batches
@@ -183,7 +182,7 @@ def batch_make_image_embeddings(
def batch_make_video_embeddings(
video_batches: PromptVideoInput, processor, llm: VllmRunner
) -> list[Qwen2VLPromptVideoEmbeddingInput]:
"""batched video embeddings for Qwen2-VL
"""Batched video embeddings for Qwen2-VL.
A NDArray represents a single video's all frames.
@@ -194,7 +193,6 @@ def batch_make_video_embeddings(
- Single-video batches: `list[NDArray]`
- Multiple-video batches: `list[list[NDArray]]`
"""
video_batches_: list[Any] = video_batches[:]
for idx in range(len(video_batches_)):
@@ -204,7 +204,6 @@ def test_variable_length_audio_batching(
@pytest.mark.asyncio
async def test_online_serving(client, audio_assets: AudioTestAssets):
"""Exercises online serving with/without chunked prefill enabled."""
messages = [
{
"role": "user",
@@ -78,7 +78,6 @@ def test_online_serving(vllm_runner, audio_assets: AudioTestAssets):
Steps run sequentially so each releases the GPU before the next starts.
"""
question = f"What's happening in these {len(audio_assets)} audio clips?"
max_tokens = 10
audio_data = [asset.audio_and_sample_rate for asset in audio_assets]
@@ -156,6 +156,7 @@ def get_wrapped_test_sizes(
Args:
test_info: Test configuration to be expanded.
test_type: The type of test being filtered for.
"""
# If it is an embedding test, we always use the EMBEDDING_SIZE_FACTORS
if test_type == VLMTestType.EMBEDDING:
@@ -200,7 +200,7 @@ def process_runner_outputs(
def process_outputs(output_processor, model, outputs_per_image):
"""Applies a model specific post-processor function to a runner's output"""
"""Applies a model specific post-processor function to a runner's output."""
return [
[output_processor(res, model) for res in outputs]
for outputs in outputs_per_image
@@ -22,6 +22,7 @@ def multi_image_multi_aspect_ratio_inputs(formatter: Callable[[str], str]):
Args:
formatter: model-specific prompt formatter.
"""
stop_sign = IMAGE_ASSETS[0].pil_image
cherry_blossom = IMAGE_ASSETS[1].pil_image
@@ -65,6 +66,7 @@ def multi_video_multi_aspect_ratio_inputs(
Args:
formatter: model-specific prompt formatter.
"""
video = sample_frames_from_video(VIDEO_ASSETS[0].np_ndarrays, num_frames)
# Apply the selected formatter to the base prompts
@@ -252,6 +252,7 @@ def qwen_prompt_path_encoder(
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.
@@ -507,15 +508,12 @@ def isaac_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
2) Ensure IsaacModel.forward returns hidden_states
for compatibility with hidden_states_to_seq_logprobs()
"""
from perceptron.tensorstream import TextType
from perceptron.tensorstream.ops import compute_mrope_pos_tensor, modality_mask
from transformers.modeling_outputs import BaseModelOutputWithPast
def compute_position_ids_input_ids(input_ids: torch.Tensor) -> torch.Tensor:
"""
Create 3D positional indices for token input.
"""
"""Create 3D positional indices for token input."""
batch_size, seq_length = input_ids.shape
position_ids = torch.arange(seq_length, device=input_ids.device)
position_ids = position_ids.view(1, -1).expand(batch_size, -1)
@@ -570,8 +568,7 @@ def isaac_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
cache_position=None,
**kwargs,
):
"""
Forward pass with MRoPE position embeddings.
"""Forward pass with MRoPE position embeddings.
Computes position embeddings once and passes them through all layers.
"""
output_hidden_states = (
@@ -1184,7 +1181,6 @@ def voxtral_patch_hf_runner(hf_model: "HfRunner") -> "HfRunner":
HfRunner.generate calls batch_decode on the full sequence (prompt +
generated).
"""
import io
import pybase64 as base64
@@ -87,7 +87,7 @@ def _run_test(
*,
dtype: str,
) -> None:
"""SET PYTHONPATH"""
"""SET PYTHONPATH."""
# NOTE: take care of the order. run vLLM first, and then run HF.
# vLLM needs a fresh new process without cuda initialization.
# if we run HF first, the cuda initialization will be done and it
@@ -108,8 +108,7 @@ def _normalize_image(image_val: str) -> str:
def create_score_multimodal_param(
content_parts: list[dict],
) -> list[ScoreMultiModalParam]:
"""
Create a ScoreMultiModalParam from a list of content dictionaries.
"""Create a ScoreMultiModalParam from a list of content dictionaries.
Each dict supports the following formats:
- Text: {'text': 'content'}
@@ -257,7 +256,7 @@ def test_model_text_image(
model: str,
dtype: str,
) -> None:
"""Visual Documents Reranking"""
"""Visual Documents Reranking."""
_run_test(
hf_runner,
vllm_runner,
@@ -280,7 +279,7 @@ def test_model_text_text(
model: str,
dtype: str,
) -> None:
"""Textual Documents Reranking"""
"""Textual Documents Reranking."""
_run_test(
hf_runner,
vllm_runner,
@@ -303,7 +302,7 @@ def test_model_image_text(
model: str,
dtype: str,
) -> None:
"""Image Querying for Textual Documents"""
"""Image Querying for Textual Documents."""
_run_test(
hf_runner,
vllm_runner,
@@ -326,7 +325,7 @@ def test_model_image_image(
model: str,
dtype: str,
) -> None:
"""Image Querying for Image Documents"""
"""Image Querying for Image Documents."""
_run_test(
hf_runner,
vllm_runner,
@@ -349,7 +348,7 @@ def test_model_text_mixed_documents(
model: str,
dtype: str,
) -> None:
"""Text Query for Mixed Text and Image Documents"""
"""Text Query for Mixed Text and Image Documents."""
_run_test(
hf_runner,
vllm_runner,
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Tests for the LlamaNemotronVL model family:
"""Tests for the LlamaNemotronVL model family:
- nvidia/llama-nemotron-embed-vl-1b-v2 (LlamaNemotronVLForCausalLM / embed)
- nvidia/llama-nemotron-rerank-vl-1b-v2
(LlamaNemotronVLForSequenceClassification / rerank)
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Regression tests for Qwen2.5-Omni and Qwen3-Omni audio-in-video processor
"""Regression tests for Qwen2.5-Omni and Qwen3-Omni audio-in-video processor
caching.
Tests the use_audio_in_video feature where audio is extracted from video and
@@ -50,8 +49,7 @@ def create_mm_data(num_videos: int) -> dict[str, list]:
@pytest.mark.parametrize("model_id", MODELS)
@pytest.mark.parametrize("num_videos", [1, 2])
def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> None:
"""
Regression test for https://github.com/vllm-project/vllm/pull/36800
"""Regression test for https://github.com/vllm-project/vllm/pull/36800.
MultiModalProcessorSenderCache.get_and_update_item returns (None, updates)
on a cache hit, so mm_kwargs["video"] items become None on the second call.
@@ -117,8 +115,7 @@ def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> Non
@pytest.mark.parametrize("model_id", MODELS)
def test_use_audio_in_video_without_audio_track(model_id: str) -> None:
"""
A video with no audio track, combined with `use_audio_in_video=True`,
"""A video with no audio track, combined with `use_audio_in_video=True`,
must raise a clear `ValueError` naming the mismatch, rather than an
opaque `StopIteration`-derived error from the underlying HF processor.
"""
@@ -33,9 +33,7 @@ from ...registry import (
def add_video_metadata(mm_data: MultiModalDataDict) -> MultiModalDataDict:
"""
Add metadata to video mm_data
"""
"""Add metadata to video mm_data."""
def create_metadata(frames: np.ndarray):
num_frames = len(frames)
@@ -61,8 +59,7 @@ def add_video_metadata(mm_data: MultiModalDataDict) -> MultiModalDataDict:
def glmasr_patch_mm_data(mm_data: MultiModalDataDict) -> MultiModalDataDict:
"""
Patch the multimodal data for GLM-ASR model.
"""Patch the multimodal data for GLM-ASR model.
GLM-ASR requires text and audio to match 1:1, so we limit audio to 1.
"""
if "audio" in mm_data:
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Regression test for DeepSeek-OCR TensorSchema validation with empty images_crop.
"""Regression test for DeepSeek-OCR TensorSchema validation with empty images_crop.
When using the Gundam preset (BASE_SIZE=1024, IMAGE_SIZE=640, CROP_MODE=True),
images that are small enough to not require cropping produce an empty
@@ -152,8 +152,7 @@ def test_video_loader_consistency(
fps: int,
backend: str,
):
"""
Ensure dynamic video loader (pre-sampled by loader) and normal video
"""Ensure dynamic video loader (pre-sampled by loader) and normal video
loader (post-sampled by processor) produce same video processing outputs.
"""
ctx = build_model_context(
@@ -116,8 +116,7 @@ def _test_image_prompt_replacements(
num_imgs: int,
image_sizes: list[ImageSize],
) -> None:
"""
Ensure LlavaNextMultiModalProcessor
"""Ensure LlavaNextMultiModalProcessor
handles prompt replacement properly for input images.
"""
failed_size_excs = list[tuple[ImageSize, Exception]]()
@@ -122,8 +122,7 @@ def _test_image_prompt_replacements(
num_imgs: int,
image_sizes: list[ImageSize],
) -> None:
"""
Ensure LlavaOnevisionMultiModalProcessor
"""Ensure LlavaOnevisionMultiModalProcessor
handles prompt replacement properly for input images.
"""
failed_size_excs = list[tuple[ImageSize, Exception]]()
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Unit tests for Qwen2.5-Omni embed_input_ids to verify embeddings are
"""Unit tests for Qwen2.5-Omni embed_input_ids to verify embeddings are
correctly assigned to audio/image/video token positions.
Regression test for: https://github.com/vllm-project/vllm/issues/34506
@@ -40,8 +39,7 @@ def _mm_embed(shape: tuple[int, ...], value: float, modality: str) -> torch.Tens
def make_token_seq(
audio_n: int, image_n: int, video_n: int, text_prefix: int = 3, text_sep: int = 2
):
"""
Build a flat token sequence:
"""Build a flat token sequence:
[text_prefix] [AUDIO * audio_n] [text_sep] [IMAGE * image_n]
[text_sep] [VIDEO * video_n] [text_sep]
Returns (input_ids tensor, is_multimodal mask, positions dict).
@@ -67,9 +65,8 @@ def make_token_seq(
def make_interleaved_seq(
video_chunks: list[int], audio_chunks: list[int], text_prefix: int = 2
):
"""
Build an interleaved sequence like use_audio_in_video:
[text] [V*v0] [A*a0] [V*v1] [A*a1] ...
"""Build an interleaved sequence like use_audio_in_video:
[text] [V*v0] [A*a0] [V*v1] [A*a1] ...
"""
tokens = [TEXT_TOKEN_ID] * text_prefix
for v, a in zip(video_chunks, audio_chunks):
@@ -140,8 +137,7 @@ class TestCheckInterleavedAudioVideo:
)
def test_batched_non_interleaved_no_false_positive(self):
"""
Regression test for https://github.com/vllm-project/vllm/issues/35394.
"""Regression test for https://github.com/vllm-project/vllm/issues/35394.
5 identical non-interleaved mixed-modality requests batched together:
each has [audio][image][video] in separate blocks with text between them.
@@ -172,8 +168,7 @@ class TestCheckInterleavedAudioVideo:
def make_mock_model(hidden: int = 8):
"""
Return a minimal mock of Qwen2_5OmniThinkerForConditionalGeneration
"""Return a minimal mock of Qwen2_5OmniThinkerForConditionalGeneration
that has enough structure to run embed_input_ids.
"""
from vllm.model_executor.models.qwen2_5_omni_thinker import (
@@ -236,8 +231,7 @@ def make_mock_model(hidden: int = 8):
def build_mm_embeds(
audio_n, image_n, video_n, hidden, audio_val=10.0, image_val=20.0, video_val=30.0
):
"""
Build multimodal_embeddings list in position order (audio, image, video).
"""Build multimodal_embeddings list in position order (audio, image, video).
Each embedding is filled with a distinct constant so we can verify placement.
"""
embs = []
@@ -252,8 +246,7 @@ def build_mm_embeds(
class TestEmbedInputIds:
def _run(self, audio_n, image_n, video_n, hidden=8):
"""
Run embed_input_ids for a non-interleaved mixed-modality sequence.
"""Run embed_input_ids for a non-interleaved mixed-modality sequence.
Returns (result_embeds, input_ids, is_multimodal).
"""
input_ids, is_multimodal = make_token_seq(audio_n, image_n, video_n)
@@ -288,8 +281,7 @@ class TestEmbedInputIds:
)
def test_mixed_modalities_audio_goes_to_audio_pos(self):
"""
Regression test for GitHub issue #34506:
"""Regression test for GitHub issue #34506:
With audio + image + video (non-interleaved), audio positions must
receive audio embeddings (not image or video embeddings).
"""
@@ -329,8 +321,7 @@ class TestEmbedInputIds:
)
def test_interleaved_use_audio_in_video(self):
"""
Interleaved (use_audio_in_video): video chunks interleaved with audio.
"""Interleaved (use_audio_in_video): video chunks interleaved with audio.
Video embeddings must go to video positions, audio to audio positions.
"""
hidden = 8
@@ -232,7 +232,6 @@ def test_mm_device_do_normalize(
num_imgs: int,
):
"""Ensure that enable mm_device_do_normalize yields the correct result."""
ctx = build_model_context(
model_id,
limit_mm_per_prompt={"image": num_imgs},
@@ -25,8 +25,7 @@ def test_processor_with_audio_sample_rate(
audio_sample_rate: int,
audio_duration_sec: float,
) -> None:
"""
Test that vLLM's processor generates expected outputs with audio_sample_rate.
"""Test that vLLM's processor generates expected outputs with audio_sample_rate.
This validates that the processor correctly handles audio_sample_rate
passed via hf_processor_mm_kwargs and generates audio tokens.
@@ -70,8 +69,7 @@ def test_processor_with_audio_sample_rate(
@pytest.mark.parametrize("model_id", ["Qwen/Qwen3-Omni-30B-A3B-Instruct"])
def test_longer_audio_generates_more_tokens(model_id: str) -> None:
"""
Test that longer audio generates more tokens than shorter audio.
"""Test that longer audio generates more tokens than shorter audio.
This validates that audio_sample_rate is being used correctly by checking
that audio duration affects token count as expected.
+3 -7
View File
@@ -215,7 +215,7 @@ def test_bailing_vl_mapper_handles_module_and_parameter_names():
def create_repo_dummy_weights(repo: str) -> Iterable[tuple[str, torch.Tensor]]:
"""Create weights from safetensors checkpoint metadata"""
"""Create weights from safetensors checkpoint metadata."""
metadata = try_get_safetensors_metadata(repo)
weight_names = list(metadata.weight_map.keys())
with torch.device("meta"):
@@ -223,9 +223,7 @@ def create_repo_dummy_weights(repo: str) -> Iterable[tuple[str, torch.Tensor]]:
def create_dummy_base_model(repo: str, model_arch: str) -> PreTrainedModel:
"""
Create weights from a dummy meta deserialized hf base model with name conversion
"""
"""Create weights from a dummy meta-deserialized HF base model, with renaming."""
config = AutoConfig.from_pretrained(repo)
with torch.device("meta"):
model = AutoModel.from_config(config)
@@ -233,9 +231,7 @@ def create_dummy_base_model(repo: str, model_arch: str) -> PreTrainedModel:
def create_dummy_model(repo: str, model_arch: str) -> PreTrainedModel:
"""
Create weights from a dummy meta deserialized hf model with name conversion
"""
"""Create weights from a dummy meta deserialized hf model with name conversion."""
model_cls: PreTrainedModel = getattr(transformers, model_arch)
config = AutoConfig.from_pretrained(repo)
with torch.device("meta"):
+2 -4
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
End-to-end accuracy test for GPT-OSS model quantization.
"""End-to-end accuracy test for GPT-OSS model quantization.
Config:
Task: gsm8k_platinum
@@ -170,8 +169,7 @@ def test_aiter_mxfp4_moe_ignores_padded_rows(
monkeypatch: pytest.MonkeyPatch,
dist_init,
) -> None:
"""
Garbage in cudagraph padding rows must not reach the unpadded outputs.
"""Garbage in cudagraph padding rows must not reach the unpadded outputs.
A cudagraph replay of a size-`TOKENS_PADDED` graph driven by
`TOKENS_UNPADDED` real tokens leaves the trailing padding row containing
+57 -18
View File
@@ -203,7 +203,14 @@ def _qsa_sparse_paged_attention_reference(
block_table: torch.Tensor,
token_to_req: torch.Tensor,
softmax_scale: float,
k_scale: float = 1.0,
v_scale: float = 1.0,
) -> torch.Tensor:
"""Dense reference for QSA sparse paged attention.
Mirrors the kernel's dequant: fp8-e4m3 K/V caches are dequantized with the
per-tensor k_scale/v_scale host floats; bf16 caches use unit scales.
"""
output = torch.zeros_like(q)
repeats = q.shape[1] // k_cache.shape[2]
page_size = k_cache.shape[1]
@@ -215,13 +222,15 @@ def _qsa_sparse_paged_attention_reference(
request = token_to_req[row].long()
pages = block_table[request, logical // page_size].long()
offsets = logical % page_size
keys = k_cache[pages, offsets].repeat_interleave(repeats, dim=1)
values = v_cache[pages, offsets].repeat_interleave(repeats, dim=1)
scores = torch.einsum("hd,khd->hk", q[row].float(), keys.float())
probabilities = torch.softmax(scores * softmax_scale, dim=-1)
output[row] = torch.einsum("hk,khd->hd", probabilities, values.float()).to(
q.dtype
keys = (k_cache[pages, offsets].float() * k_scale).repeat_interleave(
repeats, dim=1
)
values = (v_cache[pages, offsets].float() * v_scale).repeat_interleave(
repeats, dim=1
)
scores = torch.einsum("hd,khd->hk", q[row].float(), keys)
probabilities = torch.softmax(scores * softmax_scale, dim=-1)
output[row] = torch.einsum("hk,khd->hd", probabilities, values).to(q.dtype)
return output
@@ -906,22 +915,28 @@ def test_qsa_block_expansion_correctness() -> None:
"page_size",
"use_prefill_config",
"num_requests",
"fp8",
),
[
# Production page sizes from hybrid-cache block alignment: 784/800
# at TP4 and 1568/1600 at TP1/TP2 (no-MTP / MTP num_spec=3). Head
# splits are per-rank TP1/TP2/TP4; the largest batch runs both
# use_prefill_config variants.
pytest.param(1, 24, 2, 1600, True, 2, id="tp1_r1"),
pytest.param(16, 12, 1, 1600, True, 3, id="tp2_r16"),
pytest.param(32, 6, 1, 800, True, 5, id="tp4_r32"),
pytest.param(128, 24, 2, 1568, True, 7, id="tp1_r128"),
pytest.param(257, 6, 1, 800, True, 13, id="tp4_r257"),
pytest.param(513, 6, 1, 784, True, 17, id="tp4_r513"),
pytest.param(700, 6, 1, 800, True, 23, id="tp4_r700"),
pytest.param(1024, 24, 2, 1600, True, 33, id="tp1_r1024"),
pytest.param(2048, 24, 2, 1600, True, 63, id="tp1_r2048_prefill"),
pytest.param(2048, 24, 2, 1600, False, 63, id="tp1_r2048_uniform"),
pytest.param(1, 24, 2, 1600, True, 2, False, id="tp1_r1"),
pytest.param(16, 12, 1, 1600, True, 3, False, id="tp2_r16"),
pytest.param(32, 6, 1, 800, True, 5, False, id="tp4_r32"),
pytest.param(128, 24, 2, 1568, True, 7, False, id="tp1_r128"),
pytest.param(257, 6, 1, 800, True, 13, False, id="tp4_r257"),
pytest.param(513, 6, 1, 784, True, 17, False, id="tp4_r513"),
pytest.param(700, 6, 1, 800, True, 23, False, id="tp4_r700"),
pytest.param(1024, 24, 2, 1600, True, 33, False, id="tp1_r1024"),
pytest.param(2048, 24, 2, 1600, True, 63, False, id="tp1_r2048_prefill"),
pytest.param(2048, 24, 2, 1600, False, 63, False, id="tp1_r2048_uniform"),
# fp8_e4m3 K/V caches on the TP1 head split.
pytest.param(1, 24, 2, 1600, True, 2, True, id="tp1_r1_fp8"),
pytest.param(128, 24, 2, 1568, True, 7, True, id="tp1_r128_fp8"),
pytest.param(2048, 24, 2, 1600, True, 63, True, id="tp1_r2048_prefill_fp8"),
pytest.param(2048, 24, 2, 1600, False, 63, True, id="tp1_r2048_uniform_fp8"),
],
)
def test_qsa_sparse_paged_attention_correctness(
@@ -931,8 +946,18 @@ def test_qsa_sparse_paged_attention_correctness(
page_size: int,
use_prefill_config: bool,
num_requests: int,
fp8: bool,
) -> None:
"""QSA sparse paged attention matches the dense reference.
fp8 only changes the K/V cache dtype (e4m3 with a per-tensor scale pair) and
the scales; the reference dequantizes the same cache with those scales, so
both paths compare the production kernel against the reference on identical
inputs. fp8=True additionally covers the host-side scale folding.
"""
torch.manual_seed(2)
# One QSA attention problem: bf16 Q and paged K/V, a packed selection with
# the trailing count column, block table and row-to-request map.
head_dim = 256
num_selected_pages = 64
# Keep the newest page outside the synthetic top-k as causal headroom.
@@ -1013,8 +1038,18 @@ def test_qsa_sparse_paged_attention_correctness(
indexer_budget,
logical_indices,
)
assert logical_indices.shape == (num_rows, selection_width + 1)
scale = q.shape[-1] ** -0.5
scale = head_dim**-0.5
if fp8:
# A fixed non-unit pair (k != v) exercises the host-side scale folding
# and catches a k/v swap; scales are host floats, as the layer exposes
# them. Stored values are the scaled ones, as reshape_and_cache does.
k_scale, v_scale = 0.5, 2.0
k_cache = (k_cache / k_scale).to(torch.float8_e4m3fn)
v_cache = (v_cache / v_scale).to(torch.float8_e4m3fn)
else:
k_scale, v_scale = 1.0, 1.0
actual = qsa_ops.qsa_sparse_paged_attention(
q,
@@ -1024,6 +1059,8 @@ def test_qsa_sparse_paged_attention_correctness(
block_table,
token_to_req,
use_prefill_config=use_prefill_config,
k_scale=k_scale,
v_scale=v_scale,
output_gate=output_gate,
)
expected = _qsa_sparse_paged_attention_reference(
@@ -1034,6 +1071,8 @@ def test_qsa_sparse_paged_attention_correctness(
block_table,
token_to_req,
scale,
k_scale=k_scale,
v_scale=v_scale,
)
expected = expected * torch.sigmoid(output_gate)
+2 -5
View File
@@ -127,8 +127,7 @@ class _HfExamplesInfo:
check_min_version: bool = True,
check_max_version: bool = True,
) -> str | None:
"""
If the installed transformers version does not meet the requirements,
"""If the installed transformers version does not meet the requirements,
perform the given action.
"""
if (
@@ -185,9 +184,7 @@ class _HfExamplesInfo:
*,
on_fail: Literal["error", "skip"],
) -> None:
"""
If the model is not available online, perform the given action.
"""
"""If the model is not available online, perform the given action."""
if not self.is_available_online:
msg = "Model is not available online"
+1 -1
View File
@@ -118,7 +118,7 @@ def test_fi_moe_ep_backend_accepted_for_dsv4(moe_backend):
[["KimiK3ForConditionalGeneration"], ["MixtralForCausalLM"]],
)
def test_native_deep_gemm_mega_moe_not_arch_gated(architectures):
"""vLLM's own deep_gemm mega path is not DSv4-only (Kimi K3 uses it);
"""VLLM's own deep_gemm mega path is not DSv4-only (Kimi K3 uses it);
models validate their own constraints at construction time."""
validate_flashinfer_moe_ep_model("deep_gemm_mega_moe", architectures)
+37 -92
View File
@@ -300,8 +300,10 @@ def test_deepseek_v4_mega_moe_weight_loader_uses_ep_expert_ownership():
@pytest.mark.parametrize("intermediate_size", [512, 2304])
def test_deepseek_v4_mega_moe_padding_preserves_weights(monkeypatch, intermediate_size):
"""Pad gate/up separately and zero every added down-projection column."""
def test_deepseek_v4_mega_moe_preserves_checkpoint_dimensions(
monkeypatch, intermediate_size
):
"""Keep native widths so V4.1 routed and shared experts can fuse."""
experts = DeepseekV4MegaMoEExperts(
SimpleNamespace(
scheduler_config=SimpleNamespace(max_num_batched_tokens=4),
@@ -333,29 +335,15 @@ def test_deepseek_v4_mega_moe_padding_preserves_weights(monkeypatch, intermediat
)
experts.finalize_weights()
padded_size = experts.intermediate_size
assert padded_size == (intermediate_size + 511) // 512 * 512
for actual, original in zip(experts._transformed_l1_weights, originals[:2]):
assert experts.intermediate_size == intermediate_size
transformed = (*experts._transformed_l1_weights, *experts._transformed_l2_weights)
for actual, original in zip(transformed, originals):
expected = (
original
if actual.dtype == torch.int8
else (experts._ue8m0_uint8_to_float(original))
else experts._ue8m0_uint8_to_float(original)
)
actual = actual.view(expected.dtype).unflatten(1, (2, padded_size))
assert torch.equal(
actual[:, :, :intermediate_size],
expected.unflatten(1, (2, intermediate_size)),
)
assert torch.count_nonzero(actual[:, :, intermediate_size:]) == 0
for actual, original in zip(experts._transformed_l2_weights, originals[2:]):
expected = (
original
if actual.dtype == torch.int8
else (experts._ue8m0_uint8_to_float(original))
)
actual = actual.view(expected.dtype)
assert torch.equal(actual[..., : original.shape[-1]], expected)
assert torch.count_nonzero(actual[..., original.shape[-1] :]) == 0
assert torch.equal(actual.view(expected.dtype), expected)
transformed_l1 = experts._transformed_l1_weights
experts.finalize_weights()
@@ -363,20 +351,19 @@ def test_deepseek_v4_mega_moe_padding_preserves_weights(monkeypatch, intermediat
@pytest.mark.parametrize(
"hidden_size,intermediate_size,block_size,fused,mxfp8",
"hidden_size,intermediate_size,block_size,mxfp8",
[
pytest.param(128, 512, 128, True, False, id="aligned-block128"),
pytest.param(128, 512, 128, True, True, id="aligned-block128-mxfp8"),
pytest.param(5120, 2304, 32, True, False, id="deepseek-v41-flash"),
pytest.param(128, 2304, 128, True, False, id="padded-block128"),
pytest.param(5120, 2304, 32, True, True, id="deepseek-v41-flash-mxfp8"),
pytest.param(128, 2304, 128, False, False, id="padded-packed-scale-fallback"),
pytest.param(128, 512, 128, False, id="aligned-block128"),
pytest.param(128, 512, 128, True, id="aligned-block128-mxfp8"),
pytest.param(5120, 2304, 32, False, id="deepseek-v41-flash"),
pytest.param(128, 2304, 128, False, id="native-block128"),
pytest.param(5120, 2304, 32, True, id="deepseek-v41-flash-mxfp8"),
],
)
def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
monkeypatch, hidden_size, intermediate_size, block_size, fused, mxfp8
monkeypatch, hidden_size, intermediate_size, block_size, mxfp8
):
"""Shared fusion preserves checkpoint channels and zeros padded channels."""
"""Shared fusion preserves checkpoint weights and scales at native widths."""
class FakeDeepGemm:
transformed_dims: list[tuple[int, int]] = []
@@ -476,12 +463,6 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
originals = []
for linear in (shared_experts.gate_up_proj, shared_experts.down_proj):
scale = linear.weight_scale if mxfp8 else linear.weight_scale_inv
if not fused:
# Already packed scales cannot be padded as checkpoint UE8M0 bytes.
linear.weight_scale_inv = scale_parameter(
linear.weight.shape[0], linear.weight.shape[1] // 128
)
continue
scale.data.view(torch.uint8).random_(124, 130)
block_m, block_k = linear.weight_block_size
scale_1x32 = (
@@ -493,70 +474,34 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
monkeypatch.setattr("vllm.utils.deep_gemm._import_deep_gemm", lambda: FakeDeepGemm)
original_gate_up_ptr = shared_experts.gate_up_proj.weight.data_ptr()
original_down_ptr = shared_experts.down_proj.weight.data_ptr()
experts.finalize_weights(shared_experts)
assert experts.has_fused_shared_experts is fused
if not fused:
assert experts.intermediate_size == 2560
assert FakeDeepGemm.transformed_dims == [(3, 3)]
assert experts.num_shared_experts == 0
assert shared_experts.gate_up_proj.weight.data_ptr() == original_gate_up_ptr
assert shared_experts.down_proj.weight.data_ptr() == original_down_ptr
assert shared_experts.gate_up_proj.weight.shape == (
2 * intermediate_size,
hidden_size,
)
assert shared_experts.down_proj.weight.shape == (hidden_size, intermediate_size)
return
assert experts.has_fused_shared_experts
assert experts.intermediate_size == intermediate_size
assert FakeDeepGemm.transformed_dims == [(3, 3), (2, 2)]
padded_size = experts.intermediate_size
assert FakeDeepGemm.scale_inputs[-2:] == [
(1, 2 * padded_size, hidden_size // 32),
(1, hidden_size, padded_size // 32),
(1, 2 * intermediate_size, hidden_size // 32),
(1, hidden_size, intermediate_size // 32),
]
for actual, original, fill in (
for transformed, actual_scale, (weight, scale) in zip(
(
experts._transformed_shared_l1_weights[0].view(torch.uint8),
originals[0][0],
0,
experts._transformed_shared_l1_weights,
experts._transformed_shared_l2_weights,
),
(FakeDeepGemm.scale_values[-2][0], originals[0][1], 1),
FakeDeepGemm.scale_values[-2:],
originals,
):
actual = actual.unflatten(0, (2, padded_size))
assert torch.equal(
actual[:, :intermediate_size], original.unflatten(0, (2, intermediate_size))
)
assert torch.all(actual[:, intermediate_size:] == fill)
for actual, original, fill in (
(
experts._transformed_shared_l2_weights[0].view(torch.uint8),
originals[1][0],
0,
),
(FakeDeepGemm.scale_values[-1][0], originals[1][1], 1),
):
assert torch.equal(actual[:, : original.shape[1]], original)
assert torch.all(actual[:, original.shape[1] :] == fill)
if padded_size != intermediate_size:
# Generic linear post-load hooks still receive checkpoint-shaped weights.
for linear, (weight, _) in zip(
(shared_experts.gate_up_proj, shared_experts.down_proj), originals
):
assert torch.equal(linear.weight.view(torch.uint8), weight)
assert shared_experts.gate_up_proj.weight.data_ptr() == original_gate_up_ptr
assert shared_experts.down_proj.weight.data_ptr() == original_down_ptr
else:
assert shared_experts.gate_up_proj.weight.data_ptr() != original_gate_up_ptr
assert (
experts._transformed_shared_l1_weights[0].data_ptr()
== shared_experts.gate_up_proj.weight.data_ptr()
)
assert (
experts._transformed_shared_l2_weights[0].data_ptr()
== shared_experts.down_proj.weight.data_ptr()
)
assert torch.equal(transformed[0].view(torch.uint8), weight)
assert torch.equal(actual_scale[0], scale)
assert shared_experts.gate_up_proj.weight.data_ptr() != original_gate_up_ptr
assert (
experts._transformed_shared_l1_weights[0].data_ptr()
== shared_experts.gate_up_proj.weight.data_ptr()
)
assert (
experts._transformed_shared_l2_weights[0].data_ptr()
== shared_experts.down_proj.weight.data_ptr()
)
transformed_l1 = experts._transformed_shared_l1_weights
experts.finalize_weights(shared_experts)
-125
View File
@@ -15,131 +15,6 @@ pytestmark = pytest.mark.skipif(
)
def _preshuffled_fp8_linear(
holder: str = "quant_method", weight_shape: tuple[int, int] = (256, 128)
) -> nn.Module:
pytest.importorskip("aiter")
from vllm.model_executor.kernels.linear.scaled_mm.aiter import (
AiterPreshuffledFp8BlockScaledMMKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.ScaledMMLinearKernel import (
FP8ScaledMMLinearLayerConfig,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8Dynamic128Sym,
kFp8Static128BlockSym,
)
config = FP8ScaledMMLinearLayerConfig(
weight_quant_key=kFp8Static128BlockSym,
activation_quant_key=kFp8Dynamic128Sym,
input_dtype=torch.bfloat16,
out_dtype=torch.bfloat16,
weight_shape=weight_shape,
)
layer = nn.Module()
layer.weight = nn.Parameter(
torch.randn(*weight_shape, device="cuda").to(current_platform.fp8_dtype()),
requires_grad=False,
)
layer.register_parameter(
"weight_scale" if holder == "scheme" else "weight_scale_inv",
nn.Parameter(
torch.ones(*(dim // 128 for dim in weight_shape), device="cuda"),
requires_grad=False,
),
)
setattr(
layer,
holder,
SimpleNamespace(fp8_linear=AiterPreshuffledFp8BlockScaledMMKernel(config)),
)
return layer
@pytest.mark.parametrize("holder", ["quant_method", "scheme"])
def test_rocm_wo_a_keeps_row_major_weights(holder: str, default_vllm_config) -> None:
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _get_cached_wo_a_bf16
layer = _preshuffled_fp8_linear(holder)
layer.is_bmm = True
original = layer.weight.detach().clone()
kernel = getattr(layer, holder).fp8_linear
kernel.process_weights_after_loading(layer)
actual = _get_cached_wo_a_bf16(layer, 2, 128, 128)
torch.testing.assert_close(actual, original.to(torch.bfloat16).view(2, 128, 128))
@pytest.mark.parametrize("holder", ["quant_method", "scheme"])
def test_rocm_gateup_shuffles_once_and_down_proj_keeps_preshuffled_backend(
holder: str, monkeypatch: pytest.MonkeyPatch, default_vllm_config
) -> None:
from vllm._aiter_ops import rocm_aiter_ops
from vllm.models.deepseek_v4.amd import model as rocm_model
gate_up, down = _preshuffled_fp8_linear(holder), _preshuffled_fp8_linear(holder)
original_gate_up = gate_up.weight.detach().clone()
original_down = down.weight.detach().clone()
monkeypatch.setattr(
rocm_model, "MergedColumnParallelLinear", lambda *a, **k: gate_up
)
monkeypatch.setattr(rocm_model, "RowParallelLinear", lambda *a, **k: down)
monkeypatch.setattr(rocm_aiter_ops, "is_enabled", lambda: True)
model = rocm_model.DeepseekV4MLP(128, 128, "silu")
for linear in (gate_up, down):
getattr(linear, holder).fp8_linear.process_weights_after_loading(linear)
model.prepare_gateup_preshuffle()
for linear, original in ((gate_up, original_gate_up), (down, original_down)):
expected = rocm_aiter_ops.shuffle_weight(original, layout=(16, 16))
torch.testing.assert_close(
linear.weight.view(torch.uint8), expected.view(torch.uint8)
)
def test_rocm_fused_qkv_quant_matches_preshuffled_gemm_scale_layout(
monkeypatch: pytest.MonkeyPatch, default_vllm_config
) -> None:
from vllm._aiter_ops import rocm_aiter_ops
from vllm.models.deepseek_v4.amd.rocm import (
DeepseekV4ROCMAiterMLAAttention,
apply_pre_quantized_block_scaled_mm,
)
if not rocm_aiter_ops.is_blockscale_bpreshuffle_tuned(1024, 256):
pytest.skip("Requires a tuned AITER preshuffled FP8 GEMM")
linear = _preshuffled_fp8_linear(weight_shape=(1024, 256))
original = linear.weight.detach().clone()
linear.quant_method.fp8_linear.process_weights_after_loading(linear)
attention = DeepseekV4ROCMAiterMLAAttention.__new__(DeepseekV4ROCMAiterMLAAttention)
nn.Module.__init__(attention)
attention.wq_b = linear
attention.indexer = None
attention.q_lora_rank, attention.head_dim = 256, 128
attention.eps = 1e-5
attention.q_norm = SimpleNamespace(
weight=torch.ones(256, dtype=torch.bfloat16, device="cuda")
)
attention.kv_norm = SimpleNamespace(
weight=torch.ones(128, dtype=torch.bfloat16, device="cuda")
)
monkeypatch.setattr(rocm_aiter_ops, "is_linear_fp8_enabled", lambda: True)
# Multiple rows and groups with different ranges expose byte-order errors.
inputs = torch.randn(16, 384, dtype=torch.bfloat16, device="cuda")
inputs[:, :128] *= 4
quantized, scales, _ = attention._split_qkv_and_norm(inputs)
assert scales is not None
output = apply_pre_quantized_block_scaled_mm(linear, quantized, scales)
q = inputs[:, :256].float()
normalized = q * torch.rsqrt(q.square().mean(dim=-1, keepdim=True) + attention.eps)
reference_scales = normalized.view(16, 2, 128).abs().amax(dim=-1)
reference_scales /= torch.finfo(current_platform.fp8_dtype()).max
dequantized = quantized.float() * reference_scales.repeat_interleave(128, dim=1)
expected = dequantized @ original.float().T
torch.testing.assert_close(output.float(), expected, atol=0.125, rtol=0.01)
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
+2 -3
View File
@@ -64,7 +64,6 @@ def can_initialize(
The spawn process causes the _initialize_kv_caches_v1 function below to
become ineffective.
"""
model_info = EXAMPLE_MODELS.get_hf_info(model_arch)
model_info.check_available_online(on_fail="skip")
model_info.check_transformers_version(
@@ -199,13 +198,13 @@ def can_initialize(
@pytest.mark.parametrize("model_arch", MINIMAL_MODEL_ARCH_LIST)
def test_can_initialize_small_subset(model_arch: str, monkeypatch: pytest.MonkeyPatch):
"""Test initializing small subset of supported models"""
"""Test initializing small subset of supported models."""
can_initialize(model_arch, monkeypatch, HF_EXAMPLE_MODELS)
@pytest.mark.parametrize("model_arch", OTHER_MODEL_ARCH_LIST)
def test_can_initialize_large_subset(model_arch: str, monkeypatch: pytest.MonkeyPatch):
"""Test initializing large subset of supported models
"""Test initializing large subset of supported models.
This test covers the complement of the tests covered in the "small subset"
test.
+3 -8
View File
@@ -41,9 +41,7 @@ pytestmark = pytest.mark.cpu_test
def test_resolve_visual_encoder_outputs(
select_layers, num_layers_loaded, max_possible_layers, expected_features
):
"""
Test that offsets are correctly handled for vision feature layers.
"""
"""Test that offsets are correctly handled for vision feature layers."""
encoder_outputs = [torch.tensor([idx]) for idx in range(num_layers_loaded + 1)]
output_tensor = resolve_visual_encoder_outputs(
encoder_outputs=encoder_outputs,
@@ -94,11 +92,9 @@ def test_run_dp_sharded_vision_model(batch_size: int):
def run_dp_sharded_vision_model_vs_direct(
local_rank: int, world_size: int, batch_size: int, master_port: int
):
"""
Test that run_dp_sharded_vision_model produces the same results as
"""Test that run_dp_sharded_vision_model produces the same results as
calling the model directly.
"""
# Set random seed for reproducibility
set_random_seed(0)
@@ -282,8 +278,7 @@ def test_run_dp_sharded_mrope_vision_model(batch_size: int):
def run_dp_sharded_mrope_vision_model_vs_direct(
local_rank: int, world_size: int, batch_size: int, master_port: int
):
"""
Test that run_dp_sharded_mrope_vision_model produces the same results as
"""Test that run_dp_sharded_mrope_vision_model produces the same results as
calling the model directly.
"""
# Set random seed for reproducibility
+4 -4
View File
@@ -29,8 +29,7 @@ def check_outputs_equal(
name_0: str,
name_1: str,
):
"""
Compare the two sequences generated by different models,
"""Compare the two sequences generated by different models,
which should be equal.
"""
assert len(outputs_0_lst) == len(outputs_1_lst)
@@ -131,6 +130,7 @@ def check_logprobs_close(
warn_on_mismatch: Issue a warning if there is token-wise or text-wise
mismatch between the two sequences
always_check_logprobs: If true, check logprobs even when tokens match
"""
assert len(outputs_0_lst) == len(outputs_1_lst)
@@ -290,6 +290,7 @@ def build_model_context(
Returns:
InputProcessingContext for the model being considered.
"""
model_info = HF_EXAMPLE_MODELS.find_hf_info(model_id)
model_info.check_available_online(on_fail="skip")
@@ -447,8 +448,7 @@ def dummy_hf_overrides(
exist_overrides: dict[str, Any] | None = None,
use_original_num_layers: bool = False,
) -> PretrainedConfig:
"""
Dummy HF overrides function used to create dummy model
"""Dummy HF overrides function used to create dummy model
with only minimum nums of layer.
"""
# Copy because this helper is called more than once