[Feature] PersonaPlex (Moshi-based full-duplex S2S): native vLLM port + duplex serving (#4771)
Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Signed-off-by: Sy0307 <24841857+Sy0307@users.noreply.github.com> Co-authored-by: Sy0307 <24841857+Sy0307@users.noreply.github.com>
This commit is contained in:
1 parent
f24a6165ff
commit
e788ef6e76
59 files changed
+10389
-12
No files matched your search
@@ -1,10 +1,12 @@
|
||||
# Experimental Full-Duplex Runtime
|
||||
|
||||
This package contains two experimental integrations:
|
||||
This package contains three experimental integrations:
|
||||
|
||||
- the existing JoyVL framework and example integration;
|
||||
- the MiniCPM-o 4.5 native audio path used by `/v1/duplex` and
|
||||
`/v1/realtime?duplex=1`.
|
||||
`/v1/realtime?duplex=1`;
|
||||
- the PersonaPlex lockstep speech-to-speech path (browser demo + batched
|
||||
serving, see `recipes/NVIDIA/PersonaPlex.md`).
|
||||
|
||||
For the MiniCPM active runtime path, lifecycle invariants, capability boundary,
|
||||
Realtime response contract, and validation scope, see [`DESIGN.md`](DESIGN.md).
|
||||
@@ -15,14 +17,39 @@ To run JoyVL, see
|
||||
## Package boundaries
|
||||
|
||||
```text
|
||||
core/ existing JoyVL framework and experimental compatibility exports
|
||||
engine/ AsyncOmni/orchestrator scheduler data-plane adapter
|
||||
openai/ WebSocket transport, Realtime projection, and audio codecs
|
||||
minicpmo45/ MiniCPM input framing, policy, compatibility, and Stage0 state
|
||||
joyvl/ JoyVL model-specific integration
|
||||
core/ model-agnostic duplex contracts (adapter, session, turn runtime)
|
||||
engine/ AsyncOmni/orchestrator scheduler data-plane adapter
|
||||
openai/ WebSocket transport, Realtime projection, and audio codecs
|
||||
minicpmo45/ MiniCPM input framing, policy, compatibility, and Stage0 state
|
||||
joyvl/ JoyVL model-specific integration
|
||||
personaplex/ PersonaPlex lockstep engine, model-owned runtime, and serving
|
||||
```
|
||||
|
||||
MiniCPM does not run through the removed experimental `core.DuplexRuntime`
|
||||
MiniCPM does not run through the experimental `core.DuplexRuntime`
|
||||
facade. Its active path uses the `openai` session controller, the experimental
|
||||
engine contracts, the standard scheduler/model runners, and an injected
|
||||
MiniCPM-specific runtime extension from `minicpmo45/runtime.py`.
|
||||
|
||||
`personaplex/` is a Moshi-class, pure-lockstep speech-to-speech model on the
|
||||
`core/` contracts. It keeps `core/` untouched: the lockstep lifecycle (ONE
|
||||
eternal, frame-clocked response that drains on close, instead of the turn-style
|
||||
start/cancel-per-trigger one) is model policy and lives in the model package as
|
||||
`PersonaPlexDuplexRuntime`, mirroring the model-owned runtime shape of the
|
||||
MiniCPM-o duplex work. Its runnable serving path is `personaplex/serving/`
|
||||
(single-session lease or `--batch-size` elastic slots) over
|
||||
`personaplex/session.py` (lockstep driver).
|
||||
|
||||
## Adding a full-duplex model on the core contracts
|
||||
|
||||
The seam is `core.DuplexAdapter`. `core/` owns the session lifecycle,
|
||||
epoch-based barge-in, playback cursor, and the event protocol; you implement
|
||||
only model policy.
|
||||
|
||||
1. Create a sibling package `vllm_omni/experimental/fullduplex/<model>/`; keep
|
||||
model-specific code there and do not touch `core/`.
|
||||
2. Implement one `DuplexAdapter` (`capabilities` / `on_input` / `respond`; the
|
||||
rest have defaults). Turn-based models run through `core.DuplexRuntime`
|
||||
unchanged; a model needing a different lifecycle carries its own runtime in
|
||||
its package (see `personaplex/adapter.py::PersonaPlexDuplexRuntime`).
|
||||
3. Promote a helper from a model package up into `core/` only once a second
|
||||
model actually needs it.
|
||||
@@ -0,0 +1,259 @@
|
||||
# PersonaPlex Unified Full-Duplex Design
|
||||
|
||||
## Status and target
|
||||
|
||||
This design adapts PersonaPlex PR #4771 to the unified full-duplex runtime on
|
||||
top of:
|
||||
|
||||
- vLLM-Omni `origin/main`: `67c54777bb22e9e7e08fdf7c47a64f06b566fc47`
|
||||
- PersonaPlex PR head: `477fb7c225f0c06991bc8aa55eadbd908ba282e4`
|
||||
|
||||
The target is the engine-native path:
|
||||
|
||||
```text
|
||||
/v1/realtime?duplex=1
|
||||
-> OpenAI Realtime session actor
|
||||
-> DuplexRequestClient
|
||||
-> AsyncOmni correlated RPC
|
||||
-> DuplexControlPlane
|
||||
-> resumable Stage 0 request
|
||||
-> PersonaPlex Talker
|
||||
-> streaming PersonaPlex Code2Wav
|
||||
-> PersonaPlex data-plane projector
|
||||
-> response.audio.delta + response.audio_transcript.delta
|
||||
```
|
||||
|
||||
The standalone `/api/chat` and `/v1/audio/duplex` server remains a compatibility
|
||||
surface. It is not evidence that the unified engine path works.
|
||||
|
||||
## Why configuration-only enablement is invalid
|
||||
|
||||
The current staged pipeline is explicitly turn based. Its Talker reads
|
||||
`pplex_user_codes`, `pplex_prefill_text`, and `pplex_silence_codes`, but no
|
||||
production staged input path writes those fields. The voice prompt, persona
|
||||
prefill, and streaming Mimi state live only in the standalone
|
||||
`PersonaPlexEngine`.
|
||||
|
||||
Setting only the following fields would therefore advertise an endpoint whose
|
||||
model never receives the live microphone stream:
|
||||
|
||||
```python
|
||||
duplex_control_enabled = True
|
||||
duplex_runtime_extension = "..."
|
||||
duplex_serving_adapter = "..."
|
||||
```
|
||||
|
||||
The adapter must supply a real scheduler data plane, not just endpoint
|
||||
capabilities.
|
||||
|
||||
## Supported scope
|
||||
|
||||
The unified implementation supports:
|
||||
|
||||
- up to two engine-owned sessions on one replica;
|
||||
- 24 kHz mono float PCM input;
|
||||
- one 1920-sample, 80 ms model frame per physical append unit;
|
||||
- continuous user input while assistant audio is generated or played;
|
||||
- bundled `.pt` voice prompts and a session persona;
|
||||
- greedy text and depformer sampling, matching the current PersonaPlex port;
|
||||
- `/v1/realtime?duplex=1`;
|
||||
- engine lease close, disconnect cleanup, reconnect after cleanup, and explicit
|
||||
response cancellation without cross-session state reuse.
|
||||
|
||||
The implementation does not claim:
|
||||
|
||||
- more than two simultaneous PersonaPlex sessions on one replica;
|
||||
- arbitrary WAV voice cloning;
|
||||
- turn-based `response.create` semantics for an otherwise continuous model;
|
||||
- scheduler migration of live codec state between replicas;
|
||||
- exact output equality with the standalone engine after different scheduling
|
||||
boundaries.
|
||||
|
||||
The capability payload derives multi-session support from the configured
|
||||
session limit. The shipped two-session deployment reports
|
||||
`supports_multi_session=true` and `supports_multi_session_same_replica=true`.
|
||||
`duplex_session.max_sessions` is the only capacity source: config resolution
|
||||
propagates it to every stage as `duplex_max_sessions`, and both Mimi pools read
|
||||
that model-config value. Connector extras do not carry a second model-specific
|
||||
capacity knob that could drift from engine admission.
|
||||
It still reports `supports_barge_in=false`: the generic epoch fence can suppress
|
||||
stale transport output, but neither PersonaPlex nor the current MiniCPM-o 4.5
|
||||
adapter proves that model-owned streaming state can be destructively rewound or
|
||||
restarted at a playback cursor. Continuous overlapping speech is model-native
|
||||
duplex behavior, not by itself a barge-in contract.
|
||||
|
||||
## Components and ownership
|
||||
|
||||
### Serving adapter
|
||||
|
||||
`PersonaPlexServingRuntimeAdapter` owns only serving-side state:
|
||||
|
||||
- a transactional PCM append buffer;
|
||||
- validation of `voice_prompt` and `instructions`;
|
||||
- public capabilities;
|
||||
- PersonaPlex data-plane output projection.
|
||||
|
||||
It accepts 24 kHz `pcm_f32le`, groups client packets into whole 1920-sample
|
||||
frames, zero-pads only the final residual, and rolls a reservation back when an
|
||||
engine append fails. It never loads CUDA weights and never encodes user audio.
|
||||
|
||||
Client input cannot provide local filesystem paths. A voice is a bundled
|
||||
basename such as `NATF2.pt`; the worker resolves it under the local model
|
||||
checkpoint. `instructions` is the persona string.
|
||||
|
||||
### Runtime extension
|
||||
|
||||
`PersonaPlexDuplexRuntimeExtension` is pure model policy. It:
|
||||
|
||||
- configures greedy Stage 0 sampling and bounded segment lengths;
|
||||
- maps each accepted PCM append to a scheduler prompt;
|
||||
- places immutable session identity, append sequence, PCM payload, voice, and
|
||||
persona under `model_intermediate_buffer["duplex"]`;
|
||||
- reserves exactly one scheduler prompt slot per encoded Mimi frame, plus the
|
||||
first-append voice/persona prefill length;
|
||||
- never performs model inference or owns session state.
|
||||
|
||||
The extension returns no turn/listen decision. PersonaPlex is an always-clocked
|
||||
model, so visible audio/text comes from the final stage data plane.
|
||||
|
||||
### Stage 0 streaming runtime
|
||||
|
||||
The Talker owns a `PersonaPlexStage0DuplexRuntime` helper, analogous to
|
||||
MiniCPM-o's Stage 0 helper but with PersonaPlex lockstep semantics.
|
||||
|
||||
For each admitted session it owns:
|
||||
|
||||
- streaming Mimi encoder convolution and transformer state;
|
||||
- the selected voice embedding bundle;
|
||||
- persona tokenization and prefill embeddings;
|
||||
- the prior user code frame needed by the one-frame acoustic delay;
|
||||
- append identity used to make a retried scheduler update idempotent.
|
||||
|
||||
The first append builds this ordered prefill:
|
||||
|
||||
```text
|
||||
voice embeddings
|
||||
-> encoded silence
|
||||
-> <system> persona <system> tokens with encoded silence
|
||||
-> encoded silence
|
||||
-> first live user frame
|
||||
```
|
||||
|
||||
Later appends encode only new 1920-sample frames. The helper returns the
|
||||
per-frame user codes and prompt embeddings through the request's
|
||||
`model_intermediate_buffer`. The normal vLLM runner remains authoritative for
|
||||
attention metadata, block tables, KV allocation, scheduling, and sampling.
|
||||
|
||||
The Talker must distinguish resumable prompt prefill from decode positions.
|
||||
Prompt rows consume the exact prepared embeddings; sampled decode rows continue
|
||||
to use the existing delayed agent/user frame construction. No code path may
|
||||
fall back to an all-initial user stream for a duplex request.
|
||||
|
||||
Cleanup is keyed by the full `(session_id, incarnation)` identity. Every live
|
||||
session has an independent Mimi encoder instance; encoder convolution/KV state
|
||||
is never shared between asynchronously scheduled sessions. A finished or
|
||||
aborted scheduler request resets and returns only that session's encoder.
|
||||
|
||||
### Stage 1 streaming decoder
|
||||
|
||||
The current `PersonaPlexCode2Wav` calls one-shot `MimiModel.decode` and is not
|
||||
CUDA-graph safe. Unified duplex uses eager Stage 1 and maintains an independent
|
||||
streaming Mimi decoder for every active request. Decoder ownership is keyed by
|
||||
the stable Stage 1 request id and released by `on_requests_finished`; a mixed
|
||||
batch must never advance another request's convolution or transformer state.
|
||||
|
||||
Each Stage 0 segment emits de-delayed agent codebooks. Stage 1 decodes only the
|
||||
new code frames, emits only the new PCM suffix, and resets state when the
|
||||
request is closed. Connector chunk boundaries retain the final raw code frame
|
||||
needed to de-delay the next chunk.
|
||||
|
||||
The deploy default sets Stage 1 `enforce_eager: true`; a default configuration
|
||||
that fails during CUDA graph capture is not an acceptable deployment profile.
|
||||
|
||||
### Data-plane projector
|
||||
|
||||
`PersonaPlexDataPlaneSession` converts cumulative or delta Stage 1 output into
|
||||
model-neutral native results:
|
||||
|
||||
```python
|
||||
{
|
||||
"stage_role": "tts",
|
||||
"data_plane_request_id": request_id,
|
||||
"text": text_delta,
|
||||
"audio_data": encoded_audio_delta,
|
||||
"audio_format": response_format,
|
||||
"sample_rate_hz": 24000,
|
||||
"audio_duration_ms": delta_duration,
|
||||
"end_of_turn": False,
|
||||
}
|
||||
```
|
||||
|
||||
It owns per-request audio and text cursors so a cumulative output cannot replay
|
||||
old audio. PersonaPlex keeps one visible response open while continuous output
|
||||
arrives. Session close or cancellation terminates that response through the
|
||||
generic Realtime lifecycle; a codec segment finishing is not a conversational
|
||||
turn boundary.
|
||||
|
||||
## Error and lifecycle contracts
|
||||
|
||||
- Unsupported sample rate, malformed base64, non-finite PCM, invalid voice
|
||||
basename, or changed format fails before scheduler submission.
|
||||
- Append is prepare/submit/commit. Failure rolls back the exact reserved PCM
|
||||
bytes and does not advance the model frame cursor.
|
||||
- A repeated `operation_id` must not encode or submit the same frame twice.
|
||||
- Input iterator exceptions execute the same cleanup as explicit close.
|
||||
- Cancellation does not release the engine lease until the stage request and
|
||||
any in-flight codec operation are actually finished.
|
||||
- A bounded cleanup timeout returns a cleanup error and keeps the session in
|
||||
the closing admission set; it must not make the slot available while work
|
||||
still mutates shared state.
|
||||
- New sessions cannot observe the previous voice, persona, PCM tail, Mimi
|
||||
convolution state, or Talker delayed code frame.
|
||||
|
||||
The legacy `PersonaPlexDuplexRuntime.run()` and standalone server drain path
|
||||
must follow the same exception-safe rule while they remain in the tree.
|
||||
|
||||
## Testing and acceptance
|
||||
|
||||
### Contract tests
|
||||
|
||||
Tests first cover:
|
||||
|
||||
- pipeline registration enables the control plane and selects both PersonaPlex
|
||||
adapters;
|
||||
- the capability payload is two-session, 80 ms, append-only, and honest;
|
||||
- PCM reservation commit/rollback, partial-frame flush, invalid input, and
|
||||
operation idempotency;
|
||||
- runtime prompt fields and exact token budgeting;
|
||||
- first-append voice/persona prefill followed by live user codes;
|
||||
- later appends retain per-session Mimi state and do not replay prefill;
|
||||
- interleaved Stage 0 and Stage 1 work preserves independent codec histories;
|
||||
- output projection emits only audio/text deltas;
|
||||
- close, exception, timeout, and reconnect cleanup;
|
||||
- ordinary non-duplex imports do not load PersonaPlex modules.
|
||||
|
||||
### Remote H20 validation
|
||||
|
||||
Validation runs in an isolated remote worktree using the ModelScope
|
||||
`nv-community/personaplex-7b-v1` checkpoint and its Mimi dependency.
|
||||
|
||||
The required evidence is:
|
||||
|
||||
1. default `personaplex.yaml` reaches ready without a local eager override;
|
||||
2. `/health` returns 200;
|
||||
3. `/v1/realtime?duplex=1` reports `model_native_duplex`, `chunk_period_ms=80`,
|
||||
and two-session admission;
|
||||
4. paced 24 kHz PCM appends produce finite, non-silent 24 kHz audio deltas and
|
||||
text deltas;
|
||||
5. microphone input continues during assistant output without cancelling the
|
||||
scheduler request;
|
||||
6. two paced sessions simultaneously produce independent non-empty audio, and
|
||||
a third session is rejected with `resource_exhausted`;
|
||||
7. closing either session frees only its scheduler request and GPU codec state,
|
||||
after which a replacement session can use a different persona without state
|
||||
leakage;
|
||||
8. malformed input returns one typed error and does not poison the next append;
|
||||
9. all focused unit tests and `git diff --check` pass.
|
||||
|
||||
Audio that is empty, all zero, non-finite, or only a protocol `listen` event is
|
||||
not a successful end-to-end result.
|
||||
@@ -0,0 +1,40 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""PersonaPlex full-duplex backend for the experimental fullduplex framework.
|
||||
|
||||
PersonaPlex (``nvidia/personaplex-7b-v1``) is a Moshi finetune: a pure-lockstep
|
||||
speech-to-speech model. This package plugs it into the model-agnostic
|
||||
``fullduplex/core`` seam without touching the engine:
|
||||
|
||||
- :class:`PersonaPlexConfig` immutable session config (voice / persona / sampling)
|
||||
- :class:`PersonaPlexEngine` the moshi-free lockstep engine (``FrameStepper``;
|
||||
single session and B concurrent slots with elastic per-slot recycle)
|
||||
- :class:`PersonaPlexSession` lockstep driver (the runnable serving primitive)
|
||||
- :class:`PersonaPlexDuplexAdapter` the ``core.DuplexAdapter`` for lockstep audio
|
||||
- :class:`PersonaPlexDuplexRuntime` the model-owned lockstep lifecycle
|
||||
(start-once / drain-on-close; ``core`` stays verbatim upstream)
|
||||
"""
|
||||
|
||||
from vllm_omni.experimental.fullduplex.personaplex.adapter import (
|
||||
PersonaPlexDuplexAdapter,
|
||||
PersonaPlexDuplexRuntime,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.personaplex.config import PersonaPlexConfig
|
||||
from vllm_omni.experimental.fullduplex.personaplex.engine import (
|
||||
FrameOutput,
|
||||
FrameStepper,
|
||||
PersonaPlexEngine,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.personaplex.runtime import PrefillStep
|
||||
from vllm_omni.experimental.fullduplex.personaplex.session import PersonaPlexSession
|
||||
|
||||
__all__ = [
|
||||
"FrameOutput",
|
||||
"FrameStepper",
|
||||
"PersonaPlexConfig",
|
||||
"PersonaPlexDuplexAdapter",
|
||||
"PersonaPlexDuplexRuntime",
|
||||
"PersonaPlexEngine",
|
||||
"PersonaPlexSession",
|
||||
"PrefillStep",
|
||||
]
|
||||
@@ -0,0 +1,177 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""PersonaPlex duplex adapter + model-owned lockstep runtime.
|
||||
|
||||
PersonaPlex is a *continuous* (frame-clocked, no turn-taking) model: one eternal
|
||||
``respond()`` that pulls one 80 ms user frame at a time and emits one agent
|
||||
frame + text token. The shared ``core.DuplexRuntime`` implements the turn
|
||||
lifecycle (start/cancel per trigger), which does not fit lockstep, so the
|
||||
lifecycle lives HERE as :class:`PersonaPlexDuplexRuntime` — model policy stays
|
||||
in the model package, mirroring #3907's model-owned minicpmo45 runtime, and
|
||||
``core`` remains verbatim upstream.
|
||||
|
||||
Stepping happens off the event loop (``asyncio.to_thread``, as Moshi's own
|
||||
server does) so the input side stays live — that is what makes barge-in work
|
||||
without any explicit flush.
|
||||
|
||||
Depends only on the ``FrameStepper`` protocol, so it is exercised by GPU-free
|
||||
tests with a stub stepper; ``PersonaPlexEngine`` is the real backend.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.experimental.fullduplex.core import protocol as ev
|
||||
from vllm_omni.experimental.fullduplex.core.adapter import DuplexAdapter, DuplexCapability, OutputChunk
|
||||
from vllm_omni.experimental.fullduplex.core.runtime import DuplexRuntime, Emit
|
||||
from vllm_omni.experimental.fullduplex.core.session import DuplexSession, DuplexState
|
||||
from vllm_omni.experimental.fullduplex.personaplex.engine import FrameStepper
|
||||
from vllm_omni.experimental.fullduplex.personaplex.session import MAX_PENDING_INPUT, offer_realtime
|
||||
|
||||
_CLOSE = object() # sentinel: drain the inbox and end the eternal response
|
||||
|
||||
|
||||
class PersonaPlexDuplexAdapter(DuplexAdapter):
|
||||
"""Drive a :class:`FrameStepper` as a continuous full-duplex response."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
stepper: FrameStepper,
|
||||
*,
|
||||
voice_prompt: str | None = None,
|
||||
persona: str | None = None,
|
||||
) -> None:
|
||||
self._stepper = stepper
|
||||
self._voice_prompt = voice_prompt
|
||||
self._persona = persona
|
||||
self._frame_size = stepper.frame_size
|
||||
# Bounded, drop-oldest: input arriving faster than the stepper can run
|
||||
# must shed stale frames (realtime), not grow memory + latency unbounded.
|
||||
self._inbox: asyncio.Queue[Any] = asyncio.Queue(maxsize=MAX_PENDING_INPUT)
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
self._opened = False
|
||||
|
||||
def capabilities(self) -> DuplexCapability:
|
||||
return DuplexCapability(
|
||||
input_modalities=frozenset({"audio"}),
|
||||
output_modalities=frozenset({"audio", "text"}),
|
||||
proactive=True,
|
||||
)
|
||||
|
||||
async def on_input(self, session: DuplexSession, modality: str, data: Any) -> None:
|
||||
"""Frame incoming PCM into exact 80 ms windows and queue them for the loop."""
|
||||
if modality != "audio":
|
||||
return
|
||||
samples = np.ascontiguousarray(data, dtype=np.float32).reshape(-1)
|
||||
self._pending = np.concatenate([self._pending, samples]) if self._pending.size else samples
|
||||
n = self._frame_size
|
||||
while self._pending.shape[0] >= n:
|
||||
frame, self._pending = self._pending[:n], self._pending[n:]
|
||||
offer_realtime(self._inbox, frame)
|
||||
|
||||
async def respond(self, session: DuplexSession) -> AsyncIterator[OutputChunk]:
|
||||
"""The eternal lockstep loop: one user frame in, one agent frame + text out."""
|
||||
if not self._opened:
|
||||
await asyncio.to_thread(self._stepper.open_session, self._voice_prompt, self._persona)
|
||||
self._opened = True
|
||||
while True:
|
||||
frame = await self._inbox.get()
|
||||
if frame is _CLOSE:
|
||||
break
|
||||
out = await asyncio.to_thread(self._stepper.step, frame)
|
||||
if out.audio is not None:
|
||||
yield OutputChunk("audio", out.audio)
|
||||
if out.text:
|
||||
yield OutputChunk("text", out.text)
|
||||
|
||||
async def on_close(self, session: DuplexSession) -> None:
|
||||
# Model-owned drain signal (not part of the core DuplexAdapter ABC):
|
||||
# PersonaPlexDuplexRuntime calls this on every exit path. Pad + flush a
|
||||
# partial final frame (same contract as PersonaPlexSession.flush()) so
|
||||
# the tail of the user's audio is stepped, not dropped.
|
||||
if self._pending.size:
|
||||
pad = self._frame_size - self._pending.shape[0]
|
||||
frame = np.concatenate([self._pending, np.zeros(pad, dtype=np.float32)])
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
offer_realtime(self._inbox, frame)
|
||||
offer_realtime(self._inbox, _CLOSE)
|
||||
|
||||
async def on_barge_in(self, session: DuplexSession) -> None:
|
||||
# No-op: Moshi-class models perceive the user continuously, so an interrupt
|
||||
# needs no downstream flush — the next frames simply steer the model.
|
||||
return
|
||||
|
||||
|
||||
class PersonaPlexDuplexRuntime(DuplexRuntime):
|
||||
"""Model-owned lockstep lifecycle: start once, never supersede, drain on exit.
|
||||
|
||||
``core.DuplexRuntime`` runs the turn lifecycle — every trigger starts a new
|
||||
response that supersedes and cancels the previous one. A lockstep model has
|
||||
exactly ONE response for the whole session: it consumes user frames as they
|
||||
arrive and only ends when the input side goes away. Keeping this here (not
|
||||
as a flag on the shared runtime) mirrors #3907's model-owned minicpmo45
|
||||
runtime: model policy lives in the model package.
|
||||
"""
|
||||
|
||||
async def run(self, inputs: AsyncIterator[dict], emit: Emit) -> None:
|
||||
task: asyncio.Task | None = None
|
||||
try:
|
||||
async for event in inputs:
|
||||
etype = event.get("type")
|
||||
if etype == ev.INPUT_APPEND:
|
||||
modality = event.get("modality", "")
|
||||
if modality not in self._capabilities.input_modalities:
|
||||
await emit(ev.error(f"unsupported input modality: {modality}"))
|
||||
continue
|
||||
await self.adapter.on_input(self.session, modality, event.get("data"))
|
||||
self.session.state = DuplexState.LISTENING
|
||||
task = self._ensure_started(task, emit)
|
||||
elif etype in (ev.INPUT_COMMIT, ev.RESPONSE_CREATE):
|
||||
task = self._ensure_started(task, emit)
|
||||
elif etype == ev.RESPONSE_CANCEL:
|
||||
# Barge-in is native for lockstep models: bump the epoch for the
|
||||
# playback cursor but keep the single response streaming.
|
||||
await self._barge_in()
|
||||
await emit(ev.cancelled(self.session.response_index))
|
||||
elif etype == ev.PLAYBACK_ACK:
|
||||
await self.adapter.on_playback_ack(self.session, int(event.get("cursor", 0)))
|
||||
elif etype == ev.CLOSE:
|
||||
break
|
||||
finally:
|
||||
# Drain on EVERY exit path: CLOSE, iterator EOF, transport errors,
|
||||
# and cancellation must not leave the eternal response blocked on
|
||||
# its inbox or the session outside CLOSED.
|
||||
try:
|
||||
if task is not None and not task.done():
|
||||
await self.adapter.on_close(self.session)
|
||||
await task
|
||||
finally:
|
||||
self.session.state = DuplexState.CLOSED
|
||||
|
||||
def _ensure_started(self, task: asyncio.Task | None, emit: Emit) -> asyncio.Task:
|
||||
# Start the single eternal response exactly once; never supersede it.
|
||||
if task is None or task.done():
|
||||
return asyncio.create_task(self._respond_once(emit))
|
||||
return task
|
||||
|
||||
async def _respond_once(self, emit: Emit) -> None:
|
||||
# One response for the whole session. No staleness checks: the loop ends
|
||||
# only when the adapter's respond() returns (after on_close drains its
|
||||
# input).
|
||||
response_index, _ = self.session.begin_response()
|
||||
await emit(ev.created(response_index))
|
||||
try:
|
||||
async for chunk in self.adapter.respond(self.session):
|
||||
await emit(ev.delta(response_index, chunk.modality, chunk.data))
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as err:
|
||||
await emit(ev.error(f"response failed: {err}"))
|
||||
finally:
|
||||
await emit(ev.done(response_index))
|
||||
self.session.end_response()
|
||||
@@ -0,0 +1,64 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM 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 project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.experimental.fullduplex.engine.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,74 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""PersonaPlex duplex protocol home (moshi-free).
|
||||
|
||||
Defines the narrow ``FrameStepper`` seam (one 80 ms user frame in, one agent
|
||||
frame + text piece out) that the session driver, the duplex adapter and the
|
||||
GPU-free tests depend on, and re-exports the native lockstep engine that
|
||||
implements it. The implementation lives in ``runtime.py`` and is built
|
||||
entirely from vllm-omni-native components (streaming Helium temporal, input
|
||||
embeddings, depformer, streaming Mimi codec) — the external ``moshi`` package
|
||||
is no longer used.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
||||
|
||||
import numpy as np
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from numpy.typing import NDArray
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FrameOutput:
|
||||
"""Result of stepping the model by exactly one 80 ms frame.
|
||||
|
||||
Attributes:
|
||||
audio: Agent PCM for this frame (``frame_size`` mono float32 samples), or
|
||||
``None`` during the model's initial delay/warmup frames.
|
||||
text: Inner-monologue text piece for this frame, or ``None`` when the
|
||||
model emitted a padding token (silence between words).
|
||||
"""
|
||||
|
||||
audio: NDArray[np.float32] | None
|
||||
text: str | None
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class FrameStepper(Protocol):
|
||||
"""The single seam between PersonaPlex and the duplex framework.
|
||||
|
||||
A stepper consumes one user audio frame and returns one agent frame. It owns
|
||||
all conversation state (KV caches / streaming buffers); callers never re-feed
|
||||
history. ``PersonaPlexEngine`` is the real implementation; tests pass a stub.
|
||||
"""
|
||||
|
||||
sample_rate: int
|
||||
frame_size: int
|
||||
|
||||
def open_session(self, voice_prompt: str | None = None, persona: str | None = None) -> None:
|
||||
"""Reset streaming state and inject the voice clone + persona prompt."""
|
||||
...
|
||||
|
||||
def step(self, user_pcm: NDArray[np.float32]) -> FrameOutput:
|
||||
"""Advance the conversation by one frame of exactly ``frame_size`` samples."""
|
||||
...
|
||||
|
||||
|
||||
from vllm_omni.experimental.fullduplex.personaplex.runtime import ( # noqa: E402
|
||||
PersonaPlexEngine,
|
||||
PrefillStep,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"FrameOutput",
|
||||
"FrameStepper",
|
||||
"PersonaPlexEngine",
|
||||
"PrefillStep",
|
||||
]
|
||||
@@ -0,0 +1,213 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM 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 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,473 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Moshi-free PersonaPlex lockstep engine (native temporal + depformer + Mimi).
|
||||
|
||||
This is the real-time duplex backend built entirely from vllm-omni-native
|
||||
components: :class:`PersonaPlexTemporalStreaming` (ring-KV Helium),
|
||||
:class:`PersonaPlexInputEmbeddings`, :class:`PersonaPlexDepformer` and
|
||||
:class:`PersonaPlexMimiCodec`. It reimplements the reference lockstep semantics
|
||||
(staging ring, per-codebook delays, warmup gates, hybrid system-prompt prefill,
|
||||
per-slot elastic recycle) as first-class policy code, so the external ``moshi``
|
||||
package is no longer needed at runtime.
|
||||
|
||||
Lockstep contract per 80 ms tick (17 token rows: text, 8 agent codebooks, 8
|
||||
user codebooks; delays ``[0, 1x8-ish from checkpoint]``):
|
||||
|
||||
1. Mimi-encode the user frame and write it (delayed) into the staging ring.
|
||||
2. Read the model input at ``(o - 1) % CT``, embed, step the temporal.
|
||||
3. Greedy text token; depformer expands the 16 audio rows (teacher-forced where
|
||||
the staging ring already holds provided values).
|
||||
4. Write sampled rows at ``o % CT``; gather the de-delayed output frame; decode
|
||||
agent rows 1..8 through Mimi (rows still in warmup are sanitized to silence
|
||||
tokens: the LM's initial audio token id equals the codec cardinality and is
|
||||
out of range for the codebook tables).
|
||||
|
||||
Elastic recycle mirrors the verified design from the moshi-hosted path: the
|
||||
temporal ring KV masks the recycled row (plus the one LM "sacrifice tick"
|
||||
write), the staging row is wiped to initial tokens, and the system prompt
|
||||
(voice embeddings, silence spacer, persona tokens, silence) is replayed per-row
|
||||
while other slots keep conversing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import tarfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.experimental.fullduplex.personaplex.config import PersonaPlexConfig
|
||||
from vllm_omni.experimental.fullduplex.personaplex.policy import (
|
||||
AUDIO_INITIAL_TOKEN,
|
||||
AUDIO_SILENCE_FRAME_CNT,
|
||||
NON_TEXT_TOKEN_IDS,
|
||||
SILENCE_TOKENS,
|
||||
SINE_TOKENS,
|
||||
TEXT_INITIAL_TOKEN,
|
||||
TEXT_VOCAB_SIZE,
|
||||
ZERO_TEXT_TOKEN,
|
||||
PrefillStep,
|
||||
wrap_with_system_tags,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from numpy.typing import NDArray
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PersonaPlexEngine:
|
||||
"""Frame-lockstep PersonaPlex on native components only (no moshi).
|
||||
|
||||
One class serves both surfaces: the single-session ``FrameStepper`` protocol
|
||||
(``open_session`` / ``step``) and the batched slot API consumed by
|
||||
``serving/batched.py`` (``open_batch`` / ``prefill_steps`` / ``recycle_slot``
|
||||
/ ``voice_end`` / ``end_prefill`` / ``step_batch``).
|
||||
"""
|
||||
|
||||
def __init__(self, config: PersonaPlexConfig | None = None) -> None:
|
||||
self.config = config or PersonaPlexConfig()
|
||||
self.sample_rate = self.config.sample_rate
|
||||
self.frame_size = self.config.frame_size
|
||||
# Serializes the single-session FrameStepper surface (open_session/step)
|
||||
# across worker threads: a cancelled asyncio task cannot stop a running
|
||||
# engine call, so a racing open() must wait for the in-flight step.
|
||||
# The batched surface is serialized by BatchedSessionManager instead.
|
||||
self._fs_lock = threading.Lock()
|
||||
self._loaded = False
|
||||
self._opened = False
|
||||
self._tokenizer = None
|
||||
self._codec = None
|
||||
self._temporal = None
|
||||
self._emb = None
|
||||
self._dep = None
|
||||
self._voice_embeddings = None # [T, 1, 1, H]
|
||||
self._voice_cache = None # [1, K, CT]
|
||||
self._loaded_voice = None # name/path of the currently loaded voice
|
||||
# lockstep state (built at open time)
|
||||
self._cache = None # [B, K, CT] long
|
||||
self._provided = None # [B, K, CT] bool
|
||||
self._initial = None # [K] long
|
||||
self._delays = None # [K] long (python list)
|
||||
self._phys = 0
|
||||
self._local = None # [B] cpu long
|
||||
|
||||
# -- loading --------------------------------------------------------------
|
||||
|
||||
def load(self) -> PersonaPlexEngine:
|
||||
if self._loaded:
|
||||
return self
|
||||
import sentencepiece
|
||||
import torch
|
||||
from huggingface_hub import hf_hub_download
|
||||
from safetensors.torch import load_file
|
||||
|
||||
from vllm_omni.model_executor.models.personaplex.configuration_personaplex import (
|
||||
PersonaPlexConfig as _PPModelConfig,
|
||||
)
|
||||
from vllm_omni.model_executor.models.personaplex.personaplex_depformer import (
|
||||
PersonaPlexDepformer,
|
||||
)
|
||||
from vllm_omni.model_executor.models.personaplex.personaplex_embeddings import (
|
||||
PersonaPlexInputEmbeddings,
|
||||
)
|
||||
from vllm_omni.model_executor.models.personaplex.personaplex_mimi import (
|
||||
PersonaPlexMimiCodec,
|
||||
)
|
||||
from vllm_omni.model_executor.models.personaplex.personaplex_temporal import (
|
||||
PersonaPlexTemporalStreaming,
|
||||
)
|
||||
|
||||
cfg = self.config
|
||||
B = cfg.batch_size
|
||||
logger.info("PersonaPlex native: loading Mimi codec")
|
||||
self._codec = PersonaPlexMimiCodec(device=cfg.device)
|
||||
self._codec.streaming_init(B)
|
||||
|
||||
tok_path = hf_hub_download(cfg.hf_repo, "tokenizer_spm_32k_3.model")
|
||||
self._tokenizer = sentencepiece.SentencePieceProcessor(tok_path)
|
||||
|
||||
logger.info("PersonaPlex native: loading temporal + depformer + embeddings")
|
||||
sd = load_file(hf_hub_download(cfg.hf_repo, "model.safetensors"), device=cfg.device)
|
||||
dtype = torch.bfloat16
|
||||
self._temporal = PersonaPlexTemporalStreaming().to(cfg.device, dtype)
|
||||
self._temporal.load_weights(sd)
|
||||
self._temporal.eval()
|
||||
self._temporal.streaming_init(B)
|
||||
|
||||
ppcfg = _PPModelConfig()
|
||||
self._emb = PersonaPlexInputEmbeddings(ppcfg).to(cfg.device, dtype)
|
||||
self._emb.load_weights(sd)
|
||||
self._emb.eval()
|
||||
self._dep = PersonaPlexDepformer(ppcfg.depformer_config, temporal_hidden_size=4096, text_card=32000).to(
|
||||
cfg.device, dtype
|
||||
)
|
||||
self._dep.load_weights(sd)
|
||||
self._dep.eval()
|
||||
del sd
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
K = 17
|
||||
self._delays = [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1] # text, agent cb0..7, user cb0..7
|
||||
self._initial = torch.tensor(
|
||||
[TEXT_INITIAL_TOKEN] + [AUDIO_INITIAL_TOKEN] * 16, dtype=torch.long, device=cfg.device
|
||||
)
|
||||
ct = max(self._delays) + 3
|
||||
self._cache = torch.full((B, K, ct), AUDIO_INITIAL_TOKEN, dtype=torch.long, device=cfg.device)
|
||||
self._provided = torch.zeros((B, K, ct), dtype=torch.bool, device=cfg.device)
|
||||
self._local = torch.zeros(B, dtype=torch.long)
|
||||
self._sine = torch.tensor(SINE_TOKENS, dtype=torch.long, device=cfg.device)
|
||||
self._silence = torch.tensor(SILENCE_TOKENS, dtype=torch.long, device=cfg.device)
|
||||
|
||||
self._load_voice(cfg.voice_prompt)
|
||||
self._loaded = True
|
||||
return self
|
||||
|
||||
def _load_voice(self, voice: str) -> None:
|
||||
import torch
|
||||
|
||||
if voice == self._loaded_voice:
|
||||
return
|
||||
path = self._resolve_voice_prompt(voice)
|
||||
if not path.endswith(".pt"):
|
||||
raise ValueError(f"native stack needs a .pt voice-embedding bundle; got {path!r}")
|
||||
state = torch.load(path, map_location=self.config.device, weights_only=True)
|
||||
self._voice_embeddings = state["embeddings"].to(self.config.device)
|
||||
self._voice_cache = state["cache"].to(self.config.device)
|
||||
self._loaded_voice = voice
|
||||
|
||||
def _resolve_voice_prompt(self, voice: str) -> str:
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
if os.path.exists(voice):
|
||||
return voice
|
||||
tgz = Path(hf_hub_download(self.config.hf_repo, "voices.tgz"))
|
||||
vdir = tgz.parent / "voices"
|
||||
if not vdir.exists():
|
||||
with tarfile.open(tgz, "r:gz") as tar:
|
||||
tar.extractall(path=tgz.parent) # noqa: S202 - trusted first-party bundle
|
||||
cand = vdir / voice
|
||||
if not cand.exists():
|
||||
raise FileNotFoundError(f"voice prompt {voice!r} not found in voices.tgz")
|
||||
return str(cand)
|
||||
|
||||
# -- lockstep core ----------------------------------------------------------
|
||||
|
||||
def _reset_all_streaming(self) -> None:
|
||||
self._codec.reset_streaming()
|
||||
self._temporal.reset_streaming()
|
||||
self._cache.fill_(AUDIO_INITIAL_TOKEN)
|
||||
self._cache[:, 0, :] = TEXT_INITIAL_TOKEN
|
||||
self._provided.fill_(False)
|
||||
self._phys = 0
|
||||
self._local.zero_()
|
||||
|
||||
def _tick(
|
||||
self,
|
||||
user_codes, # [B, 8] long or None (prefill rows overridden separately)
|
||||
forced_moshi=None, # [B, 8] long (values used on force_mask rows)
|
||||
forced_text=None, # [B] long
|
||||
force_mask=None, # [B] bool (device)
|
||||
embed_override=None, # ([B, 1, H], [B] bool rows)
|
||||
):
|
||||
"""One lockstep step. Returns (ran, out[B,17] | None)."""
|
||||
import torch
|
||||
|
||||
B, K, CT = self._cache.shape
|
||||
o = self._phys
|
||||
lo = self._local
|
||||
|
||||
if user_codes is not None:
|
||||
for q in range(8):
|
||||
k = 9 + q
|
||||
wp = (o + self._delays[k]) % CT
|
||||
self._cache[:, k, wp] = user_codes[:, q]
|
||||
self._provided[:, k, wp] = True
|
||||
if forced_moshi is not None and force_mask is not None:
|
||||
for q in range(8):
|
||||
k = 1 + q
|
||||
wp = (o + self._delays[k]) % CT
|
||||
self._cache[force_mask, k, wp] = forced_moshi[force_mask, q]
|
||||
self._provided[force_mask, k, wp] = True
|
||||
if forced_text is not None and force_mask is not None:
|
||||
wp = (o + self._delays[0]) % CT
|
||||
self._cache[force_mask, 0, wp] = forced_text[force_mask]
|
||||
self._provided[force_mask, 0, wp] = True
|
||||
|
||||
for k, delay in enumerate(self._delays):
|
||||
warm = lo <= delay # [B] cpu bool
|
||||
if bool(warm.any()):
|
||||
wd = warm.to(self._cache.device)
|
||||
pos = o % CT
|
||||
self._cache[:, k, pos] = torch.where(wd, self._initial[k].expand(B), self._cache[:, k, pos])
|
||||
self._provided[:, k, pos] = self._provided[:, k, pos] | wd
|
||||
|
||||
if o == 0:
|
||||
# Genuine cold start: no prior physical frame to read as model input.
|
||||
self._cache[:, :, 0] = self._initial.view(1, K).expand(B, K)
|
||||
self._phys += 1
|
||||
self._local += 1
|
||||
return False, None
|
||||
|
||||
mip = (o - 1) % CT
|
||||
tp = o % CT
|
||||
input_ = self._cache[:, :, mip] # [B, K]
|
||||
target_ = self._cache[:, :, tp]
|
||||
provided_ = self._provided[:, :, tp]
|
||||
|
||||
emb = self._emb(input_.unsqueeze(-1)) # [B, 1, H]
|
||||
if embed_override is not None:
|
||||
ov, rows = embed_override
|
||||
emb = torch.where(rows.view(B, 1, 1), ov.to(emb.dtype), emb)
|
||||
hidden, text_logits = self._temporal.step(emb)
|
||||
|
||||
sampled_text = text_logits.float().view(B, -1).argmax(-1) # greedy
|
||||
next_text = torch.where(provided_[:, 0], target_[:, 0], sampled_text)
|
||||
audio = self._dep(next_text, hidden, audio_tokens=target_[:, 1:], audio_provided=provided_[:, 1:]) # [B, 16]
|
||||
|
||||
self._provided[:, :, mip] = False
|
||||
self._cache[:, 0, tp] = torch.where(~provided_[:, 0], sampled_text, self._cache[:, 0, tp])
|
||||
self._cache[:, 1:, tp] = torch.where(~provided_[:, 1:], audio, self._cache[:, 1:, tp])
|
||||
|
||||
max_delay = max(self._delays)
|
||||
valid = lo > max_delay
|
||||
if not bool(valid.any()):
|
||||
self._phys += 1
|
||||
self._local += 1
|
||||
return True, None
|
||||
|
||||
idx = torch.tensor(
|
||||
[(self._phys - max_delay + d) % CT for d in self._delays],
|
||||
device=self._cache.device,
|
||||
dtype=torch.long,
|
||||
)
|
||||
out = self._cache.gather(2, idx.view(1, K, 1).expand(B, K, 1)).squeeze(-1) # [B, K]
|
||||
self._last_valid = valid.clone()
|
||||
self._phys += 1
|
||||
self._local += 1
|
||||
return True, out
|
||||
|
||||
def _boot_prefill(self, persona: str | None) -> None:
|
||||
"""Batch-wide hybrid system prompt: voice -> cache restore -> silence ->
|
||||
persona -> silence (all rows identical)."""
|
||||
import torch
|
||||
|
||||
B = self.config.batch_size
|
||||
dev = self.config.device
|
||||
dummy_user = self._initial[9:].view(1, 8).expand(B, 8)
|
||||
dummy_moshi = self._initial[1:9].view(1, 8).expand(B, 8)
|
||||
zero_text = torch.full((B,), ZERO_TEXT_TOKEN, dtype=torch.long, device=dev)
|
||||
all_rows = torch.ones(B, dtype=torch.bool, device=dev)
|
||||
|
||||
for e in self._voice_embeddings:
|
||||
ov = e.view(1, 1, -1).expand(B, 1, -1)
|
||||
while True:
|
||||
ran, _ = self._tick(dummy_user, dummy_moshi, zero_text, all_rows, embed_override=(ov, all_rows))
|
||||
if ran:
|
||||
break
|
||||
self._cache.copy_(self._voice_cache.expand_as(self._cache))
|
||||
|
||||
sine = self._sine.view(1, 8).expand(B, 8)
|
||||
silence = self._silence.view(1, 8).expand(B, 8)
|
||||
text = persona if persona is not None else self.config.persona
|
||||
toks = self._tokenizer.encode(wrap_with_system_tags(text)) if text else []
|
||||
for phase_toks in (
|
||||
[ZERO_TEXT_TOKEN] * AUDIO_SILENCE_FRAME_CNT,
|
||||
toks,
|
||||
[ZERO_TEXT_TOKEN] * AUDIO_SILENCE_FRAME_CNT,
|
||||
):
|
||||
for t in phase_toks:
|
||||
tt = torch.full((B,), int(t), dtype=torch.long, device=dev)
|
||||
self._tick(sine, silence, tt, all_rows)
|
||||
self._codec.reset_streaming()
|
||||
|
||||
# -- batched surface (mirrors the previous engine's API) --------------------
|
||||
|
||||
def open_batch(self) -> None:
|
||||
if not self._loaded:
|
||||
self.load()
|
||||
self._reset_all_streaming()
|
||||
self._boot_prefill(None)
|
||||
self._opened = True
|
||||
logger.info("PersonaPlex native: %d slots prefilled", self.config.batch_size)
|
||||
|
||||
def prefill_steps(self, persona: str | None = None) -> list[PrefillStep]:
|
||||
zero = self._silence
|
||||
silence = [
|
||||
PrefillStep("tokens", moshi_tokens=zero, text_token=ZERO_TEXT_TOKEN, user_sine=True)
|
||||
for _ in range(AUDIO_SILENCE_FRAME_CNT)
|
||||
]
|
||||
steps: list[PrefillStep] = [PrefillStep("sacrifice")]
|
||||
for e in self._voice_embeddings:
|
||||
steps.append(PrefillStep("voice", embedding=e.view(1, 1, -1)))
|
||||
steps.append(PrefillStep("voice_end"))
|
||||
steps.extend(silence)
|
||||
text = persona if persona is not None else self.config.persona
|
||||
if text:
|
||||
for tok in self._tokenizer.encode(wrap_with_system_tags(text)):
|
||||
steps.append(PrefillStep("tokens", moshi_tokens=zero, text_token=int(tok), user_sine=True))
|
||||
steps.extend(silence)
|
||||
return steps
|
||||
|
||||
def recycle_slot(self, b: int) -> None:
|
||||
self._temporal.reset_slot(b)
|
||||
self._temporal.bump_slot_start(b) # LM sacrifice-tick semantics
|
||||
self._local[b] = 0
|
||||
self._cache[b] = self._initial.view(-1, 1).expand(-1, self._cache.shape[2])
|
||||
self._provided[b] = False
|
||||
|
||||
def voice_end(self, b: int) -> None:
|
||||
import torch
|
||||
|
||||
ct = self._cache.shape[2]
|
||||
shift = int((self._phys - int(self._local[b])) % ct)
|
||||
self._cache[b] = torch.roll(self._voice_cache[0], shifts=shift, dims=-1)
|
||||
|
||||
def end_prefill(self, b: int) -> None:
|
||||
self._codec.reset_slot(b)
|
||||
|
||||
def step_batch(self, user_pcm: NDArray[np.float32], prefill: dict[int, PrefillStep] | None = None):
|
||||
import torch
|
||||
|
||||
if not self._opened:
|
||||
raise RuntimeError("open_batch() must be called before step_batch()")
|
||||
cfg = self.config
|
||||
B = cfg.batch_size
|
||||
pcm = np.ascontiguousarray(user_pcm, dtype=np.float32).reshape(B, self.frame_size)
|
||||
codes = self._codec.encode_frame(torch.from_numpy(pcm).to(cfg.device)).long()
|
||||
return self._step_from_codes(codes, prefill)
|
||||
|
||||
def step_codes(self, user_codes, prefill: dict[int, PrefillStep] | None = None):
|
||||
"""Drive the lockstep loop from precomputed user codes (golden replays).
|
||||
|
||||
Kept public deliberately: bit-exact golden-replay verification must
|
||||
bypass the Mimi encoder, whose streaming conv state makes encoded
|
||||
codes run-order dependent (valid but not reproducible token-for-token).
|
||||
"""
|
||||
return self._step_from_codes(user_codes.to(self.config.device).long(), prefill)
|
||||
|
||||
def _step_from_codes(self, codes, prefill):
|
||||
import torch
|
||||
|
||||
from vllm_omni.experimental.fullduplex.personaplex.engine import FrameOutput
|
||||
|
||||
cfg = self.config
|
||||
B = cfg.batch_size
|
||||
dev = cfg.device
|
||||
forced_moshi = forced_text = force_mask = embed_override = None
|
||||
if prefill:
|
||||
force_mask = torch.zeros(B, dtype=torch.bool, device=dev)
|
||||
embed_rows = torch.zeros(B, dtype=torch.bool, device=dev)
|
||||
emb_full = None
|
||||
forced_moshi = self._initial[1:9].view(1, 8).expand(B, 8).clone()
|
||||
forced_text = torch.full((B,), ZERO_TEXT_TOKEN, dtype=torch.long, device=dev)
|
||||
for b, stp in prefill.items():
|
||||
if stp.kind == "voice_end":
|
||||
raise ValueError("voice_end is not a tick; call engine.voice_end(b)")
|
||||
codes[b] = self._sine if stp.user_sine else self._initial[9:]
|
||||
if stp.kind == "voice":
|
||||
embed_rows[b] = True
|
||||
if emb_full is None:
|
||||
emb_full = torch.zeros(B, 1, stp.embedding.shape[-1], dtype=stp.embedding.dtype, device=dev)
|
||||
emb_full[b] = stp.embedding[0]
|
||||
force_mask[b] = True # dummy staging like step_embeddings
|
||||
else:
|
||||
force_mask[b] = True
|
||||
if stp.kind == "tokens":
|
||||
forced_moshi[b] = stp.moshi_tokens
|
||||
forced_text[b] = int(stp.text_token)
|
||||
if bool(embed_rows.any()):
|
||||
embed_override = (emb_full, embed_rows)
|
||||
|
||||
ran, out = self._tick(codes, forced_moshi, forced_text, force_mask, embed_override)
|
||||
self.last_out_tokens = None if out is None else out.detach().cpu()
|
||||
if not ran or out is None:
|
||||
return [None] * B
|
||||
|
||||
valid = self._last_valid # [B] cpu bool
|
||||
emit = [bool(valid[b]) and (not prefill or b not in prefill) for b in range(B)]
|
||||
audio_tokens = out[:, 1:9].clone()
|
||||
if not all(emit):
|
||||
hide = torch.tensor([not e for e in emit], device=dev).view(B, 1)
|
||||
audio_tokens = torch.where(hide, self._silence.view(1, 8).expand(B, 8), audio_tokens)
|
||||
pcm_out = self._codec.decode_frame(audio_tokens) # [B, frame]
|
||||
outs = []
|
||||
for b in range(B):
|
||||
if not emit[b]:
|
||||
outs.append(None)
|
||||
continue
|
||||
audio = pcm_out[b].float().detach().cpu().numpy().astype(np.float32)
|
||||
outs.append(FrameOutput(audio=audio, text=self._decode_text(int(out[b, 0].item()))))
|
||||
return outs
|
||||
|
||||
# -- single-session FrameStepper surface -------------------------------------
|
||||
|
||||
def open_session(self, voice_prompt: str | None = None, persona: str | None = None) -> None:
|
||||
with self._fs_lock:
|
||||
if not self._loaded:
|
||||
self.load()
|
||||
# Always resolve a voice: falling back to the configured default here
|
||||
# keeps a previous session's custom voice from leaking into this one.
|
||||
self._load_voice(voice_prompt or self.config.voice_prompt)
|
||||
self._reset_all_streaming()
|
||||
self._boot_prefill(persona)
|
||||
self._opened = True
|
||||
|
||||
def step(self, user_pcm: NDArray[np.float32]):
|
||||
with self._fs_lock:
|
||||
pcm = np.ascontiguousarray(user_pcm, dtype=np.float32).reshape(-1)
|
||||
if pcm.shape[0] != self.frame_size:
|
||||
raise ValueError(f"expected {self.frame_size} samples per frame, got {pcm.shape[0]}")
|
||||
outs = self.step_batch(pcm.reshape(1, -1))
|
||||
from vllm_omni.experimental.fullduplex.personaplex.engine import FrameOutput
|
||||
|
||||
return outs[0] if outs[0] is not None else FrameOutput(audio=None, text=None)
|
||||
|
||||
def _decode_text(self, token_id: int) -> str | None:
|
||||
if token_id in NON_TEXT_TOKEN_IDS or token_id >= TEXT_VOCAB_SIZE:
|
||||
return None
|
||||
return self._tokenizer.id_to_piece(token_id).replace("▁", " ")
|
||||
@@ -0,0 +1,129 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from typing import Any
|
||||
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.experimental.fullduplex.engine.duplex_runtime import (
|
||||
DuplexAppendPlan,
|
||||
DuplexInputMode,
|
||||
DuplexOutputDecision,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.engine.messages import DuplexFence
|
||||
|
||||
_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,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""PersonaPlex full-duplex WebSocket serving (PCM in / PCM + text out)."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
__all__ = ["create_app", "main"]
|
||||
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
if name not in __all__:
|
||||
raise AttributeError(name)
|
||||
from vllm_omni.experimental.fullduplex.personaplex.serving import server
|
||||
|
||||
return getattr(server, name)
|
||||
@@ -0,0 +1,184 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Slot manager + lockstep tick loop for batched PersonaPlex serving.
|
||||
|
||||
Pure-python orchestration over a :class:`PersonaPlexEngine`-shaped object
|
||||
(injected, so tests run GPU-free with a stub): a fixed table of B conversation
|
||||
slots, one shared wall-clock 80 ms tick that advances every non-idle slot, and
|
||||
per-slot recycle prefill for new callers.
|
||||
|
||||
Threading model: ``tick()`` runs on a dedicated stepping thread (the engine call
|
||||
is synchronous CUDA work); ``acquire``/``release``/``feed`` are called from the
|
||||
asyncio thread. All slot state is guarded by one lock; per-frame output is
|
||||
handed off via each slot's ``on_output`` callback (called on the stepping
|
||||
thread -- the server bridges to asyncio with ``call_soon_threadsafe``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SlotPhase(enum.Enum):
|
||||
IDLE = "idle"
|
||||
PREFILL = "prefill"
|
||||
LIVE = "live"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Slot:
|
||||
index: int
|
||||
phase: SlotPhase = SlotPhase.IDLE
|
||||
used: bool = False # a used slot must be recycled before reuse
|
||||
needs_recycle: bool = False # engine.reset executed by the tick thread only
|
||||
epoch: int = 0
|
||||
pending: np.ndarray = field(default_factory=lambda: np.zeros(0, dtype=np.float32))
|
||||
inq: deque = field(default_factory=deque)
|
||||
prefill: deque = field(default_factory=deque)
|
||||
on_output: Callable[[Any], None] | None = None # FrameOutput, stepping thread
|
||||
on_ready: Callable[[], None] | None = None # prefill finished, stepping thread
|
||||
|
||||
|
||||
class BatchedSessionManager:
|
||||
"""Own the slot table and drive one engine tick per call to :meth:`tick`."""
|
||||
|
||||
def __init__(self, engine, max_buffered_frames: int = 25) -> None:
|
||||
self.engine = engine
|
||||
self.frame_size = engine.frame_size
|
||||
self.batch_size = engine.config.batch_size
|
||||
self.max_buffered_frames = max_buffered_frames
|
||||
self.slots = [Slot(index=i) for i in range(self.batch_size)]
|
||||
self.lock = threading.Lock()
|
||||
# step_batch advances EVERY row each tick (lockstep), so once any tick has
|
||||
# run, "pristine" idle rows have silently drifted from their boot prefill
|
||||
# and must be recycled before a client may join them.
|
||||
self._ticked = False
|
||||
|
||||
# -- connection side (asyncio thread) ------------------------------------
|
||||
|
||||
def acquire(self, persona: str | None = None) -> tuple[Slot, bool] | None:
|
||||
"""Claim an idle slot. Returns ``(slot, ready_now)`` or ``None`` if full.
|
||||
|
||||
A pristine slot (never used since boot, and claimed before the first
|
||||
engine tick) still carries the default voice + persona from
|
||||
``open_batch`` and is live immediately when no custom persona is
|
||||
requested. Otherwise the slot is recycled and its system prompt
|
||||
replayed over the next ticks (``ready_now == False``) -- including
|
||||
pristine rows after ticking has started, because lockstep stepping
|
||||
advances every row whether or not a client is attached.
|
||||
"""
|
||||
with self.lock:
|
||||
slot = next((s for s in self.slots if s.phase is SlotPhase.IDLE), None)
|
||||
if slot is None:
|
||||
return None
|
||||
slot.epoch += 1
|
||||
slot.pending = np.zeros(0, dtype=np.float32)
|
||||
slot.inq.clear()
|
||||
slot.prefill.clear()
|
||||
if not slot.used and persona is None and not self._ticked:
|
||||
slot.phase = SlotPhase.LIVE
|
||||
slot.used = True
|
||||
return slot, True
|
||||
# The engine reset itself must run BETWEEN engine steps, i.e. on the
|
||||
# stepping thread -- only mark it here; tick() executes it.
|
||||
slot.prefill.extend(self.engine.prefill_steps(persona))
|
||||
slot.needs_recycle = True
|
||||
slot.phase = SlotPhase.PREFILL
|
||||
slot.used = True
|
||||
return slot, False
|
||||
|
||||
def release(self, slot: Slot) -> None:
|
||||
with self.lock:
|
||||
slot.phase = SlotPhase.IDLE
|
||||
slot.epoch += 1
|
||||
slot.on_output = None
|
||||
slot.on_ready = None
|
||||
slot.inq.clear()
|
||||
slot.prefill.clear()
|
||||
slot.pending = np.zeros(0, dtype=np.float32)
|
||||
|
||||
def feed(self, slot: Slot, pcm: np.ndarray, epoch: int) -> None:
|
||||
"""Buffer incoming PCM and carve it into exact engine frames."""
|
||||
with self.lock:
|
||||
if slot.epoch != epoch or slot.phase is SlotPhase.IDLE:
|
||||
return
|
||||
samples = np.ascontiguousarray(pcm, dtype=np.float32).reshape(-1)
|
||||
slot.pending = np.concatenate([slot.pending, samples]) if slot.pending.size else samples
|
||||
n = self.frame_size
|
||||
while slot.pending.shape[0] >= n:
|
||||
frame, slot.pending = slot.pending[:n], slot.pending[n:]
|
||||
slot.inq.append(frame)
|
||||
while len(slot.inq) > self.max_buffered_frames:
|
||||
slot.inq.popleft() # realtime: drop the oldest backlog
|
||||
|
||||
# -- stepping side (dedicated thread) ------------------------------------
|
||||
|
||||
def tick(self) -> bool:
|
||||
"""Advance every non-idle slot one frame. Returns False when all idle."""
|
||||
with self.lock:
|
||||
if all(s.phase is SlotPhase.IDLE for s in self.slots):
|
||||
return False
|
||||
self._ticked = True
|
||||
pcm = np.zeros((self.batch_size, self.frame_size), dtype=np.float32)
|
||||
prefill: dict[int, Any] = {}
|
||||
emitters: list[tuple[Slot, int]] = []
|
||||
for slot in self.slots:
|
||||
if slot.phase is SlotPhase.LIVE:
|
||||
if slot.inq:
|
||||
pcm[slot.index] = slot.inq.popleft()
|
||||
emitters.append((slot, slot.epoch))
|
||||
elif slot.phase is SlotPhase.PREFILL:
|
||||
if slot.needs_recycle:
|
||||
self.engine.recycle_slot(slot.index)
|
||||
slot.needs_recycle = False
|
||||
while slot.prefill and slot.prefill[0].kind == "voice_end":
|
||||
self.engine.voice_end(slot.index)
|
||||
slot.prefill.popleft()
|
||||
if slot.prefill:
|
||||
prefill[slot.index] = slot.prefill.popleft()
|
||||
else:
|
||||
self.engine.end_prefill(slot.index)
|
||||
slot.phase = SlotPhase.LIVE
|
||||
emitters.append((slot, slot.epoch))
|
||||
if slot.on_ready is not None:
|
||||
slot.on_ready()
|
||||
|
||||
outs = self.engine.step_batch(pcm, prefill or None)
|
||||
|
||||
with self.lock:
|
||||
for slot, epoch in emitters:
|
||||
out = outs[slot.index]
|
||||
if out is None or slot.epoch != epoch or slot.on_output is None:
|
||||
continue
|
||||
slot.on_output(out)
|
||||
return True
|
||||
|
||||
def run_forever(self, stop: threading.Event, frame_seconds: float = 0.08) -> None:
|
||||
"""Wall-clock-paced stepping loop (run on a dedicated thread)."""
|
||||
next_t = time.monotonic()
|
||||
while not stop.is_set():
|
||||
did = self.tick()
|
||||
if not did:
|
||||
time.sleep(frame_seconds / 4)
|
||||
next_t = time.monotonic()
|
||||
continue
|
||||
next_t += frame_seconds
|
||||
delay = next_t - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
elif delay < -1.0:
|
||||
# Fell far behind realtime (e.g. B too large for the GPU); resync
|
||||
# rather than bursting to catch up.
|
||||
logger.warning("batched tick loop %.1fs behind realtime; resyncing", -delay)
|
||||
next_t = time.monotonic()
|
||||
@@ -0,0 +1,539 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""PersonaPlex full-duplex server, compatible with the OFFICIAL Moshi web client.
|
||||
|
||||
Serves the official PersonaPlex web UI (``dist.tgz`` from ``nvidia/personaplex-7b-v1``,
|
||||
the same bundle ``moshi.server`` downloads) and implements its WebSocket protocol at
|
||||
``/api/chat`` -- but driven by our native-component engine instead of moshi's server.
|
||||
|
||||
Built on **aiohttp**, mirroring ``moshi.server`` exactly: aiohttp writes+drains each
|
||||
WebSocket frame promptly, whereas uvicorn's ``websockets`` backend coalesces many small
|
||||
(~80 ms Opus) frames into a send buffer, which makes browser playback choppy even when
|
||||
the engine is real-time. aiohttp ships as a moshi dependency, so this adds nothing new.
|
||||
|
||||
Moshi protocol (binary WS messages, first byte = tag):
|
||||
server -> client ``\\x00`` handshake (ready, after system prompts)
|
||||
client -> server ``\\x01`` + opus bytes mic audio (Opus @ 24kHz)
|
||||
server -> client ``\\x01`` + opus bytes agent audio (Opus @ 24kHz)
|
||||
server -> client ``\\x02`` + utf8 inner-monologue text
|
||||
Query params on connect: ``text_prompt`` (persona), ``voice_prompt`` (voice file).
|
||||
|
||||
Run (auto-downloads the official UI; open http://<host>:8124/):
|
||||
HF_TOKEN=... CUDA_VISIBLE_DEVICES=0 python -m \\
|
||||
vllm_omni.experimental.fullduplex.personaplex.serving.server --port 8124
|
||||
|
||||
A raw-PCM endpoint (``/v1/audio/duplex``, JSON ``open`` + float32 frames) remains for
|
||||
tooling/tests that do not want an Opus dependency.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import contextlib
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import tarfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import sphn
|
||||
from aiohttp import WSMsgType, web
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
from vllm_omni.experimental.fullduplex.personaplex.config import PersonaPlexConfig
|
||||
from vllm_omni.experimental.fullduplex.personaplex.engine import PersonaPlexEngine
|
||||
from vllm_omni.experimental.fullduplex.personaplex.serving.batched import BatchedSessionManager
|
||||
from vllm_omni.experimental.fullduplex.personaplex.session import (
|
||||
PersonaPlexServingSessionState,
|
||||
PersonaPlexSession,
|
||||
offer_realtime,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_HF_REPO = "nvidia/personaplex-7b-v1"
|
||||
|
||||
|
||||
def _opus_encode(writer: sphn.OpusStreamWriter, pcm: np.ndarray) -> bytes:
|
||||
"""Encode one PCM frame to Opus bytes, across sphn API versions.
|
||||
|
||||
sphn 0.2.x returns the encoded bytes straight from ``append_pcm``; the older
|
||||
0.1.x buffers and requires a ``read_bytes`` drain. Handle both.
|
||||
"""
|
||||
out = writer.append_pcm(np.ascontiguousarray(pcm, dtype=np.float32))
|
||||
if out is None and hasattr(writer, "read_bytes"):
|
||||
out = writer.read_bytes()
|
||||
return out or b""
|
||||
|
||||
|
||||
def _opus_decode(reader: sphn.OpusStreamReader, data: bytes) -> np.ndarray | None:
|
||||
"""Decode Opus bytes to PCM, across sphn API versions (see ``_opus_encode``)."""
|
||||
out = reader.append_bytes(data)
|
||||
if out is None and hasattr(reader, "read_pcm"):
|
||||
out = reader.read_pcm()
|
||||
if out is None or getattr(out, "shape", (0,))[-1] == 0:
|
||||
return None
|
||||
return np.asarray(out, dtype=np.float32)
|
||||
|
||||
|
||||
def _official_web_dir() -> Path | None:
|
||||
"""Download + extract the official PersonaPlex web client (dist.tgz)."""
|
||||
try:
|
||||
tgz = Path(hf_hub_download(_HF_REPO, "dist.tgz"))
|
||||
dist = tgz.parent / "dist"
|
||||
if not dist.exists():
|
||||
with tarfile.open(tgz, "r:gz") as tar:
|
||||
tar.extractall(path=tgz.parent) # noqa: S202 - trusted first-party bundle
|
||||
return dist if dist.exists() else None
|
||||
except Exception as exc: # network / auth / layout
|
||||
logger.warning("official web client unavailable (%s); / will return an error note", exc)
|
||||
return None
|
||||
|
||||
|
||||
class DuplexServer:
|
||||
"""Owns the loaded engine; serves one duplex conversation at a time.
|
||||
|
||||
A capacity-one lease covers the entire WebSocket lifetime on BOTH endpoints:
|
||||
the engine is a single shared streaming state, so a second concurrent
|
||||
connection would reset and corrupt the live conversation. Extra connections
|
||||
are rejected with 1013 (try again later). Engine work (``open``/``feed``,
|
||||
synchronous CUDA) runs on a worker thread so the event loop stays free for
|
||||
WebSocket traffic and close handling.
|
||||
"""
|
||||
|
||||
def __init__(self, config: PersonaPlexConfig) -> None:
|
||||
self.config = config
|
||||
self.engine = PersonaPlexEngine(config)
|
||||
self._active = False # capacity-one session lease (event-loop confined)
|
||||
self._lease_release_tasks: set[asyncio.Task] = set()
|
||||
|
||||
def load(self) -> None:
|
||||
self.engine.load()
|
||||
|
||||
async def _lease(self, ws: web.WebSocketResponse) -> bool:
|
||||
"""Try to claim the single-session lease; reject the connection if held."""
|
||||
if self._active:
|
||||
await ws.close(code=1013, message=b"another conversation is active")
|
||||
return False
|
||||
self._active = True
|
||||
return True
|
||||
|
||||
async def _engine_call(self, state: PersonaPlexServingSessionState, fn, *args, **kwargs):
|
||||
"""Run one synchronous engine call on a worker thread, tracked for drain.
|
||||
|
||||
Cancelling the awaiting task does NOT stop the worker thread, and it
|
||||
marks the asyncio wrapper future cancelled (``done()``) even while the
|
||||
thread keeps running, so the future itself cannot signal completion.
|
||||
The worker instead sets a plain ``threading.Event`` when the call truly
|
||||
finishes; :meth:`_drain_inflight` waits on that event before the lease
|
||||
is released. Without this, a fast reconnect could acquire the lease and
|
||||
call ``open()`` while the previous connection's final ``step()`` is
|
||||
still mutating the shared engine on its thread.
|
||||
"""
|
||||
call = functools.partial(fn, *args, **kwargs)
|
||||
finished = threading.Event()
|
||||
|
||||
def run_and_signal():
|
||||
try:
|
||||
return call()
|
||||
finally:
|
||||
finished.set()
|
||||
|
||||
state.inflight = finished
|
||||
result = await asyncio.get_running_loop().run_in_executor(None, run_and_signal)
|
||||
state.inflight = None # on cancellation, the event stays referenced for drain
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
async def _drain_inflight(state: PersonaPlexServingSessionState, timeout: float = 5.0) -> bool:
|
||||
"""Wait out any engine call still running on a worker thread."""
|
||||
finished = state.inflight
|
||||
if finished is None or finished.is_set():
|
||||
return True
|
||||
return bool(await asyncio.to_thread(finished.wait, timeout))
|
||||
|
||||
async def _release_lease_when_finished(self, state: PersonaPlexServingSessionState) -> None:
|
||||
finished = state.inflight
|
||||
if finished is not None and not finished.is_set():
|
||||
await asyncio.to_thread(finished.wait)
|
||||
self._active = False
|
||||
|
||||
async def _release_lease_after_drain(
|
||||
self,
|
||||
state: PersonaPlexServingSessionState,
|
||||
*,
|
||||
timeout: float = 5.0,
|
||||
) -> bool:
|
||||
"""Release now when drained, otherwise retain the lease until completion."""
|
||||
if await self._drain_inflight(state, timeout):
|
||||
self._active = False
|
||||
return True
|
||||
|
||||
logger.error(
|
||||
"PersonaPlex engine cleanup exceeded %.1fs; retaining the session lease until the worker thread finishes",
|
||||
timeout,
|
||||
)
|
||||
task = asyncio.create_task(self._release_lease_when_finished(state))
|
||||
self._lease_release_tasks.add(task)
|
||||
task.add_done_callback(self._lease_release_tasks.discard)
|
||||
return False
|
||||
|
||||
# ---- official Moshi protocol (Opus over aiohttp WS) ---------------------
|
||||
|
||||
async def handle_chat(self, request: web.Request) -> web.WebSocketResponse:
|
||||
ws = web.WebSocketResponse()
|
||||
await ws.prepare(request)
|
||||
if not await self._lease(ws):
|
||||
return ws
|
||||
state = PersonaPlexServingSessionState()
|
||||
try:
|
||||
persona = (request.query.get("text_prompt") or "").strip() or None
|
||||
voice = (request.query.get("voice_prompt") or "").strip() or None
|
||||
sr = self.engine.sample_rate
|
||||
session = PersonaPlexSession(self.engine, self.config)
|
||||
# System-prompt prefill is seconds of GPU work; keep it off the loop.
|
||||
await self._engine_call(state, session.open, voice_prompt=voice, persona=persona)
|
||||
|
||||
reader = sphn.OpusStreamReader(sr)
|
||||
writer = sphn.OpusStreamWriter(sr)
|
||||
await ws.send_bytes(b"\x00") # ready handshake
|
||||
|
||||
async def recv_loop() -> None:
|
||||
try:
|
||||
async for msg in ws:
|
||||
if msg.type == WSMsgType.BINARY:
|
||||
data = msg.data
|
||||
if data and data[0] == 1:
|
||||
pcm = _opus_decode(reader, data[1:])
|
||||
if pcm is not None:
|
||||
offer_realtime(state.pcm_queue, pcm)
|
||||
elif msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.ERROR):
|
||||
break
|
||||
finally:
|
||||
state.closed = True
|
||||
|
||||
async def proc_loop() -> None:
|
||||
# Drain decoded PCM and step the model, streaming agent Opus + text
|
||||
# out. The synchronous engine step runs on a worker thread.
|
||||
while not state.closed:
|
||||
try:
|
||||
pcm = await asyncio.wait_for(state.pcm_queue.get(), timeout=0.25)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
for frame_out in await self._engine_call(state, session.feed, pcm):
|
||||
if frame_out.audio is not None:
|
||||
opus = _opus_encode(writer, frame_out.audio)
|
||||
if opus:
|
||||
await ws.send_bytes(b"\x01" + opus)
|
||||
if frame_out.text:
|
||||
await ws.send_bytes(b"\x02" + frame_out.text.encode("utf8"))
|
||||
|
||||
tasks = [asyncio.create_task(recv_loop()), asyncio.create_task(proc_loop())]
|
||||
try:
|
||||
_, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
for t in pending:
|
||||
t.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await t
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
await ws.close()
|
||||
finally:
|
||||
# A cancelled feed/open may still be running on its worker thread;
|
||||
# wait it out BEFORE freeing the lease, or a fast reconnect races
|
||||
# the shared engine (CUDA illegal access / cross-session bleed).
|
||||
await self._release_lease_after_drain(state)
|
||||
return ws
|
||||
|
||||
# ---- simple raw-PCM protocol (no Opus, for tests) ----------------------
|
||||
|
||||
async def handle_raw(self, request: web.Request) -> web.WebSocketResponse:
|
||||
ws = web.WebSocketResponse()
|
||||
await ws.prepare(request)
|
||||
if not await self._lease(ws):
|
||||
return ws
|
||||
session = PersonaPlexSession(self.engine, self.config)
|
||||
state = PersonaPlexServingSessionState()
|
||||
opened = False
|
||||
try:
|
||||
async for msg in ws:
|
||||
if msg.type == WSMsgType.TEXT:
|
||||
req = json.loads(msg.data)
|
||||
if req.get("type") == "open":
|
||||
await self._engine_call(
|
||||
state, session.open, voice_prompt=req.get("voice"), persona=req.get("persona")
|
||||
)
|
||||
opened = True
|
||||
await ws.send_json({"type": "ready"})
|
||||
elif req.get("type") == "close":
|
||||
if opened:
|
||||
await self._emit(ws, await self._engine_call(state, session.flush))
|
||||
await ws.send_json({"type": "done"})
|
||||
break
|
||||
elif msg.type == WSMsgType.BINARY:
|
||||
if not opened:
|
||||
await self._engine_call(state, session.open)
|
||||
opened = True
|
||||
pcm = np.frombuffer(msg.data, dtype=np.float32)
|
||||
await self._emit(ws, await self._engine_call(state, session.feed, pcm))
|
||||
elif msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.ERROR):
|
||||
break
|
||||
finally:
|
||||
# Same as handle_chat: wait out any worker-thread engine call
|
||||
# before freeing the lease (see _engine_call).
|
||||
await self._release_lease_after_drain(state)
|
||||
with contextlib.suppress(Exception):
|
||||
await ws.close()
|
||||
return ws
|
||||
|
||||
@staticmethod
|
||||
async def _emit(ws: web.WebSocketResponse, outputs: list) -> None:
|
||||
for frame_out in outputs:
|
||||
if frame_out.audio is not None:
|
||||
await ws.send_bytes(np.ascontiguousarray(frame_out.audio, dtype=np.float32).tobytes())
|
||||
if frame_out.text:
|
||||
await ws.send_json({"type": "text", "text": frame_out.text})
|
||||
|
||||
|
||||
class BatchedDuplexServer:
|
||||
"""Serve ``batch_size`` concurrent duplex conversations on one engine.
|
||||
|
||||
Same wire protocols as :class:`DuplexServer`; each connection claims a slot
|
||||
from the shared :class:`BatchedSessionManager`, whose stepping thread ticks
|
||||
all live slots in lockstep at 12.5 Hz wall clock. A connection with a custom
|
||||
``text_prompt`` (or reusing a previously used slot) waits while the slot's
|
||||
system prompt is replayed per-row (voice embeddings + persona), then gets the
|
||||
ready handshake. Per-connection custom voices are not supported in batched
|
||||
mode (fixed default voice; ``voice_prompt`` is ignored with a warning).
|
||||
"""
|
||||
|
||||
def __init__(self, config: PersonaPlexConfig) -> None:
|
||||
self.config = config
|
||||
self.engine = PersonaPlexEngine(config)
|
||||
self.manager: BatchedSessionManager | None = None
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
def load(self) -> None:
|
||||
self.engine.load()
|
||||
self.engine.open_batch()
|
||||
self.manager = BatchedSessionManager(self.engine)
|
||||
self._thread = threading.Thread(
|
||||
target=self.manager.run_forever, args=(self._stop,), daemon=True, name="pplex-tick"
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self._stop.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=2.0)
|
||||
|
||||
async def _acquire(self, ws: web.WebSocketResponse, persona: str | None):
|
||||
"""Claim a slot and wait until it is live.
|
||||
|
||||
Returns ``PersonaPlexServingSessionState`` (slot + bounded output queue)
|
||||
or ``None`` when the server is full. Exception-safe: if this coroutine
|
||||
is cancelled (client gone mid-prefill) or the wait fails, the slot is
|
||||
released instead of leaking in the PREFILL/LIVE phase.
|
||||
"""
|
||||
acquired = self.manager.acquire(persona=persona)
|
||||
if acquired is None:
|
||||
await ws.close(code=1013, message=b"all conversation slots busy")
|
||||
return None
|
||||
slot, ready_now = acquired
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
state = PersonaPlexServingSessionState(slot=slot, epoch=slot.epoch)
|
||||
ready = asyncio.Event()
|
||||
with self.manager.lock:
|
||||
# Bounded handoff: the tick thread produces one frame per 80 ms;
|
||||
# a client that stops reading gets drop-oldest, not unbounded RAM.
|
||||
slot.on_output = lambda frame_out: loop.call_soon_threadsafe(offer_realtime, state.out_queue, frame_out)
|
||||
if ready_now:
|
||||
ready.set()
|
||||
else:
|
||||
slot.on_ready = lambda: loop.call_soon_threadsafe(ready.set)
|
||||
await ready.wait()
|
||||
except BaseException:
|
||||
self.manager.release(slot)
|
||||
raise
|
||||
return state
|
||||
|
||||
async def handle_chat(self, request: web.Request) -> web.WebSocketResponse:
|
||||
ws = web.WebSocketResponse()
|
||||
await ws.prepare(request)
|
||||
persona = (request.query.get("text_prompt") or "").strip() or None
|
||||
if (request.query.get("voice_prompt") or "").strip():
|
||||
logger.warning("batched mode ignores per-connection voice_prompt (fixed default voice)")
|
||||
state = await self._acquire(ws, persona)
|
||||
if state is None:
|
||||
return ws
|
||||
try:
|
||||
sr = self.engine.sample_rate
|
||||
reader = sphn.OpusStreamReader(sr)
|
||||
writer = sphn.OpusStreamWriter(sr)
|
||||
await ws.send_bytes(b"\x00") # ready handshake
|
||||
|
||||
async def recv_loop() -> None:
|
||||
try:
|
||||
async for msg in ws:
|
||||
if msg.type == WSMsgType.BINARY:
|
||||
data = msg.data
|
||||
if data and data[0] == 1:
|
||||
pcm = _opus_decode(reader, data[1:])
|
||||
if pcm is not None:
|
||||
self.manager.feed(state.slot, pcm, state.epoch)
|
||||
elif msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.ERROR):
|
||||
break
|
||||
finally:
|
||||
state.closed = True
|
||||
|
||||
async def out_loop() -> None:
|
||||
while not state.closed:
|
||||
try:
|
||||
frame_out = await asyncio.wait_for(state.out_queue.get(), timeout=0.25)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
if frame_out.audio is not None:
|
||||
msg = _opus_encode(writer, frame_out.audio)
|
||||
if msg:
|
||||
await ws.send_bytes(b"\x01" + msg)
|
||||
if frame_out.text:
|
||||
await ws.send_bytes(b"\x02" + frame_out.text.encode("utf8"))
|
||||
|
||||
tasks = [asyncio.create_task(recv_loop()), asyncio.create_task(out_loop())]
|
||||
_, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
for t in pending:
|
||||
t.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await t
|
||||
finally:
|
||||
self.manager.release(state.slot)
|
||||
with contextlib.suppress(Exception):
|
||||
await ws.close()
|
||||
return ws
|
||||
|
||||
async def handle_raw(self, request: web.Request) -> web.WebSocketResponse:
|
||||
ws = web.WebSocketResponse()
|
||||
await ws.prepare(request)
|
||||
state: PersonaPlexServingSessionState | None = None
|
||||
sender: asyncio.Task | None = None
|
||||
|
||||
async def pump(outq: asyncio.Queue) -> None:
|
||||
# Forward slot output continuously (the tick loop produces in realtime).
|
||||
while True:
|
||||
frame_out = await outq.get()
|
||||
if frame_out.audio is not None:
|
||||
await ws.send_bytes(np.ascontiguousarray(frame_out.audio, dtype=np.float32).tobytes())
|
||||
if frame_out.text:
|
||||
await ws.send_json({"type": "text", "text": frame_out.text})
|
||||
|
||||
try:
|
||||
async for msg in ws:
|
||||
if msg.type == WSMsgType.TEXT:
|
||||
req = json.loads(msg.data)
|
||||
if req.get("type") == "open":
|
||||
if state is not None:
|
||||
# One slot lease per connection; a second `open` would
|
||||
# silently leak the first slot and its pump.
|
||||
await ws.send_json({"type": "error", "error": "session already open"})
|
||||
continue
|
||||
state = await self._acquire(ws, (req.get("persona") or "").strip() or None)
|
||||
if state is None:
|
||||
return ws
|
||||
sender = asyncio.create_task(pump(state.out_queue))
|
||||
await ws.send_json({"type": "ready"})
|
||||
elif req.get("type") == "close":
|
||||
await asyncio.sleep(0.3) # let in-flight frames flush via pump
|
||||
await ws.send_json({"type": "done"})
|
||||
break
|
||||
elif msg.type == WSMsgType.BINARY and state is not None:
|
||||
self.manager.feed(state.slot, np.frombuffer(msg.data, dtype=np.float32), state.epoch)
|
||||
elif msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.ERROR):
|
||||
break
|
||||
finally:
|
||||
# Release FIRST and unconditionally: a pump that already failed (e.g.
|
||||
# peer reset mid-send) re-raises on await and must not leak the slot.
|
||||
if state is not None:
|
||||
self.manager.release(state.slot)
|
||||
if sender is not None:
|
||||
sender.cancel()
|
||||
try:
|
||||
await sender
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
except Exception:
|
||||
logger.debug("raw output pump ended with an error", exc_info=True)
|
||||
with contextlib.suppress(Exception):
|
||||
await ws.close()
|
||||
return ws
|
||||
|
||||
|
||||
def create_app(config: PersonaPlexConfig) -> web.Application:
|
||||
server = BatchedDuplexServer(config) if config.batch_size > 1 else DuplexServer(config)
|
||||
web_dir = _official_web_dir()
|
||||
|
||||
async def _startup(_app: web.Application) -> None:
|
||||
logger.info("PersonaPlex duplex server: loading engine (batch_size=%d)", config.batch_size)
|
||||
server.load()
|
||||
logger.info("PersonaPlex duplex server: ready (official web: %s)", bool(web_dir))
|
||||
|
||||
async def _cleanup(_app: web.Application) -> None:
|
||||
if isinstance(server, BatchedDuplexServer):
|
||||
server.shutdown()
|
||||
|
||||
app = web.Application()
|
||||
app.on_startup.append(_startup)
|
||||
app.on_cleanup.append(_cleanup)
|
||||
|
||||
async def health(_request: web.Request) -> web.Response:
|
||||
return web.json_response({"status": "ok"})
|
||||
|
||||
app.router.add_get("/health", health)
|
||||
app.router.add_get("/api/chat", server.handle_chat)
|
||||
app.router.add_get("/v1/audio/duplex", server.handle_raw)
|
||||
|
||||
# Serve the official PersonaPlex web client (explicit routes are matched first).
|
||||
if web_dir is not None:
|
||||
|
||||
async def index(_request: web.Request) -> web.FileResponse:
|
||||
return web.FileResponse(web_dir / "index.html")
|
||||
|
||||
app.router.add_get("/", index)
|
||||
app.router.add_static("/", path=str(web_dir), follow_symlinks=True, name="web")
|
||||
else:
|
||||
|
||||
async def index_missing(_request: web.Request) -> web.Response:
|
||||
return web.json_response({"error": f"official web client unavailable; check access to {_HF_REPO}"})
|
||||
|
||||
app.router.add_get("/", index_missing)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--host", default="0.0.0.0")
|
||||
ap.add_argument("--port", type=int, default=8124)
|
||||
ap.add_argument("--persona", default=None)
|
||||
ap.add_argument("--voice", default="NATF2.pt")
|
||||
ap.add_argument(
|
||||
"--batch-size",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Concurrent conversation slots on one engine (elastic batching when > 1).",
|
||||
)
|
||||
args = ap.parse_args()
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
cfg = PersonaPlexConfig(
|
||||
voice_prompt=args.voice,
|
||||
batch_size=args.batch_size,
|
||||
**({"persona": args.persona} if args.persona else {}),
|
||||
)
|
||||
web.run_app(create_app(cfg), host=args.host, port=args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,233 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM 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.experimental.fullduplex.openai.protocol import (
|
||||
DuplexCapabilities,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.openai.runtime_adapter import (
|
||||
ServingRuntimeConfigError,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.personaplex.config import DEFAULT_PERSONA
|
||||
from vllm_omni.experimental.fullduplex.personaplex.data_plane import (
|
||||
PersonaPlexDataPlaneContext,
|
||||
PersonaPlexDataPlaneSession,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.personaplex.input import (
|
||||
PersonaPlexPcmAppendBuffer,
|
||||
)
|
||||
|
||||
EncodeAudio = Callable[[object, int, str, float | None], str | None]
|
||||
|
||||
_PRIVATE_RUNTIME_CONFIG_KEYS = frozenset(
|
||||
{
|
||||
"personaplex_prefill_slots",
|
||||
"personaplex_model_path",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PersonaPlexServingSessionState:
|
||||
audio_buffer: PersonaPlexPcmAppendBuffer = field(default_factory=PersonaPlexPcmAppendBuffer)
|
||||
input_since_commit: bool = False
|
||||
speech_since_commit: 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.experimental.fullduplex.personaplex.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))
|
||||
runtime_config = deepcopy(dict(current))
|
||||
runtime_config["personaplex_voice_prompt"] = cls._voice_name(getattr(config, "voice", None))
|
||||
runtime_config["personaplex_persona"] = str(getattr(config, "instructions", None) or DEFAULT_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,124 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""PersonaPlex lockstep session driver — the runnable serving primitive.
|
||||
|
||||
Mirrors JoyVL's ``serving/session.py``: a thin, framework-free driver that owns a
|
||||
``FrameStepper`` and turns arbitrary-length PCM chunks from a client into exact
|
||||
80 ms frames, stepping the model one frame at a time. This is the path that
|
||||
actually runs end to end (offline driver and any WS server build on it); the
|
||||
``DuplexAdapter`` is a separate demonstration of the generic framework seam.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.experimental.fullduplex.personaplex.config import PersonaPlexConfig
|
||||
from vllm_omni.experimental.fullduplex.personaplex.engine import FrameOutput, FrameStepper
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from numpy.typing import NDArray
|
||||
|
||||
# Realtime queue bounds: 80 ms/frame, so 50 frames = 4 s of backlog. Anything
|
||||
# beyond that means the peer cannot keep up and old frames are already useless.
|
||||
MAX_PENDING_INPUT = 50
|
||||
MAX_PENDING_OUTPUT = 50
|
||||
|
||||
|
||||
def offer_realtime(queue: asyncio.Queue, item: Any) -> None:
|
||||
"""Enqueue with a drop-oldest policy (realtime streams must never grow unbounded)."""
|
||||
while True:
|
||||
try:
|
||||
queue.put_nowait(item)
|
||||
return
|
||||
except asyncio.QueueFull:
|
||||
with contextlib.suppress(asyncio.QueueEmpty):
|
||||
queue.get_nowait()
|
||||
|
||||
|
||||
@dataclass
|
||||
class PersonaPlexServingSessionState:
|
||||
"""Mutable per-connection serving state (the minicpmo45 ``session.py`` role).
|
||||
|
||||
One instance per WebSocket connection, for both server modes: the
|
||||
single-session server uses ``pcm_queue`` (decoded mic PCM awaiting the
|
||||
engine); the batched server uses ``out_queue`` + ``slot``/``epoch`` (engine
|
||||
output awaiting send, and the claimed slot lease). ``closed`` tears both
|
||||
pump loops down.
|
||||
"""
|
||||
|
||||
pcm_queue: asyncio.Queue = field(default_factory=lambda: asyncio.Queue(maxsize=MAX_PENDING_INPUT))
|
||||
out_queue: asyncio.Queue = field(default_factory=lambda: asyncio.Queue(maxsize=MAX_PENDING_OUTPUT))
|
||||
closed: bool = False
|
||||
slot: Any = None # batched mode: the claimed serving/batched.py Slot
|
||||
epoch: int = 0 # batched mode: slot epoch at claim time (stale-guard)
|
||||
# Single-session mode: completion event of the engine call currently running
|
||||
# on a worker thread. Task cancellation cannot stop that thread (and marks
|
||||
# the asyncio future cancelled while the thread runs on), so the server
|
||||
# waits on this event before releasing its lease (DuplexServer._engine_call).
|
||||
inflight: Any = None
|
||||
|
||||
|
||||
class PersonaPlexSession:
|
||||
"""Drive one PersonaPlex conversation in strict frame lockstep.
|
||||
|
||||
A session buffers incoming PCM and emits exactly one :class:`FrameOutput` per
|
||||
completed ``frame_size`` window. Partial tails are held until enough samples
|
||||
arrive (or ``flush()`` pads them out at end of stream).
|
||||
"""
|
||||
|
||||
def __init__(self, stepper: FrameStepper, config: PersonaPlexConfig | None = None) -> None:
|
||||
self.stepper = stepper
|
||||
self.config = config or PersonaPlexConfig()
|
||||
self.frame_size = stepper.frame_size
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
self._opened = False
|
||||
|
||||
def open(self, voice_prompt: str | None = None, persona: str | None = None) -> None:
|
||||
"""Inject the voice clone + persona and arm the conversation."""
|
||||
self.stepper.open_session(voice_prompt=voice_prompt, persona=persona)
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
self._opened = True
|
||||
|
||||
def feed(self, pcm: NDArray[np.float32]) -> list[FrameOutput]:
|
||||
"""Append PCM and step every newly completed frame.
|
||||
|
||||
Returns one :class:`FrameOutput` per frame consumed from the buffer this
|
||||
call (possibly empty if fewer than ``frame_size`` samples are buffered).
|
||||
"""
|
||||
if not self._opened:
|
||||
raise RuntimeError("PersonaPlexSession.open() must be called before feed()")
|
||||
samples = np.ascontiguousarray(pcm, dtype=np.float32).reshape(-1)
|
||||
self._pending = np.concatenate([self._pending, samples]) if self._pending.size else samples
|
||||
|
||||
outputs: list[FrameOutput] = []
|
||||
n = self.frame_size
|
||||
while self._pending.shape[0] >= n:
|
||||
frame, self._pending = self._pending[:n], self._pending[n:]
|
||||
outputs.append(self.stepper.step(frame))
|
||||
return outputs
|
||||
|
||||
def flush(self) -> list[FrameOutput]:
|
||||
"""Zero-pad and step any buffered tail; call once at end of input."""
|
||||
if self._pending.shape[0] == 0:
|
||||
return []
|
||||
pad = self.frame_size - self._pending.shape[0]
|
||||
frame = np.concatenate([self._pending, np.zeros(pad, dtype=np.float32)])
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
return [self.stepper.step(frame)]
|
||||
|
||||
def run(self, pcm: NDArray[np.float32]) -> tuple[NDArray[np.float32], str]:
|
||||
"""Convenience for offline use: feed a whole utterance, return (audio, text).
|
||||
|
||||
Concatenates every emitted agent frame and joins the inner-monologue text.
|
||||
"""
|
||||
outputs = self.feed(pcm) + self.flush()
|
||||
chunks = [o.audio for o in outputs if o.audio is not None]
|
||||
audio = np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)
|
||||
text = "".join(o.text for o in outputs if o.text)
|
||||
return audio, text
|
||||
@@ -0,0 +1,467 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM 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.experimental.fullduplex.personaplex.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",
|
||||
]
|
||||
Reference in new issue
Block a user