[Perf][PersonaPlex] Serve 16 concurrent realtime duplex sessions on one GPU (#8192)

This commit is contained in:
Yueqian Lin authored and GitHub committed 2026-09-28 04:51:38 +00:00
1 parent 36b74f99f6
commit f5bdb20e9d
12 files changed
+563 -102

No files matched your search

@@ -27,6 +27,14 @@ from vllm_omni.model_executor.models.personaplex.duplex.policy import (
_FRAME_SAMPLES = FRAME_SIZE
class PersonaPlexStage0CapacityError(RuntimeError):
"""Every streaming encoder row is leased by a live session."""
class PersonaPlexStage0StaleEpochError(RuntimeError):
"""The append belongs to an epoch that a newer epoch of the same session has superseded."""
@dataclass(slots=True)
class PersonaPlexStage0PreparedAppend:
input_ids: Any
@@ -52,7 +60,9 @@ class PersonaPlexStage0SessionState:
prepared: PersonaPlexStage0PreparedAppend | None = None
last_seq: int = 0
request_ids: set[str] = field(default_factory=set)
codec: Any | None = None
slot: int | None = None
encoded_identity: tuple[int, int] | None = None
encoded_frame: Any | None = None
def _tokenizer_path(model_path: str) -> Path:
@@ -124,7 +134,13 @@ def personaplex_prefill_slots(model_path: str, voice: str, persona: str) -> int:
class PersonaPlexStage0DuplexRuntime:
"""Own per-session streaming Mimi encoders and first-append prefill."""
"""Own the shared streaming Mimi encoder and each session's first-append prefill.
One encoder holds ``max_sessions`` streaming rows; a live ``(session, epoch)``
leases one row for its lifetime. ``encode_appends`` encodes every new append
of a scheduler step in one batched call (rows without a new append are
inactive and keep their state), and ``prepare_append`` consumes the result.
"""
def __init__(
self,
@@ -145,14 +161,61 @@ class PersonaPlexStage0DuplexRuntime:
self.device = device
self.max_sessions = max_sessions
self._codec_factory = codec_factory
self._free_codecs: list[Any] = []
self._codec: Any | None = None
self._free_slots: list[int] = list(reversed(range(max_sessions)))
self._tokenizer = tokenizer
self._voice_loader = voice_loader
self.sessions: dict[tuple[str, int], PersonaPlexStage0SessionState] = {}
self.request_sessions: dict[str, tuple[str, int]] = {}
# Requests of a superseded epoch that still reached this step; they are
# finished by the engine and must not lease a row or record a sample.
self._stale_requests: set[str] = set()
if codec is not None:
codec.streaming_init(1)
self._free_codecs.append(codec)
codec.streaming_init(max_sessions)
self._codec = codec
def encode_appends(self, appends: list[dict[str, Any]]) -> None:
"""Encode the new user frame of each append in one batched encoder call.
Called once per scheduler step before the per-request ``prepare_append``
calls. An append whose ``(epoch, seq)`` is already encoded or prepared
(a chunked first prefill spans several steps) is skipped, so a row's
streaming state advances exactly once per frame. Appends that cannot be
admitted are left for ``prepare_append`` to reject.
"""
parsed: list[tuple[str, int, int, dict[str, Any]]] = []
for duplex in appends:
try:
parsed.append((*_append_identity(duplex), duplex))
except ValueError:
continue
# A cancel can put a session's aborted epoch and its restarted epoch in
# one step. Only the newest epoch is live: admitting it closes the old
# one, so the old append must neither be encoded nor re-leased.
newest: dict[str, int] = {}
for session_id, epoch, _, _ in parsed:
newest[session_id] = max(epoch, newest.get(session_id, epoch))
for session_id, epoch in self.sessions:
if session_id in newest:
newest[session_id] = max(epoch, newest[session_id])
rows: list[tuple[PersonaPlexStage0SessionState, tuple[int, int], np.ndarray]] = []
for session_id, epoch, seq, duplex in parsed:
if epoch != newest[session_id]:
continue
try:
state = self._session_state(session_id, epoch)
except PersonaPlexStage0CapacityError:
# Left for prepare_append to reject. Any other error (e.g. the
# shared codec failing to initialize) propagates immediately.
continue
identity = (epoch, seq)
if identity in (state.prepared_identity, state.encoded_identity) or seq <= state.last_seq:
continue
if any(row[0] is state for row in rows):
continue
rows.append((state, identity, self._decode_pcm(duplex.get("payload"))))
if rows:
self._encode_rows(rows)
def prepare_append(
self,
@@ -163,30 +226,15 @@ class PersonaPlexStage0DuplexRuntime:
) -> 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")
epoch = _coerce_non_negative_int(duplex.get("epoch"), "epoch")
seq = _coerce_positive_int(duplex.get("seq"), "seq")
session_id, epoch, seq = _append_identity(duplex)
identity = (epoch, seq)
key = (session_id, epoch)
state = self.sessions.get(key)
if state is None:
# A newer epoch supersedes the session's earlier lockstep state:
# the engine aborted that request, but its finish notification
# may still be in flight, so release it here rather than let the
# two epochs share the codec budget.
for stale_key in [k for k in self.sessions if k[0] == session_id and k[1] < epoch]:
self.close_session(*stale_key)
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,
epoch=epoch,
codec=self._acquire_codec(),
)
self.sessions[key] = state
try:
state = self._session_state(session_id, epoch)
except PersonaPlexStage0StaleEpochError:
if request_id:
self._stale_requests.add(request_id)
raise
if request_id:
state.request_ids.add(request_id)
self.request_sessions[request_id] = key
@@ -195,17 +243,11 @@ class PersonaPlexStage0DuplexRuntime:
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()
if state.encoded_identity != identity:
self._encode_rows([(state, identity, self._decode_pcm(duplex.get("payload")))])
user_frame = state.encoded_frame
state.encoded_identity = None
state.encoded_frame = None
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")
@@ -342,6 +384,8 @@ class PersonaPlexStage0DuplexRuntime:
"""Commit one sampled temporal frame for the next live append."""
import torch
if request_id in self._stale_requests:
return
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}")
@@ -376,6 +420,7 @@ class PersonaPlexStage0DuplexRuntime:
state.sampled_identity = state.prepared_identity
def close_request(self, request_id: str) -> None:
self._stale_requests.discard(request_id)
key = self.request_sessions.pop(request_id, None)
if key is None:
return
@@ -393,28 +438,75 @@ class PersonaPlexStage0DuplexRuntime:
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
if state.slot is not None:
self._shared_codec().reset_slot(state.slot)
self._free_slots.append(state.slot)
state.slot = None
def _acquire_codec(self):
if self._free_codecs:
return self._free_codecs.pop()
def _session_state(self, session_id: str, epoch: int) -> PersonaPlexStage0SessionState:
key = (session_id, epoch)
state = self.sessions.get(key)
if state is not None:
return state
# A newer epoch supersedes the session's earlier lockstep state: the
# engine aborted that request, but its finish notification may still
# be in flight, so release it here rather than let the two epochs share
# the encoder budget.
# The reverse also holds: once a newer epoch is live, an append of an
# older epoch is a leftover of the aborted request and must not re-lease
# a row (at capacity it would fail the whole step).
newer = [k[1] for k in self.sessions if k[0] == session_id and k[1] > epoch]
if newer:
raise PersonaPlexStage0StaleEpochError(
f"PersonaPlex Stage 0 epoch {epoch} of session {session_id} is superseded by epoch {max(newer)}"
)
for stale_key in [k for k in self.sessions if k[0] == session_id and k[1] < epoch]:
self.close_session(*stale_key)
if len(self.sessions) >= self.max_sessions or not self._free_slots:
raise PersonaPlexStage0CapacityError(
f"PersonaPlex Stage 0 session capacity {self.max_sessions} is exhausted"
)
self._shared_codec()
state = PersonaPlexStage0SessionState(session_id=session_id, epoch=epoch, slot=self._free_slots.pop())
self.sessions[key] = state
return state
def _encode_rows(self, rows: list[tuple[PersonaPlexStage0SessionState, tuple[int, int], np.ndarray]]) -> None:
import torch
codec = self._shared_codec()
pcm = torch.zeros((self.max_sessions, _FRAME_SAMPLES), dtype=torch.float32)
active = torch.zeros((self.max_sessions,), dtype=torch.bool)
for state, _, samples in rows:
assert state.slot is not None
pcm[state.slot] = torch.from_numpy(samples)
active[state.slot] = True
encoded = codec.encode_frame(pcm, active)
# One device-to-host copy per step, whatever the number of sessions.
codes = encoded.detach().to(dtype=torch.long, device="cpu")
if codes.shape[-1] < 8:
raise RuntimeError(f"PersonaPlex Mimi encoder returned {codes.shape[-1]} codebooks, expected at least 8")
for state, identity, _ in rows:
state.encoded_frame = codes[state.slot : state.slot + 1, :8].clone()
state.encoded_identity = identity
def _shared_codec(self):
if self._codec is not None:
return self._codec
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,
)
else:
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)
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(self.max_sessions)
self._codec = codec
return codec
def _load_tokenizer(self):
@@ -453,6 +545,15 @@ class PersonaPlexStage0DuplexRuntime:
return pcm_f32le_samples(raw)
def _append_identity(duplex: dict[str, Any]) -> tuple[str, int, int]:
session_id = duplex.get("session_id")
if not isinstance(session_id, str) or not session_id:
raise ValueError("PersonaPlex duplex append requires session_id")
epoch = _coerce_non_negative_int(duplex.get("epoch"), "epoch")
seq = _coerce_positive_int(duplex.get("seq"), "seq")
return session_id, epoch, seq
def _coerce_non_negative_int(value: object, name: str) -> int:
try:
result = int(value)
@@ -203,8 +203,9 @@ class PersonaPlexDepformer(nn.Module):
audio_tokens: torch.Tensor | None = None,
audio_provided: torch.Tensor | None = None,
return_logits: bool = False,
num_steps: int | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Predict the ``dep_q`` audio codes for one frame.
"""Predict the first ``num_steps`` (default ``dep_q``) audio codes for one frame.
Args:
text_token: ``[B]`` sampled text token for the frame.
@@ -213,19 +214,26 @@ class PersonaPlexDepformer(nn.Module):
audio_provided: optional ``[B, dep_q]`` bool mask; where True the
corresponding ``audio_tokens`` entry overrides the sampled code as
the next-step input (partial teacher forcing, as in Moshi).
return_logits: also return the per-step logits ``[B, dep_q, card]``.
return_logits: also return the per-step logits ``[B, num_steps, card]``.
num_steps: stop after this many inner steps. The loop is causal, so the
first ``num_steps`` codes are identical to a full ``dep_q`` run;
the trailing steps predict the user's codebooks, which the serving
path never consumes.
Returns:
``[B, dep_q]`` long tensor of sampled (greedy) audio codes, plus the
``[B, num_steps]`` long tensor of sampled (greedy) audio codes, plus the
per-step logits when ``return_logits`` is set.
"""
if transformer_out.dim() != 3 or transformer_out.shape[1] != 1:
raise ValueError(f"transformer_out must be [B, 1, H]; got {tuple(transformer_out.shape)}")
steps = self.dep_q if num_steps is None else int(num_steps)
if not 1 <= steps <= self.dep_q:
raise ValueError(f"num_steps must be in [1, {self.dep_q}]; got {num_steps}")
prev = text_token
kv = [{"k": None, "v": None} for _ in self.layers]
codes: list[torch.Tensor] = []
logits_all: list[torch.Tensor] = []
for step in range(self.dep_q):
for step in range(steps):
x = self.depformer_in[step](transformer_out) # [B, 1, dim]
if step == 0:
cond = self.depformer_text_emb(prev.unsqueeze(1))
@@ -243,9 +251,9 @@ class PersonaPlexDepformer(nn.Module):
prev = torch.where(audio_provided[:, step], audio_tokens[:, step], sampled)
else:
prev = sampled
stacked = torch.stack(codes, dim=1) # [B, dep_q]
stacked = torch.stack(codes, dim=1) # [B, steps]
if return_logits:
return stacked, torch.stack(logits_all, dim=1) # [B, dep_q, card]
return stacked, torch.stack(logits_all, dim=1) # [B, steps, card]
return stacked
# ------------------------------------------------------------------
@@ -249,8 +249,11 @@ class _MimiStreamingTransformer(nn.Module):
self._offset.zero_()
def reset_slot(self, b: int) -> None:
# A recycled row restarts at position 0, exactly like a fresh stream,
# instead of carrying its predecessor's absolute RoPE positions.
for kv in self._kv:
kv.reset_slot(b)
kv.reset_row(b)
self._offset[b] = 0
def step(self, x: torch.Tensor, active: torch.Tensor) -> torch.Tensor:
"""``x`` is ``[B, T, dim]`` (T = positions this frame, typically 2)."""
@@ -173,7 +173,9 @@ class PersonaPlexTalkerForConditionalGeneration(nn.Module):
if not audio_codes_list:
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
audio_codes = torch.cat(audio_codes_list, dim=0)
hidden = hidden[: int(audio_codes.shape[0])]
# Keep every token row: the runner indexes this tensor with token-space
# logits indices, and a step can mix a new session's multi-row prefill
# with one-row live appends, so the audio row count is not the token count.
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={"codes": {"audio": audio_codes}})
# ------------------------------------------------------------------
@@ -323,11 +325,18 @@ class PersonaPlexTalkerForConditionalGeneration(nn.Module):
prompt_len = int(prompt_len_raw)
except (TypeError, ValueError):
prompt_len = span
prepared = self._duplex_stage0_runtime().prepare_append(
duplex,
prompt_len=prompt_len,
request_id=(str(info_dict["request_id"]) if isinstance(info_dict.get("request_id"), str) else None),
from vllm_omni.model_executor.models.personaplex.duplex.stage0 import (
PersonaPlexStage0StaleEpochError,
)
try:
prepared = self._duplex_stage0_runtime().prepare_append(
duplex,
prompt_len=prompt_len,
request_id=(str(info_dict["request_id"]) if isinstance(info_dict.get("request_id"), str) else None),
)
except PersonaPlexStage0StaleEpochError:
return self._stale_append_passthrough(input_ids, span)
offset_raw = info_dict.get("duplex_token_offset", 0)
try:
offset = max(0, int(offset_raw))
@@ -435,6 +444,52 @@ class PersonaPlexTalkerForConditionalGeneration(nn.Module):
self._personaplex_duplex_stage0_runtime = runtime
return runtime
def _stale_append_passthrough(
self, input_ids: torch.Tensor, span: int
) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]:
"""Neutral inputs for a request of a superseded epoch that is still in this step.
The engine already aborted it and discards its output; it only has to keep
the batch shapes valid without touching the live session's encoder row.
"""
from vllm_omni.model_executor.models.personaplex.duplex.policy import SILENCE_TOKENS
device = input_ids.device
silence = torch.tensor(SILENCE_TOKENS, dtype=torch.long)
embeds = torch.zeros((span, self.mtp_hidden_size), device=device, dtype=self._dtype)
return (
input_ids,
embeds,
{
"pplex_depformer_audio_tokens": torch.cat([silence, silence]),
"pplex_depformer_audio_provided": torch.zeros(2 * silence.numel(), dtype=torch.bool),
"duplex": {"stage0_stale": True},
},
)
def preprocess_batch(
self,
*,
req_ids: list[str],
model_intermediate_buffer: dict[str, dict[str, Any]],
device: torch.device,
) -> None:
"""Encode every live duplex append of this step in one shared-encoder call."""
del device
appends: list[dict[str, Any]] = []
for req_id in req_ids:
info = model_intermediate_buffer.get(req_id)
if not isinstance(info, dict):
continue
duplex = info.get("duplex")
if not isinstance(duplex, dict):
additional = info.get("additional_information")
duplex = additional.get("duplex") if isinstance(additional, dict) else None
if isinstance(duplex, dict) and duplex.get("data_plane") is True:
appends.append(duplex)
if appends:
self._duplex_stage0_runtime().encode_appends(appends)
def on_requests_finished(self, finished_req_ids: set[str] | list[str]) -> None:
runtime = getattr(self, "_personaplex_duplex_stage0_runtime", None)
if runtime is None:
@@ -526,6 +581,7 @@ class PersonaPlexTalkerForConditionalGeneration(nn.Module):
device=hidden.device,
dtype=torch.bool,
),
num_steps=self.num_active_codebooks,
).to(torch.long)
runtime = self._duplex_stage0_runtime()
for row, request_id in enumerate(req_ids):
@@ -92,6 +92,12 @@ class _RingKV:
# first visible entry. (LM sacrifice-tick +1 is applied by the caller.)
self.start_offset[b] = self.end_offset[b]
def reset_row(self, b: int) -> None:
# Restart row b at position 0. Every cached entry of the row sits at or
# past the new end offset, so all of them are masked until overwritten.
self.end_offset[b] = 0
self.start_offset[b] = 0
def bump_slot_start(self, b: int) -> None:
self.start_offset[b] += 1