[TTS][Model] support MOSS-TTS series (#3420)

Signed-off-by: Zhang <jianmusings@gmail.com>
Signed-off-by: Zhang Jian <jianmusings@gmail.com>
Signed-off-by: jian <jianmusings@gmail.com>
Signed-off-by: Canlin Guo <961750412@qq.com>
Co-authored-by: Canlin Guo <961750412@qq.com>
This commit is contained in:
Zhang JianandCanlin Guo authored and GitHub committed 2026-06-02 15:46:01 +08:00
1 parent da9c45e1de
commit b550709bba
32 files changed
+4775 -37

No files matched your search

@@ -0,0 +1,13 @@
from vllm_omni.model_executor.models.moss_tts.modeling_moss_tts_codec import (
MossTTSCodecDecoder,
)
from vllm_omni.model_executor.models.moss_tts.modeling_moss_tts_talker import (
MossTTSDelayTalkerForGeneration,
MossTTSRealtimeTalkerForGeneration,
)
__all__ = [
"MossTTSDelayTalkerForGeneration",
"MossTTSRealtimeTalkerForGeneration",
"MossTTSCodecDecoder",
]
@@ -0,0 +1,578 @@
# Copyright 2026 OpenMOSS and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Vendored from OpenMOSS-Team/MOSS-Audio-Tokenizer (configuration_moss_audio_tokenizer.py
# and modeling_moss_audio_tokenizer.py). Simplified for inference-only use:
# - Streaming KV-cache infrastructure removed (single-pass batch decode only).
# - Training-only methods (forward, encode, decode) removed.
# - Dead branches removed: gating="none" always, weights_per_step=0 always,
# positional_embedding="rope" always, norm="layer_norm" always in default config.
"""MOSS Audio Tokenizer — inference-only codec (encode waveform ↔ RVQ codes)."""
from __future__ import annotations
import copy
import math
from dataclasses import dataclass
from typing import Any, cast
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PretrainedConfig
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import ModelOutput
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
class MossAudioTokenizerConfig(PretrainedConfig):
model_type = "moss-audio-tokenizer"
attribute_map = {"sample_rate": "sampling_rate"}
def __init__(
self,
version: str | None = None,
sampling_rate: int = 24000,
downsample_rate: int = 1920,
causal_transformer_context_duration: float = 10.0,
encoder_kwargs: list[dict[str, Any]] | None = None,
decoder_kwargs: list[dict[str, Any]] | None = None,
quantizer_type: str = "rlfq",
quantizer_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
kwargs.pop("model_type", None)
self.version = version
self.sampling_rate = sampling_rate
self.downsample_rate = downsample_rate
self.causal_transformer_context_duration = causal_transformer_context_duration
self.encoder_kwargs = encoder_kwargs or _default_encoder_kwargs()
self.decoder_kwargs = decoder_kwargs or _default_decoder_kwargs()
if quantizer_kwargs is None:
quantizer_kwargs = {
"input_dim": 768,
"rvq_dim": 512,
"output_dim": 768,
"num_quantizers": 32,
"codebook_size": 1024,
"codebook_dim": 8,
"quantizer_type": "rlfq",
}
kw_qtype = quantizer_kwargs.get("quantizer_type")
self.quantizer_type = kw_qtype if kw_qtype is not None else quantizer_type
quantizer_kwargs["quantizer_type"] = self.quantizer_type
self.quantizer_kwargs = quantizer_kwargs
super().__init__(**kwargs)
@property
def num_quantizers(self) -> int:
return int(self.quantizer_kwargs.get("num_quantizers", 32))
@property
def codebook_size(self) -> int:
return int(self.quantizer_kwargs.get("codebook_size", 4096))
@property
def frame_rate(self) -> float:
return self.sampling_rate / self.downsample_rate
def _transformer_block(
input_dim: int, output_dim: int, d_model: int, num_heads: int, num_layers: int
) -> dict[str, Any]:
return {
"module_type": "Transformer",
"input_dimension": input_dim,
"output_dimension": output_dim,
"d_model": d_model,
"num_heads": num_heads,
"num_layers": num_layers,
"dim_feedforward": d_model * 4,
"causal": True,
"norm": "layer_norm",
"positional_embedding": "rope",
"max_period": 10000,
"gating": "none",
"layer_scale": 0.01,
"conv_layout": True,
}
def _default_encoder_kwargs() -> list[dict[str, Any]]:
return [
{"module_type": "PatchedPretransform", "patch_size": 240},
_transformer_block(240, 384, 768, 12, 12),
{"module_type": "PatchedPretransform", "patch_size": 2},
_transformer_block(768, 384, 768, 12, 12),
{"module_type": "PatchedPretransform", "patch_size": 2},
_transformer_block(768, 640, 768, 12, 12),
{"module_type": "PatchedPretransform", "patch_size": 2},
_transformer_block(1280, 768, 1280, 20, 32),
]
def _default_decoder_kwargs() -> list[dict[str, Any]]:
return [
_transformer_block(768, 1280, 1280, 20, 32),
{"module_type": "PatchedPretransform", "patch_size": 2},
_transformer_block(640, 768, 768, 12, 12),
{"module_type": "PatchedPretransform", "patch_size": 2},
_transformer_block(384, 768, 768, 12, 12),
{"module_type": "PatchedPretransform", "patch_size": 2},
_transformer_block(384, 768, 768, 12, 12),
{"module_type": "PatchedPretransform", "patch_size": 2},
_transformer_block(384, 240, 768, 12, 12),
{"module_type": "PatchedPretransform", "patch_size": 240},
]
# ---------------------------------------------------------------------------
# Outputs
# ---------------------------------------------------------------------------
@dataclass
class MossAudioTokenizerEncoderOutput(ModelOutput):
audio_codes: torch.Tensor | None = None
audio_codes_lengths: torch.Tensor | None = None
@dataclass
class MossAudioTokenizerDecoderOutput(ModelOutput):
audio: torch.Tensor | None = None
audio_lengths: torch.Tensor | None = None
# ---------------------------------------------------------------------------
# Building blocks
# ---------------------------------------------------------------------------
class _LayerScale(nn.Module):
def __init__(self, channels: int, init: float = 1e-4, device=None, dtype=None) -> None:
super().__init__()
self.scale = nn.Parameter(torch.full((channels,), init, device=device, dtype=dtype))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.scale * x
def _apply_rope(q: torch.Tensor, k: torch.Tensor, max_period: float = 10_000) -> tuple[torch.Tensor, torch.Tensor]:
"""Rotary position embedding over sequence dimension (B, H, T, D).
Matches upstream MossAudioTokenizer's ``apply_rope``: pair the last dim
as ``(re, im)`` interleaved (GPT-J style) — *not* GPT-NeoX split-halves.
The two conventions are not interchangeable with the same checkpoint;
using the wrong one silently rotates random subspaces of the K/V vectors.
"""
B, H, T, D = q.shape
half = D // 2
ds = torch.arange(half, device=q.device, dtype=torch.float32)
freqs = torch.exp(ds * (-math.log(max_period) * 2 / D))
ts = torch.arange(T, device=q.device, dtype=torch.float32).view(1, 1, -1, 1) # (1, 1, T, 1)
rotr = torch.cos(freqs * ts) # (1, 1, T, D/2)
roti = torch.sin(freqs * ts)
dims = q.shape[:-1]
q_pair = q.view(*dims, half, 2)
k_pair = k.view(*dims, half, 2)
qr, qi = q_pair[..., 0].float(), q_pair[..., 1].float()
kr, ki = k_pair[..., 0].float(), k_pair[..., 1].float()
qor = qr * rotr - qi * roti
qoi = qr * roti + qi * rotr
kor = kr * rotr - ki * roti
koi = kr * roti + ki * rotr
qo = torch.stack([qor.to(q.dtype), qoi.to(q.dtype)], dim=-1).view(*dims, D)
ko = torch.stack([kor.to(k.dtype), koi.to(k.dtype)], dim=-1).view(*dims, D)
return qo, ko
class _Attention(nn.Module):
"""Causal multi-head self-attention with RoPE, no streaming KV cache."""
def __init__(
self, embed_dim: int, num_heads: int, causal: bool, max_period: float, device=None, dtype=None
) -> None:
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.causal = causal
self.max_period = max_period
kw = {"device": device, "dtype": dtype}
self.in_proj = nn.Linear(embed_dim, 3 * embed_dim, bias=False, **kw)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False, **kw)
# Remap legacy weight names produced by the upstream checkpoint saver.
self._register_load_state_dict_pre_hook(self._remap_weights, with_module=True)
@staticmethod
def _remap_weights(module, state_dict, prefix, *_):
for old in ("in_proj_weight", "in_proj.weight"):
key = prefix + old
if key in state_dict and (prefix + "in_proj.weight") not in state_dict:
state_dict[prefix + "in_proj.weight"] = state_dict.pop(key)
for old in ("out_proj.weight",):
key = prefix + old
# If stored under in_projs.0 / out_projs.0 (multi-module layout), remap.
for src in (prefix + "in_projs.0.weight", prefix + "out_projs.0.weight"):
if src in state_dict:
dst = src.replace("in_projs.0.", "in_proj.").replace("out_projs.0.", "out_proj.")
state_dict[dst] = state_dict.pop(src)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, T, _ = x.shape
H, D = self.num_heads, self.embed_dim // self.num_heads
qkv = self.in_proj(x).reshape(B, T, 3, H, D).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # each (B, H, T, D)
q, k = _apply_rope(q, k, self.max_period)
out = F.scaled_dot_product_attention(q, k, v, is_causal=self.causal)
out = out.transpose(1, 2).reshape(B, T, self.embed_dim)
return self.out_proj(out)
class _TransformerLayer(nn.Module):
def __init__(
self,
d_model: int,
num_heads: int,
dim_feedforward: int,
causal: bool,
max_period: float,
layer_scale: float | None,
device=None,
dtype=None,
) -> None:
super().__init__()
kw = {"device": device, "dtype": dtype}
self.norm1 = nn.LayerNorm(d_model, eps=1e-5, **kw)
self.norm2 = nn.LayerNorm(d_model, eps=1e-5, **kw)
self.attn = _Attention(d_model, num_heads, causal, max_period, device, dtype)
self.ff1 = nn.Linear(d_model, dim_feedforward, bias=False, **kw)
self.ff2 = nn.Linear(dim_feedforward, d_model, bias=False, **kw)
ls_kw = cast(dict[str, object], kw)
if layer_scale is not None:
self.ls1 = _LayerScale(d_model, layer_scale, **ls_kw)
self.ls2 = _LayerScale(d_model, layer_scale, **ls_kw)
else:
self.ls1 = nn.Identity()
self.ls2 = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x + self.ls1(self.attn(self.norm1(x)))
x = x + self.ls2(self.ff2(F.gelu(self.ff1(self.norm2(x)))))
return x
class _Transformer(nn.Module):
def __init__(
self,
d_model: int,
num_heads: int,
num_layers: int,
dim_feedforward: int,
causal: bool,
max_period: float,
layer_scale: float | None,
device=None,
dtype=None,
) -> None:
super().__init__()
self.layers = nn.ModuleList(
[
_TransformerLayer(d_model, num_heads, dim_feedforward, causal, max_period, layer_scale, device, dtype)
for _ in range(num_layers)
]
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
for layer in self.layers:
x = layer(x)
return x
class _ProjectedTransformer(nn.Module):
"""Input/output projection + causal transformer (conv-layout: B, D, T)."""
def __init__(
self, input_dimension: int, output_dimension: int, d_model: int, *, module_type: str, **kwargs: Any
) -> None:
super().__init__()
self.downsample_ratio: int = 1
self.in_proj = nn.Linear(input_dimension, d_model, bias=False) if d_model != input_dimension else nn.Identity()
self.transformer = _Transformer(d_model=d_model, **kwargs)
self.out_proj = (
nn.Linear(d_model, output_dimension, bias=False) if d_model != output_dimension else nn.Identity()
)
def forward(self, x: torch.Tensor, lengths: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
x = self.in_proj(x.transpose(1, 2)) # (B, D, T) → (B, T, d_model)
x = self.transformer(x)
x = self.out_proj(x).transpose(1, 2) # (B, T, D) → (B, D, T)
return x, lengths
class _PatchedPretransform(nn.Module):
"""Patch-based up/down-sampling (no learned weights)."""
def __init__(self, patch_size: int, is_downsample: bool, module_type: str, **_: Any) -> None:
super().__init__()
self.patch_size = patch_size
self.downsample_ratio: int = patch_size
self.is_downsample = is_downsample
def forward(self, x: torch.Tensor, lengths: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
b, d, _ = x.shape
h = self.patch_size
if self.is_downsample:
x = x.reshape(b, d, -1, h).permute(0, 1, 3, 2).reshape(b, d * h, -1)
return x, lengths // h
else:
# Upsample by ``h``: split channel dim, then flatten last two dims.
# Was ``reshape(b, d // h, -1 * h)`` which evaluates to ``-h`` and
# is rejected by torch (the failing path produced ``[1, 640, -2]``).
x = x.reshape(b, d // h, h, -1).permute(0, 1, 3, 2).reshape(b, d // h, -1)
return x, lengths * h
# ---------------------------------------------------------------------------
# Vector Quantization
# ---------------------------------------------------------------------------
def _wn_conv1d(*args: Any, **kwargs: Any) -> nn.Module:
return nn.utils.parametrizations.weight_norm(nn.Conv1d(*args, **kwargs))
class _VQ(nn.Module):
"""Single RVQ codebook (inference: encode + decode)."""
def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, **_: Any) -> None:
super().__init__()
self.in_proj = _wn_conv1d(input_dim, codebook_dim, 1) if input_dim != codebook_dim else nn.Identity()
self.out_proj = _wn_conv1d(codebook_dim, input_dim, 1) if input_dim != codebook_dim else nn.Identity()
self.codebook = nn.Embedding(codebook_size, codebook_dim)
@torch.no_grad()
def encode(self, z: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
z_e = self.in_proj(z.float())
enc = z_e.transpose(1, 2).reshape(-1, z_e.shape[1])
w = self.codebook.weight.float()
dist = enc.pow(2).sum(1, keepdim=True) - 2 * enc @ w.t() + w.pow(2).sum(1, keepdim=True).t()
ids = (-dist).max(1)[1].reshape(z.size(0), -1)
return self.out_proj(self.codebook(ids).transpose(1, 2).float()).float(), ids
def decode(self, ids: torch.Tensor) -> torch.Tensor:
return self.out_proj(self.codebook(ids).transpose(1, 2).float()).float()
class _LFQ(nn.Module):
"""Single RLFQ codebook (inference: encode + decode)."""
def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int, **_: Any) -> None:
super().__init__()
self.in_proj = _wn_conv1d(input_dim, codebook_dim, 1) if input_dim != codebook_dim else nn.Identity()
self.out_proj = _wn_conv1d(codebook_dim, input_dim, 1) if input_dim != codebook_dim else nn.Identity()
self.codebook = nn.Embedding(codebook_size, codebook_dim)
@torch.no_grad()
def encode(self, z: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
z_e = self.in_proj(z.float())
enc = F.normalize(z_e.transpose(1, 2).reshape(-1, z_e.shape[1]).float())
cb = F.normalize(self.codebook.weight.float())
dist = enc.pow(2).sum(1, keepdim=True) - 2 * enc @ cb.t() + cb.pow(2).sum(1, keepdim=True).t()
ids = (-dist).max(1)[1].reshape(z.size(0), -1)
z_q = self.codebook(ids).transpose(1, 2).float()
z_q = (z_e + (z_q - z_e).detach()).float()
return self.out_proj(z_q).float(), ids
def decode(self, ids: torch.Tensor) -> torch.Tensor:
return self.out_proj(self.codebook(ids).transpose(1, 2).float()).float()
class _ResidualQ(nn.Module):
"""Residual VQ or LFQ stack."""
def __init__(
self,
input_dim: int,
rvq_dim: int | None,
output_dim: int | None,
num_quantizers: int,
codebook_size: int,
codebook_dim: int,
quantizer_type: str = "rlfq",
**_: Any,
) -> None:
super().__init__()
self.rvq_dim = rvq_dim or input_dim
self.output_dim = output_dim or input_dim
QCls = _LFQ if quantizer_type in {"rlfq", "random_prefix_rlfq"} else _VQ
self.input_proj = _wn_conv1d(input_dim, self.rvq_dim, 1) if input_dim != self.rvq_dim else nn.Identity()
self.output_proj = (
_wn_conv1d(self.rvq_dim, self.output_dim, 1) if self.rvq_dim != self.output_dim else nn.Identity()
)
self.quantizers = nn.ModuleList(
[QCls(self.rvq_dim, codebook_size, codebook_dim) for _ in range(num_quantizers)]
)
@torch.no_grad()
def encode(
self, z: torch.Tensor, lengths: torch.Tensor, n: int | None = None
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
z = self.input_proj(z)
B, _, T = z.shape
mask = torch.arange(T, device=z.device).expand(B, T) < lengths.unsqueeze(1)
out = torch.zeros_like(z, dtype=torch.float32)
residual = z.clone().float()
codes: list[torch.Tensor] = []
for i, q in enumerate(self.quantizers[: n or len(self.quantizers)]):
zq, ids = q.encode(residual * mask.unsqueeze(1))
out += zq * mask.unsqueeze(1)
residual -= zq * mask.unsqueeze(1)
codes.append(ids)
return self.output_proj(out), torch.stack(codes), lengths
def decode_codes(self, codes: torch.Tensor) -> torch.Tensor:
"""codes: (NQ, B, T) → (B, rvq_dim, T)."""
nq, B, T = codes.shape
emb = torch.zeros(B, self.rvq_dim, T, device=codes.device, dtype=torch.float32)
for i, q in enumerate(self.quantizers[:nq]):
emb += q.decode(codes[i])
return self.output_proj(emb)
# ---------------------------------------------------------------------------
# Model
# ---------------------------------------------------------------------------
def _build_modules(
specs: list[dict[str, Any]], is_downsample: bool, context_duration: float, sampling_rate: float
) -> nn.ModuleList:
modules: list[nn.Module] = []
rate = float(sampling_rate)
for spec in specs:
spec = dict(spec)
if spec["module_type"] == "PatchedPretransform":
m = _PatchedPretransform(**spec, is_downsample=is_downsample)
else:
spec.pop("conv_layout", None)
spec.pop("module_type", None)
spec.pop("gating", None)
spec.pop("positional_embedding", None)
spec.pop("norm", None)
spec.pop("causal", None)
m = _ProjectedTransformer(
module_type="Transformer",
causal=True,
max_period=spec.pop("max_period", 10000),
layer_scale=spec.pop("layer_scale", None),
**spec,
)
modules.append(m)
rate = rate / m.downsample_ratio if is_downsample else rate * m.downsample_ratio
return nn.ModuleList(modules)
class MossAudioTokenizerModel(PreTrainedModel):
"""MOSS Audio Tokenizer — inference-only (batch_encode / batch_decode)."""
config_class = MossAudioTokenizerConfig
base_model_prefix = ""
supports_gradient_checkpointing = False
def __init__(self, config: MossAudioTokenizerConfig) -> None:
super().__init__(config)
self.sampling_rate = config.sampling_rate
self.downsample_rate = config.downsample_rate
ctx = config.causal_transformer_context_duration
sr = float(config.sampling_rate)
self.encoder = _build_modules(config.encoder_kwargs, is_downsample=True, context_duration=ctx, sampling_rate=sr)
self.decoder = _build_modules(
copy.deepcopy(config.decoder_kwargs), is_downsample=False, context_duration=ctx, sampling_rate=sr
)
kw = dict(config.quantizer_kwargs)
self.quantizer = _ResidualQ(**kw)
self.post_init()
@torch.no_grad()
def batch_encode(
self,
wav_list: list[torch.Tensor],
num_quantizers: int | None = None,
) -> MossAudioTokenizerEncoderOutput:
"""Encode a list of 1-D waveform tensors → RVQ codes (NQ, B, T)."""
device = wav_list[0].device
B = len(wav_list)
max_len = max(w.shape[-1] for w in wav_list)
x = torch.zeros(B, 1, max_len, device=device)
lengths = torch.zeros(B, device=device, dtype=torch.long)
for i, w in enumerate(wav_list):
x[i, 0, : w.shape[-1]] = w
lengths[i] = w.shape[-1]
return self._encode(x, lengths, num_quantizers)
@torch.no_grad()
def batch_decode(
self,
codes_list: list[torch.Tensor],
num_quantizers: int | None = None,
) -> MossAudioTokenizerDecoderOutput:
"""Decode a list of (NQ, T) code tensors → waveforms."""
device = codes_list[0].device
B = len(codes_list)
nq = num_quantizers or codes_list[0].shape[0]
max_t = max(c.shape[-1] for c in codes_list)
codes = torch.zeros(nq, B, max_t, device=device, dtype=torch.long)
lengths = torch.zeros(B, device=device, dtype=torch.long)
for i, c in enumerate(codes_list):
codes[:nq, i, : c.shape[-1]] = c[:nq]
lengths[i] = c.shape[-1]
return self._decode(codes, lengths)
def _encode(
self,
x: torch.Tensor,
lengths: torch.Tensor,
n_quantizers: int | None = None,
) -> MossAudioTokenizerEncoderOutput:
if x.dim() == 2:
x = x.unsqueeze(1)
T = x.shape[-1]
if T % self.downsample_rate:
x = F.pad(x, (0, self.downsample_rate - T % self.downsample_rate))
e, e_len = x, lengths
for m in self.encoder:
e, e_len = m(e, e_len)
_, codes, code_len = self.quantizer.encode(e, e_len, n_quantizers)
return MossAudioTokenizerEncoderOutput(audio_codes=codes, audio_codes_lengths=code_len)
def _decode(
self,
codes: torch.Tensor,
lengths: torch.Tensor,
) -> MossAudioTokenizerDecoderOutput:
z = self.quantizer.decode_codes(codes)
d, d_len = z, lengths
for m in self.decoder:
d, d_len = m(d, d_len)
return MossAudioTokenizerDecoderOutput(audio=d, audio_lengths=d_len)
__all__ = [
"MossAudioTokenizerConfig",
"MossAudioTokenizerModel",
"MossAudioTokenizerEncoderOutput",
"MossAudioTokenizerDecoderOutput",
]
@@ -0,0 +1,241 @@
# Copyright 2026 OpenMOSS and the vLLM-Omni team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""MOSS-TTS model configuration."""
from __future__ import annotations
from transformers import AutoConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.models.qwen3 import Qwen3Config
class MossTTSDelayConfig(PretrainedConfig):
"""Config for MossTTSDelayModel (8B: MOSS-TTS, MOSS-TTSD, MOSS-SoundEffect;
1.7B: MOSS-VoiceGenerator).
The HuggingFace checkpoint stores a nested ``language_config`` which is a
Qwen3 config. We unwrap it here so that vLLM can use ``get_text_config()``
to size KV caches and allocate memory correctly.
"""
model_type = "moss_tts_delay"
def __init__(
self,
language_config: dict | None = None,
n_vq: int = 32,
audio_vocab_size: int = 1024,
sampling_rate: int = 24000,
audio_pad_code: int = 1024,
audio_start_token_id: int = 151652,
audio_end_token_id: int = 151653,
audio_user_slot_token_id: int = 151654,
audio_assistant_gen_slot_token_id: int = 151656,
audio_assistant_delay_slot_token_id: int = 151662,
pad_token_id: int = 151643,
im_start_token_id: int = 151644,
im_end_token_id: int = 151645,
codec_model_name_or_path: str = "OpenMOSS-Team/MOSS-Audio-Tokenizer",
**kwargs: object,
) -> None:
if language_config is None:
language_config = {}
if isinstance(language_config, dict):
language_config.pop("model_type", None)
self.language_config = Qwen3Config(**language_config)
else:
self.language_config = language_config
super().__init__(**kwargs)
self.n_vq = n_vq
self.audio_vocab_size = audio_vocab_size
self.sampling_rate = sampling_rate
self.audio_pad_code = audio_pad_code
self.audio_start_token_id = audio_start_token_id
self.audio_end_token_id = audio_end_token_id
self.audio_user_slot_token_id = audio_user_slot_token_id
self.audio_assistant_gen_slot_token_id = audio_assistant_gen_slot_token_id
self.audio_assistant_delay_slot_token_id = audio_assistant_delay_slot_token_id
self.pad_token_id = pad_token_id
self.im_start_token_id = im_start_token_id
self.im_end_token_id = im_end_token_id
self.codec_model_name_or_path = codec_model_name_or_path
def get_text_config(self, **_: object) -> Qwen3Config:
return self.language_config
class MossTTSLocalTransformerConfig(PretrainedConfig):
"""Config for the lightweight local depth transformer in MossTTSRealtime.
Mirrors upstream ``MossTTSRealtimeLocalTransformerConfig`` so the realtime
checkpoint loads via ``AutoConfig`` without dropping fields silently.
"""
model_type = "moss_tts_realtime_local_transformer"
def __init__(
self,
head_dim: int = 128,
hidden_size: int = 2048,
num_hidden_layers: int = 4,
num_attention_heads: int = 16,
num_key_value_heads: int = 8,
intermediate_size: int = 6144,
max_position_embeddings: int = 33,
rms_norm_eps: float = 1e-6,
rope_theta: float = 1_000_000.0,
rope_type: str = "linear",
attention_bias: bool = False,
attention_dropout: float = 0.0,
hidden_act: str = "silu",
initializer_range: float = 0.02,
use_cache: bool = True,
tie_word_embeddings: bool = False,
pad_token_id: int = 1024,
audio_pad_token: int = 1024,
audio_vocab_size: int = 1027,
rvq: int = 16,
**kwargs: object,
) -> None:
super().__init__(pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
self.head_dim = head_dim
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.intermediate_size = intermediate_size
self.max_position_embeddings = max_position_embeddings
self.rms_norm_eps = rms_norm_eps
self.rope_theta = rope_theta
self.rope_type = rope_type
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.use_cache = use_cache
self.audio_pad_token = audio_pad_token
self.audio_vocab_size = audio_vocab_size
self.rvq = rvq
# The shared ``CodePredictorBaseModel`` (reused from Qwen3-TTS /
# Qwen3-Omni) reads ``num_code_groups`` and ``vocab_size`` to size its
# codebook embeddings and causal mask. MossTTS names the same
# quantities ``rvq`` and ``audio_vocab_size``; mirror them so the
# common transformer body can be driven from this config unchanged.
self.num_code_groups = rvq
self.vocab_size = audio_vocab_size
# rope_parameters used by transformers.modeling_rope_utils
self.rope_parameters = {
"rope_type": rope_type,
"rope_theta": rope_theta,
"factor": 1.0,
}
class MossTTSRealtimeConfig(PretrainedConfig):
"""Config for MossTTSRealtime (1.7B, TTFB ~180 ms streaming model).
Mirrors the upstream layout: a nested ``language_config`` (Qwen3) plus a
``local_config`` for the per-step depth transformer that decodes the RVQ
codebooks. The flat fields here are the *outer* model's attributes.
"""
model_type = "moss_tts_realtime"
def __init__(
self,
language_config: dict | None = None,
local_config: dict | None = None,
rvq: int = 16,
audio_vocab_size: int = 1027,
audio_pad_token: int = 1024,
sampling_rate: int = 24000,
reference_audio_pad: int = 151654,
text_pad: int = 151655,
vocab_size: int = 151936,
bos_token_id: int = 151643,
eos_token_id: int = 151645,
initializer_range: float = 0.02,
codec_model_name_or_path: str = "OpenMOSS-Team/MOSS-Audio-Tokenizer",
**kwargs: object,
) -> None:
if language_config is None:
language_config = {}
if isinstance(language_config, dict):
language_config.pop("model_type", None)
self.language_config = Qwen3Config(**language_config)
else:
self.language_config = language_config
if local_config is None:
local_config = {}
if isinstance(local_config, dict):
local_config.pop("model_type", None)
self.local_config = MossTTSLocalTransformerConfig(**local_config)
else:
self.local_config = local_config
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
self.rvq = rvq
self.n_vq = rvq # alias for uniform access from talker code
self.audio_vocab_size = audio_vocab_size
self.audio_pad_token = audio_pad_token
self.sampling_rate = sampling_rate
self.reference_audio_pad = reference_audio_pad
self.text_pad = text_pad
self.vocab_size = vocab_size
self.initializer_range = initializer_range
self.codec_model_name_or_path = codec_model_name_or_path
# The talker still reads ``hidden_size`` etc. directly from the config in
# places — proxy them through to ``language_config`` for backward compat.
@property
def hidden_size(self) -> int:
return int(self.language_config.hidden_size)
@property
def num_hidden_layers(self) -> int:
return int(self.language_config.num_hidden_layers)
@property
def num_attention_heads(self) -> int:
return int(self.language_config.num_attention_heads)
@property
def intermediate_size(self) -> int:
return int(self.language_config.intermediate_size)
@property
def max_position_embeddings(self) -> int:
return int(self.language_config.max_position_embeddings)
@property
def rms_norm_eps(self) -> float:
return float(self.language_config.rms_norm_eps)
@property
def rope_theta(self) -> float:
return float(self.language_config.rope_theta)
# vLLM sizes KV cache from get_text_config(); return the inner Qwen3 cfg.
def get_text_config(self, **_: object) -> Qwen3Config:
return self.language_config
AutoConfig.register("moss_tts_delay", MossTTSDelayConfig)
AutoConfig.register("moss_tts_realtime", MossTTSRealtimeConfig)
__all__ = ["MossTTSDelayConfig", "MossTTSRealtimeConfig", "MossTTSLocalTransformerConfig"]
@@ -0,0 +1,301 @@
# Copyright 2026 OpenMOSS and the vLLM-Omni team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
"""MOSS-TTS Stage-1 codec decoder: RVQ codes → 24 kHz waveform."""
from __future__ import annotations
import os
from collections.abc import Iterable
from typing import Any
import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.model_executor.model_loader import DefaultModelLoader
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.model_executor.models.moss_tts.audio_tokenizer import (
MossAudioTokenizerConfig,
MossAudioTokenizerModel,
)
from vllm_omni.model_executor.models.output_templates import OmniOutput
logger = init_logger(__name__)
class MossTTSCodecDecoder(nn.Module):
"""Stage-1 decoder for all MOSS-TTS variants.
Consumes ``(T, NQ)`` audio VQ codes emitted by Stage 0 and decodes them
to a 24 kHz mono waveform using the vendored
``MossAudioTokenizerModel``.
All five variants share the same codec checkpoint
``OpenMOSS-Team/MOSS-Audio-Tokenizer``. The number of quantizers
(``n_vq``) is passed as a ``num_quantizers`` argument to ``batch_decode``
so one codec instance handles both ``n_vq=32`` (MOSS-TTS) and ``n_vq=16``
(all other variants) without swapping weights.
The codec checkpoint path defaults to the value stored in
``vllm_config.model_config.hf_config.codec_model_name_or_path`` but can
be overridden by setting the environment variable
``MOSS_TTS_CODEC_PATH``.
"""
input_modalities = "audio"
have_multimodal_outputs: bool = True
has_preprocess: bool = False
has_postprocess: bool = False
enable_update_additional_information: bool = True
requires_raw_input_tokens: bool = True
_OUTPUT_SAMPLE_RATE: int = 24_000
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
super().__init__()
self.vllm_config = vllm_config
cfg = vllm_config.model_config.hf_config
self._n_vq: int = int(getattr(cfg, "n_vq", getattr(cfg, "rvq", 16)))
self._codec_path: str = str(getattr(cfg, "codec_model_name_or_path", "OpenMOSS-Team/MOSS-Audio-Tokenizer"))
# Resolved at load_weights() time
self._codec: MossAudioTokenizerModel | None = None
self._sr_tensor = torch.tensor(self._OUTPUT_SAMPLE_RATE, dtype=torch.int32)
# ------------------------------------------------------------------
# vLLM-Omni stubs (codec has no AR loop)
# ------------------------------------------------------------------
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
if input_ids.numel() == 0:
return torch.empty((0, 1), device=input_ids.device, dtype=torch.float32)
return torch.zeros((input_ids.shape[0], 1), device=input_ids.device, dtype=torch.float32)
def compute_logits(
self,
hidden_states: torch.Tensor | OmniOutput,
sampling_metadata: Any = None,
) -> None:
return None
# ------------------------------------------------------------------
# Decode
# ------------------------------------------------------------------
@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.
Stage 0 emits flat codebook-major ``[NQ * T_chunk]`` audio codes. The
chunk transfer adapter assigns those to ``request.prompt_token_ids``,
which arrives here as ``input_ids``. Per-request offsets are derived
from ``runtime_additional_information``-attached request metadata; meta
like ``left_context_size`` (overlap context for the causal decoder)
also lives there.
Returns
-------
OmniOutput with:
multimodal_outputs["model_outputs"] — list of (T_wav,) float32 tensors
multimodal_outputs["sr"] — list of scalar int32 tensors
"""
sr_tensor = self._sr_tensor
empty = torch.zeros((0,), dtype=torch.float32)
info_list: list[dict[str, Any]] = runtime_additional_information or []
num_req = max(len(info_list), 1)
if self._codec is None:
logger.warning("MossTTSCodecDecoder called before load_weights(); returning silence.")
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={
"model_outputs": [empty] * num_req,
"sr": [sr_tensor] * num_req,
},
)
audios: list[torch.Tensor] = [empty] * num_req
srs: list[torch.Tensor] = [sr_tensor] * num_req
device = next(self._codec.parameters()).device
if input_ids is None or input_ids.numel() == 0:
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": audios, "sr": srs},
)
# ``input_ids`` is concatenated across all requests; split by
# query_start_loc-style offsets from ``num_scheduled_tokens`` in
# kwargs if available, else assume one request.
ids_flat = input_ids.reshape(-1).to(dtype=torch.long)
num_scheduled_tokens = kwargs.get("num_scheduled_tokens")
if isinstance(num_scheduled_tokens, list) and len(num_scheduled_tokens) == num_req:
offsets = [0]
for n in num_scheduled_tokens:
offsets.append(offsets[-1] + int(n))
else:
offsets = [0, int(ids_flat.shape[0])]
for i, info in enumerate(info_list):
if i + 1 >= len(offsets):
break
seg = ids_flat[offsets[i] : offsets[i + 1]]
if seg.numel() == 0:
continue
if seg.numel() % self._n_vq != 0:
logger.warning(
"MossTTS codec input length %d not divisible by n_vq %d; skipping.",
int(seg.numel()),
self._n_vq,
)
continue
t_chunk = int(seg.numel() // self._n_vq)
codes_nq_t = seg.reshape(self._n_vq, t_chunk).to(device=device)
# Clamp out-of-range codes (the talker uses ``audio_pad_code``
# =``codebook_size`` for delay-pattern padding; passing it to the
# codec embedding lookup would be an OOB index. The downstream
# de-delay step is intended to drop those rows, but until that's
# wired we clamp so the kernel does not assert.)
codebook_size = self._codec.config.codebook_size
codes_nq_t = codes_nq_t.clamp_(0, int(codebook_size) - 1)
# left_context_size: number of left-context frames prepended to
# this chunk by the stage input processor (overlap-add pattern,
# same as Qwen3-TTS code2wav). We decode them together with the
# real chunk for smooth boundaries, then trim them from the output.
meta = (info.get("meta", {}) if isinstance(info, dict) else {}) or {}
left_ctx = meta.get("left_context_size", 0)
if isinstance(left_ctx, (list, tuple)):
left_ctx = int(left_ctx[0]) if left_ctx else 0
elif isinstance(left_ctx, torch.Tensor):
left_ctx = int(left_ctx.reshape(-1)[0].item()) if left_ctx.numel() else 0
left_ctx = int(left_ctx)
out = self._codec.batch_decode(codes_list=[codes_nq_t], num_quantizers=self._n_vq)
if out.audio is None:
continue
wav = out.audio.reshape(-1).to(dtype=torch.float32).cpu()
if out.audio_lengths is not None:
wav = wav[: int(out.audio_lengths[0].item())]
# Trim left-context samples.
if left_ctx > 0:
trim = left_ctx * self._codec.downsample_rate
wav = wav[trim:]
audios[i] = wav
return OmniOutput(
text_hidden_states=None,
multimodal_outputs={"model_outputs": audios, "sr": srs},
)
# ------------------------------------------------------------------
# Weight loading
# ------------------------------------------------------------------
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Drain the Stage-0 weights iterator, then load the codec from its own checkpoint.
The codec lives in a separate HuggingFace repo
(``OpenMOSS-Team/MOSS-Audio-Tokenizer``) and is loaded independently
of the talker weights.
"""
# Drain the incoming weights iterator — all Stage-0 weights are
# irrelevant to this stage.
for _ in weights:
pass
codec_path = os.environ.get("MOSS_TTS_CODEC_PATH", self._codec_path)
logger.info("Loading MOSS Audio Tokenizer from %s", codec_path)
codec_cfg = MossAudioTokenizerConfig.from_pretrained(codec_path)
codec = MossAudioTokenizerModel(codec_cfg)
model_loader = DefaultModelLoader(self.vllm_config.load_config)
source = DefaultModelLoader.Source(
model_or_path=codec_path,
revision=None,
subfolder=None,
)
codec_weights = model_loader._get_weights_iterator(source)
params_dict = dict(codec.named_parameters())
# Upstream MossAudioTokenizer uses different submodule names than the
# vendored re-implementation in ``audio_tokenizer.py``. Without this
# remap only ~half the codec parameters load (codebooks + WN convs)
# and the rest stay at their random init, which produces noise that
# sounds correct in duration but is structurally garbage.
_SUFFIX_REMAP: list[tuple[str, str]] = [
(".self_attn.in_projs.0.", ".attn.in_proj."),
(".self_attn.out_projs.0.", ".attn.out_proj."),
(".linear1.", ".ff1."),
(".linear2.", ".ff2."),
(".layer_scale_1.", ".ls1."),
(".layer_scale_2.", ".ls2."),
(".input_proj.", ".in_proj."),
(".output_proj.", ".out_proj."),
]
def _remap(name: str) -> str:
for src, dst in _SUFFIX_REMAP:
if src in name:
return name.replace(src, dst)
return name
loaded_total = 0
skipped: list[str] = []
for name, tensor in codec_weights:
# Try direct name first (e.g. ``quantizer.input_proj.*`` exists
# under the same name in both layouts), then the remap (transformer
# submodules need ``.linear1.``→``.ff1.`` etc.).
tgt = name if name in params_dict else _remap(name)
if tgt in params_dict:
default_weight_loader(params_dict[tgt], tensor)
loaded_total += 1
else:
skipped.append(name)
logger.info(
"MOSS Audio Tokenizer weights: loaded=%d/%d skipped=%d (first skipped: %s)",
loaded_total,
len(params_dict),
len(skipped),
skipped[:3] if skipped else "none",
)
device = self.vllm_config.device_config.device
codec.to(device=device, dtype=torch.float32)
codec.eval()
self._codec = codec
logger.info(
"MOSS Audio Tokenizer loaded: sampling_rate=%d, n_vq=%d",
codec_cfg.sampling_rate,
codec_cfg.num_quantizers,
)
# Move sr_tensor to the same device
self._sr_tensor = self._sr_tensor.to(device=device)
# vLLM's track_weights_loading() compares the returned set against
# ``self.named_parameters()``. After ``self._codec = codec`` above,
# those parameters are registered with the ``_codec.`` prefix, so
# mirror that here.
return {f"_codec.{name}" for name, _ in codec.named_parameters()}
__all__ = ["MossTTSCodecDecoder"]
@@ -0,0 +1,159 @@
# Copyright 2026 OpenMOSS and the vLLM-Omni team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
"""Local depth transformer for MossTTSRealtime.
A small (4-layer) Qwen3-style decoder that generates the rvq=16 RVQ codebook
codes for one audio frame, autoregressively over codebooks. It runs inside the
talker's per-step ``make_omni_output``, independent from vLLM's main scheduler.
The transformer body is shared with Qwen3-TTS and Qwen3-Omni via
``common.qwen3_code_predictor.CodePredictorBaseModel`` (re-prefill, no KV cache,
HF-compatible numerics). MossTTSRealtime differs in two ways:
* codebook 0 is generated here from ``backbone_last_hidden`` (the other models
receive it from the talker's main LM head), so we run one extra step and own
all ``rvq`` LM heads;
* sampling adds top-p and a windowed repetition penalty on top of
temperature + top-k, matching upstream ``MossTTSRealtimeInference.generate``.
Re-prefilling the (<=rvq) frame each step is numerically identical to the
previous KV-cache loop -- causal attention, only the last position is read.
"""
from __future__ import annotations
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm_omni.model_executor.models.common.qwen3_code_predictor import (
CodePredictorBaseModel,
)
from vllm_omni.model_executor.models.moss_tts.configuration_moss_tts import (
MossTTSLocalTransformerConfig,
)
class MossTTSRealtimeLocalTransformer(nn.Module):
"""Per-frame depth transformer. Mirrors upstream ``...LocalTransformer``.
State per audio frame:
- The first input token uses ``backbone_last_hidden_state`` as the
embedding (codebook 0's "input" is the backbone hidden, not a token).
- Subsequent tokens (1..rvq-1) embed via ``model.codec_embedding[idx-1]``.
Outputs:
- One logit row per codebook position, projected through
``local_lm_heads[codebook_idx]`` (passed in by the talker).
"""
def __init__(self, cfg: MossTTSLocalTransformerConfig) -> None:
super().__init__()
self.config = cfg
# Shared body. Its codec_embedding holds rvq-1 embeddings -- upstream's
# embed_tokens for codebooks 1..rvq-1 (codebook 0 uses the backbone
# hidden). embedding_dim == hidden_size, so no projection is needed.
self.model = CodePredictorBaseModel(
cfg,
embedding_dim=cfg.hidden_size,
use_parallel_embedding=False,
prefix="model",
)
@torch.no_grad()
def generate_frame(
self,
backbone_last_hidden: torch.Tensor, # (B, H)
lm_heads: nn.ModuleList, # ModuleList of rvq Linear(H -> audio_vocab_size)
*,
temperature: float = 1.0,
top_k: int = 50,
top_p: float = 0.95,
do_sample: bool = True,
repetition_penalty: float = 1.0,
history_per_codebook: list[list[int]] | None = None,
) -> torch.Tensor:
"""Generate one audio frame (rvq codebook tokens) for batch B.
Returns a ``(B, rvq)`` LongTensor.
``history_per_codebook[i]`` is a list of recently-emitted token ids for
codebook ``i``; when ``repetition_penalty != 1.0`` those tokens get
their logits scaled down (mirrors upstream's rep-penalty behaviour).
"""
device = backbone_last_hidden.device
B = backbone_last_hidden.shape[0]
rvq = self.config.rvq
hidden_size = self.config.hidden_size
codec_embeds = self.model.codec_embedding
# Re-prefill buffer: position 0 = backbone hidden, position s = embed of
# code_{s-1}. At step s we forward positions [0..s] and read the last.
embeds = backbone_last_hidden.new_zeros((B, rvq, hidden_size))
embeds[:, 0, :] = backbone_last_hidden.to(embeds.dtype)
pos_ids_full = torch.arange(rvq, device=device, dtype=torch.long).unsqueeze(0).expand(B, -1)
codes = backbone_last_hidden.new_zeros((B, rvq), dtype=torch.long)
for step in range(rvq):
seq_len = step + 1
hidden = self.model(embeds[:, :seq_len, :], pos_ids_full[:, :seq_len])
logits = lm_heads[step](hidden[:, step, :]).float()
if repetition_penalty != 1.0 and history_per_codebook is not None and step < len(history_per_codebook):
hist = history_per_codebook[step]
if hist:
hist_t = torch.tensor(hist, dtype=torch.long, device=logits.device)
sel = logits.index_select(-1, hist_t)
pos = sel > 0
sel = torch.where(pos, sel / repetition_penalty, sel * repetition_penalty)
logits.index_copy_(-1, hist_t, sel)
codes[:, step] = _sample_token(logits, temperature, top_k, top_p, do_sample)
if step + 1 < rvq:
embeds[:, step + 1, :] = codec_embeds[step](codes[:, step].view(B, 1)).view(B, hidden_size)
return codes
def _sample_token(
logits: torch.Tensor,
temperature: float,
top_k: int,
top_p: float,
do_sample: bool,
) -> torch.Tensor:
"""Top-k + top-p sampling (matches upstream's ``sample_token`` for the
inference branch).
"""
if not do_sample or temperature <= 0:
return logits.argmax(dim=-1)
logits = logits / max(temperature, 1e-6)
if top_k and top_k > 0 and top_k < logits.shape[-1]:
top_vals, _ = torch.topk(logits, top_k, dim=-1)
thresh = top_vals[..., -1:].expand_as(logits)
logits = torch.where(logits < thresh, torch.full_like(logits, float("-inf")), logits)
if 0.0 < top_p < 1.0:
sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)
probs = F.softmax(sorted_logits, dim=-1)
cum = probs.cumsum(dim=-1)
# Drop tail beyond top_p (keep at least one token).
drop = cum > top_p
drop[..., 1:] = drop[..., :-1].clone()
drop[..., 0] = False
sorted_logits = sorted_logits.masked_fill(drop, float("-inf"))
logits = torch.full_like(logits, float("-inf")).scatter_(-1, sorted_idx, sorted_logits)
probs = F.softmax(logits, dim=-1)
flat = probs.reshape(-1, probs.shape[-1])
sampled = torch.multinomial(flat, num_samples=1).reshape(probs.shape[:-1])
return sampled
__all__ = ["MossTTSRealtimeLocalTransformer"]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,88 @@
# Copyright 2026 OpenMOSS and the vLLM-Omni team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
"""Pipeline topology for all MOSS-TTS variants (2-stage: talker → codec)."""
from vllm_omni.config.stage_config import (
PipelineConfig,
StageExecutionType,
StagePipelineConfig,
)
_PROC = "vllm_omni.model_executor.stage_input_processors.moss_tts"
# ---------------------------------------------------------------------------
# Shared 2-stage pipeline (used by all 5 MOSS-TTS variants)
#
# Stage 0 (LLM_AR) — Qwen3 backbone + (n_vq+1) parallel heads
# emits interleaved text + audio VQ codes
# Stage 1 (LLM_GENERATION) — MOSS Audio Tokenizer decode
# emits 24 kHz mono waveform chunks
# ---------------------------------------------------------------------------
MOSS_TTS_PIPELINE = PipelineConfig(
model_type="moss_tts",
model_arch="MossTTSDelayModel", # HF architectures string
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="moss_tts",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.talker2codec_async_chunk"),
sampling_constraints={
"detokenize": False,
},
),
StagePipelineConfig(
stage_id=1,
model_stage="moss_tts_codec",
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(0,),
final_output=True,
final_output_type="audio",
engine_output_type="audio",
model_arch="MossTTSCodecDecoder",
sync_process_input_func=f"{_PROC}.talker2codec",
sampling_constraints={"detokenize": True},
),
),
)
MOSS_TTS_REALTIME_PIPELINE = PipelineConfig(
model_type="moss_tts_realtime",
model_arch="MossTTSRealtime", # different talker class from the delay variant
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="moss_tts",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
engine_output_type="latent",
async_chunk_process_next_stage_input_func=(f"{_PROC}.talker2codec_async_chunk"),
sampling_constraints={"detokenize": False},
),
StagePipelineConfig(
stage_id=1,
model_stage="moss_tts_codec",
execution_type=StageExecutionType.LLM_GENERATION,
input_sources=(0,),
final_output=True,
final_output_type="audio",
engine_output_type="audio",
model_arch="MossTTSCodecDecoder",
sync_process_input_func=f"{_PROC}.talker2codec",
sampling_constraints={"detokenize": True},
),
),
)
# The pipeline config is otherwise the same for all 5 variants; the per-variant
# differences (n_vq, backbone size, generation strategy) are encoded in the
# HF config.json and the deploy YAML. Realtime is split out because it has a
# different talker architecture (MossTTSRealtime vs MossTTSDelayModel).
__all__ = ["MOSS_TTS_PIPELINE", "MOSS_TTS_REALTIME_PIPELINE"]
@@ -0,0 +1,100 @@
"""Reference-audio encoding + speaker cache for the MOSS-TTS-family talker.
This lives in the model package (not the shared serving layer) so all
MOSS-specific reference handling stays with the model — mirroring how Fish
Speech (``dac_encoder.encode_reference_audio_codes``), CosyVoice3, and
Qwen3-TTS keep their reference/speaker extraction next to the model rather than
in ``serving_speech.py``. The serving layer just calls
:func:`encode_reference_codes` with its generic helpers (the audio resolver and
the process-wide speaker cache).
Kept import-light (only ``asyncio`` / ``hashlib`` / ``torch`` plus the logger)
so importing it from the API-server process does not pull the talker/codec.
"""
from __future__ import annotations
import asyncio
import hashlib
from collections.abc import Awaitable, Callable
from typing import Any
import torch
from vllm.logger import init_logger
logger = init_logger(__name__)
def _encode_wav_sync(processor: Any, wav_list: list, sr: int, sr_target: int, n_vq: int) -> torch.Tensor:
"""Blocking resample + CPU codec encode (the expensive bit)."""
wav = torch.tensor(wav_list, dtype=torch.float32)
if wav.dim() == 1:
wav = wav.unsqueeze(0)
if sr != sr_target:
import torchaudio
wav = torchaudio.functional.resample(wav, sr, sr_target)
with torch.no_grad():
codes_list = processor.encode_audios_from_wav([wav], sampling_rate=sr_target, n_vq=n_vq)
return codes_list[0]
async def encode_reference_codes(
ref_str: str,
*,
processor: Any,
resolve_ref_audio: Callable[[str], Awaitable[tuple[list, int]]],
speaker_cache: Any,
variant: str,
n_vq: int,
sr_target: int,
voice_name: str | None = None,
voice_created_at: int = 0,
) -> torch.Tensor:
"""Encode one reference clip into MOSS RVQ codes, reusing the speaker cache.
The MOSS audio tokenizer sits on CPU (to spare ~6.7 GiB next to the 8B
talker), so re-encoding the same reference is a fixed per-request cost that
otherwise dominates the 8B voice-clone variants and serializes under
concurrency. Mirror CosyVoice3 / Qwen3-TTS: cache by named voice when one is
supplied (``voice_created_at`` invalidates on re-upload), else by a content
hash of the reference. The blocking encode runs in a worker thread via
``asyncio.to_thread`` so cold/anonymous encodes from concurrent requests
overlap instead of serializing on the event loop.
Args:
ref_str: The raw reference audio (URL / path / data URL) as received.
processor: Upstream MOSS processor exposing ``encode_audios_from_wav``.
resolve_ref_audio: Async callable mapping ``ref_str`` to ``(wav_list, sr)``.
speaker_cache: Process-wide ``SpeakerEmbeddingCache``.
variant: MOSS sub-variant (``tts`` / ``ttsd`` / ...), namespaces the cache key.
n_vq: Number of RVQ codebooks (also namespaces the cache key).
sr_target: Target sample rate for the codec.
voice_name: Named/uploaded voice, if any (enables stable cross-request caching).
voice_created_at: Upload timestamp; bumps the cache slot on re-upload.
Returns:
The reference RVQ codes tensor (CPU), ready to pass to the processor.
"""
if voice_name:
speaker_name = voice_name
created_at = int(voice_created_at)
else:
speaker_name = "ref:" + hashlib.sha1((ref_str or "").encode("utf-8")).hexdigest()
created_at = 0
cache_key = speaker_cache.make_cache_key(
speaker_name,
model_type=f"moss_tts_{variant}_nq{n_vq}",
created_at=created_at,
)
cached = speaker_cache.get(cache_key)
if cached is not None:
logger.debug("Speaker cache HIT for MOSS-TTS reference '%s'", speaker_name)
return cached["codes"].clone()
wav_list, sr = await resolve_ref_audio(ref_str)
codes = await asyncio.to_thread(_encode_wav_sync, processor, wav_list, sr, sr_target, n_vq)
speaker_cache.put(cache_key, {"codes": codes.detach().cpu()})
logger.debug("Speaker cache STORE for MOSS-TTS reference '%s'", speaker_name)
return codes
@@ -223,6 +223,25 @@ _OMNI_MODELS = {
"modeling_moss_tts_nano",
"MossTTSNanoForGeneration",
),
## MOSS-TTS (full variants: Delay + Realtime)
# MossTTSDelayModel: MOSS-TTS (8B), MOSS-TTSD (8B), MOSS-SoundEffect (8B), MOSS-VoiceGenerator (1.7B)
"MossTTSDelayModel": (
"moss_tts",
"modeling_moss_tts_talker",
"MossTTSDelayTalkerForGeneration",
),
# MossTTSRealtime: MOSS-TTS-Realtime (1.7B)
"MossTTSRealtime": (
"moss_tts",
"modeling_moss_tts_talker",
"MossTTSRealtimeTalkerForGeneration",
),
# Stage-1 codec decoder (shared by all 5 variants)
"MossTTSCodecDecoder": (
"moss_tts",
"modeling_moss_tts_codec",
"MossTTSCodecDecoder",
),
"DyninOmniForConditionalGeneration": (
"dynin_omni",
"dynin_omni",