File size: 13,033 Bytes
bc7b7ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcf8a1d
 
 
bc7b7ea
 
fcf8a1d
bc7b7ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""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