CoolFace
Modelpublic

OpenMOSS-Team/MOSS-TTS-Realtime

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
107likes11kdownloads
modeling_mossttsrealtime_local.py471 linesDownload Raw Back to root
1# Copyright 2026 OpenMOSS and the HuggingFace Inc. team. All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""Local transformer used by MossTTSRealtime for RVQ codebook decoding."""15 16from __future__ import annotations17 18from typing import Optional, Union19 20import torch21import torch.nn as nn22 23from transformers.activations import ACT2FN24from transformers.cache_utils import Cache, StaticCache25from transformers.generation import GenerationMixin26from transformers.modeling_flash_attention_utils import FlashAttentionKwargs27from transformers.modeling_layers import GradientCheckpointingLayer28from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast29from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update30from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel31from transformers.masking_utils import create_causal_mask32from transformers.processing_utils import Unpack33from transformers.loss.loss_utils import ForCausalLMLoss34from transformers.utils import TransformersKwargs, logging35from .configuration_mossttsrealtime import MossTTSRealtimeLocalTransformerConfig36 37logger = logging.get_logger(__name__)38 39 40class MossTTSRealtimeLocalTransformerRMSNorm(nn.Module):41    def __init__(self, hidden_size, eps=1e-6) -> None:42        super().__init__()43        self.weight = nn.Parameter(torch.ones(hidden_size))44        self.variance_epsilon = eps45 46    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:47        input_dtype = hidden_states.dtype48        hidden_states = hidden_states.to(torch.float32)49        variance = hidden_states.pow(2).mean(-1, keepdim=True)50        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)51        return self.weight * hidden_states.to(input_dtype)52 53    def extra_repr(self):54        return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"55 56 57class MossTTSRealtimeLocalTransformerMLP(nn.Module):58    def __init__(self, config: MossTTSRealtimeLocalTransformerConfig):59        super().__init__()60        self.config = config61        self.hidden_size = config.hidden_size62        self.intermediate_size = config.intermediate_size63        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)64        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)65        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)66        self.act_fn = ACT2FN[config.hidden_act]67 68    def forward(self, x):69        down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))70        return down_proj71 72 73def rotate_half(x):74    x1 = x[..., : x.shape[-1] // 2]75    x2 = x[..., x.shape[-1] // 2 :]76    return torch.cat((-x2, x1), dim=-1)77 78 79def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):80    cos = cos.unsqueeze(unsqueeze_dim)81    sin = sin.unsqueeze(unsqueeze_dim)82    q_embed = (q * cos) + (rotate_half(q) * sin)83    k_embed = (k * cos) + (rotate_half(k) * sin)84    return q_embed, k_embed85 86 87def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:88    batch, num_key_value_heads, slen, head_dim = hidden_states.shape89    if n_rep == 1:90        return hidden_states91    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)92    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)93 94 95def eager_attention_forward(96    module: nn.Module,97    query: torch.Tensor,98    key: torch.Tensor,99    value: torch.Tensor,100    attention_mask: Optional[torch.Tensor],101    scaling: float,102    dropout: float = 0.0,103    **kwargs: Unpack[TransformersKwargs],104):105    key_states = repeat_kv(key, module.num_key_value_groups)106    value_states = repeat_kv(value, module.num_key_value_groups)107    attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling108    if attention_mask is not None:109        causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]110        attn_weights = attn_weights + causal_mask111    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)112    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)113    attn_output = torch.matmul(attn_weights, value_states)114    attn_output = attn_output.transpose(1, 2).contiguous()115    return attn_output, attn_weights116 117 118class MossTTSRealtimeLocalTransformerAttention(nn.Module):119    def __init__(self, config: MossTTSRealtimeLocalTransformerConfig, layer_idx: int):120        super().__init__()121        self.config = config122        self.layer_idx = layer_idx123        self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)124        self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads125        self.scaling = self.head_dim**-0.5126        self.attention_dropout = config.attention_dropout127        self.is_causal = True128 129        self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias)130        self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)131        self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)132        self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)133        self.q_norm = MossTTSRealtimeLocalTransformerRMSNorm(self.head_dim, eps=config.rms_norm_eps)134        self.k_norm = MossTTSRealtimeLocalTransformerRMSNorm(self.head_dim, eps=config.rms_norm_eps)135        self.sliding_window = None136 137    def forward(138        self,139        hidden_states: torch.Tensor,140        position_embeddings: tuple[torch.Tensor, torch.Tensor],141        attention_mask: Optional[torch.Tensor],142        past_key_values: Optional[Cache] = None,143        cache_position: Optional[torch.LongTensor] = None,144        **kwargs: Unpack[FlashAttentionKwargs],145    ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:146        input_shape = hidden_states.shape[:-1]147        hidden_shape = (*input_shape, -1, self.head_dim)148        query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)149        key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)150        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)151        cos, sin = position_embeddings152 153        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)154 155        if past_key_values is not None:156            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}157            key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)158 159        attention_interface = eager_attention_forward160        if self.config._attn_implementation != "eager":161            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]162 163        attn_output, attn_weights = attention_interface(164            self,165            query_states,166            key_states,167            value_states,168            attention_mask,169            dropout=0.0 if not self.training else self.attention_dropout,170            scaling=self.scaling,171            sliding_window=self.sliding_window,172            **kwargs,173        )174 175        attn_output = attn_output.reshape(*input_shape, -1).contiguous()176        attn_output = self.o_proj(attn_output)177        return attn_output, attn_weights178 179 180class MossTTSRealtimeLocalTransformerDecoderLayer(GradientCheckpointingLayer):181    def __init__(self, config: MossTTSRealtimeLocalTransformerConfig, layer_idx: int):182        super().__init__()183        self.hidden_size = config.hidden_size184        self.self_attn = MossTTSRealtimeLocalTransformerAttention(config=config, layer_idx=layer_idx)185        self.mlp = MossTTSRealtimeLocalTransformerMLP(config)186        self.input_layernorm = MossTTSRealtimeLocalTransformerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)187        self.post_attention_layernorm = MossTTSRealtimeLocalTransformerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)188        self.attention_type = "full_attention"189 190    def forward(191        self,192        hidden_states: torch.Tensor,193        attention_mask: Optional[torch.Tensor] = None,194        position_ids: Optional[torch.LongTensor] = None,195        past_key_values: Optional[Cache] = None,196        use_cache: Optional[bool] = False,197        cache_position: Optional[torch.LongTensor] = None,198        position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,199        **kwargs: Unpack[TransformersKwargs],200    ) -> torch.Tensor:201        residual = hidden_states202        hidden_states = self.input_layernorm(hidden_states)203        hidden_states, _ = self.self_attn(204            hidden_states=hidden_states,205            attention_mask=attention_mask,206            position_ids=position_ids,207            past_key_values=past_key_values,208            use_cache=use_cache,209            cache_position=cache_position,210            position_embeddings=position_embeddings,211            **kwargs,212        )213        hidden_states = residual + hidden_states214        residual = hidden_states215        hidden_states = self.post_attention_layernorm(hidden_states)216        hidden_states = self.mlp(hidden_states)217        hidden_states = residual + hidden_states218        return hidden_states219 220 221class MossTTSRealtimeLocalTransformerPreTrainedModel(PreTrainedModel):222 223    config_class = MossTTSRealtimeLocalTransformerConfig224    config: MossTTSRealtimeLocalTransformerConfig225 226    base_model_prefix = "local_transformer"227    supports_gradient_checkpointing = True228    _no_split_modules = ["MossTTSRealtimeLocalTransformerDecoderLayer"]229    _skip_keys_device_placement = ["past_key_values"]230    _supports_sdpa = True231    _supports_flex_attn = True232    _supports_flash_attn = True233    _can_compile_fullgraph = True234    _supports_attention_backend = True235 236    _can_record_outputs = {237        "hidden_states": MossTTSRealtimeLocalTransformerDecoderLayer,238        "attentions": MossTTSRealtimeLocalTransformerAttention,239    }240 241 242class MossTTSRealtimeLocalTransformerRotaryEmbedding(nn.Module):243    inv_freq: torch.Tensor244 245    def __init__(self, config: MossTTSRealtimeLocalTransformerConfig, device=None):246        super().__init__()247        self.config = config248        self.rope_type = getattr(config, "rope_type", "linear")249        self.max_seq_len_cached = config.max_position_embeddings250        self.original_max_seq_len = config.max_position_embeddings251        self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]252        inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)253        self.register_buffer("inv_freq", inv_freq, persistent=False)254        self.original_inv_freq = self.inv_freq255 256    @torch.no_grad()257    @dynamic_rope_update258    def forward(self, x, position_ids):259        inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)260        position_ids_expanded = position_ids[:, None, :].float()261        device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"262        with torch.autocast(device_type=device_type, enabled=False):263            freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)264            emb = torch.cat((freqs, freqs), dim=-1)265            cos = emb.cos() * self.attention_scaling266            sin = emb.sin() * self.attention_scaling267        return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)268 269 270class MossTTSRealtimeLocalTransformer(MossTTSRealtimeLocalTransformerPreTrainedModel):271    def __init__(self, config: MossTTSRealtimeLocalTransformerConfig):272        super().__init__(config)273        self.padding_idx = config.pad_token_id274        self.embed_tokens = nn.ModuleList(275            [nn.Embedding(config.audio_vocab_size, config.hidden_size, config.audio_pad_token) for _ in range(config.rvq - 1)]276        )277        self.layers = nn.ModuleList(278            [MossTTSRealtimeLocalTransformerDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]279        )280        self.norm = MossTTSRealtimeLocalTransformerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)281        self.rotary_emb = MossTTSRealtimeLocalTransformerRotaryEmbedding(config=config)282        self.gradient_checkpointing = False283        self.has_sliding_layers = None284        self.post_init()285 286    def forward(287        self,288        input_ids: Optional[torch.LongTensor] = None,289        backbone_last_hidden_state: Optional[torch.FloatTensor] = None,290        attention_mask: Optional[torch.Tensor] = None,291        position_ids: Optional[torch.LongTensor] = None,292        past_key_values: Optional[Cache] = None,293        inputs_embeds: Optional[torch.FloatTensor] = None,294        use_cache: Optional[bool] = None,295        cache_position: Optional[torch.LongTensor] = None,296        codebook_idx: Optional[int] = None,297        **kwargs: Unpack[TransformersKwargs],298    ) -> BaseModelOutputWithPast:299        if position_ids is not None and not torch.compiler.is_compiling():300            position_ids = None301 302        if (input_ids is None) == (inputs_embeds is None):303            raise ValueError("You must specify exactly one of input_ids or inputs_embeds.")304 305        if use_cache and past_key_values is None:306            device = inputs_embeds.device if inputs_embeds is not None else input_ids.device307            past_key_values = StaticCache(config=self.config, max_cache_len=self.config.rvq, device=device)308 309        if cache_position is None:310            past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0311            inputs_seq_length = inputs_embeds.shape[1] if inputs_embeds is not None else input_ids.shape[1]312            device = inputs_embeds.device if inputs_embeds is not None else input_ids.device313            cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_seq_length, device=device)314 315        if inputs_embeds is None:316            if codebook_idx is not None:317                if codebook_idx <= 0:318                    raise ValueError(f"`codebook_idx` must be in [1, {len(self.embed_tokens)}], got {codebook_idx}.")319                if codebook_idx > len(self.embed_tokens):320                    raise ValueError(f"`codebook_idx` must be in [1, {len(self.embed_tokens)}], got {codebook_idx}.")321                if input_ids.ndim == 1:322                    input_ids = input_ids.unsqueeze(1)323                token_emb = self.embed_tokens[codebook_idx - 1](input_ids[:, 0]).unsqueeze(1)  # [B,1,H]324                inputs_embeds = token_emb325            else:326                if input_ids.shape[1] != cache_position.shape[0]:327                    raise ValueError(328                        "`input_ids` and `cache_position` must align in sequence length: "329                        f"got {input_ids.shape[1]} and {cache_position.shape[0]}."330                    )331                codebook_idxs = torch.clamp(cache_position - 1, min=0, max=len(self.embed_tokens) - 1)332                inputs_embeds = torch.stack(333                    [334                        self.embed_tokens[codebook_idx](input_ids[:, seq_idx])335                        for seq_idx, codebook_idx in enumerate(codebook_idxs.tolist())336                    ],337                    dim=1,338                )339 340                input_ids_are_first_codebook = bool(cache_position[0] == 0)341                if backbone_last_hidden_state is not None:342                    inputs_embeds[:, 0, :] = backbone_last_hidden_state[:, 0, :]343                else:344                    if not torch.compiler.is_compiling() and input_ids_are_first_codebook:345                        logger.warning(346                            "When the first codebook token is provided, `backbone_last_hidden_state` should also be provided for correct inference."347                        )348 349        causal_mask = create_causal_mask(350            config=self.config,351            input_embeds=inputs_embeds,352            attention_mask=attention_mask,353            cache_position=cache_position,354            past_key_values=past_key_values,355            position_ids=position_ids,356        )357 358        hidden_states = inputs_embeds359        position_ids = cache_position.unsqueeze(0)360        position_embeddings = self.rotary_emb(hidden_states, position_ids)361 362        for decoder_layer in self.layers[: self.config.num_hidden_layers]:363            hidden_states = decoder_layer(364                hidden_states,365                attention_mask=causal_mask,366                position_ids=position_ids,367                past_key_values=past_key_values,368                use_cache=use_cache,369                cache_position=cache_position,370                position_embeddings=position_embeddings,371                **kwargs,372            )373        hidden_states = self.norm(hidden_states)374        return BaseModelOutputWithPast(375            last_hidden_state=hidden_states,376            past_key_values=past_key_values if use_cache else None,377        )378 379 380class MossTTSRealtimeLocalTransformerForCausalLM(MossTTSRealtimeLocalTransformerPreTrainedModel, GenerationMixin):381    _tied_weights_keys = None382    _tp_plan = None383    _pp_plan = None384 385    def __init__(self, config):386        super().__init__(config)387        self.model = MossTTSRealtimeLocalTransformer(config)388        self.audio_vocab_size = self.config.audio_vocab_size389 390        self.local_lm_heads = nn.ModuleList(391            [nn.Linear(config.hidden_size, config.audio_vocab_size, bias=False) for _ in range(config.rvq)]392        )393        self.post_init()394 395    def forward(396        self,397        input_ids: Optional[torch.LongTensor] = None,398        backbone_last_hidden_state: Optional[torch.FloatTensor] = None,399        attention_mask: Optional[torch.Tensor] = None,400        position_ids: Optional[torch.LongTensor] = None,401        past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,402        inputs_embeds: Optional[torch.FloatTensor] = None,403        labels: Optional[torch.LongTensor] = None,404        use_cache: Optional[bool] = None,405        cache_position: Optional[torch.LongTensor] = None,406        codebook_idx: Optional[int] = None,407        logits_to_keep: Union[int, torch.Tensor] = 0,408        **kwargs: Unpack[TransformersKwargs],409    ) -> Union[tuple, CausalLMOutputWithPast]:410        outputs = self.model(411            input_ids=input_ids,412            backbone_last_hidden_state=backbone_last_hidden_state,413            inputs_embeds=inputs_embeds,414            attention_mask=attention_mask,415            position_ids=position_ids,416            past_key_values=past_key_values,417            use_cache=use_cache,418            cache_position=cache_position,419            codebook_idx=codebook_idx,420            **kwargs,421        )422 423        hidden_states = outputs.last_hidden_state424 425        if isinstance(logits_to_keep, int):426            if logits_to_keep == 0:427                slice_indices = slice(0, None)428            else:429                slice_indices = slice(-logits_to_keep, None)430        else:431            slice_indices = logits_to_keep432        hs = hidden_states[:, slice_indices, :]433 434        if cache_position is not None:435            if codebook_idx is None:436                raise ValueError("`codebook_idx` must be provided when `cache_position` is provided.")437            logits = self.local_lm_heads[codebook_idx](hs[:, 0, :]).unsqueeze(1)438        else:439            if hs.shape[1] > len(self.local_lm_heads):440                raise ValueError(441                    f"Cannot project {hs.shape[1]} codebooks with only {len(self.local_lm_heads)} LM heads."442                )443            logits_list = []444            for i in range(hs.shape[1]):445                logits_list.append(self.local_lm_heads[i](hs[:, i, :]))446            logits = torch.stack(logits_list, dim=1)447 448        logits = logits.contiguous()449        loss = None450        if labels is not None:451            loss = ForCausalLMLoss(logits, None, self.audio_vocab_size, shift_labels=labels.contiguous())452 453        return CausalLMOutputWithPast(454            loss=loss,455            logits=logits,456            past_key_values=outputs.past_key_values,457            hidden_states=outputs.hidden_states,458            attentions=outputs.attentions,459        )460 461__all__ = [462    "MossTTSRealtimeLocalTransformer",463    "MossTTSRealtimeLocalTransformerAttention",464    "MossTTSRealtimeLocalTransformerConfig",465    "MossTTSRealtimeLocalTransformerDecoderLayer",466    "MossTTSRealtimeLocalTransformerForCausalLM",467    "MossTTSRealtimeLocalTransformerPreTrainedModel",468    "MossTTSRealtimeLocalTransformerRMSNorm",469    "MossTTSRealtimeLocalTransformerRotaryEmbedding",470]471