"""Evaluate every Ming TTS tier on the fixed WebFM eval set (eval/sentences.json). Runs the teacher and the distilled students over the same voice x sentence matrix, writes one wav per cell and one JSONL row per cell, then leaves the scoring to `eval/score.py`. The teacher is generated in the same run and on the same sentences: a candidate is only meaningful as a delta against it. Expected Kaggle inputs: /kaggle/input/webfm-eval/eval/sentences.json (this repo's eval/) /kaggle/input/webfm-eval/config/ming_voices.json /kaggle/input/webfm-eval/refs/wav/v01.wav .. v08.wav /kaggle/working/Ming-3.0-tts + Ming-3.0-tts-0.5b (as in ming_multistep.py) Env: VOICES=v01,v02,... subset of voices, for splitting across two GPUs MODELS=teacher,3step,4step LIMIT=40 sentences to run SEED=20261021 Resumable: a cell whose wav exists is not regenerated; the JSONL is appended and flushed per row, so a killed session keeps what it finished. """ from __future__ import annotations import json import os import re import sys import time import traceback from pathlib import Path import numpy as np import torch import torchaudio ROOT = Path("/kaggle/working") REPO = ROOT / "Ming-3.0-tts" MODEL_DIR = ROOT / "Ming-3.0-tts-0.5b" DATA = Path(os.environ.get("EVAL_DATA", "/kaggle/input/webfm-eval")) OUT = ROOT / "ming_eval" WAV = OUT / "wav" ROWS = OUT / "results.jsonl" LOG = OUT / "eval.log" SEED = int(os.environ.get("SEED", "20261021")) LIMIT = int(os.environ.get("LIMIT", "40")) VOICE_FILTER = [v for v in os.environ.get("VOICES", "").split(",") if v] MODELS = [m for m in os.environ.get("MODELS", "teacher,3step,4step").split(",") if m] TEACHER_STEPS = 10 TEACHER_CFG = 2.0 STUDENT_REPOS = { "1step": ("idefinity/ming-3.0-tts-1step-distill-int4", 1), "2step": ("idefinity/ming-3.0-tts-2step-distill-int4", 2), "3step": ("idefinity/ming-3.0-tts-3step-distill-int4", 3), "4step": ("idefinity/ming-3.0-tts-4step-distill-int4", 4), } for p in (OUT, WAV): p.mkdir(parents=True, exist_ok=True) def log(msg: str) -> None: line = f"[{time.strftime('%H:%M:%S')}] {msg}" print(line, flush=True) with open(LOG, "a") as f: f.write(line + "\n") def patch_fp32() -> None: """T4 has no bf16; the repo defaults to bf16 and NaNs out under fp16.""" for name in ("ming_tts.py", "modeling_bailingmm.py"): path = REPO / name s = path.read_text() s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32") s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)") s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32") path.write_text(s) def done_cells() -> set[tuple[str, str, str]]: seen = set() if ROWS.exists(): for line in ROWS.read_text().splitlines(): if not line.strip(): continue try: r = json.loads(line) seen.add((r["model"], r["voice"], r["id"])) except Exception: continue return seen def sample_latent(student, z, history, noise, n_steps): y = noise for i in range(n_steps): dt = 1.0 / n_steps v = student( x=y, t=torch.full((y.shape[0],), i / n_steps, device=y.device), c=z, latent_history=history, mask=None, )[:, -1:, :] y = y + v * dt return y def ar_generate(mm, dit, n_steps, prompt, text, prompt_latent, prompt_text, spk_emb, frames): """Autoregressive rollout with a chosen flow head. Length is forced to the teacher's frame count, so this measures content and timbre, not stopping.""" device = next(mm.parameters()).device dtype = next(mm.parameters()).dtype with torch.no_grad(): input_ids, inputs_embeds = mm.prepare_input_embed( prompt=prompt, text=text, spk_emb=spk_emb, prompt_latent=prompt_latent, prompt_text=prompt_text, ) attention_mask = torch.ones(input_ids.shape, device=device) position_ids = (attention_mask.cumsum(-1) - 1).masked_fill_(attention_mask == 0, 1) past = None history = torch.zeros(1, mm.history_patch_size, mm.latent_dim, device=device, dtype=dtype) if prompt_latent is not None: start = mm.history_patch_size - prompt_latent.size(1) if start < 0: history[:] = prompt_latent[:, -start:, :] else: history[:, start:, :] = prompt_latent out = [] for _ in range(frames): with torch.no_grad(): hidden = mm.model( attention_mask=attention_mask, position_ids=position_ids, inputs_embeds=inputs_embeds, audio_mask=None, image_mask=None, output_hidden_states=True, return_dict=True, use_cache=True, past_key_values=past, ) past = hidden.past_key_values z = hidden.hidden_states[-1][:, -1:, :] noise = torch.randn(1, 1, mm.latent_dim, device=device, dtype=dtype) latent = sample_latent(dit, z, history, noise, n_steps).to(device=device, dtype=dtype) out.append(latent) inputs_embeds = mm.linear_proj_audio(latent) position_ids = position_ids[:, -1:] + 1 attention_mask = torch.ones(inputs_embeds.shape[0], 1, device=device) history[:, :-mm.patch_size, :] = history[:, mm.patch_size:, :].clone() history[:, -mm.patch_size:, :] = latent with torch.no_grad(): speech = mm.audio.decode(torch.cat(out, dim=1), past_key_values=None, use_cache=False, last_chunk=True)[0] return speech.cpu().float().reshape(-1).numpy() def load_student(name: str, teacher_dit, device): from huggingface_hub import hf_hub_download repo, steps = STUDENT_REPOS[name] path = hf_hub_download(repo_id=repo, filename=f"distill/student_{steps}step.pt") state = torch.load(path, map_location="cpu") state = {k: v.float() for k, v in state.items()} import copy dit = copy.deepcopy(teacher_dit) dit.load_state_dict(state) return dit.to(device).eval(), steps def build_asr(): from transformers import pipeline kwargs = {"model": "openai/whisper-small", "device": 0} try: pipe = pipeline("automatic-speech-recognition", torch_dtype=torch.float16, **kwargs) except Exception: pipe = pipeline("automatic-speech-recognition", **kwargs) def asr(wav: np.ndarray, sr: int = 44100) -> str: # No initial_prompt here: transformers 4.46 rejects it as a generate # kwarg. Whisper's traditional-character output is handled downstream # by eval/score.py, which normalises before counting edits. out = pipe( {"array": wav.astype(np.float32), "sampling_rate": sr}, generate_kwargs={"language": "zh", "task": "transcribe"}, ) return out.get("text", "") if isinstance(out, dict) else str(out) return asr def main() -> None: torch.manual_seed(SEED) if torch.cuda.is_available(): torch.cuda.manual_seed_all(SEED) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") log(f"device={device} limit={LIMIT} models={MODELS} voices={VOICE_FILTER or 'all'}") sys.path.insert(0, str(REPO)) patch_fp32() from ming_tts import MingTTS import tts_tasks sentences = json.loads((DATA / "eval/sentences.json").read_text())["items"][:LIMIT] voices = json.loads((DATA / "config/ming_voices.json").read_text())["voices"] if VOICE_FILTER: voices = [v for v in voices if v["id"] in VOICE_FILTER] log(f"sentences={len(sentences)} voices={[v['id'] for v in voices]}") tts = MingTTS(str(MODEL_DIR), device=str(device), text_normalization=False) mm = tts.model dtype = next(mm.parameters()).dtype prompt = tts_tasks.build_tts_prompt("Chinese") teacher_dit = mm.flowloss.cfm.model.float().eval() for p in teacher_dit.parameters(): p.requires_grad_(False) students = {} for name in MODELS: if name in STUDENT_REPOS: students[name], steps = load_student(name, teacher_dit, device) log(f"loaded student {name} ({steps} steps)") asr = build_asr() spk = tts.spkemb_extractor mel = torchaudio.transforms.MelSpectrogram( sample_rate=44100, n_fft=1024, hop_length=256, n_mels=80, power=2.0 ) def speaker_cos(ref: np.ndarray, hyp: np.ndarray) -> float: a = torchaudio.functional.resample(torch.from_numpy(ref).float(), 44100, 16000).unsqueeze(0) b = torchaudio.functional.resample(torch.from_numpy(hyp).float(), 44100, 16000).unsqueeze(0) ea, eb = spk(a).reshape(-1).float(), spk(b).reshape(-1).float() return float(torch.dot(ea, eb) / (ea.norm() * eb.norm() + 1e-9)) def mel_l1(ref: np.ndarray, hyp: np.ndarray) -> float: mr = torch.log(mel(torch.from_numpy(ref).float().unsqueeze(0)) + 1e-6).squeeze(0) mh = torch.log(mel(torch.from_numpy(hyp).float().unsqueeze(0)) + 1e-6).squeeze(0) n = min(mr.shape[-1], mh.shape[-1]) return float((mr[..., :n] - mh[..., :n]).abs().mean()) seen = done_cells() log(f"resume: {len(seen)} cells already done") for voice in voices: vid = voice["id"] wav_path = DATA / voice["promptWav"] prompt_text = voice["promptText"] prompt_latent, spk_emb = tts.prepare_prompt(str(wav_path), use_spk_emb=True) prompt_latent = prompt_latent.to(device=device, dtype=dtype) spk_emb = [x.to(device=device, dtype=dtype) for x in spk_emb] for item in sentences: sid, text = item["id"], item["text"] ref_wav_path = WAV / "teacher" / vid / f"{sid}.wav" if ("teacher", vid, sid) not in seen: try: t0 = time.time() wav = tts.synthesize( task="TTS", text=text, language_id="Chinese", prompt_wav_path=str(wav_path), prompt_text=prompt_text, use_spk_emb=True, raw_text=True, max_decode_steps=max(16, min(400, int(len(text) * 3.0))), ) arr = wav.cpu().numpy().reshape(-1) ref_wav_path.parent.mkdir(parents=True, exist_ok=True) torchaudio.save(str(ref_wav_path), torch.from_numpy(arr).unsqueeze(0), 44100) frames = max(16, int(round(arr.size / 3528))) with open(ROWS, "a") as f: f.write(json.dumps({ "model": "teacher", "voice": vid, "id": sid, "bucket": item["bucket"], "text": text, "hyp_text": asr(arr), "frames": frames, "seconds": arr.size / 44100, "wall": time.time() - t0, }, ensure_ascii=False) + "\n") seen.add(("teacher", vid, sid)) log(f"teacher {vid} {sid} {arr.size/44100:.2f}s in {time.time()-t0:.1f}s") except Exception: log(f"teacher {vid} {sid} failed\n{traceback.format_exc()}") continue if not ref_wav_path.exists(): continue ref_audio, _ = torchaudio.load(str(ref_wav_path)) ref_audio = ref_audio.reshape(-1).numpy() frames = max(16, int(round(ref_audio.size / 3528))) for name, dit in students.items(): if (name, vid, sid) in seen: continue try: t0 = time.time() torch.manual_seed(SEED) arr = ar_generate(mm, dit, STUDENT_REPOS[name][1], prompt, text, prompt_latent, prompt_text, spk_emb, frames) path = WAV / name / vid / f"{sid}.wav" path.parent.mkdir(parents=True, exist_ok=True) torchaudio.save(str(path), torch.from_numpy(arr).unsqueeze(0), 44100) with open(ROWS, "a") as f: f.write(json.dumps({ "model": name, "voice": vid, "id": sid, "bucket": item["bucket"], "text": text, "hyp_text": asr(arr), "spk_cos": speaker_cos(ref_audio, arr), "mel_l1": mel_l1(ref_audio, arr), "dur_ratio": arr.size / max(1, ref_audio.size), "wall": time.time() - t0, }, ensure_ascii=False) + "\n") seen.add((name, vid, sid)) log(f"{name} {vid} {sid} in {time.time()-t0:.1f}s") except Exception: log(f"{name} {vid} {sid} failed\n{traceback.format_exc()}") log("DONE") if __name__ == "__main__": try: main() except Exception: log(traceback.format_exc()) raise