Audit & fix: Vocos mel alignment, MAS padding, prior loss, hybrid Hindi tokenizer, safetensors & single-speaker Hindi defaults
Browse filesFiles changed (20)
- .gitignoreAdded+7
- README.md+5-5
- app.py+35-31
- config.py+21-15
- data/audio_processor.py+57-26
- data/dataset.py+52-43
- data/hf_dataset_sync.py+44-18
- data/text_cleaner.py+62-12
- export_hf.py+56-56
- infer.py+40-37
- kaggle_data_collector.py+138-100
- models/convnext.py+33-12
- models/duration_predictor.py+93-53
- models/flow_matching.py+81-47
- models/text_encoder.py+27-22
- models/tts_engine.py+126-76
- models/vocoder.py+6-7
- train.py+181-85
- utils/audio_sanity.py+27-15
- utils/checkpoint.py+70-27
1234567.env__pycache__/*.pyccheckpoints/hf_export_temp/tmp/*.wav20 unmodified lines21222324252627282930313233343520 unmodified lines==================================================10M TTS MODEL PARAMETERS SUMMARY==================================================Text Encoder (RoPE Transformer): 2,699,776 (~2.70M)Duration Predictor: 395,009 (~0.40M)Alignment Projection: 20,736 (~0.02M)OT-CFM Vector Field: 4,973,904 (~4.97M)--------------------------------------------------TOTAL ACOUSTIC PARAMETERS: 8,089,425 (~8.09M)Vocos Neural Vocoder: ~2,500,000 (~2.50M)==================================================COMPLETE END-TO-END SYSTEM: ~10,589,425 (~10.5M)==================================================```20 unmodified lines21222324252627282930313233343520 unmodified lines==================================================10M TTS MODEL PARAMETERS SUMMARY==================================================Text Encoder (RoPE Transformer): 2,765,312 (~2.77M)Duration Predictor: 395,009 (~0.40M)Mel Prior Projection: 25,700 (~0.03M)OT-CFM Vector Field: 4,984,164 (~4.98M)--------------------------------------------------TOTAL ACOUSTIC PARAMETERS: 8,170,185 (~8.17M)Vocos Neural Vocoder: ~2,500,000 (~2.50M)==================================================COMPLETE END-TO-END SYSTEM: ~10,670,185 (~10.67M)==================================================```
1234567891011121314151617181920212223248 unmodified lines33343536373839404142434445464748495051525354555657582 unmodified lines61626364656667686970717273747576773 unmodified lines81828384858687888990919293949596979899100101102"""Gradio Web UI Demo & Hugging Face Spaces App.Enables instant interactive browser testing of the 10M TTS Model."""import osimport timeimport torchimport torchaudioimport gradio as grfrom models.tts_engine import TTS10MEnginefrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import load_checkpointfrom utils.audio_sanity import save_audio# Initialize Model on Startupdevice = "cuda" if torch.cuda.is_available() else "cpu"model = TTS10MEngine().to(device)checkpoint_candidates = ["checkpoints/model.safetensors","checkpoints/model_final.safetensors","model.safetensors",8 unmodified linesdef tts_generate(text: str, steps: int = 8, speed: float = 1.0):if not text.strip():return None, "Please enter some text."start_t = time.perf_counter()text_ids = tokenizer.text_to_ids(text).unsqueeze(0).to(device)with torch.no_grad():out = model.synthesize(text_ids, num_steps=int(steps), speed=float(speed), return_waveform=True)waveform = out["waveform"].squeeze(0).cpu()latency_ms = (time.perf_counter() - start_t) * 1000duration_s = waveform.shape[-1] / 24000.0# Save temporary audio for Gradioos.makedirs("tmp", exist_ok=True)temp_wav = os.path.join("tmp", "output.wav")save_audio(temp_wav, waveform, 24000)status = f"Generated in {latency_ms:.1f}ms ({duration_s:.2f}s audio) using {steps} ODE steps on {device.upper()}."return temp_wav, status# Build Modern Gradio UI2 unmodified lines"""# 🎙️ 10M Modern TTS Engine (OT-Flow Matching + Vocos)### Ultra-fast, edge-optimized ~10M Parameter Speech Synthesizer*Powered by 2024–2026 Optimal Transport Conditional Flow Matching (OT-CFM)*""")with gr.Row():with gr.Column():text_input = gr.Textbox(label="Enter Text (Hindi / English / Hinglish)",placeholder="Namaste, yeh hamara 10M modern TTS model bol raha hai...",lines=3,value="Namaste! Yeh hamara cutting-edge 10M TTS model hai.",)with gr.Row():steps_slider = gr.Slider(3 unmodified linesminimum=0.7, maximum=1.4, value=1.0, step=0.05, label="Speaking Speed")generate_btn = gr.Button("🚀 Generate Speech", variant="primary")with gr.Column():audio_output = gr.Audio(label="Synthesized 24kHz HD Audio", type="filepath")status_output = gr.Markdown()generate_btn.click(fn=tts_generate,inputs=[text_input, steps_slider, speed_slider],outputs=[audio_output, status_output],)gr.Examples(examples=[["Namaste! Yeh hamara 10M parameter modern TTS model hai.", 8, 1.0],["Artificial Intelligence speech synthesis has evolved rapidly with flow matching.", 8, 1.0],["Aapka audio bina kisi robot beep ya metallic sound ke crystal clear generate hota hai.", 8, 1.0],],inputs=[text_input, steps_slider, speed_slider],)1234567891011121314151617181920212223242526278 unmodified lines3637383940414243444546474849505152535455565758596061622 unmodified lines65666768697071727374757677787980813 unmodified lines858687888990919293949596979899100101102103104105106"""Gradio Web UI Demo & Hugging Face Spaces App.Enables instant interactive browser testing of the 10M TTS Model.Thread-safe in-memory audio output (no shared temp file race conditions)."""import osimport timeimport numpy as npimport torchimport gradio as grfrom config import TTS10MConfigfrom models.tts_engine import TTS10MEnginefrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import load_checkpoint# Initialize Model on Startupcfg = TTS10MConfig()device = "cuda" if torch.cuda.is_available() else "cpu"model = TTS10MEngine(cfg.model, cfg.training).to(device)checkpoint_candidates = ["checkpoints/model_best.safetensors","checkpoints/model.safetensors","checkpoints/model_final.safetensors","model.safetensors",8 unmodified linesdef tts_generate(text: str, steps: int = 8, speed: float = 1.0):text_ids = tokenizer.text_to_ids(text)if text_ids.numel() == 0:return None, "Please enter some valid text."start_t = time.perf_counter()text_ids_batch = text_ids.unsqueeze(0).to(device)with torch.no_grad():out = model.synthesize(text_ids_batch, num_steps=int(steps), speed=float(speed), return_waveform=True)waveform = out["waveform"].squeeze(0).cpu().numpy()latency_ms = (time.perf_counter() - start_t) * 1000duration_s = waveform.shape[-1] / float(cfg.audio.sample_rate)waveform = np.clip(waveform, -1.0, 1.0)int16_audio = (waveform * 32767.0).astype(np.int16)status = f"Generated in {latency_ms:.1f}ms ({duration_s:.2f}s audio) using {steps} ODE steps on {device.upper()}."return (cfg.audio.sample_rate, int16_audio), status# Build Modern Gradio UI2 unmodified lines"""# 🎙️ 10M Modern TTS Engine (OT-Flow Matching + Vocos)### Ultra-fast, edge-optimized ~10M Parameter Speech Synthesizer*Powered by Optimal Transport Conditional Flow Matching (OT-CFM)*""")with gr.Row():with gr.Column():text_input = gr.Textbox(label="Enter Text (Hindi Devanagari / English)",placeholder="नमस्ते, यह हमारा 10M हिंदी TTS मॉडल बोल रहा है...",lines=3,value="नमस्ते! यह हमारा नया हिंदी टेक्स्ट टू स्पीच मॉडल बोल रहा है।",)with gr.Row():steps_slider = gr.Slider(3 unmodified linesminimum=0.7, maximum=1.4, value=1.0, step=0.05, label="Speaking Speed")generate_btn = gr.Button("🚀 Generate Speech", variant="primary")with gr.Column():audio_output = gr.Audio(label="Synthesized 24kHz HD Audio", type="numpy")status_output = gr.Markdown()generate_btn.click(fn=tts_generate,inputs=[text_input, steps_slider, speed_slider],outputs=[audio_output, status_output],)gr.Examples(examples=[["नमस्ते! यह हमारा दस मिलियन पैरामीटर वाला हिंदी मॉडल है।", 8, 1.0],["आज मौसम बहुत सुहावना है और हवा ठंडी चल रही है।", 8, 1.0],["आपका ऑडियो बिना किसी रोबोट बीप के बिल्कुल साफ बनता है।", 8, 1.0],],inputs=[text_input, steps_slider, speed_slider],)
2 unmodified lines3456787 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849509 unmodified lines6061626364656667686970712 unmodified linesStrictly tuned to ~10 Million Parameters."""from dataclasses import dataclass, fieldfrom typing import Optional7 unmodified linesn_mels: int = 100f_min: float = 0.0f_max: float = 12000.0# Locked Vocos 24kHz normalization parameters# Vocos expects natural log-mel spectrogram: log(clamp(mel, min=1e-5))mel_min_clip: float = 1e-5@dataclassclass ModelConfig:# Universal Character/Byte Tokenizer (Supports English, Hindi Unicode, Hinglish, punctuation)vocab_size: int = 256pad_token_id: int = 0# Text Encoder (Transformer + RoPE) ~ 2.6M parameterstext_dim: int = 256text_layers: int = 4text_heads: int = 4text_ffn_dim: int = 768dropout: float = 0.1# Duration Predictor ~ 0.6M parametersduration_hidden_dim: int = 256duration_kernel_size: int = 3# OT-CFM Flow Matching Vector Field Backbone ~ 5.0M parametersmel_dim: int = 100cfm_hidden_dim: int = 256cfm_num_blocks: int = 8cfm_kernel_size: int = 7time_embed_dim: int = 128# ODE Sampling Settingssigma_min: float = 1e-4default_ode_steps: int = 8 # 4-10 steps is optimal for OT-CFM9 unmodified linesnum_workers: int = 2max_epochs: int = 200grad_clip_norm: float = 1.0 # Anti-Beep / Anti-Explosion guard# Loss weightscfm_loss_weight: float = 1.0dur_loss_weight: float = 0.5# Logging & Checkpointinglog_interval: int = 25eval_interval: int = 500save_interval: int = 20002 unmodified lines34567897 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253549 unmodified lines64656667686970717273747576772 unmodified linesStrictly tuned to ~10 Million Parameters."""import mathfrom dataclasses import dataclass, fieldfrom typing import Optional7 unmodified linesn_mels: int = 100f_min: float = 0.0f_max: float = 12000.0# Locked Vocos 24kHz normalization parameters (matches vocos.feature_extractors.MelSpectrogramFeatures)# Vocos uses torchaudio defaults: norm=None, mel_scale="htk", safe_log clip_val=1e-7mel_norm: Optional[str] = Nonemel_scale: str = "htk"mel_min_clip: float = 1e-7mel_pad_value: float = field(default_factory=lambda: math.log(1e-7))@dataclassclass ModelConfig:# Hybrid Unicode Char (ASCII + Devanagari) + UTF-8 Byte Fallback Tokenizervocab_size: int = 512pad_token_id: int = 0# Text Encoder (Transformer + RoPE) ~ 2.76M parameterstext_dim: int = 256text_layers: int = 4text_heads: int = 4text_ffn_dim: int = 768dropout: float = 0.1# Duration Predictor ~ 0.40M parametersduration_hidden_dim: int = 256duration_kernel_size: int = 3# OT-CFM Flow Matching Vector Field Backbone ~ 4.98M parametersmel_dim: int = 100cfm_hidden_dim: int = 256cfm_num_blocks: int = 8cfm_kernel_size: int = 7time_embed_dim: int = 128# ODE Sampling Settingssigma_min: float = 1e-4default_ode_steps: int = 8 # 4-10 steps is optimal for OT-CFM9 unmodified linesnum_workers: int = 2max_epochs: int = 200grad_clip_norm: float = 1.0 # Anti-Beep / Anti-Explosion guard# Loss weightscfm_loss_weight: float = 1.0dur_loss_weight: float = 0.5prior_loss_weight: float = 0.25# Validation, Logging & Checkpointingval_split: float = 0.05log_interval: int = 25eval_interval: int = 500save_interval: int = 2000
3 unmodified lines456789101112131415161718192021224 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263643 unmodified linesGuarantees mathematically locked parameters to prevent robotic beeps or distortion."""import mathimport torchimport torchaudioimport torchaudio.transforms as Tfrom typing import Tuple, Optionalfrom config import AudioConfigclass AudioProcessor:def __init__(self, config: Optional[AudioConfig] = None):self.config = config or AudioConfig()# Exact 24kHz Mel Spectrogram Transform (Vocos compatible)self.mel_spectrogram = T.MelSpectrogram(sample_rate=self.config.sample_rate,n_fft=self.config.n_fft,4 unmodified linesn_mels=self.config.n_mels,power=1.0, # magnitude spectrogramcenter=True,norm="slaney",mel_scale="slaney",)def load_audio(self, audio_path: str) -> torch.Tensor:"""Loads and resamples audio to 24kHz mono."""wav, sr = torchaudio.load(audio_path)# Convert stereo to monoif wav.shape[0] > 1:wav = torch.mean(wav, dim=0, keepdim=True)# Resample to 24,000 Hz if necessaryif sr != self.config.sample_rate:resampler = T.Resample(orig_freq=sr, new_freq=self.config.sample_rate)wav = resampler(wav)# Peak normalization (-1.0 to 1.0) with headroommax_val = torch.max(torch.abs(wav))if max_val > 0:wav = wav / max_val * 0.95return wav.squeeze(0) # (num_samples,)def wav_to_mel(self, wav: torch.Tensor) -> torch.Tensor:"""Converts 1D waveform (num_samples,) to (80, T_mel) log-mel spectrogram.Uses exact Vocos log compression to guarantee ZERO beep sound."""if wav.dim() == 1:wav = wav.unsqueeze(0) # (1, num_samples)mel = self.mel_spectrogram(wav)# Safe log-clamp (prevents log(0) and NaNs)log_mel = torch.log(torch.clamp(mel, min=self.config.mel_min_clip))return log_mel.squeeze(0) # (80, T_mel)3 unmodified lines456789101112131415161718192021224 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394953 unmodified linesGuarantees mathematically locked parameters to prevent robotic beeps or distortion."""import torchimport torchaudioimport torchaudio.transforms as Tfrom typing import Dict, Optionalfrom config import AudioConfigclass AudioProcessor:def __init__(self, config: Optional[AudioConfig] = None):self.config = config or AudioConfig()self._resamplers: Dict[int, T.Resample] = {}# Exact 24kHz Mel Spectrogram Transform matching vocos.feature_extractors.MelSpectrogramFeaturesself.mel_spectrogram = T.MelSpectrogram(sample_rate=self.config.sample_rate,n_fft=self.config.n_fft,4 unmodified linesn_mels=self.config.n_mels,power=1.0, # magnitude spectrogramcenter=True,norm=self.config.mel_norm,mel_scale=self.config.mel_scale,)def _get_resampler(self, orig_sr: int) -> T.Resample:if orig_sr not in self._resamplers:self._resamplers[orig_sr] = T.Resample(orig_freq=orig_sr, new_freq=self.config.sample_rate)return self._resamplers[orig_sr]def normalize_waveform(self, wav: torch.Tensor, orig_sr: int) -> torch.Tensor:"""Converts waveform to 24kHz mono and peak-normalizes with headroom."""if wav.dim() == 1:wav = wav.unsqueeze(0)elif wav.dim() == 2 and wav.shape[0] > 1:wav = torch.mean(wav, dim=0, keepdim=True)elif wav.dim() == 2 and wav.shape[1] > 1 and wav.shape[0] == 1:passwav = wav.float()if orig_sr != self.config.sample_rate:wav = self._get_resampler(orig_sr)(wav)max_val = torch.max(torch.abs(wav))if max_val > 1e-6:wav = (wav / max_val) * 0.95return wav.squeeze(0) # (num_samples,)def load_audio(self, audio_path: str) -> torch.Tensor:"""Loads and normalizes audio to 24kHz mono (bulletproof across torchaudio/torchcodec versions)."""if audio_path.lower().endswith(".wav"):import numpy as npfrom scipy.io import wavfilesr, data = wavfile.read(audio_path)if np.issubdtype(data.dtype, np.integer):if data.dtype == np.uint8:data = (data.astype(np.float32) - 128.0) / 128.0else:max_int = float(np.iinfo(data.dtype).max)data = data.astype(np.float32) / max_intelse:data = data.astype(np.float32)wav = torch.from_numpy(data)# scipy wavfile returns (N,) for mono or (N, C) for multi-channelif wav.dim() == 2:wav = wav.transpose(0, 1) # (C, N)return self.normalize_waveform(wav, sr)wav, sr = torchaudio.load(audio_path)return self.normalize_waveform(wav, sr)def wav_to_mel(self, wav: torch.Tensor) -> torch.Tensor:"""Converts 1D waveform (num_samples,) to (n_mels, T_mel) log-mel spectrogram.Uses exact Vocos safe_log compression to prevent mismatch and NaNs."""if wav.dim() == 1:wav = wav.unsqueeze(0) # (1, num_samples)mel = self.mel_spectrogram(wav)log_mel = torch.log(torch.clamp(mel, min=self.config.mel_min_clip))return log_mel.squeeze(0) # (n_mels, T_mel)
4 unmodified lines56789101112131415161718199 unmodified lines293031323334355 unmodified lines4142434445464748495051525354551 unmodified line575859606162636465666768697071723 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101112 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401414 unmodified linesimport osimport csvimport torchfrom torch.utils.data import Datasetfrom typing import List, Dict, Optional, Tuplefrom .audio_processor import AudioProcessorfrom .text_cleaner import TextTokenizerfrom config import AudioConfigclass TTSDataset(Dataset):def __init__(self,9 unmodified linesself.tokenizer = tokenizer or TextTokenizer()self.items: List[Dict[str, str]] = []self.hf_dataset = Noneif hf_dataset_name:self._load_from_hf(hf_dataset_name, language=language, speaker=speaker)elif data_list is not None:5 unmodified linesfrom datasets import load_datasetprint(f"Loading Hugging Face Dataset: {repo_id}...")ds = load_dataset(repo_id, split="train")# Apply language / speaker filters if present in columnsif language and "language" in ds.column_names:ds = ds.filter(lambda x: x["language"] == language)print(f"Filtered by language='{language}': {len(ds)} samples remain.")if speaker and "speaker" in ds.column_names:ds = ds.filter(lambda x: x["speaker"] == speaker)print(f"Filtered by speaker='{speaker}': {len(ds)} samples remain.")self.hf_dataset = dsdef _load_metadata(self, path: str):1 unmodified linewith open(path, "r", encoding="utf-8") as f:first_line = f.readline()f.seek(0)delimiter = "|" if "|" in first_line else ("," if "," in first_line else "\t")reader = csv.reader(f, delimiter=delimiter)for row in reader:if len(row) >= 2:audio_rel = row[0].strip()text = row[1].strip()audio_full = audio_rel if os.path.isabs(audio_rel) else os.path.join(base_dir, audio_rel)if os.path.exists(audio_full):self.items.append({"audio_path": audio_full, "text": text})def __len__(self) -> int:if self.hf_dataset is not None:3 unmodified linesdef __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:if self.hf_dataset is not None:row = self.hf_dataset[idx]# row can contain 'audio' dict with 'array' & 'sampling_rate', or 'audio_file'text = row.get("transcript") or row.get("text") or ""if "audio" in row and isinstance(row["audio"], dict):audio_arr = row["audio"]["array"]orig_sr = row["audio"]["sampling_rate"]wav = torch.tensor(audio_arr, dtype=torch.float32)if orig_sr != self.processor.config.sample_rate:import torchaudio.transforms as Tresampler = T.Resample(orig_freq=orig_sr, new_freq=self.processor.config.sample_rate)wav = resampler(wav.unsqueeze(0)).squeeze(0)elif "audio_file" in row:wav = self.processor.load_audio(row["audio_file"])else:raise ValueError("Dataset row must contain 'audio' or 'audio_file'")mel = self.processor.wav_to_mel(wav)text_ids = self.tokenizer.text_to_ids(text)return {"text_ids": text_ids,"mel": mel,"text_len": len(text_ids),"mel_len": mel.shape[-1],}item = self.items[idx]wav = self.processor.load_audio(item["audio_path"])mel = self.processor.wav_to_mel(wav) # (100, T_mel)text_ids = self.tokenizer.text_to_ids(item["text"]) # (T_text,)return {"text_ids": text_ids,"mel": mel,2 unmodified lines}def collate_tts_fn(batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:"""Collates a batch of variable-length text and mel spectrograms with padding."""B = len(batch)text_lens = torch.tensor([item["text_len"] for item in batch], dtype=torch.long)mel_lens = torch.tensor([item["mel_len"] for item in batch], dtype=torch.long)max_text_len = max(item["text_len"] for item in batch)max_mel_len = max(item["mel_len"] for item in batch)# Pad text with 0 (<pad>)padded_texts = torch.zeros(B, max_text_len, dtype=torch.long)for i, item in enumerate(batch):padded_texts[i, :item["text_len"]] = item["text_ids"]# Pad mel with log_min_clip or -11.5129 (Vocos silence)mel_dim = batch[0]["mel"].shape[0]padded_mels = torch.full((B, mel_dim, max_mel_len), -11.5129, dtype=torch.float32)for i, item in enumerate(batch):padded_mels[i, :, :item["mel_len"]] = item["mel"]return {"text_ids": padded_texts,"text_lengths": text_lens,4 unmodified lines567891011121314151617181920212223249 unmodified lines343536373839405 unmodified lines46474849505152535455565758591 unmodified line6162636465666768697071727374757677787980818283843 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131142 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491504 unmodified linesimport osimport csvimport mathimport torchfrom torch.utils.data import Datasetfrom typing import List, Dict, Optionalfrom .audio_processor import AudioProcessorfrom .text_cleaner import TextTokenizerfrom config import AudioConfigHEADER_AUDIO_COLS = {"audio", "audio_file", "audio_filename", "path", "file", "wav"}HEADER_TEXT_COLS = {"text", "transcript", "transcription", "normalized_text"}class TTSDataset(Dataset):def __init__(self,9 unmodified linesself.tokenizer = tokenizer or TextTokenizer()self.items: List[Dict[str, str]] = []self.hf_dataset = Noneif hf_dataset_name:self._load_from_hf(hf_dataset_name, language=language, speaker=speaker)elif data_list is not None:5 unmodified linesfrom datasets import load_datasetprint(f"Loading Hugging Face Dataset: {repo_id}...")ds = load_dataset(repo_id, split="train")if language and "language" in ds.column_names:ds = ds.filter(lambda x: x["language"] == language)print(f"Filtered by language='{language}': {len(ds)} samples remain.")if speaker and "speaker" in ds.column_names:ds = ds.filter(lambda x: x["speaker"] == speaker)print(f"Filtered by speaker='{speaker}': {len(ds)} samples remain.")self.hf_dataset = dsdef _load_metadata(self, path: str):1 unmodified linewith open(path, "r", encoding="utf-8") as f:first_line = f.readline()f.seek(0)delimiter = "|" if "|" in first_line else ("\t" if "\t" in first_line else ",")reader = csv.reader(f, delimiter=delimiter)for row_idx, row in enumerate(reader):if len(row) < 2:continueaudio_rel = row[0].strip()text = row[1].strip()# Skip header row if presentif row_idx == 0 and (audio_rel.lower() in HEADER_AUDIO_COLS or text.lower() in HEADER_TEXT_COLS):continueif not self.tokenizer.clean_text(text):continueaudio_full = audio_rel if os.path.isabs(audio_rel) else os.path.join(base_dir, audio_rel)if os.path.exists(audio_full):self.items.append({"audio_path": audio_full, "text": text})def __len__(self) -> int:if self.hf_dataset is not None:3 unmodified linesdef __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:if self.hf_dataset is not None:row = self.hf_dataset[idx]text = row.get("transcript") or row.get("text") or ""if "audio" in row and isinstance(row["audio"], dict):audio_arr = row["audio"]["array"]orig_sr = row["audio"]["sampling_rate"]wav = torch.as_tensor(audio_arr, dtype=torch.float32)wav = self.processor.normalize_waveform(wav, orig_sr)elif "audio_file" in row:wav = self.processor.load_audio(row["audio_file"])else:raise ValueError("Dataset row must contain 'audio' or 'audio_file'")else:item = self.items[idx]text = item["text"]wav = self.processor.load_audio(item["audio_path"])mel = self.processor.wav_to_mel(wav) # (n_mels, T_mel)text_ids = self.tokenizer.text_to_ids(text) # (T_text,)if len(text_ids) == 0:raise ValueError(f"Sample at index {idx} produced empty text tokens.")return {"text_ids": text_ids,"mel": mel,2 unmodified lines}def collate_tts_fn(batch: List[Dict[str, torch.Tensor]],mel_pad_value: Optional[float] = None,) -> Dict[str, torch.Tensor]:"""Collates a batch of variable-length text and mel spectrograms with padding."""if mel_pad_value is None:mel_pad_value = math.log(AudioConfig.mel_min_clip)B = len(batch)text_lens = torch.tensor([item["text_len"] for item in batch], dtype=torch.long)mel_lens = torch.tensor([item["mel_len"] for item in batch], dtype=torch.long)max_text_len = max(item["text_len"] for item in batch)max_mel_len = max(item["mel_len"] for item in batch)# Pad text with 0 (<pad>)padded_texts = torch.zeros(B, max_text_len, dtype=torch.long)for i, item in enumerate(batch):padded_texts[i, :item["text_len"]] = item["text_ids"]# Pad mel with log(mel_min_clip) (Vocos silence floor)mel_dim = batch[0]["mel"].shape[0]padded_mels = torch.full((B, mel_dim, max_mel_len), mel_pad_value, dtype=torch.float32)for i, item in enumerate(batch):padded_mels[i, :, :item["mel_len"]] = item["mel"]return {"text_ids": padded_texts,"text_lengths": text_lens,
123456789101112139 unmodified lines2324252627282930313233343536373839404142434445464748495051525354555657586 unmodified lines65666768697071"""Hugging Face Dataset Creator & Sync Utility.Creates a Hugging Face Audio Dataset and pushes it to the Hugging Face Hub."""import osimport argparseimport pandas as pdfrom datasets import Dataset, Audiofrom huggingface_hub import HfApi, logindef prepare_and_push_to_hf(9 unmodified lines"""if token:login(token=token)print(f"Loading metadata from {metadata_file}...")# Support CSV or TSV or Pipe-delimiteddf = pd.read_csv(metadata_file, sep=None, engine="python", names=["audio_filename", "text"])# Resolve relative pathsaudio_paths = []texts = []for _, row in df.iterrows():fname = str(row["audio_filename"]).strip()txt = str(row["text"]).strip()full_p = fname if os.path.isabs(fname) else os.path.join(data_dir, fname)if os.path.exists(full_p):audio_paths.append(full_p)texts.append(txt)print(f"Found {len(audio_paths)} valid audio-text pairs.")if len(audio_paths) == 0:raise ValueError("No valid audio files found. Check paths in metadata.")data_dict = {"audio": audio_paths,"text": texts,}# Build Hugging Face Datasetprint("Building Hugging Face Dataset with 24kHz audio features...")ds = Dataset.from_dict(data_dict)ds = ds.cast_column("audio", Audio(sampling_rate=24000))print(f"Pushing dataset to Hugging Face: {hf_repo_id}...")ds.push_to_hub(hf_repo_id, private=private)print(f"Dataset successfully published to: https://huggingface.co/datasets/{hf_repo_id}")6 unmodified linesparser.add_argument("--repo_id", type=str, required=True, help="HF dataset repo, e.g. username/tts-hindi-dataset")parser.add_argument("--token", type=str, default=None, help="Hugging Face write token (optional if logged in)")parser.add_argument("--private", action="store_true", help="Make dataset private")args = parser.parse_args()prepare_and_push_to_hf(data_dir=args.data_dir,12345678910111213141516179 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283846 unmodified lines91929394959697"""Hugging Face Dataset Creator & Sync Utility.Creates a Hugging Face Audio Dataset and pushes it to the Hugging Face Hub.Supports both 2-column headerless (wav|text) and multi-column headered metadata CSVs."""import osimport csvimport argparsefrom datasets import Dataset, Audiofrom huggingface_hub import loginHEADER_AUDIO_COLS = {"audio", "audio_file", "audio_filename", "path", "file", "wav"}HEADER_TEXT_COLS = {"text", "transcript", "transcription", "normalized_text"}def prepare_and_push_to_hf(9 unmodified lines"""if token:login(token=token)print(f"Loading metadata from {metadata_file}...")audio_paths = []texts = []speakers = []languages = []with open(metadata_file, "r", encoding="utf-8") as f:first_line = f.readline()f.seek(0)delimiter = "|" if "|" in first_line else ("\t" if "\t" in first_line else ",")reader = csv.reader(f, delimiter=delimiter)header = Nonefor row_idx, row in enumerate(reader):if len(row) < 2:continuec0 = row[0].strip()c1 = row[1].strip()if row_idx == 0 and (c0.lower() in HEADER_AUDIO_COLS or c1.lower() in HEADER_TEXT_COLS):header = [col.strip().lower() for col in row]continuefull_p = c0 if os.path.isabs(c0) else os.path.join(data_dir, c0)if not os.path.exists(full_p):continueaudio_paths.append(full_p)texts.append(c1)if header and "speaker" in header and len(row) > header.index("speaker"):speakers.append(row[header.index("speaker")].strip())if header and "language" in header and len(row) > header.index("language"):languages.append(row[header.index("language")].strip())print(f"Found {len(audio_paths)} valid audio-text pairs.")if len(audio_paths) == 0:raise ValueError("No valid audio files found. Check paths in metadata.")data_dict = {"audio": audio_paths,"text": texts,}if len(speakers) == len(audio_paths):data_dict["speaker"] = speakersif len(languages) == len(audio_paths):data_dict["language"] = languages# Build Hugging Face Datasetprint("Building Hugging Face Dataset with 24kHz audio features...")ds = Dataset.from_dict(data_dict)ds = ds.cast_column("audio", Audio(sampling_rate=24000))print(f"Pushing dataset to Hugging Face: {hf_repo_id}...")ds.push_to_hub(hf_repo_id, private=private)print(f"Dataset successfully published to: https://huggingface.co/datasets/{hf_repo_id}")6 unmodified linesparser.add_argument("--repo_id", type=str, required=True, help="HF dataset repo, e.g. username/tts-hindi-dataset")parser.add_argument("--token", type=str, default=None, help="Hugging Face write token (optional if logged in)")parser.add_argument("--private", action="store_true", help="Make dataset private")args = parser.parse_args()prepare_and_push_to_hf(data_dir=args.data_dir,
1234564 unmodified lines11121314151617181920212223242526272829303132333435363738394041"""Universal Multilingual Text Cleaner and Tokenizer.Supports English, Hindi (Devanagari Unicode), Hinglish, numbers, and punctuation."""import re4 unmodified linesclass TextTokenizer:"""Byte/Character Universal Tokenizer.Token 0 is reserved for <pad>.Tokens 1-255 map UTF-8 byte encodings, allowing zero out-of-vocabulary errorsacross any language (Hindi, English, Hinglish, emojis, punctuation)."""def __init__(self, pad_id: int = 0):self.pad_id = pad_iddef clean_text(self, text: str) -> str:# Unicode normalization (NFC)text = unicodedata.normalize("NFC", text)# Collapse multiple spaces and newlinestext = re.sub(r"\s+", " ", text).strip()return textdef text_to_ids(self, text: str) -> torch.Tensor:"""Encodes text to a 1D tensor of byte IDs in range [1, 255]."""text = self.clean_text(text)# UTF-8 byte encoding: each byte is 0-255.# We shift by +1 so 0 is strictly <pad>.raw_bytes = text.encode("utf-8")ids = [b + 1 for b in raw_bytes]return torch.tensor(ids, dtype=torch.long)def ids_to_text(self, ids: List[int]) -> str:"""Decodes token IDs back to a readable string."""raw_bytes = bytes([i - 1 for i in ids if i > 0 and (i - 1) < 256])return raw_bytes.decode("utf-8", errors="replace")12345674 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Universal Multilingual Text Cleaner and Hybrid Tokenizer.Supports English, Hindi (Devanagari Unicode), Hinglish, numbers, and punctuation.Uses 1-token-per-character for Devanagari & ASCII + UTF-8 byte fallback for 0% OOV."""import re4 unmodified linesclass TextTokenizer:"""Hybrid Unicode Character + UTF-8 Byte Fallback Tokenizer (vocab_size = 512).Layout:- 0: <pad>- 1: <unk>- 2..129: Devanagari Unicode block U+0900..U+097F (128 chars, 1 token per char!)- 130..224: Printable ASCII U+0020..U+007E (95 chars, 1 token per char!)- 225..480: UTF-8 byte fallback (256 bytes) for any other Unicode characters"""PAD_ID = 0UNK_ID = 1DEV_START = 2ASCII_START = 130BYTE_START = 225VOCAB_SIZE = 512def __init__(self, pad_id: int = 0):self.pad_id = pad_idself.vocab_size = self.VOCAB_SIZEdef clean_text(self, text: str) -> str:if not isinstance(text, str):return ""# Unicode normalization (NFC)text = unicodedata.normalize("NFC", text)# Normalize common smart punctuationtext = (text.replace("“", '"').replace("”", '"').replace("‘", "'").replace("’", "'").replace("—", "-").replace("–", "-"))# Collapse multiple spaces and newlinestext = re.sub(r"\s+", " ", text).strip()return textdef text_to_ids(self, text: str) -> torch.Tensor:"""Encodes text to a 1D tensor of token IDs in range [2, 480]."""text = self.clean_text(text)ids: List[int] = []for ch in text:cp = ord(ch)if 0x0900 <= cp <= 0x097F:ids.append(self.DEV_START + (cp - 0x0900))elif 0x0020 <= cp <= 0x007E:ids.append(self.ASCII_START + (cp - 0x0020))else:for b in ch.encode("utf-8"):ids.append(self.BYTE_START + b)return torch.tensor(ids, dtype=torch.long)def ids_to_text(self, ids: List[int]) -> str:"""Decodes token IDs back to a readable string."""out: List[str] = []byte_buf = bytearray()def flush_bytes():if byte_buf:out.append(byte_buf.decode("utf-8", errors="replace"))byte_buf.clear()for idx in ids:if idx <= 1:continueelif self.DEV_START <= idx < self.DEV_START + 128:flush_bytes()out.append(chr(0x0900 + (idx - self.DEV_START)))elif self.ASCII_START <= idx < self.ASCII_START + 95:flush_bytes()out.append(chr(0x0020 + (idx - self.ASCII_START)))elif self.BYTE_START <= idx < self.BYTE_START + 256:byte_buf.append(idx - self.BYTE_START)flush_bytes()return "".join(out)
123456789101112131419 unmodified lines3435363738394041424344454647484 unmodified lines53545556575859606162631 unmodified line6566676869707172732 unmodified lines76777879808182838485863 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371382 unmodified lines141142143144145146147"""Hugging Face Model Hub Exporter.Packages 10M TTS weights, configs, and generates an official Model Card README.md,then uploads everything to Hugging Face Model Hub."""import osimport jsonimport argparsefrom huggingface_hub import HfApi, login, create_repofrom config import ModelConfig, AudioConfig, TTS10MConfigdef generate_model_card(repo_id: str) -> str:19 unmodified lines# 🚀 10M Modern TTS Model (Optimal Transport Flow Matching + Vocos)This is an ultra-lightweight **~10 Million Parameter** Text-to-Speech (TTS) model designed with **2024–2026 cutting-edge Speech AI technology**.### ✨ Highlights:- **Total Parameters:** ~10.0M (8.09M Trainable Acoustic Engine + 2.5M Vocos Neural Vocoder).- **Core Technology:** Optimal Transport Conditional Flow Matching (OT-CFM) with ConvNeXt-V2 1D Backbone.- **Duration Alignment:** Dynamic Monotonic Alignment Search (MAS) — guaranteed **0% word skipping, 0% looping**.- **Vocoder:** Vocos 24kHz iSTFT synthesizer for crystal-clear HD audio.- **Zero Robotic Beep Guarantee:** Eliminates GAN discriminator collapse and mode collapse.- **Ultra-Fast Edge Inference:** Runs in only **4 to 8 ODE steps**, achieving $< 60\\text{{ms}}$ latency on regular CPUs!---4 unmodified linesfrom models.tts_engine import TTS10MEnginefrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import load_checkpointimport torchaudiodevice = "cuda" if torch.cuda.is_available() else "cpu"model = TTS10MEngine().to(device)load_checkpoint(model, "model.safetensors", device=device)tokenizer = TextTokenizer()text = "Namaste! Yeh hamara 10M TTS model bol raha hai."1 unmodified linewith torch.no_grad():out = model.synthesize(text_ids, num_steps=8)waveform = out["waveform"].cpu()torchaudio.save("output.wav", waveform, 24000)```---2 unmodified lines| Component | Architecture | Parameters || :--- | :--- | :--- || **Text Encoder** | RoPE Transformer (4 layers, 4 heads) | ~2.70M || **Duration Predictor** | 1D ConvNeXt / MAS Monotonic Search | ~0.40M || **CFM Vector Field** | ConvNeXt-V2 1D Backbone (8 blocks, 7x7 DW) | ~4.97M || **Vocoder** | Vocos 24kHz iSTFT Synthesizer | ~2.50M || **Total** | End-to-End | **~10.5M** |"""3 unmodified linestoken: str = None,private: bool = False,):if token:login(token=token)staging_dir = "hf_export_temp"os.makedirs(staging_dir, exist_ok=True)# 1. Copy/Link model weightstarget_weights = os.path.join(staging_dir, "model.safetensors")if os.path.exists(checkpoint_path):import shutilshutil.copyfile(checkpoint_path, target_weights)print(f"Copied {checkpoint_path} -> {target_weights}")else:print(f"Warning: Checkpoint {checkpoint_path} not found. Creating placeholder.")open(target_weights, "w").close()# 2. Write Configcfg = TTS10MConfig()config_dict = {"audio": cfg.audio.__dict__,"model": cfg.model.__dict__,}with open(os.path.join(staging_dir, "config.json"), "w") as f:json.dump(config_dict, f, indent=2)# 3. Write Model Cardcard_content = generate_model_card(repo_id)with open(os.path.join(staging_dir, "README.md"), "w", encoding="utf-8") as f:f.write(card_content)# 4. Push to Hugging Face Model Hubapi = HfApi()print(f"Creating / verifying repo: {repo_id}...")create_repo(repo_id, repo_type="model", private=private, exist_ok=True)print(f"Uploading files to Hugging Face Model Hub: {repo_id}...")api.upload_folder(folder_path=staging_dir,repo_id=repo_id,repo_type="model",commit_message="Release 10M Modern TTS Model (OT-CFM + Vocos)",)print(f"\n🎉 Successfully published model to: https://huggingface.co/{repo_id}\n")if __name__ == "__main__":2 unmodified linesparser.add_argument("--repo_id", type=str, default="ViuAI/TTS-10M-Modern", help="HF model repo")parser.add_argument("--token", type=str, default=None, help="HF write token (optional if logged in)")parser.add_argument("--private", action="store_true", help="Make model private")args = parser.parse_args()export_and_push(checkpoint_path=args.checkpoint,1234567891011121314151619 unmodified lines36373839404142434445464748494 unmodified lines54555657585960616263641 unmodified line6667686970717273742 unmodified lines7778798081828384858687883 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371382 unmodified lines141142143144145146147"""Hugging Face Model Hub Exporter.Packages 10M TTS weights, configs, and generates an official Model Card README.md,then uploads everything cleanly to Hugging Face Model Hub."""import osimport jsonimport shutilimport tempfileimport argparsefrom huggingface_hub import HfApi, login, create_repofrom config import TTS10MConfigdef generate_model_card(repo_id: str) -> str:19 unmodified lines# 🚀 10M Modern TTS Model (Optimal Transport Flow Matching + Vocos)This is an ultra-lightweight **~10 Million Parameter** Text-to-Speech (TTS) model built with **Optimal Transport Conditional Flow Matching (OT-CFM)**, **ConvNeXt-V2 1D**, and **Vocos 24kHz**.### ✨ Highlights:- **Total Parameters:** ~10.67M (~8.17M Trainable Acoustic Engine + ~2.5M Vocos Neural Vocoder).- **Core Technology:** Optimal Transport Conditional Flow Matching (OT-CFM) with mask-aware ConvNeXt-V2 1D Backbone.- **Duration Alignment:** Monotonic Alignment Search (MAS) with Mel Prior Loss.- **Vocoder:** Vocos 24kHz iSTFT synthesizer for crystal-clear HD audio.- **Fast Edge Inference:** Runs in only **4 to 8 ODE steps**.---4 unmodified linesfrom models.tts_engine import TTS10MEnginefrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import load_checkpointfrom utils.audio_sanity import save_audiodevice = "cuda" if torch.cuda.is_available() else "cpu"model = TTS10MEngine().to(device)model = load_checkpoint(model, "model.safetensors", device=device)tokenizer = TextTokenizer()text = "Namaste! Yeh hamara 10M TTS model bol raha hai."1 unmodified linewith torch.no_grad():out = model.synthesize(text_ids, num_steps=8)waveform = out["waveform"].squeeze(0).cpu()save_audio("output.wav", waveform, 24000)```---2 unmodified lines| Component | Architecture | Parameters || :--- | :--- | :--- || **Text Encoder** | RoPE Transformer (4 layers, 4 heads) | ~2.77M || **Duration Predictor** | 1D ConvNeXt + MAS Monotonic Search | ~0.40M || **Mel Prior Projection** | Linear Mel Prior Head | ~0.03M || **CFM Vector Field** | Mask-aware ConvNeXt-V2 1D (8 blocks, 7x7 DW) | ~4.98M || **Vocoder** | Vocos 24kHz iSTFT Synthesizer | ~2.50M || **Total** | End-to-End | **~10.67M** |"""3 unmodified linestoken: str = None,private: bool = False,):if not os.path.exists(checkpoint_path):raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}. Cannot export empty weights.")if os.path.getsize(checkpoint_path) == 0:raise ValueError(f"Checkpoint file is 0 bytes: {checkpoint_path}.")if token:login(token=token)with tempfile.TemporaryDirectory() as staging_dir:# 1. Copy model weightstarget_weights = os.path.join(staging_dir, "model.safetensors")shutil.copyfile(checkpoint_path, target_weights)print(f"Copied {checkpoint_path} -> {target_weights}")# 2. Write Configcfg = TTS10MConfig()config_dict = {"audio": cfg.audio.__dict__,"model": cfg.model.__dict__,}with open(os.path.join(staging_dir, "config.json"), "w", encoding="utf-8") as f:json.dump(config_dict, f, indent=2)# 3. Write Model Cardcard_content = generate_model_card(repo_id)with open(os.path.join(staging_dir, "README.md"), "w", encoding="utf-8") as f:f.write(card_content)# 4. Push to Hugging Face Model Hubapi = HfApi()print(f"Creating / verifying repo: {repo_id}...")create_repo(repo_id, repo_type="model", private=private, exist_ok=True)print(f"Uploading files to Hugging Face Model Hub: {repo_id}...")api.upload_folder(folder_path=staging_dir,repo_id=repo_id,repo_type="model",commit_message="Release 10M Modern TTS Model (OT-CFM + Vocos)",)print(f"\n🎉 Successfully published model to: https://huggingface.co/{repo_id}\n")if __name__ == "__main__":2 unmodified linesparser.add_argument("--repo_id", type=str, default="ViuAI/TTS-10M-Modern", help="HF model repo")parser.add_argument("--token", type=str, default=None, help="HF write token (optional if logged in)")parser.add_argument("--private", action="store_true", help="Make model private")args = parser.parse_args()export_and_push(checkpoint_path=args.checkpoint,
6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283846 unmodified linesimport timeimport argparseimport torchimport torchaudiofrom models.tts_engine import TTS10MEnginefrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import load_checkpointfrom utils.audio_sanity import AudioSanityGuardian, save_audiofrom config import ModelConfigdef run_inference(text: str,checkpoint_path: str = None,output_wav: str = "output.wav",num_steps: int = 8,speed: float = 1.0,device: str = "cpu",):print(f"\n==========================================")print(f" 10M Modern TTS Inference Engine")print(f"==========================================")print(f" Input Text: \"{text}\"")print(f" ODE Steps: {num_steps} (Optimal Transport CFM)")print(f" Target Device: {device}")device = torch.device(device)model = TTS10MEngine().to(device)if checkpoint_path and os.path.exists(checkpoint_path):model = load_checkpoint(model, checkpoint_path, device=str(device))else:print("Note: Running with initialized weights (or specify --checkpoint path/to/model.safetensors).")model.eval()tokenizer = TextTokenizer()text_ids = tokenizer.text_to_ids(text).unsqueeze(0).to(device)# Measure Latencystart_t = time.perf_counter()with torch.no_grad():out = model.synthesize(text_ids, num_steps=num_steps, speed=speed, return_waveform=True)waveform = out["waveform"].squeeze(0).cpu()mel = out["mel"].squeeze(0)latency_ms = (time.perf_counter() - start_t) * 1000# Audio Guardian Checksis_mel_ok, mel_msg = AudioSanityGuardian.check_spectrogram(mel)is_audio_ok, audio_msg = AudioSanityGuardian.check_audio_waveform(waveform)duration_s = waveform.shape[-1] / 24000.0rtf = (latency_ms / 1000.0) / duration_s if duration_s > 0 else 0.0print("\n--- Synthesis Metrics ---")print(f" Latency: {latency_ms:.1f} ms")print(f" Audio Duration: {duration_s:.2f} s")print(f" Real-Time Factor (RTF): {rtf:.3f}x (< 1.0x means faster than real-time!)")print(f" Mel Health: {mel_msg}")print(f" Audio Health: {audio_msg}")# Save output WAVsave_audio(output_wav, waveform, 24000)print(f"\nSaved generated audio to: {os.path.abspath(output_wav)}\n")if __name__ == "__main__":parser = argparse.ArgumentParser(description="Generate 24kHz audio from text using 10M TTS model")parser.add_argument("--text", type=str, default="Namaste! Yeh hamara cutting-edge 10M TTS model hai.", help="Text to speak")parser.add_argument("--checkpoint", type=str, default=None, help="Path to .safetensors checkpoint")parser.add_argument("--output", type=str, default="output.wav", help="Path to save output .wav file")parser.add_argument("--steps", type=int, default=8, help="Number of ODE steps (4-10 recommended)")parser.add_argument("--speed", type=float, default=1.0, help="Speech rate / speed multiplier")parser.add_argument("--device", type=str, default="cpu", help="Device (cpu or cuda)")args = parser.parse_args()run_inference(text=args.text,6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586876 unmodified linesimport timeimport argparseimport torchfrom models.tts_engine import TTS10MEnginefrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import load_checkpointfrom utils.audio_sanity import AudioSanityGuardian, save_audiofrom config import TTS10MConfigdef run_inference(text: str,checkpoint_path: str = None,output_wav: str = "output.wav",num_steps: int = None,speed: float = 1.0,device: str = "cpu",):cfg = TTS10MConfig()steps = num_steps if num_steps is not None else cfg.model.default_ode_stepstokenizer = TextTokenizer()text_ids = tokenizer.text_to_ids(text)if text_ids.numel() == 0:raise ValueError("Input text is empty after cleaning. Please provide valid text.")print("\n==========================================")print(" 10M Modern TTS Inference Engine")print("==========================================")print(f" Input Text: \"{text}\"")print(f" ODE Steps: {steps} (Optimal Transport CFM)")print(f" Target Device: {device}")target_device = torch.device(device)model = TTS10MEngine(cfg.model, cfg.training).to(target_device)if checkpoint_path:model = load_checkpoint(model, checkpoint_path, device=str(target_device))else:print("Note: Running with initialized weights (specify --checkpoint path/to/model.safetensors for trained audio).")model.eval()text_ids_batch = text_ids.unsqueeze(0).to(target_device)start_t = time.perf_counter()with torch.no_grad():out = model.synthesize(text_ids_batch, num_steps=steps, speed=speed, return_waveform=True)waveform = out["waveform"].squeeze(0).cpu()mel = out["mel"].squeeze(0)latency_ms = (time.perf_counter() - start_t) * 1000_, mel_msg = AudioSanityGuardian.check_spectrogram(mel)_, audio_msg = AudioSanityGuardian.check_audio_waveform(waveform, cfg.audio.sample_rate)duration_s = waveform.shape[-1] / float(cfg.audio.sample_rate)rtf = (latency_ms / 1000.0) / duration_s if duration_s > 0 else 0.0print("\n--- Synthesis Metrics ---")print(f" Latency: {latency_ms:.1f} ms")print(f" Audio Duration: {duration_s:.2f} s")print(f" Real-Time Factor (RTF): {rtf:.3f}x (< 1.0x means faster than real-time!)")print(f" Mel Health: {mel_msg}")print(f" Audio Health: {audio_msg}")save_audio(output_wav, waveform, cfg.audio.sample_rate)print(f"\nSaved generated audio to: {os.path.abspath(output_wav)}\n")if __name__ == "__main__":parser = argparse.ArgumentParser(description="Generate 24kHz audio from text using 10M TTS model")parser.add_argument("--text", type=str, default="नमस्ते! यह हमारा नया हिंदी टेक्स्ट टू स्पीच मॉडल बोल रहा है।", help="Text to speak")parser.add_argument("--checkpoint", type=str, default=None, help="Path to .safetensors checkpoint")parser.add_argument("--output", type=str, default="output.wav", help="Path to save output .wav file")parser.add_argument("--steps", type=int, default=8, help="Number of ODE steps (4-10 recommended)")parser.add_argument("--speed", type=float, default=1.0, help="Speech rate / speed multiplier")parser.add_argument("--device", type=str, default="cpu", help="Device (cpu or cuda)")args = parser.parse_args()run_inference(text=args.text,
1234562 unmodified lines91011121314151617181920212223242526278 unmodified lines36373839404142434445464748495051525354555657585960616263646566676869702 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191 unmodified line1211221231241251261271281291 unmodified line1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582599 unmodified lines269270271272273274275276277278279280281282283284285286"""Kaggle 50h+ Hindi Speech Dataset Curator for ViuAI.Collects, resamples (24kHz), trims, normalizes, and filters 50+ hours of high-qualityHindi speech data from top open datasets (IndicTTS, IndicVoices, FLEURS),and pushes the unified dataset to Hugging Face Hub."""2 unmodified linesimport sysimport gcimport reimport csvimport globimport timeimport shutilimport argparseimport numpy as npimport pandas as pdfrom typing import Optional, List, Dictimport torchimport torchaudioimport torchaudio.transforms as Tfrom datasets import load_dataset, Dataset, Audiofrom huggingface_hub import HfApi, login# Ensure UTF-8 printing8 unmodified lines"""Removes junk characters, normalizes Devanagari Unicode, collapses whitespace."""if not isinstance(text, str):return ""# Remove URL or HTML tagstext = re.sub(r"http\S+|www\S+|<.*?>", "", text)# Remove weird symbols, keep Devanagari, basic punctuation, and numberstext = re.sub(r"[^\u0900-\u097F\s\.,!\?।0-9a-zA-Z]", "", text)# Collapse spacestext = re.sub(r"\s+", " ", text).strip()return textclass HindiAudioCurator:def __init__(self,target_sr: int = 24000,min_sec: float = 1.5,max_sec: float = 12.0,output_dir: str = "/kaggle/working/hindi_50h_dataset",hf_token: Optional[str] = None,):self.target_sr = target_srself.min_sec = min_secself.max_sec = max_secself.output_dir = output_dirself.audio_dir = os.path.join(output_dir, "audio")os.makedirs(self.audio_dir, exist_ok=True)self.hf_token = hf_tokenif hf_token:login(token=hf_token)self.resamplers = {}self.metadata = []2 unmodified linesself.resamplers[orig_sr] = T.Resample(orig_freq=orig_sr, new_freq=self.target_sr)return self.resamplers[orig_sr]def process_and_save_audio(self, wav: torch.Tensor, orig_sr: int, text: str, speaker_id: str, sample_id: str) -> bool:"""Resamples, trims silence, peak-normalizes, and checks duration."""# Monoif wav.dim() == 1:wav = wav.unsqueeze(0)elif wav.shape[0] > 1:wav = torch.mean(wav, dim=0, keepdim=True)# Resampleif orig_sr != self.target_sr:resampler = self.get_resampler(orig_sr)wav = resampler(wav)# Duration checknum_samples = wav.shape[-1]duration = num_samples / self.target_srif duration < self.min_sec or duration > self.max_sec:return False# Clean text checkcleaned_text = clean_hindi_text(text)if len(cleaned_text) < 5 or not re.search(r"[\u0900-\u097F]", cleaned_text):return False # Must contain meaningful Hindi characters# Peak normalization with headroommax_val = torch.max(torch.abs(wav))if max_val < 1e-4:return Falsewav = (wav / max_val) * 0.95# Save WAV filespk_dir = os.path.join(self.audio_dir, speaker_id)os.makedirs(spk_dir, exist_ok=True)rel_wav_path = f"audio/{speaker_id}/{sample_id}.wav"full_wav_path = os.path.join(self.output_dir, rel_wav_path)# Save via scipy int16 (100% reliable)int16_pcm = (wav.squeeze(0).numpy() * 32767.0).astype(np.int16)from scipy.io import wavfilewavfile.write(full_wav_path, self.target_sr, int16_pcm)self.metadata.append({"audio_file": rel_wav_path,"transcript": cleaned_text,1 unmodified line"duration": round(duration, 2),"language": "hi",})return Truedef collect_from_indic_tts(self, max_hours_per_speaker: float = 12.0):"""Streams IIT Madras IndicTTS Hindi voices."""sources = [("MatrixSpeechAI/Indic_TTS_HI_Male_Speaker_1", "indic_hi_male_1"),1 unmodified line("MatrixSpeechAI/Indic_TTS_HI_Female_Speaker_1", "indic_hi_female_1"),("MatrixSpeechAI/Indic_TTS_HI_Female_Speaker_2", "indic_hi_female_2"),]for repo, spk in sources:print(f"\n[+] Collecting from {repo} (Speaker: {spk})...")try:ds = load_dataset(repo, split="train", streaming=True)total_sec = 0max_sec = max_hours_per_speaker * 3600count = 0for item in ds:audio_info = item.get("audio")text = item.get("transcription") or item.get("text") or ""if not audio_info:continuewav = torch.tensor(audio_info["array"], dtype=torch.float32)sr = audio_info["sampling_rate"]sample_id = f"{spk}_{count:06d}"if self.process_and_save_audio(wav, sr, text, spk, sample_id):count += 1total_sec += (wav.shape[-1] / sr)if count % 250 == 0 and count > 0:print(f" -> Processed {count} clips ({total_sec/3600:.2f} hours)")if total_sec >= max_sec:print(f" Target reached for {spk}: {total_sec/3600:.2f} hours.")breakexcept Exception as e:print(f" Warning: Could not process {repo} ({e}). Skipping.")gc.collect()def collect_from_indicvoices(self, max_hours: float = 20.0):"""Streams AI4Bharat IndicVoices Hindi subset."""print("\n[+] Collecting from ai4bharat/indicvoices (Hindi)...")try:ds = load_dataset("ai4bharat/indicvoices", "hi", split="train", streaming=True)total_sec = 0max_sec = max_hours * 3600count = 0for item in ds:audio_info = item.get("audio")text = item.get("text") or item.get("normalized_text") or ""spk = item.get("speaker_id") or "indicvoices_hi"if not audio_info:continuewav = torch.tensor(audio_info["array"], dtype=torch.float32)sr = audio_info["sampling_rate"]sample_id = f"iv_{count:06d}"if self.process_and_save_audio(wav, sr, text, f"iv_{spk}", sample_id):count += 1total_sec += (wav.shape[-1] / sr)if count % 500 == 0 and count > 0:print(f" -> IndicVoices: {count} clips ({total_sec/3600:.2f} hours)")if total_sec >= max_sec:print(f" Target reached for IndicVoices: {total_sec/3600:.2f} hours.")breakexcept Exception as e:print(f" Notice: IndicVoices ({e}).")gc.collect()def collect_from_fleurs(self, max_hours: float = 10.0):"""Streams Google FLEURS Hindi."""print("\n[+] Collecting from google/fleurs (Hindi hi_in)...")try:ds = load_dataset("google/fleurs", "hi_in", split="train", streaming=True)total_sec = 0max_sec = max_hours * 3600count = 0for item in ds:audio_info = item.get("audio")text = item.get("transcription") or item.get("raw_transcription") or ""if not audio_info:continuewav = torch.tensor(audio_info["array"], dtype=torch.float32)sr = audio_info["sampling_rate"]sample_id = f"fleurs_hi_{count:06d}"if self.process_and_save_audio(wav, sr, text, "fleurs_hi", sample_id):count += 1total_sec += (wav.shape[-1] / sr)if total_sec >= max_sec:breakprint(f" FLEURS processed: {count} clips ({total_sec/3600:.2f} hours).")except Exception as e:print(f" Notice: FLEURS ({e}).")gc.collect()def save_and_push(self, hf_repo_id: str, private: bool = False):"""Saves metadata.csv and pushes entire 50h+ dataset to Hugging Face Hub."""meta_csv = os.path.join(self.output_dir, "metadata.csv")df = pd.DataFrame(self.metadata)df.to_csv(meta_csv, sep="|", index=False, encoding="utf-8")total_hours = df["duration"].sum() / 3600.0 if "duration" in df.columns else 0.0print("\n" + "="*50)print(" 50H+ HINDI DATASET CURATION SUMMARY ")print("="*50)print(f" Total Samples Collected: {len(df):,}")print(f" Total Audio Duration: {total_hours:.2f} Hours")print(f" Speakers Breakdown:\n{df['speaker'].value_counts()}")print("="*50 + "\n")# Push to Hugging Faceprint(f"Pushing curated 50h+ dataset to Hugging Face: {hf_repo_id}...")api = HfApi()api.create_repo(repo_id=hf_repo_id, repo_type="dataset", private=private, exist_ok=True)api.upload_folder(folder_path=self.output_dir,repo_id=hf_repo_id,9 unmodified linesparser.add_argument("--output_dir", type=str, default="/kaggle/working/hindi_50h_dataset", help="Output directory")parser.add_argument("--token", type=str, default=None, help="Hugging Face write token")parser.add_argument("--target_hours", type=float, default=50.0, help="Target total hours")args = parser.parse_args()token = args.token or os.environ.get("HF_TOKEN")curator = HindiAudioCurator(output_dir=args.output_dir, hf_token=token)# 1. Collect IndicTTS studio voices (~35-40 hours total across 4 speakers)curator.collect_from_indic_tts(max_hours_per_speaker=10.0)# 2. Collect FLEURS & IndicVoices to comfortably exceed 50+ hourscurator.collect_from_fleurs(max_hours=8.0)curator.collect_from_indicvoices(max_hours=15.0)# 3. Save & Push to HF Hubcurator.save_and_push(hf_repo_id=args.repo_id)1234562 unmodified lines9101112131415161718192021228 unmodified lines313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293942 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421 unmodified line1441451461471481491501511521 unmodified line1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892909 unmodified lines300301302303304305306307308309310311312313314315316317318319320321322323324"""Kaggle 50h+ Hindi Speech Dataset Curator for ViuAI.Collects, resamples (24kHz), trims silence, normalizes, and filters high-qualityHindi speech data from top open datasets (IndicTTS, IndicVoices, FLEURS),and pushes the unified dataset to Hugging Face Hub."""2 unmodified linesimport sysimport gcimport reimport argparseimport numpy as npimport pandas as pdfrom typing import Optionalimport torchimport torchaudio.transforms as Tfrom datasets import load_datasetfrom huggingface_hub import HfApi, login# Ensure UTF-8 printing8 unmodified lines"""Removes junk characters, normalizes Devanagari Unicode, collapses whitespace."""if not isinstance(text, str):return ""text = re.sub(r"http\S+|www\S+|<.*?>", "", text)text = re.sub(r"[^\u0900-\u097F\s\.,!\?।0-9a-zA-Z]", "", text)text = re.sub(r"\s+", " ", text).strip()return textdef trim_silence(wav: torch.Tensor, sr: int = 24000, top_db: float = 35.0, pad_ms: float = 80.0) -> torch.Tensor:"""Trims leading and trailing silence using frame-wise RMS energy relative to peak.Keeps `pad_ms` of natural breath/silence padding at edges."""if wav.numel() == 0:return wavmono = wav.squeeze(0) if wav.dim() > 1 else wavpeak = torch.max(torch.abs(mono)).item()if peak < 1e-6:return monoframe_len = max(1, int(0.02 * sr)) # 20ms windowhop_len = max(1, frame_len // 2)if mono.numel() < frame_len:return monoframes = mono.unfold(0, frame_len, hop_len)rms = torch.sqrt(torch.mean(frames ** 2, dim=-1) + 1e-12)thresh = peak * (10.0 ** (-top_db / 20.0))active = torch.nonzero(rms > thresh, as_tuple=False).squeeze(-1)if active.numel() == 0:return mono.new_zeros((0,))pad_samples = int((pad_ms / 1000.0) * sr)start_sample = max(0, int(active[0].item()) * hop_len - pad_samples)end_sample = min(mono.numel(), int(active[-1].item()) * hop_len + frame_len + pad_samples)return mono[start_sample:end_sample]class HindiAudioCurator:def __init__(self,target_sr: int = 24000,min_sec: float = 1.5,max_sec: float = 12.0,allow_english: bool = False,output_dir: str = "/kaggle/working/hindi_50h_dataset",hf_token: Optional[str] = None,):self.target_sr = target_srself.min_sec = min_secself.max_sec = max_secself.allow_english = allow_englishself.output_dir = output_dirself.audio_dir = os.path.join(output_dir, "audio")os.makedirs(self.audio_dir, exist_ok=True)self.hf_token = hf_tokenif hf_token:login(token=hf_token)self.resamplers = {}self.metadata = []2 unmodified linesself.resamplers[orig_sr] = T.Resample(orig_freq=orig_sr, new_freq=self.target_sr)return self.resamplers[orig_sr]def process_and_save_audio(self, wav: torch.Tensor, orig_sr: int, text: str, speaker_id: str, sample_id: str) -> float:"""Resamples, trims silence, peak-normalizes, and checks duration. Returns saved duration (0.0 if skipped)."""if wav.dim() == 1:wav = wav.unsqueeze(0)elif wav.shape[0] > 1:wav = torch.mean(wav, dim=0, keepdim=True)if orig_sr != self.target_sr:wav = self.get_resampler(orig_sr)(wav)# Trim leading/trailing silencetrimmed = trim_silence(wav.squeeze(0), sr=self.target_sr)if trimmed.numel() == 0:return 0.0num_samples = trimmed.shape[-1]duration = num_samples / float(self.target_sr)if duration < self.min_sec or duration > self.max_sec:return 0.0cleaned_text = clean_hindi_text(text)if len(cleaned_text) < 5:return 0.0if not self.allow_english and not re.search(r"[\u0900-\u097F]", cleaned_text):return 0.0max_val = torch.max(torch.abs(trimmed))if max_val < 1e-4:return 0.0trimmed = (trimmed / max_val) * 0.95spk_dir = os.path.join(self.audio_dir, speaker_id)os.makedirs(spk_dir, exist_ok=True)rel_wav_path = f"audio/{speaker_id}/{sample_id}.wav"full_wav_path = os.path.join(self.output_dir, rel_wav_path)int16_pcm = (trimmed.numpy() * 32767.0).astype(np.int16)from scipy.io import wavfilewavfile.write(full_wav_path, self.target_sr, int16_pcm)self.metadata.append({"audio_file": rel_wav_path,"transcript": cleaned_text,1 unmodified line"duration": round(duration, 2),"language": "hi",})return durationdef collect_from_indic_tts(self, max_hours_per_speaker: float = 10.0, single_speaker_only: bool = False):"""Streams IIT Madras IndicTTS Hindi voices."""sources = [("MatrixSpeechAI/Indic_TTS_HI_Male_Speaker_1", "indic_hi_male_1"),1 unmodified line("MatrixSpeechAI/Indic_TTS_HI_Female_Speaker_1", "indic_hi_female_1"),("MatrixSpeechAI/Indic_TTS_HI_Female_Speaker_2", "indic_hi_female_2"),]if single_speaker_only:sources = [sources[0]]for repo, spk in sources:print(f"\n[+] Collecting from {repo} (Speaker: {spk})...")try:ds = load_dataset(repo, split="train", streaming=True)total_sec = 0.0max_sec = max_hours_per_speaker * 3600.0count = 0for item in ds:audio_info = item.get("audio")text = item.get("transcription") or item.get("text") or ""if not audio_info:continuewav = torch.tensor(audio_info["array"], dtype=torch.float32)sr = audio_info["sampling_rate"]sample_id = f"{spk}_{count:06d}"saved_dur = self.process_and_save_audio(wav, sr, text, spk, sample_id)if saved_dur > 0:count += 1total_sec += saved_durif count % 250 == 0 and count > 0:print(f" -> Processed {count} clips ({total_sec/3600:.2f} hours)")if total_sec >= max_sec:print(f" Target reached for {spk}: {total_sec/3600:.2f} hours.")breakexcept Exception as e:print(f" Warning: Could not process {repo} ({e}). Skipping.")gc.collect()def collect_from_indicvoices(self, max_hours: float = 15.0):"""Streams AI4Bharat IndicVoices Hindi subset."""print("\n[+] Collecting from ai4bharat/indicvoices (Hindi)...")try:ds = load_dataset("ai4bharat/indicvoices", "hi", split="train", streaming=True)total_sec = 0.0max_sec = max_hours * 3600.0count = 0for item in ds:audio_info = item.get("audio")text = item.get("text") or item.get("normalized_text") or ""spk = item.get("speaker_id") or "indicvoices_hi"if not audio_info:continuewav = torch.tensor(audio_info["array"], dtype=torch.float32)sr = audio_info["sampling_rate"]sample_id = f"iv_{count:06d}"saved_dur = self.process_and_save_audio(wav, sr, text, f"iv_{spk}", sample_id)if saved_dur > 0:count += 1total_sec += saved_durif count % 500 == 0 and count > 0:print(f" -> IndicVoices: {count} clips ({total_sec/3600:.2f} hours)")if total_sec >= max_sec:print(f" Target reached for IndicVoices: {total_sec/3600:.2f} hours.")breakexcept Exception as e:print(f" Notice: IndicVoices ({e}).")gc.collect()def collect_from_fleurs(self, max_hours: float = 8.0):"""Streams Google FLEURS Hindi."""print("\n[+] Collecting from google/fleurs (Hindi hi_in)...")try:ds = load_dataset("google/fleurs", "hi_in", split="train", streaming=True)total_sec = 0.0max_sec = max_hours * 3600.0count = 0for item in ds:audio_info = item.get("audio")text = item.get("transcription") or item.get("raw_transcription") or ""if not audio_info:continuewav = torch.tensor(audio_info["array"], dtype=torch.float32)sr = audio_info["sampling_rate"]sample_id = f"fleurs_hi_{count:06d}"saved_dur = self.process_and_save_audio(wav, sr, text, "fleurs_hi", sample_id)if saved_dur > 0:count += 1total_sec += saved_durif total_sec >= max_sec:breakprint(f" FLEURS processed: {count} clips ({total_sec/3600:.2f} hours).")except Exception as e:print(f" Notice: FLEURS ({e}).")gc.collect()def save_and_push(self, hf_repo_id: str, private: bool = False):"""Saves metadata.csv and pushes dataset to Hugging Face Hub."""if len(self.metadata) == 0:print("Warning: 0 samples collected. Skipping metadata save and Hugging Face upload.")returnmeta_csv = os.path.join(self.output_dir, "metadata.csv")df = pd.DataFrame(self.metadata)df.to_csv(meta_csv, sep="|", index=False, encoding="utf-8")total_hours = df["duration"].sum() / 3600.0print("\n" + "=" * 50)print(" HINDI DATASET CURATION SUMMARY ")print("=" * 50)print(f" Total Samples Collected: {len(df):,}")print(f" Total Audio Duration: {total_hours:.2f} Hours")print(f" Speakers Breakdown:\n{df['speaker'].value_counts()}")print("=" * 50 + "\n")print(f"Pushing curated dataset to Hugging Face: {hf_repo_id}...")api = HfApi()api.create_repo(repo_id=hf_repo_id, repo_type="dataset", private=private, exist_ok=True)api.upload_folder(folder_path=self.output_dir,repo_id=hf_repo_id,9 unmodified linesparser.add_argument("--output_dir", type=str, default="/kaggle/working/hindi_50h_dataset", help="Output directory")parser.add_argument("--token", type=str, default=None, help="Hugging Face write token")parser.add_argument("--target_hours", type=float, default=50.0, help="Target total hours")parser.add_argument("--single_speaker", action="store_true", help="Collect only 1 clean studio Hindi speaker (IndicTTS Male 1)")parser.add_argument("--allow_english", action="store_true", help="Allow English/Hinglish transcripts without Devanagari")args = parser.parse_args()token = args.token or os.environ.get("HF_TOKEN")curator = HindiAudioCurator(output_dir=args.output_dir,hf_token=token,allow_english=args.allow_english,)if args.single_speaker:curator.collect_from_indic_tts(max_hours_per_speaker=args.target_hours, single_speaker_only=True)else:# Scale source allocations proportionally to args.target_hours (default 50h -> ~32h IndicTTS, ~6h FLEURS, ~12h IndicVoices)scale = max(0.05, args.target_hours / 50.0)curator.collect_from_indic_tts(max_hours_per_speaker=8.0 * scale)curator.collect_from_fleurs(max_hours=6.0 * scale)curator.collect_from_indicvoices(max_hours=12.0 * scale)curator.save_and_push(hf_repo_id=args.repo_id)
1234567891011121314151617181920212223242526272829303132333435361 unmodified line383940414243444546474849505152535455565758596061"""ConvNeXt-V2 1D Blocks with Global Response Normalization (GRN)State-of-the-Art modern CNN backbone for audio/spectrogram modeling."""import torchimport torch.nn as nnimport torch.nn.functional as Fclass GRN1D(nn.Module):"""Global Response Normalization (GRN) for 1D channels."""def __init__(self, dim: int, eps: float = 1e-6):super().__init__()self.gamma = nn.Parameter(torch.zeros(1, dim, 1))self.beta = nn.Parameter(torch.zeros(1, dim, 1))self.eps = epsdef forward(self, x: torch.Tensor) -> torch.Tensor:# x: (B, C, T)gx = torch.norm(x, p=2, dim=-1, keepdim=True) # (B, C, 1)nx = gx / (gx.mean(dim=1, keepdim=True) + self.eps)return self.gamma * (x * nx) + self.beta + xclass ConvNeXtV2Block1D(nn.Module):"""1D ConvNeXt-V2 Block:- Depthwise 7x7 Conv1D- LayerNorm across channels- Pointwise Conv 1x1 (expansion 4x)- GELU activation- GRN (Global Response Normalization)- Pointwise Conv 1x1 (projection back)- Residual connection"""1 unmodified linesuper().__init__()if intermediate_dim is None:intermediate_dim = 4 * dimself.dwconv = nn.Conv1d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim)self.norm = nn.GroupNorm(1, dim) # Equivalent to LayerNorm across channelsself.pwconv1 = nn.Conv1d(dim, intermediate_dim, kernel_size=1)self.act = nn.GELU()self.grn = GRN1D(intermediate_dim)self.pwconv2 = nn.Conv1d(intermediate_dim, dim, kernel_size=1)self.drop = nn.Dropout(dropout) if dropout > 0 else nn.Identity()def forward(self, x: torch.Tensor) -> torch.Tensor:residual = xx = self.dwconv(x)x = self.norm(x)x = self.pwconv1(x)x = self.act(x)x = self.grn(x)x = self.pwconv2(x)x = self.drop(x)return residual + x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051521 unmodified line5455565758596061626364656667686970717273747576777879808182"""ConvNeXt-V2 1D Blocks with Global Response Normalization (GRN)State-of-the-Art modern CNN backbone for audio/spectrogram modeling.Mask-aware so variable-length batch padding never leaks into valid frames."""import torchimport torch.nn as nnfrom typing import Optionalclass ChannelLayerNorm1d(nn.Module):"""Per-timestep LayerNorm across the channel dimension (B, C, T) -> zero padding leakage."""def __init__(self, dim: int, eps: float = 1e-6):super().__init__()self.norm = nn.LayerNorm(dim, eps=eps)def forward(self, x: torch.Tensor) -> torch.Tensor:return self.norm(x.transpose(1, 2)).transpose(1, 2)class GRN1D(nn.Module):"""Mask-aware Global Response Normalization (GRN) for 1D channels."""def __init__(self, dim: int, eps: float = 1e-6):super().__init__()self.gamma = nn.Parameter(torch.zeros(1, dim, 1))self.beta = nn.Parameter(torch.zeros(1, dim, 1))self.eps = epsdef forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:# x: (B, C, T), mask: (B, 1, T)if mask is not None:x = x * maskgx = torch.norm(x, p=2, dim=-1, keepdim=True) # (B, C, 1)nx = gx / (gx.mean(dim=1, keepdim=True) + self.eps)out = self.gamma * (x * nx) + self.beta + xif mask is not None:out = out * maskreturn outclass ConvNeXtV2Block1D(nn.Module):"""1D ConvNeXt-V2 Block:- Depthwise 7x7 Conv1D- Per-timestep Channel LayerNorm- Pointwise Conv 1x1 (expansion 4x)- GELU activation- Mask-aware GRN (Global Response Normalization)- Pointwise Conv 1x1 (projection back)- Residual connection"""1 unmodified linesuper().__init__()if intermediate_dim is None:intermediate_dim = 4 * dimself.dwconv = nn.Conv1d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim)self.norm = ChannelLayerNorm1d(dim)self.pwconv1 = nn.Conv1d(dim, intermediate_dim, kernel_size=1)self.act = nn.GELU()self.grn = GRN1D(intermediate_dim)self.pwconv2 = nn.Conv1d(intermediate_dim, dim, kernel_size=1)self.drop = nn.Dropout(dropout) if dropout > 0 else nn.Identity()def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:residual = xif mask is not None:x = x * maskx = self.dwconv(x)x = self.norm(x)x = self.pwconv1(x)x = self.act(x)x = self.grn(x, mask=mask)x = self.pwconv2(x)x = self.drop(x)out = residual + xif mask is not None:out = out * maskreturn out
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Monotonic Alignment Search (MAS) & Duration Predictor.Guarantees strictly monotonic text-to-audio alignment — 0% word skipping, 0% looping."""import mathimport torchimport torch.nn as nnimport torch.nn.functional as Fdef maximum_path(neg_cent: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:"""Monotonic Alignment Search (Dynamic Programming).neg_cent: (B, T_text, T_mel) negative distance between text & mel framesmask: (B, T_text, T_mel)Returns: hard alignment matrix (B, T_text, T_mel) with 1s on optimal path."""device = neg_cent.devicedtype = neg_cent.dtypeneg_cent = neg_cent * maskB, T_text, T_mel = neg_cent.shapepath = torch.zeros(B, T_text, T_mel, device=device, dtype=dtype)for b in range(B):# Value matrix for dynamic programmingvalue = torch.full((T_text, T_mel), float("-inf"), device=device, dtype=dtype)value[0, 0] = neg_cent[b, 0, 0]for t in range(1, T_mel):for s in range(T_text):if mask[b, s, t] == 0:continuev_stay = value[s, t - 1]if s > 0:v_max = torch.maximum(v_stay, value[s - 1, t - 1])else:v_max = v_stayif not torch.isinf(v_max):value[s, t] = v_max + neg_cent[b, s, t]# Backtrack optimal paths = T_text - 1# Find ending text index from maskwhile s > 0 and mask[b, s, T_mel - 1] == 0:s -= 1for t in range(T_mel - 1, -1, -1):path[b, s, t] = 1.0if s > 0 and (t == 0 or value[s - 1, t - 1] >= value[s, t - 1]):s -= 1return pathclass DurationPredictor(nn.Module):"""Lightweight ~0.6M parameter Duration Predictor.Predicts log-durations for each input text token."""def __init__(self, in_dim: int = 256, hidden_dim: int = 256, kernel_size: int = 3, dropout: float = 0.1):super().__init__()self.conv1 = nn.Conv1d(in_dim, hidden_dim, kernel_size=kernel_size, padding=kernel_size // 2)self.norm1 = nn.GroupNorm(1, hidden_dim)self.act1 = nn.GELU()self.drop1 = nn.Dropout(dropout)self.conv2 = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=kernel_size, padding=kernel_size // 2)self.norm2 = nn.GroupNorm(1, hidden_dim)self.act2 = nn.GELU()self.drop2 = nn.Dropout(dropout)self.proj = nn.Conv1d(hidden_dim, 1, kernel_size=1)def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:# x: (B, T, C) -> transpose to (B, C, T)h = x.transpose(1, 2)h = self.drop1(self.act1(self.norm1(self.conv1(h))))h = self.drop2(self.act2(self.norm2(self.conv2(h))))log_dur = self.proj(h).squeeze(1) # (B, T)if mask is not None:log_dur = log_dur.masked_fill(~mask, 0.0)return log_durdef expand_by_duration(h: torch.Tensor, durations: torch.Tensor) -> torch.Tensor:"""Expands text representations h of shape (B, T_text, C)into mel frame length (B, T_mel, C) based on durations."""B, T_text, C = h.shapeexpanded_list = []for b in range(B):dur_b = torch.clamp(durations[b].round().long(), min=1)expanded_b = torch.repeat_interleave(h[b], dur_b, dim=0)expanded_list.append(expanded_b)max_len = max(x.shape[0] for x in expanded_list)padded = torch.zeros(B, max_len, C, device=h.device, dtype=h.dtype)for b in range(B):padded[b, :expanded_list[b].shape[0]] = expanded_list[b]return padded123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""Monotonic Alignment Search (MAS) & Duration Predictor.Guarantees strictly monotonic text-to-audio alignment without padding corruption."""import numpy as npimport torchimport torch.nn as nnfrom typing import Optional, Tuple, Unionfrom .convnext import ChannelLayerNorm1ddef maximum_path(neg_cent: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:"""Monotonic Alignment Search (Dynamic Programming) on valid unpadded sub-matrices.neg_cent: (B, T_text, T_mel) log-likelihood / negative distance between text & mel framesmask: (B, T_text, T_mel) binary/bool mask indicating valid (non-padded) positionsReturns: hard alignment matrix (B, T_text, T_mel) with 1s strictly on valid frames."""device = neg_cent.devicedtype = neg_cent.dtypeneg_cent_np = neg_cent.detach().float().cpu().numpy()mask_np = mask.detach().cpu().numpy() > 0B, T_text, T_mel = neg_cent_np.shapepath_np = np.zeros((B, T_text, T_mel), dtype=np.float32)for b in range(B):t_len = int(mask_np[b, :, 0].sum()) if T_mel > 0 else 0m_len = int(mask_np[b, 0, :].sum()) if T_text > 0 else 0if t_len <= 0 or m_len <= 0:continuecent = neg_cent_np[b, :t_len, :m_len]value = np.full((t_len, m_len), -np.inf, dtype=np.float32)value[0, 0] = cent[0, 0]for t in range(1, m_len):s_max = min(t + 1, t_len)# Vectorized transition across s for timestep tv_stay = value[:s_max, t - 1]v_prev = np.empty(s_max, dtype=np.float32)v_prev[0] = -np.infif s_max > 1:v_prev[1:] = value[: s_max - 1, t - 1]value[:s_max, t] = np.maximum(v_stay, v_prev) + cent[:s_max, t]# Backtrack strictly from valid end (t_len - 1, m_len - 1) if m_len >= t_len,# or from the best reachable token at m_len - 1 if m_len < t_len.if m_len >= t_len:s = t_len - 1else:s = int(np.argmax(value[:, m_len - 1]))for t in range(m_len - 1, -1, -1):path_np[b, s, t] = 1.0if s > 0 and (t == 0 or value[s - 1, t - 1] >= value[s, t - 1]):s -= 1return torch.from_numpy(path_np).to(device=device, dtype=dtype)class DurationPredictor(nn.Module):"""Lightweight ~0.4M parameter Duration Predictor.Predicts log-durations for each input text token."""def __init__(self, in_dim: int = 256, hidden_dim: int = 256, kernel_size: int = 3, dropout: float = 0.1):super().__init__()self.conv1 = nn.Conv1d(in_dim, hidden_dim, kernel_size=kernel_size, padding=kernel_size // 2)self.norm1 = ChannelLayerNorm1d(hidden_dim)self.act1 = nn.GELU()self.drop1 = nn.Dropout(dropout)self.conv2 = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=kernel_size, padding=kernel_size // 2)self.norm2 = ChannelLayerNorm1d(hidden_dim)self.act2 = nn.GELU()self.drop2 = nn.Dropout(dropout)self.proj = nn.Conv1d(hidden_dim, 1, kernel_size=1)def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:# x: (B, T, C), mask: (B, T) boolh = x.transpose(1, 2)mask_3d = mask.unsqueeze(1).to(h.dtype) if mask is not None else Noneif mask_3d is not None:h = h * mask_3dh = self.drop1(self.act1(self.norm1(self.conv1(h))))if mask_3d is not None:h = h * mask_3dh = self.drop2(self.act2(self.norm2(self.conv2(h))))if mask_3d is not None:h = h * mask_3dlog_dur = self.proj(h).squeeze(1) # (B, T)if mask is not None:log_dur = log_dur.masked_fill(~mask, 0.0)return log_durdef expand_by_duration(h: torch.Tensor,durations: torch.Tensor,text_mask: Optional[torch.Tensor] = None,return_lengths: bool = False,) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:"""Expands text representations h of shape (B, T_text, C)into mel frame length (B, T_mel, C) based on durations.Respects text_mask so padded tokens expand to 0 frames."""B, T_text, C = h.shapeexpanded_list = []mel_lengths = []for b in range(B):if text_mask is not None:valid_len = int(text_mask[b].sum().item())h_b = h[b, :valid_len]dur_raw = durations[b, :valid_len]else:h_b = h[b]dur_raw = durations[b]if h_b.shape[0] == 0:expanded_b = h_b.new_zeros((0, C))else:dur_b = torch.clamp(dur_raw.round().long(), min=1)expanded_b = torch.repeat_interleave(h_b, dur_b, dim=0)expanded_list.append(expanded_b)mel_lengths.append(expanded_b.shape[0])max_len = max(mel_lengths) if mel_lengths else 0padded = torch.zeros(B, max_len, C, device=h.device, dtype=h.dtype)for b in range(B):if mel_lengths[b] > 0:padded[b, : mel_lengths[b]] = expanded_list[b]if return_lengths:return padded, torch.tensor(mel_lengths, device=h.device, dtype=torch.long)return padded
12345678910111213145 unmodified lines202122232425262728293013 unmodified lines444546474849501 unmodified line525354555657585960613 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331342 unmodified lines1371381391401411422 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170"""Optimal Transport Conditional Flow Matching (OT-CFM) Engine.State-of-the-Art Generative Speech Framework (2024–2026).Straight-line ODE trajectories enable crystal-clear audio synthesis in just 4-10 steps."""import mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom .convnext import ConvNeXtV2Block1Dclass SinusoidalTimeEmbedding(nn.Module):5 unmodified linesdef forward(self, t: torch.Tensor) -> torch.Tensor:# t: (B,)half_dim = self.dim // 2emb = math.log(10000) / (half_dim - 1)emb = torch.exp(torch.arange(half_dim, device=t.device, dtype=torch.float32) * -emb)emb = t[:, None] * emb[None, :]emb = torch.cat((emb.sin(), emb.cos()), dim=-1)return emb # (B, dim)class CFMVectorField(nn.Module):13 unmodified linessuper().__init__()self.mel_dim = mel_dimself.hidden_dim = hidden_dim# Time embedding MLPself.time_embed = nn.Sequential(SinusoidalTimeEmbedding(time_dim),1 unmodified linenn.GELU(),nn.Linear(hidden_dim, hidden_dim),)# Input projection (Mel + Condition)self.in_proj = nn.Conv1d(mel_dim + cond_dim, hidden_dim, kernel_size=1)# ConvNeXt-V2 Blocks with Time Conditioning Projectionsself.blocks = nn.ModuleList([ConvNeXtV2Block1D(hidden_dim, kernel_size=kernel_size)3 unmodified linesnn.Linear(hidden_dim, hidden_dim)for _ in range(num_blocks)])# Output projection back to Mel dimension (100 channels)self.final_norm = nn.GroupNorm(1, hidden_dim)self.out_proj = nn.Conv1d(hidden_dim, mel_dim, kernel_size=1)def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:"""x: (B, 80, T) - current noisy state at time tt: (B,) - continuous time in [0, 1]cond: (B, cond_dim, T) - expanded text condition"""# Time conditioningt_emb = self.time_embed(t) # (B, hidden_dim)# Concatenate audio state and conditioningfeat = torch.cat([x, cond], dim=1) # (B, 80 + cond_dim, T)h = self.in_proj(feat) # (B, hidden_dim, T)for block, t_proj in zip(self.blocks, self.time_projs):t_scale = t_proj(t_emb).unsqueeze(-1) # (B, hidden_dim, 1)h = h + t_scaleh = block(h)h = self.final_norm(h)v = self.out_proj(h) # (B, 80, T)return vclass OptimalTransportCFM(nn.Module):"""Optimal Transport Conditional Flow Matching (OT-CFM) Module.Computes training loss and performs ultrafast ODE sampling."""def __init__(self, vector_field: CFMVectorField, sigma_min: float = 1e-4):super().__init__()self.vf = vector_fieldself.sigma_min = sigma_mindef compute_loss(self, x1: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:"""x1: Ground truth target Mel spectrogram (B, 80, T)cond: Text condition (B, cond_dim, T)"""B, C, T = x1.shapedevice = x1.device# 1. Sample continuous time t uniformly in [0, 1]t = torch.rand(B, device=device, dtype=x1.dtype)# 2. Sample prior noise x0 ~ N(0, I)x0 = torch.randn_like(x1)# 3. Compute OT straight-line trajectory: x_t = (1 - (1 - sigma_min)*t)*x0 + t*x1t_expand = t[:, None, None]xt = (1.0 - (1.0 - self.sigma_min) * t_expand) * x0 + t_expand * x1# 4. Target vector field: u_t(x1 | x0) = x1 - (1 - sigma_min)*x0ut = x1 - (1.0 - self.sigma_min) * x0# 5. Predict vector field with neural networkvt = self.vf(xt, t, cond)# 6. Mean Squared Error (MSE) Loss — strictly stable, no GAN instability!loss = F.mse_loss(vt, ut)return loss@torch.no_grad()2 unmodified linescond: torch.Tensor,num_steps: int = 8,method: str = "midpoint",) -> torch.Tensor:"""Ultrafast ODE sampling from t=0 (noise) to t=1 (mel spectrogram).2 unmodified lines"""B, _, T = cond.shapedevice = cond.device# Start at noise x0 ~ N(0, I)x = torch.randn(B, self.vf.mel_dim, T, device=device)dt = 1.0 / num_stepst_steps = torch.linspace(0.0, 1.0, num_steps + 1, device=device)for i in range(num_steps):t_curr = t_steps[i].repeat(B)if method == "midpoint":# 2nd-order Runge-Kutta (Midpoint)v1 = self.vf(x, t_curr, cond)x_mid = x + 0.5 * dt * v1t_mid = (t_steps[i] + 0.5 * dt).repeat(B)v2 = self.vf(x_mid, t_mid, cond)x = x + dt * v2else:# 1st-order Euler solverv = self.vf(x, t_curr, cond)x = x + dt * vreturn x # (B, 80, T) - Generated high quality Mel-spectrogram1234567891011121314155 unmodified lines212223242526272829303113 unmodified lines454647484950511 unmodified line535455565758596061623 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591602 unmodified lines1631641651661671681692 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204"""Optimal Transport Conditional Flow Matching (OT-CFM) Engine.State-of-the-Art Generative Speech Framework (2024-2026).Straight-line ODE trajectories enable crystal-clear audio synthesis in just 4-10 steps."""import mathimport torchimport torch.nn as nnfrom typing import Optionalfrom .convnext import ConvNeXtV2Block1D, ChannelLayerNorm1dclass SinusoidalTimeEmbedding(nn.Module):5 unmodified linesdef forward(self, t: torch.Tensor) -> torch.Tensor:# t: (B,)half_dim = self.dim // 2emb = math.log(10000) / max(half_dim - 1, 1)emb = torch.exp(torch.arange(half_dim, device=t.device, dtype=torch.float32) * -emb)emb = t.float()[:, None] * emb[None, :]emb = torch.cat((emb.sin(), emb.cos()), dim=-1)return emb.to(t.dtype) # (B, dim)class CFMVectorField(nn.Module):13 unmodified linessuper().__init__()self.mel_dim = mel_dimself.hidden_dim = hidden_dim# Time embedding MLPself.time_embed = nn.Sequential(SinusoidalTimeEmbedding(time_dim),1 unmodified linenn.GELU(),nn.Linear(hidden_dim, hidden_dim),)# Input projection (Mel + Condition)self.in_proj = nn.Conv1d(mel_dim + cond_dim, hidden_dim, kernel_size=1)# ConvNeXt-V2 Blocks with Time Conditioning Projectionsself.blocks = nn.ModuleList([ConvNeXtV2Block1D(hidden_dim, kernel_size=kernel_size)3 unmodified linesnn.Linear(hidden_dim, hidden_dim)for _ in range(num_blocks)])# Output projection back to Mel dimension (mel_dim channels)self.final_norm = ChannelLayerNorm1d(hidden_dim)self.out_proj = nn.Conv1d(hidden_dim, mel_dim, kernel_size=1)def forward(self,x: torch.Tensor,t: torch.Tensor,cond: torch.Tensor,mask: Optional[torch.Tensor] = None,) -> torch.Tensor:"""x: (B, mel_dim, T) - current noisy state at time tt: (B,) - continuous time in [0, 1]cond: (B, cond_dim, T) - expanded text conditionmask: Optional (B, 1, T) float/bool mask"""t_emb = self.time_embed(t) # (B, hidden_dim)feat = torch.cat([x, cond], dim=1) # (B, mel_dim + cond_dim, T)h = self.in_proj(feat) # (B, hidden_dim, T)if mask is not None:h = h * maskfor block, t_proj in zip(self.blocks, self.time_projs):t_scale = t_proj(t_emb).unsqueeze(-1) # (B, hidden_dim, 1)h = h + t_scaleh = block(h, mask=mask)h = self.final_norm(h)v = self.out_proj(h) # (B, mel_dim, T)if mask is not None:v = v * maskreturn vclass OptimalTransportCFM(nn.Module):"""Optimal Transport Conditional Flow Matching (OT-CFM) Module.Computes masked training loss and performs ultrafast ODE sampling."""def __init__(self, vector_field: CFMVectorField, sigma_min: float = 1e-4):super().__init__()self.vf = vector_fieldself.sigma_min = sigma_mindef compute_loss(self,x1: torch.Tensor,cond: torch.Tensor,mel_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:"""x1: Ground truth target Mel spectrogram (B, mel_dim, T)cond: Text condition (B, cond_dim, T)mel_mask: Optional (B, T) bool mask for valid frames"""B, C, T = x1.shapedevice = x1.devicemask_3d = mel_mask.unsqueeze(1).to(x1.dtype) if mel_mask is not None else None# 1. Sample continuous time t uniformly in [0, 1]t = torch.rand(B, device=device, dtype=x1.dtype)# 2. Sample prior noise x0 ~ N(0, I)x0 = torch.randn_like(x1)# 3. Compute OT straight-line trajectory: x_t = (1 - (1 - sigma_min)*t)*x0 + t*x1t_expand = t[:, None, None]xt = (1.0 - (1.0 - self.sigma_min) * t_expand) * x0 + t_expand * x1# 4. Target vector field: u_t(x1 | x0) = x1 - (1 - sigma_min)*x0ut = x1 - (1.0 - self.sigma_min) * x0if mask_3d is not None:xt = xt * mask_3dcond = cond * mask_3d# 5. Predict vector field with neural networkvt = self.vf(xt, t, cond, mask=mask_3d)# 6. Masked Mean Squared Error (MSE) Losssq_err = (vt - ut) ** 2if mask_3d is not None:loss = (sq_err * mask_3d).sum() / (mask_3d.sum() * C).clamp(min=1.0)else:loss = sq_err.mean()return loss@torch.no_grad()2 unmodified linescond: torch.Tensor,num_steps: int = 8,method: str = "midpoint",mel_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:"""Ultrafast ODE sampling from t=0 (noise) to t=1 (mel spectrogram).2 unmodified lines"""B, _, T = cond.shapedevice = cond.devicemask_3d = mel_mask.unsqueeze(1).to(cond.dtype) if mel_mask is not None else None# Start at noise x0 ~ N(0, I)x = torch.randn(B, self.vf.mel_dim, T, device=device, dtype=cond.dtype)if mask_3d is not None:x = x * mask_3dcond = cond * mask_3ddt = 1.0 / num_stepst_steps = torch.linspace(0.0, 1.0, num_steps + 1, device=device, dtype=cond.dtype)for i in range(num_steps):t_curr = t_steps[i].repeat(B)if method == "midpoint":v1 = self.vf(x, t_curr, cond, mask=mask_3d)x_mid = x + 0.5 * dt * v1if mask_3d is not None:x_mid = x_mid * mask_3dt_mid = (t_steps[i] + 0.5 * dt).repeat(B)v2 = self.vf(x_mid, t_mid, cond, mask=mask_3d)x = x + dt * v2else:v = self.vf(x, t_curr, cond, mask=mask_3d)x = x + dt * vif mask_3d is not None:x = x * mask_3dreturn x # (B, mel_dim, T)
12345678910111218 unmodified lines31323334353637382 unmodified lines41424344454647484950511 unmodified line5354555657585960616263646566676869707172737414 unmodified lines899091929394951 unmodified line97989910010110210310410510610710810 unmodified lines119120121122123124125126127128129130131132133134135136137"""Text Encoder with Rotary Positional Embeddings (RoPE) and Transformer Blocks.Total parameter budget: ~2.5M - 2.6M params."""import mathimport torchimport torch.nn as nnimport torch.nn.functional as Fclass RotaryEmbedding(nn.Module):18 unmodified linesdef apply_rope(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):# q, k: (B, H, T, D)cos = cos.unsqueeze(0).unsqueeze(0) # (1, 1, T, D)sin = sin.unsqueeze(0).unsqueeze(0) # (1, 1, T, D)q_embed = (q * cos) + (rotate_half(q) * sin)k_embed = (k * cos) + (rotate_half(k) * sin)return q_embed, k_embed2 unmodified linesclass MultiHeadAttentionRoPE(nn.Module):def __init__(self, dim: int, heads: int = 4, dropout: float = 0.1):super().__init__()self.dim = dimself.heads = headsself.head_dim = dim // headsself.scale = self.head_dim ** -0.5self.q_proj = nn.Linear(dim, dim)self.k_proj = nn.Linear(dim, dim)self.v_proj = nn.Linear(dim, dim)1 unmodified lineself.dropout = nn.Dropout(dropout)self.rope = RotaryEmbedding(self.head_dim)def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:# x: (B, T, C)B, T, C = x.shapeq = self.q_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2)k = self.k_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2)v = self.v_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2)cos, sin = self.rope(T, x.device)q, k = apply_rope(q, k, cos, sin)scores = torch.matmul(q, k.transpose(-2, -1)) * self.scaleif mask is not None:# mask: (B, 1, 1, T) or (B, 1, T, T)scores = scores.masked_fill(~mask, float("-inf"))attn = F.softmax(scores, dim=-1)attn = self.dropout(attn)out = torch.matmul(attn, v) # (B, H, T, D)out = out.transpose(1, 2).contiguous().view(B, T, C)14 unmodified linesnn.Dropout(dropout),)def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:x = x + self.attn(self.norm1(x), mask=mask)x = x + self.ffn(self.norm2(x))return x1 unmodified lineclass TextEncoder(nn.Module):"""State-of-the-art ~2.6M parameter Transformer Text Encoder with RoPE.Encodes text token IDs into contextual hidden representations."""def __init__(self,vocab_size: int = 256,dim: int = 256,layers: int = 4,heads: int = 4,10 unmodified lines])self.final_norm = nn.LayerNorm(dim)def forward(self, text_ids: torch.Tensor, text_lengths: torch.Tensor = None):# text_ids: (B, T_text)B, T = text_ids.shapex = self.embedding(text_ids)mask = Noneif text_lengths is not None:# (B, 1, 1, T)mask = torch.arange(T, device=text_ids.device).unsqueeze(0) < text_lengths.unsqueeze(1)mask = mask.unsqueeze(1).unsqueeze(2) # for multihead attentionfor block in self.blocks:x = block(x, mask=mask)x = self.final_norm(x)return x # (B, T_text, dim)12345678910111218 unmodified lines31323334353637382 unmodified lines414243444546474849505152531 unmodified line555657585960616263646566676869707172737475767714 unmodified lines929394959697981 unmodified line10010110210310410510610710810911011110 unmodified lines122123124125126127128129130131132133134135136137138139140141142"""Text Encoder with Rotary Positional Embeddings (RoPE) and Transformer Blocks.Total parameter budget: ~2.7M params."""import torchimport torch.nn as nnimport torch.nn.functional as Ffrom typing import Optionalclass RotaryEmbedding(nn.Module):18 unmodified linesdef apply_rope(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):# q, k: (B, H, T, D)cos = cos.unsqueeze(0).unsqueeze(0).to(q.dtype) # (1, 1, T, D)sin = sin.unsqueeze(0).unsqueeze(0).to(q.dtype) # (1, 1, T, D)q_embed = (q * cos) + (rotate_half(q) * sin)k_embed = (k * cos) + (rotate_half(k) * sin)return q_embed, k_embed2 unmodified linesclass MultiHeadAttentionRoPE(nn.Module):def __init__(self, dim: int, heads: int = 4, dropout: float = 0.1):super().__init__()if dim % heads != 0:raise ValueError(f"dim ({dim}) must be divisible by heads ({heads})")self.dim = dimself.heads = headsself.head_dim = dim // headsself.scale = self.head_dim ** -0.5self.q_proj = nn.Linear(dim, dim)self.k_proj = nn.Linear(dim, dim)self.v_proj = nn.Linear(dim, dim)1 unmodified lineself.dropout = nn.Dropout(dropout)self.rope = RotaryEmbedding(self.head_dim)def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:# x: (B, T, C)B, T, C = x.shapeq = self.q_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2)k = self.k_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2)v = self.v_proj(x).view(B, T, self.heads, self.head_dim).transpose(1, 2)cos, sin = self.rope(T, x.device)q, k = apply_rope(q, k, cos, sin)scores = torch.matmul(q, k.transpose(-2, -1)) * self.scaleif mask is not None:# mask: (B, 1, 1, T) or (B, 1, T, T)scores = scores.masked_fill(~mask, torch.finfo(scores.dtype).min)attn = F.softmax(scores, dim=-1)attn = torch.nan_to_num(attn, nan=0.0)attn = self.dropout(attn)out = torch.matmul(attn, v) # (B, H, T, D)out = out.transpose(1, 2).contiguous().view(B, T, C)14 unmodified linesnn.Dropout(dropout),)def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:x = x + self.attn(self.norm1(x), mask=mask)x = x + self.ffn(self.norm2(x))return x1 unmodified lineclass TextEncoder(nn.Module):"""Transformer Text Encoder with RoPE.Encodes text token IDs into contextual hidden representations."""def __init__(self,vocab_size: int = 512,dim: int = 256,layers: int = 4,heads: int = 4,10 unmodified lines])self.final_norm = nn.LayerNorm(dim)def forward(self, text_ids: torch.Tensor, text_lengths: Optional[torch.Tensor] = None) -> torch.Tensor:# text_ids: (B, T_text)B, T = text_ids.shapex = self.embedding(text_ids)token_mask = Noneattn_mask = Noneif text_lengths is not None:token_mask = torch.arange(T, device=text_ids.device).unsqueeze(0) < text_lengths.unsqueeze(1)attn_mask = token_mask.unsqueeze(1).unsqueeze(2) # (B, 1, 1, T)for block in self.blocks:x = block(x, mask=attn_mask)x = self.final_norm(x)if token_mask is not None:x = x.masked_fill(~token_mask.unsqueeze(-1), 0.0)return x # (B, T_text, dim)
123456789101112131415161718192021222324252627282930313 unmodified lines35363738394041424344454647484950515253541 unmodified line56575859606162636465666768697071727374757677787980818283848586878889909192939495966 unmodified lines103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""Unified 10M Modern TTS Engine (Optimal Transport CFM + Vocos).Combines Text Encoder, Duration Predictor, and Flow Matching Vector Field.Total Parameter Count: ~9.5M - 10.0M."""import osimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom typing import Dict, Tuple, Optionalfrom .text_encoder import TextEncoderfrom .duration_predictor import DurationPredictor, maximum_path, expand_by_durationfrom .flow_matching import CFMVectorField, OptimalTransportCFMfrom .vocoder import VocosVocoderfrom config import ModelConfig, AudioConfigclass TTS10MEngine(nn.Module):"""Cutting-Edge 10M Parameter TTS Architecture (2024–2026)."""def __init__(self, config: Optional[ModelConfig] = None):super().__init__()self.config = config or ModelConfig()# 1. Text Encoder (~2.6M params)self.text_encoder = TextEncoder(vocab_size=self.config.vocab_size,dim=self.config.text_dim,3 unmodified linesdropout=self.config.dropout,pad_token_id=self.config.pad_token_id,)# 2. Duration Predictor (~0.6M params)self.duration_predictor = DurationPredictor(in_dim=self.config.text_dim,hidden_dim=self.config.duration_hidden_dim,kernel_size=self.config.duration_kernel_size,dropout=self.config.dropout,)# Alignment projection for Monotonic Alignment Searchself.mel_proj = nn.Conv1d(self.config.mel_dim, self.config.text_dim, kernel_size=1)# 3. Flow Matching Vector Field (~5.0M params)self.vector_field = CFMVectorField(mel_dim=self.config.mel_dim,cond_dim=self.config.text_dim,hidden_dim=self.config.cfm_hidden_dim,1 unmodified linekernel_size=self.config.cfm_kernel_size,time_dim=self.config.time_embed_dim,)# Flow Matching Moduleself.cfm = OptimalTransportCFM(self.vector_field, sigma_min=self.config.sigma_min)# Vocoderself.vocoder = VocosVocoder()def get_num_params(self) -> Dict[str, int]:"""Returns parameter count of each component and total."""text_params = sum(p.numel() for p in self.text_encoder.parameters() if p.requires_grad)dur_params = sum(p.numel() for p in self.duration_predictor.parameters() if p.requires_grad)mel_proj_params = sum(p.numel() for p in self.mel_proj.parameters() if p.requires_grad)cfm_params = sum(p.numel() for p in self.vector_field.parameters() if p.requires_grad)total_trainable = text_params + dur_params + mel_proj_params + cfm_paramsreturn {"text_encoder": text_params,"duration_predictor": dur_params,"mel_projection": mel_proj_params,"cfm_vector_field": cfm_params,"total_acoustic_params": total_trainable,}def print_summary(self):params = self.get_num_params()print("\n" + "="*50)print(" 10M TTS MODEL PARAMETERS SUMMARY ")print("="*50)print(f" Text Encoder (RoPE Transformer): {params['text_encoder']:,} (~{params['text_encoder']/1e6:.2f}M)")print(f" Duration Predictor: {params['duration_predictor']:,} (~{params['duration_predictor']/1e6:.2f}M)")print(f" Alignment Projection: {params['mel_projection']:,} (~{params['mel_projection']/1e6:.2f}M)")print(f" OT-CFM Vector Field: {params['cfm_vector_field']:,} (~{params['cfm_vector_field']/1e6:.2f}M)")print("-"*50)print(f" TOTAL TRAINABLE PARAMETERS: {params['total_acoustic_params']:,} (~{params['total_acoustic_params']/1e6:.2f}M)")print("="*50 + "\n")def forward_train(self,6 unmodified linesTraining Forward Pass.text_ids: (B, T_text)text_lengths: (B,)mel_gt: (B, 100, T_mel)mel_lengths: (B,)"""B, T_text = text_ids.shape_, _, T_mel = mel_gt.shapedevice = text_ids.device# 1. Encode texth_text = self.text_encoder(text_ids, text_lengths) # (B, T_text, text_dim)# 2. Monotonic Alignment Search (MAS)# Project mel to text_dim space to compute distancemel_mapped = self.mel_proj(mel_gt).transpose(1, 2) # (B, T_mel, text_dim)# Negative L2 distance matrix: (B, T_text, T_mel)dist = -torch.cdist(h_text, mel_mapped, p=2)# Maskstext_mask = torch.arange(T_text, device=device).unsqueeze(0) < text_lengths.unsqueeze(1)mel_mask = torch.arange(T_mel, device=device).unsqueeze(0) < mel_lengths.unsqueeze(1)align_mask = text_mask.unsqueeze(2) * mel_mask.unsqueeze(1) # (B, T_text, T_mel)with torch.no_grad():align_path = maximum_path(dist, align_mask) # (B, T_text, T_mel)target_durations = align_path.sum(dim=-1) # (B, T_text)# 3. Duration losslog_dur_pred = self.duration_predictor(h_text, text_mask)target_log_dur = torch.log(torch.clamp(target_durations, min=1.0))dur_loss = F.mse_loss(log_dur_pred * text_mask, target_log_dur * text_mask)# 4. Expand text representations to mel length using alignment# align_path: (B, T_text, T_mel)# h_text: (B, T_text, C) -> expand: (B, C, T_mel)cond_mel = torch.bmm(h_text.transpose(1, 2), align_path) # (B, C, T_mel)# 5. Flow Matching Losscfm_loss = self.cfm.compute_loss(mel_gt, cond_mel)total_loss = cfm_loss + 0.5 * dur_lossreturn {"total_loss": total_loss,"cfm_loss": cfm_loss,"dur_loss": dur_loss,}@torch.no_grad()def synthesize(self,text_ids: torch.Tensor,num_steps: int = 8,speed: float = 1.0,return_waveform: bool = True,) -> Dict[str, torch.Tensor]:"""Fast Inference Synthesis.Solves ODE in 4-10 steps and decodes with Vocos.text_ids: (1, T_text)"""self.eval()B, T_text = text_ids.shape# 1. Encode texth_text = self.text_encoder(text_ids) # (B, T_text, C)# 2. Predict durationslog_dur = self.duration_predictor(h_text)durations = torch.exp(log_dur) / speeddurations = torch.clamp(durations, min=1.0)# 3. Expand text representationsh_expanded = expand_by_duration(h_text, durations) # (B, T_mel, C)cond = h_expanded.transpose(1, 2) # (B, C, T_mel)# 4. Solve Flow Matching ODE (4-10 steps)mel_pred = self.cfm.sample(cond, num_steps=num_steps, method="midpoint")result = {"mel": mel_pred}# 5. Decode to 24kHz waveformif return_waveform:waveform = self.vocoder.decode(mel_pred)result["waveform"] = waveformreturn result123456789101112131415161718192021222324252627282930313233343 unmodified lines38394041424344454647484950515253545556575859601 unmodified line62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051066 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241"""Unified 10M Modern TTS Engine (Optimal Transport CFM + Vocos).Combines Text Encoder, Duration Predictor, Mel Prior Alignment, and Flow Matching Vector Field.Total Trainable Acoustic Parameter Count: ~8.17M (+ ~2.5M Vocos = ~10.67M)."""import torchimport torch.nn as nnfrom typing import Dict, Optionalfrom .text_encoder import TextEncoderfrom .duration_predictor import DurationPredictor, maximum_path, expand_by_durationfrom .flow_matching import CFMVectorField, OptimalTransportCFMfrom .vocoder import VocosVocoderfrom config import ModelConfig, TrainingConfigclass TTS10MEngine(nn.Module):"""Cutting-Edge ~10M Parameter TTS Architecture."""def __init__(self,config: Optional[ModelConfig] = None,train_config: Optional[TrainingConfig] = None,):super().__init__()self.config = config or ModelConfig()self.train_config = train_config or TrainingConfig()# 1. Text Encoder (~2.76M params)self.text_encoder = TextEncoder(vocab_size=self.config.vocab_size,dim=self.config.text_dim,3 unmodified linesdropout=self.config.dropout,pad_token_id=self.config.pad_token_id,)# 2. Duration Predictor (~0.40M params)self.duration_predictor = DurationPredictor(in_dim=self.config.text_dim,hidden_dim=self.config.duration_hidden_dim,kernel_size=self.config.duration_kernel_size,dropout=self.config.dropout,)# Differentiable Mel Prior Projection for Monotonic Alignment Search (MAS)# Predicts coarse log-mel prior mu_text from h_text so MAS aligns against real mel_gt# without representation collapse or frozen random weights.self.prior_proj = nn.Linear(self.config.text_dim, self.config.mel_dim)# 3. Flow Matching Vector Field (~4.98M params)# Registered once inside self.cfm to avoid shared-tensor duplication in safetensorsvector_field = CFMVectorField(mel_dim=self.config.mel_dim,cond_dim=self.config.text_dim,hidden_dim=self.config.cfm_hidden_dim,1 unmodified linekernel_size=self.config.cfm_kernel_size,time_dim=self.config.time_embed_dim,)# Flow Matching Moduleself.cfm = OptimalTransportCFM(vector_field, sigma_min=self.config.sigma_min)# Vocoderself.vocoder = VocosVocoder()@propertydef vector_field(self) -> CFMVectorField:return self.cfm.vfdef get_num_params(self) -> Dict[str, int]:"""Returns parameter count of each component and total."""text_params = sum(p.numel() for p in self.text_encoder.parameters() if p.requires_grad)dur_params = sum(p.numel() for p in self.duration_predictor.parameters() if p.requires_grad)prior_params = sum(p.numel() for p in self.prior_proj.parameters() if p.requires_grad)cfm_params = sum(p.numel() for p in self.vector_field.parameters() if p.requires_grad)total_trainable = text_params + dur_params + prior_params + cfm_paramsreturn {"text_encoder": text_params,"duration_predictor": dur_params,"prior_projection": prior_params,"cfm_vector_field": cfm_params,"total_acoustic_params": total_trainable,}def print_summary(self):params = self.get_num_params()print("\n" + "=" * 54)print(" 10M TTS MODEL PARAMETERS SUMMARY ")print("=" * 54)print(f" Text Encoder (RoPE Transformer): {params['text_encoder']:,} (~{params['text_encoder']/1e6:.2f}M)")print(f" Duration Predictor: {params['duration_predictor']:,} (~{params['duration_predictor']/1e6:.2f}M)")print(f" Mel Prior Projection: {params['prior_projection']:,} (~{params['prior_projection']/1e6:.2f}M)")print(f" OT-CFM Vector Field: {params['cfm_vector_field']:,} (~{params['cfm_vector_field']/1e6:.2f}M)")print("-" * 54)print(f" TOTAL TRAINABLE PARAMETERS: {params['total_acoustic_params']:,} (~{params['total_acoustic_params']/1e6:.2f}M)")print("=" * 54 + "\n")def forward_train(self,6 unmodified linesTraining Forward Pass.text_ids: (B, T_text)text_lengths: (B,)mel_gt: (B, n_mels, T_mel)mel_lengths: (B,)"""B, T_text = text_ids.shape_, C_mel, T_mel = mel_gt.shapedevice = text_ids.device# 1. Encode texth_text = self.text_encoder(text_ids, text_lengths) # (B, T_text, text_dim)# Maskstext_mask = torch.arange(T_text, device=device).unsqueeze(0) < text_lengths.unsqueeze(1)mel_mask = torch.arange(T_mel, device=device).unsqueeze(0) < mel_lengths.unsqueeze(1)align_mask = text_mask.unsqueeze(2) & mel_mask.unsqueeze(1) # (B, T_text, T_mel)# 2. Monotonic Alignment Search (MAS) in mel prior spacemu_text = self.prior_proj(h_text) # (B, T_text, mel_dim)mel_t = mel_gt.transpose(1, 2) # (B, T_mel, mel_dim)# Negative squared L2 distance (Gaussian log-likelihood up to constant)with torch.no_grad():mu_f32 = mu_text.float()mel_f32 = mel_t.float()s_mu = (mu_f32 ** 2).sum(dim=-1, keepdim=True) # (B, T_text, 1)s_mel = (mel_f32 ** 2).sum(dim=-1).unsqueeze(1) # (B, 1, T_mel)neg_cent = -0.5 * (s_mu + s_mel - 2.0 * torch.bmm(mu_f32, mel_f32.transpose(1, 2)))align_path = maximum_path(neg_cent, align_mask) # (B, T_text, T_mel)target_durations = align_path.sum(dim=-1) # (B, T_text)# Differentiable Mel Prior Loss (trains prior_proj + text_encoder!)mu_expanded = torch.bmm(mu_text.transpose(1, 2), align_path.to(mu_text.dtype)) # (B, mel_dim, T_mel)mel_mask_3d = mel_mask.unsqueeze(1).to(mu_expanded.dtype)prior_loss = ((mu_expanded - mel_gt) ** 2 * mel_mask_3d).sum() / (mel_mask_3d.sum() * C_mel).clamp(min=1.0)# 3. Duration loss (normalized strictly by valid token count)log_dur_pred = self.duration_predictor(h_text, text_mask)target_log_dur = torch.log(torch.clamp(target_durations, min=1.0))text_mask_f = text_mask.to(log_dur_pred.dtype)dur_loss = ((log_dur_pred - target_log_dur) ** 2 * text_mask_f).sum() / text_mask_f.sum().clamp(min=1.0)# 4. Expand text representations to mel length using alignmentcond_mel = torch.bmm(h_text.transpose(1, 2), align_path.to(h_text.dtype)) # (B, C, T_mel)# 5. Masked Flow Matching Losscfm_loss = self.cfm.compute_loss(mel_gt, cond_mel, mel_mask=mel_mask)total_loss = (self.train_config.cfm_loss_weight * cfm_loss+ self.train_config.dur_loss_weight * dur_loss+ self.train_config.prior_loss_weight * prior_loss)return {"total_loss": total_loss,"cfm_loss": cfm_loss,"dur_loss": dur_loss,"prior_loss": prior_loss,}@torch.no_grad()def synthesize(self,text_ids: torch.Tensor,text_lengths: Optional[torch.Tensor] = None,num_steps: Optional[int] = None,speed: float = 1.0,return_waveform: bool = True,) -> Dict[str, torch.Tensor]:"""Fast Inference Synthesis.Solves ODE in 4-10 steps and decodes with Vocos.text_ids: (B, T_text)"""if text_ids.ndim != 2 or text_ids.shape[1] == 0:raise ValueError("text_ids must have shape (B, T_text) with T_text > 0.")if speed <= 0:raise ValueError(f"speed must be > 0, got {speed}")self.eval()B, T_text = text_ids.shapedevice = text_ids.deviceif text_lengths is None:text_mask = text_ids != self.config.pad_token_idtext_lengths = text_mask.sum(dim=1)else:text_mask = torch.arange(T_text, device=device).unsqueeze(0) < text_lengths.unsqueeze(1)if (text_lengths == 0).any():raise ValueError("Every sequence in text_ids must contain at least one non-pad token.")# 1. Encode texth_text = self.text_encoder(text_ids, text_lengths=text_lengths) # (B, T_text, C)# 2. Predict durationslog_dur = self.duration_predictor(h_text, mask=text_mask)durations = torch.exp(log_dur) / speeddurations = torch.clamp(durations, min=1.0)# 3. Expand text representations respecting text_maskh_expanded, mel_lengths = expand_by_duration(h_text, durations, text_mask=text_mask, return_lengths=True)cond = h_expanded.transpose(1, 2) # (B, C, T_mel)T_mel = cond.shape[-1]mel_mask = torch.arange(T_mel, device=device).unsqueeze(0) < mel_lengths.unsqueeze(1)# 4. Solve Flow Matching ODEsteps = num_steps if num_steps is not None else self.config.default_ode_stepsmel_pred = self.cfm.sample(cond,num_steps=steps,method=self.config.ode_method,mel_mask=mel_mask,)result = {"mel": mel_pred, "mel_lengths": mel_lengths}# 5. Decode to 24kHz waveformif return_waveform:waveform = self.vocoder.decode(mel_pred)result["waveform"] = waveformreturn result
12345678910 unmodified lines202122232425262728298 unmodified lines383940414243444546474849505152"""Vocos 24kHz Neural Vocoder Wrapper.Reconstructs crystal-clear 24kHz audio waveforms from 80-bin Mel-spectrograms in real-time."""import osimport torchimport torch.nn as nnfrom typing import Optional10 unmodified linesself.model = Noneself._target_device = devicedef load_vocoder(self, device: torch.device = None):if self.model is not None:returntarget_device = device or self._target_device or torch.device("cpu")try:from vocos import Vocos8 unmodified lines@torch.no_grad()def decode(self, mel: torch.Tensor) -> torch.Tensor:"""mel: (B, 80, T) - Log Mel SpectrogramReturns: (B, num_samples) - 24kHz Audio Waveform"""if self.model is None:self.load_vocoder(mel.device)if self.model is None:raise RuntimeError("Vocos model could not be loaded. Check internet or install vocos.")self.model.to(mel.device)# Vocos decode expects (B, 80, T)audio = self.model.decode(mel)return audio1234567810 unmodified lines192021222324252627288 unmodified lines373839404142434445464748495051"""Vocos 24kHz Neural Vocoder Wrapper.Reconstructs crystal-clear 24kHz audio waveforms from 100-bin Mel-spectrograms in real-time."""import torchimport torch.nn as nnfrom typing import Optional10 unmodified linesself.model = Noneself._target_device = devicedef load_vocoder(self, device: Optional[torch.device] = None):if self.model is not None:returntarget_device = device or self._target_device or torch.device("cpu")try:from vocos import Vocos8 unmodified lines@torch.no_grad()def decode(self, mel: torch.Tensor) -> torch.Tensor:"""mel: (B, 100, T) - Log Mel SpectrogramReturns: (B, num_samples) - 24kHz Audio Waveform"""if self.model is None:self.load_vocoder(mel.device)if self.model is None:raise RuntimeError("Vocos model could not be loaded. Check internet or install vocos.")self.model.to(mel.device)# Vocos decode expects (B, 100, T)audio = self.model.decode(mel)return audio
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081821 unmodified line848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931946 unmodified lines201202203204205"""Modern Training Script for 10M TTS Engine.Features:- AdamW Optimizer with Cosine Annealing & Warmup- Anti-Beep & Anti-Explosion Gradient Clipping (max_norm=1.0)- Automatic Mixed Precision (AMP) support for GPUs- Audio Sanity Guard to guarantee no robotic beep sounds- Automatic periodic audio sample generation"""import osimport timeimport argparseimport torchfrom torch.utils.data import DataLoaderimport torchaudiofrom config import TTS10MConfigfrom models.tts_engine import TTS10MEnginefrom data.dataset import TTSDataset, collate_tts_fnfrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import save_checkpointfrom utils.audio_sanity import AudioSanityGuardian, save_audiodef train(metadata_path: str = "dataset/metadata.csv",hf_dataset: str = None,language: str = None,speaker: str = None,output_dir: str = "checkpoints",batch_size: int = 16,learning_rate: float = 2e-4,max_epochs: int = 100,save_interval: int = 1000,eval_interval: int = 250,device: str = None,):cfg = TTS10MConfig()cfg.training.output_dir = output_diros.makedirs(output_dir, exist_ok=True)os.makedirs(os.path.join(output_dir, "samples"), exist_ok=True)# 1. Device selectionif device is None:device = "cuda" if torch.cuda.is_available() else "cpu"device = torch.device(device)print(f"\n==========================================")print(f" Training 10M SOTA TTS Engine on: {device}")print(f"==========================================")# 2. Initialize Modelmodel = TTS10MEngine(cfg.model).to(device)model.print_summary()# 3. Load Dataset (from HF Hub or local)if hf_dataset:print(f"Loading direct from Hugging Face Hub: {hf_dataset}...")dataset = TTSDataset(hf_dataset_name=hf_dataset, language=language, speaker=speaker)else:print(f"Loading dataset from: {metadata_path}...")dataset = TTSDataset(metadata_path=metadata_path)if len(dataset) == 0:print(f"Warning: Dataset has 0 samples.")print("Please check your audio files and metadata configuration.")returnprint(f"Successfully loaded {len(dataset)} audio-text pairs.")dataloader = DataLoader(dataset,batch_size=batch_size,shuffle=True,collate_fn=collate_tts_fn,num_workers=0 if os.name == "nt" else 2,pin_memory=(device.type == "cuda"),)# 4. Optimizer & LR Scheduleroptimizer = torch.optim.AdamW(model.parameters(),lr=learning_rate,1 unmodified linebetas=(0.9, 0.98),eps=1e-8,)total_steps = len(dataloader) * max_epochsscheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_steps, eta_min=1e-6)scaler = torch.cuda.amp.GradScaler(enabled=(device.type == "cuda"))tokenizer = TextTokenizer()global_step = 0start_time = time.time()# 5. Training Loopfor epoch in range(1, max_epochs + 1):model.train()print(f"\n--- Epoch {epoch}/{max_epochs} ---")for batch_idx, batch in enumerate(dataloader):global_step += 1text_ids = batch["text_ids"].to(device)text_lens = batch["text_lengths"].to(device)mel_gt = batch["mel_gt"].to(device)mel_lens = batch["mel_lengths"].to(device)optimizer.zero_grad()with torch.cuda.amp.autocast(enabled=(device.type == "cuda")):loss_dict = model.forward_train(text_ids, text_lens, mel_gt, mel_lens)total_loss = loss_dict["total_loss"]# Anti-Explosion Checkif torch.isnan(total_loss) or torch.isinf(total_loss):print(f"[Step {global_step}] CRITICAL WARNING: Loss is NaN/Inf! Skipping step to protect weights.")continuescaler.scale(total_loss).backward()# Anti-Beep: Strict Gradient Clippingscaler.unscale_(optimizer)torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=cfg.training.grad_clip_norm)scaler.step(optimizer)scaler.update()scheduler.step()# Loggingif global_step % cfg.training.log_interval == 0:elapsed = time.time() - start_timelr = scheduler.get_last_lr()[0]print(f"Step {global_step:06d} | "f"Total Loss: {total_loss.item():.4f} | "f"CFM Loss: {loss_dict['cfm_loss'].item():.4f} | "f"Dur Loss: {loss_dict['dur_loss'].item():.4f} | "f"LR: {lr:.2e} | "f"Time: {elapsed:.1f}s")# Periodic Evaluation & Sample Audio Generationif global_step % eval_interval == 0:print(f"\n>>> Running evaluation and generating test audio at step {global_step}...")model.eval()test_prompt = "Namaste, yeh hamara 10M cutting edge TTS model bol raha hai."test_ids = tokenizer.text_to_ids(test_prompt).unsqueeze(0).to(device)with torch.no_grad():out = model.synthesize(test_ids, num_steps=8, return_waveform=True)mel = out["mel"].squeeze(0)waveform = out["waveform"].squeeze(0).cpu()# Sanity Checkis_mel_valid, mel_msg = AudioSanityGuardian.check_spectrogram(mel)is_audio_valid, audio_msg = AudioSanityGuardian.check_audio_waveform(waveform)print(f" [Sanity Check] Mel: {mel_msg}")print(f" [Sanity Check] Audio: {audio_msg}")# Save sample audiosample_path = os.path.join(output_dir, "samples", f"step_{global_step}.wav")save_audio(sample_path, waveform, 24000)print(f" Saved sample audio to: {sample_path}\n")model.train()# Periodic Checkpoint Savingif global_step % save_interval == 0:save_checkpoint(model, optimizer, global_step, output_dir)# Final savesave_checkpoint(model, optimizer, global_step, output_dir, prefix="model_final")print(f"\nTraining complete! Total steps: {global_step}. Checkpoints saved in {output_dir}")if __name__ == "__main__":parser = argparse.ArgumentParser(description="Train 10M Modern TTS Engine")parser.add_argument("--metadata", type=str, default="dataset/metadata.csv", help="Path to metadata.csv")parser.add_argument("--hf_dataset", type=str, default=None, help="Hugging Face Dataset name (e.g. ViuAI/ViuAI_TTS_Dataset)")parser.add_argument("--language", type=str, default=None, help="Filter dataset by language (e.g. 'hi')")parser.add_argument("--speaker", type=str, default=None, help="Filter dataset by speaker (e.g. 'indic_hi_male_1')")parser.add_argument("--output_dir", type=str, default="checkpoints", help="Output directory for checkpoints")parser.add_argument("--batch_size", type=int, default=16, help="Batch size")parser.add_argument("--lr", type=float, default=2e-4, help="Learning rate")parser.add_argument("--epochs", type=int, default=100, help="Number of epochs")parser.add_argument("--save_interval", type=int, default=1000, help="Save checkpoint interval (steps)")parser.add_argument("--eval_interval", type=int, default=250, help="Evaluation & audio sample interval (steps)")parser.add_argument("--device", type=str, default=None, help="Device: cuda or cpu")args = parser.parse_args()train(metadata_path=args.metadata,6 unmodified linesmax_epochs=args.epochs,save_interval=args.save_interval,eval_interval=args.eval_interval,device=args.device,)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481 unmodified line1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872886 unmodified lines295296297298299300301"""Modern Training Script for 10M TTS Engine.Features:- AdamW Optimizer with Linear Warmup + Cosine Annealing LR- Anti-Beep & Anti-Explosion Gradient Clipping (max_norm=1.0)- Automatic Mixed Precision (torch.amp) support for GPUs- Train/Validation Split & Best Model Checkpointing- Resume Support (weights + optimizer + scheduler + scaler)- Audio Sanity Guard & periodic sample generation"""import osimport mathimport timeimport argparseimport torchfrom torch.utils.data import DataLoader, random_splitfrom config import TTS10MConfigfrom models.tts_engine import TTS10MEnginefrom data.dataset import TTSDataset, collate_tts_fnfrom data.text_cleaner import TextTokenizerfrom utils.checkpoint import save_checkpoint, load_checkpoint, load_trainer_statefrom utils.audio_sanity import AudioSanityGuardian, save_audiodef build_warmup_cosine_scheduler(optimizer, warmup_steps: int, total_steps: int, min_lr_ratio: float = 0.005):def lr_lambda(current_step: int) -> float:if warmup_steps > 0 and current_step < warmup_steps:return float(current_step + 1) / float(max(1, warmup_steps))progress = float(current_step - warmup_steps) / float(max(1, total_steps - warmup_steps))progress = min(max(progress, 0.0), 1.0)cosine = 0.5 * (1.0 + math.cos(math.pi * progress))return min_lr_ratio + (1.0 - min_lr_ratio) * cosinereturn torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)@torch.no_grad()def evaluate_validation(model: TTS10MEngine, val_loader: DataLoader, device: torch.device, use_amp: bool) -> float:model.eval()total_loss = 0.0num_batches = 0for batch in val_loader:text_ids = batch["text_ids"].to(device)text_lens = batch["text_lengths"].to(device)mel_gt = batch["mel_gt"].to(device)mel_lens = batch["mel_lengths"].to(device)with torch.amp.autocast("cuda", enabled=use_amp):loss_dict = model.forward_train(text_ids, text_lens, mel_gt, mel_lens)if not (torch.isnan(loss_dict["total_loss"]) or torch.isinf(loss_dict["total_loss"])):total_loss += loss_dict["total_loss"].item()num_batches += 1model.train()return total_loss / max(1, num_batches)def train(metadata_path: str = "dataset/metadata.csv",hf_dataset: str = None,language: str = None,speaker: str = None,output_dir: str = None,batch_size: int = None,learning_rate: float = None,max_epochs: int = None,save_interval: int = None,eval_interval: int = None,val_split: float = None,resume: str = None,device: str = None,):cfg = TTS10MConfig()output_dir = output_dir or cfg.training.output_dirbatch_size = batch_size or cfg.training.batch_sizelearning_rate = learning_rate or cfg.training.learning_ratemax_epochs = max_epochs or cfg.training.max_epochssave_interval = save_interval or cfg.training.save_intervaleval_interval = eval_interval or cfg.training.eval_intervalval_split = cfg.training.val_split if val_split is None else val_splitcfg.training.output_dir = output_diros.makedirs(output_dir, exist_ok=True)os.makedirs(os.path.join(output_dir, "samples"), exist_ok=True)# 1. Device selectionif device is None:device = "cuda" if torch.cuda.is_available() else "cpu"device = torch.device(device)use_amp = device.type == "cuda"print("\n==========================================")print(f" Training 10M SOTA TTS Engine on: {device}")print("==========================================")# 2. Initialize Modelmodel = TTS10MEngine(cfg.model, cfg.training).to(device)model.print_summary()# 3. Load Datasetif hf_dataset:print(f"Loading direct from Hugging Face Hub: {hf_dataset}...")dataset = TTSDataset(hf_dataset_name=hf_dataset, language=language, speaker=speaker)else:print(f"Loading dataset from: {metadata_path}...")dataset = TTSDataset(metadata_path=metadata_path)if len(dataset) == 0:print("Warning: Dataset has 0 samples. Please check your audio files and metadata configuration.")returnprint(f"Successfully loaded {len(dataset)} audio-text pairs.")val_loader = Noneif val_split > 0 and len(dataset) >= 20:val_size = max(1, int(len(dataset) * val_split))train_size = len(dataset) - val_sizetrain_ds, val_ds = random_split(dataset, [train_size, val_size], generator=torch.Generator().manual_seed(42))print(f"Split dataset -> Train: {train_size} | Val: {val_size}")val_loader = DataLoader(val_ds,batch_size=batch_size,shuffle=False,collate_fn=collate_tts_fn,num_workers=0 if os.name == "nt" else cfg.training.num_workers,pin_memory=use_amp,)else:train_ds = datasetdataloader = DataLoader(train_ds,batch_size=batch_size,shuffle=True,collate_fn=collate_tts_fn,num_workers=0 if os.name == "nt" else cfg.training.num_workers,pin_memory=use_amp,)if len(dataloader) == 0:print("Warning: DataLoader has 0 batches.")return# 4. Optimizer, Warmup+Cosine Scheduler & AMP Scaleroptimizer = torch.optim.AdamW(model.parameters(),lr=learning_rate,1 unmodified linebetas=(0.9, 0.98),eps=1e-8,)total_steps = len(dataloader) * max_epochsscheduler = build_warmup_cosine_scheduler(optimizer, warmup_steps=cfg.training.warmup_steps, total_steps=total_steps)scaler = torch.amp.GradScaler("cuda", enabled=use_amp)global_step = 0start_epoch = 1best_val_loss = float("inf")if resume:load_checkpoint(model, resume, device=str(device))resume_dir = os.path.dirname(resume) or output_dirstate = load_trainer_state(resume_dir, optimizer, scheduler, scaler, device=str(device))global_step = state.get("step", 0)start_epoch = state.get("epoch", 0) + 1if state.get("best_val_loss") is not None:best_val_loss = state["best_val_loss"]tokenizer = TextTokenizer()start_time = time.time()# 5. Training Loopfor epoch in range(start_epoch, max_epochs + 1):model.train()print(f"\n--- Epoch {epoch}/{max_epochs} ---")for batch in dataloader:global_step += 1text_ids = batch["text_ids"].to(device)text_lens = batch["text_lengths"].to(device)mel_gt = batch["mel_gt"].to(device)mel_lens = batch["mel_lengths"].to(device)optimizer.zero_grad(set_to_none=True)with torch.amp.autocast("cuda", enabled=use_amp):loss_dict = model.forward_train(text_ids, text_lens, mel_gt, mel_lens)total_loss = loss_dict["total_loss"]if torch.isnan(total_loss) or torch.isinf(total_loss):print(f"[Step {global_step}] CRITICAL WARNING: Loss is NaN/Inf! Skipping step to protect weights.")optimizer.zero_grad(set_to_none=True)scheduler.step()continuescaler.scale(total_loss).backward()scaler.unscale_(optimizer)torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=cfg.training.grad_clip_norm)scaler.step(optimizer)scaler.update()scheduler.step()if global_step % cfg.training.log_interval == 0:elapsed = time.time() - start_timelr = scheduler.get_last_lr()[0]print(f"Step {global_step:06d} | "f"Total: {total_loss.item():.4f} | "f"CFM: {loss_dict['cfm_loss'].item():.4f} | "f"Dur: {loss_dict['dur_loss'].item():.4f} | "f"Prior: {loss_dict['prior_loss'].item():.4f} | "f"LR: {lr:.2e} | "f"Time: {elapsed:.1f}s")if global_step % eval_interval == 0:print(f"\n>>> Running evaluation at step {global_step}...")if val_loader is not None:val_loss = evaluate_validation(model, val_loader, device, use_amp)print(f" [Validation] Loss: {val_loss:.4f} (Best: {best_val_loss:.4f})")if val_loss < best_val_loss:best_val_loss = val_losssave_checkpoint(model, optimizer, global_step, output_dir,prefix="model_best", scheduler=scheduler, scaler=scaler,epoch=epoch, best_val_loss=best_val_loss, save_latest=False,)model.eval()test_prompt = "नमस्ते, यह हमारा हिंदी टेक्स्ट टू स्पीच मॉडल बोल रहा है।"test_ids = tokenizer.text_to_ids(test_prompt).unsqueeze(0).to(device)with torch.no_grad():out = model.synthesize(test_ids, num_steps=cfg.model.default_ode_steps, return_waveform=True)mel = out["mel"].squeeze(0)waveform = out["waveform"].squeeze(0).cpu()_, mel_msg = AudioSanityGuardian.check_spectrogram(mel)_, audio_msg = AudioSanityGuardian.check_audio_waveform(waveform, cfg.audio.sample_rate)print(f" [Sanity Check] Mel: {mel_msg}")print(f" [Sanity Check] Audio: {audio_msg}")sample_path = os.path.join(output_dir, "samples", f"step_{global_step}.wav")save_audio(sample_path, waveform, cfg.audio.sample_rate)print(f" Saved sample audio to: {sample_path}\n")model.train()if global_step % save_interval == 0:save_checkpoint(model, optimizer, global_step, output_dir,scheduler=scheduler, scaler=scaler, epoch=epoch, best_val_loss=best_val_loss,)save_checkpoint(model, optimizer, global_step, output_dir, prefix="model_final",scheduler=scheduler, scaler=scaler, epoch=max_epochs, best_val_loss=best_val_loss,)print(f"\nTraining complete! Total steps: {global_step}. Checkpoints saved in {output_dir}")if __name__ == "__main__":default_cfg = TTS10MConfig()parser = argparse.ArgumentParser(description="Train 10M Modern TTS Engine")parser.add_argument("--metadata", type=str, default="dataset/metadata.csv", help="Path to metadata.csv")parser.add_argument("--hf_dataset", type=str, default=None, help="Hugging Face Dataset name")parser.add_argument("--language", type=str, default=None, help="Filter dataset by language")parser.add_argument("--speaker", type=str, default=None, help="Filter dataset by speaker")parser.add_argument("--output_dir", type=str, default=default_cfg.training.output_dir, help="Output directory")parser.add_argument("--batch_size", type=int, default=default_cfg.training.batch_size, help="Batch size")parser.add_argument("--lr", type=float, default=default_cfg.training.learning_rate, help="Learning rate")parser.add_argument("--epochs", type=int, default=default_cfg.training.max_epochs, help="Number of epochs")parser.add_argument("--save_interval", type=int, default=default_cfg.training.save_interval, help="Save interval")parser.add_argument("--eval_interval", type=int, default=default_cfg.training.eval_interval, help="Eval interval")parser.add_argument("--val_split", type=float, default=default_cfg.training.val_split, help="Validation split fraction")parser.add_argument("--resume", type=str, default=None, help="Path to checkpoint to resume from")parser.add_argument("--device", type=str, default=None, help="Device: cuda or cpu")args = parser.parse_args()train(metadata_path=args.metadata,6 unmodified linesmax_epochs=args.epochs,save_interval=args.save_interval,eval_interval=args.eval_interval,val_split=args.val_split,resume=args.resume,device=args.device,)
2 unmodified lines3456789101 unmodified line12131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354554 unmodified lines6061626364656667686970712 unmodified linesDetects flat tones, robotic beeps, NaNs, clipping, or collapsed spectrograms in real-time."""import torchfrom typing import Dict, Tupleclass AudioSanityGuardian:1 unmodified linedef check_spectrogram(mel: torch.Tensor) -> Tuple[bool, str]:"""Validates Mel-spectrogram before vocoding.mel: (80, T) or (B, 80, T)"""if torch.isnan(mel).any() or torch.isinf(mel).any():return False, "CRITICAL ERROR: Spectrogram contains NaN or Inf values!"# Check standard deviation across frequency bins# A robotic beep has near zero frequency variance (pure horizontal stripe)freq_std = torch.std(mel, dim=-2).mean().item()if freq_std < 0.05:return False, f"WARNING: Collapsed spectrum detected (freq std={freq_std:.4f} < 0.05). Risk of beep tone!"return True, "Spectrogram is healthy and diverse."@staticmethod4 unmodified lines"""if waveform.dim() > 1:waveform = waveform.squeeze(0)if torch.isnan(waveform).any() or torch.isinf(waveform).any():return False, "CRITICAL ERROR: Waveform contains NaN/Inf values!"max_amp = torch.max(torch.abs(waveform)).item()if max_amp < 1e-4:return False, "WARNING: Audio is completely silent!"# Check for pure sinusoidal tone / beep by inspecting peak energy ratio in FFTfft = torch.fft.rfft(waveform)power = torch.abs(fft) ** 2total_energy = power.sum().item()max_energy = power.max().item()if total_energy > 0 and (max_energy / total_energy) > 0.85:return False, "WARNING: Strong single-frequency tone detected (Peak energy > 85%). This is a robot beep!"return True, "Audio waveform is clean and natural."4 unmodified lines"""import numpy as npfrom scipy.io import wavfileif isinstance(waveform, torch.Tensor):waveform = waveform.detach().cpu().squeeze().numpy()# Clip and convert to int16 PCMwaveform = np.clip(waveform, -1.0, 1.0)int16_audio = (waveform * 32767.0).astype(np.int16)wavfile.write(file_path, sample_rate, int16_audio)2 unmodified lines345678910111 unmodified line131415161718192021222324252627282930313233344 unmodified lines39404142434445464748495051525354555657585960616263644 unmodified lines6970717273747576777879808182832 unmodified linesDetects flat tones, robotic beeps, NaNs, clipping, or collapsed spectrograms in real-time."""import osimport torchfrom typing import Tupleclass AudioSanityGuardian:1 unmodified linedef check_spectrogram(mel: torch.Tensor) -> Tuple[bool, str]:"""Validates Mel-spectrogram before vocoding.mel: (n_mels, T) or (B, n_mels, T)"""if torch.isnan(mel).any() or torch.isinf(mel).any():return False, "CRITICAL ERROR: Spectrogram contains NaN or Inf values!"# Check standard deviation across frequency binsfreq_std = torch.std(mel, dim=-2).mean().item()if freq_std < 0.05:return False, f"WARNING: Collapsed spectrum detected (freq std={freq_std:.4f} < 0.05). Risk of beep tone!"# Check standard deviation across time frames (catches constant sustained buzz/tone)if mel.shape[-1] > 1:time_std = torch.std(mel, dim=-1).mean().item()if time_std < 0.02:return False, f"WARNING: Constant static spectrum across time (time std={time_std:.4f} < 0.02). Risk of sustained tone!"return True, "Spectrogram is healthy and diverse."@staticmethod4 unmodified lines"""if waveform.dim() > 1:waveform = waveform.squeeze(0)if waveform.numel() == 0:return False, "WARNING: Audio waveform is empty!"if torch.isnan(waveform).any() or torch.isinf(waveform).any():return False, "CRITICAL ERROR: Waveform contains NaN/Inf values!"max_amp = torch.max(torch.abs(waveform)).item()if max_amp < 1e-4:return False, "WARNING: Audio is completely silent!"# Check for pure sinusoidal tone / beep by inspecting peak energy ratio in FFTfft = torch.fft.rfft(waveform.float())power = torch.abs(fft) ** 2total_energy = power.sum().item()max_energy = power.max().item()if total_energy > 0 and (max_energy / total_energy) > 0.85:return False, "WARNING: Strong single-frequency tone detected (Peak energy > 85%). This is a robot beep!"return True, "Audio waveform is clean and natural."4 unmodified lines"""import numpy as npfrom scipy.io import wavfileparent_dir = os.path.dirname(file_path)if parent_dir:os.makedirs(parent_dir, exist_ok=True)if isinstance(waveform, torch.Tensor):waveform = waveform.detach().cpu().squeeze().numpy()waveform = np.clip(waveform, -1.0, 1.0)int16_audio = (waveform * 32767.0).astype(np.int16)wavfile.write(file_path, sample_rate, int16_audio)
1234561 unmodified line8910111213142 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859601 unmodified line62636465666768697071727374757677"""Checkpointing and Hugging Face Model Hub Publishing Utilities.Uses safe, modern .safetensors format and automatic model card generation."""import os1 unmodified lineimport torchfrom safetensors.torch import save_file, load_filefrom huggingface_hub import HfApi, login, create_repofrom typing import Optional, Dictdef save_checkpoint(2 unmodified linesstep: int,output_dir: str,prefix: str = "model",):"""Saves model weights using safe .safetensors format."""os.makedirs(output_dir, exist_ok=True)# 1. Save model weightsstate_dict = model.state_dict()# Filter out vocoder weights (which are loaded from Vocos pretrained)acoustic_weights = {k: v for k, v in state_dict.items() if not k.startswith("vocoder.")}weights_path = os.path.join(output_dir, f"{prefix}_{step}.safetensors")save_file(acoustic_weights, weights_path)# 2. Save latest symlink/copylatest_path = os.path.join(output_dir, "model.safetensors")save_file(acoustic_weights, latest_path)# 3. Save training metadatameta = {"step": step}with open(os.path.join(output_dir, "metadata.json"), "w") as f:json.dump(meta, f, indent=2)print(f"Checkpoint saved successfully at step {step} -> {weights_path}")def load_checkpoint(model: torch.nn.Module, checkpoint_path: str, device: str = "cpu"):"""Loads weights from .safetensors or .pt."""print(f"Loading checkpoint from: {checkpoint_path}...")if checkpoint_path.endswith(".safetensors"):state_dict = load_file(checkpoint_path, device=device)else:state_dict = torch.load(checkpoint_path, map_location=device)# Non-strict load to ignore preloaded vocodermissing, unexpected = model.load_state_dict(state_dict, strict=False)print(f"Loaded successfully. (Missing keys: {len(missing)}, Unexpected keys: {len(unexpected)})")return modeldef push_to_huggingface_hub(repo_id: str,folder_path: str,1 unmodified lineprivate: bool = False,commit_message: str = "Upload 10M Modern TTS model",):"""Pushes model checkpoints, configs, and README to Hugging Face Model Hub."""if token:login(token=token)api = HfApi()print(f"Ensuring repository exists on Hugging Face: {repo_id}...")create_repo(repo_id, repo_type="model", private=private, exist_ok=True)print(f"Uploading files from {folder_path} to {repo_id}...")api.upload_folder(folder_path=folder_path,1234561 unmodified line8910111213142 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051 unmodified line107108109110111112113114115116117118119120"""Checkpointing and Hugging Face Model Hub Publishing Utilities.Uses safe, modern .safetensors format for weights and companion trainer_state.pt for resume."""import os1 unmodified lineimport torchfrom safetensors.torch import save_file, load_filefrom huggingface_hub import HfApi, login, create_repofrom typing import Optional, Dict, Anydef save_checkpoint(2 unmodified linesstep: int,output_dir: str,prefix: str = "model",scheduler: Optional[Any] = None,scaler: Optional[Any] = None,epoch: int = 0,best_val_loss: Optional[float] = None,save_latest: bool = True,):"""Saves acoustic model weights (.safetensors) and optional trainer state (.pt)."""os.makedirs(output_dir, exist_ok=True)state_dict = model.state_dict()acoustic_weights = {k: v.detach().cpu() for k, v in state_dict.items() if not k.startswith("vocoder.")}weights_path = os.path.join(output_dir, f"{prefix}_{step}.safetensors") if prefix != "model_best" else os.path.join(output_dir, "model_best.safetensors")save_file(acoustic_weights, weights_path)if save_latest:latest_path = os.path.join(output_dir, "model.safetensors")save_file(acoustic_weights, latest_path)if optimizer is not None:trainer_state: Dict[str, Any] = {"step": step,"epoch": epoch,"best_val_loss": best_val_loss,"optimizer": optimizer.state_dict(),}if scheduler is not None:trainer_state["scheduler"] = scheduler.state_dict()if scaler is not None:trainer_state["scaler"] = scaler.state_dict()torch.save(trainer_state, os.path.join(output_dir, "trainer_state.pt"))meta = {"step": step, "epoch": epoch, "best_val_loss": best_val_loss}with open(os.path.join(output_dir, "metadata.json"), "w", encoding="utf-8") as f:json.dump(meta, f, indent=2)print(f"Checkpoint saved successfully at step {step} -> {weights_path}")def load_checkpoint(model: torch.nn.Module, checkpoint_path: str, device: str = "cpu"):"""Loads weights from .safetensors or .pt."""if not os.path.exists(checkpoint_path):raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")print(f"Loading checkpoint from: {checkpoint_path}...")if checkpoint_path.endswith(".safetensors"):state_dict = load_file(checkpoint_path, device=device)else:state_dict = torch.load(checkpoint_path, map_location=device, weights_only=True)if not state_dict:raise ValueError(f"Checkpoint {checkpoint_path} is empty.")# Remap legacy vector_field.* keys to cfm.vf.* if neededremapped = {}for k, v in state_dict.items():if k.startswith("vector_field.") and ("cfm.vf." + k[len("vector_field."):]) not in state_dict:remapped["cfm.vf." + k[len("vector_field."):]] = velse:remapped[k] = vmissing, unexpected = model.load_state_dict(remapped, strict=False)print(f"Loaded successfully. (Missing keys: {len(missing)}, Unexpected keys: {len(unexpected)})")return modeldef load_trainer_state(checkpoint_dir: str, optimizer, scheduler=None, scaler=None, device: str = "cpu") -> Dict[str, Any]:"""Loads optimizer/scheduler/scaler state from trainer_state.pt if present."""state_path = os.path.join(checkpoint_dir, "trainer_state.pt")if not os.path.exists(state_path):return {"step": 0, "epoch": 0, "best_val_loss": None}state = torch.load(state_path, map_location=device, weights_only=False)if optimizer is not None and "optimizer" in state:optimizer.load_state_dict(state["optimizer"])if scheduler is not None and "scheduler" in state:scheduler.load_state_dict(state["scheduler"])if scaler is not None and "scaler" in state:scaler.load_state_dict(state["scaler"])print(f"Resumed trainer state at epoch {state.get('epoch', 0)}, step {state.get('step', 0)}.")return statedef push_to_huggingface_hub(repo_id: str,folder_path: str,1 unmodified lineprivate: bool = False,commit_message: str = "Upload 10M Modern TTS model",):"""Pushes model checkpoints, configs, and README to Hugging Face Model Hub."""if token:login(token=token)api = HfApi()print(f"Ensuring repository exists on Hugging Face: {repo_id}...")create_repo(repo_id, repo_type="model", private=private, exist_ok=True)print(f"Uploading files from {folder_path} to {repo_id}...")api.upload_folder(folder_path=folder_path,
.gitignoreAdded+7
README.md+5-5
app.py+35-31
config.py+21-15
data/audio_processor.py+57-26
data/dataset.py+52-43
data/hf_dataset_sync.py+44-18
data/text_cleaner.py+62-12
export_hf.py+56-56
infer.py+40-37
kaggle_data_collector.py+138-100
models/convnext.py+33-12
models/duration_predictor.py+93-53
models/flow_matching.py+81-47
models/text_encoder.py+27-22
models/tts_engine.py+126-76
models/vocoder.py+6-7
train.py+181-85
utils/audio_sanity.py+27-15
utils/checkpoint.py+70-27