[WIP][Bugfix][MiniCPM-o] Fix Full duplex bugs for minicpm-challenge (#5496)
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
60 files changed
+3696
-634
No files matched your search
@@ -65,12 +65,11 @@ class MiniCPMO45DataPlaneSession:
|
||||
def begin_request(self, request_id: str) -> None:
|
||||
state = self._requests.setdefault(request_id, _RequestState())
|
||||
state.terminal = False
|
||||
# Preserve turn-scoped cursors for resumable requests. The legacy path
|
||||
# only reset request-scoped terminal markers on append.
|
||||
request_turn = state.turns.get(None)
|
||||
if request_turn is not None:
|
||||
request_turn.tts_eos_done = False
|
||||
request_turn.turn_eos_done = False
|
||||
# A resumable append starts a new Talker segment, even when it
|
||||
# continues the same model turn. Re-arm only the segment boundary;
|
||||
# turn EOS remains deduplicated until the model advances the turn.
|
||||
for turn_state in state.turns.values():
|
||||
turn_state.tts_eos_done = False
|
||||
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
if request_id is None:
|
||||
|
||||
@@ -2,11 +2,19 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PcmSpan:
|
||||
byte_count: int
|
||||
force_listen: bool
|
||||
is_speech: bool
|
||||
|
||||
|
||||
class MiniCPMO45PcmAppendReservation:
|
||||
__slots__ = (
|
||||
"_active",
|
||||
@@ -15,6 +23,7 @@ class MiniCPMO45PcmAppendReservation:
|
||||
"_owner",
|
||||
"_raw",
|
||||
"_sample_rate_hz",
|
||||
"_spans",
|
||||
"_turn_had_speech",
|
||||
"_video_frames",
|
||||
"operation_id",
|
||||
@@ -31,6 +40,7 @@ class MiniCPMO45PcmAppendReservation:
|
||||
sample_rate_hz: int,
|
||||
force_listen: bool,
|
||||
is_speech: bool,
|
||||
spans: list[_PcmSpan] | None = None,
|
||||
turn_had_speech: bool = False,
|
||||
video_frames: list[str] | None = None,
|
||||
) -> None:
|
||||
@@ -41,6 +51,7 @@ class MiniCPMO45PcmAppendReservation:
|
||||
self._sample_rate_hz = sample_rate_hz
|
||||
self._force_listen = force_listen
|
||||
self._is_speech = is_speech
|
||||
self._spans = list(spans or [])
|
||||
self._turn_had_speech = turn_had_speech
|
||||
self._video_frames = list(video_frames or [])
|
||||
self._active = True
|
||||
@@ -97,9 +108,8 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._buffer = bytearray()
|
||||
self._spans: list[_PcmSpan] = []
|
||||
self._sample_rate_hz: int | None = None
|
||||
self._force_listen = False
|
||||
self._is_speech = False
|
||||
self._turn_had_speech = False
|
||||
self._reservation_seq = 0
|
||||
self._reservations: list[MiniCPMO45PcmAppendReservation] = []
|
||||
@@ -112,14 +122,13 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
reservation._active = False
|
||||
self._reservations.clear()
|
||||
self._buffer.clear()
|
||||
self._spans.clear()
|
||||
self._frame_queue.clear()
|
||||
self._sample_rate_hz = None
|
||||
self._force_listen = False
|
||||
self._is_speech = False
|
||||
self._turn_had_speech = False
|
||||
|
||||
def clear_force_listen(self) -> None:
|
||||
self._force_listen = False
|
||||
self._spans = [_PcmSpan(span.byte_count, False, span.is_speech) for span in self._spans]
|
||||
|
||||
def has_pending(self) -> bool:
|
||||
return bool(self._buffer)
|
||||
@@ -131,6 +140,56 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
def pending_byte_count(self) -> int:
|
||||
return len(self._buffer)
|
||||
|
||||
def _append_span(self, span: _PcmSpan) -> None:
|
||||
if span.byte_count <= 0:
|
||||
return
|
||||
if (
|
||||
self._spans
|
||||
and self._spans[-1].force_listen == span.force_listen
|
||||
and self._spans[-1].is_speech == span.is_speech
|
||||
):
|
||||
previous = self._spans[-1]
|
||||
self._spans[-1] = _PcmSpan(
|
||||
previous.byte_count + span.byte_count,
|
||||
span.force_listen,
|
||||
span.is_speech,
|
||||
)
|
||||
return
|
||||
self._spans.append(span)
|
||||
|
||||
def _consume_spans(self, byte_count: int) -> list[_PcmSpan]:
|
||||
consumed: list[_PcmSpan] = []
|
||||
remaining = byte_count
|
||||
while remaining:
|
||||
if not self._spans:
|
||||
raise RuntimeError("MiniCPM-o PCM metadata is shorter than buffered audio")
|
||||
span = self._spans.pop(0)
|
||||
take = min(remaining, span.byte_count)
|
||||
consumed.append(_PcmSpan(take, span.force_listen, span.is_speech))
|
||||
if take < span.byte_count:
|
||||
self._spans.insert(
|
||||
0,
|
||||
_PcmSpan(
|
||||
span.byte_count - take,
|
||||
span.force_listen,
|
||||
span.is_speech,
|
||||
),
|
||||
)
|
||||
remaining -= take
|
||||
return consumed
|
||||
|
||||
def _prepend_spans(self, spans: list[_PcmSpan]) -> None:
|
||||
current = self._spans
|
||||
self._spans = []
|
||||
for span in [*spans, *current]:
|
||||
self._append_span(span)
|
||||
|
||||
def _buffer_force_listen(self) -> bool:
|
||||
return any(span.force_listen for span in self._spans)
|
||||
|
||||
def _buffer_is_speech(self) -> bool:
|
||||
return any(span.is_speech for span in self._spans)
|
||||
|
||||
def _reserve_passthrough(
|
||||
self,
|
||||
payload: dict[str, object],
|
||||
@@ -180,12 +239,17 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
raise ValueError("MiniCPM-o native duplex audio append sample_rate_hz changed within a session")
|
||||
self._sample_rate_hz = sample_rate_hz
|
||||
self._buffer.extend(raw)
|
||||
self._append_span(
|
||||
_PcmSpan(
|
||||
len(raw),
|
||||
bool(payload.get("force_listen", False)),
|
||||
bool(payload.get("is_speech", False)),
|
||||
)
|
||||
)
|
||||
frames_in = payload.get("video_frames")
|
||||
if isinstance(frames_in, list):
|
||||
self._frame_queue.extend(frame for frame in frames_in if isinstance(frame, str) and frame)
|
||||
self._turn_had_speech = self._turn_had_speech or bool(payload.get("is_speech", False))
|
||||
self._force_listen = self._force_listen or bool(payload.get("force_listen", False))
|
||||
self._is_speech = self._is_speech or bool(payload.get("is_speech", False))
|
||||
if not allow_emit:
|
||||
return None
|
||||
|
||||
@@ -208,6 +272,7 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
pad_samples = 0
|
||||
emit_bytes = emit_samples * 4
|
||||
reserved_raw = bytes(self._buffer[:emit_bytes])
|
||||
reserved_spans = self._consume_spans(emit_bytes)
|
||||
emit_raw = reserved_raw + b"\x00" * (pad_samples * 4)
|
||||
del self._buffer[:emit_bytes]
|
||||
|
||||
@@ -227,11 +292,8 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
if emit_samples + pad_samples >= min_samples and self._frame_queue:
|
||||
attached_frames = [self._frame_queue.pop(0)]
|
||||
out["video_frames"] = attached_frames
|
||||
out["force_listen"] = self._force_listen
|
||||
out["is_speech"] = self._is_speech
|
||||
if not self._buffer:
|
||||
self._force_listen = False
|
||||
self._is_speech = False
|
||||
out["force_listen"] = any(span.force_listen for span in reserved_spans)
|
||||
out["is_speech"] = any(span.is_speech for span in reserved_spans)
|
||||
reservation = MiniCPMO45PcmAppendReservation(
|
||||
owner=self,
|
||||
operation_id=operation_id,
|
||||
@@ -240,6 +302,7 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
sample_rate_hz=sample_rate_hz,
|
||||
force_listen=bool(out.get("force_listen", False)),
|
||||
is_speech=bool(out.get("is_speech", False)),
|
||||
spans=reserved_spans,
|
||||
turn_had_speech=self._turn_had_speech,
|
||||
video_frames=attached_frames,
|
||||
)
|
||||
@@ -261,8 +324,8 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
"audio": "",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": self._sample_rate_hz or 16000,
|
||||
"force_listen": self._force_listen,
|
||||
"is_speech": self._is_speech,
|
||||
"force_listen": self._buffer_force_listen(),
|
||||
"is_speech": self._buffer_is_speech(),
|
||||
}
|
||||
reservation = self.prepare_append(
|
||||
payload,
|
||||
@@ -280,8 +343,8 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
payload=None,
|
||||
raw=b"",
|
||||
sample_rate_hz=self._sample_rate_hz or 0,
|
||||
force_listen=self._force_listen,
|
||||
is_speech=self._is_speech,
|
||||
force_listen=self._buffer_force_listen(),
|
||||
is_speech=self._buffer_is_speech(),
|
||||
turn_had_speech=had_speech,
|
||||
)
|
||||
self._reservations.append(reservation)
|
||||
@@ -289,8 +352,6 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
# Open the next physical input generation without touching already
|
||||
# reserved appends. A rollback restores this generation's metadata.
|
||||
self._sample_rate_hz = None
|
||||
self._force_listen = False
|
||||
self._is_speech = False
|
||||
self._turn_had_speech = False
|
||||
return reservation
|
||||
|
||||
@@ -335,12 +396,11 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
rolled_back = self._reservations[index:]
|
||||
restored = b"".join(item._raw for item in rolled_back)
|
||||
self._buffer[:0] = restored
|
||||
self._prepend_spans([span for item in rolled_back for span in item._spans])
|
||||
restored_frames = [frame for item in rolled_back for frame in item._video_frames]
|
||||
if restored_frames:
|
||||
self._frame_queue[:0] = restored_frames
|
||||
self._sample_rate_hz = self._sample_rate_hz or reservation._sample_rate_hz
|
||||
self._force_listen = self._force_listen or any(item._force_listen for item in rolled_back)
|
||||
self._is_speech = self._is_speech or any(item._is_speech for item in rolled_back)
|
||||
self._turn_had_speech = self._turn_had_speech or any(item._turn_had_speech for item in rolled_back)
|
||||
for item in rolled_back:
|
||||
item._active = False
|
||||
@@ -354,8 +414,8 @@ class MiniCPMO45PcmAppendBuffer:
|
||||
"audio": "",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": self._sample_rate_hz or 16000,
|
||||
"force_listen": self._force_listen,
|
||||
"is_speech": self._is_speech,
|
||||
"force_listen": self._buffer_force_listen(),
|
||||
"is_speech": self._buffer_is_speech(),
|
||||
}
|
||||
return self.append(payload, chunk_period_ms=chunk_period_ms, flush=True)
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import sys
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
@@ -14,6 +14,7 @@ from vllm_omni.experimental.fullduplex.minicpmo45.policy import MiniCPMO45Duplex
|
||||
|
||||
_MINICPMO45_SPECIAL_TOKEN_FIELDS = MiniCPMO45DuplexPolicy.SPECIAL_TOKEN_FIELDS
|
||||
_MINICPMO45_OPTIONAL_TOKEN_FIELDS = MiniCPMO45DuplexPolicy.OPTIONAL_TOKEN_FIELDS
|
||||
_MINICPMO45_PROCESSOR_LOAD_LOCK = Lock()
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -35,7 +36,7 @@ class _MiniCPMO45Stage0SessionState:
|
||||
pending_speech_context: bool = False
|
||||
pending_speech_append_identity: tuple[int | None, int] | None = None
|
||||
pending_speech_response_open: bool = False
|
||||
generated_text_tokens: list[int] = field(default_factory=list)
|
||||
generated_tokens: list[int] = field(default_factory=list)
|
||||
|
||||
|
||||
class MiniCPMO45Stage0DuplexRuntime:
|
||||
@@ -58,6 +59,8 @@ class MiniCPMO45Stage0DuplexRuntime:
|
||||
else getattr(stage_model, "tokenizer", None)
|
||||
)
|
||||
self._init_token_ids()
|
||||
if self.tokenizer is not None:
|
||||
self._require_special_token_ids()
|
||||
|
||||
def _stage_runtime_ready(self) -> bool:
|
||||
return self.processor is not None and self.tokenizer is not None and self.thinker is not None
|
||||
@@ -196,19 +199,15 @@ class MiniCPMO45Stage0DuplexRuntime:
|
||||
embed_parts.extend(state.context_embeds)
|
||||
token_ids.extend(state.context_token_ids)
|
||||
|
||||
# Consume every complete chunk in the buffer so the appended span and
|
||||
# the scheduler's slot reservation for this append agree exactly. A
|
||||
# final append may zero-pad a real residual chunk, but it must not add
|
||||
# a whole silence unit after all input was already consumed: official
|
||||
# duplex generation runs once per microphone unit and client commit is
|
||||
# not an additional model decision.
|
||||
# Consume every complete processor chunk in the buffer so the appended
|
||||
# span and the scheduler's slot reservation agree exactly. The serving
|
||||
# PCM buffer pads a final real residual before it reaches Stage0. Do not
|
||||
# pad again here: the first processor chunk is hop-aligned below 1035ms
|
||||
# and intentionally leaves a small carry that is not another model unit.
|
||||
units_built = 0
|
||||
while True:
|
||||
if len(state.audio_buffer) < chunk_size:
|
||||
if not final or len(state.audio_buffer) == 0:
|
||||
break
|
||||
pad = np.zeros(chunk_size - len(state.audio_buffer), dtype=np.float32)
|
||||
state.audio_buffer = np.concatenate([state.audio_buffer, pad])
|
||||
break
|
||||
audio_chunk = state.audio_buffer[:chunk_size]
|
||||
batch_feature = self._process_streaming_audio(audio_chunk, state.audio_chunk_idx, processor=processor)
|
||||
for name, value in (
|
||||
@@ -224,6 +223,11 @@ class MiniCPMO45Stage0DuplexRuntime:
|
||||
if units_built == 0:
|
||||
return self._stage_prefill_result(False, start_time, "streaming audio embedding returned empty")
|
||||
break
|
||||
consumed_samples = self._consumed_audio_samples(
|
||||
state.audio_chunk_idx,
|
||||
chunk_size,
|
||||
processor=processor,
|
||||
)
|
||||
if state.audio_chunk_idx > 0:
|
||||
# Official duplex closes every unit (finalize_unit feeds the
|
||||
# sampled terminator + </unit>) before the next <unit> opens.
|
||||
@@ -255,9 +259,7 @@ class MiniCPMO45Stage0DuplexRuntime:
|
||||
token_ids.extend(
|
||||
[self._audio_embedding_placeholder_token_id()] * int(self._as_2d_tensor(audio_embeds).shape[0])
|
||||
)
|
||||
state.audio_buffer = state.audio_buffer[
|
||||
self._consumed_audio_samples(state.audio_chunk_idx, chunk_size, processor=processor) :
|
||||
]
|
||||
state.audio_buffer = state.audio_buffer[consumed_samples:]
|
||||
state.audio_chunk_idx += 1
|
||||
units_built += 1
|
||||
chunk_size = self._streaming_chunk_size(processor)
|
||||
@@ -610,14 +612,33 @@ class MiniCPMO45Stage0DuplexRuntime:
|
||||
def _load_processor_from_path(model_path: str | None) -> Any | None:
|
||||
if not model_path:
|
||||
return None
|
||||
if model_path not in sys.path:
|
||||
sys.path.insert(0, model_path)
|
||||
try:
|
||||
from processing_minicpmo import MiniCPMOProcessor
|
||||
from transformers import AutoImageProcessor, AutoProcessor
|
||||
|
||||
return MiniCPMOProcessor.from_pretrained(model_path, trust_remote_code=True)
|
||||
except Exception:
|
||||
return None
|
||||
original_register = AutoImageProcessor.register
|
||||
|
||||
def register_image_processor(config_class, *args, **kwargs):
|
||||
# The checkpoint's auto_map already loads this class. Its
|
||||
# legacy string registration is incompatible with some
|
||||
# Transformers versions and is otherwise redundant.
|
||||
if config_class == "MiniCPMVImageProcessor":
|
||||
return None
|
||||
return original_register(config_class, *args, **kwargs)
|
||||
|
||||
with _MINICPMO45_PROCESSOR_LOAD_LOCK:
|
||||
AutoImageProcessor.register = staticmethod(register_image_processor)
|
||||
try:
|
||||
processor = AutoProcessor.from_pretrained(
|
||||
model_path,
|
||||
trust_remote_code=True,
|
||||
)
|
||||
finally:
|
||||
AutoImageProcessor.register = staticmethod(original_register)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Failed to load MiniCPM-o duplex processor from {model_path!r}") from exc
|
||||
if getattr(processor, "tokenizer", None) is None:
|
||||
raise RuntimeError(f"MiniCPM-o duplex processor loaded from {model_path!r} does not expose a tokenizer")
|
||||
return processor
|
||||
|
||||
def _init_token_ids(self) -> None:
|
||||
if self.tokenizer is None:
|
||||
|
||||
@@ -503,11 +503,45 @@ class DuplexSessionRunnerMixin:
|
||||
clear_completed_pending_silence()
|
||||
pending_silence = native.pending_silence_task
|
||||
if pending_silence is not None and not pending_silence.done():
|
||||
if pending_silence is asyncio.current_task():
|
||||
return False
|
||||
try:
|
||||
if not await pending_silence:
|
||||
return False
|
||||
except asyncio.CancelledError:
|
||||
current = asyncio.current_task()
|
||||
if current is not None and current.cancelling():
|
||||
raise
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
clear_completed_pending_silence()
|
||||
pending_silence = native.pending_silence_task
|
||||
if pending_silence is not None and not pending_silence.done():
|
||||
return False
|
||||
append_tail = actor.native_append_tail
|
||||
if (append_tail is None or append_tail.done()) and real_native_input_waiting():
|
||||
return False
|
||||
if actor.native_append_tail is not None and not actor.native_append_tail.done():
|
||||
return False
|
||||
if real_native_input_waiting():
|
||||
return False
|
||||
continuation_delay_s = max(
|
||||
0.0,
|
||||
float(session.capabilities.chunk_period_ms or 1000) / 1000.0,
|
||||
)
|
||||
if continuation_delay_s > 0:
|
||||
await asyncio.sleep(continuation_delay_s)
|
||||
if (
|
||||
actor.native_append_tail is not append_tail
|
||||
or ((append_tail is None or append_tail.done()) and real_native_input_waiting())
|
||||
or self._native_silence_continuation_is_stale(
|
||||
session,
|
||||
request_id=request_id,
|
||||
response_id=response_id,
|
||||
response_owned=response_owned,
|
||||
expected_epoch=expected_epoch,
|
||||
expected_incarnation=expected_incarnation,
|
||||
expected_model_turn_id=expected_model_turn_id,
|
||||
)
|
||||
):
|
||||
return False
|
||||
|
||||
def _still_valid() -> bool:
|
||||
return not real_native_input_waiting() and not self._native_silence_continuation_is_stale(
|
||||
|
||||
Reference in new issue
Block a user