"""Distil the Ming flow head on the seven mined voices. Why this run: the existing 3/4-step students were trained on 200 utterances of a single voice (`lingguang`). On a clean prompt at eval time they cost +5.2 pp (v08, 4step) to +11.8 pp (3step) CER against the teacher. The hypothesis is that the gap is voice generalisation, not step count, and the fix is trajectory data that spans the voices we actually ship. One variable changes this round: the data. The training recipe is copied from ming_multistep.py unchanged, including the CFG coefficient, so the new student is comparable to the old one. If multi-voice data does not close the gap, that coefficient is the next thing to look at. Stages: STAGE=traj shard by VOICES env, write traj/{voice}/{i}.pt, resumable STAGE=train merge shards, train the 4-step CFG-free student STAGE=export ONNX fp32 + int4, validate against PyTorch STAGE=eval 40 sentences x EVAL_VOICES x {teacher, student} STAGE=all train -> export -> eval (traj is run separately, per GPU) """ import json import os import sys import time import traceback from pathlib import Path import numpy as np ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working")) REPO = ROOT / "Ming-3.0-tts" MODEL = ROOT / "Ming-3.0-tts-0.5b" BUNDLE = ROOT / "webfm-eval" OUT = ROOT / "train" TRAJ = OUT / "traj" STAGE = os.environ.get("STAGE", "all") SEED = 20261030 STEPS = int(os.environ.get("STEPS", "4")) TRAIN_STEPS = int(os.environ.get("TRAIN_STEPS", "1500")) BATCH = int(os.environ.get("BATCH", "16")) LR = float(os.environ.get("LR", "1e-4")) VOICE_FILTER = [v for v in os.environ.get("VOICES", "").split(",") if v] EVAL_VOICES = [v for v in os.environ.get("EVAL_VOICES", "").split(",") if v] HOLDOUT = {v for v in os.environ.get("HOLDOUT", "").split(",") if v} N_TEXTS = int(os.environ.get("N_TEXTS", "120")) SMOKE = os.environ.get("SMOKE", "0") == "1" SAVE_WAVS = os.environ.get("SAVE_WAVS", "0") == "1" TEACHER_CFG = 2.0 CFG_MULT = 2.0 # unchanged from ming_multistep.py, for comparability DROP = {"Miss哈尼"} def log(msg: str) -> None: print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) def patch_fp32() -> None: 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 voices(include_holdout: bool = False) -> list[dict]: vs = json.loads((BUNDLE / "mined/manifest.json").read_text())["voices"] vs = [v for v in vs if v["artist"] not in DROP] if not include_holdout: vs = [v for v in vs if v["slot"] not in HOLDOUT] if VOICE_FILTER: vs = [v for v in vs if v["slot"] in VOICE_FILTER] return vs def texts() -> list[str]: t = json.loads((BUNDLE / "train_texts.json").read_text())["texts"] return t[:N_TEXTS] def stage_traj() -> None: import torch sys.path.insert(0, str(REPO)) from ming_tts import MingTTS import tts_tasks TRAJ.mkdir(parents=True, exist_ok=True) tts = MingTTS(str(MODEL), device="cuda", text_normalization=False) mm = tts.model device = next(mm.parameters()).device dtype = next(mm.parameters()).dtype task_prompt = tts_tasks.build_tts_prompt("Chinese") torch.set_grad_enabled(False) total = 0 for v in voices(): vdir = TRAJ / v["slot"] vdir.mkdir(parents=True, exist_ok=True) prompt_latent, spk = tts.prepare_prompt(str(BUNDLE / v["wav"]), use_spk_emb=True) prompt_latent = prompt_latent.to(device=device, dtype=dtype) spk = [x.to(device=device, dtype=dtype) for x in spk] for i, text in enumerate(texts()): dst = vdir / f"{i:04d}.pt" if dst.exists(): continue try: torch.manual_seed(SEED + i) input_ids, inputs_embeds = mm.prepare_input_embed( prompt=task_prompt, text=text, spk_emb=spk, prompt_latent=prompt_latent, prompt_text=v["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 hist = torch.zeros(1, mm.history_patch_size, mm.latent_dim, device=device, dtype=dtype) start = mm.history_patch_size - prompt_latent.size(1) if start < 0: hist[:] = prompt_latent[:, -start:, :] else: hist[:, start:, :] = prompt_latent budget = (512 - inputs_embeds.shape[1]) // mm.patch_size n = max(1, min(200, max(16, int(len(text) * 2.6)), budget)) zs, hs, ns, ls = [], [], [], [] for _ in range(n): with torch.no_grad(): out = 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 = out.past_key_values z = out.hidden_states[-1][:, -1:, :] noise = torch.randn(1, 1, mm.latent_dim, device=device, dtype=dtype) sde = torch.randn(10, 1, 1, mm.latent_dim, device=device, dtype=dtype) with torch.no_grad(): latent = mm.flowloss.cfm.sample( noise=noise, c=z, latent_history=hist, sde_noise=sde, cfg_scale=TEACHER_CFG, sway_sampling_coef=-1.0, use_epss=True, patch_size=1, sigma=0.25, temperature=0.0, ) zs.append(z[0, 0].detach().float().cpu()) hs.append(hist[0].detach().float().cpu()) ns.append(noise[0, 0].detach().float().cpu()) ls.append(latent[0, 0].detach().float().cpu()) inputs_embeds = mm.linear_proj_audio(latent) position_ids = position_ids[:, -1:] + 1 attention_mask = torch.ones(inputs_embeds.shape[0], 1, device=device) hist[:, :-mm.patch_size, :] = hist[:, mm.patch_size:, :].clone() hist[:, -mm.patch_size:, :] = latent torch.save({"text": text, "voice": v["slot"], "z": torch.stack(zs), "history": torch.stack(hs), "noise": torch.stack(ns), "latent": torch.stack(ls)}, dst) total += n if i % 10 == 0: log(f"{v['slot']} {i+1}/{len(texts())} frames={n} total={total}") except Exception: log(f"{v['slot']} {i} failed\n{traceback.format_exc()}") if SMOKE and i >= 4: break log(f"traj done: {total} frames") def load_dataset(): import torch cache = BUNDLE / "traj.zip" if not any(TRAJ.glob("*/*.pt")) and cache.exists(): import zipfile log(f"unpacking {cache} ({cache.stat().st_size // 1024 // 1024} MB)") with zipfile.ZipFile(cache) as z: z.extractall(ROOT / "train") zs, hs, ns, ls = [], [], [], [] for path in sorted(TRAJ.glob("*/*.pt")): row = torch.load(path, map_location="cpu", weights_only=False) zs.append(row["z"]); hs.append(row["history"]) ns.append(row["noise"]); ls.append(row["latent"]) if not zs: raise RuntimeError("no trajectories") z, h, n, l = (torch.cat(x).float() for x in (zs, hs, ns, ls)) log(f"dataset: {z.shape[0]} frames from {len(zs)} files") return z, h, n, l def train_student(teacher, data, n_steps, device): import copy import torch import torch.nn.functional as F z, h, n, target = [x.to(device) for x in data] count = z.shape[0] student = copy.deepcopy(teacher).to(device).train() for p in student.parameters(): p.requires_grad_(True) opt = torch.optim.AdamW(student.parameters(), lr=LR, weight_decay=0.01) times = torch.linspace(0, 1, n_steps + 1).tolist() losses = [] for step in range(TRAIN_STEPS): idx = torch.randint(0, count, (min(BATCH, count),), device=device) bz, bh = z[idx].unsqueeze(1), h[idx] bn, bt = n[idx].unsqueeze(1), target[idx].unsqueeze(1) y = bn loss = 0.0 for i in range(n_steps): ti, dt = times[i], times[i + 1] - times[i] with torch.no_grad(): pred_cfg = teacher.forward_with_cfg( x=y, t=torch.tensor(float(ti), device=device), c=bz, latent_history=bh, patch_size=1, ) pred, null = torch.chunk(pred_cfg, 2, dim=0) tv = pred + (pred - null) * CFG_MULT sv = student( x=y, t=torch.full((y.shape[0],), float(ti), device=device), c=bz, latent_history=bh, mask=None, )[:, -1:, :] loss = loss + F.mse_loss(sv, tv) * dt y = (y + sv * dt).detach() loss = loss + 0.5 * F.mse_loss(y, bt) opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0) opt.step() losses.append(float(loss.detach().cpu())) if step % 100 == 0 or step == TRAIN_STEPS - 1: log(f"train {step+1}/{TRAIN_STEPS} loss={losses[-1]:.5f}") student.eval() return student, losses class _unused: pass def export_onnx(student, path: Path): import copy import torch class Graph(torch.nn.Module): def __init__(self, dit): super().__init__() self.dit = dit def forward(self, x, t, c, history): return self.dit(x=x, t=t, c=c, latent_history=history, mask=None)[:, -1:, :] g = Graph(copy.deepcopy(student).float()).cpu().eval() x = torch.randn(1, 1, 64); t = torch.tensor([0.5]) c = torch.randn(1, 1, 896); h = torch.randn(1, 1, 64) with torch.inference_mode(): ref = g(x, t, c, h) torch.onnx.export(g, (x, t, c, h), str(path), input_names=["x", "t", "c", "history"], output_names=["velocity"], opset_version=20, do_constant_folding=True, dynamo=False) import onnxruntime as ort sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]) got = sess.run(None, {"x": x.numpy(), "t": t.numpy(), "c": c.numpy(), "history": h.numpy()})[0] err = float(np.abs(ref.numpy().reshape(-1) - got.reshape(-1)).max()) log(f"{path.name} {path.stat().st_size/1e6:.1f}MB max_abs={err:.2e}") return err def quantize(src: Path, dst: Path) -> None: from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer q = MatMulNBitsQuantizer(str(src), bits=4, block_size=32, is_symmetric=True, accuracy_level=4, op_types_to_quantize=("MatMul",)) q.process() q.model.save_model_to_file(str(dst), use_external_data_format=False) log(f"{dst.name} {dst.stat().st_size/1e6:.1f}MB") def sample_latent(dit, z, hist, noise, n_steps): import torch y = noise for i in range(n_steps): dt = 1.0 / n_steps v = dit(x=y, t=torch.full((y.shape[0],), i / n_steps, device=y.device), c=z, latent_history=hist, mask=None)[:, -1:, :] y = y + v * dt return y def ar_generate(mm, sample_fn, text, task_prompt, prompt_latent, prompt_text, spk, frames): import torch device = next(mm.parameters()).device dtype = next(mm.parameters()).dtype with torch.no_grad(): input_ids, inputs_embeds = mm.prepare_input_embed( prompt=task_prompt, text=text, spk_emb=spk, 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 hist = torch.zeros(1, mm.history_patch_size, mm.latent_dim, device=device, dtype=dtype) start = mm.history_patch_size - prompt_latent.size(1) if start < 0: hist[:] = prompt_latent[:, -start:, :] else: hist[:, 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) # no_grad matters: the DiT params require grad, so an unguarded sample # builds a graph per frame that stays alive through `hist`. with torch.no_grad(): latent = sample_fn(z, hist, noise).to(device=device, dtype=dtype) out.append(latent.detach()) inputs_embeds = mm.linear_proj_audio(latent) position_ids = position_ids[:, -1:] + 1 attention_mask = torch.ones(inputs_embeds.shape[0], 1, device=device) hist[:, :-mm.patch_size, :] = hist[:, mm.patch_size:, :].clone() hist[:, -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 stage_eval() -> None: import copy import torch from transformers import pipeline sys.path.insert(0, str(REPO)) from ming_tts import MingTTS import tts_tasks sys.path.insert(0, str(BUNDLE / "eval")) from score import load_t2s, score_row table = load_t2s() task_prompt = tts_tasks.build_tts_prompt("Chinese") ckpt = OUT / f"student{STEPS}.pt" state = {k: v.float() for k, v in torch.load(ckpt, map_location="cpu").items()} tts = MingTTS(str(MODEL), device="cuda", text_normalization=False) mm = tts.model device = next(mm.parameters()).device teacher = mm.flowloss.cfm.model.float().eval() asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0, torch_dtype=torch.float16) def asr(y): out = asr_pipe({"array": y.astype(np.float32), "sampling_rate": 44100}, generate_kwargs={"language": "zh", "task": "transcribe"}) return (out.get("text", "") if isinstance(out, dict) else str(out)).strip() sents = json.loads((BUNDLE / "eval/sentences.json").read_text())["items"] want = EVAL_VOICES or [v["slot"] for v in voices()[:2]] sel = [x for x in voices(include_holdout=True) if x["slot"] in want] wav_dir = OUT / "eval_wavs" wav_dir.mkdir(parents=True, exist_ok=True) rows = [] # Pass 1: teacher only. Both DiTs resident does not fit on a 15 GB T4. for v in sel: latent, spk = tts.prepare_prompt(str(BUNDLE / v["wav"]), use_spk_emb=True) latent = latent.to(device=device, dtype=next(mm.parameters()).dtype) spk = [x.to(device=device, dtype=next(mm.parameters()).dtype) for x in spk] for item in sents: text = item["text"] try: # Seed the teacher too: unseeded teacher sampling moved the # baseline CER by ~2 pp between runs, which is the same size as # the effect we are trying to measure. torch.manual_seed(SEED) tw = tts.synthesize(task="TTS", text=text, language_id="Chinese", prompt_wav_path=str(BUNDLE / v["wav"]), prompt_text=v["prompt_text"], use_spk_emb=True, raw_text=True, max_decode_steps=max(32, min(400, int(len(text) * 3.5)))) tw = tw.cpu().numpy().reshape(-1) p = wav_dir / f"{v['slot']}_{item['id']}_teacher.wav" torch.save(torch.from_numpy(tw), p.with_suffix(".pt")) if SAVE_WAVS: import soundfile as sf sf.write(str(p), tw, 44100) hyp = asr(tw) s = score_row({"text": text, "hyp_text": hyp}, table) rows.append({"voice": v["slot"], "artist": v["artist"], "id": item["id"], "model": "teacher", "text": text, "cer": s["cer_norm"], "cer_head": s["cer_prefix"], "hyp": hyp}) except Exception: log(f"teacher {v['slot']} {item['id']} failed\n{traceback.format_exc()}") torch.cuda.empty_cache() log(f"teacher {v['slot']} done ({len(rows)} rows)") del teacher torch.cuda.empty_cache() # Pass 2: student only. Load it here, not alongside the teacher: two DiTs # plus the 1.48 B backbone do not fit in 15 GB. import copy as _copy student = _copy.deepcopy(mm.flowloss.cfm.model.float()) student.load_state_dict(state) student = student.to(device).eval() # Pass 2: student only, reusing the teacher audio for frame count. for v in sel: latent, spk = tts.prepare_prompt(str(BUNDLE / v["wav"]), use_spk_emb=True) latent = latent.to(device=device, dtype=next(mm.parameters()).dtype) spk = [x.to(device=device, dtype=next(mm.parameters()).dtype) for x in spk] for item in sents: text = item["text"] try: tp = wav_dir / f"{v['slot']}_{item['id']}_teacher.pt" tw = torch.load(tp, map_location="cpu").numpy() frames = max(16, int(round(tw.size / 3528))) torch.manual_seed(SEED) sw = ar_generate(mm, lambda z, h, n: sample_latent(student, z, h, n, STEPS), text, task_prompt, latent, v["prompt_text"], spk, frames) hyp = asr(sw) s = score_row({"text": text, "hyp_text": hyp}, table) if SAVE_WAVS: import soundfile as sf sf.write(str(wav_dir / f"{v['slot']}_{item['id']}_student.wav"), sw, 44100) rows.append({"voice": v["slot"], "artist": v["artist"], "id": item["id"], "model": "student", "text": text, "cer": s["cer_norm"], "cer_head": s["cer_prefix"], "hyp": hyp}) except Exception: log(f"student {v['slot']} {item['id']} failed\n{traceback.format_exc()}") torch.cuda.empty_cache() log(f"student {v['slot']} done ({len(rows)} rows)") (OUT / "eval_rows.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1)) for name in ("teacher", "student"): sel_rows = [r for r in rows if r["model"] == name] if sel_rows: log(f"{name:<8} n={len(sel_rows)} cer={np.mean([r['cer'] for r in sel_rows]):.4f} " f"head={np.mean([r['cer_head'] for r in sel_rows]):.4f}") for v in sorted({r["voice"] for r in sel_rows}): vs = [r["cer"] for r in sel_rows if r["voice"] == v] log(f" {v} n={len(vs)} cer={np.mean(vs):.4f}") def stage_eval_int4() -> None: """Same cells as stage_eval, sampled through the int4 ONNX graph. Runs as its own process so the PyTorch DiT is not resident: the ORT session plus the backbone is already close to a 15 GB T4. """ import onnxruntime as ort import torch from transformers import pipeline sys.path.insert(0, str(REPO)) from ming_tts import MingTTS import tts_tasks sys.path.insert(0, str(BUNDLE / "eval")) from score import load_t2s, score_row table = load_t2s() model_path = OUT / f"dit{STEPS}_int4.onnx" if not model_path.exists(): raise SystemExit(f"{model_path} missing") sess = ort.InferenceSession(str(model_path), providers=["CUDAExecutionProvider"]) log(f"int4 session providers: {sess.get_providers()}") def ort_sample(z, hist, noise): times = [i / STEPS for i in range(STEPS + 1)] y = noise.detach().cpu().numpy() zc, hc = z.detach().cpu().numpy(), hist.detach().cpu().numpy() for i in range(STEPS): v = sess.run(None, {"x": y, "t": np.array([times[i]], np.float32), "c": zc, "history": hc})[0] y = y + v * (times[i + 1] - times[i]) return torch.from_numpy(y) tts = MingTTS(str(MODEL), device="cuda", text_normalization=False) mm = tts.model device = next(mm.parameters()).device dtype = next(mm.parameters()).dtype task_prompt = tts_tasks.build_tts_prompt("Chinese") asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0, torch_dtype=torch.float16) def asr(y): out = asr_pipe({"array": y.astype(np.float32), "sampling_rate": 44100}, generate_kwargs={"language": "zh", "task": "transcribe"}) return (out.get("text", "") if isinstance(out, dict) else str(out)).strip() sents = json.loads((BUNDLE / "eval/sentences.json").read_text())["items"] want = EVAL_VOICES or [v["slot"] for v in voices(include_holdout=True)[:2]] wav_dir = OUT / "eval_wavs" rows = [] for v in [x for x in voices(include_holdout=True) if x["slot"] in want]: latent, spk = tts.prepare_prompt(str(BUNDLE / v["wav"]), use_spk_emb=True) latent = latent.to(device=device, dtype=dtype) spk = [x.to(device=device, dtype=dtype) for x in spk] for item in sents: text = item["text"] try: tp = wav_dir / f"{v['slot']}_{item['id']}_teacher.pt" tw = torch.load(tp, map_location="cpu").numpy() frames = max(16, int(round(tw.size / 3528))) torch.manual_seed(SEED) sw = ar_generate(mm, ort_sample, text, task_prompt, latent, v["prompt_text"], spk, frames) hyp = asr(sw) s = score_row({"text": text, "hyp_text": hyp}, table) rows.append({"voice": v["slot"], "artist": v["artist"], "id": item["id"], "model": "int4", "text": text, "cer": s["cer_norm"], "cer_head": s["cer_prefix"], "hyp": hyp}) except Exception: log(f"int4 {v['slot']} {item['id']} failed\n{traceback.format_exc()}") torch.cuda.empty_cache() log(f"int4 {v['slot']} done ({len(rows)} rows)") (OUT / "eval_rows_int4.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1)) sel_rows = rows if sel_rows: log(f"int4 n={len(sel_rows)} cer={np.mean([r['cer'] for r in sel_rows]):.4f} " f"head={np.mean([r['cer_head'] for r in sel_rows]):.4f}") for v in sorted({r["voice"] for r in sel_rows}): vs = [r["cer"] for r in sel_rows if r["voice"] == v] log(f" {v} n={len(vs)} cer={np.mean(vs):.4f}") def main() -> None: import torch torch.manual_seed(SEED) if torch.cuda.is_available(): torch.cuda.manual_seed_all(SEED) device = torch.device("cuda") if STAGE == "traj": patch_fp32() stage_traj() return if STAGE == "eval_int4": patch_fp32() stage_eval_int4() return sys.path.insert(0, str(REPO)) patch_fp32() from ming_tts import MingTTS tts = MingTTS(str(MODEL), device="cuda", text_normalization=False) mm = tts.model if STAGE in ("train", "all"): data = load_dataset() teacher = mm.flowloss.cfm.model.float().to(device).eval() for p in teacher.parameters(): p.requires_grad_(False) student, losses = train_student(teacher, data, STEPS, device) torch.save({k: v.half().cpu() for k, v in student.state_dict().items()}, OUT / f"student{STEPS}.pt") (OUT / "train_loss.json").write_text(json.dumps({"first": losses[0], "last": losses[-1], "steps": TRAIN_STEPS, "lr": LR})) log(f"saved student{STEPS}.pt loss {losses[0]:.4f} -> {losses[-1]:.4f}") if STAGE in ("export", "all"): student = copy_state(mm, OUT / f"student{STEPS}.pt", device) if STAGE == "export" else student fp32 = OUT / f"dit{STEPS}.onnx" export_onnx(student, fp32) quantize(fp32, OUT / f"dit{STEPS}_int4.onnx") if STAGE in ("eval", "all"): stage_eval() def copy_state(mm, path, device): import copy import torch state = {k: v.float() for k, v in torch.load(path, map_location="cpu").items()} dit = copy.deepcopy(mm.flowloss.cfm.model.float()) dit.load_state_dict(state) return dit.to(device).eval() if __name__ == "__main__": main()