[Model] Default MOSS Local 1.5 to adaptive CUDA MRV2 with MPS (#8438)

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 authored and GitHub committed 2026-10-06 08:20:46 -07:00
1 parent ee9ab9ea88
commit 7be49aa0ce
30 files changed
+808 -152

No files matched your search

@@ -64,6 +64,7 @@ class MossFirstChunkFastPath:
sample_rate: torch.Tensor,
device: torch.device,
gate_main: bool = False,
max_active_streams: int = 0,
handoff_timeout_s: float = 30.0,
) -> None:
if not math.isfinite(handoff_timeout_s) or handoff_timeout_s <= 0:
@@ -74,6 +75,7 @@ class MossFirstChunkFastPath:
# 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._max_active_streams = max(0, int(max_active_streams))
self._inflight: torch.cuda.Event | None = None
self._wrapper = wrapper
self._n_vq = int(n_vq)
@@ -154,6 +156,7 @@ class MossFirstChunkFastPath:
or self._thread is None
or not self._thread.is_alive()
or request_key in req_slots
or (self._max_active_streams and len(req_slots) >= self._max_active_streams)
):
return False
delivery = self._sink.prepare([request_id])
@@ -208,9 +208,12 @@ class MossLocalModelState(OmniModelState):
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)
selected = tensor[: len(rows)]
else:
indices = _metadata_to_device(np.asarray(rows, dtype=np.int64), tensor.device)
selected = tensor.index_select(0, indices)
# vLLM 0.31 uses int32 slot mappings; index_copy_ requires int64.
return selected.long()
def run_preprocess(self, input_batch, model_inputs, req_states=None, mtp_batch_descriptor_dispatcher=None):
input_ids = model_inputs.get("input_ids")
@@ -255,7 +258,9 @@ class MossLocalModelState(OmniModelState):
continue
if self._batch_prefill:
ref = (buf.get("codes", {}) or {}).get("ref")
ref_offset = int(buf.get("ref_offset", 0))
# Prefix hits skip hooks for cached prompt tokens. Use the
# scheduler's absolute prompt position, also on first admission.
ref_offset = int(computed) if computed is not None else 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":
@@ -264,7 +269,7 @@ class MossLocalModelState(OmniModelState):
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:
if chunk.numel():
references.append((start, chunk))
# Text embeddings have already been computed for all input
# tokens. Match the canonical prefill state transition.
@@ -419,7 +424,7 @@ class MossLocalModelState(OmniModelState):
# 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)
0, input_batch.idx_mapping[: input_batch.num_reqs].long(), hidden_states.index_select(0, last)
)
if self._local_eager_mtp:
completing = self._completing_rows
@@ -802,6 +802,7 @@ class MossTTSCodecDecoder(nn.Module):
sample_rate=self._sr_tensor,
device=next(self._codec.parameters()).device,
gate_main=bool(self._connector_int("codec_first_chunk_gate", default=0)),
max_active_streams=self._connector_int("codec_first_chunk_max_active_streams", default=0),
)
logger.info(
"MOSS-TTS codec first-chunk fast path ready: B=%s T=%d",
@@ -197,7 +197,9 @@ class MossTTSLocalDepthTransformer(nn.Module):
every cache position before reading it, including CUDA Graph replay.
"""
def __init__(self, gpt2_config, hidden_size: int | None = None) -> None:
def __init__(
self, gpt2_config, hidden_size: int | None = None, *, compile_audio_sampler: bool | None = None
) -> None:
super().__init__()
self.hidden_size = int(hidden_size if hidden_size is not None else gpt2_config.n_embd)
n_head = int(gpt2_config.n_head)
@@ -208,6 +210,7 @@ class MossTTSLocalDepthTransformer(nn.Module):
self.ln_f = nn.LayerNorm(self.hidden_size, eps=eps)
self._compiled_forward_prefix = None
self._compiled_audio_sampler = None
self._compile_audio_sampler = compile_audio_sampler
def _forward_prefix(
self,
@@ -231,7 +234,10 @@ class MossTTSLocalDepthTransformer(nn.Module):
dynamic=True,
options={"epilogue_fusion": False},
)
if os.environ.get("VLLM_OMNI_MOSS_LOCAL_COMPILE_AUDIO_SAMPLER", "0") == "1":
compile_sampler = self._compile_audio_sampler
if compile_sampler is None:
compile_sampler = os.environ.get("VLLM_OMNI_MOSS_LOCAL_COMPILE_AUDIO_SAMPLER", "0") == "1"
if compile_sampler:
# 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.
@@ -1349,7 +1349,11 @@ class MossTTSLocalTalkerForGeneration(nn.Module):
[nn.Linear(hidden_size, self.audio_vocab_size, bias=False) for _ in range(self.n_vq)]
)
self.local_text_lm_head = nn.Linear(hidden_size, 2, bias=False)
self.local_transformer = MossTTSLocalDepthTransformer(self.config.gpt2_config, hidden_size=hidden_size)
self.local_transformer = MossTTSLocalDepthTransformer(
self.config.gpt2_config,
hidden_size=hidden_size,
compile_audio_sampler=getattr(self.config, "local_compile_audio_sampler", None),
)
self._batch_state: list[dict[str, Any]] | None = None
# Stacked embedding cache built after load_weights() for vectorised
@@ -1520,16 +1524,18 @@ class MossTTSLocalTalkerForGeneration(nn.Module):
embeds = self.model.embed_tokens(input_ids)
ref_codes = (info_dict.get("codes", {}) or {}).get("ref")
ref_offset = int(info_dict.get("ref_offset", 0))
# Cached prompt tokens already consumed their reference rows even
# though this request's preprocessing hook never saw those tokens.
ref_offset = int(info_dict.get("_omni_num_computed_tokens", info_dict.get("ref_offset", 0)))
if isinstance(ref_codes, torch.Tensor) and ref_codes.numel() > 0:
if ref_codes.dim() == 1 and ref_codes.numel() % self.n_vq == 0:
ref_codes = ref_codes.view(-1, self.n_vq)
if isinstance(ref_codes, torch.Tensor) and ref_codes.dim() == 2:
end_off = ref_offset + span_len
chunk = ref_codes[ref_offset:end_off]
if chunk.numel() > 0 and chunk.shape[0] == span_len:
if chunk.numel() > 0:
codes = chunk.to(device=device, dtype=torch.long)
embeds = embeds + self._audio_embed(codes)
embeds[: chunk.shape[0]] += self._audio_embed(codes)
info_update: dict[str, Any] = {
"audio_state": {"is_stopping": False},
@@ -1701,6 +1707,10 @@ class MossTTSLocalTalkerForGeneration(nn.Module):
"""Honor the same platform graph-safety override as the V1 runner."""
return self.talker_mtp_graph_safe
@property
def mtp_accepts_per_row_generators(self) -> bool:
return self.talker_mtp_accepts_per_row_generators
# Package runner-generated audio frames
# ------------------------------------------------------------------
@@ -6,6 +6,11 @@
# Licensed under the Apache License, Version 2.0 (the "License").
"""Pipeline topology for all MOSS-TTS variants (2-stage: talker → codec)."""
import shutil
from dataclasses import replace
from transformers import PretrainedConfig
from vllm.logger import init_logger
from vllm.sampling_params import RequestOutputKind
from vllm_omni.config.stage_config import (
@@ -13,8 +18,10 @@ from vllm_omni.config.stage_config import (
StageExecutionType,
StagePipelineConfig,
)
from vllm_omni.model_executor.models.moss_tts.configuration_moss_tts import MossTTSLocalConfig
_PROC = "vllm_omni.model_executor.stage_input_processors.moss_tts"
logger = init_logger(__name__)
# ---------------------------------------------------------------------------
# Shared 2-stage pipeline (used by all 5 MOSS-TTS variants)
@@ -135,4 +142,40 @@ MOSS_TTS_LOCAL_PIPELINE = PipelineConfig(
# they have different talker architectures from the delay variant
# (MossTTSRealtime / MossTTSLocalModel vs MossTTSDelayModel).
__all__ = ["MOSS_TTS_PIPELINE", "MOSS_TTS_REALTIME_PIPELINE", "MOSS_TTS_LOCAL_PIPELINE"]
def resolve_moss_tts_local_pipeline(hf_config: PretrainedConfig | None = None) -> PipelineConfig | None:
"""Select CUDA MRV2, with the C128 system profile when prerequisites are met.
The platform memory query uses NVML, avoiding CUDA initialization before
workers spawn. Explicit deploy configs override this pipeline default.
"""
from vllm.platforms import current_platform
from vllm_omni.platforms import current_omni_platform
if hf_config is not None and not isinstance(hf_config, MossTTSLocalConfig):
return None
if current_omni_platform.device_name != "cuda":
return replace(MOSS_TTS_LOCAL_PIPELINE, default_deploy_config_name="moss_tts_local_v1.yaml")
if shutil.which("nvidia-cuda-mps-control") is None:
logger.info("MOSS Local defaults to CUDA MRV2/C64 without MPS: nvidia-cuda-mps-control is unavailable")
return replace(MOSS_TTS_LOCAL_PIPELINE, default_deploy_config_name="moss_tts_local_mrv2.yaml")
try:
memory_bytes = current_platform.get_device_total_memory()
except Exception as exc:
logger.warning("Cannot query CUDA memory for MOSS Local; using MRV2/C64 with MPS: %s", exc)
return MOSS_TTS_LOCAL_PIPELINE
if memory_bytes >= 140 * 1024**3:
return replace(
MOSS_TTS_LOCAL_PIPELINE,
default_deploy_config_name="moss_tts_local_mrv2_optimized.yaml",
)
return MOSS_TTS_LOCAL_PIPELINE
__all__ = [
"MOSS_TTS_PIPELINE",
"MOSS_TTS_REALTIME_PIPELINE",
"MOSS_TTS_LOCAL_PIPELINE",
"resolve_moss_tts_local_pipeline",
]
@@ -45,6 +45,7 @@ from vllm.triton_utils import tl, triton
from vllm_omni.platforms import current_omni_platform
_KERNEL = 7
_CUDA_SIN = current_omni_platform.is_cuda()
# --------------------------------------------------------------------------- kernels
@@ -68,13 +69,15 @@ def _rvq_gather_kernel(codes_ptr, books_ptr, out_ptr, NQ: tl.constexpr, CB: tl.c
@triton.jit
def _fast_sin(y):
def _fast_sin(y, CUDA_SIN: tl.constexpr = _CUDA_SIN):
# Two-step reduction to [-pi, pi], then the hardware approximation
# (absolute error ~4e-7 there): accurate sin's instruction count, not
# memory, bounds every kernel that applies SnakeBeta.
k = tl.extra.cuda.libdevice.rint(y * 0.15915494309189535)
k = tl.extra.libdevice.rint(y * 0.15915494309189535)
r = tl.fma(-k, -1.7484555314695172e-07, tl.fma(-k, 6.2831854820251465, y))
return tl.inline_asm_elementwise("sin.approx.f32 $0, $1;", "=r,r", [r], dtype=tl.float32, is_pure=True, pack=1)
if CUDA_SIN:
return tl.inline_asm_elementwise("sin.approx.f32 $0, $1;", "=r,r", [r], dtype=tl.float32, is_pure=True, pack=1)
return tl.sin(r)
@triton.jit