[Model] Reduce MiniCPM-o 4.5 reference setup and Talker overhead (#7968)

Signed-off-by: natureofnature <wzliu@connect.hku.hk>
Co-authored-by: xjwu <wuxianjin633@gmail.com>
Co-authored-by: Eric(Qun) <186020953+0xtoward@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-09-24 05:18:56 -07:00
1 parent ba3d48e1c7
commit 9c1656c607
6 files changed
+683 -59

No files matched your search

@@ -9,11 +9,14 @@ steady-state calls share one capture shape; ``_decode_cfm`` trims the output
back. These tests pin the decision math on CPU, no CUDA required.
"""
from types import SimpleNamespace
import pytest
import torch
from vllm_omni.model_executor.models.minicpmo_4_5.batched_token2wav import (
_cfm_pad_frames,
_zero_padded_cnn_cache,
_zero_padded_frames,
)
@@ -160,3 +163,67 @@ def test_zero_padded_frames_is_a_noop_without_padding():
_zero_padded_frames(x, None)
_zero_padded_frames(x, 32)
assert torch.all(x == 1.0)
def _cnn_cache_estimator(widths):
return SimpleNamespace(
blocks=[
SimpleNamespace(conv=SimpleNamespace(block=[None, SimpleNamespace(causal_padding=(width, 0))]))
for width in widths
]
)
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
@pytest.mark.parametrize("noncontiguous", [False, True])
@pytest.mark.parametrize(
"widths,cache_width,pad_frames,cache_depth",
[
((4, 4), 4, 1, 2),
((4, 4), 4, 0, 2),
((4, 4), 4, 7, 2),
((4, 2), 4, 1, 2),
((2, 2), 4, 1, 2),
((6, 6), 4, 1, 2),
((0, 4, -1), 4, 1, 3),
((0, -1), 4, 7, 2),
((4, 4), 4, -1, 2),
((4, 4), 4, 1, 3),
((), 4, 1, 1),
],
)
def test_zero_padded_cnn_cache_matches_per_block_writes(
dtype, noncontiguous, widths, cache_width, pad_frames, cache_depth
):
# Compare all storage, including the untouched columns of a strided view.
storage_width = cache_width * (2 if noncontiguous else 1)
original = torch.arange(cache_depth * 2 * 3 * storage_width, dtype=torch.float32)
original = (original.reshape(cache_depth, 2, 3, storage_width) + 1).to(dtype)
expected_storage = original.clone()
actual_storage = original.clone()
expected = expected_storage[..., ::2] if noncontiguous else expected_storage
actual = actual_storage[..., ::2] if noncontiguous else actual_storage
for index, width in enumerate(widths):
if width > 0:
zero_from = max(0, width - pad_frames)
if zero_from < width:
expected[index][..., zero_from:] = 0.0
result = _zero_padded_cnn_cache(actual, _cnn_cache_estimator(widths), pad_frames)
assert result is None
assert torch.equal(actual_storage, expected_storage)
assert actual.dtype == dtype
assert actual.stride() == expected.stride()
def test_zero_padded_cnn_cache_uniform_blocks_use_one_write():
cache = torch.ones(16, 2, 3, 4)
version = cache._version
_zero_padded_cnn_cache(cache, _cnn_cache_estimator([4] * 16), 1)
# CPU mutation count pins the mechanism without making a CUDA timing claim.
assert cache._version - version == 1
assert torch.equal(cache[..., :3], torch.ones(16, 2, 3, 3))
assert torch.count_nonzero(cache[..., 3:]) == 0
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import gc
import subprocess
import sys
from contextlib import contextmanager
@@ -153,7 +154,7 @@ class _FakeToken2Wav:
raise AssertionError("sequential __call__ fallback must never be called")
def _config(minimum: int = 1, initial: int = 0):
def _config(minimum: int = 1, initial: int = 0, *, runtime_prompt_cache_size: int = 4, setup_cache_size: int = 1):
return SimpleNamespace(
model_config=SimpleNamespace(
model="/fake/model",
@@ -161,6 +162,8 @@ def _config(minimum: int = 1, initial: int = 0):
"extra": {
"code2wav_min_batch_size": minimum,
"code2wav_initial_batch_size": initial,
"token2wav_runtime_prompt_cache_size": runtime_prompt_cache_size,
"token2wav_setup_cache_size": setup_cache_size,
"prompt_cache_id": "shared",
"prompt_wav": "/fake/prompt.wav",
}
@@ -169,15 +172,71 @@ def _config(minimum: int = 1, initial: int = 0):
)
def _model(initial: int = 0, minimum: int = 1):
def _model(initial: int = 0, minimum: int = 1, *, runtime_prompt_cache_size: int = 4, setup_cache_size: int = 1):
token2wav = _FakeToken2Wav()
backend = BatchedToken2Wav(token2wav)
backend = BatchedToken2Wav(token2wav, setup_cache_size=setup_cache_size)
_enable_fake_ragged_kernel(backend)
model = MiniCPMO45Code2Wav(vllm_config=_config(minimum=minimum, initial=initial))
model = MiniCPMO45Code2Wav(
vllm_config=_config(
minimum=minimum,
initial=initial,
runtime_prompt_cache_size=runtime_prompt_cache_size,
setup_cache_size=setup_cache_size,
)
)
model.backend = backend
return model, token2wav
def test_setup_cache_reuses_read_only_state_for_the_same_exact_batch():
token2wav = _FakeToken2Wav()
adapter = BatchedToken2Wav(token2wav, setup_cache_size=2)
prompt = adapter.prepare_prompt("shared", "/fake/prompt.wav")
first = adapter.setup_batch(prompt, 1)
encoder_calls = list(token2wav.flow.encoder.calls)
snapshots = {name: tensor.clone() for name, tensor in {**first[0].flow_cache, **first[0].hift_cache}.items()}
second = adapter.setup_batch(prompt, 1)
assert first is not second
assert first[0] is second[0]
assert token2wav.flow.encoder.calls == encoder_calls
adapter.decode_batch(
torch.tensor([[10, 11]]),
prompt,
second,
last_chunk=False,
)
for name, expected in snapshots.items():
cache = first[0].flow_cache if name in first[0].flow_cache else first[0].hift_cache
torch.testing.assert_close(cache[name], expected)
def test_setup_cache_keys_batch_size_and_evicts_least_recent_entry():
token2wav = _FakeToken2Wav()
adapter = BatchedToken2Wav(token2wav, setup_cache_size=1)
prompt = adapter.prepare_prompt("shared", "/fake/prompt.wav")
adapter.setup_batch(prompt, 1)
adapter.setup_batch(prompt, 2)
adapter.setup_batch(prompt, 1)
assert token2wav.flow.encoder.calls == [1, 2, 1]
assert list(adapter._setup_cache) == [(prompt.cache_key, 1, 0)]
def test_evict_prompt_clears_features_and_setup_state():
token2wav = _FakeToken2Wav()
adapter = BatchedToken2Wav(token2wav, setup_cache_size=2)
first = adapter.prepare_prompt("first", "/fake/first.wav")
adapter.setup_batch(first, 1)
adapter.evict_prompt("first", "/fake/first.wav")
assert ("first", "/fake/first.wav") not in adapter._prompt_features
assert all(key[0] != first.cache_key for key in adapter._setup_cache)
def _enable_fake_ragged_kernel(adapter: BatchedToken2Wav) -> None:
"""Keep fake-model tests focused on ragged grouping and row mapping."""
estimator = adapter.flow.decoder.estimator
@@ -239,6 +298,176 @@ def _forward(model, infos, placeholder_counts=None, request_ids=None):
)
def _runtime_ref_info(request_id: str, reference: torch.Tensor):
info = _info(request_id, 0, [10, 11])
info["codes"]["ref"] = reference
info["meta"]["ref_audio_sr"] = 16000
info["meta"].pop("prompt_cache_id")
return info
def test_runtime_prompt_cache_rejects_negative_capacity():
with pytest.raises(ValueError, match="runtime prompt cache capacity must be >= 0"):
_model(runtime_prompt_cache_size=-1)
@pytest.mark.parametrize("capacity", [0, 4])
@pytest.mark.parametrize("initial_codes", [[], [10, 11]])
def test_runtime_prompt_reuse_preserves_output_without_caching_setup(capacity, initial_codes):
model, token2wav = _model(runtime_prompt_cache_size=capacity, setup_cache_size=0)
reference = torch.tensor([0.0, 0.25, -0.25, 0.0])
def request(request_id):
info = _runtime_ref_info(request_id, reference)
info["codes"]["audio"] = torch.tensor(initial_codes, dtype=torch.long)
if not initial_codes:
info["meta"].update(code_flat_numel=0, tts_is_last_chunk=True, turn_end=False)
return info
first = _forward(model, [request("voice-a")], request_ids=["internal-a"])
key = model._request_prompt_keys["internal-a"]
prompt = model._runtime_prompts[key]
features = model.backend._prompt_features[(prompt.cache_id, prompt.path)]
feature_snapshots = [value.clone() for value in (features.speech_tokens, features.speaker_embedding, features.mels)]
first_state = model._states["internal-a"].token2wav
model.on_requests_finished(["internal-a"])
assert not model._states
assert not model._request_prompt_keys
assert Path(prompt.path).is_file() == bool(capacity)
assert (key in model._runtime_prompts) == bool(capacity)
if capacity:
assert prompt.owners == set()
second = _forward(model, [request("voice-b")], request_ids=["internal-b"])
second_state = model._states["internal-b"].token2wav
assert token2wav.prompt_calls == (1 if capacity else 2)
# Every request still runs setup; only immutable reference extraction is reused.
assert token2wav.flow.encoder.calls == [1] * (4 if initial_codes else 2)
torch.testing.assert_close(
first.multimodal_outputs["model_outputs"][0],
second.multimodal_outputs["model_outputs"][0],
rtol=0,
atol=0,
)
for old_cache, new_cache in (
(first_state.flow_cache, second_state.flow_cache),
(first_state.hift_cache, second_state.hift_cache),
):
for name, value in new_cache.items():
torch.testing.assert_close(value, old_cache[name], rtol=0, atol=0)
if value.numel():
assert value.data_ptr() != old_cache[name].data_ptr()
for actual, expected in zip(
(features.speech_tokens, features.speaker_embedding, features.mels), feature_snapshots, strict=True
):
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
model.on_requests_finished(["internal-b"])
assert not model._states
assert not model._request_prompt_keys
assert bool(model.backend._prompt_features) == bool(capacity)
def test_runtime_prompt_cache_evicts_only_unowned_references():
model, _ = _model(runtime_prompt_cache_size=1)
_forward(model, [_runtime_ref_info("a", torch.tensor([0.0, 0.1]))])
first_key = model._request_prompt_keys["a"]
first = model._runtime_prompts[first_key]
_forward(model, [_runtime_ref_info("b", torch.tensor([0.0, 0.2]))])
second_key = model._request_prompt_keys["b"]
second = model._runtime_prompts[second_key]
assert set(model._runtime_prompts) == {first_key, second_key}
assert first.owners == {"a"}
assert second.owners == {"b"}
assert Path(first.path).is_file() and Path(second.path).is_file()
model.on_requests_finished(["a"])
assert list(model._runtime_prompts) == [second_key]
assert not Path(first.path).exists()
assert (first.cache_id, first.path) not in model.backend._prompt_features
assert Path(second.path).is_file()
assert set(model._states) == {"b"}
assert model._request_prompt_keys == {"b": second_key}
model.on_requests_finished(["b"])
assert list(model._runtime_prompts) == [second_key]
assert second.owners == set()
assert not model._states
assert not model._request_prompt_keys
def test_runtime_prompt_cache_refreshes_lru_order():
model, token2wav = _model(runtime_prompt_cache_size=2)
keys, paths = {}, {}
for index, voice in enumerate((1, 2, 1, 3)):
request_id = str(index)
_forward(model, [_runtime_ref_info(request_id, torch.tensor([0.0, voice / 10]))])
key = model._request_prompt_keys[request_id]
keys[voice] = key
paths[voice] = Path(model._runtime_prompts[key].path)
model.on_requests_finished([request_id])
assert token2wav.prompt_calls == 3
assert list(model._runtime_prompts) == [keys[1], keys[3]]
assert not paths[2].exists()
assert paths[1].is_file() and paths[3].is_file()
assert len(model.backend._prompt_features) == 2
def test_runtime_prompt_zero_capacity_preserves_same_batch_reference_swap():
model, token2wav = _model(runtime_prompt_cache_size=0)
reference_a = torch.tensor([0.0, 0.1])
reference_b = torch.tensor([0.0, 0.2])
request_ids = ["internal-a", "internal-b"]
_forward(
model,
[_runtime_ref_info("voice-a", reference_a), _runtime_ref_info("voice-b", reference_b)],
request_ids=request_ids,
)
key_a, key_b = (model._request_prompt_keys[request_id] for request_id in request_ids)
prompts = {key: model._runtime_prompts[key] for key in (key_a, key_b)}
features = {key: model.backend._prompt_features[(prompt.cache_id, prompt.path)] for key, prompt in prompts.items()}
# Both old owners must transfer before capacity-zero eviction can run:
# releasing A first would otherwise delete the reference needed by B.
swapped = [_runtime_ref_info("voice-a", reference_b), _runtime_ref_info("voice-b", reference_a)]
for info in swapped:
info["meta"]["cache_epoch"] = 1
_forward(model, swapped, request_ids=request_ids)
expected_keys = {"internal-a": key_b, "internal-b": key_a}
assert model._request_prompt_keys == expected_keys
assert set(model._runtime_prompts) == {key_a, key_b}
assert token2wav.prompt_calls == 2
for request_id, key in expected_keys.items():
prompt = prompts[key]
assert model._runtime_prompts[key] is prompt
assert prompt.owners == {request_id}
assert Path(prompt.path).is_file()
assert model.backend._prompt_features[(prompt.cache_id, prompt.path)] is features[key]
state = model._states[request_id]
assert (state.cache_epoch, state.chunk_seq) == (1, 0)
assert (state.prompt_cache_id, state.prompt_wav) == (prompt.cache_id, prompt.path)
model.on_requests_finished(request_ids)
assert not model._states
assert not model._request_prompt_keys
assert not model._runtime_prompts
assert not model.backend._prompt_features
assert all(not Path(prompt.path).exists() for prompt in prompts.values())
def test_runtime_prompt_cache_removes_retained_wavs_on_model_destruction(tmp_path, monkeypatch):
monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
model, _ = _model()
_forward(model, [_runtime_ref_info("a", torch.tensor([0.0, 0.1]))])
key = model._request_prompt_keys["a"]
path = Path(model._runtime_prompts[key].path)
model.on_requests_finished(["a"])
assert path.is_file()
del model
gc.collect()
assert not path.exists()
assert not path.parent.exists()
def test_adapter_runs_true_batch_cfg_and_splits_request_caches():
token2wav = _FakeToken2Wav()
adapter = BatchedToken2Wav(token2wav)
@@ -888,8 +1117,9 @@ def test_initial_empty_segment_marker_initializes_stream_without_audio():
assert "duplex" in model._states
def test_initial_empty_segment_markers_respect_initial_batch_limit():
model, token2wav = _model(initial=2)
@pytest.mark.parametrize("setup_cache_size,expected_calls", [(0, [2, 2, 1]), (1, [2, 1])])
def test_initial_empty_segment_markers_respect_initial_batch_limit(setup_cache_size, expected_calls):
model, token2wav = _model(initial=2, setup_cache_size=setup_cache_size)
names = ["a", "b", "c", "d", "e"]
boundaries = []
for name in names:
@@ -905,14 +1135,14 @@ def test_initial_empty_segment_markers_respect_initial_batch_limit():
output = _forward(model, boundaries)
assert token2wav.flow.encoder.calls == [2, 2, 1]
assert token2wav.flow.encoder.calls == expected_calls
assert [audio.numel() for audio in output.multimodal_outputs["model_outputs"]] == [0] * len(names)
assert set(model._states) == set(names)
def test_shared_runtime_prompt_recreates_missing_file_before_second_owner(tmp_path, monkeypatch):
monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
model, _ = _model()
model, _ = _model(runtime_prompt_cache_size=0)
reference = torch.tensor([0.0, 0.25, -0.25, 0.0])
first = _info("voice-a", 0, [10, 11])
@@ -968,8 +1198,8 @@ def test_runtime_prompt_write_failure_does_not_publish_partial_file(tmp_path, mo
def test_runtime_prompt_files_are_isolated_between_model_instances(tmp_path, monkeypatch):
monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
first_model, _ = _model()
second_model, _ = _model()
first_model, _ = _model(runtime_prompt_cache_size=0)
second_model, _ = _model(runtime_prompt_cache_size=0)
reference = torch.tensor([0.0, 0.25, -0.25, 0.0])
def runtime_ref_info(request_id: str):
@@ -1276,7 +1506,7 @@ def test_cleanup_uses_generation_runner_internal_request_ids():
def test_reference_voice_and_duplex_metadata_follow_request_lifecycle():
model, _ = _model()
model, _ = _model(runtime_prompt_cache_size=0)
first = _info("voice-a", 0, [1, 2])
first["codes"]["ref"] = torch.linspace(-0.1, 0.1, 160)
segment_text_utf8 = torch.tensor(list(b"hello"), dtype=torch.uint8)
@@ -1366,6 +1596,45 @@ def _padded_decode_adapter(bucket_frames: int) -> tuple[BatchedToken2Wav, int, i
return adapter, mel_frames, pad_frames
@pytest.mark.parametrize("disable_during_setup", [False, True], ids=["after-setup", "during-setup"])
def test_setup_cache_misses_when_cfm_graph_padding_is_disabled(monkeypatch, disable_during_setup):
adapter, _, _ = _padded_decode_adapter(bucket_frames=16)
adapter.flow.decoder.rand_noise = torch.randn(1, 1, 400)
prompt = batched_token2wav_module.PromptFeatures(
cache_key=("voice", "voice.wav"),
# The fake encoder consumes one of the three appended lookahead tokens.
speech_tokens=torch.full((1, 298), 5, dtype=torch.long),
speaker_embedding=torch.ones(1, 1),
mels=torch.ones(1, 300, 1),
)
wrapper = adapter._cfm_graph_wrapper
if disable_during_setup:
replay = wrapper.replay
def replay_then_disable(*args, **kwargs):
result = replay(*args, **kwargs)
wrapper.enabled = False
return result
monkeypatch.setattr(wrapper, "replay", replay_then_disable)
with torch.no_grad():
padded = adapter.setup_batch(prompt, 1)
assert padded[0].flow_cache["estimator_att_cache"].shape[4] == 304
padded_keys = list(adapter._setup_cache)
wrapper.enabled = False
unpadded = adapter.setup_batch(prompt, 1)
reused = adapter.setup_batch(prompt, 1)
assert unpadded[0].flow_cache["estimator_att_cache"].shape[4] == 300
assert unpadded[0] is not padded[0]
assert reused[0] is unpadded[0]
assert adapter.flow.encoder.calls == [1, 1]
assert padded_keys == [(prompt.cache_key, 1, 16)]
assert list(adapter._setup_cache) == [(prompt.cache_key, 1, 0)]
def test_padded_chunk_keeps_the_cross_chunk_caches_on_the_valid_boundary():
"""Caches the next chunk reads must not carry padding.
@@ -213,7 +213,7 @@ def test_batched_repetition_penalty_matches_rows_across_chunks(mocker) -> None:
],
dim=0,
)
bincount = mocker.spy(torch, "bincount")
zeros = mocker.spy(torch, "zeros")
actual = _apply_batched_repetition_penalty(
logits,
histories,
@@ -222,13 +222,35 @@ def test_batched_repetition_penalty_matches_rows_across_chunks(mocker) -> None:
)
assert torch.equal(actual, expected)
assert [call.kwargs["minlength"] for call in bincount.call_args_list] == [
assert [call.args[0] for call in zeros.call_args_list] == [
_REPETITION_PENALTY_CHUNK_SIZE * vocab_size,
_REPETITION_PENALTY_CHUNK_SIZE * vocab_size,
vocab_size,
]
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
def test_codec_penalty_keeps_per_row_values_without_host_scalar_reads(dtype, monkeypatch):
logits = torch.tensor([[-2, -1, 0, 1, 2]] * 4, dtype=dtype)
histories = [torch.tensor([1, 1, 4, 4]), torch.tensor([1, 1]), torch.tensor([3, 3]), torch.tensor([])]
penalties = torch.tensor([1.2, 1.0, 0.8, 1.05], dtype=dtype)
expected = torch.cat(
[
_reference_repetition_penalty(logits[i : i + 1], history, penalty=penalties[i], window_size=3)
for i, history in enumerate(histories)
]
)
def disallow_host_scalar(*args, **kwargs):
raise AssertionError("codec penalty must not read a GPU-dependent scalar on the host")
with monkeypatch.context() as patch:
patch.setattr(torch.Tensor, "__bool__", disallow_host_scalar)
patch.setattr(torch, "bincount", disallow_host_scalar)
actual = _apply_batched_repetition_penalty(logits, histories, penalty=penalties, window_size=3)
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
def test_scheduler_prompt_is_fully_blanked_for_penalties() -> None:
# The handoff path fills the prompt with 0s and the non-handoff path passes
# thinker token ids; neither is codec history, so every position is padded.
@@ -661,6 +683,75 @@ def test_make_omni_output_packs_the_previous_codec_id() -> None:
assert _routed(output, 0)["meta"]["finished"].item() is False
@pytest.mark.parametrize("device", ["cpu", "cuda"])
def test_make_omni_output_reads_history_from_runner_cpu_buffer(monkeypatch, device) -> None:
if device == "cuda" and not torch.cuda.is_available():
pytest.skip("requires CUDA codec output")
from types import SimpleNamespace
from vllm_omni.worker.gpu_model_runner import OmniGPUModelRunner
talker = _make_talker()
talker.emb_code = nn.ModuleList([nn.Embedding(8, 2, device=device)])
talker.gpu_resident_buffer_keys = {("codes", "audio")}
model = MiniCPMO45OmniForConditionalGeneration.__new__(MiniCPMO45OmniForConditionalGeneration)
nn.Module.__init__(model)
model.model_stage = "tts"
model.model = model.talker = talker
state = {"finished": False, "step": 16, "recent_codes": [0] + [1] * 14 + [2]}
talker._request_audio_states["req"] = state
runner = object.__new__(OmniGPUModelRunner)
runner.model = model
runner.requests = {"req": SimpleNamespace(output_token_ids=[])}
runner.input_batch = SimpleNamespace(req_ids=["req"])
runner.model_intermediate_buffer = {"req": {"request_id": "req", "audio_state": state}}
_, _, updates = model.preprocess(
torch.tensor([3], dtype=torch.int32, device=device),
**runner.model_intermediate_buffer["req"],
)
assert updates["codes"]["audio"].device.type == "cpu"
assert updates["codes"]["audio"].dtype == torch.long
# The real outer model does not expose its Talker's GPU-resident keys.
runner._update_intermediate_buffer("req", updates)
infos = runner._gather_runtime_additional_information()
source = infos[0]["codes"]["audio"]
assert source.device.type == "cpu"
torch.testing.assert_close(source, torch.tensor([[3]], dtype=torch.long))
original_tolist = torch.Tensor.tolist
readback_devices = []
def cpu_only_tolist(tensor):
readback_devices.append(tensor.device.type)
assert tensor.device.type == "cpu", "codec history must use the CPU transport delta"
return original_tolist(tensor)
with monkeypatch.context() as patch:
patch.setattr(torch.Tensor, "tolist", cpu_only_tolist)
output = model.make_omni_output(
torch.ones(1, 2, device=device),
model_intermediate_buffer=infos,
request_token_spans=[(0, 1)],
)
assert readback_devices == ["cpu"]
emitted = output.multimodal_outputs["codes"]["audio"][0]
assert emitted.device.type == "cpu"
torch.testing.assert_close(emitted, source)
expected_codes = [1] * 14 + [2, 3]
assert state["step"] == 17
assert state["recent_codes"] == expected_codes
expected_history = torch.tensor(expected_codes, dtype=torch.long, device=device)
torch.testing.assert_close(talker._penalty_histories[0], expected_history.cpu())
logits = torch.arange(-4, 4, dtype=torch.float32, device=device).reshape(1, 8)
actual, _ = talker._apply_codec_repetition_penalty(
logits.clone(), _CodecSamplingMetadata(repetition_penalties=torch.tensor([1.05], device=device))
)
expected = _reference_repetition_penalty(logits, expected_history, penalty=1.05, window_size=_CODEC_PENALTY_WINDOW)
torch.testing.assert_close(actual, expected)
def test_talker_projects_request_aligned_duplex_metadata() -> None:
talker = _make_talker()
infos = [
@@ -742,6 +833,135 @@ def test_decode_preprocess_drops_codec_eos() -> None:
assert updates["codes"]["audio"].numel() == 0
@pytest.mark.parametrize("device", ["cpu", "cuda"])
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
@pytest.mark.parametrize("code_id", [0, 3, 7])
def test_cpu_codec_transport_preserves_embedding_and_owns_delta(device, dtype, code_id) -> None:
if device == "cuda" and not torch.cuda.is_available():
pytest.skip("requires CUDA embedding")
talker = _make_talker()
talker.emb_code = nn.ModuleList([nn.Embedding(8, 2, device=device, dtype=dtype)])
ids = torch.tensor([code_id], device=device, dtype=torch.int32)
expected_embeds = talker.emb_code[0](ids.to(dtype=torch.long))
state = {"finished": False, "step": 0}
# Factories must explicitly choose CPU even inside a non-CPU default device.
with torch.device("meta"):
returned_ids, embeds, updates = talker.preprocess(ids, None, request_id="req", audio_state=state)
delta = updates["codes"]["audio"]
assert returned_ids is ids
assert embeds.device == ids.device
torch.testing.assert_close(embeds, expected_embeds, rtol=0, atol=0)
assert delta.device.type == "cpu" and delta.dtype == torch.long
assert delta.shape == ((0,) if code_id == 7 else (1, 1))
assert delta.tolist() == ([] if code_id == 7 else [[code_id]])
assert state == {"finished": code_id == 7, "step": 0}
ids.fill_(5)
assert delta.tolist() == ([] if code_id == 7 else [[code_id]])
@pytest.mark.parametrize("use_snapshot", [False, True])
def test_cpu_codec_transport_routes_owned_payloads_with_hidden(monkeypatch, use_snapshot) -> None:
from types import SimpleNamespace
from tests.worker.test_gpu_ar_model_runner import _make_async_output_runner
from vllm_omni.model_executor.stage_input_processors.minicpmo_4_5_omni import _extract_codec_delta
from vllm_omni.worker.gpu_ar_model_runner import GPUARModelRunner, _snapshot_tensor_payload_to_cpu_async
talker = _make_talker()
req_ids = ["r2", "r1", "r3"]
codes = [torch.tensor([[0]]), torch.empty(0, dtype=torch.long), torch.tensor([[3]])]
talker._request_audio_states = {
"r2": {"finished": False, "step": 0},
"r1": {"finished": True, "step": 0},
"r3": {"finished": False, "step": 0},
}
hidden = torch.arange(6, dtype=torch.float32).reshape(3, 2)
model_output = talker.make_omni_output(
hidden,
model_intermediate_buffer=[
{"request_id": rid, "codes": {"audio": code}} for rid, code in zip(req_ids, codes, strict=True)
],
request_token_spans=[(0, 1), (1, 2), (2, 3)],
)
assert model_output.text_hidden_states is hidden
mm = model_output.multimodal_outputs
assert [value.device.type for value in mm["codes"]["audio"]] == ["cpu"] * 3
assert [value.shape for value in mm["codes"]["audio"]] == [(1, 1), (0, 1), (1, 1)]
if use_snapshot:
snapshot = _snapshot_tensor_payload_to_cpu_async(
{"hidden_states": hidden, "multimodal_outputs": mm}, copy_stream=None, pin_memory=False
)
assert snapshot._ready_event is None
snapshot.wait()
mm = snapshot.payload["multimodal_outputs"]
codes[0].fill_(6)
assert mm["codes"]["audio"][0].tolist() == [[0]]
runner = _make_async_output_runner(engine_output_type="latent")
assert runner._pooler_payload_include_hidden_flag is True
runner.requests = {rid: object() for rid in req_ids}
monkeypatch.setattr(GPUARModelRunner, "_resolve_pooler_payload_req_ids", lambda self, ids: ("latent", ids))
monkeypatch.setattr(GPUARModelRunner, "_should_accumulate_full_payload_output", lambda self: False)
monkeypatch.setattr(GPUARModelRunner, "get_omni_connector_output", lambda self: None)
monkeypatch.setattr(GPUARModelRunner, "_process_additional_information_updates", lambda *args, **kwargs: None)
output = runner._build_omni_model_runner_output_from_snapshot(
scheduler_output=SimpleNamespace(total_num_scheduled_tokens=3, num_scheduled_tokens=dict.fromkeys(req_ids, 1)),
hidden_states=hidden,
staged_hidden_states_cpu=None,
multimodal_outputs=mm,
req_ids_output_copy=req_ids,
req_id_to_index_output_copy={rid: index for index, rid in enumerate(req_ids)},
valid_sampled_token_ids=[[1], [7], [1]],
logprobs_lists=None,
prompt_logprobs_dict={},
num_nans_in_logits=None,
kv_connector_output=None,
ec_connector_output=None,
cudagraph_stats=None,
kv_extracted_req_ids=None,
num_scheduled_tokens_np=torch.ones(3, dtype=torch.int32).numpy(),
query_start_loc_cpu=torch.arange(3),
)
for code in codes:
code.fill_(6)
for code in mm["codes"]["audio"]:
code.fill_(5)
talker.on_requests_finished(set(req_ids))
talker._flush_deferred_cleanup()
talker._request_audio_states["r2"] = {"finished": False, "step": 0}
extracted = [
_extract_codec_delta(payload, rid) for rid, payload in zip(req_ids, output.inter_stage_outputs, strict=True)
]
assert extracted == [[0], [], [3]]
assert [payload["meta.finished"].item() for payload in output.inter_stage_outputs] == [False, True, False]
assert all(payload["codes.audio"].device.type == "cpu" for payload in output.inter_stage_outputs)
for index, payload in enumerate(output.inter_stage_outputs):
torch.testing.assert_close(payload["hidden"], hidden[index : index + 1])
@pytest.mark.parametrize("device", ["cpu", "cuda"])
def test_cpu_codec_transport_accepts_direct_device_source(device) -> None:
if device == "cuda" and not torch.cuda.is_available():
pytest.skip("requires CUDA codec source")
talker = _make_talker()
hidden = torch.ones(1, 2, device=device)
output = talker.make_omni_output(
hidden,
model_intermediate_buffer=[
{"request_id": "req", "codes": {"audio": torch.tensor([[0]], device=device, dtype=torch.int32)}}
],
request_token_spans=[(0, 1)],
)
assert output.text_hidden_states is hidden
delta = output.multimodal_outputs["codes"]["audio"][0]
assert delta.device.type == "cpu" and delta.dtype == torch.long
assert delta.tolist() == [[0]]
assert talker._request_audio_states["req"]["recent_codes"] == [0]
assert talker._request_audio_states["req"]["step"] == 1
assert talker._penalty_histories[0].tolist() == [0]
assert not output.multimodal_outputs["meta"]["finished"][0].item()
def test_missing_conditioning_fails_clearly() -> None:
talker = _make_talker()
@@ -773,6 +993,8 @@ def test_empty_speech_segment_finishes_without_sampling_codes() -> None:
assert torch.equal(embeds, talker.emb_text(torch.tensor([5, 6])))
assert updates["audio_state"]["finished"] is True
assert updates["codes"]["audio"].numel() == 0
assert updates["codes"]["audio"].device.type == "cpu"
assert updates["codes"]["audio"].shape == (0,)
# min_tokens can keep scheduling leftover decode rows after an empty
# speech segment. Those rows have no previous codec id to embed.
@@ -785,6 +1007,8 @@ def test_empty_speech_segment_finishes_without_sampling_codes() -> None:
assert decode_embeds.shape == (1, 4)
assert decode_updates["codes"]["audio"].numel() == 0
assert decode_updates["codes"]["audio"].device.type == "cpu"
assert decode_updates["codes"]["audio"].shape == (0,)
def test_chunked_prefill_tail_aligns_condition_with_prompt_length(mocker) -> None: