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:
@@ -4,18 +4,23 @@
|
||||
|
||||
The decode path hands the kernel column slices of the merged ``q|k|v`` conv
|
||||
output and of the fused ``qkvbfg_a`` projection (beta), so q/k/v/beta are
|
||||
token-strided rather than contiguous. The kernel must read them in place,
|
||||
match a pure-PyTorch recurrence, and reject layouts it cannot address.
|
||||
token-strided rather than contiguous. Both backends must match a pure-PyTorch
|
||||
recurrence. CUDA reads these slices in place and rejects unsupported layouts;
|
||||
the ROCm wrapper makes contiguous copies before launching its kernel.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.glm5next.nvidia.ops.third_party.kda import fused_recurrent_kda
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from vllm.models.glm5next.amd.ops.third_party.kda import fused_recurrent_kda
|
||||
else:
|
||||
from vllm.models.glm5next.nvidia.ops.third_party.kda import fused_recurrent_kda
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="CUDA-only Triton kernel"
|
||||
not current_platform.is_cuda_alike(), reason="Requires CUDA or ROCm"
|
||||
)
|
||||
|
||||
H, D = 16, 128
|
||||
@@ -160,6 +165,10 @@ def test_fused_recurrent_kda_strided_inputs_bit_identical_to_contiguous(
|
||||
torch.testing.assert_close(state, state_ref, rtol=0, atol=0)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(),
|
||||
reason="Only the CUDA implementation requires zero-copy token-strided layouts",
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_fused_recurrent_kda_rejects_unaddressable_layouts():
|
||||
"""Layouts the token-stride addressing cannot express must fail loudly
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""GLM-5.3-Flash sequence-parallel MoE layout.
|
||||
|
||||
With DP > 1, TP > 1 and expert parallelism, ``Glm5NextModel`` shards the token
|
||||
dimension across the TP group once at the model entry and every layer runs its
|
||||
MLP on that shard. A module that still does tensor-parallel collectives there
|
||||
sums the partial results of *different* tokens held by different ranks, so the
|
||||
dense MLP of the first ``first_k_dense_replace`` layers must hold replicated
|
||||
weights and run without any collective, like the shared experts already do.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor import parameter
|
||||
from vllm.model_executor.layers import linear
|
||||
from vllm.models.glm5next.common import model as glm_model
|
||||
from vllm.transformers_utils.configs.glm5_next import Glm5NextTextConfig
|
||||
|
||||
HIDDEN, INTERMEDIATE, TP_SIZE = 8, 16, 2
|
||||
|
||||
|
||||
class _Attention(nn.Module):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__()
|
||||
self.o_proj = SimpleNamespace(reduce_results=True)
|
||||
|
||||
|
||||
def _fake_tensor_parallel_world(monkeypatch) -> None:
|
||||
"""Pretend to be rank 1 of a TP=2 group whose all-reduce must never run."""
|
||||
|
||||
def _forbidden_all_reduce(*args, **kwargs):
|
||||
raise AssertionError("tensor-parallel all-reduce on a sequence-parallel shard")
|
||||
|
||||
for module in (linear, parameter):
|
||||
monkeypatch.setattr(
|
||||
module, "get_tensor_model_parallel_world_size", lambda: TP_SIZE
|
||||
)
|
||||
monkeypatch.setattr(module, "get_tensor_model_parallel_rank", lambda: 1)
|
||||
monkeypatch.setattr(
|
||||
linear, "tensor_model_parallel_all_reduce", _forbidden_all_reduce
|
||||
)
|
||||
|
||||
|
||||
def _reference_mlp(mlp: glm_model.Glm5NextMLP, x: torch.Tensor) -> torch.Tensor:
|
||||
gate_up = x @ mlp.gate_up_proj.weight.T
|
||||
gate, up = gate_up.split(INTERMEDIATE, dim=-1)
|
||||
return (torch.nn.functional.silu(gate) * up) @ mlp.down_proj.weight.T
|
||||
|
||||
|
||||
def _assert_runs_locally_on_shard(mlp: glm_model.Glm5NextMLP) -> None:
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
mlp.to(device)
|
||||
assert mlp.gate_up_proj.weight.shape == (2 * INTERMEDIATE, HIDDEN)
|
||||
assert mlp.down_proj.weight.shape == (HIDDEN, INTERMEDIATE)
|
||||
torch.manual_seed(0)
|
||||
for param in mlp.parameters():
|
||||
param.data.normal_()
|
||||
shard = torch.randn(3, HIDDEN, device=device)
|
||||
torch.testing.assert_close(mlp(shard), _reference_mlp(mlp, shard))
|
||||
|
||||
|
||||
def test_dense_mlp_runs_locally_on_the_sequence_parallel_shard(
|
||||
monkeypatch, default_vllm_config
|
||||
):
|
||||
_fake_tensor_parallel_world(monkeypatch)
|
||||
|
||||
sharded = glm_model.Glm5NextMLP(HIDDEN, INTERMEDIATE, "silu")
|
||||
assert sharded.down_proj.tp_size == TP_SIZE
|
||||
assert sharded.gate_up_proj.weight.shape == (2 * INTERMEDIATE // TP_SIZE, HIDDEN)
|
||||
|
||||
_assert_runs_locally_on_shard(
|
||||
glm_model.Glm5NextMLP(HIDDEN, INTERMEDIATE, "silu", is_sequence_parallel=True)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_sequence_parallel_moe", [True, False])
|
||||
def test_dense_layer_mlp_follows_the_sequence_parallel_layout(
|
||||
monkeypatch, default_vllm_config, use_sequence_parallel_moe: bool
|
||||
):
|
||||
_fake_tensor_parallel_world(monkeypatch)
|
||||
monkeypatch.setattr(glm_model, "Glm5NextLinearAttention", _Attention)
|
||||
monkeypatch.setattr(glm_model, "Glm5NextMLAAttention", _Attention)
|
||||
|
||||
config = Glm5NextTextConfig(
|
||||
hidden_size=HIDDEN,
|
||||
intermediate_size=INTERMEDIATE,
|
||||
num_hidden_layers=2,
|
||||
first_k_dense_replace=1,
|
||||
n_routed_experts=4,
|
||||
layer_types=["linear_attention", "deepseek_sparse_attention"],
|
||||
mhc=False,
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
cache_config=None,
|
||||
quant_config=None,
|
||||
parallel_config=SimpleNamespace(
|
||||
use_sequence_parallel_moe=use_sequence_parallel_moe
|
||||
),
|
||||
kernel_config=SimpleNamespace(enable_jit_warmup=False),
|
||||
)
|
||||
|
||||
layer = glm_model.Glm5NextDecoderLayer(vllm_config, config, layer_idx=0)
|
||||
|
||||
assert isinstance(layer.mlp, glm_model.Glm5NextMLP)
|
||||
assert layer.self_attn.o_proj.reduce_results is not use_sequence_parallel_moe
|
||||
if use_sequence_parallel_moe:
|
||||
_assert_runs_locally_on_shard(layer.mlp)
|
||||
else:
|
||||
assert layer.mlp.down_proj.tp_size == TP_SIZE
|
||||
@@ -0,0 +1,72 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.models.kimi_k3.amd.kda import KimiK3DeltaAttention
|
||||
from vllm.models.kimi_k3.amd.linear import KimiDecoderLayer
|
||||
|
||||
|
||||
class _ReturningAttention(nn.Module):
|
||||
def __init__(self, result: torch.Tensor) -> None:
|
||||
super().__init__()
|
||||
self.result = result
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, positions: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return self.result
|
||||
|
||||
|
||||
class _TupleProjection(nn.Module):
|
||||
def __init__(self, result: torch.Tensor) -> None:
|
||||
super().__init__()
|
||||
self.result = result
|
||||
|
||||
def forward(self, _: torch.Tensor) -> tuple[torch.Tensor, None]:
|
||||
return self.result, None
|
||||
|
||||
|
||||
def _make_layer(self_attn: nn.Module) -> KimiDecoderLayer:
|
||||
layer = object.__new__(KimiDecoderLayer)
|
||||
nn.Module.__init__(layer)
|
||||
layer.self_attn = self_attn
|
||||
return layer
|
||||
|
||||
|
||||
def test_kda_self_attention_returns_projection_storage_directly() -> None:
|
||||
hidden_states = torch.randn(4, 8)
|
||||
projected = torch.randn_like(hidden_states)
|
||||
layer = _make_layer(_ReturningAttention(projected))
|
||||
|
||||
output = layer._run_self_attn(torch.arange(4), hidden_states)
|
||||
|
||||
assert output is projected
|
||||
assert output.data_ptr() == projected.data_ptr()
|
||||
|
||||
|
||||
def test_k3_kda_forward_returns_output_projection_storage() -> None:
|
||||
hidden_states = torch.randn(4, 8)
|
||||
projected = torch.randn_like(hidden_states)
|
||||
|
||||
def fill_core_output(**kwargs: torch.Tensor) -> None:
|
||||
kwargs["core_attn_out"].fill_(1)
|
||||
|
||||
attention = SimpleNamespace(
|
||||
local_projection_size=4,
|
||||
head_dim=2,
|
||||
local_num_heads=2,
|
||||
in_proj_padding=0,
|
||||
in_proj_qkvgfab=_TupleProjection(torch.randn(4, 20)),
|
||||
f_b_proj=_TupleProjection(torch.randn(4, 4)),
|
||||
o_proj=_TupleProjection(projected),
|
||||
_forward=fill_core_output,
|
||||
)
|
||||
|
||||
output = KimiK3DeltaAttention.forward(attention, hidden_states, torch.arange(4))
|
||||
|
||||
assert output is projected
|
||||
assert output.data_ptr() == projected.data_ptr()
|
||||
@@ -0,0 +1,38 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.models.kimi_k3.amd.linear import KimiDecoderLayer, KimiMLAAttention
|
||||
|
||||
|
||||
class _DirectMLA(KimiMLAAttention):
|
||||
def __init__(self, result: torch.Tensor) -> None:
|
||||
nn.Module.__init__(self)
|
||||
self.result = result
|
||||
|
||||
def forward(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.result
|
||||
|
||||
|
||||
def _make_layer(self_attn: nn.Module) -> KimiDecoderLayer:
|
||||
layer = object.__new__(KimiDecoderLayer)
|
||||
nn.Module.__init__(layer)
|
||||
layer.self_attn = self_attn
|
||||
return layer
|
||||
|
||||
|
||||
def test_mla_self_attention_returns_projection_storage_directly() -> None:
|
||||
hidden_states = torch.randn(4, 8)
|
||||
projected = torch.randn_like(hidden_states)
|
||||
layer = _make_layer(_DirectMLA(projected))
|
||||
|
||||
output = layer._run_self_attn(torch.arange(4), hidden_states)
|
||||
|
||||
assert output is projected
|
||||
assert output.data_ptr() == projected.data_ptr()
|
||||
@@ -14,6 +14,10 @@ import torch.nn.functional as F
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
from vllm.model_executor.layers.mamba.checkpoint import MambaPrefillCheckpointMetadata
|
||||
from vllm.model_executor.layers.mamba.kda_checkpoint import (
|
||||
FlashKDAPrefillCheckpointExporter,
|
||||
)
|
||||
from vllm.model_executor.layers.mamba.ops.causal_conv1d import causal_conv1d_update
|
||||
from vllm.model_executor.layers.mamba.ops.gather_initial_states import (
|
||||
gather_initial_states,
|
||||
@@ -25,7 +29,6 @@ from vllm.models.kimi_k3.nvidia import kda as nvidia_kda
|
||||
from vllm.models.kimi_k3.nvidia.kda import (
|
||||
_flashinfer_kda_prefill,
|
||||
_flashkda_prefill,
|
||||
_store_cache_checkpoints_kernel,
|
||||
is_flashinfer_fused_kda_decode_supported,
|
||||
is_flashinfer_recurrent_kda_prefill_supported,
|
||||
is_flashkda_supported,
|
||||
@@ -1498,36 +1501,13 @@ def test_flashkda_checkpoint_correctness(state_dtype: torch.dtype, tolerance: fl
|
||||
checkpoint_state_indices = torch.tensor(
|
||||
[1, NULL_BLOCK_ID], dtype=torch.int32, device=DEVICE
|
||||
)
|
||||
state_len = conv_state.shape[-1]
|
||||
width = H * D
|
||||
recurrent_row_size = checkpoint_state[0].numel()
|
||||
block_size = 256
|
||||
_store_cache_checkpoints_kernel[
|
||||
(
|
||||
checkpoint_state_indices.numel(),
|
||||
(max(width * state_len, recurrent_row_size) + block_size - 1) // block_size,
|
||||
)
|
||||
](
|
||||
conv_input,
|
||||
conv_state,
|
||||
checkpoint_state,
|
||||
recurrent_state,
|
||||
cu_seqlens,
|
||||
checkpoint_offsets,
|
||||
checkpoint_state_indices,
|
||||
conv_input.stride(0),
|
||||
conv_input.stride(1),
|
||||
conv_state.stride(0),
|
||||
conv_state.stride(1),
|
||||
conv_state.stride(2),
|
||||
checkpoint_state.stride(0),
|
||||
recurrent_state.stride(0),
|
||||
checkpoint_offsets.stride(0),
|
||||
state_len,
|
||||
width,
|
||||
recurrent_row_size,
|
||||
NULL_BLOCK_ID,
|
||||
block_size,
|
||||
FlashKDAPrefillCheckpointExporter().export(
|
||||
MambaPrefillCheckpointMetadata(checkpoint_offsets, checkpoint_state_indices),
|
||||
raw_qkv=conv_input,
|
||||
conv_state=conv_state,
|
||||
recurrent_checkpoint=checkpoint_state,
|
||||
recurrent_state=recurrent_state,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
torch.testing.assert_close(conv_state[1], q[0, 13:16].flatten(1).transpose(0, 1))
|
||||
torch.testing.assert_close(recurrent_state[1], checkpoint_state[0])
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.models.kimi_k3.nvidia.model import KimiDecoderLayer
|
||||
|
||||
|
||||
class _ReturningSharedKDA(nn.Module):
|
||||
def __init__(self, result: torch.Tensor) -> None:
|
||||
super().__init__()
|
||||
self.result = result
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, positions: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return self.result
|
||||
|
||||
|
||||
def test_low_rank_kda_caller_returns_projection_storage_directly() -> None:
|
||||
hidden_states = torch.randn(4, 8)
|
||||
projected = torch.randn_like(hidden_states)
|
||||
layer = object.__new__(KimiDecoderLayer)
|
||||
nn.Module.__init__(layer)
|
||||
layer.self_attn = _ReturningSharedKDA(projected)
|
||||
|
||||
output = layer._run_self_attn(torch.arange(4), hidden_states)
|
||||
|
||||
assert output is projected
|
||||
assert output.data_ptr() == projected.data_ptr()
|
||||
@@ -158,7 +158,9 @@ def test_models(
|
||||
hf_model.model.device
|
||||
)
|
||||
if prompt_embeds is not None:
|
||||
embed = hf_model.model.get_input_embeddings()(token_ids)
|
||||
# Retained prompt values must not keep reference weights alive.
|
||||
with torch.no_grad():
|
||||
embed = hf_model.model.get_input_embeddings()(token_ids)
|
||||
|
||||
# MiniCPM models apply scale_emb to embeddings internally.
|
||||
# vLLM expects pre-scaled embeddings when using inputs_embeds.
|
||||
|
||||
@@ -33,6 +33,8 @@ def release_gpu_memory_between_tests():
|
||||
gc.collect()
|
||||
if torch.accelerator.is_available():
|
||||
torch.accelerator.empty_cache()
|
||||
if current_platform.is_rocm():
|
||||
return
|
||||
try:
|
||||
wait_for_memory_to_settle()
|
||||
except ValueError as e:
|
||||
|
||||
@@ -9,6 +9,7 @@ import torch
|
||||
|
||||
from tests.utils import wait_for_memory_to_settle
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -26,6 +27,8 @@ def release_gpu_memory_between_tests():
|
||||
gc.collect()
|
||||
if torch.accelerator.is_available():
|
||||
torch.accelerator.empty_cache()
|
||||
if current_platform.is_rocm():
|
||||
return
|
||||
try:
|
||||
wait_for_memory_to_settle()
|
||||
except ValueError as e:
|
||||
|
||||
@@ -151,10 +151,12 @@ VLM_TEST_SETTINGS = {
|
||||
img_idx_to_prompt=lambda idx: "<|vision_start|><|image_pad|><|vision_end|>",
|
||||
video_idx_to_prompt=lambda idx: "<|vision_start|><|video_pad|><|vision_end|>",
|
||||
enforce_eager=False,
|
||||
needs_video_metadata=True,
|
||||
max_model_len=4096,
|
||||
max_num_seqs=2,
|
||||
auto_cls=AutoModelForImageTextToText,
|
||||
vllm_output_post_proc=model_utils.qwen2_vllm_to_hf_output,
|
||||
patch_hf_runner=model_utils.qwen3_vl_patch_hf_runner,
|
||||
image_size_factors=[(0.25,), (0.25, 0.25, 0.25), (0.25, 0.2, 0.15)],
|
||||
marks=[pytest.mark.core_model, pytest.mark.cpu_model],
|
||||
),
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
import pytest
|
||||
|
||||
from vllm.assets.image import ImageAsset
|
||||
from vllm.multimodal.video import sample_frames_from_video
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ....conftest import VIDEO_ASSETS
|
||||
from .vlm_utils.builders import sample_frames_with_video_metadata
|
||||
|
||||
models = ["Qwen/Qwen2.5-VL-3B-Instruct"]
|
||||
target_dtype = "bfloat16"
|
||||
@@ -81,7 +81,9 @@ def test_qwen2_5_vl_evs_functionality(
|
||||
|
||||
# Sample frames from video assets
|
||||
sampled_vids = [
|
||||
sample_frames_from_video(asset.np_ndarrays, num_frames)
|
||||
sample_frames_with_video_metadata(
|
||||
(asset.np_ndarrays, asset.metadata), num_frames
|
||||
)
|
||||
for asset in video_assets
|
||||
]
|
||||
|
||||
@@ -145,7 +147,9 @@ def test_qwen2_5_vl_evs_batched_videos(
|
||||
monkeypatch.setenv("VLLM_USE_BYTECODE_HOOK", "1" if use_bytecode_hook else "0")
|
||||
# Sample frames from video assets
|
||||
sampled_vids = [
|
||||
sample_frames_from_video(asset.np_ndarrays, num_frames)
|
||||
sample_frames_with_video_metadata(
|
||||
(asset.np_ndarrays, asset.metadata), num_frames
|
||||
)
|
||||
for asset in video_assets
|
||||
]
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ MODEL_CONFIGS: dict[str, VitCudagraphTestConfig] = {
|
||||
"<|vision_start|><|video_pad|><|vision_end|>"
|
||||
"Describe this video in one sentence."
|
||||
),
|
||||
needs_video_metadata=False,
|
||||
needs_video_metadata=True,
|
||||
marks=[pytest.mark.core_model],
|
||||
),
|
||||
"kimi_vl": VitCudagraphTestConfig(
|
||||
@@ -236,7 +236,11 @@ MODEL_CONFIGS: dict[str, VitCudagraphTestConfig] = {
|
||||
},
|
||||
vllm_runner_kwargs={
|
||||
"load_format": "dummy",
|
||||
"attention_backend": "FLASHMLA_SPARSE_DSV41",
|
||||
"attention_backend": (
|
||||
"ROCM_FLASHMLA_SPARSE_DSV4"
|
||||
if current_platform.is_rocm()
|
||||
else "FLASHMLA_SPARSE_DSV41"
|
||||
),
|
||||
"hf_overrides": partial(
|
||||
dummy_hf_overrides,
|
||||
model_arch="DeepseekV41ForCausalLM",
|
||||
|
||||
@@ -9,6 +9,7 @@ import torch
|
||||
|
||||
from tests.utils import wait_for_memory_to_settle
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -26,6 +27,8 @@ def release_gpu_memory_between_tests():
|
||||
gc.collect()
|
||||
if torch.accelerator.is_available():
|
||||
torch.accelerator.empty_cache()
|
||||
if current_platform.is_rocm():
|
||||
return
|
||||
try:
|
||||
wait_for_memory_to_settle()
|
||||
except ValueError as e:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from transformers import AutoConfig, AutoModel, CLIPImageProcessor
|
||||
from transformers import AutoConfig, AutoModel, CLIPImageProcessor, PreTrainedModel
|
||||
|
||||
from vllm.distributed import cleanup_dist_env_and_memory
|
||||
from vllm.platforms import current_platform
|
||||
@@ -12,11 +12,6 @@ from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE
|
||||
|
||||
from ....conftest import ImageTestAssets
|
||||
|
||||
pytestmark = pytest.mark.skip(
|
||||
reason="InternVisionModel's custom code is incompatible with "
|
||||
"transformers v5 (missing all_tied_weights_keys)"
|
||||
)
|
||||
|
||||
# we use snapshot_download to prevent conflicts between
|
||||
# dynamic_module and trust_remote_code for hf_runner
|
||||
DOWNLOAD_PATTERN = ["*.json", "*.py", "*.safetensors", "*.txt", "*.model"]
|
||||
@@ -45,9 +40,23 @@ def run_intern_vit_test(
|
||||
if not getattr(config, "norm_type", None):
|
||||
config.norm_type = "rms_norm"
|
||||
|
||||
hf_model = AutoModel.from_pretrained(
|
||||
model, dtype=torch_dtype, trust_remote_code=True
|
||||
).to(DEVICE_TYPE)
|
||||
# Monkey-patch for transformers v5 compatibility: InternVisionModel's
|
||||
# custom code doesn't call post_init(), so all_tied_weights_keys is
|
||||
# never set. Remove once https://github.com/OpenGVLab/InternVL fixes it.
|
||||
_orig_init = PreTrainedModel.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_orig_init(self, *args, **kwargs)
|
||||
self.all_tied_weights_keys = {}
|
||||
|
||||
PreTrainedModel.__init__ = _patched_init
|
||||
|
||||
try:
|
||||
hf_model = AutoModel.from_pretrained(
|
||||
model, dtype=torch_dtype, trust_remote_code=True
|
||||
).to(DEVICE_TYPE)
|
||||
finally:
|
||||
PreTrainedModel.__init__ = _orig_init
|
||||
hf_outputs_per_image = [
|
||||
hf_model(pixel_value.to(DEVICE_TYPE)).last_hidden_state
|
||||
for pixel_value in pixel_values
|
||||
|
||||
@@ -22,7 +22,7 @@ import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.cache import MultiModalProcessorSenderCache
|
||||
from vllm.multimodal.cache import LruKeyReplicatedSenderCache
|
||||
|
||||
from ....multimodal.utils import random_audio, random_video
|
||||
from ...utils import build_model_context
|
||||
@@ -68,7 +68,7 @@ def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> Non
|
||||
# Sender cache: on a cache hit returns (None, prompt_updates) for each
|
||||
# item, setting mm_kwargs["video"] = [None] – the exact condition that
|
||||
# triggered the original bug.
|
||||
sender_cache = MultiModalProcessorSenderCache(ctx.model_config)
|
||||
sender_cache = LruKeyReplicatedSenderCache(ctx.model_config)
|
||||
|
||||
video_token_id = processor.info.get_hf_config().video_token_id
|
||||
|
||||
|
||||
@@ -159,7 +159,6 @@ def get_token_prompt(
|
||||
processor: BaseMultiModalProcessor,
|
||||
mm_data: MultiModalDataDict,
|
||||
) -> list[int]:
|
||||
dummy_inputs = processor.dummy_inputs
|
||||
tokenizer: TokenizerLike = processor.info.get_tokenizer()
|
||||
model_config = processor.info.ctx.model_config
|
||||
|
||||
@@ -174,7 +173,7 @@ def get_token_prompt(
|
||||
mm_counts = {k: len(vs) for k, vs in parsed_data.items()}
|
||||
|
||||
if is_mistral_tokenizer(tokenizer):
|
||||
inputs = dummy_inputs.get_dummy_processor_inputs(
|
||||
inputs = processor.get_dummy_inputs(
|
||||
model_config.max_model_len,
|
||||
mm_counts,
|
||||
mm_options=MultiModalDummyOptions(),
|
||||
@@ -182,7 +181,7 @@ def get_token_prompt(
|
||||
mm_data=mm_data, # type: ignore[call-arg]
|
||||
)
|
||||
else:
|
||||
inputs = dummy_inputs.get_dummy_processor_inputs(
|
||||
inputs = processor.get_dummy_inputs(
|
||||
model_config.max_model_len,
|
||||
mm_counts,
|
||||
mm_options=MultiModalDummyOptions(),
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import pytest
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import BatchFeature
|
||||
from transformers import AutoProcessor, BatchFeature
|
||||
|
||||
from vllm.model_executor.models.lightonocr import LightOnOCRProcessingInfo
|
||||
from vllm.model_executor.models.mistral3 import Mistral3HFEncoderInfo
|
||||
@@ -22,25 +22,41 @@ _MODEL_ID = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
|
||||
_LIGHTON_MODEL_ID = "lightonai/LightOnOCR-1B-1025"
|
||||
|
||||
|
||||
def _processed_pixel_values(
|
||||
def _process_images_with_hf(
|
||||
hf_processor,
|
||||
images: list[Image.Image],
|
||||
mm_processor_kwargs: dict[str, object],
|
||||
) -> list[torch.Tensor]:
|
||||
"""Resize via the HF image processor and un-pad to per-image H×W."""
|
||||
image_processor = hf_processor.image_processor
|
||||
hf_out = image_processor(images=images, return_tensors="pt", **mm_processor_kwargs)
|
||||
) -> tuple[list[torch.Tensor], list[int]]:
|
||||
"""Process images and placeholders through the public HF processor."""
|
||||
hf_out = hf_processor(
|
||||
text=hf_processor.image_token * len(images),
|
||||
images=images,
|
||||
return_tensors="pt",
|
||||
**mm_processor_kwargs,
|
||||
)
|
||||
pixel_values = hf_out["pixel_values"]
|
||||
image_sizes = hf_out["image_sizes"]
|
||||
return [p[:, :h, :w] for p, (h, w) in zip(pixel_values, image_sizes)]
|
||||
unpadded = [p[:, :h, :w] for p, (h, w) in zip(pixel_values, image_sizes)]
|
||||
|
||||
special_token_ids = {
|
||||
hf_processor.image_token_id,
|
||||
hf_processor.image_break_token_id,
|
||||
hf_processor.image_end_token_id,
|
||||
}
|
||||
placeholder_tokens = [
|
||||
token_id
|
||||
for token_id in hf_out["input_ids"][0].tolist()
|
||||
if token_id in special_token_ids
|
||||
]
|
||||
return unpadded, placeholder_tokens
|
||||
|
||||
|
||||
def _placeholder_count_from_prompt_updates(
|
||||
def _placeholder_tokens_from_prompt_updates(
|
||||
processor,
|
||||
images: list[Image.Image],
|
||||
pixel_values: list[torch.Tensor],
|
||||
mm_processor_kwargs: dict[str, object],
|
||||
) -> int:
|
||||
) -> list[int]:
|
||||
hf_inputs = BatchFeature({"pixel_values": pixel_values})
|
||||
fields_config = processor._get_mm_fields_config(hf_inputs, mm_processor_kwargs)
|
||||
out_mm_kwargs = MultiModalKwargsItems.from_hf_inputs(hf_inputs, fields_config)
|
||||
@@ -49,13 +65,11 @@ def _placeholder_count_from_prompt_updates(
|
||||
updates = processor._get_prompt_updates(
|
||||
mm_items, mm_processor_kwargs, out_mm_kwargs
|
||||
)
|
||||
image_token_id = processor.info.get_hf_config().image_token_index
|
||||
|
||||
total = 0
|
||||
placeholder_tokens: list[int] = []
|
||||
for item_idx in range(len(images)):
|
||||
details = updates[0].resolve(item_idx).content
|
||||
total += details.full.count(image_token_id)
|
||||
return total
|
||||
placeholder_tokens.extend(details.full)
|
||||
return placeholder_tokens
|
||||
|
||||
|
||||
def _expected_placeholder_tokens_per_image(
|
||||
@@ -72,12 +86,12 @@ def _expected_placeholder_tokens_per_image(
|
||||
patch_h = patch_w = int(patch_size)
|
||||
|
||||
spatial_merge_size = getattr(hf_processor, "spatial_merge_size", 1)
|
||||
assert image_h % patch_h == 0
|
||||
assert image_w % patch_w == 0
|
||||
merged_patch_h = patch_h * spatial_merge_size
|
||||
merged_patch_w = patch_w * spatial_merge_size
|
||||
assert image_h % merged_patch_h == 0
|
||||
assert image_w % merged_patch_w == 0
|
||||
|
||||
return (image_h // (patch_h * spatial_merge_size)) * (
|
||||
image_w // (patch_w * spatial_merge_size)
|
||||
)
|
||||
return (image_h // merged_patch_h) * (image_w // merged_patch_w)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [_MODEL_ID])
|
||||
@@ -87,8 +101,8 @@ def _expected_placeholder_tokens_per_image(
|
||||
({}, (448, 448), 256),
|
||||
({"size": {"longest_edge": 1008}}, (1540, 1540), 1296),
|
||||
({"size": {"longest_edge": 1288}}, (1536, 1187), 1656),
|
||||
({"size": {"longest_edge": 1008}}, (29, 29), 1),
|
||||
({"size": {"longest_edge": 1000}}, (1540, 1700), 1152),
|
||||
({"size": {"longest_edge": 1008}}, (29, 29), 4),
|
||||
({"size": {"longest_edge": 1000}}, (1540, 1700), 1188),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("num_imgs", [1, 2])
|
||||
@@ -109,21 +123,29 @@ def test_processor_size_override(
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
hf_processor_mm_kwargs = {} if kwargs_on_init else mm_processor_kwargs
|
||||
hf_processor = processor.info.get_hf_processor(**hf_processor_mm_kwargs)
|
||||
hf_processor = AutoProcessor.from_pretrained(
|
||||
model_id,
|
||||
fix_mistral_regex=True,
|
||||
)
|
||||
|
||||
dummy_image = Image.new("RGB", image_size, color=(127, 127, 127))
|
||||
images = [dummy_image] * num_imgs
|
||||
merged_mm_kwargs = processor.info.ctx.get_merged_mm_kwargs(hf_processor_mm_kwargs)
|
||||
pixel_values = _processed_pixel_values(hf_processor, images, merged_mm_kwargs)
|
||||
pixel_values, hf_placeholder_tokens = _process_images_with_hf(
|
||||
hf_processor, images, merged_mm_kwargs
|
||||
)
|
||||
|
||||
image_token_count = _placeholder_count_from_prompt_updates(
|
||||
prompt_update_tokens = _placeholder_tokens_from_prompt_updates(
|
||||
processor, images, pixel_values, hf_processor_mm_kwargs
|
||||
)
|
||||
expected_from_pixel_values = _expected_placeholder_tokens_per_image(
|
||||
hf_processor, pixel_values[0]
|
||||
)
|
||||
assert expected_from_pixel_values == expected_toks_per_img
|
||||
assert image_token_count == expected_from_pixel_values * num_imgs
|
||||
assert hf_placeholder_tokens.count(hf_processor.image_token_id) == (
|
||||
expected_from_pixel_values * num_imgs
|
||||
)
|
||||
assert prompt_update_tokens == hf_placeholder_tokens
|
||||
|
||||
|
||||
def test_lightonocr_keeps_vision_config_image_size():
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from PIL import Image
|
||||
@@ -208,6 +211,35 @@ def test_get_image_size_with_most_features(
|
||||
assert tokens < max_tokens
|
||||
|
||||
|
||||
def _build_qwen2_5_vl_video_mm_data(num_frames: int, fps: float) -> dict[str, Any]:
|
||||
video = np.zeros((num_frames, 56, 56, 3), dtype=np.uint8)
|
||||
metadata = {
|
||||
"fps": fps,
|
||||
"duration": num_frames / fps,
|
||||
"total_num_frames": num_frames,
|
||||
"frames_indices": list(range(num_frames)),
|
||||
"video_backend": "opencv",
|
||||
"do_sample_frames": False,
|
||||
}
|
||||
return {"video": [(video, metadata)]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", ["Qwen/Qwen2.5-VL-3B-Instruct"])
|
||||
def test_qwen2_5_vl_video_fps_to_second_per_grid_ts(model_id: str) -> None:
|
||||
ctx = build_model_context(model_id, limit_mm_per_prompt={"image": 0, "video": 1})
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
temporal_patch_size = (
|
||||
processor.info.get_hf_processor().video_processor.temporal_patch_size
|
||||
)
|
||||
|
||||
prompt = "<|vision_start|><|video_pad|><|vision_end|>"
|
||||
for fps in (1.0, 30.0):
|
||||
mm_data = _build_qwen2_5_vl_video_mm_data(num_frames=32, fps=fps)
|
||||
processed = processor(prompt, mm_items=processor.info.parse_mm_data(mm_data))
|
||||
spg = processed["mm_kwargs"]["video"][0].get_data()["second_per_grid_ts"]
|
||||
assert float(spg) == pytest.approx(temporal_patch_size / fps, rel=2e-2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_id", ["Qwen/Qwen2-VL-2B-Instruct", "Qwen/Qwen2.5-VL-3B-Instruct"]
|
||||
)
|
||||
|
||||
@@ -90,13 +90,12 @@ def create_batched_mm_kwargs(
|
||||
size_factors: tuple[float, ...] = (1.0, 0.5, 0.25),
|
||||
) -> Iterable[tuple[str, int, BatchedTensorInputs]]:
|
||||
processing_info = processor.info
|
||||
dummy_inputs = processor.dummy_inputs
|
||||
supported_mm_limits = processing_info.get_supported_mm_limits()
|
||||
mm_counts = {
|
||||
modality: 3 if limit is None else limit
|
||||
for modality, limit in supported_mm_limits.items()
|
||||
}
|
||||
processor_inputs = dummy_inputs.get_dummy_processor_inputs(
|
||||
processor_inputs = processor.get_dummy_inputs(
|
||||
seq_len=model_config.max_model_len,
|
||||
mm_counts=mm_counts,
|
||||
mm_options=MultiModalDummyOptions(),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for Whisper's multimodal preprocessing."""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
from ...utils import build_model_context
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", ["openai/whisper-large-v3-turbo"])
|
||||
@pytest.mark.parametrize("audio_duration_s", [5, 30, 35])
|
||||
def test_audio_features_fit_encoder_window(
|
||||
model_id: str,
|
||||
audio_duration_s: int,
|
||||
) -> None:
|
||||
"""The encoder only has positions for one 30 s window, so a longer clip
|
||||
has to be cut to that window like the HF feature extractor does by default.
|
||||
"""
|
||||
ctx = build_model_context(model_id, limit_mm_per_prompt={"audio": 1})
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
feature_extractor = processor.info.get_feature_extractor()
|
||||
|
||||
sampling_rate = feature_extractor.sampling_rate
|
||||
rng = np.random.RandomState(0)
|
||||
audio = rng.rand(sampling_rate * audio_duration_s).astype(np.float32)
|
||||
|
||||
processed_inputs = processor(
|
||||
"<|startoftranscript|>",
|
||||
mm_items=processor.info.parse_mm_data({"audio": [(audio, sampling_rate)]}),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
|
||||
input_features = processed_inputs["mm_kwargs"].get_data()["input_features"]
|
||||
assert input_features.shape[-1] == feature_extractor.nb_max_frames
|
||||
@@ -19,6 +19,7 @@ import torch
|
||||
|
||||
from vllm.model_executor.models.mimo_v2 import _shard_fp8_qkv_proj
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.torch_utils import set_default_torch_num_threads
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
@@ -39,6 +40,13 @@ GEOMETRIES = {
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def single_threaded_cpu_ops():
|
||||
# Do not prime the parent's thread pool before later engine forks.
|
||||
with set_default_torch_num_threads(1):
|
||||
yield
|
||||
|
||||
|
||||
def _chunk_rows(num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp):
|
||||
return (
|
||||
num_heads // ckpt_tp * head_dim
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.deepseek_v4.amd import dspark as dspark_module
|
||||
from vllm.models.deepseek_v4.amd.dspark import DSparkDeepseekV4ForCausalLM
|
||||
|
||||
|
||||
def _make_uninitialized_model(confidence_head):
|
||||
model = DSparkDeepseekV4ForCausalLM.__new__(DSparkDeepseekV4ForCausalLM)
|
||||
object.__setattr__(
|
||||
model,
|
||||
"model",
|
||||
SimpleNamespace(confidence_head=confidence_head),
|
||||
)
|
||||
return model
|
||||
|
||||
|
||||
def _prepare_loader_model(model, named_parameters):
|
||||
object.__setattr__(
|
||||
model,
|
||||
"config",
|
||||
SimpleNamespace(
|
||||
n_routed_experts=1,
|
||||
expert_dtype="fp4",
|
||||
num_attention_heads=1,
|
||||
),
|
||||
)
|
||||
object.__setattr__(model, "named_parameters", lambda: named_parameters)
|
||||
|
||||
|
||||
def _disable_distributed_loader_paths(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setattr(
|
||||
dspark_module,
|
||||
"fused_moe_make_expert_params_mapping",
|
||||
lambda *args, **kwargs: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dspark_module, "get_tensor_model_parallel_world_size", lambda: 1
|
||||
)
|
||||
monkeypatch.setattr(dspark_module, "get_tensor_model_parallel_rank", lambda: 0)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_v4_rocm_dspark_maps_enabled_confidence_head():
|
||||
model = _make_uninitialized_model(object())
|
||||
|
||||
assert (
|
||||
model._remap_dspark_name("mtp.2.confidence_head.proj.weight")
|
||||
== "model.confidence_head.proj.weight"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_v4_rocm_dspark_skips_disabled_confidence_head():
|
||||
model = _make_uninitialized_model(None)
|
||||
|
||||
assert model._remap_dspark_name("mtp.2.confidence_head.proj.weight") is None
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_v4_rocm_dspark_disables_unloaded_confidence_head(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
model = _make_uninitialized_model(object())
|
||||
_prepare_loader_model(model, [])
|
||||
_disable_distributed_loader_paths(monkeypatch)
|
||||
|
||||
assert model.load_weights([]) == set()
|
||||
assert model.model.confidence_head is None
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_v4_rocm_dspark_loads_complete_confidence_head(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
class FakeParameter:
|
||||
loaded_weight = None
|
||||
|
||||
def weight_loader(self, param, loaded_weight):
|
||||
assert param is self
|
||||
self.loaded_weight = loaded_weight
|
||||
|
||||
confidence_head = object()
|
||||
parameter = FakeParameter()
|
||||
model = _make_uninitialized_model(confidence_head)
|
||||
_prepare_loader_model(
|
||||
model,
|
||||
[("model.confidence_head.proj.weight", parameter)],
|
||||
)
|
||||
_disable_distributed_loader_paths(monkeypatch)
|
||||
loaded_weight = torch.tensor([[1.0, 2.0]])
|
||||
|
||||
loaded = model.load_weights([("mtp.2.confidence_head.proj.weight", loaded_weight)])
|
||||
|
||||
assert loaded == {"model.confidence_head.proj.weight"}
|
||||
assert parameter.loaded_weight is loaded_weight
|
||||
assert model.model.confidence_head is confidence_head
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_v4_rocm_dspark_confidence_is_probability():
|
||||
class ConfidenceHead:
|
||||
def __call__(self, head_hidden, markov_embed):
|
||||
return (head_hidden[:, 0] + markov_embed[:, 0]).float()
|
||||
|
||||
model = _make_uninitialized_model(ConfidenceHead())
|
||||
head_hidden = torch.tensor([[0.0], [1.0]], dtype=torch.bfloat16)
|
||||
markov_embed = torch.tensor([[0.0], [-2.0]], dtype=torch.bfloat16)
|
||||
|
||||
confidence = model.compute_confidence(head_hidden, markov_embed)
|
||||
|
||||
torch.testing.assert_close(
|
||||
confidence,
|
||||
torch.sigmoid(torch.tensor([0.0, -1.0])),
|
||||
)
|
||||
assert torch.all((confidence >= 0) & (confidence <= 1))
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_deepseek_v4_rocm_dspark_confidence_requires_a_head():
|
||||
model = _make_uninitialized_model(None)
|
||||
empty = torch.zeros((1, 1))
|
||||
|
||||
with pytest.raises(RuntimeError, match="confidence_head"):
|
||||
model.compute_confidence(empty, empty)
|
||||
@@ -7,6 +7,7 @@ import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.model_executor.models.utils import WeightsMapper
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
@@ -100,7 +101,9 @@ def test_rocm_moe_wires_vision_routing_on_hash_and_regular_layers(
|
||||
n_shared_experts=None,
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(hf_config=config), quant_config=None
|
||||
model_config=SimpleNamespace(hf_config=config),
|
||||
quant_config=None,
|
||||
parallel_config=ParallelConfig(),
|
||||
)
|
||||
|
||||
hash_moe = rocm_model.DeepseekV4MoE(vllm_config, prefix="model.layers.0.ffn")
|
||||
@@ -115,6 +118,24 @@ def test_rocm_moe_wires_vision_routing_on_hash_and_regular_layers(
|
||||
assert factory_kwargs["image_sentinel_lo"] == IMAGE_SENTINEL_BASE_ID
|
||||
|
||||
|
||||
def test_rocm_fse_rejects_data_parallel_deployment(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from vllm.models.deepseek_v4.amd.model import _fuse_shared_experts_enabled
|
||||
|
||||
config = SimpleNamespace(n_shared_experts=1)
|
||||
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS", "1")
|
||||
with pytest.raises(ValueError, match="data parallelism"):
|
||||
_fuse_shared_experts_enabled(config, ParallelConfig(data_parallel_size=2))
|
||||
|
||||
# Expert parallelism already disables FSE: no raise, FSE stays off.
|
||||
assert not _fuse_shared_experts_enabled(
|
||||
config, ParallelConfig(data_parallel_size=2, enable_expert_parallel=True)
|
||||
)
|
||||
assert _fuse_shared_experts_enabled(config, ParallelConfig())
|
||||
|
||||
|
||||
def test_rocm_mtp_forwards_input_ids_for_vision_routing(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
|
||||
@@ -51,6 +51,18 @@ def _num_captured_graphs(_worker):
|
||||
return compilation_counter.num_cudagraph_captured
|
||||
|
||||
|
||||
def _piecewise_compile_state(worker):
|
||||
from vllm.compilation.counter import compilation_counter
|
||||
|
||||
# `cudagraph_mode` is returned by name: the enum does not survive the
|
||||
# collective_rpc round trip, it arrives as its bare value.
|
||||
return (
|
||||
compilation_counter.num_models_seen,
|
||||
compilation_counter.num_cudagraph_captured,
|
||||
worker.vllm_config.compilation_config.cudagraph_mode.name,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tp,enforce_eager,mtp,dtype,kv_cache_dtype",
|
||||
[
|
||||
@@ -135,3 +147,39 @@ def test_hyv4_dummy_generation(
|
||||
and metric.value > 0
|
||||
for metric in model.llm.get_metrics()
|
||||
), "MTP drafter did not run"
|
||||
|
||||
|
||||
def test_hyv4_backbone_reaches_the_compiler(vllm_runner, enable_pickle) -> None:
|
||||
"""Guard against the backbone losing `@support_torch_compile`.
|
||||
|
||||
An undecorated backbone is not a hard failure: vLLM downgrades
|
||||
`cudagraph_mode` to NONE and serves the whole model eager, which on TP8
|
||||
gfx942 cost ~4x decode latency.
|
||||
"""
|
||||
with vllm_runner(
|
||||
"tencent/Hy4-preview",
|
||||
trust_remote_code=True,
|
||||
skip_tokenizer_init=True,
|
||||
load_format="dummy",
|
||||
dtype="bfloat16",
|
||||
hf_overrides=_small_hyv4_config,
|
||||
max_model_len=256,
|
||||
max_num_batched_tokens=128,
|
||||
max_num_seqs=8,
|
||||
enable_chunked_prefill=True,
|
||||
enable_prefix_caching=False,
|
||||
kv_cache_memory_bytes=128 * 1024 * 1024,
|
||||
enforce_eager=False,
|
||||
seed=17,
|
||||
compilation_config=CompilationConfig(
|
||||
mode=CompilationMode.VLLM_COMPILE,
|
||||
cudagraph_mode=CUDAGraphMode.PIECEWISE,
|
||||
cudagraph_capture_sizes=[1, 2, 4],
|
||||
),
|
||||
) as model:
|
||||
for models_seen, captured, mode in model.collective_rpc(
|
||||
_piecewise_compile_state
|
||||
):
|
||||
assert models_seen > 0, "backbone was never handed to the compiler"
|
||||
assert mode == CUDAGraphMode.PIECEWISE.name
|
||||
assert captured > 0
|
||||
|
||||
Reference in New Issue
Block a user