[Core] Graduate MiniCPM-o 4.5 and PersonaPlex full-duplex serving out of experimental (#6196)

Signed-off-by: chickeyton <ngton2014@gmail.com>
Signed-off-by: Gao Han <hgaoaf@connect.ust.hk>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gao Han <hgaoaf@connect.ust.hk>
This commit is contained in:
authored and GitHub committed 2026-09-05 08:20:21 +00:00
1 parent d4096e01fe
commit 5d7fdf9350
179 files changed
+6462 -3832

No files matched your search

@@ -0,0 +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 .policy import MiniCPMO45DuplexPolicy
from .stage0 import MiniCPMO45Stage0DuplexRuntime
__all__ = [
"MiniCPMO45DuplexPolicy",
"MiniCPMO45NativeDuplexServingAdapter",
"MiniCPMO45ClientRuntimeConfigError",
"MiniCPMO45PcmAppendBuffer",
"MiniCPMO45Stage0DuplexRuntime",
]
@@ -0,0 +1,335 @@
# 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)
@@ -0,0 +1,48 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from vllm_omni.entrypoints.duplex.protocol import DuplexCapabilities
def minicpmo45_native_capabilities(*, max_sessions: int = 1) -> DuplexCapabilities:
"""The MiniCPM-o 4.5 native-duplex preset of the generic capability payload."""
supports_multi_session = max_sessions > 1
return DuplexCapabilities(
supports_model_native_turn_policy=True,
supports_barge_in=True,
supports_input_append=True,
supports_replace_latest_chunk=False,
supports_reencode_context=False,
supports_turn_commit_only=False,
supports_kv_lease=False,
supports_core_kv_lease=False,
supports_model_internal_state=True,
supports_stage_resumption=True,
supports_scheduler_native_append=False,
supports_core_resumable_request=True,
supports_stage_connector_handoff=True,
supports_independent_io_streams=True,
supports_realtime_endpoint=True,
supports_multi_session=supports_multi_session,
supports_multi_session_same_replica=supports_multi_session,
supports_session_lease=True,
supports_session_resume=True,
session_admission_mode="engine_managed",
supports_audio_truncate=True,
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,
# Barge-in latency depends on client chunking and lacks hardware E2E
# measurement, so do not advertise an invented target.
target_barge_in_latency_ms=None,
)
__all__ = ["minicpmo45_native_capabilities"]
@@ -0,0 +1,46 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from typing import Any
def patch_minicpmo_remote_config(config: Any) -> None:
"""Fill config fields expected by the vLLM MiniCPM implementation."""
seen: set[int] = set()
def patch_cfg(cfg: Any) -> None:
if cfg is None or id(cfg) in seen:
return
seen.add(id(cfg))
if getattr(cfg, "base_model_tp_plan", None) is None:
setattr(cfg, "base_model_tp_plan", {})
for value in getattr(cfg, "__dict__", {}).values():
if value is cfg:
continue
if hasattr(value, "__dict__") and (
value.__class__.__name__.endswith("Config")
or hasattr(value, "model_type")
or hasattr(value, "base_model_tp_plan")
):
patch_cfg(value)
patch_cfg(config)
tts_config = getattr(config, "tts_config", None)
if tts_config is None:
return
defaults = {
"top_p": 0.8,
"top_k": 100,
"temperature": 0.8,
"repetition_penalty": 1.05,
}
for name, value in defaults.items():
if isinstance(tts_config, dict):
tts_config.setdefault(name, value)
elif not hasattr(tts_config, name):
setattr(tts_config, name, value)
__all__ = ["patch_minicpmo_remote_config"]
@@ -0,0 +1,840 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass, field
import numpy as np
from vllm.logger import init_logger
from vllm_omni.engine.duplex.contracts import (
duplex_resource_request_belongs_to_session,
)
from vllm_omni.outputs.duplex import get_duplex_output_decision
logger = init_logger(__name__)
EncodeAudio = Callable[[object, int, str, float | None], str | None]
@dataclass(frozen=True, slots=True)
class MiniCPMO45DataPlaneContext:
"""Serving state needed to project one MiniCPM data-plane output."""
epoch: int = 0
turn_id: int = 0
active_response_turn_id: int | None = None
active_response_id: str | None = None
auto_responds: bool = False
response_format: str = "wav"
speed: float | None = None
modalities: tuple[str, ...] = ()
@dataclass(slots=True)
class _TurnState:
sent_segment_text: str = ""
has_text: bool = False
tts_eos_done: bool = False
turn_eos_done: bool = False
@dataclass(slots=True)
class _RequestState:
audio_offset: int = 0
uses_segment_text_metadata: bool = False
pending_audio_without_text: list[dict[str, object]] = field(default_factory=list)
terminal: bool = False
turns: dict[int | None, _TurnState] = field(default_factory=dict)
def turn(self, turn_id: int | None) -> _TurnState:
return self.turns.setdefault(turn_id, _TurnState())
class MiniCPMO45DataPlaneSession:
"""MiniCPM output projector and request/turn cursor owner.
The scheduler request owns cumulative Stage1 audio, while model turns own
transcript and terminal cursors. Keeping both levels in one object avoids
leaking MiniCPM-specific state into the generic Realtime handler.
"""
def __init__(self, encode_audio: EncodeAudio) -> None:
self._encode_audio = encode_audio
self._requests: dict[str, _RequestState] = {}
def begin_request(self, request_id: str) -> None:
state = self._requests.setdefault(request_id, _RequestState())
state.terminal = 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:
return False
state = self._requests.get(request_id)
return state is not None and state.terminal
def mark_terminal(self, request_id: str) -> None:
self._requests.setdefault(request_id, _RequestState()).terminal = True
def close_stream(self, request_id: str) -> None:
"""Release non-resumable request cursors after its drain finishes."""
state = self._requests.get(request_id)
if state is None:
return
state.audio_offset = 0
state.turns.pop(None, None)
def close_request(self, request_id: str) -> None:
self._requests.pop(request_id, None)
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None:
if active_request_id is not None:
self.close_request(active_request_id)
for request_id in list(self._requests):
if self.request_belongs_to_session(request_id, session_id):
self.close_request(request_id)
def has_request(self, request_id: str) -> bool:
return request_id in self._requests
def has_pending_audio(self, request_id: str) -> bool:
state = self._requests.get(request_id)
return bool(state and state.pending_audio_without_text)
def audio_offset(self, request_id: str | None) -> int | None:
if request_id is None:
return None
state = self._requests.get(request_id)
return state.audio_offset if state is not None and state.audio_offset > 0 else None
def project(
self,
result: object,
*,
context: MiniCPMO45DataPlaneContext | None = None,
) -> Iterator[dict[str, object]]:
if not isinstance(result, dict):
return
outputs = result.get("data_plane_outputs")
if not isinstance(outputs, list):
return
for output in outputs:
yield from self.project_output(output, context=context)
def project_output(
self,
output: object,
*,
context: MiniCPMO45DataPlaneContext | None = None,
) -> Iterator[dict[str, object]]:
context = context or MiniCPMO45DataPlaneContext()
stage_metrics = _output_stage_metrics(output)
def runtime_result(**values: object) -> dict[str, object]:
result = _runtime_result(**values)
if stage_metrics is not None:
result["stage_metrics"] = stage_metrics
return result
request_id = getattr(output, "request_id", None)
if not isinstance(request_id, str) or not request_id:
request_id = None
request_state = self._requests.setdefault(request_id, _RequestState()) if request_id is not None else None
outputs = getattr(output, "outputs", None)
completion = outputs[0] if isinstance(outputs, list) and outputs else None
text = getattr(completion, "text", "") if completion is not None else ""
direct_decision = get_duplex_output_decision(output)
direct_metadata = getattr(direct_decision, "metadata", None)
if isinstance(direct_metadata, Mapping):
mm_output = direct_metadata
else:
mm_output = getattr(output, "multimodal_output", None)
if not isinstance(mm_output, Mapping):
mm_output = getattr(completion, "multimodal_output", {}) if completion is not None else {}
if not mm_output:
inner_output = getattr(output, "request_output", None)
if inner_output is not None and inner_output is not output:
inner_mm_output = getattr(inner_output, "multimodal_output", None)
if isinstance(inner_mm_output, Mapping) and inner_mm_output:
mm_output = inner_mm_output
else:
inner_outputs = getattr(inner_output, "outputs", None)
inner_completion = inner_outputs[0] if isinstance(inner_outputs, list) and inner_outputs else None
inner_mm_output = (
getattr(inner_completion, "multimodal_output", None) if inner_completion is not None else None
)
if completion is None and inner_completion is not None:
completion = inner_completion
text = getattr(inner_completion, "text", "") or text
if isinstance(inner_mm_output, Mapping):
mm_output = inner_mm_output
mm_output = dict(mm_output) if isinstance(mm_output, Mapping) else {}
output_turn_id = output_turn_id_from_metadata(mm_output)
output_epoch = output_epoch_from_metadata(mm_output)
expected_turn_id = context.active_response_turn_id
stale_turn = expected_turn_id is not None and output_turn_id is not None and output_turn_id < expected_turn_id
if expected_turn_id is None and output_turn_id is not None:
stale_turn = output_turn_id < context.turn_id
stale_epoch = output_epoch is not None and output_epoch != context.epoch
if context.auto_responds and (stale_turn or stale_epoch):
return
mm_text = _llm_output_text(mm_output)
if mm_text:
text = mm_text
if request_state is not None:
request_state.uses_segment_text_metadata = True
elif request_state is not None and request_state.uses_segment_text_metadata:
text = ""
finished = bool(getattr(output, "finished", False))
tts_is_last_chunk = _bool_metadata(mm_output, ("tts_is_last_chunk",), default=False)
token_ids = _completion_token_ids(completion)
native_decision = _native_decision(completion, mm_output, token_ids=token_ids, finished=finished)
if native_decision == "listen":
listen_result = runtime_result(
stage_role="llm",
is_listen=True,
model_listen=True,
listen_source="model_listen",
data_plane_request_id=request_id,
end_of_turn=False,
)
if output_turn_id is not None:
listen_result["model_turn_id"] = output_turn_id
yield listen_result
return
raw_audio = next((mm_output[key] for key in ("audio", "model_outputs", "latent") if key in mm_output), None)
raw_audio_samples = _audio_num_samples(raw_audio)
offset_before = self.audio_offset(request_id)
audio_chunks = list(
self._encode_audio_chunks_with_duration(
mm_output,
request_id=request_id,
response_format=context.response_format,
speed=context.speed,
)
)
stage_turn_end = _bool_metadata(mm_output, ("turn_end", "end_of_turn"), default=False)
terminal_turn_state = request_state.turn(output_turn_id) if request_state is not None else None
stage_tts_eos = (
context.auto_responds
and 151645 in token_ids
and not audio_chunks
and raw_audio_samples is not None
and (raw_audio_samples == 0 or raw_audio_samples == offset_before)
and (terminal_turn_state is None or not terminal_turn_state.tts_eos_done)
)
tts_segment_end = bool(tts_is_last_chunk or stage_tts_eos) and (
terminal_turn_state is None or not terminal_turn_state.tts_eos_done
)
if tts_segment_end and terminal_turn_state is not None:
terminal_turn_state.tts_eos_done = True
stage_turn_end_new = bool(stage_turn_end) and (
terminal_turn_state is None or not terminal_turn_state.turn_eos_done
)
if stage_turn_end_new and terminal_turn_state is not None:
terminal_turn_state.turn_eos_done = True
unit_end_of_turn = stage_turn_end_new or (finished and not context.auto_responds)
text_turn_id = output_turn_id if output_turn_id is not None else context.turn_id
text_turn_state = request_state.turn(text_turn_id) if request_state is not None else None
if audio_chunks:
delta_text = self.segment_text_delta(request_id, text, turn_id=text_turn_id)
last_idx = len(audio_chunks) - 1
sample_rate_hz = _sample_rate_hz(mm_output)
audio_text_marks = _audio_text_marks(mm_output)
fallback_marks = _fallback_audio_text_marks(audio_chunks, delta_text)
audio_results: list[dict[str, object]] = []
for idx, (audio, duration_ms) in enumerate(audio_chunks):
native_result = runtime_result(
stage_role="tts",
is_listen=False,
data_plane_request_id=request_id,
text=delta_text if idx == 0 else "",
audio_data=audio,
audio_format=context.response_format,
audio_duration_ms=duration_ms,
audio_text_mark=idx == last_idx,
sample_rate_hz=sample_rate_hz,
end_of_turn=unit_end_of_turn and idx == last_idx,
abort_data_plane_request=tts_segment_end and idx == last_idx,
)
if output_turn_id is not None:
native_result["model_turn_id"] = output_turn_id
if audio_text_marks and idx == last_idx:
native_result["audio_text_marks"] = audio_text_marks
native_result["audio_text_marks_are_cumulative"] = True
elif idx < len(fallback_marks) and fallback_marks[idx]:
native_result["audio_text_marks"] = fallback_marks[idx]
native_result["audio_text_marks_are_cumulative"] = True
audio_results.append(native_result)
if context.auto_responds:
if delta_text and text_turn_state is not None:
text_turn_state.has_text = True
future_model_turn = (
context.active_response_turn_id is not None
and output_turn_id is not None
and output_turn_id > context.active_response_turn_id
)
response_turn_bound = context.active_response_id is not None and (
output_turn_id is None
or context.active_response_turn_id is None
or context.active_response_turn_id == output_turn_id
)
turn_has_text = text_turn_state is not None and text_turn_state.has_text
if not future_model_turn and not response_turn_bound and not turn_has_text:
if request_state is not None:
if tts_segment_end:
request_state.pending_audio_without_text.clear()
else:
request_state.pending_audio_without_text.extend(audio_results)
if tts_segment_end:
terminal_result = dict(audio_results[-1])
terminal_result.update(
audio_data="",
audio_duration_ms=0,
audio_text_mark=False,
end_of_turn=True,
)
yield terminal_result
return
if request_state is not None and request_state.pending_audio_without_text:
pending = request_state.pending_audio_without_text
request_state.pending_audio_without_text = []
yield from pending
yield from audio_results
return
if context.auto_responds and request_state is not None and isinstance(text, str) and text:
pending_audio = request_state.pending_audio_without_text
request_state.pending_audio_without_text = []
if pending_audio:
delta_text = self.segment_text_delta(request_id, text, turn_id=text_turn_id)
if delta_text:
pending_audio[0]["text"] = delta_text
if text_turn_state is not None:
text_turn_state.has_text = True
total_duration_ms = sum(
max(0, int(result.get("audio_duration_ms", 0) or 0)) for result in pending_audio
)
if total_duration_ms > 0 and not pending_audio[-1].get("audio_text_marks"):
pending_audio[-1]["audio_text_marks"] = [
{"text_chars": len(delta_text), "audio_end_ms": total_duration_ms}
]
pending_audio[-1]["audio_text_marks_are_cumulative"] = True
if unit_end_of_turn:
pending_audio[-1]["end_of_turn"] = True
if tts_segment_end:
pending_audio[-1]["abort_data_plane_request"] = True
yield from pending_audio
return
request_state.pending_audio_without_text = pending_audio
if tts_segment_end:
if unit_end_of_turn and request_state is not None and request_state.pending_audio_without_text:
request_state.pending_audio_without_text[-1]["end_of_turn"] = True
request_state.pending_audio_without_text[-1]["abort_data_plane_request"] = True
terminal_result = runtime_result(
stage_role="tts",
is_listen=False,
data_plane_request_id=request_id,
text="",
audio_data="",
audio_format=context.response_format,
audio_text_mark=False,
end_of_turn=unit_end_of_turn,
abort_data_plane_request=True,
)
if output_turn_id is not None:
terminal_result["model_turn_id"] = output_turn_id
yield terminal_result
return
if context.active_response_id is not None and unit_end_of_turn:
terminal_result = runtime_result(
stage_role="tts",
is_listen=False,
data_plane_request_id=request_id,
text="",
audio_data="",
audio_format=context.response_format,
audio_text_mark=False,
end_of_turn=True,
)
if output_turn_id is not None:
terminal_result["model_turn_id"] = output_turn_id
yield terminal_result
return
if request_id is not None and context.auto_responds and unit_end_of_turn and context.active_response_id is None:
# The legacy projector only removed the request-scoped pending
# buffer here when no explicit model-turn key was present.
if request_state is not None and output_turn_id is None:
request_state.pending_audio_without_text.clear()
terminal_result = runtime_result(
stage_role="tts",
is_listen=False,
data_plane_request_id=request_id,
text="",
audio_data="",
audio_format=context.response_format,
audio_text_mark=False,
end_of_turn=True,
abort_data_plane_request=True,
)
if output_turn_id is not None:
terminal_result["model_turn_id"] = output_turn_id
yield terminal_result
return
if (
finished
and context.auto_responds
and context.active_response_id is not None
and request_id is not None
and not unit_end_of_turn
):
listen_result = runtime_result(
stage_role="llm",
is_listen=True,
model_listen=False,
listen_source="auto_response_segment_complete",
reason="auto_response_segment_complete",
data_plane_request_id=request_id,
end_of_turn=False,
)
if output_turn_id is not None:
listen_result["model_turn_id"] = output_turn_id
yield listen_result
return
if not text:
if context.auto_responds:
return
if finished:
listen_result = runtime_result(
stage_role="llm",
is_listen=True,
model_listen=False,
listen_source="data_plane_finished_without_output",
reason="data_plane_finished_without_output",
data_plane_request_id=request_id,
end_of_turn=False,
)
if output_turn_id is not None:
listen_result["model_turn_id"] = output_turn_id
yield listen_result
return
if context.auto_responds:
return
if "audio" in context.modalities:
yield runtime_result(
stage_role="tts",
error_code="runtime_data_plane_text_without_audio",
error="MiniCPM-o native duplex data-plane produced text without audio.",
data_plane_request_id=request_id,
)
return
yield runtime_result(
stage_role="llm",
is_listen=False,
data_plane_request_id=request_id,
text=text if isinstance(text, str) else "",
audio_data="",
end_of_turn=unit_end_of_turn,
)
def segment_text_delta(self, request_id: str | None, text: object, *, turn_id: int | None = None) -> str:
if not isinstance(text, str) or not text:
return ""
if request_id is None:
return text
turn_state = self._requests.setdefault(request_id, _RequestState()).turn(turn_id)
sent_text = turn_state.sent_segment_text
if not sent_text:
delta_text = text
elif text == sent_text:
delta_text = ""
elif text.startswith(sent_text):
delta_text = text[len(sent_text) :]
else:
# The producer sends text for the current thinker segment, not a
# cumulative turn snapshot. Distinct adjacent segments need not
# have a prefix relationship and must both remain visible.
delta_text = text
turn_state.sent_segment_text = text
return delta_text
def slice_cumulative_audio(self, request_id: str | None, audio_data: object) -> object:
if request_id is None:
return audio_data
num_samples = _audio_num_samples(audio_data)
if num_samples is None or num_samples <= 0:
return audio_data
state = self._requests.setdefault(request_id, _RequestState())
prev_samples = state.audio_offset
if prev_samples <= 0:
state.audio_offset = num_samples
return audio_data
if num_samples == prev_samples:
return None
if num_samples < prev_samples:
state.audio_offset = num_samples
return audio_data
state.audio_offset = num_samples
try:
import torch
if isinstance(audio_data, torch.Tensor):
return audio_data.reshape(-1)[prev_samples:].contiguous()
return np.asarray(audio_data, dtype=np.float32).reshape(-1)[prev_samples:]
except Exception:
logger.exception("Failed to slice cumulative duplex audio output")
return audio_data
def _encode_audio_chunks_with_duration(
self,
mm_output: dict[str, object],
*,
request_id: str | None,
response_format: str,
speed: float | None,
) -> Iterator[tuple[str, int]]:
sample_rate_hz = _sample_rate_hz(mm_output)
audio_data = next((mm_output[key] for key in ("audio", "model_outputs", "latent") if key in mm_output), None)
if isinstance(audio_data, list):
for value in audio_data:
encoded = self._encode_audio(value, sample_rate_hz, response_format, speed)
if encoded:
duration_ms = int((_audio_num_samples(value) or 0) * 1000 / max(1, sample_rate_hz))
yield encoded, duration_ms
return
sliced = self.slice_cumulative_audio(request_id, audio_data)
encoded = self._encode_audio(sliced, sample_rate_hz, response_format, speed)
if encoded:
duration_ms = int((_audio_num_samples(sliced) or 0) * 1000 / max(1, sample_rate_hz))
yield encoded, duration_ms
@staticmethod
def request_belongs_to_session(request_id: str, session_id: str) -> bool:
return (
duplex_resource_request_belongs_to_session(request_id, session_id)
or request_id.startswith(f"duplex-{session_id}-")
or request_id.startswith(f"chatcmpl-duplex-{session_id}-")
)
def coerce_int(value: object) -> int | None:
if hasattr(value, "detach"):
try:
value = value.detach().cpu().reshape(-1)
if value.numel() == 0:
return None
value = value[0].item()
except Exception:
return None
elif hasattr(value, "reshape") and hasattr(value, "size"):
try:
value = value.reshape(-1)
if int(value.size) == 0:
return None
item = value[0]
value = item.item() if hasattr(item, "item") else item
except Exception:
return None
try:
return int(value)
except (TypeError, ValueError):
return None
def payload_turn_id(payload: object) -> int | None:
if not isinstance(payload, Mapping):
return None
return coerce_int(payload.get("duplex_turn_id"))
def output_turn_id_from_metadata(mm_output: dict[str, object]) -> int | None:
return _first_metadata_int(mm_output, "duplex_turn_id", "turn_id")
def output_epoch_from_metadata(mm_output: dict[str, object]) -> int | None:
return _first_metadata_int(mm_output, "duplex_epoch", "epoch")
def _first_metadata_int(mm_output: dict[str, object], *names: str) -> int | None:
candidates: list[object] = []
meta = mm_output.get("meta")
for name in names:
candidates.extend((mm_output.get(name), mm_output.get(f"meta.{name}")))
if isinstance(meta, dict):
candidates.append(meta.get(name))
for value in candidates:
result = coerce_int(value)
if result is not None:
return result
return None
def _runtime_result(**values: object) -> dict[str, object]:
return {
"supported": True,
**values,
"uses_model_runner_scheduler": True,
"runner_kv_backed": True,
"runtime_impl": "scheduler_data_plane",
"owned_runtime": False,
}
def _output_stage_metrics(output: object) -> dict[str, dict[str, object]] | None:
metrics = getattr(output, "metrics", None)
if not isinstance(metrics, Mapping):
return None
stage_metrics = metrics.get("stage_metrics")
if not isinstance(stage_metrics, Mapping):
return None
snapshot = {
str(stage_id): dict(values) for stage_id, values in stage_metrics.items() if isinstance(values, Mapping)
}
return snapshot or None
def _native_decision(
completion: object,
mm_output: dict[str, object],
*,
token_ids: list[int],
finished: bool,
) -> str | None:
if not finished:
return None
if mm_output.get("duplex_native_decision") == "listen" or mm_output.get("model_listen") is True:
return "listen"
listen_id = _special_token_ids(mm_output).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
if coerce_int(stop_reason) == listen_id:
return "listen"
return "listen" if token_ids and token_ids[-1] == listen_id else None
def _special_token_ids(mm_output: dict[str, object]) -> dict[str, int]:
sources: list[object] = []
raw_special = mm_output.get("special_token_ids")
if isinstance(raw_special, dict):
sources.append(raw_special)
raw_meta = mm_output.get("meta")
if isinstance(raw_meta, dict):
sources.append(raw_meta)
sources.append(
{
key.removeprefix("meta."): value
for key, value in mm_output.items()
if isinstance(key, str) and key.startswith("meta.")
}
)
out: dict[str, int] = {}
for source in sources:
if not isinstance(source, dict):
continue
for key, value in source.items():
if not isinstance(key, str):
continue
token_id = coerce_int(value)
if token_id is not None and token_id >= 0:
out[key] = token_id
return out
def _completion_token_ids(completion: object) -> list[int]:
if completion is None:
return []
for candidate in (
getattr(completion, "token_ids", None),
getattr(completion, "cumulative_token_ids", None),
):
token_ids = _coerce_int_list(candidate)
if token_ids:
return token_ids
return []
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 [item for raw in value if (item := coerce_int(raw)) is not None]
def _audio_num_samples(audio_data: object) -> int | None:
try:
import torch
if isinstance(audio_data, torch.Tensor):
return int(audio_data.numel())
return int(np.asarray(audio_data, dtype=np.float32).size)
except Exception:
return None
def _bool_metadata(
mm_output: dict[str, object],
names: tuple[str, ...],
*,
default: bool,
) -> bool:
def coerce(value: object) -> bool | None:
if value is None:
return None
if isinstance(value, bool):
return value
try:
import torch
if isinstance(value, torch.Tensor):
return bool(value.reshape(-1)[-1].item()) if value.numel() else None
except Exception:
pass
if isinstance(value, np.ndarray):
return bool(value.reshape(-1)[-1].item()) if value.size else None
if isinstance(value, np.generic):
return bool(value.item())
if isinstance(value, (list, tuple)):
return coerce(value[-1]) if value else None
if isinstance(value, (int, float)):
return bool(value)
return None
meta = mm_output.get("meta")
for name in names:
for key in (name, f"meta.{name}"):
result = coerce(mm_output.get(key))
if result is not None:
return result
if isinstance(meta, dict):
result = coerce(meta.get(name))
if result is not None:
return result
return default
def _sample_rate_hz(mm_output: dict[str, object]) -> int:
sr_raw = mm_output.get("sr")
if sr_raw is None:
sr_raw = mm_output.get("sample_rate_hz", mm_output.get("sample_rate"))
meta = mm_output.get("meta")
if sr_raw is None and isinstance(meta, dict):
sr_raw = meta.get("sr") or meta.get("sample_rate_hz") or meta.get("sample_rate")
if sr_raw is None:
sr_raw = mm_output.get("meta.sr") or mm_output.get("meta.sample_rate_hz") or mm_output.get("meta.sample_rate")
if hasattr(sr_raw, "item"):
try:
return int(sr_raw.item())
except Exception:
return 24000
return int(sr_raw) if isinstance(sr_raw, (int, float)) else 24000
def _audio_text_marks(mm_output: dict[str, object]) -> list[dict[str, object]]:
names = ("audio_text_marks", "text_audio_marks", "audio_text_alignment", "alignment_marks")
candidates = [mm_output.get(name) for name in names]
meta = mm_output.get("meta")
if isinstance(meta, dict):
candidates.extend(meta.get(name) for name in names)
candidates.extend(
value
for key, value in mm_output.items()
if isinstance(key, str) and key.startswith("meta.") and key.rsplit(".", 1)[-1] in names
)
for raw in candidates:
if not isinstance(raw, list):
continue
marks: list[dict[str, object]] = []
for item in raw:
if not isinstance(item, dict):
continue
text_chars = item.get("text_chars")
audio_end_ms = item.get("audio_end_ms", item.get("audio_ms"))
if isinstance(text_chars, (int, float)) and isinstance(audio_end_ms, (int, float)):
marks.append({"text_chars": max(0, int(text_chars)), "audio_end_ms": max(0, int(audio_end_ms))})
if marks:
return marks
return []
def _llm_output_text(mm_output: dict[str, object]) -> str:
candidates: list[object] = [
mm_output.get("llm_output_text"),
mm_output.get("text"),
mm_output.get("llm_output_text_utf8"),
mm_output.get("meta.llm_output_text_utf8"),
]
meta = mm_output.get("meta")
if isinstance(meta, dict):
candidates.extend((meta.get("llm_output_text"), meta.get("text"), meta.get("llm_output_text_utf8")))
candidates.extend(mm_output.get(key) for key in ("meta.llm_output_text", "meta.text"))
for value in candidates:
if isinstance(value, str) and value:
return value
decoded = _decode_text_tensor(value)
if decoded:
return decoded
if isinstance(value, list):
text_chunks = [item for item in value if isinstance(item, str)]
if text_chunks:
return "".join(text_chunks)
return ""
def _decode_text_tensor(value: object) -> str:
if value is None:
return ""
try:
if isinstance(value, np.ndarray):
raw = value.astype(np.uint8, copy=False).reshape(-1).tobytes()
elif hasattr(value, "detach"):
raw = value.detach().cpu().numpy().astype(np.uint8, copy=False).reshape(-1).tobytes()
else:
return ""
return raw.decode("utf-8", errors="ignore")
except Exception:
return ""
def _fallback_audio_text_marks(
audio_chunks: list[tuple[str, int]],
delta_text: str,
) -> list[list[dict[str, int]] | None]:
if not delta_text:
return []
total_duration_ms = sum(max(0, int(duration_ms)) for _, duration_ms in audio_chunks)
cumulative_duration_ms = 0
marks: list[list[dict[str, int]] | None] = []
for _, duration_ms in audio_chunks:
cumulative_duration_ms += max(0, int(duration_ms))
if total_duration_ms <= 0:
marks.append(None)
continue
text_chars = int(len(delta_text) * min(1.0, cumulative_duration_ms / float(total_duration_ms)))
marks.append([{"text_chars": max(0, text_chars), "audio_end_ms": max(0, cumulative_duration_ms)}])
return marks
@@ -0,0 +1,447 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
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",
"_force_listen",
"_is_speech",
"_owner",
"_raw",
"_sample_rate_hz",
"_spans",
"_turn_had_speech",
"_video_frames",
"operation_id",
"payload",
)
def __init__(
self,
*,
owner: MiniCPMO45PcmAppendBuffer,
operation_id: str,
payload: dict[str, object] | None,
raw: bytes,
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:
self._owner = owner
self.operation_id = operation_id
self.payload = payload
self._raw = raw
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
@property
def active(self) -> bool:
return self._active
@property
def byte_count(self) -> int:
return len(self._raw)
def commit(self) -> None:
self._owner._commit_reservation(self)
def rollback(self) -> None:
self._owner._rollback_reservation(self)
def validate_native_ref_audio_config(session_config: dict[str, Any]) -> None:
extra_body = session_config.get("extra_body")
if not isinstance(extra_body, dict):
extra_body = {}
if any(key in session_config for key in ("ref_audio_path", "tts_ref_audio_path")) or any(
key in extra_body for key in ("ref_audio_path", "tts_ref_audio_path")
):
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:
validate_native_ref_audio_config(session_config)
extra_body = session_config.get("extra_body")
if not isinstance(extra_body, dict):
extra_body = {}
audio_data = extra_body.get("ref_audio_data")
if audio_data is None:
return None
if not isinstance(audio_data, str):
raise TypeError("native duplex ref_audio_data must be base64 pcm_f32le")
fmt = extra_body.get("ref_audio_format") or "pcm_f32le"
if fmt != "pcm_f32le":
raise ValueError(f"unsupported native duplex ref_audio_format: {fmt!r}")
try:
raw = base64.b64decode(audio_data, validate=True)
except (ValueError, binascii.Error) as exc:
raise ValueError("invalid native duplex ref_audio_data") from exc
if len(raw) % 4:
raise ValueError("invalid native duplex ref_audio_data length")
return np.frombuffer(raw, dtype="<f4").astype(np.float32, copy=True)
class MiniCPMO45PcmAppendBuffer:
"""Accumulates short native-duplex PCM chunks into model-sized appends."""
def __init__(self) -> None:
self._buffer = bytearray()
self._spans: list[_PcmSpan] = []
self._sample_rate_hz: int | None = None
self._turn_had_speech = False
self._reservation_seq = 0
self._reservations: list[MiniCPMO45PcmAppendReservation] = []
# Omni duplex: queued camera frames (base64 JPEG), consumed FIFO at
# one frame per emitted model unit alongside the unit's audio.
self._frame_queue: list[str] = []
def clear(self) -> None:
for reservation in self._reservations:
reservation._active = False
self._reservations.clear()
self._buffer.clear()
self._spans.clear()
self._frame_queue.clear()
self._sample_rate_hz = None
self._turn_had_speech = False
def clear_force_listen(self) -> None:
self._spans = [_PcmSpan(span.byte_count, False, span.is_speech) for span in self._spans]
def has_pending(self) -> bool:
return bool(self._buffer)
def has_reserved(self) -> bool:
return bool(self._reservations)
@property
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],
*,
operation_id: str,
) -> MiniCPMO45PcmAppendReservation:
sample_rate_hz = payload.get("sample_rate_hz")
if isinstance(payload, dict) and "video_frames" in payload:
# Frames align to whole audio units; a passthrough payload has no
# unit framing for Stage0 to interleave against.
payload = {key: value for key, value in payload.items() if key != "video_frames"}
reservation = MiniCPMO45PcmAppendReservation(
owner=self,
operation_id=operation_id,
payload=payload,
raw=b"",
sample_rate_hz=sample_rate_hz if isinstance(sample_rate_hz, int) else 0,
force_listen=bool(payload.get("force_listen", False)),
is_speech=bool(payload.get("is_speech", False)),
turn_had_speech=bool(payload.get("is_speech", False)),
)
self._reservations.append(reservation)
return reservation
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
flush: bool = False,
allow_emit: bool = True,
) -> MiniCPMO45PcmAppendReservation | None:
fmt = payload.get("format")
sample_rate_hz = payload.get("sample_rate_hz")
audio = payload.get("audio")
if fmt != "pcm_f32le" or not isinstance(sample_rate_hz, int) or not isinstance(audio, str):
return self._reserve_passthrough(payload, operation_id=operation_id)
try:
raw = base64.b64decode(audio, validate=True)
except (binascii.Error, ValueError):
return self._reserve_passthrough(payload, operation_id=operation_id)
if len(raw) % 4 != 0:
return self._reserve_passthrough(payload, operation_id=operation_id)
if self._sample_rate_hz is not None and self._sample_rate_hz != sample_rate_hz:
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))
if not allow_emit:
return None
min_samples = max(1, int(sample_rate_hz * max(1, int(chunk_period_ms)) / 1000))
buffered_samples = len(self._buffer) // 4
if not flush and buffered_samples < min_samples:
return None
# Emit whole model chunks only: the engine reserves scheduler slots
# from the payload size and the worker consumes whole chunks per
# append, so partial chunks would turn into pad embeddings inside the
# model KV. On flush, the tail is zero-padded (silence) up to the
# chunk boundary instead.
if flush:
emit_samples = buffered_samples
remainder = emit_samples % min_samples
pad_samples = (min_samples - remainder) if remainder else 0
else:
emit_samples = min_samples
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]
out = dict(payload)
out.pop("force_speak", None)
out.pop("video_frames", None)
out["audio"] = base64.b64encode(emit_raw).decode("ascii")
out["sample_rate_hz"] = sample_rate_hz
# Omni duplex: attach at most one queued camera frame per emitted
# model unit (official cadence: one frame per 1 s chunk). The engine
# budgets 66 scheduler slots per attached frame from this payload.
# Official omni cadence is one frame per ~1 s chunk, and the first
# append consumes extra samples (1035 ms first window), so per-unit
# attachment could outrun the units Stage0 actually builds. Attach at
# most ONE frame per emitted payload; the rest stay queued.
attached_frames: list[str] = []
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"] = 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,
payload=out,
raw=reserved_raw,
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,
)
self._reservations.append(reservation)
return reservation
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> MiniCPMO45PcmAppendReservation:
"""Reserve the terminal payload without invalidating prior appends."""
had_speech = self._turn_had_speech
reservation: MiniCPMO45PcmAppendReservation | None = None
if had_speech and self._buffer:
payload: dict[str, object] = {
"type": "audio",
"audio": "",
"format": "pcm_f32le",
"sample_rate_hz": self._sample_rate_hz or 16000,
"force_listen": self._buffer_force_listen(),
"is_speech": self._buffer_is_speech(),
}
reservation = self.prepare_append(
payload,
operation_id=operation_id,
chunk_period_ms=chunk_period_ms,
flush=True,
)
assert reservation is not None
assert reservation.payload is not None
reservation.payload["final"] = True
if reservation is None:
reservation = MiniCPMO45PcmAppendReservation(
owner=self,
operation_id=operation_id,
payload=None,
raw=b"",
sample_rate_hz=self._sample_rate_hz or 0,
force_listen=self._buffer_force_listen(),
is_speech=self._buffer_is_speech(),
turn_had_speech=had_speech,
)
self._reservations.append(reservation)
# Open the next physical input generation without touching already
# reserved appends. A rollback restores this generation's metadata.
self._sample_rate_hz = None
self._turn_had_speech = False
return reservation
def append(
self,
payload: dict[str, object],
*,
chunk_period_ms: int,
flush: bool = False,
allow_emit: bool = True,
) -> dict[str, object] | None:
self._reservation_seq += 1
reservation = self.prepare_append(
payload,
operation_id=f"immediate-{self._reservation_seq}",
chunk_period_ms=chunk_period_ms,
flush=flush,
allow_emit=allow_emit,
)
if reservation is None:
return None
reservation.commit()
assert reservation.payload is not None
return reservation.payload
def _commit_reservation(self, reservation: MiniCPMO45PcmAppendReservation) -> None:
if not reservation._active:
return
if not self._reservations or self._reservations[0] is not reservation:
raise RuntimeError("PCM append reservations must commit in wire order")
self._reservations.pop(0)
reservation._active = False
def _rollback_reservation(self, reservation: MiniCPMO45PcmAppendReservation) -> None:
if not reservation._active:
return
try:
index = self._reservations.index(reservation)
except ValueError:
reservation._active = False
return
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._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
del self._reservations[index:]
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
if not self._buffer:
return None
payload: dict[str, object] = {
"type": "audio",
"audio": "",
"format": "pcm_f32le",
"sample_rate_hz": self._sample_rate_hz or 16000,
"force_listen": self._buffer_force_listen(),
"is_speech": self._buffer_is_speech(),
}
return self.append(payload, chunk_period_ms=chunk_period_ms, flush=True)
def commit(self, *, chunk_period_ms: int) -> dict[str, object] | None:
"""Commit the real residual PCM and reset per-client-input state.
Complete model units are emitted by :meth:`append` as soon as they are
available. A commit at that exact boundary therefore has no payload;
synthesizing another unit would add a model decision that does not
exist in the official continuous streaming loop.
"""
self._reservation_seq += 1
reservation = self.prepare_commit(
operation_id=f"immediate-commit-{self._reservation_seq}",
chunk_period_ms=chunk_period_ms,
)
reservation.commit()
return reservation.payload
__all__ = [
"MiniCPMO45PcmAppendReservation",
"MiniCPMO45PcmAppendBuffer",
"decode_native_ref_audio_from_config",
"validate_native_ref_audio_config",
]
@@ -0,0 +1,154 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from typing import Any
class MiniCPMO45DuplexPolicy:
"""MiniCPM-o 4.5 native duplex model policy.
Keep model-specific token names, input modes, and handoff type strings out
of the generic scheduler/orchestrator path. These names are part of the
MiniCPM-o 4.5 remote-code contract, not a general vLLM-Omni duplex schema.
"""
# Audio framing contract shared by serving, orchestrator, and worker.
# MiniCPM-o consumes 1 s units at 16 kHz and pools audio to one embedding
# per 100 ms, so a unit contributes exactly 10 audio embeddings plus the
# <unit> open (and a </unit> closure for every unit after the first).
# Scheduler token budgets must match the worker-built embeddings exactly:
# surplus slots become pad embeddings inside the KV and measurably corrupt
# the model's listen/speak behavior.
SAMPLE_RATE_HZ = 16000
CHUNK_SAMPLES = 16000
SAMPLES_PER_AUDIO_TOKEN = 1600
# Vision framing contract (omni duplex). Official streaming_prefill feeds
# each frame as <image> + 64 resampler embeddings + </image> inside the
# unit, ahead of the unit's audio embeddings (max_slice_nums=1 in
# streaming, so exactly one 64-token block per frame). A unit may carry
# its base frame plus an optional stacked composite of the sub-frames
# captured inside that unit (2 blocks).
VISION_EMBEDS_PER_FRAME = 64
VISION_TOKENS_PER_FRAME = VISION_EMBEDS_PER_FRAME + 2 # <image> + embeds + </image>
DEFAULT_MAX_NEW_SPEAK_TOKENS_PER_CHUNK = 20
DEFAULT_MAX_SPEAK_CHARS_PER_CHUNK = 28
DEFAULT_MIN_NEW_SPEAK_TOKENS_BEFORE_CHUNK_BOUNDARY = 8
REPETITION_HISTORY_SIZE = 512
@classmethod
def audio_token_count(cls, sample_count: int) -> int:
"""Audio embedding count for a clip of ``sample_count`` samples.
Matches the whole-clip encoder math (hop 160 mel frames -> CNN stride 2
-> avg-pool 5) for any multiple of ``SAMPLES_PER_AUDIO_TOKEN``; serving
normalizes clips to that boundary before this is used for budgets.
"""
return max(0, int(sample_count) // cls.SAMPLES_PER_AUDIO_TOKEN)
@staticmethod
def session_context_texts(
instructions: object,
has_ref_audio: bool,
initial_user_text: object = None,
) -> tuple[str, str]:
"""System-context prefix/suffix, matching MiniCPMODuplex.prepare()."""
system_prompt = (
instructions if isinstance(instructions, str) and instructions else "Streaming Omni Conversation."
)
prefix = f"<|im_start|>system\n{system_prompt}"
suffix = "<|im_end|>"
if has_ref_audio:
prefix += "\n<|audio_start|>"
suffix = "<|audio_end|>" + suffix
if isinstance(initial_user_text, str) and initial_user_text:
suffix += f"\n<|im_start|>user\n{initial_user_text}<|im_end|>\n<|im_start|>assistant\n"
return prefix, suffix
SPECIAL_TOKEN_FIELDS: dict[str, str] = {
"unit_token_id": "<unit>",
"unit_end_token_id": "</unit>",
"listen_token_id": "<|listen|>",
"speak_token_id": "<|speak|>",
"tts_bos_token_id": "<|tts_bos|>",
"tts_eos_token_id": "<|tts_eos|>",
"tts_pad_token_id": "<|tts_pad|>",
"chunk_eos_token_id": "<|chunk_eos|>",
"chunk_tts_eos_token_id": "<|chunk_tts_eos|>",
"turn_eos_token_id": "<|turn_eos|>",
}
OPTIONAL_TOKEN_FIELDS: dict[str, str] = {
"audio_placeholder_token_id": "<|audio|>",
"image_start_token_id": "<image>",
"image_end_token_id": "</image>",
"slice_start_token_id": "<slice>",
"slice_end_token_id": "</slice>",
}
@classmethod
def token_ids_from_tokenizer(cls, tokenizer: Any) -> dict[str, int]:
convert = getattr(tokenizer, "convert_tokens_to_ids", None)
def token_id(token: str) -> int:
if not callable(convert):
value = None
else:
value = convert(token)
if isinstance(value, list):
value = value[0] if len(value) == 1 else None
unk_token_id = getattr(tokenizer, "unk_token_id", None)
try:
candidate = int(value) if value is not None else -1
except (TypeError, ValueError):
candidate = -1
if candidate >= 0 and candidate != unk_token_id:
return candidate
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:
candidate = int(ids[0])
except (TypeError, ValueError):
candidate = -1
if candidate >= 0 and candidate != unk_token_id:
return candidate
return -1
resolved = {field: token_id(token) for field, token in cls.SPECIAL_TOKEN_FIELDS.items()}
resolved.update({field: token_id(token) for field, token in cls.OPTIONAL_TOKEN_FIELDS.items()})
if resolved.get("listen_token_id", -1) < 0:
eos_id = getattr(tokenizer, "eos_token_id", None)
try:
if eos_id is not None:
resolved["listen_token_id"] = int(eos_id)
except (TypeError, ValueError):
pass
return resolved
@staticmethod
def native_forbidden_token_ids(
token_ids: dict[str, int],
*,
bad_token_ids: list[int] | tuple[int, ...] = (),
) -> list[int]:
return [
token_ids.get("tts_pad_token_id", -1),
*list(bad_token_ids),
token_ids.get("chunk_eos_token_id", -1),
]
@staticmethod
def native_special_token_ids(
token_ids: dict[str, int],
*,
tokenizer_special_ids: list[int] | tuple[int, ...] = (),
) -> set[int]:
special = set(tokenizer_special_ids or [])
special.update(value for value in token_ids.values() if isinstance(value, int) and value >= 0)
return special
@@ -0,0 +1,372 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
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 + 2 patches on 960x540) and the composite is not.
_DUPLEX_HD_SLICES_PER_BASE_FRAME = 3
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, 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",
]
@@ -0,0 +1,102 @@
# 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,
)
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
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."""
audio_buffer: MiniCPMO45PcmAppendBuffer = field(default_factory=MiniCPMO45PcmAppendBuffer)
input_since_commit: bool = False
speech_since_commit: bool = False
native_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,
payload: dict[str, object],
*,
operation_id: str | None,
reserved_bytes: int = 0,
) -> None:
self.committed_audio_payload = payload
self.committed_audio_operation_id = operation_id
self.committed_audio_reserved_bytes += max(0, int(reserved_bytes))
def clear_committed_audio(self) -> int:
reserved_bytes = self.committed_audio_reserved_bytes
self.committed_audio_payload = None
self.committed_audio_operation_id = None
self.committed_audio_reserved_bytes = 0
self.deferred_response_create = False
self.deferred_precreate_response = False
return reserved_bytes
def clear_continuation(self) -> None:
self.continuation_owner_id = None
self.continuation_units = 0
self.pending_silence_task = None
self.pending_silence_owner_id = None
@@ -0,0 +1,896 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import base64
import copy
import time
from contextlib import suppress
from dataclasses import dataclass, field
from threading import Lock
from typing import Any
import numpy as np
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.policy import MiniCPMO45DuplexPolicy
_MINICPMO45_SPECIAL_TOKEN_FIELDS = MiniCPMO45DuplexPolicy.SPECIAL_TOKEN_FIELDS
_MINICPMO45_OPTIONAL_TOKEN_FIELDS = MiniCPMO45DuplexPolicy.OPTIONAL_TOKEN_FIELDS
_MINICPMO45_PROCESSOR_LOAD_LOCK = Lock()
@dataclass
class _MiniCPMO45Stage0SessionState:
session_id: str
streaming_processor: Any | None = None
audio_buffer: np.ndarray = field(default_factory=lambda: np.array([], dtype=np.float32))
audio_chunk_idx: int = 0
context_embeds: list[Any] = 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_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
pending_terminator_token: int | None = None
last_terminator_token: int | None = None
pending_speech_context: bool = False
pending_speech_append_identity: tuple[int | None, int] | None = None
pending_speech_response_open: bool = False
generated_tokens: list[int] = field(default_factory=list)
class MiniCPMO45Stage0DuplexRuntime:
"""Build scheduler-owned MiniCPM-o 4.5 Stage0 duplex inputs."""
unit_token_id: int = -1
unit_end_token_id: int = -1
listen_token_id: int = -1
speak_token_id: int = -1
tts_bos_token_id: int = -1
tts_eos_token_id: int = -1
tts_pad_token_id: int = -1
chunk_eos_token_id: int = -1
chunk_tts_eos_token_id: int = -1
turn_eos_token_id: int = -1
audio_placeholder_token_id: int = -1
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:
self.stage_model = stage_model
self.model_path = model_path
self.device = device
self.sessions: dict[tuple[str, int], _MiniCPMO45Stage0SessionState] = {}
self.thinker = getattr(stage_model, "thinker", None) or getattr(stage_model, "model", None) or stage_model
self.processor = (
getattr(stage_model, "processor", None)
or getattr(self.thinker, "processor", None)
or self._load_processor_from_path(model_path)
)
self.tokenizer = (
getattr(self.processor, "tokenizer", None)
if self.processor is not None
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
def _configure_streaming_processor(
self,
state: _MiniCPMO45Stage0SessionState | None = None,
) -> Any | None:
processor = self.processor
if processor is None:
return None
if state is not None:
if state.streaming_processor is not None:
return state.streaming_processor
processor = copy.copy(processor)
shared_mel = getattr(self.processor, "_streaming_mel_processor", None)
if shared_mel is not None:
processor._streaming_mel_processor = copy.deepcopy(shared_mel)
state.streaming_processor = processor
if processor is None:
return None
set_streaming_mode = getattr(processor, "set_streaming_mode", None)
if callable(set_streaming_mode):
set_streaming_mode(
mode="exact",
chunk_ms=int(self._stage_param("chunk_ms", 1000)),
first_chunk_ms=int(self._stage_param("first_chunk_ms", 1035)),
cnn_redundancy_ms=int(self._stage_param("cnn_redundancy_ms", 20)),
enable_sliding_window=True,
slide_trigger_seconds=30.0,
slide_stride_seconds=10.0,
)
# Match official init_streaming_processor: reset the streaming mel-processor
# buffers at session init (modeling_minicpmo_unified.py:207).
reset_streaming = getattr(processor, "reset_streaming", None)
if callable(reset_streaming):
reset_streaming()
return processor
configure_streaming = getattr(processor, "configure_streaming", None)
if callable(configure_streaming):
configure_streaming(
chunk_ms=int(self._stage_param("chunk_ms", 1000)),
enable_sliding_window=True,
slide_trigger_seconds=30.0,
slide_stride_seconds=10.0,
)
return processor
def _prepare_session_context(
self,
state: _MiniCPMO45Stage0SessionState,
session_config: dict[str, Any],
*,
runtime_config: dict[str, Any] | None = None,
) -> None:
if not self._stage_runtime_ready():
return
self._require_special_token_ids()
ref_audio = self._decode_ref_audio_from_session_config(runtime_config or {})
# Matches MiniCPMODuplex.prepare() in the released checkpoint's
# modeling_minicpmo.py: the <|audio_start|>/<|audio_end|> markers are
# only present when reference audio is embedded between them. The
# template is shared with the serving adapter so the first-append
# scheduler reserve can count these tokens exactly.
prefix, suffix = MiniCPMO45DuplexPolicy.session_context_texts(
session_config.get("instructions"),
ref_audio is not None,
(runtime_config or {}).get("initial_user_text"),
)
for token_id in self._encode_text(prefix):
state.context_embeds.append(self._embed_token(token_id))
state.context_token_ids.append(token_id)
if ref_audio is not None:
ref_audio_embeds = self._stage_ref_audio_embeddings(ref_audio, state=state)
if ref_audio_embeds is not None:
ref_audio_embeds = self._as_2d_tensor(ref_audio_embeds)
state.context_embeds.append(ref_audio_embeds)
state.context_token_ids.extend([self.unit_token_id] * int(ref_audio_embeds.shape[0]))
for token_id in self._encode_text(suffix):
state.context_embeds.append(self._embed_token(token_id))
state.context_token_ids.append(token_id)
def _stage_prefill_embeddings_only(
self,
state: _MiniCPMO45Stage0SessionState,
audio_waveform: Any,
*,
video_frames: list[Any] | None = None,
epoch: int | None = None,
seq: int | None = None,
is_speech: bool = False,
final: bool = False,
) -> dict[str, Any]:
"""Build scheduler-owned Stage0 input embeddings for one audio append.
Unlike the legacy worker-control path, this method never calls an eager
model forward. The normal vLLM runner consumes the returned embeddings
and owns attention metadata, block tables, KV cache, and sampling.
"""
start_time = time.time()
processor = self._configure_streaming_processor(state)
append_identity = (epoch, seq) if seq is not None else None
if (
append_identity is not None
and state.prepared_append_identity == append_identity
and state.prepared_inputs_embeds is not None
):
result = dict(state.prepared_result)
result["inputs_embeds"] = state.prepared_inputs_embeds
result["input_token_ids"] = list(state.prepared_input_token_ids)
return result
self._require_special_token_ids()
if audio_waveform is None or len(audio_waveform) == 0:
return self._stage_prefill_result(False, start_time, "empty audio")
state.audio_buffer = np.concatenate([state.audio_buffer, np.asarray(audio_waveform, dtype=np.float32)])
chunk_size = self._streaming_chunk_size(processor)
self._pad_first_audio_chunk_if_needed(state, processor)
if len(state.audio_buffer) < chunk_size:
if video_frames:
# Frames belong to the unit this append closes, and the
# scheduler already reserved their vision tokens against this
# append. A frame arriving before its unit can close has
# nowhere to go, so report it instead of dropping it under a
# generic buffering result.
return self._stage_prefill_result(
False,
start_time,
f"{len(video_frames)} video frame(s) on an append that closes no model unit "
f"(need {chunk_size} samples, only {len(state.audio_buffer)}); "
"send frames on unit boundaries",
)
return self._stage_prefill_result(
False,
start_time,
f"audio not enough: need {chunk_size} samples, only {len(state.audio_buffer)}",
)
# 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] = []
if video_frames:
self._require_vision_token_ids()
encoded_frames = self._stage_vision_embeddings(video_frames)
if encoded_frames is None or len(encoded_frames) != len(video_frames):
return self._stage_prefill_result(False, start_time, "streaming vision embedding failed")
if any(not slices for slices in encoded_frames):
return self._stage_prefill_result(False, start_time, "streaming vision embedding failed")
frame_blocks = encoded_frames
embed_parts: list[Any] = []
token_ids: list[int] = []
if state.audio_chunk_idx == 0 and state.context_embeds:
embed_parts.extend(state.context_embeds)
token_ids.extend(state.context_token_ids)
# 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:
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 (
("chunk_idx", state.audio_chunk_idx),
("use_extra_context", True),
("prefix_extra_frames", 0 if state.audio_chunk_idx == 0 else 2),
("suffix_extra_frames", 2),
):
with suppress(Exception):
setattr(batch_feature, name, value)
audio_embeds = self._stage_audio_embeddings(batch_feature, state=state)
if audio_embeds is None:
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.
# The scheduler session update discards the previous segment's
# sampled terminator token, so it is re-injected here ahead of
# the closure; the model's listen/speak policy depends on
# seeing its own past decisions in context.
pending_terminator = state.pending_terminator_token
if pending_terminator is not None and units_built == 0:
state.pending_terminator_token = None
embed_parts.append(self._embed_token(pending_terminator))
token_ids.append(int(pending_terminator))
embed_parts.append(self._embed_token(self.unit_end_token_id))
token_ids.append(self.unit_end_token_id)
embed_parts.append(self._embed_token(self.unit_token_id))
token_ids.append(self.unit_token_id)
if frame_blocks:
# Official order inside a unit: every frame_list entry as
# <image> + 64 embeds + </image>, then any HD patches as
# <slice> + 64 embeds + </slice>, all ahead of this unit's
# *one* second of audio. stack_frames never stacks audio.
vision_placeholder = self._vision_embedding_placeholder_token_id()
for frame_slices in frame_blocks:
for slice_index, frame_block in enumerate(frame_slices):
vision_block = self._as_2d_tensor(frame_block)
start_id, end_id = self._vision_slice_token_ids(is_source=slice_index == 0)
embed_parts.append(self._embed_token(start_id))
token_ids.append(int(start_id))
embed_parts.append(vision_block)
token_ids.extend([vision_placeholder] * int(vision_block.shape[0]))
embed_parts.append(self._embed_token(end_id))
token_ids.append(int(end_id))
frame_blocks = []
embed_parts.append(audio_embeds)
token_ids.extend(
[self._audio_embedding_placeholder_token_id()] * int(self._as_2d_tensor(audio_embeds).shape[0])
)
state.audio_buffer = state.audio_buffer[consumed_samples:]
state.audio_chunk_idx += 1
units_built += 1
chunk_size = self._streaming_chunk_size(processor)
# Match official streaming_prefill: per chunk feed ONLY <unit>+audio. The assistant
# turn is opened once at session init; re-emitting the turn-open prefix per chunk
# re-opened the turn each chunk -> degenerate repetition. tts_bos/listen/turn_eos are
# model-generated and tracked via current_turn_ended (mirrors streaming_generate).
prompt_suffix_len = 0
import torch
inputs_embeds = torch.cat([self._as_2d_tensor(embed) for embed in embed_parts], dim=0)
result = self._stage_prefill_result(True, start_time)
result.update(
{
"inputs_embeds": inputs_embeds,
"input_token_ids": token_ids,
"special_token_ids": self._special_token_ids(),
"num_input_tokens": int(inputs_embeds.shape[0]),
"prompt_suffix_len": prompt_suffix_len,
"uses_model_runner_scheduler": True,
"runner_kv_backed": True,
"runtime_impl": "scheduler_data_plane",
}
)
if is_speech and (append_identity is None or state.pending_speech_append_identity != append_identity):
state.pending_speech_context = True
state.pending_speech_append_identity = append_identity
if append_identity is not None:
state.prepared_append_identity = append_identity
state.prepared_inputs_embeds = inputs_embeds
state.prepared_input_token_ids = list(token_ids)
state.prepared_result = {k: v for k, v in result.items() if k not in {"inputs_embeds", "input_token_ids"}}
return result
@staticmethod
def _stage_prefill_result(success: bool, start_time: float, reason: str = "") -> dict[str, Any]:
return {
"success": success,
"prefill_success": success,
"is_buffering": not success,
"reason": reason,
"cost_all": time.time() - start_time,
"stage_runtime_ready": True,
}
@staticmethod
def _as_2d_tensor(value: Any) -> Any:
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:
import torch
token = torch.tensor([int(token_id)], dtype=torch.long, device=self._model_device())
embedder = self._token_embedder()
embeds = embedder(token)
return self._as_2d_tensor(embeds)
def _token_embedding_dtype(self) -> Any:
"""dtype of the decoder token embeddings, the unit's reference dtype.
Official ``get_vllm_embedding`` casts vision hidden states to the token
embedding dtype before they enter the sequence, so the vision tower's
own dtype must not leak into the concatenated unit.
"""
embedder = self._token_embedder()
weight = getattr(embedder, "weight", None)
dtype = getattr(weight, "dtype", None)
if dtype is not None:
return dtype
return getattr(next(self.thinker.parameters()), "dtype", None)
def _token_embedder(self) -> Any:
nested_embed = getattr(getattr(getattr(self.thinker, "llm", None), "model", None), "embed_tokens", None)
if callable(nested_embed):
return nested_embed
for target in (self.thinker, self.stage_model):
embedder = getattr(target, "get_input_embeddings", None)
if callable(embedder):
try:
embeddings = embedder()
if callable(embeddings):
return embeddings
except TypeError:
return embedder
raise AttributeError("MiniCPM-o stage0 model does not expose token embeddings")
def _model_device(self) -> Any:
try:
return next(self.thinker.parameters()).device
except Exception:
pass
try:
return next(self.stage_model.parameters()).device
except Exception:
pass
return self.device
def _streaming_chunk_size(self, processor: Any | None = None) -> int:
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:
processor = processor or self.processor
return int(
self._stage_param(
"sample_rate",
getattr(getattr(processor, "_streaming_mel_processor", None), "sample_rate", 16000),
)
)
def _first_chunk_samples(self, default_chunk_size: int, processor: Any | None = None) -> int:
processor = processor or self.processor
if getattr(processor, "_streaming_mel_processor", None) is None:
return default_chunk_size
return int(self._stage_param("first_chunk_ms", 1035) * self._sample_rate(processor) / 1000)
def _pad_first_audio_chunk_if_needed(
self,
state: _MiniCPMO45Stage0SessionState,
processor: Any | None = None,
) -> None:
if state.audio_chunk_idx != 0 or len(state.audio_buffer) == 0:
return
first_chunk_samples = self._first_chunk_samples(
self._streaming_chunk_size(processor),
processor,
)
if len(state.audio_buffer) >= first_chunk_samples:
return
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:
for target in (self.stage_model, self.thinker, getattr(self.thinker, "llm", None)):
value = getattr(target, name, None)
if value is not None:
return value
value = getattr(target, name.upper(), None)
if value is not None:
return value
return default
def _consumed_audio_samples(
self,
chunk_idx: int,
default_chunk_size: int,
*,
processor: Any | None = None,
) -> int:
processor = processor or self.processor
if chunk_idx != 0:
chunk_ms = int(self._stage_param("chunk_ms", 1000))
return int(chunk_ms * self._sample_rate(processor) / 1000)
mel_processor = getattr(processor, "_streaming_mel_processor", None)
get_config = getattr(mel_processor, "get_config", None)
if callable(get_config):
cfg = get_config()
if isinstance(cfg, dict):
consumed_ms = int(cfg.get("effective_first_chunk_ms", self._stage_param("first_chunk_ms", 1035)))
return int(consumed_ms * self._sample_rate(processor) / 1000)
return default_chunk_size
def _process_streaming_audio(
self,
audio_chunk: Any,
chunk_idx: int,
*,
processor: Any | None = None,
) -> Any:
processor = processor or self.processor
process = getattr(processor, "process_audio_streaming", None)
if callable(process):
try:
return process(audio_chunk, reset=False, return_batch_feature=True)
except TypeError:
return process(audio_chunk, chunk_idx=chunk_idx)
return {"audio_features": audio_chunk, "audio_feature_lens": [[len(audio_chunk)]]}
def _stage_audio_embeddings(
self,
batch_feature: Any,
*,
state: _MiniCPMO45Stage0SessionState | None = None,
) -> Any | None:
if hasattr(batch_feature, "to"):
batch_feature = batch_feature.to(self.device)
self._ensure_dynamic_cache_compat()
has_audio_cache = state is not None and hasattr(self.thinker, "audio_past_key_values")
previous_audio_past_key_values = (
getattr(self.thinker, "audio_past_key_values", None) if has_audio_cache else None
)
if has_audio_cache and state is not None:
self.thinker.audio_past_key_values = state.audio_past_key_values
try:
for target in (self.stage_model, self.thinker):
get_streaming = getattr(target, "get_audio_embedding_streaming", None)
if callable(get_streaming):
try:
result = self._cat_nested_tensors(
get_streaming(
batch_feature,
use_extra_context=True,
prefix_extra_frames=0 if int(getattr(batch_feature, "chunk_idx", 0)) == 0 else 2,
suffix_extra_frames=2,
)
)
if has_audio_cache and state is not None:
state.audio_past_key_values = getattr(self.thinker, "audio_past_key_values", None)
return result
except TypeError:
result = self._cat_nested_tensors(get_streaming(batch_feature))
if has_audio_cache and state is not None:
state.audio_past_key_values = getattr(self.thinker, "audio_past_key_values", None)
return result
get_hidden = getattr(target, "get_audio_hidden_states", None)
if callable(get_hidden):
result = self._cat_nested_tensors(get_hidden(batch_feature))
if has_audio_cache and state is not None:
state.audio_past_key_values = getattr(self.thinker, "audio_past_key_values", None)
return result
return None
finally:
if has_audio_cache:
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:
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,
*,
state: _MiniCPMO45Stage0SessionState | None = None,
) -> Any | None:
process_audio = getattr(self.processor, "process_audio", None)
if callable(process_audio):
batch_feature = process_audio([ref_audio])
if hasattr(batch_feature, "to"):
batch_feature = batch_feature.to(self.device)
self._ensure_dynamic_cache_compat()
for target in (self.stage_model, self.thinker):
get_audio_embedding = getattr(target, "get_audio_embedding", None)
if callable(get_audio_embedding):
try:
chunk_length = getattr(getattr(target, "config", None), "audio_chunk_length", None)
if chunk_length is not None:
return self._cat_nested_tensors(
get_audio_embedding(batch_feature, chunk_length=chunk_length)
)
except TypeError:
pass
return self._cat_nested_tensors(get_audio_embedding(batch_feature))
# The split vLLM stage0 wrapper ports official
# get_audio_embedding(chunk_length=...) as
# get_audio_hidden_states (chunk_length comes from config).
get_hidden = getattr(target, "get_audio_hidden_states", None)
if callable(get_hidden):
return self._cat_nested_tensors(get_hidden(batch_feature))
# The split vLLM stage0 wrapper may only expose the streaming encoder
# path. Use it as a fallback so the server-resolved reference audio is
# still represented in the same system context location as official
# MiniCPM-o prepare().
processor = state.streaming_processor if state is not None else self.processor
batch_feature = self._process_streaming_audio(ref_audio, 0, processor=processor)
for name, value in (
("chunk_idx", 0),
("use_extra_context", True),
("prefix_extra_frames", 0),
("suffix_extra_frames", 2),
):
with suppress(Exception):
setattr(batch_feature, name, value)
return self._stage_audio_embeddings(batch_feature, state=state)
@staticmethod
def _ensure_dynamic_cache_compat() -> None:
try:
from transformers.cache_utils import DynamicCache
except Exception:
return
if hasattr(DynamicCache, "get_usable_length"):
return
def get_usable_length(self, new_seq_length: int | None = None, layer_idx: int = 0) -> int:
get_seq_length = getattr(self, "get_seq_length", None)
if not callable(get_seq_length):
return 0
try:
return int(get_seq_length(layer_idx))
except TypeError:
return int(get_seq_length())
DynamicCache.get_usable_length = get_usable_length # type: ignore[attr-defined]
@staticmethod
def _cat_nested_tensors(value: Any) -> Any | None:
import torch
tensors = []
def collect(item: Any) -> None:
if item is None:
return
if hasattr(item, "detach"):
tensors.append(item)
return
if isinstance(item, dict):
for child in item.values():
collect(child)
return
if isinstance(item, (list, tuple)):
for child in item:
collect(child)
collect(value)
if not tensors:
return None
return torch.cat([tensor.reshape(-1, tensor.shape[-1]) for tensor in tensors], dim=0)
def _encode_text(self, text: str) -> list[int]:
encode = getattr(self.tokenizer, "encode", None)
if callable(encode):
return list(encode(text, add_special_tokens=False))
return []
def _special_token_ids(self) -> dict[str, int]:
return {
name: value
for name, value in {
"unit_token_id": self.unit_token_id,
"unit_end_token_id": self.unit_end_token_id,
"listen_token_id": self.listen_token_id,
"speak_token_id": self.speak_token_id,
"tts_bos_token_id": self.tts_bos_token_id,
"tts_eos_token_id": self.tts_eos_token_id,
"tts_pad_token_id": self.tts_pad_token_id,
"chunk_eos_token_id": self.chunk_eos_token_id,
"chunk_tts_eos_token_id": self.chunk_tts_eos_token_id,
"turn_eos_token_id": self.turn_eos_token_id,
}.items()
if isinstance(value, int) and value >= 0
}
@staticmethod
def _load_processor_from_path(model_path: str | None) -> Any | None:
if not model_path:
return None
try:
from transformers import AutoImageProcessor, AutoProcessor
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:
setattr(AutoImageProcessor, "register", staticmethod(register_image_processor))
try:
processor = AutoProcessor.from_pretrained(
model_path,
trust_remote_code=True,
)
finally:
setattr(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:
for field_name in _MINICPMO45_SPECIAL_TOKEN_FIELDS:
setattr(self, field_name, -1)
for field_name in _MINICPMO45_OPTIONAL_TOKEN_FIELDS:
setattr(self, field_name, -1)
else:
for field_name, token in _MINICPMO45_SPECIAL_TOKEN_FIELDS.items():
setattr(self, field_name, self._resolve_special_token_id(token))
for field_name, token in _MINICPMO45_OPTIONAL_TOKEN_FIELDS.items():
setattr(self, field_name, self._resolve_special_token_id(token))
def _resolve_special_token_id(self, token: str) -> int:
if self.tokenizer is None:
return -1
unk_token_id = getattr(self.tokenizer, "unk_token_id", None)
candidate = None
convert = getattr(self.tokenizer, "convert_tokens_to_ids", None)
if callable(convert):
value = convert(token)
if isinstance(value, list):
value = value[0] if len(value) == 1 else None
with suppress(TypeError, ValueError):
candidate = int(value)
if candidate is not None and candidate >= 0 and candidate != unk_token_id:
return candidate
encode = getattr(self.tokenizer, "encode", None)
if callable(encode):
ids = list(encode(token, add_special_tokens=False))
if len(ids) == 1:
value = int(ids[0])
if value >= 0 and value != unk_token_id:
return value
return -1
def _require_special_token_ids(self) -> None:
missing = [
token
for field_name, token in _MINICPMO45_SPECIAL_TOKEN_FIELDS.items()
if not isinstance(getattr(self, field_name, None), int) or getattr(self, field_name) < 0
]
if missing:
raise ValueError(
"MiniCPM-o 4.5 native duplex requires tokenizer-defined special "
f"tokens, missing or unknown: {', '.join(missing)}"
)
def _required_token_id(self, field_name: str) -> int:
token_id = getattr(self, field_name, None)
if not isinstance(token_id, int) or token_id < 0:
token = _MINICPMO45_SPECIAL_TOKEN_FIELDS.get(field_name, field_name)
raise ValueError(f"MiniCPM-o 4.5 missing required special token id for {token}")
return token_id
def stage_padding_token_id(self) -> int:
return self._required_token_id("unit_end_token_id")
def _audio_embedding_placeholder_token_id(self) -> int:
token_id = getattr(self, "audio_placeholder_token_id", -1)
if isinstance(token_id, int) and token_id >= 0:
return token_id
return self.stage_padding_token_id()
@staticmethod
def _decode_audio_payload(payload: dict[str, Any]) -> Any:
audio = payload.get("audio") or payload.get("data")
if not isinstance(audio, str):
raise ValueError("audio append payload requires base64 audio")
fmt = payload.get("format") or "pcm_f32le"
if fmt != "pcm_f32le":
raise ValueError(f"MiniCPM-o stage0 expects pcm_f32le audio, got {fmt!r}")
return np.frombuffer(base64.b64decode(audio), dtype=np.float32)
@staticmethod
def _decode_video_frames_payload(payload: dict[str, Any]) -> list[Any]:
"""Decode omni-duplex camera frames (base64 JPEG/PNG) to PIL images."""
frames = payload.get("video_frames")
if not isinstance(frames, list) or not frames:
return []
from io import BytesIO
from PIL import Image
decoded: list[Any] = []
for frame_b64 in frames:
if not isinstance(frame_b64, str) or not frame_b64:
continue
try:
raw = base64.b64decode(frame_b64, validate=True)
image = Image.open(BytesIO(raw))
image.load()
except Exception as exc: # noqa: BLE001 - normalized below
raise ValueError("invalid omni duplex video frame payload") from exc
decoded.append(image.convert("RGB"))
return decoded
def _vision_embedding_placeholder_token_id(self) -> int:
unk_token_id = getattr(self.tokenizer, "unk_token_id", None)
if isinstance(unk_token_id, int) and unk_token_id >= 0:
return unk_token_id
return self._required_optional_token_id("image_start_token_id")
def _required_optional_token_id(self, field_name: str) -> int:
token_id = getattr(self, field_name, None)
if not isinstance(token_id, int) or token_id < 0:
token = _MINICPMO45_OPTIONAL_TOKEN_FIELDS.get(field_name, field_name)
raise ValueError(f"MiniCPM-o 4.5 missing required special token id for {token}")
return token_id
def _require_vision_token_ids(self) -> None:
missing = [
_MINICPMO45_OPTIONAL_TOKEN_FIELDS[field_name]
for field_name in ("image_start_token_id", "image_end_token_id")
if not isinstance(getattr(self, field_name, None), int) or getattr(self, field_name) < 0
]
if missing:
raise ValueError(
"MiniCPM-o 4.5 omni duplex requires tokenizer-defined image tokens, "
f"missing or unknown: {', '.join(missing)}"
)
def _vision_slice_token_ids(self, *, is_source: bool) -> tuple[int, int]:
if is_source:
return int(self.image_start_token_id), int(self.image_end_token_id)
start = getattr(self, "slice_start_token_id", None)
end = getattr(self, "slice_end_token_id", None)
if isinstance(start, int) and start >= 0 and isinstance(end, int) and end >= 0:
return start, end
return int(self.image_start_token_id), int(self.image_end_token_id)
def _official_max_slice_nums(self, frame_count: int) -> list[int]:
"""Official stacked pair uses HD on the current frame only: ``[2, 1]``."""
if frame_count <= 0:
return []
if frame_count == 1:
return [1]
return [2] + [1] * (frame_count - 1)
def _encode_processed_vision(self, processed: Any) -> list[Any] | None:
targets = (self.stage_model, self.thinker, getattr(self.stage_model, "model", None))
for target in targets:
if target is None:
continue
get_hidden = getattr(target, "get_vision_hidden_states", None)
vpm = getattr(target, "vpm", None)
if not callable(get_hidden) or vpm is None:
continue
try:
import torch
vpm_param = next(vpm.parameters())
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] = []
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))
tgt_tensor = image_tgt if hasattr(image_tgt, "reshape") else torch.tensor(image_tgt)
flat_tgt.append(tgt_tensor.reshape(-1, 2))
if not flat_pixels:
return None
tgt_sizes = torch.cat(flat_tgt, dim=0).to(device=device, dtype=torch.int64)
with torch.no_grad():
hidden = get_hidden({"pixel_values": flat_pixels, "tgt_sizes": tgt_sizes})
except Exception: # noqa: BLE001 - prefill fails with a reason
return None
expected = MiniCPMO45DuplexPolicy.VISION_EMBEDS_PER_FRAME
embed_dtype = self._token_embedding_dtype()
out: list[Any] = []
for block in hidden:
block_2d = self._as_2d_tensor(block)
if int(block_2d.shape[0]) != expected:
return None
if embed_dtype is not None and block_2d.dtype != embed_dtype:
block_2d = block_2d.to(dtype=embed_dtype)
out.append(block_2d)
return out
return None
def _stage_vision_embeddings(self, frames: list[Any]) -> list[list[Any]] | None:
"""Encode camera frames for omni duplex via the loaded vision tower.
Official ``streaming_prefill`` encodes each ``frame_list`` entry as its
own image (source + optional HD slices) and never stacks audio: the
unit still carries one second of soundtrack. A stacked pair uses
``max_slice_nums=[2, 1]`` so the current frame keeps the elevator
display readable and the composite stays a single 448-normalized tile.
Frames are processed one at a time because ``process_image([a, b])``
packs both PILs into one batch item.
"""
process_image = getattr(self.processor, "process_image", None)
if not callable(process_image):
return None
out: list[list[Any]] = []
for frame, max_slices in zip(frames, self._official_max_slice_nums(len(frames))):
try:
processed = process_image([frame], max_slice_nums=max_slices)
except Exception: # noqa: BLE001 - prefill fails with a reason
return None
encoded = self._encode_processed_vision(processed)
if encoded is None:
return None
out.append(encoded)
return out
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Adapted from:
# https://huggingface.co/openbmb/MiniCPM-o-4_5/blob/main/modeling_minicpmo.py
#
@@ -34,8 +34,8 @@ from vllm.sequence import IntermediateTensors
from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
from vllm_omni.experimental.fullduplex.minicpmo45.policy import MiniCPMO45DuplexPolicy
from vllm_omni.experimental.fullduplex.model_executor import DuplexSamplingRow
from vllm_omni.model_executor.duplex_sampling import DuplexSamplingRow
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.policy import MiniCPMO45DuplexPolicy
from vllm_omni.model_executor.models.minicpmo_4_5.minicpmo_4_5_omni_llm import (
MiniCPMO45OmniLLMDummyInputsBuilder,
MiniCPMO45OmniLLMMultiModalProcessor,
@@ -85,7 +85,7 @@ class MiniCPMO45OmniForConditionalGeneration(nn.Module, SupportsMultiModal, Supp
# Store configs
self.config = config
self.multimodal_config = multimodal_config
from vllm_omni.experimental.fullduplex.minicpmo45.compat import (
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.compat import (
patch_minicpmo_remote_config,
)
@@ -338,7 +338,7 @@ class MiniCPMO45OmniForConditionalGeneration(nn.Module, SupportsMultiModal, Supp
session_key = (session_id, incarnation)
state = helper.sessions.get(session_key)
if state is None:
from vllm_omni.experimental.fullduplex.minicpmo45.stage0 import (
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.stage0 import (
_MiniCPMO45Stage0SessionState,
)
@@ -456,7 +456,7 @@ class MiniCPMO45OmniForConditionalGeneration(nn.Module, SupportsMultiModal, Supp
helper = getattr(self, "_minicpmo45_duplex_data_plane_helper", None)
if helper is not None:
return helper
from vllm_omni.experimental.fullduplex.minicpmo45.stage0 import MiniCPMO45Stage0DuplexRuntime
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.stage0 import MiniCPMO45Stage0DuplexRuntime
model_path = getattr(getattr(self.vllm_config, "model_config", None), "model", None)
device = str(self._module_device(self.thinker if self.thinker is not None else self))
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Adapted from:
# https://huggingface.co/openbmb/MiniCPM-o-4_5/blob/main/modeling_minicpmo.py
#
@@ -3941,7 +3941,7 @@ class MiniCPMO45OmniLLMForConditionalGeneration(nn.Module, SupportsMultiModal, S
else:
text_config = Qwen2Config.from_dict(config_dict)
llm_arch = "Qwen2ForCausalLM"
from vllm_omni.experimental.fullduplex.minicpmo45.compat import (
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.compat import (
patch_minicpmo_remote_config,
)
@@ -27,7 +27,7 @@ from vllm.model_executor.models.llama import LlamaModel
from vllm.model_executor.models.utils import maybe_prefix
from vllm.v1.sample.sampler import Sampler
from vllm_omni.experimental.fullduplex.engine.intermediate import get_tts_handoff
from vllm_omni.engine.duplex.intermediate import get_tts_handoff
from vllm_omni.model_executor.models.minicpmo_4_5 import MINICPMO45_DUPLEX_CODEC_TOKENS_PER_CHUNK
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.platforms import current_omni_platform
@@ -24,9 +24,11 @@ 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.experimental.fullduplex.minicpmo45.runtime.MiniCPMO45DuplexRuntimeExtension"),
duplex_runtime_extension=(
"vllm_omni.model_executor.models.minicpmo_4_5.duplex.runtime.MiniCPMO45DuplexRuntimeExtension"
),
duplex_serving_adapter=(
"vllm_omni.experimental.fullduplex.minicpmo45.serving_adapter.MiniCPMO45ServingRuntimeAdapter"
"vllm_omni.model_executor.models.minicpmo_4_5.duplex.serving_adapter.MiniCPMO45ServingRuntimeAdapter"
),
duplex_control_enabled=True,
# MiniCPM-o 4.5's HF config.json reports `model_type="minicpmo"` and
@@ -0,0 +1,4 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Native Full-Duplex integration for NVIDIA NemotronLabs VoiceChat."""
@@ -0,0 +1,403 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Output projection for Nemotron VoiceChat's independent channels."""
from __future__ import annotations
import json
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass, field
from typing import Any
from uuid import uuid4
import numpy as np
import torch
from vllm.logger import init_logger
from vllm_omni.engine.duplex.contracts import (
duplex_resource_request_belongs_to_session,
)
from vllm_omni.outputs.duplex import (
get_duplex_output_decision,
)
logger = init_logger(__name__)
EncodeAudio = Callable[[object, int, str, float | None], str | None]
@dataclass(frozen=True, slots=True)
class NemotronVoiceChatDataPlaneContext:
epoch: int = 0
turn_id: int = 0
auto_responds: bool = True
response_format: str = "wav"
speed: float | None = None
modalities: tuple[str, ...] = ("text", "audio")
@dataclass(slots=True)
class _RequestState:
text_frames: int = 0
audio_frames: int = 0
pending_speech_end_frames: list[int] = field(default_factory=list)
function_active: bool = False
function_tokens: list[int] = field(default_factory=list)
function_call_id: str | None = None
terminal: bool = False
def _coerce_ints(value: object) -> list[int]:
if value is None:
return []
if isinstance(value, torch.Tensor):
value = value.detach().cpu().reshape(-1).tolist()
elif isinstance(value, np.ndarray):
value = value.reshape(-1).tolist()
if isinstance(value, int):
return [value]
if not isinstance(value, list | tuple):
return []
values: list[int] = []
for item in value:
if isinstance(item, torch.Tensor):
if item.numel() != 1:
continue
item = item.item()
elif isinstance(item, np.generic):
item = item.item()
try:
values.append(int(item))
except (TypeError, ValueError):
continue
return values
def _unwrap(output: object) -> tuple[object, object | None, int | None]:
stage_id = getattr(output, "stage_id", None)
inner = getattr(output, "request_output", None)
if inner is not None and inner is not output:
output = inner
outputs = getattr(output, "outputs", None)
completion = outputs[0] if isinstance(outputs, list) and outputs else None
if stage_id is None:
stage_id = getattr(output, "stage_id", None)
return output, completion, int(stage_id) if isinstance(stage_id, int) else None
def _multimodal(output: object, completion: object | None) -> dict[str, object]:
decision = get_duplex_output_decision(output)
metadata = getattr(decision, "metadata", None)
if isinstance(metadata, Mapping):
return dict(metadata)
for candidate in (
getattr(output, "multimodal_output", None),
getattr(completion, "multimodal_output", None) if completion is not None else None,
):
if isinstance(candidate, Mapping):
return dict(candidate)
return {}
def _audio_value(metadata: Mapping[str, object]) -> object | None:
value = next((metadata[key] for key in ("audio", "model_outputs", "latent") if key in metadata), None)
if isinstance(value, list) and len(value) == 1:
return value[0]
return value
def _sample_rate(metadata: Mapping[str, object]) -> int:
value = metadata.get("sr", metadata.get("sample_rate_hz", 22050))
if isinstance(value, list) and value:
value = value[0]
if hasattr(value, "item"):
value = value.item()
return int(value) if isinstance(value, int | float) else 22050
def _audio_samples(audio: object | None) -> int:
if audio is None:
return 0
if isinstance(audio, torch.Tensor):
return int(audio.numel())
try:
return int(np.asarray(audio, dtype=np.float32).size)
except (TypeError, ValueError):
return 0
def _speech_end_event(request_id: str) -> dict[str, object]:
return {
"stage_role": "tts",
"is_listen": False,
"data_plane_request_id": request_id,
"text": "",
"end_of_turn": True,
}
class NemotronVoiceChatDataPlaneSession:
"""Join frame-locked text/function outputs with Stage-2 audio."""
def __init__(self, encode_audio: EncodeAudio) -> None:
self._encode_audio = encode_audio
self._requests: dict[str, _RequestState] = {}
self._tokenizer = None
self._tokenizer_ref: str | None = None
self._special_ids: dict[str, int] | None = None
def configure_runtime(self, runtime_config: Mapping[str, object], *, tokenizer: Any | None = None) -> None:
"""Install the serving-resolved tokenizer contract as the sole truth."""
try:
special_ids = {
"bos": int(runtime_config["nvc_text_bos_id"]),
"eos": int(runtime_config["nvc_text_eos_id"]),
"pad": int(runtime_config["nvc_text_pad_id"]),
"sotc": int(runtime_config["nvc_function_sotc_id"]),
"eotc": int(runtime_config["nvc_function_eotc_id"]),
}
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("Nemotron VoiceChat data plane requires resolved special-token ids") from exc
tokenizer_ref = runtime_config.get("nvc_tokenizer_ref")
if not isinstance(tokenizer_ref, str) or not tokenizer_ref:
raise ValueError("Nemotron VoiceChat data plane requires nvc_tokenizer_ref")
self._special_ids = special_ids
self._tokenizer_ref = tokenizer_ref
self._tokenizer = tokenizer
def begin_request(self, request_id: str) -> None:
self._requests.setdefault(request_id, _RequestState()).terminal = False
def is_terminal(self, request_id: str | None) -> bool:
return bool(request_id and self._requests.get(request_id) and self._requests[request_id].terminal)
def mark_terminal(self, request_id: str) -> None:
self._requests.setdefault(request_id, _RequestState()).terminal = True
def close_stream(self, request_id: str) -> None:
self._requests.pop(request_id, None)
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None:
if active_request_id:
self._requests.pop(active_request_id, None)
for request_id in tuple(self._requests):
if duplex_resource_request_belongs_to_session(request_id, session_id):
self._requests.pop(request_id, None)
def _load_tokenizer(self):
if self._tokenizer is None:
from transformers import AutoTokenizer
if self._tokenizer_ref is None:
raise RuntimeError("Nemotron VoiceChat data plane was used before runtime configuration")
self._tokenizer = AutoTokenizer.from_pretrained(self._tokenizer_ref, trust_remote_code=False)
return self._tokenizer
def _ids(self) -> dict[str, int]:
if self._special_ids is None:
raise RuntimeError("Nemotron VoiceChat data plane was used before runtime configuration")
return self._special_ids
def _decode(self, token_ids: list[int]) -> str:
if not token_ids:
return ""
return str(self._load_tokenizer().decode(token_ids, skip_special_tokens=True))
def project(
self,
result: object,
*,
context: NemotronVoiceChatDataPlaneContext | None = None,
) -> Iterator[dict[str, object]]:
if not isinstance(result, dict):
return
outputs = result.get("data_plane_outputs")
if not isinstance(outputs, list):
return
for output in outputs:
yield from self.project_output(output, context=context)
def project_output(
self,
output: object,
*,
context: NemotronVoiceChatDataPlaneContext | None = None,
) -> Iterator[dict[str, object]]:
context = context or NemotronVoiceChatDataPlaneContext()
outer = output
output, completion, stage_id = _unwrap(output)
request_id = getattr(output, "request_id", None) or getattr(outer, "request_id", None)
request_id = str(request_id) if request_id is not None else ""
state = self._requests.setdefault(request_id, _RequestState())
metadata = _multimodal(outer, completion)
modalities = {modality.lower() for modality in context.modalities}
wants_text = "text" in modalities
wants_audio = "audio" in modalities
if stage_id == 0 or "nvc_text_token_ids" in metadata:
ids = self._ids()
text_ids = _coerce_ints(metadata.get("nvc_text_token_ids"))
if not text_ids and completion is not None:
text_ids = _coerce_ints(
getattr(completion, "token_ids", None) or getattr(completion, "cumulative_token_ids", None)
)
for token_id in text_ids[-1:]:
state.text_frames += 1
if token_id == ids["eos"]:
if state.audio_frames >= state.text_frames:
yield _speech_end_event(request_id)
else:
state.pending_speech_end_frames.append(state.text_frames)
elif token_id == ids["pad"]:
yield {
"stage_role": "llm",
"is_listen": True,
"model_listen": True,
"listen_source": "model_listen",
"data_plane_request_id": request_id,
"end_of_turn": False,
}
elif token_id != ids["bos"] and wants_text:
text = self._decode([token_id])
if text:
yield {
"stage_role": "llm",
"is_listen": False,
"data_plane_request_id": request_id,
"text": text,
"end_of_turn": False,
}
for function_id in _coerce_ints(metadata.get("nvc_function_token"))[-1:]:
yield from self._project_function_token(
function_id,
state=state,
request_id=request_id,
ids=ids,
)
return
audio = _audio_value(metadata)
sample_rate = _sample_rate(metadata)
sample_count = _audio_samples(audio)
encoded = (
self._encode_audio(audio, sample_rate, context.response_format, context.speed)
if wants_audio and audio is not None
else None
)
audio_chunk_complete = sample_count > 0
if audio_chunk_complete:
# A native-duplex Stage-2 segment can contain one or more 80 ms
# codec frames. Count them against the frame-locked Stage-0 text
# channel. The long-lived codec request deliberately keeps
# ``finished=False`` across scheduler wakes; a non-empty decoded
# chunk, not request lifetime, is the audio-coverage signal.
duration_ms = sample_count * 1000 / max(1, sample_rate)
state.audio_frames += max(1, round(duration_ms / 80))
end_of_turn = bool(state.pending_speech_end_frames) and state.audio_frames >= state.pending_speech_end_frames[0]
if encoded:
yield {
"stage_role": "tts",
"is_listen": False,
"data_plane_request_id": request_id,
"text": "",
"audio_data": encoded,
"audio_format": context.response_format,
"sample_rate_hz": sample_rate,
"audio_duration_ms": round(sample_count * 1000 / max(1, sample_rate)),
"audio_text_mark": True,
"end_of_turn": end_of_turn,
}
elif end_of_turn:
yield _speech_end_event(request_id)
if end_of_turn:
state.pending_speech_end_frames.pop(0)
def _project_function_token(
self,
token_id: int,
*,
state: _RequestState,
request_id: str,
ids: Mapping[str, int],
) -> Iterator[dict[str, object]]:
if token_id == ids["sotc"]:
state.function_active = True
state.function_tokens.clear()
state.function_call_id = f"call_{uuid4().hex}"
return
if token_id == ids["eotc"] and state.function_active:
state.function_active = False
raw = self._decode(state.function_tokens)
state.function_tokens.clear()
try:
calls = self._parse_calls(raw)
except ValueError as exc:
state.function_call_id = None
yield {
"stage_role": "function",
"data_plane_request_id": request_id,
"error_code": "nemotron_function_call_parse_error",
"error": str(exc),
}
return
for index, call in enumerate(calls):
yield {
"stage_role": "function",
"data_plane_request_id": request_id,
"function_call": True,
"call_id": (
state.function_call_id if index == 0 and state.function_call_id else f"call_{uuid4().hex}"
),
"name": str(call["name"]),
"arguments": (
call.get("arguments")
if isinstance(call.get("arguments"), str)
else json.dumps(call.get("arguments", {}), separators=(",", ":"))
),
}
state.function_call_id = None
return
if state.function_active and token_id != ids["pad"]:
state.function_tokens.append(token_id)
@staticmethod
def _parse_calls(value: str) -> list[dict[str, object]]:
text = value.strip()
if "<TOOLCALL>" in text:
text = text.split("<TOOLCALL>", 1)[1]
if "</TOOLCALL>" in text:
text = text.split("</TOOLCALL>", 1)[0]
try:
parsed = json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError("Nemotron VoiceChat produced malformed function-call JSON") from exc
if isinstance(parsed, dict):
parsed = [parsed]
if not isinstance(parsed, list) or not parsed:
raise ValueError("Nemotron VoiceChat function-call payload must be a non-empty object or list")
calls: list[dict[str, object]] = []
for item in parsed:
if not isinstance(item, dict):
raise ValueError("Nemotron VoiceChat function-call entries must be objects")
name = item.get("name")
if not isinstance(name, str) or not name.strip():
raise ValueError("Nemotron VoiceChat function-call entries require a non-empty name")
arguments = item.get("arguments", {})
if isinstance(arguments, str):
try:
decoded_arguments = json.loads(arguments)
except json.JSONDecodeError as exc:
raise ValueError("Nemotron VoiceChat function-call arguments contain malformed JSON") from exc
if not isinstance(decoded_arguments, dict):
raise ValueError("Nemotron VoiceChat function-call arguments must encode a JSON object")
elif not isinstance(arguments, dict):
raise ValueError("Nemotron VoiceChat function-call arguments must be a JSON object")
calls.append({"name": name.strip(), "arguments": arguments})
return calls
__all__ = [
"NemotronVoiceChatDataPlaneContext",
"NemotronVoiceChatDataPlaneSession",
]
@@ -0,0 +1,225 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""80 ms PCM packetization for Nemotron VoiceChat native duplex."""
from __future__ import annotations
import binascii
import numpy as np
import pybase64 as base64
NEMOTRON_VOICECHAT_SAMPLE_RATE = 16000
NEMOTRON_VOICECHAT_FRAME_SAMPLES = 1280
_SAMPLE_BYTES = 4
_FRAME_BYTES = NEMOTRON_VOICECHAT_FRAME_SAMPLES * _SAMPLE_BYTES
def _require_terminal_tail(buffered_bytes: int) -> None:
if buffered_bytes > _FRAME_BYTES:
raise ValueError(
"Nemotron VoiceChat manual/deferred commit cannot contain more than one 80 ms frame; "
"enable extra_body.auto_response for native full-duplex streaming"
)
def decode_pcm_f32le(payload: object, *, exact_frame: bool = False) -> bytes:
if not isinstance(payload, dict):
raise ValueError("Nemotron VoiceChat duplex audio payload must be a mapping")
if payload.get("format") != "pcm_f32le":
raise ValueError("Nemotron VoiceChat duplex audio format must be pcm_f32le")
if payload.get("sample_rate_hz") != NEMOTRON_VOICECHAT_SAMPLE_RATE:
raise ValueError("Nemotron VoiceChat duplex audio sample_rate_hz must be 16000")
encoded = payload.get("audio")
if not isinstance(encoded, str):
raise ValueError("Nemotron VoiceChat duplex audio must be base64 pcm_f32le")
try:
raw = base64.b64decode(encoded, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("Nemotron VoiceChat duplex audio is not valid base64") from exc
if len(raw) % _SAMPLE_BYTES:
raise ValueError("Nemotron VoiceChat pcm_f32le payload has a partial sample")
values = np.frombuffer(raw, dtype="<f4")
if values.size and not bool(np.isfinite(values).all()):
raise ValueError("Nemotron VoiceChat duplex audio samples must be finite")
if exact_frame and len(raw) != _FRAME_BYTES:
raise ValueError(
f"Nemotron VoiceChat native duplex append must contain exactly {NEMOTRON_VOICECHAT_FRAME_SAMPLES} samples"
)
return raw
def _frame_payload(raw: bytes, *, final: bool) -> dict[str, object]:
return {
"type": "audio",
"audio": base64.b64encode(raw).decode("ascii"),
"format": "pcm_f32le",
"sample_rate_hz": NEMOTRON_VOICECHAT_SAMPLE_RATE,
"final": final,
}
class NemotronVoiceChatPcmAppendReservation:
def __init__(
self,
owner: NemotronVoiceChatPcmAppendBuffer,
*,
operation_id: str,
payload: dict[str, object] | None,
raw: bytes,
) -> None:
self._owner = owner
self.operation_id = operation_id
self.payload = payload
self.raw = raw
self._active = True
@property
def active(self) -> bool:
return self._active
@property
def byte_count(self) -> int:
return len(self.raw)
def commit(self) -> None:
if not self._active:
return
self._active = False
if self in self._owner._reservations:
self._owner._reservations.remove(self)
def rollback(self) -> None:
if not self._active:
return
try:
index = self._owner._reservations.index(self)
except ValueError:
self._active = False
return
restore = bytearray()
for reservation in self._owner._reservations[index:]:
if reservation._active:
restore.extend(reservation.raw)
reservation._active = False
del self._owner._reservations[index:]
self._owner._buffer[:0] = restore
class NemotronVoiceChatPcmAppendBuffer:
"""Adapt Realtime packets to the current full-duplex PCM buffer contract.
The model consumes exactly one 1280-sample frame per scheduler append.
Realtime packets may split a frame arbitrarily, but a single packet is
capped at one frame so the serving contract never silently drops a second
ready frame behind a single-reservation API.
"""
def __init__(self) -> None:
self._buffer = bytearray()
self._reservations: list[NemotronVoiceChatPcmAppendReservation] = []
@property
def pending_byte_count(self) -> int:
return len(self._buffer)
def clear(self) -> None:
for reservation in self._reservations:
reservation._active = False
self._reservations.clear()
self._buffer.clear()
def clear_force_listen(self) -> None:
# Nemotron VoiceChat has no serving-side force-listen packet bit.
return
def has_pending(self) -> bool:
return bool(self._buffer)
def has_reserved(self) -> bool:
return any(reservation.active for reservation in self._reservations)
def _reserve_frame(
self,
*,
operation_id: str,
final: bool,
) -> NemotronVoiceChatPcmAppendReservation | None:
if len(self._buffer) < _FRAME_BYTES:
return None
raw = bytes(self._buffer[:_FRAME_BYTES])
del self._buffer[:_FRAME_BYTES]
reservation = NemotronVoiceChatPcmAppendReservation(
self,
operation_id=operation_id,
payload=_frame_payload(raw, final=final),
raw=raw,
)
self._reservations.append(reservation)
return reservation
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
allow_emit: bool,
) -> NemotronVoiceChatPcmAppendReservation | None:
if chunk_period_ms != 80:
raise ValueError("Nemotron VoiceChat native duplex chunk_period_ms must be 80")
raw = decode_pcm_f32le(payload)
if len(raw) > _FRAME_BYTES:
raise ValueError("Nemotron VoiceChat Realtime append must contain at most 1280 samples")
self._buffer.extend(raw)
if not allow_emit:
return None
return self._reserve_frame(operation_id=operation_id, final=False)
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> NemotronVoiceChatPcmAppendReservation:
if chunk_period_ms != 80:
raise ValueError("Nemotron VoiceChat native duplex chunk_period_ms must be 80")
_require_terminal_tail(len(self._buffer))
if not self._buffer:
reservation = NemotronVoiceChatPcmAppendReservation(
self,
operation_id=operation_id,
payload=None,
raw=b"",
)
else:
raw = bytes(self._buffer)
self._buffer.clear()
reservation = NemotronVoiceChatPcmAppendReservation(
self,
operation_id=operation_id,
payload=_frame_payload(raw + bytes(_FRAME_BYTES - len(raw)), final=True),
raw=raw,
)
self._reservations.append(reservation)
return reservation
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
if chunk_period_ms != 80:
raise ValueError("Nemotron VoiceChat native duplex chunk_period_ms must be 80")
_require_terminal_tail(len(self._buffer))
if not self._buffer:
return None
raw = bytes(self._buffer)
self._buffer.clear()
return _frame_payload(raw + bytes(_FRAME_BYTES - len(raw)), final=True)
__all__ = [
"NEMOTRON_VOICECHAT_FRAME_SAMPLES",
"NEMOTRON_VOICECHAT_SAMPLE_RATE",
"NemotronVoiceChatPcmAppendBuffer",
"NemotronVoiceChatPcmAppendReservation",
"decode_pcm_f32le",
]
@@ -0,0 +1,167 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Engine policy for Nemotron VoiceChat's frame-locked duplex timeline."""
from __future__ import annotations
from typing import Any
from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm_omni.engine.duplex.contracts import (
DuplexAppendPlan,
DuplexInputMode,
DuplexOutputAction,
DuplexOutputDecision,
)
from vllm_omni.engine.duplex.messages import DuplexFence
from vllm_omni.model_executor.models.nemotron_voicechat.duplex.input import (
decode_pcm_f32le,
)
def _plain_token_ids(value: object, *, name: str) -> list[int]:
if not isinstance(value, list | tuple) or not value:
raise ValueError(f"Nemotron VoiceChat runtime requires non-empty {name}")
try:
return [int(token_id) for token_id in value]
except (TypeError, ValueError) as exc:
raise ValueError(f"Nemotron VoiceChat {name} must contain token ids") from exc
def _positive_int(value: object, *, name: str) -> int:
try:
parsed = int(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"Nemotron VoiceChat requires a positive {name}") from exc
if parsed <= 0:
raise ValueError(f"Nemotron VoiceChat requires a positive {name}")
return parsed
class NemotronVoiceChatDuplexRuntimeExtension:
"""Append one 80 ms acoustic frame to one resumable thinker request."""
def configure_sampling_params(
self,
*,
runtime_config: dict[str, Any],
defaults: tuple[object, ...],
) -> tuple[object, ...]:
del runtime_config
if not defaults:
return defaults
# Every scheduler segment is one transport wake of a long-lived
# request. CUMULATIVE output makes the multimodal output processor
# concatenate all earlier Stage-2 waveforms and resend them on every
# wake (80, 160, 240, ... ms), causing O(n^2) audio replay. Duplex
# consumers require per-wake deltas at every stage.
configured = [params.clone() if isinstance(params, SamplingParams) else params for params in defaults]
for params in configured:
if isinstance(params, SamplingParams):
params.output_kind = RequestOutputKind.DELTA
stage0 = defaults[0]
if isinstance(stage0, SamplingParams):
stage0 = stage0.clone()
stage0.temperature = 0.0
stage0.top_p = 1.0
stage0.top_k = 0
stage0.max_tokens = 1
stage0.ignore_eos = True
stage0.output_kind = RequestOutputKind.DELTA
configured[0] = stage0
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, turn_seq
if mode is not DuplexInputMode.APPEND_AUDIO_CHUNK:
raise ValueError(f"Nemotron VoiceChat does not support duplex input mode {mode.value!r}")
decode_pcm_f32le(payload, exact_frame=True)
normalized_payload = dict(payload)
prompt_ids = _plain_token_ids(
runtime_config.get("nvc_prompt_token_ids"),
name="nvc_prompt_token_ids",
)
max_model_len = _positive_int(
runtime_config.get("nvc_max_model_len"),
name="nvc_max_model_len",
)
required_model_len = len(prompt_ids) + seq + 1
if required_model_len > max_model_len:
raise ValueError(
"Nemotron VoiceChat native duplex session exceeds the Stage-0 "
f"max_model_len: prompt_tokens={len(prompt_ids)} + input_frames={seq} + "
f"sampled_token=1 gives {required_model_len} > {max_model_len}; "
"start a new session or raise Stage 0 max_model_len"
)
try:
pad_id = int(runtime_config["nvc_text_pad_id"])
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("Nemotron VoiceChat runtime requires nvc_text_pad_id") from exc
scheduler_prompt = prompt_ids + [pad_id] if seq <= 1 else [pad_id]
return DuplexAppendPlan(
prompt={
"prompt_token_ids": scheduler_prompt,
"model_intermediate_buffer": {
"request_id": request_id,
"global_request_id": [fence.session_id],
"duplex": {
"data_plane": True,
"fence": fence,
"session_id": fence.session_id,
"incarnation": fence.incarnation,
"epoch": fence.epoch,
"source_input_seq": seq,
"seq": seq,
"mode": mode.value,
"payload": normalized_payload,
"final": final,
"session_config": dict(session_config),
"runtime_config": dict(runtime_config),
"scheduler_token_budget": len(scheduler_prompt),
},
},
}
)
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:
del final_stage_id, segment_finished, output
if stage_id != 0:
return None
metadata = dict(segment_output_metadata)
metadata["nvc_text_token_ids"] = list(segment_token_ids)
# Stage 0 is a client-visible side channel even though Stage 2 is the
# configured audio response stage. Mark it explicitly so the shared
# collector does not discard it while waiting for the final stage.
metadata["duplex_direct_response"] = True
return DuplexOutputDecision(
action=DuplexOutputAction.DIRECT_RESPONSE,
metadata=metadata,
final_output_type="text",
)
__all__ = ["NemotronVoiceChatDuplexRuntimeExtension"]
@@ -0,0 +1,363 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Realtime serving adapter for Nemotron VoiceChat native duplex."""
from __future__ import annotations
import asyncio
import json
import os
from collections.abc import Callable, Mapping
from copy import deepcopy
from typing import Any
from vllm_omni.entrypoints.duplex.protocol import DuplexCapabilities
from vllm_omni.entrypoints.duplex.runtime_adapter import ServingRuntimeConfigError
from vllm_omni.model_executor.models.minicpmo_4_5.duplex.session import (
MiniCPMO45ServingSessionState,
)
from vllm_omni.model_executor.models.nemotron_voicechat.duplex.data_plane import (
NemotronVoiceChatDataPlaneContext,
NemotronVoiceChatDataPlaneSession,
)
from vllm_omni.model_executor.models.nemotron_voicechat.duplex.input import (
NemotronVoiceChatPcmAppendBuffer,
)
EncodeAudio = Callable[[object, int, str, float | None], str | None]
_DEFAULT_SYSTEM_PROMPT = (
"You are an AI voice assistant developed by NVIDIA. "
"Your name is NVIDIA Voice Chat. "
"Answer in a spoken, conversational style rather than a written one. "
"Do not repeat the same sentence over and over again. "
"Start the conversation by greeting the user."
)
_PRIVATE_KEYS = frozenset(
{
"nvc_prompt_token_ids",
"nvc_text_bos_id",
"nvc_text_eos_id",
"nvc_text_pad_id",
"nvc_function_sotc_id",
"nvc_function_eotc_id",
"nvc_function_eotr_id",
"nvc_max_model_len",
"nvc_tokenizer_ref",
"nvc_tools_signature",
"nvc_function_response_generation",
"nvc_function_response_token_ids",
"nvc_function_response_call_id",
"nvc_function_response_batches",
}
)
def _stt_config(model_config: Any) -> dict[str, Any]:
hf_config = getattr(model_config, "hf_config", None)
stt_cfg = getattr(hf_config, "stt_cfg", None)
if not isinstance(stt_cfg, dict):
raise ServingRuntimeConfigError("Nemotron VoiceChat checkpoint STT configuration is unavailable")
return stt_cfg
def _normalized_tools(config: object) -> tuple[list[dict[str, object]], str]:
extra_body = getattr(config, "extra_body", None)
raw_tools = extra_body.get("realtime_tools") if isinstance(extra_body, dict) else None
if raw_tools is None:
return [], "[]"
if not isinstance(raw_tools, list):
raise ServingRuntimeConfigError("Nemotron VoiceChat tools must be a list")
if len(raw_tools) > 5:
raise ServingRuntimeConfigError("Nemotron VoiceChat supports at most 5 tools per session")
normalized: list[dict[str, object]] = []
for index, tool in enumerate(raw_tools):
if not isinstance(tool, dict):
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tool {index} must be an object")
function = tool.get("function", tool)
if not isinstance(function, dict):
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tool {index} has no function definition")
definition = {key: value for key, value in function.items() if key != "type"}
if not isinstance(definition.get("name"), str) or not str(definition["name"]).strip():
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tool {index} requires a name")
normalized.append(definition)
signature = json.dumps(normalized, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return normalized, signature
def _render_tool_prompt(instructions: str, tools: list[dict[str, object]]) -> str:
if not tools:
return instructions
available = json.dumps(tools, ensure_ascii=False, sort_keys=True)
return (
f"{instructions}\n\n"
"You can use the following tools to assist the user if required:"
f"\n<AVAILABLE_TOOLS>{available}</AVAILABLE_TOOLS>\n\n"
"If you decide to call any tool(s), use the following format:\n"
'<TOOLCALL>[{"name": "tool_name1", "arguments": "tool_args1"}, '
'{"name": "tool_name2", "arguments": "tool_args2"}]</TOOLCALL>\n\n'
"The user will execute tool-calls and return responses from tool(s) in this format:\n"
'<TOOL_RESPONSE>[{"tool_response1"}, {"tool_response2"}]</TOOL_RESPONSE>\n\n'
"Based on the tool responses, you can call additional tools if needed, correct tool calls if any "
"errors are found, or just respond to the user."
)
def _render_tool_response(output: str) -> str:
"""Serialize one Realtime function result using NVIDIA's function channel."""
try:
value = json.loads(output)
except json.JSONDecodeError:
value = output
payload = json.dumps([value], ensure_ascii=True, separators=(",", ":"))
return f"<TOOL_RESPONSE>{payload}</TOOL_RESPONSE>"
def _require_native_full_duplex(config: object) -> None:
extra_body = getattr(config, "extra_body", None)
enabled = isinstance(extra_body, dict) and (
extra_body.get("auto_response") is True or extra_body.get("full_duplex") is True
)
if not enabled:
raise ServingRuntimeConfigError(
"Nemotron VoiceChat currently supports model-native full-duplex streaming only; "
"set extra_body.auto_response=true",
code="unsupported_nemotron_duplex_mode",
)
def _tokenize_runtime(model_config: Any, instructions: str) -> tuple[dict[str, object], Any]:
from transformers import AutoTokenizer
stt_cfg = _stt_config(model_config)
tokenizer_ref = os.environ.get("NEMOTRON_VOICECHAT_LLM_PATH") or stt_cfg.get(
"pretrained_llm", "nvidia/NVIDIA-Nemotron-Nano-9B-v2"
)
tokenizer = AutoTokenizer.from_pretrained(tokenizer_ref, trust_remote_code=False)
def token(name: str, default: str) -> int:
value = tokenizer.convert_tokens_to_ids(stt_cfg.get(name, default))
if value is None:
raise ServingRuntimeConfigError(f"Nemotron VoiceChat tokenizer does not define {name}")
return int(value)
bos_id = token("bos_token", "<s>")
eos_id = token("eos_token", "</s>")
pad_id = token("pad_token", "<SPECIAL_12>")
prompt_ids = [bos_id] + list(tokenizer.encode(instructions, add_special_tokens=False)) + [eos_id]
runtime = {
"instructions": instructions,
"nvc_prompt_token_ids": prompt_ids,
"nvc_text_bos_id": bos_id,
"nvc_text_eos_id": eos_id,
"nvc_text_pad_id": pad_id,
"nvc_function_sotc_id": int(tokenizer.convert_tokens_to_ids("<SPECIAL_20>")),
"nvc_function_eotc_id": int(tokenizer.convert_tokens_to_ids("<SPECIAL_21>")),
"nvc_function_eotr_id": int(tokenizer.convert_tokens_to_ids("<SPECIAL_22>")),
"nvc_tokenizer_ref": str(tokenizer_ref),
}
return runtime, tokenizer
class NemotronVoiceChatServingRuntimeAdapter:
adapter_id = "nemotron_voicechat"
silence_continuation_samples = 1280
# The session-owned persistent drain is the sole data-plane output
# consumer. Collecting on append would race that drain and can consume a
# Stage2 audio output before the realtime projector observes it.
collect_outputs_on_append = False
clean_response_done_prefix = ""
interrupted_tts_prefix = ""
private_runtime_config_keys = _PRIVATE_KEYS
def __init__(self, encode_audio: EncodeAudio) -> None:
self.session_states: dict[str, MiniCPMO45ServingSessionState] = {}
self.data_plane = NemotronVoiceChatDataPlaneSession(encode_audio)
self._tokenizer: Any | None = None
def create_session_state(self) -> MiniCPMO45ServingSessionState:
return MiniCPMO45ServingSessionState(
audio_buffer=NemotronVoiceChatPcmAppendBuffer(),
)
def session_state(self, session_id: str) -> MiniCPMO45ServingSessionState:
return self.session_states.setdefault(session_id, self.create_session_state())
def remove_session_state(self, session_id: str) -> None:
self.session_states.pop(session_id, None)
@staticmethod
def is_enabled(config: object) -> bool:
del config
return True
@staticmethod
def capabilities(*, max_sessions: int) -> DuplexCapabilities:
supports_multi_session = max_sessions > 1
return DuplexCapabilities(
supports_model_native_turn_policy=True,
supports_external_turn_signal=False,
supports_client_commit=True,
supports_barge_in=False,
supports_playback_ack=True,
supports_input_append=True,
supports_replace_latest_chunk=False,
supports_reencode_context=False,
supports_rollback_to_checkpoint=False,
supports_turn_commit_only=False,
supports_kv_lease=False,
supports_core_kv_lease=False,
supports_model_internal_state=True,
supports_stage_resumption=True,
supports_scheduler_native_append=False,
supports_core_resumable_request=True,
supports_stage_connector_handoff=True,
supports_independent_io_streams=True,
supports_realtime_endpoint=True,
supports_multi_session=supports_multi_session,
supports_multi_session_same_replica=False,
supports_session_lease=True,
supports_session_resume=True,
session_admission_mode="engine_managed",
supports_audio_truncate=False,
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"],
stage_handoff_transport="scheduler_data_plane",
chunk_period_ms=80,
target_barge_in_latency_ms=None,
)
@staticmethod
def validate_client_extra_body(extra_body: object) -> None:
if not isinstance(extra_body, dict):
return
private = sorted(_PRIVATE_KEYS.intersection(extra_body))
if private:
raise ServingRuntimeConfigError(
"Nemotron VoiceChat runtime configuration is server-owned: " + ", ".join(private)
)
async def prepare_runtime_config(
self,
config: object,
*,
model_config: Any,
) -> dict[str, object]:
self.validate_client_extra_body(getattr(config, "extra_body", None))
_require_native_full_duplex(config)
instructions = str(getattr(config, "instructions", None) or _DEFAULT_SYSTEM_PROMPT)
tools, tools_signature = _normalized_tools(config)
rendered_prompt = _render_tool_prompt(instructions, tools)
runtime, tokenizer = await asyncio.to_thread(_tokenize_runtime, model_config, rendered_prompt)
max_model_len = getattr(model_config, "max_model_len", None)
if not isinstance(max_model_len, int) or max_model_len <= 0:
raise ServingRuntimeConfigError("Nemotron VoiceChat requires a positive Stage-0 max_model_len")
runtime["nvc_max_model_len"] = max_model_len
# Keep raw session values for immutable-in-incarnation update checks;
# only the rendered prompt token ids enter Stage-0 KV.
runtime["instructions"] = instructions
runtime["nvc_tools_signature"] = tools_signature
self.data_plane.configure_runtime(runtime, tokenizer=tokenizer)
self._tokenizer = tokenizer
return runtime
def runtime_config_for_function_output(
self,
item: Mapping[str, object],
current: Mapping[str, object],
) -> dict[str, object]:
"""Queue a client tool result for frame-locked function-channel injection."""
call_id = item.get("call_id")
output = item.get("output")
if not isinstance(call_id, str) or not call_id:
raise ServingRuntimeConfigError(
"function_call_output requires call_id",
code="invalid_function_call_output",
)
if not isinstance(output, str):
raise ServingRuntimeConfigError(
"function_call_output requires a string output",
code="invalid_function_call_output",
)
if self._tokenizer is None:
raise ServingRuntimeConfigError(
"Nemotron VoiceChat tokenizer is unavailable for function output",
code="invalid_function_call_output",
)
response_token_ids = list(
self._tokenizer.encode(
_render_tool_response(output),
add_special_tokens=False,
)
)
if not response_token_ids:
raise ServingRuntimeConfigError(
"function_call_output tokenized to an empty response",
code="invalid_function_call_output",
)
runtime = deepcopy(dict(current))
generation = int(runtime.get("nvc_function_response_generation", 0)) + 1
token_ids = [int(token_id) for token_id in response_token_ids]
batches = runtime.get("nvc_function_response_batches")
if not isinstance(batches, list):
batches = []
batches = [*batches, {"generation": generation, "call_id": call_id, "token_ids": token_ids}]
runtime["nvc_function_response_generation"] = generation
runtime["nvc_function_response_token_ids"] = token_ids
runtime["nvc_function_response_call_id"] = call_id
runtime["nvc_function_response_batches"] = batches
return runtime
@staticmethod
def runtime_config_for_update(
config: object,
current: Mapping[str, object],
) -> dict[str, object]:
NemotronVoiceChatServingRuntimeAdapter.validate_client_extra_body(getattr(config, "extra_body", None))
_require_native_full_duplex(config)
runtime = deepcopy(dict(current))
instructions = str(getattr(config, "instructions", None) or _DEFAULT_SYSTEM_PROMPT)
_, tools_signature = _normalized_tools(config)
# The system/tool prompt is already resident in Stage-0 KV. Updating it
# without a new incarnation would make the advertised config disagree
# with model state, so reject such updates explicitly.
if runtime and instructions != runtime.get("instructions"):
raise ServingRuntimeConfigError(
"Nemotron VoiceChat instructions cannot change inside an active duplex incarnation"
)
if runtime and tools_signature != runtime.get("nvc_tools_signature", "[]"):
raise ServingRuntimeConfigError(
"Nemotron VoiceChat tools cannot change inside an active duplex incarnation"
)
return runtime
@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, ...],
) -> NemotronVoiceChatDataPlaneContext:
del active_response_turn_id, active_response_id
return NemotronVoiceChatDataPlaneContext(
epoch=epoch,
turn_id=turn_id,
auto_responds=auto_responds,
response_format=response_format,
speed=speed,
modalities=modalities,
)
__all__ = ["NemotronVoiceChatServingRuntimeAdapter"]
@@ -52,7 +52,7 @@ from vllm.model_executor.models.utils import init_vllm_registered_model, maybe_p
from vllm.v1.outputs import SamplerOutput
from vllm.v1.sample.metadata import SamplingMetadata
from vllm_omni.experimental.fullduplex.model_executor import DuplexSamplingRow
from vllm_omni.model_executor.duplex_sampling import DuplexSamplingRow
from vllm_omni.model_executor.models.nemotron_voicechat.runtime_info import (
merge_runtime_info,
require_request_id,
@@ -497,7 +497,7 @@ class NemotronVoiceChatThinkerForConditionalGeneration(nn.Module, HasInnerState,
f"Nemotron VoiceChat duplex input sequence moved backwards: {source_input_seq} < {last_input_seq}"
)
from vllm_omni.experimental.fullduplex.nemotron_voicechat.input import (
from vllm_omni.model_executor.models.nemotron_voicechat.duplex.input import (
decode_pcm_f32le,
)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""NemotronVoiceChat pipeline: thinker (speech -> frame-locked text) -> talker
(text timeline -> 31-quantizer RVQ code stacks) -> code2wav (codes -> 22.05 kHz PCM).
@@ -32,10 +32,10 @@ NEMOTRON_VOICECHAT_PIPELINE = PipelineConfig(
model_type="nemotron_voicechat",
model_arch="NemotronVoiceChatThinkerForConditionalGeneration",
duplex_runtime_extension=(
"vllm_omni.experimental.fullduplex.nemotron_voicechat.runtime.NemotronVoiceChatDuplexRuntimeExtension"
"vllm_omni.model_executor.models.nemotron_voicechat.duplex.runtime.NemotronVoiceChatDuplexRuntimeExtension"
),
duplex_serving_adapter=(
"vllm_omni.experimental.fullduplex.nemotron_voicechat.serving_adapter.NemotronVoiceChatServingRuntimeAdapter"
"vllm_omni.model_executor.models.nemotron_voicechat.duplex.serving_adapter.NemotronVoiceChatServingRuntimeAdapter"
),
duplex_control_enabled=True,
# Named after the alias key so the deploy-yaml stem substring-matches the
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""PersonaPlex full-duplex integration.
PersonaPlex (``nvidia/personaplex-7b-v1``) is a Moshi finetune: a pure-lockstep
speech-to-speech model. This package plugs it into the generic duplex serving
stack through the standard plugin seams (``duplex_serving_adapter`` /
``duplex_runtime_extension`` dotted strings in the model's ``pipeline.py``):
- :class:`PersonaPlexConfig` immutable session config (voice / persona / sampling)
- :class:`PersonaPlexServingRuntimeAdapter` the ``ServingRuntimeAdapter`` impl
- :class:`PersonaPlexDuplexRuntimeExtension` the engine ``DuplexRuntimeExtension``
- :class:`PersonaPlexStage0DuplexRuntime` Stage 0 session state and prefill
- :class:`PersonaPlexPcmAppendBuffer` PCM input framing
"""
from .config import (
PersonaPlexConfig,
)
from .input import (
PersonaPlexPcmAppendBuffer,
)
from .policy import PrefillStep
from .runtime_extension import (
PersonaPlexDuplexRuntimeExtension,
)
from .serving_adapter import (
PersonaPlexServingRuntimeAdapter,
)
from .stage0 import (
PersonaPlexStage0DuplexRuntime,
)
__all__ = [
"PersonaPlexConfig",
"PersonaPlexDuplexRuntimeExtension",
"PersonaPlexPcmAppendBuffer",
"PersonaPlexServingRuntimeAdapter",
"PersonaPlexStage0DuplexRuntime",
"PrefillStep",
]
@@ -0,0 +1,64 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Configuration for the PersonaPlex full-duplex backend.
PersonaPlex (``nvidia/personaplex-7b-v1``) is a Moshi finetune: a pure-lockstep
full-duplex speech-to-speech model running at the Mimi codec frame rate
(12.5 Hz / 80 ms). One config drives both the offline driver and the duplex
adapter. Defaults mirror the PersonaPlex reference loop.
"""
from __future__ import annotations
from dataclasses import dataclass
# Mimi codec constants (loaders.py: SAMPLE_RATE / FRAME_RATE). Fixed by the
# pretrained checkpoint; exposed here only so the rest of the package never
# hard-codes them.
SAMPLE_RATE = 24000
FRAME_RATE = 12.5
FRAME_SIZE = int(SAMPLE_RATE / FRAME_RATE) # 1920 samples per 80 ms frame
# Default assistant persona shipped with PersonaPlex (offline.py:335).
DEFAULT_PERSONA = "You are a wise and friendly teacher. Answer questions or provide advice in a clear and engaging way."
@dataclass(frozen=True)
class PersonaPlexConfig:
"""Immutable session configuration for a PersonaPlex conversation.
Attributes:
hf_repo: HuggingFace repo holding the weights, Mimi codec and tokenizer.
voice_prompt: Voice-clone reference. Either a bundled basename
(``"NATF2.pt"`` / ``"NATM1.pt"`` from ``voices.tgz``) or a path to a
``.pt`` embedding bundle or a reference ``.wav``.
persona: System role text; injected as ``<system> ... <system>`` into the
inner-monologue stream at session start.
device: Torch device for the backend (``"cuda"`` / ``"cpu"``).
cpu_offload: Offload LM layers to CPU when GPU memory is tight (needs
``accelerate``).
batch_size: Concurrent conversation slots sharing one engine. ``1`` is
the single-session path; ``> 1`` enables elastic batching with
per-slot recycle for new callers.
Note: the native stepper decodes greedily (argmax) for both the text head
and the depformer, so there are no sampling knobs here yet. Temperature /
top-k / seed fields will be added if and when a sampling path is wired in.
"""
hf_repo: str = "nvidia/personaplex-7b-v1"
voice_prompt: str = "NATF2.pt"
persona: str = DEFAULT_PERSONA
device: str = "cuda"
cpu_offload: bool = False
batch_size: int = 1
@property
def sample_rate(self) -> int:
return SAMPLE_RATE
@property
def frame_size(self) -> int:
return FRAME_SIZE
@@ -0,0 +1,228 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass
import numpy as np
from vllm_omni.engine.duplex.contracts import (
duplex_resource_request_belongs_to_session,
)
EncodeAudio = Callable[[object, int, str, float | None], str | None]
@dataclass(frozen=True, slots=True)
class PersonaPlexDataPlaneContext:
epoch: int = 0
turn_id: int = 0
active_response_turn_id: int | None = None
active_response_id: str | None = None
auto_responds: bool = True
response_format: str = "wav"
speed: float | None = None
modalities: tuple[str, ...] = ("audio", "text")
@dataclass(slots=True)
class _RequestCursor:
audio_samples: int = 0
text: str = ""
terminal: bool = False
class PersonaPlexDataPlaneSession:
"""Project cumulative staged PersonaPlex output into Realtime deltas."""
def __init__(self, encode_audio: EncodeAudio) -> None:
self._encode_audio = encode_audio
self._requests: dict[str, _RequestCursor] = {}
def begin_request(self, request_id: str) -> None:
self._requests.setdefault(request_id, _RequestCursor()).terminal = False
def is_terminal(self, request_id: str | None) -> bool:
if request_id is None:
return False
state = self._requests.get(request_id)
return state is not None and state.terminal
def mark_terminal(self, request_id: str) -> None:
self._requests.setdefault(request_id, _RequestCursor()).terminal = True
def close_stream(self, request_id: str) -> None:
self._requests.pop(request_id, None)
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None:
if active_request_id is not None:
self._requests.pop(active_request_id, None)
for request_id in list(self._requests):
if duplex_resource_request_belongs_to_session(request_id, session_id):
self._requests.pop(request_id, None)
def project(
self,
result: object,
*,
context: PersonaPlexDataPlaneContext | None = None,
) -> Iterator[dict[str, object]]:
if not isinstance(result, dict):
return
outputs = result.get("data_plane_outputs")
if not isinstance(outputs, list):
return
context = context or PersonaPlexDataPlaneContext()
for output in outputs:
projected = self._project_output(output, context=context)
if projected is not None:
yield projected
def _project_output(
self,
output: object,
*,
context: PersonaPlexDataPlaneContext,
) -> dict[str, object] | None:
output, completion = _unwrap_output(output)
request_id = getattr(output, "request_id", None)
if not isinstance(request_id, str) or not request_id:
request_id = None
state = self._requests.setdefault(request_id, _RequestCursor()) if request_id is not None else _RequestCursor()
multimodal = _multimodal_output(output, completion)
audio = _audio_value(multimodal)
audio_delta = _slice_audio(audio, state.audio_samples)
audio_samples = _num_samples(audio)
if audio_samples is not None:
state.audio_samples = audio_samples
text = _text_value(multimodal, completion)
text_delta = _text_delta(text, state.text)
if text:
state.text = text
sample_rate_hz = _sample_rate(multimodal)
encoded = self._encode_audio(audio_delta, sample_rate_hz, context.response_format, context.speed)
if not encoded and not text_delta:
return None
delta_samples = _num_samples(audio_delta) or 0
return {
"supported": True,
"stage_role": "tts",
"is_listen": False,
"data_plane_request_id": request_id,
"text": text_delta,
"audio_data": encoded or "",
"audio_format": context.response_format,
"sample_rate_hz": sample_rate_hz,
"audio_duration_ms": round(delta_samples * 1000 / max(1, sample_rate_hz)),
"end_of_turn": False,
"uses_model_runner_scheduler": True,
"runner_kv_backed": True,
"runtime_impl": "scheduler_data_plane",
"owned_runtime": False,
}
def _unwrap_output(output: object) -> tuple[object, object | None]:
inner = getattr(output, "request_output", None)
if inner is not None and inner is not output:
output = inner
outputs = getattr(output, "outputs", None)
completion = outputs[0] if isinstance(outputs, list) and outputs else None
return output, completion
def _multimodal_output(output: object, completion: object | None) -> dict[str, object]:
for candidate in (
getattr(output, "multimodal_output", None),
getattr(completion, "multimodal_output", None) if completion is not None else None,
):
if isinstance(candidate, Mapping) and candidate:
return dict(candidate)
return {}
def _audio_value(multimodal: dict[str, object]) -> object | None:
value = next(
(multimodal[key] for key in ("audio", "model_outputs", "latent") if key in multimodal),
None,
)
if isinstance(value, list) and len(value) == 1:
return value[0]
return value
def _text_value(multimodal: dict[str, object], completion: object | None) -> str:
for candidate in (
multimodal.get("text"),
multimodal.get("llm_output_text"),
getattr(completion, "text", None) if completion is not None else None,
):
if isinstance(candidate, str) and candidate:
return candidate
return ""
def _text_delta(text: str, previous: str) -> str:
if not text:
return ""
if text == previous:
return ""
if previous and text.startswith(previous):
return text[len(previous) :]
return text
def _slice_audio(audio: object | None, offset: int) -> object | None:
samples = _num_samples(audio)
if samples is None or samples <= 0:
return None
if offset <= 0 or samples < offset:
return audio
if samples == offset:
return None
try:
import torch
if isinstance(audio, torch.Tensor):
return audio.reshape(-1)[offset:].contiguous()
except Exception:
pass
return np.asarray(audio, dtype=np.float32).reshape(-1)[offset:]
def _num_samples(audio: object | None) -> int | None:
if audio is None:
return None
try:
import torch
if isinstance(audio, torch.Tensor):
return int(audio.numel())
except Exception:
pass
try:
return int(np.asarray(audio, dtype=np.float32).size)
except Exception:
return None
def _sample_rate(multimodal: dict[str, object]) -> int:
value = multimodal.get("sr", multimodal.get("sample_rate_hz", 24000))
if isinstance(value, list) and value:
value = value[0]
if hasattr(value, "item"):
try:
value = value.item()
except Exception:
value = 24000
return int(value) if isinstance(value, int | float) else 24000
__all__ = [
"PersonaPlexDataPlaneContext",
"PersonaPlexDataPlaneSession",
]
@@ -0,0 +1,213 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import base64
import binascii
import numpy as np
_SAMPLE_RATE_HZ = 24000
_FRAME_SAMPLES = 1920
_BYTES_PER_SAMPLE = 4
class PersonaPlexPcmAppendReservation:
__slots__ = (
"_active",
"_owner",
"_raw",
"operation_id",
"payload",
)
def __init__(
self,
*,
owner: PersonaPlexPcmAppendBuffer,
operation_id: str,
payload: dict[str, object] | None,
raw: bytes,
) -> None:
self._owner = owner
self.operation_id = operation_id
self.payload = payload
self._raw = raw
self._active = True
@property
def active(self) -> bool:
return self._active
@property
def byte_count(self) -> int:
return len(self._raw)
def commit(self) -> None:
self._owner._commit_reservation(self)
def rollback(self) -> None:
self._owner._rollback_reservation(self)
class PersonaPlexPcmAppendBuffer:
"""Transactionally frame 24 kHz float PCM into PersonaPlex 80 ms units."""
def __init__(self) -> None:
self._buffer = bytearray()
self._sample_rate_hz: int | None = None
self._reservations: list[PersonaPlexPcmAppendReservation] = []
@property
def pending_byte_count(self) -> int:
return len(self._buffer)
def has_pending(self) -> bool:
return bool(self._buffer)
def has_reserved(self) -> bool:
return any(reservation.active for reservation in self._reservations)
def clear_force_listen(self) -> None:
return
def clear(self) -> None:
for reservation in self._reservations:
reservation._active = False
self._reservations.clear()
self._buffer.clear()
self._sample_rate_hz = None
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
allow_emit: bool,
) -> PersonaPlexPcmAppendReservation | None:
if chunk_period_ms != 80:
raise ValueError("PersonaPlex chunk_period_ms must be 80")
if any(reservation.active and reservation.operation_id == operation_id for reservation in self._reservations):
raise ValueError(f"PersonaPlex duplicate active operation_id: {operation_id}")
raw = self._decode_payload(payload)
self._buffer.extend(raw)
if not allow_emit or len(self._buffer) < _FRAME_SAMPLES * _BYTES_PER_SAMPLE:
return None
return self._reserve_frame(payload, operation_id=operation_id, flush=False)
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> PersonaPlexPcmAppendReservation:
if chunk_period_ms != 80:
raise ValueError("PersonaPlex chunk_period_ms must be 80")
if not self._buffer:
reservation = PersonaPlexPcmAppendReservation(
owner=self,
operation_id=operation_id,
payload=None,
raw=b"",
)
self._reservations.append(reservation)
return reservation
payload: dict[str, object] = {
"type": "audio",
"format": "pcm_f32le",
"sample_rate_hz": self._sample_rate_hz or _SAMPLE_RATE_HZ,
"audio": "",
"final": True,
}
return self._reserve_frame(payload, operation_id=operation_id, flush=True)
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
reservation = self.prepare_commit(
operation_id="personaplex-flush",
chunk_period_ms=chunk_period_ms,
)
payload = reservation.payload
reservation.commit()
return payload
def _decode_payload(self, payload: dict[str, object]) -> bytes:
if payload.get("format") != "pcm_f32le":
raise ValueError("PersonaPlex input format must be pcm_f32le")
sample_rate_hz = payload.get("sample_rate_hz")
if sample_rate_hz != _SAMPLE_RATE_HZ:
raise ValueError("PersonaPlex sample_rate_hz must be 24000")
if self._sample_rate_hz is not None and self._sample_rate_hz != sample_rate_hz:
raise ValueError("PersonaPlex sample_rate_hz changed within a session")
audio = payload.get("audio")
if not isinstance(audio, str):
raise ValueError("PersonaPlex audio must be base64 pcm_f32le")
try:
raw = base64.b64decode(audio, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("PersonaPlex audio is not valid base64") from exc
if len(raw) % _BYTES_PER_SAMPLE:
raise ValueError("PersonaPlex pcm_f32le byte length must be divisible by four")
samples = np.frombuffer(raw, dtype="<f4")
if not np.isfinite(samples).all():
raise ValueError("PersonaPlex pcm_f32le samples must be finite")
self._sample_rate_hz = int(sample_rate_hz)
return raw
def _reserve_frame(
self,
source_payload: dict[str, object],
*,
operation_id: str,
flush: bool,
) -> PersonaPlexPcmAppendReservation:
frame_bytes = _FRAME_SAMPLES * _BYTES_PER_SAMPLE
if flush:
consumed_bytes = min(len(self._buffer), frame_bytes)
else:
consumed_bytes = frame_bytes
raw = bytes(self._buffer[:consumed_bytes])
del self._buffer[:consumed_bytes]
encoded_raw = raw + b"\x00" * (frame_bytes - consumed_bytes)
payload = dict(source_payload)
payload["type"] = "audio"
payload["format"] = "pcm_f32le"
payload["sample_rate_hz"] = _SAMPLE_RATE_HZ
payload["audio"] = base64.b64encode(encoded_raw).decode("ascii")
reservation = PersonaPlexPcmAppendReservation(
owner=self,
operation_id=operation_id,
payload=payload,
raw=raw,
)
self._reservations.append(reservation)
return reservation
def _commit_reservation(self, reservation: PersonaPlexPcmAppendReservation) -> None:
if not reservation.active:
return
reservation._active = False
self._reservations.remove(reservation)
def _rollback_reservation(self, reservation: PersonaPlexPcmAppendReservation) -> None:
if not reservation.active:
return
try:
index = self._reservations.index(reservation)
except ValueError:
reservation._active = False
return
rolled_back = self._reservations[index:]
restored = b"".join(item._raw for item in rolled_back if item.active)
self._buffer[:0] = restored
for item in rolled_back:
item._active = False
del self._reservations[index:]
__all__ = [
"PersonaPlexPcmAppendBuffer",
"PersonaPlexPcmAppendReservation",
]
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""PersonaPlex frame/token contract (the model *policy*, no engine state).
This mirrors the ``minicpmo45`` model-package layout from PR #3907: the token
contract lives in ``policy.py``, the model-owned runtime in ``runtime.py``.
Everything here is a constant or a pure function of the checkpoint's lockstep
conventions; nothing touches weights, devices, or streaming state.
Frame layout per 80 ms tick: 17 token rows -- row 0 inner-monologue text,
rows 1-8 agent audio codebooks, rows 9-16 user audio codebooks.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
# Inner-monologue token ids that carry no displayable text (EPAD, PAD).
NON_TEXT_TOKEN_IDS = frozenset({0, 3})
ZERO_TEXT_TOKEN = 3
# Mimi token constants for the hybrid system prompt (agent silence / user sine).
SILENCE_TOKENS = (948, 243, 1178, 546, 1736, 1030, 1978, 2008)
SINE_TOKENS = (430, 1268, 381, 1611, 1095, 1495, 56, 472)
# LM initial ("beginning of stream") token ids: audio rows use the codec
# cardinality, the text row uses the text vocabulary size.
AUDIO_INITIAL_TOKEN = 2048
TEXT_INITIAL_TOKEN = 32000
TEXT_VOCAB_SIZE = 32000
AUDIO_SILENCE_FRAME_CNT = 6 # 0.5 s at 12.5 Hz
@dataclass(frozen=True)
class PrefillStep:
"""One tick of a recycled slot's system-prompt replay (see batched serving)."""
kind: str # "sacrifice" | "voice" | "voice_end" | "tokens"
embedding: Any = None # [1, 1, H] tensor for kind == "voice"
moshi_tokens: Any = None # [8] tensor for kind == "tokens"
text_token: int | None = None
user_sine: bool = False
def wrap_with_system_tags(text: str) -> str:
t = text.strip()
return t if t.startswith("<system>") else f"<system> {t} <system>"
__all__ = [
"AUDIO_INITIAL_TOKEN",
"AUDIO_SILENCE_FRAME_CNT",
"NON_TEXT_TOKEN_IDS",
"PrefillStep",
"SILENCE_TOKENS",
"SINE_TOKENS",
"TEXT_INITIAL_TOKEN",
"TEXT_VOCAB_SIZE",
"ZERO_TEXT_TOKEN",
"wrap_with_system_tags",
]
@@ -0,0 +1,129 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import base64
import binascii
from typing import Any
from vllm.sampling_params import SamplingParams
from vllm_omni.engine.duplex.messages import DuplexFence
from vllm_omni.engine.duplex.runtime import (
DuplexAppendPlan,
DuplexInputMode,
DuplexOutputDecision,
)
_FRAME_BYTES = 1920 * 4
def _validated_frame_payload(payload: object) -> dict[str, object]:
if not isinstance(payload, dict):
raise ValueError("PersonaPlex duplex append payload must be a mapping")
if payload.get("format") != "pcm_f32le":
raise ValueError("PersonaPlex duplex append format must be pcm_f32le")
if payload.get("sample_rate_hz") != 24000:
raise ValueError("PersonaPlex duplex append sample_rate_hz must be 24000")
audio = payload.get("audio")
if not isinstance(audio, str):
raise ValueError("PersonaPlex duplex append audio must be base64 pcm_f32le")
try:
raw = base64.b64decode(audio, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("PersonaPlex duplex append audio is not valid base64") from exc
if len(raw) != _FRAME_BYTES:
raise ValueError("PersonaPlex duplex append must contain exactly 1920 samples")
return dict(payload)
class PersonaPlexDuplexRuntimeExtension:
"""PersonaPlex policy for the engine-owned resumable duplex request."""
def configure_sampling_params(
self,
*,
runtime_config: dict[str, Any],
defaults: tuple[object, ...],
) -> tuple[object, ...]:
del runtime_config
if not defaults:
return defaults
configured = list(defaults)
stage0 = defaults[0]
if isinstance(stage0, SamplingParams):
stage0 = stage0.clone()
stage0.temperature = 0.0
stage0.top_k = 1
stage0.max_tokens = 1
configured[0] = stage0
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
if mode is not DuplexInputMode.APPEND_AUDIO_CHUNK:
raise ValueError(f"PersonaPlex does not support duplex input mode {mode.value!r}")
normalized_payload = _validated_frame_payload(payload)
prefill_slots = runtime_config.get("personaplex_prefill_slots", 0)
try:
prefill_slots = max(0, int(prefill_slots))
except (TypeError, ValueError) as exc:
raise ValueError("personaplex_prefill_slots must be a non-negative integer") from exc
prompt_slots = 1 + (prefill_slots if seq <= 1 else 0)
return DuplexAppendPlan(
prompt={
"prompt_token_ids": [0] * prompt_slots,
"model_intermediate_buffer": {
"request_id": request_id,
"global_request_id": [fence.session_id],
"duplex": {
"data_plane": True,
"fence": fence,
"session_id": fence.session_id,
"incarnation": fence.incarnation,
"epoch": fence.epoch,
"turn_id": fence.turn_id,
"response_seq": fence.response_seq,
"seq": seq,
"turn_seq": turn_seq,
"mode": mode.value,
"payload": normalized_payload,
"final": final,
"session_config": dict(session_config),
"runtime_config": dict(runtime_config),
"scheduler_token_budget": prompt_slots,
},
},
}
)
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:
del stage_id, final_stage_id, segment_finished
del segment_token_ids, segment_output_metadata, output
return None
__all__ = ["PersonaPlexDuplexRuntimeExtension"]
@@ -0,0 +1,253 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Mapping
from copy import deepcopy
from dataclasses import dataclass, field
from pathlib import PurePath
from typing import Any
from vllm_omni.entrypoints.duplex.protocol import (
DuplexCapabilities,
)
from vllm_omni.entrypoints.duplex.runtime_adapter import (
ServingRuntimeConfigError,
reject_changed_runtime_value,
)
from vllm_omni.model_executor.models.personaplex.duplex.config import DEFAULT_PERSONA
from vllm_omni.model_executor.models.personaplex.duplex.data_plane import (
PersonaPlexDataPlaneContext,
PersonaPlexDataPlaneSession,
)
from vllm_omni.model_executor.models.personaplex.duplex.input import (
PersonaPlexPcmAppendBuffer,
)
EncodeAudio = Callable[[object, int, str, float | None], str | None]
_PRIVATE_RUNTIME_CONFIG_KEYS = frozenset(
{
"personaplex_prefill_slots",
"personaplex_model_path",
# PersonaPlex is always model-native; the per-session opt-in knob
# (canonical name and its deprecated alias) is server-owned here.
"native_duplex",
"minicpmo45_native_duplex",
}
)
@dataclass(slots=True)
class PersonaPlexServingSessionState:
audio_buffer: PersonaPlexPcmAppendBuffer = field(default_factory=PersonaPlexPcmAppendBuffer)
input_since_commit: bool = False
speech_since_commit: bool = False
native_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,
payload: dict[str, object],
*,
operation_id: str | None,
reserved_bytes: int = 0,
) -> None:
self.committed_audio_payload = payload
self.committed_audio_operation_id = operation_id
self.committed_audio_reserved_bytes += max(0, int(reserved_bytes))
def clear_committed_audio(self) -> int:
reserved_bytes = self.committed_audio_reserved_bytes
self.committed_audio_payload = None
self.committed_audio_operation_id = None
self.committed_audio_reserved_bytes = 0
self.deferred_response_create = False
self.deferred_precreate_response = False
return reserved_bytes
def clear_continuation(self) -> None:
self.continuation_owner_id = None
self.continuation_units = 0
self.pending_silence_task = None
self.pending_silence_owner_id = None
class PersonaPlexServingRuntimeAdapter:
adapter_id = "personaplex"
clean_response_done_prefix = ""
interrupted_tts_prefix = ""
private_runtime_config_keys = _PRIVATE_RUNTIME_CONFIG_KEYS
def __init__(self, encode_audio: EncodeAudio) -> None:
self.session_states: dict[str, PersonaPlexServingSessionState] = {}
self.data_plane = PersonaPlexDataPlaneSession(encode_audio)
def create_session_state(self) -> PersonaPlexServingSessionState:
return PersonaPlexServingSessionState()
def session_state(self, session_id: str) -> PersonaPlexServingSessionState:
return self.session_states.setdefault(session_id, self.create_session_state())
def remove_session_state(self, session_id: str) -> None:
self.session_states.pop(session_id, None)
@staticmethod
def is_enabled(config: object) -> bool:
del config
return True
@staticmethod
def capabilities(*, max_sessions: int) -> DuplexCapabilities:
supports_multi_session = max_sessions > 1
return DuplexCapabilities(
supports_model_native_turn_policy=True,
supports_external_turn_signal=False,
supports_client_commit=False,
supports_barge_in=False,
supports_playback_ack=True,
supports_input_append=True,
supports_replace_latest_chunk=False,
supports_reencode_context=False,
supports_rollback_to_checkpoint=False,
supports_turn_commit_only=False,
supports_model_internal_state=True,
supports_stage_resumption=True,
supports_core_resumable_request=True,
supports_stage_connector_handoff=True,
supports_independent_io_streams=True,
supports_realtime_endpoint=True,
supports_multi_session=supports_multi_session,
supports_multi_session_same_replica=supports_multi_session,
supports_session_lease=True,
supports_session_resume=False,
session_admission_mode="engine_managed",
supports_audio_truncate=False,
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"],
stage_handoff_transport="scheduler_data_plane",
chunk_period_ms=80,
target_barge_in_latency_ms=None,
)
@staticmethod
def validate_client_extra_body(extra_body: object) -> None:
if not isinstance(extra_body, dict):
return
private = sorted(_PRIVATE_RUNTIME_CONFIG_KEYS.intersection(extra_body))
if private:
raise ServingRuntimeConfigError("PersonaPlex runtime configuration is server-owned: " + ", ".join(private))
@classmethod
async def prepare_runtime_config(
cls,
config: object,
*,
model_config: Any,
) -> dict[str, object]:
extra_body = getattr(config, "extra_body", None)
cls.validate_client_extra_body(extra_body)
model_path = getattr(model_config, "model", None)
if not isinstance(model_path, str) or not model_path:
raise ServingRuntimeConfigError("PersonaPlex model path is unavailable")
voice = cls._voice_name(getattr(config, "voice", None))
instructions = getattr(config, "instructions", None) or DEFAULT_PERSONA
from vllm_omni.model_executor.models.personaplex.duplex.stage0 import (
personaplex_prefill_slots,
)
try:
prefill_slots = await asyncio.to_thread(
personaplex_prefill_slots,
model_path,
voice,
str(instructions),
)
except Exception as exc:
raise ServingRuntimeConfigError(f"PersonaPlex voice/persona prefill could not be prepared: {exc}") from exc
return {
"personaplex_model_path": model_path,
"personaplex_voice_prompt": voice,
"personaplex_persona": str(instructions),
"personaplex_prefill_slots": prefill_slots,
}
@classmethod
def runtime_config_for_update(
cls,
config: object,
current: Mapping[str, object],
) -> dict[str, object]:
cls.validate_client_extra_body(getattr(config, "extra_body", None))
new_persona = str(getattr(config, "instructions", None) or DEFAULT_PERSONA)
reject_changed_runtime_value(
new_persona,
current.get("personaplex_persona"),
message="PersonaPlex persona (instructions) cannot be changed after the session is created",
code="persona_update_unsupported",
)
new_voice = cls._voice_name(getattr(config, "voice", None))
reject_changed_runtime_value(
new_voice,
current.get("personaplex_voice_prompt"),
message="PersonaPlex voice cannot be changed after the session is created",
code="voice_update_unsupported",
)
runtime_config = deepcopy(dict(current))
runtime_config["personaplex_voice_prompt"] = new_voice
runtime_config["personaplex_persona"] = new_persona
return runtime_config
@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, ...],
) -> PersonaPlexDataPlaneContext:
return PersonaPlexDataPlaneContext(
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,
)
@staticmethod
def _voice_name(value: object) -> str:
voice = value if isinstance(value, str) and value else "NATF2.pt"
path = PurePath(voice)
if path.name != voice or path.suffix != ".pt" or any(part == ".." for part in path.parts):
raise ServingRuntimeConfigError("PersonaPlex voice must be a bundled .pt basename")
return voice
__all__ = [
"PersonaPlexServingRuntimeAdapter",
"PersonaPlexServingSessionState",
]
@@ -0,0 +1,467 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import base64
import binascii
import io
import tarfile
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import numpy as np
from vllm_omni.model_executor.models.personaplex.duplex.policy import (
AUDIO_SILENCE_FRAME_CNT,
SILENCE_TOKENS,
SINE_TOKENS,
ZERO_TEXT_TOKEN,
wrap_with_system_tags,
)
_FRAME_SAMPLES = 1920
@dataclass(slots=True)
class PersonaPlexStage0PreparedAppend:
input_ids: Any
inputs_embeds: Any
user_codes: Any
info_update: dict[str, Any]
prefill_applied: bool
prompt_offset: int
@dataclass(slots=True)
class PersonaPlexStage0SessionState:
session_id: str
incarnation: int
user_codes: Any | None = None
last_text_token: Any | None = None
last_agent_codes: Any | None = None
prefill_slots: int = 0
prepared_identity: tuple[int, int] | None = None
sampled_identity: tuple[int, int] | None = None
prepared: PersonaPlexStage0PreparedAppend | None = None
last_seq: int = 0
request_ids: set[str] = field(default_factory=set)
codec: Any | None = None
def _tokenizer_path(model_path: str) -> Path:
path = Path(model_path) / "tokenizer_spm_32k_3.model"
if not path.is_file():
raise FileNotFoundError(f"PersonaPlex tokenizer not found: {path}")
return path
def load_personaplex_tokenizer(model_path: str):
import sentencepiece
tokenizer = sentencepiece.SentencePieceProcessor(str(_tokenizer_path(model_path)))
return lambda text: list(tokenizer.encode(text))
def load_personaplex_voice_state(model_path: str, voice: str) -> dict[str, Any]:
import torch
root = Path(model_path)
for candidate in (root / "voices" / voice, root / voice):
if candidate.is_file():
state = torch.load(candidate, map_location="cpu", weights_only=True)
if isinstance(state, dict):
return state
raise ValueError(f"PersonaPlex voice bundle is not a mapping: {candidate}")
archive = root / "voices.tgz"
if archive.is_file():
with tarfile.open(archive, "r:gz") as tar:
member = next(
(item for item in tar.getmembers() if item.isfile() and Path(item.name).name == voice),
None,
)
if member is not None:
extracted = tar.extractfile(member)
if extracted is None:
raise FileNotFoundError(f"PersonaPlex voice prompt {voice!r} is unreadable")
state = torch.load(io.BytesIO(extracted.read()), map_location="cpu", weights_only=True)
if isinstance(state, dict):
return state
raise ValueError(f"PersonaPlex voice bundle {voice!r} is not a mapping")
raise FileNotFoundError(f"PersonaPlex bundled voice prompt {voice!r} was not found under {model_path!r}")
def personaplex_prefill_slots(model_path: str, voice: str, persona: str) -> int:
state = load_personaplex_voice_state(model_path, voice)
embeddings = state.get("embeddings")
if not hasattr(embeddings, "shape") or len(embeddings.shape) < 1:
raise ValueError(f"PersonaPlex voice prompt {voice!r} has no embeddings")
tokenizer = load_personaplex_tokenizer(model_path)
persona_tokens = tokenizer(wrap_with_system_tags(persona)) if persona else []
return int(embeddings.shape[0]) + 2 * AUDIO_SILENCE_FRAME_CNT + len(persona_tokens)
class PersonaPlexStage0DuplexRuntime:
"""Own per-session streaming Mimi encoders and first-append prefill."""
def __init__(
self,
stage_model: Any,
*,
model_path: str,
device: str,
codec: Any | None = None,
codec_factory: Callable[[], Any] | None = None,
max_sessions: int = 1,
tokenizer=None,
voice_loader=None,
) -> None:
if max_sessions <= 0:
raise ValueError("PersonaPlex Stage 0 max_sessions must be positive")
self.stage_model = stage_model
self.model_path = model_path
self.device = device
self.max_sessions = max_sessions
self._codec_factory = codec_factory
self._free_codecs: list[Any] = []
self._tokenizer = tokenizer
self._voice_loader = voice_loader
self.sessions: dict[tuple[str, int], PersonaPlexStage0SessionState] = {}
self.request_sessions: dict[str, tuple[str, int]] = {}
if codec is not None:
codec.streaming_init(1)
self._free_codecs.append(codec)
def prepare_append(
self,
duplex: dict[str, Any],
*,
prompt_len: int,
request_id: str | None = None,
) -> PersonaPlexStage0PreparedAppend:
import torch
session_id = duplex.get("session_id")
if not isinstance(session_id, str) or not session_id:
raise ValueError("PersonaPlex duplex append requires session_id")
incarnation = _coerce_non_negative_int(duplex.get("incarnation"), "incarnation")
epoch = _coerce_non_negative_int(duplex.get("epoch"), "epoch")
seq = _coerce_positive_int(duplex.get("seq"), "seq")
identity = (epoch, seq)
key = (session_id, incarnation)
state = self.sessions.get(key)
if state is None:
if len(self.sessions) >= self.max_sessions:
raise RuntimeError(f"PersonaPlex Stage 0 session capacity {self.max_sessions} is exhausted")
state = PersonaPlexStage0SessionState(
session_id=session_id,
incarnation=incarnation,
codec=self._acquire_codec(),
)
self.sessions[key] = state
if request_id:
state.request_ids.add(request_id)
self.request_sessions[request_id] = key
if state.prepared_identity == identity and state.prepared is not None:
return state.prepared
if seq <= state.last_seq:
raise ValueError(f"PersonaPlex duplex append seq must increase: last={state.last_seq}, got={seq}")
pcm = self._decode_pcm(duplex.get("payload"))
codec = state.codec
if codec is None:
raise RuntimeError("PersonaPlex Stage 0 session has no streaming encoder")
encoded = codec.encode_frame(torch.from_numpy(pcm).reshape(1, _FRAME_SAMPLES))
user_frame = encoded.detach().to(dtype=torch.long, device="cpu").reshape(1, -1)
if user_frame.shape[1] < 8:
raise RuntimeError(
f"PersonaPlex Mimi encoder returned {user_frame.shape[1]} codebooks, expected at least 8"
)
user_frame = user_frame[:, :8].contiguous()
state.user_codes = user_frame if state.user_codes is None else torch.cat([state.user_codes, user_frame], dim=0)
runtime_config = duplex.get("runtime_config")
runtime_config = dict(runtime_config) if isinstance(runtime_config, dict) else {}
first_append = state.last_seq == 0
device, dtype = self._model_device_dtype()
silence = torch.tensor(SILENCE_TOKENS, dtype=torch.long, device=device)
sine = torch.tensor(SINE_TOKENS, dtype=torch.long, device=device)
text_token = state.last_text_token
if text_token is None:
text_token = torch.tensor([ZERO_TEXT_TOKEN], dtype=torch.long, device=device)
last_agent = state.last_agent_codes if state.last_agent_codes is not None else silence
user_frame_count = state.user_codes.shape[0]
# Match the native lockstep ring: the temporal input sees the previous
# effective agent frame. User cb0 trails the frame being appended by one
# tick and user cb1..7 trail it by two ticks. Before live user frames
# fill those slots, text-prompt prefill leaves encoded sine on user rows.
user_d0 = state.user_codes[-2].to(device) if user_frame_count > 1 else sine
user_d1 = state.user_codes[-3].to(device) if user_frame_count > 2 else sine
depformer_audio_tokens = torch.cat(
[
silence,
user_frame[0, :1].to(device),
user_d0[1:8],
]
)
depformer_audio_provided = torch.tensor(
[
False,
*([first_append] * 7),
*([True] * 8),
],
dtype=torch.bool,
device=device,
)
live_embed = self.stage_model._build_frame_embed(
text_token,
last_agent,
last_agent,
device,
user_d0=user_d0,
user_d1=user_d1,
)
if first_append:
voice = runtime_config.get("personaplex_voice_prompt", "NATF2.pt")
persona = runtime_config.get("personaplex_persona", "")
if not isinstance(voice, str) or not voice:
raise ValueError("PersonaPlex runtime voice prompt is invalid")
if not isinstance(persona, str):
raise ValueError("PersonaPlex runtime persona is invalid")
voice_state = self._load_voice(voice)
voice_embeddings = voice_state.get("embeddings")
if not isinstance(voice_embeddings, torch.Tensor) or voice_embeddings.numel() == 0:
raise ValueError(f"PersonaPlex voice prompt {voice!r} has no embeddings")
voice_embeddings = voice_embeddings.reshape(-1, voice_embeddings.shape[-1]).to(
device=device,
dtype=dtype,
)
tokenizer = self._load_tokenizer()
persona_tokens = tokenizer(wrap_with_system_tags(persona)) if persona else []
prefill_tokens = torch.tensor(
[
*([ZERO_TEXT_TOKEN] * AUDIO_SILENCE_FRAME_CNT),
*persona_tokens,
*([ZERO_TEXT_TOKEN] * AUDIO_SILENCE_FRAME_CNT),
],
dtype=torch.long,
device=device,
)
token_prefill = self.stage_model._build_prefill_embed(
prefill_tokens,
0,
int(prefill_tokens.numel()),
device,
silence,
user_sine=sine,
)
prefill_embeds = torch.cat(
[
voice_embeddings,
token_prefill.to(dtype=dtype),
],
dim=0,
)
state.prefill_slots = int(prefill_embeds.shape[0])
full_embeds = torch.cat([prefill_embeds, live_embed.to(dtype=dtype)], dim=0)
else:
full_embeds = live_embed.to(dtype=dtype)
prepared_len = int(full_embeds.shape[0])
prompt_offset = int(prompt_len) - prepared_len
if prompt_offset < 0:
raise ValueError(
f"PersonaPlex scheduler prompt reservation mismatch: reserved={prompt_len}, prepared={prepared_len}"
)
input_ids = torch.zeros((prepared_len,), dtype=torch.long, device=device)
info_update = {
"pplex_user_codes": state.user_codes,
"pplex_silence_codes": silence.detach().cpu(),
"pplex_depformer_audio_tokens": depformer_audio_tokens.detach().cpu(),
"pplex_depformer_audio_provided": depformer_audio_provided.detach().cpu(),
"meta": {
"pplex_frame": state.prefill_slots + int(state.user_codes.shape[0]),
"pplex_prefill_len": state.prefill_slots,
},
"duplex": {
"stage0_prepared": True,
"prefill_applied": first_append,
"session_id": session_id,
"incarnation": incarnation,
"epoch": epoch,
"seq": seq,
},
}
prepared = PersonaPlexStage0PreparedAppend(
input_ids=input_ids,
inputs_embeds=full_embeds,
user_codes=state.user_codes,
info_update=info_update,
prefill_applied=first_append,
prompt_offset=prompt_offset,
)
state.prepared_identity = identity
state.prepared = prepared
state.last_seq = seq
return prepared
def record_sample(
self,
*,
request_id: str,
text_token: Any,
agent_codes: Any,
) -> None:
"""Commit one sampled temporal frame for the next live append."""
import torch
key = self.request_sessions.get(request_id)
if key is None:
raise KeyError(f"PersonaPlex Stage 0 request is not attached to a live session: {request_id}")
state = self.sessions.get(key)
if state is None or state.prepared_identity is None:
raise RuntimeError(f"PersonaPlex Stage 0 request has no prepared append: {request_id}")
if state.sampled_identity == state.prepared_identity:
return
text = torch.as_tensor(text_token, device=self._model_device_dtype()[0], dtype=torch.long).reshape(-1)
codes = torch.as_tensor(agent_codes, device=text.device, dtype=torch.long).reshape(-1)
if text.numel() != 1:
raise ValueError(f"PersonaPlex Stage 0 expected one sampled text token, got {text.numel()}")
if codes.numel() < 8:
raise ValueError(f"PersonaPlex Stage 0 expected at least 8 agent codes, got {codes.numel()}")
effective_codes = codes[:8].clone()
prepared = state.prepared
if prepared is None:
raise RuntimeError(f"PersonaPlex Stage 0 request has no prepared payload: {request_id}")
target = prepared.info_update.get("pplex_depformer_audio_tokens")
provided = prepared.info_update.get("pplex_depformer_audio_provided")
if not isinstance(target, torch.Tensor) or not isinstance(provided, torch.Tensor):
raise RuntimeError("PersonaPlex Stage 0 prepared payload has no depformer teacher-forcing state")
target = target.reshape(-1).to(device=effective_codes.device, dtype=torch.long)
provided = provided.reshape(-1).to(device=effective_codes.device, dtype=torch.bool)
if target.numel() < 8 or provided.numel() < 8:
raise RuntimeError("PersonaPlex Stage 0 depformer teacher-forcing state is shorter than one agent frame")
effective_codes = torch.where(provided[:8], target[:8], effective_codes)
state.last_agent_codes = effective_codes.detach()
state.last_text_token = text.detach()
state.sampled_identity = state.prepared_identity
def close_request(self, request_id: str) -> None:
key = self.request_sessions.pop(request_id, None)
if key is None:
return
state = self.sessions.get(key)
if state is None:
return
state.request_ids.discard(request_id)
if not state.request_ids:
self.close_session(*key)
def close_session(self, session_id: str, incarnation: int) -> None:
key = (session_id, incarnation)
state = self.sessions.pop(key, None)
if state is None:
return
for request_id in state.request_ids:
self.request_sessions.pop(request_id, None)
if state.codec is not None:
state.codec.reset_streaming()
self._free_codecs.append(state.codec)
state.codec = None
def _acquire_codec(self):
if self._free_codecs:
return self._free_codecs.pop()
if self._codec_factory is not None:
codec = self._codec_factory()
codec.streaming_init(1)
return codec
from vllm_omni.model_executor.models.personaplex.personaplex_mimi import (
PersonaPlexMimiCodec,
)
checkpoint = Path(self.model_path) / "tokenizer-e351c8d8-checkpoint125.safetensors"
codec = PersonaPlexMimiCodec(
checkpoint=str(checkpoint) if checkpoint.is_file() else None,
device=self.device,
)
codec.streaming_init(1)
return codec
def _load_tokenizer(self):
if self._tokenizer is None:
self._tokenizer = load_personaplex_tokenizer(self.model_path)
return self._tokenizer
def _load_voice(self, voice: str) -> dict[str, Any]:
if self._voice_loader is not None:
state = self._voice_loader(voice)
else:
state = load_personaplex_voice_state(self.model_path, voice)
if not isinstance(state, dict):
raise ValueError(f"PersonaPlex voice prompt {voice!r} is not a mapping")
return state
def _model_device_dtype(self):
import torch
try:
parameter = next(self.stage_model.parameters())
return parameter.device, parameter.dtype
except Exception:
device = getattr(self.stage_model, "device", torch.device(self.device))
dtype = getattr(self.stage_model, "dtype", torch.float32)
return torch.device(device), dtype
@staticmethod
def _decode_pcm(payload: object) -> np.ndarray:
if not isinstance(payload, dict):
raise ValueError("PersonaPlex duplex payload must be a mapping")
if payload.get("format") != "pcm_f32le" or payload.get("sample_rate_hz") != 24000:
raise ValueError("PersonaPlex Stage 0 requires 24 kHz pcm_f32le")
audio = payload.get("audio")
if not isinstance(audio, str):
raise ValueError("PersonaPlex Stage 0 requires base64 audio")
try:
raw = base64.b64decode(audio, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("PersonaPlex Stage 0 audio is not valid base64") from exc
samples = np.frombuffer(raw, dtype="<f4")
if samples.size != _FRAME_SAMPLES:
raise ValueError(f"PersonaPlex Stage 0 requires {_FRAME_SAMPLES} samples per append")
if not np.isfinite(samples).all():
raise ValueError("PersonaPlex Stage 0 samples must be finite")
return np.ascontiguousarray(samples, dtype=np.float32).copy()
def _coerce_non_negative_int(value: object, name: str) -> int:
try:
result = int(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"PersonaPlex duplex {name} must be an integer") from exc
if result < 0:
raise ValueError(f"PersonaPlex duplex {name} must be non-negative")
return result
def _coerce_positive_int(value: object, name: str) -> int:
result = _coerce_non_negative_int(value, name)
if result <= 0:
raise ValueError(f"PersonaPlex duplex {name} must be positive")
return result
__all__ = [
"PersonaPlexStage0DuplexRuntime",
"PersonaPlexStage0PreparedAppend",
"PersonaPlexStage0SessionState",
"load_personaplex_tokenizer",
"load_personaplex_voice_state",
"personaplex_prefill_slots",
]
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Stage-1 Code2Wav model for PersonaPlex (Moshi finetune).
This is the ``LLM_GENERATION`` codec stage of the 2-stage PersonaPlex pipeline.
@@ -23,7 +23,7 @@ Layout contract (mirrors ``Qwen3TTSCode2Wav``):
The Mimi decoder is the transformers ``MimiModel`` (kyutai/mimi weights), not
in vLLM's safetensors loader, so they are loaded eagerly in ``load_weights``
part of the vLLM weights iterator (the codec owns its own checkpoint; see the
experimental fullduplex package for the same pattern).
``duplex`` subpackage of this model folder for the same pattern).
"""
from __future__ import annotations
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""PersonaPlex talker: the temporal transformer as a vLLM-native omni AR stage.
This is the stage-0 (``LLM_AR``) model the OmniGPUModelRunner drives. It composes
@@ -420,7 +420,7 @@ class PersonaPlexTalkerForConditionalGeneration(nn.Module):
runtime = getattr(self, "_personaplex_duplex_stage0_runtime", None)
if runtime is not None:
return runtime
from vllm_omni.experimental.fullduplex.personaplex.stage0 import (
from vllm_omni.model_executor.models.personaplex.duplex.stage0 import (
PersonaPlexStage0DuplexRuntime,
)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""PersonaPlex pipeline: Talker (AR decode -> Mimi codebooks) -> Code2Wav (codebooks -> 24 kHz PCM).
PersonaPlex is a Moshi finetune (full-duplex speech-to-speech). For offline/batch
@@ -32,10 +32,10 @@ PERSONAPLEX_PIPELINE = PipelineConfig(
model_arch="PersonaPlexTalkerForConditionalGeneration",
default_deploy_config_name="personaplex.yaml",
duplex_runtime_extension=(
"vllm_omni.experimental.fullduplex.personaplex.runtime_extension.PersonaPlexDuplexRuntimeExtension"
"vllm_omni.model_executor.models.personaplex.duplex.runtime_extension.PersonaPlexDuplexRuntimeExtension"
),
duplex_serving_adapter=(
"vllm_omni.experimental.fullduplex.personaplex.serving_adapter.PersonaPlexServingRuntimeAdapter"
"vllm_omni.model_executor.models.personaplex.duplex.serving_adapter.PersonaPlexServingRuntimeAdapter"
),
duplex_control_enabled=True,
stages=(