From 5078c7ad66c393f16bf9092c2a66d1c179354008 Mon Sep 17 00:00:00 2001 From: Zhichao Zhang <60429419+smartDream-chao@users.noreply.github.com> Date: Wed, 9 Sep 2026 09:38:11 +0800 Subject: [PATCH] [Bugfix][MiMo-Audio] Align code2wav decode with tokenizer device (#6539) Signed-off-by: chaosansui Signed-off-by: Zhichao Zhang <60429419+smartDream-chao@users.noreply.github.com> --- .../test_mimo_audio_code2wav_batch_decode.py | 6 +- .../test_mimo_audio_tokenizer_worker_cache.py | 115 ++++++++++++++++++ .../models/mimo_audio/mimo_audio_code2wav.py | 61 ++++++---- 3 files changed, 160 insertions(+), 22 deletions(-) create mode 100644 tests/model_executor/models/mimo_audio/test_mimo_audio_tokenizer_worker_cache.py diff --git a/tests/model_executor/models/mimo_audio/test_mimo_audio_code2wav_batch_decode.py b/tests/model_executor/models/mimo_audio/test_mimo_audio_code2wav_batch_decode.py index 194a024db..c20ee7f48 100644 --- a/tests/model_executor/models/mimo_audio/test_mimo_audio_code2wav_batch_decode.py +++ b/tests/model_executor/models/mimo_audio/test_mimo_audio_code2wav_batch_decode.py @@ -91,7 +91,11 @@ def _minimal_model(mocker: MockerFixture): decoder=decoder, config=SimpleNamespace(avg_pooler=2, stride_size=2, hop_length=240), ) - model._tokenizer_service = SimpleNamespace(audio_tokenizer=audio_tok, cuda_graph_wrapper=None) + model._tokenizer_service = SimpleNamespace( + audio_tokenizer=audio_tok, + cuda_graph_wrapper=None, + device="cpu", + ) return model, audio_tok diff --git a/tests/model_executor/models/mimo_audio/test_mimo_audio_tokenizer_worker_cache.py b/tests/model_executor/models/mimo_audio/test_mimo_audio_tokenizer_worker_cache.py new file mode 100644 index 000000000..06b16f853 --- /dev/null +++ b/tests/model_executor/models/mimo_audio/test_mimo_audio_tokenizer_worker_cache.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Regression tests for the MiMo-Audio tokenizer-worker cache key. + +The worker cache key used to keep only the device *type*, so an explicit +``MIMO_AUDIO_TOKENIZER_DEVICE=cuda:1`` silently loaded the tokenizer on the +process's current CUDA device and shared one cache entry with ``cuda:0``. +The index must survive both the cache key and the worker constructor. + +CPU-only and weight-free: the worker class is replaced by a stub so no +tokenizer weights are loaded. +""" + +from __future__ import annotations + +import functools + +import pytest + +torch = pytest.importorskip("torch") + +pytestmark = [pytest.mark.core_model, pytest.mark.cpu] + +_TOK_PATH = "/models/mimo-audio-tokenizer" + + +@functools.lru_cache(maxsize=1) +def _code2wav_module(): + """Defer the import (pulls vLLM model_executor) until first use.""" + from vllm_omni.model_executor.models.mimo_audio import mimo_audio_code2wav + + return mimo_audio_code2wav + + +class _StubWorker: + def __init__(self, device_str: str, config_path: str | None, audio_tokenizer_path: str): + self.device = device_str + self.config_path = config_path + self.audio_tokenizer_path = audio_tokenizer_path + + +@pytest.fixture +def isolated_worker_cache(monkeypatch): + """Empty worker cache with the real worker replaced by a stub.""" + mod = _code2wav_module() + monkeypatch.setattr(mod, "MiMoAudioTokenizerWorker", _StubWorker) + monkeypatch.setattr(mod, "_TOKENIZER_WORKER_CACHE", {}) + return mod + + +@pytest.mark.parametrize("device", [torch.device("cuda:1"), "cuda:1"]) +def test_cache_key_keeps_cuda_index(device): + """Both torch.device and string spellings retain the index.""" + mod = _code2wav_module() + key = mod._normalize_tokenizer_worker_cache_key(device, None, _TOK_PATH) + assert key[0] == "cuda:1" + + +def test_cache_key_cpu_unchanged(): + mod = _code2wav_module() + key = mod._normalize_tokenizer_worker_cache_key(torch.device("cpu"), None, _TOK_PATH) + assert key[0] == "cpu" + + +def test_cache_key_bare_cuda_resolves_to_current_device(monkeypatch): + """A bare "cuda" shares the entry with its equivalent indexed spelling.""" + mod = _code2wav_module() + monkeypatch.setattr(torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(torch.accelerator, "current_device_index", lambda: 3) + + bare = mod._normalize_tokenizer_worker_cache_key(torch.device("cuda"), None, _TOK_PATH) + indexed = mod._normalize_tokenizer_worker_cache_key(torch.device("cuda:3"), None, _TOK_PATH) + assert bare[0] == "cuda:3" + assert bare == indexed + + +def test_worker_constructed_on_requested_index(isolated_worker_cache): + mod = isolated_worker_cache + worker = mod.get_tokenizer_worker( + device=torch.device("cuda:1"), + config_path=None, + audio_tokenizer_path=_TOK_PATH, + ) + assert worker.device == "cuda:1" + + +def test_distinct_cuda_indices_get_distinct_workers(isolated_worker_cache): + mod = isolated_worker_cache + first = mod.get_tokenizer_worker( + device=torch.device("cuda:0"), + config_path=None, + audio_tokenizer_path=_TOK_PATH, + ) + second = mod.get_tokenizer_worker( + device=torch.device("cuda:1"), + config_path=None, + audio_tokenizer_path=_TOK_PATH, + ) + assert first is not second + assert (first.device, second.device) == ("cuda:0", "cuda:1") + + +def test_same_device_reuses_cached_worker(isolated_worker_cache): + mod = isolated_worker_cache + first = mod.get_tokenizer_worker( + device=torch.device("cuda:1"), + config_path=None, + audio_tokenizer_path=_TOK_PATH, + ) + second = mod.get_tokenizer_worker( + device="cuda:1", + config_path=None, + audio_tokenizer_path=_TOK_PATH, + ) + assert first is second diff --git a/vllm_omni/model_executor/models/mimo_audio/mimo_audio_code2wav.py b/vllm_omni/model_executor/models/mimo_audio/mimo_audio_code2wav.py index 019670cf9..5423788a0 100644 --- a/vllm_omni/model_executor/models/mimo_audio/mimo_audio_code2wav.py +++ b/vllm_omni/model_executor/models/mimo_audio/mimo_audio_code2wav.py @@ -99,8 +99,10 @@ class MiMoAudioTokenizerWorker: self.audio_tokenizer.config.nfft, ) mel_start = time.monotonic() - self.mel_transform = ( - MelSpectrogram( + # Build on CPU first: torchaudio MelSpectrogram init can mix CPU/CUDA + # tensors on newer PyTorch when default device is CUDA. + with torch.device("cpu"): + self.mel_transform = MelSpectrogram( sample_rate=self.audio_tokenizer.config.sampling_rate, n_fft=self.audio_tokenizer.config.nfft, hop_length=self.audio_tokenizer.config.hop_length, @@ -110,10 +112,9 @@ class MiMoAudioTokenizerWorker: n_mels=self.audio_tokenizer.config.n_mels, power=1.0, center=True, - ) - .to(self.device) - .to(torch.float32) - ) + ).to(torch.float32) + if self.device != "cpu": + self.mel_transform = self.mel_transform.to(self.device) logger.info( "[tokenizer worker] MelSpectrogram ready in %.2fs", time.monotonic() - mel_start, @@ -382,12 +383,19 @@ def extract_audio_code_tensor( def _normalize_tokenizer_worker_cache_key( - device: torch.device, + device: torch.device | str, config_path: str | None, audio_tokenizer_path: str, ) -> tuple[str, str, str]: """Normalize cache key so that same tokenizer always hits the same cache entry.""" - device_type = device.type if isinstance(device, torch.device) else str(device).split(":")[0] + dev = device if isinstance(device, torch.device) else torch.device(str(device)) + # Keep the index: an explicit "cuda:1" must not collapse onto the process's + # current CUDA device. Resolve a bare "cuda" so it shares the cache entry + # with the equivalent indexed spelling. + if dev.type == "cuda" and dev.index is None and torch.cuda.is_available(): + # Repo bans torch.cuda.current_device; match mimo_audio.py. + dev = torch.device("cuda", torch.accelerator.current_device_index()) + device_key = str(dev) # Use realpath so symlinks / trailing slash don't create duplicate entries ap = audio_tokenizer_path or "" if ap and os.path.exists(ap): @@ -398,22 +406,21 @@ def _normalize_tokenizer_worker_cache_key( if not cp and ap: cp = os.path.dirname(ap) - return (device_type, cp, ap) + return (device_key, cp, ap) _TOKENIZER_WORKER_CACHE: dict[tuple[str, str, str], MiMoAudioTokenizerWorker] = {} def get_tokenizer_worker( - device: torch.device, - config_path: str, + device: torch.device | str, + config_path: str | None, audio_tokenizer_path: str, ) -> MiMoAudioTokenizerWorker: key = _normalize_tokenizer_worker_cache_key(device, config_path, audio_tokenizer_path) if key not in _TOKENIZER_WORKER_CACHE: - device_type = key[0] _TOKENIZER_WORKER_CACHE[key] = MiMoAudioTokenizerWorker( - device_str=device_type, + device_str=key[0], config_path=config_path, audio_tokenizer_path=audio_tokenizer_path, ) @@ -469,8 +476,14 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): or self.config.name_or_path ) + _tok_dev = os.environ.get("MIMO_AUDIO_TOKENIZER_DEVICE") + if _tok_dev: + tokenizer_device = torch.device("cpu" if _tok_dev.lower() == "cpu" else _tok_dev) + else: + tokenizer_device = self.device + self._tokenizer_service: MiMoAudioTokenizerWorker | None = get_tokenizer_worker( - device=self.device, + device=tokenizer_device, config_path=self.tokenizer_config_path, audio_tokenizer_path=self.audio_tokenizer_path, ) @@ -723,7 +736,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): Instead of calling _decode_waveform_from_codes per request (which incurs 4 GPU↔CPU round-trips each), this method: 1. Extracts audio_codes for all valid requests on CPU (cheap). - 2. Runs quantizer.decode_vq (embedding lookup) for each on GPU. + 2. Runs quantizer.decode_vq (embedding lookup) on the tokenizer device. 3. Packs all hidden-states into one tensor and calls decoder(packed_hs, input_lengths) once. 4. Splits the output waveforms back to per-request tensors. @@ -734,6 +747,9 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): return [empty] tokenizer = self._tokenizer_service.audio_tokenizer + # Codes/weights must share the tokenizer device (may be CPU via + # MIMO_AUDIO_TOKENIZER_DEVICE), not the stage CUDA device. + tok_device = torch.device(self._tokenizer_service.device) group_size = self.streamer_config.group_size audio_channels = self.streamer_config.audio_channels @@ -768,7 +784,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): use_cuda_graph = cg_ready and len(extracted) == 1 if use_cuda_graph: - wav_out = cg_wrapper.decode(extracted[0][1].to(self.device)) + wav_out = cg_wrapper.decode(extracted[0][1].to(tok_device)) wav = wav_out.squeeze(0).squeeze(0) cfg = tokenizer.config frames_per_token = cfg.avg_pooler * cfg.stride_size * cfg.hop_length @@ -782,7 +798,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): hidden_list: list[torch.Tensor] = [] lengths: list[int] = [] for _, audio_codes in extracted: - hs = tokenizer.encoder.decode_vq(audio_codes.to(self.device)) + hs = tokenizer.encoder.decode_vq(audio_codes.to(tok_device)) hidden_list.append(hs) lengths.append(hs.size(0)) @@ -790,7 +806,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): packed_hs = hidden_list[0] else: packed_hs = torch.cat(hidden_list, dim=0) - input_lengths = torch.tensor(lengths, device=self.device) + input_lengths = torch.tensor(lengths, device=tok_device) recon_wav = tokenizer.decoder(packed_hs, input_lengths) @@ -831,6 +847,9 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): return [empty] tokenizer = self._tokenizer_service.audio_tokenizer + # Codes/weights must share the tokenizer device (may be CPU via + # MIMO_AUDIO_TOKENIZER_DEVICE), not the stage CUDA device. + tok_device = torch.device(self._tokenizer_service.device) group_size = self.streamer_config.group_size audio_channels = self.streamer_config.audio_channels @@ -886,7 +905,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): frames_per_token = cfg.avg_pooler * cfg.stride_size * cfg.hop_length if use_cuda_graph: - wav_out = cg_wrapper.decode(extracted[0][1].to(self.device)) + wav_out = cg_wrapper.decode(extracted[0][1].to(tok_device)) wav = wav_out.squeeze(0).squeeze(0) valid_len = extracted[0][1].shape[-1] * frames_per_token if wav.numel() > valid_len: @@ -903,7 +922,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): hidden_list: list[torch.Tensor] = [] lengths: list[int] = [] for _, audio_codes in extracted: - hs = tokenizer.encoder.decode_vq(audio_codes.to(self.device)) + hs = tokenizer.encoder.decode_vq(audio_codes.to(tok_device)) hidden_list.append(hs) lengths.append(hs.size(0)) @@ -911,7 +930,7 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP): packed_hs = hidden_list[0] else: packed_hs = torch.cat(hidden_list, dim=0) - input_lengths = torch.tensor(lengths, device=self.device) + input_lengths = torch.tensor(lengths, device=tok_device) recon_wav = tokenizer.decoder(packed_hs, input_lengths)