[Rebase] Rebase to vllm v0.24.0 (#4709)

This commit is contained in:
Zhou Taichang authored and GitHub committed 2026-06-30 19:41:06 +08:00
1 parent 9a105bf90d
commit a560ed184d
60 files changed
+789 -203

No files matched your search

@@ -8,11 +8,11 @@ from types import SimpleNamespace
import pytest
import torch
from vllm.model_executor.layers.linear import LinearBase
from vllm.model_executor.layers.quantization.gguf import UNQUANTIZED_TYPES, UnquantizedLinearMethod
from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod
from vllm_omni.quantization import build_quant_config
from vllm_omni.quantization.gguf_config import (
UNQUANTIZED_TYPES,
DiffusionGGUFConfig,
DiffusionGGUFLinearMethod,
dequant_gemm_gguf,
@@ -38,13 +38,13 @@ class _ToyKernel:
def _make_fp8_toy_module(out_features: int = 16, in_features: int = 32):
"""Return a module whose weight is ``qweight.t()`` (non-contiguous) and whose
``quant_method`` is an ``Fp8OnlineLinearMethod`` with a ``_ToyKernel``.
``quant_method`` is an ``Fp8LinearMethod`` with a ``_ToyKernel``.
"""
from vllm.model_executor.layers.quantization.fp8 import Fp8OnlineLinearMethod
from vllm.model_executor.layers.quantization.fp8 import Fp8LinearMethod
# Create the quant-method instance without calling __init__ (avoids
# heavyweight upstream config dependencies). isinstance() still works.
qm = object.__new__(Fp8OnlineLinearMethod)
qm = object.__new__(Fp8LinearMethod)
qm.fp8_linear = _ToyKernel()
# randn does not support float8 on CPU; zeros does and the test only
@@ -72,6 +72,10 @@ class TestHiggsAudioV3OnlineHappyPath:
"stream": False,
"response_format": "wav",
"timeout": DEFAULT_SPEECH_TIMEOUT_S,
# whisper-small mishears this short clip ~0.5% of the time; on a
# failed match re-verify with this stronger ASR before failing so
# the gate is not flaky. Local-only key (not forwarded to server).
"transcript_escalation_model": "large-v3",
}
)
@@ -40,11 +40,21 @@ def get_batch_token_config(default_path):
Uses the new flat-stage schema (``stages.<id>.<field>``); the legacy
``stage_args.<id>.engine_args.<field>`` path no longer applies because
the deploy YAML doesn't nest engine fields under ``engine_args:``.
Note:
64 was the original value but caused a GPU hang (NVIDIA watchdog killed
the process after ~2 s) when 5 concurrent requests arrived, due to an
upstream scheduler change (``throttle_prefills`` API in vLLM commit
0b131b16c). 512 was first tried but caused output quality degradation for
long audio (~120 s) inputs. 2048 gives the scheduler enough token budget
to handle 5 concurrent requests even with multi-second audio prefill,
while still being well below the default 32768.
If the upstream scheduler changes again, this value may need adjustment.
"""
return modify_stage_config(
default_path,
updates={
"stages": {0: {"max_num_batched_tokens": 64}, 1: {"max_num_batched_tokens": 64}},
"stages": {0: {"max_num_batched_tokens": 2048}, 1: {"max_num_batched_tokens": 2048}},
},
)
@@ -79,6 +79,7 @@ def test_create_chat_completion_converts_value_error_to_error_response(mocker: M
serving_chat.renderer.get_tokenizer.return_value = mocker.MagicMock()
serving_chat.reasoning_parser_cls = None
serving_chat.tool_parser = None
serving_chat.parser_cls = None
serving_chat.use_harmony = False
serving_chat.enable_auto_tools = False
serving_chat.exclude_tools_when_tool_choice_none = False
@@ -86,8 +87,9 @@ def test_create_chat_completion_converts_value_error_to_error_response(mocker: M
serving_chat.chat_template = None
serving_chat.chat_template_content_format = "string"
serving_chat.default_chat_template_kwargs = {}
serving_chat._validate_chat_template = mocker.MagicMock(return_value=None)
serving_chat._prepare_extra_chat_template_kwargs = mocker.MagicMock(return_value={})
serving_chat.openai_serving_render = mocker.MagicMock()
serving_chat.openai_serving_render.validate_chat_template.return_value = None
serving_chat._effective_chat_template_kwargs = mocker.MagicMock(return_value={})
serving_chat._preprocess_chat = mocker.AsyncMock(
side_effect=ValueError("Invalid speaker 'uncle_fu'. Supported: ethan, vivian")
)
+74 -5
View File
@@ -23,6 +23,15 @@ from tests.helpers.media import (
_GENDER_PIPELINE = None
_GENDER_PIPELINE_LOCK = threading.Lock()
# Transcript gates default to whisper ``small`` for speed. ``small`` mishears a
# short TTS clip ~0.5% of the time (e.g. "Hello"->"fellow", or hallucinating a
# leading SFX token), which flakes the deterministic similarity gate. A test can
# opt in to ASR escalation by setting ``transcript_escalation_model`` to a
# whisper model name (e.g. ``"large-v3"``) in its request_config: on a failed
# fast pass the clip is re-transcribed with that stronger ASR before the test
# fails, so a weak-ASR mishear is rescued while a genuine model artifact still
# fails (the strong ASR mismatches too). Tests that do not opt in keep the
# strict behaviour.
_PCM_SPEECH_SAMPLE_RATE_HZ = 24_000
_MIN_PCM_SPEECH_HNR_DB = 1.0
_PRESET_VOICE_GENDER_MAP: dict[str, str] = {
@@ -456,7 +465,15 @@ def _omni_assertion_needs_audio_transcript(request_config: dict[str, Any], run_l
if "audio" not in modalities:
return False
keywords_dict = request_config.get("key_words", {}) or {}
if keywords_dict.get("audio") and "text" not in modalities:
# When text is not an output modality, the keyword loop validates keywords
# against the audio transcript -- for keywords under ANY word_type
# (text/image/audio/video), not just "audio". Mirror that here so the
# transcript is actually computed; otherwise the loop hits
# `assert transcript is not None` with transcript=None (e.g. an audio-only
# request carrying key_words={"text": [...]}).
if "text" not in modalities and any(
keywords_dict.get(word_type) for word_type in ("text", "image", "audio", "video")
):
return True
if request_config.get("audio_ref_text"):
return True
@@ -590,6 +607,56 @@ def assert_omni_response(response: Any, request_config: dict[str, Any], run_leve
)
def _assert_transcript_matches(
transcript: str,
audio_bytes: bytes | None,
expected_text: Any,
*,
threshold: float,
escalation_model: str | None = None,
) -> None:
"""Assert spoken audio matches ``expected_text``.
``transcript`` is the fast whisper-``small`` result. If it clears
``threshold`` the check passes immediately.
When ``escalation_model`` is set (opt-in via the ``transcript_escalation_model``
request_config key) and the fast check fails, the clip is re-transcribed with
that stronger ASR and the assertion is decided on its verdict -- so a weak
whisper-``small`` mishear on a short clip does not flake the gate, while a
genuine model artifact still fails (the strong ASR mismatches too). When
``escalation_model`` is ``None`` the original strict behaviour is preserved,
so other tests are unaffected.
"""
expected = str(expected_text).strip().lower()
similarity = cosine_similarity_text(transcript.strip().lower(), expected)
print(f"Cosine similarity: {similarity:.3f}")
if similarity > threshold:
return
if escalation_model and audio_bytes:
print(
f"whisper-small below threshold ({similarity:.2f} <= {threshold}); "
f"escalating to whisper-{escalation_model} to rule out an ASR mishear"
)
strong_transcript = convert_audio_bytes_to_text(audio_bytes, model_size=escalation_model)
strong_similarity = cosine_similarity_text(strong_transcript.strip().lower(), expected)
print(
f"audio content (whisper-{escalation_model}): {strong_transcript}\n"
f"Cosine similarity (whisper-{escalation_model}): {strong_similarity:.3f}"
)
assert strong_similarity > threshold, (
f"Transcript doesn't match input after ASR escalation: "
f"input={expected_text!r}; whisper-small='{transcript}' (sim={similarity:.2f}); "
f"whisper-{escalation_model}='{strong_transcript}' (sim={strong_similarity:.2f})"
)
return
assert similarity > threshold, (
f"Transcript doesn't match input: similarity={similarity:.2f}, transcript='{transcript}'"
)
def assert_audio_speech_response(response: Any, request_config: dict[str, Any], run_level: str) -> None:
"""Validate speech API results from :class:`~tests.helpers.runtime.OmniResponse`.
@@ -643,10 +710,12 @@ def assert_audio_speech_response(response: Any, request_config: dict[str, Any],
if expected_text:
print(f"audio content is: {transcript}")
print(f"input text is: {expected_text}")
similarity = cosine_similarity_text(transcript.strip().lower(), str(expected_text).lower())
print(f"Cosine similarity: {similarity:.3f}")
assert similarity > 0.9, (
f"Transcript doesn't match input: similarity={similarity:.2f}, transcript='{transcript}'"
_assert_transcript_matches(
transcript,
getattr(response, "audio_bytes", None),
expected_text,
threshold=0.9,
escalation_model=request_config.get("transcript_escalation_model"),
)
_assert_preset_voice_gender_from_audio(
response.audio_bytes,
+10 -10
View File
@@ -617,11 +617,11 @@ def _merge_base64_audio_to_segment(base64_list: list[str]) -> _AudioBuffer:
@contextmanager
def _serialize_whisper_small_model_download():
"""Serialize Whisper ``small`` cache writes across processes (Linux/Unix)."""
def _serialize_whisper_model_download(model_size: str = "small"):
"""Serialize Whisper cache writes across processes (Linux/Unix), per model."""
import fcntl
lock_path = Path.home() / ".cache" / "whisper" / ".small_model_download.lock"
lock_path = Path.home() / ".cache" / "whisper" / f".{model_size}_model_download.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
f = open(lock_path, "a+b")
try:
@@ -632,7 +632,7 @@ def _serialize_whisper_small_model_download():
f.close()
def _whisper_transcribe_in_current_process(output_path: str) -> str:
def _whisper_transcribe_in_current_process(output_path: str, model_size: str = "small") -> str:
import whisper
device_index = None
@@ -656,8 +656,8 @@ def _whisper_transcribe_in_current_process(output_path: str) -> str:
use_accelerator = False
device = "cpu"
with _serialize_whisper_small_model_download():
model = whisper.load_model("small", device=device)
with _serialize_whisper_model_download(model_size):
model = whisper.load_model(model_size, device=device)
try:
text = model.transcribe(
output_path,
@@ -674,15 +674,15 @@ def _whisper_transcribe_in_current_process(output_path: str) -> str:
return text or ""
def convert_audio_file_to_text(output_path: str) -> str:
def convert_audio_file_to_text(output_path: str, model_size: str = "small") -> str:
"""Convert an audio file to text in an isolated subprocess."""
ctx = multiprocessing.get_context("spawn")
with concurrent.futures.ProcessPoolExecutor(max_workers=1, mp_context=ctx) as executor:
future = executor.submit(_whisper_transcribe_in_current_process, output_path)
future = executor.submit(_whisper_transcribe_in_current_process, output_path, model_size)
return future.result()
def convert_audio_bytes_to_text(raw_bytes: bytes) -> str:
def convert_audio_bytes_to_text(raw_bytes: bytes, model_size: str = "small") -> str:
output_fd, output_path = tempfile.mkstemp(prefix="test_", suffix=".wav")
os.close(output_fd)
if os.environ.get("VLLM_OMNI_KEEP_REQUEST_MEDIA", "").lower() not in ("1", "true", "yes"):
@@ -690,7 +690,7 @@ def convert_audio_bytes_to_text(raw_bytes: bytes) -> str:
data, samplerate = sf.read(io.BytesIO(raw_bytes))
sf.write(output_path, data, samplerate, format="WAV", subtype="PCM_16")
print(f"audio data is saved: {output_path}")
return convert_audio_file_to_text(output_path)
return convert_audio_file_to_text(output_path, model_size)
__all__ = [
+8 -2
View File
@@ -482,6 +482,7 @@ _CI_OVERLAYS: dict[str, dict[str, Any]] = {
{
"stage_id": 1,
"max_num_seqs": 1,
"gpu_memory_utilization": 0.5,
},
],
},
@@ -577,10 +578,15 @@ _CI_OVERLAYS: dict[str, dict[str, Any]] = {
{
"stage_id": 0,
"max_num_seqs": 1,
"gpu_memory_utilization": 0.9,
# Tuned for the heavier rebased stack (vLLM v0.23.1rc1 + torch 2.11 + CUDA 13
# + flashinfer) on a 24 GiB L4: the 16.78 GiB model weights + non-KV overhead
# + a 16384-token activation peak left 0 KV cache at util 0.85 (build 2354
# OOM). The abort test only needs the engine to init, so a smaller batched-
# token budget is fine; outputs are unaffected (chunked prefill is on).
"gpu_memory_utilization": 0.90,
"enforce_eager": True,
"enable_prefix_caching": False,
"max_num_batched_tokens": 16384,
"max_num_batched_tokens": 2048,
"max_model_len": 16384,
"skip_mm_profiling": True,
"mm_processor_cache_gb": 0,
@@ -156,14 +156,19 @@ class TestPerRequestRouting:
assert torch.all(audio[0][1] == 0) # this step's row 0 appended
assert torch.all(audio[1] == 1)
def test_runs_without_spans_backward_compat(self):
"""Missing request_token_spans must not crash (equal-split fallback)
and still yields a batch-aligned list."""
def test_runs_with_spans(self):
"""request_token_spans are required for correct per-request routing;
verify that passing them produces a batch-aligned list."""
talker = _make_bare_delay_talker()
hidden = _row_indexed_hidden(2)
info_dicts = [{}, {}]
spans = [(0, 1), (1, 2)]
result = talker.make_omni_output(hidden, runtime_additional_information=info_dicts)
result = talker.make_omni_output(
hidden,
runtime_additional_information=info_dicts,
request_token_spans=spans,
)
audio = _audio_payload(result)
assert isinstance(audio, list)
assert len(audio) == 2
@@ -41,6 +41,7 @@ def _make_minimal_talker(
def _default_raise(**_kwargs):
raise AssertionError("build_prompt_embeds was not stubbed in this test")
model._embedding_dtype = torch.bfloat16
model._prompt_builder = SimpleNamespace(
build_prompt_embeds=build_prompt_embeds if build_prompt_embeds is not None else _default_raise,
)
@@ -89,6 +90,7 @@ def _make_minimal_builder(
)
builder._speaker_cache = None
builder._text_tokenizer = None
builder._embedding_dtype = torch.bfloat16
builder._ref_audio_artifact_cache_max_entries = 256
builder._ref_audio_artifact_cache = OrderedDict()
builder._resampler_cache = OrderedDict()
+5 -1
View File
@@ -434,8 +434,12 @@ def test_sample_tokens_tail_only_prefix_cache_uses_staged_cpu_hidden_states(monk
output = GPUARModelRunner.sample_tokens(runner, grammar_output=None)
assert output.inter_stage_outputs is None
# Non-async-chunk now ships the full payload to the next stage, so
# inter_stage_outputs mirrors multimodal_outputs (PR #4792).
assert output.inter_stage_outputs is not None
assert output.multimodal_outputs is not None
assert torch.equal(output.inter_stage_outputs[0]["hidden"], output.multimodal_outputs[0]["hidden"])
assert torch.equal(output.inter_stage_outputs[1]["hidden"], output.multimodal_outputs[1]["hidden"])
assert torch.equal(output.multimodal_outputs[0]["hidden"], torch.tensor([[1.0, 10.0]]))
assert torch.equal(
output.multimodal_outputs[1]["hidden"],