[BugFix]Add MiniCPM-o 4.5 end-to-end test suite (offline, online serving) (#5237)
Signed-off-by: y_null <y_null@qq.com> Signed-off-by: amy-why-3459 <wuhaiyan17@huawei.com> Co-authored-by: amy-why-3459 <wuhaiyan17@huawei.com> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
27 files changed
+1338
-46
No files matched your search
@@ -15,6 +15,20 @@ import torch.nn.functional as F
|
||||
_SILENCE_TOKEN = 4218
|
||||
|
||||
|
||||
def _autocast_disabled(device: torch.device):
|
||||
"""Disable any enclosing autocast region on ``device``.
|
||||
|
||||
``torch.amp.autocast`` resolves the autocast dtype for ``device_type``
|
||||
while constructing the context, which raises on accelerators (e.g. Ascend
|
||||
NPU) that never registered autocast support. Degrade to a no-op there: an
|
||||
enclosing region can only exist on a device type torch already knows.
|
||||
"""
|
||||
try:
|
||||
return torch.amp.autocast(device.type, enabled=False)
|
||||
except (RuntimeError, TypeError, ValueError):
|
||||
return nullcontext()
|
||||
|
||||
|
||||
def tensor_signature(value: torch.Tensor) -> tuple[tuple[int, ...], str, str]:
|
||||
return tuple(value.shape), str(value.dtype), value.device.type
|
||||
|
||||
@@ -72,7 +86,7 @@ class BatchedToken2Wav(nn.Module):
|
||||
previous_dtype = torch.get_default_dtype()
|
||||
try:
|
||||
torch.set_default_dtype(torch.float32)
|
||||
with torch.amp.autocast("cuda", enabled=False):
|
||||
with _autocast_disabled(self.speech_window.device):
|
||||
values = self._token2wav._prepare_prompt(prompt_wav)
|
||||
finally:
|
||||
torch.set_default_dtype(previous_dtype)
|
||||
@@ -106,6 +120,16 @@ class BatchedToken2Wav(nn.Module):
|
||||
dtype=torch.float16,
|
||||
)
|
||||
|
||||
def _pre_lookahead_len(self) -> int | None:
|
||||
"""Right-context width of the encoder's pre-lookahead convolution.
|
||||
|
||||
``None`` when the encoder does not expose one, so callers keep working
|
||||
against encoder implementations without that layer.
|
||||
"""
|
||||
layer = getattr(self.flow.encoder, "pre_lookahead_layer", None)
|
||||
width = getattr(layer, "pre_lookahead_len", None)
|
||||
return int(width) if width is not None else None
|
||||
|
||||
def _encode_chunk(
|
||||
self,
|
||||
tokens: torch.Tensor,
|
||||
@@ -278,7 +302,11 @@ class BatchedToken2Wav(nn.Module):
|
||||
batch_size: int,
|
||||
) -> list[BatchedToken2WavState]:
|
||||
prompt_tokens, speakers, prompt_mels = self._repeat_prompt(features, batch_size)
|
||||
lookahead = prompt_tokens.new_full((batch_size, 3), _SILENCE_TOKEN)
|
||||
lookahead_width = self._pre_lookahead_len()
|
||||
lookahead = prompt_tokens.new_full(
|
||||
(batch_size, 3 if lookahead_width is None else lookahead_width),
|
||||
_SILENCE_TOKEN,
|
||||
)
|
||||
with self._autocast(prompt_tokens.device):
|
||||
hidden, conformer_cnn, conformer_att = self._encode_chunk(
|
||||
torch.cat((prompt_tokens, lookahead), dim=1),
|
||||
@@ -336,6 +364,19 @@ class BatchedToken2Wav(nn.Module):
|
||||
batch_size = int(tokens.shape[0])
|
||||
if batch_size != len(states):
|
||||
raise ValueError(f"tokens batch {batch_size} != state batch {len(states)}")
|
||||
# The encoder's pre-lookahead convolution consumes ``pre_lookahead_len``
|
||||
# frames of right context and keeps no left cache, so a non-final chunk
|
||||
# must carry at least one full kernel. Only the final chunk is allowed
|
||||
# to be shorter: ``forward_chunk`` zero-pads it by the lookahead width.
|
||||
lookahead = self._pre_lookahead_len()
|
||||
if lookahead is not None and not last_chunk:
|
||||
num_frames = int(tokens.shape[1])
|
||||
if num_frames <= lookahead:
|
||||
raise RuntimeError(
|
||||
"MiniCPMO45Code2WavBatchError "
|
||||
f'{{"reason":"chunk_below_lookahead_window","frames":{num_frames},'
|
||||
f'"minimum":{lookahead + 1}}}'
|
||||
)
|
||||
flow_cache = self._stack_flow_cache(states)
|
||||
speakers = features.speaker_embedding.expand(batch_size, -1)
|
||||
with self._autocast(tokens.device):
|
||||
|
||||
@@ -17,6 +17,7 @@ import soundfile as sf
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
|
||||
@@ -26,6 +27,8 @@ from .batched_token2wav import (
|
||||
state_shape_signature,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _batch_error(reason: str, **details: Any) -> RuntimeError:
|
||||
payload = {"reason": reason, **details}
|
||||
@@ -48,6 +51,23 @@ def _codec_tensor(value: Any, fallback: torch.Tensor) -> torch.Tensor:
|
||||
return fallback.reshape(-1).to(dtype=torch.long)
|
||||
|
||||
|
||||
# Keys the runner stamps on every step regardless of stage input (see
|
||||
# OmniGPUModelRunner._preprocess and the NPU _gather_runtime_additional_information
|
||||
# override). A step carrying only these has no producer payload at all.
|
||||
_RUNNER_STAMPED_KEYS = frozenset({"request_id", "req_id", "generated_len", "meta"})
|
||||
|
||||
|
||||
def _carries_stage_payload(info: Mapping[str, Any], meta: Mapping[str, Any]) -> bool:
|
||||
"""Whether this step carries anything the Talker stage actually sent.
|
||||
|
||||
Any real async-chunk payload brings producer metadata along, whether the
|
||||
transport delivers it nested under ``meta`` or as flattened ``meta.*`` keys.
|
||||
"""
|
||||
if any(key not in _RUNNER_STAMPED_KEYS for key in info):
|
||||
return True
|
||||
return meta is not info and any(key not in _RUNNER_STAMPED_KEYS for key in meta)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _RequestState:
|
||||
cache_epoch: int
|
||||
@@ -74,6 +94,7 @@ class _WorkItem:
|
||||
duplex_epoch: int | None
|
||||
segment_end: bool
|
||||
turn_end: bool
|
||||
has_payload: bool = True
|
||||
|
||||
|
||||
class MiniCPMO45Code2Wav(nn.Module):
|
||||
@@ -207,6 +228,32 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
if not isinstance(meta, Mapping):
|
||||
meta = info
|
||||
request_id = str(_scalar(meta.get("request_id"), _scalar(info.get("request_id"), "")))
|
||||
if not _carries_stage_payload(info, meta):
|
||||
# The producer attached nothing to this step, only the bookkeeping
|
||||
# the runner stamps on every request. The stage was scheduled on
|
||||
# the placeholder prompt that async-chunk pre-warm submits before
|
||||
# the first codec window arrives: those tokens are reserved slots,
|
||||
# not codec data, and one bogus frame is shorter than the vocoder's
|
||||
# lookahead window. Such a step carries no producer metadata at
|
||||
# all, so it cannot be held to the payload contract below either.
|
||||
return _WorkItem(
|
||||
output_index=index,
|
||||
state_id=state_id,
|
||||
request_id=request_id or state_id,
|
||||
cache_epoch=0,
|
||||
chunk_seq=0,
|
||||
prompt_cache_id=self._default_prompt_id,
|
||||
prompt_wav=self._default_prompt_wav,
|
||||
last_chunk=False,
|
||||
tokens=segment.new_empty(0, dtype=torch.long),
|
||||
previous=None,
|
||||
segment_text="",
|
||||
duplex_turn_id=None,
|
||||
duplex_epoch=None,
|
||||
segment_end=False,
|
||||
turn_end=False,
|
||||
has_payload=False,
|
||||
)
|
||||
if not request_id:
|
||||
raise _batch_error("missing_request_id", output_index=index)
|
||||
cache_epoch = int(_scalar(meta.get("cache_epoch"), 0))
|
||||
@@ -358,7 +405,18 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
runtime_infos=len(runtime_additional_information),
|
||||
)
|
||||
if self.backend is None:
|
||||
raise _batch_error("backend_not_loaded")
|
||||
# load_format=dummy (CI core_model runs) skips model.load_weights()
|
||||
# entirely, but Token2wav's assets live beside the checkpoint rather
|
||||
# than in its weight iterator, so they still have to be loaded for
|
||||
# this stage to produce anything. Build them on first use, outside
|
||||
# inference mode so the parameters are ordinary tensors.
|
||||
logger.warning_once(
|
||||
"MiniCPM-o Code2Wav backend was not built during weight loading "
|
||||
"(load_format=%s); loading Token2wav assets now.",
|
||||
getattr(getattr(self.vllm_config, "load_config", None), "load_format", "unknown"),
|
||||
)
|
||||
with torch.inference_mode(False), torch.no_grad():
|
||||
self._build_backend()
|
||||
|
||||
state_ids = kwargs.get("request_ids")
|
||||
if state_ids is None:
|
||||
@@ -393,7 +451,9 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
outputs = [empty for _ in segments]
|
||||
sentinels = [item for item in items if item.last_chunk and item.tokens.numel() == 0]
|
||||
compute_items = [item for item in items if item.tokens.numel() > 0]
|
||||
invalid_empty = [item.request_id for item in items if not item.last_chunk and item.tokens.numel() == 0]
|
||||
invalid_empty = [
|
||||
item.request_id for item in items if item.has_payload and not item.last_chunk and item.tokens.numel() == 0
|
||||
]
|
||||
if invalid_empty:
|
||||
raise _batch_error("empty_nonfinal_chunk", request_ids=invalid_empty)
|
||||
|
||||
@@ -514,9 +574,30 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
for _ in weights:
|
||||
pass
|
||||
self._build_backend()
|
||||
# Token2wav loads flow.pt and hift.pt inside its constructor instead of
|
||||
# from the parent MiniCPM checkpoint iterator. Report those registered
|
||||
# parameters as initialized so vLLM's strict loader audit does not
|
||||
# misclassify the independently loaded Stage-2 weights as missing.
|
||||
return {name for name, _ in self.named_parameters()}
|
||||
|
||||
def _build_backend(self) -> None:
|
||||
"""Load the Token2wav assets that back this stage."""
|
||||
if self.backend is not None:
|
||||
return {name for name, _ in self.named_parameters()}
|
||||
from stepaudio2.token2wav import Token2wav
|
||||
return
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
if current_omni_platform.is_npu():
|
||||
# NPU/Ascend: the external `stepaudio2` package hard-codes `.cuda()`,
|
||||
# so use the in-tree NPU-aware adapter instead. It delegates to
|
||||
# StepAudio2Token2WavCore, which auto-applies the Ascend fixes
|
||||
# (HiFT linear downsample, DiT mask expand, MATH SDPA) on NPU.
|
||||
from vllm_omni.model_executor.models.minicpmo_4_5.minicpmo_4_5_token2wav import (
|
||||
MiniCPMO45Token2wav as Token2wav,
|
||||
)
|
||||
else:
|
||||
from stepaudio2.token2wav import Token2wav
|
||||
|
||||
extra = self._extra_config()
|
||||
prompt_path = Path(self._default_prompt_wav)
|
||||
@@ -540,8 +621,3 @@ class MiniCPMO45Code2Wav(nn.Module):
|
||||
finally:
|
||||
torch.set_default_dtype(previous_dtype)
|
||||
self.backend = BatchedToken2Wav(token2wav)
|
||||
# Token2wav loads flow.pt and hift.pt inside its constructor instead of
|
||||
# from the parent MiniCPM checkpoint iterator. Report those registered
|
||||
# parameters as initialized so vLLM's strict loader audit does not
|
||||
# misclassify the independently loaded Stage-2 weights as missing.
|
||||
return {name for name, _ in self.named_parameters()}
|
||||
@@ -19,6 +19,7 @@ import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from transformers import LlamaConfig
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.interfaces import SupportsPP
|
||||
from vllm.model_executor.models.llama import LlamaModel
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
@@ -28,6 +29,8 @@ from vllm_omni.experimental.fullduplex.engine.intermediate import get_tts_handof
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_REPETITION_WINDOW = 16
|
||||
_MIN_AUDIO_TOKENS = 64
|
||||
_MAX_AUDIO_TOKENS = 2048
|
||||
@@ -202,11 +205,27 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
)
|
||||
self.make_empty_intermediate_tensors = self.tts_model.make_empty_intermediate_tensors
|
||||
|
||||
def _boundary_embeddings(self) -> torch.Tensor:
|
||||
"""Embed the ``<text_eos><audio_bos>`` tail every condition ends with."""
|
||||
ids = torch.tensor(
|
||||
[self._text_eos_id, self._tts_bos_id],
|
||||
device=self.emb_text.weight.device,
|
||||
dtype=torch.long,
|
||||
)
|
||||
return self.emb_text(ids)
|
||||
|
||||
def _build_condition_embeddings(
|
||||
self,
|
||||
tts_token_ids: torch.Tensor,
|
||||
tts_hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
if tts_token_ids.numel() == 0 or tts_hidden_states.numel() == 0:
|
||||
# The thinker can legally emit an empty speech segment (<|tts_bos|>
|
||||
# immediately followed by a boundary token) when it decides not to
|
||||
# speak. Condition on the boundary tokens alone, which matches the
|
||||
# 2-token scheduler prompt the stage bridge builds for an empty
|
||||
# handoff.
|
||||
return self._boundary_embeddings()
|
||||
device = self.emb_text.weight.device
|
||||
dtype = self.emb_text.weight.dtype
|
||||
token_ids = tts_token_ids.to(device=device, dtype=torch.long).reshape(-1)
|
||||
@@ -220,9 +239,7 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
hidden_embeds = self.projector_semantic(hidden)
|
||||
if self._normalize:
|
||||
hidden_embeds = F.normalize(hidden_embeds, p=2, dim=-1)
|
||||
text_eos = self.emb_text(torch.tensor([self._text_eos_id], device=device, dtype=torch.long))
|
||||
audio_bos = self.emb_text(torch.tensor([self._tts_bos_id], device=device, dtype=torch.long))
|
||||
return torch.cat([text_embeds + hidden_embeds, text_eos, audio_bos], dim=0)
|
||||
return torch.cat([text_embeds + hidden_embeds, self._boundary_embeddings()], dim=0)
|
||||
|
||||
def preprocess(
|
||||
self,
|
||||
@@ -255,8 +272,15 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
f"hidden_states={type(hidden_states).__name__}, "
|
||||
f"available_keys={available}"
|
||||
)
|
||||
if token_ids.numel() == 0 or hidden_states.numel() == 0:
|
||||
raise ValueError("MiniCPM-o Talker conditioning must not be empty")
|
||||
# An empty condition means the thinker chose not to speak: finish the
|
||||
# request up front so it emits zero audio codes instead of killing
|
||||
# the stage engine.
|
||||
empty_condition = token_ids.numel() == 0 or hidden_states.numel() == 0
|
||||
if empty_condition:
|
||||
logger.warning_once(
|
||||
"MiniCPM-o Talker received an empty condition (request %s); this request produces no audio.",
|
||||
info_dict.get("request_id"),
|
||||
)
|
||||
full_embeds = self._build_condition_embeddings(token_ids, hidden_states)
|
||||
offset = int(info_dict.get("_omni_num_computed_tokens", 0))
|
||||
if offset == 0 and span_len > full_embeds.shape[0]:
|
||||
@@ -288,7 +312,7 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
state = {
|
||||
"step": 0,
|
||||
"max_tokens": max_tokens,
|
||||
"finished": False,
|
||||
"finished": empty_condition,
|
||||
}
|
||||
request_id = str(info_dict.get("request_id", "0"))
|
||||
request_states = getattr(self, "_request_audio_states", None)
|
||||
@@ -311,6 +335,13 @@ class MiniCPMO45OmniTTSForConditionalGeneration(nn.Module, SupportsPP):
|
||||
|
||||
current = (info_dict.get("audio_codes", {}) or {}).get("current")
|
||||
if not isinstance(current, torch.Tensor) or current.numel() != 1:
|
||||
if state.get("finished"):
|
||||
# A request that finished before sampling any code can still be
|
||||
# scheduled for decode steps while sampling min_tokens masks the
|
||||
# stop token. make_omni_output ignores its hidden states, so any
|
||||
# shape-correct embedding will do.
|
||||
weight = self.emb_code[0].weight
|
||||
return input_ids, weight.new_zeros((span_len, weight.shape[1])), {}
|
||||
raise RuntimeError("MiniCPM-o Talker decode is missing the previous request-local audio code")
|
||||
code = current.to(device=self.emb_code[0].weight.device, dtype=torch.long).reshape(1)
|
||||
embeds = self.emb_code[0](code)
|
||||
|
||||
@@ -82,6 +82,44 @@ class MiniCPMO45Token2wav:
|
||||
self.stream_cache: Any | None = None
|
||||
self.hift_cache_dict: dict[str, torch.Tensor] = {}
|
||||
|
||||
# The external ``stepaudio2.Token2wav`` class builds ``speech_window``
|
||||
# eagerly in ``__init__``. ``StepAudio2Token2WavCore`` only creates it
|
||||
# lazily inside ``setup_stream_for``, so materialize it here: the
|
||||
# 3-stage ``BatchedToken2Wav`` wrapper clones it at construction time.
|
||||
if self._core.speech_window is None:
|
||||
self._core.speech_window = torch.from_numpy(np.hamming(2 * self._core.source_cache_len)).to(
|
||||
device=self.device, dtype=torch.float32
|
||||
)
|
||||
|
||||
# --- Surface expected by ``BatchedToken2Wav`` (3-stage Code2Wav) ---------
|
||||
# ``BatchedToken2Wav`` wraps this object as a one-time asset loader and
|
||||
# module holder; it never calls ``__call__`` / ``stream`` / ``set_stream_cache``.
|
||||
# Expose the same attributes the upstream ``stepaudio2.Token2wav`` provides.
|
||||
|
||||
@property
|
||||
def flow(self) -> torch.nn.Module:
|
||||
return self._core.flow
|
||||
|
||||
@property
|
||||
def hift(self) -> torch.nn.Module:
|
||||
return self._core.hift
|
||||
|
||||
@property
|
||||
def mel_cache_len(self) -> int:
|
||||
return self._core.mel_cache_len
|
||||
|
||||
@property
|
||||
def source_cache_len(self) -> int:
|
||||
return self._core.source_cache_len
|
||||
|
||||
@property
|
||||
def speech_window(self) -> torch.Tensor:
|
||||
return self._core.speech_window
|
||||
|
||||
def _prepare_prompt(self, prompt_wav: str):
|
||||
"""Delegate prompt feature extraction to the wrapped core."""
|
||||
return self._core._prepare_prompt(prompt_wav)
|
||||
|
||||
def __call__(self, generated_speech_tokens, prompt_wav) -> bytes:
|
||||
"""One-shot tokens → 24 kHz WAV bytes."""
|
||||
return self._core.forward(
|
||||
|
||||
Reference in new issue
Block a user