[Mini-vLLM] SM86-only cut: models, backends, Rust, tests
- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries - Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels - Remove inc/quark quant loaders; keep compressed-tensors and Marlin - Drop the Rust frontend, pooling entrypoints, and idle test suites - Rebuild kernels for sm_80;sm_86 and strip the extensions - Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,182 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Collective-safety tests for the Moondream3 MoE layer.
|
||||
|
||||
The MoE forward may fall back from the fused kernel to a Python expert loop.
|
||||
That decision is made per rank from a rank-local exception, so every path has
|
||||
to issue exactly one all-reduce. A path that issues two (or none) desyncs the
|
||||
tensor-parallel group and wedges it for the rest of the run.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import ensure_current_vllm_config
|
||||
from vllm.distributed.parallel_state import (
|
||||
destroy_distributed_environment,
|
||||
destroy_model_parallel,
|
||||
init_distributed_environment,
|
||||
initialize_model_parallel,
|
||||
)
|
||||
from vllm.model_executor.models import moondream3
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
from vllm.utils.system_utils import update_environment_variables
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
HIDDEN_SIZE = 8
|
||||
EXPERT_INNER_DIM = 16
|
||||
NUM_EXPERTS = 4
|
||||
EXPERTS_PER_TOKEN = 2
|
||||
NUM_TOKENS = 3
|
||||
|
||||
|
||||
class _StubGate(torch.nn.Module):
|
||||
"""Router stand-in, so the test does not depend on platform-specific
|
||||
``ReplicatedLinear`` weight post-processing."""
|
||||
|
||||
def __init__(self, hidden_size: int, num_experts: int):
|
||||
super().__init__()
|
||||
self.linear = torch.nn.Linear(hidden_size, num_experts)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, None]:
|
||||
return self.linear(x), None
|
||||
|
||||
|
||||
class _CountingAllReduce:
|
||||
"""Stand-in for tensor_model_parallel_all_reduce that counts calls."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
|
||||
def __call__(self, x: torch.Tensor) -> torch.Tensor:
|
||||
self.calls += 1
|
||||
return x
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tp1_cpu():
|
||||
"""A single-rank CPU tensor-parallel group, enough to build the layer."""
|
||||
update_environment_variables(
|
||||
{
|
||||
"RANK": "0",
|
||||
"LOCAL_RANK": "0",
|
||||
"WORLD_SIZE": "1",
|
||||
"MASTER_ADDR": "localhost",
|
||||
"MASTER_PORT": str(get_open_port()),
|
||||
}
|
||||
)
|
||||
init_distributed_environment(backend="gloo")
|
||||
with ensure_current_vllm_config():
|
||||
initialize_model_parallel(tensor_model_parallel_size=1)
|
||||
yield
|
||||
destroy_model_parallel()
|
||||
destroy_distributed_environment()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def moe(tp1_cpu) -> moondream3.Moondream3TextMoE:
|
||||
"""A single-rank MoE layer with deterministic weights."""
|
||||
layer = moondream3.Moondream3TextMoE(
|
||||
hidden_size=HIDDEN_SIZE,
|
||||
expert_inner_dim=EXPERT_INNER_DIM,
|
||||
num_experts=NUM_EXPERTS,
|
||||
experts_per_token=EXPERTS_PER_TOKEN,
|
||||
)
|
||||
layer.gate = _StubGate(HIDDEN_SIZE, NUM_EXPERTS)
|
||||
torch.nn.init.normal_(layer.fc1_weight, std=0.02)
|
||||
torch.nn.init.normal_(layer.fc2_weight, std=0.02)
|
||||
return layer
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def all_reduce(monkeypatch: pytest.MonkeyPatch) -> _CountingAllReduce:
|
||||
counter = _CountingAllReduce()
|
||||
monkeypatch.setattr(moondream3, "tensor_model_parallel_all_reduce", counter)
|
||||
return counter
|
||||
|
||||
|
||||
def test_expert_loop_all_reduces_once(moe, all_reduce):
|
||||
"""The Python expert loop issues exactly one all-reduce."""
|
||||
moe._use_fused_moe = False
|
||||
x = torch.randn(NUM_TOKENS, HIDDEN_SIZE)
|
||||
|
||||
out = moe(x)
|
||||
|
||||
assert out.shape == x.shape
|
||||
assert all_reduce.calls == 1
|
||||
|
||||
|
||||
def test_fused_path_all_reduces_once(moe, all_reduce, monkeypatch):
|
||||
"""The fused kernel path issues exactly one all-reduce."""
|
||||
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
|
||||
monkeypatch.setattr(
|
||||
moondream3,
|
||||
"fused_experts",
|
||||
lambda **kwargs: torch.zeros_like(kwargs["hidden_states"]),
|
||||
)
|
||||
x = torch.randn(NUM_TOKENS, HIDDEN_SIZE)
|
||||
|
||||
out = moe(x)
|
||||
|
||||
assert out.shape == x.shape
|
||||
assert all_reduce.calls == 1
|
||||
|
||||
|
||||
def test_all_reduce_failure_is_not_retried(moe, monkeypatch):
|
||||
"""A failing all-reduce must propagate, not trigger a second collective.
|
||||
|
||||
Regression test. The all-reduce used to sit inside the ``try`` guarding
|
||||
the fused kernel, so a ``RuntimeError`` raised by the collective itself
|
||||
was caught, and this rank went on to run the fallback loop and all-reduce
|
||||
a *second* time -- two collectives on one rank against one on each of its
|
||||
peers, which desyncs the tensor-parallel group and wedges it for good.
|
||||
"""
|
||||
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
|
||||
monkeypatch.setattr(
|
||||
moondream3,
|
||||
"fused_experts",
|
||||
lambda **kwargs: torch.zeros_like(kwargs["hidden_states"]),
|
||||
)
|
||||
calls = []
|
||||
|
||||
def _failing_all_reduce(x: torch.Tensor) -> torch.Tensor:
|
||||
calls.append(x)
|
||||
raise RuntimeError("collective failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
moondream3, "tensor_model_parallel_all_reduce", _failing_all_reduce
|
||||
)
|
||||
x = torch.randn(NUM_TOKENS, HIDDEN_SIZE)
|
||||
|
||||
with pytest.raises(RuntimeError, match="collective failed"):
|
||||
moe(x)
|
||||
|
||||
assert len(calls) == 1, (
|
||||
"the failed all-reduce was retried on the fallback path; peers issued "
|
||||
"one collective and this rank issued two"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exc", [RuntimeError("boom"), NotImplementedError()])
|
||||
def test_fallback_after_fused_failure_all_reduces_once(
|
||||
moe, all_reduce, monkeypatch, exc
|
||||
):
|
||||
"""A rank whose fused kernel fails still all-reduces exactly once."""
|
||||
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
|
||||
|
||||
def _raise(**kwargs):
|
||||
raise exc
|
||||
|
||||
monkeypatch.setattr(moondream3, "fused_experts", _raise)
|
||||
x = torch.randn(NUM_TOKENS, HIDDEN_SIZE)
|
||||
|
||||
out = moe(x)
|
||||
|
||||
assert out.shape == x.shape
|
||||
assert all_reduce.calls == 1
|
||||
# The fused path is disabled for subsequent forwards...
|
||||
assert moe._use_fused_moe is False
|
||||
# ...and those still all-reduce exactly once each.
|
||||
moe(x)
|
||||
assert all_reduce.calls == 2
|
||||
@@ -1,155 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.assets.audio import AudioAsset
|
||||
from vllm.model_executor.models.moss_audio import MOSS_AUDIO_PLACEHOLDER
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ...registry import HF_EXAMPLE_MODELS
|
||||
from ...utils import check_logprobs_close
|
||||
|
||||
CORE_MODEL = pytest.param(
|
||||
"OpenMOSS-Team/MOSS-Audio-4B-Instruct",
|
||||
marks=pytest.mark.core_model,
|
||||
id="4b-instruct",
|
||||
)
|
||||
|
||||
EXTENDED_MODELS = [
|
||||
"OpenMOSS-Team/MOSS-Audio-4B-Thinking",
|
||||
"OpenMOSS-Team/MOSS-Audio-8B-Instruct",
|
||||
"OpenMOSS-Team/MOSS-Audio-8B-Thinking",
|
||||
]
|
||||
|
||||
ACCURACY_MODELS = [CORE_MODEL, *EXTENDED_MODELS]
|
||||
|
||||
PARALLEL_SMOKE_CASES = [
|
||||
pytest.param({"tensor_parallel_size": 2}, id="tp2"),
|
||||
pytest.param({"pipeline_parallel_size": 2}, id="pp2"),
|
||||
pytest.param(
|
||||
{"tensor_parallel_size": 2, "pipeline_parallel_size": 2},
|
||||
id="tp2_pp2",
|
||||
),
|
||||
]
|
||||
|
||||
HF_ACCURACY_SKIP_REASON = (
|
||||
"HF AutoModelForCausalLM cannot load remote MOSS-Audio configs; "
|
||||
"vLLM generation coverage is provided by the smoke tests below."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
def test_moss_audio_generation_smoke(vllm_runner) -> None:
|
||||
model = "OpenMOSS-Team/MOSS-Audio-4B-Instruct"
|
||||
model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
|
||||
model_info.check_available_online(on_fail="skip")
|
||||
model_info.check_transformers_version(on_fail="skip")
|
||||
|
||||
prompts = [f"{MOSS_AUDIO_PLACEHOLDER}\nBriefly describe this audio."]
|
||||
audios = [[AudioAsset("mary_had_lamb").audio_and_sample_rate[0]]]
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype="half",
|
||||
enforce_eager=True,
|
||||
max_model_len=1024,
|
||||
limit_mm_per_prompt={"audio": 1},
|
||||
trust_remote_code=True,
|
||||
) as vllm_model:
|
||||
outputs = vllm_model.generate_greedy(
|
||||
prompts,
|
||||
max_tokens=4,
|
||||
audios=audios,
|
||||
)
|
||||
|
||||
assert len(outputs) == 1
|
||||
assert len(outputs[0][1]) > 0
|
||||
|
||||
|
||||
@pytest.mark.skip(reason=HF_ACCURACY_SKIP_REASON)
|
||||
@pytest.mark.parametrize("model", ACCURACY_MODELS)
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.parametrize("max_tokens", [8])
|
||||
@pytest.mark.parametrize("num_logprobs", [5])
|
||||
def test_moss_audio_hf_vllm_accuracy(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
model: str,
|
||||
dtype: str,
|
||||
max_tokens: int,
|
||||
num_logprobs: int,
|
||||
) -> None:
|
||||
model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
|
||||
model_info.check_available_online(on_fail="skip")
|
||||
model_info.check_transformers_version(on_fail="skip")
|
||||
|
||||
prompts = [f"{MOSS_AUDIO_PLACEHOLDER}\nTranscribe this audio."]
|
||||
audios = [[AudioAsset("mary_had_lamb").audio_and_sample_rate[0]]]
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype=dtype,
|
||||
enforce_eager=True,
|
||||
max_model_len=1024,
|
||||
limit_mm_per_prompt={"audio": 1},
|
||||
trust_remote_code=True,
|
||||
) as vllm_model:
|
||||
vllm_outputs = vllm_model.generate_greedy_logprobs(
|
||||
prompts,
|
||||
max_tokens,
|
||||
num_logprobs=num_logprobs,
|
||||
audios=audios,
|
||||
)
|
||||
|
||||
with hf_runner(model, dtype=dtype, trust_remote_code=True) as hf_model:
|
||||
hf_outputs = hf_model.generate_greedy_logprobs_limit(
|
||||
prompts,
|
||||
max_tokens,
|
||||
num_logprobs=num_logprobs,
|
||||
audios=audios,
|
||||
)
|
||||
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=hf_outputs,
|
||||
outputs_1_lst=vllm_outputs,
|
||||
name_0="hf",
|
||||
name_1="vllm",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.parametrize("parallel_kwargs", PARALLEL_SMOKE_CASES)
|
||||
def test_moss_audio_parallel_smoke(vllm_runner, parallel_kwargs) -> None:
|
||||
model = "OpenMOSS-Team/MOSS-Audio-4B-Instruct"
|
||||
required_gpus = parallel_kwargs.get(
|
||||
"tensor_parallel_size", 1
|
||||
) * parallel_kwargs.get("pipeline_parallel_size", 1)
|
||||
if current_platform.device_count() < required_gpus:
|
||||
# TP/PP integration smoke runs on local or multi-GPU CI only.
|
||||
pytest.skip(f"Requires at least {required_gpus} GPUs")
|
||||
|
||||
model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
|
||||
model_info.check_available_online(on_fail="skip")
|
||||
model_info.check_transformers_version(on_fail="skip")
|
||||
|
||||
prompts = [f"{MOSS_AUDIO_PLACEHOLDER}\nBriefly describe this audio."]
|
||||
audios = [[AudioAsset("mary_had_lamb").audio_and_sample_rate[0]]]
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype="half",
|
||||
enforce_eager=True,
|
||||
max_model_len=1024,
|
||||
limit_mm_per_prompt={"audio": 1},
|
||||
trust_remote_code=True,
|
||||
**parallel_kwargs,
|
||||
) as vllm_model:
|
||||
outputs = vllm_model.generate_greedy(
|
||||
prompts,
|
||||
max_tokens=4,
|
||||
audios=audios,
|
||||
)
|
||||
|
||||
assert len(outputs) == 1
|
||||
assert len(outputs[0][1]) > 0
|
||||
@@ -1,225 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.logprobs import Logprob, SampleLogprobs
|
||||
from vllm.model_executor.models.pixtral import _make_packed_sequence_metadata
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
from ....utils import VLLM_PATH, large_gpu_test
|
||||
from ...utils import check_logprobs_close
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from _typeshed import StrPath
|
||||
|
||||
PIXTRAL_ID = "mistralai/Pixtral-12B-2409"
|
||||
MISTRAL_SMALL_3_1_ID = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
|
||||
MINISTRAL_3B_ID = "mistralai/Ministral-3-3B-Instruct-2512"
|
||||
|
||||
MODELS = [PIXTRAL_ID, MISTRAL_SMALL_3_1_ID]
|
||||
|
||||
IMG_URLS = [
|
||||
"237-400x300.jpg", # "https://huggingface.co/datasets/Isotr0py/mistral-test-images/resolve/main/237-400x300.jpg",
|
||||
"231-200x300.jpg", # "https://huggingface.co/datasets/Isotr0py/mistral-test-images/resolve/main/237-400x300.jpg",
|
||||
"27-500x500.jpg", # "https://huggingface.co/datasets/Isotr0py/mistral-test-images/resolve/main/237-400x300.jpg",
|
||||
"17-150x600.jpg", # "https://huggingface.co/datasets/Isotr0py/mistral-test-images/resolve/main/237-400x300.jpg",
|
||||
]
|
||||
PROMPT = "Describe each image in one short sentence."
|
||||
|
||||
|
||||
def _create_msg_format(urls: list[str]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": PROMPT,
|
||||
}
|
||||
]
|
||||
+ [{"type": "image_url", "image_url": {"url": url}} for url in urls],
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
SAMPLING_PARAMS = SamplingParams(max_tokens=512, temperature=0.0, logprobs=5)
|
||||
LIMIT_MM_PER_PROMPT = dict(image=4)
|
||||
|
||||
MAX_MODEL_LEN = [8192, 65536]
|
||||
|
||||
FIXTURES_PATH = VLLM_PATH / "tests/models/fixtures"
|
||||
assert FIXTURES_PATH.exists()
|
||||
|
||||
FIXTURE_LOGPROBS_CHAT = {
|
||||
PIXTRAL_ID: FIXTURES_PATH / "pixtral_chat.json",
|
||||
MISTRAL_SMALL_3_1_ID: FIXTURES_PATH / "mistral_small_3_chat.json",
|
||||
MINISTRAL_3B_ID: FIXTURES_PATH / "ministral_3b_chat.json",
|
||||
}
|
||||
|
||||
OutputsLogprobs = list[tuple[list[int], str, SampleLogprobs | None]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
[
|
||||
AttentionBackendEnum.FLASH_ATTN,
|
||||
AttentionBackendEnum.FLASHINFER,
|
||||
AttentionBackendEnum.TORCH_SDPA,
|
||||
],
|
||||
)
|
||||
def test_packed_sequence_metadata(backend: AttentionBackendEnum) -> None:
|
||||
cu_seqlens, max_seqlen, sequence_lengths = _make_packed_sequence_metadata(
|
||||
[4, 6],
|
||||
backend,
|
||||
hidden_size=64,
|
||||
tp_size=1,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
|
||||
assert cu_seqlens.dtype == torch.int32
|
||||
assert max_seqlen.dtype == torch.int32
|
||||
if backend == AttentionBackendEnum.FLASHINFER:
|
||||
assert max_seqlen.item() >= 6
|
||||
assert sequence_lengths is not None
|
||||
assert sequence_lengths.dtype == torch.int32
|
||||
assert len(cu_seqlens) % 2 == 0
|
||||
else:
|
||||
expected_max_seqlen = 6 if backend == AttentionBackendEnum.FLASH_ATTN else 0
|
||||
assert max_seqlen.item() == expected_max_seqlen
|
||||
assert cu_seqlens.tolist() == [0, 4, 10]
|
||||
assert sequence_lengths is None
|
||||
|
||||
|
||||
# For the test author to store golden output in JSON
|
||||
def _dump_outputs_w_logprobs(
|
||||
outputs: OutputsLogprobs,
|
||||
filename: "StrPath",
|
||||
) -> None:
|
||||
json_data = [
|
||||
(
|
||||
tokens,
|
||||
text,
|
||||
[
|
||||
{k: asdict(v) for k, v in token_logprobs.items()}
|
||||
for token_logprobs in (logprobs or [])
|
||||
],
|
||||
)
|
||||
for tokens, text, logprobs in outputs
|
||||
]
|
||||
|
||||
with open(filename, "w") as f:
|
||||
json.dump(json_data, f)
|
||||
|
||||
|
||||
def load_outputs_w_logprobs(filename: "StrPath") -> OutputsLogprobs:
|
||||
with open(filename, "rb") as f:
|
||||
json_data = json.load(f)
|
||||
|
||||
return [
|
||||
(
|
||||
tokens,
|
||||
text,
|
||||
[
|
||||
{int(k): Logprob(**v) for k, v in token_logprobs.items()}
|
||||
for token_logprobs in logprobs
|
||||
],
|
||||
)
|
||||
for tokens, text, logprobs in json_data
|
||||
]
|
||||
|
||||
|
||||
@large_gpu_test(min_gb=80)
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("max_model_len", MAX_MODEL_LEN)
|
||||
@pytest.mark.parametrize("dtype", ["bfloat16"])
|
||||
def test_chat(
|
||||
vllm_runner, max_model_len: int, model: str, dtype: str, local_asset_server
|
||||
) -> None:
|
||||
if (
|
||||
model == MISTRAL_SMALL_3_1_ID
|
||||
and max_model_len == 65536
|
||||
and current_platform.is_rocm()
|
||||
):
|
||||
pytest.skip(
|
||||
"OOM on ROCm: 24B model with 65536 context length exceeds GPU memory"
|
||||
)
|
||||
|
||||
EXPECTED_CHAT_LOGPROBS = load_outputs_w_logprobs(FIXTURE_LOGPROBS_CHAT[model])
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype=dtype,
|
||||
tokenizer_mode="mistral",
|
||||
load_format="mistral",
|
||||
config_format="mistral",
|
||||
max_model_len=max_model_len,
|
||||
limit_mm_per_prompt=LIMIT_MM_PER_PROMPT,
|
||||
) as vllm_model:
|
||||
outputs = []
|
||||
|
||||
urls_all = [local_asset_server.url_for(u) for u in IMG_URLS]
|
||||
msgs = [
|
||||
_create_msg_format(urls_all[:1]),
|
||||
_create_msg_format(urls_all[:2]),
|
||||
_create_msg_format(urls_all),
|
||||
]
|
||||
for msg in msgs:
|
||||
output = vllm_model.llm.chat(msg, sampling_params=SAMPLING_PARAMS)
|
||||
|
||||
outputs.extend(output)
|
||||
|
||||
logprobs = vllm_runner._final_steps_generate_w_logprobs(outputs)
|
||||
# Remove last `None` prompt_logprobs to compare with fixture
|
||||
for i in range(len(logprobs)):
|
||||
assert logprobs[i][-1] is None
|
||||
logprobs[i] = logprobs[i][:-1]
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=EXPECTED_CHAT_LOGPROBS,
|
||||
outputs_1_lst=logprobs,
|
||||
name_0="h100_ref",
|
||||
name_1="output",
|
||||
)
|
||||
|
||||
|
||||
@large_gpu_test(min_gb=16)
|
||||
@pytest.mark.parametrize("dtype", ["bfloat16"])
|
||||
def test_chat_consolidated(vllm_runner, dtype: str, local_asset_server) -> None:
|
||||
EXPECTED_CHAT_LOGPROBS = load_outputs_w_logprobs(
|
||||
FIXTURE_LOGPROBS_CHAT[MINISTRAL_3B_ID]
|
||||
)
|
||||
with vllm_runner(
|
||||
MINISTRAL_3B_ID,
|
||||
dtype=dtype,
|
||||
tokenizer_mode="mistral",
|
||||
load_format="mistral",
|
||||
config_format="mistral",
|
||||
max_model_len=8192,
|
||||
limit_mm_per_prompt=LIMIT_MM_PER_PROMPT,
|
||||
) as vllm_model:
|
||||
outputs = []
|
||||
urls_all = [local_asset_server.url_for(u) for u in IMG_URLS]
|
||||
msgs = [
|
||||
_create_msg_format(urls_all[:1]),
|
||||
_create_msg_format(urls_all[:2]),
|
||||
_create_msg_format(urls_all),
|
||||
]
|
||||
for msg in msgs:
|
||||
output = vllm_model.llm.chat(msg, sampling_params=SAMPLING_PARAMS)
|
||||
outputs.extend(output)
|
||||
|
||||
logprobs = vllm_runner._final_steps_generate_w_logprobs(outputs)
|
||||
for i in range(len(logprobs)):
|
||||
assert logprobs[i][-1] is None
|
||||
logprobs[i] = logprobs[i][:-1]
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=EXPECTED_CHAT_LOGPROBS,
|
||||
outputs_1_lst=logprobs,
|
||||
name_0="h100_ref",
|
||||
name_1="output",
|
||||
)
|
||||
@@ -1,357 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from fractions import Fraction
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from mistral_common.protocol.transcription.request import (
|
||||
StreamingMode,
|
||||
TranscriptionRequest,
|
||||
)
|
||||
from mistral_common.tokens.tokenizers.audio import Audio
|
||||
from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
|
||||
from mistral_common.tokens.tokenizers.tekken import SpecialTokenPolicy
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.assets.audio import AudioAsset
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.engine.protocol import StreamingInput
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.renderers.inputs.preprocess import parse_model_prompt
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.kv_cache_interface import SlidingWindowSpec
|
||||
|
||||
from ....utils import ROCM_ENGINE_KWARGS, create_new_process_for_each_test
|
||||
|
||||
MODEL_NAME = "mistralai/Voxtral-Mini-4B-Realtime-2602"
|
||||
AUDIO_LAYER_NAME = "whisper_encoder.whisper_encoder.layers.0.layers.self_attn.attn"
|
||||
ENGINE_CONFIG = {
|
||||
"model": MODEL_NAME,
|
||||
"max_model_len": 8192,
|
||||
"max_num_seqs": 4,
|
||||
"limit_mm_per_prompt": {"audio": 1},
|
||||
"config_format": "mistral",
|
||||
"load_format": "mistral",
|
||||
"tokenizer_mode": "mistral",
|
||||
"enforce_eager": True,
|
||||
"gpu_memory_utilization": 0.9,
|
||||
**ROCM_ENGINE_KWARGS,
|
||||
}
|
||||
|
||||
|
||||
EXPECTED_TEXT = [
|
||||
(
|
||||
" First words I spoke in the original phonograph. "
|
||||
"A little piece of practical poetry. Mary had a little lamb,"
|
||||
" its fleece was quite a slow, and everywhere that Mary went, "
|
||||
"the lamb was sure to go."
|
||||
),
|
||||
(
|
||||
" And the 0-1 pitch on the way to Edgar Martinez. Swung on"
|
||||
" the line. Down the left field line for OBS. Here comes Joy. "
|
||||
"Here is Junior to third base. They're going to wave him in. "
|
||||
"The throw to the plate will be late. The Mariners are going"
|
||||
" to play. For the American League Championship, "
|
||||
"I don't believe it. It just continues. My, oh, my."
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _normalize(texts: list[str]) -> list[str]:
|
||||
# The model occasionally transcribes "OBS" as "a base hit" and
|
||||
# "oh, my" as "oh my", but both are acoustically valid. Normalise so
|
||||
# the assertion is stable across runs and hardware.
|
||||
texts[1] = texts[1].replace("a base hit", "OBS").replace("oh my", "oh, my")
|
||||
return texts
|
||||
|
||||
|
||||
def assert_encoder_kv_cache_spec(engine: LLM) -> None:
|
||||
vllm_config = engine.llm_engine.vllm_config
|
||||
audio_config = vllm_config.model_config.hf_config.audio_config
|
||||
kv_cache_specs_per_rank = engine.llm_engine.model_executor.get_kv_cache_specs()
|
||||
|
||||
assert len(kv_cache_specs_per_rank) == 1
|
||||
kv_cache_specs = kv_cache_specs_per_rank[0]
|
||||
assert AUDIO_LAYER_NAME in kv_cache_specs, kv_cache_specs.keys()
|
||||
spec = kv_cache_specs[AUDIO_LAYER_NAME]
|
||||
|
||||
assert audio_config.sliding_window == 750
|
||||
assert audio_config.block_pool_size == 4
|
||||
assert isinstance(spec, SlidingWindowSpec)
|
||||
assert spec.block_size == 16
|
||||
assert spec.num_kv_heads == 32
|
||||
assert spec.tokens_per_state == Fraction(1, 4)
|
||||
# cdiv(750, 4) == 188 pooled tokens cover the model's window; the extra
|
||||
# +1 is an eviction margin (see whisper_causal.py get_kv_cache_spec).
|
||||
assert spec.sliding_window == cdiv(750, 4) + 1 == 189
|
||||
assert (
|
||||
spec.max_admission_blocks_per_request(
|
||||
max_in_flight_tokens=1,
|
||||
max_model_len=vllm_config.model_config.max_model_len,
|
||||
)
|
||||
== 13
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def audio_assets() -> list[AudioAsset]:
|
||||
return [AudioAsset("mary_had_lamb"), AudioAsset("winning_call")]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tokenizer() -> MistralTokenizer:
|
||||
return MistralTokenizer.from_hf_hub(MODEL_NAME)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def async_engine(request):
|
||||
engine_config = {**ENGINE_CONFIG, **getattr(request, "param", {})}
|
||||
gpu_memory_utilization = ENGINE_CONFIG.get("gpu_memory_utilization", 0.9)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from tests.utils import wait_for_memory_to_settle
|
||||
|
||||
wait_for_memory_to_settle(threshold_ratio=1.0 - gpu_memory_utilization)
|
||||
|
||||
engine_args = AsyncEngineArgs(**engine_config)
|
||||
llm = AsyncLLM.from_engine_args(engine_args)
|
||||
try:
|
||||
yield llm
|
||||
finally:
|
||||
shutdown_timeout = 60.0 if current_platform.is_rocm() else None
|
||||
llm.shutdown(timeout=shutdown_timeout)
|
||||
del llm
|
||||
import torch
|
||||
|
||||
torch._dynamo.reset()
|
||||
from vllm.distributed import cleanup_dist_env_and_memory
|
||||
|
||||
cleanup_dist_env_and_memory()
|
||||
from tests.utils import wait_for_memory_to_settle
|
||||
|
||||
wait_for_memory_to_settle(threshold_ratio=1.0 - gpu_memory_utilization)
|
||||
|
||||
|
||||
def _build_inputs(
|
||||
audio_assets: list[AudioAsset], tokenizer: MistralTokenizer
|
||||
) -> tuple[list[dict], list[SamplingParams]]:
|
||||
audio_config = tokenizer.instruct_tokenizer.tokenizer.audio
|
||||
inputs = []
|
||||
sampling_params = []
|
||||
for audio_asset in audio_assets:
|
||||
audio = Audio.from_file(audio_asset.get_local_path(), strict=False)
|
||||
req = TranscriptionRequest(
|
||||
audio=audio.to_base64(audio.format),
|
||||
streaming=StreamingMode.OFFLINE,
|
||||
language=None,
|
||||
)
|
||||
tokenized = tokenizer.instruct_tokenizer.encode_transcription(req)
|
||||
tokens = tokenized.tokens
|
||||
audio_array = tokenized.audios[0].audio_array
|
||||
|
||||
num_samples = audio_array.shape[0]
|
||||
max_tokens = audio_config.num_audio_tokens(num_samples) - len(tokens) - 1
|
||||
sampling_params.append(SamplingParams(temperature=0.0, max_tokens=max_tokens))
|
||||
inputs.append(
|
||||
{
|
||||
"multi_modal_data": {"audio": [(audio_array, None)]},
|
||||
"prompt_token_ids": tokens,
|
||||
}
|
||||
)
|
||||
return inputs, sampling_params
|
||||
|
||||
|
||||
def _assert_expected_text(outputs) -> None:
|
||||
texts = _normalize([out.outputs[0].text for out in outputs])
|
||||
for i, (got, expected) in enumerate(zip(texts, EXPECTED_TEXT)):
|
||||
assert got == expected, (
|
||||
f"Output mismatch at index {i}:\n"
|
||||
f" got: {got!r}\n"
|
||||
f" expected: {expected!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_voxtral_realtime_forward(audio_assets, tokenizer, vllm_runner, monkeypatch):
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
|
||||
vllm_kwargs = {**ENGINE_CONFIG}
|
||||
vllm_kwargs["model_name"] = vllm_kwargs.pop("model")
|
||||
|
||||
with vllm_runner(**vllm_kwargs) as vllm_model:
|
||||
assert_encoder_kv_cache_spec(vllm_model.llm)
|
||||
inputs, sampling_params = _build_inputs(audio_assets, tokenizer)
|
||||
|
||||
outputs = vllm_model.llm.generate(inputs, sampling_params=sampling_params)
|
||||
_assert_expected_text(outputs)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="Full cudagraphs require CUDA"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode",
|
||||
[CUDAGraphMode.FULL_DECODE_ONLY, CUDAGraphMode.FULL_AND_PIECEWISE],
|
||||
)
|
||||
@create_new_process_for_each_test(method="spawn")
|
||||
def test_voxtral_realtime_cudagraph(
|
||||
audio_assets, tokenizer, vllm_runner, monkeypatch, cudagraph_mode
|
||||
):
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
|
||||
vllm_kwargs = {**ENGINE_CONFIG}
|
||||
vllm_kwargs["model_name"] = vllm_kwargs.pop("model")
|
||||
vllm_kwargs["enforce_eager"] = False
|
||||
vllm_kwargs["compilation_config"] = {
|
||||
"cudagraph_mode": cudagraph_mode,
|
||||
# max_num_seqs is 4, so this is the only decode size worth capturing.
|
||||
"cudagraph_capture_sizes": [4],
|
||||
}
|
||||
|
||||
with vllm_runner(**vllm_kwargs) as vllm_model:
|
||||
inputs, sampling_params = _build_inputs(audio_assets, tokenizer)
|
||||
|
||||
outputs = vllm_model.llm.generate(inputs, sampling_params=sampling_params)
|
||||
_assert_expected_text(outputs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_voxtral_realtime_generator(audio_assets, tokenizer, async_engine):
|
||||
# Lazy import to avoid CUDA-reinitialization error
|
||||
from vllm.model_executor.models.voxtral_realtime import VoxtralRealtimeBuffer
|
||||
|
||||
sampling_params = SamplingParams(temperature=0.0, max_tokens=1)
|
||||
audio_config = tokenizer.instruct_tokenizer.audio_encoder.audio_config
|
||||
|
||||
async def input_stream(audio_buffer):
|
||||
async for prompt in audio_buffer.get_input_stream():
|
||||
parsed_prompt = parse_model_prompt(async_engine.model_config, prompt)
|
||||
(engine_input,) = await async_engine.renderer.render_cmpl_async(
|
||||
[parsed_prompt]
|
||||
)
|
||||
yield StreamingInput(prompt=engine_input)
|
||||
|
||||
output_tokens_list = []
|
||||
for i, audio_asset in enumerate(audio_assets):
|
||||
output_tokens = []
|
||||
audio = Audio.from_file(audio_asset.get_local_path(), strict=False)
|
||||
|
||||
req = TranscriptionRequest(
|
||||
streaming=StreamingMode.OFFLINE,
|
||||
audio=audio.to_base64(audio.format),
|
||||
language=None,
|
||||
)
|
||||
audio_enc = tokenizer.encode_transcription(req)
|
||||
|
||||
buffer = VoxtralRealtimeBuffer(audio_config, audio_enc.tokens)
|
||||
await buffer.append_audio(audio_enc.audios[0].audio_array)
|
||||
await buffer.append_audio(None)
|
||||
|
||||
request_id = f"session-{i}"
|
||||
|
||||
async for resp in async_engine.generate(
|
||||
prompt=input_stream(buffer),
|
||||
sampling_params=sampling_params,
|
||||
request_id=request_id,
|
||||
):
|
||||
tokens = resp.outputs[0].token_ids[-1:]
|
||||
output_tokens.extend(tokens)
|
||||
await buffer.append_tokens(tokens)
|
||||
|
||||
output_tokens_list.append(output_tokens)
|
||||
|
||||
texts = _normalize(
|
||||
[
|
||||
tokenizer.decode(
|
||||
output_tokens, special_token_policy=SpecialTokenPolicy.IGNORE
|
||||
)
|
||||
for output_tokens in output_tokens_list
|
||||
]
|
||||
)
|
||||
for i, (got, expected) in enumerate(zip(texts, EXPECTED_TEXT)):
|
||||
assert got == expected, (
|
||||
f"Output mismatch at index {i}:\n"
|
||||
f" got: {got!r}\n"
|
||||
f" expected: {expected!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_voxtral_realtime_buffer_stops_at_max_model_len(tokenizer):
|
||||
from vllm.model_executor.models.voxtral_realtime import VoxtralRealtimeBuffer
|
||||
|
||||
audio_config = tokenizer.instruct_tokenizer.audio_encoder.audio_config
|
||||
audio = Audio.from_file(AudioAsset("winning_call").get_local_path(), strict=False)
|
||||
req = TranscriptionRequest(
|
||||
streaming=StreamingMode.OFFLINE,
|
||||
audio=audio.to_base64(audio.format),
|
||||
language=None,
|
||||
)
|
||||
audio_enc = tokenizer.encode_transcription(req)
|
||||
|
||||
max_model_len = 64
|
||||
buffer = VoxtralRealtimeBuffer(
|
||||
audio_config, audio_enc.tokens, max_model_len=max_model_len
|
||||
)
|
||||
await buffer.append_audio(audio_enc.audios[0].audio_array)
|
||||
await buffer.append_audio(None)
|
||||
# Unlimited feedback tokens so only the length cap can stop the stream.
|
||||
await buffer.append_tokens([0] * max_model_len)
|
||||
|
||||
n_tokens = 0
|
||||
async for prompt in buffer.get_input_stream():
|
||||
n_tokens += len(prompt["prompt_token_ids"])
|
||||
|
||||
assert len(audio_enc.tokens) < n_tokens < max_model_len
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_engine", [{"max_model_len": 128}], indirect=True)
|
||||
async def test_voxtral_realtime_generator_max_model_len(
|
||||
audio_assets, tokenizer, async_engine
|
||||
):
|
||||
# Lazy import to avoid CUDA-reinitialization error
|
||||
from vllm.model_executor.models.voxtral_realtime import VoxtralRealtimeBuffer
|
||||
|
||||
max_model_len = async_engine.model_config.max_model_len
|
||||
sampling_params = SamplingParams(temperature=0.0, max_tokens=1)
|
||||
audio_config = tokenizer.instruct_tokenizer.audio_encoder.audio_config
|
||||
|
||||
async def input_stream(audio_buffer):
|
||||
async for prompt in audio_buffer.get_input_stream():
|
||||
parsed_prompt = parse_model_prompt(async_engine.model_config, prompt)
|
||||
(engine_input,) = await async_engine.renderer.render_cmpl_async(
|
||||
[parsed_prompt]
|
||||
)
|
||||
yield StreamingInput(prompt=engine_input)
|
||||
|
||||
# winning_call is ~300 tokens long, well past max_model_len.
|
||||
audio = Audio.from_file(audio_assets[1].get_local_path(), strict=False)
|
||||
req = TranscriptionRequest(
|
||||
streaming=StreamingMode.OFFLINE,
|
||||
audio=audio.to_base64(audio.format),
|
||||
language=None,
|
||||
)
|
||||
audio_enc = tokenizer.encode_transcription(req)
|
||||
buffer = VoxtralRealtimeBuffer(
|
||||
audio_config, audio_enc.tokens, max_model_len=max_model_len
|
||||
)
|
||||
await buffer.append_audio(audio_enc.audios[0].audio_array)
|
||||
await buffer.append_audio(None)
|
||||
|
||||
output_tokens = []
|
||||
async for resp in async_engine.generate(
|
||||
prompt=input_stream(buffer),
|
||||
sampling_params=sampling_params,
|
||||
request_id="session-max-len",
|
||||
):
|
||||
tokens = resp.outputs[0].token_ids[-1:]
|
||||
output_tokens.extend(tokens)
|
||||
await buffer.append_tokens(tokens)
|
||||
|
||||
assert resp.finished
|
||||
assert 0 < len(output_tokens) < max_model_len
|
||||
# The engine is still healthy after the session hit the cap.
|
||||
assert not async_engine.errored
|
||||
@@ -1,418 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import AutoModelForSpeechSeq2Seq
|
||||
|
||||
from vllm.assets.audio import AudioAsset
|
||||
from vllm.multimodal.audio import AudioResampler
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ....conftest import HfRunner, PromptAudioInput, VllmRunner
|
||||
from ....utils import create_new_process_for_each_test, multi_gpu_test
|
||||
from ...registry import HF_EXAMPLE_MODELS
|
||||
from ...utils import check_logprobs_close
|
||||
|
||||
VLLM_PROMPT = "<|startoftranscript|><|en|><|transcribe|><|notimestamps|>"
|
||||
HF_PROMPT = ""
|
||||
# Whisper expects 16kHz audio
|
||||
WHISPER_SAMPLE_RATE = 16000
|
||||
BEAM_WIDTHS = (1, 2)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def use_spawn_for_whisper(monkeypatch):
|
||||
"""Whisper has issues with forked workers, use spawn instead."""
|
||||
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
|
||||
def run_test(
|
||||
hf_runner: type[HfRunner],
|
||||
vllm_runner: type[VllmRunner],
|
||||
inputs: Sequence[tuple[list[str], list[str], PromptAudioInput]],
|
||||
model: str,
|
||||
*,
|
||||
max_model_len: int,
|
||||
dtype: str,
|
||||
max_tokens: int,
|
||||
num_logprobs: int,
|
||||
tensor_parallel_size: int,
|
||||
distributed_executor_backend: str | None = None,
|
||||
enforce_eager: bool = True,
|
||||
gpu_memory_utilization: float = 0.9,
|
||||
) -> None:
|
||||
"""Inference result should be the same between hf and vllm.
|
||||
|
||||
All the audio fixtures for the test are from AudioAsset.
|
||||
For huggingface runner, we provide the audio as input.
|
||||
For vllm runner, we provide MultiModalDataDict objects
|
||||
and corresponding MultiModalConfig as input.
|
||||
"""
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype=dtype,
|
||||
max_model_len=max_model_len,
|
||||
tensor_parallel_size=tensor_parallel_size,
|
||||
distributed_executor_backend=distributed_executor_backend,
|
||||
limit_mm_per_prompt={"audio": 2},
|
||||
enforce_eager=enforce_eager,
|
||||
gpu_memory_utilization=gpu_memory_utilization,
|
||||
disable_custom_all_reduce=True,
|
||||
) as vllm_model:
|
||||
vllm_outputs_per_case = [
|
||||
vllm_model.generate_greedy_logprobs(
|
||||
vllm_prompts,
|
||||
max_tokens,
|
||||
num_logprobs=num_logprobs,
|
||||
audios=audios,
|
||||
)
|
||||
for vllm_prompts, _, audios in inputs
|
||||
]
|
||||
|
||||
with hf_runner(model, dtype=dtype, auto_cls=AutoModelForSpeechSeq2Seq) as hf_model:
|
||||
hf_outputs_per_case = [
|
||||
hf_model.generate_greedy_logprobs_limit(
|
||||
hf_prompts,
|
||||
max_tokens,
|
||||
num_logprobs=num_logprobs,
|
||||
audios=audios,
|
||||
)
|
||||
for _, hf_prompts, audios in inputs
|
||||
]
|
||||
|
||||
for hf_outputs, vllm_outputs in zip(hf_outputs_per_case, vllm_outputs_per_case):
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=hf_outputs,
|
||||
outputs_1_lst=vllm_outputs,
|
||||
name_0="hf",
|
||||
name_1="vllm",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def resampled_assets() -> list[tuple[Any, int]]:
|
||||
audio_assets = [AudioAsset("mary_had_lamb"), AudioAsset("winning_call")]
|
||||
sampled_assets = []
|
||||
resampler = AudioResampler(target_sr=WHISPER_SAMPLE_RATE)
|
||||
for asset in audio_assets:
|
||||
audio, orig_sr = asset.audio_and_sample_rate
|
||||
# Resample to Whisper's expected sample rate (16kHz)
|
||||
if orig_sr != WHISPER_SAMPLE_RATE:
|
||||
audio = resampler.resample(audio, orig_sr=orig_sr)
|
||||
sampled_assets.append(
|
||||
(audio, WHISPER_SAMPLE_RATE),
|
||||
)
|
||||
return sampled_assets
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def input_audios(
|
||||
resampled_assets,
|
||||
) -> list[tuple[list[str], list[str], list[tuple[Any, int]]]]:
|
||||
inputs = []
|
||||
# audio assets are resampled to WHISPER_SAMPLE_RATE
|
||||
for audio_info in resampled_assets:
|
||||
# vLLM prompts, HF prompts, audio inputs
|
||||
inputs.append(([VLLM_PROMPT], [HF_PROMPT], [audio_info]))
|
||||
return inputs
|
||||
|
||||
|
||||
def check_model_available(model: str) -> None:
|
||||
model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
|
||||
model_info.check_available_online(on_fail="skip")
|
||||
model_info.check_transformers_version(on_fail="skip")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.parametrize("max_tokens", [64])
|
||||
def test_beam_search_encoder_decoder(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
dtype: str,
|
||||
max_tokens: int,
|
||||
resampled_assets,
|
||||
) -> None:
|
||||
"""Test beam search with encoder-decoder models (Whisper)."""
|
||||
model = "openai/whisper-large-v3-turbo"
|
||||
check_model_available(model)
|
||||
|
||||
hf_prompts = [
|
||||
"<|startoftranscript|>",
|
||||
"<|startoftranscript|>",
|
||||
]
|
||||
|
||||
with hf_runner(model, dtype=dtype, auto_cls=AutoModelForSpeechSeq2Seq) as hf_model:
|
||||
hf_outputs_by_beam_width = [
|
||||
hf_model.generate_beam_search(
|
||||
hf_prompts,
|
||||
beam_width=beam_width,
|
||||
max_tokens=max_tokens,
|
||||
audios=resampled_assets,
|
||||
)
|
||||
for beam_width in BEAM_WIDTHS
|
||||
]
|
||||
|
||||
# Test both explicit encoder/decoder prompts
|
||||
vllm_prompts = [
|
||||
# Implicit encoder/decoder prompt
|
||||
{
|
||||
"prompt": "<|startoftranscript|>",
|
||||
"multi_modal_data": {"audio": resampled_assets[0]},
|
||||
},
|
||||
# Explicit encoder/decover prompt
|
||||
{
|
||||
"encoder_prompt": {
|
||||
"prompt": "",
|
||||
"multi_modal_data": {"audio": resampled_assets[1]},
|
||||
},
|
||||
"decoder_prompt": "<|startoftranscript|>",
|
||||
},
|
||||
]
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype="half",
|
||||
max_model_len=448,
|
||||
tensor_parallel_size=1,
|
||||
max_num_seqs=4,
|
||||
limit_mm_per_prompt={"audio": 2},
|
||||
enforce_eager=True,
|
||||
) as vllm_model:
|
||||
vllm_outputs_by_beam_width = [
|
||||
vllm_model.generate_beam_search(
|
||||
vllm_prompts,
|
||||
beam_width=beam_width,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
for beam_width in BEAM_WIDTHS
|
||||
]
|
||||
|
||||
for beam_width, hf_outputs, vllm_outputs in zip(
|
||||
BEAM_WIDTHS, hf_outputs_by_beam_width, vllm_outputs_by_beam_width
|
||||
):
|
||||
for i in range(len(vllm_prompts)):
|
||||
hf_output_ids, hf_output_texts = hf_outputs[i]
|
||||
vllm_output_ids, vllm_output_texts = vllm_outputs[i]
|
||||
|
||||
for j, (hf_text, vllm_text) in enumerate(
|
||||
zip(hf_output_texts, vllm_output_texts)
|
||||
):
|
||||
print(f">>>{j}-th hf output [NOTE: special tokens are filtered]:")
|
||||
print(hf_text)
|
||||
print(f">>>{j}-th vllm output:")
|
||||
print(vllm_text)
|
||||
|
||||
# Check that we got the same number of beams
|
||||
assert len(hf_output_ids) == len(vllm_output_ids) == beam_width
|
||||
|
||||
# For encoder-decoder models, we primarily want to verify that:
|
||||
# 1. Beam search completes without errors
|
||||
# 2. We get the expected number of beams
|
||||
# 3. Outputs are reasonable (non-empty, diverse beams)
|
||||
for j in range(len(vllm_output_ids)):
|
||||
# Check that outputs are not empty
|
||||
assert len(vllm_output_ids[j]) > 0, (
|
||||
f"Prompt {i}, beam {j}: empty output"
|
||||
)
|
||||
# Check that decoded text is not empty
|
||||
assert len(vllm_output_texts[j].strip()) > 0, (
|
||||
f"Prompt {i}, beam {j}: empty text output"
|
||||
)
|
||||
|
||||
|
||||
def test_parse_language_detection_output():
|
||||
"""Unit test for WhisperForConditionalGeneration.parse_language_detection_output.
|
||||
|
||||
No GPU or model loading required.
|
||||
"""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from vllm.model_executor.models.whisper import (
|
||||
WhisperForConditionalGeneration,
|
||||
)
|
||||
|
||||
cls = WhisperForConditionalGeneration
|
||||
|
||||
def make_tokenizer(return_value: str) -> MagicMock:
|
||||
tok = MagicMock()
|
||||
tok.decode = MagicMock(return_value=return_value)
|
||||
return tok
|
||||
|
||||
# English
|
||||
assert (
|
||||
cls.parse_language_detection_output([50259], make_tokenizer("<|en|>")) == "en"
|
||||
)
|
||||
|
||||
# German
|
||||
assert (
|
||||
cls.parse_language_detection_output([50261], make_tokenizer("<|de|>")) == "de"
|
||||
)
|
||||
|
||||
# Unsupported language code
|
||||
with pytest.raises(AssertionError):
|
||||
cls.parse_language_detection_output([99999], make_tokenizer("<|xx|>"))
|
||||
|
||||
# No special token format
|
||||
with pytest.raises(AssertionError):
|
||||
cls.parse_language_detection_output([1], make_tokenizer("hello"))
|
||||
|
||||
# Empty token_ids
|
||||
with pytest.raises((AssertionError, IndexError)):
|
||||
cls.parse_language_detection_output([], make_tokenizer("anything"))
|
||||
|
||||
|
||||
def test_create_fake_bias_for_k_proj_injects_out_features():
|
||||
"""Packed k_proj weights get a zeros bias of length ``out_features``."""
|
||||
from vllm.model_executor.models.whisper import _create_fake_bias_for_k_proj
|
||||
|
||||
packed = torch.ones(2, 16)
|
||||
result = dict(
|
||||
_create_fake_bias_for_k_proj(
|
||||
[("model.encoder.layers.0.self_attn.k_proj.weight_packed", packed)],
|
||||
".k_proj.weight_packed",
|
||||
out_features=8,
|
||||
)
|
||||
)
|
||||
bias_name = "model.encoder.layers.0.self_attn.k_proj.bias"
|
||||
assert bias_name in result
|
||||
assert "model.encoder.layers.0.self_attn.k_proj.bias_packed" not in result
|
||||
assert tuple(result[bias_name].shape) == (8,)
|
||||
assert torch.equal(result[bias_name], torch.zeros(8))
|
||||
|
||||
|
||||
def test_create_fake_bias_for_k_proj_forwards_real_bias():
|
||||
"""A checkpoint bias is forwarded and no extra fake bias is emitted."""
|
||||
from vllm.model_executor.models.whisper import _create_fake_bias_for_k_proj
|
||||
|
||||
weight = torch.ones(8, 16)
|
||||
real_bias = torch.ones(8)
|
||||
items = list(
|
||||
_create_fake_bias_for_k_proj(
|
||||
[
|
||||
("layers.0.self_attn.k_proj.weight", weight),
|
||||
("layers.0.self_attn.k_proj.bias", real_bias),
|
||||
],
|
||||
".k_proj.weight",
|
||||
out_features=8,
|
||||
)
|
||||
)
|
||||
names = [n for n, _ in items]
|
||||
assert names == [
|
||||
"layers.0.self_attn.k_proj.weight",
|
||||
"layers.0.self_attn.k_proj.bias",
|
||||
]
|
||||
assert items[1][1] is real_bias
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.cpu_model
|
||||
@pytest.mark.parametrize("model", ["openai/whisper-large-v3-turbo"])
|
||||
@pytest.mark.parametrize("dtype", ["half", "float"])
|
||||
@pytest.mark.parametrize("num_logprobs", [5])
|
||||
@pytest.mark.parametrize("enforce_eager", [True, False])
|
||||
def test_models(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
model: str,
|
||||
dtype: str,
|
||||
num_logprobs: int,
|
||||
input_audios,
|
||||
enforce_eager: bool,
|
||||
) -> None:
|
||||
check_model_available(model)
|
||||
if current_platform.is_cpu() and not enforce_eager:
|
||||
pytest.skip("Skipping test for CPU with non-eager mode")
|
||||
run_test(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
input_audios,
|
||||
model,
|
||||
dtype=dtype,
|
||||
max_model_len=448,
|
||||
max_tokens=200,
|
||||
num_logprobs=num_logprobs,
|
||||
tensor_parallel_size=1,
|
||||
enforce_eager=enforce_eager,
|
||||
)
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.parametrize("model", ["openai/whisper-large-v3-turbo"])
|
||||
@pytest.mark.parametrize("distributed_executor_backend", ["ray", "mp"])
|
||||
@pytest.mark.parametrize("dtype", ["half"])
|
||||
@pytest.mark.parametrize("max_tokens", [200])
|
||||
@pytest.mark.parametrize("num_logprobs", [5])
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_models_distributed(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
model: str,
|
||||
distributed_executor_backend: str,
|
||||
dtype: str,
|
||||
max_tokens: int,
|
||||
num_logprobs: int,
|
||||
input_audios,
|
||||
) -> None:
|
||||
check_model_available(model)
|
||||
run_test(
|
||||
hf_runner,
|
||||
vllm_runner,
|
||||
input_audios,
|
||||
model,
|
||||
dtype=dtype,
|
||||
max_model_len=448,
|
||||
max_tokens=max_tokens,
|
||||
num_logprobs=num_logprobs,
|
||||
tensor_parallel_size=2,
|
||||
distributed_executor_backend=distributed_executor_backend,
|
||||
enforce_eager=False,
|
||||
gpu_memory_utilization=0.65,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.core_model
|
||||
@pytest.mark.parametrize("model", ["openai/whisper-large-v3-turbo"])
|
||||
def test_encoder_cache_cleanup(
|
||||
vllm_runner,
|
||||
model: str,
|
||||
input_audios,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""Test that encoder cache is properly cleaned up after requests complete.
|
||||
|
||||
This is a regression test for a bug where encoder cache entries were freed
|
||||
in the same scheduling step they were allocated, before the model could use
|
||||
them.
|
||||
"""
|
||||
# Set single-process mode to access the model runner's encoder cache directly
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
check_model_available(model)
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype="half",
|
||||
max_model_len=448,
|
||||
tensor_parallel_size=1,
|
||||
limit_mm_per_prompt={"audio": 2},
|
||||
enforce_eager=True,
|
||||
) as vllm_model:
|
||||
engine_core = vllm_model.llm.llm_engine.engine_core.engine_core
|
||||
model_runner = engine_core.model_executor.driver_worker.worker.model_runner
|
||||
encoder_cache = model_runner.encoder_cache
|
||||
|
||||
# Run multiple sequential requests to ensure cache is properly managed
|
||||
for vllm_prompts, _, audios in input_audios:
|
||||
vllm_model.generate_greedy(vllm_prompts, max_tokens=50, audios=audios)
|
||||
|
||||
# After all requests complete, encoder cache should be empty
|
||||
cache_size = len(encoder_cache)
|
||||
assert cache_size == 0, (
|
||||
f"Encoder cache should be empty after all requests complete, "
|
||||
f"but has {cache_size} entries. This indicates encoder cache "
|
||||
f"entries are not being properly freed."
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user