Text-to-Speech
Transformers
ONNX
Safetensors
lingv3_tts
feature-extraction
audio
voice-cloning
multilingual
mixture-of-experts
speech-generation
custom_code
Run this model with HF Jobs
Run ml-resources/Ming-3.0-tts-tiny on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ml-resources/Ming-3.0-tts-tiny. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ml-resources/Ming-3.0-tts-tiny on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ml-resources/Ming-3.0-tts-tiny with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ml-resources/Ming-3.0-tts-tiny with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-to-speech", model="ml-resources/Ming-3.0-tts-tiny", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("ml-resources/Ming-3.0-tts-tiny", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Mirror inclusionAI/Ming-3.0-tts-tiny
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+3
- CFM.pyAdded+263
- README.mdAdded+334
- __init__.pyAdded+19
- aggregator.pyAdded+93
- campplus.onnxAdded+3
- chat_template.jinjaAdded+126
- config.jsonAdded+228
- configuration_audio_vae.pyAdded+35
- configuration_bailing_moe_v3.pyAdded+126
- configuration_lingv3_tts.pyAdded+159
- conversion_manifest.jsonAdded+283
- dit.pyAdded+193
- figures/ant-bailing.pngAdded
- figures/icons/github-color.svgAdded
- figures/icons/modelscope-color.svgAdded
- figures/icons/technical-report.svgAdded
- figures/ming-3.0-tts-tiny-architecture.pngAdded
- figures/ming_3.0_tts.pngAdded
- flowloss.pyAdded+74
- fm_utils.pyAdded+11
- generation_config.jsonAdded+6
- istft.pyAdded+181
- mlp.pyAdded+355
- model-00001-of-00030.safetensorsAdded+3
- model-00002-of-00030.safetensorsAdded+3
- model-00003-of-00030.safetensorsAdded+3
- model-00004-of-00030.safetensorsAdded+3
- model-00005-of-00030.safetensorsAdded+3
- model-00006-of-00030.safetensorsAdded+3
- model-00007-of-00030.safetensorsAdded+3
- model-00008-of-00030.safetensorsAdded+3
- model-00009-of-00030.safetensorsAdded+3
- model-00010-of-00030.safetensorsAdded+3
- model-00011-of-00030.safetensorsAdded+3
- model-00012-of-00030.safetensorsAdded+3
- model-00013-of-00030.safetensorsAdded+3
- model-00014-of-00030.safetensorsAdded+3
- model-00015-of-00030.safetensorsAdded+3
- model-00016-of-00030.safetensorsAdded+3
- model-00017-of-00030.safetensorsAdded+3
- model-00018-of-00030.safetensorsAdded+3
- model-00019-of-00030.safetensorsAdded+3
- model-00020-of-00030.safetensorsAdded+3
- model-00021-of-00030.safetensorsAdded+3
- model-00022-of-00030.safetensorsAdded+3
- model-00023-of-00030.safetensorsAdded+3
- model-00024-of-00030.safetensorsAdded+3
- model-00025-of-00030.safetensorsAdded+3
- model-00026-of-00030.safetensorsAdded+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373832 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -textfigures/ming_3.0_tts.png filter=lfs diff=lfs merge=lfs -textfigures/ming-3.0-tts-tiny-architecture.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263"""ein notation:b - batchn - sequencent - text sequencenw - raw wave lengthd - dimension"""
from __future__ import annotations
import torchimport torch.nn.functional as Ffrom torch import nn
class Solver: def __init__( self, func, y0, sigma=0.25, temperature=1.5, generator=None, ) -> None: self.func = func self.y0 = y0 self.sigma = sigma self.temperature = temperature self.generator = generator
def integrate(self, t): solution = torch.empty(len(t), *self.y0.shape, dtype=self.y0.dtype, device=self.y0.device) solution[0] = self.y0
j = 1 y0 = self.y0 for t0, t1 in zip(t[:-1], t[1:]): dt = t1 - t0 f0 = self.func(t0, y0) dy = dt * f0 y1 = y0 + dy
while j < len(t) and t1 >= t[j]: solution[j] = self._linear_interp(t0, t1, y0, y1, t[j]) j += 1
noise = torch.randn( y0.shape, device=y0.device, dtype=y0.dtype, generator=self.generator, ) shift = self.sigma * (self.temperature ** 0.5) * (abs(dt) ** 0.5) * noise y0 = y1 + shift
return solution
def _linear_interp(self, t0, t1, y0, y1, t): if t == t0: return y0 if t == t1: return y1 slope = (t - t0) / (t1 - t0) return y0 + slope * (y1 - y0)
def get_epss_timesteps(n, device, dtype): dt = 1 / 32 predefined_timesteps = { 5: [0, 2, 4, 8, 16, 32], 6: [0, 2, 4, 6, 8, 16, 32], 7: [0, 2, 4, 6, 8, 16, 24, 32], 10: [0, 2, 4, 6, 8, 12, 16, 20, 24, 28, 32], 12: [0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32], 16: [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32], } t = predefined_timesteps.get(n, []) if not t: return torch.linspace(0, 1, n + 1, device=device, dtype=dtype) return dt * torch.tensor(t, device=device, dtype=dtype)
class CFM(nn.Module): def __init__( self, model: nn.Module, sigma=0.0, odeint_kwargs: dict = dict( # atol = 1e-5, # rtol = 1e-5, method="euler" # 'midpoint' ), audio_drop_prob=0.3, cond_drop_prob=0.2, ): super().__init__()
# classifier-free guidance self.audio_drop_prob = audio_drop_prob self.cond_drop_prob = cond_drop_prob
# transformer self.model = model
# conditional flow related self.sigma = sigma
# sampling related self.odeint_kwargs = odeint_kwargs
@property def device(self): return next(self.parameters()).device
@torch.no_grad() def sample( self, noise, c, latent_history, steps=10, cfg_scale=1.0, sway_sampling_coef=-1.0, seed: int | None = None, use_epss=True, patch_size=1, sigma=0.25, temperature=0.0, generator=None, ): # raw wave
def fn(t, x): # at each step, conditioning is fixed # step_cond = torch.where(cond_mask, cond, torch.zeros_like(cond))
# The custom Euler solver supplies a scalar timestep. The # batched CFG path expands it inside DiT.forward_with_cfg(), but # the direct conditional/unconditional paths call DiT.forward() # and therefore must expand it here. direct_t = t if direct_t.ndim == 0: direct_t = direct_t.repeat(x.shape[0]) if direct_t.ndim != 1 or direct_t.shape[0] != x.shape[0]: raise ValueError( "CFM timestep must be scalar or have one value per " f"sample, got {tuple(direct_t.shape)} for batch " f"{x.shape[0]}" )
# Pure unconditional branch. if cfg_scale < 1e-5: pred = self.model( x=x, t=direct_t, c=torch.zeros_like(c), latent_history=latent_history, ) return pred[:, -patch_size:, :]
# At exactly 1.0 no second DiT pass is necessary. if cfg_scale == 1.0: pred = self.model( x=x, t=direct_t, c=c, latent_history=latent_history, ) return pred[:, -patch_size:, :]
# predict flow (cond and uncond), for classifier-free guidance pred_cfg = self.model.forward_with_cfg( x=x, t=t, c=c, latent_history=latent_history, cfg_scale=cfg_scale, patch_size=patch_size,
) pred, null_pred = torch.chunk(pred_cfg, 2, dim=0) return pred + (pred - null_pred) * cfg_scale
y0 = noise.transpose(1, 2)
t_start = 0
if t_start == 0 and use_epss: # use Empirically Pruned Step Sampling for low NFE t = get_epss_timesteps(steps, device=self.device, dtype=noise.dtype) else: t = torch.linspace(t_start, 1, steps + 1, device=self.device, dtype=noise.dtype) if sway_sampling_coef is not None: t = t + sway_sampling_coef * (torch.cos(torch.pi / 2 * t) - 1 + t)
solver = Solver( fn, y0, sigma=sigma, temperature=temperature, generator=generator, ) trajectory = solver.integrate(t) # trajectory = odeint(fn, y0, t, **self.odeint_kwargs) sampled = trajectory[-1] out = sampled
return out, trajectory
def forward( self, cond, target, latent_history, mask, patch_size, ):
# mel is x1 x1 = target
batch, dtype = x1.shape[0], x1.dtype
# x0 is gaussian noise x0 = torch.randn_like(x1)
# time step time = torch.rand((batch,), dtype=dtype, device=self.device) # time = compute_density_for_timestep_sampling( # weighting_scheme="logit_normal", # batch_size=batch, # logit_mean=0, # logit_std=1, # mode_scale=None, # ).to(dtype=dtype, device=self.device) # TODO. noise_scheduler
# sample xt (φ_t(x) in the paper) t = time.unsqueeze(-1).unsqueeze(-1) # only for sample x = (1 - t) * x0 + t * x1 flow = x1 - x0
pred = self.model(x=x, t=time, c=cond, latent_history=latent_history, mask=mask.to(torch.bool)) pred = pred[:, -patch_size:, :]
loss = F.mse_loss(pred, flow, reduction="none") #[batch, seq_len ,Channel] mask = (mask == 1) loss = loss[mask] #rand_span_mask , [batch, seq_len]
if loss.numel() == 0: import logging logging.warning(f"[CFM] WARNING: loss mask is empty! mask shape={mask.shape}, mask sum={mask.sum().item()}. Returning zero loss.") return torch.tensor(0.0, dtype=dtype, device=x1.device, requires_grad=True)
return loss.mean()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334---license: mitlanguage:- zh- en- de- es- fr- ko- japipeline_tag: text-to-speechlibrary_name: transformerstags:- audio- text-to-speech- voice-cloning- multilingual- mixture-of-experts- speech-generation---> Mirror of [inclusionAI/Ming-3.0-tts-tiny](https://huggingface.co/inclusionAI/Ming-3.0-tts-tiny). All credit to the original authors. Not an official release from them. License unchanged (mit).
<div align="center"> <img src="./figures/ant-bailing.png" width="60" alt="Ming-3.0-tts Logo" /> <h1>Ming-3.0-tts-tiny</h1> <p><i>7.9B-A1.3B multilingual MoE speech synthesis with paralinguistic and free-form control.</i></p></div>
<p align="center"> <span style="white-space: nowrap;"><img src="./figures/icons/github-color.svg" width="18" height="18" alt="" style="display: inline-block; vertical-align: middle; margin: 0;" /> <a href="https://github.com/inclusionAI/Ming-3.0-tts">GitHub</a></span> | <span style="white-space: nowrap;"><img src="./figures/icons/technical-report.svg" width="18" height="18" alt="" style="display: inline-block; vertical-align: middle; margin: 0;" /> <a href="https://nomorecoding.github.io/Ming-3.0-tts/">Blog & Demos</a></span> | <span style="white-space: nowrap;"><img src="./figures/icons/modelscope-color.svg" width="18" height="18" alt="" style="display: inline-block; vertical-align: middle; margin: 0;" /> <a href="https://modelscope.cn/models/inclusionAI/Ming-3.0-tts-tiny">ModelScope</a></span></p>
This repository contains **Ming-3.0-tts-tiny**, the Ming-3.0-tts mixture-of-experts checkpoint built on Ling V3. Its Ling V3 backbone has 7.9B total parameters and activates about 1.3B parameters per token. The repository includes sharded weights, supporting model code, audio tokenizer, speaker encoder and text tokenizer.
> **Inference requires the [Ming-3.0-tts GitHub repository](https://github.com/inclusionAI/Ming-3.0-tts).** This Hugging Face repository is for checkpoint distribution and does not provide a standalone inference setup. Clone the GitHub repository and follow its README for the current dependencies, inference code and usage instructions. The CLI scripts and Python APIs referenced below are provided by the GitHub repository.
## Model Details
| Item | Value || --- | --- || Architecture | Mixture of Experts, Ling V3 backbone || Backbone parameters | 7.9B total, about 1.3B active per token || Languages | Chinese, English, German, Spanish, French, Korean, Japanese || Dialects | Sichuanese, Cantonese || Python API | `ming_tiny.MingTinyTTS` || CLI | `infer_tiny.py` || Prompt protocol | `thinking_v1` |
## Capabilities
- Zero-shot voice cloning from a short reference clip- Voice Design from a natural-language speaker description- Free-form control of delivery and speaking style- 100+ built-in Chinese voices and five built-in English voices- Multilingual synthesis and Sichuanese/Cantonese dialect control- 14 inline tags for breath, cough, sigh, laughter, hesitation, surprise and question/confirmation sounds in Chinese or English- Explicit emotion, speed, pitch and volume control- Multi-speaker dialogue from a script and speaker references (`podcast`)
<p align="center"> <img src="./figures/ming-3.0-tts-tiny-architecture.png" width="900" alt="Ming-3.0-tts-tiny architecture" /></p>
## Quick Start
### Installation
```bashgit clone https://github.com/inclusionAI/Ming-3.0-tts.gitcd Ming-3.0-ttsconda create -n ming-tiny python=3.10.15 -yconda activate ming-tinypip install -r requirements-tiny.txt```
Tiny uses a separate reference inference environment: Python **3.10.15**, PyTorch and torchaudio **2.7.1+cu118** (CUDA 11.8 wheels), and `transformers==4.46.3`. Install the pinned dependencies from [requirements-tiny.txt](https://github.com/inclusionAI/Ming-3.0-tts/blob/main/requirements-tiny.txt) in a dedicated environment, as other dependency versions differ from 0.5B. We recommend using NVIDIA H800 for inference.
### Download
```bashpip install "huggingface_hub[cli]"hf download inclusionAI/Ming-3.0-tts-tiny --local-dir Ming-3.0-tts-tiny```
### CLI Inference
```bashpython infer_tiny.py \ --model_path inclusionAI/Ming-3.0-tts-tiny \ --task dialect \ --text "今日天气几好,我哋食完饭一齐去海边行下啦。" \ --dialect 广粤话 \ --prompt_wav data/wavs/10002287-00000094.wav \ --output_path output/tiny.wav```
### Python API
Loading configures the release runtime (bf16, portable MoE loop, fp32 recurrent state) and checks the checkpoint against it; `generate()` defaults to `cfg_scale=2.0`, `temperature=0`, `flow_steps=10`, and `sigma=0.25`.
```pythonfrom ming_tiny import MingTinyTTS
tts = MingTinyTTS.from_pretrained("inclusionAI/Ming-3.0-tts-tiny", device="cuda:0")tts.generate( task="seed", text="傍晚的风从山口吹过来,远处的云慢慢染成了金色。", prompt_wav="data/wavs/10002287-00000094.wav", prompt_text="在此奉劝大家别乱打美白针。", target_language="Chinese", # English for English text output_path="outputs/seed.wav",)```
### Supported Tasks
Each call selects one task and accepts the inputs listed below:
| Task | Reference audio | Reference text | `target_language` | Controls || --- | --- | --- | --- | --- || `seed` | one | required | `Chinese` / `English`, required | — || `multilingual` | one | required | `German` / `Spanish` / `French` / `Korean` / `Japanese` | — || `paralinguistic` | one | required | `Chinese` / `English` | inline tags in `text` || `podcast` | one per speaker | one per speaker, same order | inferred from the text | `speaker_N:` at the start of every line || `basic` | one | not accepted | — | `speed`, `pitch`, `volume`, all three || `emotion` | one | not accepted | — | `emotion` || `dialect` | one | not accepted | — | `dialect`: `川渝话` / `广粤话` || `freeform` | one | not accepted | — | `instruction` || `voice_design` | none | — | — | `style` || `ip` | none | — | — | `ip` |
Freeform always requires a reference clip and cannot be combined with voice design, a built-in voice, emotion, dialect or attribute controls. For `podcast`, start every dialogue line with `speaker_N:` and provide one reference audio clip and transcript per speaker, in speaker order. Repeat `--prompt_wav` and `--prompt_text` on the command line.
See the [Tiny examples](https://github.com/inclusionAI/Ming-3.0-tts#ming-30-tts-tiny) for a Podcast Python example and [examples/one_click/](https://github.com/inclusionAI/Ming-3.0-tts/tree/main/examples/one_click) for scripts for every task. `python infer_tiny.py --help` lists the CLI arguments.
### Verify the Checkpoint
```bashpython tools/preflight_tiny.py --model_path /path/to/Ming-3.0-tts-tiny```
## Performance
Benchmark comparisons from the [project README](https://github.com/inclusionAI/Ming-3.0-tts#performance).
**Bold** and <u>underline</u> mark the best and second-best values among the listed open-source models; ties share a mark. Seed-TTS and NVbench-GT are unranked reference rows.
### Zero-shot TTS (Seed-TTS testset)
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th rowspan="2" style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">Model</th><th colspan="2" style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">seed-tts-eval-zh</th><th colspan="2" style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">seed-tts-eval-en</th></tr> <tr><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">WER ↓</th><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">WER ↓</th><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">SIM ↑</th></tr> </thead> <tbody> <tr><td style="padding: 5px 12px; border: none; color: rgb(119, 119, 119);"><i>Seed-TTS</i></td><td align="center" style="padding: 5px 12px; border: none; color: rgb(119, 119, 119);">1.110%</td><td align="center" style="padding: 5px 12px; border: none; color: rgb(119, 119, 119);">0.796</td><td align="center" style="padding: 5px 12px; border: none; color: rgb(119, 119, 119);">2.240%</td><td align="center" style="padding: 5px 12px; border: none; color: rgb(119, 119, 119);">0.762</td></tr> <tr><td style="padding: 5px 12px; border: none;">GLM-TTS</td><td align="center" style="padding: 5px 12px; border: none;">1.030%</td><td align="center" style="padding: 5px 12px; border: none;">0.761</td><td align="center" style="padding: 5px 12px; border: none;">2.230%</td><td align="center" style="padding: 5px 12px; border: none;">0.672</td></tr> <tr><td style="padding: 5px 12px; border: none;">Qwen3-TTS</td><td align="center" style="padding: 5px 12px; border: none;">1.070%</td><td align="center" style="padding: 5px 12px; border: none;">—</td><td align="center" style="padding: 5px 12px; border: none;">1.390%</td><td align="center" style="padding: 5px 12px; border: none;">—</td></tr> <tr><td style="padding: 5px 12px; border: none;">Qwen3-TTS-12Hz-0.6B-Base</td><td align="center" style="padding: 5px 12px; border: none;">0.920%</td><td align="center" style="padding: 5px 12px; border: none;">—</td><td align="center" style="padding: 5px 12px; border: none;"><u>1.320%</u></td><td align="center" style="padding: 5px 12px; border: none;">—</td></tr> <tr><td style="padding: 5px 12px; border: none;">Qwen3-TTS-12Hz-1.7B-Base</td><td align="center" style="padding: 5px 12px; border: none;"><u>0.770%</u></td><td align="center" style="padding: 5px 12px; border: none;">—</td><td align="center" style="padding: 5px 12px; border: none;"><b>1.240%</b></td><td align="center" style="padding: 5px 12px; border: none;">—</td></tr> <tr><td style="padding: 5px 12px; border: none;">CosyVoice3-0.5B</td><td align="center" style="padding: 5px 12px; border: none;">1.160%</td><td align="center" style="padding: 5px 12px; border: none;"><u>0.780</u></td><td align="center" style="padding: 5px 12px; border: none;">2.020%</td><td align="center" style="padding: 5px 12px; border: none;"><u>0.718</u></td></tr> <tr><td style="padding: 5px 12px; border: none;">CosyVoice3-1.5B</td><td align="center" style="padding: 5px 12px; border: none;"><b>0.710%</b></td><td align="center" style="padding: 5px 12px; border: none;">0.775</td><td align="center" style="padding: 5px 12px; border: none;">1.450%</td><td align="center" style="padding: 5px 12px; border: none;">0.695</td></tr> <tr><td style="padding: 5px 12px; border: none;">F5-TTS</td><td align="center" style="padding: 5px 12px; border: none;">1.560%</td><td align="center" style="padding: 5px 12px; border: none;">0.741</td><td align="center" style="padding: 5px 12px; border: none;">1.830%</td><td align="center" style="padding: 5px 12px; border: none;">0.647</td></tr> <tr><td style="padding: 5px 12px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 12px; border: none; border-top: 1px solid black;">0.800%</td><td align="center" style="padding: 5px 12px; border: none; border-top: 1px solid black;">0.758</td><td align="center" style="padding: 5px 12px; border: none; border-top: 1px solid black;">1.584%</td><td align="center" style="padding: 5px 12px; border: none; border-top: 1px solid black;">0.691</td></tr> <tr><td style="padding: 5px 12px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 12px; border: none;">0.820%</td><td align="center" style="padding: 5px 12px; border: none;"><b>0.781</b></td><td align="center" style="padding: 5px 12px; border: none;">1.666%</td><td align="center" style="padding: 5px 12px; border: none;"><b>0.728</b></td></tr> </tbody></table>
### Multilingual (MiniMax test set, selected languages)
Evaluated on the German, Spanish, French, Korean, and Japanese subsets of [MiniMaxAI/TTS-Multilingual-Test-Set](https://huggingface.co/datasets/MiniMaxAI/TTS-Multilingual-Test-Set).
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th rowspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Model</th><th colspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">German</th><th colspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Spanish</th><th colspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">French</th><th colspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Korean</th><th colspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Japanese</th></tr> <tr><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">WER ↓</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">WER ↓</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">WER ↓</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">CER ↓</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">CER ↓</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">SIM ↑</th></tr> </thead> <tbody> <tr><td style="padding: 5px 10px; border: none;">dots.tts</td><td align="center" style="padding: 5px 10px; border: none;">0.452%</td><td align="center" style="padding: 5px 10px; border: none;"><u>0.798</u></td><td align="center" style="padding: 5px 10px; border: none;">2.593%</td><td align="center" style="padding: 5px 10px; border: none;"><u>0.839</u></td><td align="center" style="padding: 5px 10px; border: none;">19.878%</td><td align="center" style="padding: 5px 10px; border: none;"><u>0.789</u></td><td align="center" style="padding: 5px 10px; border: none;">4.837%</td><td align="center" style="padding: 5px 10px; border: none;"><u>0.853</u></td><td align="center" style="padding: 5px 10px; border: none;">5.134%</td><td align="center" style="padding: 5px 10px; border: none;"><b>0.838</b></td></tr> <tr><td style="padding: 5px 10px; border: none;">VoxCPM2</td><td align="center" style="padding: 5px 10px; border: none;">0.963%</td><td align="center" style="padding: 5px 10px; border: none;">0.790</td><td align="center" style="padding: 5px 10px; border: none;">1.324%</td><td align="center" style="padding: 5px 10px; border: none;">0.836</td><td align="center" style="padding: 5px 10px; border: none;"><b>3.380%</b></td><td align="center" style="padding: 5px 10px; border: none;">0.761</td><td align="center" style="padding: 5px 10px; border: none;">3.547%</td><td align="center" style="padding: 5px 10px; border: none;">0.839</td><td align="center" style="padding: 5px 10px; border: none;">4.358%</td><td align="center" style="padding: 5px 10px; border: none;"><u>0.825</u></td></tr> <tr><td style="padding: 5px 10px; border: none;">Fish Audio S2</td><td align="center" style="padding: 5px 10px; border: none;">1.045%</td><td align="center" style="padding: 5px 10px; border: none;">0.714</td><td align="center" style="padding: 5px 10px; border: none;">1.216%</td><td align="center" style="padding: 5px 10px; border: none;">0.748</td><td align="center" style="padding: 5px 10px; border: none;">3.636%</td><td align="center" style="padding: 5px 10px; border: none;">0.698</td><td align="center" style="padding: 5px 10px; border: none;"><u>1.675%</u></td><td align="center" style="padding: 5px 10px; border: none;">0.761</td><td align="center" style="padding: 5px 10px; border: none;"><u>3.427%</u></td><td align="center" style="padding: 5px 10px; border: none;">0.755</td></tr> <tr><td style="padding: 5px 10px; border: none;">FireRedTTS3</td><td align="center" style="padding: 5px 10px; border: none;"><u>0.348%</u></td><td align="center" style="padding: 5px 10px; border: none;"><b>0.825</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>1.086%</u></td><td align="center" style="padding: 5px 10px; border: none;"><b>0.868</b></td><td align="center" style="padding: 5px 10px; border: none;">4.366%</td><td align="center" style="padding: 5px 10px; border: none;"><b>0.807</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>1.644%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>0.864</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>3.418%</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>0.825</u></td></tr> <tr><td style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">0.365%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">0.753</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">1.099%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">0.763</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">4.264%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">0.675</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">1.728%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">0.793</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">3.765%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">0.765</td></tr> <tr><td style="padding: 5px 10px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>0.325%</b></td><td align="center" style="padding: 5px 10px; border: none;">0.791</td><td align="center" style="padding: 5px 10px; border: none;"><b>0.971%</b></td><td align="center" style="padding: 5px 10px; border: none;">0.797</td><td align="center" style="padding: 5px 10px; border: none;"><u>3.470%</u></td><td align="center" style="padding: 5px 10px; border: none;">0.733</td><td align="center" style="padding: 5px 10px; border: none;">6.000%</td><td align="center" style="padding: 5px 10px; border: none;">0.797</td><td align="center" style="padding: 5px 10px; border: none;"><u>3.427%</u></td><td align="center" style="padding: 5px 10px; border: none;">0.780</td></tr> </tbody></table>
<p><small>Each open-source model was evaluated using its recommended inference settings under a unified ASR-based WER/CER evaluation protocol.</small></p>
### Paralinguistic Control (NVBench)
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th rowspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">Model</th><th colspan="6" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">Single</th><th colspan="6" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">Multi</th></tr> <tr><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">Chinese</th><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">English</th><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">Chinese</th><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">English</th></tr> <tr><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">PCER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">OCER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">PCER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">OCER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">PCER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">OCER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">PCER</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">OCER</th></tr> </thead> <tbody> <tr><td style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);"><i>NVbench-GT</i></td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">3.86</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">9.38</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">4.07</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">6.73</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">8.31</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">6.90</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">3.79</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">23.71</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">5.07</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">7.26</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">21.41</td><td align="center" style="padding: 5px 8px; border: none; color: rgb(119, 119, 119);">8.62</td></tr> <tr><td style="padding: 5px 8px; border: none;">Orpheus-TTS</td><td align="center" style="padding: 5px 8px; border: none;">11.36</td><td align="center" style="padding: 5px 8px; border: none;">88.77</td><td align="center" style="padding: 5px 8px; border: none;">13.91</td><td align="center" style="padding: 5px 8px; border: none;">9.03</td><td align="center" style="padding: 5px 8px; border: none;">71.92</td><td align="center" style="padding: 5px 8px; border: none;">10.63</td><td align="center" style="padding: 5px 8px; border: none;">19.83</td><td align="center" style="padding: 5px 8px; border: none;">84.85</td><td align="center" style="padding: 5px 8px; border: none;">24.38</td><td align="center" style="padding: 5px 8px; border: none;">8.68</td><td align="center" style="padding: 5px 8px; border: none;">71.46</td><td align="center" style="padding: 5px 8px; border: none;">11.89</td></tr> <tr><td style="padding: 5px 8px; border: none;">SMIIP-NV-CV2</td><td align="center" style="padding: 5px 8px; border: none;">8.80</td><td align="center" style="padding: 5px 8px; border: none;">75.64</td><td align="center" style="padding: 5px 8px; border: none;">11.34</td><td align="center" style="padding: 5px 8px; border: none;">17.92</td><td align="center" style="padding: 5px 8px; border: none;">56.80</td><td align="center" style="padding: 5px 8px; border: none;">19.47</td><td align="center" style="padding: 5px 8px; border: none;">10.66</td><td align="center" style="padding: 5px 8px; border: none;">77.20</td><td align="center" style="padding: 5px 8px; border: none;">14.79</td><td align="center" style="padding: 5px 8px; border: none;">20.93</td><td align="center" style="padding: 5px 8px; border: none;">54.49</td><td align="center" style="padding: 5px 8px; border: none;">23.87</td></tr> <tr><td style="padding: 5px 8px; border: none;">Emilia-NV-CV2</td><td align="center" style="padding: 5px 8px; border: none;">5.05</td><td align="center" style="padding: 5px 8px; border: none;">40.00</td><td align="center" style="padding: 5px 8px; border: none;">6.64</td><td align="center" style="padding: 5px 8px; border: none;">12.50</td><td align="center" style="padding: 5px 8px; border: none;">55.30</td><td align="center" style="padding: 5px 8px; border: none;">13.21</td><td align="center" style="padding: 5px 8px; border: none;">5.54</td><td align="center" style="padding: 5px 8px; border: none;">48.74</td><td align="center" style="padding: 5px 8px; border: none;">8.09</td><td align="center" style="padding: 5px 8px; border: none;">11.71</td><td align="center" style="padding: 5px 8px; border: none;">60.28</td><td align="center" style="padding: 5px 8px; border: none;">14.63</td></tr> <tr><td style="padding: 5px 8px; border: none;">CosyVoice3</td><td align="center" style="padding: 5px 8px; border: none;">3.85</td><td align="center" style="padding: 5px 8px; border: none;">57.69</td><td align="center" style="padding: 5px 8px; border: none;">5.86</td><td align="center" style="padding: 5px 8px; border: none;">7.87</td><td align="center" style="padding: 5px 8px; border: none;">62.75</td><td align="center" style="padding: 5px 8px; border: none;">9.06</td><td align="center" style="padding: 5px 8px; border: none;">4.75</td><td align="center" style="padding: 5px 8px; border: none;">61.94</td><td align="center" style="padding: 5px 8px; border: none;">8.26</td><td align="center" style="padding: 5px 8px; border: none;"><u>6.39</u></td><td align="center" style="padding: 5px 8px; border: none;">57.84</td><td align="center" style="padding: 5px 8px; border: none;">10.69</td></tr> <tr><td style="padding: 5px 8px; border: none;">NV-FlexiVoice</td><td align="center" style="padding: 5px 8px; border: none;">6.98</td><td align="center" style="padding: 5px 8px; border: none;">31.08</td><td align="center" style="padding: 5px 8px; border: none;">8.15</td><td align="center" style="padding: 5px 8px; border: none;">11.88</td><td align="center" style="padding: 5px 8px; border: none;">50.43</td><td align="center" style="padding: 5px 8px; border: none;">13.21</td><td align="center" style="padding: 5px 8px; border: none;">8.20</td><td align="center" style="padding: 5px 8px; border: none;">39.37</td><td align="center" style="padding: 5px 8px; border: none;">10.39</td><td align="center" style="padding: 5px 8px; border: none;">9.60</td><td align="center" style="padding: 5px 8px; border: none;">51.32</td><td align="center" style="padding: 5px 8px; border: none;">13.76</td></tr> <tr><td style="padding: 5px 8px; border: none;">NV-CV3</td><td align="center" style="padding: 5px 8px; border: none;">3.80</td><td align="center" style="padding: 5px 8px; border: none;">27.69</td><td align="center" style="padding: 5px 8px; border: none;"><u>4.90</u></td><td align="center" style="padding: 5px 8px; border: none;">8.33</td><td align="center" style="padding: 5px 8px; border: none;">46.13</td><td align="center" style="padding: 5px 8px; border: none;">9.44</td><td align="center" style="padding: 5px 8px; border: none;"><b>3.44</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>30.04</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>4.84</b></td><td align="center" style="padding: 5px 8px; border: none;">6.70</td><td align="center" style="padding: 5px 8px; border: none;"><u>47.13</u></td><td align="center" style="padding: 5px 8px; border: none;"><u>10.10</u></td></tr> <tr><td style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>2.70</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>22.80</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>3.20</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>7.60</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>37.00</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>8.90</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>3.50</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">36.60</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">8.10</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">7.90</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">47.30</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">10.40</td></tr> <tr><td style="padding: 5px 8px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 8px; border: none;"><u>2.80</u></td><td align="center" style="padding: 5px 8px; border: none;"><b>17.23</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>3.20</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>5.86</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>32.95</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>7.05</b></td><td align="center" style="padding: 5px 8px; border: none;">4.49</td><td align="center" style="padding: 5px 8px; border: none;"><u>32.88</u></td><td align="center" style="padding: 5px 8px; border: none;"><u>5.81</u></td><td align="center" style="padding: 5px 8px; border: none;"><b>5.12</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>46.13</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>7.68</b></td></tr> </tbody></table>
### Dialect Control
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th rowspan="2" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">Model</th><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">WSC-Eval-TTS-easy</th><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">WSC-Eval-TTS-hard</th><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">WSYue-TTS-eval-Base</th><th colspan="3" style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">WSYue-TTS-eval-Coverage</th></tr> <tr><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER ↓</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">ACC ↑</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER ↓</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">ACC ↑</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER ↓</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">ACC ↑</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">CER ↓</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">SIM ↑</th><th style="padding: 6px 8px; border: none; border-bottom: 1px solid black;">ACC ↑</th></tr> </thead> <tbody> <tr><td style="padding: 5px 8px; border: none;">Qwen3-TTS</td><td align="center" style="padding: 5px 8px; border: none;">4.13%</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">7.35%</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td></tr> <tr><td style="padding: 5px 8px; border: none;">CosyVoice3-0.5B</td><td align="center" style="padding: 5px 8px; border: none;">3.17%</td><td align="center" style="padding: 5px 8px; border: none;">0.696</td><td align="center" style="padding: 5px 8px; border: none;">76.05%</td><td align="center" style="padding: 5px 8px; border: none;">4.07%</td><td align="center" style="padding: 5px 8px; border: none;"><u>0.723</u></td><td align="center" style="padding: 5px 8px; border: none;">81.41%</td><td align="center" style="padding: 5px 8px; border: none;">8.36%</td><td align="center" style="padding: 5px 8px; border: none;">0.611</td><td align="center" style="padding: 5px 8px; border: none;">91.70%</td><td align="center" style="padding: 5px 8px; border: none;">8.95%</td><td align="center" style="padding: 5px 8px; border: none;">0.658</td><td align="center" style="padding: 5px 8px; border: none;"><b>95.80%</b></td></tr> <tr><td style="padding: 5px 8px; border: none;">CosyVoice3-1.5B + DiffRO-EMO</td><td align="center" style="padding: 5px 8px; border: none;">7.14%</td><td align="center" style="padding: 5px 8px; border: none;">0.703</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">9.06%</td><td align="center" style="padding: 5px 8px; border: none;">0.601</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">14.38%</td><td align="center" style="padding: 5px 8px; border: none;"><u>0.812</u></td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">13.74%</td><td align="center" style="padding: 5px 8px; border: none;"><u>0.826</u></td><td align="center" style="padding: 5px 8px; border: none;">—</td></tr> <tr><td style="padding: 5px 8px; border: none;">CosyVoice2-WSC</td><td align="center" style="padding: 5px 8px; border: none;">4.28%</td><td align="center" style="padding: 5px 8px; border: none;"><u>0.728</u></td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">8.87%</td><td align="center" style="padding: 5px 8px; border: none;">0.626</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td></tr> <tr><td style="padding: 5px 8px; border: none;">CosyVoice2-WSC-SFT</td><td align="center" style="padding: 5px 8px; border: none;">4.08%</td><td align="center" style="padding: 5px 8px; border: none;"><b>0.788</b></td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">7.22%</td><td align="center" style="padding: 5px 8px; border: none;">0.680</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td></tr> <tr><td style="padding: 5px 8px; border: none;">CosyVoice2-Yue</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">10.33%</td><td align="center" style="padding: 5px 8px; border: none;"><b>0.821</b></td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">9.49%</td><td align="center" style="padding: 5px 8px; border: none;"><b>0.834</b></td><td align="center" style="padding: 5px 8px; border: none;">—</td></tr> <tr><td style="padding: 5px 8px; border: none;">Sparks-TTS</td><td align="center" style="padding: 5px 8px; border: none;">10.83%</td><td align="center" style="padding: 5px 8px; border: none;">0.677</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">12.52%</td><td align="center" style="padding: 5px 8px; border: none;">0.545</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">27.79%</td><td align="center" style="padding: 5px 8px; border: none;">0.762</td><td align="center" style="padding: 5px 8px; border: none;">—</td><td align="center" style="padding: 5px 8px; border: none;">24.25%</td><td align="center" style="padding: 5px 8px; border: none;">0.781</td><td align="center" style="padding: 5px 8px; border: none;">—</td></tr> <tr><td style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>2.27%</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">0.689</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>80.68%</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>3.35%</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">0.691</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>87.64%</u></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>6.15%</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">0.586</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>98.00%</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><b>8.15%</b></td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;">0.622</td><td align="center" style="padding: 5px 8px; border: none; border-top: 1px solid black;"><u>95.27%</u></td></tr> <tr><td style="padding: 5px 8px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 8px; border: none;"><u>2.53%</u></td><td align="center" style="padding: 5px 8px; border: none;">0.721</td><td align="center" style="padding: 5px 8px; border: none;"><b>86.09%</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>3.11%</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>0.738</b></td><td align="center" style="padding: 5px 8px; border: none;"><b>88.94%</b></td><td align="center" style="padding: 5px 8px; border: none;"><u>7.40%</u></td><td align="center" style="padding: 5px 8px; border: none;">0.605</td><td align="center" style="padding: 5px 8px; border: none;"><u>92.90%</u></td><td align="center" style="padding: 5px 8px; border: none;"><u>8.67%</u></td><td align="center" style="padding: 5px 8px; border: none;">0.653</td><td align="center" style="padding: 5px 8px; border: none;">95.16%</td></tr> </tbody></table>
### Emotion Control (CV3)
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th rowspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Model</th><th rowspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Average</th><th colspan="3" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Text-Related</th><th colspan="3" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Text-Unrelated</th></tr> <tr><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Happy</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Sad</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Angry</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Happy</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Sad</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Angry</th></tr> </thead> <tbody> <tr><td style="padding: 5px 10px; border: none;">CosyVoice3-0.5B</td><td align="center" style="padding: 5px 10px; border: none;">66.33%</td><td align="center" style="padding: 5px 10px; border: none;">92%</td><td align="center" style="padding: 5px 10px; border: none;">70%</td><td align="center" style="padding: 5px 10px; border: none;">72%</td><td align="center" style="padding: 5px 10px; border: none;">64%</td><td align="center" style="padding: 5px 10px; border: none;">42%</td><td align="center" style="padding: 5px 10px; border: none;">58%</td></tr> <tr><td style="padding: 5px 10px; border: none;">CosyVoice3-1.5B</td><td align="center" style="padding: 5px 10px; border: none;">63.00%</td><td align="center" style="padding: 5px 10px; border: none;">86%</td><td align="center" style="padding: 5px 10px; border: none;">64%</td><td align="center" style="padding: 5px 10px; border: none;">72%</td><td align="center" style="padding: 5px 10px; border: none;">64%</td><td align="center" style="padding: 5px 10px; border: none;">44%</td><td align="center" style="padding: 5px 10px; border: none;">48%</td></tr> <tr><td style="padding: 5px 10px; border: none;">CosyVoice3-1.5B + DiffRO-EMO</td><td align="center" style="padding: 5px 10px; border: none;"><b>77.67%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>98%</b></td><td align="center" style="padding: 5px 10px; border: none;">68%</td><td align="center" style="padding: 5px 10px; border: none;">84%</td><td align="center" style="padding: 5px 10px; border: none;"><b>98%</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>50%</u></td><td align="center" style="padding: 5px 10px; border: none;">68%</td></tr> <tr><td style="padding: 5px 10px; border: none;">F5-TTS</td><td align="center" style="padding: 5px 10px; border: none;">64.67%</td><td align="center" style="padding: 5px 10px; border: none;">92%</td><td align="center" style="padding: 5px 10px; border: none;">52%</td><td align="center" style="padding: 5px 10px; border: none;">72%</td><td align="center" style="padding: 5px 10px; border: none;"><u>80%</u></td><td align="center" style="padding: 5px 10px; border: none;">28%</td><td align="center" style="padding: 5px 10px; border: none;">64%</td></tr> <tr><td style="padding: 5px 10px; border: none;">Sparks-TTS</td><td align="center" style="padding: 5px 10px; border: none;">55.33%</td><td align="center" style="padding: 5px 10px; border: none;">80%</td><td align="center" style="padding: 5px 10px; border: none;">56%</td><td align="center" style="padding: 5px 10px; border: none;">50%</td><td align="center" style="padding: 5px 10px; border: none;">50%</td><td align="center" style="padding: 5px 10px; border: none;"><b>60%</b></td><td align="center" style="padding: 5px 10px; border: none;">36%</td></tr> <tr><td style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">72.33%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>96%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>76%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>94%</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">52%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">36%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>80%</b></td></tr> <tr><td style="padding: 5px 10px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>74.00%</u></td><td align="center" style="padding: 5px 10px; border: none;"><b>98%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>82%</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>90%</u></td><td align="center" style="padding: 5px 10px; border: none;">60%</td><td align="center" style="padding: 5px 10px; border: none;">36%</td><td align="center" style="padding: 5px 10px; border: none;"><u>78%</u></td></tr> </tbody></table>
### Emotion Control (CV3N, hard emotion control)
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th rowspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Model</th><th rowspan="2" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Average</th><th colspan="3" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Text-Related</th><th colspan="3" style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Text-Unrelated</th></tr> <tr><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Happy</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Sad</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Angry</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Happy</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Sad</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Angry</th></tr> </thead> <tbody> <tr><td style="padding: 5px 10px; border: none;">CosyVoice3-0.5B</td><td align="center" style="padding: 5px 10px; border: none;"><b>40.00%</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>68%</u></td><td align="center" style="padding: 5px 10px; border: none;">30%</td><td align="center" style="padding: 5px 10px; border: none;"><b>78%</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>14%</u></td><td align="center" style="padding: 5px 10px; border: none;"><u>4%</u></td><td align="center" style="padding: 5px 10px; border: none;"><b>46%</b></td></tr> <tr><td style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>37.33%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>70%</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>36%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>70%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>14%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>4%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>30%</u></td></tr> <tr><td style="padding: 5px 10px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 10px; border: none;">30.67%</td><td align="center" style="padding: 5px 10px; border: none;">60%</td><td align="center" style="padding: 5px 10px; border: none;"><b>40%</b></td><td align="center" style="padding: 5px 10px; border: none;">44%</td><td align="center" style="padding: 5px 10px; border: none;"><b>18%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>10%</b></td><td align="center" style="padding: 5px 10px; border: none;">12%</td></tr> </tbody></table>
### Voice Design (InstructTTSEval-ZH)
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Model</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Average</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">APS</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">DSD</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">RP</th></tr> </thead> <tbody> <tr><td style="padding: 5px 10px; border: none;">Qwen3-TTS</td><td align="center" style="padding: 5px 10px; border: none;"><b>77.13%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>85.20%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>81.10%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>65.10%</b></td></tr> <tr><td style="padding: 5px 10px; border: none;">Mimo-Audio-7B-Instruct</td><td align="center" style="padding: 5px 10px; border: none;">70.50%</td><td align="center" style="padding: 5px 10px; border: none;">75.70%</td><td align="center" style="padding: 5px 10px; border: none;">74.30%</td><td align="center" style="padding: 5px 10px; border: none;"><u>61.50%</u></td></tr> <tr><td style="padding: 5px 10px; border: none;">VoiceSculptor</td><td align="center" style="padding: 5px 10px; border: none;">67.30%</td><td align="center" style="padding: 5px 10px; border: none;">75.70%</td><td align="center" style="padding: 5px 10px; border: none;">64.70%</td><td align="center" style="padding: 5px 10px; border: none;"><u>61.50%</u></td></tr> <tr><td style="padding: 5px 10px; border: none;">VoxInstruct</td><td align="center" style="padding: 5px 10px; border: none;">47.47%</td><td align="center" style="padding: 5px 10px; border: none;">47.50%</td><td align="center" style="padding: 5px 10px; border: none;">52.30%</td><td align="center" style="padding: 5px 10px; border: none;">42.60%</td></tr> <tr><td style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">72.29%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">78.54%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">77.28%</td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;">61.06%</td></tr> <tr><td style="padding: 5px 10px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 10px; border: none;"><u>75.37%</u></td><td align="center" style="padding: 5px 10px; border: none;"><u>85.10%</u></td><td align="center" style="padding: 5px 10px; border: none;"><u>79.90%</u></td><td align="center" style="padding: 5px 10px; border: none;">61.10%</td></tr> </tbody></table>
### Basic Attribute Control
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Model</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Speed</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Volume</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Pitch</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">Average</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">WER ↓</th><th style="padding: 6px 10px; border: none; border-bottom: 1px solid black;">SIM ↑</th></tr> </thead> <tbody> <tr><td style="padding: 5px 10px; border: none;">CosyVoice3-0.5B</td><td align="center" style="padding: 5px 10px; border: none;"><b>100.00%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>97.67%</b></td><td align="center" style="padding: 5px 10px; border: none;">65.33%</td><td align="center" style="padding: 5px 10px; border: none;">87.67%</td><td align="center" style="padding: 5px 10px; border: none;">1.210%</td><td align="center" style="padding: 5px 10px; border: none;">0.580</td></tr> <tr><td style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-0.5b</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>99.00%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>95.00%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>86.00%</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><b>93.30%</b></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>0.317%</u></td><td align="center" style="padding: 5px 10px; border: none; border-top: 1px solid black;"><u>0.712</u></td></tr> <tr><td style="padding: 5px 10px; border: none;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 10px; border: none;">93.00%</td><td align="center" style="padding: 5px 10px; border: none;">93.00%</td><td align="center" style="padding: 5px 10px; border: none;"><u>78.70%</u></td><td align="center" style="padding: 5px 10px; border: none;"><u>88.23%</u></td><td align="center" style="padding: 5px 10px; border: none;"><b>0.274%</b></td><td align="center" style="padding: 5px 10px; border: none;"><b>0.742</b></td></tr> </tbody></table>
### Podcast
<table style="border-collapse: collapse; border-top: 1.5px solid black; border-bottom: 1.5px solid black; margin: 16px 0;"> <thead> <tr><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">Model</th><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">CER ↓</th><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">cpSIM ↑</th><th style="padding: 6px 12px; border: none; border-bottom: 1px solid black;">UTMOS ↑</th></tr> </thead> <tbody> <tr><td style="padding: 5px 12px; border: none;">FireRedTTS2</td><td align="center" style="padding: 5px 12px; border: none;">3.34%</td><td align="center" style="padding: 5px 12px; border: none;">0.512</td><td align="center" style="padding: 5px 12px; border: none;">1.90</td></tr> <tr><td style="padding: 5px 12px; border: none;">SoulX-Podcast</td><td align="center" style="padding: 5px 12px; border: none;"><u>2.20%</u></td><td align="center" style="padding: 5px 12px; border: none;"><b>0.599</b></td><td align="center" style="padding: 5px 12px; border: none;">2.09</td></tr> <tr><td style="padding: 5px 12px; border: none;">VibeVoice-1.5B</td><td align="center" style="padding: 5px 12px; border: none;">12.87%</td><td align="center" style="padding: 5px 12px; border: none;">0.455</td><td align="center" style="padding: 5px 12px; border: none;">1.74</td></tr> <tr><td style="padding: 5px 12px; border: none;">MOSS-TTSD</td><td align="center" style="padding: 5px 12px; border: none;">8.62%</td><td align="center" style="padding: 5px 12px; border: none;">0.421</td><td align="center" style="padding: 5px 12px; border: none;">1.70</td></tr> <tr><td style="padding: 5px 12px; border: none;">ZipVoice-Dia</td><td align="center" style="padding: 5px 12px; border: none;">3.39%</td><td align="center" style="padding: 5px 12px; border: none;">0.553</td><td align="center" style="padding: 5px 12px; border: none;"><b>2.24</b></td></tr> <tr><td style="padding: 5px 12px; border: none;">MoonCast</td><td align="center" style="padding: 5px 12px; border: none;">27.43%</td><td align="center" style="padding: 5px 12px; border: none;">0.441</td><td align="center" style="padding: 5px 12px; border: none;">1.76</td></tr> <tr><td style="padding: 5px 12px; border: none; border-top: 1px solid black;"><b>Ming-3.0-tts-tiny</b></td><td align="center" style="padding: 5px 12px; border: none; border-top: 1px solid black;"><b>2.03%</b></td><td align="center" style="padding: 5px 12px; border: none; border-top: 1px solid black;"><u>0.561</u></td><td align="center" style="padding: 5px 12px; border: none; border-top: 1px solid black;"><u>2.12</u></td></tr> </tbody></table>
## Limitations
- Korean CER (6.000%) is the clearest multilingual content-accuracy gap for this checkpoint.- Speaker similarity remains weaker than content accuracy on several multilingual and dialect evaluations.- NVBench Multi trails Single on several metrics; stability with multiple paralinguistic events in one sentence is still improving.- Emotion control is harder when the words carry no emotional signal.- Pitch is less accurate than speed and volume, and open-ended Voice Design does not yet match the strongest evaluated system.- Podcast audio quality remains a limitation: UTMOS is 2.12, below ZipVoice-Dia's 2.24 and the historical Ming-omni-tts-0.5B score of 2.25.
## Usage Disclaimer
- Voice cloning and built-in character voices are provided for research and legitimate creative use. Do not use them to impersonate a real person without consent, to deceive, or for any illegal purpose.- Label synthetic speech as synthetic where it could be mistaken for a real recording.- The authors accept no liability for misuse. If you find abuse of this project, please report it to us.
## Acknowledgements
- Ling V3 for the mixture-of-experts backbone- [CAM++](https://modelscope.cn/models/iic/speech_campplus_sv_zh-cn_16k-common) for speaker embedding extraction- [Ming-omni-tts](https://github.com/inclusionAI/Ming-omni-tts), the previous generation, whose audio tokenizer this release builds on
## License
Released under the [MIT license](https://github.com/inclusionAI/Ming-3.0-tts/blob/main/LICENSE).12345678910111213141516171819"""Standalone Hugging Face inference helpers with lazy model imports."""
from typing import Any
__all__ = ["LingV3TTSConfig", "LingV3TTSForConditionalGeneration"]
def __getattr__(name: str) -> Any: if name == "LingV3TTSConfig": from .configuration_lingv3_tts import LingV3TTSConfig
return LingV3TTSConfig if name == "LingV3TTSForConditionalGeneration": from .modeling_lingv3_tts import ( LingV3TTSForConditionalGeneration, )
return LingV3TTSForConditionalGeneration raise AttributeError(name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# --------------------------------------------------------# References:# GLIDE: https://github.com/openai/glide-text2im# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py# --------------------------------------------------------
import torchimport torch.nn as nnfrom .modules import FinalLayer, DiTBlockfrom x_transformers.x_transformers import RotaryEmbedding
class Aggregator(nn.Module): """ Diffusion model with a Transformer backbone. """ def __init__( self, in_channels=4, hidden_size=1152, depth=28, num_heads=16, mlp_ratio=4.0, llm_input_dim=896, **kwargs, ):
super().__init__() self.in_channels = in_channels self.out_channels = in_channels self.num_heads = num_heads
self.word_embedder = nn.Embedding(1, hidden_size) self.x_embedder = nn.Linear(in_channels, hidden_size) self.hidden_size = hidden_size
self.rotary_embed = RotaryEmbedding(hidden_size // num_heads)
self.blocks = nn.ModuleList([ DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, **kwargs) for _ in range(depth) ]) self.final_layer = FinalLayer(hidden_size, llm_input_dim) self.initialize_weights()
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w_x = self.x_embedder.weight.data nn.init.xavier_uniform_(w_x.view([w_x.shape[0], -1])) nn.init.constant_(self.x_embedder.bias, 0)
# Initialize word embedding table: nn.init.normal_(self.word_embedder.weight, std=0.02)
# Zero-out output layers: nn.init.constant_(self.final_layer.linear.weight, 0) nn.init.constant_(self.final_layer.linear.bias, 0)
def forward(self, x, mask=None): """ Forward pass of DiT. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N,) tensor of class labels """ x = self.x_embedder(x) cls_embed = self.word_embedder(torch.zeros((x.shape[0], 1), dtype=torch.long, device=x.device)) # cls token for bidirectional attention x = torch.cat([cls_embed, x], dim=1)
rope = self.rotary_embed.forward_from_seq_len(x.shape[1]) if mask is not None: mask_pad = mask.clone().detach()[:, :1] mask = torch.cat([mask_pad, mask], dim=-1) for block in self.blocks: x = block(x, mask, rope) # (N, T, D) x = self.final_layer(x) # (N, T, patch_size ** 2 * out_channels) x = x[:,:1, :] return x123version https://git-lfs.github.com/spec/v1oid sha256:a6ac6a63997761ae2997373e2ee1c47040854b4b759ea41ec48e4e42df0f4d73size 28303423123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126{#- Bailing V3 chat template -#}{#- Supports: thinking option, tool calling -#}
{#- ==================== thinking option normalization ==================== -#}{%- if enable_thinking is defined and enable_thinking %} {%- set thinking_option = 'on' %}{%- elif thinking_option is not defined %} {%- set thinking_option = 'off' %}{%- endif %}
{#- ==================== preserved thinking ==================== -#}{% set preserved_thinking = true %}
{#- ==================== system message ==================== -#}{{- '<role>SYSTEM</role>' }}{%- if tools %} {%- if messages[0].role == 'system' %} {{- messages[0].content + '\n' }} {%- endif %} {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>\n\nIf none of the functions can be used, point it out. If the given question lacks the parameters required by the function, also point it out.\nIf you need to use a function, for each function call, output the function name and arguments within the following XML format:\n<tool_call>{function-name}\n<arg_key>{arg-key-1}</arg_key>\n<arg_value>{arg-value-1}</arg_value>\n<arg_key>{arg-key-2}</arg_key>\n<arg_value>{arg-value-2}</arg_value>\n...\n</tool_call>\n" }} {%- if messages[0].role == 'system' and messages[0].content is string and ('detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content) %} {{- '<|role_end|>' }} {%- else %} {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }} {%- endif %}{%- else %} {%- if messages[0].role == 'system' %} {%- if 'detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content %} {{- messages[0].content + '<|role_end|>' }} {%- else %} {{- messages[0].content + '\n' }} {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }} {%- endif %} {% else %} {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %}{%- endfor %}{%- for message in messages %} {%- if message.content is string %} {%- set content = message.content %} {%- else %} {%- set content = '' %} {%- endif %} {%- if message.role == "user" %} {{- '<role>HUMAN</role>' + message.content + '<|role_end|>' }} {%- elif message.role == "system" and not loop.first %} {{- '<role>SYSTEM</role>' + message.content + '<|role_end|>' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string and message.reasoning_content != '' %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if preserved_thinking or loop.index0 > ns.last_query_index %} {%- if reasoning_content != '' %} {{- '<role>ASSISTANT</role>' + '\n<think>' + reasoning_content.strip('\n') + '</think>' + content.lstrip('\n') }} {%- else %} {{- '<role>ASSISTANT</role>\n<think></think>' + content }} {%- endif %} {%- else %} {{- '<role>ASSISTANT</role>\n<think></think>' + content }} {%- endif %} {%- if message.tool_calls %} {%- for tool_call in message.tool_calls %} {%- if (loop.first and content) or (not loop.first) %} {{- '\n' }} {%- endif %} {%- set tc = tool_call %} {%- if tool_call.function %} {%- set tc = tool_call.function %} {%- endif %} {{- '<tool_call>' + tc.name }} {% set _args = tc.arguments %} {%- for k, v in _args.items() %} {{- '<arg_key>' + k + '</arg_key>' }} {{- '\n<arg_value>' }} {%- if v is string %} {{- v }} {%- else %} {{- v | tojson(ensure_ascii=False) }} {%- endif %} {{- '</arg_value>' }} {%- endfor %} {{- '\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|role_end|>' }} {%- elif message.role == "tool" %} {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} {{- '<role>OBSERVATION</role>' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} {{- '<|role_end|>' }} {%- endif %} {%- endif %}{%- endfor %}
{#- ==================== generation prompt ==================== -#}{%- if add_generation_prompt %} {{- '<role>ASSISTANT</role>' }} {%- if thinking_option == 'on' %} {{- '\n<think>' }} {%- elif thinking_option == 'off' %} {{- '\n<think></think>' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228{ "architectures": [ "LingV3TTSForConditionalGeneration" ], "model_type": "lingv3_tts", "auto_map": { "AutoConfig": "configuration_lingv3_tts.LingV3TTSConfig", "AutoModel": "modeling_lingv3_tts.LingV3TTSForConditionalGeneration" }, "tie_word_embeddings": false, "llm_config": { "architectures": [ "BailingMoeV3ForCausalLM" ], "model_type": "bailing_moe_v3", "vocab_size": 157184, "hidden_size": 1536, "intermediate_size": 4608, "num_hidden_layers": 24, "num_attention_heads": 16, "num_key_value_heads": 16, "hidden_act": "silu", "use_qkv_bias": false, "use_bias": false, "rms_norm_eps": 1e-06, "tie_word_embeddings": false, "embedding_dropout": 0.0, "attention_dropout": 0.0, "output_dropout": 0.0, "initializer_range": 0.006, "max_position_embeddings": 4096, "rope_theta": 10000, "use_cache": true, "max_window_layers": 24, "rope_scaling": null, "bos_token_id": 156891, "pad_token_id": 156892, "eos_token_id": [ 156892, 156895 ], "num_experts": 128, "num_shared_experts": 1, "num_experts_per_tok": 8, "n_group": 8, "topk_group": 4, "moe_intermediate_size": 512, "moe_shared_expert_intermediate_size": 512, "first_k_dense_replace": 1, "head_dim": 128, "output_router_logits": false, "use_qk_norm": true, "num_nextn_predict_layers": 0, "mtp_loss_scaling_factor": 0.1, "moe_router_enable_expert_bias": true, "routed_scaling_factor": 2.5, "moe_router_topk_scaling_factor": 2.5, "layer_group_size": 4, "kv_lora_rank": 512, "q_lora_rank": 256, "qk_rope_head_dim": 64, "v_head_dim": 128, "qk_nope_head_dim": 128, "rope_interleave": true, "score_function": "sigmoid", "scoring_func": "sigmoid", "seq_aux": true, "topk_method": "noaux_tc", "router_dtype": "fp32", "gated_attention_proj_granularity_type": "head_wise", "no_kda_lora": true, "kda_safe_gate": true, "kda_lower_bound": -5.0, "short_conv_kernel_size": 4, "moe_layer_freq": [ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], "torch_dtype": "bfloat16", "norm_topk_prob": true, "use_expert_bias": true, "moe_z_loss_coeff": 2.9e-06, "rotary_percent": 0.5, "position_embedding_type": "rope" }, "audio_config": { "architectures": [ "AudioVAE" ], "sample_rate": 44100, "enc_kwargs": { "backbone": { "_attn_implementation": "flash_attention_2", "attention_dropout": 0.0, "hidden_act": "silu", "hidden_size": 896, "initializer_range": 0.02, "intermediate_size": 4864, "is_causal": true, "max_position_embeddings": 32768, "max_window_layers": 0, "model_type": "qwen2", "num_attention_heads": 14, "num_hidden_layers": 24, "num_key_value_heads": 2, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "sliding_window": 64, "tie_word_embeddings": true, "torch_dtype": "bfloat16", "use_cache": false, "use_sliding_window": true, "vocab_size": 1 }, "hop_size": 882, "input_dim": 882, "latent_dim": 64 }, "dec_kwargs": { "backbone": { "_attn_implementation": "flash_attention_2", "attention_dropout": 0.0, "hidden_act": "silu", "hidden_size": 896, "initializer_range": 0.02, "intermediate_size": 4864, "is_causal": true, "max_position_embeddings": 32768, "max_window_layers": 0, "model_type": "qwen2", "num_attention_heads": 14, "num_hidden_layers": 24, "num_key_value_heads": 2, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "sliding_window": 64, "tie_word_embeddings": true, "torch_dtype": "bfloat16", "use_cache": false, "use_sliding_window": true, "vocab_size": 1 }, "latent_dim": 64, "output_dim": 882 }, "semantic_module_kwargs": null, "init_method": "kaiming", "patch_size": 4, "torch_dtype": "bfloat16" }, "tts_config": { "protocol_version": "thinking_v1", "prompt_format": "legacy_antmmf", "tokenizer_contract": "legacy_antmmf", "sampling_contract": "native_fp32", "enable_tts_target_language": true, "infer_tts_language_from_text": true, "conditioning_mode": "speaker_only", "sampling_temperature": 1.5, "prompt_eos_token_id": 156895, "sample_rate": 44100, "speaker_embedding_dim": 192, "latent_dim": 64, "patch_size": 1, "history_size": 1, "audio_patch_token_id": 157164, "audio_start_token_id": 157165, "audio_end_token_id": 157166, "speaker_start_token_id": 157175, "speaker_end_token_id": 157176, "stop_threshold": 0.5, "minimum_decode_steps": 13, "maximum_decode_steps": 250, "decode_alignment": "old_shift", "task_contract": "lingv3_sft_multitask_v1", "task_decode_alignment": { "podcast": "old_shift" }, "with_rml": true }, "flow_config": { "z_channels": 64, "hidden_size": 1024, "depth": 16, "num_heads": 16, "mlp_ratio": 4, "dropout": 0.1, "qk_norm": null, "pe_attn_head": null, "attn_backend": "torch", "attn_mask_enabled": false }, "aggregator_config": { "in_channels": 64, "hidden_size": 1024, "depth": 8, "num_heads": 16, "mlp_ratio": 4, "dropout": 0.1, "qk_norm": null, "pe_attn_head": null, "attn_backend": "torch", "attn_mask_enabled": false }, "torch_dtype": "bfloat16"}1234567891011121314151617181920212223242526272829303132333435from transformers import PretrainedConfig
class AudioVAEconfig(PretrainedConfig): def __init__( self, sample_rate: int=16000, enc_kwargs: dict = None, semantic_module_kwargs: dict = None, dec_kwargs: dict = None, hifi_gan_disc_kwargs: dict = None, spec_disc_kwargs: dict = None, lambda_disc=1.0, lambda_mel_loss=15, lambda_adv=1.0, lambda_feat_match_loss=1.0, lambda_semantic=5.0, init_method='normal', patch_size=-1, **kwargs ): self.sample_rate = sample_rate self.enc_kwargs = enc_kwargs self.semantic_module_kwargs = semantic_module_kwargs self.dec_kwargs = dec_kwargs self.hifi_gan_disc_kwargs = hifi_gan_disc_kwargs self.spec_disc_kwargs = spec_disc_kwargs self.lambda_disc = lambda_disc self.lambda_mel_loss = lambda_mel_loss self.lambda_adv = lambda_adv self.lambda_feat_match_loss = lambda_feat_match_loss self.lambda_semantic = lambda_semantic self.init_method = init_method self.patch_size = patch_size super().__init__(**kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""Bailing MoE V2 model configuration"""
from transformers.configuration_utils import PretrainedConfig
class BailingMoeV3Config(PretrainedConfig):
def __init__( self, vocab_size=157184, hidden_size=2048, intermediate_size=5120, num_hidden_layers=20, num_attention_heads=16, num_key_value_heads=4, hidden_act="silu", use_qkv_bias=False, # bailing only use_bias=False, # bailing only rms_norm_eps=1e-06, tie_word_embeddings=False, # PretrainedConfig key, here change default value. embedding_dropout=0.0, attention_dropout=0.0, output_dropout=0.0, initializer_range=0.02, max_position_embeddings=32768, rope_theta=600000.0, use_cache=True, max_window_layers=20, rope_scaling=None, pad_token_id=156892, eos_token_id=156892, num_experts=256, num_shared_experts=1, num_experts_per_tok=8, n_group=8, topk_group=4, moe_intermediate_size=512, moe_shared_expert_intermediate_size=512, first_k_dense_replace=1, head_dim=128, output_router_logits=False, use_qk_norm=True, num_nextn_predict_layers=0, mtp_loss_scaling_factor=0, moe_router_enable_expert_bias=True, routed_scaling_factor=1.0, layer_group_size=5, kv_lora_rank=512, q_lora_rank=None, qk_rope_head_dim=64, v_head_dim=128, qk_nope_head_dim=128, rope_interleave=True, score_function="sigmoid", scoring_func="sigmoid", seq_aux=True, topk_method="noaux_tc", router_dtype="fp32", gated_attention_proj_granularity_type=None, no_kda_lora=False, kda_safe_gate=False, kda_lower_bound=None, short_conv_kernel_size=4, **kwargs, ): self.num_hidden_layers = num_hidden_layers self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.use_qkv_bias = use_qkv_bias self.use_bias = use_bias self.rms_norm_eps = rms_norm_eps self.embedding_dropout = embedding_dropout self.attention_dropout = attention_dropout self.output_dropout = output_dropout self.num_nextn_predict_layers = num_nextn_predict_layers self.mtp_loss_scaling_factor = mtp_loss_scaling_factor self.initializer_range = initializer_range self.max_position_embeddings = max_position_embeddings self.rope_theta = rope_theta self.use_cache = use_cache self.max_window_layers = max_window_layers self.head_dim = head_dim or self.hidden_size // self.num_attention_heads self.rope_scaling = rope_scaling self.use_qk_norm = use_qk_norm self.moe_router_enable_expert_bias = moe_router_enable_expert_bias self.routed_scaling_factor = routed_scaling_factor
# MoE configs self.num_experts = num_experts self.num_shared_experts = num_shared_experts self.num_experts_per_tok = num_experts_per_tok self.n_group = n_group self.topk_group = topk_group self.moe_intermediate_size = moe_intermediate_size self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size self.first_k_dense_replace = first_k_dense_replace self.output_router_logits = output_router_logits
# Linear configs self.layer_group_size = layer_group_size # mla self.kv_lora_rank = kv_lora_rank self.q_lora_rank = q_lora_rank self.qk_rope_head_dim = qk_rope_head_dim
self.score_function = score_function self.scoring_func = scoring_func self.seq_aux = seq_aux self.topk_method = topk_method self.v_head_dim = v_head_dim self.qk_nope_head_dim = qk_nope_head_dim self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim self.rope_interleave = rope_interleave self.router_dtype = router_dtype self.gated_attention_proj_granularity_type = gated_attention_proj_granularity_type self.no_kda_lora = no_kda_lora self.kda_safe_gate = kda_safe_gate self.kda_lower_bound = kda_lower_bound self.short_conv_kernel_size = short_conv_kernel_size super().__init__( pad_token_id=pad_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Configuration for the standalone LingV3 TTS Hugging Face model."""
from __future__ import annotations
from copy import deepcopyfrom typing import Any, Dict, Optional
from transformers.configuration_utils import PretrainedConfig
from .configuration_audio_vae import AudioVAEconfigfrom .configuration_bailing_moe_v3 import BailingMoeV3Config
DEFAULT_TTS_CONFIG: Dict[str, Any] = { "protocol_version": "legacy_antmmf", "prompt_format": "legacy_antmmf", "tokenizer_contract": "legacy_antmmf", "sampling_contract": "native_fp32", "sample_rate": 44100, "latent_dim": 64, "speaker_embedding_dim": 192, "patch_size": 1, "history_size": 1, "audio_patch_token_id": 157164, "audio_start_token_id": 157165, "audio_end_token_id": 157166, "speaker_start_token_id": 157175, "speaker_end_token_id": 157176, "minimum_decode_steps": 5,}
DEFAULT_AGGREGATOR_CONFIG: Dict[str, Any] = { "in_channels": 64, "hidden_size": 1024, "depth": 8, "num_heads": 16, "mlp_ratio": 4, "dropout": 0.1, "qk_norm": None, "pe_attn_head": None, "attn_backend": "torch", "attn_mask_enabled": False,}
DEFAULT_FLOW_CONFIG: Dict[str, Any] = { "z_channels": 64, "flow_model_type": None, "hidden_size": 1024, "depth": 16, "num_heads": 16, "mlp_ratio": 4, "dropout": 0.1, "qk_norm": None, "pe_attn_head": None, "attn_backend": "torch", "attn_mask_enabled": False,}
class LingV3TTSConfig(PretrainedConfig): """Nested configuration for the LingV3 backbone and TTS modules."""
model_type = "lingv3_tts" is_composition = True
def __init__( self, llm_config: Optional[Dict[str, Any] | BailingMoeV3Config] = None, audio_config: Optional[Dict[str, Any] | AudioVAEconfig] = None, tts_config: Optional[Dict[str, Any]] = None, aggregator_config: Optional[Dict[str, Any]] = None, flow_config: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> None: if llm_config is None: llm_config = {} self.llm_config = ( BailingMoeV3Config(**llm_config) if isinstance(llm_config, dict) else llm_config )
if audio_config is None: audio_config = {} self.audio_config = ( AudioVAEconfig(**audio_config) if isinstance(audio_config, dict) else audio_config )
supplied_tts = dict(tts_config or {}) # Checkpoints produced before protocol_version was introduced used # the later thinking prompt and token rows. Infer that one legacy # metadata case so existing converted models remain loadable. if "protocol_version" not in supplied_tts: supplied_patch_id = supplied_tts.get("audio_patch_token_id") if supplied_patch_id == 157168: supplied_tts["protocol_version"] = "thinking_v1" selected_protocol = supplied_tts.get( "protocol_version", DEFAULT_TTS_CONFIG["protocol_version"] ) supplied_tts.setdefault("prompt_format", selected_protocol) supplied_tts.setdefault("tokenizer_contract", selected_protocol) supplied_tts.setdefault( "sampling_contract", ( "native_fp32" if selected_protocol == "legacy_antmmf" else "device_dtype" ), ) merged_tts = deepcopy(DEFAULT_TTS_CONFIG) merged_tts.update(supplied_tts) self.tts_config = merged_tts
merged_aggregator = deepcopy(DEFAULT_AGGREGATOR_CONFIG) merged_aggregator.update(aggregator_config or {}) self.aggregator_config = merged_aggregator
merged_flow = deepcopy(DEFAULT_FLOW_CONFIG) merged_flow.update(flow_config or {}) self.flow_config = merged_flow
kwargs.setdefault( "architectures", ["LingV3TTSForConditionalGeneration"] ) # This is a composite checkpoint whose LingV3 input embedding and # language-model head are two independently trained matrices. The # PretrainedConfig default is True and would silently collapse them # during PreTrainedModel.tie_weights(). kwargs.setdefault("tie_word_embeddings", False) kwargs.setdefault( "auto_map", { "AutoConfig": "configuration_lingv3_tts.LingV3TTSConfig", "AutoModel": ( "modeling_lingv3_tts." "LingV3TTSForConditionalGeneration" ), }, ) super().__init__(**kwargs)
def get_text_config( self, decoder: Optional[bool] = None, encoder: Optional[bool] = None ) -> BailingMoeV3Config: """Return the actual LingV3 text config to Hugging Face helpers."""
return self.llm_config
def to_dict(self) -> Dict[str, Any]: output = super().to_dict() output["llm_config"] = self.llm_config.to_dict() output["audio_config"] = self.audio_config.to_dict() output["tts_config"] = deepcopy(self.tts_config) output["aggregator_config"] = deepcopy(self.aggregator_config) output["flow_config"] = deepcopy(self.flow_config) output["model_type"] = self.model_type return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283{ "source_checkpoint": "/pcache-mnt/ro/checkpoint/854014/duleilei.dll/ckpts/tiny_old_sft2_plus_v6_0914_64gpu_muon_8task_nowall_oldemo_pt1_36k_alias100_20b_seq4096_all_12p5hz/iter_0039000", "source_common_metadata": "/pcache-mnt/ro/checkpoint/854014/duleilei.dll/ckpts/tiny_old_sft2_plus_v6_0914_64gpu_muon_8task_nowall_oldemo_pt1_36k_alias100_20b_seq4096_all_12p5hz/iter_0039000/for_infer/pure_common.pt", "source_metadata_sha256": "71b4d63075f127b8d1fd73c3a814dbab9427b6752470ecd94bfce83b201cc64c", "source_iteration": 39000, "conversion": "Megatron DCP global model tensors to LingV3 TTS HF safetensors; optimizer excluded; MTP=0", "schema": { "checkpoint_path": "/pcache-mnt/ro/checkpoint/854014/duleilei.dll/ckpts/tiny_old_sft2_plus_v6_0914_64gpu_muon_8task_nowall_oldemo_pt1_36k_alias100_20b_seq4096_all_12p5hz/iter_0039000", "iteration": 39000, "source_tensor_count": 1475, "source_component_counts": { "audio": 643, "flowloss": 236, "linear_proj_audio": 119, "model": 473, "spk_head": 2, "stop_head": 2 }, "excluded_tensor_count": 2421, "excluded_component_counts": { "chained_0": 2283, "chained_1": 138 }, "source_dtype_counts": { "bfloat16": 1416, "float32": 59 }, "target_tensor_count": 10285, "target_component_counts": { "audio": 643, "flowloss": 236, "linear_proj_audio": 119, "model": 9283, "spk_head": 2, "stop_head": 2 }, "target_dtype_counts": { "bfloat16": 10226, "float32": 59 }, "target_parameter_count": 8981004468, "target_total_bytes": 17962089128, "target_schema_sha256": "627a6b3a872b210e38d5c30778305155b9a0f6710924a33558226e85aaf58fa3", "groups": [ { "name": "model-base", "source_tensor_count": 3, "target_tensor_count": 3 }, { "name": "model-layer-00", "source_tensor_count": 17, "target_tensor_count": 18 }, { "name": "model-layer-01", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-02", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-03", "source_tensor_count": 16, "target_tensor_count": 399 }, { "name": "model-layer-04", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-05", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-06", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-07", "source_tensor_count": 16, "target_tensor_count": 399 }, { "name": "model-layer-08", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-09", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-10", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-11", "source_tensor_count": 16, "target_tensor_count": 399 }, { "name": "model-layer-12", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-13", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-14", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-15", "source_tensor_count": 16, "target_tensor_count": 399 }, { "name": "model-layer-16", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-17", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-18", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-19", "source_tensor_count": 16, "target_tensor_count": 399 }, { "name": "model-layer-20", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-21", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-22", "source_tensor_count": 21, "target_tensor_count": 404 }, { "name": "model-layer-23", "source_tensor_count": 16, "target_tensor_count": 399 }, { "name": "audio", "source_tensor_count": 643, "target_tensor_count": 643 }, { "name": "flowloss", "source_tensor_count": 236, "target_tensor_count": 236 }, { "name": "linear-proj-audio", "source_tensor_count": 119, "target_tensor_count": 119 }, { "name": "spk-head", "source_tensor_count": 2, "target_tensor_count": 2 }, { "name": "stop-head", "source_tensor_count": 2, "target_tensor_count": 2 } ], "independent_target_schema": "/workspace/bin/moe-model-convert/schemas/lingv3_moe_tts_8b.json", "independent_target_schema_validated": true }, "audio_config_source": "embedded-inference-architecture", "campplus_source": "/workspace/bin/moe-model-convert/assets/campplus.onnx", "campplus_sha256": "a6ac6a63997761ae2997373e2ee1c47040854b4b759ea41ec48e4e42df0f4d73", "tts_config": { "protocol_version": "thinking_v1", "prompt_format": "legacy_antmmf", "tokenizer_contract": "legacy_antmmf", "sampling_contract": "native_fp32", "enable_tts_target_language": true, "infer_tts_language_from_text": true, "conditioning_mode": "speaker_only", "sampling_temperature": 1.5, "prompt_eos_token_id": 156895, "sample_rate": 44100, "speaker_embedding_dim": 192, "latent_dim": 64, "patch_size": 1, "history_size": 1, "audio_patch_token_id": 157164, "audio_start_token_id": 157165, "audio_end_token_id": 157166, "speaker_start_token_id": 157175, "speaker_end_token_id": 157176, "stop_threshold": 0.5, "minimum_decode_steps": 13, "maximum_decode_steps": 250, "decode_alignment": "old_shift", "task_contract": "lingv3_sft_multitask_v1", "task_decode_alignment": { "podcast": "old_shift" }, "with_rml": true }, "tokenizer": { "source": "/pcache-mnt/ro/checkpoint/854014/duleilei.dll/ckpts/tiny_old_sft2_plus_v6_0914_64gpu_muon_8task_nowall_oldemo_pt1_36k_alias100_20b_seq4096_all_12p5hz/iter_0039000/for_infer", "contract": "legacy_antmmf", "prompt_eos_token_id": 156895, "tts_token_ids": { "<audioPatch>": 157164, "<audio>": 157165, "</audio>": 157166, "<spk>": 157175, "</spk>": 157176 }, "source_files_sha256": { "tokenizer.json": "7e831c9b79b2cc4af0d3c7c7878a073371a5cbbaf1f4cb33f6fbce20417722f2", "tokenizer_config.json": "7368e7cb06ef86c782f959b9796e21622aae4aace075c2cd5356604277ee2dee", "special_tokens_map.json": "97cb54787ce5ed537fe2b0211768bfce371defabe8241d39459493de9f23b1fc" }, "portable_wrapper": "PreTrainedTokenizerFast", "multimodal_token_count": 24 }, "inference_contract": { "training_recipe": "rc1.6", "runtime_protocol": "thinking_v1", "prompt_protocol": "legacy_antmmf", "tokenizer_contract": "legacy_antmmf", "sampling_contract": "native_fp32", "decode_alignment": "old_shift", "task_decode_alignment": { "podcast": "old_shift" }, "decode_policy": { "minimum_decode_steps": 13, "maximum_decode_steps": 250, "stop_threshold": 0.5, "basis": "1--20 second training filter at 12.5 latent Hz" }, "llm_hidden_source": "24-layer main decoder final hidden (MTP=0)", "autoregressive_feedback": "Flow latent -> Aggregator -> LLM KV cache", "flow": { "latent_dim": 64, "patch_size": 1, "history_size": 1, "depth": 16 } }, "topology": { "world_size": 64, "tensor_parallel": 1, "pipeline_parallel": 1, "expert_parallel": 8, "context_parallel": 1 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# --------------------------------------------------------# References:# GLIDE: https://github.com/openai/glide-text2im# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py# --------------------------------------------------------
import torchimport torch.nn as nnimport numpy as npimport mathfrom .modules import FinalLayer, DiTBlockfrom x_transformers.x_transformers import RotaryEmbedding
################################################################################## Embedding Layers for Timesteps and Class Labels ##################################################################################
class SinusPositionEmbedding(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim
def forward(self, x, scale=1000): device = x.device half_dim = self.dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb) emb = scale * x.unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat((emb.sin(), emb.cos()), dim=-1) return emb
class TimestepEmbedder(nn.Module): def __init__(self, dim, freq_embed_dim=256): super().__init__() self.time_embed = SinusPositionEmbedding(freq_embed_dim) self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
def forward(self, timestep): time_hidden = self.time_embed(timestep) time_hidden = time_hidden.to(timestep.dtype) time = self.time_mlp(time_hidden) # b d return time
class CondEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles llm hidden dropout for classifier-free guidance. """ def __init__(self, input_feature_size, hidden_size, dropout_prob): super().__init__() self.dropout_prob = dropout_prob self.cond_embedder = nn.Linear(input_feature_size, hidden_size)
def cond_drop(self, llm_cond): """ Drops llm hidden to enable classifier-free guidance. """ bsz = llm_cond.shape[0] drop_latent_mask = torch.rand(bsz) < self.dropout_prob drop_latent_mask = drop_latent_mask.unsqueeze(-1).unsqueeze(-1).to(llm_cond.dtype).to(llm_cond.device) fake_latent = torch.zeros(llm_cond.shape).to(llm_cond.device) llm_cond = drop_latent_mask * fake_latent + (1 - drop_latent_mask) * llm_cond
return llm_cond
def forward(self, llm_cond, train): use_dropout = self.dropout_prob > 0 if train and use_dropout: llm_cond = self.cond_drop(llm_cond)
llm_cond = self.cond_embedder(llm_cond)
return llm_cond
class DiT(nn.Module): """ Diffusion model with a Transformer backbone. """ def __init__( self, in_channels=4, hidden_size=1024, depth=28, num_heads=16, mlp_ratio=4.0, llm_cond_dim=896, cfg_dropout_prob=0.1, **kwargs, ): super().__init__()
self.in_channels = in_channels self.out_channels = in_channels self.num_heads = num_heads
self.t_embedder = TimestepEmbedder(hidden_size) self.x_embedder = nn.Linear(in_channels, hidden_size) self.c_embedder = CondEmbedder(llm_cond_dim, hidden_size, cfg_dropout_prob) self.hidden_size = hidden_size
self.rotary_embed = RotaryEmbedding(hidden_size // num_heads)
self.blocks = nn.ModuleList([ DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, **kwargs) for _ in range(depth) ]) self.final_layer = FinalLayer(hidden_size, self.out_channels) self.initialize_weights()
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w_x = self.x_embedder.weight.data nn.init.xavier_uniform_(w_x.view([w_x.shape[0], -1])) nn.init.constant_(self.x_embedder.bias, 0)
# Initialize label embedding table: w_c = self.c_embedder.cond_embedder.weight.data nn.init.xavier_uniform_(w_c.view([w_c.shape[0], -1])) nn.init.constant_(self.c_embedder.cond_embedder.bias, 0)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.time_mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.time_mlp[2].weight, std=0.02)
# Zero-out output layers: nn.init.constant_(self.final_layer.linear.weight, 0) nn.init.constant_(self.final_layer.linear.bias, 0)
def forward(self, x, t, c, latent_history, mask=None): """ Forward pass of DiT. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N,) tensor of class labels """ t = self.t_embedder(t).unsqueeze(1) # (N, D) x_now = self.x_embedder(x) #转换x_noise的维度 x_history = self.x_embedder(latent_history) #转换target history的维度 x = torch.cat([x_history, x_now], dim=1) # 拼接patch history和当前patch c = self.c_embedder(c, self.training) # (N, 1, 896) -> (N, 1, D),同时带有CFG替换操作 y = t + c x = torch.cat([y, x], dim=1) # # (N, 1 + patch_size *2, D) rope = self.rotary_embed.forward_from_seq_len(x.shape[1])
if mask is not None: mask_pad = mask.clone().detach()[:, :1].expand(-1, x_history.shape[1] + c.shape[1]) mask = torch.cat([mask_pad, mask], dim=-1) for block in self.blocks: x = block(x, mask, rope) # (N, T, D) x = self.final_layer(x) # (N, T, patch_size ** 2 * out_channels) #x = self.unpatchify(x) # (N, out_channels, H, W) return x
def forward_with_cfg(self, x, t, c, cfg_scale, latent_history, patch_size): """ Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance. """ # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb if not cfg_scale == 1: x = torch.cat([x, x], dim=0) latent_history = torch.cat([latent_history, latent_history], dim=0) fake_latent = torch.zeros(c.shape).to(c.device) c = torch.cat([c, fake_latent], dim=0) if t.ndim == 0: t = t.repeat(x.shape[0]) model_out = self.forward(x, t, c, latent_history) return model_out[:, -patch_size:, :]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import torchimport torch.nn as nn
from .dit import DiTfrom .CFM import CFMfrom .mlp import SimpleMLPAdaLN
class FlowLoss(nn.Module): """Diffusion Loss""" def __init__(self, z_channels, llm_cond_dim, flow_model_type=None, **kwargs): super(FlowLoss, self).__init__()
self.z_channels = z_channels if not flow_model_type: self.cfm = CFM( model=DiT(in_channels=z_channels, llm_cond_dim=llm_cond_dim, **kwargs) ) elif flow_model_type == "vmlp": self.cfm = CFM( model=SimpleMLPAdaLN(**kwargs) )
def forward(self, target, z, mask=None, latent_history=None, patch_size=1): loss = self.cfm(cond=z, target=target, latent_history=latent_history, mask=mask, patch_size=patch_size) return loss
def sample( self, z, latent_history, cfg=1.0, patch_size=1, sigma=0.25, temperature=0.0, steps=10, generator=None, noise_dtype=None, initial_noise_on_cpu=False, ): # diffusion loss sampling if noise_dtype is None: noise_dtype = z.dtype noise_device = torch.device("cpu") if initial_noise_on_cpu else z.device noise = torch.randn( z.shape[0], self.z_channels, patch_size, device=noise_device, dtype=noise_dtype, generator=generator, ) if initial_noise_on_cpu: # The native reference uses ``torch.randn(...).cuda()``. The random # values therefore come from the CPU RNG and are copied to CUDA; # generating them directly on CUDA changes both the values and # the CUDA RNG state for every later Flow token. noise = noise.to(device=z.device)
sampled_token_latent = self.cfm.sample( noise=noise, c=z, latent_history=latent_history, cfg_scale=cfg, patch_size=patch_size, sigma=sigma, temperature=temperature, steps=steps, generator=generator, )
return sampled_token_latent1234567891011
def is_package_available(package_name: str) -> bool: try: import importlib
package_exists = importlib.util.find_spec(package_name) is not None return package_exists except Exception: return False123456{ "temperature": 1.5, "lingv3_conditioning": "speaker_only", "lingv3_min_decode_steps": 13, "lingv3_max_decode_steps": 250}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181import torch.nn as nnimport torch
class ISTFT(nn.Module): """ Custom implementation of ISTFT since torch.istft doesn't allow custom padding (other than `center=True`) with windowing. This is because the NOLA (Nonzero Overlap Add) check fails at the edges. See issue: https://github.com/pytorch/pytorch/issues/62323 Specifically, in the context of neural vocoding we are interested in "same" padding analogous to CNNs. The NOLA constraint is met as we trim padded samples anyway.
Args: n_fft (int): Size of Fourier transform. hop_length (int): The distance between neighboring sliding window frames. win_length (int): The size of window frame and STFT filter. padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same". """
def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"): super().__init__() if padding not in ["center", "same"]: raise ValueError("Padding must be 'center' or 'same'.") self.padding = padding self.n_fft = n_fft self.hop_length = hop_length self.win_length = win_length window = torch.hann_window(win_length) self.register_buffer("window", window)
self.audio_buffer = None self.window_buffer = None self.buffer_len = self.win_length - self.hop_length
def __buffer_process(self, x, buffer, pad, last_chunk=False, streaming=False): if streaming: if buffer is None: # first chunk x = x[:, pad:] if buffer is not None: # next chunk x[:, :self.buffer_len] += buffer buffer = x[:, -self.buffer_len:] if not last_chunk: x = x[:, :-self.buffer_len] else: x = x[:, :-pad] else: x = x[:, pad:-pad]
return x, buffer
def forward( self, spec: torch.Tensor, audio_buffer=None, window_buffer=None, streaming=False, last_chunk=False ): """ Compute the Inverse Short Time Fourier Transform (ISTFT) of a complex spectrogram.
Args: spec (Tensor): Input complex spectrogram of shape (B, N, T), where B is the batch size, N is the number of frequency bins, and T is the number of time frames. audio_buffer (Tensor): [Streaming Input/State] The audio overlap buffer from the previous chunk. Shape: (B, win_length - hop_length) window_buffer (Tensor): [Streaming Input/State] The window overlap buffer from the previous chunk. streaming: If `True`, the function operates in streaming mode, processing `spec` as a single chunk. last_chunk: When `streaming=True` and `last_chunk=True`, the function can perform final "flush" operations
Returns: Tensor: Reconstructed time-domain signal of shape (B, L), where L is the length of the output signal. """ if self.padding == "center": # Fallback to pytorch native implementation return torch.istft(spec, self.n_fft, self.hop_length, self.win_length, self.window, center=True) elif self.padding == "same": pad = (self.win_length - self.hop_length) // 2 else: raise ValueError("Padding must be 'center' or 'same'.")
assert spec.dim() == 3, "Expected a 3D tensor as input" B, N, T = spec.shape
# Inverse FFT ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward") ifft = ifft * self.window[None, :, None]
# Overlap and Add output_size = (T - 1) * self.hop_length + self.win_length y = torch.nn.functional.fold( ifft, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length), )[:, 0, 0, :]
y, audio_buffer = self.__buffer_process(y, audio_buffer, pad, last_chunk=last_chunk, streaming=streaming)
# Window envelope window_sq = self.window.square().expand(1, T, -1).transpose(1, 2) window_envelope = torch.nn.functional.fold( window_sq, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length), ).squeeze(0).squeeze(0)
window_envelope, window_buffer = self.__buffer_process(window_envelope, window_buffer, pad, last_chunk=last_chunk, streaming=streaming) window_envelope = window_envelope.squeeze()
# Normalize assert (window_envelope > 1e-11).all() y = y / window_envelope
return y, audio_buffer, window_buffer
class FourierHead(nn.Module): """Base class for inverse fourier modules."""
def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x (Tensor): Input tensor of shape (B, L, H), where B is the batch size, L is the sequence length, and H denotes the model dimension.
Returns: Tensor: Reconstructed time-domain audio signal of shape (B, T), where T is the length of the output signal. """ raise NotImplementedError("Subclasses must implement the forward method.")
class ISTFTHead(FourierHead): """ ISTFT Head module for predicting STFT complex coefficients.
Args: dim (int): Hidden dimension of the model. n_fft (int): Size of Fourier transform. hop_length (int): The distance between neighboring sliding window frames, which should align with the resolution of the input features. padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same". """
def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"): super().__init__() out_dim = n_fft + 2 self.out = torch.nn.Linear(dim, out_dim) self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding)
def forward( self, x: torch.Tensor, audio_buffer=None, window_buffer=None, streaming=False, last_chunk=False ): """ Forward pass of the ISTFTHead module.
Args: x (Tensor): Input tensor of shape (B, L, H), where B is the batch size, L is the sequence length, and H denotes the model dimension.
Returns: Tensor: Reconstructed time-domain audio signal of shape (B, T), where T is the length of the output signal. """ x_pred = self.out(x ) # x_pred = x x_pred = x_pred.transpose(1, 2) mag, p = x_pred.chunk(2, dim=1) mag = torch.exp(mag) mag = torch.clip(mag, max=1e2) # safeguard to prevent excessively large magnitudes # wrapping happens here. These two lines produce real and imaginary value x = torch.cos(p) y = torch.sin(p) # recalculating phase here does not produce anything new # only costs time # phase = torch.atan2(y, x) # S = mag * torch.exp(phase * 1j) # better directly produce the complex value S = mag * (x + 1j * y) audio, audio_buffer, window_buffer = self.istft(S, audio_buffer=audio_buffer, window_buffer=window_buffer, streaming=streaming, last_chunk=last_chunk) return audio.unsqueeze(1),x_pred, audio_buffer, window_buffer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355# Author: wanren# Date: 2025/9/15from typing import Callable, Optionalimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.utils.checkpoint import checkpointimport math
# 保留原有代码的其他类和函数(SimpleMLPAdaLN, TimestepEmbedder, ResBlock, FinalLayer等)def modulate(x, shift, scale): return x * (1 + scale) + shift
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """
def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size self._freqs = None self._dim_for_freqs = None self._max_period_for_freqs = None
def freqs(self, device, dim, max_period=10000): if self._freqs is None or max_period != self._max_period_for_freqs or dim != self._dim_for_freqs: # print("Building freqs") self._dim_for_freqs = dim self._max_period_for_freqs = max_period
half = dim // 2 self._freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=device) return self._freqs
def timestep_embedding(self, t, dim, max_period=10000): """ Create sinusoidal timestep embeddings. :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an (N, D) Tensor of positional embeddings. """ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py half = dim // 2 # freqs = torch.exp( # -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half # ).to(device=t.device) args = t[:, None].float() * self.freqs(t.device, dim, max_period)[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t): t_freq = self.timestep_embedding(t, self.frequency_embedding_size) t_emb = self.mlp(t_freq) return t_emb
class SwiGLUFFN(nn.Module): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = None, drop: float = 0.0, bias: bool = True, ) -> None: super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) self.drop = nn.Dropout(drop) self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
def forward(self, x): x12 = self.w12(x) x1, x2 = x12.chunk(2, dim=-1) hidden = F.silu(x1) * x2 hidden = self.drop(hidden) return self.w3(hidden)
class SwiGLUFFNFused(SwiGLUFFN): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = None, drop: float = 0.0, bias: bool = True, ) -> None: out_features = out_features or in_features hidden_features = hidden_features or in_features hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 super().__init__( in_features=in_features, hidden_features=hidden_features, out_features=out_features, drop=drop, bias=bias, )
class ResBlock(nn.Module): """ A residual block that can optionally change the number of channels. :param channels: the number of input channels. """
def __init__( self, channels, mlp_mult=1., drop=0., ): super().__init__() self.channels = channels
self.in_ln = nn.LayerNorm(channels, eps=1e-6) # print(f"hidden feature for ResBlock: {channels * mlp_mult}") self.mlp = SwiGLUFFNFused( in_features=channels, hidden_features=int(channels * mlp_mult), drop=drop )
self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(channels, 3 * channels, bias=True) )
def forward(self, x, y): shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(y).chunk(3, dim=-1) h = modulate(self.in_ln(x), shift_mlp, scale_mlp) h = self.mlp(h) return x + gate_mlp * h
class FinalLayer(nn.Module): """ The final layer adopted from DiT. """
def __init__(self, model_channels, out_channels): super().__init__() self.norm_final = nn.LayerNorm(model_channels, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(model_channels, out_channels, bias=True) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(model_channels, 2 * model_channels, bias=True) )
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class SimpleMLPAdaLN(nn.Module): """ The MLP for Diffusion Loss. :param in_channels: channels in the input Tensor. :param model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param z_channels: channels in the condition. :param num_res_blocks: number of residual blocks per downsample. """
def __init__( self, in_channels=64, model_channels=3072, out_channels=64, z_channels=896, num_res_blocks=12, mlp_mult=4, cfg_prob=0.1, grad_checkpointing=False, is_mf=False, drop=0., ): super().__init__()
self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels self.num_res_blocks = num_res_blocks self.cfg_prob = cfg_prob self.grad_checkpointing = grad_checkpointing self.is_mf = is_mf
self.time_embed = TimestepEmbedder(model_channels) self.cond_embed = nn.Linear(z_channels, model_channels*2 if is_mf else model_channels)
self.input_proj = nn.Linear(in_channels, model_channels)
self.c_proj = nn.Sequential( nn.Linear(model_channels*2, model_channels, bias=True), nn.SiLU(), nn.Linear(model_channels, model_channels, bias=True), nn.SiLU()) if is_mf else None
res_blocks = [] for i in range(num_res_blocks): res_blocks.append(ResBlock( model_channels, mlp_mult, drop=drop, ))
self.res_blocks = nn.ModuleList(res_blocks) self.final_layer = FinalLayer(model_channels, out_channels)
self.initialize_weights()
def initialize_weights(self): def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0)
self.apply(_basic_init)
# Initialize timestep embedding MLP nn.init.normal_(self.time_embed.mlp[0].weight, std=0.02) nn.init.normal_(self.time_embed.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers for block in self.res_blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out output layers nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) nn.init.constant_(self.final_layer.linear.weight, 0) nn.init.constant_(self.final_layer.linear.bias, 0)
# def forward(self, x, t, c): # """ # Apply the model to an input batch. # :param x: an [N x C] Tensor of inputs. # :param t: a 1-D batch of timesteps. # :param c: conditioning from AR transformer. # :return: an [N x C] Tensor of outputs. # """ # # import ipdb;ipdb.set_trace() # x = self.input_proj(x) # t = self.time_embed(t) # c = self.cond_embed(c)
# y = t + c
# if self.grad_checkpointing and not torch.jit.is_scripting(): # for block in self.res_blocks: # x = checkpoint(block, x, y) # else: # for block in self.res_blocks: # x = block(x, y)
# return self.final_layer(x, y)
# 以下是SimpleMLPAdaLN的forward方法,需要适应时间步t是标量而非整数 def forward(self, x, t, c, latent_history=None, mask=None): """ Apply the model to an input batch. :param x: an [N x C] Tensor of inputs. :param t: a 1-D batch of timesteps (0 to 1). :param c: conditioning from AR transformer. :return: velocity field prediction """ x = self.input_proj(x) x_his = self.input_proj(latent_history)
if self.training and self.cfg_prob > 0: drop_cfg = torch.rand(c.shape[0]) >= self.cfg_prob drop_cfg = drop_cfg[:, None, None].to(dtype=c.dtype, device=c.device) c = c * drop_cfg c = self.cond_embed(c)
if self.is_mf: t = torch.cat([self.time_embed(t[0] * 1000), self.time_embed(t[1] * 1000)], dim=-1)[:, None] y = self.c_proj(c + t) else: t = self.time_embed(t * 1000).unsqueeze(1) y = c + t
y = y + x_his
if self.grad_checkpointing and not torch.jit.is_scripting(): for block in self.res_blocks: x = checkpoint(block, x, y, use_reentrant=True) else: for block in self.res_blocks: x = block(x, y)
return self.final_layer(x, y)
def forward_with_cfg(self, x, t, c, latent_history, spk_emb=None, **kwargs): x = torch.cat([x, x], dim=0) latent_history = torch.cat([latent_history, latent_history], dim=0) fake_latent = torch.zeros(c.shape).to(c.device) c = torch.cat([c, fake_latent], dim=0) if self.is_mf: if t[0].ndim == 0: t = (t[0].repeat(x.shape[0]), t[1].repeat(x.shape[0])) else: if t.ndim == 0: t = t.repeat(x.shape[0]) if spk_emb is not None: spk_emb = torch.cat([spk_emb, spk_emb], dim=0) model_out = self.forward(x, t, c, latent_history, spk_emb) return model_out[:, -x.shape[1]:, :]
if __name__ == "__main__": # a = RectifiedFlowLoss( # target_channels=32, # z_channels=3584, # depth=12, # width=3072, # num_sampling_steps="16", # mlp_mult=4., # grad_checkpointing=False) # num = 0 # for k, v in a.named_parameters(): # num += v.numel() # print(num) a = TimestepEmbedder(1024) print("running b") b = a(torch.rand(8, device="cpu")) print("running c") c = a(torch.rand(8, device="cpu")) print("running d") d = a(torch.rand(8, device="cpu")) print("ok")123version https://git-lfs.github.com/spec/v1oid sha256:4ca80f04a78064932cbed455aa1a4cdee352feb4f6f758b5ec76329d2455d32esize 965741912123version https://git-lfs.github.com/spec/v1oid sha256:3d18804ddcfb1a49fcbeb73c2c9f50bf61e2985e59809af1e2d4656e53e06dc2size 80331128123version https://git-lfs.github.com/spec/v1oid sha256:028350cd0d60ca1aded89a008123998ca4af4dc0e77a774f75583c5881bbbb70size 647005032123version https://git-lfs.github.com/spec/v1oid sha256:e6d57795f6ad969683d1920bbcb1e42cea760967bbf9203c52c9e8647efc48cbsize 647005032123version https://git-lfs.github.com/spec/v1oid sha256:88031f3afe410542edc79a50cf5779ee2371f8801702a11f81c9097903c4b129size 623814136123version https://git-lfs.github.com/spec/v1oid sha256:9e8d7f4b149228105f46fb41388bd7e53596e0a0a82ca1a582b34ea9383c6e29size 647005032123version https://git-lfs.github.com/spec/v1oid sha256:fa7161f8a58fd4a30ef7ad63edcffa719143787a2a7492a792ed2dd3fd34c370size 647005032123version https://git-lfs.github.com/spec/v1oid sha256:55cbb4ad1e5cdbae03bfed256c5d3207277296ff9bb00e97380dbb41bf731db3size 647005032123version https://git-lfs.github.com/spec/v1oid sha256:a0f88fe126825f6cc67551ae616256dfaf713916ab5e9983024d92ef21a506dasize 623814136123version https://git-lfs.github.com/spec/v1oid sha256:2b590fabb029f8653604ac81f0ce61f493713de6cdcefabe439014a7f0b63fc4size 647005032123version https://git-lfs.github.com/spec/v1oid sha256:9cb2183e67d5df5325a5ec4620b5a8c02dc8b204c4c32f4b0c17e220655206b1size 647005032123version https://git-lfs.github.com/spec/v1oid sha256:da309bc97964e6a591cdd66512e510013fb229ddb4b4a034e984cef917ef45a6size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:efb95b8a3dee7e647ef85a5f2d2962f6df3f077f00a9e9ca4afe50bda4a5df1asize 623814536123version https://git-lfs.github.com/spec/v1oid sha256:261794f8c9e9eae56f57485393fa0705742c680721e421d770055b5bc1a89410size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:a1dc73be7c176dafa9a4c37f494a655faeb8713ece5522736f61c10151a3a0f0size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:cb87be885c8dbe6e9a7026320702a730cf3878bd0b87dd94db4dcd451d7779d8size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:366509ff79f509a712d096357f9ac6ce4c8ea0a9904b0f2919d0c0ec16ebfbbdsize 623814536123version https://git-lfs.github.com/spec/v1oid sha256:09a3d13f4640f4a506466175b5f4313d314c20e3080d9942a521c71697aeaf77size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:a03fd3321d21b2c7c6441c5d16f4a579bddda55e2fb8847f114eaa91b085cc13size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:8f53ace8fdc9e5bf75c208a337e2d1facd2a64a083e2b7c5e50a6fe2fc64eddesize 647005432123version https://git-lfs.github.com/spec/v1oid sha256:70b7b05b20976b77733168e0a2a5abb3a605cdf5a9f0599a5548c7281de7d6bdsize 623814536123version https://git-lfs.github.com/spec/v1oid sha256:c3c7c71925ae95762bea4313f87d92ace88d9d70579081765206c4a36011f403size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:845929a1b626c78f2ddd73def10c9646846f3c30df4e5a03e53dbf800aa5f2c9size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:938b2370dd0968f5d80b92d7b9f58f6f50ce5cbad4181d509a10d66a443546f8size 647005432123version https://git-lfs.github.com/spec/v1oid sha256:4f87d70dd15509d48876ad2dfbce6cf91b91039ccee5252a92e0391ade1a4f71size 623814536123version https://git-lfs.github.com/spec/v1oid sha256:aabe4b48977064f3e5f40bf8e1ce44c36c7558facc5439904592e6a3a3bdf0adsize 1560859924.gitattributes+3
CFM.pyAdded+263
README.mdAdded+334
__init__.pyAdded+19
aggregator.pyAdded+93
campplus.onnxAdded+3
chat_template.jinjaAdded+126
config.jsonAdded+228
configuration_audio_vae.pyAdded+35
configuration_bailing_moe_v3.pyAdded+126
configuration_lingv3_tts.pyAdded+159
conversion_manifest.jsonAdded+283
dit.pyAdded+193
figures/ant-bailing.pngAdded

figures/icons/github-color.svgAdded
figures/icons/modelscope-color.svgAdded
figures/icons/technical-report.svgAdded
figures/ming-3.0-tts-tiny-architecture.pngAdded

Large File Pointer Details
- SHA256: 8ccb87480ca0d3b5a852cd69c0e4974c9330733685afc87e155fa37dd8b2d55a
- Pointer size: 131 Bytes
- Size of remote file: 630 kB
figures/ming_3.0_tts.pngAdded

Large File Pointer Details
- SHA256: 8ccb87480ca0d3b5a852cd69c0e4974c9330733685afc87e155fa37dd8b2d55a
- Pointer size: 131 Bytes
- Size of remote file: 630 kB
flowloss.pyAdded+74
fm_utils.pyAdded+11
generation_config.jsonAdded+6
istft.pyAdded+181
mlp.pyAdded+355
model-00001-of-00030.safetensorsAdded+3
model-00002-of-00030.safetensorsAdded+3
model-00003-of-00030.safetensorsAdded+3
model-00004-of-00030.safetensorsAdded+3
model-00005-of-00030.safetensorsAdded+3
model-00006-of-00030.safetensorsAdded+3
model-00007-of-00030.safetensorsAdded+3
model-00008-of-00030.safetensorsAdded+3
model-00009-of-00030.safetensorsAdded+3
model-00010-of-00030.safetensorsAdded+3
model-00011-of-00030.safetensorsAdded+3
model-00012-of-00030.safetensorsAdded+3
model-00013-of-00030.safetensorsAdded+3
model-00014-of-00030.safetensorsAdded+3
model-00015-of-00030.safetensorsAdded+3
model-00016-of-00030.safetensorsAdded+3
model-00017-of-00030.safetensorsAdded+3
model-00018-of-00030.safetensorsAdded+3
model-00019-of-00030.safetensorsAdded+3
model-00020-of-00030.safetensorsAdded+3
model-00021-of-00030.safetensorsAdded+3
model-00022-of-00030.safetensorsAdded+3
model-00023-of-00030.safetensorsAdded+3
model-00024-of-00030.safetensorsAdded+3
model-00025-of-00030.safetensorsAdded+3
model-00026-of-00030.safetensorsAdded+3