[Model] Add single-stage Qwen3-TTS with in-Talker streaming codec decode (#8259)

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 authored and GitHub committed 2026-10-02 21:34:30 +10:00
1 parent 596487fe62
commit e84014dffb
43 files changed
+3565 -90

No files matched your search

+158
View File
@@ -35,3 +35,161 @@ def test_recursive_deploy_inheritance(tmp_path):
merged = resolve_deploy_yaml(leaf)
assert merged["speech_cache"] == {"nested": {"a": 1, "b": 0}}
assert merged["async_chunk"] is False
def test_single_stage_streaming_capability_uses_central_async_resolver():
from vllm_omni.config.stage_config import DeployConfig, _resolve_pipeline_async_chunk_enabled
from vllm_omni.model_executor.models.qwen3_tts.pipeline import QWEN3_TTS_FUSED_PIPELINE
assert _resolve_pipeline_async_chunk_enabled(QWEN3_TTS_FUSED_PIPELINE, DeployConfig())
with pytest.raises(ValueError, match="requires async_chunk=True"):
_resolve_pipeline_async_chunk_enabled(QWEN3_TTS_FUSED_PIPELINE, DeployConfig(async_chunk=False))
@pytest.mark.parametrize(
"pipeline_key,profile,stage_count",
[
("qwen3_tts", "qwen3_tts_high_concurrency_mrv2_single_gpu.yaml", 2),
("qwen3_tts_fused", "qwen3_tts_fused_single_gpu.yaml", 1),
],
)
def test_qwen3_tts_deployment_selection_preserves_output_and_transport_contract(pipeline_key, profile, stage_count):
from tests.helpers.stage_config import get_deploy_config_path
from vllm_omni.config.pipeline_registry import resolve_pipeline_config
from vllm_omni.config.stage_config import load_deploy_config, merge_pipeline_deploy
pipeline = resolve_pipeline_config(pipeline_key)
assert pipeline is not None
deploy = load_deploy_config(get_deploy_config_path(profile))
stages = merge_pipeline_deploy(pipeline, deploy)
assert len(stages) == stage_count
talker = stages[0]
if stage_count == 1:
assert talker.final_output and talker.final_output_type == "audio"
assert talker.yaml_engine_args["engine_output_type"] == "audio"
assert "custom_process_next_stage_input_func" not in talker.yaml_engine_args
assert not talker.yaml_extras.get("output_connectors")
assert talker.yaml_engine_args["supports_running_prefix_cache_reset"] is False
assert talker.yaml_engine_args["additional_config"]["ref_code_context_frames"] == 72
else:
assert not talker.final_output
assert talker.yaml_engine_args["engine_output_type"] == "latent"
assert talker.yaml_engine_args["custom_process_next_stage_input_func"].endswith("talker2code2wav_async_chunk")
assert talker.yaml_extras["output_connectors"]
assert stages[1].input_sources == [0] and stages[1].final_output_type == "audio"
assert talker.yaml_engine_args.get("supports_running_prefix_cache_reset", True)
def test_single_stage_running_reset_capability_cannot_be_overridden():
from vllm_omni.config.omni_config import VllmOmniConfig
from vllm_omni.config.stage_config import DeployConfig, StageDeployConfig, merge_pipeline_deploy
from vllm_omni.model_executor.models.qwen3_tts.pipeline import QWEN3_TTS_FUSED_PIPELINE
deploy = DeployConfig(
stages=[StageDeployConfig(stage_id=0, engine_extras={"supports_running_prefix_cache_reset": True})]
)
legacy = merge_pipeline_deploy(QWEN3_TTS_FUSED_PIPELINE, deploy)[0]
legacy.runtime_overrides["supports_running_prefix_cache_reset"] = True
assert legacy.to_omegaconf().engine_args.supports_running_prefix_cache_reset is False
with pytest.raises(ValueError, match="no structured config owner: supports_running_prefix_cache_reset"):
VllmOmniConfig.from_pipeline_config(QWEN3_TTS_FUSED_PIPELINE, user_deploy_config=deploy)
structured = VllmOmniConfig.from_pipeline_config(QWEN3_TTS_FUSED_PIPELINE)
assert structured.stage_by_id(0).model_config.supports_running_prefix_cache_reset is False
@pytest.fixture
def single_stage_tts_config(mocker):
from vllm.config import VllmConfig
config = mocker.Mock(spec=VllmConfig)
config.additional_config = {"talker_stream_decode": True}
config.model_config = mocker.Mock(
stage_connector_config={},
engine_output_type="audio",
final_output=True,
supports_running_prefix_cache_reset=False,
use_v2_model_runner=True,
async_chunk=True,
)
config.parallel_config = mocker.Mock(
tensor_parallel_size=1, pipeline_parallel_size=1, distributed_executor_backend="uni"
)
config.cache_config = mocker.Mock(enable_prefix_caching=False)
config.device_config = mocker.Mock(device="cuda")
mocker.patch(
"vllm_omni.model_executor.models.qwen3_tts.stream_decode.current_omni_platform.is_cuda", return_value=True
)
return config
def test_single_stage_tts_rejects_unsupported_decoder_configuration(single_stage_tts_config):
from vllm_omni.model_executor.models.qwen3_tts.stream_decode import talker_stream_decode_enabled
config = single_stage_tts_config
config.cache_config.enable_prefix_caching = True
with pytest.raises(ValueError, match="enable_prefix_caching=False"):
talker_stream_decode_enabled(config)
config.cache_config.enable_prefix_caching = False
assert talker_stream_decode_enabled(config)
@pytest.mark.parametrize("option_location", ["additional_config", "connector"])
@pytest.mark.parametrize("output_type", ["latent", "audio"])
def test_two_stage_talker_rejects_single_stage_pcm_option(single_stage_tts_config, option_location, output_type):
from vllm_omni.model_executor.models.qwen3_tts.stream_decode import talker_stream_decode_enabled
config = single_stage_tts_config
config.model_config.engine_output_type = output_type
config.model_config.final_output = False
if option_location == "connector":
config.model_config.stage_connector_config = {"extra": config.additional_config}
config.additional_config = {}
with pytest.raises(ValueError, match="final audio-output Talker"):
talker_stream_decode_enabled(config)
def test_two_stage_first_audio_remains_independent(single_stage_tts_config):
from vllm_omni.model_executor.models.qwen3_tts.first_audio import talker_first_audio_enabled
from vllm_omni.model_executor.models.qwen3_tts.stream_decode import talker_stream_decode_enabled
config = single_stage_tts_config
config.model_config.engine_output_type = "latent"
config.additional_config = {}
config.model_config.stage_connector_config = {"extra": {"talker_first_audio": True}}
assert not talker_stream_decode_enabled(config)
assert talker_first_audio_enabled(config)
config.model_config.stage_connector_config["extra"]["talker_stream_first_audio"] = True
with pytest.raises(ValueError, match="requires the single-stage"):
talker_stream_decode_enabled(config)
def test_single_stage_pcm_requires_cuda_device_and_own_first_audio_option(single_stage_tts_config):
from vllm_omni.model_executor.models.qwen3_tts.stream_decode import talker_stream_decode_enabled
config = single_stage_tts_config
config.device_config.device = "cpu"
with pytest.raises(ValueError, match="requires CUDA"):
talker_stream_decode_enabled(config)
config.device_config.device = "cuda"
config.additional_config["talker_first_audio"] = True
with pytest.raises(ValueError, match="mutually exclusive"):
talker_stream_decode_enabled(config)
config.additional_config.pop("talker_first_audio")
config.additional_config["talker_stream_first_audio"] = True
assert talker_stream_decode_enabled(config)
def test_single_stage_audio_talker_requires_pcm_option(single_stage_tts_config):
from vllm_omni.model_executor.models.qwen3_tts.stream_decode import talker_stream_decode_enabled
single_stage_tts_config.additional_config = {}
with pytest.raises(ValueError, match="requires talker_stream_decode=True"):
talker_stream_decode_enabled(single_stage_tts_config)
def test_single_stage_pcm_requires_reset_capability_declaration(single_stage_tts_config):
from vllm_omni.model_executor.models.qwen3_tts.stream_decode import talker_stream_decode_enabled
single_stage_tts_config.model_config.supports_running_prefix_cache_reset = True
with pytest.raises(ValueError, match="must disable running prefix-cache reset"):
talker_stream_decode_enabled(single_stage_tts_config)
+1
View File
@@ -1046,6 +1046,7 @@ def test_sub_config_fields_match_structured_scopes():
"interleave_mm_strings",
"media_io_kwargs",
"final_output",
"supports_running_prefix_cache_reset",
"active_stream_window",
"session_mode",
"duplex_max_sessions",
@@ -106,7 +106,7 @@ def _make_drain_sched(session: Request) -> MagicMock:
return sched
def _run_step(sched: MagicMock, session: Request, *, num_scheduled: int, token: int) -> bool:
def _run_step(sched: MagicMock, session: Request, *, num_scheduled: int, token: int, spec=None) -> bool:
"""Feed one model-runner frame through update_from_output.
Returns True when the frame's tokens were delivered (the append ran),
@@ -114,7 +114,7 @@ def _run_step(sched: MagicMock, session: Request, *, num_scheduled: int, token:
"""
scheduler_output = MagicMock(spec=SchedulerOutput)
scheduler_output.num_scheduled_tokens = {session.request_id: num_scheduled}
scheduler_output.scheduled_spec_decode_tokens = {}
scheduler_output.scheduled_spec_decode_tokens = {session.request_id: spec} if spec else {}
scheduler_output.num_invalid_spec_tokens = 0
model_runner_output = MagicMock(spec=ModelRunnerOutput)
@@ -134,6 +134,27 @@ def _run_step(sched: MagicMock, session: Request, *, num_scheduled: int, token:
return sched._update_request_with_output.called
def test_connector_prompt_replacement_drops_old_frame_and_delivers_new_frame() -> None:
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
session = _make_session()
session.num_computed_tokens = 6
session.num_in_flight_tokens = 1
session.num_output_placeholders = 1
sched = _make_drain_sched(session)
sched.chunk_transfer_adapter.replaced_streaming_prompt_ids = {session.request_id}
sched.chunk_transfer_adapter.requests_with_ready_chunks = {session.request_id}
sched.chunk_transfer_adapter.requests_num_chunks_sent = {session.external_req_id: 2}
OmniSchedulerMixin._reset_ready_async_chunk_replacements(sched)
assert session.num_stale_output_tokens == 1 and session.drop_stale_output
assert session.num_output_placeholders == 0
sched._release_replaced_streaming_prompt_cache.assert_called_once_with(session)
assert _run_step(sched, session, num_scheduled=1, token=42) is False
assert session.num_stale_output_tokens == 0
assert _run_step(sched, session, num_scheduled=1, token=43) is True
def test_exact_drain_delivers_new_segment_frame() -> None:
"""One in-flight decode frame at replacement: its late output drains the
counter exactly and the new segment's first frame is delivered."""
@@ -225,3 +246,80 @@ def test_in_flight_prefill_chunk_drains_exactly_without_underflow() -> None:
assert _run_step(sched, session, num_scheduled=5, token=42) is False # late prefill chunk dropped
assert session.num_stale_output_tokens == 0
assert _run_step(sched, session, num_scheduled=1, token=43) is True # new segment survives
@pytest.mark.parametrize("drop", [False, True])
def test_preemption_stale_output_follows_upstream_delivery_policy(drop):
request = _make_session()
request.status = RequestStatus.PREEMPTED
request.num_stale_output_tokens = 1
request.num_in_flight_tokens = 1
request.drop_stale_output = drop
sched = _make_drain_sched(request)
assert _run_step(sched, request, num_scheduled=1, token=42) is (not drop)
assert request.num_stale_output_tokens == 0
if not drop:
sched._update_request_with_output.assert_called_once_with(request, [42], is_stale=True)
def test_preemption_stale_spec_rejection_does_not_roll_back_resumed_counters():
request = _make_session()
request.num_stale_output_tokens = 2
request.num_in_flight_tokens = 2
request.num_computed_tokens = 3
request.num_output_placeholders = 2
request.drop_stale_output = False
sched = _make_drain_sched(request)
assert _run_step(sched, request, num_scheduled=2, token=42, spec=[41])
assert request.num_computed_tokens == 3
assert request.num_output_placeholders == 2
@pytest.mark.parametrize(
"arch,supports_reset,running,reset_running,blocked",
[
("Qwen3TTSTalkerForConditionalGeneration", False, True, True, True),
("Qwen3TTSTalkerForConditionalGeneration", False, False, True, False),
("Qwen3TTSTalkerForConditionalGeneration", False, True, False, False),
("Qwen3TTSTalkerForConditionalGeneration", True, True, True, False),
("AnotherStatefulAudioModel", False, True, True, True),
("AnotherStatefulAudioModel", True, True, True, False),
],
)
def test_reset_running_streaming_codec_is_rejected_before_preemption(
mocker, arch, supports_reset, running, reset_running, blocked
):
from vllm.config import VllmConfig
from vllm.v1.core.sched.scheduler import Scheduler
from vllm_omni.config.model import OmniModelConfig
scheduler = OmniARScheduler.__new__(OmniARScheduler)
scheduler.vllm_config = mocker.Mock(
spec=VllmConfig,
model_config=mocker.Mock(
spec=OmniModelConfig,
model_arch=arch,
supports_running_prefix_cache_reset=supports_reset,
),
)
request = _make_session()
request.num_in_flight_tokens = 1
request.num_output_placeholders = 1
scheduler.running = [request] if running else []
def reset_cache(_self, reset_running_requests=False, reset_connector=False):
assert reset_running_requests is reset_running and reset_connector is True
return True
reset = mocker.patch.object(Scheduler, "reset_prefix_cache", autospec=True, side_effect=reset_cache)
assert scheduler.reset_prefix_cache(reset_running, reset_connector=True) is (not blocked)
if blocked:
reset.assert_not_called()
assert scheduler.running == [request]
assert request.status == RequestStatus.RUNNING
assert request.num_in_flight_tokens == request.num_output_placeholders == 1
assert not request.drop_stale_output
else:
reset.assert_called_once()
+55 -4
View File
@@ -114,10 +114,10 @@ def _raw(*, first=False, required=False, terminal=False, samples=(1, 1, 1, 1)):
)
async def _codec_output(obj, raw):
replica = obj.stage_pools[1].replica_id
processed = await obj._process_llm_stage_outputs(1, replica, raw, set())
await obj._handle_processed_outputs(1, replica, processed)
async def _codec_output(obj, raw, stage=1):
replica = obj.stage_pools[stage].replica_id
processed = await obj._process_llm_stage_outputs(stage, replica, raw, set())
await obj._handle_processed_outputs(stage, replica, processed)
def _messages(obj):
@@ -132,6 +132,57 @@ def _audio(output):
return torch.cat(audio) if isinstance(audio, list) else audio
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", list(RequestOutputKind))
@pytest.mark.parametrize("suffix_overtook", [False, True])
async def test_single_stage_first_audio_obeys_output_kind_and_terminal_order(kind, suffix_overtook):
obj = _orchestrator(kind, final_stage_id=0)
obj.stage_pools = [obj.stage_pools[1]]
suffix = _raw(required=True, samples=(20, 21))
terminal = _raw(required=True, terminal=True, samples=(30, 31))
if suffix_overtook:
await _codec_output(obj, suffix, stage=0)
await _codec_output(obj, terminal, stage=0)
assert obj.output_async_queue.empty()
await obj._route_upstream_first_audio(0, 2, _raw(first=True, samples=(10, 11)))
if not suffix_overtook:
await _codec_output(obj, suffix, stage=0)
await _codec_output(obj, terminal, stage=0)
messages = _messages(obj)
expected = {
RequestOutputKind.DELTA: [[10, 11], [20, 21], [30, 31]],
RequestOutputKind.CUMULATIVE: [[10, 11], [10, 11, 20, 21], [10, 11, 20, 21, 30, 31]],
RequestOutputKind.FINAL_ONLY: [[10, 11, 20, 21, 30, 31]],
}
assert [_audio(message.engine_outputs).tolist() for message in messages] == expected[kind]
assert all((message.stage_id, message.replica_id) == (0, 2) for message in messages)
assert messages[-1].finished
assert not obj.request_states["r"].pending_first_audio_outputs
@pytest.mark.asyncio
async def test_single_stage_cancellation_discards_overtaking_terminal_and_late_first_audio():
obj = _orchestrator(final_stage_id=0)
obj.stage_pools = [obj.stage_pools[1]]
await _codec_output(obj, _raw(required=True, terminal=True), stage=0)
assert obj.request_states["r"].pending_first_audio_outputs
await obj._cleanup_request_ids(["r"], abort=True)
await obj._route_upstream_first_audio(0, 2, _raw(first=True))
assert not obj.request_states and obj.output_async_queue.empty()
@pytest.mark.asyncio
async def test_single_stage_first_audio_processing_failure_releases_waiting_terminal():
obj = _orchestrator(final_stage_id=0)
obj.stage_pools = [obj.stage_pools[1]]
await _codec_output(obj, _raw(required=True, terminal=True), stage=0)
obj.stage_pools[0].process_llm_raw_outputs = AsyncMock(side_effect=RuntimeError("processing failed"))
await obj._route_upstream_first_audio(0, 2, _raw(first=True))
error = obj.output_async_queue.get_nowait()
assert isinstance(error, ErrorMessage) and error.stage_id == 0
assert not obj.request_states
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", list(RequestOutputKind))
@pytest.mark.parametrize("codec_overtook", [False, True])
+29 -1
View File
@@ -1,9 +1,37 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from vllm.v1.engine.core import EngineCoreProc
from vllm.v1.executor.uniproc_executor import UniProcExecutor
from vllm_omni.engine.stage_engine_core_proc import StageEngineCoreProc
from vllm_omni.engine.stage_engine_core_proc import StageEngineCoreProc, _bind_first_audio_sink
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.mark.parametrize(
"first_decoder,stream_decoder,stream_first_audio,expected",
[(True, False, False, True), (False, True, False, False), (False, True, True, True), (False, False, True, False)],
)
def test_first_audio_sink_preserves_first_decoder_and_opts_in_stream_decoder(
mocker,
first_decoder,
stream_decoder,
stream_first_audio,
expected,
):
executor = UniProcExecutor.__new__(UniProcExecutor)
executor.driver_worker = mocker.Mock()
runner = executor.driver_worker.worker.model_runner
runner.model.first_frame_decoder = object() if first_decoder else None
runner.model.stream_decoder = object() if stream_decoder else None
runner.model.stream_first_audio = stream_first_audio
assert _bind_first_audio_sink(executor, mocker.Mock(), mocker.Mock()) is expected
assert runner.model_state.set_first_audio_sink.call_count == int(expected)
def test_preprocess_add_request_preserves_omni_fields():
@@ -346,3 +346,19 @@ def test_chat_audio_metadata_survives_response_serialization(stream, fmt):
assert audio_file.samplerate == 22050
else:
assert len(raw) == frame_count * 2
def test_float32_pcm_fast_path_matches_soundfile():
from vllm_omni.entrypoints.openai.audio_utils_mixin import _float32_to_pcm16_bytes
rng = np.random.default_rng(0)
audio = np.concatenate(
[
rng.uniform(-1.2, 1.2, 4096),
np.array([-1.0, 1.0, 0.0, -0.0, 32767 / 32768, -1 / 32768, 0.5 / 32768, -0.5 / 32768]),
]
).astype(np.float32)
with BytesIO() as buffer:
soundfile.write(buffer, audio, 24000, format="RAW", subtype="PCM_16")
expected = buffer.getvalue()
assert _float32_to_pcm16_bytes(audio) == expected
@@ -569,6 +569,27 @@ class TestCodePredictorPerRowGenerators:
)
@pytest.mark.parametrize("fused_requested", [False, True])
@pytest.mark.parametrize("invalid_input", ["uniforms", "generators"])
def test_sampling_contract_rejected_before_dispatch(mocker, loaded_target_classes, fused_requested, invalid_input):
predictor, talker_config = TestCodePredictorPerRowGenerators()._make_predictor(mocker, loaded_target_classes)
predictor._fused_requested = fused_requested
predictor._fused = mocker.Mock()
setup = mocker.patch.object(predictor, "_setup_compile")
uniforms = torch.full((2, 3, 1 if invalid_input == "uniforms" else 64), 0.5)
generators = [torch.Generator()] if invalid_input == "generators" else None
with pytest.raises(ValueError, match="sample_uniforms must have shape|one entry per row"):
predictor(
torch.zeros(2, dtype=torch.long),
torch.randn(2, talker_config.hidden_size),
torch.randn(2, talker_config.hidden_size),
sample_uniforms=uniforms,
generators=generators,
)
setup.assert_not_called()
predictor._fused.assert_not_called()
class TestCodePredictorModelDtype:
"""Test the inner model forward with different dtypes."""
@@ -663,6 +684,8 @@ class TestCodePredictorGraphReplay:
predictor = object.__new__(code_predictor_wrapper)
torch.nn.Module.__init__(predictor)
predictor._fused_requested = False
predictor._fused = None
predictor._num_groups = 3
predictor._model_dtype = torch.float32
predictor._setup_compile = mocker.Mock()
@@ -2,6 +2,8 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Supplied-uniform samples must match the existing ATen path exactly."""
from types import SimpleNamespace
import pytest
import torch
@@ -12,6 +14,79 @@ pytestmark = [
]
@pytest.mark.parametrize("top_k", [0, 1, 50, 2048])
@torch.inference_mode()
def test_fused_sample_kernel_preserves_signed_zero_cutoff_ties(top_k):
from vllm_omni.model_executor.models.qwen3_tts.fused_code_predictor import _cp_sample_kernel
vocab, hidden, groups = 2048, 64, 4
logits = torch.zeros(2, vocab, device="cuda", dtype=torch.bfloat16)
logits[0, 1] = -0.0
logits[1, ::2] = -0.0
uniforms = torch.full((2, groups - 1, vocab), 0.01, device="cuda")[:, 1, :]
uniforms[0, 1] = uniforms[1, 2] = 0.99
codes = torch.full((2, groups), -1, device="cuda", dtype=torch.int64)
table = torch.randn(vocab, hidden, device="cuda", dtype=torch.bfloat16)
next_input = torch.empty(2, hidden, device="cuda", dtype=table.dtype)
def sample():
_cp_sample_kernel[(2,)](
logits, uniforms, uniforms.stride(0), codes, 1, groups, table, next_input, 1.0,
V=vocab, TOPK=top_k, HID=hidden, HAS_NEXT=True, num_warps=4,
) # fmt: skip
scaled = logits.float()
if top_k > 0:
scaled = scaled.masked_fill(scaled < scaled.topk(top_k).values[:, -1:], -torch.inf)
expected = (scaled - torch.log(-torch.log(uniforms))).argmax(-1)
assert expected.tolist() == [1, 2]
sample()
torch.testing.assert_close(codes[:, 1], expected)
torch.testing.assert_close(next_input, table[expected])
assert (codes[:, [0, 2, 3]] == -1).all()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
sample()
codes.fill_(-1)
graph.replay()
torch.testing.assert_close(codes[:, 1], expected)
torch.testing.assert_close(next_input, table[expected])
@torch.inference_mode()
def test_fused_predictor_warmup_with_capacity_one():
from vllm_omni.model_executor.models.qwen3_tts.configuration_qwen3_tts import (
Qwen3TTSTalkerCodePredictorConfig,
Qwen3TTSTalkerConfig,
)
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_code_predictor_vllm import (
Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM,
)
cp = Qwen3TTSTalkerCodePredictorConfig(
vocab_size=64, hidden_size=64, intermediate_size=128, num_hidden_layers=1,
num_attention_heads=4, num_key_value_heads=2, head_dim=16, num_code_groups=4,
) # fmt: skip
talker = Qwen3TTSTalkerConfig(hidden_size=64, num_code_groups=4)
config = SimpleNamespace(
model_config=SimpleNamespace(stage_connector_config={}),
additional_config={"code_predictor_kv_cache": True, "code_predictor_fused": True},
scheduler_config=SimpleNamespace(max_num_seqs=1),
)
predictor = Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM(
vllm_config=config, config=cp, talker_config=talker
).to(device="cuda", dtype=torch.bfloat16)
predictor._setup_compile()
assert predictor._fused is not None
hidden = torch.randn(1, 1, 64, device="cuda", dtype=torch.bfloat16)
result = predictor(
torch.zeros(1, 1, device="cuda", dtype=torch.long), hidden, hidden,
sample_uniforms=torch.full((1, 3, 64), 0.5, device="cuda"),
) # fmt: skip
assert result.shape == (1, 4)
assert ((result >= 0) & (result < 64)).all()
@pytest.mark.parametrize("batch", [1, 64])
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32])
@pytest.mark.parametrize("top_k", [-1, 1, 50, 2048])
@@ -66,3 +141,47 @@ def test_topk_gumbel_accepts_strided_supplied_uniforms(top_k):
expected = (scaled.float() - torch.log(-torch.log(uniforms))).argmax(-1, keepdim=True)
actual = sample_code_topk_gumbel(logits, uniforms, top_k, 1 / 0.9)
torch.testing.assert_close(actual, expected)
@pytest.mark.parametrize("batch", [1, 4])
@pytest.mark.parametrize("top_k", [1, 50])
@torch.inference_mode()
def test_fused_predictor_matches_full_reference_with_fixed_uniforms(mocker, batch, top_k):
from vllm.config import VllmConfig
from vllm_omni.model_executor.models.qwen3_tts.configuration_qwen3_tts import (
Qwen3TTSTalkerCodePredictorConfig,
Qwen3TTSTalkerConfig,
)
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_code_predictor_vllm import (
Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM,
)
torch.manual_seed(42)
cp = Qwen3TTSTalkerCodePredictorConfig(
vocab_size=64, hidden_size=64, intermediate_size=128, num_hidden_layers=1,
num_attention_heads=4, num_key_value_heads=2, head_dim=16, num_code_groups=4,
) # fmt: skip
config = mocker.Mock(
spec=VllmConfig,
model_config=mocker.Mock(stage_connector_config={}),
additional_config={"code_predictor_kv_cache": True, "code_predictor_fused": True},
scheduler_config=mocker.Mock(max_num_seqs=4),
)
predictor = Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM(
vllm_config=config, config=cp, talker_config=Qwen3TTSTalkerConfig(hidden_size=64, num_code_groups=4)
).to(device="cuda", dtype=torch.bfloat16)
predictor._setup_compile()
assert predictor._fused is not None
ids = torch.randint(0, 64, (batch, 1), device="cuda")
embeds = torch.randn(batch, 1, 64, device="cuda", dtype=torch.bfloat16)
hidden = torch.randn_like(embeds)
uniforms = torch.rand(batch, 3, 64, device="cuda").clamp_(1e-6, 1 - 1e-6)
actual = predictor(ids, embeds, hidden, top_k=top_k, sample_uniforms=uniforms).clone()
# Use identical parameters through the full re-prefill and ATen sampling
# path, bypassing both the fused predictor and its frame-local KV cache.
predictor._fused_requested = False
predictor._fused = None
predictor._frame_cache = None
expected = predictor(ids, embeds, hidden, top_k=top_k, sample_uniforms=uniforms)
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Prefix graphs must follow per-request first-audio delivery, not a capture hint."""
import math
from types import SimpleNamespace
import pytest
@@ -18,6 +19,38 @@ pytestmark = [pytest.mark.core_model]
DEVICE = torch.device("cuda:0")
@pytest.mark.cpu
@pytest.mark.parametrize("capacity,model_type", [(1, "base"), (128, "base"), (128, "custom_voice")])
def test_stream_priming_graph_workspace_respects_token_budget(monkeypatch, capacity, model_type):
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import Qwen3TTSTalkerForConditionalGeneration
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz import streaming_decoder
captures = []
def capture(stream, sizes, frames=1):
captures.append((sizes, frames))
return SimpleNamespace(sizes=sizes, frames=frames)
monkeypatch.setattr(streaming_decoder, "StreamingDecodeGraphs", capture)
model = SimpleNamespace(
stream_decoder=SimpleNamespace(max_frames=33),
stream_graphs=None,
stream_prime_graphs=None,
stream_ref_context_frames=25,
stream_chunk_frames=25,
config=SimpleNamespace(tts_model_type=model_type),
vllm_config=SimpleNamespace(scheduler_config=SimpleNamespace(max_num_batched_tokens=512)),
)
sizes = [size for size in [1, 2, 4, 8, 16, 32, 64, 128] if size <= capacity]
Qwen3TTSTalkerForConditionalGeneration.capture_stream_decode_graphs(model, sizes)
expected = [(sizes, 1)]
if model_type == "base":
expected.append(([size for size in sizes if size * 25 <= 512], 25))
assert captures == expected
Qwen3TTSTalkerForConditionalGeneration.capture_stream_decode_graphs(model, sizes)
assert captures == expected
@pytest.mark.cpu
@pytest.mark.parametrize("skip_flags", [(False, False), (True, True), (False, True), (True, False)])
@pytest.mark.parametrize("initial_frames", [1, 3])
@@ -124,3 +157,134 @@ def test_xvec_graphs_follow_request_first_audio_flags(initial_frames, time_major
torch.testing.assert_close(got, want, atol=1e-4, rtol=1e-4)
for key in ("ref_hidden", "ref_conv", "prefix_hidden", "suffix_quantized", "suffix_conv"):
torch.testing.assert_close(cache[key], expected_cache[key], atol=1e-5, rtol=1e-5)
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@torch.inference_mode()
def test_stream_decoder_preemption_restores_all_state_into_a_different_slot():
from tests.model_executor.models.qwen3_tts.test_time_major_decoder import _make_decoder
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.streaming_decoder import StreamingCodecDecoder
decoder = _make_decoder().to(device=DEVICE, dtype=torch.bfloat16)
for name, param in decoder.named_parameters():
if name.endswith("embedding_sum"):
param.normal_()
decoder.config.head_dim = decoder.config.hidden_size // decoder.config.num_attention_heads
stream = StreamingCodecDecoder(decoder, num_slots=2, dtype=torch.bfloat16)
codes = torch.randint(0, 32, (1, 8, 2), device=DEVICE)
slot = torch.tensor([0], device=DEVICE, dtype=torch.int32)
for pos in range(7):
stream(codes[:, pos : pos + 1], slot, torch.tensor([pos], device=DEVICE, dtype=torch.int32))
saved = stream.save_slot(0)
expected = stream(codes[:, 7:], slot, torch.tensor([7], device=DEVICE, dtype=torch.int32)).clone()
# Both the freed slot and the destination can hold an unrelated request.
other_codes = (codes[:, :3] + 1) % 32
for pos in range(3):
stream(
other_codes[:, pos : pos + 1].expand(2, -1, -1).contiguous(),
torch.tensor([0, 1], device=DEVICE, dtype=torch.int32),
torch.full((2,), pos, device=DEVICE, dtype=torch.int32),
)
without_restore = stream(
codes[:, 7:],
torch.tensor([1], device=DEVICE, dtype=torch.int32),
torch.tensor([7], device=DEVICE, dtype=torch.int32),
).clone()
assert not torch.equal(without_restore, expected)
stream.restore_slot(1, saved)
actual = stream(
codes[:, 7:],
torch.tensor([1], device=DEVICE, dtype=torch.int32),
torch.tensor([7], device=DEVICE, dtype=torch.int32),
)
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("use_graph", [False, True])
@torch.inference_mode()
def test_batched_reference_priming_matches_serial_decoder_continuation(use_graph):
from tests.model_executor.models.qwen3_tts.test_time_major_decoder import _make_decoder
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import Qwen3TTSTalkerForConditionalGeneration
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.streaming_decoder import (
StreamingCodecDecoder,
StreamingDecodeGraphs,
)
decoder = _make_decoder().to(device=DEVICE, dtype=torch.bfloat16)
for name, param in decoder.named_parameters():
if name.endswith("embedding_sum"):
param.normal_()
decoder.config.head_dim = decoder.config.hidden_size // decoder.config.num_attention_heads
stream = StreamingCodecDecoder(decoder, num_slots=5, dtype=torch.bfloat16)
graphs = StreamingDecodeGraphs(stream, [2], frames=25) if use_graph else None
model = Qwen3TTSTalkerForConditionalGeneration.__new__(Qwen3TTSTalkerForConditionalGeneration)
torch.nn.Module.__init__(model)
model.stream_decoder = stream
model.stream_prime_graphs = graphs
model.stream_chunk_frames = 25
refs = [torch.randint(0, 32, (length, 2), device=DEVICE) for length in [25, 3, 51, 25]]
slots = [2, 0, 3, 4]
frame = torch.randint(0, 32, (4, 1, 2), device=DEVICE)
slot_tensor = torch.tensor(slots, device=DEVICE, dtype=torch.int32)
positions = torch.tensor([len(ref) for ref in refs], device=DEVICE, dtype=torch.int32)
for slot, ref in zip(slots, refs, strict=True):
for t0 in range(0, len(ref), 25):
stream(
ref[None, t0 : t0 + 25].to(torch.int32).contiguous(),
torch.tensor([slot], device=DEVICE, dtype=torch.int32),
torch.tensor([t0], device=DEVICE, dtype=torch.int32),
)
expected = stream(frame, slot_tensor, positions).clone()
untouched = stream.save_slot(1)
# Reuse dirty slots; pos=0 must reset every causal layer for each group.
model.prime_stream_decoder(list(zip(slots, refs, strict=True)))
actual = stream(frame, slot_tensor, positions)
torch.testing.assert_close(actual, expected, rtol=0, atol=3e-5)
for got, want in zip(stream.save_slot(1), untouched, strict=True):
torch.testing.assert_close(got, want, rtol=0, atol=0)
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("use_graph", [False, True])
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
@torch.inference_mode()
def test_stream_frames_match_fp32_exact_decoder(use_graph, dtype):
from tests.model_executor.models.qwen3_tts.test_time_major_decoder import _make_decoder
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.streaming_decoder import (
StreamingCodecDecoder,
StreamingDecodeGraphs,
)
decoder = _make_decoder().to(device=DEVICE, dtype=dtype)
# The tiny HF default initialization shrinks the deep conv stack to
# near-zero PCM. Keep the oracle signal large enough to catch lost state.
for module in decoder.modules():
if isinstance(module, (torch.nn.Conv1d, torch.nn.ConvTranspose1d, torch.nn.Linear)):
torch.nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5))
if module.bias is not None:
module.bias.uniform_(-0.01, 0.01)
for name, param in decoder.named_parameters():
if name.endswith("embedding_sum"):
param.normal_()
decoder.config.head_dim = decoder.config.hidden_size // decoder.config.num_attention_heads
reference = _make_decoder().to(device=DEVICE, dtype=torch.float32)
reference.load_state_dict(decoder.state_dict())
reference.precompute_snake_caches()
# Cross both the attention window and KV ring wrap, checking every frame.
codes = torch.randint(0, 32, (2, 136, 2), device=DEVICE)
expected = reference._forward_exact(codes.transpose(1, 2))[:, 0]
assert expected.square().sum() > 1e-3
stream = StreamingCodecDecoder(decoder, num_slots=3, dtype=dtype)
decode = StreamingDecodeGraphs(stream, [2]) if use_graph else stream
slots = torch.tensor([2, 0], device=DEVICE, dtype=torch.int32)
spf = int(stream.spf)
for frame in range(codes.shape[1]):
positions = torch.full((2,), frame, device=DEVICE, dtype=torch.int32)
actual = decode(codes[:, frame : frame + 1].contiguous().to(torch.int32), slots, positions).reshape(2, -1)
exact_frame = expected[:, frame * spf : (frame + 1) * spf]
relative_rms = (actual - exact_frame).square().mean(1).sqrt() / exact_frame.square().mean(1).sqrt()
# BF16 kernels are approximate; compare every frame to the independent
# FP32 full decoder, not only one streaming implementation to itself.
tolerance = 0.05 if dtype == torch.bfloat16 else 5e-4
assert torch.all(relative_rms < tolerance), (frame, relative_rms)
@@ -0,0 +1,57 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Streaming col2im preserves PCM inputs and ping-pong slot state."""
import pytest
import torch
from vllm.triton_utils import triton
from tests.helpers.mark import hardware_test
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.streaming_decoder import _col2im_kernel
pytestmark = [pytest.mark.core_model, pytest.mark.tts]
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.parametrize("batch,frames,channels,rate", [(1, 1, 5, 2), (3, 3, 129, 3), (9, 1, 64, 4)])
def test_col2im_partial_tiles_and_reordered_slot_state(batch: int, frames: int, channels: int, rate: int):
torch.manual_seed(23)
capacity = batch + 2
z = torch.randn(batch, frames, 2 * rate, channels).to(torch.bfloat16)
bias = torch.randn(channels).to(torch.bfloat16)
state = torch.randn(2, capacity, rate, channels).to(torch.bfloat16)
expected_state = state.clone()
slots = torch.arange(batch - 1, -1, -1, dtype=torch.int32)
positions = torch.arange(batch, dtype=torch.int32)
parity = torch.arange(capacity, dtype=torch.int32) % 2
expected = torch.empty(batch, frames, rate, channels, dtype=torch.bfloat16)
for b in range(batch):
slot = int(slots[b])
side = int(parity[slot])
for t in range(frames):
previous = z[b, t - 1, rate:] if t else state[side, slot] if positions[b] else torch.zeros(rate, channels)
expected[b, t] = (z[b, t, :rate].float() + previous.float() + bias.float()).to(torch.bfloat16)
expected_state[1 - side, slot] = z[b, -1, rate:]
z_gpu, bias_gpu, state_gpu = z.cuda(), bias.cuda(), state.cuda()
slots_gpu, positions_gpu, parity_gpu = slots.cuda(), positions.cuda(), parity.cuda()
actual = torch.empty_like(expected, device="cuda")
width = min(128, triton.next_power_of_2(channels))
rows = batch * frames
_col2im_kernel[(rows, rate, triton.cdiv(channels, width))](
z_gpu,
bias_gpu,
state_gpu,
slots_gpu,
positions_gpu,
parity_gpu,
actual,
frames,
capacity,
R=rate,
C=channels,
BC=width,
num_warps=4,
)
torch.testing.assert_close(actual.cpu(), expected, rtol=0, atol=0)
torch.testing.assert_close(state_gpu.cpu(), expected_state, rtol=0, atol=0)
@@ -594,6 +594,40 @@ def test_streaming_ref_code_context_is_bounded_for_batchable_shapes():
torch.testing.assert_close(frames[:3], ref_code[-3:])
@pytest.mark.parametrize("tensor_frames", [False, True])
def test_async_chunks_preserve_codebook_order_with_reference_and_short_tail(tensor_frames):
tm = _tm(left_context=3, initial_chunk_frames=1)
rid = "r-codebook-order"
quantizers = 16
reference = [[1500 + f * quantizers + q for q in range(quantizers)] for f in range(5)]
tm.request_payload[rid] = torch.tensor(reference, dtype=torch.long)
generated = [[1 + f * quantizers + q for q in range(quantizers)] for f in range(30)]
for start, end, finished in [(0, 1, False), (1, 26, False), (26, 30, True)]:
rows = generated[:end]
if tensor_frames:
# Non-contiguous int32 rows exercise conversion independently of
# the native producer's contiguous CPU-long representation.
storage = torch.tensor(rows, dtype=torch.int32).repeat_interleave(2, dim=1)
tm.code_prompt_token_ids[rid] = list(storage[:, ::2].unbind())
else:
tm.code_prompt_token_ids[rid] = rows
payload = talker2code2wav_async_chunk(
transfer_manager=tm,
multimodal_output=None if finished else {},
request=_req(rid, finished=finished),
is_finished=finished,
)
assert payload is not None
expected = (reference[-3:] if start == 0 else []) + generated[start:end]
codes = payload.codes.audio
assert codes.dtype == torch.long and codes.device.type == "cpu" and codes.is_contiguous()
torch.testing.assert_close(codes.reshape(quantizers, -1).T, torch.tensor(expected))
assert payload.meta.left_context_size == (3 if start == 0 else 0)
assert payload.meta.finished.item() == finished
tm.put_req_chunk[rid] += 1
def test_ref_code_context_can_be_buffered_before_first_emit():
tm = _tm()
rid = "r-ref-buffered"
+21
View File
@@ -0,0 +1,21 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
import torch
from vllm_omni.utils.device_copy import index_to_device
pytestmark = [pytest.mark.core_model, pytest.mark.cuda]
def test_index_staging_survives_later_copies_and_graph_replay():
stream = torch.cuda.Stream()
graph = torch.cuda.CUDAGraph()
with torch.cuda.stream(stream):
with torch.cuda.graph(graph, stream=stream):
captured = index_to_device([17] * 6, "cuda")
for _ in range(32):
index_to_device([99] * 6, "cuda")
graph.replay()
torch.accelerator.synchronize()
assert captured.tolist() == [17] * 6
@@ -25,6 +25,9 @@ class _FakeStream:
def wait_stream(self, _stream) -> None:
pass
def wait_event(self, _event) -> None:
pass
class _FakeEvent:
def record(self, _stream) -> None:
@@ -138,6 +141,7 @@ def test_last_pp_rank_orchestration_and_kv_resolver(monkeypatch, needs_history)
def test_async_mm_snapshot_owns_output_until_copy_finishes() -> None:
runner = OmniARModelRunner.__new__(OmniARModelRunner)
runner.model_config = SimpleNamespace(async_chunk=True)
runner.model = SimpleNamespace()
runner._async_mm_snapshot_slots, runner._async_mm_snapshot_events = [{}], [None]
runner._async_mm_snapshot_pending, runner._async_mm_snapshot_cursor = [False], 0
waited: list[object] = []
@@ -307,6 +311,231 @@ def test_request_reference_codes_preserve_local_axis(prefill_first, padded):
assert torch.equal(outputs[i]["codes.audio"], codes[offsets[i] : offsets[i + 1]])
def test_stream_audio_cancel_rejects_inflight_output_and_id_reuse() -> None:
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer
buffer = StreamingAudioBuffer(samples_per_frame=4, chunk_frames=3)
cancelled = buffer.add("request")
buffer.finish({"request"})
replacement = buffer.add("request")
assert cancelled.push(torch.ones(4), False) is None
assert not cancelled.pending
assert replacement.push(torch.full((4,), 2.0), False).tolist() == [2.0] * 4
buffer.finish({"request"})
assert not buffer.requests
def test_stream_audio_length_end_flushes_first_and_partial_chunks() -> None:
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer, StreamingAudioOutput
buffer = StreamingAudioBuffer(samples_per_frame=4, chunk_frames=3)
state = buffer.add("request")
output = StreamingAudioOutput(
torch.ones(1, 4),
torch.tensor([True]),
torch.tensor(24000),
None,
np.array([0, 1]),
[state],
np.array([True]),
)
assert output.get_output()[0]["model_outputs"].numel() == 4
assert not state.active
state = buffer.add("another")
assert state.push(torch.ones(4), False).numel() == 4
assert state.push(torch.ones(4), False) is None
assert state.push(torch.ones(4), True).numel() == 8
@pytest.mark.parametrize("dtype", [torch.float16, torch.float32, torch.float64, torch.bfloat16])
def test_stream_audio_batch_views_retain_pcm_after_output_release(dtype):
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer, StreamingAudioOutput
buffer = StreamingAudioBuffer(samples_per_frame=4, chunk_frames=3)
states = [buffer.add("a"), buffer.add("b")]
expected: list[list[torch.Tensor]] = [[], []]
emitted: list[list[torch.Tensor]] = [[], []]
for step in range(5):
# Mixed prefill/decode spans, invalid rows, and a final partial chunk.
wav = (torch.arange(16).reshape(4, 4) + 100 * step).to(dtype)
valid = torch.tensor([False, True, True, step != 4])
output = StreamingAudioOutput(
wav,
valid,
torch.tensor(24000),
None,
np.array([0, 3, 4]),
states,
np.array([step == 4, step == 4]),
)
for i, (start, end) in enumerate([(0, 3), (3, 4)]):
expected[i].append(wav[start:end][valid[start:end]].reshape(-1).clone())
for i, payload in enumerate(output.get_output()):
if payload is not None:
emitted[i].append(payload["model_outputs"])
del output, wav # Pending views must keep the old host allocation alive.
for i in range(2):
assert torch.equal(torch.cat(emitted[i]), torch.cat(expected[i]))
assert torch.cat(emitted[i]).dtype == dtype
assert not states[i].active and not states[i].pending
assert states[i].pending_samples == 0
def test_stream_audio_numpy_direct_first_cancel_and_mixed_fallback():
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer
buffer = StreamingAudioBuffer(samples_per_frame=4, chunk_frames=3)
state = buffer.add("r")
state.accept_first_audio()
assert state.push(np.arange(8, dtype=np.float32), False) is None
assert state.pending_samples == 4
# A dtype fallback can arrive while a NumPy frame is pending.
chunk = state.push(torch.arange(8, 12, dtype=torch.bfloat16), True)
assert chunk.tolist() == list(range(4, 12))
assert state.pending_samples == 0
buffer.finish({"r"})
replacement = buffer.add("r")
assert state.push(np.ones(4, dtype=np.float32), False) is None
assert replacement.push(np.full(4, 99, dtype=np.float32), False).tolist() == [99] * 4
replacement.push(np.ones(4, dtype=np.float32), False)
assert replacement.pending_samples == 4
buffer.finish({"r"})
assert replacement.pending_samples == 0 and not replacement.pending
def test_stream_audio_prefill_length_end_reaches_output(mocker) -> None:
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.states import RequestState
from vllm_omni.worker_v2.model_states.eager_mtp import EagerMTPState
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer
owner = mocker.Mock()
owner.vllm_config.model_config.max_model_len = 4096
owner._stream_decode_event = None
eager = EagerMTPState(owner)
eager._audio_buffer = StreamingAudioBuffer(4, 25)
eager._audio_buffer.add("request")
eager._frame_requests = {"request"}
batch = InputBatch.__new__(InputBatch)
batch.num_reqs, batch.req_ids = 1, ["request"]
batch.num_computed_tokens_np = np.array([0])
batch.num_scheduled_tokens = np.array([3])
batch.idx_mapping_np = np.array([0])
batch.query_start_loc_np = np.array([0, 3])
batch.is_prefilling_np = np.array([True])
states = RequestState.__new__(RequestState)
states.max_seq_len = np.array([4])
mm = {
"model_outputs": torch.ones(3, 4),
"meta": {"codec_frame_valid": torch.tensor([0, 0, 1])},
"sr": [torch.tensor(24000)],
}
output = eager.prepare_audio_output(batch, states, mm)
assert output.get_output()[0]["model_outputs"].numel() == 4
assert "model_outputs" not in mm
def test_stream_audio_preemption_preserves_position_rng_and_pending_pcm(mocker) -> None:
from vllm_omni.worker_v2.model_states.eager_mtp import EagerMTPState, TalkerInputs
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer
owner = mocker.Mock()
owner._stream_pos = {"request": 37}
owner._eager_embeds = torch.arange(18).reshape(6, 3).float()
owner._eager_ready = {}
owner.intermediate_buffer.buffers = [{} for _ in range(6)]
generator = torch.Generator().manual_seed(42)
owner._mtp_generators = {"request": generator}
saved = [torch.arange(6)]
owner.model.stream_decoder.save_slot.return_value = saved
eager = EagerMTPState(owner)
eager._talker_inputs["request"] = TalkerInputs(torch.ones(20, 3), 10)
eager._side_stream = mocker.Mock()
eager._audio_buffer = StreamingAudioBuffer(4, 25)
request = eager._audio_buffer.add("request")
request.push(torch.ones(4), False)
request.push(torch.ones(4), False)
eager.suspend_audio("request", 2)
owner._stream_pos.clear()
owner._mtp_generators.clear()
eager.resume_audio("request", 5)
assert owner._stream_pos["request"] == 37
assert owner._mtp_generators["request"] is generator
assert eager._restore_audio["request"] is saved
assert sum(part.numel() for part in request.pending) == 4
# A second preemption can happen before the restored slot is used.
eager.suspend_audio("request", 5)
owner.model.stream_decoder.save_slot.assert_called_once_with(2)
eager.finish_audio({"request"})
assert not eager._suspended_audio and not eager._restore_audio
assert not eager._audio_buffer.requests and not request.active
def test_stream_audio_replay_uses_exact_inputs_and_consumes_last_frame_once(mocker):
from vllm_omni.worker_v2.model_states.eager_mtp import EagerMTPState, TalkerInputs
owner = mocker.Mock()
owner._eager_embeds = torch.tensor([[20.0, 30.0]])
owner.model.preprocess.return_value = (None, None, {"mtp_inputs": (None, torch.tensor([[2.0, 3.0]]))})
owner.intermediate_buffer.buffers = [{"req_id": "request"}]
eager = EagerMTPState(owner)
eager._restore_audio["request"] = []
history = torch.arange(8).reshape(4, 2).float()
eager._talker_inputs["request"] = TalkerInputs(history, 4)
first = torch.empty(2, 2)
assert eager.replay_inputs("request", 0, 0, torch.ones(2), first)
torch.testing.assert_close(first, history[:2])
owner.model.preprocess.assert_not_called()
last = torch.empty(3, 2)
assert eager.replay_inputs("request", 0, 2, torch.ones(3), last)
torch.testing.assert_close(last, torch.cat((history[2:], torch.tensor([[22.0, 33.0]]))))
owner.model.preprocess.assert_called_once()
with pytest.raises(RuntimeError, match="exceeds saved inputs"):
eager.replay_inputs("request", 0, 4, torch.ones(2), torch.empty(2, 2))
def test_stream_reference_priming_groups_lengths_without_padding_or_slot_aliasing(mocker):
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import Qwen3TTSTalkerForConditionalGeneration
primes = [(4, torch.full((26, 2), 4)), (1, torch.full((3, 2), 1)), (7, torch.full((26, 2), 7))]
calls = []
def stream(codes, slots, pos):
calls.append((codes.clone(), slots.clone(), pos.clone()))
decoder = mocker.Mock(side_effect=stream, device=torch.device("cpu"))
model = mocker.Mock(stream_decoder=decoder, stream_prime_graphs=None, stream_chunk_frames=25)
Qwen3TTSTalkerForConditionalGeneration.prime_stream_decoder(model, primes)
assert len(calls) == 3
for (codes, slots, pos), frames, indices, position in zip(
calls, [25, 1, 3], [[4, 7], [4, 7], [1]], [0, 25, 0], strict=True
):
assert codes.shape == (len(indices), frames, 2)
assert codes.dtype == slots.dtype == pos.dtype == torch.int32
assert slots.tolist() == indices and pos.tolist() == [position] * len(indices)
for row, idx in enumerate(indices):
assert torch.all(codes[row] == idx)
Qwen3TTSTalkerForConditionalGeneration.prime_stream_decoder(model, [])
assert len(calls) == 3
@pytest.mark.parametrize("context_frames", [25, 72])
def test_model_owned_reference_context_respects_configured_boundary(mocker, context_frames):
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import Qwen3TTSTalkerForConditionalGeneration
model = mocker.Mock(stream_ref_context_frames=context_frames, talker_config=mocker.Mock(num_code_groups=16))
reference = torch.arange(100 * 16).reshape(100, 16)
info = {"codes": {"ref": reference}}
got = Qwen3TTSTalkerForConditionalGeneration.get_stream_ref_context(model, info)
torch.testing.assert_close(got, reference[-context_frames:])
assert info["codes"]["ref"] is reference
assert Qwen3TTSTalkerForConditionalGeneration.get_stream_ref_context(model, {}) is None
assert (
Qwen3TTSTalkerForConditionalGeneration.get_stream_ref_context(model, {"codes": {"ref": torch.empty(0)}}) is None
)
@pytest.mark.parametrize("streaming", [False, True])
def test_model_owned_audio_finalizer_runs_after_copy_without_hidden(monkeypatch, streaming):
monkeypatch.setattr(torch.cuda, "set_stream", lambda _stream: None)
@@ -340,6 +569,136 @@ def test_model_owned_audio_finalizer_runs_after_copy_without_hidden(monkeypatch,
assert (result.pooler_output is None) == streaming
def test_stream_audio_history_replays_exact_inputs_after_batch_reordering(mocker):
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm_omni.worker_v2.model_states.eager_mtp import EagerMTPState
owner = mocker.Mock()
owner.vllm_config.model_config.max_model_len = 12
eager = EagerMTPState(owner)
first = torch.arange(9, dtype=torch.float32).reshape(3, 3)
second = torch.arange(9, 18, dtype=torch.float32).reshape(3, 3)
expected = {"a": torch.cat((first[:2], second[2:])), "b": torch.cat((first[2:], second[:2]))}
batch = InputBatch.__new__(InputBatch)
batch.req_ids = ["a", "b"]
batch.query_start_loc_np = np.array([0, 2, 3])
batch.num_computed_tokens_np = np.array([0, 0])
eager.record_inputs(batch, first)
batch.req_ids = ["b", "a"]
batch.num_computed_tokens_np = np.array([1, 2])
eager.record_inputs(batch, second)
# Later input-buffer reuse must not change the conditioned replay history.
first.fill_(-1)
second.fill_(-2)
for request_id, wanted in expected.items():
eager._restore_audio[request_id] = []
replayed = torch.empty_like(wanted)
assert eager.replay_inputs(request_id, 0, 0, torch.zeros(3, dtype=torch.long), replayed)
torch.testing.assert_close(replayed, wanted)
@pytest.mark.parametrize("valid", [False, True])
def test_stream_audio_direct_first_requires_only_real_pcm_on_terminal(valid):
from vllm_omni.data_entry_keys import FIRST_AUDIO_REQUIRED_KEY
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer, StreamingAudioOutput
buffer = StreamingAudioBuffer(samples_per_frame=4, chunk_frames=3)
state = buffer.add("r")
state.accept_first_audio()
first = StreamingAudioOutput(
torch.arange(4).reshape(1, 4),
torch.tensor([valid]),
torch.tensor(24000),
None,
np.array([0, 1]),
[state],
np.array([True]),
)
payload = first.get_output()[0]
if valid:
assert payload == {FIRST_AUDIO_REQUIRED_KEY: torch.tensor(True)}
else:
assert payload is None # EOS has no promised first PCM to wait for.
assert not state.active and not state.pending
buffer.finish({"r"})
replacement = buffer.add("r")
assert replacement.push(torch.full((4,), 99), False).tolist() == [99] * 4
def test_stream_audio_direct_first_drops_one_frame_and_retains_partial_suffix():
from vllm_omni.worker_v2.streaming_audio import AudioRequest
state = AudioRequest(samples_per_frame=4, chunk_frames=3)
state.accept_first_audio()
assert state.push(torch.arange(4), False) is None
assert state.first_audio_required and state.emitted
assert state.push(torch.arange(4, 8), False) is None
chunk = state.push(torch.arange(8, 12), True)
assert chunk.tolist() == list(range(4, 12))
assert not state.active and not state.pending
@pytest.mark.parametrize("consumer", ["pcm_only", "finalizer", "extra"])
def test_stream_audio_snapshot_skips_discarded_code_partition(monkeypatch, mocker, consumer):
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm_omni.worker_v2.output_snapshot import RequestOutputSnapshot
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer, StreamingAudioOutput
monkeypatch.setattr(torch.cuda, "set_stream", lambda _stream: None)
monkeypatch.setattr(
OmniARModelRunner,
"_build_async_chunk_outputs_from_mm",
lambda *args: pytest.fail("in-stage PCM unnecessarily partitioned code outputs"),
)
batch = InputBatch.__new__(InputBatch)
batch.num_reqs = 3
batch.query_start_loc_np = np.array([0, 1, 2, 4])
batch.num_scheduled_tokens = np.array([1, 1, 2])
batch.num_tokens_after_padding = 4
buffer = StreamingAudioBuffer(samples_per_frame=4, chunk_frames=3)
states = [buffer.add(request_id) for request_id in ["frame", "eos", "prefill"]]
wav = torch.arange(16, dtype=torch.float32).reshape(4, 4)
streaming_audio = StreamingAudioOutput(
wav,
torch.tensor([True, False, True, False]),
torch.tensor(24000),
None,
batch.query_start_loc_np.copy(),
states,
np.array([False, False, True]),
)
copy_mm = mocker.spy(omni_ar_model_runner, "_async_copy_mm")
def finalize(payload, counts):
assert payload["codes"]["audio"].shape == (4, 2)
return RequestOutputSnapshot([None] * batch.num_reqs)
finalizer = mocker.Mock(side_effect=finalize) if consumer == "finalizer" else None
extra = ({"extra": torch.tensor([7])}, _FakeEvent()) if consumer == "extra" else None
result = _async_output(
req_ids=["frame", "eos", "prefill"],
sampler_output=SamplerOutput(torch.tensor([[1], [2], [3]]), None, None, None),
num_sampled_tokens=torch.tensor([1, 1, 1]),
multimodal_outputs={"codes": {"audio": torch.ones(4, 2)}},
input_batch=batch,
async_chunk=True,
streaming_audio=streaming_audio,
finalize_multimodal=finalizer,
extra_multimodal_outputs=extra,
).get_output()
assert copy_mm.call_count == {"pcm_only": 0, "finalizer": 1, "extra": 2}[consumer]
if finalizer is not None:
finalizer.assert_called_once()
wav.fill_(-1)
assert result.inter_stage_outputs is None
assert result.multimodal_outputs[0]["model_outputs"].tolist() == [0, 1, 2, 3]
assert result.multimodal_outputs[1] == {}
assert result.multimodal_outputs[2]["model_outputs"].tolist() == [8, 9, 10, 11]
assert not states[1].active and not states[2].active
@pytest.mark.parametrize("streaming", [False, True])
def test_request_owned_snapshot_skips_generic_partition(monkeypatch, streaming):
from vllm_omni.worker_v2.output_snapshot import RequestOutputSnapshot
+6
View File
@@ -36,6 +36,7 @@ class _DummyInputBatch:
def _make_state(max_num_reqs=4, has_preprocess=False, has_postprocess=False, have_multimodal_outputs=False):
state = object.__new__(OmniModelState)
model = MagicMock()
model.stream_decoder = None
model.has_preprocess = has_preprocess
model.has_postprocess = has_postprocess
model.have_multimodal_outputs = have_multimodal_outputs
@@ -62,6 +63,10 @@ def _make_state(max_num_reqs=4, has_preprocess=False, has_postprocess=False, hav
state.intermediate_buffer = OmniIntermediateBuffer(max_num_reqs)
state._static_inputs_embeds = None
from vllm_omni.worker_v2.model_states.eager_mtp import EagerMTPState
state._eager_state = EagerMTPState(state)
state._stream_pos = {}
state._mtp_generators = {}
state._mtp_runner = None
for name in ("_mtp_input_ids", "_mtp_input_embeds", "_mtp_hidden", "_mtp_text_step", "_mtp_offsets"):
@@ -264,6 +269,7 @@ def test_seed_independence_resolve_once_and_sampling_kwargs():
# vLLM sampling seed must not produce a talker generator.
cpu = torch.device("cpu")
assert state._get_mtp_generator("r1", SimpleNamespace(extra_args={}, seed=42), cpu) is None
state._mtp_generators.clear() # The following rows are new requests.
# Same model-local seed reproduces identical uniforms regardless of batch makeup.
state._mtp_sample_uniforms = torch.empty((2, 2, 4))
assert torch.equal(