[Model] Add GLM-TTS text-to-speech model support (#3141)
Signed-off-by: BeatSeat <wendavid552@gmail.com> Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com> Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
1 parent
748470c1fb
commit
28ce618f0e
38 files changed
+7568
-7
No files matched your search
Binary file not shown.
@@ -0,0 +1,148 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""E2E Offline inference tests for GLM-TTS voice cloning.
|
||||
|
||||
GLM-TTS is a zero-shot voice cloning model that always requires ref_audio.
|
||||
There is no text-only / non-clone inference path in the official implementation.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import soundfile as sf
|
||||
|
||||
from tests.helpers.assertions import assert_audio_speech_response
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import convert_audio_file_to_text, get_asset_path
|
||||
from tests.helpers.runtime import OmniResponse
|
||||
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
|
||||
from vllm_omni.model_executor.models.glm_tts.glm_tts import build_glm_tts_prefill_metadata
|
||||
|
||||
MODEL = os.environ.get("GLM_TTS_MODEL_PATH", "zai-org/GLM-TTS")
|
||||
REF_TEXT = "他当时还跟线下其他的站姐吵架,然后,打架进局子了。"
|
||||
|
||||
DEPLOY_CONFIG = get_deploy_config_path("glm_tts.yaml")
|
||||
|
||||
REFERENCE_PROMPT_WAV_PATH = get_asset_path("glm_tts/jiayan_zh.wav")
|
||||
|
||||
ASYNC_CHUNK_MODES = [
|
||||
pytest.param(False, id="sync"),
|
||||
pytest.param(True, id="async_chunk"),
|
||||
]
|
||||
|
||||
|
||||
def _load_ref_audio() -> tuple[np.ndarray, int]:
|
||||
audio, sr = sf.read(str(REFERENCE_PROMPT_WAV_PATH), dtype="float32", always_2d=False)
|
||||
if isinstance(audio, np.ndarray) and audio.ndim > 1:
|
||||
audio = np.mean(audio, axis=-1)
|
||||
return np.asarray(audio, dtype=np.float32), int(sr)
|
||||
|
||||
|
||||
def _concat_audio(audio_val) -> np.ndarray:
|
||||
import torch
|
||||
|
||||
if isinstance(audio_val, list):
|
||||
tensors = [torch.as_tensor(t).float().reshape(-1) for t in audio_val if t is not None]
|
||||
if not tensors:
|
||||
return np.zeros((0,), dtype=np.float32)
|
||||
return torch.cat(tensors, dim=-1).cpu().numpy().astype(np.float32, copy=False)
|
||||
if isinstance(audio_val, torch.Tensor):
|
||||
return audio_val.float().cpu().numpy().reshape(-1)
|
||||
return np.asarray(audio_val, dtype=np.float32).reshape(-1)
|
||||
|
||||
|
||||
def _extract_sample_rate(audio_mm: dict) -> int:
|
||||
sr_raw = audio_mm.get("sr", 24000)
|
||||
if isinstance(sr_raw, list):
|
||||
sr_raw = sr_raw[-1] if sr_raw else 24000
|
||||
if hasattr(sr_raw, "item"):
|
||||
return int(sr_raw.item())
|
||||
return int(sr_raw)
|
||||
|
||||
|
||||
def _get_deploy_config(*, async_chunk: bool) -> str:
|
||||
"""Build deploy config with explicit sync/async mode and eager execution."""
|
||||
return modify_stage_config(
|
||||
DEPLOY_CONFIG,
|
||||
updates={
|
||||
"async_chunk": async_chunk,
|
||||
"stages": {
|
||||
0: {
|
||||
"enforce_eager": True,
|
||||
"async_scheduling": bool(async_chunk),
|
||||
},
|
||||
1: {
|
||||
"enforce_eager": True,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@pytest.mark.parametrize("async_chunk", ASYNC_CHUNK_MODES)
|
||||
def test_offline_voice_clone_zh(async_chunk: bool) -> None:
|
||||
"""
|
||||
Test voice cloning offline inference.
|
||||
Deploy Setting: glm_tts.yaml with explicit sync/async mode, enforce_eager
|
||||
Input Modal: text + ref_audio + ref_text
|
||||
Output Modal: audio
|
||||
|
||||
Uses the official jiayan_zh.wav reference audio from the upstream
|
||||
GLM-TTS repository (real human speech matching REF_TEXT).
|
||||
"""
|
||||
synth_text = "今天天气真不错,适合出去散散步。"
|
||||
prompt_audio = _load_ref_audio()
|
||||
from tests.helpers.runtime import OmniRunner
|
||||
|
||||
with OmniRunner(
|
||||
MODEL,
|
||||
stage_configs_path=_get_deploy_config(async_chunk=async_chunk),
|
||||
stage_init_timeout=600,
|
||||
) as omni_runner:
|
||||
outputs = omni_runner.omni.generate(
|
||||
[
|
||||
{
|
||||
"prompt": synth_text,
|
||||
"multi_modal_data": {"audio": prompt_audio},
|
||||
"modalities": ["audio"],
|
||||
"mm_processor_kwargs": {"prompt_text": REF_TEXT},
|
||||
"additional_information": build_glm_tts_prefill_metadata(
|
||||
MODEL,
|
||||
synth_text,
|
||||
REF_TEXT,
|
||||
trust_remote_code=True,
|
||||
),
|
||||
}
|
||||
],
|
||||
omni_runner.get_default_sampling_params_list(),
|
||||
)
|
||||
|
||||
assert outputs, "No outputs returned"
|
||||
audio_mm = outputs[0].multimodal_output
|
||||
assert "audio" in audio_mm, "No audio output found"
|
||||
audio = _concat_audio(audio_mm["audio"])
|
||||
assert audio.size > 0, "Generated audio is empty"
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".wav") as out_file:
|
||||
sf.write(out_file.name, audio, samplerate=_extract_sample_rate(audio_mm), format="WAV")
|
||||
transcript = convert_audio_file_to_text(out_file.name)
|
||||
audio_bytes = open(out_file.name, "rb").read()
|
||||
|
||||
assert_audio_speech_response(
|
||||
OmniResponse(
|
||||
success=True,
|
||||
audio_bytes=audio_bytes,
|
||||
audio_content=transcript,
|
||||
audio_format="audio/wav",
|
||||
),
|
||||
{"input": synth_text, "response_format": "wav"},
|
||||
run_level="advanced_model",
|
||||
)
|
||||
@@ -0,0 +1,131 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
E2E Online tests for GLM-TTS model with text input and audio output.
|
||||
|
||||
These tests verify the /v1/audio/speech endpoint works correctly with
|
||||
the GLM-TTS two-stage pipeline (AR + DiT).
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "0"
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import load_test_audio_data_url
|
||||
from tests.helpers.runtime import OmniServerParams
|
||||
from tests.helpers.stage_config import get_deploy_config_path
|
||||
|
||||
MODEL = os.environ.get("GLM_TTS_MODEL_PATH", "zai-org/GLM-TTS")
|
||||
REF_TEXT = "他当时还跟线下其他的站姐吵架,然后,打架进局子了。"
|
||||
|
||||
DEPLOY_CONFIG = get_deploy_config_path("glm_tts.yaml")
|
||||
|
||||
# Official GLM-TTS reference audio and transcript. Vendored under tests/assets/
|
||||
# so Buildkite does not depend on raw.githubusercontent.com during E2E.
|
||||
REF_AUDIO_URL = load_test_audio_data_url("glm_tts/jiayan_zh.wav")
|
||||
|
||||
|
||||
SYNC_EXTRA_ARGS = [
|
||||
"--trust-remote-code",
|
||||
"--disable-log-stats",
|
||||
"--no-async-chunk",
|
||||
]
|
||||
|
||||
ASYNC_EXTRA_ARGS = [
|
||||
"--trust-remote-code",
|
||||
"--disable-log-stats",
|
||||
]
|
||||
|
||||
tts_sync_server_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=DEPLOY_CONFIG,
|
||||
server_args=SYNC_EXTRA_ARGS,
|
||||
stage_init_timeout=600,
|
||||
),
|
||||
id="glm_tts_sync",
|
||||
)
|
||||
]
|
||||
|
||||
tts_async_chunk_server_params = [
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=DEPLOY_CONFIG,
|
||||
server_args=ASYNC_EXTRA_ARGS,
|
||||
stage_init_timeout=600,
|
||||
),
|
||||
id="glm_tts_async_chunk",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
# GLM-TTS is a zero-shot voice cloning model (always requires ref_audio).
|
||||
# There is no text-only / non-clone path — the official implementation
|
||||
# asserts prompt_feat.shape[1] != 0 in token2wav_with_cache and every
|
||||
# example prompt includes a reference audio. CosyVoice3 follows the same
|
||||
# pattern: all tests are voice_clone_*.
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_sync_server_params, indirect=True)
|
||||
def test_voice_clone_zh_sync(omni_server, openai_client) -> None:
|
||||
"""
|
||||
Test voice cloning TTS with Chinese text.
|
||||
Deploy Setting: glm_tts.yaml with ``--no-async-chunk`` (sync two-stage)
|
||||
Input Modal: text + ref_audio + ref_text
|
||||
Output Modal: audio
|
||||
Input Setting: stream=False
|
||||
|
||||
Uses the official jiayan_zh.wav reference audio from the upstream
|
||||
GLM-TTS repository (real human speech matching REF_TEXT).
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": "今天天气真不错,适合出去散散步。",
|
||||
"stream": False,
|
||||
"response_format": "wav",
|
||||
"ref_audio": REF_AUDIO_URL,
|
||||
"ref_text": REF_TEXT,
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_async_chunk_server_params, indirect=True)
|
||||
def test_voice_clone_zh_async_chunk(omni_server, openai_client) -> None:
|
||||
"""
|
||||
Test voice cloning TTS with Chinese text via async_chunk streaming.
|
||||
Deploy Setting: glm_tts.yaml default ``async_chunk: true``
|
||||
Input Modal: text + ref_audio + ref_text
|
||||
Output Modal: audio
|
||||
Input Setting: stream=True
|
||||
"""
|
||||
request_config = {
|
||||
"model": omni_server.model,
|
||||
"input": "今天天气真不错,适合出去散散步。",
|
||||
"stream": True,
|
||||
"response_format": "wav",
|
||||
"ref_audio": REF_AUDIO_URL,
|
||||
"ref_text": REF_TEXT,
|
||||
}
|
||||
openai_client.send_audio_speech_request(request_config)
|
||||
|
||||
|
||||
@pytest.mark.advanced_model
|
||||
@pytest.mark.omni
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@pytest.mark.parametrize("omni_server", tts_sync_server_params, indirect=True)
|
||||
def test_models_endpoint(omni_server, openai_client) -> None:
|
||||
"""Test the /v1/models endpoint returns loaded model."""
|
||||
models = openai_client.client.models.list()
|
||||
assert len(models.data) > 0
|
||||
@@ -2335,6 +2335,84 @@ class TestCosyVoice3Serving:
|
||||
cosyvoice3_server._build_cosyvoice3_prompt.assert_awaited_once()
|
||||
|
||||
|
||||
# ---- GLM-TTS Serving Tests ----
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def glm_tts_server(mocker: MockerFixture):
|
||||
mocker.patch.object(OmniOpenAIServingSpeech, "_load_supported_speakers", return_value=set())
|
||||
mocker.patch.object(OmniOpenAIServingSpeech, "_load_codec_frame_rate", return_value=None)
|
||||
|
||||
mock_engine_client = mocker.MagicMock()
|
||||
mock_engine_client.errored = False
|
||||
mock_engine_client.model_config = mocker.MagicMock(
|
||||
model="zai-org/GLM-TTS",
|
||||
hf_config=SimpleNamespace(min_token_text_ratio=2, max_token_text_ratio=20),
|
||||
)
|
||||
mock_engine_client.default_sampling_params_list = [
|
||||
SimpleNamespace(max_tokens=2048, min_tokens=None, extra_args=None)
|
||||
]
|
||||
mock_engine_client.tts_batch_max_items = 32
|
||||
mock_engine_client.generate = mocker.MagicMock(return_value="generator")
|
||||
mock_engine_client.stage_configs = [
|
||||
SimpleNamespace(
|
||||
engine_args=SimpleNamespace(model_stage="glm_tts"),
|
||||
tts_args={},
|
||||
)
|
||||
]
|
||||
|
||||
mock_models = mocker.MagicMock()
|
||||
mock_models.is_base_model.return_value = True
|
||||
|
||||
return OmniOpenAIServingSpeech(
|
||||
engine_client=mock_engine_client,
|
||||
models=mock_models,
|
||||
request_logger=mocker.MagicMock(),
|
||||
)
|
||||
|
||||
|
||||
class TestGLMTTSServing:
|
||||
def test_validate_glm_tts_requires_ref_audio(self, glm_tts_server):
|
||||
request = OpenAICreateSpeechRequest(input="Hello", ref_text="Reference transcript")
|
||||
error = glm_tts_server._validate_glm_tts_request(request)
|
||||
assert error is not None
|
||||
assert "ref_audio" in error
|
||||
|
||||
def test_validate_glm_tts_requires_ref_text(self, glm_tts_server):
|
||||
request = OpenAICreateSpeechRequest(input="Hello", ref_audio="data:audio/wav;base64,abc")
|
||||
error = glm_tts_server._validate_glm_tts_request(request)
|
||||
assert error is not None
|
||||
assert "ref_text" in error
|
||||
|
||||
def test_estimate_glm_tts_target_text_len_uses_tokenizer_tokens(
|
||||
self,
|
||||
glm_tts_server,
|
||||
mocker: MockerFixture,
|
||||
):
|
||||
class FakeTokenizer:
|
||||
def encode(self, text):
|
||||
assert text == "normalized target"
|
||||
return [10, 20, 30]
|
||||
|
||||
mocker.patch(
|
||||
"vllm_omni.model_executor.models.glm_tts.glm_tts.resolve_glm_tts_tokenizer_path",
|
||||
return_value="resolved-tokenizer",
|
||||
)
|
||||
load_tokenizer = mocker.patch(
|
||||
"vllm_omni.model_executor.models.glm_tts.glm_tts.load_glm_tts_tokenizer",
|
||||
return_value=FakeTokenizer(),
|
||||
)
|
||||
mocker.patch(
|
||||
"vllm_omni.model_executor.models.glm_tts.text_frontend.GLMTTSTextFrontend.text_normalize",
|
||||
return_value="normalized target",
|
||||
)
|
||||
|
||||
text_token_len = glm_tts_server._estimate_glm_tts_text_token_len("abcdef")
|
||||
|
||||
assert text_token_len == 3
|
||||
load_tokenizer.assert_called_once()
|
||||
|
||||
|
||||
class TestTTSAsyncOffloading:
|
||||
"""Tests for event-loop-safe offloading of blocking TTS operations."""
|
||||
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.common.nucleus_ras_sampling import ras_sample_one
|
||||
from vllm_omni.model_executor.models.glm_tts import glm_tts as glm_tts_module
|
||||
from vllm_omni.model_executor.models.glm_tts.glm_tts import GLMTTSForConditionalGeneration
|
||||
from vllm_omni.model_executor.models.glm_tts.text_frontend import GLMTTSTextFrontend
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_glm_tts_ras_fallback_matches_official_random_resample() -> None:
|
||||
sampled = ras_sample_one(
|
||||
torch.tensor([0.0, float("-inf")]),
|
||||
decoded_tokens=[0] * 10,
|
||||
top_p=1.0,
|
||||
top_k=1,
|
||||
win_size=10,
|
||||
tau_r=0.1,
|
||||
generator=None,
|
||||
)
|
||||
|
||||
assert sampled == 0
|
||||
|
||||
|
||||
def test_glm_tts_text_frontend_applies_official_symbol_replacements() -> None:
|
||||
frontend = GLMTTSTextFrontend()
|
||||
|
||||
assert frontend.pre_replace("3-2 咯,") == "3减2 喽,"
|
||||
assert frontend.post_replace("α②∈A/B~C²") == "阿尔法二属于A每B到C平方"
|
||||
|
||||
|
||||
def test_glm_tts_call_hf_processor_builds_prompt_text_text_boa(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
processor = object.__new__(glm_tts_module.GLMTTSMultiModalProcessor)
|
||||
processor.info = SimpleNamespace(
|
||||
ctx=SimpleNamespace(
|
||||
get_hf_config=lambda *_args, **_kwargs: SimpleNamespace(),
|
||||
model_config=SimpleNamespace(model="fake-model"),
|
||||
)
|
||||
)
|
||||
processor.text_frontend = object()
|
||||
processor.special_ids = {"boa": 99}
|
||||
processor.speech_tokenizer = object()
|
||||
processor.processor_device = torch.device("cpu")
|
||||
processor.campplus_session = object()
|
||||
|
||||
monkeypatch.setattr(
|
||||
processor,
|
||||
"_ensure_cached_runtime_components",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
processor,
|
||||
"_encode_text",
|
||||
lambda text: torch.tensor([[11, 12]]) if text.endswith(" ") else torch.tensor([[21, 22, 23]]),
|
||||
)
|
||||
monkeypatch.setattr(processor, "_get_audio", lambda _mm_data: (torch.zeros(8), 24000))
|
||||
monkeypatch.setattr(
|
||||
glm_tts_module,
|
||||
"_normalize_glm_tts_processor_text",
|
||||
lambda _frontend, text, add_trailing_space=False: text + (" " if add_trailing_space else ""),
|
||||
)
|
||||
monkeypatch.setattr(glm_tts_module, "extract_prompt_speech_token", lambda *_args, **_kwargs: [7, 8, 9, 10])
|
||||
monkeypatch.setattr(glm_tts_module, "extract_prompt_feat", lambda *_args, **_kwargs: torch.ones(4, 3))
|
||||
monkeypatch.setattr(glm_tts_module, "extract_spk_embedding", lambda *_args, **_kwargs: [0.1, 0.2, 0.3])
|
||||
|
||||
out = processor._call_hf_processor(
|
||||
prompt="target text",
|
||||
mm_data={"audio": object()},
|
||||
mm_kwargs={"prompt_text": "reference text"},
|
||||
tok_kwargs={},
|
||||
)
|
||||
|
||||
assert out["input_ids"].tolist() == [[11, 12, 21, 22, 23, 99]]
|
||||
assert out["prompt_speech_token"].tolist() == [[7, 8, 9, 10]]
|
||||
assert out["prompt_speech_token_len"][0].item() == 4
|
||||
assert out["glm_tts_text_token_len"][0].item() == 3
|
||||
|
||||
|
||||
def test_glm_tts_prompt_updates_append_single_audio_suffix() -> None:
|
||||
processor = object.__new__(glm_tts_module.GLMTTSMultiModalProcessor)
|
||||
out_mm_kwargs = {
|
||||
"audio": [{"prompt_speech_token_len": SimpleNamespace(data=[torch.tensor([5], dtype=torch.long)])}]
|
||||
}
|
||||
|
||||
updates = processor._get_prompt_updates(
|
||||
mm_items=object(),
|
||||
hf_processor_mm_kwargs={},
|
||||
out_mm_kwargs=out_mm_kwargs,
|
||||
)
|
||||
|
||||
assert len(updates) == 1
|
||||
assert updates[0].modality == "audio"
|
||||
assert updates[0].insertion(0) == [1, 1, 1, 1, 1]
|
||||
|
||||
|
||||
def test_glm_tts_dummy_inputs_forbid_dummy_wav(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
builder = object.__new__(glm_tts_module.GLMTTSDummyInputsBuilder)
|
||||
monkeypatch.setattr(
|
||||
builder,
|
||||
"_get_dummy_audios",
|
||||
lambda *_args, **_kwargs: pytest.fail("GLM-TTS dummy inputs must not fabricate wav audio"),
|
||||
)
|
||||
|
||||
assert builder.get_dummy_mm_data(seq_len=16, mm_counts={"audio": 1}) == {}
|
||||
|
||||
|
||||
def test_glm_tts_processing_info_declares_audio_token_budget() -> None:
|
||||
info = object.__new__(glm_tts_module.GLMTTSMultiModalProcessingInfo)
|
||||
|
||||
assert info.get_mm_max_tokens_per_item(seq_len=4096, mm_counts={"audio": 1}) == {"audio": 1024}
|
||||
assert info.get_mm_max_tokens_per_item(seq_len=512, mm_counts={"audio": 1}) == {"audio": 512}
|
||||
assert info.get_mm_max_tokens_per_item(seq_len=4096, mm_counts={}) == {}
|
||||
|
||||
|
||||
def test_glm_tts_text_only_processor_skips_voice_clone(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
class FakeTokenizer:
|
||||
def encode(self, text: str) -> list[int]:
|
||||
return [11, 12, 13]
|
||||
|
||||
processor = object.__new__(glm_tts_module.GLMTTSMultiModalProcessor)
|
||||
processor.info = SimpleNamespace(
|
||||
ctx=SimpleNamespace(
|
||||
get_hf_config=lambda *_args, **_kwargs: SimpleNamespace(),
|
||||
model_config=SimpleNamespace(model="fake-model", tokenizer=None, trust_remote_code=True),
|
||||
)
|
||||
)
|
||||
|
||||
monkeypatch.setattr(glm_tts_module, "resolve_glm_tts_model_dir", lambda *_args, **_kwargs: "/fake-root")
|
||||
monkeypatch.setattr(glm_tts_module, "load_glm_tts_tokenizer", lambda *_args, **_kwargs: FakeTokenizer())
|
||||
monkeypatch.setattr(glm_tts_module, "get_glm_tts_special_token_ids", lambda _tokenizer: {"boa": 99})
|
||||
monkeypatch.setattr(glm_tts_module, "GLMTTSTextFrontend", lambda: object())
|
||||
monkeypatch.setattr(
|
||||
glm_tts_module,
|
||||
"_normalize_glm_tts_processor_text",
|
||||
lambda _frontend, text, add_trailing_space=False: text,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
glm_tts_module,
|
||||
"load_voice_clone_frontend",
|
||||
lambda *_args, **_kwargs: pytest.fail("text-only dummy path should not load voice clone frontend"),
|
||||
)
|
||||
|
||||
out = processor._call_hf_processor(prompt="target text", mm_data={}, mm_kwargs={}, tok_kwargs={})
|
||||
|
||||
assert out["input_ids"].tolist() == [[11, 12, 13, 99]]
|
||||
assert out["prompt_speech_token"].shape == (1, 1024)
|
||||
assert out["prompt_speech_token_len"][0].item() == 1024
|
||||
assert out["glm_tts_prompt_text_token_len"][0].item() == 0
|
||||
assert out["glm_tts_text_token_len"][0].item() == 3
|
||||
|
||||
fields = processor._get_mm_fields_config(out, {})
|
||||
assert {key: value.modality for key, value in fields.items()} == {
|
||||
"prompt_speech_token": "audio",
|
||||
"prompt_speech_token_len": "audio",
|
||||
"glm_tts_prompt_text_token_len": "audio",
|
||||
"glm_tts_text_token_len": "audio",
|
||||
}
|
||||
|
||||
updates = processor._get_prompt_updates(
|
||||
mm_items=object(),
|
||||
hf_processor_mm_kwargs={},
|
||||
out_mm_kwargs={
|
||||
"audio": [{"prompt_speech_token_len": SimpleNamespace(data=[out["prompt_speech_token_len"][0]])}]
|
||||
},
|
||||
)
|
||||
assert len(updates) == 1
|
||||
assert len(updates[0].insertion(0)) == 1024
|
||||
|
||||
|
||||
def test_glm_tts_embed_replaces_multimodal_positions_per_request() -> None:
|
||||
class FakeModel(torch.nn.Module):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.marker = torch.nn.Parameter(torch.zeros(()))
|
||||
|
||||
def embed_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return input_ids.to(torch.float32).reshape(-1, 1)
|
||||
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
torch.nn.Module.__init__(model)
|
||||
model.model_stage = "glm_tts"
|
||||
model.model = FakeModel()
|
||||
|
||||
input_ids = torch.tensor([101, 102, 1, 1, 201, 1, 1, 1])
|
||||
is_multimodal = torch.tensor([False, False, True, True, False, True, True, True])
|
||||
mm_embeds = [
|
||||
torch.tensor([[1001.0], [1002.0]]),
|
||||
torch.tensor([[2001.0], [2002.0], [2003.0]]),
|
||||
]
|
||||
|
||||
out = model.embed_input_ids(input_ids, multimodal_embeddings=mm_embeds, is_multimodal=is_multimodal)
|
||||
|
||||
assert out.squeeze(-1).tolist() == [
|
||||
101.0,
|
||||
102.0,
|
||||
1001.0,
|
||||
1002.0,
|
||||
201.0,
|
||||
2001.0,
|
||||
2002.0,
|
||||
2003.0,
|
||||
]
|
||||
|
||||
|
||||
def test_glm_tts_embed_multimodal_keeps_all_batched_requests() -> None:
|
||||
class FakeModel(torch.nn.Module):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.marker = torch.nn.Parameter(torch.zeros(()))
|
||||
|
||||
def embed_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return input_ids.to(torch.float32).reshape(*input_ids.shape, 1)
|
||||
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
torch.nn.Module.__init__(model)
|
||||
model.model_stage = "glm_tts"
|
||||
model.model = FakeModel()
|
||||
model._ats = 1000
|
||||
|
||||
out = model.embed_multimodal(
|
||||
prompt_speech_token=[
|
||||
torch.tensor([[1, 2]]),
|
||||
torch.tensor([[3, 4, 5]]),
|
||||
]
|
||||
)
|
||||
|
||||
assert out is not None
|
||||
assert len(out) == 2
|
||||
assert out[0].squeeze(-1).tolist() == [1001.0, 1002.0]
|
||||
assert out[1].squeeze(-1).tolist() == [1003.0, 1004.0, 1005.0]
|
||||
|
||||
|
||||
def test_glm_tts_embed_multimodal_returns_one_item_for_single_request() -> None:
|
||||
class FakeModel(torch.nn.Module):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.marker = torch.nn.Parameter(torch.zeros(()))
|
||||
|
||||
def embed_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return input_ids.to(torch.float32).reshape(*input_ids.shape, 1)
|
||||
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
torch.nn.Module.__init__(model)
|
||||
model.model_stage = "glm_tts"
|
||||
model.model = FakeModel()
|
||||
model._ats = 1000
|
||||
|
||||
out = model.embed_multimodal(prompt_speech_token=torch.tensor([[1, 2, 3]]))
|
||||
|
||||
assert out is not None
|
||||
assert len(out) == 1
|
||||
assert out[0].squeeze(-1).tolist() == [1001.0, 1002.0, 1003.0]
|
||||
|
||||
|
||||
def test_glm_tts_embed_multimodal_treats_scalar_tensor_list_as_one_item() -> None:
|
||||
class FakeModel(torch.nn.Module):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.marker = torch.nn.Parameter(torch.zeros(()))
|
||||
|
||||
def embed_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return input_ids.to(torch.float32).reshape(*input_ids.shape, 1)
|
||||
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
torch.nn.Module.__init__(model)
|
||||
model.model_stage = "glm_tts"
|
||||
model.model = FakeModel()
|
||||
model._ats = 1000
|
||||
|
||||
out = model.embed_multimodal(prompt_speech_token=[torch.tensor(1), torch.tensor(2)])
|
||||
|
||||
assert out is not None
|
||||
assert len(out) == 1
|
||||
assert out[0].squeeze(-1).tolist() == [1001.0, 1002.0]
|
||||
|
||||
|
||||
def test_glm_tts_preprocess_treats_one_token_text_tail_as_prefill() -> None:
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
model._pad = 0
|
||||
model._ats = 1000
|
||||
model._ate = 2000
|
||||
model._eoa = 3000
|
||||
model._model_dtype = lambda: torch.float32
|
||||
|
||||
input_ids, input_embeds, info = model.preprocess(
|
||||
torch.tensor([123]),
|
||||
torch.tensor([[1.0, 2.0]]),
|
||||
glm_tts_mm_prefill_done=True,
|
||||
)
|
||||
|
||||
assert input_ids.tolist() == [0]
|
||||
assert input_embeds.tolist() == [[1.0, 2.0]]
|
||||
assert info["glm_tts_mm_prefill_done"] is True
|
||||
assert info["speech_tokens"].tolist() == [[-1]]
|
||||
|
||||
|
||||
def test_glm_tts_preprocess_initializes_generation_bounds_before_sampling() -> None:
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
model._pad = 0
|
||||
model._ats = 1000
|
||||
model._ate = 2000
|
||||
model._eoa = 3000
|
||||
model._model_dtype = lambda: torch.float32
|
||||
model.config = SimpleNamespace(min_token_text_ratio=2.0, max_token_text_ratio=20.0)
|
||||
|
||||
_, _, info = model.preprocess(
|
||||
torch.tensor([11, 12]),
|
||||
torch.tensor([[1.0], [2.0]]),
|
||||
glm_tts_text_token_len=[torch.tensor([27])],
|
||||
)
|
||||
|
||||
assert info["glm_tts_text_token_len"][0].item() == 27
|
||||
|
||||
|
||||
def test_glm_tts_make_omni_output_emits_prompt_speech_len_once() -> None:
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
|
||||
out = model.make_omni_output(
|
||||
torch.randn(2, 4),
|
||||
model_intermediate_buffer=[{}],
|
||||
prompt_speech_token_len=[torch.tensor([9])],
|
||||
glm_tts_text_token_len=[torch.tensor([5])],
|
||||
)
|
||||
|
||||
assert out.multimodal_outputs is not None
|
||||
assert out.multimodal_outputs["prompt_speech_token_len"][0].item() == 9
|
||||
assert out.multimodal_outputs["glm_tts_text_token_len"][0].item() == 5
|
||||
|
||||
|
||||
def test_glm_tts_postprocess_caches_prompt_speech_token_len() -> None:
|
||||
model = object.__new__(GLMTTSForConditionalGeneration)
|
||||
model.config = SimpleNamespace(min_token_text_ratio=2.0, max_token_text_ratio=20.0)
|
||||
|
||||
update = model.postprocess(
|
||||
torch.randn(2, 4),
|
||||
multimodal_outputs={
|
||||
"prompt_speech_token_len": [torch.tensor([13])],
|
||||
"glm_tts_text_token_len": [torch.tensor([6])],
|
||||
},
|
||||
)
|
||||
|
||||
assert update["prompt_speech_token_len"].item() == 13
|
||||
assert update["glm_tts_text_token_len"].item() == 6
|
||||
@@ -0,0 +1,278 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.engine.serialization import serialize_additional_information
|
||||
from vllm_omni.model_executor.models.glm_tts.glm_tts_dit_wrapper import (
|
||||
split_request_ids,
|
||||
valid_speech_tokens,
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.glm_tts import (
|
||||
ar_to_dit,
|
||||
ar_to_dit_async_chunk,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _Request:
|
||||
external_req_id = "req-1"
|
||||
additional_information = None
|
||||
|
||||
def is_finished(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _transfer_manager() -> SimpleNamespace:
|
||||
connector = SimpleNamespace(
|
||||
config={
|
||||
"extra": {
|
||||
"codec_chunk_frames": 25,
|
||||
"codec_left_context_frames": 25,
|
||||
}
|
||||
}
|
||||
)
|
||||
return SimpleNamespace(connector=connector)
|
||||
|
||||
|
||||
def _progressive_transfer_manager() -> SimpleNamespace:
|
||||
connector = SimpleNamespace(
|
||||
config={
|
||||
"extra": {
|
||||
"codec_chunk_frames": [25, 50, 200],
|
||||
"codec_left_context_frames": 25,
|
||||
}
|
||||
}
|
||||
)
|
||||
return SimpleNamespace(connector=connector)
|
||||
|
||||
|
||||
def _source_output(mm: dict, request_id: str = "req-0") -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
request_id=request_id,
|
||||
outputs=[
|
||||
SimpleNamespace(
|
||||
multimodal_output=mm,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _audio_codes(payload) -> list[int]:
|
||||
assert payload.codes is not None
|
||||
assert payload.codes.audio is not None
|
||||
return payload.codes.audio.tolist()
|
||||
|
||||
|
||||
def test_ar_to_dit_filters_invalid_tokens_and_preserves_conditioning() -> None:
|
||||
prompt_token = torch.tensor([[1, 2, 3]])
|
||||
prompt_feat = torch.randn(1, 4, 80)
|
||||
embedding = torch.randn(1, 192)
|
||||
source_outputs = [
|
||||
_source_output(
|
||||
{
|
||||
"speech_tokens": torch.tensor([[-1, 0, 7, -1, 32767]]),
|
||||
"prompt_token": prompt_token,
|
||||
"prompt_feat": prompt_feat,
|
||||
"embedding": embedding,
|
||||
}
|
||||
)
|
||||
]
|
||||
|
||||
outputs = ar_to_dit(source_outputs)
|
||||
|
||||
assert len(outputs) == 1
|
||||
assert outputs[0]["prompt_token_ids"] == [0, 7, 32767]
|
||||
additional_info = outputs[0]["additional_information"]
|
||||
assert additional_info["speech_tokens"] == [0, 7, 32767]
|
||||
# Voice clone data stored in nested embed dict (matches async_chunk path)
|
||||
embed = additional_info["embed"]
|
||||
assert embed["speech_token"] is prompt_token
|
||||
assert embed["speech_feat"] is prompt_feat
|
||||
assert embed["embedding"] is embedding
|
||||
# Meta dict enables block-causal attention in DiT wrapper
|
||||
meta = additional_info["meta"]
|
||||
assert meta["req_id"] == ["req-0"]
|
||||
assert meta["left_context_size"] == 0
|
||||
assert meta["stream_finished"] is True
|
||||
private = additional_info["kv_metadata"]["glm_tts"]
|
||||
assert private["block_pattern"] == [3] # len([0, 7, 32767])
|
||||
assert private["chunk_sizes_history"] == [3]
|
||||
|
||||
|
||||
def test_dit_explicit_empty_speech_tokens_override_scheduler_placeholder() -> None:
|
||||
placeholder = torch.tensor([0], dtype=torch.long)
|
||||
|
||||
token = valid_speech_tokens([], device=placeholder.device, fallback=placeholder)
|
||||
|
||||
assert token.numel() == 0
|
||||
|
||||
|
||||
def test_ar_to_dit_async_chunk_restores_serialized_conditioning_payload() -> None:
|
||||
transfer = _transfer_manager()
|
||||
request = _Request()
|
||||
prompt_token = torch.tensor([[1, 2, 3]])
|
||||
prompt_feat = torch.randn(1, 4, 80)
|
||||
embedding = torch.randn(1, 192)
|
||||
request.additional_information = serialize_additional_information(
|
||||
{
|
||||
"prompt_speech_token": prompt_token,
|
||||
"prompt_feat": prompt_feat,
|
||||
"embedding": embedding,
|
||||
}
|
||||
)
|
||||
|
||||
payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
{"speech_tokens": torch.tensor([[0]])},
|
||||
request,
|
||||
is_finished=False,
|
||||
)
|
||||
|
||||
assert payload is None
|
||||
state = transfer.request_payload["req-1"]["_glm_tts_async_state"]
|
||||
prompt_payload = state["prompt_payload"]
|
||||
assert torch.equal(prompt_payload["prompt_speech_token"], prompt_token)
|
||||
assert torch.equal(prompt_payload["prompt_feat"], prompt_feat)
|
||||
assert torch.equal(prompt_payload["embedding"], embedding)
|
||||
|
||||
|
||||
def test_split_request_ids_uses_seq_token_counts() -> None:
|
||||
ids = torch.tensor([1, 2, 3, 4, 5, 6], dtype=torch.long)
|
||||
|
||||
split = split_request_ids(ids, seq_token_counts=[2, 3, 1])
|
||||
|
||||
assert [part.tolist() for part in split] == [[1, 2], [3, 4, 5], [6]]
|
||||
|
||||
|
||||
def test_ar_to_dit_async_chunk_emits_cumulative_prefixes() -> None:
|
||||
transfer = _transfer_manager()
|
||||
request = _Request()
|
||||
payloads = []
|
||||
|
||||
for token in range(75):
|
||||
payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
{"speech_tokens": torch.tensor([[token]])},
|
||||
request,
|
||||
is_finished=False,
|
||||
)
|
||||
if payload is not None:
|
||||
payloads.append(payload)
|
||||
|
||||
assert len(payloads) == 3
|
||||
assert _audio_codes(payloads[0]) == list(range(25))
|
||||
assert payloads[0].meta.left_context_size == 0
|
||||
assert payloads[0].kv_metadata["glm_tts"]["block_pattern"] == [25]
|
||||
assert _audio_codes(payloads[1]) == list(range(50))
|
||||
assert payloads[1].meta.left_context_size == 25
|
||||
assert payloads[1].kv_metadata["glm_tts"]["block_pattern"] == [25]
|
||||
assert _audio_codes(payloads[2]) == list(range(75))
|
||||
assert payloads[2].meta.left_context_size == 50
|
||||
assert payloads[2].kv_metadata["glm_tts"]["block_pattern"] == [25]
|
||||
|
||||
|
||||
def test_ar_to_dit_async_chunk_keeps_progressive_block_pattern_fixed() -> None:
|
||||
transfer = _progressive_transfer_manager()
|
||||
request = _Request()
|
||||
payloads = []
|
||||
|
||||
for token in range(30):
|
||||
payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
{"speech_tokens": torch.tensor([[token]])},
|
||||
request,
|
||||
is_finished=False,
|
||||
)
|
||||
if payload is not None:
|
||||
payloads.append(payload)
|
||||
|
||||
final_payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
None,
|
||||
request,
|
||||
is_finished=True,
|
||||
)
|
||||
|
||||
assert len(payloads) == 1
|
||||
assert payloads[0].kv_metadata["glm_tts"]["chunk_sizes_history"] == [25]
|
||||
assert payloads[0].kv_metadata["glm_tts"]["block_pattern"] == [25, 50, 200]
|
||||
assert final_payload is not None
|
||||
assert final_payload.kv_metadata["glm_tts"]["chunk_sizes_history"] == [25, 5]
|
||||
assert final_payload.kv_metadata["glm_tts"]["block_pattern"] == [25, 50, 200]
|
||||
|
||||
|
||||
def test_ar_to_dit_async_chunk_terminal_boundary_is_metadata_only() -> None:
|
||||
transfer = _transfer_manager()
|
||||
request = _Request()
|
||||
payloads = []
|
||||
|
||||
for token in range(50):
|
||||
payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
{"speech_tokens": torch.tensor([[token]])},
|
||||
request,
|
||||
is_finished=False,
|
||||
)
|
||||
if payload is not None:
|
||||
payloads.append(payload)
|
||||
|
||||
final_payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
None,
|
||||
request,
|
||||
is_finished=True,
|
||||
)
|
||||
|
||||
assert len(payloads) == 2
|
||||
assert final_payload is not None
|
||||
assert _audio_codes(final_payload) == []
|
||||
assert final_payload.meta.left_context_size == 50
|
||||
assert final_payload.meta.req_id == ["req-1"]
|
||||
assert bool(final_payload.meta.stream_finished.item())
|
||||
|
||||
|
||||
def test_ar_to_dit_async_chunk_finished_flushes_partial_unsent_tail() -> None:
|
||||
transfer = _transfer_manager()
|
||||
request = _Request()
|
||||
payloads = []
|
||||
|
||||
for token in range(30):
|
||||
payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
{"speech_tokens": torch.tensor([[token]])},
|
||||
request,
|
||||
is_finished=False,
|
||||
)
|
||||
if payload is not None:
|
||||
payloads.append(payload)
|
||||
|
||||
final_payload = ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
None,
|
||||
request,
|
||||
is_finished=True,
|
||||
)
|
||||
|
||||
assert len(payloads) == 1
|
||||
assert _audio_codes(payloads[0]) == list(range(25))
|
||||
assert payloads[0].meta.left_context_size == 0
|
||||
assert final_payload is not None
|
||||
assert _audio_codes(final_payload) == list(range(30))
|
||||
assert final_payload.meta.left_context_size == 25
|
||||
assert final_payload.meta.req_id == ["req-1"]
|
||||
assert bool(final_payload.meta.finished.item())
|
||||
assert bool(final_payload.meta.stream_finished.item())
|
||||
assert (
|
||||
ar_to_dit_async_chunk(
|
||||
transfer,
|
||||
None,
|
||||
request,
|
||||
is_finished=True,
|
||||
)
|
||||
is None
|
||||
)
|
||||
Reference in new issue
Block a user