EmoSphere-PP-16kHz / modeling_emosphere_pp.py
RetentionLabs's picture
Mixed float32 and float16 weights without NVFP4, and a new model card
4be7049 verified
Raw History Blame Contribute Delete
56 kB
# Copyright 2026 The EmoSphere++ Authors, The Matcha-TTS Authors, The Glow-TTS Authors, Huawei Technologies Co., Ltd., # TICTAP-11 and b-re-w. All rights reserved. # # Licensed under the MIT License. You may obtain a copy of the License at # # https://opensource.org/licenses/MIT # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """PyTorch EmoSphere++ model.""" import math import random import re from dataclasses import dataclass from pathlib import Path import torch import torch.nn.functional as F from torch import nn from transformers import initialization as init from transformers.modeling_outputs import ModelOutput from transformers.modeling_utils import PreTrainedModel from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import Qwen2_5OmniSnakeBeta from transformers.models.vits.modeling_vits import VitsAttention, VitsDurationPredictor, VitsEncoder from voicestudio.models.cosyvoice_v1.modeling_cosyvoice_v1 import CosyVoiceV1ConditionalCFM, CosyVoiceV1ConditionalDecoder, CosyVoiceV1EstimatorFeedForward from .configuration_emosphere_pp import EmoSpherePPConfig __all__ = [ "EMOSPHERE_PP_VAD_CENTERS", "EmoSpherePPConditionalCFM", "EmoSpherePPConvReluNorm", "EmoSpherePPDecoder", "EmoSpherePPForConditionalGeneration", "EmoSpherePPOutput", "EmoSpherePPPreTrainedModel", "EmoSpherePPSnakeBeta", "EmoSpherePPStyleEncoder", "EmoSpherePPTextEncoder", "convert_emosphere_pp_state_dict", "emotion_adaptive_spherical_vector", "fix_length_compatibility", "generate_path", "maximum_path", "sequence_mask", ] # Centers $M_k$ of the emotion-adaptive coordinate systems that upstream fixes for ESD # (`data_gen/tts/base_binarizer.py:236`), in the output order of `audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim`: # arousal, dominance, valence. EMOSPHERE_PP_VAD_CENTERS = { "neutral": (0.4135, 0.5169, 0.3620), "angry": (0.37068613, 0.4814421, 0.37709341), "happy": (0.36792182, 0.48303542, 0.34562907), "sad": (0.48519272, 0.57727589, 0.39524114), "surprise": (0.36877737, 0.48431942, 0.36644742), } # Bin boundaries of the elevation and azimuth embeddings (`models/tts/EmoSpherepp/model.py:89` to `:91`). _ELEVATION_BOUNDARIES = (math.pi / 2, math.pi, 2) _AZIMUTH_BOUNDARIES = (-math.pi / 2, math.pi, 4) def sequence_mask(lengths: torch.Tensor, max_length: int | None = None) -> torch.Tensor: r""" Args: lengths (`torch.Tensor` of shape `(batch_size,)`): Valid length of every sequence. max_length (`int`, *optional*): Length of the mask. Defaults to the largest of `lengths`. Returns: `torch.Tensor` of shape `(batch_size, max_length)`: `True` on the valid positions. """ if max_length is None: max_length = int(lengths.max()) positions = torch.arange(int(max_length), dtype=lengths.dtype, device=lengths.device) return positions.unsqueeze(0) < lengths.unsqueeze(1) def fix_length_compatibility(length: int, num_downsamplings: int = 2) -> int: r""" Args: length (`int`): Number of mel frames. num_downsamplings (`int`, *optional*, defaults to 2): Number of halvings the length has to survive. Upstream keeps the Matcha-TTS default of 2 although its U-Net halves the time axis once. Returns: `int`: The smallest multiple of $2^{n}$ that is not below `length`. """ factor = 2**num_downsamplings return -(-length // factor) * factor def generate_path(duration: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: r""" Expands token durations into a hard monotonic alignment. Args: duration (`torch.Tensor` of shape `(batch_size, text_length)`): Number of frames of every token. mask (`torch.Tensor` of shape `(batch_size, text_length, mel_length)`): 1 on the valid pairs of a token and a frame. Returns: `torch.Tensor` of shape `(batch_size, text_length, mel_length)`: 1 where frame $j$ belongs to token $i$. """ batch_size, text_length, mel_length = mask.shape cumulative = torch.cumsum(duration, 1).view(batch_size * text_length) path = sequence_mask(cumulative, mel_length).to(mask.dtype).view(batch_size, text_length, mel_length) path = path - F.pad(path, [0, 0, 1, 0, 0, 0])[:, :-1] return path * mask @torch.no_grad() def maximum_path(value: torch.Tensor, mask: torch.Tensor, max_neg_val: float = -1e9) -> torch.Tensor: r""" Monotonic alignment search of Glow-TTS. It is the search of the Cython `maximum_path_c` upstream builds (`monotonic_align/core.pyx`), run over the frames one step at a time and over the batch and the tokens at once, in single precision as upstream runs it. Args: value (`torch.Tensor` of shape `(batch_size, text_length, mel_length)`): Log likelihood of every frame under every token. mask (`torch.Tensor` of shape `(batch_size, text_length, mel_length)`): 1 on the valid pairs of a token and a frame. max_neg_val (`float`, *optional*, defaults to -1e9): Score of the moves the search may not take. Returns: `torch.Tensor` of shape `(batch_size, text_length, mel_length)`: The most likely monotonic alignment, 1 where frame $j$ belongs to token $i$. """ dtype = value.dtype value = (value * mask).float() batch_size, text_length, mel_length = value.shape text_lengths = mask.sum(1)[:, 0].long() mel_lengths = mask.sum(2)[:, 0].long() tokens = torch.arange(text_length, device=value.device) blocked = torch.full((batch_size, 1), max_neg_val, dtype=value.dtype, device=value.device) for frame in range(mel_length): previous = value[:, :, frame - 1] stay = torch.where(tokens == frame, torch.full_like(previous, max_neg_val), previous) first = torch.zeros_like(blocked) if frame == 0 else blocked advance = torch.cat([first, previous[:, :-1]], dim=1) lower = (text_lengths + frame - mel_lengths).clamp(min=0).unsqueeze(1) upper = text_lengths.clamp(max=frame + 1).unsqueeze(1) reachable = (tokens >= lower) & (tokens < upper) & (frame < mel_lengths).unsqueeze(1) value[:, :, frame] = torch.where(reachable, torch.maximum(stay, advance) + value[:, :, frame], value[:, :, frame]) path = torch.zeros_like(value) batch = torch.arange(batch_size, device=value.device) index = text_lengths - 1 for frame in range(mel_length - 1, -1, -1): active = frame < mel_lengths path[batch[active], index[active], frame] = 1 if frame == 0: break stay_score = value[batch, index, frame - 1] advance_score = value[batch, (index - 1).clamp(min=0), frame - 1] move = active & (index != 0) & ((index == frame) | (stay_score < advance_score)) index = index - move.long() return path.to(dtype) def emotion_adaptive_spherical_vector( vad: torch.Tensor, center: torch.Tensor, first_quartile: float, third_quartile: float ) -> torch.Tensor: r""" Emotion-adaptive spherical vector of a non neutral utterance (`data_gen/tts/base_binarizer.py:366`). The VAD vector is shifted by the center $M_k$ of its emotion, turned into spherical coordinates and its radius is clamped to the interquartile bounds of that emotion and rescaled to $[0, 1]$: $$ r_{IQR}=\frac{\min(\max(r, r_{min}), r_{max})-r_{min}}{r_{max}-r_{min}},\qquad \vartheta=\arccos\frac{e_2}{r},\qquad \phi=\operatorname{atan2}(e_1, e_0), $$ with $r_{min}=Q_1-1.5(Q_3-Q_1)$ and $r_{max}=Q_3+1.5(Q_3-Q_1)$. Both angles are zero where $r_{IQR}=0$. Upstream gives every neutral utterance the vector $(0, 0, 0)$ instead. Args: vad (`torch.Tensor` of shape `(batch_size, 3)`): Output of `audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim`, in its order: arousal, dominance, valence. center (`torch.Tensor` of shape `(3,)`): Center $M_k$ of the emotion, for example from [`EMOSPHERE_PP_VAD_CENTERS`]. first_quartile (`float`): First quartile $Q_1$ of the distance to `center` over the training utterances of the emotion. third_quartile (`float`): Third quartile $Q_3$ of the same distances. Returns: `torch.Tensor` of shape `(batch_size, 3)`: $(r_{IQR}, \vartheta, \phi)$. The model reads the first column as `emotion_intensity` and the last two as `emotion_style`. """ shifted = vad - center radius = torch.sqrt(torch.sum(shifted**2, dim=-1)) spread = (third_quartile - first_quartile) * 1.5 radius_max = third_quartile + spread radius_min = first_quartile - spread intensity = (torch.clamp(radius, min=radius_min, max=radius_max) - radius_min) / (radius_max - radius_min) elevation = torch.acos(shifted[..., 2] / radius) azimuth = torch.atan2(shifted[..., 1], shifted[..., 0]) at_center = intensity == 0 elevation = torch.where(at_center, torch.zeros_like(elevation), elevation) azimuth = torch.where(at_center, torch.zeros_like(azimuth), azimuth) return torch.stack((intensity, elevation, azimuth), dim=-1) class EmoSpherePPConvReluNorm(nn.Module): r""" Constructs the residual pre-net of the Glow-TTS text encoder (`ConvReluNorm` in `models/tts/EmoSpherepp/text_encoder.py:32`): convolutions, each followed by a channel layer norm, a ReLU and dropout, and a zero initialized projection added to the input. Args: config ([`EmoSpherePPConfig`]): Model configuration. """ def __init__(self, config: EmoSpherePPConfig): super().__init__() channels = config.text_hidden_size kernel_size = config.prenet_kernel_size self.conv_layers = nn.ModuleList( [nn.Conv1d(channels, channels, kernel_size, padding=kernel_size // 2) for _ in range(config.prenet_num_layers)] ) self.norm_layers = nn.ModuleList( [nn.LayerNorm(channels, eps=config.layer_norm_eps) for _ in range(config.prenet_num_layers)] ) self.dropout = nn.Dropout(config.prenet_dropout) self.proj = nn.Conv1d(channels, channels, 1) def forward(self, hidden_states: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: r""" Args: hidden_states (`torch.Tensor` of shape `(batch_size, channels, text_length)`): Scaled phoneme embeddings. mask (`torch.Tensor` of shape `(batch_size, 1, text_length)`): 1 on the valid tokens. Returns: `torch.Tensor` of shape `(batch_size, channels, text_length)`: The pre-net output. """ residual = hidden_states for conv, norm in zip(self.conv_layers, self.norm_layers): hidden_states = conv(hidden_states * mask) hidden_states = norm(hidden_states.transpose(1, 2)).transpose(1, 2) hidden_states = self.dropout(torch.relu(hidden_states)) return (residual + self.proj(hidden_states)) * mask class EmoSpherePPTextEncoder(nn.Module): r""" Constructs the Glow-TTS text encoder of Matcha-TTS with the style embedding of EmoSphere++ (`TextEncoder` in `models/tts/EmoSpherepp/text_encoder.py:369`). The phoneme embeddings pass the pre-net, the style embedding is concatenated to every token, and a stack of relative position transformer layers produces the prior mean $\mu$ and, from its detached output, the log durations. The transformer layers and the duration predictor are [`VitsEncoder`] and [`VitsDurationPredictor`], which VITS inherits from Glow-TTS unchanged: the attention adds the same shared relative key and value embeddings, the feed forward is the same pair of masked convolutions, and both normalize after the residual. Args: config ([`EmoSpherePPConfig`]): Model configuration. """ def __init__(self, config: EmoSpherePPConfig): super().__init__() self.hidden_size = config.text_hidden_size vits_config = config.get_text_encoder_config() self.embed_tokens = nn.Embedding(config.vocab_size, config.text_hidden_size) self.prenet = EmoSpherePPConvReluNorm(config) self.encoder = VitsEncoder(vits_config) self.mean_proj = nn.Conv1d(config.text_encoder_hidden_size, config.num_mel_bins, 1) self.duration_predictor = VitsDurationPredictor(vits_config) def forward( self, input_ids: torch.Tensor, input_lengths: torch.Tensor, style_embedding: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: r""" Args: input_ids (`torch.Tensor` of shape `(batch_size, text_length)`): Phoneme ids with the blank id between every two phonemes. input_lengths (`torch.Tensor` of shape `(batch_size,)`): Number of valid ids per sequence. style_embedding (`torch.Tensor` of shape `(batch_size, condition_size)`): Joint attribute style embedding. Returns: `tuple(torch.Tensor)`: The prior mean of shape `(batch_size, num_mel_bins, text_length)`, the log durations of shape `(batch_size, 1, text_length)` and the token mask of shape `(batch_size, 1, text_length)`. """ hidden_states = self.embed_tokens(input_ids) * math.sqrt(self.hidden_size) padding = sequence_mask(input_lengths, input_ids.shape[1]) mask = padding.unsqueeze(1).to(hidden_states.dtype) hidden_states = self.prenet(hidden_states.transpose(1, 2), mask) style = style_embedding.unsqueeze(-1).expand(-1, -1, hidden_states.shape[-1]) hidden_states = torch.cat([hidden_states, style], dim=1) hidden_states = self.encoder( hidden_states.transpose(1, 2), padding_mask=mask.transpose(1, 2), attention_mask=padding.long(), return_dict=True, ).last_hidden_state.transpose(1, 2) mean = self.mean_proj(hidden_states) * mask log_durations = self.duration_predictor(hidden_states, mask) return mean, log_durations, mask class EmoSpherePPStyleEncoder(nn.Module): r""" Constructs the joint attribute style encoder of EmoSphere++ (`models/tts/EmoSpherepp/model.py:84` to `:107` and `:226` to `:257`). A WavLM x-vector and an emotion2vec utterance embedding each pass a two layer perceptron. The elevation and the azimuth of the emotion-adaptive spherical vector select one of 2 and one of 4 learned embeddings, which are projected and concatenated to the emotion embedding. The pair passes a softplus and a layer norm, and the projected intensity is added: $$ e_{emo}=\mathrm{LN}(\mathrm{softplus}([\mathrm{MLP}_{emo}(e);W_s[E_\vartheta;E_\phi]]))+W_r r,\qquad e_{sty}=[\mathrm{MLP}_{spk}(s);e_{emo}]. $$ Args: config ([`EmoSpherePPConfig`]): Model configuration. """ def __init__(self, config: EmoSpherePPConfig): super().__init__() size = config.style_embedding_size self.speaker_mlp = nn.Sequential( nn.Linear(config.speaker_embedding_size, config.style_hidden_size), nn.Mish(), nn.Linear(config.style_hidden_size, size), ) self.emotion_mlp = nn.Sequential( nn.Linear(config.emotion_embedding_size, config.style_hidden_size), nn.Mish(), nn.Linear(config.style_hidden_size, size), ) self.intensity_proj = nn.Linear(1, 2 * size) self.elevation_embedding = nn.Embedding(_ELEVATION_BOUNDARIES[2], size // 2) self.azimuth_embedding = nn.Embedding(_AZIMUTH_BOUNDARIES[2], size // 2) self.style_proj = nn.Linear(size, size) self.emotion_layer_norm = nn.LayerNorm(2 * size) self.elevation_bins = nn.Buffer(torch.linspace(*_ELEVATION_BOUNDARIES), persistent=False) self.azimuth_bins = nn.Buffer(torch.linspace(*_AZIMUTH_BOUNDARIES), persistent=False) def elevation_index(self, elevation: torch.Tensor) -> torch.Tensor: r""" Args: elevation (`torch.Tensor`): Elevation $\vartheta$ in $[0, \pi]$. Returns: `torch.Tensor`: 0 up to $\pi/2$ and 1 above it. """ return torch.bucketize(elevation, self.elevation_bins) def azimuth_index(self, azimuth: torch.Tensor) -> torch.Tensor: r""" Args: azimuth (`torch.Tensor`): Azimuth $\phi$ in $(-\pi, \pi]$. Returns: `torch.Tensor`: 0 up to $-\pi/2$, 1 up to $0$, 2 up to $\pi/2$ and 3 above it. """ return torch.bucketize(azimuth, self.azimuth_bins) def forward( self, speaker_embeddings: torch.Tensor, emotion_embeddings: torch.Tensor, emotion_intensity: torch.Tensor, emotion_style: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: r""" Args: speaker_embeddings (`torch.Tensor` of shape `(batch_size, speaker_embedding_size)`): x-vector of `microsoft/wavlm-base-sv` for the reference utterance. emotion_embeddings (`torch.Tensor` of shape `(batch_size, emotion_embedding_size)`): Utterance embedding of `emotion2vec_plus_base` for the reference utterance. emotion_intensity (`torch.Tensor` of shape `(batch_size, 1)`): Radius $r_{IQR}$ of the emotion-adaptive spherical vector. emotion_style (`torch.Tensor` of shape `(batch_size, 2)`): Elevation $\vartheta$ and azimuth $\phi$ of the emotion-adaptive spherical vector. Returns: `tuple(torch.Tensor)`: The joint attribute style embedding of shape `(batch_size, 3 * style_embedding_size)` and the outputs of the speaker and emotion perceptrons, which the orthogonality loss compares. """ speaker_hidden = self.speaker_mlp(speaker_embeddings) emotion_hidden = self.emotion_mlp(emotion_embeddings) intensity = self.intensity_proj(emotion_intensity) angles = torch.cat( ( self.elevation_embedding(self.elevation_index(emotion_style[:, 0].contiguous())), self.azimuth_embedding(self.azimuth_index(emotion_style[:, 1].contiguous())), ), dim=-1, ) emotion = F.softplus(torch.cat((emotion_hidden, self.style_proj(angles)), dim=-1)) emotion = self.emotion_layer_norm(emotion) + intensity return torch.cat((speaker_hidden, emotion), dim=-1), speaker_hidden, emotion_hidden class EmoSpherePPSnakeBeta(Qwen2_5OmniSnakeBeta): r""" Constructs the projecting snakebeta activation of the Matcha-TTS estimator feed forward (`SnakeBeta` in `models/tts/EmoSpherepp/transformer.py:17`): a linear projection followed by $x+\frac{1}{e^{\beta}+10^{-9}}\sin^2(e^{\alpha}x)$ over the last axis, with $\alpha$ and $\beta$ starting at zero. Args: in_features (`int`): Size of the input. out_features (`int`): Size of the projection, and number of $\alpha$ and $\beta$ parameters. """ def __init__(self, in_features: int, out_features: int): super().__init__(out_features) self.proj = nn.Linear(in_features, out_features) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: r""" Args: hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, in_features)`): Activation input. Returns: `torch.Tensor` of shape `(batch_size, sequence_length, out_features)`: The activation output. """ hidden_states = self.proj(hidden_states) return super().forward(hidden_states.transpose(1, -1)).transpose(1, -1) class EmoSpherePPDecoder(CosyVoiceV1ConditionalDecoder): r""" Constructs the one dimensional U-Net of Matcha-TTS that predicts the flow matching vector field (`Decoder` in `models/tts/EmoSpherepp/decoder.py:209`). CosyVoice took this U-Net from Matcha-TTS, so the layers, their order and their parameter names are those of [`CosyVoiceV1ConditionalDecoder`]. Two things differ: - the feed forward of every transformer block activates with [`EmoSpherePPSnakeBeta`] instead of GELU when `config.estimator_act_fn` is `"snakebeta"`; - Matcha-TTS hands the 0/1 frame mask to `diffusers`' `Attention`, which adds it to the attention scores as it is. Padded frames therefore stay visible to every query, with a score 1 lower than the valid ones. The estimator reads no mel prefix, so its input is the noisy spectrogram, the prior and the style embedding. Args: config ([`EmoSpherePPConfig`]): Model configuration. """ def __init__(self, config: EmoSpherePPConfig): super().__init__(config) if config.estimator_act_fn == "snakebeta": feed_forwards = [module for module in self.modules() if isinstance(module, CosyVoiceV1EstimatorFeedForward)] for feed_forward in feed_forwards: projection = feed_forward.net[0].proj feed_forward.net[0] = EmoSpherePPSnakeBeta(projection.in_features, projection.out_features) def forward( self, hidden_states: torch.Tensor, mask: torch.Tensor, mu: torch.Tensor, timesteps: torch.Tensor, speaker_hidden_states: torch.Tensor, conditioning: torch.Tensor | None = None, ) -> torch.Tensor: r""" Args: hidden_states (`torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`): Noisy mel spectrogram. mask (`torch.Tensor` of shape `(batch_size, 1, mel_length)`): 1 on valid frames. mu (`torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`): Prior mean aligned to the frames. timesteps (`torch.Tensor` of shape `(batch_size,)` or `()`): Flow matching time. speaker_hidden_states (`torch.Tensor` of shape `(batch_size, condition_size)`): Joint attribute style embedding. conditioning (`torch.Tensor` of shape `(batch_size, channels, mel_length)`, *optional*): Extra channels concatenated to the input. EmoSphere++ has none. Returns: `torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`: The predicted vector field. """ timesteps = timesteps.to(device=hidden_states.device, dtype=hidden_states.dtype) if conditioning is None: conditioning = hidden_states.new_zeros(hidden_states.shape[0], 0, hidden_states.shape[-1]) return super().forward(hidden_states, mask, mu, timesteps, speaker_hidden_states, conditioning) @staticmethod def _attention_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: """ Args: mask (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): 1 on valid frames. dtype (`torch.dtype`): Floating point type of the returned bias. Returns: `torch.Tensor` of shape `(batch_size, 1, 1, sequence_length)`: The mask itself, added to the scores. """ return mask.to(dtype).unsqueeze(1) class EmoSpherePPConditionalCFM(CosyVoiceV1ConditionalCFM): r""" Constructs the conditional flow matching decoder of Matcha-TTS (`CFM` in `models/tts/EmoSpherepp/flow_matching.py:128`). Training follows [`CosyVoiceV1ConditionalCFM.compute_loss`], which is the Matcha-TTS loss: the optimal transport path $\phi_t(x_0)=(1-(1-\sigma_{min})t)x_0+tx_1$ and the masked mean squared error to its velocity $x_1-(1-\sigma_{min})x_0$. Sampling is the fixed step Euler solver of Matcha-TTS from noise scaled by the temperature, with the guidance of EmoSphere++ that pushes away from the prior averaged over time: $$ v=v_\theta(x_t,\mu,e_{sty},t)+\gamma\,(v_\theta(x_t,\mu,e_{sty},t)-v_\theta(x_t,\bar\mu,e_{sty},t)). $$ Args: config ([`EmoSpherePPConfig`]): Model configuration. """ def __init__(self, config: EmoSpherePPConfig): super().__init__(config) # the parent builds a CosyVoice estimator, which this one replaces self.estimator = EmoSpherePPDecoder(config) @torch.no_grad() def forward( self, mu: torch.Tensor, mask: torch.Tensor, num_steps: int, speaker_hidden_states: torch.Tensor, temperature: float = 1.0, guidance_scale: float = 0.0, ) -> torch.Tensor: r""" Args: mu (`torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`): Prior mean aligned to the frames. mask (`torch.Tensor` of shape `(batch_size, 1, mel_length)`): 1 on valid frames. num_steps (`int`): Number of Euler steps. speaker_hidden_states (`torch.Tensor` of shape `(batch_size, condition_size)`): Joint attribute style embedding. temperature (`float`, *optional*, defaults to 1.0): Scale of the initial noise. guidance_scale (`float`, *optional*, defaults to 0.0): Guidance $\gamma$ away from the time averaged prior. Returns: `torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`: The sampled mel spectrogram. """ noise = torch.randn_like(mu) * temperature t_span = torch.linspace(0, 1, num_steps + 1, device=mu.device) return self.solve_euler(noise, t_span, mu, mask, speaker_hidden_states, guidance_scale) def solve_euler( self, hidden_states: torch.Tensor, t_span: torch.Tensor, mu: torch.Tensor, mask: torch.Tensor, speaker_hidden_states: torch.Tensor, guidance_scale: float = 0.0, ) -> torch.Tensor: r""" Args: hidden_states (`torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`): Initial noise. t_span (`torch.Tensor` of shape `(num_steps + 1,)`): Times of the solver. mu (`torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`): Prior mean aligned to the frames. mask (`torch.Tensor` of shape `(batch_size, 1, mel_length)`): 1 on valid frames. speaker_hidden_states (`torch.Tensor` of shape `(batch_size, condition_size)`): Joint attribute style embedding. guidance_scale (`float`, *optional*, defaults to 0.0): Guidance $\gamma$ away from the time averaged prior. Returns: `torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`: The sampled mel spectrogram. """ # The state integrates in the dtype of `mu`; the estimator runs in the dtype of its weights. estimator_dtype = next(self.estimator.parameters()).dtype def estimate(prior: torch.Tensor) -> torch.Tensor: arguments = (hidden_states, mask, prior, timestep, speaker_hidden_states) field = self.estimator(*(argument.to(estimator_dtype) for argument in arguments)) return field.to(hidden_states.dtype) timestep, delta = t_span[0], t_span[1] - t_span[0] for step in range(1, len(t_span)): vector_field = estimate(mu) if guidance_scale > 0.0: average_field = estimate(mu.mean(2, keepdim=True).expand_as(mu)) vector_field = vector_field + guidance_scale * (vector_field - average_field) hidden_states = hidden_states + delta * vector_field timestep = timestep + delta if step < len(t_span) - 1: delta = t_span[step + 1] - timestep return hidden_states def compute_loss( self, target: torch.Tensor, mask: torch.Tensor, mu: torch.Tensor, speaker_hidden_states: torch.Tensor ) -> torch.Tensor: r""" Args: target (`torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`): Ground truth mel spectrogram. mask (`torch.Tensor` of shape `(batch_size, 1, mel_length)`): 1 on valid frames. mu (`torch.Tensor` of shape `(batch_size, num_mel_bins, mel_length)`): Prior mean aligned to the frames. speaker_hidden_states (`torch.Tensor` of shape `(batch_size, condition_size)`): Joint attribute style embedding. Returns: `torch.Tensor`: The conditional flow matching loss. """ conditioning = mu.new_zeros(mu.shape[0], 0, mu.shape[-1]) return super().compute_loss(target, mask, mu, speaker_hidden_states, conditioning) @dataclass class EmoSpherePPOutput(ModelOutput): r""" loss (`torch.FloatTensor` of shape `()`, *optional*): $\mathcal L_{dur}+\mathcal L_{enc}+\mathcal L_{cfm}+\lambda_{ort}\mathcal L_{ort}$, returned by `forward`. duration_loss (`torch.FloatTensor` of shape `()`, *optional*): Squared error between the predicted log durations and the log durations of the monotonic alignment, summed and divided by the number of tokens. prior_loss (`torch.FloatTensor` of shape `()`, *optional*): Negative log likelihood of the target frames under $\mathcal N(\mu, I)$, averaged over frames and channels. flow_matching_loss (`torch.FloatTensor` of shape `()`, *optional*): Conditional flow matching loss of the decoder. orthogonality_loss (`torch.FloatTensor` of shape `()`, *optional*): Normalized orthogonality loss $\sum_{i,j}\frac{(s_i^\top e_j)^2}{\lVert s_i\rVert^2\lVert e_j\rVert^2}$ between the speaker and emotion perceptron outputs of the batch, before its weight. audio_values (`torch.FloatTensor`, *optional*): Padded waveforms with int16 scaling and -20 LUFS normalization applied once. audio_lengths (`torch.LongTensor`, *optional*): Valid sample counts, excluding batch padding. sampling_rate (`int`, *optional*): Output audio sampling rate, 16000 Hz. spectrogram (`torch.FloatTensor` of shape `(batch_size, mel_length, num_mel_bins)`, *optional*): Generated log mel spectrogram, returned by `generate`. spectrogram_lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Number of valid frames of every generated spectrogram. prior_spectrogram (`torch.FloatTensor` of shape `(batch_size, mel_length, num_mel_bins)`, *optional*): Prior mean $\mu$ aligned to the frames. alignment (`torch.FloatTensor` of shape `(batch_size, text_length, mel_length)`, *optional*): Hard alignment between tokens and frames. """ loss: torch.FloatTensor | None = None duration_loss: torch.FloatTensor | None = None prior_loss: torch.FloatTensor | None = None flow_matching_loss: torch.FloatTensor | None = None orthogonality_loss: torch.FloatTensor | None = None audio_values: torch.FloatTensor | None = None audio_lengths: torch.LongTensor | None = None sampling_rate: int | None = None spectrogram: torch.FloatTensor | None = None spectrogram_lengths: torch.LongTensor | None = None prior_spectrogram: torch.FloatTensor | None = None alignment: torch.FloatTensor | None = None # Upstream parameter names (`models/tts/EmoSpherepp/model.py`) and the names of this implementation. The first rule # that matches a key renames it. _UPSTREAM_RENAMES = [ (r"^encoder\.emb\.", r"text_encoder.embed_tokens."), (r"^encoder\.prenet\.norm_layers\.(\d+)\.gamma$", r"text_encoder.prenet.norm_layers.\1.weight"), (r"^encoder\.prenet\.norm_layers\.(\d+)\.beta$", r"text_encoder.prenet.norm_layers.\1.bias"), (r"^encoder\.prenet\.", r"text_encoder.prenet."), (r"^encoder\.encoder\.attn_layers\.(\d+)\.conv_q\.", r"text_encoder.encoder.layers.\1.attention.q_proj."), (r"^encoder\.encoder\.attn_layers\.(\d+)\.conv_k\.", r"text_encoder.encoder.layers.\1.attention.k_proj."), (r"^encoder\.encoder\.attn_layers\.(\d+)\.conv_v\.", r"text_encoder.encoder.layers.\1.attention.v_proj."), (r"^encoder\.encoder\.attn_layers\.(\d+)\.conv_o\.", r"text_encoder.encoder.layers.\1.attention.out_proj."), (r"^encoder\.encoder\.attn_layers\.(\d+)\.emb_rel_(k|v)$", r"text_encoder.encoder.layers.\1.attention.emb_rel_\2"), (r"^encoder\.encoder\.norm_layers_1\.(\d+)\.gamma$", r"text_encoder.encoder.layers.\1.layer_norm.weight"), (r"^encoder\.encoder\.norm_layers_1\.(\d+)\.beta$", r"text_encoder.encoder.layers.\1.layer_norm.bias"), (r"^encoder\.encoder\.norm_layers_2\.(\d+)\.gamma$", r"text_encoder.encoder.layers.\1.final_layer_norm.weight"), (r"^encoder\.encoder\.norm_layers_2\.(\d+)\.beta$", r"text_encoder.encoder.layers.\1.final_layer_norm.bias"), (r"^encoder\.encoder\.ffn_layers\.(\d+)\.", r"text_encoder.encoder.layers.\1.feed_forward."), (r"^encoder\.proj_m\.", r"text_encoder.mean_proj."), (r"^encoder\.proj_w\.norm_(\d)\.gamma$", r"text_encoder.duration_predictor.norm_\1.weight"), (r"^encoder\.proj_w\.norm_(\d)\.beta$", r"text_encoder.duration_predictor.norm_\1.bias"), (r"^encoder\.proj_w\.", r"text_encoder.duration_predictor."), (r"^decoder\.", r"decoder."), (r"^spk_mlp\.", r"style_encoder.speaker_mlp."), (r"^emo_mlp\.", r"style_encoder.emotion_mlp."), (r"^emo_VAD_inten_proj\.", r"style_encoder.intensity_proj."), (r"^emosty_layer_norm\.", r"style_encoder.emotion_layer_norm."), (r"^sty_proj\.", r"style_encoder.style_proj."), (r"^elevation_emb\.", r"style_encoder.elevation_embedding."), (r"^azimuth_emb\.", r"style_encoder.azimuth_embedding."), ] # Projections upstream builds and never calls (`models/tts/EmoSpherepp/model.py:94` and `:95`). _UPSTREAM_UNUSED_PREFIXES = ("spk_embed_proj.", "emo_proj.") _UPSTREAM_BINS = {"elevation_bins": _ELEVATION_BOUNDARIES, "azimuth_bins": _AZIMUTH_BOUNDARIES} _ATTENTION_PROJECTION = re.compile(r"\.attention\.(q|k|v|out)_proj\.weight$") def convert_emosphere_pp_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: r""" Renames the parameters of an upstream `EmoSpherepp` module to the names of [`EmoSpherePPForConditionalGeneration`]. The 1x1 convolutions of the upstream attention become the weights of linear projections, the channel layer norms rename `gamma` and `beta` to `weight` and `bias`, the two projections upstream never calls are dropped, and the fixed bin boundaries are checked and dropped. Args: state_dict (`dict[str, torch.Tensor]`): The `state_dict["model"]` entry of an upstream checkpoint. Returns: `dict[str, torch.Tensor]`: The renamed parameters. Keys no rule matches are kept as they are, so that loading reports them. Raises: `ValueError`: If the bin boundaries of the checkpoint are not those of upstream. """ converted = {} for key, value in state_dict.items(): if key.startswith(_UPSTREAM_UNUSED_PREFIXES): continue if key in _UPSTREAM_BINS: if not torch.allclose(value.float(), torch.linspace(*_UPSTREAM_BINS[key])): raise ValueError(f"`{key}` of the checkpoint is {value.tolist()}, not the upstream boundaries.") continue new_key = key for pattern, replacement in _UPSTREAM_RENAMES: if re.search(pattern, key): new_key = re.sub(pattern, replacement, key) break if _ATTENTION_PROJECTION.search(new_key) and value.dim() == 3: value = value.squeeze(-1) converted[new_key] = value return converted class EmoSpherePPPreTrainedModel(PreTrainedModel): r""" An abstract class to handle weights initialization and the loading of upstream checkpoints. Every module is initialized as upstream initializes it: PyTorch defaults, Xavier uniform query, key and value projections and $\mathcal N(0, d^{-1/2})$ relative embeddings in the text encoder, a zero pre-net projection, phoneme embeddings from $\mathcal N(0, d^{-1/2})$, and Kaiming normal convolutions and linear layers in the estimator. """ config: EmoSpherePPConfig base_model_prefix = "emosphere_pp" main_input_name = "input_ids" supports_gradient_checkpointing = False # Durations are rounded up from the text encoder output, so it and the style encoder stay FP32 when the # checkpoint dtype is FP16 or BF16; only the flow matching estimator takes that dtype. _keep_in_fp32_modules_strict = ["style_encoder", "text_encoder"] @staticmethod def _default_init(module: nn.Module) -> None: init.kaiming_uniform_(module.weight, a=math.sqrt(5)) if module.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight) bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 init.uniform_(module.bias, -bound, bound) @torch.no_grad() def _init_weights(self, module: nn.Module) -> None: if isinstance(module, (nn.Linear, nn.Conv1d, nn.ConvTranspose1d)): self._default_init(module) elif isinstance(module, nn.Embedding): init.normal_(module.weight) elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)): init.ones_(module.weight) init.zeros_(module.bias) elif isinstance(module, Qwen2_5OmniSnakeBeta): init.zeros_(module.alpha) init.zeros_(module.beta) elif isinstance(module, VitsAttention): for projection in (module.q_proj, module.k_proj, module.v_proj): init.xavier_uniform_(projection.weight) init.normal_(module.emb_rel_k, std=module.head_dim**-0.5) init.normal_(module.emb_rel_v, std=module.head_dim**-0.5) elif isinstance(module, EmoSpherePPConvReluNorm): init.zeros_(module.proj.weight) init.zeros_(module.proj.bias) elif isinstance(module, EmoSpherePPTextEncoder): init.normal_(module.embed_tokens.weight, std=module.hidden_size**-0.5) elif isinstance(module, EmoSpherePPStyleEncoder): init.copy_(module.elevation_bins, torch.linspace(*_ELEVATION_BOUNDARIES)) init.copy_(module.azimuth_bins, torch.linspace(*_AZIMUTH_BOUNDARIES)) elif isinstance(module, EmoSpherePPDecoder): for submodule in module.modules(): if isinstance(submodule, (nn.Conv1d, nn.Linear)): init.kaiming_normal_(submodule.weight, nonlinearity="relu") if submodule.bias is not None: init.zeros_(submodule.bias) elif isinstance(submodule, nn.GroupNorm): init.ones_(submodule.weight) init.zeros_(submodule.bias) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Args: pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*): Repository id or local directory of a saved model, or an upstream checkpoint file (`model_ckpt_steps_<step>.ckpt`), whose parameters are renamed by [`convert_emosphere_pp_state_dict`]. model_args: Forwarded to [`~PreTrainedModel.from_pretrained`]. kwargs: Forwarded to [`~PreTrainedModel.from_pretrained`]. Without a `config`, an upstream checkpoint is read with the default configuration and the vocabulary size of its phoneme embedding. Returns: [`EmoSpherePPPreTrainedModel`]: The loaded model. """ if pretrained_model_name_or_path is not None: path = Path(pretrained_model_name_or_path) if path.is_file() and path.suffix == ".ckpt": checkpoint = torch.load(path, map_location="cpu", weights_only=True) state_dict = convert_emosphere_pp_state_dict(checkpoint["state_dict"]["model"]) config = kwargs.pop("config", None) if config is None: vocab_size = state_dict["text_encoder.embed_tokens.weight"].shape[0] config = EmoSpherePPConfig(vocab_size=vocab_size) return super().from_pretrained(None, *model_args, config=config, state_dict=state_dict, **kwargs) return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) class EmoSpherePPForConditionalGeneration(EmoSpherePPPreTrainedModel): r""" EmoSphere++, an emotion controllable zero shot text to speech model (`EmoSpherepp` in `models/tts/EmoSpherepp/model.py:28`). A joint attribute style embedding is built from a speaker x-vector, an emotion2vec embedding and the emotion-adaptive spherical vector. The Glow-TTS text encoder predicts a prior mean and durations conditioned on it, and the Matcha-TTS flow matching decoder turns the aligned prior into a log mel spectrogram, also conditioned on it. `forward` returns the upstream training objective. `generate` renders 16 kHz audio through a frozen BigVGAN sub-model loaded on first use. `output_audio=False` returns only the spectrogram. Args: config ([`EmoSpherePPConfig`]): Model configuration. """ def __init__(self, config: EmoSpherePPConfig): super().__init__(config) self.style_encoder = EmoSpherePPStyleEncoder(config) self.text_encoder = EmoSpherePPTextEncoder(config) self.decoder = EmoSpherePPConditionalCFM(config) self.post_init() @staticmethod def orthogonality_loss(speaker_hidden: torch.Tensor, emotion_hidden: torch.Tensor) -> torch.Tensor: r""" Normalized orthogonality loss of EmoSphere++ (`tasks/tts/EmoSpherepp.py:160`), without its weight. Args: speaker_hidden (`torch.Tensor` of shape `(batch_size, style_embedding_size)`): Outputs of the speaker perceptron. emotion_hidden (`torch.Tensor` of shape `(batch_size, style_embedding_size)`): Outputs of the emotion perceptron. Returns: `torch.Tensor`: $\lVert C\rVert_F^2$ with $C_{ij}=\frac{e_i^\top s_j}{\lVert e_i\rVert\lVert s_j\rVert}$. """ products = torch.matmul(emotion_hidden, speaker_hidden.t()) norms = torch.norm(emotion_hidden, dim=1, keepdim=True) * torch.norm(speaker_hidden, dim=1, keepdim=True).t() return torch.norm(products / norms, p="fro") ** 2 @staticmethod def _log_prior(mean: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """Log likelihood of every frame under every token, `models/tts/EmoSpherepp/model.py:270` to `:275`.""" constant = -0.5 * math.log(2 * math.pi) * target.shape[1] factor = -0.5 * torch.ones(mean.shape, dtype=mean.dtype, device=mean.device) target_square = torch.matmul(factor.transpose(1, 2), target**2) target_mean = torch.matmul(2.0 * (factor * mean).transpose(1, 2), target) mean_square = torch.sum(factor * (mean**2), 1).unsqueeze(-1) return target_square - target_mean + mean_square + constant def _segment( self, target: torch.Tensor, alignment: torch.Tensor, target_lengths: torch.Tensor, segment_size: int ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Random segment of `segment_size` frames per utterance, `models/tts/EmoSpherepp/model.py:286` to `:320`.""" max_offset = (target_lengths - segment_size).clamp(0).tolist() offsets = [random.choice(range(0, end)) if end > 0 else 0 for end in max_offset] target_segment = target.new_zeros(target.shape[0], target.shape[1], segment_size) alignment_segment = alignment.new_zeros(alignment.shape[0], alignment.shape[1], segment_size) segment_lengths = (target_lengths.clamp(max=segment_size)).tolist() for index, (offset, length) in enumerate(zip(offsets, segment_lengths)): target_segment[index, :, :length] = target[index, :, offset : offset + length] alignment_segment[index, :, :length] = alignment[index, :, offset : offset + length] lengths = torch.tensor(segment_lengths, device=target_lengths.device) return target_segment, alignment_segment, lengths def forward( self, input_ids: torch.Tensor, input_lengths: torch.Tensor, speaker_embeddings: torch.Tensor, emotion_embeddings: torch.Tensor, emotion_intensity: torch.Tensor, emotion_style: torch.Tensor, labels: torch.Tensor | None = None, label_lengths: torch.Tensor | None = None, **kwargs, ) -> EmoSpherePPOutput: r""" Training objective of EmoSphere++ (`EmoSpherepp.compute_loss` in `models/tts/EmoSpherepp/model.py:209` and `EmoSpherepp.forward` in `tasks/tts/EmoSpherepp.py:11`). The monotonic alignment search aligns the target frames with the prior, the duration loss fits the log durations to that alignment, and the decoder and the prior loss see one random segment of `config.segment_size` frames per utterance: $$ \mathcal L=\mathcal L_{dur}+\mathcal L_{enc}+\mathcal L_{cfm}+\lambda_{ort}\mathcal L_{ort}. $$ Every parameter of the model is trained. The WavLM and emotion2vec encoders that produce `speaker_embeddings` and `emotion_embeddings` are frozen and run outside the model. Args: input_ids (`torch.Tensor` of shape `(batch_size, text_length)`): Phoneme ids with the blank id between every two phonemes. input_lengths (`torch.Tensor` of shape `(batch_size,)`): Number of valid ids per sequence. speaker_embeddings (`torch.Tensor` of shape `(batch_size, speaker_embedding_size)`): x-vector of `microsoft/wavlm-base-sv` for the reference utterance. emotion_embeddings (`torch.Tensor` of shape `(batch_size, emotion_embedding_size)`): Utterance embedding of `emotion2vec_plus_base` for the reference utterance. emotion_intensity (`torch.Tensor` of shape `(batch_size, 1)`): Radius $r_{IQR}$ of the emotion-adaptive spherical vector. emotion_style (`torch.Tensor` of shape `(batch_size, 2)`): Elevation and azimuth of the emotion-adaptive spherical vector. labels (`torch.Tensor` of shape `(batch_size, mel_length, num_mel_bins)`): Target log mel spectrogram. label_lengths (`torch.Tensor` of shape `(batch_size,)`): Number of valid frames per target. Returns: [`EmoSpherePPOutput`]: The loss and its four terms. Raises: `ValueError`: If `labels` or `label_lengths` is missing. """ if labels is None or label_lengths is None: raise ValueError("`forward` needs `labels` and `label_lengths`. Use `generate` to synthesize.") style, speaker_hidden, emotion_hidden = self.style_encoder( speaker_embeddings, emotion_embeddings, emotion_intensity, emotion_style ) mean, log_durations, text_mask = self.text_encoder(input_ids, input_lengths, style) target = labels.transpose(1, 2) target_mask = sequence_mask(label_lengths, target.shape[-1]).unsqueeze(1).to(text_mask) pair_mask = text_mask.unsqueeze(-1) * target_mask.unsqueeze(2) with torch.no_grad(): alignment = maximum_path(self._log_prior(mean, target), pair_mask.squeeze(1)).detach() target_log_durations = torch.log(1e-8 + torch.sum(alignment.unsqueeze(1), -1)) * text_mask duration_loss = torch.sum((log_durations - target_log_durations) ** 2) / torch.sum(input_lengths) if self.config.segment_size is not None: target, alignment, segment_lengths = self._segment( target, alignment, label_lengths, self.config.segment_size ) target_mask = sequence_mask(segment_lengths, self.config.segment_size).unsqueeze(1).to(target_mask) aligned_mean = torch.matmul(alignment.transpose(1, 2), mean.transpose(1, 2)).transpose(1, 2) flow_matching_loss = self.decoder.compute_loss(target, target_mask, aligned_mean, style) prior_loss = torch.sum(0.5 * ((target - aligned_mean) ** 2 + math.log(2 * math.pi)) * target_mask) prior_loss = prior_loss / (torch.sum(target_mask) * self.config.num_mel_bins) orthogonality_loss = self.orthogonality_loss(speaker_hidden, emotion_hidden) loss = ( duration_loss + prior_loss + flow_matching_loss + self.config.orthogonality_loss_weight * orthogonality_loss ) return EmoSpherePPOutput( loss=loss, duration_loss=duration_loss, prior_loss=prior_loss, flow_matching_loss=flow_matching_loss, orthogonality_loss=orthogonality_loss, ) @torch.no_grad() def generate( self, input_ids: torch.Tensor, input_lengths: torch.Tensor, speaker_embeddings: torch.Tensor, emotion_embeddings: torch.Tensor, emotion_intensity: torch.Tensor, emotion_style: torch.Tensor, num_steps: int = 100, temperature: float = 1.0, length_scale: float = 1.0, guidance_scale: float = 0.0, output_audio: bool = True, ) -> EmoSpherePPOutput: r""" Synthesizes a log mel spectrogram (`EmoSpherepp.forward` in `models/tts/EmoSpherepp/model.py:110`). The predicted durations are rounded up and scaled, the prior is expanded along them, and the decoder integrates the flow from noise. The defaults are those of upstream inference (`tasks/tts/EmoSpherepp.py:89`). Args: input_ids (`torch.Tensor` of shape `(batch_size, text_length)`): Phoneme ids with the blank id between every two phonemes. input_lengths (`torch.Tensor` of shape `(batch_size,)`): Number of valid ids per sequence. speaker_embeddings (`torch.Tensor` of shape `(batch_size, speaker_embedding_size)`): x-vector of `microsoft/wavlm-base-sv` for the reference utterance. emotion_embeddings (`torch.Tensor` of shape `(batch_size, emotion_embedding_size)`): Utterance embedding of `emotion2vec_plus_base` for the reference utterance. emotion_intensity (`torch.Tensor` of shape `(batch_size, 1)`): Radius $r_{IQR}$ of the emotion-adaptive spherical vector. emotion_style (`torch.Tensor` of shape `(batch_size, 2)`): Elevation and azimuth of the emotion-adaptive spherical vector. num_steps (`int`, *optional*, defaults to 100): Number of Euler steps. temperature (`float`, *optional*, defaults to 1.0): Scale of the initial noise. length_scale (`float`, *optional*, defaults to 1.0): Factor on the rounded durations. Larger is slower. guidance_scale (`float`, *optional*, defaults to 0.0): Guidance $\gamma$ away from the time averaged prior. output_audio (`bool`, *optional*, defaults to `True`): Render postprocessed 16 kHz audio using the lazily loaded vocoder. Returns: [`EmoSpherePPOutput`]: The spectrogram, its lengths, the aligned prior and the alignment. """ core_dtype = next(self.parameters()).dtype with torch.autocast(input_ids.device.type, dtype=torch.bfloat16, enabled=core_dtype == torch.bfloat16): style, _, _ = self.style_encoder(speaker_embeddings, emotion_embeddings, emotion_intensity, emotion_style) mean, log_durations, text_mask = self.text_encoder(input_ids, input_lengths, style) durations = torch.ceil(torch.exp(log_durations) * text_mask) * length_scale spectrogram_lengths = torch.clamp_min(torch.sum(durations, [1, 2]), 1).long() max_length = int(spectrogram_lengths.max()) padded_length = fix_length_compatibility(max_length) frame_mask = sequence_mask(spectrogram_lengths, padded_length).unsqueeze(1).to(text_mask.dtype) pair_mask = text_mask.unsqueeze(-1) * frame_mask.unsqueeze(2) alignment = generate_path(durations.squeeze(1), pair_mask.squeeze(1)) aligned_mean = torch.matmul(alignment.transpose(1, 2), mean.transpose(1, 2)).transpose(1, 2) spectrogram = self.decoder(aligned_mean, frame_mask, num_steps, style, temperature, guidance_scale) output = EmoSpherePPOutput( spectrogram=spectrogram[:, :, :max_length].transpose(1, 2), spectrogram_lengths=spectrogram_lengths, prior_spectrogram=aligned_mean[:, :, :max_length].transpose(1, 2), alignment=alignment[:, :, :max_length], ) if output_audio: from transformers import AutoModel from .processing_emosphere_pp import EmoSpherePPProcessor if getattr(self, "vocoder", None) is None: self.vocoder = AutoModel.from_pretrained( self.config.vocoder_repo_id, revision=self.config.vocoder_revision, trust_remote_code=True, dtype=getattr(torch, self.config.vocoder_dtype), ).requires_grad_(False) vocoder_dtype = getattr(torch, self.config.vocoder_dtype) self.vocoder.to(device=spectrogram.device, dtype=vocoder_dtype).eval() waveforms = [] for mel, length in zip(output.spectrogram, output.spectrogram_lengths): features = mel[:int(length)].T.unsqueeze(0).to(vocoder_dtype) with torch.autocast(spectrogram.device.type, dtype=torch.bfloat16, enabled=vocoder_dtype == torch.bfloat16): waveform = self.vocoder(input_features=features).audio_values[0] waveform = EmoSpherePPProcessor.postprocess(waveform.float().cpu().numpy()) waveforms.append(torch.from_numpy(waveform).to(spectrogram.device)) output.audio_lengths = torch.tensor([wave.numel() for wave in waveforms], device=spectrogram.device) output.audio_values = nn.utils.rnn.pad_sequence(waveforms, batch_first=True) output.sampling_rate = self.config.sampling_rate return output
# Copyright 2026 The EmoSphere++ Authors, The Matcha-TTS Authors, The Glow-TTS Authors, Huawei Technologies Co., Ltd.,
# TICTAP-11 and b-re-w. All rights reserved.
#
# Licensed under the MIT License. You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""PyTorch EmoSphere++ model."""
import math
import random
import re
from dataclasses import dataclass
from pathlib import Path
import torch
import torch.nn.functional as F
from torch import nn
from transformers import initialization as init
from transformers.modeling_outputs import ModelOutput
from transformers.modeling_utils import PreTrainedModel
from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import Qwen2_5OmniSnakeBeta
from transformers.models.vits.modeling_vits import VitsAttention, VitsDurationPredictor, VitsEncoder
from voicestudio.models.cosyvoice_v1.modeling_cosyvoice_v1 import CosyVoiceV1ConditionalCFM, CosyVoiceV1ConditionalDecoder, CosyVoiceV1EstimatorFeedForward
from .configuration_emosphere_pp import EmoSpherePPConfig
__all__ = [
"EMOSPHERE_PP_VAD_CENTERS",
"EmoSpherePPConditionalCFM",
"EmoSpherePPConvReluNorm",
"EmoSpherePPDecoder",
"EmoSpherePPForConditionalGeneration",
"EmoSpherePPOutput",
"EmoSpherePPPreTrainedModel",
"EmoSpherePPSnakeBeta",
"EmoSpherePPStyleEncoder",
"EmoSpherePPTextEncoder",
"convert_emosphere_pp_state_dict",
"emotion_adaptive_spherical_vector",
"fix_length_compatibility",
"generate_path",
"maximum_path",
"sequence_mask",
]
# Centers $M_k$ of the emotion-adaptive coordinate systems that upstream fixes for ESD
# (`data_gen/tts/base_binarizer.py:236`), in the output order of `audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim`:
# arousal, dominance, valence.
EMOSPHERE_PP_VAD_CENTERS = {
"neutral": (0.4135, 0.5169, 0.3620),
"angry": (0.37068613, 0.4814421, 0.37709341),
"happy": (0.36792182, 0.48303542, 0.34562907),
"sad": (0.48519272, 0.57727589, 0.39524114),
"surprise": (0.36877737, 0.48431942, 0.36644742),
}
# Bin boundaries of the elevation and azimuth embeddings (`models/tts/EmoSpherepp/model.py:89` to `:91`).
_ELEVATION_BOUNDARIES = (math.pi / 2, math.pi, 2)
_AZIMUTH_BOUNDARIES = (-math.pi / 2, math.pi, 4)
def sequence_mask(lengths: torch.Tensor, max_length: int | None = None) -> torch.Tensor:
r"""
Args:
lengths (`torch.Tensor` of shape `(batch_size,)`):
Valid length of every sequence.
max_length (`int`, *optional*):
Length of the mask. Defaults to the largest of `lengths`.
Returns:
`torch.Tensor` of shape `(batch_size, max_length)`: `True` on the valid positions.
"""
if max_length is None:
max_length = int(lengths.max())
positions = torch.arange(int(max_length), dtype=lengths.dtype, device=lengths.device)
return positions.unsqueeze(0) < lengths.unsqueeze(1)
def fix_length_compatibility(length: int, num_downsamplings: int = 2) -> int:
r"""
Args:
length (`int`):
Number of mel frames.
num_downsamplings (`int`, *optional*, defaults to 2):
Number of halvings the length has to survive. Upstream keeps the Matcha-TTS default of 2 although its