[Model] Optimize MOSS Local 1.5 MRV2 serving and progressive chunks (#8213)

Signed-off-by: Sy03 <1370724210@qq.com>
Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
Sy03andYueqian Lin authored and GitHub committed 2026-10-02 18:03:14 +00:00
1 parent 527982d886
commit 3bc3f1a7d0
70 files changed
+8519 -347

No files matched your search

@@ -539,11 +539,15 @@ class RingKVCache:
end_offset = self.end_offset.index_select(0, slots)
row_cache = self.cache.index_select(1, slots)
indexes = torch.arange(T, device=end_offset.device, dtype=end_offset.dtype)
# Upsampling can make a chunk longer than the ring. Only the last
# capacity tokens survive; writing all T tokens gives scatter_
# duplicate destinations and nondeterministic cache contents.
write_length = min(T, self.capacity)
indexes = torch.arange(T - write_length, T, device=end_offset.device, dtype=end_offset.dtype)
indexes = (indexes + end_offset.view(-1, 1)) % self.capacity
scatter_indexes = indexes.view(B, 1, T, 1).expand(-1, H, T, D)
row_cache[0].scatter_(2, scatter_indexes, k)
row_cache[1].scatter_(2, scatter_indexes, v)
scatter_indexes = indexes.view(B, 1, write_length, 1).expand(-1, H, write_length, D)
row_cache[0].scatter_(2, scatter_indexes, k[:, :, -write_length:])
row_cache[1].scatter_(2, scatter_indexes, v[:, :, -write_length:])
# Live and graph-padding rows always map to distinct slots. The
# latter map only to scratch state, so this write cannot corrupt a
# request even though dense graph operators still execute it.
@@ -729,7 +733,13 @@ class MossAudioTokenizerMultiheadAttention(StreamingModule):
if self.context is None:
capacity = self.weights_per_step if self.weights_per_step else 1024
else:
capacity = self.context
# RingKVCache.complete writes a whole chunk before attending, so a
# ring of exactly ``context`` entries lets a T-token chunk evict up
# to T tokens of history that the chunk's own queries should still
# see (and, for T > context, evict part of the chunk itself).
# ``_ring_headroom`` (max chunk tokens at this layer) keeps every
# in-window key resident; 0 preserves the legacy truncation.
capacity = self.context + int(getattr(self, "_ring_headroom", 0))
kv_cache = RingKVCache(
batch_size,
@@ -791,29 +801,63 @@ class MossAudioTokenizerMultiheadAttention(StreamingModule):
if self.rope:
q, k = self.rope(q, k, offset, time_before_heads=False)
k, v, pos_k = self._complete_kv(k, v, execution_context)
pos_k = pos_k[:, None]
if self.causal:
pos_q = offset.view(-1, 1, 1) + torch.arange(T, device=q.device, dtype=torch.long).view(-1, 1)
delta = pos_q - pos_k
attn_bias = (pos_k >= 0) & (delta >= 0)
if self.context is not None:
attn_bias = attn_bias & (delta < self.context)
attn_bias = attn_bias[:, None]
slot_attention = getattr(self, "_slot_attention", None)
slot_attention_rows = getattr(self, "_slot_attention_rows", None)
advance_kv_offset = False
slot_path = state is not None and execution_context is not None and self.causal
if slot_path and slot_attention_rows is not None:
# One launch: the gathered MHA offset equals the ring's end_offset
# for every slot, and both advance together below.
valid_lengths = execution_context.valid_rows.to(dtype=torch.int32) * T
x = slot_attention_rows(
q,
k,
v,
state.kv_cache.cache,
offset,
execution_context.state_slot_ids,
valid_lengths,
self.context if self.context is not None else -1,
)
advance_kv_offset = True
elif slot_attention is not None and slot_path:
# Current streaming batches use one exact T. Padding rows own
# scratch slots and must not advance persistent attention state.
valid_lengths = execution_context.valid_rows.to(dtype=torch.int32) * T
x = slot_attention(
q,
k,
v,
state.kv_cache.cache,
state.kv_cache.end_offset,
execution_context.state_slot_ids,
valid_lengths,
self.context if self.context is not None else -1,
)
else:
attn_bias = None
k, v, pos_k = self._complete_kv(k, v, execution_context)
pos_k = pos_k[:, None]
streaming_attention = getattr(self, "_streaming_attention", None)
if (
streaming_attention is not None
and attn_bias is not None
and q.dtype == torch.bfloat16
and q.shape[-1] == 64
):
x = streaming_attention(q, k, v, attn_bias)
else:
x = F.scaled_dot_product_attention(q, k, v, attn_bias, dropout_p=0.0)
if self.causal:
pos_q = offset.view(-1, 1, 1) + torch.arange(T, device=q.device, dtype=torch.long).view(-1, 1)
delta = pos_q - pos_k
attn_bias = (pos_k >= 0) & (delta >= 0)
if self.context is not None:
attn_bias = attn_bias & (delta < self.context)
attn_bias = attn_bias[:, None]
else:
attn_bias = None
streaming_attention = getattr(self, "_streaming_attention", None)
if (
streaming_attention is not None
and attn_bias is not None
and q.dtype == torch.bfloat16
and q.shape[-1] == 64
):
x = streaming_attention(q, k, v, attn_bias)
else:
x = F.scaled_dot_product_attention(q, k, v, attn_bias, dropout_p=0.0)
x = x.transpose(1, 2).reshape(B, T, self.embed_dim)
x = apply_weights_per_step(self.out_projs, self.weights_per_step_schedule, x, offset_cpu)
@@ -824,6 +868,8 @@ class MossAudioTokenizerMultiheadAttention(StreamingModule):
else:
next_offset = torch.where(execution_context.valid_rows, offset + T, offset)
state.offset.index_copy_(0, execution_context.state_slot_ids, next_offset)
if advance_kv_offset:
state.kv_cache.end_offset.index_copy_(0, execution_context.state_slot_ids, next_offset)
return x
@@ -1624,6 +1670,7 @@ class MossAudioTokenizerModel(MossAudioTokenizerPreTrainedModel):
decoder_kwargs_list = copy.deepcopy(config.decoder_kwargs)
self.decoder = nn.ModuleList()
decoder_input_frame_rate = current_frame_rate
for decoder_kwargs_i in decoder_kwargs_list:
decoder_kwargs_i = dict(decoder_kwargs_i)
if decoder_kwargs_i["module_type"] == "PatchedPretransform":
@@ -1638,6 +1685,11 @@ class MossAudioTokenizerModel(MossAudioTokenizerPreTrainedModel):
context=int(round(current_frame_rate * context_duration)),
)
)
# Tokens this transformer sees per input code frame. Streaming
# ring headroom is sized from it (see initialize_decoder_state_pool).
self.decoder[-1].tokens_per_input_frame = max(
1, int(round(current_frame_rate / decoder_input_frame_rate))
)
current_frame_rate *= self.decoder[-1].downsample_ratio
expected_output_frame_rate = float(self.sampling_rate * channel_interleave_factor)
@@ -1731,10 +1783,29 @@ class MossAudioTokenizerModel(MossAudioTokenizerPreTrainedModel):
self._decoder_state_capacity = 0
self._decoder_slot_offsets = None
def initialize_decoder_state_pool(self, state_capacity: int, scratch_capacity: int = 0) -> None:
"""Allocate persistent decoder state independently of execution B."""
if state_capacity <= 0 or scratch_capacity < 0:
raise ValueError(f"Invalid decoder state capacities: state={state_capacity}, scratch={scratch_capacity}.")
def initialize_decoder_state_pool(
self, state_capacity: int, scratch_capacity: int = 0, chunk_frames: int = 0
) -> None:
"""Allocate persistent decoder state independently of execution B.
``chunk_frames`` > 0 sizes every decoder attention ring as
``context + chunk_frames * tokens_per_input_frame`` so that a chunk of
up to ``chunk_frames`` code frames never evicts keys inside its own
causal window; chunked streaming then matches whole-sequence decoding.
``chunk_frames`` = 0 keeps the legacy ``context``-sized rings.
"""
if state_capacity <= 0 or scratch_capacity < 0 or chunk_frames < 0:
raise ValueError(
"Invalid decoder state capacities: "
f"state={state_capacity}, scratch={scratch_capacity}, chunk_frames={chunk_frames}."
)
for module in self.decoder:
if not isinstance(module, MossAudioTokenizerProjectedTransformer):
continue
tokens_per_frame = int(getattr(module, "tokens_per_input_frame", 1))
for attention in module.modules():
if isinstance(attention, MossAudioTokenizerMultiheadAttention):
attention._ring_headroom = chunk_frames * tokens_per_frame
self._start_streaming(state_capacity + scratch_capacity, decoder_only=True)
self._decoder_state_capacity = state_capacity + scratch_capacity
@@ -81,15 +81,31 @@ class CUDAGraphStreamingDecoderWrapper:
frame_sizes: list[int],
num_quantizers: int,
vllm_config: VllmConfig,
scratch_base: int | None = None,
private_pool: bool = False,
compiled_decode: nn.Module | None = None,
) -> None:
self.codec = codec
self.state_capacity = int(state_capacity)
# Graph padding rows use scratch slots [scratch_base, scratch_base+B).
# A wrapper replaying concurrently with another needs its own scratch
# range and graph memory pool.
self.scratch_base = self.state_capacity if scratch_base is None else int(scratch_base)
self._private_pool = bool(private_pool)
# Graphs bake in the cuBLAS workspace of the stream they were captured
# on, and torch.cuda.graph shares one default capture stream. Split-K
# GEMMs synchronize through that workspace, so two graphs replaying
# concurrently from one capture stream can spin on each other forever.
self._capture_stream: torch.cuda.Stream | None = None
self.batch_sizes = sorted({int(size) for size in batch_sizes if 0 < int(size) <= state_capacity})
self.frame_sizes = sorted({int(size) for size in frame_sizes if int(size) > 0})
self.num_quantizers = int(num_quantizers)
self.graphs: dict[tuple[int, int], _CapturedStreamingDecodeGraph] = {}
self._pool = None
self._warmed_up = False
if compiled_decode is not None:
self._compiled_decode: nn.Module | None = compiled_decode
return
# vLLM owns Inductor compilation; this wrapper remains the sole owner
# of CUDA Graph capture/replay because it understands persistent codec
# state slots. Disable vLLM's CUDA Graph layer to avoid nested graphs.
@@ -98,7 +114,7 @@ class CUDAGraphStreamingDecoderWrapper:
compile_config.compilation_config.cudagraph_mode = CUDAGraphMode.NONE
compile_config.compilation_config.static_forward_context = {}
with set_current_vllm_config(compile_config):
self._compiled_decode: nn.Module | None = _MossStreamingDecodeCompileAdapter(
self._compiled_decode = _MossStreamingDecodeCompileAdapter(
codec,
vllm_config=compile_config,
)
@@ -175,7 +191,7 @@ class CUDAGraphStreamingDecoderWrapper:
frame_size,
exc_info=True,
)
scratch_slots = self.state_capacity + torch.arange(
scratch_slots = self.scratch_base + torch.arange(
batch_size,
dtype=torch.long,
device=device,
@@ -206,10 +222,13 @@ class CUDAGraphStreamingDecoderWrapper:
device=device,
)
lengths = torch.zeros(batch_size, dtype=torch.long, device=device)
scratch_slots = self.state_capacity + torch.arange(batch_size, dtype=torch.long, device=device)
scratch_slots = self.scratch_base + torch.arange(batch_size, dtype=torch.long, device=device)
valid_rows = torch.zeros(batch_size, dtype=torch.bool, device=device)
stream = torch.cuda.Stream()
if self._private_pool and self._capture_stream is None:
self._capture_stream = torch.cuda.Stream(device=device)
# Warm up on the capture stream so its workspace exists before capture.
stream = self._capture_stream or torch.cuda.Stream()
stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(stream):
for _ in range(3):
@@ -219,9 +238,11 @@ class CUDAGraphStreamingDecoderWrapper:
self.codec.reset_decoder_state_slots(scratch_slots)
if self._pool is None:
self._pool = current_platform.get_global_graph_pool()
self._pool = (
torch.cuda.graph_pool_handle() if self._private_pool else current_platform.get_global_graph_pool()
)
graph = CUDAGraph()
with torch.cuda.graph(graph, pool=self._pool, capture_error_mode="thread_local"):
with torch.cuda.graph(graph, pool=self._pool, stream=self._capture_stream, capture_error_mode="thread_local"):
audio, audio_lengths = decode(codes, lengths, scratch_slots, valid_rows)
self.graphs[(batch_size, frame_size)] = _CapturedStreamingDecodeGraph(
@@ -272,7 +293,7 @@ class CUDAGraphStreamingDecoderWrapper:
entry.static_lengths.zero_()
entry.static_lengths[:actual_batch_size].fill_(int(frame_size))
entry.static_state_slot_ids.copy_(
self.state_capacity + torch.arange(batch_size, dtype=torch.long, device=entry.static_state_slot_ids.device)
self.scratch_base + torch.arange(batch_size, dtype=torch.long, device=entry.static_state_slot_ids.device)
)
entry.static_state_slot_ids[:actual_batch_size].copy_(state_slot_ids, non_blocking=True)
entry.static_valid_rows.zero_()
@@ -0,0 +1,333 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Decode a stream's first codec chunk as soon as Stage 1 receives it.
The Stage-1 engine loop only sees a new chunk between steps, and a step waits
for its codec graph to finish. A first chunk that arrives mid-step therefore
waits for the rest of that step, then for its own replay. This path takes the
first chunk from the receive thread, replays a small dedicated graph on its
own stream while the main step runs, and emits the audio straight to the
engine output queue. The main path later receives the same chunk, finds it
already decoded, and continues the stream from the state written here.
"""
from __future__ import annotations
import math
import queue
import threading
import time
from dataclasses import dataclass
from typing import Any
import torch
from vllm.logger import init_logger
from vllm_omni.platforms import current_omni_platform
from vllm_omni.worker_v2.first_audio_sender import FirstAudioSink, _PreparedDelivery
logger = init_logger(__name__)
class _SlotHandoff:
"""Orders the main path's first use of a slot after the fast decode."""
__slots__ = ("done", "event", "error")
def __init__(self) -> None:
self.done = threading.Event()
self.event: torch.cuda.Event | None = None
self.error: Exception | None = None
@dataclass
class _Job:
request_id: str
request_key: str
delivery: _PreparedDelivery
slot: int
codes: torch.Tensor # (n_vq, T) int64 on host
handoff: _SlotHandoff
class MossFirstChunkFastPath:
def __init__(
self,
session: Any,
wrapper: Any,
*,
n_vq: int,
frames: int,
codebook_size: int,
samples_per_frame: int,
n_channels: int,
sample_rate: torch.Tensor,
device: torch.device,
gate_main: bool = False,
handoff_timeout_s: float = 30.0,
) -> None:
if not math.isfinite(handoff_timeout_s) or handoff_timeout_s <= 0:
raise ValueError("handoff_timeout_s must be positive and finite")
self._handoff_timeout_s = float(handoff_timeout_s)
self._session = session
# When set, the main codec stream waits for an in-flight fast decode
# before its next replay, so the small first-chunk graph runs mostly
# uncontended instead of interleaving with a large regular replay.
self._gate_main = bool(gate_main)
self._inflight: torch.cuda.Event | None = None
self._wrapper = wrapper
self._n_vq = int(n_vq)
self.frames = int(frames)
self._codebook_size = int(codebook_size)
self._samples = int(frames) * int(samples_per_frame)
self._n_channels = int(n_channels)
self._sr = sample_rate
if device.index is None:
device = torch.device(device.type, torch.accelerator.current_device_index())
self._device = device
self._max_batch = max(wrapper.batch_sizes)
self._stream = torch.cuda.Stream(device=device, priority=-1)
self._host_codes = torch.zeros((self._n_vq, self._max_batch, self.frames), dtype=torch.long).pin_memory()
self._host_slots = torch.zeros(self._max_batch, dtype=torch.long).pin_memory()
audio_shape = (self._max_batch, self._n_channels, self._samples)
self._host_audio = torch.empty(audio_shape, dtype=torch.float32).pin_memory()
self._copied = torch.cuda.Event()
self._sink: FirstAudioSink | None = None
# Request key -> slot for chunks decoded here and not yet seen by the main path.
self._decoded: dict[str, int] = {}
# A failed output-queue handoff must be replayed from the already
# decoded samples. Re-decoding would advance the streaming state twice.
self._unsent_audio: dict[str, torch.Tensor] = {}
self._handoffs: dict[int, _SlotHandoff] = {}
self._lock = threading.Lock()
self._jobs: queue.SimpleQueue[_Job | None] = queue.SimpleQueue()
self._thread: threading.Thread | None = None
self._closed = False
self._worker_error: Exception | None = None
self._emitted = 0
self._batches = 0
self._decode_s = 0.0
def bind(self, sink: FirstAudioSink) -> None:
if not callable(getattr(sink, "prepare", None)):
raise TypeError("The codec first-chunk sink requires prepare(request_ids)")
with self._lock:
if self._closed:
raise RuntimeError("The codec first-chunk decoder is closed")
self._sink = sink
if self._thread is None:
self._thread = threading.Thread(target=self._run, name="moss-codec-first-chunk", daemon=True)
self._thread.start()
def close(self) -> None:
with self._lock:
if not self._closed:
self._closed = True
self._jobs.put(None)
thread = self._thread
if thread is not None:
thread.join(timeout=5.0)
# A stalled decode may still own GPU state: keep its thread and
# handoff, rather than permitting a restart or slot reuse.
if thread.is_alive():
logger.warning("Codec first-chunk decoder is still stopping; slot waits remain bounded")
# ------------------------------------------------------------------
# Receive thread
# ------------------------------------------------------------------
def submit(
self,
request_id: str,
request_key: str,
codes_flat: Any,
req_slots: dict[str, int],
) -> bool:
"""Claim a first chunk for fast decode; False leaves it to the main path."""
# Own the codes: the job outlives this call and the payload it came from.
codes = torch.as_tensor(codes_flat, dtype=torch.long).reshape(-1).clone()
if codes.numel() != self._n_vq * self.frames:
return False
with self._lock:
if (
self._closed
or self._sink is None
or self._thread is None
or not self._thread.is_alive()
or request_key in req_slots
):
return False
delivery = self._sink.prepare([request_id])
if request_id not in delivery.routes:
return False
slot = self._session.acquire(oldest=True)
if slot is None:
return False
handoff = _SlotHandoff()
self._handoffs[slot] = handoff
self._decoded[request_key] = slot
req_slots[request_key] = slot
codes = codes.reshape(self._n_vq, self.frames)
# Enqueue under the admission lock: close's sentinel cannot
# overtake an accepted job.
self._jobs.put(_Job(request_id, request_key, delivery, slot, codes, handoff))
return True
# ------------------------------------------------------------------
# Main (engine) thread
# ------------------------------------------------------------------
def get_request_slot(self, request_key: str, req_slots: dict[str, int]) -> int | None:
"""Observe a completed admission before deciding whether cleanup is needed.
The scheduler removes cancelled routes before the runner's finish hook.
A submit that already froze its route must finish leasing its slot
before that hook checks it. Waiting for decode happens outside this
lock, so the worker can still complete the slot handoff.
"""
with self._lock:
return req_slots.get(request_key)
def take_decoded(self, request_key: str) -> bool:
"""True once per request whose first chunk this path already decoded."""
with self._lock:
return self._decoded.pop(request_key, None) is not None
def take_unsent_audio(self, request_key: str) -> torch.Tensor | None:
"""Return first-chunk samples when the out-of-band sink rejected them."""
with self._lock:
return self._unsent_audio.pop(request_key, None)
def forget(self, request_key: str) -> None:
with self._lock:
self._decoded.pop(request_key, None)
self._unsent_audio.pop(request_key, None)
def gate(self) -> None:
"""Queue the current stream behind the latest fast decode, if still running."""
event = self._inflight
if self._gate_main and event is not None and not event.query():
torch.cuda.current_stream(self._device).wait_event(event)
def order_after(self, slot: int) -> None:
"""Make the current stream's next use of ``slot`` follow the fast decode."""
with self._lock:
handoff = self._handoffs.get(slot)
if handoff is None:
return
if not handoff.done.wait(timeout=self._handoff_timeout_s):
# Keep the handoff. The worker may still be writing the slot, so
# neither cancellation nor a retry may release/re-decode it.
raise TimeoutError(f"Codec first-chunk slot {slot} did not complete within {self._handoff_timeout_s:g}s")
if handoff.error is not None:
raise RuntimeError(f"Codec first-chunk decode failed for slot {slot}") from handoff.error
if handoff.event is not None:
torch.cuda.current_stream(self._device).wait_event(handoff.event)
with self._lock:
self._handoffs.pop(slot, None)
# ------------------------------------------------------------------
# Decode thread
# ------------------------------------------------------------------
def _run(self) -> None:
try:
current_omni_platform.set_device(self._device)
self._run_jobs()
except Exception as error:
logger.exception("MOSS codec first-chunk worker failed")
self._worker_error = error
finally:
with self._lock:
self._closed = True
for handoff in self._handoffs.values():
if not handoff.done.is_set():
handoff.error = self._worker_error or RuntimeError("Codec first-chunk worker stopped")
handoff.done.set()
# Accepted, unprocessed routes must not be left waiting for PCM.
while True:
try:
job = self._jobs.get_nowait()
except queue.Empty:
break
if job is not None:
self._fail_delivery(job)
@staticmethod
def _fail_delivery(job: _Job) -> None:
try:
job.delivery.fail([job.request_id])
except Exception:
logger.exception("Codec first-chunk error delivery failed for %s", job.request_id)
def _run_jobs(self) -> None:
while True:
job = self._jobs.get()
if job is None:
return
jobs = [job]
while len(jobs) < self._max_batch:
try:
extra = self._jobs.get_nowait()
except queue.Empty:
break
if extra is None:
self._jobs.put(None)
break
jobs.append(extra)
try:
start = time.perf_counter()
self._decode(jobs)
self._decode_s += time.perf_counter() - start
self._batches += 1
before, self._emitted = self._emitted, self._emitted + len(jobs)
if self._emitted // 1000 != before // 1000:
logger.info(
"MOSS codec first-chunk fast path: %d chunks in %d batches, %.2f ms/batch",
self._emitted,
self._batches,
1e3 * self._decode_s / self._batches,
)
except Exception as error:
logger.exception("MOSS codec first-chunk fast decode failed for %s", [j.request_id for j in jobs])
# A partial graph replay may have advanced the slot. Surface
# the failure instead of re-decoding and advancing it twice.
for item in jobs:
item.handoff.error = error
item.handoff.done.set()
self._fail_delivery(item)
raise
@torch.no_grad()
def _decode(self, jobs: list[_Job]) -> None:
n = len(jobs)
for row, item in enumerate(jobs):
self._host_codes[:, row].copy_(item.codes)
self._host_slots[row] = item.slot
stream = self._stream
with torch.cuda.stream(stream):
for item in jobs:
self._session.order_after_reset(item.slot, stream)
codes = self._host_codes[:, :n].to(self._device, non_blocking=True).clamp_(0, self._codebook_size - 1)
slots = self._host_slots[:n].to(self._device, non_blocking=True)
result = self._wrapper.decode(codes, slots)
if result is None:
raise RuntimeError(f"no first-chunk codec graph for B={n}, T={self.frames}")
audio = result[0][:n, ..., : self._samples].float()
state_written = torch.cuda.Event()
state_written.record(stream)
self._inflight = state_written
self._host_audio[:n].view_as(audio).copy_(audio, non_blocking=True)
self._copied.record(stream)
for item in jobs:
item.handoff.event = state_written
self._copied.synchronize()
for row, item in enumerate(jobs):
wav = self._host_audio[row].clone()
if self._n_channels == 1:
wav = wav.reshape(-1)
try:
item.delivery([item.request_id], [wav], self._sr)
except Exception:
logger.exception("MOSS codec first-chunk output failed for %s", item.request_id)
with self._lock:
self._unsent_audio[item.request_key] = wav
finally:
item.handoff.done.set()
@@ -0,0 +1,447 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""MOSS Local request-slot state, independent of each step's batch order.
State writes, gathers and MTP replay run on the runner stream. Output gathers
own their storage; the runner retains its normal asynchronous output snapshot.
No request dictionary holds a view into a mutable slot or CUDA graph buffer.
"""
import numpy as np
import torch
from vllm.config import CUDAGraphMode
from vllm.forward_context import set_forward_context
from vllm.logger import init_logger
from vllm.utils.torch_utils import async_tensor_h2d
from vllm.v1.worker.gpu.input_batch import get_num_sampled_and_rejected
from vllm.v1.worker.gpu.sample.output import SamplerOutput
from vllm.v1.worker.gpu.sample.sampler import Sampler
from vllm_omni.model_executor.output_snapshot import PackedOutputSnapshot
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState
logger = init_logger(__name__)
def _metadata_to_device(data: np.ndarray, device: torch.device) -> torch.Tensor:
# CPU state tests need no CUDA allocator. The serving CUDA path retains
# vLLM's asynchronous pinned upload and its ownership/lifetime handling.
if device.type == "cpu":
return torch.from_numpy(data)
return async_tensor_h2d(data, device=device)
class _CodeRowsSnapshot(PackedOutputSnapshot):
"""Owned per-request code rows backed by one gathered device tensor.
The generic snapshot flattens every per-request leaf, concatenates them
into a slab and slices each back, then slices each again after the D2H.
Here the gathered ``[decode_rows, n_vq]`` tensor is already owned, so the
copy is a single D2H and the per-request views come from one ``split``.
"""
def __init__(self, codes: torch.Tensor, decode_rows: list[int], num_reqs: int) -> None:
dict.__init__(self, {"codes": {"audio": self._rows(codes, decode_rows, num_reqs)}})
self._codes = codes
self._decode_rows = decode_rows
self._num_reqs = num_reqs
self.producer_event = None
@staticmethod
def _rows(codes: torch.Tensor, decode_rows: list[int], num_reqs: int) -> list[torch.Tensor]:
outputs = [codes.new_empty((0, codes.shape[-1]))] * num_reqs
for batch_row, row in zip(decode_rows, codes.split(1), strict=True):
outputs[batch_row] = row
return outputs
def copy_to_cpu(self, copy_tensor):
cpu = copy_tensor(self._codes)
return {"codes": {"audio": self._rows(cpu, self._decode_rows, self._num_reqs)}}
class MossLocalModelState(OmniModelState):
def __init__(self, vllm_config, model, encoder_cache, device):
super().__init__(vllm_config, model, encoder_cache, device)
self._init_slot_buffers(self.scheduler_config.max_num_seqs, model.hidden_size, device, self.dtype)
self._batch_prefill = bool(getattr(model.config, "mrv2_batch_prefill", False))
self._direct_tokens = bool(getattr(model.config, "mrv2_direct_tokens", False))
self._local_eager_mtp = bool(getattr(model.config, "mrv2_eager_mtp", False))
logger.info(
"MOSS Local MRV2 batch prefill=%s, determined tokens=%s, eager MTP=%s",
self._batch_prefill,
self._direct_tokens,
self._local_eager_mtp,
)
logger.info("MOSS Local MRV2 GPU slot state enabled: capacity=%d", self.scheduler_config.max_num_seqs)
def _init_slot_buffers(self, capacity, hidden_size, device, dtype):
self._hidden_pool = torch.zeros((capacity, hidden_size), dtype=dtype, device=device)
self._codes_pool = torch.full(
(capacity, self.model.n_vq), self.model.audio_pad_token_id, dtype=torch.long, device=device
)
# Execution eligibility mirrors audio_state.is_stopping. Binary MTP
# continuation is a per-step output, not a sticky request-state update.
self._active_pool = torch.zeros(capacity, dtype=torch.bool, device=device)
self._active_host = [False] * capacity
self._decode_rows = []
self._prefill_staging = []
self._batch_prefill = False
self._direct_tokens = False
# Eager MTP: a frame is sampled right after the forward that produced
# its hidden state, one step earlier than the canonical preprocess
# path. Its input-embedding contribution (audio embedding times emit
# mask) is added to the next step's text embedding; ``_keep_pool``
# chains emission so a stopped stream cannot emit again.
self._local_eager_mtp = False
self._eager_emb_pool = torch.zeros((capacity, hidden_size), dtype=dtype, device=device)
self._keep_pool = torch.zeros(capacity, dtype=torch.bool, device=device)
self._completing_rows = []
self._local_eager_rows = []
# A slot takes the eager path only after its final prefill chunk ran
# an eager MTP in this state; others keep the canonical path, so a
# reused slot never reads a previous request's frame state.
self._eager_host = [False] * capacity
self._mtp_dispatcher = None
def sample_determined_tokens(self, batch, sampler):
"""Skip full-vocabulary sampling only for unconstrained Local tokens.
The audio/binary MTP sampler has already made the random decision. The
outer text distribution has exactly one finite logit. Keep the original
path for processors that can mask it or request distribution metadata.
"""
if not self._direct_tokens or type(sampler) is not Sampler:
return None
rows = batch.idx_mapping_np
if (
sampler.compute_nans
or sampler.return_sampling_mask
or sampler.trace_replay_state is not None
or sampler.get_logprobs_dims(rows) is not None
or np.any(sampler.logit_bias_state.use_logit_bias[rows])
or np.any(sampler.penalties_state.use_penalty[rows])
or np.any(sampler.bad_words_state.num_bad_words.np[rows])
or (
sampler.thinking_budget_state.enabled
and np.any(sampler.thinking_budget_state.use_thinking_budget[rows])
)
):
return None
keep = self.model._batch_should_continue
if keep is None or keep.numel() != batch.num_reqs:
return None
# Owned storage: subsequent forwards can replace the continue mask
# while these token IDs are being copied or delivered asynchronously.
tokens = torch.where(keep, self.model.audio_assistant_slot_token_id, self.model.im_end_token_id)
num_sampled, num_rejected = get_num_sampled_and_rejected(
batch.seq_lens.new_ones(batch.num_reqs),
batch.seq_lens,
batch.cu_num_logits,
batch.idx_mapping,
sampler.req_states.prefill_len.gpu,
)
return SamplerOutput(tokens.reshape(-1, 1), None, None, num_sampled, num_rejected)
def _apply_reference_batch(self, embeds, references):
"""One owned pinned upload for reference codes and their token positions.
Host storage may be reused only after its H2D event completes. Device
storage is consumed and overwritten in runner-stream order. If all
cached slots are busy, allocate a transient snapshot instead of waiting.
"""
if not references:
return
count = sum(codes.shape[0] for _, codes in references)
capacity = max(count, self._static_inputs_embeds.shape[0])
staging = None
for item in self._prefill_staging:
if item[0].shape[0] >= count and (item[2] is None or item[2].query()):
staging = item
break
if staging is None:
host = torch.empty((capacity, self.model.n_vq + 1), dtype=torch.long, pin_memory=embeds.is_cuda)
device = torch.empty_like(host, device=embeds.device) if embeds.is_cuda else host
staging = [host, device, torch.cuda.Event() if embeds.is_cuda else None]
if len(self._prefill_staging) < 3:
self._prefill_staging.append(staging)
host, device, event = staging
offset = 0
for start, codes in references:
end = offset + codes.shape[0]
host[offset:end, 0].numpy()[:] = np.arange(start, start + codes.shape[0])
host[offset:end, 1:].copy_(codes)
offset = end
if embeds.is_cuda:
device[:count].copy_(host[:count], non_blocking=True)
event.record(torch.cuda.current_stream(embeds.device))
packed = device[:count]
positions = packed[:, 0]
audio = self.model._audio_embed(packed[:, 1:])
embeds.index_copy_(0, positions, embeds.index_select(0, positions) + audio)
def add_request(self, req_index, new_req_data):
super().add_request(req_index, new_req_data)
self._hidden_pool[req_index].zero_()
self._codes_pool[req_index].fill_(self.model.audio_pad_token_id)
self._active_pool[req_index].fill_(True)
self._active_host[req_index] = True
self._eager_host[req_index] = False
self._keep_pool[req_index].fill_(False)
self._eager_emb_pool[req_index].zero_()
def remove_request(self, req_index_or_id):
# Freeing is CPU bookkeeping. Reinitialization happens on admission,
# in stream order, so pending output snapshots remain independent.
super().remove_request(req_index_or_id)
def _select_rows(self, tensor, rows):
if rows == list(range(len(rows))):
return tensor[: len(rows)]
indices = _metadata_to_device(np.asarray(rows, dtype=np.int64), tensor.device)
return tensor.index_select(0, indices)
def run_preprocess(self, input_batch, model_inputs, req_states=None, mtp_batch_descriptor_dispatcher=None):
input_ids = model_inputs.get("input_ids")
if input_ids is None:
input_ids = input_batch.input_ids
embeds = model_inputs.get("inputs_embeds")
if embeds is None:
embeds = self.model.embed_input_ids(input_ids[: input_batch.num_tokens])
model_inputs["inputs_embeds"] = embeds
elif self._static_inputs_embeds is not None and embeds.data_ptr() == self._static_inputs_embeds.data_ptr():
embeds[: input_batch.num_tokens].copy_(self.model.embed_input_ids(input_ids[: input_batch.num_tokens]))
decode_rows = []
completing_rows = []
references = []
for row in range(input_batch.num_reqs):
slot = int(input_batch.idx_mapping_np[row])
buf = self.intermediate_buffer.buffers[slot]
if not buf or str(buf.get("req_id", "")).startswith("_warmup_"):
continue
start = int(input_batch.query_start_loc_np[row])
count = int(input_batch.num_scheduled_tokens[row])
prompt_len = (
None if req_states is None else self._get_req_state_value(getattr(req_states, "prompt_len", None), slot)
)
computed = (
None
if req_states is None
else self._get_req_state_value(getattr(req_states, "num_computed_tokens", None), slot)
)
if computed is None:
computed = self._get_input_batch_num_computed(input_batch, slot, row)
prefill = computed < prompt_len if computed is not None and prompt_len is not None else count > 1
if prefill and computed is not None and prompt_len is not None and computed + count >= prompt_len:
completing_rows.append(row)
if count == 1 and not prefill and isinstance(buf.get("audio_state"), dict):
active = not bool(buf["audio_state"].get("is_stopping"))
if active != self._active_host[slot]:
self._active_pool[slot].fill_(active)
self._active_host[slot] = active
decode_rows.append(row)
continue
if self._batch_prefill:
ref = (buf.get("codes", {}) or {}).get("ref")
ref_offset = int(buf.get("ref_offset", 0))
# Device-side references keep the canonical path; do not add
# an implicit D2H just to place them in a host staging buffer.
if not isinstance(ref, torch.Tensor) or ref.device.type == "cpu":
if isinstance(ref, torch.Tensor) and ref.numel():
if ref.dim() == 1 and ref.numel() % self.model.n_vq == 0:
ref = ref.view(-1, self.model.n_vq)
if ref.dim() == 2:
chunk = ref[ref_offset : ref_offset + count]
if chunk.numel() and chunk.shape[0] == count:
references.append((start, chunk))
# Text embeddings have already been computed for all input
# tokens. Match the canonical prefill state transition.
self.intermediate_buffer.update(
slot,
{
"audio_state": {"is_stopping": False},
"ref_offset": ref_offset + count,
},
self.model.gpu_resident_buffer_keys,
)
if not self._active_host[slot]:
self._active_pool[slot].fill_(True)
self._active_host[slot] = True
continue
# Reference conditioning and chunked-prefill coordinates retain
# the model's canonical scalar implementation.
info = dict(buf)
info["_omni_is_prefill"] = prefill
if prompt_len is not None:
info["_omni_prompt_len"] = prompt_len
if computed is not None:
info["_omni_num_computed_tokens"] = computed
ids = input_ids[start : start + count]
previous = embeds[start : start + count]
new_ids, new_embeds, updates = self.model.preprocess(ids, previous, **info)
if "mtp_inputs" in updates:
raise RuntimeError("MOSS slot state requires an admitted prefill before decode")
if self._preprocess_result_needs_writeback(ids, new_ids):
ids.copy_(new_ids)
if self._preprocess_result_needs_writeback(previous, new_embeds):
previous.copy_(new_embeds)
self.intermediate_buffer.update(slot, updates, self.model.gpu_resident_buffer_keys)
active = not bool(updates.get("audio_state", {}).get("is_stopping", False))
if active != self._active_host[slot]:
self._active_pool[slot].fill_(active)
self._active_host[slot] = active
self._apply_reference_batch(embeds, references)
self._decode_rows = decode_rows
if self._local_eager_mtp:
self._completing_rows = completing_rows
self._mtp_dispatcher = mtp_batch_descriptor_dispatcher
eager_rows = [row for row in decode_rows if self._eager_host[int(input_batch.idx_mapping_np[row])]]
canonical_rows = [row for row in decode_rows if not self._eager_host[int(input_batch.idx_mapping_np[row])]]
self._local_eager_rows = eager_rows
if eager_rows:
# Their frame was sampled after the previous forward.
slots = self._select_rows(input_batch.idx_mapping, eager_rows)
offsets = self._mtp_offsets[: len(eager_rows)]
offsets.copy_(self._select_rows(input_batch.query_start_loc, eager_rows))
embeds.index_copy_(
0, offsets, embeds.index_select(0, offsets) + self._eager_emb_pool.index_select(0, slots)
)
if canonical_rows:
self._run_slot_mtp(input_batch, input_ids, embeds, canonical_rows, mtp_batch_descriptor_dispatcher)
elif decode_rows:
self._run_slot_mtp(input_batch, input_ids, embeds, decode_rows, mtp_batch_descriptor_dispatcher)
def _run_slot_mtp(self, batch, input_ids, embeds, rows, dispatcher):
bsz = len(rows)
slots = self._select_rows(batch.idx_mapping, rows)
# Upstream query_start_loc is int32; index_copy_ requires int64.
offsets = self._mtp_offsets[:bsz]
offsets.copy_(self._select_rows(batch.query_start_loc, rows))
ids, emb = self._mtp_input_ids[:bsz], self._mtp_input_embeds[:bsz]
hidden, step = self._mtp_hidden[:bsz], self._mtp_text_step[:bsz]
ids.copy_(input_ids.index_select(0, offsets)) # MRV2 token inputs are int32.
torch.index_select(embeds, 0, offsets, out=emb)
torch.index_select(self._hidden_pool, 0, slots, out=hidden)
step[:, 0].copy_(self._active_pool.index_select(0, slots))
buffers = [self.intermediate_buffer.buffers[int(batch.idx_mapping_np[row])] for row in rows]
req_ids = [str(buf["req_id"]) for buf in buffers]
generators = [
self._get_mtp_generator(req_id, buf.get("sampling_params"), ids.device)
for req_id, buf in zip(req_ids, buffers, strict=True)
]
can_graph = self._is_mtp_graph_runner() and not any(g is not None for g in generators)
desc = dispatcher(bsz) if can_graph and dispatcher is not None else None
mode = getattr(desc, "cg_mode", CUDAGraphMode.FULL) if can_graph else CUDAGraphMode.NONE
num_tokens = int(desc.num_tokens) if desc is not None else bsz
with set_forward_context(
None, self.vllm_config, num_tokens=num_tokens, cudagraph_runtime_mode=mode, batch_descriptor=desc
):
new_emb, codes = self._call_mtp_with_sampling(
self._mtp_input_ids[:num_tokens],
self._mtp_input_embeds[:num_tokens],
self._mtp_hidden[:num_tokens],
self._mtp_text_step[:num_tokens],
buffers=buffers,
req_ids=req_ids,
generators=generators,
)
embeds.index_copy_(0, offsets, new_emb[:bsz])
self._codes_pool.index_copy_(0, slots, codes[:bsz])
def _run_local_eager_mtp(self, batch, rows, completing):
"""Sample the next frame from this forward's hidden state.
Same MTP inputs as the canonical next-step preprocess (hidden state
and active flag); the input embedding is zero, so the returned
embedding is exactly the audio contribution the next step adds to its
text embedding. A decode row emits only if its previous frame did.
"""
bsz = len(rows)
slots = self._select_rows(batch.idx_mapping, rows)
ids, emb = self._mtp_input_ids[:bsz], self._mtp_input_embeds[:bsz]
hidden, step = self._mtp_hidden[:bsz], self._mtp_text_step[:bsz]
ids.zero_() # the MTP does not read token ids
emb.zero_()
torch.index_select(self._hidden_pool, 0, slots, out=hidden)
gate = self._keep_pool.index_select(0, slots)
if completing:
first = _metadata_to_device(
np.asarray([row in completing for row in rows], dtype=np.bool_),
gate.device,
)
gate = gate | first
step[:, 0].copy_(self._active_pool.index_select(0, slots) & gate)
buffers = [self.intermediate_buffer.buffers[int(batch.idx_mapping_np[row])] for row in rows]
req_ids = [str(buf["req_id"]) for buf in buffers]
generators = [
self._get_mtp_generator(req_id, buf.get("sampling_params"), ids.device)
for req_id, buf in zip(req_ids, buffers, strict=True)
]
dispatcher = self._mtp_dispatcher
can_graph = self._is_mtp_graph_runner() and not any(g is not None for g in generators)
desc = dispatcher(bsz) if can_graph and dispatcher is not None else None
mode = getattr(desc, "cg_mode", CUDAGraphMode.FULL) if can_graph else CUDAGraphMode.NONE
num_tokens = int(desc.num_tokens) if desc is not None else bsz
with set_forward_context(
None, self.vllm_config, num_tokens=num_tokens, cudagraph_runtime_mode=mode, batch_descriptor=desc
):
contribution, codes = self._call_mtp_with_sampling(
self._mtp_input_ids[:num_tokens],
self._mtp_input_embeds[:num_tokens],
self._mtp_hidden[:num_tokens],
self._mtp_text_step[:num_tokens],
buffers=buffers,
req_ids=req_ids,
generators=generators,
)
codes = codes[:bsz]
self._eager_emb_pool.index_copy_(0, slots, contribution[:bsz])
self._codes_pool.index_copy_(0, slots, codes)
self._keep_pool.index_copy_(0, slots, codes.ne(self.model.audio_pad_token_id).any(dim=-1))
def run_postprocess(self, hidden_states, input_batch):
# query_start_loc is already device-resident and authoritative for
# mixed/chunked-prefill batches. index_copy snapshots graph outputs.
last = input_batch.query_start_loc[1 : input_batch.num_reqs + 1] - 1
self._hidden_pool.index_copy_(
0, input_batch.idx_mapping[: input_batch.num_reqs], hidden_states.index_select(0, last)
)
if self._local_eager_mtp:
completing = self._completing_rows
rows = sorted(self._local_eager_rows + completing)
# Canonical decode rows emit their preprocess frame; eager rows
# and completed prefills emit the frame sampled below.
self._decode_rows = sorted(set(self._decode_rows) | set(completing))
if rows:
self._run_local_eager_mtp(input_batch, rows, set(completing))
for row in completing:
self._eager_host[int(input_batch.idx_mapping_np[row])] = True
def postprocess_model_output(self, model_output, input_batch, req_states):
# Local backbone returns a tensor; keep the standard runner's output
# snapshot/materializer contract and omit hidden payload transport.
if not isinstance(model_output, torch.Tensor):
raise TypeError("MOSS Local slot state requires a tensor backbone output")
model = self.model
model._batch_state = None
model._batch_state_spans = None
model._batch_should_continue = torch.ones(input_batch.num_reqs, device=model_output.device, dtype=torch.bool)
if not self._decode_rows:
return model_output, {}
# This gather is an owned snapshot. Later slot writes cannot change
# data already handed to the runner, even before its D2H completes.
slots = self._select_rows(input_batch.idx_mapping, self._decode_rows)
codes = self._codes_pool.index_select(0, slots)
keep = codes.ne(model.audio_pad_token_id).any(dim=-1)
if self._decode_rows == list(range(input_batch.num_reqs)):
model._batch_should_continue = keep
else:
rows = _metadata_to_device(
np.asarray(self._decode_rows, dtype=np.int64),
codes.device,
)
model._batch_should_continue.index_copy_(0, rows, keep)
return model_output, _CodeRowsSnapshot(codes, list(self._decode_rows), input_batch.num_reqs)
@@ -0,0 +1,100 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Single-query attention for the frame-local MOSS depth transformer.
The caller has already written this token's K/V and provides only its valid
prefix. There is no persistent state here. BF16 probability rounding matches
the FlashAttention P/V multiply, but reduction order is not bit-identical.
"""
import torch
from vllm.triton_utils import tl, triton
@triton.jit
def _short_attention(
q_ptr,
k_ptr,
v_ptr,
out_ptr,
qs0: tl.constexpr,
qs1: tl.constexpr,
ks0: tl.constexpr,
ks1: tl.constexpr,
ks2: tl.constexpr,
vs0: tl.constexpr,
vs1: tl.constexpr,
vs2: tl.constexpr,
heads: tl.constexpr,
dim: tl.constexpr,
tokens: tl.constexpr,
block_d: tl.constexpr,
block_t: tl.constexpr,
):
row = tl.program_id(0)
batch, head = row // heads, row % heads
d, t = tl.arange(0, block_d), tl.arange(0, block_t)
query = tl.load(q_ptr + batch * qs0 + head * qs1 + d, d < dim, 0).to(tl.float32)
keys = tl.load(
k_ptr + batch * ks0 + head * ks1 + t[:, None] * ks2 + d[None, :],
(t[:, None] < tokens) & (d[None, :] < dim),
0,
).to(tl.float32)
logits = tl.sum(keys * query[None, :], axis=1) * (dim**-0.5 * 1.4426950408889634)
logits = tl.where(t < tokens, logits, float("-inf"))
probs = tl.exp2(logits - tl.max(logits, axis=0))
denominator = tl.sum(probs, axis=0)
values = tl.load(
v_ptr + batch * vs0 + head * vs1 + t[:, None] * vs2 + d[None, :],
(t[:, None] < tokens) & (d[None, :] < dim),
0,
)
probs = probs.to(values.dtype).to(tl.float32)
output = tl.sum(values.to(tl.float32) * probs[:, None], axis=0) / denominator
tl.store(out_ptr + row * dim + d, output, d < dim)
@torch.library.custom_op("vllm_omni::moss_local_short_attention", mutates_args=())
def local_short_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
batch, heads, seq_len, dim = query.shape
if not (
query.is_cuda
and key.device == query.device
and value.device == query.device
and query.dtype == key.dtype == value.dtype == torch.bfloat16
and seq_len == 1
and 0 < dim <= 128
and key.shape == value.shape
and key.shape[:2] == query.shape[:2]
and key.shape[-1] == dim
and 0 < key.shape[2] <= 16
and query.stride(-1) == key.stride(-1) == value.stride(-1) == 1
):
raise ValueError("MOSS short attention requires CUDA BF16 single-query inputs and 1..16 valid keys")
output = query.new_empty((batch, heads, 1, dim))
_short_attention[(batch * heads,)](
query,
key,
value,
output,
query.stride(0),
query.stride(1),
key.stride(0),
key.stride(1),
key.stride(2),
value.stride(0),
value.stride(1),
value.stride(2),
heads,
dim,
key.shape[2],
triton.next_power_of_2(dim),
triton.next_power_of_2(key.shape[2]),
num_warps=1,
)
return output
@local_short_attention.register_fake
def _fake_local_short_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
return query.new_empty(query.shape)
@@ -8,7 +8,10 @@
from __future__ import annotations
import threading
from collections.abc import Iterable
from contextlib import nullcontext
from functools import partial
from typing import Any
import torch
@@ -32,11 +35,16 @@ from vllm_omni.model_executor.models.moss_tts.configuration_moss_audio_tokenizer
from vllm_omni.model_executor.models.moss_tts.cuda_graph_streaming_decoder_wrapper import (
CUDAGraphStreamingDecoderWrapper,
)
from vllm_omni.model_executor.models.moss_tts.first_chunk_fast_path import (
MossFirstChunkFastPath,
)
from vllm_omni.model_executor.models.moss_tts.moss_codec_cudagraph import (
MossTTSCUDAGraphCodecWrapper,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.model_executor.output_snapshot import PackedOutputSnapshot, pack_output_snapshot
from vllm_omni.model_executor.stage_input_processors.chunk_size_utils import parse_chunk_ramp
from vllm_omni.worker_v2.first_audio_sender import FirstAudioSink
logger = init_logger(__name__)
@@ -53,18 +61,46 @@ class _MossCodecStreamSession:
vllm_config: VllmConfig,
graph_batch_sizes: list[int] | None = None,
graph_frame_sizes: list[int] | None = None,
gpu_output: bool = False,
chunk_frames: int = 0,
ring_headroom: bool = False,
fast_batch_sizes: list[int] | None = None,
fast_frames: int = 0,
) -> None:
self._codec = codec
self._state_capacity = int(state_capacity)
self._chunk_frames = int(chunk_frames)
self._ring_headroom = bool(ring_headroom)
self._n_vq = int(n_vq)
self._device = next(codec.parameters()).device
self._gpu_output = gpu_output and self._device.type == "cuda"
self._free_stream_slots = list(reversed(range(self._state_capacity)))
self._leased_slots: set[int] = set()
# The first-chunk fast path leases slots from its decode thread.
self._slot_lock = threading.Lock()
self._slot_reset_events: dict[int, torch.cuda.Event] = {}
self._closed = False
self._metadata_index = 0
self._metadata_ring = []
if self._gpu_output:
# The metadata DMA is tiny, but a short ring forces the producer
# CPU thread to synchronize with the codec stream while it waits
# for a host slab to become reusable. Keep enough entries for a
# scheduler burst so staging remains enqueue-only in practice.
for _ in range(64):
host = torch.empty(2 * self._state_capacity, dtype=torch.long, pin_memory=True)
gpu = torch.empty_like(host, device=self._device)
self._metadata_ring.append((host, host.numpy(), gpu, torch.cuda.Event(), False))
self._cudagraph_wrapper: CUDAGraphStreamingDecoderWrapper | None = None
self._fast_wrapper: CUDAGraphStreamingDecoderWrapper | None = None
batch_sizes = sorted({int(size) for size in (graph_batch_sizes or []) if 0 < int(size) <= self._state_capacity})
frame_sizes = sorted({int(size) for size in (graph_frame_sizes or []) if int(size) > 0})
scratch_capacity = max(batch_sizes, default=0) if self._device.type in ("cuda", "npu") else 0
fast_batch_sizes = sorted({int(size) for size in (fast_batch_sizes or []) if 0 < int(size)})
if not (fast_frames > 0 and fast_batch_sizes and batch_sizes and frame_sizes and self._device.type == "cuda"):
fast_batch_sizes = []
fast_scratch_base = self._state_capacity + scratch_capacity
scratch_capacity += max(fast_batch_sizes, default=0)
self._total_state_capacity = self._state_capacity + scratch_capacity
self._state_slot_ids = torch.arange(
self._total_state_capacity,
@@ -76,7 +112,14 @@ class _MossCodecStreamSession:
if not callable(initialize_state_pool):
raise RuntimeError("The streaming codec does not implement a decoder state pool.")
with torch.no_grad():
initialize_state_pool(self._state_capacity, scratch_capacity)
if self._ring_headroom:
if self._chunk_frames <= 0:
raise ValueError("codec_ring_headroom requires a positive codec chunk frame count.")
# Size every attention ring for context + one full chunk so a
# chunk write never evicts keys inside its own causal window.
initialize_state_pool(self._state_capacity, scratch_capacity, chunk_frames=self._chunk_frames)
else:
initialize_state_pool(self._state_capacity, scratch_capacity)
if batch_sizes and frame_sizes and self._device.type in ("cuda", "npu"):
if self._device.type == "npu":
from vllm_omni.platforms.npu.models.moss_tts_streaming_decode_wrapper import (
@@ -101,16 +144,34 @@ class _MossCodecStreamSession:
vllm_config=vllm_config,
)
self._cudagraph_wrapper.warmup(self._device)
if fast_batch_sizes and self._cudagraph_wrapper.is_ready:
main_compiled = self._cudagraph_wrapper._compiled_decode
self._fast_wrapper = CUDAGraphStreamingDecoderWrapper(
codec,
state_capacity=self._state_capacity,
batch_sizes=fast_batch_sizes,
frame_sizes=[int(fast_frames)],
num_quantizers=self._n_vq,
vllm_config=vllm_config,
scratch_base=fast_scratch_base,
private_pool=True,
compiled_decode=main_compiled if main_compiled is not None else codec.decode_streaming_tensors,
)
self._fast_wrapper.warmup(self._device)
if not self._fast_wrapper.is_ready:
self._fast_wrapper = None
self.reset_slots(list(range(self._state_capacity + scratch_capacity)))
if not self._cudagraph_wrapper.is_ready:
self._cudagraph_wrapper = None
def acquire(self) -> int | None:
if not self._free_stream_slots:
return None
slot = self._free_stream_slots.pop()
self._leased_slots.add(slot)
return slot
def acquire(self, *, oldest: bool = False) -> int | None:
"""Lease a slot; ``oldest`` takes the one whose reset was queued first."""
with self._slot_lock:
if not self._free_stream_slots:
return None
slot = self._free_stream_slots.pop(0 if oldest else -1)
self._leased_slots.add(slot)
return slot
def release(self, slot: int, *, state_already_reset: bool = False) -> None:
if self._closed:
@@ -119,8 +180,23 @@ class _MossCodecStreamSession:
return
if not state_already_reset:
self.reset_slots([slot])
self._leased_slots.remove(slot)
self._free_stream_slots.append(slot)
reset_event = None
if self._fast_wrapper is not None:
# The fast path decodes on another stream; it must not read this
# slot before the reset queued on the current stream has run.
reset_event = torch.cuda.Event()
reset_event.record(torch.cuda.current_stream(self._device))
with self._slot_lock:
if reset_event is not None:
self._slot_reset_events[slot] = reset_event
self._leased_slots.remove(slot)
self._free_stream_slots.append(slot)
def order_after_reset(self, slot: int, stream: torch.cuda.Stream) -> None:
with self._slot_lock:
event = self._slot_reset_events.pop(slot, None)
if event is not None and not event.query():
stream.wait_event(event)
def _reset_slot_ids(self, slot_ids: torch.Tensor) -> None:
reset_streaming_slots = getattr(self._codec, "reset_decoder_state_slots", None)
@@ -139,9 +215,29 @@ class _MossCodecStreamSession:
raise ValueError(f"Decoder state slots must be contiguous, got {slots}")
self._reset_slot_ids(self._state_slot_ids[start : start + len(slots)])
def _stage_slot_ids(self, slots: list[int], terminal_slots: set[int]) -> tuple[torch.Tensor, torch.Tensor]:
# Host slabs cannot be overwritten until their DMA completes. Device
# slabs are reused in producer-stream order, after all previous reads.
index = self._metadata_index
host, view, gpu, event, recorded = self._metadata_ring[index]
if recorded and not event.query():
event.synchronize()
terminal_ids = [slot for slot in slots if slot in terminal_slots]
n, end = len(slots), len(slots) + len(terminal_ids)
view[:n] = slots
view[n:end] = terminal_ids
gpu[:end].copy_(host[:end], non_blocking=True)
event.record(torch.cuda.current_stream(self._device))
self._metadata_ring[index] = (host, view, gpu, event, True)
self._metadata_index = (index + 1) % len(self._metadata_ring)
return gpu[:n], gpu[n:end]
def close(self) -> None:
if self._closed:
return
for _, _, _, event, recorded in self._metadata_ring:
if recorded:
event.synchronize()
close_state_pool = getattr(self._codec, "close_decoder_state_pool", None)
with torch.no_grad():
if callable(close_state_pool):
@@ -154,6 +250,7 @@ class _MossCodecStreamSession:
slot_codes: dict[int, torch.Tensor],
*,
terminal_slots: set[int] | None = None,
output_buffers: dict[int, torch.Tensor] | None = None,
) -> dict[int, torch.Tensor]:
if not slot_codes:
return {}
@@ -178,17 +275,22 @@ class _MossCodecStreamSession:
],
dim=1,
)
state_slot_ids = torch.tensor(slots, device=self._device, dtype=torch.long)
staged_terminal_ids = None
if self._metadata_ring:
state_slot_ids, staged_terminal_ids = self._stage_slot_ids(slots, terminal_slots)
else:
state_slot_ids = torch.tensor(slots, device=self._device, dtype=torch.long)
graph_output: tuple[torch.Tensor, torch.Tensor, int] | None = None
if self._cudagraph_wrapper is not None:
# A terminal tail can safely pad T to a larger graph: decoder
# attention is causal, audio_lengths trims the padding, and every
# affected state slot is reset immediately after this step.
# An all-terminal group may borrow the next larger frame graph.
# The decoder is causal, so cropping the padded tail on the time
# axis recovers the exact-T waveform up to attention-ring
# eviction (see codec_ring_headroom); the state is reset below.
graph_output = self._cudagraph_wrapper.decode(
codes_step,
state_slot_ids,
allow_frame_padding=len(terminal_slots) == len(slots),
allow_frame_padding=bool(terminal_slots) and len(terminal_slots) == len(slots),
)
used_cudagraph = graph_output is not None
@@ -214,11 +316,69 @@ class _MossCodecStreamSession:
audio_tensor = result.audio
if terminal_slots:
terminal_rows = [row for row, slot in enumerate(slots) if slot in terminal_slots]
terminal_slot_ids = state_slot_ids if len(terminal_rows) == len(slots) else state_slot_ids[terminal_rows]
if staged_terminal_ids is not None:
terminal_slot_ids = staged_terminal_ids
else:
terminal_rows = [row for row, slot in enumerate(slots) if slot in terminal_slots]
terminal_slot_ids = (
state_slot_ids if len(terminal_rows) == len(slots) else state_slot_ids[terminal_rows]
)
self._reset_slot_ids(terminal_slot_ids)
audio = audio_tensor.detach().to("cpu", torch.float32)
if self._gpu_output and output_buffers is not None:
# Write directly into the caller-owned per-forward slab. This
# preserves graph output before the next replay without creating
# a temporary waveform tensor that would be packed again later.
out: dict[int, torch.Tensor] = {}
row = 0
while row < len(slots):
destination = output_buffers.get(slots[row])
if destination is None:
row += 1
continue
end = row + 1
if end < len(slots) and destination.is_contiguous():
storage = destination.untyped_storage().data_ptr()
offset = destination.storage_offset()
row_elements = destination.numel()
while end < len(slots):
following = output_buffers.get(slots[end])
if not (
following is not None
and following.shape == destination.shape
and following.dtype == destination.dtype
and following.device == destination.device
and following.is_contiguous()
and following.untyped_storage().data_ptr() == storage
and following.storage_offset() == offset + (end - row) * row_elements
):
break
end += 1
if end > row + 1:
# A mixed-frame forward can leave gaps between equal-sized
# rows in its slab. Copy each adjacent run as one batch,
# without overwriting the intervening requests' output.
destination = destination.as_strided(
(end - row, *destination.shape), (destination.numel(), *destination.stride())
)
source = audio_tensor[row:end]
else:
source = audio_tensor[row]
# Crop time before reshaping: flattening first mixes stereo
# channels whenever a row is shorter than the decode batch.
destination.copy_(source[..., : destination.shape[-1]].view_as(destination))
out.update((slot, output_buffers[slot]) for slot in slots[row:end])
row = end
return out
if self._gpu_output:
# A graph's static output is overwritten on every replay, including
# multiple replays within one forward. Snapshot on the producer
# stream before returning; record_stream alone cannot prevent this
# overwrite. MRV2 owns the subsequent pinned, asynchronous D2H.
audio = audio_tensor.detach().to(dtype=torch.float32, copy=True)
else:
audio = audio_tensor.detach().to("cpu", torch.float32)
out: dict[int, torch.Tensor] = {}
for row, slot in enumerate(slots):
audio_length = int(slot_codes[slot].shape[1]) * self._samples_per_frame
@@ -270,6 +430,7 @@ class MossTTSCodecDecoder(nn.Module):
requires_exact_input_shape: bool = True
_OUTPUT_SAMPLE_RATE: int = 24_000
_first_chunk_fast_path: MossFirstChunkFastPath | None = None
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
super().__init__()
@@ -292,20 +453,38 @@ class MossTTSCodecDecoder(nn.Module):
self._n_channels: int = 1
self._sr_tensor = torch.tensor(self._OUTPUT_SAMPLE_RATE, dtype=torch.int32)
self._stream_session: _MossCodecStreamSession | None = None
self._codec_stream: torch.cuda.Stream | None = None
scheduler_cfg = getattr(self.vllm_config, "scheduler_config", None)
self._stream_state_capacity = max(1, int(getattr(scheduler_cfg, "max_num_seqs", 1) or 1))
self._initial_stream_chunk_frames: int = self._connector_int("initial_codec_chunk_frames", default=0)
self._stream_chunk_frames: int = self._connector_int("codec_chunk_frames", default=0)
self._stream_max_step_frames: int = self._stream_chunk_frames or 100
# Opt-in: size codec attention rings as context + one chunk so chunked
# streaming reproduces whole-sequence decoding (costs ring memory).
self._stream_ring_headroom: bool = bool(self._connector_int("codec_ring_headroom", default=0))
self._stream_req_slots: dict[str, int] = {}
# Opt-in: decode each stream's first chunk from the receive thread.
self._first_chunk_fast = bool(self._connector_int("codec_first_chunk_fast_path", default=0))
self._first_chunk_fast_path: MossFirstChunkFastPath | None = None
self._async_chunk = bool(getattr(self.vllm_config.model_config, "async_chunk", False))
self._gpu_stream_output = (
self._async_chunk
and bool(getattr(vllm_config.model_config, "use_v2_model_runner", False))
and getattr(cfg, "model_type", None) == "moss_tts_local"
# Diagnostic switch: 0 copies each decode group's batch to the host synchronously.
and bool(self._connector_int("codec_gpu_stream_output", default=1))
)
self._streaming_graph_batch_sizes = self._streaming_graph_batch_sizes_from_compilation_config()
# codec_chunk_ramp ladder sizes join the streaming graph frame-size
# set so every ladder (B, T) combination is captured during warmup.
ramp = parse_chunk_ramp(self._connector_extra(), steady=self._stream_chunk_frames)
if ramp:
# The sender gives the ramp precedence over initial chunk size.
# The dedicated first-chunk graph must use that same first shape.
self._initial_stream_chunk_frames = ramp[0]
self._stream_max_step_frames = max(
self._stream_max_step_frames, self._initial_stream_chunk_frames, *(ramp or [])
)
self._streaming_graph_frame_sizes = _resolve_streaming_graph_frame_sizes(
self._initial_stream_chunk_frames,
self._stream_chunk_frames,
self._connector_extra_cfg(),
self._initial_stream_chunk_frames, self._stream_chunk_frames, self._connector_extra()
)
# ------------------------------------------------------------------
@@ -337,6 +516,41 @@ class MossTTSCodecDecoder(nn.Module):
inputs_embeds: torch.Tensor | None = None,
runtime_additional_information: list[dict[str, Any]] | None = None,
**kwargs: Any,
) -> OmniOutput:
if self._gpu_stream_output and input_ids is not None and input_ids.is_cuda:
if self._codec_stream is None:
self._codec_stream = torch.cuda.Stream(device=input_ids.device)
main_stream = torch.cuda.current_stream(input_ids.device)
# Runner input storage is reused by the next batch on main_stream.
# Own it before allowing that preparation to overlap codec decode.
owned_input_ids = input_ids.clone()
with torch.cuda.stream(self._codec_stream):
self._codec_stream.wait_stream(main_stream)
owned_input_ids.record_stream(self._codec_stream)
output = self._forward(
owned_input_ids,
positions,
intermediate_tensors,
inputs_embeds,
runtime_additional_information,
**kwargs,
)
if isinstance(output.multimodal_outputs, PackedOutputSnapshot):
output.multimodal_outputs.record_producer_event(self._codec_stream)
return output
return self._forward(
input_ids, positions, intermediate_tensors, inputs_embeds, runtime_additional_information, **kwargs
)
@torch.no_grad()
def _forward(
self,
input_ids: torch.Tensor | None = None,
positions: torch.Tensor | None = None,
intermediate_tensors: Any = None,
inputs_embeds: torch.Tensor | None = None,
runtime_additional_information: list[dict[str, Any]] | None = None,
**kwargs: Any,
) -> OmniOutput:
"""Decode audio VQ codes to waveform.
@@ -493,13 +707,37 @@ class MossTTSCodecDecoder(nn.Module):
audios[i] = wav.reshape(-1) if wav.ndim == 1 or int(wav.shape[0]) == 1 else wav
if streaming_work:
for i, wav in self._decode_streaming_batch(streaming_work).items():
stream_output_slab = None
stream_output_buffers: dict[int, torch.Tensor] = {}
if self._gpu_stream_output and device.type == "cuda":
total_elements = 0
for output_index, _, codes_nq_t, _ in streaming_work:
samples = int(codes_nq_t.shape[1]) * self._codec.downsample_rate
total_elements += samples * (self._n_channels if self._n_channels > 1 else 1)
if total_elements:
stream_output_slab = torch.empty(total_elements, dtype=torch.float32, device=device)
offset = 0
for output_index, _, codes_nq_t, _ in streaming_work:
samples = int(codes_nq_t.shape[1]) * self._codec.downsample_rate
elements = samples * (self._n_channels if self._n_channels > 1 else 1)
shape = (self._n_channels, samples) if self._n_channels > 1 else (samples,)
stream_output_buffers[output_index] = stream_output_slab.narrow(0, offset, elements).view(shape)
offset += elements
for i, wav in self._decode_streaming_batch(
streaming_work,
output_buffers=stream_output_buffers or None,
).items():
audios[i] = wav.reshape(-1) if wav.ndim == 1 or int(wav.shape[0]) == 1 else wav
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": audios, "sr": srs},
)
payload = {"model_outputs": audios, "sr": srs}
if self._gpu_stream_output and device.type == "cuda":
# One transfer per dtype/device preserves ragged request lengths
# without issuing one D2H per waveform. A fresh slot owns each
# output until the runner completes its copy; no reusable ring.
packed = pack_output_snapshot(payload, {}, max_buckets=0, reuse_existing_storage=True)
if packed is not None:
payload = packed
return OmniOutput(text_hidden_states=None, multimodal_outputs=payload)
@staticmethod
def _normalize_seq_token_counts(value: Any) -> list[int] | None:
@@ -546,25 +784,104 @@ class MossTTSCodecDecoder(nn.Module):
vllm_config=self.vllm_config,
graph_batch_sizes=self._streaming_graph_batch_sizes,
graph_frame_sizes=self._streaming_graph_frame_sizes,
gpu_output=self._gpu_stream_output,
chunk_frames=self._stream_max_step_frames,
ring_headroom=self._stream_ring_headroom,
fast_batch_sizes=[1, 2, 4, 8] if self._first_chunk_fast else None,
fast_frames=self._initial_stream_chunk_frames if self._first_chunk_fast else 0,
)
if self._stream_session._fast_wrapper is not None:
self._first_chunk_fast_path = MossFirstChunkFastPath(
self._stream_session,
self._stream_session._fast_wrapper,
n_vq=self._n_vq,
frames=self._initial_stream_chunk_frames,
codebook_size=int(self._codec.config.codebook_size),
samples_per_frame=int(self._codec.downsample_rate),
n_channels=self._n_channels,
sample_rate=self._sr_tensor,
device=next(self._codec.parameters()).device,
gate_main=bool(self._connector_int("codec_first_chunk_gate", default=0)),
)
logger.info(
"MOSS-TTS codec first-chunk fast path ready: B=%s T=%d",
self._stream_session._fast_wrapper.capture_sizes,
self._initial_stream_chunk_frames,
)
elif self._first_chunk_fast:
logger.warning("MOSS-TTS codec first-chunk fast path requested but unavailable; using the main path.")
if self._stream_ring_headroom:
logger.info(
"MOSS-TTS codec attention rings sized with headroom for %d-frame chunks",
self._stream_max_step_frames,
)
return self._stream_session
def bind_first_chunk_fast_path(self, sink: FirstAudioSink) -> Any:
"""Start the fast path with an output sink; returns the receive hook."""
fast = self._first_chunk_fast_path
if fast is None:
return None
fast.bind(sink)
return self._submit_first_chunk
def _submit_first_chunk(self, request_id: str, handle: Any, payload: Any) -> bool:
fast = self._first_chunk_fast_path
if fast is None or not isinstance(payload, dict):
return False
codes = payload.get("codes")
codes = codes.get("audio") if isinstance(codes, dict) else None
if codes is None:
return False
meta = payload.get("meta") if isinstance(payload.get("meta"), dict) else {}
key = meta.get("req_id")
if isinstance(key, (list, tuple)):
key = key[0] if key else None
if key is None:
key = getattr(handle, "external_req_id", None) or request_id
return fast.submit(request_id, str(key), codes, self._stream_req_slots)
def _decode_streaming_batch(
self,
items: list[tuple[int, str, torch.Tensor, bool]],
*,
output_buffers: dict[int, torch.Tensor] | None = None,
) -> dict[int, torch.Tensor]:
session = self._ensure_stream_session()
if session is None:
return {}
outputs: dict[int, torch.Tensor] = {}
unsent_first_audio: dict[int, torch.Tensor] = {}
grouped: dict[int, list[tuple[int, str, int, torch.Tensor, bool]]] = {}
max_step_frames = max(1, int(self._stream_max_step_frames))
graph = session._cudagraph_wrapper
# Terminal tails join the regular padded frame bucket when every
# execution batch width has a graph, so a step stays one replay
# instead of one eager or plain-graph decode per distinct tail length.
coalesce_tails = graph is not None and max(graph.batch_sizes, default=0) >= self._stream_state_capacity
fast = self._first_chunk_fast_path
for output_index, request_id, codes_nq_t, finished in items:
slot = self._stream_req_slots.get(request_id)
if fast is not None and slot is not None:
fast.order_after(slot)
if fast.take_decoded(request_id):
unsent = fast.take_unsent_audio(request_id)
if unsent is not None:
unsent_first_audio[output_index] = unsent
# The fast path already emitted this chunk's audio and
# advanced the slot state past it.
codes_nq_t = codes_nq_t[:, fast.frames :]
if codes_nq_t.shape[1] == 0:
if unsent is not None:
outputs[output_index] = unsent
if finished:
self._finish_stream_request(request_id, session, slot)
continue
if output_buffers is not None:
# Sized for the untrimmed chunk; decode into a fresh tensor.
output_buffers.pop(output_index, None)
if slot is None:
slot = session.acquire()
if slot is None:
@@ -580,9 +897,11 @@ class MossTTSCodecDecoder(nn.Module):
slot,
codes_nq_t,
terminal=finished,
output_buffer=output_buffers.get(output_index) if output_buffers is not None else None,
)
if wav is not None:
outputs[output_index] = wav
prefix = unsent_first_audio.pop(output_index, None)
outputs[output_index] = torch.cat((prefix, wav), dim=-1) if prefix is not None else wav
if finished:
self._finish_stream_request(
request_id,
@@ -593,21 +912,33 @@ class MossTTSCodecDecoder(nn.Module):
continue
frame_count = int(codes_nq_t.shape[1])
# Only combine tails that already used the same padded graph.
# Preserve exact-size graphs (including T=1) and the eager path.
group_frames = frame_count
if coalesce_tails and finished:
# Only terminal rows may be padded: their state is reset after
# the step, and the output is cropped to the exact frame count.
group_frames = graph._select_frame_size(frame_count, allow_padding=True) or frame_count
grouped.setdefault(group_frames, []).append((output_index, request_id, slot, codes_nq_t, finished))
if fast is not None and grouped:
fast.gate()
for group in grouped.values():
plan = {slot: codes_nq_t for _, _, slot, codes_nq_t, _ in group}
terminal_slots = {slot for _, _, slot, _, finished in group if finished}
decoded = session.step(plan, terminal_slots=terminal_slots)
step_buffers = (
{
slot: output_buffers[output_index]
for output_index, _, slot, _, _ in group
if output_buffers is not None and output_index in output_buffers
}
if output_buffers is not None
else None
)
decoded = session.step(plan, terminal_slots=terminal_slots, output_buffers=step_buffers)
for output_index, request_id, slot, _, finished in group:
wav = decoded.get(slot)
if wav is not None:
outputs[output_index] = wav
prefix = unsent_first_audio.pop(output_index, None)
outputs[output_index] = torch.cat((prefix, wav), dim=-1) if prefix is not None else wav
if finished:
self._finish_stream_request(
request_id,
@@ -625,6 +956,7 @@ class MossTTSCodecDecoder(nn.Module):
codes_nq_t: torch.Tensor,
*,
terminal: bool = False,
output_buffer: torch.Tensor | None = None,
) -> torch.Tensor | None:
if codes_nq_t.numel() == 0:
return None
@@ -633,13 +965,24 @@ class MossTTSCodecDecoder(nn.Module):
for start in range(0, int(codes_nq_t.shape[1]), max_step_frames):
chunk = codes_nq_t[:, start : start + max_step_frames]
is_terminal_chunk = terminal and start + max_step_frames >= int(codes_nq_t.shape[1])
chunk_samples = int(chunk.shape[1]) * self._codec.downsample_rate
chunk_buffer = (
output_buffer[
..., start * self._codec.downsample_rate : start * self._codec.downsample_rate + chunk_samples
]
if output_buffer is not None
else None
)
decoded = session.step(
{slot: chunk},
terminal_slots={slot} if is_terminal_chunk else None,
output_buffers={slot: chunk_buffer} if chunk_buffer is not None else None,
)
wav = decoded.get(slot)
if wav is not None:
parts.append(wav)
if output_buffer is not None:
return output_buffer
if not parts:
return None
return torch.cat(parts, dim=-1) if len(parts) > 1 else parts[0]
@@ -665,29 +1008,30 @@ class MossTTSCodecDecoder(nn.Module):
terminal payload, so the runner calls this hook from its finished-request
path to avoid leaking stream slots and buffered codes.
"""
session = self._stream_session
for req_id in finished_req_ids:
request_id = str(req_id)
slot = self._stream_req_slots.get(request_id)
if slot is None:
continue
if session is not None:
self._finish_stream_request(request_id, session, slot)
else:
self._stream_req_slots.pop(request_id, None)
# Cancellation and terminal cleanup share the decoder's stream order;
# a reused slot must not be reset ahead of an outstanding decode.
context = torch.cuda.stream(self._codec_stream) if self._codec_stream is not None else nullcontext()
with context:
session = self._stream_session
for req_id in finished_req_ids:
request_id = str(req_id)
fast = self._first_chunk_fast_path
slot = (
fast.get_request_slot(request_id, self._stream_req_slots)
if fast is not None
else self._stream_req_slots.get(request_id)
)
if slot is None:
continue
if fast is not None:
fast.order_after(slot)
fast.forget(request_id)
if session is not None:
self._finish_stream_request(request_id, session, slot)
else:
self._stream_req_slots.pop(request_id, None)
def _connector_int(self, name: str, default: int = 0) -> int:
model_cfg = getattr(self.vllm_config, "model_config", None)
connector_cfg = getattr(model_cfg, "stage_connector_config", None)
if isinstance(connector_cfg, dict):
extra_cfg: dict | None = connector_cfg.get("extra", connector_cfg)
else:
extra_cfg = getattr(connector_cfg, "extra", None)
if isinstance(extra_cfg, dict) and name in extra_cfg:
return int(extra_cfg[name])
return default
def _connector_extra_cfg(self) -> dict:
def _connector_extra(self) -> dict[str, Any]:
model_cfg = getattr(self.vllm_config, "model_config", None)
connector_cfg = getattr(model_cfg, "stage_connector_config", None)
if isinstance(connector_cfg, dict):
@@ -696,6 +1040,9 @@ class MossTTSCodecDecoder(nn.Module):
extra_cfg = getattr(connector_cfg, "extra", None)
return extra_cfg if isinstance(extra_cfg, dict) else {}
def _connector_int(self, name: str, default: int = 0) -> int:
return int(self._connector_extra().get(name, default))
def _streaming_graph_batch_sizes_from_compilation_config(self) -> list[int]:
if getattr(self.vllm_config.model_config, "enforce_eager", True):
return []
@@ -816,15 +1163,33 @@ class MossTTSCodecDecoder(nn.Module):
codec.decoder.to(dtype=torch.bfloat16)
attention_backend = getattr(self.vllm_config.model_config.hf_config, "codec_attention_backend", "sdpa")
if attention_backend != "sdpa":
if attention_backend != "triton" or device.type != "cuda":
if attention_backend not in {"triton", "triton_slot"} or device.type != "cuda":
raise ValueError(f"Unsupported codec attention backend/device: {attention_backend}/{device.type}")
from vllm_omni.model_executor.models.moss_tts.audio_tokenizer_v2 import MossAudioTokenizerMultiheadAttention
from vllm_omni.model_executor.models.moss_tts.streaming_attention import masked_attention
if attention_backend == "triton_slot":
from vllm_omni.model_executor.models.moss_tts.slot_attention import (
slot_ring_attention,
slot_ring_attention_rows,
)
skip_empty_tiles = bool(self._connector_int("codec_skip_empty_attention_tiles", default=0))
fused_slots = bool(self._connector_int("codec_fused_slot_attention", default=0))
if skip_empty_tiles and fused_slots:
raise ValueError("codec_skip_empty_attention_tiles requires unfused slot attention")
if skip_empty_tiles:
slot_ring_attention = partial(slot_ring_attention, skip_empty_tiles=True)
logger.info("MOSS codec slot attention: skipping empty tiles for T <= 32")
for module in codec.decoder.modules():
if isinstance(module, MossAudioTokenizerMultiheadAttention):
module._streaming_attention = masked_attention
logger.info("Enabled Triton masked attention for the streaming codec decoder")
if attention_backend == "triton_slot":
module._slot_attention = slot_ring_attention
if self._connector_int("codec_fused_slot_attention", default=0):
module._slot_attention_rows = slot_ring_attention_rows
logger.info("Enabled codec attention backend=%s", attention_backend)
build_decode_lut = getattr(codec.quantizer, "build_decode_lut", None)
if callable(build_decode_lut):
lut_dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
@@ -21,7 +21,8 @@ checkpoint 1:1 so ``load_weights()`` needs no remapping.
from __future__ import annotations
from collections.abc import Sequence
import os
from collections.abc import Callable, Sequence
import torch
import torch.nn as nn
@@ -52,6 +53,7 @@ class _MossTTSLocalAttention(nn.Module):
self.n_head = n_head
self.head_dim = hidden_size // n_head
self.embed_dim = hidden_size
self._short_attention = os.environ.get("VLLM_OMNI_MOSS_LOCAL_SHORT_ATTN", "0") == "1"
self.c_attn = nn.Linear(hidden_size, 3 * hidden_size, bias=True)
self.c_proj = nn.Linear(hidden_size, hidden_size, bias=True)
inv_freq = 1.0 / (rope_base ** (torch.arange(0, self.head_dim, 2, dtype=torch.float32) / self.head_dim))
@@ -134,7 +136,19 @@ class _MossTTSLocalAttention(nn.Module):
v_cache[:, :, position : position + 1].copy_(value)
key = k_cache[:, :, : position + 1]
value = v_cache[:, :, : position + 1]
attn_output = F.scaled_dot_product_attention(query, key, value, is_causal=kv_cache is None)
if (
self._short_attention
and kv_cache is not None
and query.is_cuda
and query.dtype == torch.bfloat16
and self.head_dim <= 128
and key.shape[2] <= 16
):
from vllm_omni.model_executor.models.moss_tts.local_short_attention import local_short_attention
attn_output = local_short_attention(query, key, value)
else:
attn_output = F.scaled_dot_product_attention(query, key, value, is_causal=kv_cache is None)
attn_output = attn_output.transpose(1, 2).reshape(batch_size, seq_len, self.embed_dim)
return self.c_proj(attn_output)
@@ -193,6 +207,7 @@ class MossTTSLocalDepthTransformer(nn.Module):
self.h = nn.ModuleList([_MossTTSLocalBlock(self.hidden_size, n_head, inner_size, rope_base, eps)])
self.ln_f = nn.LayerNorm(self.hidden_size, eps=eps)
self._compiled_forward_prefix = None
self._compiled_audio_sampler = None
def _forward_prefix(
self,
@@ -216,6 +231,14 @@ class MossTTSLocalDepthTransformer(nn.Module):
dynamic=True,
options={"epilogue_fusion": False},
)
if os.environ.get("VLLM_OMNI_MOSS_LOCAL_COMPILE_AUDIO_SAMPLER", "0") == "1":
# Keep the existing top-k/top-p algorithm and torch RNG. Explicit
# per-request generators use the original helper below. The
# binary continue/stop head is deliberately unchanged.
self._compiled_audio_sampler = torch.compile(
_sample_token, fullgraph=True, dynamic=True, options={"fallback_random": True}
)
logger.info("MOSS-TTS Local compiled audio-channel sampler enabled")
logger.info("MOSS-TTS local depth frame-local KV execution enabled with torch.compile")
def _run_prefix(
@@ -239,6 +262,7 @@ class MossTTSLocalDepthTransformer(nn.Module):
do_sample: bool,
generator: torch.Generator | None,
generators: Sequence[torch.Generator | None] | None = None,
sample_token: Callable[..., torch.Tensor] | None = None,
) -> torch.Tensor:
"""Compute channel logits, apply repetition penalty, sample, store."""
channel_logits = audio_lm_heads[channel_index](local_hidden).float()
@@ -250,7 +274,7 @@ class MossTTSLocalDepthTransformer(nn.Module):
pos = sel > 0
sel = torch.where(pos, sel / repetition_penalty, sel * repetition_penalty)
channel_logits.index_copy_(-1, hist_t, sel)
channel_token = _sample_token(
channel_token = (sample_token or _sample_token)(
channel_logits,
temperature,
top_k,
@@ -351,6 +375,7 @@ class MossTTSLocalDepthTransformer(nn.Module):
do_sample=do_sample,
generator=generator,
generators=generators,
sample_token=self._compiled_audio_sampler if generator is None and generators is None else None,
)
if channel_index + 1 < n_vq:
@@ -37,6 +37,7 @@ from vllm_omni.model_executor.models.moss_tts.modeling_moss_tts_local_depth impo
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.platforms import current_omni_platform
from vllm_omni.worker.sampling_utils import get_tts_local_seed
logger = init_logger(__name__)
@@ -1675,6 +1676,31 @@ class MossTTSLocalTalkerForGeneration(nn.Module):
return input_embeds_out, output_codes
# ------------------------------------------------------------------
# MRV2 reads model-owned capabilities; retain the V1 hook and platform
# graph-safety setting as the canonical implementation.
mtp = talker_mtp
get_mtp_seed = staticmethod(get_tts_local_seed)
def create_mrv2_model_state(self, vllm_config, encoder_cache, device):
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState
state_cls = OmniModelState
if getattr(self.config, "mrv2_gpu_slot_state", False):
from .local_model_state import MossLocalModelState
state_cls = MossLocalModelState
return state_cls(vllm_config, self, encoder_cache, device)
@property
def mtp_output_key(self) -> tuple[str, str]:
"""Return the request-buffer destination for one local audio frame."""
return self.talker_mtp_output_key
@property
def mtp_graph_safe(self) -> bool:
"""Honor the same platform graph-safety override as the V1 runner."""
return self.talker_mtp_graph_safe
# Package runner-generated audio frames
# ------------------------------------------------------------------
@@ -97,6 +97,7 @@ MOSS_TTS_LOCAL_PIPELINE = PipelineConfig(
StagePipelineConfig(
stage_id=0,
model_stage="moss_tts_local",
supports_native_mrv2_data_plane=True,
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
@@ -114,6 +115,7 @@ MOSS_TTS_LOCAL_PIPELINE = PipelineConfig(
StagePipelineConfig(
stage_id=1,
model_stage="moss_tts_local_codec",
supports_native_mrv2_data_plane=True,
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(0,),
final_output=True,
@@ -25,7 +25,10 @@ so importing it from the API-server process does not pull the talker/codec.
from __future__ import annotations
import asyncio
import contextlib
import hashlib
import os
from collections import OrderedDict
from collections.abc import Awaitable, Callable
from functools import lru_cache
from typing import Any
@@ -35,22 +38,93 @@ import torch
from numpy.typing import NDArray
from vllm.logger import init_logger
from vllm_omni.model_executor.models.moss_tts.reference_encoder_graphs import (
FINE_BATCH_SIZES,
FINE_BUCKET_SECONDS,
MossReferenceEncoderGraphs,
install_windowed_attention,
)
from vllm_omni.model_executor.models.moss_tts.shared_reference_encoder import (
SharedReferenceEncoderClient,
SharedReferenceEncoderHost,
SharedReferenceEncoderStartupError,
elect_host,
)
logger = init_logger(__name__)
# Coalescing defaults. Kept as module constants (not env/CLI) to match the
# ``_REF_AUDIO_RESOLVE_CACHE_MAX_*`` convention in serving_speech.py.
_REF_ENCODE_BATCH_WINDOW_MS = 10.0
_REF_ENCODE_MAX_BATCH = 8
_REF_ENCODE_MAX_BATCH = 32
# Experiment switches for cold-reference latency (see the A/B notes):
# batch window in ms; batches in flight per API process with a shared encoder;
# "high" puts reference encodes on the highest-priority CUDA stream.
_REF_ENCODE_WINDOW_ENV = "VLLM_OMNI_MOSS_REF_BATCH_WINDOW_MS"
_REF_ENCODE_INFLIGHT_ENV = "VLLM_OMNI_MOSS_REF_INFLIGHT"
_REF_ENCODE_PRIORITY_ENV = "VLLM_OMNI_MOSS_REF_STREAM_PRIORITY"
# "1" resamples and loudness-normalizes clips on the encoder's GPU instead of
# the API process's CPU (not bit-identical to the CPU path).
_REF_ENCODE_GPU_PREP_ENV = "VLLM_OMNI_MOSS_REF_GPU_PREP"
_INT32_MAX = 2**31
# Inline (data: URI) references already resolved and encoded, keyed by the
# serving resolve key. Codes are small; the URI itself is not retained.
_INLINE_INDEX_MAX_ENTRIES = 4096
# Optional directory (e.g. under /dev/shm) that API processes of one server
# share, so an inline reference encoded by any frontend is reused by all.
_SHARED_CODES_DIR_ENV = "VLLM_OMNI_MOSS_REF_CODES_SHARED_DIR"
# "0" keeps one reference encoder per API process even with a shared directory.
_SHARED_ENCODER_ENV = "VLLM_OMNI_MOSS_REF_SHARED_ENCODER"
_shared_role: str | None = None
# Concurrent encode workers in the shared host, each with its own CUDA graphs.
_SHARED_WORKERS_ENV = "VLLM_OMNI_MOSS_REF_ENCODER_WORKERS"
_SHARED_WORKER_BATCH_SECONDS = 96.0
def shared_encoder_role() -> str:
"""``"host"``, ``"client"`` or ``""`` (no shared encoder) for this process.
Decided once, before the processor places its tokenizer on the GPU, so
client processes can leave it on the CPU.
"""
global _shared_role
if _shared_role is None:
shared_dir = os.environ.get(_SHARED_CODES_DIR_ENV)
if not shared_dir or os.environ.get(_SHARED_ENCODER_ENV, "1") == "0":
_shared_role = ""
else:
os.makedirs(shared_dir, exist_ok=True)
_shared_role = "host" if elect_host(shared_dir) else "client"
return _shared_role
# Opt in to reference graphs; existing deployments keep the eager encoder.
_REF_ENCODE_GRAPHS_ENV = "VLLM_OMNI_MOSS_REF_GRAPHS"
def reference_graphs_enabled() -> bool:
return os.environ.get(_REF_ENCODE_GRAPHS_ENV, "0") == "1"
def reference_stream_priority() -> int:
"""CUDA stream priority for reference encodes (lower is more urgent)."""
if os.environ.get(_REF_ENCODE_PRIORITY_ENV, "") == "high" and torch.cuda.is_available():
return torch.cuda.Stream.priority_range()[1]
return 0
# "sdpa" keeps the tokenizer's dense masked SDPA attention. By default the
# reference encoder attends through a local-window flash kernel, the backend
# the tokenizer config selects (flash_attention_2) when flash-attn is present.
_REF_ENCODE_ATTN_ENV = "VLLM_OMNI_MOSS_REF_ATTN"
# "0" captures the encoder's eager kernels. By default the captured encoder is
# compiled first, which fuses its many small elementwise kernels.
_REF_ENCODE_COMPILE_ENV = "VLLM_OMNI_MOSS_REF_COMPILE"
_Waveform = NDArray[np.float32] | list[float]
def _sha1(s: str) -> str:
return hashlib.sha1((s or "").encode("utf-8")).hexdigest()
@lru_cache(maxsize=16)
def _reference_resampler(sr: int, sr_target: int) -> torch.nn.Module:
import torchaudio
@@ -72,6 +146,13 @@ def _prep_wav_sync(waveform: _Waveform, sr: int, sr_target: int) -> torch.Tensor
return wav
def _inline_reference_key(ref_str: str) -> str | None:
"""SHA-1 of a ``data:`` URI, matching the serving resolve key for it."""
if not isinstance(ref_str, str) or ref_str[:5].lower() != "data:":
return None
return hashlib.sha1(ref_str.encode("utf-8")).hexdigest()
def _to_compact_codes(codes: torch.Tensor) -> torch.Tensor:
"""Downcast RVQ codes to int32 for compact caching."""
codes = codes.detach().cpu().contiguous()
@@ -119,18 +200,26 @@ class _RefEncodeBatcher:
*,
window_ms: float,
max_batch: int,
max_inflight: int = 1,
):
# encode_batch_fn: sync, takes [(waveform, sr), ...], returns a list of
# (codes_tensor | Exception) aligned to the input order.
self._encode_batch_fn = encode_batch_fn
self._window_s = max(0.0, float(window_ms) / 1000.0)
self._max_batch = max(1, int(max_batch))
# Batches encoded at once. Clips that arrive while every slot is busy
# are queued and form the next batch.
self._max_inflight = max(1, int(max_inflight))
self._queue: asyncio.Queue | None = None
self._slots: asyncio.Semaphore | None = None
self._inflight: set[asyncio.Task] = set()
self._drainer: asyncio.Task | None = None
def _ensure_started(self) -> None:
if self._queue is None:
self._queue = asyncio.Queue()
if self._slots is None:
self._slots = asyncio.Semaphore(self._max_inflight)
if self._drainer is None or self._drainer.done():
self._drainer = asyncio.create_task(self._drain_loop())
@@ -141,16 +230,27 @@ class _RefEncodeBatcher:
return await fut
async def _drain_loop(self) -> None:
assert self._queue is not None
assert self._queue is not None and self._slots is not None
while True:
first = await self._queue.get()
jobs = None
await self._slots.acquire()
try:
jobs = await self._coalesce(first)
await self._run_batch(jobs)
finally:
# Do not retain the completed batch while waiting for new work.
del first, jobs
jobs = await self._coalesce(await self._queue.get())
except BaseException:
self._slots.release()
raise
task = asyncio.create_task(self._run_and_release(jobs))
self._inflight.add(task)
task.add_done_callback(self._inflight.discard)
# Do not retain the batch here while waiting for new work.
del jobs
async def _run_and_release(self, jobs: list[tuple[_Waveform, int, asyncio.Future]]) -> None:
try:
await self._run_batch(jobs)
finally:
del jobs
assert self._slots is not None
self._slots.release()
async def _coalesce(self, first: tuple) -> list[tuple]:
"""Group ``first`` with jobs arriving within the batch window."""
@@ -200,6 +300,8 @@ class _RefEncodeBatcher:
except (asyncio.CancelledError, Exception): # noqa: BLE001
pass
self._drainer = None
for task in list(self._inflight):
task.cancel()
class MossReferenceEncoder:
@@ -213,7 +315,7 @@ class MossReferenceEncoder:
n_vq: int,
sr_target: int,
speaker_cache: Any,
window_ms: float = _REF_ENCODE_BATCH_WINDOW_MS,
window_ms: float | None = None,
max_batch: int = _REF_ENCODE_MAX_BATCH,
):
self._processor = processor
@@ -224,8 +326,33 @@ class MossReferenceEncoder:
# model_type namespaces the whole family so a moss_tts server never
# collides with another model's speaker-cache entries.
self._model_type = f"moss_tts_{variant}_nq{int(n_vq)}"
self._inflight: dict[str, asyncio.Task] = {}
self._batcher = _RefEncodeBatcher(self._encode_batch_sync, window_ms=window_ms, max_batch=max_batch)
self._inflight: dict[str | tuple[str, str], asyncio.Task] = {}
self._inline_index: OrderedDict[str, torch.Tensor] = OrderedDict()
self._shared_codes_dir = os.environ.get(_SHARED_CODES_DIR_ENV) or None
if self._shared_codes_dir:
os.makedirs(self._shared_codes_dir, exist_ok=True)
# Realtime encodes with its own codec and never shares the encoder.
self._shares_encoder = bool(self._shared_codes_dir) and type(self)._encode_prepared is (
MossReferenceEncoder._encode_prepared
)
self._shared_host: SharedReferenceEncoderHost | None = None
self._shared_client: SharedReferenceEncoderClient | None = None
self._graphs: MossReferenceEncoderGraphs | None = None
self._attention_installed = False
self._graphs_enabled = reference_graphs_enabled()
if window_ms is None:
window_ms = float(os.environ.get(_REF_ENCODE_WINDOW_ENV, _REF_ENCODE_BATCH_WINDOW_MS))
# A shared encoder serves several batches at once (one per host
# worker); a process's own graphs replay one batch at a time.
inflight = 1
if self._shares_encoder and os.environ.get(_SHARED_ENCODER_ENV, "1") != "0":
inflight = max(1, int(os.environ.get(_REF_ENCODE_INFLIGHT_ENV, "1")))
self._local_stream: torch.cuda.Stream | None = None
self._gpu_prep = os.environ.get(_REF_ENCODE_GPU_PREP_ENV, "0") == "1"
self._gpu_resamplers: dict[torch.device, torch.nn.Module] = {}
self._batcher = _RefEncodeBatcher(
self._encode_batch_sync, window_ms=window_ms, max_batch=max_batch, max_inflight=inflight
)
def _make_cache_key(self, name: str, created_at: int) -> tuple:
return self._speaker_cache.make_cache_key(name, model_type=self._model_type, created_at=int(created_at))
@@ -251,6 +378,7 @@ class MossReferenceEncoder:
caller salts those requests with ``voice_created_at`` instead).
"""
voice_name, created_at = _registered_voice(voice_name, voice_created_at)
inline_key: str | None = None
if voice_name:
# A named voice has a stable key that does not depend on the
@@ -260,6 +388,16 @@ class MossReferenceEncoder:
if cached is not None:
return _clone_out(cached["codes"]), None
else:
inline_key = _inline_reference_key(ref_str)
if inline_key is not None:
codes = self._inline_index.get(inline_key)
if codes is None:
codes = self._load_shared_codes(inline_key)
if codes is not None:
# A data: URI is immutable content, and its serving
# resolve key is this same digest: skip the resolve hop.
self._inline_index.move_to_end(inline_key)
return _clone_out(codes), inline_key
# Anonymous refs have no pre-resolve hot path: the content key must
# come from the resolve itself (mtime/size from a single stat) so an
# on-disk edit invalidates the cached codes; the flight body
@@ -267,17 +405,55 @@ class MossReferenceEncoder:
# when the resolve cache is warm. The flight key is the request-side
# reference (not the content hash), so concurrent requests for the
# same ref_str also share the resolve/download, not just the encode.
flight_key = "ref:" + _sha1(ref_str)
# Key by the locator itself: equality is exact, and hashing a
# large inline data URI once per request object is much cheaper
# than a separate SHA-1 of its UTF-8 copy on the event loop.
flight_key = ("ref", ref_str)
codes, resolve_key = await self._single_flight(
flight_key,
lambda: self._resolve_and_encode(ref_str, resolve_ref_audio, get_artifact_key, voice_name, created_at),
)
if not voice_name and inline_key is not None and resolve_key == inline_key:
# Only index when the resolver's key is exactly this digest.
self._remember_inline(inline_key, codes)
self._store_shared_codes(inline_key, codes)
return _clone_out(codes), resolve_key
def _remember_inline(self, key: str, codes: torch.Tensor) -> None:
self._inline_index[key] = codes
self._inline_index.move_to_end(key)
while len(self._inline_index) > _INLINE_INDEX_MAX_ENTRIES:
self._inline_index.popitem(last=False)
def _load_shared_codes(self, key: str) -> torch.Tensor | None:
if not self._shared_codes_dir:
return None
try:
array = np.load(os.path.join(self._shared_codes_dir, key + ".npy"), allow_pickle=False)
except (OSError, ValueError):
return None
if array.ndim != 2 or array.shape[1] != self._n_vq or array.dtype not in (np.int32, np.int64):
return None
codes = torch.from_numpy(array)
self._remember_inline(key, codes)
return codes
def _store_shared_codes(self, key: str, codes: torch.Tensor) -> None:
if not self._shared_codes_dir:
return
path = os.path.join(self._shared_codes_dir, key + ".npy")
tmp = f"{path}.{os.getpid()}.tmp"
try:
with open(tmp, "wb") as handle:
np.save(handle, codes.detach().cpu().numpy(), allow_pickle=False)
os.replace(tmp, path)
except OSError:
logger.warning("MOSS ref codes: could not write shared entry %s", path, exc_info=True)
async def _single_flight(
self,
flight_key: str,
flight_key: str | tuple[str, str],
start_flight: Callable[[], Awaitable[tuple[torch.Tensor, str]]],
) -> tuple[torch.Tensor, str]:
"""Join the in-flight encode for ``flight_key``, starting one if absent.
@@ -300,7 +476,7 @@ class MossReferenceEncoder:
# a duplicate resolve/encode instead of joining this one. Identity
# guard: only drop the slot if it still holds *our* task (a later
# request may have replaced it after ours completed).
def _retire(t: asyncio.Task, key: str = flight_key) -> None:
def _retire(t: asyncio.Task, key: str | tuple[str, str] = flight_key) -> None:
if self._inflight.get(key) is t:
self._inflight.pop(key, None)
@@ -350,29 +526,228 @@ class MossReferenceEncoder:
prepared_idx: list[int] = []
for i, (waveform, sr) in enumerate(payload):
try:
prepared.append(_prep_wav_sync(waveform, sr, self._sr_target))
prepared.append(self._encoder_input(_prep_wav_sync(waveform, sr, self._sr_target)))
prepared_idx.append(i)
except Exception as exc: # noqa: BLE001 — isolate this clip's failure
results[i] = exc
if not prepared:
return results
try:
codes_list = self._encode_prepared(prepared)
for local_i, orig_i in enumerate(prepared_idx):
results[orig_i] = codes_list[local_i]
except Exception: # noqa: BLE001 — batch forward failed; retry item-by-item
logger.warning("MOSS ref batch encode (n=%d) failed; falling back to per-item", len(prepared))
for local_i, orig_i in enumerate(prepared_idx):
try:
results[orig_i] = self._encode_prepared([prepared[local_i]])[0]
except Exception as exc: # noqa: BLE001 — isolate this clip's failure
results[orig_i] = exc
for orig_i, codes in zip(prepared_idx, self._encode_shared_or_local(prepared)):
results[orig_i] = codes
return results
def _encode_prepared(self, prepared: list[torch.Tensor]) -> list[torch.Tensor]:
with torch.no_grad():
return self._processor.encode_audios_from_wav(prepared, sampling_rate=self._sr_target, n_vq=self._n_vq)
def prepare(self) -> None:
"""Capture the CUDA graphs (or start the shared encoder) before the first request."""
role = shared_encoder_role() if self._shares_encoder else ""
if role == "host":
self._host().wait_until_ready()
elif role == "client":
if self._shared_client is None:
self._shared_client = SharedReferenceEncoderClient(self._shared_codes_dir)
self._shared_client.wait_until_ready()
elif role == "":
self._reference_graphs()
def _host(self) -> SharedReferenceEncoderHost:
if self._shared_host is None:
# Graph capture runs in the background; clips queue until it ends.
self._shared_host = SharedReferenceEncoderHost(
self._shared_codes_dir,
self._host_workers(),
stream_priority=reference_stream_priority(),
batch_window_ms=float(os.environ.get("VLLM_OMNI_MOSS_REF_HOST_WINDOW_MS", "0")),
)
return self._shared_host
def _encode_shared_or_local(self, prepared: list[torch.Tensor]) -> list:
role = shared_encoder_role() if self._shares_encoder else ""
if role == "host":
return self._host().encode(prepared)
if role == "client":
if self._shared_client is None:
self._shared_client = SharedReferenceEncoderClient(self._shared_codes_dir)
try:
return self._shared_client.encode(prepared)
except SharedReferenceEncoderStartupError:
raise
except Exception: # noqa: BLE001 — the host is unreachable: encode here
logger.warning("MOSS shared reference encoder unavailable; encoding locally", exc_info=True)
self._place_tokenizer_for_local_encode()
with self._local_stream_context():
return self._encode_local(prepared)
def _local_stream_context(self):
tokenizer = getattr(self._processor, "audio_tokenizer", None)
params = next(tokenizer.parameters(), None) if isinstance(tokenizer, torch.nn.Module) else None
if params is None or params.device.type != "cuda":
return contextlib.nullcontext()
if self._local_stream is None:
self._local_stream = torch.cuda.Stream(device=params.device, priority=reference_stream_priority())
return torch.cuda.stream(self._local_stream)
def _host_workers(self) -> list:
"""Encode workers of the shared host, each with its own graphs and stream."""
count = max(1, int(os.environ.get(_SHARED_WORKERS_ENV, "4")))
if not self._graph_capable():
return [(self._encode_local, None)] * count
workers = []
for _ in range(count):
graphs = MossReferenceEncoderGraphs(
self._processor.audio_tokenizer,
n_vq=self._n_vq,
batch_sizes=FINE_BATCH_SIZES,
bucket_seconds=FINE_BUCKET_SECONDS,
max_batch_seconds=_SHARED_WORKER_BATCH_SECONDS,
compile_core=self._compile_graphs(),
batched_transfer=os.environ.get("VLLM_OMNI_MOSS_REF_BATCHED_TRANSFER", "0") == "1",
singleton_bucket_seconds=self._singleton_bucket_seconds(),
)
workers.append(((lambda wavs, g=graphs: self._encode_local(wavs, g)), graphs.capture))
return workers
def _encode_local(self, prepared: list[torch.Tensor], graphs: MossReferenceEncoderGraphs | None = None) -> list:
"""One batched forward, retried per clip so one bad clip fails alone."""
try:
return list(self._encode_prepared(prepared, graphs))
except Exception: # noqa: BLE001 — batch forward failed; retry item-by-item
logger.warning("MOSS ref batch encode (n=%d) failed; falling back to per-item", len(prepared))
results: list = []
for wav in prepared:
try:
results.append(self._encode_prepared([wav], graphs)[0])
except Exception as exc: # noqa: BLE001 — isolate this clip's failure
results.append(exc)
return results
def _place_tokenizer_for_local_encode(self) -> None:
"""A client process keeps the tokenizer off the GPU until it must encode."""
tokenizer = getattr(self._processor, "audio_tokenizer", None)
device = getattr(self._processor, "_vllm_omni_ref_encoder_device", None)
if tokenizer is not None and device is not None and next(tokenizer.parameters()).device != device:
self._processor.audio_tokenizer = tokenizer.to(device)
def _encode_prepared(
self, prepared: list[torch.Tensor], graphs: MossReferenceEncoderGraphs | None = None
) -> list[torch.Tensor]:
# ``prepared`` clips come from _encoder_input, at ``_clip_rate()``.
graphs = graphs or self._reference_graphs()
if graphs is None:
with torch.no_grad():
return self._processor.encode_audios_from_wav(
prepared, sampling_rate=self._clip_rate(), n_vq=self._n_vq
)
codes = graphs.encode([self._finish_prepare(wav) for wav in prepared])
missing = [i for i, c in enumerate(codes) if c is None]
if missing:
with torch.no_grad():
eager = self._processor.encode_audios_from_wav(
[prepared[i] for i in missing], sampling_rate=self._clip_rate(), n_vq=self._n_vq
)
for i, c in zip(missing, eager):
codes[i] = c
return codes
def _graph_capable(self) -> bool:
"""True when the tokenizer can run graphs; installs windowed attention once."""
if not self._graphs_enabled:
return False
tokenizer = getattr(self._processor, "audio_tokenizer", None)
device = next(tokenizer.parameters()).device if tokenizer is not None else None
if device is None or device.type != "cuda" or not hasattr(tokenizer, "_codec_inference_autocast"):
self._graphs_enabled = False
return False
if not self._attention_installed and os.environ.get(_REF_ENCODE_ATTN_ENV, "flash") == "flash":
logger.info(
"MOSS reference encoder: %d attention layers use local-window flash attention",
install_windowed_attention(
tokenizer,
fa_version=int(os.environ.get("VLLM_OMNI_MOSS_REF_FA_VERSION", "2")),
cache_rope=os.environ.get("VLLM_OMNI_MOSS_REF_CACHE_ROPE", "0") == "1",
skip_padded_query_mask=os.environ.get("VLLM_OMNI_MOSS_REF_SKIP_PADDED_QUERY_MASK", "0") == "1",
),
)
self._attention_installed = True
return True
@staticmethod
def _compile_graphs() -> bool:
return os.environ.get(_REF_ENCODE_COMPILE_ENV, "1") != "0"
@staticmethod
def _singleton_bucket_seconds() -> tuple[float, ...] | None:
step_ms = int(os.environ.get("VLLM_OMNI_MOSS_REF_SINGLETON_BUCKET_MS", "0"))
if step_ms == 0:
return None
if not 80 <= step_ms <= 1000:
raise ValueError("MOSS reference singleton bucket step must be 80..1000 ms, or 0 to disable")
return tuple(ms / 1000 for ms in range(3000, 10001, step_ms))
def _reference_graphs(self) -> MossReferenceEncoderGraphs | None:
"""Capture on first use, on the encode worker thread that replays them."""
if self._graphs is None:
if not self._graph_capable():
return None
graphs = MossReferenceEncoderGraphs(
self._processor.audio_tokenizer,
n_vq=self._n_vq,
compile_core=self._compile_graphs(),
batched_transfer=os.environ.get("VLLM_OMNI_MOSS_REF_BATCHED_TRANSFER", "0") == "1",
singleton_bucket_seconds=self._singleton_bucket_seconds(),
)
graphs.capture()
self._graphs = graphs
return self._graphs
def _tokenizer_rate(self) -> int:
return int(getattr(getattr(self._processor, "model_config", None), "sampling_rate", self._sr_target))
def _encoder_input(self, wav: torch.Tensor) -> torch.Tensor:
"""A prepped clip at the tokenizer rate, one or two channels.
This is the costly half of the processor's per-clip preparation; it runs
in the process that received the request, even with a shared encoder.
"""
import torchaudio
if wav.ndim == 1:
wav = wav.unsqueeze(0)
if wav.shape[0] > 2:
wav = wav[:2]
if self._clip_rate() != self._sr_target:
# Channels resample independently, so a mono clip is resampled
# once before it is duplicated; the result is the same.
wav = torchaudio.functional.resample(wav, self._sr_target, self._tokenizer_rate())
return wav
def _clip_rate(self) -> int:
"""Sample rate of the clips _encoder_input hands to the encoder."""
return self._sr_target if self._gpu_prep else self._tokenizer_rate()
def _finish_prepare(self, wav: torch.Tensor) -> torch.Tensor:
"""The rest of the processor's preparation: two channels, normalized loudness."""
if self._gpu_prep:
device = next(self._processor.audio_tokenizer.parameters()).device
wav = wav.to(device)
if self._clip_rate() != self._tokenizer_rate():
wav = self._gpu_resampler(device)(wav)
if wav.shape[0] == 1:
wav = wav.repeat(2, 1)
return self._processor.loudness_normalize(wav)
def _gpu_resampler(self, device: torch.device) -> torch.nn.Module:
resampler = self._gpu_resamplers.get(device)
if resampler is None:
import torchaudio
# The same windowed-sinc filter as torchaudio.functional.resample's defaults.
resampler = torchaudio.transforms.Resample(self._sr_target, self._tokenizer_rate()).to(device)
self._gpu_resamplers[device] = resampler
return resampler
def _processor_prepare(self, wav: torch.Tensor) -> torch.Tensor:
"""Per-clip preparation of the processor's ``encode_audios_from_wav``."""
return self._finish_prepare(self._encoder_input(wav))
async def aclose(self) -> None:
"""Release the batcher drainer + any in-flight encodes (tests/shutdown)."""
@@ -385,7 +760,10 @@ class MossReferenceEncoder:
class MossRealtimeReferenceEncoder(MossReferenceEncoder):
"""Use the realtime codec with the shared reference cache and batcher."""
def _encode_prepared(self, prepared: list[torch.Tensor]) -> list[torch.Tensor]:
def _encoder_input(self, wav: torch.Tensor) -> torch.Tensor:
return wav # the realtime codec takes the clip at the working rate
def _encode_prepared(self, prepared: list[torch.Tensor], graphs: Any = None) -> list[torch.Tensor]:
with torch.no_grad():
encoded = self._processor.batch_encode([wav.squeeze(0) for wav in prepared], num_quantizers=self._n_vq)
return [
@@ -0,0 +1,399 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""CUDA graphs for batched MOSS reference-audio encoding.
Reference clips are encoded by the upstream MOSS audio tokenizer that the
processor loads. Its eager forward is dominated by kernel launches for the
small batches that serving produces. This runner replays graphs of the same
encoder and quantizer modules, captured per ``(batch, length)`` bucket. For a
given padded input the codes are bit-identical to the tokenizer's own
``_encode_frame``. Only the per-clip crop, which needs host values, runs
outside the graph.
The encoder is causal, so padding a clip to its length bucket leaves its valid
frames unchanged up to kernel selection for the padded shape, the same effect
that batching already has when the tokenizer pads a batch to its longest clip.
"""
from __future__ import annotations
import math
import types
from dataclasses import dataclass
import torch
from vllm.logger import init_logger
logger = init_logger(__name__)
DEFAULT_BATCH_SIZES = (1, 2, 4, 8, 16, 32)
DEFAULT_BUCKET_SECONDS = (4.0, 6.0, 8.0, 10.0, 12.0, 16.0, 20.0)
# Fine steps keep padding small: a padded row or padded time is encoded in
# full. Worth the extra graphs where several encoders share one GPU.
FINE_BATCH_SIZES = (1, 2, 3, 4, 5, 6, 8)
FINE_BUCKET_SECONDS = (3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 12.0, 14.0, 16.0, 20.0)
# Graphs are captured only while batch * bucket stays within this much audio,
# which bounds the shared graph memory pool by its largest batch.
DEFAULT_MAX_BATCH_SECONDS = 256.0
@torch.compile(dynamic=False)
def _reference_rope_factors(seqlen: int, head_dim: int, max_period: float, device: torch.device):
# Use the same compiled FP32 arithmetic as the encoder. Eager libdevice
# sin/cos and compiled sin/cos can round differently near a VQ boundary.
ds = torch.arange(head_dim // 2, device=device, dtype=torch.float32)
freqs = torch.exp(ds * (-math.log(max_period) * 2 / head_dim))
angles = torch.arange(seqlen, device=device, dtype=torch.float32)[:, None] * freqs[None, :]
return torch.cos(angles), torch.sin(angles)
def _cached_reference_rope(self, q: torch.Tensor, k: torch.Tensor, cache: dict):
if self.rope is None:
return q, k
batch, heads, seqlen, dim = q.shape
key = (dim, self.rope.max_period, q.device)
if key not in cache or cache[key][0].shape[0] < seqlen:
cache[key] = _reference_rope_factors(seqlen, dim, self.rope.max_period, q.device)
cos, sin = cache[key]
cos, sin = cos[:seqlen], sin[:seqlen]
qr, qi = q.view(batch, heads, seqlen, dim // 2, 2).unbind(-1)
kr, ki = k.view(batch, heads, seqlen, dim // 2, 2).unbind(-1)
qr, qi, kr, ki = qr.float(), qi.float(), kr.float(), ki.float()
# Preserve the original arithmetic, casts, and B/H/T/D output layout.
qo = torch.stack(((qr * cos - qi * sin).to(q.dtype), (qr * sin + qi * cos).to(q.dtype)), dim=-1)
ko = torch.stack(((kr * cos - ki * sin).to(k.dtype), (kr * sin + ki * cos).to(k.dtype)), dim=-1)
return qo.view(batch, heads, seqlen, dim), ko.view(batch, heads, seqlen, dim)
def _windowed_attention(
self,
x: torch.Tensor,
input_lengths: torch.Tensor,
*,
sdpa,
fa_version: int = 2,
rope_cache: dict | None = None,
skip_padded_query_mask: bool = False,
) -> torch.Tensor:
"""The tokenizer's non-streaming attention with a local-window flash kernel.
Same projection, RoPE and padded-row zeroing as the tokenizer's SDPA path.
That path masks each query to ``context`` keys (distance 0 .. context-1)
inside a dense block; the flash kernel visits only that window.
"""
batch, seqlen, _ = x.shape
q, k, v = self._project_qkv(x)
q, k = self._apply_dense_rope(q, k) if rope_cache is None else _cached_reference_rope(self, q, k, rope_cache)
if q.dtype not in (torch.bfloat16, torch.float16):
return sdpa(x, input_lengths)
from vllm.vllm_flash_attn import flash_attn_varlen_func
heads, dim = q.shape[1], q.shape[-1]
def packed(t: torch.Tensor) -> torch.Tensor:
return t.transpose(1, 2).reshape(batch * seqlen, heads, dim)
starts = torch.arange(0, (batch + 1) * seqlen, seqlen, device=x.device, dtype=torch.int32)
window = [self.context - 1, 0] if self.causal and self.context is not None else [-1, -1]
out = flash_attn_varlen_func(
packed(q),
packed(k),
packed(v),
max_seqlen_q=seqlen,
cu_seqlens_q=starts,
max_seqlen_k=seqlen,
cu_seqlens_k=starts,
causal=self.causal,
window_size=window,
fa_version=fa_version,
).view(batch, seqlen, heads, dim)
if not skip_padded_query_mask:
valid = (torch.arange(seqlen, device=x.device).view(1, seqlen) < input_lengths.view(-1, 1)).view(
batch, seqlen, 1, 1
)
out = torch.where(valid, out, torch.zeros((), device=out.device, dtype=out.dtype))
return out.reshape(batch, seqlen, self.embed_dim)
def _validate_unmasked_reference_encoder(tokenizer: torch.nn.Module) -> None:
"""Restrict the optimization to the audited HF encoder's valid-prefix contract.
Causal attention and pointwise transformer operations cannot read future
padded rows. Its patch-downsample floors lengths, so every valid output
group consists entirely of valid input rows. The quantizer is pointwise
and the caller crops codes by those lengths. Padded *outputs* may differ.
This argument does not apply to the streaming decoder or to upsampling.
"""
transformers = 0
for module in tokenizer.encoder:
name = type(module).__name__
if name == "MossAudioTokenizerPatchedPretransform" and module.is_downsample:
continue
if name == "MossAudioTokenizerProjectedTransformer":
layers = module.transformer.layers
if layers and all(layer.self_attn.causal for layer in layers):
transformers += 1
continue
raise ValueError("Unmasked reference queries require the causal MOSS patch-downsample encoder")
if not transformers:
raise ValueError("Unmasked reference queries require at least one causal MOSS transformer")
if type(tokenizer.quantizer).__name__ not in {
"MossAudioTokenizerResidualVQ",
"MossAudioTokenizerResidualLFQ",
}:
raise ValueError("Unmasked reference queries require the pointwise MOSS quantizer")
for module in tokenizer.quantizer.modules():
if isinstance(module, torch.nn.Conv1d) and module.kernel_size != (1,):
raise ValueError("Unmasked reference queries do not support temporal quantizer convolutions")
def install_windowed_attention(
tokenizer: torch.nn.Module,
*,
fa_version: int = 2,
cache_rope: bool = False,
skip_padded_query_mask: bool = False,
) -> int:
"""Route the encoder's non-streaming attention through a local-window flash kernel."""
if skip_padded_query_mask:
_validate_unmasked_reference_encoder(tokenizer)
logger.info("MOSS reference encoder: skipping padded query masks (valid-prefix outputs only)")
count = 0
rope_cache = {} if cache_rope else None
if cache_rope:
tokenizer._moss_reference_rope_cache = rope_cache
tokenizer._moss_reference_rope_prepared_samples = 0
for module in tokenizer.encoder.modules():
sdpa = getattr(module, "_forward_non_streaming_sdpa", None)
if sdpa is None or not hasattr(module, "_project_qkv") or not getattr(module, "causal", False):
continue
def attention(self, x, input_lengths, _sdpa=sdpa):
return _windowed_attention(
self,
x,
input_lengths,
sdpa=_sdpa,
fa_version=fa_version,
rope_cache=rope_cache,
skip_padded_query_mask=skip_padded_query_mask,
)
module._forward_non_streaming_sdpa = types.MethodType(attention, module)
count += 1
return count
@dataclass
class _Graph:
graph: torch.cuda.CUDAGraph
audio: torch.Tensor # (B, C, T) float32 input
lengths: torch.Tensor # (B,) int64 input, in samples per channel
codes: torch.Tensor # (n_vq, B, frames) output
code_lengths: torch.Tensor # (B,) output
class MossReferenceEncoderGraphs:
"""Encode prepared reference waveforms with captured tokenizer graphs."""
def __init__(
self,
tokenizer: torch.nn.Module,
*,
n_vq: int,
batch_sizes: tuple[int, ...] = DEFAULT_BATCH_SIZES,
bucket_seconds: tuple[float, ...] = DEFAULT_BUCKET_SECONDS,
max_batch_seconds: float = DEFAULT_MAX_BATCH_SECONDS,
compile_core: bool = False,
batched_transfer: bool = False,
singleton_bucket_seconds: tuple[float, ...] | None = None,
) -> None:
self._tokenizer = tokenizer
self._compile_core = compile_core
self._batched_transfer = batched_transfer
self._n_vq = int(n_vq)
self._device = next(tokenizer.parameters()).device
self._channels = int(tokenizer.number_channels)
frame = int(tokenizer.downsample_rate)
sampling_rate = int(tokenizer.sampling_rate)
# Whole frames, so the tokenizer's own frame padding is a no-op.
self._buckets = sorted({int(math.ceil(s * sampling_rate / frame)) * frame for s in bucket_seconds})
self._singleton_buckets = sorted(
set(self._buckets)
| {int(math.ceil(s * sampling_rate / frame)) * frame for s in (singleton_bucket_seconds or ())}
)
self._batch_sizes = sorted({int(b) for b in batch_sizes if int(b) > 0})
self._max_batch_samples = float(max_batch_seconds) * sampling_rate
self._graphs: dict[tuple[int, int], _Graph] = {}
self._pool = None
self._transfer_buffers = None
@property
def max_batch(self) -> int:
return self._batch_sizes[-1]
@property
def captured(self) -> list[tuple[int, int]]:
return sorted(self._graphs)
def _core(self, audio: torch.Tensor, lengths: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
# Mirrors the tokenizer's _encode_frame without its host-side crop.
tokenizer = self._tokenizer
values, value_lengths = tokenizer._flatten_channels_for_codec(audio, lengths)
with tokenizer._codec_inference_autocast():
hidden, hidden_lengths = values, value_lengths
for module in tokenizer.encoder:
hidden, hidden_lengths = module(hidden, hidden_lengths)
_, codes, code_lengths = tokenizer.quantizer(hidden.float(), hidden_lengths, self._n_vq)
return codes, code_lengths
@torch.no_grad()
def capture(self) -> None:
if self._device.type != "cuda" or self._graphs:
return
self._pool = torch.cuda.graph_pool_handle()
stream = torch.cuda.Stream(device=self._device)
prepared = getattr(self._tokenizer, "_moss_reference_rope_prepared_samples", None)
max_samples = max(self._singleton_buckets)
if prepared is not None and prepared < max_samples:
# Prime immutable FP32 factors at the largest length before any
# capture or compilation. Smaller lengths use a prefix of the
# same table; the dictionary stays fixed throughout capture and
# workers share tables without introducing dynamic-shape guards
# for a separate dictionary key at each sequence length.
audio = torch.zeros(1, self._channels, max_samples, device=self._device)
lengths = torch.full((1,), max_samples, dtype=torch.long, device=self._device)
self._core(audio, lengths)
self._tokenizer._moss_reference_rope_prepared_samples = max_samples
core = self._core
if self._compile_core:
# Fuses the encoder's many small elementwise kernels (casts, RoPE,
# residuals). Only capture runs the compiled code; replays do not.
core = torch.compile(self._core, dynamic=True)
# Each encoder stage is its own module shape: allow a compile per stage.
with torch._dynamo.config.patch(recompile_limit=64):
self._capture_all(core, stream)
if self._batched_transfer and self._graphs:
# One reusable slab per worker, rather than one per graph bucket.
entries = list(self._graphs.values())
self._transfer_buffers = (
torch.empty(max(e.audio.numel() for e in entries), dtype=entries[0].audio.dtype, pin_memory=True),
torch.empty(max(e.lengths.numel() for e in entries), dtype=entries[0].lengths.dtype, pin_memory=True),
torch.empty(max(e.codes.numel() for e in entries), dtype=entries[0].codes.dtype, pin_memory=True),
torch.empty(
max(e.code_lengths.numel() for e in entries), dtype=entries[0].code_lengths.dtype, pin_memory=True
),
torch.cuda.Event(),
)
logger.info(
"MOSS reference encoder CUDA graphs: batch=%s buckets(s)=%s compiled=%s captured=%d",
self._batch_sizes,
[round(s / int(self._tokenizer.sampling_rate), 2) for s in self._buckets],
self._compile_core,
len(self._graphs),
)
if self._singleton_buckets != self._buckets:
logger.info(
"MOSS reference encoder singleton buckets(s): %s",
[round(s / int(self._tokenizer.sampling_rate), 2) for s in self._singleton_buckets],
)
def _capture_all(self, core, stream: torch.cuda.Stream) -> None:
for batch in reversed(self._batch_sizes):
buckets = self._singleton_buckets if batch == 1 else self._buckets
for samples in reversed(buckets):
if batch > 1 and batch * samples > self._max_batch_samples:
continue
audio = torch.zeros(batch, self._channels, samples, device=self._device)
lengths = torch.full((batch,), samples, dtype=torch.long, device=self._device)
try:
stream.wait_stream(torch.cuda.current_stream(self._device))
with torch.cuda.stream(stream):
# Lazy library setup must happen before capture; one run does it.
core(audio, lengths)
torch.cuda.current_stream(self._device).wait_stream(stream)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, pool=self._pool, stream=stream):
codes, code_lengths = core(audio, lengths)
except Exception:
logger.warning(
"MOSS reference encoder graph (B=%d, samples=%d) not captured; using eager",
batch,
samples,
exc_info=True,
)
continue
self._graphs[(batch, samples)] = _Graph(graph, audio, lengths, codes, code_lengths)
@torch.no_grad()
def encode(self, wavs: list[torch.Tensor]) -> list[torch.Tensor | None]:
"""Codes ``(frames, n_vq)`` int64 on CPU per clip; None where no graph fits.
``wavs`` are prepared the way the processor prepares them: ``(C, T)``
float32 after channel handling, resampling and loudness normalization.
Clips are grouped longest first, so each replay pads to the bucket of
similar-length clips.
"""
out: list[torch.Tensor | None] = [None] * len(wavs)
order = sorted(range(len(wavs)), key=lambda i: -int(wavs[i].shape[-1]))
pos = 0
while pos < len(order):
longest = int(wavs[order[pos]].shape[-1])
# Fine singleton buckets reduce padding without fragmenting an
# already assembled batch into separate graph replays.
buckets = self._singleton_buckets if len(order) - pos == 1 else self._buckets
samples = next((s for s in buckets if s >= longest and (1, s) in self._graphs), None)
if samples is None:
pos += 1 # longer than every bucket: left to the caller
continue
widest = max(b for b in self._batch_sizes if (b, samples) in self._graphs)
rows = order[pos : pos + widest]
batch = next(b for b in self._batch_sizes if b >= len(rows) and (b, samples) in self._graphs)
for row, codes in zip(rows, self._replay(self._graphs[(batch, samples)], [wavs[i] for i in rows])):
out[row] = codes
pos += len(rows)
return out
def _replay(self, entry: _Graph, wavs: list[torch.Tensor]) -> list[torch.Tensor]:
if self._transfer_buffers is not None and all(w.device.type == "cpu" for w in wavs):
return self._replay_batched_transfer(entry, wavs)
count, batch, samples = len(wavs), entry.audio.shape[0], entry.audio.shape[-1]
# Unused rows encode full-length silence: a fully masked row would be
# all-NaN inside attention, and rows never mix.
entry.audio.zero_()
lengths = [int(w.shape[-1]) for w in wavs] + [samples] * (batch - count)
entry.lengths.copy_(torch.tensor(lengths, dtype=torch.long))
for row, wav in enumerate(wavs):
entry.audio[row, :, : wav.shape[-1]].copy_(wav)
entry.graph.replay()
codes = entry.codes[:, :count].cpu()
code_lengths = entry.code_lengths[:count].tolist()
return [codes[:, row, : int(code_lengths[row])].transpose(0, 1).contiguous().long() for row in range(count)]
def _replay_batched_transfer(self, entry: _Graph, wavs: list[torch.Tensor]) -> list[torch.Tensor]:
"""Stage one batch on pinned host memory, then wait once for its outputs."""
audio_slab, lengths_slab, codes_slab, code_lengths_slab, copied = self._transfer_buffers
count, batch, samples = len(wavs), entry.audio.shape[0], entry.audio.shape[-1]
audio = audio_slab[: entry.audio.numel()].view_as(entry.audio)
lengths = lengths_slab[:batch]
audio.zero_()
lengths.fill_(samples)
for row, wav in enumerate(wavs):
audio[row, :, : wav.shape[-1]].copy_(wav)
lengths[row] = wav.shape[-1]
entry.audio.copy_(audio, non_blocking=True)
entry.lengths.copy_(lengths, non_blocking=True)
entry.graph.replay()
result = entry.codes[:, :count]
codes = codes_slab[: result.numel()].view_as(result)
code_lengths = code_lengths_slab[:count]
codes.copy_(result, non_blocking=True)
code_lengths.copy_(entry.code_lengths[:count], non_blocking=True)
copied.record(torch.cuda.current_stream(self._device))
copied.synchronize()
# Returned codes must outlive this worker's next replay, including
# one-frame clips whose transpose is already contiguous.
return [
codes[:, row, : int(code_lengths[row])].transpose(0, 1).to(dtype=torch.long, copy=True).contiguous()
for row in range(count)
]
@@ -0,0 +1,334 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""One reference-audio encoder shared by the API processes of a server.
Each API process otherwise loads its own copy of the audio tokenizer on the
GPU and encodes only the clips it receives. When the processes share a
directory (``VLLM_OMNI_MOSS_REF_CODES_SHARED_DIR``), the first one to take the lock in it
hosts the encoder and serves the others over a Unix socket in that directory.
Requests from all processes are merged into batches, and only the host keeps
the tokenizer and its CUDA graphs on the GPU.
Messages carry raw arrays and a JSON header; nothing is unpickled. A client
that cannot reach the host encodes locally instead.
"""
from __future__ import annotations
import collections
import fcntl
import json
import os
import threading
import time
from collections.abc import Callable
from contextlib import nullcontext
from multiprocessing.connection import Client, Connection, Listener
import numpy as np
import torch
from vllm.logger import init_logger
logger = init_logger(__name__)
_LOCK_NAME = "ref-encoder.lock"
_SOCKET_NAME = "ref-encoder.sock"
# Clips one worker merges into an encode, across all API processes. Several
# workers encode concurrently on their own streams: one serial queue of large
# batches makes a burst of new references wait behind each other. A free
# worker takes what is queued without waiting for more: API processes already
# gather their clips before sending them.
_MAX_BATCH = 8
# A client gives up on the host after this long and encodes locally.
_CONNECT_TIMEOUT_S = 120.0
_REQUEST_TIMEOUT_S = 120.0
# First-time compilation can outlast a normal encode request. Readiness has a
# separate deadline and must finish before the API starts accepting requests.
_STARTUP_TIMEOUT_S = 1200.0
EncodeFn = Callable[[list[torch.Tensor]], list]
# Open for the life of the process: closing it would release the host lock.
_host_lock_handle = None
class SharedReferenceEncoderStartupError(RuntimeError):
"""The shared encoder cannot safely accept requests yet."""
def elect_host(shared_dir: str) -> bool:
"""True in the one process that holds the encoder lock for ``shared_dir``.
The lock is held for the life of the process, so a restarted server
elects a new host even if the old socket file is still present.
"""
global _host_lock_handle
path = os.path.join(shared_dir, _LOCK_NAME)
handle = open(path, "a+") # noqa: SIM115 - kept open to hold the lock
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
handle.close()
return False
_host_lock_handle = handle
return True
def _send(conn: Connection, header: dict, arrays: list[np.ndarray]) -> None:
conn.send_bytes(json.dumps(header).encode())
for array in arrays:
conn.send_bytes(np.ascontiguousarray(array).tobytes())
def _recv(conn: Connection) -> tuple[dict, list[bytes]]:
header = json.loads(conn.recv_bytes().decode())
return header, [conn.recv_bytes() for _ in range(int(header["count"]))]
class _Job:
__slots__ = ("wav", "done", "result", "queued_at")
def __init__(self, wav: torch.Tensor) -> None:
self.wav = wav
self.done = threading.Event()
self.result: torch.Tensor | BaseException | None = None
self.queued_at = time.monotonic()
class SharedReferenceEncoderHost:
"""Serves reference encodes for every API process sharing ``shared_dir``.
``workers`` pairs each worker's encode function with an optional warmup
(for example, capturing that worker's CUDA graphs).
"""
def __init__(
self,
shared_dir: str,
workers: list[tuple[EncodeFn, Callable[[], object] | None]],
*,
stream_priority: int = 0,
batch_window_ms: float = 0.0,
) -> None:
self._stream_priority = stream_priority
self._batch_window_s = max(0.0, float(batch_window_ms)) / 1000
self._pending: collections.deque[_Job] = collections.deque()
# Includes jobs already taken by a worker, so shutdown can release
# every caller without waiting for an in-flight GPU operation.
self._outstanding: set[_Job] = set()
self._ready = threading.Condition()
self._path = os.path.join(shared_dir, _SOCKET_NAME)
if os.path.exists(self._path):
os.unlink(self._path) # left by a previous host; we hold the lock
self._listener = Listener(self._path, family="AF_UNIX")
os.chmod(self._path, 0o600)
self._closed = False
self._started = threading.Event()
self._startup_error: Exception | None = None
threading.Thread(
target=self._start_workers, args=(workers,), name="moss-ref-encoder-start", daemon=True
).start()
threading.Thread(target=self._accept_loop, name="moss-ref-encoder-accept", daemon=True).start()
logger.info("MOSS shared reference encoder serving at %s with %d workers", self._path, len(workers))
def encode(self, wavs: list[torch.Tensor]) -> list:
"""Encode on behalf of the host process itself."""
self.wait_until_ready()
jobs = [_Job(wav) for wav in wavs]
with self._ready:
if self._closed:
raise RuntimeError("shared reference encoder is closed")
self._outstanding.update(jobs)
self._pending.extend(jobs)
self._ready.notify(len(jobs))
for job in jobs:
job.done.wait()
return [job.result for job in jobs]
def close(self) -> None:
with self._ready:
self._closed = True
self._started.set()
for job in self._outstanding:
job.result = RuntimeError("shared reference encoder closed before encoding completed")
job.done.set()
self._outstanding.clear()
self._pending.clear()
self._ready.notify_all()
try:
self._listener.close()
except OSError:
pass
def wait_until_ready(self) -> None:
if not self._started.wait(_STARTUP_TIMEOUT_S):
raise SharedReferenceEncoderStartupError("shared reference encoder warmup timed out")
if self._closed or self._startup_error is not None:
raise SharedReferenceEncoderStartupError("shared reference encoder startup failed") from self._startup_error
def _accept_loop(self) -> None:
while not self._closed:
try:
conn = self._listener.accept()
except OSError:
return
threading.Thread(target=self._serve, args=(conn,), name="moss-ref-encoder-conn", daemon=True).start()
def _serve(self, conn: Connection) -> None:
with conn:
while True:
try:
header, payloads = _recv(conn)
except (EOFError, OSError):
return
if header.get("op") == "ready":
try:
self.wait_until_ready()
error = None
except SharedReferenceEncoderStartupError as exc:
error = str(exc)
try:
_send(conn, {"count": 0, "ready": error is None, "error": error}, [])
except OSError:
return
continue
wavs = [
torch.from_numpy(np.frombuffer(data, dtype=np.float32).reshape(shape).copy())
for data, shape in zip(payloads, header["shapes"])
]
results = self.encode(wavs)
errors = [None if isinstance(r, torch.Tensor) else repr(r) for r in results]
codes = [r.to(torch.int32).numpy() for r in results if isinstance(r, torch.Tensor)]
reply = {"count": len(codes), "shapes": [list(c.shape) for c in codes], "errors": errors}
try:
_send(conn, reply, codes)
except OSError:
return
def _start_workers(self, workers: list[tuple[EncodeFn, Callable[[], object] | None]]) -> None:
# Every warmup (graph capture) finishes before any worker encodes: CUDA
# work in another thread would invalidate a capture in progress.
try:
for _, warmup in workers:
if warmup is not None:
warmup()
if self._closed:
return
for index, (encode_fn, _) in enumerate(workers):
threading.Thread(
target=self._encode_loop, args=(encode_fn,), name=f"moss-ref-encoder-{index}", daemon=True
).start()
logger.info("MOSS shared reference encoder ready: %d workers", len(workers))
except Exception as exc: # noqa: BLE001 - wake readiness waiters with the failure
self._startup_error = exc
logger.exception("MOSS shared reference encoder startup failed")
finally:
self._started.set()
def _encode_loop(self, encode_fn: EncodeFn) -> None:
stream = torch.cuda.Stream(priority=self._stream_priority) if torch.cuda.is_available() else None
with torch.cuda.stream(stream) if stream is not None else nullcontext():
self._serve_jobs(encode_fn)
def _serve_jobs(self, encode_fn: EncodeFn) -> None:
while True:
with self._ready:
while True:
if self._closed:
return
if not self._pending:
self._ready.wait()
continue
remaining = self._pending[0].queued_at + self._batch_window_s - time.monotonic()
if remaining > 0 and len(self._pending) < _MAX_BATCH:
# Keep clips in the common queue while collecting;
# workers must not each reserve a singleton first.
self._ready.wait(remaining)
continue
break
jobs = [self._pending.popleft() for _ in range(min(_MAX_BATCH, len(self._pending)))]
try:
results = encode_fn([job.wav for job in jobs])
if len(results) != len(jobs):
raise RuntimeError(
f"shared reference encoder returned {len(results)} results for {len(jobs)} clips"
)
except Exception as error: # noqa: BLE001 - every waiter gets the failure
results = [error] * len(jobs)
with self._ready:
for job, result in zip(jobs, results, strict=True):
# close() may already have completed this caller with an
# error. A late GPU result must not replace that outcome.
if not job.done.is_set():
job.result = result
job.done.set()
self._outstanding.discard(job)
class SharedReferenceEncoderClient:
"""Sends reference clips to the host process of ``shared_dir``."""
def __init__(self, shared_dir: str) -> None:
self._path = os.path.join(shared_dir, _SOCKET_NAME)
# One connection per request in flight; idle ones are reused.
self._idle: list[Connection] = []
self._lock = threading.Lock()
self._connected = False
def _connect(self) -> Connection:
# The host may still be starting until the first connection succeeds;
# later reconnects are quick.
deadline = time.monotonic() + (1.0 if self._connected else _CONNECT_TIMEOUT_S)
while True:
try:
conn = Client(self._path, family="AF_UNIX")
self._connected = True
break
except (FileNotFoundError, ConnectionRefusedError):
if time.monotonic() >= deadline:
raise
time.sleep(0.2)
try:
_send(conn, {"op": "ready", "count": 0}, [])
if not conn.poll(_STARTUP_TIMEOUT_S):
raise SharedReferenceEncoderStartupError("shared reference encoder readiness timed out")
header, _ = _recv(conn)
if not header.get("ready"):
raise SharedReferenceEncoderStartupError(header.get("error", "shared reference encoder not ready"))
return conn
except BaseException:
conn.close()
raise
def wait_until_ready(self) -> None:
"""Startup handshake, without encoding or populating the reference cache."""
try:
conn = self._connect()
except Exception as exc:
raise SharedReferenceEncoderStartupError("shared reference encoder is not ready") from exc
with self._lock:
self._idle.append(conn)
def encode(self, wavs: list[torch.Tensor]) -> list:
"""Codes (or an exception) per clip; raises when the host is unreachable."""
with self._lock:
conn = self._idle.pop() if self._idle else None
try:
if conn is None:
conn = self._connect()
arrays = [w.detach().to(torch.float32).cpu().numpy() for w in wavs]
_send(conn, {"count": len(arrays), "shapes": [list(a.shape) for a in arrays]}, arrays)
if not conn.poll(_REQUEST_TIMEOUT_S):
raise TimeoutError(f"no reply from the shared reference encoder in {_REQUEST_TIMEOUT_S}s")
header, payloads = _recv(conn)
except BaseException:
if conn is not None:
conn.close()
raise
with self._lock:
self._idle.append(conn)
codes = iter(
torch.from_numpy(np.frombuffer(data, dtype=np.int32).reshape(shape).copy()).long()
for data, shape in zip(payloads, header["shapes"])
)
return [next(codes) if error is None else RuntimeError(error) for error in header["errors"]]
@@ -0,0 +1,475 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Direct-slot ring attention for MOSS streaming codec.
Inputs q/k/v are (execution_batch, heads, padded_T, head_dim). cache is
contiguous (2, state_capacity, heads, ring_capacity, head_dim). end_offset
contains absolute *pre-call* positions per state slot. slot_ids and valid_lengths
contain one entry per execution row. valid_lengths=0 is a scratch/padding row.
This op writes only valid tokens, attends to the resulting ring with the same
position semantics as RingKVCache.complete, then advances only active offsets.
Slots must be unique and in bounds; 0 <= valid_lengths <= padded_T. Chunks
longer than the ring retain only their final ring_capacity tokens.
These device-value preconditions are caller-owned to avoid host synchronization.
The op deliberately preserves chunk-complete ring overwrite semantics; it does
not recover entries overwritten by later tokens of the same input chunk.
"""
import torch
from vllm.triton_utils import tl, triton
@triton.jit
def _write(
k_ptr,
v_ptr,
cache_ptr,
end_ptr,
slots_ptr,
lengths_ptr,
ks0: tl.constexpr,
ks1: tl.constexpr,
ks2: tl.constexpr,
ks3: tl.constexpr,
vs0: tl.constexpr,
vs1: tl.constexpr,
vs2: tl.constexpr,
vs3: tl.constexpr,
end_stride: tl.constexpr,
slot_stride: tl.constexpr,
length_stride: tl.constexpr,
state_capacity: tl.constexpr,
num_heads: tl.constexpr,
num_frames: tl.constexpr,
ring_capacity: tl.constexpr,
head_dim: tl.constexpr,
block_size: tl.constexpr,
):
row = tl.program_id(0)
slot = tl.load(slots_ptr + row * slot_stride)
length = tl.load(lengths_ptr + row * length_stride)
start = tl.load(end_ptr + slot * end_stride)
x = tl.program_id(1) * block_size + tl.arange(0, block_size)
dim = x % head_dim
token = (x // head_dim) % num_frames
head = x // (num_frames * head_dim)
# For chunks longer than the ring, write only the final C tokens. This
# avoids duplicate physical addresses (and write races) in one launch.
skip = tl.maximum(length - ring_capacity, 0)
source_token = token + skip
mask = (head < num_heads) & (source_token < length)
pos = (start + source_token) % ring_capacity
dst = ((slot * num_heads + head) * ring_capacity + pos) * head_dim + dim
kval = tl.load(k_ptr + row * ks0 + head * ks1 + source_token * ks2 + dim * ks3, mask, 0)
vval = tl.load(v_ptr + row * vs0 + head * vs1 + source_token * vs2 + dim * vs3, mask, 0)
tl.store(cache_ptr + dst, kval, mask)
tl.store(cache_ptr + state_capacity * num_heads * ring_capacity * head_dim + dst, vval, mask)
@triton.jit
def _attend(
q_ptr,
cache_ptr,
end_ptr,
slots_ptr,
lengths_ptr,
out_ptr,
qs0: tl.constexpr,
qs1: tl.constexpr,
qs2: tl.constexpr,
qs3: tl.constexpr,
end_stride: tl.constexpr,
slot_stride: tl.constexpr,
length_stride: tl.constexpr,
state_capacity: tl.constexpr,
num_heads: tl.constexpr,
num_frames: tl.constexpr,
ring_capacity: tl.constexpr,
head_dim: tl.constexpr,
context_size: tl.constexpr,
block_m: tl.constexpr,
block_n: tl.constexpr,
skip_empty_tiles: tl.constexpr = False,
):
rows = tl.program_id(0) * block_m + tl.arange(0, block_m)
bh = tl.program_id(1)
batch, head = bh // num_heads, bh % num_heads
slot = tl.load(slots_ptr + batch * slot_stride)
length = tl.load(lengths_ptr + batch * length_stride)
start = tl.load(end_ptr + slot * end_stride)
end = start + length
dims = tl.arange(0, head_dim)
q = tl.load(
q_ptr + batch * qs0 + head * qs1 + rows[:, None] * qs2 + dims[None, :] * qs3, rows[:, None] < num_frames, 0
)
acc = tl.full((block_m, head_dim), 0.0, tl.float32)
maximum = tl.full((block_m,), -float("inf"), tl.float32)
denominator = tl.full((block_m,), 0.0, tl.float32)
# Padding rows own scratch slots and must emit zeros without reading KV.
# Keep valid-row accumulation and the ring overwrite semantics unchanged.
if skip_empty_tiles:
block_start = tl.program_id(0) * block_m
live = (length > 0) & (block_start < length)
live = live & (block_start + block_m > tl.maximum(length - ring_capacity, 0))
else:
live = length > 0
if live:
# Physical-ring order matches the existing masked_attention accumulation.
last = end - 1
last_index = last % ring_capacity
if skip_empty_tiles:
# Before the first wrap, only physical keys [0, end) exist.
# Omitted blocks have zero probability for every query; keep the
# physical order and arithmetic of all remaining blocks unchanged.
key_blocks = tl.cdiv(tl.minimum(end, ring_capacity), block_n)
else:
key_blocks = tl.cdiv(ring_capacity, block_n)
for first in range(key_blocks):
cols = first * block_n + tl.arange(0, block_n)
delta = cols - last_index
positions = tl.where(delta <= 0, last + delta, last + delta - ring_capacity)
distance = start + rows[:, None] - positions[None, :]
allowed = (
(rows[:, None] < length)
& (cols[None, :] < ring_capacity)
& (positions[None, :] >= 0)
& (positions[None, :] < end)
& (distance >= 0)
)
if context_size > 0:
allowed = allowed & (distance < context_size)
base = (slot * num_heads + head) * ring_capacity * head_dim
k = tl.load(cache_ptr + base + cols[None, :] * head_dim + dims[:, None], cols[None, :] < ring_capacity, 0)
score = tl.dot(q, k).to(tl.float32) * (head_dim**-0.5)
score = tl.where(allowed, score, -float("inf"))
next_max = tl.maximum(maximum, tl.max(score, 1))
safe_max = tl.where(next_max == -float("inf"), 0.0, next_max)
rescale = tl.exp(maximum - safe_max)
p = tl.exp(score - safe_max[:, None])
denominator = denominator * rescale + tl.sum(p, 1)
v = tl.load(
cache_ptr
+ state_capacity * num_heads * ring_capacity * head_dim
+ base
+ cols[:, None] * head_dim
+ dims[None, :],
cols[:, None] < ring_capacity,
0,
)
acc = acc * rescale[:, None] + tl.dot(p.to(v.dtype), v)
maximum = next_max
out = acc / tl.where(denominator > 0, denominator, 1.0)[:, None]
tl.store(
out_ptr + ((batch * num_heads + head) * num_frames + rows[:, None]) * head_dim + dims[None, :],
out,
rows[:, None] < num_frames,
)
@triton.jit
def _advance(
end_ptr,
slots_ptr,
lengths_ptr,
end_stride: tl.constexpr,
slot_stride: tl.constexpr,
length_stride: tl.constexpr,
batch_size: tl.constexpr,
block_size: tl.constexpr,
):
row = tl.arange(0, block_size)
slot = tl.load(slots_ptr + row * slot_stride, row < batch_size, 0)
length = tl.load(lengths_ptr + row * length_stride, row < batch_size, 0)
active = (row < batch_size) & (length > 0)
start = tl.load(end_ptr + slot * end_stride, active, 0)
tl.store(end_ptr + slot * end_stride, start + length, active)
@triton.jit
def _write_attend(
q_ptr,
k_ptr,
v_ptr,
cache_ptr,
starts_ptr,
slots_ptr,
lengths_ptr,
out_ptr,
qs0: tl.constexpr,
qs1: tl.constexpr,
qs2: tl.constexpr,
qs3: tl.constexpr,
ks0: tl.constexpr,
ks1: tl.constexpr,
ks2: tl.constexpr,
ks3: tl.constexpr,
vs0: tl.constexpr,
vs1: tl.constexpr,
vs2: tl.constexpr,
vs3: tl.constexpr,
start_stride: tl.constexpr,
slot_stride: tl.constexpr,
length_stride: tl.constexpr,
state_capacity: tl.constexpr,
num_heads: tl.constexpr,
num_frames: tl.constexpr,
ring_capacity: tl.constexpr,
head_dim: tl.constexpr,
context_size: tl.constexpr,
write_frames: tl.constexpr,
block_m: tl.constexpr,
block_n: tl.constexpr,
block_w: tl.constexpr,
):
rows = tl.program_id(0) * block_m + tl.arange(0, block_m)
bh = tl.program_id(1)
batch, head = bh // num_heads, bh % num_heads
slot = tl.load(slots_ptr + batch * slot_stride)
length = tl.load(lengths_ptr + batch * length_stride)
start = tl.load(starts_ptr + batch * start_stride)
end = start + length
dims = tl.arange(0, head_dim)
base = (slot * num_heads + head) * ring_capacity * head_dim
v_base = state_capacity * num_heads * ring_capacity * head_dim + base
# Every program of this (row, head) writes the whole chunk for its head,
# so it only reads ring entries it wrote itself (duplicate writes across
# query blocks store identical values). Chunks longer than the ring keep
# only their final ring_capacity tokens, as in _write.
skip = tl.maximum(length - ring_capacity, 0)
for first in range(tl.cdiv(write_frames, block_w)):
token = first * block_w + tl.arange(0, block_w)
source = token + skip
mask = (source < length)[:, None]
pos = (start + source) % ring_capacity
kval = tl.load(k_ptr + batch * ks0 + head * ks1 + source[:, None] * ks2 + dims[None, :] * ks3, mask, 0)
vval = tl.load(v_ptr + batch * vs0 + head * vs1 + source[:, None] * vs2 + dims[None, :] * vs3, mask, 0)
dst = pos[:, None] * head_dim + dims[None, :]
tl.store(cache_ptr + base + dst, kval, mask)
tl.store(cache_ptr + v_base + dst, vval, mask)
tl.debug_barrier()
q = tl.load(
q_ptr + batch * qs0 + head * qs1 + rows[:, None] * qs2 + dims[None, :] * qs3, rows[:, None] < num_frames, 0
)
acc = tl.full((block_m, head_dim), 0.0, tl.float32)
maximum = tl.full((block_m,), -float("inf"), tl.float32)
denominator = tl.full((block_m,), 0.0, tl.float32)
if length > 0:
last = end - 1
last_index = last % ring_capacity
for first in range(tl.cdiv(ring_capacity, block_n)):
cols = first * block_n + tl.arange(0, block_n)
delta = cols - last_index
positions = tl.where(delta <= 0, last + delta, last + delta - ring_capacity)
distance = start + rows[:, None] - positions[None, :]
allowed = (
(rows[:, None] < length)
& (cols[None, :] < ring_capacity)
& (positions[None, :] >= 0)
& (positions[None, :] < end)
& (distance >= 0)
)
if context_size > 0:
allowed = allowed & (distance < context_size)
k = tl.load(cache_ptr + base + cols[None, :] * head_dim + dims[:, None], cols[None, :] < ring_capacity, 0)
score = tl.dot(q, k).to(tl.float32) * (head_dim**-0.5)
score = tl.where(allowed, score, -float("inf"))
next_max = tl.maximum(maximum, tl.max(score, 1))
safe_max = tl.where(next_max == -float("inf"), 0.0, next_max)
rescale = tl.exp(maximum - safe_max)
p = tl.exp(score - safe_max[:, None])
denominator = denominator * rescale + tl.sum(p, 1)
v = tl.load(
cache_ptr + v_base + cols[:, None] * head_dim + dims[None, :],
cols[:, None] < ring_capacity,
0,
)
acc = acc * rescale[:, None] + tl.dot(p.to(v.dtype), v)
maximum = next_max
out = acc / tl.where(denominator > 0, denominator, 1.0)[:, None]
tl.store(
out_ptr + ((batch * num_heads + head) * num_frames + rows[:, None]) * head_dim + dims[None, :],
out,
rows[:, None] < num_frames,
)
@torch.library.custom_op("vllm_omni::moss_slot_ring_attention", mutates_args=("cache", "end_offset"))
def slot_ring_attention(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cache: torch.Tensor,
end_offset: torch.Tensor,
slot_ids: torch.Tensor,
valid_lengths: torch.Tensor,
context: int = -1,
skip_empty_tiles: bool = False,
) -> torch.Tensor:
"""Fused address/mask path, with three ordered launches and no KV gather.
q/k are already rotary-position encoded. The caller still advances its
separate MHA/RoPE offset state; this op advances only end_offset in place.
context=-1 means unbounded causal attention over available ring entries.
Outputs beyond each row's valid_lengths are exactly zero.
skip_empty_tiles skips wholly masked tiles for small (T <= 32) chunks.
Larger chunks keep the static loop, which benchmarks faster after wrap.
"""
b, h, t, d = q.shape
if k.shape != q.shape or v.shape != q.shape:
raise ValueError("q/k/v must have identical shapes")
if q.dtype not in (torch.bfloat16, torch.float16) or k.dtype != q.dtype or v.dtype != q.dtype:
raise ValueError("q/k/v must share bf16 or fp16 dtype")
if d not in (32, 64, 128) or t < 1:
raise ValueError("requires head_dim 32/64/128 and positive padded_T")
if cache.ndim != 5 or cache.shape[0] != 2 or cache.shape[2] != h or cache.shape[4] != d:
raise ValueError("cache must be (2, state_capacity, heads, capacity, head_dim)")
s, c = cache.shape[1], cache.shape[3]
if not cache.is_contiguous() or cache.dtype != q.dtype:
raise ValueError("cache must be contiguous and share q dtype")
if end_offset.shape != (s,) or slot_ids.shape != (b,) or valid_lengths.shape != (b,):
raise ValueError("invalid metadata shapes")
if any(x.dtype not in (torch.int32, torch.int64) for x in (end_offset, slot_ids, valid_lengths)):
raise ValueError("metadata must be int32/int64")
if q.device.type != "cuda" or any(x.device != q.device for x in (k, v, cache, end_offset, slot_ids, valid_lengths)):
raise ValueError("all tensors must share one CUDA device")
if context == 0 or context < -1:
raise ValueError("context must be -1 or positive")
out = torch.empty(q.shape, device=q.device, dtype=q.dtype)
if b == 0:
return out
strides = (end_offset.stride(0), slot_ids.stride(0), valid_lengths.stride(0))
_write[(b, triton.cdiv(h * t * d, 256))](
k, v, cache, end_offset, slot_ids, valid_lengths, *k.stride(), *v.stride(), *strides, s, h, t, c, d, 256
)
bm = 16 if t <= 32 else 64
_attend[(triton.cdiv(t, bm), b * h)](
q,
cache,
end_offset,
slot_ids,
valid_lengths,
out,
*q.stride(),
*strides,
s,
h,
t,
c,
d,
context,
bm,
64,
skip_empty_tiles=skip_empty_tiles and t <= 32,
num_warps=8 if c <= 256 else 4,
num_stages=2,
)
_advance[(1,)](end_offset, slot_ids, valid_lengths, *strides, b, triton.next_power_of_2(b))
return out
@slot_ring_attention.register_fake
def _(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cache: torch.Tensor,
end_offset: torch.Tensor,
slot_ids: torch.Tensor,
valid_lengths: torch.Tensor,
context: int = -1,
skip_empty_tiles: bool = False,
) -> torch.Tensor:
return torch.empty(q.shape, device=q.device, dtype=q.dtype)
def _check_inputs(q, k, v, cache, metadata, context):
b, h, t, d = q.shape
if k.shape != q.shape or v.shape != q.shape:
raise ValueError("q/k/v must have identical shapes")
if q.dtype not in (torch.bfloat16, torch.float16) or k.dtype != q.dtype or v.dtype != q.dtype:
raise ValueError("q/k/v must share bf16 or fp16 dtype")
if d not in (32, 64, 128) or t < 1:
raise ValueError("requires head_dim 32/64/128 and positive padded_T")
if cache.ndim != 5 or cache.shape[0] != 2 or cache.shape[2] != h or cache.shape[4] != d:
raise ValueError("cache must be (2, state_capacity, heads, capacity, head_dim)")
if not cache.is_contiguous() or cache.dtype != q.dtype:
raise ValueError("cache must be contiguous and share q dtype")
if any(x.dtype not in (torch.int32, torch.int64) for x in metadata):
raise ValueError("metadata must be int32/int64")
if q.device.type != "cuda" or any(x.device != q.device for x in (k, v, cache, *metadata)):
raise ValueError("all tensors must share one CUDA device")
if context == 0 or context < -1:
raise ValueError("context must be -1 or positive")
@torch.library.custom_op("vllm_omni::moss_slot_ring_attention_rows", mutates_args=("cache",))
def slot_ring_attention_rows(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cache: torch.Tensor,
starts: torch.Tensor,
slot_ids: torch.Tensor,
valid_lengths: torch.Tensor,
context: int = -1,
) -> torch.Tensor:
"""``slot_ring_attention`` as one launch, with per-row start positions.
``starts`` holds each execution row's pre-call absolute position (the
caller's gathered offset). The ring is written and attended exactly as by
``slot_ring_attention``; no offset is advanced here, so the caller owns
every offset update and can fuse them with its own.
"""
b, h, t, d = q.shape
_check_inputs(q, k, v, cache, (starts, slot_ids, valid_lengths), context)
if starts.shape != (b,) or slot_ids.shape != (b,) or valid_lengths.shape != (b,):
raise ValueError("invalid metadata shapes")
out = torch.empty(q.shape, device=q.device, dtype=q.dtype)
if b == 0:
return out
s, c = cache.shape[1], cache.shape[3]
bm = 16 if t <= 32 else 64
_write_attend[(triton.cdiv(t, bm), b * h)](
q,
k,
v,
cache,
starts,
slot_ids,
valid_lengths,
out,
*q.stride(),
*k.stride(),
*v.stride(),
starts.stride(0),
slot_ids.stride(0),
valid_lengths.stride(0),
s,
h,
t,
c,
d,
context,
min(t, c),
bm,
64,
16,
num_warps=8 if c <= 256 else 4,
num_stages=2,
)
return out
@slot_ring_attention_rows.register_fake
def _(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cache: torch.Tensor,
starts: torch.Tensor,
slot_ids: torch.Tensor,
valid_lengths: torch.Tensor,
context: int = -1,
) -> torch.Tensor:
return torch.empty(q.shape, device=q.device, dtype=q.dtype)