Merge main into dev/vllm-align for vLLM 0.31 release

Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
This commit is contained in:
tzhouam committed 2026-10-03 21:05:17 +08:00
commit 008fa25263
252 files changed
+27589 -1237

No files matched your search

+11 -8
View File
@@ -111,9 +111,10 @@ class _PreparedDelivery:
class _EngineOutputSink:
def __init__(self, output_queue: Any, scheduler: Any) -> None:
def __init__(self, output_queue: Any, scheduler: Any, *, upstream_first_audio: bool = True) -> None:
self.output_queue = output_queue
self.scheduler = scheduler
self.upstream_first_audio = upstream_first_audio
def prepare(self, request_ids: list[str]) -> _PreparedDelivery:
routes = {}
@@ -130,15 +131,14 @@ class _EngineOutputSink:
for request_id, pcm in zip(request_ids, pcm_rows, strict=True):
if request_id not in routes:
continue
payload = {"model_outputs": pcm, "sr": sample_rate}
if self.upstream_first_audio:
payload[FIRST_AUDIO_KEY] = torch.tensor(True)
by_client.setdefault(routes[request_id], []).append(
OmniEngineCoreOutput(
request_id=request_id,
new_token_ids=[],
multimodal_output={
"model_outputs": pcm,
"sr": sample_rate,
FIRST_AUDIO_KEY: torch.tensor(True),
},
multimodal_output=payload,
)
)
for client_index, outputs in by_client.items():
@@ -163,5 +163,8 @@ class _EngineOutputSink:
routes.pop(request_id)
def engine_output_queue_sink(output_queue: Any, scheduler: Any) -> _EngineOutputSink:
return _EngineOutputSink(output_queue, scheduler)
def engine_output_queue_sink(
output_queue: Any, scheduler: Any, *, upstream_first_audio: bool = True
) -> _EngineOutputSink:
"""Route prepared audio; final-stage PCM must not carry the upstream marker."""
return _EngineOutputSink(output_queue, scheduler, upstream_first_audio=upstream_first_audio)
@@ -38,6 +38,12 @@ def init_omni_model_state(
getattr(model, flag, False) is True for flag in ("has_preprocess", "has_postprocess", "have_multimodal_outputs")
)
if uses_omni_lifecycle:
factory = getattr(type(model), "create_mrv2_model_state", None)
if callable(factory):
state = factory(model, vllm_config, encoder_cache, device)
if not isinstance(state, ModelState):
raise TypeError("create_mrv2_model_state must return a ModelState")
return state
from vllm_omni.worker_v2.model_states.omni_model_state import (
OmniModelState,
)
@@ -5,13 +5,17 @@
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
import numpy as np
import torch
from vllm.logger import init_logger
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.states import RequestState
from vllm_omni.utils.device_copy import index_to_device
from vllm_omni.worker_v2.streaming_audio import StreamingAudioBuffer, StreamingAudioOutput
if TYPE_CHECKING:
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState
@@ -24,12 +28,175 @@ def _has_ref_codes(buffer: dict[str, Any]) -> bool:
return isinstance(ref, torch.Tensor) and ref.numel() > 0
def _snapshot_runtime(value: Any) -> Any:
if isinstance(value, torch.Tensor):
return value.to("cpu", copy=True)
if isinstance(value, dict):
return {key: _snapshot_runtime(item) for key, item in value.items()}
if isinstance(value, list):
return [_snapshot_runtime(item) for item in value]
if isinstance(value, tuple):
return tuple(_snapshot_runtime(item) for item in value)
return value
@dataclass
class TalkerInputs:
embeds: torch.Tensor
length: int = 0
@dataclass
class SuspendedAudio:
position: int
decoder_state: list[torch.Tensor]
generator: torch.Generator | None
runtime: dict[str, Any]
frame_embed: torch.Tensor
class EagerMTPState:
"""Used only by models explicitly declaring ``mtp_eager_frames``."""
def __init__(self, owner: OmniModelState) -> None:
self.owner = owner
self._first_audio_valid: torch.Tensor | None = None
self._side_stream: torch.cuda.Stream | None = None
self._fast_ok: bool | None = None
self._audio_buffer: StreamingAudioBuffer | None = None
self._frame_requests: set[str] = set()
self._suspended_audio: dict[str, SuspendedAudio] = {}
self._restore_audio: dict[str, list[torch.Tensor]] = {}
self._talker_inputs: dict[str, TalkerInputs] = {}
def suspend_audio(self, req_id: str, req_idx: int) -> None:
decoder = getattr(self.owner.model, "stream_decoder", None)
position = self.owner._stream_pos.get(req_id)
if decoder is None or position is None:
return
# Slot reuse is rare and must wait for the last side-stream write.
saved = self._restore_audio.pop(req_id, None)
if saved is None:
self._decode_stream.synchronize()
saved = decoder.save_slot(req_idx)
history = self._talker_inputs[req_id]
history.embeds = history.embeds[: history.length].to("cpu", copy=True)
runtime = self.owner.intermediate_buffer.buffers[req_idx]
assert self.owner._eager_embeds is not None
self._suspended_audio[req_id] = SuspendedAudio(
position,
saved,
self.owner._mtp_generators.get(req_id),
_snapshot_runtime(runtime),
self.owner._eager_embeds[req_idx].to("cpu", copy=True),
)
def resume_audio(self, req_id: str, req_idx: int) -> None:
saved = self._suspended_audio.pop(req_id, None)
if saved is not None:
self.owner._stream_pos[req_id] = saved.position
self.owner._mtp_generators[req_id] = saved.generator
self._restore_audio[req_id] = saved.decoder_state
self.owner.intermediate_buffer.buffers[req_idx] = saved.runtime
assert self.owner._eager_embeds is not None
self.owner._eager_embeds[req_idx].copy_(saved.frame_embed)
self.owner._eager_ready[req_idx] = req_id
def finish_audio(self, req_ids: set[str]) -> None:
for req_id in req_ids:
self._suspended_audio.pop(req_id, None)
self._restore_audio.pop(req_id, None)
self.owner._stream_pos.pop(req_id, None)
self._talker_inputs.pop(req_id, None)
if self._audio_buffer is not None:
self._audio_buffer.finish(req_ids)
def replay_inputs(self, req_id: str, req_idx: int, offset: int, ids: torch.Tensor, embeds: torch.Tensor) -> bool:
"""Rebuild freed Talker KV from the exact conditioned inputs, without rerunning MTP."""
if req_id not in self._restore_audio:
return False
history = self._talker_inputs[req_id]
count = min(len(ids), max(0, history.length - offset))
if count:
embeds[:count].copy_(history.embeds[offset : offset + count])
if count < len(ids):
# Recompute ends with the last accepted CB0, whose full eager frame
# was saved but has not yet been consumed as a Talker input.
if len(ids) - count != 1 or offset + count != history.length:
raise RuntimeError(f"Talker replay exceeds saved inputs for {req_id}")
info = self.owner.intermediate_buffer.buffers[req_idx]
_, _, updates = self.owner.model.preprocess(ids[count:], embeds[count:], **info, _omni_is_prefill=False)
mtp_inputs = updates.pop("mtp_inputs", None)
if mtp_inputs is None:
raise RuntimeError(f"Talker replay has no text conditioning for {req_id}")
assert self.owner._eager_embeds is not None
embeds[count:].copy_(self.owner._eager_embeds[req_idx] + mtp_inputs[1].reshape(1, -1))
self.owner.intermediate_buffer.update(req_idx, updates, self.owner.model.gpu_resident_buffer_keys)
return True
def record_inputs(self, input_batch: InputBatch, embeds: torch.Tensor) -> None:
if getattr(self.owner.model, "stream_decoder", None) is None:
return
history_slices: list[torch.Tensor] = []
input_slices: list[torch.Tensor] = []
for i, req_id in enumerate(input_batch.req_ids):
start, end = input_batch.query_start_loc_np[i : i + 2]
offset = int(input_batch.num_computed_tokens_np[i])
length = offset + int(end - start)
history = self._talker_inputs.get(req_id)
if history is None or history.embeds.device != embeds.device:
storage = torch.empty(
self.owner.vllm_config.model_config.max_model_len,
embeds.shape[-1],
device=embeds.device,
dtype=embeds.dtype,
)
if history is not None:
storage[: history.length].copy_(history.embeds)
history = TalkerInputs(storage, history.length if history else 0)
self._talker_inputs[req_id] = history
history_slices.append(history.embeds[offset:length])
input_slices.append(embeds[start:end])
history.length = max(history.length, length)
if history_slices:
# Keep exact inputs for replay without launching one copy per row.
torch._foreach_copy_(history_slices, input_slices)
def prepare_audio_output(
self, input_batch: InputBatch, req_states: RequestState, outputs: dict[str, Any]
) -> StreamingAudioOutput | None:
if self._audio_buffer is None:
return None
wav = outputs.pop("model_outputs", None)
if not isinstance(wav, torch.Tensor):
return None
n = input_batch.num_reqs
total_after = input_batch.num_computed_tokens_np[:n] + np.asarray(input_batch.num_scheduled_tokens[:n]) + 1
limits = np.minimum(
req_states.max_seq_len[input_batch.idx_mapping_np[:n]], self.owner.vllm_config.model_config.max_model_len
)
requests = [
self._audio_buffer.requests.get(rid) if rid in self._frame_requests else None for rid in input_batch.req_ids
]
self._frame_requests.clear()
event = self.owner._stream_decode_event
self.owner._stream_decode_event = None
return StreamingAudioOutput(
wav,
outputs["meta"]["codec_frame_valid"],
outputs["sr"][0],
event,
input_batch.query_start_loc_np[: n + 1].copy(),
requests,
total_after >= limits,
)
@property
def _decode_stream(self) -> torch.cuda.Stream:
"""Side stream for Talker stream decode, so the codec overlaps the next step."""
if self._side_stream is None:
self._side_stream = torch.cuda.Stream()
return self._side_stream
def set_first_audio_sink(self, sink: Any) -> None:
from vllm_omni.worker_v2.first_audio_sender import FirstAudioSender
@@ -106,6 +273,14 @@ class EagerMTPState:
bsz = len(entries)
device = text_hidden.device
if self._fast_path_ok(codes_out, text_hidden):
self._run_eager_mtp_fused(
input_batch, text_hidden, sampled_token_ids, multimodal_outputs, entries, input_ids,
codes_out, valid_out, mtp_batch_descriptor_dispatcher,
) # fmt: skip
return
if getattr(self.owner.model, "stream_decoder", None) is not None:
raise RuntimeError("Talker stream decode requires the fused eager-MTP path")
batch_rows = index_to_device([i for i, _req_idx, _req_id, _prefill in entries], device)
req_indices = [req_idx for _i, req_idx, _req_id, _prefill in entries]
last_tokens = input_batch.query_start_loc.index_select(0, batch_rows + 1).long() - 1
@@ -162,6 +337,168 @@ class EagerMTPState:
scheduled *= self._first_audio_valid.index_select(0, rows)
first_audio.index_copy_(0, last_tokens, scheduled.to(first_audio.dtype))
def _embedding_weight(self) -> torch.Tensor | None:
inner = getattr(self.owner.model, "model", None)
embed = getattr(inner, "embed_tokens", None)
weight = getattr(embed, "weight", None)
method = getattr(embed, "quant_method", None)
unquantized = method is None or type(method).__name__ == "UnquantizedEmbeddingMethod"
tp = getattr(embed, "tp_size", 1)
if isinstance(weight, torch.Tensor) and weight.ndim == 2 and unquantized and tp == 1:
return weight
return None
def _fast_path_ok(self, codes_out: torch.Tensor, text_hidden: torch.Tensor) -> bool:
if self._fast_ok is None:
self._fast_ok = (
text_hidden.is_cuda
and not self.owner.vllm_config.cache_config.enable_prefix_caching
and self._embedding_weight() is not None
and hasattr(self.owner.model, "_codebook_vocab_size")
)
return self._fast_ok and codes_out.ndim == 2 and text_hidden.is_contiguous()
def _run_eager_mtp_fused(
self,
input_batch: InputBatch,
text_hidden: torch.Tensor,
sampled_token_ids: torch.Tensor,
multimodal_outputs: dict[str, Any],
entries: list[tuple[int, int, str, bool]],
input_ids: torch.Tensor,
codes_out: torch.Tensor,
valid_out: torch.Tensor,
mtp_batch_descriptor_dispatcher: Callable[[int], Any] | None,
) -> None:
from vllm_omni.worker_v2.model_states.eager_mtp_kernels import eager_post, eager_pre
owner = self.owner
bsz = len(entries)
device = text_hidden.device
first_audio = multimodal_outputs.get("meta", {}).get("first_audio")
fa_requests = owner._first_audio_requests
model = owner.model
stream = getattr(model, "stream_decoder", None)
stream_out = multimodal_outputs.get("model_outputs") if stream is not None else None
pos_list: list[int] = []
first_rows: list[int] = []
primes: list[tuple[int, torch.Tensor]] = []
if isinstance(stream_out, torch.Tensor):
assert stream is not None
# Frame index of each row's frame in its request's stream; 0 starts
# a fresh decoder state in the request's slot. A voice-clone
# request's stream starts after its reference codes, which prime
# the decoder state first (as Code2Wav's first-chunk context does).
if self._audio_buffer is None:
self._audio_buffer = StreamingAudioBuffer(int(stream.spf), int(model.stream_chunk_frames))
self._frame_requests = {req_id for _i, _idx, req_id, _p in entries}
positions = owner._stream_pos
for row, (_i, req_idx, req_id, _p) in enumerate(entries):
self._audio_buffer.add(req_id)
p = positions.get(req_id)
if p is None:
first_rows.append(row)
ref = model.get_stream_ref_context(owner.intermediate_buffer.buffers[req_idx])
p = 0
if ref is not None:
primes.append((req_idx, ref))
p = int(ref.shape[0])
pos_list.append(p)
positions[req_id] = p + 1
meta_list = (
[i for i, _r, _q, _p in entries]
+ [r for _i, r, _q, _p in entries]
+ [int(p) for _i, _r, _q, p in entries]
+ [int(q in fa_requests) for _i, _r, q, _p in entries]
+ pos_list
)
meta = index_to_device(meta_list, device)
rows = meta[bsz : 2 * bsz]
sampled = sampled_token_ids.reshape(input_batch.num_reqs, -1)
assert owner._mtp_input_ids is not None and owner._mtp_input_embeds is not None
assert owner._mtp_hidden is not None and owner._mtp_text_step is not None
batch_ids = owner._mtp_input_ids[:bsz]
batch_emb = owner._mtp_input_embeds[:bsz]
batch_hidden = owner._mtp_hidden[:bsz]
batch_step = owner._mtp_text_step[:bsz]
last_tokens, layer0 = eager_pre(
meta, bsz, input_batch.query_start_loc, sampled, text_hidden, self._embedding_weight(),
batch_ids, batch_emb, batch_hidden, batch_step,
) # fmt: skip
req_indices = meta_list[bsz : 2 * bsz]
frame_embeds, codes = owner._mtp_forward(
req_indices, batch_ids, batch_emb, batch_hidden, batch_step, mtp_batch_descriptor_dispatcher
)
assert codes is not None
has_prefill = any(p for _i, _r, _q, p in entries)
fa_in_kernel = isinstance(first_audio, torch.Tensor) and not has_prefill
valid = eager_post(
meta, bsz, last_tokens, layer0, frame_embeds.reshape(frame_embeds.shape[0], -1).contiguous(),
owner._eager_embeds, codes.contiguous(), codes_out, input_ids, valid_out,
first_audio if fa_in_kernel else None, self._first_audio_valid if fa_in_kernel else None,
owner.model._codebook_vocab_size,
) # fmt: skip
for _i, req_idx, req_id, _prefill in entries:
owner._eager_ready[req_idx] = req_id
if pos_list:
assert stream is not None
assert isinstance(stream_out, torch.Tensor)
decode = model.stream_graphs if model.stream_graphs is not None else stream
frame_codes = codes[:bsz].reshape(bsz, 1, -1).to(torch.int32)
# The next Talker step does not read the PCM, so the codec runs
# beside it; only the output copies wait for it.
side = self._decode_stream
side.wait_stream(torch.cuda.current_stream())
for t in (frame_codes, meta, last_tokens, valid, stream_out):
t.record_stream(side)
with torch.cuda.stream(side):
for _i, req_idx, req_id, _p in entries:
saved = self._restore_audio.pop(req_id, None)
if saved is not None:
stream.restore_slot(req_idx, saved)
model.prime_stream_decoder(primes)
pcm = decode(frame_codes, rows, meta[4 * bsz : 5 * bsz])
stream_out.index_copy_(0, last_tokens, pcm.reshape(bsz, -1).to(stream_out.dtype))
self._send_stream_first_frames(entries, pcm, valid, first_rows)
done = torch.cuda.Event()
done.record(side)
owner._stream_decode_event = done
if has_prefill:
self._publish_first_audio(input_batch, entries, codes[:bsz], valid)
if isinstance(first_audio, torch.Tensor):
# Requests accepted by this step's publish count as scheduled.
scheduled = index_to_device(
[int(q in owner._first_audio_requests) for _i, _r, q, _p in entries], device
)
if self._first_audio_valid is None:
scheduled.zero_()
else:
scheduled *= self._first_audio_valid.index_select(0, rows)
first_audio.index_copy_(0, last_tokens, scheduled.to(first_audio.dtype))
def _send_stream_first_frames(
self,
entries: list[tuple[int, int, str, bool]],
pcm: torch.Tensor,
valid: torch.Tensor,
first_rows: list[int],
) -> None:
sender = self.owner._first_audio_sender
if sender is None or not first_rows:
return
rows = index_to_device(first_rows, pcm.device)
request_ids = [entries[row][2] for row in first_rows]
sample_rate = torch.tensor(int(self.owner.model.stream_sample_rate), dtype=torch.int32)
accepted = sender.submit(
request_ids,
pcm.reshape(pcm.shape[0], -1).index_select(0, rows).float(),
sample_rate,
valid=valid.index_select(0, rows),
)
assert self._audio_buffer is not None
for request_id in accepted:
self._audio_buffer.requests[request_id].accept_first_audio()
def _publish_first_audio(
self,
input_batch: InputBatch,
@@ -0,0 +1,126 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# ruff: noqa: N803 - Triton constexpr parameters use kernel-style capitals.
"""Gather/scatter kernels around the eager Talker-MTP call.
Each engine step, the rows sampled this step need their CB0, codec embedding
and last hidden state gathered into the MTP inputs, and the MTP results
scattered back into the eager-frame embeddings and the retained outputs. As
separate torch ops that is a few dozen small launches per step, and the engine
loop is host-bound, so each costs the whole batch. These two kernels do the
same indexing in one launch each; the row metadata arrives in one H2D copy.
"""
from __future__ import annotations
import torch
from vllm.triton_utils import tl, triton
@triton.jit
def _pre_kernel(
meta_ptr, # int64 [4, n]: batch row, request index, prefill flag, first-audio scheduled
n,
qsl_ptr, # query_start_loc
sampled_ptr, # [num_reqs, s_stride]
s_stride,
hidden_ptr, # [T, H]
emb_w_ptr, # [V, H]
ids_ptr, # [n] MTP input ids
emb_ptr, # [n, H]
mtp_hidden_ptr, # [n, H]
step_ptr, # [n, H]
last_ptr, # int64 [n] out
layer0_ptr, # int64 [n] out
H: tl.constexpr,
BH: tl.constexpr,
):
b = tl.program_id(0)
row = tl.load(meta_ptr + b)
last = tl.load(qsl_ptr + row + 1).to(tl.int64) - 1
l0 = tl.load(sampled_ptr + row * s_stride).to(tl.int64)
tl.store(ids_ptr + b, l0.to(ids_ptr.dtype.element_ty))
tl.store(last_ptr + b, last)
tl.store(layer0_ptr + b, l0)
for h0 in tl.static_range(0, H, BH):
c = h0 + tl.arange(0, BH)
m = c < H
tl.store(emb_ptr + b * H + c, tl.load(emb_w_ptr + l0 * H + c, mask=m).to(emb_ptr.dtype.element_ty), mask=m)
tl.store(mtp_hidden_ptr + b * H + c, tl.load(hidden_ptr + last * H + c, mask=m), mask=m)
tl.store(step_ptr + b * H + c, tl.zeros([BH], dtype=step_ptr.dtype.element_ty), mask=m)
@triton.jit
def _post_kernel(
meta_ptr,
n,
last_ptr,
layer0_ptr,
frame_ptr, # [>=n, H] MTP frame embeddings
eager_ptr, # [R, H]
codes_ptr, # [>=n, Q]
codes_out_ptr, # [T, Q]
input_ids_ptr, # [T] this step's input ids
valid_out_ptr, # [T]
valid_ptr, # [n] bool out
fa_ptr, # [T] first_audio output or dummy
fa_valid_ptr, # [R] bool or dummy
vocab,
H: tl.constexpr,
Q: tl.constexpr,
QP: tl.constexpr,
BH: tl.constexpr,
WRITE_FA: tl.constexpr,
HAS_FA_VALID: tl.constexpr,
):
b = tl.program_id(0)
req = tl.load(meta_ptr + n + b)
prefill = tl.load(meta_ptr + 2 * n + b) != 0
last = tl.load(last_ptr + b)
l0 = tl.load(layer0_ptr + b)
for h0 in tl.static_range(0, H, BH):
c = h0 + tl.arange(0, BH)
m = c < H
v = tl.load(frame_ptr + b * H + c, mask=m)
tl.store(eager_ptr + req * H + c, v.to(eager_ptr.dtype.element_ty), mask=m)
q = tl.arange(0, QP)
qm = q < Q
cv = tl.load(codes_ptr + b * Q + q, mask=qm)
tl.store(codes_out_ptr + last * Q + q, cv.to(codes_out_ptr.dtype.element_ty), mask=qm)
inp = tl.load(input_ids_ptr + last).to(tl.int64)
in_valid = ((inp >= 0) & (inp < vocab)) | prefill
valid = (l0 >= 0) & (l0 < vocab) & in_valid
tl.store(valid_out_ptr + last, valid.to(valid_out_ptr.dtype.element_ty))
tl.store(valid_ptr + b, valid)
if WRITE_FA:
scheduled = tl.load(meta_ptr + 3 * n + b) != 0
if HAS_FA_VALID:
scheduled = scheduled & (tl.load(fa_valid_ptr + req) != 0)
else:
scheduled = scheduled & False
tl.store(fa_ptr + last, scheduled.to(fa_ptr.dtype.element_ty))
def eager_pre(meta, n, qsl, sampled, hidden, emb_w, ids, emb, mtp_hidden, step):
last = torch.empty(n, dtype=torch.long, device=hidden.device)
layer0 = torch.empty(n, dtype=torch.long, device=hidden.device)
H = hidden.shape[-1]
_pre_kernel[(n,)](
meta, n, qsl, sampled, sampled.stride(0), hidden, emb_w, ids, emb, mtp_hidden, step, last, layer0,
H=H, BH=min(1024, triton.next_power_of_2(H)),
) # fmt: skip
return last, layer0
def eager_post(meta, n, last, layer0, frames, eager, codes, codes_out, input_ids, valid_out, fa, fa_valid, vocab):
valid = torch.empty(n, dtype=torch.bool, device=last.device)
H = eager.shape[-1]
Q = codes_out.shape[-1]
dummy = valid
_post_kernel[(n,)](
meta, n, last, layer0, frames, eager, codes, codes_out, input_ids, valid_out, valid,
fa if fa is not None else dummy, fa_valid if fa_valid is not None else dummy, int(vocab),
H=H, Q=Q, QP=triton.next_power_of_2(Q), BH=min(1024, triton.next_power_of_2(H)),
WRITE_FA=fa is not None, HAS_FA_VALID=fa_valid is not None,
) # fmt: skip
return valid
@@ -41,6 +41,7 @@ from vllm_omni.worker_v2.model_states.eager_mtp import EagerMTPState
from vllm_omni.worker_v2.model_states.intermediate_buffer import (
OmniIntermediateBuffer,
)
from vllm_omni.worker_v2.streaming_audio import StreamingAudioOutput
logger = init_logger(__name__)
@@ -85,6 +86,9 @@ def _make_safe_get_rope(orig_get_rope):
return _safe_get_rope
_NO_SEED = object()
class OmniModelState(DefaultModelState):
"""Generic Omni ``ModelState`` — works for **all** Omni model stages.
@@ -146,7 +150,7 @@ class OmniModelState(DefaultModelState):
self.have_multimodal_outputs: bool = getattr(model, "have_multimodal_outputs", False)
self._decode_preprocess = self._resolve_decode_preprocess(model)
self._decode_preprocess_is_identity = bool(getattr(model, "mrv2_decode_preprocess_is_identity", False))
self._mtp_generators: dict[str, torch.Generator] = {}
self._mtp_generators: dict[str, torch.Generator | None] = {}
# Talker's codec_embedding dim may differ from hf_text_config.hidden_size; probe real dim.
self._embed_dim = self._get_embed_dim(model, device) if self.has_preprocess else 0
@@ -167,6 +171,10 @@ class OmniModelState(DefaultModelState):
self._mtp_offsets: torch.Tensor | None = None
self._mtp_sample_uniforms: torch.Tensor | None = None
self._mtp_runner: Any | None = None
# Talker stream decode: each request's next frame position, and the
# side-stream event the step's PCM output copy must wait on.
self._stream_pos: dict[str, int] = {}
self._stream_decode_event: torch.cuda.Event | None = None
if self._embed_dim > 0 and hasattr(model, "mtp"):
max_bs = max_num_reqs
self._mtp_input_ids = torch.zeros(max_bs, dtype=torch.long, device=device)
@@ -218,6 +226,17 @@ class OmniModelState(DefaultModelState):
input_batch, text_hidden, sampled_token_ids, multimodal_outputs, mtp_batch_descriptor_dispatcher
)
def prepare_streaming_audio_output(
self, input_batch: InputBatch, req_states: RequestState, outputs: dict[str, Any]
) -> StreamingAudioOutput | None:
return self._eager_state.prepare_audio_output(input_batch, req_states, outputs)
def on_requests_finished(self, req_ids: set[str]) -> None:
self._eager_state.finish_audio(req_ids)
def on_request_preempted(self, req_id: str, req_index: int) -> None:
self._eager_state.suspend_audio(req_id, req_index)
def custom_sampler(self, sampler: Any) -> tuple[Any, Any] | None:
"""Let the model replace or wrap the MRv2 sampler (``mrv2_custom_sampler``)."""
hook = getattr(self.model, "mrv2_custom_sampler", None)
@@ -372,6 +391,7 @@ class OmniModelState(DefaultModelState):
def add_request(self, req_index: int, new_req_data: NewRequestData) -> None:
super().add_request(req_index, new_req_data)
self.intermediate_buffer.add_request(req_index, new_req_data)
self._eager_state.resume_audio(new_req_data.req_id, req_index)
self._initialize_upstream_warmup_buffer(req_index, new_req_data.req_id)
def _initialize_upstream_warmup_buffer(self, req_index: int, req_id: str) -> None:
@@ -407,6 +427,7 @@ class OmniModelState(DefaultModelState):
req_id = self.intermediate_buffer.buffers[req_index].get("req_id")
if req_id is not None:
getattr(self, "_mtp_generators", {}).pop(req_id, None)
self._stream_pos.pop(req_id, None)
getattr(self, "_first_audio_requests", set()).discard(req_id)
getattr(self, "_eager_ready", {}).pop(req_index, None)
getattr(self, "_eager_settled", {}).pop(req_index, None)
@@ -427,12 +448,18 @@ class OmniModelState(DefaultModelState):
for_capture: bool = False,
ubatch_idx: int = 0,
) -> dict[str, Any]:
if for_capture and input_batch.max_query_len is None:
if (
for_capture
and input_batch.max_query_len is None
and not self.vllm_config.compilation_config.cudagraph_mode.separate_routine()
):
# vLLM 0.30 distributes dummy tokens evenly across requests. For
# an unconstrained FULL graph that split is not a query-length
# bound: replay may put the entire token bucket in one request.
# Attention launch parameters are fixed at capture, so use the
# bucket's worst-case query length, not the dummy per-row length.
# Separate decode graphs must retain their uniform query bound:
# FA3's captured GQA layout must match the runtime AOT schedule.
# Keep explicit bounds (e.g. varlen decode) and runtime metadata.
input_batch = replace(input_batch, max_query_len=input_batch.num_tokens)
return super().prepare_attn(
@@ -464,7 +491,7 @@ class OmniModelState(DefaultModelState):
mm_embeds, is_mm_embed = self.gather_mm_embeddings(input_batch)
kwargs: dict[str, Any] = {"multimodal_embeddings": mm_embeds, "is_multimodal": is_mm_embed}
if mm_embeds:
kwargs["query_start_loc"] = input_batch.query_start_loc_np.tolist()
kwargs["query_start_loc"] = input_batch.query_start_loc_np[: input_batch.num_reqs + 1].tolist()
embeds = self.model.embed_input_ids(input_batch.input_ids[: input_batch.num_tokens], **kwargs)
inputs_embeds = self.encoder_runner.inputs_embeds
inputs_embeds[: embeds.shape[0]] = embeds
@@ -673,6 +700,7 @@ class OmniModelState(DefaultModelState):
preprocess_entries: list[tuple[int, int, int, int, dict[str, Any], bool]] = []
settled = self._eager_settled if self._eager_fastpath else None
settled_rows: list[tuple[int, int, int, str]] = []
replay_rows: list[tuple[int, int, str, bool]] = []
# Declared identity decode has no per-row updates or hook work.
skip_decode_rows = self._decode_preprocess_is_identity and not self._eager_mtp
is_prefilling_np = getattr(input_batch, "is_prefilling_np", None) if skip_decode_rows else None
@@ -684,6 +712,20 @@ class OmniModelState(DefaultModelState):
continue
start = int(input_batch.query_start_loc_np[i])
n_tok = int(input_batch.num_scheduled_tokens[i])
if (
self._eager_mtp
and self.model.stream_decoder is not None
and self._eager_state.replay_inputs(
buf["req_id"],
req_idx,
int(input_batch.num_computed_tokens_np[i]),
input_ids[start : start + n_tok],
embeds[start : start + n_tok],
)
):
if input_batch.num_computed_prefill_tokens_np[i] + n_tok >= input_batch.prefill_len_np[i]:
replay_rows.append((i, req_idx, buf["req_id"], True))
continue
if settled and n_tok == 1 and settled.get(req_idx) == buf["req_id"]:
settled_rows.append((i, req_idx, start, buf["req_id"]))
continue
@@ -725,7 +767,8 @@ class OmniModelState(DefaultModelState):
if not is_prefill
or int(info.get("_omni_num_computed_tokens", 0)) + n_tok >= int(info.get("_omni_prompt_len", 0))
]
+ [(i, req_idx, str(req_id), False) for i, req_idx, _start, req_id in settled_rows],
+ [(i, req_idx, str(req_id), False) for i, req_idx, _start, req_id in settled_rows]
+ replay_rows,
input_ids,
)
@@ -760,7 +803,7 @@ class OmniModelState(DefaultModelState):
batch_offsets = None
else:
# A pageable host tensor would block on the stream here.
batch_offsets = torch.as_tensor(starts, device=input_ids.device, dtype=torch.long)
batch_offsets = index_to_device(starts, input_ids.device)
batch_ids = input_ids.index_select(0, batch_offsets)
batch_embeds = embeds.index_select(0, batch_offsets)
@@ -866,6 +909,9 @@ class OmniModelState(DefaultModelState):
prepacked_mtp_inputs=prepacked_mtp_inputs,
)
if self._eager_mtp:
self._eager_state.record_inputs(input_batch, embeds)
def publish_sampled_embeddings(
self, input_batch: InputBatch, sampled_token_ids: torch.Tensor
) -> tuple[dict[str, Any], torch.cuda.Event] | None:
@@ -890,15 +936,15 @@ class OmniModelState(DefaultModelState):
finishing = computed + scheduled >= input_batch.prefill_len_np[:num_reqs]
kept = ~input_batch.is_prefilling_np[:num_reqs] | finishing
rows = np.flatnonzero(kept).tolist()
if not rows:
return None
device = sampled_token_ids.device
first = sampled_token_ids.reshape(num_reqs, -1)[:, 0].index_select(0, index_to_device(rows, device))
embeds = self.model.embed_input_ids(first.long())
empty = torch.empty(0, dtype=embeds.dtype)
sampled: list[torch.Tensor] = [empty] * num_reqs
for k, row in enumerate(rows):
sampled[row] = embeds[k : k + 1]
# Preserve the empty per-row prefill marker even when every request
# is prefilling; absence would look like a broken decode handoff.
sampled: list[torch.Tensor] = [torch.empty(0)] * num_reqs
if rows:
first = sampled_token_ids.reshape(num_reqs, -1)[:, 0].index_select(0, index_to_device(rows, device))
embeds = self.model.embed_input_ids(first.long())
for k, row in enumerate(rows):
sampled[row] = embeds[k : k + 1]
done = torch.cuda.Event()
done.record()
extra: dict[str, Any] = {"embed": {"sampled": sampled}}
@@ -989,7 +1035,7 @@ class OmniModelState(DefaultModelState):
offsets.copy_(query_start_loc[:bsz], non_blocking=True)
return offsets
return torch.as_tensor([start for _i, start, _mtp in mtp_batches], device=device, dtype=torch.long)
return index_to_device([start for _i, start, _mtp in mtp_batches], device)
def _run_batched_mtp(
self,
@@ -1180,15 +1226,21 @@ class OmniModelState(DefaultModelState):
sampling_params: Any,
device: torch.device,
) -> torch.Generator | None:
resolve_seed = getattr(self.model, "get_mtp_seed", None)
seed = resolve_seed(sampling_params) if resolve_seed is not None else None
if seed is None:
return None
cache = getattr(self, "_mtp_generators", None)
if cache is None:
cache = {}
self._mtp_generators = cache
generator = cache.get(req_id, _NO_SEED)
if generator is None:
# Resolved earlier: this request has no seed.
return None
if generator is not _NO_SEED and generator.device == device:
return generator
resolve_seed = getattr(self.model, "get_mtp_seed", None)
seed = resolve_seed(sampling_params) if resolve_seed is not None else None
if seed is None:
cache[req_id] = None
return None
generator = cache.get(req_id)
if generator is None or generator.device != device:
generator = torch.Generator(device=device)
+70 -7
View File
@@ -14,6 +14,7 @@ Extends ``OmniGPUModelRunner`` with:
from __future__ import annotations
from contextlib import nullcontext
from functools import partial
from typing import Any, cast
import numpy as np
@@ -37,6 +38,7 @@ from vllm_omni.utils.mm_outputs import partition_flat_payload
from vllm_omni.worker_v2.omni_model_runner import OmniGPUModelRunner
from vllm_omni.worker_v2.omni_sampler import sample_with_output
from vllm_omni.worker_v2.output_snapshot import PackedOutputSnapshot, RequestOutputSnapshot, pack_output_snapshot
from vllm_omni.worker_v2.streaming_audio import StreamingAudioOutput
logger = init_logger(__name__)
_ASYNC_MM_SNAPSHOT_MAX_BUCKETS_PER_SLOT = 64
@@ -136,6 +138,23 @@ class OmniARModelRunner(OmniGPUModelRunner):
# sample_tokens: OmniOutput handling + pooler_output + async D2H
# ------------------------------------------------------------------
def sample(self, hidden_states, input_batch, grammar_output):
# An explicitly declared model-state hook may return already determined
# tokens. Unsupported sampling features retain the upstream path.
sample_determined = getattr(type(self.model_state), "sample_determined_tokens", None)
if (
sample_determined is not None
and grammar_output is None
and self.batch_sharder is None
and self.pp_handler is None
and input_batch.num_draft_tokens == 0
and input_batch.num_reqs > 0
):
output = sample_determined(self.model_state, input_batch, self.sampler)
if output is not None:
return output, output.num_sampled, output.num_rejected
return super().sample(hidden_states, input_batch, grammar_output)
@torch.inference_mode()
@step_eplb_after()
def sample_tokens(
@@ -259,6 +278,13 @@ class OmniARModelRunner(OmniGPUModelRunner):
model_runner_output.kv_extracted_req_ids = kv_extracted
model_runner_output._async_chunk = bool(getattr(self.model_config, "async_chunk", False))
prepare_streaming = getattr(self.model_state, "prepare_streaming_audio_output", None)
streaming_audio = (
prepare_streaming(input_batch, self.req_states, multimodal_outputs)
if need_pooler and multimodal_outputs and callable(prepare_streaming)
else None
)
# --- Async D2H via OmniAsyncOutput ---
materialize_native = self._uses_native_output_materializer()
async_output = OmniAsyncOutput(
@@ -275,6 +301,7 @@ class OmniARModelRunner(OmniGPUModelRunner):
finalize_multimodal=sampling_output.finalize_multimodal,
check_ep_fault=self.check_ep_fault,
pending_aux_output=pending_aux_output,
streaming_audio=streaming_audio,
extra_multimodal_outputs=extra_outputs,
)
self._release_multimodal_snapshot(snapshot_slot, async_output.copy_event)
@@ -306,6 +333,15 @@ class OmniARModelRunner(OmniGPUModelRunner):
def _retain_multimodal_outputs(self, outputs: dict[str, Any]) -> dict[str, Any]:
if not bool(getattr(self.model_config, "async_chunk", False)) or not outputs:
return outputs
if getattr(self.model, "mm_outputs_fresh_per_step", False):
# Freshly allocated each step and filled after sampling; nothing
# overwrites them before the host copy.
return outputs
# A producer-side PackedOutputSnapshot already owns its device slabs
# for this forward and carries the event that makes them visible to
# the output copy stream. Repacking it would add a second GPU copy.
if isinstance(outputs, PackedOutputSnapshot):
return outputs
slot_index = self._async_mm_snapshot_cursor
if self._async_mm_snapshot_pending[slot_index]:
raise RuntimeError("Async multimodal snapshot ring exhausted before sample_tokens().")
@@ -525,6 +561,12 @@ def _async_copy_mm_value(
for key, val in value.items()
}
if isinstance(value, list):
if len(value) > 1 and isinstance(value[0], torch.Tensor) and value[0].device.type == "cpu":
first = value[0]
if all(val is first for val in value):
# One shared per-step host tensor (e.g. every request's sample
# rate): one copy serves all entries.
return [_async_copy_tensor(first)] * len(value)
return [
_async_copy_mm_value(
val,
@@ -556,6 +598,8 @@ def _async_copy_mm(
if not mm_outputs:
return {}
if isinstance(mm_outputs, PackedOutputSnapshot):
if mm_outputs.producer_event is not None:
mm_outputs.producer_event.wait(copy_stream)
return mm_outputs.copy_to_cpu(
lambda tensor: _async_copy_tensor(tensor, copy_stream=copy_stream, pin_memory=pin_memory)
)
@@ -688,6 +732,7 @@ class OmniAsyncOutput(AsyncModelRunnerOutput):
finalize_multimodal: Any | None = None,
check_ep_fault: bool = False,
pending_aux_output: Any | None = None,
streaming_audio: StreamingAudioOutput | None = None,
extra_multimodal_outputs: tuple[dict[str, Any], torch.cuda.Event] | None = None,
):
self.model_runner_output = model_runner_output
@@ -787,17 +832,31 @@ class OmniAsyncOutput(AsyncModelRunnerOutput):
self._hidden_cpu: torch.Tensor | None = None
self._mm_cpu: dict[str, Any] = {}
self._mm_snapshot: dict[str, Any] = {}
self._streaming_audio = (
streaming_audio.to_cpu(
copy_stream, partial(_async_copy_tensor, copy_stream=copy_stream, pin_memory=pin_memory)
)
if streaming_audio is not None
else None
)
if self._need_pooler and (self._async_chunk or self._finalize_multimodal is not None):
# CUDA graph replay reuses the model's output buffers. Take
# ownership directly in pinned host memory on the output copy
# stream so deferred finalization never performs a blocking
# D2H copy on the runner thread.
self._mm_snapshot = _async_copy_mm(
multimodal_outputs,
self._total_tokens,
copy_stream=copy_stream,
pin_memory=pin_memory,
)
if (
streaming_audio is None
or self._finalize_multimodal is not None
or extra_multimodal_outputs is not None
):
# PCM owns its request partition. Generic codes/meta are
# discarded unless a finalizer or extra payload needs them.
self._mm_snapshot = _async_copy_mm(
multimodal_outputs,
self._total_tokens,
copy_stream=copy_stream,
pin_memory=pin_memory,
)
if extra_multimodal_outputs:
# Produced after sampling on the producer stream; copy only
# once its completion event has been observed.
@@ -876,7 +935,9 @@ class OmniAsyncOutput(AsyncModelRunnerOutput):
pooler_client is not None and len(pooler_client) != self._num_reqs
):
raise ValueError("Model-owned output snapshot does not match the request batch")
else:
elif self._streaming_audio is None:
# In-stage PCM already owns its request partition. Building
# generic code payloads here would immediately discard them.
pooler_inter, pooler_client = OmniARModelRunner._build_async_chunk_outputs_from_mm(
self._mm_snapshot,
self._query_start_loc_np,
@@ -885,6 +946,8 @@ class OmniAsyncOutput(AsyncModelRunnerOutput):
self._total_tokens,
self._padded_total_tokens,
)
if self._streaming_audio is not None:
pooler_inter, pooler_client = None, self._streaming_audio.get_output()
self.model_runner_output.pooler_output = None if self._async_chunk else pooler_inter
self.model_runner_output.inter_stage_outputs = pooler_inter
self.model_runner_output.multimodal_outputs = (
+13
View File
@@ -437,6 +437,10 @@ class OmniGPUModelRunner(GPUModelRunner):
capture_first_frame = getattr(self.model, "capture_first_frame_graphs", None)
if callable(capture_first_frame):
capture_first_frame()
capture_stream = getattr(self.model, "capture_stream_decode_graphs", None)
if callable(capture_stream):
sizes = [int(s) for s in self.model_state._get_mtp_capture_sizes()]
capture_stream(sorted(set(sizes + [1])))
return result
def _dispatch_mtp_batch_descriptor(self, num_mtp_reqs: int) -> Any:
@@ -742,7 +746,16 @@ class OmniGPUModelRunner(GPUModelRunner):
# Request-owned state outlives generation slots and chunk boundaries.
# Notify even if the last chunk already released its runner slot.
on_finished(finished)
finish_state = getattr(self.model_state, "on_requests_finished", None)
if finished and callable(finish_state):
finish_state(finished)
preempted = scheduler_output.preempted_req_ids
suspend_state = getattr(self.model_state, "on_request_preempted", None)
if preempted and callable(suspend_state):
for req_id in preempted - finished:
idx = self.req_states.req_id_to_index.get(req_id)
if idx is not None:
suspend_state(req_id, idx)
all_done = finished | preempted if preempted else finished
for req_id in all_done:
idx = self.req_states.req_id_to_index.get(req_id)
+7 -87
View File
@@ -1,91 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Owned, dtype-grouped snapshots for asynchronous runner outputs."""
"""Compatibility imports for the shared model/runner output snapshot contract."""
from __future__ import annotations
from vllm_omni.model_executor.output_snapshot import (
PackedOutputSnapshot,
RequestOutputSnapshot,
pack_output_snapshot,
)
from collections import defaultdict
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import torch
from torch.utils._pytree import tree_flatten, tree_unflatten
@dataclass(frozen=True)
class RequestOutputSnapshot:
"""Already partitioned, CPU-owned payloads in the current request order.
Model finalizers may return this after D2H completes to avoid recursively
cloning and partitioning data whose request ownership is already known.
"""
inter_stage: list[dict[str, Any] | None]
client: list[dict[str, Any] | None] | None = None
class PackedOutputSnapshot(dict):
"""A normal payload mapping with an internal batched-copy plan.
The runner's snapshot-slot event protects the device slabs until D2H is
complete. Host slabs are allocated per output, so downstream consumers can
retain their views without depending on reuse of the device ring slot.
"""
def __init__(self, leaves: list[Any], spec: Any, groups: list[tuple[list[int], torch.Tensor]]) -> None:
super().__init__(tree_unflatten(leaves, spec))
self._leaves = leaves
self._spec = spec
self._groups = groups
def copy_to_cpu(self, copy_tensor: Callable[[torch.Tensor], torch.Tensor]) -> dict[str, Any]:
leaves = list(self._leaves)
for indices, slab in self._groups:
cpu = copy_tensor(slab)
offset = 0
for index in indices:
value = leaves[index]
size = value.numel()
leaves[index] = cpu.narrow(0, offset, size).view(value.shape)
offset += size
return tree_unflatten(leaves, self._spec)
def pack_output_snapshot(
payload: dict[str, Any], slot: dict[tuple[Any, ...], torch.Tensor], *, max_buckets: int
) -> PackedOutputSnapshot | None:
"""Copy tensor leaves once per dtype/device, retaining their exact values.
No CUDA synchronization is introduced here. The caller must select the
producer stream and wait for the previous consumer before reusing a slot.
"""
leaves, spec = tree_flatten(payload)
grouped: dict[tuple[Any, ...], list[int]] = defaultdict(list)
for index, value in enumerate(leaves):
if isinstance(value, torch.Tensor):
# Preserve the existing per-tensor path for unusual layouts.
if value.layout != torch.strided or value.is_quantized:
return None
grouped[(value.dtype, value.device)].append(index)
groups = []
for (dtype, device), indices in grouped.items():
values = [leaves[index].detach().reshape(-1) for index in indices]
size = sum(value.numel() for value in values)
key = ("packed-output", dtype, device, size)
slab = slot.get(key)
if slab is None:
slab = torch.empty(size, dtype=dtype, device=device)
if len(slot) < max_buckets:
slot[key] = slab
if len(values) == 1:
slab.copy_(values[0])
else:
torch.cat(values, out=slab)
offset = 0
for index, value in zip(indices, values):
shape = leaves[index].shape
leaves[index] = slab.narrow(0, offset, value.numel()).view(shape)
offset += value.numel()
groups.append((indices, slab))
return PackedOutputSnapshot(leaves, spec, groups)
__all__ = ["PackedOutputSnapshot", "RequestOutputSnapshot", "pack_output_snapshot"]
+154
View File
@@ -0,0 +1,154 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Request-owned PCM accumulation for a stage that decodes audio in place."""
from __future__ import annotations
import threading
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
import numpy as np
import torch
from vllm_omni.data_entry_keys import FIRST_AUDIO_REQUIRED_KEY
@dataclass
class AudioRequest:
samples_per_frame: int
chunk_frames: int
active: bool = True
emitted: bool = False
direct_first_pending: bool = False
first_audio_required: bool = False
pending: list[torch.Tensor | np.ndarray] = field(default_factory=list)
pending_samples: int = 0
lock: threading.Lock = field(default_factory=threading.Lock)
def accept_first_audio(self) -> None:
with self.lock:
if self.active:
self.direct_first_pending = True
def push(self, pcm: torch.Tensor | np.ndarray, ended: bool) -> torch.Tensor | None:
with self.lock:
if not self.active:
return None
size = pcm.numel() if isinstance(pcm, torch.Tensor) else pcm.size
if self.direct_first_pending:
self.direct_first_pending = False
if size:
pcm = pcm[self.samples_per_frame :]
size = max(0, size - self.samples_per_frame)
self.emitted = True
self.first_audio_required = True
if size:
self.pending.append(pcm)
self.pending_samples += size
frames = self.pending_samples // self.samples_per_frame
out = None
if frames and (ended or not self.emitted or frames >= self.chunk_frames):
if all(isinstance(part, np.ndarray) for part in self.pending):
array = np.concatenate(self.pending) if len(self.pending) > 1 else self.pending[0]
out = torch.from_numpy(array)
else:
parts = [torch.from_numpy(part) if isinstance(part, np.ndarray) else part for part in self.pending]
out = torch.cat(parts) if len(parts) > 1 else parts[0]
self.pending.clear()
self.pending_samples = 0
self.emitted = True
if ended:
self.active = False
self.pending.clear()
self.pending_samples = 0
return out
def finish(self) -> None:
with self.lock:
self.active = False
self.pending.clear()
self.pending_samples = 0
class StreamingAudioBuffer:
def __init__(self, samples_per_frame: int, chunk_frames: int) -> None:
self.samples_per_frame = samples_per_frame
self.chunk_frames = chunk_frames
self.requests: dict[str, AudioRequest] = {}
def add(self, request_id: str) -> AudioRequest:
if request_id not in self.requests:
self.requests[request_id] = AudioRequest(self.samples_per_frame, self.chunk_frames)
return self.requests[request_id]
def finish(self, request_ids: Iterable[str]) -> None:
for request_id in request_ids:
state = self.requests.pop(request_id, None)
if state is not None:
# Already queued outputs retain this object, never a fresh lookup
# by ID. A late copy cannot resurrect a cancelled request.
state.finish()
@dataclass
class StreamingAudioOutput:
wav: torch.Tensor
valid: torch.Tensor
sample_rate: torch.Tensor
event: torch.cuda.Event | None
query_start_loc: np.ndarray
requests: list[AudioRequest | None]
length_end: np.ndarray
def to_cpu(
self,
copy_stream: torch.cuda.Stream,
copy_tensor: Callable[[torch.Tensor], torch.Tensor],
) -> StreamingAudioOutput:
if self.event is not None:
copy_stream.wait_event(self.event)
return StreamingAudioOutput(
copy_tensor(self.wav),
copy_tensor(self.valid),
self.sample_rate,
None,
self.query_start_loc,
self.requests,
self.length_end,
)
def get_output(self) -> list[dict[str, torch.Tensor] | None]:
valid = self.valid.numpy().astype(bool)
# Each D2H batch owns its host allocation. NumPy slices retain that
# backing tensor while a request accumulates PCM across steps; no
# per-request Torch views are needed until an audio chunk is emitted.
# Keep the tensor path for dtypes NumPy cannot represent (e.g. BF16).
wav = self.wav.numpy() if self.wav.dtype in (torch.float16, torch.float32, torch.float64) else None
output: list[dict[str, torch.Tensor] | None] = []
required_marker = None
for i, state in enumerate(self.requests):
payload = None
start, end = self.query_start_loc[i : i + 2]
if state is not None and end > start:
if wav is not None:
if end - start == 1:
pcm = wav[start:end].reshape(-1) if valid[start] else wav[0:0].reshape(-1)
else:
pcm = wav[start:end][valid[start:end]].reshape(-1)
elif end - start == 1:
pcm = self.wav[start:end].reshape(-1) if valid[start] else self.wav.new_empty(0)
else:
pcm = self.wav[start:end][torch.from_numpy(valid[start:end])].reshape(-1)
ended = bool(self.length_end[i]) or not valid[end - 1]
chunk = state.push(pcm, ended)
if chunk is not None:
payload = {"model_outputs": chunk, "sr": self.sample_rate}
if state.first_audio_required and (chunk is not None or ended):
if required_marker is None:
required_marker = torch.tensor(True)
if payload is None:
payload = {}
payload[FIRST_AUDIO_REQUIRED_KEY] = required_marker
output.append(payload)
return output