[Hardware][Ascend][Model] Add NPU support for MiniCPM-o 4.5 talker/vo… (#5117)
Signed-off-by: amy-why-3459 <wuhaiyan17@huawei.com>
This commit is contained in:
1 parent
a06664a243
commit
74f2742ac2
11 files changed
+724
-62
No files matched your search
@@ -760,7 +760,12 @@ class MiniCPMVImageProcessor(BaseImageProcessor):
|
||||
)
|
||||
|
||||
|
||||
AutoImageProcessor.register("MiniCPMVImageProcessor", MiniCPMVImageProcessor)
|
||||
# transformers >= 5.x requires the config *class* (not a string) as the
|
||||
# first arg to AutoImageProcessor.register — it does `key.__module__`
|
||||
# internally. Passing "MiniCPMVImageProcessor" raises:
|
||||
# AttributeError: 'str' object has no attribute '__module__'
|
||||
# See also processing_gr00t_n1d7.py for the same transformers API change.
|
||||
AutoImageProcessor.register(MiniCPMOConfig, MiniCPMVImageProcessor, exist_ok=True)
|
||||
|
||||
|
||||
# ============== SigLIP Vision Transformer Classes ==============
|
||||
|
||||
@@ -15,6 +15,7 @@ Pipeline:
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from collections.abc import Iterable
|
||||
|
||||
import numpy as np
|
||||
@@ -27,13 +28,33 @@ from vllm.model_executor.models.interfaces import SupportsPP
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
try:
|
||||
from stepaudio2 import Token2wav as _Token2wav
|
||||
# Preserve the established external vocoder on CUDA. Ascend uses the in-tree
|
||||
# adapter because ``stepaudio2-minicpmo`` hard-codes CUDA device placement.
|
||||
if current_omni_platform.is_npu():
|
||||
try:
|
||||
from vllm_omni.model_executor.models.minicpmo_4_5.minicpmo_4_5_token2wav import (
|
||||
MiniCPMO45Token2wav as _Token2wav,
|
||||
)
|
||||
|
||||
_stepaudio2_available = True
|
||||
except ImportError:
|
||||
_Token2wav = None
|
||||
_stepaudio2_available = False
|
||||
_token2wav_backend = "step_audio2_core"
|
||||
except ImportError:
|
||||
try:
|
||||
from stepaudio2 import Token2wav as _Token2wav
|
||||
|
||||
_token2wav_backend = "stepaudio2_pkg"
|
||||
except ImportError:
|
||||
_Token2wav = None
|
||||
_token2wav_backend = None
|
||||
else:
|
||||
try:
|
||||
from stepaudio2 import Token2wav as _Token2wav
|
||||
|
||||
_token2wav_backend = "stepaudio2_pkg"
|
||||
except ImportError:
|
||||
_Token2wav = None
|
||||
_token2wav_backend = None
|
||||
|
||||
_stepaudio2_available = _Token2wav is not None
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -101,14 +122,25 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
return
|
||||
try:
|
||||
model_path = self.vllm_config.model_config.model
|
||||
import os
|
||||
import sys
|
||||
|
||||
if model_path not in sys.path:
|
||||
sys.path.insert(0, model_path)
|
||||
from transformers import AutoImageProcessor
|
||||
from transformers.dynamic_module_utils import get_class_from_dynamic_module
|
||||
|
||||
MiniCPMTTS = get_class_from_dynamic_module("modeling_minicpmo.MiniCPMTTS", model_path)
|
||||
# openbmb/MiniCPM-o-4_5/processing_minicpmo.py registers via a
|
||||
# string: AutoImageProcessor.register("MiniCPMVImageProcessor", ...),
|
||||
# which crashes on transformers>=5 (register reads key.__module__).
|
||||
# Loading MiniCPMTTS imports that module, so no-op the string form
|
||||
# (unused by the standalone talker) while it runs, then restore.
|
||||
original_register = AutoImageProcessor.register
|
||||
AutoImageProcessor.register = ( # type: ignore[method-assign]
|
||||
lambda key, *a, **k: None if isinstance(key, str) else original_register(key, *a, **k)
|
||||
)
|
||||
try:
|
||||
MiniCPMTTS = get_class_from_dynamic_module("modeling_minicpmo.MiniCPMTTS", model_path)
|
||||
finally:
|
||||
AutoImageProcessor.register = original_register # type: ignore[method-assign]
|
||||
|
||||
# MiniCPMTTS.__init__ reads `config.top_p / top_k / repetition_penalty`
|
||||
# directly (modeling_minicpmo.py L4112-4114), but the model repo's
|
||||
@@ -121,6 +153,11 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
if not hasattr(self._tts_config, _attr):
|
||||
setattr(self._tts_config, _attr, _default)
|
||||
|
||||
# The copied Hugging Face flash_attention_2 setting is not valid
|
||||
# for this standalone MiniCPMTTS path. Use PyTorch SDPA on every
|
||||
# backend until a dedicated flash-attention implementation exists.
|
||||
self._tts_config.attn_implementation = "sdpa"
|
||||
|
||||
prev_dtype = torch.get_default_dtype()
|
||||
torch.set_default_dtype(torch.float32)
|
||||
try:
|
||||
@@ -159,7 +196,11 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
finally:
|
||||
torch.set_default_dtype(prev_dtype2)
|
||||
self.tts_obj.audio_tokenizer = self.audio_tokenizer
|
||||
logger.info("Loaded Token2wav from %s", token2wav_dir)
|
||||
logger.info(
|
||||
"Loaded Token2wav from %s (backend=%s)",
|
||||
token2wav_dir,
|
||||
_token2wav_backend,
|
||||
)
|
||||
# Only mark init as complete after every step succeeds, so a
|
||||
# partial failure leaves the next call free to retry the full
|
||||
# init instead of short-circuiting back to a silent empty path.
|
||||
@@ -189,19 +230,25 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
|
||||
tts = self.tts_obj
|
||||
device = tts.emb_text.weight.device
|
||||
dtype = tts.emb_text.weight.dtype
|
||||
# MiniCPMTTS AR backbone uses FlashAttention (fp16/bf16 only). The
|
||||
# submodule is constructed under float32 default dtype during lazy init,
|
||||
# so pin the condition embeddings to bfloat16 explicitly rather than
|
||||
# inheriting the (float32) parameter dtype — a float32 condition breaks
|
||||
# the CUDA FA2 path and wastes memory on the NPU sdpa path.
|
||||
ar_dtype = torch.bfloat16
|
||||
|
||||
llm_embeds = tts.emb_text(tts_token_ids.to(device))
|
||||
hidden_embeds = tts.projector_semantic(tts_hidden_states.to(device=device, dtype=dtype))
|
||||
hidden_embeds = tts.projector_semantic(tts_hidden_states.to(device=device, dtype=ar_dtype))
|
||||
if getattr(tts.config, "normalize_projected_hidden", False):
|
||||
hidden_embeds = F.normalize(hidden_embeds, p=2, dim=-1)
|
||||
tts_embeds = llm_embeds + hidden_embeds
|
||||
tts_embeds = (llm_embeds + hidden_embeds).to(dtype=ar_dtype)
|
||||
|
||||
text_eos = tts.emb_text(torch.tensor([tts.config.text_eos_token_id], device=device, dtype=torch.long))
|
||||
audio_bos = tts.emb_text(torch.tensor([tts.audio_bos_token_id], device=device, dtype=torch.long))
|
||||
spk_embeds = torch.zeros(0, tts.config.hidden_size, device=device, dtype=tts_embeds.dtype)
|
||||
spk_embeds = torch.zeros(0, tts.config.hidden_size, device=device, dtype=ar_dtype)
|
||||
|
||||
inputs_embeds = torch.cat([spk_embeds, tts_embeds, text_eos, audio_bos], dim=0).unsqueeze(0)
|
||||
inputs_embeds = inputs_embeds.to(dtype=ar_dtype)
|
||||
logger.info("generate_speech: inputs_embeds shape=%s", list(inputs_embeds.shape))
|
||||
|
||||
# Scale max_new_token with input text length to avoid mid-stream truncation on long
|
||||
@@ -249,7 +296,15 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
prev_dtype = torch.get_default_dtype()
|
||||
torch.set_default_dtype(torch.float32)
|
||||
try:
|
||||
with torch.amp.autocast("cuda", enabled=False):
|
||||
# Vocoder path is float32; use the platform abstraction because
|
||||
# torch.amp.autocast validates unsupported device types even when
|
||||
# autocast is disabled.
|
||||
autocast_device = device.type if isinstance(device, torch.device) else str(device)
|
||||
with current_omni_platform.create_autocast_context(
|
||||
device_type=autocast_device,
|
||||
dtype=torch.float32,
|
||||
enabled=False,
|
||||
):
|
||||
token_list = generated_tokens.squeeze(0).tolist()
|
||||
num_tokens = len(token_list)
|
||||
|
||||
@@ -418,7 +473,17 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
return None, None
|
||||
|
||||
def compute_logits(self, hidden_states, *args, **kwargs):
|
||||
return torch.zeros(1, 2, device=hidden_states.device if isinstance(hidden_states, torch.Tensor) else "cuda")
|
||||
# Placeholder logits: one row per sampled request (the scheduler
|
||||
# indexes sampled_token_ids by req_index). Hardcoding a single row
|
||||
# breaks batched/concurrent decoding with IndexError. The values are
|
||||
# discarded — real output is the waveform via multimodal_outputs.
|
||||
if isinstance(hidden_states, torch.Tensor):
|
||||
device = hidden_states.device
|
||||
num_reqs = hidden_states.shape[0] if hidden_states.ndim >= 1 else 1
|
||||
else:
|
||||
device = current_omni_platform.get_torch_device()
|
||||
num_reqs = 1
|
||||
return torch.zeros(num_reqs, 2, device=device)
|
||||
|
||||
def sample(self, logits, sampling_metadata):
|
||||
return None
|
||||
@@ -442,10 +507,31 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
logger.warning("TTS missing keys (%d): %s", len(missing), missing[:5])
|
||||
if unexpected:
|
||||
logger.warning("TTS unexpected keys (%d): %s", len(unexpected), unexpected[:5])
|
||||
self.tts_obj = self.tts_obj.to("cuda")
|
||||
# Move the AR backbone to the active device (cuda / npu / …) and
|
||||
# cast to bfloat16: MiniCPMTTS AR uses FlashAttention (fp16/bf16
|
||||
# only) and is built under a float32 default dtype during lazy
|
||||
# init, so an uncast float32 backbone breaks CUDA FA2 and wastes
|
||||
# memory on the NPU sdpa path. Detach the Token2wav vocoder first
|
||||
# so the cast does not drag it onto the accelerator or downcast
|
||||
# its float32 flow/HiFT weights: it manages its own device
|
||||
# placement (e.g. CPU HiFT on NPU) and may not be an nn.Module.
|
||||
device = current_omni_platform.get_torch_device()
|
||||
audio_tok = getattr(self.tts_obj, "audio_tokenizer", None)
|
||||
if audio_tok is not None:
|
||||
self.tts_obj.audio_tokenizer = None
|
||||
try:
|
||||
self.tts_obj = self.tts_obj.to(device=device, dtype=torch.bfloat16)
|
||||
finally:
|
||||
if audio_tok is not None:
|
||||
self.tts_obj.audio_tokenizer = audio_tok
|
||||
self.audio_tokenizer = audio_tok
|
||||
self.emb_text = self.tts_obj.emb_text
|
||||
self.projector_semantic = self.tts_obj.projector_semantic
|
||||
logger.info("Loaded %d TTS weights, moved to cuda", len(tts_weights))
|
||||
logger.info(
|
||||
"Loaded %d TTS weights, moved to %s (bfloat16)",
|
||||
len(tts_weights),
|
||||
device,
|
||||
)
|
||||
|
||||
return loaded
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""MiniCPM-o 4.5 Token2wav adapter over in-tree ``StepAudio2Token2WavCore``.
|
||||
|
||||
``minicpmo_4_5_omni_tts`` historically depended on the external
|
||||
``from stepaudio2 import Token2wav`` entry point (``stepaudio2-minicpmo``).
|
||||
That package hard-codes ``.cuda()`` and duplicates the flow/HiFT stack that
|
||||
vLLM-Omni already vendors for Step-Audio2 (which also carries the Ascend/NPU
|
||||
fixes: CPU HiFT, DiT mask expand, MATH SDPA, compile disable, PE buffer
|
||||
extension).
|
||||
|
||||
This module exposes the same call surface MiniCPM expects
|
||||
(``__call__`` / ``set_stream_cache`` / ``stream``) while delegating the
|
||||
actual vocoder work to
|
||||
``vllm_omni.model_executor.models.step_audio2.step_audio2_token2wav.StepAudio2Token2WavCore``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.step_audio2.step_audio2_token2wav import (
|
||||
StepAudio2Token2WavCore,
|
||||
_StreamState,
|
||||
)
|
||||
|
||||
|
||||
def _resolve_device(device: str | torch.device | None) -> str:
|
||||
if device is not None:
|
||||
return str(device)
|
||||
try:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
plat_dev = getattr(current_omni_platform, "device_type", None)
|
||||
if plat_dev:
|
||||
return str(plat_dev)
|
||||
except Exception:
|
||||
pass
|
||||
if torch.cuda.is_available():
|
||||
return "cuda"
|
||||
if hasattr(torch, "npu") and torch.npu.is_available():
|
||||
return "npu"
|
||||
return "cpu"
|
||||
|
||||
|
||||
class MiniCPMO45Token2wav:
|
||||
"""Token2wav-compatible facade around ``StepAudio2Token2WavCore``.
|
||||
|
||||
Matches the MiniCPM-o / ``stepaudio2-minicpmo`` vocoder API used by
|
||||
``MiniCPMO45OmniTTSForConditionalGeneration.generate_speech``:
|
||||
|
||||
* ``Token2wav(model_path, float16=False, n_timesteps=10)``
|
||||
* ``__(tokens, prompt_wav) -> wav_bytes``
|
||||
* ``set_stream_cache(prompt_wav) -> (stream_cache, hift_cache_dict)``
|
||||
* ``stream(tokens, prompt_wav, last_chunk=..., return_waveform=...)``
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_path: str,
|
||||
float16: bool = False,
|
||||
n_timesteps: int = 10,
|
||||
device: str | torch.device | None = None,
|
||||
):
|
||||
self.float16 = float16
|
||||
self.n_timesteps = n_timesteps
|
||||
self.device = _resolve_device(device)
|
||||
self._core = StepAudio2Token2WavCore(
|
||||
model_path=model_path,
|
||||
float16=float16,
|
||||
device=self.device,
|
||||
n_timesteps=n_timesteps,
|
||||
)
|
||||
# Eager-load so construction failures surface at init time (same as
|
||||
# the external Token2wav package), not on the first request.
|
||||
self._core._ensure_models_loaded()
|
||||
|
||||
# Mutable streaming fields expected by MiniCPM's long-form path.
|
||||
self.stream_cache: Any | None = None
|
||||
self.hift_cache_dict: dict[str, torch.Tensor] = {}
|
||||
|
||||
def __call__(self, generated_speech_tokens, prompt_wav) -> bytes:
|
||||
"""One-shot tokens → 24 kHz WAV bytes."""
|
||||
return self._core.forward(
|
||||
generated_speech_tokens,
|
||||
prompt_wav,
|
||||
return_bytes=True,
|
||||
)
|
||||
|
||||
def set_stream_cache(self, prompt_wav: str):
|
||||
"""Initialise flow + HiFT caches for chunked vocoding.
|
||||
|
||||
Returns ``(stream_cache, hift_cache_dict)`` so callers can assign them
|
||||
back onto this object the way ``stepaudio2.Token2wav`` does.
|
||||
"""
|
||||
state = _StreamState()
|
||||
self._core.setup_stream_for(prompt_wav, state)
|
||||
self.stream_cache = state.stream_cache
|
||||
self.hift_cache_dict = state.hift_cache_dict
|
||||
return self.stream_cache, self.hift_cache_dict
|
||||
|
||||
def stream(
|
||||
self,
|
||||
generated_speech_tokens,
|
||||
prompt_wav: str,
|
||||
last_chunk: bool = False,
|
||||
return_waveform: bool = False,
|
||||
):
|
||||
"""Process one streaming chunk; updates ``stream_cache`` / ``hift_cache_dict``."""
|
||||
if self.stream_cache is None:
|
||||
raise ValueError("stream_cache is not set")
|
||||
|
||||
state = _StreamState()
|
||||
state.setup_done = True
|
||||
state.stream_cache = self.stream_cache
|
||||
state.hift_cache_dict = self.hift_cache_dict
|
||||
|
||||
speech = self._core.stream_chunk_for(
|
||||
list(generated_speech_tokens),
|
||||
prompt_wav,
|
||||
last_chunk,
|
||||
state,
|
||||
)
|
||||
self.stream_cache = state.stream_cache
|
||||
self.hift_cache_dict = state.hift_cache_dict
|
||||
|
||||
wav_np = speech.detach().float().cpu().numpy()
|
||||
if return_waveform:
|
||||
return wav_np
|
||||
|
||||
wav_np = np.clip(wav_np, -1.0, 1.0)
|
||||
wav_int16 = (wav_np * 32767.0).astype("<i2")
|
||||
return wav_int16.tobytes()
|
||||
@@ -95,6 +95,22 @@ class StepAudio2Token2WavCore(nn.Module):
|
||||
self.source_cache_len = STREAM_SOURCE_CACHE_LEN
|
||||
self.speech_window: torch.Tensor | None = None # created lazily on device
|
||||
|
||||
# On Ascend the talker worker never routes through
|
||||
# ``NPUOmniPlatform.set_device``, so gate on ``current_omni_platform``
|
||||
# and apply the Token2Wav NPU patch here (idempotent) before
|
||||
# ``_ensure_models_loaded`` runs. Covers every
|
||||
# construction site (Step-Audio2 wrapper + MiniCPM-o facade): patched
|
||||
# ``_ensure_models_loaded`` offloads HiFT to CPU and patched ``forward``
|
||||
# expands CosyVoice DiT masks + forces MATH SDPA (avoids FA 161001).
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
if current_omni_platform.is_npu():
|
||||
from vllm_omni.platforms.npu.models.step_audio2_token2wav import (
|
||||
apply_step_audio2_token2wav_npu_patch,
|
||||
)
|
||||
|
||||
apply_step_audio2_token2wav_npu_patch()
|
||||
|
||||
def _ensure_models_loaded(self):
|
||||
"""Lazy load models on first use"""
|
||||
if self._models_loaded:
|
||||
|
||||
Reference in new issue
Block a user