[Core][Frontend] Unified Full-duplex Framework (#7413)

Signed-off-by: chickeyton <ngton2014@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
chickeytonandClaude Opus 5 authored and GitHub committed 2026-09-16 15:35:36 +08:00
1 parent 9005d78903
commit 99ff4f3070
182 files changed
+26951 -34743

No files matched your search

@@ -1,15 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from .adapter import MiniCPMO45ClientRuntimeConfigError, MiniCPMO45NativeDuplexServingAdapter
from .input import MiniCPMO45PcmAppendBuffer
from .plugin import MiniCPMO45ClientRuntimeConfigError, MiniCPMO45DuplexPlugin
from .policy import MiniCPMO45DuplexPolicy
from .stage0 import MiniCPMO45Stage0DuplexRuntime
__all__ = [
"MiniCPMO45DuplexPolicy",
"MiniCPMO45NativeDuplexServingAdapter",
"MiniCPMO45ClientRuntimeConfigError",
"MiniCPMO45DuplexPlugin",
"MiniCPMO45DuplexPolicy",
"MiniCPMO45PcmAppendBuffer",
"MiniCPMO45Stage0DuplexRuntime",
]
@@ -1,335 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import base64
from copy import deepcopy
from typing import Any
import numpy as np
from vllm.multimodal.media import MediaConnector
from vllm_omni.entrypoints.duplex.protocol import DuplexSessionConfig, native_duplex_opt_in
from vllm_omni.entrypoints.duplex.runtime_adapter import (
ServingRuntimeConfigError,
reject_changed_runtime_value,
)
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.policy import MiniCPMO45DuplexPolicy
class MiniCPMO45ClientRuntimeConfigError(ServingRuntimeConfigError):
pass
class MiniCPMO45NativeDuplexServingAdapter:
"""Serving-side MiniCPM-o 4.5 native duplex session preparation.
The generic duplex WebSocket handler should not let client-supplied local
paths reach workers. This adapter follows the existing media connector
boundary: serving resolves client media URIs, then workers receive only
normalized PCM payloads. Server-owned model assets remain local paths here.
"""
PRIVATE_RUNTIME_CONFIG_KEYS = frozenset(
{
"duplex_stage_sampling_params",
"duplex_stage_max_tokens",
"duplex_stage0_max_tokens",
"duplex_scheduler_token_id",
"duplex_first_append_context_tokens",
"ref_audio_data",
"ref_audio_format",
"ref_audio_sample_rate_hz",
"initial_user_text",
}
)
@classmethod
def is_enabled(cls, config: DuplexSessionConfig) -> bool:
return native_duplex_opt_in(config.extra_body) is True
@classmethod
def validate_client_config(cls, config: DuplexSessionConfig) -> None:
cls.validate_client_extra_body(config.extra_body)
@classmethod
def validate_client_extra_body(cls, extra_body: object) -> None:
if not isinstance(extra_body, dict):
return
private_keys = sorted(cls.PRIVATE_RUNTIME_CONFIG_KEYS.intersection(extra_body))
if private_keys:
raise MiniCPMO45ClientRuntimeConfigError(
"native duplex runtime configuration is server-owned: " + ", ".join(private_keys)
)
@classmethod
def runtime_config_for_update(
cls,
config: DuplexSessionConfig,
current: object,
) -> dict[str, object]:
runtime_config = deepcopy(dict(current)) if isinstance(current, dict) else {}
reject_changed_runtime_value(
config.instructions,
runtime_config.get("instructions"),
message="instructions cannot be changed after the session is created",
code="instructions_update_unsupported",
error_cls=MiniCPMO45ClientRuntimeConfigError,
)
stage_max_tokens = runtime_config.get("duplex_stage_max_tokens")
stage_max_tokens = deepcopy(stage_max_tokens) if isinstance(stage_max_tokens, dict) else {}
stage_max_tokens["0"] = (
config.max_tokens if isinstance(config.max_tokens, int) and config.max_tokens > 0 else 20
)
stage_max_tokens.setdefault("1", 8192)
runtime_config["duplex_stage_max_tokens"] = stage_max_tokens
stage_sampling = runtime_config.get("duplex_stage_sampling_params")
stage_sampling = deepcopy(stage_sampling) if isinstance(stage_sampling, dict) else {}
stage0 = stage_sampling.get("0")
stage0 = deepcopy(stage0) if isinstance(stage0, dict) else {}
stage0["temperature"] = config.temperature if config.temperature is not None else 0.7
stage_sampling["0"] = stage0
runtime_config["duplex_stage_sampling_params"] = stage_sampling
return runtime_config
@classmethod
async def prepare_runtime_config(cls, config: DuplexSessionConfig, *, model_config: Any) -> dict[str, object]:
extra_body = dict(config.extra_body)
if any(key in extra_body for key in ("ref_audio_path", "tts_ref_audio_path")):
raise ValueError("ref_audio_path is not accepted by native duplex; use ref_audio URI instead")
cls.validate_client_config(config)
runtime_config: dict[str, object] = {"instructions": config.instructions}
initial_user_text = extra_body.pop("duplex_initial_user_text", None)
if isinstance(initial_user_text, str) and initial_user_text:
runtime_config["initial_user_text"] = initial_user_text
cls._apply_default_scheduler_policy(runtime_config, config=config, model_config=model_config)
ref_audio = config.ref_audio
extra_ref_audio = extra_body.get("ref_audio")
if ref_audio is None and isinstance(extra_ref_audio, str):
extra_body.pop("ref_audio")
ref_audio = extra_ref_audio
extra_tts_ref_audio = extra_body.get("tts_ref_audio")
if ref_audio is None and isinstance(extra_tts_ref_audio, str):
extra_body.pop("tts_ref_audio")
ref_audio = extra_tts_ref_audio
if ref_audio is None:
if any(str(modality).lower() == "audio" for modality in config.modalities):
raise MiniCPMO45ClientRuntimeConfigError(
"MiniCPM-o native duplex audio output requires ref_audio",
code="ref_audio_required",
)
cls._apply_first_append_context_tokens(
runtime_config,
model_config=model_config,
instructions=config.instructions,
initial_user_text=initial_user_text,
ref_sample_count=None,
)
config.extra_body = extra_body
return runtime_config
else:
wav_np, sr = await cls.resolve_ref_audio(ref_audio, model_config=model_config)
wav_np = cls.normalize_ref_audio(wav_np, int(sr), target_sr=16000)
# Trim to a whole number of pooled audio embeddings (100 ms frames) so
# the first-append scheduler reserve can count them exactly.
usable = (len(wav_np) // MiniCPMO45DuplexPolicy.SAMPLES_PER_AUDIO_TOKEN) * (
MiniCPMO45DuplexPolicy.SAMPLES_PER_AUDIO_TOKEN
)
wav_np = wav_np[:usable]
ref_audio_bytes = np.ascontiguousarray(wav_np, dtype=np.float32).tobytes()
runtime_config["ref_audio_data"] = base64.b64encode(ref_audio_bytes).decode("ascii")
runtime_config["ref_audio_format"] = "pcm_f32le"
runtime_config["ref_audio_sample_rate_hz"] = 16000
cls._apply_first_append_context_tokens(
runtime_config,
model_config=model_config,
instructions=config.instructions,
initial_user_text=initial_user_text,
ref_sample_count=len(wav_np),
)
config.extra_body = extra_body
config.ref_audio = None
return runtime_config
@classmethod
def _apply_default_scheduler_policy(
cls,
runtime_config: dict[str, object],
*,
config: DuplexSessionConfig,
model_config: Any,
) -> None:
stage0_max_tokens = config.max_tokens if isinstance(config.max_tokens, int) and config.max_tokens > 0 else 20
runtime_config["duplex_stage_max_tokens"] = {"0": stage0_max_tokens, "1": 8192}
stage0_params: dict[str, object] = {
"temperature": config.temperature if config.temperature is not None else 0.7,
"top_p": 0.8,
"top_k": 20,
"repetition_penalty": 1.05,
}
stop_token_ids = cls._native_stage0_stop_token_ids(model_config)
if stop_token_ids:
stage0_params["stop_token_ids"] = stop_token_ids
# Stage 1 keeps the deploy YAML's codec knobs, minus upstream's
# min_new_token=50: that floor is for whole-utterance chat TTS, while a
# duplex chunk is 26 codec samples, so check_stop would never release
# the Talker and Thinker would stall on the next model turn.
runtime_config["duplex_stage_sampling_params"] = {"0": stage0_params, "1": {"min_tokens": 0}}
scheduler_token_id = cls._native_scheduler_token_id(model_config)
if scheduler_token_id is not None:
runtime_config["duplex_scheduler_token_id"] = scheduler_token_id
@classmethod
def _apply_first_append_context_tokens(
cls,
runtime_config: dict[str, object],
*,
model_config: Any,
instructions: object,
initial_user_text: object,
ref_sample_count: int | None,
) -> None:
"""Precompute the exact session-context token count for the engine.
The first data-plane append carries the system template and optional
reference-audio embeddings ahead of the first unit. The engine
reserves scheduler slots from this count; an inexact count turns into
pad embeddings inside the model KV (surplus) or truncated context
(deficit), so it is computed with the same template and pooling math
the worker uses.
"""
if "duplex_first_append_context_tokens" in runtime_config:
return
tokenizer = cls._load_native_tokenizer(model_config)
if tokenizer is None:
return
prefix, suffix = MiniCPMO45DuplexPolicy.session_context_texts(
instructions,
ref_sample_count is not None,
initial_user_text,
)
try:
prefix_ids = tokenizer.encode(prefix, add_special_tokens=False)
suffix_ids = tokenizer.encode(suffix, add_special_tokens=False)
except Exception:
return
ref_tokens = MiniCPMO45DuplexPolicy.audio_token_count(ref_sample_count or 0)
runtime_config["duplex_first_append_context_tokens"] = len(prefix_ids) + ref_tokens + len(suffix_ids)
@staticmethod
def _native_stage0_stop_token_ids(model_config: Any) -> list[int]:
tokenizer = MiniCPMO45NativeDuplexServingAdapter._load_native_tokenizer(model_config)
if tokenizer is None:
return []
out: list[int] = []
stop_token_fields = (
"chunk_eos_token_id",
"chunk_tts_eos_token_id",
"listen_token_id",
"turn_eos_token_id",
)
for field in stop_token_fields:
token = MiniCPMO45DuplexPolicy.SPECIAL_TOKEN_FIELDS[field]
token_id = MiniCPMO45NativeDuplexServingAdapter._convert_token_to_id(tokenizer, token)
if token_id is not None and token_id not in out:
out.append(token_id)
return out
@staticmethod
def _native_scheduler_token_id(model_config: Any) -> int | None:
tokenizer = MiniCPMO45NativeDuplexServingAdapter._load_native_tokenizer(model_config)
if tokenizer is None:
return None
scheduler_tokens = (
MiniCPMO45DuplexPolicy.SPECIAL_TOKEN_FIELDS["unit_token_id"],
MiniCPMO45DuplexPolicy.OPTIONAL_TOKEN_FIELDS["audio_placeholder_token_id"],
)
for token in scheduler_tokens:
token_id = MiniCPMO45NativeDuplexServingAdapter._convert_token_to_id(tokenizer, token)
if token_id is not None:
return token_id
eos_id = getattr(tokenizer, "eos_token_id", None)
if eos_id is None:
return None
try:
return int(eos_id)
except (TypeError, ValueError):
return None
@staticmethod
def _load_native_tokenizer(model_config: Any) -> Any | None:
model_path = getattr(model_config, "model", None)
if not isinstance(model_path, str) or not model_path:
return None
try:
from transformers import AutoTokenizer
return AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
local_files_only=True,
)
except Exception:
return None
@staticmethod
def _convert_token_to_id(tokenizer: Any, token: str) -> int | None:
convert = getattr(tokenizer, "convert_tokens_to_ids", None)
value = None
if callable(convert):
value = convert(token)
if isinstance(value, list):
value = value[0] if len(value) == 1 else None
if value is None:
token_id = -1
else:
try:
token_id = int(value)
except (TypeError, ValueError):
token_id = -1
unk_token_id = getattr(tokenizer, "unk_token_id", None)
if token_id >= 0 and token_id != unk_token_id:
return token_id
encode = getattr(tokenizer, "encode", None)
if callable(encode):
try:
ids = list(encode(token, add_special_tokens=False))
except TypeError:
ids = list(encode(token))
if len(ids) == 1:
try:
token_id = int(ids[0])
except (TypeError, ValueError):
token_id = -1
if token_id >= 0 and token_id != unk_token_id:
return token_id
return None
@staticmethod
async def resolve_ref_audio(ref_audio: str, *, model_config: Any) -> tuple[np.ndarray, int]:
connector = MediaConnector(
allowed_local_media_path=getattr(model_config, "allowed_local_media_path", None),
allowed_media_domains=getattr(model_config, "allowed_media_domains", None),
)
wav_np, sr = await connector.fetch_audio_async(ref_audio)
return np.asarray(wav_np, dtype=np.float32), int(sr)
@staticmethod
def normalize_ref_audio(wav_np: np.ndarray, sample_rate: int, *, target_sr: int) -> np.ndarray:
wav_np = np.asarray(wav_np, dtype=np.float32)
if wav_np.ndim > 1:
wav_np = wav_np.mean(axis=-1)
wav_np = wav_np.reshape(-1)
if sample_rate <= 0 or sample_rate == target_sr or wav_np.size == 0:
return wav_np.astype(np.float32, copy=False)
import torch
import torchaudio
audio = torch.from_numpy(wav_np).to(dtype=torch.float32).unsqueeze(0)
resampled = torchaudio.functional.resample(audio, int(sample_rate), int(target_sr))
return resampled.squeeze(0).cpu().numpy().astype(np.float32, copy=False)
@@ -3,7 +3,12 @@
from __future__ import annotations
from vllm_omni.entrypoints.duplex.protocol import DuplexCapabilities
from vllm_omni.engine.duplex.config import DuplexCapabilities
#: Silence units a text-seeded turn is given to generate on. The model speaks
#: per audio unit, so a seeded turn still needs a clock; three units is what
#: the benchmark harness uses for the same purpose.
MINICPMO45_TEXT_TURN_PRIMING_UNITS = 3
def minicpmo45_native_capabilities(*, max_sessions: int = 1) -> DuplexCapabilities:
@@ -31,11 +36,14 @@ def minicpmo45_native_capabilities(*, max_sessions: int = 1) -> DuplexCapabiliti
supports_session_resume=True,
session_admission_mode="engine_managed",
supports_audio_truncate=True,
# The session template ends at the assistant turn, so seeded text puts
# the model in position to answer; it still generates per audio unit,
# hence the priming units.
supports_chat_completions=True, # via initial_user_text
text_turn_priming_units=MINICPMO45_TEXT_TURN_PRIMING_UNITS,
requires_model_runner_kv=True,
requires_native_stage_role=True,
implementation_level="model_native_duplex",
adapter_patterns=["scheduler_data_plane"],
input_modes=["append_audio_chunk"],
signal_sources=["model_native", "client_event", "server_policy"],
stage_handoff_transport="scheduler_data_plane",
chunk_period_ms=1000,
@@ -3,14 +3,12 @@
from __future__ import annotations
from typing import Any
def patch_minicpmo_remote_config(config: Any) -> None:
def patch_minicpmo_remote_config(config: object) -> None:
"""Fill config fields expected by the vLLM MiniCPM implementation."""
seen: set[int] = set()
def patch_cfg(cfg: Any) -> None:
def patch_cfg(cfg: object) -> None:
if cfg is None or id(cfg) in seen:
return
seen.add(id(cfg))
@@ -12,6 +12,7 @@ from vllm.logger import init_logger
from vllm_omni.engine.duplex.contracts import (
duplex_resource_request_belongs_to_session,
)
from vllm_omni.engine.duplex.plugin import DuplexDataPlane
from vllm_omni.outputs.duplex import get_duplex_output_decision
logger = init_logger(__name__)
@@ -44,6 +45,9 @@ class _TurnState:
@dataclass(slots=True)
class _RequestState:
audio_offset: int = 0
#: A snapshot below ``audio_offset`` that has not been accepted as a restart
#: yet. See :meth:`MiniCPMO45DataPlaneSession.slice_cumulative_audio`.
audio_restart_candidate: int | None = None
uses_segment_text_metadata: bool = False
pending_audio_without_text: list[dict[str, object]] = field(default_factory=list)
terminal: bool = False
@@ -53,7 +57,7 @@ class _RequestState:
return self.turns.setdefault(turn_id, _TurnState())
class MiniCPMO45DataPlaneSession:
class MiniCPMO45DataPlaneSession(DuplexDataPlane):
"""MiniCPM output projector and request/turn cursor owner.
The scheduler request owns cumulative Stage1 audio, while model turns own
@@ -487,13 +491,33 @@ class MiniCPMO45DataPlaneSession:
prev_samples = state.audio_offset
if prev_samples <= 0:
state.audio_offset = num_samples
state.audio_restart_candidate = None
return audio_data
if num_samples == prev_samples:
return None
if num_samples < prev_samples:
# Below the cursor means one of two things, and they are not
# distinguishable from this snapshot alone: the producer restarted
# its buffer, or this is a unit that carries no cumulative audio at
# all (a continuation placeholder arrives as a single sample).
# Rewinding the cursor for the second case is expensive and silent:
# the next real snapshot is then sliced from ~0 and the whole
# session's audio goes out again as one delta. So defer the
# decision — hold the candidate and leave the cursor where it is.
candidate = state.audio_restart_candidate
if candidate is None or num_samples <= candidate:
state.audio_restart_candidate = num_samples
return audio_data
# A second below-cursor snapshot that grew from the first: the
# producer really did restart, and this is its delta.
state.audio_offset = num_samples
state.audio_restart_candidate = num_samples
prev_samples = candidate
else:
# Above the cursor: whatever the dip was, this stream never
# restarted, so it is sliced from the cursor as usual.
state.audio_restart_candidate = None
state.audio_offset = num_samples
return audio_data
state.audio_offset = num_samples
try:
import torch
@@ -6,9 +6,11 @@ from __future__ import annotations
import base64
import binascii
from dataclasses import dataclass
from typing import Any
import numpy as np
from numpy.typing import NDArray
from vllm_omni.engine.duplex.plugin import PcmAppendBuffer, PcmAppendReservation
@dataclass(frozen=True, slots=True)
@@ -18,7 +20,7 @@ class _PcmSpan:
is_speech: bool
class MiniCPMO45PcmAppendReservation:
class MiniCPMO45PcmAppendReservation(PcmAppendReservation):
__slots__ = (
"_active",
"_force_listen",
@@ -74,7 +76,7 @@ class MiniCPMO45PcmAppendReservation:
self._owner._rollback_reservation(self)
def validate_native_ref_audio_config(session_config: dict[str, Any]) -> None:
def validate_native_ref_audio_config(session_config: dict[str, object]) -> None:
extra_body = session_config.get("extra_body")
if not isinstance(extra_body, dict):
extra_body = {}
@@ -84,7 +86,7 @@ def validate_native_ref_audio_config(session_config: dict[str, Any]) -> None:
raise ValueError("native duplex ref_audio_path is not accepted; resolve ref_audio in serving first")
def decode_native_ref_audio_from_config(session_config: dict[str, Any]) -> np.ndarray | None:
def decode_native_ref_audio_from_config(session_config: dict[str, object]) -> NDArray[np.float32] | None:
validate_native_ref_audio_config(session_config)
extra_body = session_config.get("extra_body")
if not isinstance(extra_body, dict):
@@ -106,7 +108,7 @@ def decode_native_ref_audio_from_config(session_config: dict[str, Any]) -> np.nd
return np.frombuffer(raw, dtype="<f4").astype(np.float32, copy=True)
class MiniCPMO45PcmAppendBuffer:
class MiniCPMO45PcmAppendBuffer(PcmAppendBuffer):
"""Accumulates short native-duplex PCM chunks into model-sized appends."""
def __init__(self) -> None:
@@ -0,0 +1,773 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""MiniCPM-o 4.5 full-duplex model plugin: engine policy and session policy in one class.
Engine policy (scheduler token budget, resumable Stage0 prompt, listen
decision) and session policy (client config validation, reference-audio
resolution, per-stage sampling knobs) both run engine-side, so one class owns
them. Client-supplied media URIs are resolved here through the media
connector; workers only ever receive normalized PCM payloads.
"""
from __future__ import annotations
import asyncio
import base64
from base64 import b64decode
from binascii import Error as BinasciiError
from collections.abc import Mapping
from copy import deepcopy
from typing import TYPE_CHECKING, Any, cast
import numpy as np
from numpy.typing import NDArray
from vllm.multimodal.media import MediaConnector
from vllm.sampling_params import SamplingParams
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
from vllm_omni.engine.duplex.contracts import (
DuplexAppendPlan,
DuplexFence,
DuplexOutputAction,
DuplexOutputDecision,
)
from vllm_omni.engine.duplex.plugin import (
DuplexModelPlugin,
DuplexRuntimeConfigError,
EncodeAudio,
reject_changed_runtime_value,
)
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.capabilities import (
minicpmo45_native_capabilities,
)
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.data_plane import (
MiniCPMO45DataPlaneContext,
MiniCPMO45DataPlaneSession,
)
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.policy import MiniCPMO45DuplexPolicy
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.session import (
MiniCPMO45ServingSessionState,
)
if TYPE_CHECKING:
import torch
from transformers import PreTrainedTokenizerBase
from vllm.config import ModelConfig
_DUPLEX_CHUNK_SAMPLES = 16000
_DUPLEX_SAMPLES_PER_AUDIO_TOKEN = 1600
# <image> + 64 resampler embeddings + </image> per frame (max_slice_nums=1),
# matching MiniCPMO45DuplexPolicy.VISION_TOKENS_PER_FRAME.
_DUPLEX_VISION_TOKENS_PER_FRAME = 66
# Official stacked pair uses max_slice_nums=[2, 1]: the current frame is HD
# sliced (1 source + 2 patches on 960x540) and the composite is not.
_DUPLEX_HD_SLICES_PER_BASE_FRAME = 3
PRIVATE_RUNTIME_CONFIG_KEYS = frozenset(
{
"duplex_stage_sampling_params",
"duplex_stage_max_tokens",
"duplex_stage0_max_tokens",
"duplex_scheduler_token_id",
"duplex_first_append_context_tokens",
"ref_audio_data",
"ref_audio_format",
"ref_audio_sample_rate_hz",
"initial_user_text",
}
)
class MiniCPMO45ClientRuntimeConfigError(DuplexRuntimeConfigError):
pass
# ---- engine policy helpers: scheduler token budget ----
def _duplex_frame_count(payload: object) -> int:
if not isinstance(payload, dict):
return 0
frames = payload.get("video_frames")
if not isinstance(frames, list):
return 0
return sum(1 for frame in frames if isinstance(frame, str) and frame)
def _duplex_vision_tokens(payload: object) -> int:
"""Scheduler slots for this append's camera track.
Audio is never stacked: a unit still carries one second of soundtrack.
``stack_frames`` only adds a second *image*. Official HD on that pair is
``[2, 1]``, so the base frame reserves three 66-token blocks and every
extra frame reserves one.
"""
count = _duplex_frame_count(payload)
if count <= 0:
return 0
if count >= 2:
return (_DUPLEX_HD_SLICES_PER_BASE_FRAME + (count - 1)) * _DUPLEX_VISION_TOKENS_PER_FRAME
return count * _DUPLEX_VISION_TOKENS_PER_FRAME
def _duplex_pcm_sample_count(payload: object) -> int | None:
if not isinstance(payload, dict):
return None
audio = payload.get("audio") or payload.get("data")
if payload.get("format") != "pcm_f32le" or not isinstance(audio, str):
return None
try:
raw = b64decode(audio, validate=True)
except (BinasciiError, ValueError):
return None
return len(raw) // 4
def duplex_payload_is_exact_chunks(payload: object) -> bool:
sample_count = _duplex_pcm_sample_count(payload)
return sample_count is not None and sample_count != 0 and sample_count % _DUPLEX_CHUNK_SAMPLES == 0
def duplex_first_append_unit_count(payload: object) -> int | None:
sample_count = _duplex_pcm_sample_count(payload)
if not sample_count or sample_count % _DUPLEX_CHUNK_SAMPLES != 0:
return None
return max(1, sample_count // _DUPLEX_CHUNK_SAMPLES - 1)
def duplex_scheduler_token_budget(payload: object, *, default: int = 64) -> int:
vision_tokens = _duplex_vision_tokens(payload)
sample_count = _duplex_pcm_sample_count(payload)
if sample_count is None:
return max(1, int(default)) + vision_tokens
sample_count = max(1, sample_count)
if sample_count % _DUPLEX_CHUNK_SAMPLES == 0:
units = sample_count // _DUPLEX_CHUNK_SAMPLES
return units * (2 + _DUPLEX_CHUNK_SAMPLES // _DUPLEX_SAMPLES_PER_AUDIO_TOKEN) + vision_tokens
return max(16, min(768, sample_count // _DUPLEX_SAMPLES_PER_AUDIO_TOKEN + 8)) + vision_tokens
def duplex_first_append_context_reserve(runtime_config: object) -> int:
if not isinstance(runtime_config, dict):
return 48
exact = runtime_config.get("duplex_first_append_context_tokens")
if isinstance(exact, int) and exact >= 0:
return exact
reserve = 48
ref = runtime_config.get("ref_audio_data")
if isinstance(ref, str) and ref:
try:
raw = b64decode(ref, validate=True)
except (BinasciiError, ValueError):
raw = b""
if raw:
reserve += max(0, (len(raw) // 4) // _DUPLEX_SAMPLES_PER_AUDIO_TOKEN + 8)
return reserve
def _duplex_force_listen_count(extra_body: object) -> int:
raw = extra_body.get("force_listen_count") if isinstance(extra_body, dict) else None
try:
return 0 if raw is None else max(0, int(raw))
except (TypeError, ValueError):
return 0
def build_duplex_data_plane_prompt(
*,
request_id: str,
fence: DuplexFence,
session_config: dict[str, object],
runtime_config: dict[str, object],
seq: int,
turn_seq: int,
payload: object,
final: bool,
) -> dict[str, object]:
token_budget = duplex_scheduler_token_budget(payload)
if seq <= 1:
context_reserve = duplex_first_append_context_reserve(runtime_config)
token_budget += context_reserve
first_units = duplex_first_append_unit_count(payload)
if first_units is not None:
token_budget = context_reserve + first_units * 12 - 1 + _duplex_vision_tokens(payload)
if seq > 1 and duplex_payload_is_exact_chunks(payload):
token_budget += 1
if final and duplex_payload_is_exact_chunks(payload):
token_budget += 12
extra_body = session_config.get("extra_body")
raw_token_id = runtime_config.get("duplex_scheduler_token_id")
try:
token_id = 0 if raw_token_id is None else max(0, int(raw_token_id))
except (TypeError, ValueError):
token_id = 0
force_listen_count = _duplex_force_listen_count(extra_body)
if (
force_listen_count > 0
and turn_seq <= force_listen_count
and isinstance(payload, dict)
and payload.get("force_listen") is not True
):
payload = {**payload, "force_listen": True}
return {
"prompt_token_ids": [token_id] * token_budget,
"model_intermediate_buffer": {
"request_id": request_id,
"global_request_id": [fence.session_id],
"duplex": {
"fence": fence,
"session_id": fence.session_id,
"epoch": fence.epoch,
"seq": seq,
"turn_id": fence.turn_id,
"turn_seq": turn_seq,
"mode": "append_audio_chunk",
"payload": payload,
"final": final,
"data_plane": True,
"session_config": dict(session_config),
"runtime_config": dict(runtime_config),
"scheduler_token_budget": token_budget,
"scheduler_token_id": token_id,
},
},
}
# ---- engine policy helpers: listen decision ----
def _coerce_int(value: object) -> int | None:
detach = getattr(value, "detach", None)
if callable(detach):
try:
flat: torch.Tensor = detach().cpu().reshape(-1)
if flat.numel() == 0:
return None
value = flat[0].item()
except Exception:
return None
try:
return int(cast(Any, value)) # Any: duck-typed scalar (int/float/str/tensor item)
except (TypeError, ValueError):
return None
def _coerce_int_list(value: object) -> list[int]:
if value is None:
return []
if hasattr(value, "detach"):
try:
value = value.detach().cpu().reshape(-1).tolist()
except Exception:
return []
if not isinstance(value, (list, tuple)):
return []
return [token_id for item in value if (token_id := _coerce_int(item)) is not None]
def _first_completion(output: object) -> object | None:
outputs = getattr(output, "outputs", None)
return outputs[0] if isinstance(outputs, list) and outputs else None
def _multimodal_output(output: object, completion: object | None) -> dict[str, object]:
metadata = getattr(output, "multimodal_output", None)
if isinstance(metadata, dict):
return metadata
metadata = getattr(completion, "multimodal_output", None) if completion is not None else None
return metadata if isinstance(metadata, dict) else {}
def _special_token_ids(metadata: dict[str, object]) -> dict[str, int]:
sources: list[object] = [metadata.get("special_token_ids"), metadata.get("meta")]
sources.append(
{
key.removeprefix("meta."): value
for key, value in metadata.items()
if isinstance(key, str) and key.startswith("meta.")
}
)
token_ids: dict[str, int] = {}
for source in sources:
if not isinstance(source, dict):
continue
for key, value in source.items():
token_id = _coerce_int(value)
if isinstance(key, str) and token_id is not None and token_id >= 0:
token_ids[key] = token_id
return token_ids
def _completion_token_ids(completion: object | None) -> list[int]:
if completion is None:
return []
for attribute in ("token_ids", "cumulative_token_ids"):
token_ids = _coerce_int_list(getattr(completion, attribute, None))
if token_ids:
return token_ids
return []
def _stage_config_value(runtime_config: dict[str, object], key: str, stage_id: int) -> object | None:
raw = runtime_config.get(key)
if isinstance(raw, dict):
value = raw.get(stage_id)
return raw.get(str(stage_id)) if value is None else value
if isinstance(raw, (list, tuple)) and stage_id < len(raw):
return raw[stage_id]
return None
# ---- session policy helpers: tokenizer / reference audio ----
def _load_tokenizer(model_config: ModelConfig | None) -> PreTrainedTokenizerBase | None:
model_path = getattr(model_config, "model", None)
if not isinstance(model_path, str) or not model_path:
return None
try:
from transformers import AutoTokenizer
return AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
local_files_only=True,
)
except Exception:
return None
def _convert_token_to_id(tokenizer: PreTrainedTokenizerBase, token: str) -> int | None:
convert = getattr(tokenizer, "convert_tokens_to_ids", None)
value = None
if callable(convert):
value = convert(token)
if isinstance(value, list):
value = value[0] if len(value) == 1 else None
if value is None:
token_id = -1
else:
try:
token_id = int(value)
except (TypeError, ValueError):
token_id = -1
unk_token_id = getattr(tokenizer, "unk_token_id", None)
if token_id >= 0 and token_id != unk_token_id:
return token_id
encode = getattr(tokenizer, "encode", None)
if callable(encode):
try:
ids = list(encode(token, add_special_tokens=False))
except TypeError:
ids = list(encode(token))
if len(ids) == 1:
try:
token_id = int(ids[0])
except (TypeError, ValueError):
token_id = -1
if token_id >= 0 and token_id != unk_token_id:
return token_id
return None
def _stage0_stop_token_ids(tokenizer: PreTrainedTokenizerBase | None) -> list[int]:
if tokenizer is None:
return []
out: list[int] = []
stop_token_fields = (
"chunk_eos_token_id",
"chunk_tts_eos_token_id",
"listen_token_id",
"turn_eos_token_id",
)
for field in stop_token_fields:
token = MiniCPMO45DuplexPolicy.SPECIAL_TOKEN_FIELDS[field]
token_id = _convert_token_to_id(tokenizer, token)
if token_id is not None and token_id not in out:
out.append(token_id)
return out
def _scheduler_token_id(tokenizer: PreTrainedTokenizerBase | None) -> int | None:
if tokenizer is None:
return None
scheduler_tokens = (
MiniCPMO45DuplexPolicy.SPECIAL_TOKEN_FIELDS["unit_token_id"],
MiniCPMO45DuplexPolicy.OPTIONAL_TOKEN_FIELDS["audio_placeholder_token_id"],
)
for token in scheduler_tokens:
token_id = _convert_token_to_id(tokenizer, token)
if token_id is not None:
return token_id
eos_id = getattr(tokenizer, "eos_token_id", None)
if eos_id is None:
return None
try:
return int(eos_id)
except (TypeError, ValueError):
return None
async def resolve_ref_audio(ref_audio: str, *, model_config: ModelConfig | None) -> tuple[NDArray[np.float32], int]:
connector = MediaConnector(
allowed_local_media_path=getattr(model_config, "allowed_local_media_path", None),
allowed_media_domains=getattr(model_config, "allowed_media_domains", None),
)
wav_np, sr = await connector.fetch_audio_async(ref_audio)
return np.asarray(wav_np, dtype=np.float32), int(sr)
def normalize_ref_audio(wav_np: NDArray[np.float32], sample_rate: int, *, target_sr: int) -> NDArray[np.float32]:
wav_np = np.asarray(wav_np, dtype=np.float32)
if wav_np.ndim > 1:
wav_np = wav_np.mean(axis=-1)
wav_np = wav_np.reshape(-1)
if sample_rate <= 0 or sample_rate == target_sr or wav_np.size == 0:
return wav_np.astype(np.float32, copy=False)
import torch
import torchaudio
audio = torch.from_numpy(wav_np).to(dtype=torch.float32).unsqueeze(0)
resampled = torchaudio.functional.resample(audio, int(sample_rate), int(target_sr))
return resampled.squeeze(0).cpu().numpy().astype(np.float32, copy=False)
def _apply_first_append_context_tokens(
runtime_config: dict[str, object],
*,
tokenizer: PreTrainedTokenizerBase | None,
instructions: object,
initial_user_text: object,
ref_sample_count: int | None,
) -> None:
"""Precompute the exact session-context token count for the engine.
The first data-plane append carries the system template and optional
reference-audio embeddings ahead of the first unit. The engine reserves
scheduler slots from this count; an inexact count turns into pad
embeddings inside the model KV (surplus) or truncated context (deficit),
so it is computed with the same template and pooling math the worker uses.
"""
if "duplex_first_append_context_tokens" in runtime_config or tokenizer is None:
return
prefix, suffix = MiniCPMO45DuplexPolicy.session_context_texts(
instructions,
ref_sample_count is not None,
initial_user_text,
)
try:
prefix_ids = tokenizer.encode(prefix, add_special_tokens=False)
suffix_ids = tokenizer.encode(suffix, add_special_tokens=False)
except Exception:
return
ref_tokens = MiniCPMO45DuplexPolicy.audio_token_count(ref_sample_count or 0)
runtime_config["duplex_first_append_context_tokens"] = len(prefix_ids) + ref_tokens + len(suffix_ids)
def _apply_default_scheduler_policy(
runtime_config: dict[str, object],
*,
config: DuplexSessionConfig,
tokenizer: PreTrainedTokenizerBase | None,
) -> None:
stage0_max_tokens = config.max_tokens if isinstance(config.max_tokens, int) and config.max_tokens > 0 else 20
runtime_config["duplex_stage_max_tokens"] = {"0": stage0_max_tokens, "1": 8192}
stage0_params: dict[str, object] = {
"temperature": config.temperature if config.temperature is not None else 0.7,
"top_p": 0.8,
"top_k": 20,
"repetition_penalty": 1.05,
}
stop_token_ids = _stage0_stop_token_ids(tokenizer)
if stop_token_ids:
stage0_params["stop_token_ids"] = stop_token_ids
# Stage 1 keeps the deploy YAML's codec knobs, minus upstream's
# min_new_token=50: that floor is for whole-utterance chat TTS, while a
# duplex chunk is 26 codec samples, so check_stop would never release
# the Talker and Thinker would stall on the next model turn.
runtime_config["duplex_stage_sampling_params"] = {"0": stage0_params, "1": {"min_tokens": 0}}
scheduler_token_id = _scheduler_token_id(tokenizer)
if scheduler_token_id is not None:
runtime_config["duplex_scheduler_token_id"] = scheduler_token_id
class MiniCPMO45DuplexPlugin(DuplexModelPlugin):
"""MiniCPM-owned sampling policy, append planning, session state and output projection."""
plugin_id = "minicpmo45"
private_runtime_config_keys = PRIVATE_RUNTIME_CONFIG_KEYS
silence_continuation_samples = 16000
def __init__(self, encode_audio: EncodeAudio) -> None:
super().__init__(encode_audio)
self.data_plane = MiniCPMO45DataPlaneSession(encode_audio)
# The tokenizer is only needed for special-token ids and the session
# context token count; it is the same for every session, so load it
# once per model path, off the orchestrator loop.
self._tokenizers: dict[str, PreTrainedTokenizerBase | None] = {}
self._tokenizer_lock = asyncio.Lock()
async def _tokenizer_for(self, model_config: ModelConfig | None) -> PreTrainedTokenizerBase | None:
model_path = getattr(model_config, "model", None)
key = model_path if isinstance(model_path, str) else ""
if key in self._tokenizers:
return self._tokenizers[key]
async with self._tokenizer_lock:
if key not in self._tokenizers:
self._tokenizers[key] = await asyncio.to_thread(_load_tokenizer, model_config)
return self._tokenizers[key]
# ---- engine policy (the resumable Stage0 request) ----
def configure_sampling_params(
self,
*,
runtime_config: dict[str, object],
defaults: tuple[object, ...],
) -> tuple[object, ...]:
configured: list[object] = []
for stage_id, default in enumerate(defaults):
max_tokens = _coerce_int(_stage_config_value(runtime_config, "duplex_stage_max_tokens", stage_id))
raw_overrides = _stage_config_value(runtime_config, "duplex_stage_sampling_params", stage_id)
overrides = dict(raw_overrides) if isinstance(raw_overrides, dict) else {}
if not isinstance(default, SamplingParams) or (not overrides and (max_tokens is None or max_tokens <= 0)):
configured.append(default)
continue
params = default.clone()
if max_tokens is not None and max_tokens > 0:
params.max_tokens = max_tokens
for name, value in overrides.items():
if not hasattr(params, name):
continue
setattr(params, name, value)
if name == "stop_token_ids":
all_stop_token_ids = getattr(params, "_all_stop_token_ids", None)
if isinstance(all_stop_token_ids, set):
all_stop_token_ids.update(int(token_id) for token_id in value)
configured.append(params)
return tuple(configured)
def plan_append(
self,
*,
request_id: str,
fence: DuplexFence,
session_config: dict[str, object],
runtime_config: dict[str, object],
seq: int,
turn_seq: int,
payload: object,
final: bool,
sampling_params: object,
) -> DuplexAppendPlan:
del sampling_params
return DuplexAppendPlan(
prompt=build_duplex_data_plane_prompt(
request_id=request_id,
fence=fence,
session_config=session_config,
runtime_config=runtime_config,
seq=seq,
turn_seq=turn_seq,
payload=payload,
final=final,
)
)
def decide_output(
self,
*,
stage_id: int,
final_stage_id: int,
segment_finished: bool,
segment_token_ids: tuple[int, ...],
segment_output_metadata: dict[str, object],
output: object,
) -> DuplexOutputDecision | None:
if stage_id >= final_stage_id or not segment_finished:
return None
completion = _first_completion(output)
output_metadata = _multimodal_output(output, completion)
special_token_ids = _special_token_ids(segment_output_metadata)
special_token_ids.update(_special_token_ids(output_metadata))
listen_id = special_token_ids.get("listen_token_id")
if listen_id is None:
return None
stop_reason = getattr(completion, "stop_reason", None) if completion is not None else None
token_ids = _completion_token_ids(completion) or list(segment_token_ids)
if _coerce_int(stop_reason) != listen_id and (not token_ids or token_ids[-1] != listen_id):
return None
metadata = dict(output_metadata)
for key, value in special_token_ids.items():
metadata.setdefault(f"meta.{key}", value)
metadata.update(
{
"duplex_direct_response": True,
"duplex_native_decision": "listen",
"model_listen": True,
"listen_source": "model_listen",
}
)
return DuplexOutputDecision(
action=DuplexOutputAction.DIRECT_RESPONSE,
metadata=metadata,
)
# ---- session policy ----
def create_session_state(self) -> MiniCPMO45ServingSessionState:
return MiniCPMO45ServingSessionState()
def capabilities(self, *, max_sessions: int) -> DuplexCapabilities:
return minicpmo45_native_capabilities(max_sessions=max_sessions)
def validate_client_extra_body(self, extra_body: object) -> None:
if not isinstance(extra_body, dict):
return
private_keys = sorted(PRIVATE_RUNTIME_CONFIG_KEYS.intersection(extra_body))
if private_keys:
raise MiniCPMO45ClientRuntimeConfigError(
"duplex runtime configuration is server-owned: " + ", ".join(private_keys)
)
async def prepare_runtime_config(
self, config: DuplexSessionConfig, *, model_config: ModelConfig | None
) -> dict[str, object]:
extra_body = dict(config.extra_body)
if any(key in extra_body for key in ("ref_audio_path", "tts_ref_audio_path")):
raise MiniCPMO45ClientRuntimeConfigError(
"ref_audio_path is not accepted by duplex sessions; use ref_audio URI instead",
code="unsupported_ref_audio_path",
)
runtime_config: dict[str, object] = {"instructions": config.instructions}
# ``duplex_initial_user_text`` is the older extra_body spelling and
# still works; the session field is the framework-level one.
initial_user_text = extra_body.pop("duplex_initial_user_text", None)
if not (isinstance(initial_user_text, str) and initial_user_text):
initial_user_text = config.initial_user_text
if isinstance(initial_user_text, str) and initial_user_text:
runtime_config["initial_user_text"] = initial_user_text
tokenizer = await self._tokenizer_for(model_config)
_apply_default_scheduler_policy(runtime_config, config=config, tokenizer=tokenizer)
ref_audio = config.ref_audio
extra_ref_audio = extra_body.get("ref_audio")
if ref_audio is None and isinstance(extra_ref_audio, str):
extra_body.pop("ref_audio")
ref_audio = extra_ref_audio
extra_tts_ref_audio = extra_body.get("tts_ref_audio")
if ref_audio is None and isinstance(extra_tts_ref_audio, str):
extra_body.pop("tts_ref_audio")
ref_audio = extra_tts_ref_audio
if ref_audio is None:
if any(str(modality).lower() == "audio" for modality in config.modalities):
raise MiniCPMO45ClientRuntimeConfigError(
"MiniCPM-o duplex audio output requires ref_audio",
code="ref_audio_required",
)
_apply_first_append_context_tokens(
runtime_config,
tokenizer=tokenizer,
instructions=config.instructions,
initial_user_text=initial_user_text,
ref_sample_count=None,
)
config.extra_body = extra_body
return runtime_config
wav_np, sr = await resolve_ref_audio(ref_audio, model_config=model_config)
# torchaudio resampling is CPU work: keep it off the orchestrator loop.
wav_np = await asyncio.to_thread(normalize_ref_audio, wav_np, int(sr), target_sr=16000)
# Trim to a whole number of pooled audio embeddings (100 ms frames) so
# the first-append scheduler reserve can count them exactly.
usable = (len(wav_np) // MiniCPMO45DuplexPolicy.SAMPLES_PER_AUDIO_TOKEN) * (
MiniCPMO45DuplexPolicy.SAMPLES_PER_AUDIO_TOKEN
)
wav_np = wav_np[:usable]
ref_audio_bytes = np.ascontiguousarray(wav_np, dtype=np.float32).tobytes()
runtime_config["ref_audio_data"] = base64.b64encode(ref_audio_bytes).decode("ascii")
runtime_config["ref_audio_format"] = "pcm_f32le"
runtime_config["ref_audio_sample_rate_hz"] = 16000
_apply_first_append_context_tokens(
runtime_config,
tokenizer=tokenizer,
instructions=config.instructions,
initial_user_text=initial_user_text,
ref_sample_count=len(wav_np),
)
config.extra_body = extra_body
config.ref_audio = None
return runtime_config
def runtime_config_for_update(
self,
config: DuplexSessionConfig,
current: Mapping[str, object],
) -> dict[str, object]:
runtime_config = deepcopy(dict(current))
reject_changed_runtime_value(
config.instructions,
runtime_config.get("instructions"),
message="instructions cannot be changed after the session is created",
code="instructions_update_unsupported",
error_cls=MiniCPMO45ClientRuntimeConfigError,
)
stage_max_tokens = runtime_config.get("duplex_stage_max_tokens")
stage_max_tokens = deepcopy(stage_max_tokens) if isinstance(stage_max_tokens, dict) else {}
stage_max_tokens["0"] = (
config.max_tokens if isinstance(config.max_tokens, int) and config.max_tokens > 0 else 20
)
stage_max_tokens.setdefault("1", 8192)
runtime_config["duplex_stage_max_tokens"] = stage_max_tokens
stage_sampling = runtime_config.get("duplex_stage_sampling_params")
stage_sampling = deepcopy(stage_sampling) if isinstance(stage_sampling, dict) else {}
stage0 = stage_sampling.get("0")
stage0 = deepcopy(stage0) if isinstance(stage0, dict) else {}
stage0["temperature"] = config.temperature if config.temperature is not None else 0.7
stage_sampling["0"] = stage0
runtime_config["duplex_stage_sampling_params"] = stage_sampling
return runtime_config
def data_plane_context(
self,
*,
epoch: int,
turn_id: int,
active_response_turn_id: int | None,
active_response_id: str | None,
auto_responds: bool,
response_format: str,
speed: float | None,
modalities: tuple[str, ...],
) -> MiniCPMO45DataPlaneContext:
return MiniCPMO45DataPlaneContext(
epoch=epoch,
turn_id=turn_id,
active_response_turn_id=active_response_turn_id,
active_response_id=active_response_id,
auto_responds=auto_responds,
response_format=response_format,
speed=speed,
modalities=modalities,
)
__all__ = [
"PRIVATE_RUNTIME_CONFIG_KEYS",
"MiniCPMO45ClientRuntimeConfigError",
"MiniCPMO45DuplexPlugin",
"build_duplex_data_plane_prompt",
"duplex_first_append_context_reserve",
"duplex_first_append_unit_count",
"duplex_payload_is_exact_chunks",
"duplex_scheduler_token_budget",
"normalize_ref_audio",
"resolve_ref_audio",
]
@@ -3,7 +3,10 @@
from __future__ import annotations
from typing import Any
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from transformers import PreTrainedTokenizerBase
class MiniCPMO45DuplexPolicy:
@@ -89,7 +92,7 @@ class MiniCPMO45DuplexPolicy:
}
@classmethod
def token_ids_from_tokenizer(cls, tokenizer: Any) -> dict[str, int]:
def token_ids_from_tokenizer(cls, tokenizer: PreTrainedTokenizerBase) -> dict[str, int]:
convert = getattr(tokenizer, "convert_tokens_to_ids", None)
def token_id(token: str) -> int:
@@ -1,439 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import math
from base64 import b64decode
from binascii import Error as BinasciiError
from typing import Any, cast
from vllm.sampling_params import SamplingParams
from vllm_omni.engine.duplex.messages import DuplexFence
from vllm_omni.engine.duplex.runtime import (
DuplexAppendPlan,
DuplexInputMode,
DuplexOutputAction,
DuplexOutputDecision,
)
_DUPLEX_CHUNK_SAMPLES = 16000
_DUPLEX_SAMPLES_PER_AUDIO_TOKEN = 1600
# <image> + 64 resampler embeddings + </image> per frame (max_slice_nums=1),
# matching MiniCPMO45DuplexPolicy.VISION_TOKENS_PER_FRAME.
_DUPLEX_VISION_TOKENS_PER_FRAME = 66
# Official stacked pair uses max_slice_nums=[2, 1]: the current frame is HD
# sliced (1 source + up to 2 patches, e.g. on 960x540) and the composite is
# not. The patch count depends on the frame size (see
# ``_duplex_hd_slice_count``); the constant is the fallback when the frame
# header cannot be read.
_DUPLEX_HD_SLICES_PER_BASE_FRAME = 3
_DUPLEX_HD_MAX_SLICE_NUMS = 2
_DUPLEX_SCALE_RESOLUTION = 448
def _duplex_frames(payload: object) -> list[str]:
if not isinstance(payload, dict):
return []
frames = payload.get("video_frames")
if not isinstance(frames, list):
return []
return [frame for frame in frames if isinstance(frame, str) and frame]
def _duplex_frame_count(payload: object) -> int:
return len(_duplex_frames(payload))
def _duplex_frame_size(frame_b64: str) -> tuple[int, int] | None:
"""Pixel size of a base64 JPEG/PNG frame from its header, or ``None``."""
from io import BytesIO
try:
from PIL import Image
with Image.open(BytesIO(b64decode(frame_b64, validate=True))) as image:
width, height = image.size
except Exception: # noqa: BLE001 - Stage0 rejects bad frames with a reason
return None
if width <= 0 or height <= 0:
return None
return int(width), int(height)
def _duplex_hd_slice_count(image_size: tuple[int, int], max_slice_nums: int) -> int:
"""Number of HD patches ``MiniCPMVImageProcessor.get_sliced_grid`` adds.
Port of the official grid selection (``scale_resolution=448``): an image
whose area fits in one 448x448 tile is not sliced at all, otherwise the
grid closest to the image aspect ratio among ``multiple-1 .. multiple+1``
splits is used. Stage0 runs the same processor, so the scheduler budget
and the worker-built embeddings agree.
"""
width, height = image_size
ratio = width * height / (_DUPLEX_SCALE_RESOLUTION * _DUPLEX_SCALE_RESOLUTION)
multiple = min(math.ceil(ratio), max_slice_nums)
if multiple <= 1:
return 0
log_ratio = math.log(width / height)
best_grid = (1, 1)
min_error = float("inf")
for split_grids_nums in (multiple - 1, multiple, multiple + 1):
if split_grids_nums == 1 or split_grids_nums > max_slice_nums:
continue
for m in range(1, split_grids_nums + 1):
if split_grids_nums % m:
continue
grid = (m, split_grids_nums // m)
error = abs(log_ratio - math.log(grid[0] / grid[1]))
if error < min_error:
best_grid = grid
min_error = error
return best_grid[0] * best_grid[1]
def _duplex_vision_tokens(payload: object) -> int:
"""Scheduler slots for this append's camera track.
Audio is never stacked: a unit still carries one second of soundtrack.
``stack_frames`` only adds a second *image*. Official HD on that pair is
``max_slice_nums=[2, 1]``: the base frame keeps its source block plus the
HD patches the processor cuts for its size (two for a 960x540 camera
frame, none for anything that fits in one 448x448 tile) and every extra
frame is one block. A single frame is never sliced. The count must match
the embeddings Stage0 builds exactly: surplus slots become pad
embeddings inside the KV.
"""
frames = _duplex_frames(payload)
count = len(frames)
if count <= 0:
return 0
if count == 1:
return _DUPLEX_VISION_TOKENS_PER_FRAME
base_size = _duplex_frame_size(frames[0])
if base_size is None:
base_blocks = _DUPLEX_HD_SLICES_PER_BASE_FRAME
else:
base_blocks = 1 + _duplex_hd_slice_count(base_size, _DUPLEX_HD_MAX_SLICE_NUMS)
return (base_blocks + (count - 1)) * _DUPLEX_VISION_TOKENS_PER_FRAME
def _duplex_pcm_sample_count(payload: object) -> int | None:
if not isinstance(payload, dict):
return None
audio = payload.get("audio") or payload.get("data")
if payload.get("format") != "pcm_f32le" or not isinstance(audio, str):
return None
try:
raw = b64decode(audio, validate=True)
except (BinasciiError, ValueError):
return None
return len(raw) // 4
def duplex_payload_is_exact_chunks(payload: object) -> bool:
sample_count = _duplex_pcm_sample_count(payload)
return sample_count is not None and sample_count != 0 and sample_count % _DUPLEX_CHUNK_SAMPLES == 0
def duplex_first_append_unit_count(payload: object) -> int | None:
sample_count = _duplex_pcm_sample_count(payload)
if not sample_count or sample_count % _DUPLEX_CHUNK_SAMPLES != 0:
return None
return max(1, sample_count // _DUPLEX_CHUNK_SAMPLES - 1)
def duplex_scheduler_token_budget(payload: object, *, default: int = 64) -> int:
vision_tokens = _duplex_vision_tokens(payload)
sample_count = _duplex_pcm_sample_count(payload)
if sample_count is None:
return max(1, int(default)) + vision_tokens
sample_count = max(1, sample_count)
if sample_count % _DUPLEX_CHUNK_SAMPLES == 0:
units = sample_count // _DUPLEX_CHUNK_SAMPLES
return units * (2 + _DUPLEX_CHUNK_SAMPLES // _DUPLEX_SAMPLES_PER_AUDIO_TOKEN) + vision_tokens
return max(16, min(768, sample_count // _DUPLEX_SAMPLES_PER_AUDIO_TOKEN + 8)) + vision_tokens
def duplex_first_append_context_reserve(runtime_config: object) -> int:
if not isinstance(runtime_config, dict):
return 48
exact = runtime_config.get("duplex_first_append_context_tokens")
if isinstance(exact, int) and exact >= 0:
return exact
reserve = 48
ref = runtime_config.get("ref_audio_data")
if isinstance(ref, str) and ref:
try:
raw = b64decode(ref, validate=True)
except (BinasciiError, ValueError):
raw = b""
if raw:
reserve += max(0, (len(raw) // 4) // _DUPLEX_SAMPLES_PER_AUDIO_TOKEN + 8)
return reserve
def _duplex_force_listen_count(extra_body: object) -> int:
raw = extra_body.get("force_listen_count") if isinstance(extra_body, dict) else None
try:
return 0 if raw is None else max(0, int(raw))
except (TypeError, ValueError):
return 0
def build_duplex_data_plane_prompt(
*,
request_id: str,
fence: DuplexFence,
session_config: dict[str, Any],
runtime_config: dict[str, Any],
seq: int,
turn_seq: int,
mode: DuplexInputMode,
payload: object,
final: bool,
) -> dict[str, Any]:
token_budget = duplex_scheduler_token_budget(payload)
if seq <= 1:
context_reserve = duplex_first_append_context_reserve(runtime_config)
token_budget += context_reserve
first_units = duplex_first_append_unit_count(payload)
if first_units is not None:
token_budget = context_reserve + first_units * 12 - 1 + _duplex_vision_tokens(payload)
if seq > 1 and duplex_payload_is_exact_chunks(payload):
token_budget += 1
if final and duplex_payload_is_exact_chunks(payload):
token_budget += 12
extra_body = session_config.get("extra_body")
raw_token_id = runtime_config.get("duplex_scheduler_token_id")
try:
token_id = 0 if raw_token_id is None else max(0, int(raw_token_id))
except (TypeError, ValueError):
token_id = 0
force_listen_count = _duplex_force_listen_count(extra_body)
if (
force_listen_count > 0
and turn_seq <= force_listen_count
and isinstance(payload, dict)
and payload.get("force_listen") is not True
):
payload = {**payload, "force_listen": True}
return {
"prompt_token_ids": [token_id] * token_budget,
"model_intermediate_buffer": {
"request_id": request_id,
"global_request_id": [fence.session_id],
"duplex": {
"fence": fence,
"session_id": fence.session_id,
"incarnation": fence.incarnation,
"epoch": fence.epoch,
"seq": seq,
"turn_id": fence.turn_id,
"response_seq": fence.response_seq,
"turn_seq": turn_seq,
"mode": mode.value,
"payload": payload,
"final": final,
"data_plane": True,
"session_config": dict(session_config),
"runtime_config": dict(runtime_config),
"scheduler_token_budget": token_budget,
"scheduler_token_id": token_id,
},
},
}
def _coerce_int(value: object) -> int | None:
detach = getattr(value, "detach", None)
if callable(detach):
try:
flat: Any = detach().cpu().reshape(-1)
if flat.numel() == 0:
return None
value = flat[0].item()
except Exception:
return None
try:
return int(cast(Any, value))
except (TypeError, ValueError):
return None
def _coerce_int_list(value: object) -> list[int]:
if value is None:
return []
if hasattr(value, "detach"):
try:
value = value.detach().cpu().reshape(-1).tolist()
except Exception:
return []
if not isinstance(value, (list, tuple)):
return []
return [token_id for item in value if (token_id := _coerce_int(item)) is not None]
def _first_completion(output: object) -> object | None:
outputs = getattr(output, "outputs", None)
return outputs[0] if isinstance(outputs, list) and outputs else None
def _multimodal_output(output: object, completion: object | None) -> dict[str, Any]:
metadata = getattr(output, "multimodal_output", None)
if isinstance(metadata, dict):
return metadata
metadata = getattr(completion, "multimodal_output", None) if completion is not None else None
return metadata if isinstance(metadata, dict) else {}
def _special_token_ids(metadata: dict[str, Any]) -> dict[str, int]:
sources: list[object] = [metadata.get("special_token_ids"), metadata.get("meta")]
sources.append(
{
key.removeprefix("meta."): value
for key, value in metadata.items()
if isinstance(key, str) and key.startswith("meta.")
}
)
token_ids: dict[str, int] = {}
for source in sources:
if not isinstance(source, dict):
continue
for key, value in source.items():
token_id = _coerce_int(value)
if isinstance(key, str) and token_id is not None and token_id >= 0:
token_ids[key] = token_id
return token_ids
def _completion_token_ids(completion: object | None) -> list[int]:
if completion is None:
return []
for attribute in ("token_ids", "cumulative_token_ids"):
token_ids = _coerce_int_list(getattr(completion, attribute, None))
if token_ids:
return token_ids
return []
def _stage_config_value(runtime_config: dict[str, Any], key: str, stage_id: int) -> object | None:
raw = runtime_config.get(key)
if isinstance(raw, dict):
value = raw.get(stage_id)
return raw.get(str(stage_id)) if value is None else value
if isinstance(raw, (list, tuple)) and stage_id < len(raw):
return raw[stage_id]
return None
class MiniCPMO45DuplexRuntimeExtension:
def configure_sampling_params(
self,
*,
runtime_config: dict[str, Any],
defaults: tuple[object, ...],
) -> tuple[object, ...]:
configured: list[object] = []
for stage_id, default in enumerate(defaults):
max_tokens = _coerce_int(_stage_config_value(runtime_config, "duplex_stage_max_tokens", stage_id))
raw_overrides = _stage_config_value(runtime_config, "duplex_stage_sampling_params", stage_id)
overrides = dict(raw_overrides) if isinstance(raw_overrides, dict) else {}
if not isinstance(default, SamplingParams) or (not overrides and (max_tokens is None or max_tokens <= 0)):
configured.append(default)
continue
params = default.clone()
if max_tokens is not None and max_tokens > 0:
params.max_tokens = max_tokens
for name, value in overrides.items():
if not hasattr(params, name):
continue
setattr(params, name, value)
if name == "stop_token_ids":
all_stop_token_ids = getattr(params, "_all_stop_token_ids", None)
if isinstance(all_stop_token_ids, set):
all_stop_token_ids.update(int(token_id) for token_id in value)
configured.append(params)
return tuple(configured)
def plan_append(
self,
*,
request_id: str,
fence: DuplexFence,
session_config: dict[str, Any],
runtime_config: dict[str, Any],
seq: int,
turn_seq: int,
mode: DuplexInputMode,
payload: object,
final: bool,
sampling_params: object,
) -> DuplexAppendPlan:
del sampling_params
return DuplexAppendPlan(
prompt=build_duplex_data_plane_prompt(
request_id=request_id,
fence=fence,
session_config=session_config,
runtime_config=runtime_config,
seq=seq,
turn_seq=turn_seq,
mode=mode,
payload=payload,
final=final,
)
)
def decide_output(
self,
*,
stage_id: int,
final_stage_id: int,
segment_finished: bool,
segment_token_ids: tuple[int, ...],
segment_output_metadata: dict[str, Any],
output: object,
) -> DuplexOutputDecision | None:
if stage_id >= final_stage_id or not segment_finished:
return None
completion = _first_completion(output)
output_metadata = _multimodal_output(output, completion)
special_token_ids = _special_token_ids(segment_output_metadata)
special_token_ids.update(_special_token_ids(output_metadata))
listen_id = special_token_ids.get("listen_token_id")
if listen_id is None:
return None
stop_reason = getattr(completion, "stop_reason", None) if completion is not None else None
token_ids = _completion_token_ids(completion) or list(segment_token_ids)
if _coerce_int(stop_reason) != listen_id and (not token_ids or token_ids[-1] != listen_id):
return None
metadata = dict(output_metadata)
for key, value in special_token_ids.items():
metadata.setdefault(f"meta.{key}", value)
metadata.update(
{
"duplex_direct_response": True,
"duplex_native_decision": "listen",
"model_listen": True,
"listen_source": "model_listen",
}
)
return DuplexOutputDecision(
action=DuplexOutputAction.DIRECT_RESPONSE,
metadata=metadata,
)
__all__ = [
"MiniCPMO45DuplexRuntimeExtension",
"build_duplex_data_plane_prompt",
"duplex_first_append_context_reserve",
"duplex_first_append_unit_count",
"duplex_payload_is_exact_chunks",
"duplex_scheduler_token_budget",
]
@@ -1,102 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from collections.abc import Callable, Mapping
from typing import Any
from vllm_omni.entrypoints.duplex.protocol import DuplexCapabilities
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.adapter import (
MiniCPMO45NativeDuplexServingAdapter,
)
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.capabilities import (
minicpmo45_native_capabilities,
)
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.data_plane import (
MiniCPMO45DataPlaneContext,
MiniCPMO45DataPlaneSession,
)
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.session import (
MiniCPMO45ServingSessionState,
)
EncodeAudio = Callable[[object, int, str, float | None], str | None]
class MiniCPMO45ServingRuntimeAdapter:
"""MiniCPM-owned serving state, input packing, and output projection."""
adapter_id = "minicpmo45"
clean_response_done_prefix = ""
interrupted_tts_prefix = ""
private_runtime_config_keys = MiniCPMO45NativeDuplexServingAdapter.PRIVATE_RUNTIME_CONFIG_KEYS
def __init__(self, encode_audio: EncodeAudio) -> None:
self.session_states: dict[str, MiniCPMO45ServingSessionState] = {}
self.data_plane = MiniCPMO45DataPlaneSession(encode_audio)
def create_session_state(self) -> MiniCPMO45ServingSessionState:
return MiniCPMO45ServingSessionState()
def session_state(self, session_id: str) -> MiniCPMO45ServingSessionState:
state = self.session_states.get(session_id)
if state is None:
state = self.create_session_state()
self.session_states[session_id] = state
return state
def remove_session_state(self, session_id: str) -> None:
self.session_states.pop(session_id, None)
@staticmethod
def is_enabled(config: object) -> bool:
return MiniCPMO45NativeDuplexServingAdapter.is_enabled(config) # type: ignore[arg-type]
@staticmethod
def capabilities(*, max_sessions: int) -> DuplexCapabilities:
return minicpmo45_native_capabilities(max_sessions=max_sessions)
@staticmethod
def validate_client_extra_body(extra_body: object) -> None:
MiniCPMO45NativeDuplexServingAdapter.validate_client_extra_body(extra_body)
@staticmethod
async def prepare_runtime_config(config: object, *, model_config: Any) -> dict[str, object]:
return await MiniCPMO45NativeDuplexServingAdapter.prepare_runtime_config(
config, # type: ignore[arg-type]
model_config=model_config,
)
@staticmethod
def runtime_config_for_update(
config: object,
current: Mapping[str, object],
) -> dict[str, object]:
return MiniCPMO45NativeDuplexServingAdapter.runtime_config_for_update(
config, # type: ignore[arg-type]
dict(current),
)
@staticmethod
def data_plane_context(
*,
epoch: int,
turn_id: int,
active_response_turn_id: int | None,
active_response_id: str | None,
auto_responds: bool,
response_format: str,
speed: float | None,
modalities: tuple[str, ...],
) -> MiniCPMO45DataPlaneContext:
return MiniCPMO45DataPlaneContext(
epoch=epoch,
turn_id=turn_id,
active_response_turn_id=active_response_turn_id,
active_response_id=active_response_id,
auto_responds=auto_responds,
response_format=response_format,
speed=speed,
modalities=modalities,
)
@@ -4,34 +4,31 @@
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from vllm_omni.engine.duplex.plugin import DuplexModelSessionState
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.input import (
MiniCPMO45PcmAppendBuffer,
)
@dataclass(slots=True)
class MiniCPMO45ServingSessionState:
"""Mutable serving state owned by one MiniCPM duplex session."""
class MiniCPMO45ServingSessionState(DuplexModelSessionState):
"""Mutable model-owned state of one MiniCPM duplex session (owned by the session runner)."""
audio_buffer: MiniCPMO45PcmAppendBuffer = field(default_factory=MiniCPMO45PcmAppendBuffer)
input_since_commit: bool = False
speech_since_commit: bool = False
native_context_locked: bool = False
context_locked: bool = False
committed_audio_payload: dict[str, object] | None = None
committed_audio_operation_id: str | None = None
committed_audio_reserved_bytes: int = 0
deferred_response_create: bool = False
deferred_precreate_response: bool = False
data_plane_task: asyncio.Task[None] | None = None
data_plane_restart_requested: bool = False
continuation_owner_id: str | None = None
continuation_units: int = 0
pending_silence_task: asyncio.Task[bool] | None = None
pending_silence_owner_id: str | None = None
silence_continuation_scheduler: Callable[..., Awaitable[bool]] | None = None
def retain_committed_audio(
self,
@@ -6,15 +6,22 @@ from __future__ import annotations
import base64
import copy
import time
from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass, field
from threading import Lock
from typing import Any
from typing import TYPE_CHECKING, Any, cast
import numpy as np
from numpy.typing import NDArray
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.policy import MiniCPMO45DuplexPolicy
if TYPE_CHECKING:
import torch
from PIL import Image
from torch import nn
_MINICPMO45_SPECIAL_TOKEN_FIELDS = MiniCPMO45DuplexPolicy.SPECIAL_TOKEN_FIELDS
_MINICPMO45_OPTIONAL_TOKEN_FIELDS = MiniCPMO45DuplexPolicy.OPTIONAL_TOKEN_FIELDS
_MINICPMO45_PROCESSOR_LOAD_LOCK = Lock()
@@ -23,17 +30,19 @@ _MINICPMO45_PROCESSOR_LOAD_LOCK = Lock()
@dataclass
class _MiniCPMO45Stage0SessionState:
session_id: str
#: Any: MiniCPM-o remote-code processor (transformers, no importable type).
streaming_processor: Any | None = None
audio_buffer: np.ndarray = field(default_factory=lambda: np.array([], dtype=np.float32))
audio_buffer: NDArray[np.float32] = field(default_factory=lambda: np.array([], dtype=np.float32))
audio_chunk_idx: int = 0
context_embeds: list[Any] = field(default_factory=list)
context_embeds: list[torch.Tensor] = field(default_factory=list)
context_token_ids: list[int] = field(default_factory=list)
current_turn_ended: bool = True
prepared_append_identity: tuple[int | None, int] | None = None
prepared_inputs_embeds: Any | None = None
prepared_inputs_embeds: torch.Tensor | None = None
prepared_input_token_ids: list[int] = field(default_factory=list)
prepared_result: dict[str, Any] = field(default_factory=dict)
audio_past_key_values: Any | None = None
prepared_result: dict[str, object] = field(default_factory=dict)
#: Opaque transformers cache, handed back to the model unchanged.
audio_past_key_values: object | None = None
pending_terminator_token: int | None = None
last_terminator_token: int | None = None
pending_speech_context: bool = False
@@ -59,7 +68,7 @@ class MiniCPMO45Stage0DuplexRuntime:
image_start_token_id: int = -1
image_end_token_id: int = -1
def __init__(self, stage_model: Any, *, model_path: str | None = None, device: str = "cuda") -> None:
def __init__(self, stage_model: nn.Module, *, model_path: str | None = None, device: str = "cuda") -> None:
self.stage_model = stage_model
self.model_path = model_path
self.device = device
@@ -85,7 +94,7 @@ class MiniCPMO45Stage0DuplexRuntime:
def _configure_streaming_processor(
self,
state: _MiniCPMO45Stage0SessionState | None = None,
) -> Any | None:
) -> Any | None: # Any: MiniCPM-o remote-code processor
processor = self.processor
if processor is None:
return None
@@ -129,9 +138,9 @@ class MiniCPMO45Stage0DuplexRuntime:
def _prepare_session_context(
self,
state: _MiniCPMO45Stage0SessionState,
session_config: dict[str, Any],
session_config: dict[str, object],
*,
runtime_config: dict[str, Any] | None = None,
runtime_config: dict[str, object] | None = None,
) -> None:
if not self._stage_runtime_ready():
return
@@ -163,14 +172,14 @@ class MiniCPMO45Stage0DuplexRuntime:
def _stage_prefill_embeddings_only(
self,
state: _MiniCPMO45Stage0SessionState,
audio_waveform: Any,
audio_waveform: NDArray[np.float32] | None,
*,
video_frames: list[Any] | None = None,
video_frames: list[Image.Image] | None = None,
epoch: int | None = None,
seq: int | None = None,
is_speech: bool = False,
final: bool = False,
) -> dict[str, Any]:
) -> dict[str, object]:
"""Build scheduler-owned Stage0 input embeddings for one audio append.
Unlike the legacy worker-control path, this method never calls an eager
@@ -217,7 +226,7 @@ class MiniCPMO45Stage0DuplexRuntime:
# Omni duplex: encode this append's camera frames so the first unit can
# carry them, mirroring official streaming_prefill (feed <unit>, then
# every frame_list entry as its own <image> block, then the audio).
frame_blocks: list[Any] = []
frame_blocks: list[list[torch.Tensor]] = []
if video_frames:
self._require_vision_token_ids()
encoded_frames = self._stage_vision_embeddings(video_frames)
@@ -227,7 +236,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return self._stage_prefill_result(False, start_time, "streaming vision embedding failed")
frame_blocks = encoded_frames
embed_parts: list[Any] = []
embed_parts: list[torch.Tensor] = []
token_ids: list[int] = []
if state.audio_chunk_idx == 0 and state.context_embeds:
embed_parts.extend(state.context_embeds)
@@ -336,7 +345,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return result
@staticmethod
def _stage_prefill_result(success: bool, start_time: float, reason: str = "") -> dict[str, Any]:
def _stage_prefill_result(success: bool, start_time: float, reason: str = "") -> dict[str, object]:
return {
"success": success,
"prefill_success": success,
@@ -347,14 +356,14 @@ class MiniCPMO45Stage0DuplexRuntime:
}
@staticmethod
def _as_2d_tensor(value: Any) -> Any:
def _as_2d_tensor(value: torch.Tensor) -> torch.Tensor:
if value.ndim == 1:
return value.unsqueeze(0)
if value.ndim == 3 and value.shape[0] == 1:
return value.squeeze(0)
return value
def _embed_token(self, token_id: int) -> Any:
def _embed_token(self, token_id: int) -> torch.Tensor:
import torch
token = torch.tensor([int(token_id)], dtype=torch.long, device=self._model_device())
@@ -362,7 +371,7 @@ class MiniCPMO45Stage0DuplexRuntime:
embeds = embedder(token)
return self._as_2d_tensor(embeds)
def _token_embedding_dtype(self) -> Any:
def _token_embedding_dtype(self) -> torch.dtype | None:
"""dtype of the decoder token embeddings, the unit's reference dtype.
Official ``get_vllm_embedding`` casts vision hidden states to the token
@@ -376,7 +385,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return dtype
return getattr(next(self.thinker.parameters()), "dtype", None)
def _token_embedder(self) -> Any:
def _token_embedder(self) -> Callable[[torch.Tensor], torch.Tensor]:
nested_embed = getattr(getattr(getattr(self.thinker, "llm", None), "model", None), "embed_tokens", None)
if callable(nested_embed):
return nested_embed
@@ -391,7 +400,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return embedder
raise AttributeError("MiniCPM-o stage0 model does not expose token embeddings")
def _model_device(self) -> Any:
def _model_device(self) -> torch.device | str:
try:
return next(self.thinker.parameters()).device
except Exception:
@@ -402,14 +411,14 @@ class MiniCPMO45Stage0DuplexRuntime:
pass
return self.device
def _streaming_chunk_size(self, processor: Any | None = None) -> int:
def _streaming_chunk_size(self, processor: Any | None = None) -> int: # Any: remote-code processor
processor = processor or self.processor
get_chunk = getattr(processor, "get_streaming_chunk_size", None)
if callable(get_chunk):
return int(get_chunk())
return 16000
def _sample_rate(self, processor: Any | None = None) -> int:
def _sample_rate(self, processor: Any | None = None) -> int: # Any: remote-code processor
processor = processor or self.processor
return int(
self._stage_param(
@@ -418,7 +427,7 @@ class MiniCPMO45Stage0DuplexRuntime:
)
)
def _first_chunk_samples(self, default_chunk_size: int, processor: Any | None = None) -> int:
def _first_chunk_samples(self, default_chunk_size: int, processor: Any | None = None) -> int: # Any: processor
processor = processor or self.processor
if getattr(processor, "_streaming_mel_processor", None) is None:
return default_chunk_size
@@ -427,7 +436,7 @@ class MiniCPMO45Stage0DuplexRuntime:
def _pad_first_audio_chunk_if_needed(
self,
state: _MiniCPMO45Stage0SessionState,
processor: Any | None = None,
processor: Any | None = None, # Any: remote-code processor
) -> None:
if state.audio_chunk_idx != 0 or len(state.audio_buffer) == 0:
return
@@ -440,7 +449,7 @@ class MiniCPMO45Stage0DuplexRuntime:
padding: np.ndarray = np.zeros(first_chunk_samples - len(state.audio_buffer), dtype=np.float32)
state.audio_buffer = np.concatenate([padding, state.audio_buffer])
def _stage_param(self, name: str, default: Any) -> Any:
def _stage_param(self, name: str, default: object) -> Any: # Any: attribute read off the remote-code model
for target in (self.stage_model, self.thinker, getattr(self.thinker, "llm", None)):
value = getattr(target, name, None)
if value is not None:
@@ -455,7 +464,7 @@ class MiniCPMO45Stage0DuplexRuntime:
chunk_idx: int,
default_chunk_size: int,
*,
processor: Any | None = None,
processor: Any | None = None, # Any: remote-code processor
) -> int:
processor = processor or self.processor
if chunk_idx != 0:
@@ -472,11 +481,11 @@ class MiniCPMO45Stage0DuplexRuntime:
def _process_streaming_audio(
self,
audio_chunk: Any,
audio_chunk: NDArray[np.float32],
chunk_idx: int,
*,
processor: Any | None = None,
) -> Any:
processor: Any | None = None, # Any: remote-code processor
) -> Any: # Any: transformers BatchFeature (or the dict fallback below)
processor = processor or self.processor
process = getattr(processor, "process_audio_streaming", None)
if callable(process):
@@ -488,10 +497,10 @@ class MiniCPMO45Stage0DuplexRuntime:
def _stage_audio_embeddings(
self,
batch_feature: Any,
batch_feature: Any, # Any: transformers BatchFeature
*,
state: _MiniCPMO45Stage0SessionState | None = None,
) -> Any | None:
) -> torch.Tensor | None:
if hasattr(batch_feature, "to"):
batch_feature = batch_feature.to(self.device)
self._ensure_dynamic_cache_compat()
@@ -534,17 +543,17 @@ class MiniCPMO45Stage0DuplexRuntime:
self.thinker.audio_past_key_values = previous_audio_past_key_values
@staticmethod
def _decode_ref_audio_from_session_config(session_config: dict[str, Any]) -> Any | None:
def _decode_ref_audio_from_session_config(session_config: dict[str, object]) -> NDArray[np.float32] | None:
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.input import decode_native_ref_audio_from_config
return decode_native_ref_audio_from_config({"extra_body": session_config})
def _stage_ref_audio_embeddings(
self,
ref_audio: Any,
ref_audio: NDArray[np.float32],
*,
state: _MiniCPMO45Stage0SessionState | None = None,
) -> Any | None:
) -> torch.Tensor | None:
process_audio = getattr(self.processor, "process_audio", None)
if callable(process_audio):
batch_feature = process_audio([ref_audio])
@@ -606,16 +615,16 @@ class MiniCPMO45Stage0DuplexRuntime:
DynamicCache.get_usable_length = get_usable_length # type: ignore[attr-defined]
@staticmethod
def _cat_nested_tensors(value: Any) -> Any | None:
def _cat_nested_tensors(value: object) -> torch.Tensor | None:
import torch
tensors = []
tensors: list[torch.Tensor] = []
def collect(item: Any) -> None:
def collect(item: object) -> None:
if item is None:
return
if hasattr(item, "detach"):
tensors.append(item)
tensors.append(cast("torch.Tensor", item))
return
if isinstance(item, dict):
for child in item.values():
@@ -655,7 +664,7 @@ class MiniCPMO45Stage0DuplexRuntime:
}
@staticmethod
def _load_processor_from_path(model_path: str | None) -> Any | None:
def _load_processor_from_path(model_path: str | None) -> Any | None: # Any: remote-code AutoProcessor
if not model_path:
return None
try:
@@ -752,7 +761,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return self.stage_padding_token_id()
@staticmethod
def _decode_audio_payload(payload: dict[str, Any]) -> Any:
def _decode_audio_payload(payload: dict[str, object]) -> NDArray[np.float32]:
audio = payload.get("audio") or payload.get("data")
if not isinstance(audio, str):
raise ValueError("audio append payload requires base64 audio")
@@ -762,7 +771,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return np.frombuffer(base64.b64decode(audio), dtype=np.float32)
@staticmethod
def _decode_video_frames_payload(payload: dict[str, Any]) -> list[Any]:
def _decode_video_frames_payload(payload: dict[str, object]) -> list[Image.Image]:
"""Decode omni-duplex camera frames (base64 JPEG/PNG) to PIL images."""
frames = payload.get("video_frames")
if not isinstance(frames, list) or not frames:
@@ -771,7 +780,7 @@ class MiniCPMO45Stage0DuplexRuntime:
from PIL import Image
decoded: list[Any] = []
decoded: list[Image.Image] = []
for frame_b64 in frames:
if not isinstance(frame_b64, str) or not frame_b64:
continue
@@ -826,7 +835,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return [1]
return [2] + [1] * (frame_count - 1)
def _encode_processed_vision(self, processed: Any) -> list[Any] | None:
def _encode_processed_vision(self, processed: Any) -> list[torch.Tensor] | None: # Any: BatchFeature
targets = (self.stage_model, self.thinker, getattr(self.stage_model, "model", None))
for target in targets:
if target is None:
@@ -842,8 +851,8 @@ class MiniCPMO45Stage0DuplexRuntime:
device, dtype = vpm_param.device, vpm_param.dtype
pixel_nested = processed["pixel_values"]
tgt_nested = processed["tgt_sizes"]
flat_pixels: list[Any] = []
flat_tgt: list[Any] = []
flat_pixels: list[torch.Tensor] = []
flat_tgt: list[torch.Tensor] = []
for image_slices, image_tgt in zip(pixel_nested, tgt_nested):
for slice_pixels in image_slices:
flat_pixels.append(slice_pixels.to(device=device, dtype=dtype))
@@ -858,7 +867,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return None
expected = MiniCPMO45DuplexPolicy.VISION_EMBEDS_PER_FRAME
embed_dtype = self._token_embedding_dtype()
out: list[Any] = []
out: list[torch.Tensor] = []
for block in hidden:
block_2d = self._as_2d_tensor(block)
if int(block_2d.shape[0]) != expected:
@@ -869,7 +878,7 @@ class MiniCPMO45Stage0DuplexRuntime:
return out
return None
def _stage_vision_embeddings(self, frames: list[Any]) -> list[list[Any]] | None:
def _stage_vision_embeddings(self, frames: list[Image.Image]) -> list[list[torch.Tensor]] | None:
"""Encode camera frames for omni duplex via the loaded vision tower.
Official ``streaming_prefill`` encodes each ``frame_list`` entry as its
@@ -883,7 +892,7 @@ class MiniCPMO45Stage0DuplexRuntime:
process_image = getattr(self.processor, "process_image", None)
if not callable(process_image):
return None
out: list[list[Any]] = []
out: list[list[torch.Tensor]] = []
for frame, max_slices in zip(frames, self._official_max_slice_nums(len(frames))):
try:
processed = process_image([frame], max_slice_nums=max_slices)
@@ -157,15 +157,13 @@ class MiniCPMO45OmniForConditionalGeneration(nn.Module, SupportsMultiModal, Supp
del sampling_metadata
self._minicpmo45_active_duplex_rows = [row.row_idx for row in rows]
self._minicpmo45_duplex_row_sessions = {
row.row_idx: (row.session_id, row.incarnation) for row in rows if row.session_id is not None
row.row_idx: row.session_id for row in rows if row.session_id is not None
}
request_sessions = getattr(self, "_minicpmo45_duplex_request_sessions", None)
if not isinstance(request_sessions, dict):
request_sessions = {}
self._minicpmo45_duplex_request_sessions = request_sessions
request_sessions.update(
{row.request_id: (row.session_id, row.incarnation) for row in rows if row.session_id is not None}
)
request_sessions.update({row.request_id: row.session_id for row in rows if row.session_id is not None})
self._minicpmo45_duplex_row_payloads = {row.row_idx: row.payload for row in rows if row.payload is not None}
self._minicpmo45_duplex_row_max_tokens = {
row.row_idx: row.max_tokens for row in rows if row.max_tokens is not None
@@ -199,7 +197,7 @@ class MiniCPMO45OmniForConditionalGeneration(nn.Module, SupportsMultiModal, Supp
force_listen = payload.get("force_listen") is True
is_speech = payload.get("is_speech")
segment_key = (row.request_id, row.seq if row.seq is not None else -1)
session_key = (row.session_id, row.incarnation) if row.session_id is not None else None
session_key = row.session_id
if turn_eos_id >= 0 and session_key is not None:
state = helper_sessions.get(session_key) if isinstance(helper_sessions, dict) else None
pending_speech_context = (
@@ -326,16 +324,12 @@ class MiniCPMO45OmniForConditionalGeneration(nn.Module, SupportsMultiModal, Supp
helper = self._duplex_data_plane_helper()
session_id = str(duplex.get("session_id") or "")
try:
incarnation = int(duplex.get("incarnation", 0))
except (TypeError, ValueError):
incarnation = 0
payload = duplex.get("payload")
if not session_id or not isinstance(payload, dict):
embeds = input_embeds if input_embeds is not None else self.get_input_embeddings(input_ids)
return input_ids, embeds, {"duplex": {"prefill_success": False, "reason": "bad_duplex_payload"}}
session_key = (session_id, incarnation)
session_key = session_id
state = helper.sessions.get(session_key)
if state is None:
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.stage0 import (
@@ -24,13 +24,7 @@ MINICPMO_4_5_PIPELINE = PipelineConfig(
model_type="minicpmo_4_5",
default_deploy_config_name="minicpmo_4_5.yaml",
model_arch="MiniCPMO45OmniForConditionalGeneration",
duplex_runtime_extension=(
"vllm_omni.model_executor.models.minicpmo_4_5.duplex.runtime.MiniCPMO45DuplexRuntimeExtension"
),
duplex_serving_adapter=(
"vllm_omni.model_executor.models.minicpmo_4_5.duplex.serving_adapter.MiniCPMO45ServingRuntimeAdapter"
),
duplex_control_enabled=True,
duplex_plugin="vllm_omni.model_executor.models.minicpmo_4_5.duplex.plugin.MiniCPMO45DuplexPlugin",
# MiniCPM-o 4.5's HF config.json reports `model_type="minicpmo"` and
# `architectures=["MiniCPMO"]` — both shared verbatim with older MiniCPM-o
# 1.0 / 2.6 checkpoints. The only field distinguishing the generations is