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:
@@ -0,0 +1,41 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Focused unit tests for the GLM decode top-k dispatch."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.glm5next.nvidia.sparse_indexer import _use_cooperative_topk
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="CUDA-only dispatch"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_rows", [1, 64], ids=["1row", "64rows"])
|
||||
@torch.inference_mode()
|
||||
def test_cooperative_topk_is_selected_for_supported_batch(num_rows: int):
|
||||
logits = torch.empty(num_rows, 8192, dtype=torch.float32, device="cuda")
|
||||
assert _use_cooperative_topk(logits, 512, num_rows)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("num_rows", "select_k", "stride_padding"),
|
||||
[
|
||||
(65, 512, 0),
|
||||
(1, 256, 0),
|
||||
(1, 512, 1),
|
||||
],
|
||||
ids=["too_many_rows", "unsupported_k", "unaligned_stride"],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_cooperative_topk_falls_back_on_unsupported_batch(
|
||||
num_rows: int, select_k: int, stride_padding: int
|
||||
):
|
||||
logits = torch.empty(
|
||||
num_rows, 8192 + stride_padding, dtype=torch.float32, device="cuda"
|
||||
)
|
||||
if stride_padding:
|
||||
logits = logits[:, :8192]
|
||||
assert not _use_cooperative_topk(logits, select_k, num_rows)
|
||||
@@ -3,8 +3,6 @@
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from packaging.version import Version
|
||||
from transformers import __version__ as TRANSFORMERS_VERSION
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
@@ -26,7 +24,7 @@ AITER_MODEL_LIST = [
|
||||
"meta-llama/Llama-3.2-1B-Instruct",
|
||||
"openbmb/MiniCPM3-4B",
|
||||
"Qwen/Qwen2.5-0.5B-Instruct",
|
||||
"TitanML/tiny-mixtral",
|
||||
"axolotl-ai-co/tiny-mixtral-30m",
|
||||
"Qwen/Qwen3-8B",
|
||||
]
|
||||
|
||||
@@ -95,7 +93,7 @@ AITER_MODEL_LIST = [
|
||||
pytest.param("stabilityai/stablelm-3b-4e1t"), # stablelm
|
||||
pytest.param("bigcode/starcoder2-3b"), # starcoder2
|
||||
pytest.param(
|
||||
"TitanML/tiny-mixtral", # mixtral
|
||||
"axolotl-ai-co/tiny-mixtral-30m", # mixtral
|
||||
marks=[pytest.mark.core_model],
|
||||
),
|
||||
pytest.param("swiss-ai/Apertus-8B-Instruct-2509"), # apertus
|
||||
@@ -126,12 +124,6 @@ def test_models(
|
||||
model_info.check_available_online(on_fail="skip")
|
||||
model_info.check_transformers_version(on_fail="skip")
|
||||
|
||||
if current_platform.is_rocm() and model == "TitanML/tiny-mixtral":
|
||||
# Its single-token router selects LLMM1, whose low-precision
|
||||
# accumulation can change the top-2 experts. Keep the optimized kernel
|
||||
# enabled generally, but use the reference GEMM for this accuracy test.
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_SKINNY_GEMM", "0")
|
||||
|
||||
if use_rocm_aiter and (model in AITER_MODEL_LIST):
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
|
||||
elif use_rocm_aiter and model not in AITER_MODEL_LIST:
|
||||
@@ -168,16 +160,6 @@ def test_models(
|
||||
if prompt_embeds is not None:
|
||||
embed = hf_model.model.get_input_embeddings()(token_ids)
|
||||
|
||||
if "gemma" in model.lower() and (
|
||||
Version(TRANSFORMERS_VERSION) < Version("5.3.0.dev0")
|
||||
):
|
||||
# For Gemma 1/2 models with Transformers 5.4.0+, the prompt
|
||||
# embeddings are normalised in `get_prompt_embeddings`,
|
||||
# like Gemma 3. For older versions, we need to manually normalise.
|
||||
embed_scale = hf_model.config.hidden_size**0.5
|
||||
normalizer = torch.tensor(embed_scale, dtype=embed.dtype)
|
||||
embed *= normalizer
|
||||
|
||||
# MiniCPM models apply scale_emb to embeddings internally.
|
||||
# vLLM expects pre-scaled embeddings when using inputs_embeds.
|
||||
if model in EMBED_SCALING_MODELS:
|
||||
|
||||
@@ -14,7 +14,10 @@ from vllm.model_executor.models.gemma3n import (
|
||||
Gemma3nTextModel,
|
||||
_kv_sharing_weights_mapper,
|
||||
)
|
||||
from vllm.model_executor.models.gemma4 import Gemma4Model
|
||||
from vllm.model_executor.models.gemma4 import (
|
||||
Gemma4ForCausalLM,
|
||||
_gemma4_layer_weights_mapper,
|
||||
)
|
||||
|
||||
MODELS = ["google/gemma-2b", "google/gemma-2-2b", "google/gemma-3-4b-it"]
|
||||
|
||||
@@ -57,36 +60,70 @@ def test_checkpoint_lm_head_can_override_tied_config(monkeypatch) -> None:
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_gemma4_kv_shared_layer_loads_plain_q_proj() -> None:
|
||||
"""KV-shared layers have q_proj instead of a packed qkv_proj; their
|
||||
redundant K/V tensors in original checkpoints have no parameter and are
|
||||
skipped rather than failing the load."""
|
||||
model = torch.nn.Module()
|
||||
model.config = SimpleNamespace(num_experts=0)
|
||||
model.start_layer, model.end_layer = 0, 2
|
||||
model.layers = torch.nn.ModuleList([torch.nn.Module(), torch.nn.Module()])
|
||||
for layer in model.layers:
|
||||
layer.self_attn = torch.nn.Module()
|
||||
model.layers[0].self_attn.qkv_proj = torch.nn.Linear(2, 6, bias=False)
|
||||
model.layers[1].self_attn.q_proj = torch.nn.Linear(2, 2, bias=False)
|
||||
shards: list[str] = []
|
||||
model.layers[0].self_attn.qkv_proj.weight.weight_loader = (
|
||||
lambda param, weight, shard_id: shards.append(shard_id)
|
||||
def test_gemma4_attention_mapper() -> None:
|
||||
"""Layers with a qkv_proj pack q/k/v; `attention_k_eq_v` full-attention
|
||||
layers also load K as the V shard, and leave any v_proj such a checkpoint
|
||||
ships unmapped so it fails the load rather than silently overwriting V;
|
||||
KV-shared layers keep q_proj and drop the K/V tensors original checkpoints
|
||||
still ship for them."""
|
||||
config = SimpleNamespace(
|
||||
num_hidden_layers=3,
|
||||
num_kv_shared_layers=1,
|
||||
attention_k_eq_v=True,
|
||||
layer_types=["sliding_attention", "full_attention", "sliding_attention"],
|
||||
)
|
||||
|
||||
q_weight = torch.full((2, 2), 2.0)
|
||||
weights = [
|
||||
(f"layers.{i}.self_attn.{tensor}.weight", q_weight)
|
||||
for i in (0, 1)
|
||||
for tensor in ("q_proj", "k_proj", "v_proj")
|
||||
] + [("layers.1.self_attn.k_norm.weight", torch.ones(2))]
|
||||
loaded = Gemma4Model.load_weights(cast(Gemma4Model, model), weights)
|
||||
(f"model.layers.{i}.self_attn.{tensor}.weight", torch.full((2, 2), i + 1.0))
|
||||
for i in range(3)
|
||||
for tensor in ("q_proj", "k_proj", "k_norm")
|
||||
] + [
|
||||
("model.layers.0.mlp.up_proj.weight", torch.empty(0)),
|
||||
("model.layers.1.self_attn.v_proj.weight", torch.empty(0)),
|
||||
]
|
||||
|
||||
assert shards == ["q", "k", "v"]
|
||||
assert "layers.1.self_attn.q_proj.weight" in loaded
|
||||
assert not any(name.startswith("layers.1.self_attn.k") for name in loaded)
|
||||
assert not any(name.startswith("layers.1.self_attn.v") for name in loaded)
|
||||
assert torch.equal(model.layers[1].self_attn.q_proj.weight, q_weight)
|
||||
mapper = _gemma4_layer_weights_mapper(config)
|
||||
mapped = list(mapper.apply(weights))
|
||||
|
||||
assert [(name, getattr(w, "shard_id", None)) for name, w in mapped] == [
|
||||
("model.layers.0.self_attn.qkv_proj.weight", "q"),
|
||||
("model.layers.0.self_attn.qkv_proj.weight", "k"),
|
||||
("model.layers.0.self_attn.k_norm.weight", None),
|
||||
("model.layers.1.self_attn.qkv_proj.weight", "q"),
|
||||
("model.layers.1.self_attn.qkv_proj.weight", "k"),
|
||||
("model.layers.1.self_attn.qkv_proj.weight", "v"),
|
||||
("model.layers.1.self_attn.k_norm.weight", None),
|
||||
("model.layers.2.self_attn.q_proj.weight", None),
|
||||
("model.layers.0.mlp.gate_up_proj.weight", 1),
|
||||
("model.layers.1.self_attn.v_proj.weight", None),
|
||||
]
|
||||
k_weight, v_weight = weights[4][1], mapped[5][1]
|
||||
assert torch.equal(v_weight, k_weight) and v_weight is not k_weight
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_gemma4_expert_names_strip_language_model_prefix() -> None:
|
||||
"""The text-only path reuses the conditional wrapper's checkpoint naming,
|
||||
so fused and per-expert tensors reach the experts under `model.*`."""
|
||||
prefix = "model.language_model.layers.0."
|
||||
weights = [
|
||||
(prefix + name, torch.empty(0))
|
||||
for name in (
|
||||
"experts.gate_up_proj",
|
||||
"experts.3.down_proj.weight_packed",
|
||||
"router.per_expert_scale",
|
||||
)
|
||||
]
|
||||
|
||||
mapped = [
|
||||
(name, getattr(w, "shard_id", None))
|
||||
for name, w in Gemma4ForCausalLM.hf_to_vllm_mapper.apply(weights)
|
||||
]
|
||||
|
||||
assert mapped == [
|
||||
("model.layers.0.experts.gate_up_proj", None),
|
||||
("model.layers.0.experts.3.down_proj.weight_packed", None),
|
||||
("model.layers.0.router.per_expert_scale", None),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
|
||||
@@ -2,12 +2,40 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Pytest configuration for vLLM language generation tests."""
|
||||
|
||||
import gc
|
||||
|
||||
import pytest
|
||||
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__)
|
||||
|
||||
|
||||
def pytest_sessionstart(session):
|
||||
"""Configure ROCm-specific settings before test session starts."""
|
||||
if current_platform.is_rocm():
|
||||
torch.set_float32_matmul_precision("high")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def release_gpu_memory_between_tests():
|
||||
"""Reclaim cached GPU memory between tests in this shard.
|
||||
|
||||
These tests start many vLLM/HF engines sequentially in one pytest
|
||||
process; without explicit reclamation between tests, VRAM fragmentation
|
||||
accumulates and later tests fail at engine startup ("Engine core
|
||||
initialization failed").
|
||||
"""
|
||||
yield
|
||||
gc.collect()
|
||||
if torch.accelerator.is_available():
|
||||
torch.accelerator.empty_cache()
|
||||
try:
|
||||
wait_for_memory_to_settle()
|
||||
except ValueError as e:
|
||||
# Longer-lived (class/module-scoped) engine fixtures may legitimately
|
||||
# still hold VRAM; nothing further to reclaim in that case.
|
||||
logger.info("Failed to clean GPU memory: %s", e)
|
||||
|
||||
@@ -128,9 +128,12 @@ def _load_projection_weight(model_name: str, hf_spec: dict, device: torch.device
|
||||
"""Download and return the ColBERT linear projection weight."""
|
||||
from safetensors.torch import load_file
|
||||
|
||||
from vllm.transformers_utils.repo_utils import hf_api
|
||||
from vllm.transformers_utils.repo_utils import hf_api, with_retry
|
||||
|
||||
path = hf_api().hf_hub_download(model_name, filename=hf_spec["weights_file"])
|
||||
path = with_retry(
|
||||
lambda: hf_api().hf_hub_download(model_name, filename=hf_spec["weights_file"]),
|
||||
f"Error downloading {hf_spec['weights_file']} from {model_name}",
|
||||
)
|
||||
weights = load_file(path)
|
||||
return weights[hf_spec["weights_key"]].to(device)
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# ruff: noqa: SIM117
|
||||
|
||||
from functools import partial
|
||||
|
||||
import pytest
|
||||
|
||||
from ...utils import EmbedModelInfo
|
||||
@@ -26,6 +28,22 @@ original_max_position_embeddings = 2048
|
||||
max_model_len = int(original_max_position_embeddings * factor)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def predownload_models():
|
||||
"""Warm the HF cache so engine startup never hits transient hub errors."""
|
||||
from vllm.transformers_utils.repo_utils import hf_api, with_retry
|
||||
|
||||
for model_info in MODELS:
|
||||
with_retry(
|
||||
partial(
|
||||
hf_api().snapshot_download,
|
||||
model_info.name,
|
||||
revision=model_info.revision,
|
||||
),
|
||||
f"Error downloading {model_info.name}",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_info", MODELS)
|
||||
def test_default(model_info, vllm_runner):
|
||||
with vllm_runner(
|
||||
|
||||
@@ -115,6 +115,7 @@ def test_modernbert_models(
|
||||
|
||||
@pytest.mark.parametrize("model", ["Davlan/xlm-roberta-base-ner-hrl"])
|
||||
@pytest.mark.parametrize("dtype", ["float"])
|
||||
@pytest.mark.flaky(reruns=3)
|
||||
@torch.inference_mode
|
||||
def test_xlm_roberta_models(
|
||||
hf_runner,
|
||||
@@ -197,6 +198,7 @@ def test_openai_privacy_filter(
|
||||
|
||||
@pytest.mark.parametrize("model", ["bd2lcco/Qwen3-0.6B-finetuned"])
|
||||
@pytest.mark.parametrize("dtype", ["float"])
|
||||
@pytest.mark.flaky(reruns=3)
|
||||
@torch.inference_mode
|
||||
def test_auto_conversion(
|
||||
hf_runner,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Pytest configuration for vLLM pooling MTEB tests."""
|
||||
|
||||
import gc
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import wait_for_memory_to_settle
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def release_gpu_memory_between_tests():
|
||||
"""Reclaim cached GPU memory between tests in this shard.
|
||||
|
||||
These tests start many vLLM/HF engines sequentially in one pytest
|
||||
process; without explicit reclamation between tests, VRAM fragmentation
|
||||
accumulates and later tests fail at engine startup ("Engine core
|
||||
initialization failed").
|
||||
"""
|
||||
yield
|
||||
gc.collect()
|
||||
if torch.accelerator.is_available():
|
||||
torch.accelerator.empty_cache()
|
||||
try:
|
||||
wait_for_memory_to_settle()
|
||||
except ValueError as e:
|
||||
# Longer-lived (class/module-scoped) engine fixtures may legitimately
|
||||
# still hold VRAM; nothing further to reclaim in that case.
|
||||
logger.info("Failed to clean GPU memory: %s", e)
|
||||
@@ -161,10 +161,14 @@ def mteb_test_embed_models(
|
||||
model_info: EmbedModelInfo,
|
||||
vllm_extra_kwargs=None,
|
||||
hf_model_callback=None,
|
||||
atol=MTEB_EMBED_TOL,
|
||||
atol: float | None = None,
|
||||
prompt_prefix: str | None = None,
|
||||
vllm_model_callback=None,
|
||||
):
|
||||
if atol is None:
|
||||
atol = (
|
||||
model_info.mteb_tol if model_info.mteb_tol is not None else MTEB_EMBED_TOL
|
||||
)
|
||||
vllm_extra_kwargs = get_vllm_extra_kwargs(model_info, vllm_extra_kwargs)
|
||||
|
||||
# Test embed_dims, isnan and whether to use normalize
|
||||
@@ -268,4 +272,8 @@ def mteb_test_embed_models(
|
||||
|
||||
# We are not concerned that the vllm mteb results are better
|
||||
# than SentenceTransformers, so we only perform one-sided testing.
|
||||
assert st_main_score - vllm_main_score < atol
|
||||
diff = st_main_score - vllm_main_score
|
||||
assert diff < atol, (
|
||||
f"diff={diff:.6g} tol={atol} model={model_info.name} "
|
||||
f"(st={st_main_score}, vllm={vllm_main_score})"
|
||||
)
|
||||
|
||||
@@ -230,8 +230,12 @@ def mteb_test_rerank_models(
|
||||
hf_runner=HFMtebCrossEncoder,
|
||||
vllm_extra_kwargs=None,
|
||||
vllm_mteb_encoder=VllmMtebCrossEncoder,
|
||||
atol=MTEB_RERANK_TOL,
|
||||
atol: float | None = None,
|
||||
):
|
||||
if atol is None:
|
||||
atol = (
|
||||
model_info.mteb_tol if model_info.mteb_tol is not None else MTEB_RERANK_TOL
|
||||
)
|
||||
vllm_extra_kwargs = get_vllm_extra_kwargs(model_info, vllm_extra_kwargs)
|
||||
|
||||
# Maybe load chat_template.
|
||||
@@ -308,4 +312,8 @@ def mteb_test_rerank_models(
|
||||
|
||||
# We are not concerned that the vllm mteb results are better
|
||||
# than SentenceTransformers, so we only perform one-sided testing.
|
||||
assert st_main_score - vllm_main_score < atol
|
||||
diff = st_main_score - vllm_main_score
|
||||
assert diff < atol, (
|
||||
f"diff={diff:.6g} tol={atol} model={model_info.name} "
|
||||
f"(st={st_main_score}, vllm={vllm_main_score})"
|
||||
)
|
||||
|
||||
@@ -17,6 +17,7 @@ MODELS = [
|
||||
"BAAI/bge-base-en",
|
||||
architecture="BertModel",
|
||||
mteb_score=0.779336792,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -54,6 +55,7 @@ MODELS = [
|
||||
"BAAI/bge-m3",
|
||||
architecture="XLMRobertaModel",
|
||||
mteb_score=0.787343078,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -82,6 +84,7 @@ RERANK_MODELS = [
|
||||
"BAAI/bge-reranker-base",
|
||||
architecture="XLMRobertaForSequenceClassification",
|
||||
mteb_score=0.32398,
|
||||
mteb_tol=1e-2,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -101,6 +104,7 @@ RERANK_MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
|
||||
@@ -113,6 +117,7 @@ def test_embed_models_correctness(
|
||||
correctness_test_embed_models(hf_runner, vllm_runner, model_info, example_prompts)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
mteb_test_rerank_models(vllm_runner, model_info)
|
||||
|
||||
@@ -26,6 +26,7 @@ RERANK_MODELS = [
|
||||
"method": "no_post_processing",
|
||||
},
|
||||
mteb_score=0.33757,
|
||||
mteb_tol=1e-2,
|
||||
seq_pooling_type="LAST",
|
||||
attn_type="decoder",
|
||||
is_prefix_caching_supported=True,
|
||||
@@ -127,6 +128,7 @@ class GemmaRerankerHfRunner(MtebCrossEncoderMixin, HfRunner):
|
||||
return torch.Tensor(scores)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
mteb_test_rerank_models(
|
||||
|
||||
@@ -17,6 +17,7 @@ RERANK_MODELS = [
|
||||
is_prefix_caching_supported=False,
|
||||
is_chunked_prefill_supported=False,
|
||||
mteb_score=0.32898,
|
||||
mteb_tol=1e-2,
|
||||
),
|
||||
RerankModelInfo(
|
||||
"tomaarsen/Qwen3-Reranker-0.6B-seq-cls",
|
||||
@@ -27,10 +28,12 @@ RERANK_MODELS = [
|
||||
is_chunked_prefill_supported=True,
|
||||
chat_template_name="qwen3_reranker.jinja",
|
||||
mteb_score=0.33459,
|
||||
mteb_tol=1e-2,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
mteb_test_rerank_models(vllm_runner, model_info)
|
||||
|
||||
@@ -18,6 +18,7 @@ MODELS = [
|
||||
EmbedModelInfo(
|
||||
"thenlper/gte-large",
|
||||
mteb_score=0.76807651,
|
||||
mteb_tol=2e-3,
|
||||
architecture="BertModel",
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
@@ -44,6 +45,7 @@ MODELS = [
|
||||
"Alibaba-NLP/gte-multilingual-base",
|
||||
architecture="GteNewModel",
|
||||
mteb_score=0.775074696,
|
||||
mteb_tol=2e-3,
|
||||
hf_overrides={"architectures": ["GteNewModel"]},
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
@@ -79,6 +81,7 @@ MODELS = [
|
||||
EmbedModelInfo(
|
||||
"Alibaba-NLP/gte-modernbert-base",
|
||||
mteb_score=0.748193353,
|
||||
mteb_tol=2e-3,
|
||||
architecture="ModernBertModel",
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
@@ -90,6 +93,7 @@ MODELS = [
|
||||
EmbedModelInfo(
|
||||
"Qwen/Qwen3-Embedding-0.6B",
|
||||
mteb_score=0.771163695,
|
||||
mteb_tol=2e-3,
|
||||
architecture="Qwen3ForCausalLM",
|
||||
seq_pooling_type="LAST",
|
||||
attn_type="decoder",
|
||||
@@ -109,6 +113,7 @@ RERANK_MODELS = [
|
||||
# classifier_pooling: mean
|
||||
"Alibaba-NLP/gte-reranker-modernbert-base",
|
||||
mteb_score=0.33386,
|
||||
mteb_tol=1e-2,
|
||||
architecture="ModernBertForSequenceClassification",
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
@@ -119,6 +124,7 @@ RERANK_MODELS = [
|
||||
RerankModelInfo(
|
||||
"Alibaba-NLP/gte-multilingual-reranker-base",
|
||||
mteb_score=0.33062,
|
||||
mteb_tol=1e-2,
|
||||
architecture="GteNewForSequenceClassification",
|
||||
hf_overrides={"architectures": ["GteNewForSequenceClassification"]},
|
||||
seq_pooling_type="CLS",
|
||||
@@ -130,6 +136,7 @@ RERANK_MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
|
||||
@@ -142,6 +149,7 @@ def test_embed_models_correctness(
|
||||
correctness_test_embed_models(hf_runner, vllm_runner, model_info, example_prompts)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
vllm_extra_kwargs = {}
|
||||
|
||||
@@ -13,6 +13,7 @@ MODELS = [
|
||||
"intfloat/e5-small",
|
||||
architecture="BertModel",
|
||||
mteb_score=0.742285423,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -29,6 +30,7 @@ MODELS = [
|
||||
"intfloat/multilingual-e5-base",
|
||||
architecture="XLMRobertaModel",
|
||||
mteb_score=0.779325955,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -48,6 +50,7 @@ MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
|
||||
|
||||
@@ -23,6 +23,7 @@ EMBEDDING_MODELS = [
|
||||
EmbedModelInfo(
|
||||
"jinaai/jina-embeddings-v3",
|
||||
mteb_score=0.824413164,
|
||||
mteb_tol=2e-3,
|
||||
architecture="XLMRobertaModel",
|
||||
is_matryoshka=True,
|
||||
seq_pooling_type="MEAN",
|
||||
@@ -33,6 +34,7 @@ EMBEDDING_MODELS = [
|
||||
EmbedModelInfo(
|
||||
"jinaai/jina-embeddings-v5-text-small",
|
||||
mteb_score=0.794535707854956,
|
||||
mteb_tol=2e-3,
|
||||
architecture="JinaEmbeddingsV5Model",
|
||||
seq_pooling_type="LAST",
|
||||
attn_type="decoder",
|
||||
@@ -42,6 +44,7 @@ EMBEDDING_MODELS = [
|
||||
EmbedModelInfo(
|
||||
"jinaai/jina-embeddings-v5-text-nano",
|
||||
architecture="JinaEmbeddingsV5Model",
|
||||
mteb_tol=2e-3,
|
||||
dtype="bfloat16" if current_platform.is_rocm() else "auto",
|
||||
seq_pooling_type="LAST",
|
||||
attn_type="encoder_only",
|
||||
@@ -54,6 +57,7 @@ RERANK_MODELS = [
|
||||
RerankModelInfo(
|
||||
"jinaai/jina-reranker-v2-base-multilingual",
|
||||
mteb_score=0.33643,
|
||||
mteb_tol=1e-2,
|
||||
architecture="XLMRobertaForSequenceClassification",
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
@@ -63,6 +67,7 @@ RERANK_MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", EMBEDDING_MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
task = "retrieval" if "v5" in model_info.name else "text-matching"
|
||||
@@ -98,6 +103,7 @@ def test_embed_models_correctness(
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
mteb_test_rerank_models(vllm_runner, model_info)
|
||||
|
||||
@@ -56,6 +56,7 @@ def _assert_modernbert_online_fp8(model) -> None:
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.skipif(
|
||||
_fp8_scaled_mm_unsupported(),
|
||||
reason="No FP8 ScaledMM kernel is available on this GPU type.",
|
||||
|
||||
@@ -30,6 +30,7 @@ RERANK_MODELS = [
|
||||
is_chunked_prefill_supported=True,
|
||||
chat_template_name="mxbai_rerank_v2.jinja",
|
||||
mteb_score=0.33651,
|
||||
mteb_tol=1e-2,
|
||||
enable_test=True,
|
||||
),
|
||||
RerankModelInfo(
|
||||
@@ -104,6 +105,7 @@ class MxbaiRerankerHfRunner(MtebCrossEncoderMixin, HfRunner):
|
||||
return torch.Tensor(scores)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
mteb_test_rerank_models(vllm_runner, model_info, hf_runner=MxbaiRerankerHfRunner)
|
||||
|
||||
@@ -19,6 +19,7 @@ EMBEDDING_MODELS = [
|
||||
"nvidia/llama-nemotron-embed-1b-v2",
|
||||
architecture="LlamaBidirectionalModel",
|
||||
mteb_score=0.689164662128673,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -32,6 +33,7 @@ RERANK_MODELS = [
|
||||
architecture="LlamaBidirectionalForSequenceClassification",
|
||||
chat_template_name="nemotron-rerank.jinja",
|
||||
mteb_score=0.33994,
|
||||
mteb_tol=1e-2,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -40,11 +42,13 @@ RERANK_MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", EMBEDDING_MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
mteb_test_rerank_models(vllm_runner, model_info)
|
||||
|
||||
@@ -17,6 +17,7 @@ MODELS = [
|
||||
# HF version and remove revision set.
|
||||
revision="720244025c1a7e15661a174c63cce63c8218e52b",
|
||||
mteb_score=0.737568559,
|
||||
mteb_tol=2e-3,
|
||||
enable_test=True,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
@@ -35,6 +36,7 @@ MODELS = [
|
||||
"nomic-ai/nomic-embed-text-v2-moe",
|
||||
architecture="NomicBertModel",
|
||||
mteb_score=0.715488912,
|
||||
mteb_tol=2e-3,
|
||||
enable_test=True,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
@@ -44,6 +46,7 @@ MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
|
||||
|
||||
@@ -32,6 +32,7 @@ RERANK_MODELS = [
|
||||
is_prefix_caching_supported=True,
|
||||
is_chunked_prefill_supported=True,
|
||||
mteb_score=0.33459,
|
||||
mteb_tol=1e-2,
|
||||
enable_test=True,
|
||||
),
|
||||
RerankModelInfo(
|
||||
@@ -108,11 +109,13 @@ class Qwen3RerankerHfRunner(MtebCrossEncoderMixin, HfRunner):
|
||||
return torch.Tensor(scores)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
def test_rerank_models_mteb(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
mteb_test_rerank_models(vllm_runner, model_info, hf_runner=Qwen3RerankerHfRunner)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", RERANK_MODELS)
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
def test_rerank_models_mteb_tp(vllm_runner, model_info: RerankModelInfo) -> None:
|
||||
|
||||
@@ -14,6 +14,7 @@ MODELS = [
|
||||
is_matryoshka=False,
|
||||
architecture="BertModel",
|
||||
mteb_score=0.714927797,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -37,6 +38,7 @@ MODELS = [
|
||||
is_matryoshka=False,
|
||||
architecture="NomicBertModel",
|
||||
mteb_score=0.681146831,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -54,6 +56,7 @@ MODELS = [
|
||||
is_matryoshka=True,
|
||||
architecture="BertModel",
|
||||
mteb_score=0.649088363,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -65,6 +68,7 @@ MODELS = [
|
||||
is_matryoshka=True,
|
||||
architecture="XLMRobertaModel",
|
||||
mteb_score=0.712258299,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -76,6 +80,7 @@ MODELS = [
|
||||
is_matryoshka=True,
|
||||
architecture="GteModel",
|
||||
mteb_score=0.706622444,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="CLS",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -85,6 +90,7 @@ MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
|
||||
|
||||
@@ -14,6 +14,7 @@ ST_PROJECTOR_MODELS = [
|
||||
"TencentBAC/Conan-embedding-v1",
|
||||
architecture="BertModel",
|
||||
mteb_score=0.688611955,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -24,6 +25,7 @@ ST_PROJECTOR_MODELS = [
|
||||
"google/embeddinggemma-300m",
|
||||
architecture="Gemma3TextModel",
|
||||
mteb_score=0.7473819294684156,
|
||||
mteb_tol=2e-3,
|
||||
seq_pooling_type="MEAN",
|
||||
attn_type="encoder_only",
|
||||
is_prefix_caching_supported=False,
|
||||
@@ -33,6 +35,7 @@ ST_PROJECTOR_MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", ST_PROJECTOR_MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
mteb_test_embed_models(hf_runner, vllm_runner, model_info)
|
||||
|
||||
@@ -22,6 +22,7 @@ MODELS = [
|
||||
"num_labels": 2048,
|
||||
},
|
||||
mteb_score=0.7054,
|
||||
mteb_tol=2e-3,
|
||||
# === MTEB Results ===
|
||||
# STS12: 0.6613
|
||||
# STS13: 0.6906
|
||||
@@ -34,6 +35,7 @@ MODELS = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2)
|
||||
@pytest.mark.parametrize("model_info", MODELS)
|
||||
def test_embed_models_mteb(hf_runner, vllm_runner, model_info: EmbedModelInfo) -> None:
|
||||
# Encoder-only attention models need enforce_eager=True to avoid
|
||||
|
||||
@@ -317,8 +317,6 @@ VLM_TEST_SETTINGS = {
|
||||
img_idx_to_prompt=lambda idx: "",
|
||||
auto_cls=AutoModelForImageTextToText,
|
||||
vllm_output_post_proc=model_utils.blip2_vllm_to_hf_output,
|
||||
# FIXME: https://github.com/huggingface/transformers/pull/38510
|
||||
marks=[pytest.mark.skip("Model is broken")],
|
||||
),
|
||||
"cosmos3": VLMTestInfo(
|
||||
models=["nvidia/Cosmos3-Nano"],
|
||||
@@ -819,10 +817,6 @@ VLM_TEST_SETTINGS = {
|
||||
patch_hf_runner=model_utils.paddleocr_vl_patch_hf_runner,
|
||||
image_size_factors=[(0.25,)],
|
||||
marks=[
|
||||
pytest.mark.skipif(
|
||||
Version(TRANSFORMERS_VERSION) == Version("4.57.3"),
|
||||
reason="This model is broken in Transformers v4.57.3",
|
||||
),
|
||||
pytest.mark.skipif(
|
||||
Version(TRANSFORMERS_VERSION) >= Version("5.0.0"),
|
||||
reason="Model's custom code uses ROPE_INIT_FUNCTIONS"
|
||||
|
||||
@@ -499,3 +499,118 @@ def test_vit_cudagraph_video(model_id, vllm_runner, video_assets):
|
||||
|
||||
# Ensure the output is a string
|
||||
assert isinstance(output_text, str)
|
||||
|
||||
|
||||
def _check_eonly_encoder_outputs(worker, batches):
|
||||
"""Compare real E-only replay with eager, retaining outputs across replay."""
|
||||
import torch
|
||||
|
||||
from vllm.v1.worker.mm_encoder_model_runner import MMEncoderModelRunner
|
||||
|
||||
runner = worker.model_runner
|
||||
assert isinstance(runner, MMEncoderModelRunner)
|
||||
manager = runner.model_state.encoder_runner.cudagraph_manager
|
||||
assert manager is not None and manager.is_captured()
|
||||
retained: list[tuple[torch.Tensor, torch.Tensor]] = []
|
||||
max_error = 0.0
|
||||
stats = []
|
||||
with torch.inference_mode():
|
||||
for batch in batches:
|
||||
kwargs = {key: value.to(runner.device) for key, value in batch.items()}
|
||||
actual = manager.execute(kwargs)
|
||||
expected = runner.model.embed_multimodal(**kwargs)
|
||||
assert len(actual) == len(expected)
|
||||
for output, reference in zip(actual, expected):
|
||||
assert torch.isfinite(output).all()
|
||||
# Two BF16 ulps at unit scale, fixed before model validation.
|
||||
torch.testing.assert_close(output, reference, rtol=0.016, atol=0.016)
|
||||
max_error = max(max_error, (output - reference).abs().max().item())
|
||||
for output, snapshot in retained:
|
||||
torch.testing.assert_close(output, snapshot, rtol=0, atol=0)
|
||||
retained.extend((output, output.clone()) for output in actual)
|
||||
stats.append(manager.get_cumulative_stats())
|
||||
assert stats[0]["graph_hits"] > 0
|
||||
assert stats[1]["graph_hits"] > stats[0]["graph_hits"]
|
||||
assert stats[2]["graph_misses"] > stats[1]["graph_misses"]
|
||||
assert stats[3]["graph_hits"] > stats[2]["graph_hits"]
|
||||
assert stats[4]["graph_hits"] > stats[3]["graph_hits"]
|
||||
assert stats[5]["graph_hits"] > stats[4]["graph_hits"]
|
||||
assert stats[6]["graph_hits"] > stats[5]["graph_hits"]
|
||||
return {"max_abs_error": max_error, "stats": stats}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_id",
|
||||
params_with_marks({key: MODEL_CONFIGS[key] for key in ("qwen3_vl", "qwen3_5")}),
|
||||
)
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA graphs")
|
||||
def test_eonly_vit_cudagraph_outputs(
|
||||
model_id, vllm_runner, image_assets, video_assets, monkeypatch
|
||||
):
|
||||
"""Exercise startup capture, image/video replay, fallback and output ownership."""
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from transformers import AutoProcessor
|
||||
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
config = MODEL_CONFIGS[model_id]
|
||||
token_budgets = [64, 256, 2048]
|
||||
processor = AutoProcessor.from_pretrained(config.model)
|
||||
first, second = [asset.pil_image for asset in image_assets]
|
||||
batches = [
|
||||
[first.resize((224, 224))],
|
||||
[second.resize((448, 224)), first.resize((224, 224))],
|
||||
[second.resize((1792, 1792))],
|
||||
[second.resize((224, 224))],
|
||||
[first.resize((1280, 720))],
|
||||
[first.resize((224, 224))],
|
||||
]
|
||||
frames = sample_frames_from_video(video_assets[0].np_ndarrays, 2)
|
||||
video = np.stack(
|
||||
[np.asarray(Image.fromarray(frame).resize((224, 224))) for frame in frames]
|
||||
)
|
||||
with vllm_runner(
|
||||
config.model,
|
||||
dtype=config.dtype,
|
||||
mm_encoder_only=True,
|
||||
# FA padding NaNs are tracked separately in #57136.
|
||||
mm_encoder_attn_backend="FLASHINFER",
|
||||
enable_prefix_caching=False,
|
||||
max_model_len=4096,
|
||||
max_num_seqs=2,
|
||||
limit_mm_per_prompt={"image": 2, "video": 1},
|
||||
compilation_config={
|
||||
"cudagraph_mode": "NONE",
|
||||
"cudagraph_mm_encoder": True,
|
||||
"encoder_cudagraph_token_budgets": token_budgets,
|
||||
"encoder_cudagraph_max_vision_items_per_batch": 2,
|
||||
"encoder_cudagraph_max_frames_per_batch": 2,
|
||||
},
|
||||
) as model:
|
||||
mm_config = model.llm.llm_engine.vllm_config.model_config.multimodal_config
|
||||
processor_kwargs = mm_config.merge_mm_processor_kwargs({})
|
||||
inputs = [
|
||||
dict(
|
||||
processor.image_processor(
|
||||
images=images, return_tensors="pt", **processor_kwargs
|
||||
)
|
||||
)
|
||||
for images in batches
|
||||
]
|
||||
inputs.append(
|
||||
dict(
|
||||
processor.video_processor(
|
||||
videos=[video],
|
||||
do_sample_frames=False,
|
||||
return_tensors="pt",
|
||||
**processor_kwargs,
|
||||
)
|
||||
)
|
||||
)
|
||||
results = model.llm.collective_rpc(
|
||||
partial(_check_eonly_encoder_outputs, batches=inputs)
|
||||
)
|
||||
for result in results:
|
||||
assert result["stats"][0]["token_budgets"] == token_budgets
|
||||
print(f"E-only {model_id}: {results}")
|
||||
|
||||
@@ -308,16 +308,6 @@ def gemma3_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
|
||||
|
||||
hf_model.processor = processor
|
||||
|
||||
orig_generate = hf_model.model.generate
|
||||
|
||||
def _generate(self, *args, **kwargs):
|
||||
# FIXME: https://github.com/huggingface/transformers/issues/38333
|
||||
kwargs["disable_compile"] = True
|
||||
|
||||
return orig_generate(*args, **kwargs)
|
||||
|
||||
hf_model.model.generate = types.MethodType(_generate, hf_model.model)
|
||||
|
||||
return hf_model
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Pytest configuration for vLLM multimodal pooling tests."""
|
||||
|
||||
import gc
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import wait_for_memory_to_settle
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def release_gpu_memory_between_tests():
|
||||
"""Reclaim cached GPU memory between tests in this shard.
|
||||
|
||||
These tests start many vLLM/HF engines sequentially in one pytest
|
||||
process; without explicit reclamation between tests, VRAM fragmentation
|
||||
accumulates and later tests fail at engine startup ("Engine core
|
||||
initialization failed").
|
||||
"""
|
||||
yield
|
||||
gc.collect()
|
||||
if torch.accelerator.is_available():
|
||||
torch.accelerator.empty_cache()
|
||||
try:
|
||||
wait_for_memory_to_settle()
|
||||
except ValueError as e:
|
||||
# Longer-lived (class/module-scoped) engine fixtures may legitimately
|
||||
# still hold VRAM; nothing further to reclaim in that case.
|
||||
logger.info("Failed to clean GPU memory: %s", e)
|
||||
@@ -2,8 +2,6 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import transformers
|
||||
from packaging import version
|
||||
from transformers import AutoModel
|
||||
|
||||
from vllm.assets.base import VLLM_S3_BUCKET_URL
|
||||
@@ -246,10 +244,6 @@ def _run_test(
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.skipif(
|
||||
version.parse(transformers.__version__) == version.parse("4.57.5"),
|
||||
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
|
||||
)
|
||||
def test_model_text_image(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
@@ -269,10 +263,6 @@ def test_model_text_image(
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.skipif(
|
||||
version.parse(transformers.__version__) == version.parse("4.57.5"),
|
||||
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
|
||||
)
|
||||
def test_model_text_text(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
@@ -292,10 +282,6 @@ def test_model_text_text(
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.skipif(
|
||||
version.parse(transformers.__version__) == version.parse("4.57.5"),
|
||||
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
|
||||
)
|
||||
def test_model_image_text(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
@@ -315,10 +301,6 @@ def test_model_image_text(
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.skipif(
|
||||
version.parse(transformers.__version__) == version.parse("4.57.5"),
|
||||
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
|
||||
)
|
||||
def test_model_image_image(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
@@ -338,10 +320,6 @@ def test_model_image_image(
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.skipif(
|
||||
version.parse(transformers.__version__) == version.parse("4.57.5"),
|
||||
reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
|
||||
)
|
||||
def test_model_text_mixed_documents(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
|
||||
@@ -63,36 +63,32 @@ def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> Non
|
||||
mm_processor_cache_gb=1,
|
||||
)
|
||||
|
||||
# Baseline: no cache, always processes from scratch.
|
||||
baseline_processor = MULTIMODAL_REGISTRY.create_processor(
|
||||
ctx.model_config, cache=None
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
|
||||
# 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)
|
||||
cached_processor = MULTIMODAL_REGISTRY.create_processor(
|
||||
ctx.model_config, cache=sender_cache
|
||||
)
|
||||
|
||||
video_token_id = baseline_processor.info.get_hf_config().video_token_id
|
||||
video_token_id = processor.info.get_hf_config().video_token_id
|
||||
|
||||
mm_data = create_mm_data(num_videos)
|
||||
hf_processor_mm_kwargs = {"use_audio_in_video": True}
|
||||
|
||||
def run(processor):
|
||||
def run(processor, cache):
|
||||
return processor(
|
||||
[video_token_id] * num_videos,
|
||||
mm_items=baseline_processor.info.parse_mm_data(mm_data),
|
||||
mm_items=processor.info.parse_mm_data(mm_data),
|
||||
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
|
||||
cache=cache,
|
||||
)["prompt_token_ids"]
|
||||
|
||||
baseline_ids = run(baseline_processor)
|
||||
baseline_ids = run(processor, cache=None)
|
||||
|
||||
# First call on the sender-cache processor: cache miss.
|
||||
# mm_kwargs["video"] items are real tensors; use_audio_in_video is
|
||||
# detected normally from the item data.
|
||||
first_ids = run(cached_processor)
|
||||
first_ids = run(processor, cache=sender_cache)
|
||||
assert first_ids == baseline_ids, (
|
||||
"Cache-miss call produced different prompt_token_ids than baseline.\n"
|
||||
f" baseline : {baseline_ids}\n"
|
||||
@@ -103,7 +99,7 @@ def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> Non
|
||||
# MultiModalProcessorSenderCache.get_and_update_item returns (None, …),
|
||||
# so mm_kwargs["video"] = [None]. Before the fix, use_audio_in_video was
|
||||
# not detected, yielding wrong token ids.
|
||||
second_ids = run(cached_processor)
|
||||
second_ids = run(processor, cache=sender_cache)
|
||||
assert second_ids == baseline_ids, (
|
||||
"Cache-hit call produced different prompt_token_ids than baseline.\n"
|
||||
"This is the regression introduced when use_audio_in_video detection\n"
|
||||
@@ -123,7 +119,7 @@ def test_use_audio_in_video_without_audio_track(model_id: str) -> None:
|
||||
model_id,
|
||||
limit_mm_per_prompt={"audio": 1, "image": 0, "video": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config, cache=None)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
video_token_id = processor.info.get_hf_config().video_token_id
|
||||
|
||||
rng = np.random.RandomState(0)
|
||||
|
||||
@@ -25,6 +25,7 @@ import torch
|
||||
from transformers import PretrainedConfig
|
||||
|
||||
from tests.models.registry import HF_EXAMPLE_MODELS
|
||||
from vllm.config.multimodal import MultiModalDummyOptions
|
||||
|
||||
|
||||
class MockAudioFlamingo3Config(PretrainedConfig):
|
||||
@@ -127,7 +128,7 @@ def test_dummy_data_generation(mock_ctx):
|
||||
builder = AudioFlamingo3DummyInputsBuilder(info)
|
||||
|
||||
mm_counts = {"audio": 2}
|
||||
dummy_data = builder.get_dummy_mm_data(100, mm_counts, {})
|
||||
dummy_data = builder.get_dummy_mm_data(100, mm_counts, MultiModalDummyOptions())
|
||||
|
||||
assert "audio" in dummy_data
|
||||
assert len(dummy_data["audio"]) == 2
|
||||
|
||||
@@ -13,6 +13,7 @@ from vllm.config.multimodal import (
|
||||
AudioDummyOptions,
|
||||
BaseDummyOptions,
|
||||
ImageDummyOptions,
|
||||
MultiModalDummyOptions,
|
||||
VideoDummyOptions,
|
||||
)
|
||||
from vllm.inputs import MultiModalDataDict, MultiModalInput
|
||||
@@ -71,6 +72,8 @@ def glmasr_patch_mm_data(mm_data: MultiModalDataDict) -> MultiModalDataDict:
|
||||
|
||||
|
||||
_IGNORE_MM_KEYS = {
|
||||
# Dithering causes minor divergence
|
||||
"cohere_asr": {"input_features"},
|
||||
# In Ultravox, the audio_features can be different depending on padding
|
||||
# The slight difference should not be a problem though, since
|
||||
# attention_mask lets us ignore the difference.
|
||||
@@ -174,7 +177,7 @@ def get_token_prompt(
|
||||
inputs = dummy_inputs.get_dummy_processor_inputs(
|
||||
model_config.max_model_len,
|
||||
mm_counts,
|
||||
mm_options={},
|
||||
mm_options=MultiModalDummyOptions(),
|
||||
# Assume all Mistral models define this extra argument
|
||||
mm_data=mm_data, # type: ignore[call-arg]
|
||||
)
|
||||
@@ -182,7 +185,7 @@ def get_token_prompt(
|
||||
inputs = dummy_inputs.get_dummy_processor_inputs(
|
||||
model_config.max_model_len,
|
||||
mm_counts,
|
||||
mm_options={},
|
||||
mm_options=MultiModalDummyOptions(),
|
||||
)
|
||||
|
||||
if not isinstance(inputs.prompt, list):
|
||||
@@ -278,13 +281,14 @@ def _test_processing_correctness(
|
||||
return BaseDummyOptions(count=count)
|
||||
|
||||
# Assign normalized DummyOptions to the model config
|
||||
model_config.get_multimodal_config().limit_per_prompt = {
|
||||
modality: _to_dummy_options(modality, count)
|
||||
for modality, count in limit_mm_per_prompt_ints.items()
|
||||
}
|
||||
model_config.get_multimodal_config().limit_per_prompt = MultiModalDummyOptions(
|
||||
{
|
||||
modality: _to_dummy_options(modality, count)
|
||||
for modality, count in limit_mm_per_prompt_ints.items()
|
||||
}
|
||||
)
|
||||
|
||||
baseline_processor = factories.build_processor(ctx, cache=None)
|
||||
cached_processor = factories.build_processor(ctx, cache=cache)
|
||||
processor = factories.build_processor(ctx)
|
||||
|
||||
rng = np.random.RandomState(0)
|
||||
|
||||
@@ -333,41 +337,42 @@ def _test_processing_correctness(
|
||||
_test_processing_correctness_one(
|
||||
model_config,
|
||||
mm_data,
|
||||
baseline_processor,
|
||||
cached_processor,
|
||||
processor,
|
||||
batch_idx,
|
||||
hit_rate,
|
||||
num_batches,
|
||||
simplify_rate,
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
|
||||
def _test_processing_correctness_one(
|
||||
model_config: ModelConfig,
|
||||
mm_data: MultiModalDataDict,
|
||||
baseline_processor: BaseMultiModalProcessor,
|
||||
cached_processor: BaseMultiModalProcessor,
|
||||
processor: BaseMultiModalProcessor,
|
||||
batch_idx: int,
|
||||
hit_rate: float,
|
||||
num_batches: int,
|
||||
simplify_rate: float,
|
||||
cache: MultiModalProcessorOnlyCache,
|
||||
):
|
||||
model_type = model_config.hf_config.model_type
|
||||
|
||||
token_prompt = get_token_prompt(baseline_processor, mm_data)
|
||||
mm_items = baseline_processor.info.parse_mm_data(mm_data)
|
||||
token_prompt = get_token_prompt(processor, mm_data)
|
||||
mm_items = processor.info.parse_mm_data(mm_data)
|
||||
ignore_mm_keys = _IGNORE_MM_KEYS.get(model_type, set[str]())
|
||||
|
||||
baseline_tokenized_result = baseline_processor(
|
||||
baseline_tokenized_result = processor(
|
||||
token_prompt,
|
||||
mm_items=mm_items,
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
|
||||
cached_tokenized_result = cached_processor(
|
||||
cached_tokenized_result = processor(
|
||||
token_prompt,
|
||||
mm_items=mm_items,
|
||||
hf_processor_mm_kwargs={},
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
_assert_inputs_equal(
|
||||
|
||||
@@ -221,7 +221,7 @@ def test_video_cache_is_independent_of_image_kwargs(
|
||||
mm_processor_cache_gb=1,
|
||||
)
|
||||
cache = MultiModalProcessorOnlyCache(ctx.model_config)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config, cache=cache)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
hf_processor = processor.info.get_hf_processor()
|
||||
image = PILImage.new("RGB", (48, 48), color=(128, 128, 128))
|
||||
frames = np.stack([np.asarray(image)] * 2)
|
||||
@@ -230,15 +230,16 @@ def test_video_cache_is_independent_of_image_kwargs(
|
||||
{"image": image, "video": [(frames, metadata)]}
|
||||
)
|
||||
|
||||
def process(mm_kwargs):
|
||||
def process(mm_kwargs, cache):
|
||||
return processor(
|
||||
hf_processor.image_token + hf_processor.video_token,
|
||||
mm_items,
|
||||
mm_uuid_items={"video": [video_uuid]},
|
||||
hf_processor_mm_kwargs=mm_kwargs,
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
baseline = process({})
|
||||
baseline = process({}, cache=None)
|
||||
if kwargs_on_init:
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
@@ -247,12 +248,12 @@ def test_video_cache_is_independent_of_image_kwargs(
|
||||
mm_processor_cache_gb=1,
|
||||
)
|
||||
cache = MultiModalProcessorOnlyCache(ctx.model_config)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config, cache=cache)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
request_kwargs = {} if kwargs_on_init else kwargs
|
||||
process(request_kwargs)
|
||||
cached = process(request_kwargs)
|
||||
process(request_kwargs, cache=cache)
|
||||
cached = process(request_kwargs, cache=cache)
|
||||
cache.clear_cache()
|
||||
fresh = process(request_kwargs)
|
||||
fresh = process(request_kwargs, cache=cache)
|
||||
|
||||
def pixels(result, modality, field):
|
||||
return result["mm_kwargs"][modality][0][field].data
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
"""Tests for Idefics3's multimodal preprocessing kwargs."""
|
||||
|
||||
import pytest
|
||||
from packaging.version import Version
|
||||
from transformers import Idefics3Config
|
||||
from transformers import __version__ as TRANSFORMERS_VERSION
|
||||
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
@@ -13,10 +11,6 @@ from ....conftest import ImageTestAssets
|
||||
from ...utils import build_model_context
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
Version(TRANSFORMERS_VERSION) < Version("5.2.0"),
|
||||
reason="See https://github.com/huggingface/transformers/pull/43948",
|
||||
)
|
||||
@pytest.mark.parametrize("model_id", ["HuggingFaceM4/Idefics3-8B-Llama3"])
|
||||
@pytest.mark.parametrize(
|
||||
("mm_processor_kwargs", "expected_toks_per_img"),
|
||||
|
||||
@@ -23,11 +23,9 @@ def test_profiling(model_id: str, max_model_len: int):
|
||||
model_config_kwargs=model_config_kwargs,
|
||||
limit_mm_per_prompt=mm_counts,
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
|
||||
mm_inputs = MULTIMODAL_REGISTRY.get_dummy_mm_inputs(
|
||||
ctx.model_config,
|
||||
mm_counts=mm_counts,
|
||||
)
|
||||
mm_inputs = processor.get_dummy_mm_inputs(mm_counts)
|
||||
|
||||
hf_config = ctx.get_hf_config(Llama4Config)
|
||||
image_size = hf_config.vision_config.image_size
|
||||
|
||||
@@ -6,7 +6,7 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config.multimodal import VideoDummyOptions
|
||||
from vllm.config.multimodal import MultiModalDummyOptions, VideoDummyOptions
|
||||
from vllm.model_executor.models.molmo2 import (
|
||||
Molmo2DummyInputsBuilder,
|
||||
build_flat_image_bool_length,
|
||||
@@ -83,7 +83,9 @@ def test_dummy_video_num_frames_override_honors_min_of_two(
|
||||
data = builder.get_dummy_mm_data(
|
||||
seq_len=128,
|
||||
mm_counts={"image": 0, "video": 1},
|
||||
mm_options={"video": VideoDummyOptions(num_frames=num_frames_override)},
|
||||
mm_options=MultiModalDummyOptions(
|
||||
video=VideoDummyOptions(num_frames=num_frames_override)
|
||||
),
|
||||
)
|
||||
|
||||
video, _metadata = data["video"][0]
|
||||
|
||||
@@ -168,7 +168,6 @@ def _build_moss_audio_processor(cache=None):
|
||||
MossAudioMultiModalProcessor(
|
||||
info,
|
||||
MossAudioDummyInputsBuilder(info),
|
||||
cache=cache,
|
||||
),
|
||||
ctx,
|
||||
)
|
||||
@@ -259,21 +258,24 @@ def test_moss_audio_multimodal_processor_handles_token_and_cache_paths():
|
||||
)
|
||||
|
||||
cache = MultiModalProcessorOnlyCache(ctx.model_config)
|
||||
cached_processor, _ = _build_moss_audio_processor(cache=cache)
|
||||
cached_processor, _ = _build_moss_audio_processor()
|
||||
cached_text_miss = cached_processor(
|
||||
prompt,
|
||||
mm_items=mm_items,
|
||||
hf_processor_mm_kwargs={},
|
||||
cache=cache,
|
||||
)
|
||||
cached_text_hit = cached_processor(
|
||||
prompt,
|
||||
mm_items=mm_items,
|
||||
hf_processor_mm_kwargs={},
|
||||
cache=cache,
|
||||
)
|
||||
cached_token_hit = cached_processor(
|
||||
token_prompt,
|
||||
mm_items=mm_items,
|
||||
hf_processor_mm_kwargs={},
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
expected_audio_tokens = MossAudioEncoder.compute_num_audio_tokens(raw_mel_len)
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from packaging.version import Version
|
||||
from PIL import Image
|
||||
from transformers import __version__ as TRANSFORMERS_VERSION
|
||||
|
||||
from vllm.model_executor.models.vision import FusedInputNorm
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
@@ -28,7 +26,6 @@ def test_jina_vl_processing_order() -> None:
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(
|
||||
ctx.model_config,
|
||||
tokenizer=ctx.tokenizer,
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
placeholder = "<|vision_start|><|image_pad|><|vision_end|>"
|
||||
@@ -39,6 +36,7 @@ def test_jina_vl_processing_order() -> None:
|
||||
return processor(
|
||||
placeholder * len(images),
|
||||
mm_items=processor.info.parse_mm_data({"image": images}),
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
query = process([query_image])
|
||||
@@ -133,12 +131,6 @@ def test_processor_override(
|
||||
kwargs_on_init: bool,
|
||||
):
|
||||
"""Ensure Qwen2VLMultiModalProcessor handles min/max pixels properly."""
|
||||
if (
|
||||
Version(TRANSFORMERS_VERSION) < Version("5.2.0")
|
||||
and "size" in mm_processor_kwargs
|
||||
):
|
||||
pytest.skip("`size` ignored by `Qwen2VLProcessor.__call__`")
|
||||
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
mm_processor_kwargs=mm_processor_kwargs if kwargs_on_init else None,
|
||||
@@ -184,12 +176,6 @@ def test_get_image_size_with_most_features(
|
||||
model_id: str,
|
||||
mm_processor_kwargs: dict[str, object],
|
||||
):
|
||||
if (
|
||||
Version(TRANSFORMERS_VERSION) < Version("5.2.0")
|
||||
and "size" in mm_processor_kwargs
|
||||
):
|
||||
pytest.skip("`size` ignored by `Qwen2VLProcessor.__call__`")
|
||||
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
mm_processor_kwargs=mm_processor_kwargs,
|
||||
|
||||
@@ -12,6 +12,7 @@ import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.config.multimodal import MultiModalDummyOptions
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
from ...registry import HF_EXAMPLE_MODELS
|
||||
@@ -339,7 +340,9 @@ def test_dummy_video_spreads_budget_when_frame_cap_enabled(model_id: str) -> Non
|
||||
limit_mm_per_prompt={"image": 0, "video": 1},
|
||||
)
|
||||
capped = MULTIMODAL_REGISTRY.create_processor(capped_ctx.model_config)
|
||||
capped_dummy = capped.dummy_inputs.get_dummy_mm_data(1024, {"video": 1}, {})
|
||||
capped_dummy = capped.dummy_inputs.get_dummy_mm_data(
|
||||
1024, {"video": 1}, MultiModalDummyOptions()
|
||||
)
|
||||
capped_frames = capped_dummy["video"][0][0].shape[0]
|
||||
assert capped_frames == 16, (
|
||||
f"Expected the dummy to spread the budget over 16 frames, got {capped_frames}"
|
||||
@@ -351,7 +354,9 @@ def test_dummy_video_spreads_budget_when_frame_cap_enabled(model_id: str) -> Non
|
||||
limit_mm_per_prompt={"image": 0, "video": 1},
|
||||
)
|
||||
uncapped = MULTIMODAL_REGISTRY.create_processor(uncapped_ctx.model_config)
|
||||
uncapped_dummy = uncapped.dummy_inputs.get_dummy_mm_data(1024, {"video": 1}, {})
|
||||
uncapped_dummy = uncapped.dummy_inputs.get_dummy_mm_data(
|
||||
1024, {"video": 1}, MultiModalDummyOptions()
|
||||
)
|
||||
uncapped_frames = uncapped_dummy["video"][0][0].shape[0]
|
||||
assert uncapped_frames == 2, (
|
||||
f"Expected the uncapped dummy to keep 2 frames, got {uncapped_frames}"
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
"""Tests for smolvlm's multimodal preprocessing kwargs."""
|
||||
|
||||
import pytest
|
||||
from packaging.version import Version
|
||||
from transformers import SmolVLMConfig
|
||||
from transformers import __version__ as TRANSFORMERS_VERSION
|
||||
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
@@ -13,10 +11,6 @@ from ....conftest import ImageTestAssets
|
||||
from ...utils import build_model_context
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
Version(TRANSFORMERS_VERSION) < Version("5.2.0"),
|
||||
reason="See https://github.com/huggingface/transformers/pull/43948",
|
||||
)
|
||||
@pytest.mark.parametrize("model_id", ["HuggingFaceTB/SmolVLM2-2.2B-Instruct"])
|
||||
@pytest.mark.parametrize(
|
||||
("mm_processor_kwargs", "expected_toks_per_img"),
|
||||
|
||||
@@ -18,6 +18,7 @@ from vllm.config.multimodal import (
|
||||
AudioDummyOptions,
|
||||
BaseDummyOptions,
|
||||
ImageDummyOptions,
|
||||
MultiModalDummyOptions,
|
||||
VideoDummyOptions,
|
||||
)
|
||||
from vllm.distributed import (
|
||||
@@ -98,7 +99,7 @@ def create_batched_mm_kwargs(
|
||||
processor_inputs = dummy_inputs.get_dummy_processor_inputs(
|
||||
seq_len=model_config.max_model_len,
|
||||
mm_counts=mm_counts,
|
||||
mm_options={},
|
||||
mm_options=MultiModalDummyOptions(),
|
||||
)
|
||||
mm_items = processor_inputs.mm_data_items
|
||||
resized_mm_data = {
|
||||
@@ -248,11 +249,13 @@ def test_model_tensor_schema(model_id: str):
|
||||
return AudioDummyOptions(count=count)
|
||||
return BaseDummyOptions(count=count)
|
||||
|
||||
model_config.get_multimodal_config().limit_per_prompt = {
|
||||
modality: _to_dummy_options(modality, count)
|
||||
for modality, count in limit_mm_per_prompt.items()
|
||||
}
|
||||
processor = factories.build_processor(ctx, cache=None)
|
||||
model_config.get_multimodal_config().limit_per_prompt = MultiModalDummyOptions(
|
||||
{
|
||||
modality: _to_dummy_options(modality, count)
|
||||
for modality, count in limit_mm_per_prompt.items()
|
||||
}
|
||||
)
|
||||
processor = factories.build_processor(ctx)
|
||||
|
||||
with initialize_dummy_model(model_cls, model_config) as model:
|
||||
for modality, _, mm_kwargs in create_batched_mm_kwargs(model_config, processor):
|
||||
|
||||
@@ -245,6 +245,7 @@ def test_repeated_image_hits_the_processor_cache():
|
||||
prompt="<image>\nWhat is this?",
|
||||
mm_items=mm_processor.info.parse_mm_data({"image": image}),
|
||||
hf_processor_mm_kwargs={},
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
first, second = process(), process()
|
||||
|
||||
@@ -48,4 +48,4 @@ def create_cached_processor(model_id: str, processor_cls):
|
||||
)
|
||||
info = MultiModalProcessingInfo(ctx)
|
||||
cache = MultiModalProcessorOnlyCache(model_config)
|
||||
return processor_cls(info, MultiModalDummyInputsBuilder(info), cache=cache), cache
|
||||
return processor_cls(info, MultiModalDummyInputsBuilder(info)), cache
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import AriaTextConfig
|
||||
from transformers.models.aria.modeling_aria import AriaTextMoELayer as HFMoE
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors import ( # noqa: E501
|
||||
CompressedTensorsConfig,
|
||||
)
|
||||
from vllm.model_executor.models.aria import AriaTextModel, AriaTextMoELayer
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.usefixtures("dist_init")
|
||||
@pytest.mark.parametrize(
|
||||
"checkpoint_name,loaded_name,param_name",
|
||||
[
|
||||
(
|
||||
"experts.fc1.weight",
|
||||
"experts.w13_weight",
|
||||
"experts.routed_experts.w13_weight",
|
||||
),
|
||||
(
|
||||
"experts.fc2.weight",
|
||||
"experts.w2_weight",
|
||||
"experts.routed_experts.w2_weight",
|
||||
),
|
||||
(
|
||||
"shared_experts.down_proj.weight",
|
||||
"shared_experts.down_proj.weight",
|
||||
"shared_experts.down_proj.weight",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_aria_expert_weights_load_with_checkpoint_layout(
|
||||
checkpoint_name: str, loaded_name: str, param_name: str
|
||||
):
|
||||
"""Real Aria checkpoint weights must reach the right parameter and layout."""
|
||||
config = AriaTextConfig(
|
||||
hidden_size=32,
|
||||
intermediate_size=64,
|
||||
moe_num_experts=2,
|
||||
moe_topk=1,
|
||||
moe_num_shared_experts=1,
|
||||
)
|
||||
checkpoint_weight = HFMoE(config).state_dict()[checkpoint_name]
|
||||
checkpoint_weight.copy_(
|
||||
torch.arange(
|
||||
checkpoint_weight.numel(), dtype=checkpoint_weight.dtype
|
||||
).reshape_as(checkpoint_weight)
|
||||
)
|
||||
expected = checkpoint_weight.clone()
|
||||
if checkpoint_name.startswith("experts."):
|
||||
expected = expected.transpose(-1, -2)
|
||||
|
||||
layer = AriaTextMoELayer(config, quant_config=None, prefix="mlp")
|
||||
loaded = AutoWeightsLoader(layer).load_weights(
|
||||
[(checkpoint_name, checkpoint_weight)], mapper=AriaTextModel.hf_to_vllm_mapper
|
||||
)
|
||||
|
||||
assert loaded == {loaded_name}
|
||||
torch.testing.assert_close(
|
||||
dict(layer.named_parameters())[param_name], expected, rtol=0, atol=0
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_aria_quant_config_renames_expert_modules():
|
||||
quant_config = CompressedTensorsConfig(
|
||||
target_scheme_map={},
|
||||
ignore=[
|
||||
"model.layers.0.mlp.experts.fc1",
|
||||
"model.layers.0.mlp.experts.fc2",
|
||||
],
|
||||
quant_format="pack-quantized",
|
||||
)
|
||||
AriaTextModel.__new__(
|
||||
AriaTextModel, vllm_config=VllmConfig(quant_config=quant_config)
|
||||
)
|
||||
|
||||
assert quant_config.ignore == [
|
||||
"model.layers.0.mlp.experts.gate_up_proj",
|
||||
"model.layers.0.mlp.experts.down_proj",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize(
|
||||
"name,expected", [("fc1", "gate_up_proj"), ("fc2", "down_proj")]
|
||||
)
|
||||
def test_aria_expert_scale_names(name: str, expected: str):
|
||||
suffixes = ["weight_scale", "input_scale"]
|
||||
names = [f"model.layers.0.mlp.experts.{name}.{suffix}" for suffix in suffixes]
|
||||
assert AriaTextModel.hf_to_vllm_mapper.apply_list(names) == [
|
||||
f"model.layers.0.mlp.experts.{expected}.{suffix}" for suffix in suffixes
|
||||
]
|
||||
@@ -4,9 +4,65 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import SpeechToTextConfig
|
||||
from vllm.model_executor.models.cohere_asr import CohereAsrForConditionalGeneration
|
||||
from vllm.model_executor.models.cohere_asr import (
|
||||
CohereAsrForConditionalGeneration,
|
||||
RelPositionMultiHeadAttention,
|
||||
)
|
||||
|
||||
|
||||
class _ReferenceRelPositionMultiHeadAttention(RelPositionMultiHeadAttention):
|
||||
"""Relative attention implementation before score accumulation is fused."""
|
||||
|
||||
def forward(self, query, key, value, mask, pos_emb=None):
|
||||
q, k, v = self.forward_qkv(query, key, value)
|
||||
q = q.transpose(1, 2)
|
||||
|
||||
assert pos_emb is not None
|
||||
n_batch_pos = pos_emb.size(0)
|
||||
p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)
|
||||
p = p.transpose(1, 2)
|
||||
|
||||
q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)
|
||||
q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)
|
||||
|
||||
matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
|
||||
matrix_bd = self.rel_shift(matrix_bd)
|
||||
matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))
|
||||
matrix_bd = matrix_bd[:, :, :, : matrix_ac.size(-1)]
|
||||
scores = (matrix_ac + matrix_bd) / self.s_d_k
|
||||
return self.forward_attention(v, scores, mask)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("query_len", "key_len"), [(2, 2), (3, 5)])
|
||||
def test_relative_attention_fuses_score_accumulation(monkeypatch, query_len, key_len):
|
||||
torch.manual_seed(7)
|
||||
batch, heads, model_dim = 2, 4, 32
|
||||
optimized = RelPositionMultiHeadAttention(heads, model_dim, None, None)
|
||||
reference = _ReferenceRelPositionMultiHeadAttention(heads, model_dim, None, None)
|
||||
reference.load_state_dict(optimized.state_dict())
|
||||
|
||||
query = torch.randn(batch, query_len, model_dim)
|
||||
key = torch.randn(batch, key_len, model_dim)
|
||||
value = torch.randn(batch, key_len, model_dim)
|
||||
pos_emb = torch.randn(1, query_len + key_len - 1, model_dim)
|
||||
expected = reference(query, key, value, None, pos_emb)
|
||||
|
||||
original_baddbmm = torch.baddbmm
|
||||
calls = 0
|
||||
|
||||
def tracked_baddbmm(*args, **kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return original_baddbmm(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(torch, "baddbmm", tracked_baddbmm)
|
||||
actual = optimized(query, key, value, None, pos_emb)
|
||||
|
||||
torch.testing.assert_close(actual, expected)
|
||||
assert calls == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit test for MiMo-V2 fused fp8 ``qkv_proj`` sharding.
|
||||
|
||||
The checkpoint stores the fused QKV pre-sharded at ``num_key_value_heads``
|
||||
chunks (``ckpt_tp``), each holding that slice's ``[Q_c | K_c | V_c]`` rows with
|
||||
its own block scale grid. ``ckpt_tp`` is not the layer's KV-head count: a
|
||||
MiMo-V2.5 SWA layer has 8 KV heads but 4 chunks of 3712 rows (= 29 blocks), so
|
||||
each chunk carries two KV heads. Reading the scales as one slice per KV head
|
||||
expands 14 x 128 = 1792 rows for an 1856-row slice and fails.
|
||||
|
||||
These tests build such checkpoints for the GA, SWA and Pro geometries and check
|
||||
that every rank gets exactly the weights it should own, for TP sizes below,
|
||||
equal to and above ``ckpt_tp`` (the last case replicating KV heads).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.models.mimo_v2 import _shard_fp8_qkv_proj
|
||||
from vllm.utils.math_utils import cdiv
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
BLOCK = 128
|
||||
FP8_DTYPE = torch.float8_e4m3fn
|
||||
FP8_MAX = torch.finfo(FP8_DTYPE).max
|
||||
COLS = 128 # one column block is enough to exercise the row mapping
|
||||
# fp8 e4m3 has 3 mantissa bits, so a single block-quantization round trip costs
|
||||
# ~2-3% relative L2; a wrong row -> scale pairing costs >= 10%.
|
||||
TOL = 0.06
|
||||
|
||||
# (num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp): MiMo-V2.5 GA, its
|
||||
# SWA/MTP layers, and MiMo-V2.5-Pro.
|
||||
GEOMETRIES = {
|
||||
"ga": (64, 4, 192, 128, 4),
|
||||
"swa": (64, 8, 192, 128, 4),
|
||||
"pro": (128, 8, 192, 128, 8),
|
||||
}
|
||||
|
||||
|
||||
def _chunk_rows(num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp):
|
||||
return (
|
||||
num_heads // ckpt_tp * head_dim
|
||||
+ num_kv_heads // ckpt_tp * head_dim
|
||||
+ num_kv_heads // ckpt_tp * v_head_dim
|
||||
)
|
||||
|
||||
|
||||
def _quantize_chunks(truth, num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp):
|
||||
"""Block-quantize each checkpoint chunk on its own grid, like the export."""
|
||||
rows_per_chunk = _chunk_rows(num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp)
|
||||
weights, scales = [], []
|
||||
for chunk in range(ckpt_tp):
|
||||
rows = truth[chunk * rows_per_chunk : (chunk + 1) * rows_per_chunk]
|
||||
quantized = torch.zeros_like(rows)
|
||||
scale = torch.zeros(
|
||||
cdiv(rows_per_chunk, BLOCK), rows.shape[1] // BLOCK, dtype=torch.float32
|
||||
)
|
||||
for row in range(0, rows_per_chunk, BLOCK):
|
||||
for col in range(0, rows.shape[1], BLOCK):
|
||||
block = rows[row : row + BLOCK, col : col + BLOCK]
|
||||
amax = block.abs().max().clamp(min=1e-12) / FP8_MAX
|
||||
scale[row // BLOCK, col // BLOCK] = amax
|
||||
quantized[row : row + BLOCK, col : col + BLOCK] = block / amax
|
||||
weights.append(quantized.to(FP8_DTYPE))
|
||||
scales.append(scale)
|
||||
return torch.cat(weights, dim=0), torch.cat(scales, dim=0)
|
||||
|
||||
|
||||
def _owned_rows(
|
||||
truth, num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp, tp_rank, tp_size
|
||||
):
|
||||
"""Rows the rank must own, in the forward's `[Q | K | V]` order."""
|
||||
rows_per_chunk = _chunk_rows(num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp)
|
||||
q_per_chunk = num_heads // ckpt_tp * head_dim
|
||||
k_per_chunk = num_kv_heads // ckpt_tp * head_dim
|
||||
kv_heads: list[int] = []
|
||||
if tp_size <= num_kv_heads:
|
||||
kv_heads = list(
|
||||
range(
|
||||
tp_rank * (num_kv_heads // tp_size),
|
||||
(tp_rank + 1) * (num_kv_heads // tp_size),
|
||||
)
|
||||
)
|
||||
else:
|
||||
kv_heads = [tp_rank // (tp_size // num_kv_heads)]
|
||||
index = []
|
||||
for head in range(
|
||||
tp_rank * (num_heads // tp_size), (tp_rank + 1) * (num_heads // tp_size)
|
||||
):
|
||||
chunk, offset = divmod(head, num_heads // ckpt_tp)
|
||||
start = chunk * rows_per_chunk + offset * head_dim
|
||||
index += list(range(start, start + head_dim))
|
||||
for head in kv_heads:
|
||||
chunk, offset = divmod(head, num_kv_heads // ckpt_tp)
|
||||
start = chunk * rows_per_chunk + q_per_chunk + offset * head_dim
|
||||
index += list(range(start, start + head_dim))
|
||||
for head in kv_heads:
|
||||
chunk, offset = divmod(head, num_kv_heads // ckpt_tp)
|
||||
start = chunk * rows_per_chunk + q_per_chunk + k_per_chunk + offset * v_head_dim
|
||||
index += list(range(start, start + v_head_dim))
|
||||
return truth[torch.tensor(index)]
|
||||
|
||||
|
||||
def _dequantize(weight, scale):
|
||||
"""What the kernel computes: scale[row // block] applied per weight row."""
|
||||
per_row = scale.repeat_interleave(BLOCK, dim=1)
|
||||
return weight.to(torch.float32) * per_row[torch.arange(weight.shape[0]) // BLOCK]
|
||||
|
||||
|
||||
def _relative_l2(got, expected):
|
||||
return ((got - expected).norm() / expected.norm()).item()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("geometry", list(GEOMETRIES))
|
||||
@pytest.mark.parametrize("tp_size", [1, 2, 4, 8])
|
||||
def test_fused_qkv_proj_sharding(geometry, tp_size):
|
||||
num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp = GEOMETRIES[geometry]
|
||||
if num_heads % tp_size or (tp_size > num_kv_heads and tp_size % num_kv_heads):
|
||||
pytest.skip("TP size does not divide the head counts")
|
||||
|
||||
rows_per_chunk = _chunk_rows(num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp)
|
||||
truth = torch.randn(ckpt_tp * rows_per_chunk, COLS)
|
||||
for chunk in range(ckpt_tp): # per-chunk magnitude spread, as in the export
|
||||
truth[chunk * rows_per_chunk : (chunk + 1) * rows_per_chunk] *= 1.0 + chunk
|
||||
weight, scale = _quantize_chunks(
|
||||
truth, num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp
|
||||
)
|
||||
|
||||
kv_per_rank = (num_kv_heads // tp_size) if tp_size <= num_kv_heads else 1
|
||||
rows_rank = (num_heads // tp_size) * head_dim + kv_per_rank * (
|
||||
head_dim + v_head_dim
|
||||
)
|
||||
for tp_rank in range(tp_size):
|
||||
w_rank, s_rank = _shard_fp8_qkv_proj(
|
||||
weight,
|
||||
scale,
|
||||
num_heads=num_heads,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_dim=head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
tp_rank=tp_rank,
|
||||
tp_size=tp_size,
|
||||
ckpt_tp=ckpt_tp,
|
||||
)
|
||||
assert w_rank.shape == (rows_rank, COLS)
|
||||
assert s_rank.shape == (cdiv(rows_rank, BLOCK), scale.shape[1])
|
||||
expected = _owned_rows(
|
||||
truth,
|
||||
num_heads,
|
||||
num_kv_heads,
|
||||
head_dim,
|
||||
v_head_dim,
|
||||
ckpt_tp,
|
||||
tp_rank,
|
||||
tp_size,
|
||||
)
|
||||
assert _relative_l2(_dequantize(w_rank, s_rank), expected) <= TOL
|
||||
|
||||
|
||||
@pytest.mark.parametrize("geometry", ["ga", "swa"])
|
||||
@pytest.mark.parametrize("tp_size", [1, 2, 4])
|
||||
def test_exact_chunk_matches_checkpoint(geometry, tp_size):
|
||||
"""At tp_size <= ckpt_tp the chunk count is the only thing that matters."""
|
||||
num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp = GEOMETRIES[geometry]
|
||||
rows_per_chunk = _chunk_rows(num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp)
|
||||
truth = torch.randn(ckpt_tp * rows_per_chunk, COLS)
|
||||
weight, scale = _quantize_chunks(
|
||||
truth, num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp
|
||||
)
|
||||
if tp_size == ckpt_tp:
|
||||
w_rank, s_rank = _shard_fp8_qkv_proj(
|
||||
weight,
|
||||
scale,
|
||||
num_heads=num_heads,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_dim=head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
tp_rank=0,
|
||||
tp_size=tp_size,
|
||||
ckpt_tp=ckpt_tp,
|
||||
)
|
||||
# The checkpoint chunk *is* the rank's slice: no re-quantization.
|
||||
# (torch.equal has no fp8 kernel, so compare the underlying bytes.)
|
||||
expected_w = weight.chunk(tp_size, dim=0)[0]
|
||||
assert torch.equal(w_rank.view(torch.uint8), expected_w.view(torch.uint8))
|
||||
assert torch.equal(s_rank, scale.chunk(tp_size, dim=0)[0])
|
||||
|
||||
|
||||
def test_wrong_chunk_count_is_detected():
|
||||
"""Reading SWA scales as one slice per KV head must not look correct.
|
||||
|
||||
This is the regression the fix addresses: 116 scale rows are 4 x 29 (29 =
|
||||
ceil(3712 / 128)), not 8 x 15, so ``ckpt_tp = num_kv_heads`` pairs every
|
||||
weight row with the wrong scale.
|
||||
"""
|
||||
num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp = GEOMETRIES["swa"]
|
||||
rows_per_chunk = _chunk_rows(num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp)
|
||||
truth = torch.randn(ckpt_tp * rows_per_chunk, COLS)
|
||||
for chunk in range(ckpt_tp):
|
||||
truth[chunk * rows_per_chunk : (chunk + 1) * rows_per_chunk] *= 1.0 + chunk
|
||||
weight, scale = _quantize_chunks(
|
||||
truth, num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp
|
||||
)
|
||||
assert scale.shape[0] == ckpt_tp * cdiv(rows_per_chunk, BLOCK)
|
||||
assert scale.shape[0] != num_kv_heads * cdiv(rows_per_chunk, BLOCK)
|
||||
|
||||
kw = dict(
|
||||
num_heads=num_heads,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_dim=head_dim,
|
||||
v_head_dim=v_head_dim,
|
||||
tp_rank=0,
|
||||
tp_size=1,
|
||||
)
|
||||
correct = _shard_fp8_qkv_proj(weight, scale, ckpt_tp=ckpt_tp, **kw)
|
||||
wrong = _shard_fp8_qkv_proj(weight, scale, ckpt_tp=num_kv_heads, **kw)
|
||||
assert correct[0].shape == wrong[0].shape
|
||||
|
||||
expected = _owned_rows(
|
||||
truth, num_heads, num_kv_heads, head_dim, v_head_dim, ckpt_tp, 0, 1
|
||||
)
|
||||
assert _relative_l2(_dequantize(*correct), expected) <= TOL
|
||||
assert _relative_l2(_dequantize(*wrong), expected) > 5 * TOL
|
||||
@@ -111,11 +111,6 @@ def test_mxfp8_aiter_requires_swigluoai_activation(
|
||||
"_supports_current_device",
|
||||
staticmethod(lambda: True),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
aiter_mxfp8_moe,
|
||||
"is_aiter_mxfp8_moe_available",
|
||||
lambda: True,
|
||||
)
|
||||
|
||||
config = FusedMoEConfig(
|
||||
num_experts=8,
|
||||
@@ -164,11 +159,6 @@ def test_mxfp8_aiter_requires_swigluoai_params(
|
||||
"_supports_current_device",
|
||||
staticmethod(lambda: True),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
aiter_mxfp8_moe,
|
||||
"is_aiter_mxfp8_moe_available",
|
||||
lambda: True,
|
||||
)
|
||||
|
||||
config = FusedMoEConfig(
|
||||
num_experts=8,
|
||||
@@ -218,11 +208,6 @@ def test_mxfp8_aiter_accepts_swigluoai_params(
|
||||
"_supports_current_device",
|
||||
staticmethod(lambda: True),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
aiter_mxfp8_moe,
|
||||
"is_aiter_mxfp8_moe_available",
|
||||
lambda: True,
|
||||
)
|
||||
|
||||
config = FusedMoEConfig(
|
||||
num_experts=8,
|
||||
|
||||
@@ -447,7 +447,10 @@ _TEXT_GENERATION_EXAMPLE_MODELS = {
|
||||
),
|
||||
"MixtralForCausalLM": _HfExamplesInfo(
|
||||
"mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
{"tiny": "TitanML/tiny-mixtral"},
|
||||
{
|
||||
"tiny": "axolotl-ai-co/tiny-mixtral-30m",
|
||||
"tiny-random": "TitanML/tiny-mixtral",
|
||||
},
|
||||
),
|
||||
"NemotronForCausalLM": _HfExamplesInfo("nvidia/Minitron-8B-Base"),
|
||||
"NemotronHForCausalLM": _HfExamplesInfo(
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""SWA bounded replay in DeepseekV41ModelState: the batch's replay starts reach
|
||||
the sliding-window builders, and the replayed tokens' slots are padded in the
|
||||
prefix-cacheable groups only."""
|
||||
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.models.deepseek_v41.nvidia.model_state import DeepseekV41ModelState
|
||||
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadataBuilder
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
|
||||
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
|
||||
|
||||
pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
|
||||
|
||||
DEVICE = torch.device("cuda")
|
||||
WINDOW = 4
|
||||
# Group 0 is prefix-cacheable (compressed KV), group 1 is the replayed window.
|
||||
KV_CACHE_CONFIG = SimpleNamespace(
|
||||
kv_cache_groups=[
|
||||
SimpleNamespace(
|
||||
kv_cache_spec=SimpleNamespace(prefix_cacheable=True, prefix_replay_tokens=0)
|
||||
),
|
||||
SimpleNamespace(
|
||||
kv_cache_spec=SimpleNamespace(
|
||||
prefix_cacheable=False, prefix_replay_tokens=WINDOW
|
||||
)
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def state(monkeypatch):
|
||||
cfg = MagicMock()
|
||||
cfg.model_config.enable_prompt_embeds = False
|
||||
cfg.model_config.uses_mrope = False
|
||||
cfg.model_config.is_multimodal_model = False
|
||||
cfg.scheduler_config.max_num_seqs = 8
|
||||
cfg.scheduler_config.max_num_batched_tokens = 64
|
||||
seen: dict = {}
|
||||
|
||||
def prepare_attn(self, input_batch, cg_mode, block_tables, slot_mappings, *a, **kw):
|
||||
seen["slot_mappings"] = slot_mappings.clone()
|
||||
seen["extra"] = kw["model_specific_attn_metadata"]
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(DefaultModelState, "prepare_attn", prepare_attn)
|
||||
state = DeepseekV41ModelState(
|
||||
cfg, SimpleNamespace(token_lookback_depth=0), None, DEVICE
|
||||
)
|
||||
state.seen = seen # type: ignore[attr-defined]
|
||||
return state
|
||||
|
||||
|
||||
def _batch(query_lens, seq_lens, idx_mapping, is_prefilling):
|
||||
num_reqs, num_tokens = len(query_lens), sum(query_lens)
|
||||
batch = InputBatch.make_dummy(num_reqs, num_tokens, InputBuffers(8, 64, DEVICE))
|
||||
return replace(
|
||||
batch,
|
||||
query_start_loc=torch.tensor(
|
||||
[0, *np.cumsum(query_lens)], dtype=torch.int32, device=DEVICE
|
||||
),
|
||||
idx_mapping_np=np.array(idx_mapping, dtype=np.intp),
|
||||
is_prefilling_np=np.array(is_prefilling, dtype=np.bool_),
|
||||
positions=torch.cat(
|
||||
[torch.arange(s - q, s) for q, s in zip(query_lens, seq_lens)]
|
||||
).to(DEVICE),
|
||||
)
|
||||
|
||||
|
||||
def _prepare(state, batch):
|
||||
slot_mappings = torch.arange(2 * batch.num_tokens, device=DEVICE).view(2, -1)
|
||||
state.prepare_attn(
|
||||
batch, CUDAGraphMode.NONE, (), slot_mappings, [], KV_CACHE_CONFIG
|
||||
)
|
||||
swa_builder = MagicMock(spec=DeepseekSparseSWAMetadataBuilder)
|
||||
extra = state.seen["extra"]
|
||||
replay_start = extra.get_extra_attn_kwargs(swa_builder, batch.num_reqs)[
|
||||
"replay_start"
|
||||
]
|
||||
assert extra.get_extra_attn_kwargs(MagicMock(), batch.num_reqs) == {}
|
||||
return replay_start.tolist(), state.seen["slot_mappings"]
|
||||
|
||||
|
||||
def test_replayed_tokens_write_only_the_window_group(state):
|
||||
# Request state 3 resumes a hit at 16: positions 16..19 are replayed.
|
||||
state.add_request(3, SimpleNamespace(replay_start=16))
|
||||
state.add_request(1, SimpleNamespace(replay_start=0))
|
||||
batch = _batch([6, 2], [22, 2], idx_mapping=[3, 1], is_prefilling=[True, True])
|
||||
replay_start, slots = _prepare(state, batch)
|
||||
assert replay_start == [16, 0]
|
||||
padded = [PAD_SLOT_ID] * WINDOW + [4, 5, 6, 7]
|
||||
assert slots[0].tolist() == padded # compressed KV keeps its cached rows
|
||||
assert slots[1].tolist() == list(range(8, 16)) # the window is rebuilt
|
||||
|
||||
|
||||
def test_only_prefills_carry_a_replay_start(state):
|
||||
state.add_request(0, SimpleNamespace(replay_start=16))
|
||||
# The same request, decoding: its rows sit above the hit.
|
||||
batch = _batch([1], [40], idx_mapping=[0], is_prefilling=[False])
|
||||
replay_start, slots = _prepare(state, batch)
|
||||
assert replay_start == [0]
|
||||
assert slots.tolist() == [[0], [1]]
|
||||
@@ -15,6 +15,7 @@ from vllm.models.deepseek_v4.nvidia.model import (
|
||||
DeepseekV4MegaMoEExperts,
|
||||
DeepseekV4MoE,
|
||||
make_deepseek_v4_expert_params_mapping,
|
||||
prepare_mega_gate_routing_metadata,
|
||||
)
|
||||
from vllm.models.deepseek_v4.nvidia.mtp import DeepSeekV4MTP
|
||||
from vllm.models.deepseek_v4.nvidia.ops.prepare_megamoe import prepare_megamoe_inputs
|
||||
@@ -22,6 +23,7 @@ from vllm.models.deepseek_v41.common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
|
||||
from vllm.models.deepseek_v41.nvidia.model import DeepseekV4MoE as DeepseekV41MoE
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.transformers_utils.configs.deepseek_v41 import DeepseekV41Config
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(),
|
||||
@@ -33,6 +35,7 @@ pytestmark = pytest.mark.skipif(
|
||||
def v41_moe_config(dist_init):
|
||||
return SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
dtype=torch.bfloat16,
|
||||
hf_config=DeepseekV41Config(
|
||||
text_config=dict(
|
||||
hidden_size=128,
|
||||
@@ -63,28 +66,52 @@ def v41_moe_config(dist_init):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_cudagraph", [False, True])
|
||||
@pytest.mark.parametrize("above_threshold", [False, True])
|
||||
@pytest.mark.parametrize("vision", [False, True])
|
||||
@pytest.mark.parametrize("layer_id,num_experts,top_k", [(0, 8, 2), (2, 4, 3)])
|
||||
@pytest.mark.parametrize("layer_id,num_experts,top_k", [(0, 384, 6), (2, 128, 3)])
|
||||
def test_deepseek_v41_moe_routes_without_hash_table(
|
||||
v41_moe_config, monkeypatch, vision, layer_id, num_experts, top_k
|
||||
v41_moe_config,
|
||||
monkeypatch,
|
||||
vision,
|
||||
layer_id,
|
||||
num_experts,
|
||||
top_k,
|
||||
above_threshold,
|
||||
use_cudagraph,
|
||||
):
|
||||
"""Main and draft layers select experts by score and preserve image routing."""
|
||||
if not current_platform.is_device_capability_family(100):
|
||||
pytest.skip("DeepGEMM Mega Gate requires SM100")
|
||||
|
||||
config = v41_moe_config.model_config.hf_config
|
||||
config.hidden_size = 256
|
||||
config.n_routed_experts = 384
|
||||
config.num_experts_per_tok = 6
|
||||
config.dspark_n_routed_experts = 128
|
||||
num_tokens = (1 if num_experts == 128 else 16) + int(above_threshold)
|
||||
config.vision_n_layers = int(vision)
|
||||
with torch.device("cuda"):
|
||||
with (
|
||||
set_default_torch_dtype(v41_moe_config.model_config.dtype),
|
||||
torch.device("cuda"),
|
||||
):
|
||||
moe = DeepseekV41MoE(v41_moe_config, prefix=f"model.layers.{layer_id}.ffn")
|
||||
hidden_states = torch.randn(4, config.hidden_size)
|
||||
hidden_states = torch.randn(
|
||||
num_tokens, config.hidden_size, dtype=torch.bfloat16
|
||||
)
|
||||
input_ids = (
|
||||
torch.tensor([42, IMAGE_SENTINEL_BASE_ID, IMAGE_SENTINEL_BASE_ID, 129257])
|
||||
torch.tensor(
|
||||
[42, IMAGE_SENTINEL_BASE_ID, IMAGE_SENTINEL_BASE_ID, 129257]
|
||||
).repeat((num_tokens + 3) // 4)[:num_tokens]
|
||||
if vision
|
||||
else None
|
||||
)
|
||||
assert moe.gate.tid2eid is None
|
||||
assert moe.gate.weight.shape == (num_experts, config.hidden_size)
|
||||
assert isinstance(moe.experts, DeepseekV4MegaMoEExperts)
|
||||
assert moe.experts.w13_weight.shape == (num_experts, 256, 64)
|
||||
assert moe.experts.w13_weight.shape == (num_experts, 256, 128)
|
||||
assert moe.experts.top_k == top_k
|
||||
assert (config.n_routed_experts, config.num_experts_per_tok) == (8, 2)
|
||||
assert (config.n_routed_experts, config.num_experts_per_tok) == (384, 6)
|
||||
|
||||
with torch.no_grad():
|
||||
moe.gate.weight.normal_(std=0.01)
|
||||
@@ -93,7 +120,7 @@ def test_deepseek_v41_moe_routes_without_hash_table(
|
||||
moe.gate.bias_vl.copy_(-moe.gate.e_score_correction_bias)
|
||||
|
||||
scores = torch.nn.functional.softplus(
|
||||
torch.nn.functional.linear(hidden_states, moe.gate.weight)
|
||||
torch.mm(hidden_states, moe.gate.weight.t(), out_dtype=torch.float32)
|
||||
).sqrt()
|
||||
bias = moe.gate.e_score_correction_bias
|
||||
if vision:
|
||||
@@ -105,15 +132,49 @@ def test_deepseek_v41_moe_routes_without_hash_table(
|
||||
dim=-1, keepdim=True
|
||||
)
|
||||
|
||||
routed = {}
|
||||
|
||||
def check_routing(x, weights, ids, *, activation_clamp):
|
||||
torch.testing.assert_close(ids, expected_ids)
|
||||
torch.testing.assert_close(weights, expected_weights)
|
||||
routed["ids"], routed["weights"] = ids, weights
|
||||
assert activation_clamp == config.swiglu_limit
|
||||
return x.clone()
|
||||
|
||||
monkeypatch.setattr(moe.experts, "forward", check_routing)
|
||||
monkeypatch.setattr(moe.shared_experts, "forward", lambda x: 2 * x)
|
||||
torch.testing.assert_close(moe(hidden_states, input_ids), 3 * hidden_states)
|
||||
routing_input_ids = (
|
||||
input_ids
|
||||
if input_ids is not None
|
||||
else torch.zeros(num_tokens, dtype=torch.int64, device="cuda")
|
||||
)
|
||||
metadata = prepare_mega_gate_routing_metadata(
|
||||
routing_input_ids,
|
||||
has_hash_routing=False,
|
||||
image_sentinel_base_id=IMAGE_SENTINEL_BASE_ID if vision else None,
|
||||
)
|
||||
if use_cudagraph:
|
||||
stream = torch.cuda.Stream()
|
||||
stream.wait_stream(torch.cuda.current_stream())
|
||||
with torch.cuda.stream(stream):
|
||||
for _ in range(3):
|
||||
moe(hidden_states, input_ids, metadata)
|
||||
stream.synchronize()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph, stream=stream):
|
||||
output = moe(hidden_states, input_ids, metadata)
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
else:
|
||||
output = moe(hidden_states, input_ids, metadata)
|
||||
|
||||
ids, weights = routed["ids"], routed["weights"]
|
||||
torch.testing.assert_close(ids, expected_ids)
|
||||
torch.testing.assert_close(
|
||||
weights,
|
||||
expected_weights,
|
||||
rtol=1e-3,
|
||||
atol=1e-4,
|
||||
)
|
||||
torch.testing.assert_close(output, 3 * hidden_states)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -156,6 +217,67 @@ def test_deepseek_v4_moe_preserves_configured_hash_layers(v41_moe_config):
|
||||
moe(torch.zeros(1, 128))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_tokens", [16, 17])
|
||||
def test_deepseek_v4_mega_gate_hash_routing_correctness(
|
||||
v41_moe_config, monkeypatch, num_tokens
|
||||
):
|
||||
if not current_platform.is_device_capability_family(100):
|
||||
pytest.skip("DeepGEMM Mega Gate requires SM100")
|
||||
|
||||
config = v41_moe_config.model_config.hf_config
|
||||
config.hidden_size = 256
|
||||
config.num_hash_layers = 1
|
||||
config.vocab_size = 32
|
||||
with (
|
||||
set_default_torch_dtype(v41_moe_config.model_config.dtype),
|
||||
torch.device("cuda"),
|
||||
):
|
||||
moe = DeepseekV4MoE(
|
||||
v41_moe_config,
|
||||
prefix="model.layers.0.ffn",
|
||||
num_hash_layers=config.num_hash_layers,
|
||||
)
|
||||
hidden_states = torch.randn(
|
||||
num_tokens, config.hidden_size, dtype=torch.bfloat16
|
||||
)
|
||||
input_ids = torch.arange(num_tokens)
|
||||
|
||||
token_ids = torch.arange(config.vocab_size, device="cuda")
|
||||
fixed_ids = torch.stack(
|
||||
(
|
||||
token_ids % config.n_routed_experts,
|
||||
(token_ids + 3) % config.n_routed_experts,
|
||||
),
|
||||
dim=1,
|
||||
)
|
||||
with torch.no_grad():
|
||||
moe.gate.weight.normal_(std=0.01)
|
||||
moe.gate.tid2eid.copy_(fixed_ids)
|
||||
|
||||
expected_ids = fixed_ids[input_ids]
|
||||
scores = torch.nn.functional.softplus(
|
||||
torch.mm(hidden_states, moe.gate.weight.t(), out_dtype=torch.float32)
|
||||
).sqrt()
|
||||
expected_weights = scores.gather(1, expected_ids)
|
||||
expected_weights *= config.routed_scaling_factor / expected_weights.sum(
|
||||
dim=-1, keepdim=True
|
||||
)
|
||||
|
||||
def check_routing(x, weights, ids, *, activation_clamp):
|
||||
torch.testing.assert_close(ids, expected_ids)
|
||||
torch.testing.assert_close(weights, expected_weights, rtol=1e-3, atol=1e-4)
|
||||
return x.clone()
|
||||
|
||||
monkeypatch.setattr(moe.experts, "forward", check_routing)
|
||||
monkeypatch.setattr(moe.shared_experts, "forward", torch.zeros_like)
|
||||
metadata = prepare_mega_gate_routing_metadata(
|
||||
input_ids,
|
||||
has_hash_routing=True,
|
||||
image_sentinel_base_id=None,
|
||||
)
|
||||
torch.testing.assert_close(moe(hidden_states, input_ids, metadata), hidden_states)
|
||||
|
||||
|
||||
def test_deepseek_v4_mega_moe_expert_mapping():
|
||||
mapping = make_deepseek_v4_expert_params_mapping(2)
|
||||
|
||||
@@ -513,6 +635,7 @@ def test_deepseek_v4_mega_moe_does_not_double_add_fused_shared_expert(
|
||||
monkeypatch, fused
|
||||
):
|
||||
class FakeGate(torch.nn.Module):
|
||||
weight = torch.empty(2, 128)
|
||||
tid2eid = None
|
||||
e_score_correction_bias = None
|
||||
|
||||
@@ -563,12 +686,14 @@ def test_deepseek_v4_mega_moe_does_not_double_add_fused_shared_expert(
|
||||
not torch.cuda.is_available(),
|
||||
reason="DeepSeek V4 MegaMoE fused input staging requires CUDA.",
|
||||
)
|
||||
def test_deepseek_v4_mega_moe_fused_input_staging_is_bitwise_exact():
|
||||
@pytest.mark.parametrize("num_tokens", [7, 63, 64, 65, 127, 128, 135, 434, 16384])
|
||||
@pytest.mark.parametrize("hidden_size", [256, 5120])
|
||||
def test_deepseek_v4_mega_moe_fused_input_staging_is_bitwise_exact(
|
||||
num_tokens, hidden_size
|
||||
):
|
||||
from vllm.third_party.deep_gemm.utils import per_token_cast_to_fp8
|
||||
|
||||
device = torch.device("cuda")
|
||||
num_tokens = 7
|
||||
hidden_size = 256
|
||||
top_k = 8
|
||||
|
||||
generator = torch.Generator(device=device)
|
||||
@@ -723,6 +848,7 @@ def test_deepseek_v4_mega_moe_stages_shared_scale_tma_layout(shared_block_m):
|
||||
assert torch.equal(fused_x.view(torch.uint8), ref_x.view(torch.uint8))
|
||||
assert torch.equal(fused_x_sf, ref_x_sf)
|
||||
assert torch.equal(fused_shared_x_sf[populated], ref_shared_x_sf[populated])
|
||||
assert torch.all(fused_shared_x_sf[~populated] == -1)
|
||||
|
||||
|
||||
def test_deepseek_v4_pwal_hook_finalizes_mega_moe_and_mhc_broadcast():
|
||||
@@ -760,11 +886,14 @@ def test_deepseek_v4_drafter_pwal_hooks_finalize_mega_moe():
|
||||
not torch.cuda.is_available(),
|
||||
reason="DeepSeek V4 MegaMoE fused input staging requires CUDA.",
|
||||
)
|
||||
def test_deepseek_v4_mega_moe_fused_input_staging_masks_padding():
|
||||
@pytest.mark.parametrize("nonfinite_padding", [False, True])
|
||||
@pytest.mark.parametrize("num_tokens", [7, 65, 135])
|
||||
def test_deepseek_v4_mega_moe_fused_input_staging_masks_padding(
|
||||
nonfinite_padding, num_tokens
|
||||
):
|
||||
from vllm.third_party.deep_gemm.utils import per_token_cast_to_fp8
|
||||
|
||||
device = torch.device("cuda")
|
||||
num_tokens = 7
|
||||
hidden_size = 256
|
||||
top_k = 8
|
||||
|
||||
@@ -792,10 +921,11 @@ def test_deepseek_v4_mega_moe_fused_input_staging_masks_padding():
|
||||
dtype=torch.float32,
|
||||
generator=generator,
|
||||
)
|
||||
is_padding = torch.tensor(
|
||||
[False, True, False, False, True, False, True],
|
||||
device=device,
|
||||
)
|
||||
is_padding = torch.zeros(num_tokens, device=device, dtype=torch.bool)
|
||||
is_padding[1::3] = True
|
||||
is_padding[-1] = True
|
||||
if nonfinite_padding:
|
||||
topk_weights[is_padding] = float("nan")
|
||||
|
||||
ref_x, ref_x_sf = per_token_cast_to_fp8(
|
||||
hidden_states,
|
||||
|
||||
@@ -11,6 +11,7 @@ from vllm.compilation.wrapper import TorchCompileWithNoGuardsWrapper
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.models.qwen3_dspark import DSparkMarkovHead
|
||||
from vllm.model_executor.models.registry import ModelRegistry
|
||||
from vllm.models.deepseek_v4.nvidia import dspark as dsv4_dspark
|
||||
from vllm.models.kimi_k3.nvidia import dspark_mla
|
||||
from vllm.models.kimi_k3.nvidia.dspark_mla import K3DSparkForCausalLM, K3DSparkModel
|
||||
|
||||
@@ -262,3 +263,75 @@ def test_v41_dspark_loads_linear_scales(
|
||||
assert loaded == {runtime_name}
|
||||
assert shards == [() if shard_id is None else (shard_id,)]
|
||||
torch.testing.assert_close(param, checkpoint_scale)
|
||||
|
||||
|
||||
def test_dsv4_context_wkv_weights_are_duplicated_by_draft_layer():
|
||||
weights = [
|
||||
("mtp.0.attn.wkv.weight", torch.arange(4)),
|
||||
("mtp.1.attn.wq_a.weight", torch.arange(3)),
|
||||
("mtp.2.attn.wkv.scale", torch.tensor(0.5)),
|
||||
("mtp.3.attn.wkv.weight", torch.arange(2)),
|
||||
]
|
||||
|
||||
duplicated = list(dsv4_dspark._duplicate_context_wkv_weights(weights, 3))
|
||||
|
||||
assert [name for name, _ in duplicated] == [
|
||||
"mtp.0.attn.wkv.weight",
|
||||
"context_wkv_proj.weight",
|
||||
"mtp.1.attn.wq_a.weight",
|
||||
"mtp.2.attn.wkv.scale",
|
||||
"context_wkv_proj.scale",
|
||||
"mtp.3.attn.wkv.weight",
|
||||
]
|
||||
assert duplicated[1][1].shard_id == 0
|
||||
assert duplicated[4][1].shard_id == 2
|
||||
assert duplicated[0][1].data_ptr() == duplicated[1][1].data_ptr()
|
||||
assert duplicated[3][1].data_ptr() == duplicated[4][1].data_ptr()
|
||||
|
||||
|
||||
def test_dsv4_context_kv_uses_one_stacked_wkv_projection(monkeypatch):
|
||||
calls = []
|
||||
stacked_output = torch.arange(24, dtype=torch.float32).view(2, 12)
|
||||
|
||||
class StackedProjection:
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
|
||||
def __call__(self, main_x):
|
||||
self.calls += 1
|
||||
assert main_x.shape == (2, 5)
|
||||
return stacked_output
|
||||
|
||||
projection = StackedProjection()
|
||||
layers = [
|
||||
SimpleNamespace(attn=SimpleNamespace(kv_norm=lambda kv, offset=i: kv + offset))
|
||||
for i in range(3)
|
||||
]
|
||||
model = SimpleNamespace(
|
||||
config=SimpleNamespace(head_dim=4),
|
||||
context_wkv_proj=projection,
|
||||
layers=layers,
|
||||
num_dspark_layers=3,
|
||||
)
|
||||
slot_mappings = [torch.tensor([0, 1]), None, torch.tensor([4, 5])]
|
||||
monkeypatch.setattr(
|
||||
dsv4_dspark,
|
||||
"_insert_context_kv",
|
||||
lambda attn, kv, positions, slots: calls.append(
|
||||
(attn, kv.clone(), positions, slots)
|
||||
),
|
||||
)
|
||||
|
||||
dsv4_dspark.DSparkDeepseekV4Model.precompute_and_store_context_kv(
|
||||
model,
|
||||
torch.zeros(2, 5),
|
||||
torch.tensor([7, 8]),
|
||||
slot_mappings,
|
||||
)
|
||||
|
||||
assert projection.calls == 1
|
||||
assert len(calls) == 2
|
||||
assert torch.equal(calls[0][1], stacked_output.view(2, 3, 4)[:, 0])
|
||||
assert torch.equal(calls[1][1], stacked_output.view(2, 3, 4)[:, 2] + 2)
|
||||
assert calls[0][3] is slot_mappings[0]
|
||||
assert calls[1][3] is slot_mappings[2]
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import gc
|
||||
from collections.abc import Generator
|
||||
from functools import partial
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm import LLM
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.mem_constants import GiB_bytes
|
||||
from vllm.v1.attention.backends.utils import resolve_kv_cache_layout
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
@@ -15,7 +20,12 @@ from vllm.v1.core.kv_cache_utils import (
|
||||
)
|
||||
from vllm.v1.engine.core import EngineCore as V1EngineCore
|
||||
|
||||
from ..utils import create_new_process_for_each_test, requires_spawn_multiprocessing
|
||||
from ..utils import (
|
||||
create_new_process_for_each_test,
|
||||
requires_spawn_multiprocessing,
|
||||
wait_for_gpu_memory_to_clear,
|
||||
wait_for_memory_to_settle,
|
||||
)
|
||||
from .registry import (
|
||||
_TRANSFORMERS_BACKEND_MODELS,
|
||||
AUTO_EXAMPLE_MODELS,
|
||||
@@ -24,6 +34,8 @@ from .registry import (
|
||||
)
|
||||
from .utils import dummy_hf_overrides
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# This minimal list of model architectures is smaller than the total list of
|
||||
# supported models. The intention is that in the "typical" regression testing
|
||||
# scenario, we only test initializing these models. This subset was chosen
|
||||
@@ -53,6 +65,37 @@ OTHER_MODEL_ARCH_LIST = set(HF_EXAMPLE_MODELS.get_supported_archs()) - set(
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def cleanup_gpu_memory_between_tests() -> Generator[None, None, None]:
|
||||
"""Reclaim GPU memory left over by each test's forked subprocess.
|
||||
|
||||
These tests are known to leave behind GPU memory (see the comment at
|
||||
``gpu_memory_utilization=0.80`` below). Each parametrized case builds an
|
||||
LLM in a forked subprocess whose VRAM is only reclaimed asynchronously
|
||||
when the subprocess exits, so the leftovers can OOM a later test in this
|
||||
module (observed with the heavier multimodal archs, e.g.
|
||||
InternVLChatModel). Mirrors ``clean_gpu_memory_between_tests`` in the
|
||||
top-level conftest, but unconditionally for this module.
|
||||
"""
|
||||
yield
|
||||
gc.collect()
|
||||
if not torch.cuda.is_available():
|
||||
return
|
||||
torch.accelerator.empty_cache()
|
||||
if current_platform.is_rocm() or current_platform.is_xpu():
|
||||
wait_for_memory_to_settle()
|
||||
return
|
||||
try:
|
||||
wait_for_gpu_memory_to_clear(
|
||||
devices=list(range(torch.accelerator.device_count())),
|
||||
threshold_ratio=0.1,
|
||||
)
|
||||
except Exception as e:
|
||||
# NVML is not usable on MIG slices (raises NVMLError_NoPermission);
|
||||
# cleanup is best-effort, so never fail a test over it.
|
||||
logger.info("Failed to clean GPU memory: %s", e)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def can_initialize(
|
||||
model_arch: str, monkeypatch: pytest.MonkeyPatch, EXAMPLE_MODELS: HfExampleModels
|
||||
|
||||
@@ -217,3 +217,25 @@ def test_get_rename_mapper_keeps_only_renames():
|
||||
for name in ("drop_regex.w", "drop_substr.w", "drop_prefix.w", "w.drop_suffix"):
|
||||
assert mapper._map_name(name) is None
|
||||
assert renames._map_name(name) == name
|
||||
|
||||
|
||||
def test_weights_mapper_stacks_one_weight_into_several_shards():
|
||||
"""One checkpoint tensor can feed more than one shard of a stacked
|
||||
parameter, and a dropped name stays dropped rather than reappearing as a
|
||||
shard of the stacked one."""
|
||||
mapper = WeightsMapper(
|
||||
orig_to_new_substr={"layers.1.k_proj.": None},
|
||||
orig_to_new_stacked={".k_proj.": (".qkv_proj.", ["k", "v"])},
|
||||
)
|
||||
weight = torch.ones(2)
|
||||
weights = [(f"layers.{i}.k_proj.weight", weight) for i in (0, 1)]
|
||||
|
||||
mapped = list(mapper.apply(weights))
|
||||
|
||||
assert [(name, w.shard_id) for name, w in mapped] == [
|
||||
("layers.0.qkv_proj.weight", "k"),
|
||||
("layers.0.qkv_proj.weight", "v"),
|
||||
]
|
||||
# Each shard needs its own tensor object, but they alias one allocation.
|
||||
assert mapped[0][1] is not mapped[1][1]
|
||||
assert mapped[0][1].data_ptr() == mapped[1][1].data_ptr() == weight.data_ptr()
|
||||
|
||||
@@ -53,7 +53,6 @@ def _match(q_lora_rank: int | None) -> MLAFuser | None:
|
||||
def test_discovers_modules_without_q_lora():
|
||||
fuser = _match(q_lora_rank=None)
|
||||
assert isinstance(fuser, MLAFuser)
|
||||
assert not fuser.has_q_lora
|
||||
assert fuser.q_proj_name == "q_proj"
|
||||
assert fuser.kv_a_proj_name == "kv_a_proj_with_mqa"
|
||||
assert fuser.kv_a_layernorm_name == "kv_a_layernorm"
|
||||
@@ -68,7 +67,6 @@ def test_discovers_modules_without_q_lora():
|
||||
def test_discovers_modules_with_q_lora():
|
||||
fuser = _match(q_lora_rank=64)
|
||||
assert isinstance(fuser, MLAFuser)
|
||||
assert fuser.has_q_lora
|
||||
assert fuser.q_a_proj_name == "q_a_proj"
|
||||
assert fuser.q_a_layernorm_name == "q_a_layernorm"
|
||||
assert fuser.q_b_proj_name == "q_b_proj"
|
||||
@@ -107,7 +105,7 @@ def test_update_forward_rewrites_real_attention(q_lora_rank):
|
||||
assert isinstance(fuser, MLAFuser)
|
||||
fuser.update_forward(_attention(q_lora_rank))
|
||||
names = set(fuser.fused_forward.__code__.co_names)
|
||||
if fuser.has_q_lora:
|
||||
if fuser.q_a_proj_name is not None:
|
||||
assert _FUSED_QKV_A_PROJ in names
|
||||
assert not {"q_a_proj", "kv_a_proj_with_mqa"} & names
|
||||
|
||||
@@ -158,7 +156,7 @@ def test_discovers_modules_under_arbitrary_names():
|
||||
module = RenamedMLA()
|
||||
fuser = MLAFuser.match(trace(module), module)
|
||||
assert isinstance(fuser, MLAFuser)
|
||||
assert not fuser.has_q_lora
|
||||
assert fuser.q_a_proj_name is None
|
||||
assert fuser.q_proj_name == "alpha"
|
||||
assert fuser.kv_a_proj_name == "beta"
|
||||
assert fuser.kv_a_layernorm_name == "gamma"
|
||||
|
||||
@@ -396,6 +396,8 @@ class ModelInfo:
|
||||
@dataclass
|
||||
class EmbedModelInfo(ModelInfo):
|
||||
mteb_score: float | None = None
|
||||
# Per-model MTEB score tolerance; falls back to MTEB_EMBED_TOL.
|
||||
mteb_tol: float | None = None
|
||||
is_matryoshka: bool = False
|
||||
matryoshka_dimensions: list[int] | None = None
|
||||
|
||||
@@ -403,6 +405,8 @@ class EmbedModelInfo(ModelInfo):
|
||||
@dataclass
|
||||
class RerankModelInfo(ModelInfo):
|
||||
mteb_score: float | None = None
|
||||
# Per-model MTEB score tolerance; falls back to MTEB_RERANK_TOL.
|
||||
mteb_tol: float | None = None
|
||||
chat_template_name: str | None = None
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user