[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:
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:
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Mapping
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import dataclass
|
||||
@@ -111,6 +112,15 @@ def _zero_padded_cnn_cache(
|
||||
Padding is at most ``pad_frames`` wide, so only the trailing positions that
|
||||
can come from it are cleared; the valid part of the window is kept.
|
||||
"""
|
||||
blocks = estimator.blocks
|
||||
if pad_frames > 0 and blocks and len(blocks) == cnn_cache.shape[0]:
|
||||
width = int(cnn_cache.shape[-1])
|
||||
if width > 0 and all(int(block.conv.block[1].causal_padding[0]) == width for block in blocks):
|
||||
# _estimator_buffers packs equal-width blocks into one tensor.
|
||||
# Clear their shared tail with one write instead of one per block.
|
||||
cnn_cache[..., max(0, width - pad_frames) :] = 0.0
|
||||
return
|
||||
|
||||
for index, block in enumerate(estimator.blocks):
|
||||
width = int(block.conv.block[1].causal_padding[0])
|
||||
if width <= 0:
|
||||
@@ -191,6 +201,7 @@ def state_shape_signature(state: BatchedToken2WavState) -> tuple[Any, ...]:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromptFeatures:
|
||||
cache_key: tuple[str, str]
|
||||
speech_tokens: torch.Tensor
|
||||
speaker_embedding: torch.Tensor
|
||||
mels: torch.Tensor
|
||||
@@ -238,8 +249,11 @@ class BatchedToken2Wav(nn.Module):
|
||||
hift_graph_config: Mapping[str, Any] | None = None,
|
||||
cfm_graph_config: Mapping[str, Any] | None = None,
|
||||
bfloat16_attention_cache: bool = False,
|
||||
setup_cache_size: int = 1,
|
||||
):
|
||||
super().__init__()
|
||||
if setup_cache_size < 0:
|
||||
raise ValueError("setup_cache_size must be >= 0")
|
||||
self._token2wav = token2wav
|
||||
# Optional TrtDiTStepper (step_audio2_dit_trt): replaces only the
|
||||
# per-timestep DiT estimator call; encoder and HiFT stay on torch.
|
||||
@@ -335,6 +349,10 @@ class BatchedToken2Wav(nn.Module):
|
||||
self._cfm_graph_bucket_frames,
|
||||
)
|
||||
self._prompt_features: dict[tuple[str, str], PromptFeatures] = {}
|
||||
self._setup_cache_size = setup_cache_size
|
||||
self._setup_cache: OrderedDict[tuple[tuple[str, str], int, int], tuple[BatchedToken2WavState, ...]] = (
|
||||
OrderedDict()
|
||||
)
|
||||
|
||||
def _hift_inference(
|
||||
self,
|
||||
@@ -360,6 +378,7 @@ class BatchedToken2Wav(nn.Module):
|
||||
finally:
|
||||
torch.set_default_dtype(previous_dtype)
|
||||
cached = PromptFeatures(
|
||||
cache_key=cache_key,
|
||||
speech_tokens=values[0],
|
||||
speaker_embedding=values[2],
|
||||
mels=values[3],
|
||||
@@ -368,8 +387,12 @@ class BatchedToken2Wav(nn.Module):
|
||||
return cached
|
||||
|
||||
def evict_prompt(self, prompt_cache_id: str, prompt_wav: str) -> None:
|
||||
"""Release request-owned prompt features after stream completion."""
|
||||
self._prompt_features.pop((prompt_cache_id, prompt_wav), None)
|
||||
"""Release all cached artifacts associated with one prompt."""
|
||||
prompt_key = (prompt_cache_id, prompt_wav)
|
||||
self._prompt_features.pop(prompt_key, None)
|
||||
for setup_key in list(self._setup_cache):
|
||||
if setup_key[0] == prompt_key:
|
||||
self._setup_cache.pop(setup_key)
|
||||
|
||||
@staticmethod
|
||||
def _repeat_prompt(features: PromptFeatures, batch_size: int) -> tuple[torch.Tensor, ...]:
|
||||
@@ -871,7 +894,7 @@ class BatchedToken2Wav(nn.Module):
|
||||
"estimator_att_cache": estimator_att,
|
||||
}
|
||||
|
||||
def setup_batch(
|
||||
def _create_initial_states(
|
||||
self,
|
||||
features: PromptFeatures,
|
||||
batch_size: int,
|
||||
@@ -917,6 +940,27 @@ class BatchedToken2Wav(nn.Module):
|
||||
for row in split
|
||||
]
|
||||
|
||||
def setup_batch(self, features: PromptFeatures, batch_size: int) -> list[BatchedToken2WavState]:
|
||||
"""Reuse read-only prompt conditioning for the same shape and padding."""
|
||||
bucket_frames = (
|
||||
self._cfm_graph_bucket_frames
|
||||
if self._cfm_graph_wrapper is not None and self._cfm_graph_wrapper.enabled
|
||||
else 0
|
||||
)
|
||||
# Capture the policy before setup: graph capture may disable the wrapper
|
||||
# after padding has already been chosen for these initial states.
|
||||
cache_key = (features.cache_key, batch_size, bucket_frames)
|
||||
cached = self._setup_cache.get(cache_key)
|
||||
if cached is not None:
|
||||
self._setup_cache.move_to_end(cache_key)
|
||||
return list(cached)
|
||||
states = self._create_initial_states(features, batch_size)
|
||||
if self._setup_cache_size > 0:
|
||||
self._setup_cache[cache_key] = tuple(states)
|
||||
while len(self._setup_cache) > self._setup_cache_size:
|
||||
self._setup_cache.popitem(last=False)
|
||||
return states
|
||||
|
||||
@staticmethod
|
||||
def _fade_in_out(
|
||||
speech: torch.Tensor,
|
||||
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
@@ -247,12 +248,18 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
self._model_revision = getattr(vllm_config.model_config, "revision", None)
|
||||
self.backend: BatchedToken2Wav | None = None
|
||||
self._states: dict[str, _RequestState] = {}
|
||||
self._runtime_prompts: dict[str, _RuntimePrompt] = {}
|
||||
self._runtime_prompts: OrderedDict[str, _RuntimePrompt] = OrderedDict()
|
||||
self._request_prompt_keys: dict[str, str] = {}
|
||||
self._runtime_prompt_dir = tempfile.TemporaryDirectory(
|
||||
prefix="minicpmo45-runtime-prompts-",
|
||||
)
|
||||
extra = self._extra_config()
|
||||
self._runtime_prompt_cache_size = int(extra.get("token2wav_runtime_prompt_cache_size", 4))
|
||||
if self._runtime_prompt_cache_size < 0:
|
||||
raise ValueError("MiniCPM-o Code2Wav runtime prompt cache capacity must be >= 0")
|
||||
self._setup_cache_size = int(extra.get("token2wav_setup_cache_size", 1))
|
||||
if self._setup_cache_size < 0:
|
||||
raise ValueError("MiniCPM-o Code2Wav setup cache capacity must be >= 0")
|
||||
self._connector_config = {
|
||||
"codec_chunk_frames": int(extra.get("codec_chunk_frames", 25)),
|
||||
"codec_left_context_frames": int(extra.get("codec_left_context_frames", 3)),
|
||||
@@ -374,6 +381,8 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
if entry is None:
|
||||
entry = _RuntimePrompt(cache_id=cache_id, path=path, owners=set())
|
||||
self._runtime_prompts[cache_key] = entry
|
||||
else:
|
||||
self._runtime_prompts.move_to_end(cache_key)
|
||||
prompt_path = Path(entry.path)
|
||||
if not prompt_path.is_file():
|
||||
with tempfile.NamedTemporaryFile(
|
||||
@@ -437,8 +446,9 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
if entry is None:
|
||||
return
|
||||
entry.owners.discard(state_id)
|
||||
if entry.owners:
|
||||
return
|
||||
self._trim_runtime_prompts()
|
||||
|
||||
def _evict_runtime_prompt(self, cache_key: str, entry: _RuntimePrompt) -> None:
|
||||
if self.backend is not None:
|
||||
self.backend.evict_prompt(entry.cache_id, entry.path)
|
||||
Path(entry.path).unlink(missing_ok=True)
|
||||
@@ -450,21 +460,25 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
if cache_key is None:
|
||||
continue
|
||||
previous_key = self._request_prompt_keys.get(item.state_id)
|
||||
if previous_key != cache_key:
|
||||
self._release_request_prompt(item.state_id)
|
||||
entry = self._runtime_prompts.get(cache_key)
|
||||
if entry is not None:
|
||||
entry.owners.add(item.state_id)
|
||||
self._request_prompt_keys[item.state_id] = cache_key
|
||||
|
||||
def _prune_unowned_runtime_prompts(self) -> None:
|
||||
for cache_key, entry in list(self._runtime_prompts.items()):
|
||||
if entry.owners:
|
||||
if entry is None:
|
||||
continue
|
||||
if self.backend is not None:
|
||||
self.backend.evict_prompt(entry.cache_id, entry.path)
|
||||
Path(entry.path).unlink(missing_ok=True)
|
||||
self._runtime_prompts.pop(cache_key, None)
|
||||
if previous_key != cache_key:
|
||||
previous = self._runtime_prompts.get(previous_key) if previous_key is not None else None
|
||||
if previous is not None:
|
||||
previous.owners.discard(item.state_id)
|
||||
entry.owners.add(item.state_id)
|
||||
self._request_prompt_keys[item.state_id] = cache_key
|
||||
self._runtime_prompts.move_to_end(cache_key)
|
||||
self._trim_runtime_prompts()
|
||||
|
||||
def _trim_runtime_prompts(self) -> None:
|
||||
"""Evict least-recent unowned references, never request-owned state."""
|
||||
while len(self._runtime_prompts) > self._runtime_prompt_cache_size:
|
||||
victim = next(((key, entry) for key, entry in self._runtime_prompts.items() if not entry.owners), None)
|
||||
if victim is None:
|
||||
return
|
||||
self._evict_runtime_prompt(*victim)
|
||||
|
||||
@staticmethod
|
||||
def _split_segments(input_ids: torch.Tensor, counts: Any) -> list[torch.Tensor]:
|
||||
@@ -760,11 +774,11 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
)
|
||||
items.append(self._parse_item(index, str(state_id), segment, info))
|
||||
except Exception:
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
raise
|
||||
state_ids = [item.state_id for item in items]
|
||||
if len(state_ids) != len(set(state_ids)):
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
raise _batch_error("duplicate_request_in_forward", request_ids=state_ids)
|
||||
outputs = [empty for _ in segments]
|
||||
sentinels = [item for item in items if item.last_chunk and item.tokens.numel() == 0]
|
||||
@@ -778,7 +792,7 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
if item.has_payload and not item.last_chunk and not item.tts_is_last_chunk and item.tokens.numel() == 0
|
||||
]
|
||||
if invalid_empty:
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
raise _batch_error("empty_nonfinal_chunk", request_ids=invalid_empty)
|
||||
|
||||
buckets: dict[tuple[Any, ...], list[_WorkItem]] = {}
|
||||
@@ -794,7 +808,7 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
if len(bucket) < self._min_batch_size
|
||||
]
|
||||
if undersized:
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
raise _batch_error(
|
||||
"exact_shape_bucket_below_minimum",
|
||||
minimum=self._min_batch_size,
|
||||
@@ -833,7 +847,7 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
)
|
||||
states = self.backend.setup_batch(features, len(bucket))
|
||||
except Exception as exc:
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
if isinstance(exc, RuntimeError) and str(exc).startswith("MiniCPMO45Code2WavBatchError "):
|
||||
raise
|
||||
raise _batch_error(
|
||||
@@ -843,7 +857,7 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
error=str(exc),
|
||||
) from exc
|
||||
if len(states) != len(bucket):
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
raise _batch_error(
|
||||
"backend_result_size_mismatch",
|
||||
expected=len(bucket),
|
||||
@@ -886,7 +900,7 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
last_chunk=bucket[0].last_chunk,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
if isinstance(exc, RuntimeError) and str(exc).startswith("MiniCPMO45Code2WavBatchError "):
|
||||
raise
|
||||
raise _batch_error(
|
||||
@@ -896,7 +910,7 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
error=str(exc),
|
||||
) from exc
|
||||
if len(audios) != batch_size or len(next_states) != batch_size:
|
||||
self._prune_unowned_runtime_prompts()
|
||||
self._trim_runtime_prompts()
|
||||
raise _batch_error(
|
||||
"backend_result_size_mismatch",
|
||||
expected=batch_size,
|
||||
@@ -1034,4 +1048,5 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
hift_graph_config=self._hift_graph_config,
|
||||
cfm_graph_config=self._cfm_graph_config,
|
||||
bfloat16_attention_cache=bool(extra.get("code2wav_bfloat16_attention_cache", False)),
|
||||
setup_cache_size=self._setup_cache_size,
|
||||
)
|
||||
@@ -130,27 +130,29 @@ def _apply_batched_repetition_penalty(
|
||||
penalties = penalties.expand(batch_size)
|
||||
elif penalties.numel() != batch_size:
|
||||
raise ValueError(f"expected 1 or {batch_size} codec repetition penalties, got {penalties.numel()}")
|
||||
if not bool((penalties != 1.0).any()):
|
||||
return logits
|
||||
|
||||
penalized = logits.clone()
|
||||
for start in range(0, batch_size, _REPETITION_PENALTY_CHUNK_SIZE):
|
||||
end = min(start + _REPETITION_PENALTY_CHUNK_SIZE, batch_size)
|
||||
chunk_logits = logits[start:end]
|
||||
chunk_histories = histories[start:end]
|
||||
# The runner keeps codec history on the CPU. Pack it before uploading
|
||||
# instead of transferring one small tensor per request on every step.
|
||||
history_device = "cpu" if all(history.device.type == "cpu" for history in chunk_histories) else logits.device
|
||||
encoded_rows: list[torch.Tensor] = []
|
||||
for local_row, history in enumerate(histories[start:end]):
|
||||
recent = history.reshape(-1)[-window_size:].to(device=logits.device, dtype=torch.long)
|
||||
for local_row, history in enumerate(chunk_histories):
|
||||
recent = history.reshape(-1)[-window_size:].to(device=history_device, dtype=torch.long)
|
||||
if recent.numel() > 0:
|
||||
encoded_rows.append(recent + local_row * vocab_size)
|
||||
if not encoded_rows:
|
||||
continue
|
||||
|
||||
# Bound the int64 bincount workspace independently of request concurrency.
|
||||
# The vocabulary fixes the output size. CUDA bincount still reads the
|
||||
# maximum id back to the host even when minlength is provided.
|
||||
encoded = encoded_rows[0] if len(encoded_rows) == 1 else torch.cat(encoded_rows)
|
||||
frequencies = torch.bincount(
|
||||
encoded,
|
||||
minlength=(end - start) * vocab_size,
|
||||
).reshape(end - start, vocab_size)
|
||||
encoded = encoded.to(device=logits.device)
|
||||
frequencies = torch.zeros((end - start) * vocab_size, dtype=torch.long, device=logits.device)
|
||||
frequencies.scatter_add_(0, encoded, torch.ones_like(encoded))
|
||||
frequencies = frequencies.reshape(end - start, vocab_size)
|
||||
alpha = torch.pow(penalties[start:end].unsqueeze(1), frequencies.to(dtype=logits.dtype))
|
||||
penalized[start:end] = torch.where(chunk_logits < 0, chunk_logits * alpha, chunk_logits / alpha)
|
||||
|
||||
@@ -537,7 +539,7 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
request_states = {}
|
||||
self._request_audio_states = request_states
|
||||
request_states[request_id] = state
|
||||
empty_codes = torch.empty(0, dtype=torch.long, device=embeds.device)
|
||||
empty_codes = torch.empty(0, dtype=torch.long, device="cpu")
|
||||
return (
|
||||
input_ids,
|
||||
embeds,
|
||||
@@ -557,7 +559,7 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
# eligible. The sampler is forced to EOS; any shape-correct
|
||||
# embedding is enough for these leftover decode rows.
|
||||
weight = self.emb_code[0].weight
|
||||
empty_codes = torch.empty(0, dtype=torch.long, device=weight.device)
|
||||
empty_codes = torch.empty(0, dtype=torch.long, device="cpu")
|
||||
return input_ids, weight.new_zeros((span_len, weight.shape[1])), {"codes": {"audio": empty_codes}}
|
||||
|
||||
# Decode: vLLM's previous sampled codec id is this step's input.
|
||||
@@ -571,9 +573,11 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
state["finished"] = True
|
||||
elif stored is None:
|
||||
self._request_audio_states[request_id] = {"finished": True, "step": 0}
|
||||
delta = torch.empty(0, dtype=torch.long, device=code.device)
|
||||
delta = torch.empty(0, dtype=torch.long, device="cpu")
|
||||
else:
|
||||
delta = code.reshape(1, 1)
|
||||
# The runner and connector consume CPU IDs; reuse the scalar
|
||||
# already read for EOS instead of copying the same token again.
|
||||
delta = torch.tensor([[code_id]], dtype=torch.long, device="cpu")
|
||||
return input_ids, embeds, {"codes": {"audio": delta}}
|
||||
|
||||
def make_omni_output(
|
||||
@@ -595,12 +599,12 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
duplex_turn_ids: list[torch.Tensor] = []
|
||||
segment_texts_utf8: list[torch.Tensor] = []
|
||||
turn_end_flags: list[torch.Tensor] = []
|
||||
empty_delta = hidden.new_empty((0, 1), dtype=torch.long)
|
||||
empty_delta = torch.empty((0, 1), dtype=torch.long, device="cpu")
|
||||
codec_deltas = [empty_delta for _ in infos]
|
||||
terminal_flags = [torch.tensor(False, dtype=torch.bool) for _ in infos]
|
||||
force_eos_rows = [False] * len(infos)
|
||||
mask_eos_rows = [False] * len(infos)
|
||||
empty_history = hidden.new_empty((0,), dtype=torch.long)
|
||||
empty_history = torch.empty(0, dtype=torch.long, device="cpu")
|
||||
penalty_histories = [empty_history for _ in infos]
|
||||
for index, info in enumerate(infos):
|
||||
info_dict = info if isinstance(info, dict) else {}
|
||||
@@ -657,16 +661,17 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
codes = info.get("codes", {})
|
||||
audio = codes.get("audio") if isinstance(codes, Mapping) else None
|
||||
if isinstance(audio, torch.Tensor) and audio.numel() > 0:
|
||||
codec_deltas[index] = audio.to(device=hidden.device, dtype=torch.long).reshape(-1, 1)
|
||||
audio = audio.to(device="cpu", dtype=torch.long)
|
||||
codec_deltas[index] = audio.reshape(-1, 1)
|
||||
state["step"] = int(state.get("step", 0)) + 1
|
||||
# ``audio`` is the id sampled last step, i.e. exactly upstream's
|
||||
# ``new_tokens[:, 0:t]`` history for the logits computed below.
|
||||
recent = state.get("recent_codes")
|
||||
recent = (recent if isinstance(recent, list) else []) + codec_deltas[index].reshape(-1).tolist()
|
||||
recent = (recent if isinstance(recent, list) else []) + audio.reshape(-1).tolist()
|
||||
state["recent_codes"] = recent[-_CODEC_PENALTY_WINDOW:]
|
||||
recent_codes = state.get("recent_codes")
|
||||
if recent_codes:
|
||||
penalty_histories[index] = torch.tensor(recent_codes, dtype=torch.long, device=hidden.device)
|
||||
penalty_histories[index] = torch.tensor(recent_codes, dtype=torch.long, device="cpu")
|
||||
max_tokens = state.get("max_tokens")
|
||||
min_tokens = state.get("min_tokens")
|
||||
step = int(state.get("step", 0))
|
||||
|
||||
Reference in new issue
Block a user