Download kaggle/ming_distill.py from idefinity/webfm-eval: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/kaggle/ming_distill.py
- Command line
-
hf download hf://datasets/idefinity/webfm-eval/kaggle/ming_distill.py
-
curl -L -o ming_distill.py https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/kaggle/ming_distill.py
13.5 kB
| """Distill the Ming-3.0-tts flow head to 4-step CFG-free. | |
| Teacher: 10-step CFG=2, fp16/fp32 Ming reference. | |
| Student: same DiT architecture, initialized from the teacher, trained to match | |
| teacher velocity on student states. | |
| Environment: | |
| N_UTTERANCES=20 number of teacher trajectories (smoke default 20) | |
| TRAIN_STEPS=100 optimizer steps (smoke default 100) | |
| BATCH=8 | |
| LR=1e-4 | |
| """ | |
| import contextlib | |
| import copy | |
| import json | |
| import math | |
| import os | |
| import random | |
| import re | |
| import sys | |
| import time | |
| import traceback | |
| import urllib.request | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| ROOT = Path("/kaggle/working") | |
| REPO = ROOT / "Ming-3.0-tts" | |
| MODEL_DIR = ROOT / "Ming-3.0-tts-0.5b" | |
| OUT = ROOT / "ming_distill" | |
| DATA = OUT / "trajectories" | |
| LOG = ROOT / "distill.log" | |
| TEXT_URL = "https://paste.rs/m5OkO" | |
| N_UTTERANCES = int(os.environ.get("N_UTTERANCES", "20")) | |
| TRAIN_STEPS = int(os.environ.get("TRAIN_STEPS", "100")) | |
| BATCH = int(os.environ.get("BATCH", "8")) | |
| LR = float(os.environ.get("LR", "1e-4")) | |
| STUDENT_STEPS = 4 | |
| SEED = 20261021 | |
| DTYPE = os.environ.get("DTYPE", "fp32").lower() | |
| MODEL_DTYPE_NAME = "torch.float32" if DTYPE == "fp32" else "torch.float16" | |
| MODEL_DTYPE = torch.float32 if DTYPE == "fp32" else torch.float16 | |
| DATA.mkdir(parents=True, exist_ok=True) | |
| def log(msg): | |
| line = f"[{time.strftime('%H:%M:%S')}] {msg}" | |
| print(line, flush=True) | |
| with open(LOG, "a") as f: | |
| f.write(line + "\n") | |
| def load_texts(n): | |
| raw = urllib.request.urlopen(TEXT_URL, timeout=60).read().decode("utf-8", "ignore") | |
| parts = re.split(r"(?<=[。!?!?;;])\s*", raw) | |
| rows = [] | |
| for part in parts: | |
| text = re.sub(r"\s+", "", part).strip() | |
| if 12 <= len(text) <= 55 and not text.startswith(("一", "二", "三", "四", "五", "六", "七", "八", "九", "十")): | |
| rows.append(text) | |
| random.Random(SEED).shuffle(rows) | |
| if len(rows) < n: | |
| raise RuntimeError(f"only {len(rows)} usable texts") | |
| return rows[:n] | |
| class DiTGraph(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:, :] | |
| def build_models(): | |
| sys.path.insert(0, str(REPO)) | |
| subprocess_patch() | |
| from ming_tts import MingTTS | |
| import tts_tasks | |
| return MingTTS, tts_tasks | |
| def subprocess_patch(): | |
| for name in ("ming_tts.py", "modeling_bailingmm.py"): | |
| path = REPO / name | |
| s = path.read_text() | |
| s = s.replace("torch_dtype=torch.bfloat16", f"torch_dtype={MODEL_DTYPE_NAME}") | |
| s = s.replace(".eval().to(torch.bfloat16).to(device)", f".eval().to({MODEL_DTYPE_NAME}).to(device)") | |
| s = s.replace("dtype=torch.bfloat16", f"dtype={MODEL_DTYPE_NAME}") | |
| path.write_text(s) | |
| def autocast_ctx(): | |
| if DTYPE == "fp16" and torch.cuda.is_available(): | |
| return torch.autocast(device_type="cuda", dtype=torch.float16) | |
| return contextlib.nullcontext() | |
| def teacher_trajectories(tts, tts_tasks, texts): | |
| torch.set_grad_enabled(False) | |
| mm = tts.model | |
| device = next(mm.parameters()).device | |
| dtype = next(mm.parameters()).dtype | |
| prompts = json.loads((REPO / "data/voice_presets/voice_prompts.json").read_text()) | |
| prompt_text = prompts["lingguang"]["text"] | |
| prompt_wav = REPO / "data/voice_presets/voice_audio/lingguang.wav" | |
| torch.manual_seed(1234) | |
| prompt_latent, spk_emb = tts.prepare_prompt(str(prompt_wav), 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] | |
| prompt = tts_tasks.build_tts_prompt("Chinese") | |
| log(f"prompt latent {tuple(prompt_latent.shape)} spk {len(spk_emb)}") | |
| total_frames = 0 | |
| for i, text in enumerate(texts): | |
| torch.manual_seed(SEED + i) | |
| try: | |
| 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 | |
| latent_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: | |
| latent_history[:] = prompt_latent[:, -start:, :] | |
| else: | |
| latent_history[:, start:, :] = prompt_latent | |
| budget = (512 - inputs_embeds.shape[1]) // mm.patch_size | |
| cap = min(200, max(16, int(len(text) * 2.6))) | |
| steps = max(1, min(cap, budget)) | |
| zs, hs, ns, ls = [], [], [], [] | |
| for step in range(steps): | |
| with autocast_ctx(): | |
| 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 autocast_ctx(): | |
| latent = mm.flowloss.cfm.sample( | |
| noise=noise, | |
| c=z, | |
| latent_history=latent_history, | |
| sde_noise=sde, | |
| cfg_scale=2.0, | |
| 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(latent_history[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) | |
| latent_history[:, :-mm.patch_size, :] = latent_history[:, mm.patch_size:, :].clone() | |
| latent_history[:, -mm.patch_size:, :] = latent | |
| payload = { | |
| "text": text, | |
| "z": torch.stack(zs), | |
| "history": torch.stack(hs), | |
| "noise": torch.stack(ns), | |
| "latent": torch.stack(ls), | |
| } | |
| torch.save(payload, DATA / f"{i:04d}.pt") | |
| total_frames += steps | |
| if i % 5 == 0 or i == len(texts) - 1: | |
| log(f"trajectory {i+1}/{len(texts)} frames={steps} total={total_frames}") | |
| except Exception: | |
| log(f"trajectory {i} failed: {text}\n{traceback.format_exc()}") | |
| log(f"trajectories done frames={total_frames}") | |
| torch.set_grad_enabled(True) | |
| return total_frames | |
| def load_dataset(): | |
| zs, hs, ns, ls = [], [], [], [] | |
| for path in sorted(DATA.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 = torch.cat(zs).float() | |
| h = torch.cat(hs).float() | |
| n = torch.cat(ns).float() | |
| l = torch.cat(ls).float() | |
| log(f"dataset frames={z.shape[0]} z={tuple(z.shape)}") | |
| return z, h, n, l | |
| def train(student, teacher, data, device): | |
| z, h, n, target = [x.to(device) for x in data] | |
| n_frames = z.shape[0] | |
| optimizer = torch.optim.AdamW(student.parameters(), lr=LR, weight_decay=0.01) | |
| scaler = None | |
| if DTYPE == "fp16": | |
| try: | |
| scaler = torch.cuda.amp.GradScaler() | |
| except Exception: | |
| scaler = torch.amp.GradScaler("cuda") | |
| student.train() | |
| teacher.eval() | |
| losses = [] | |
| times = [0.0, 0.25, 0.5, 0.75, 1.0] | |
| for step in range(TRAIN_STEPS): | |
| idx = torch.randint(0, n_frames, (min(BATCH, n_frames),), device=device) | |
| bz = z[idx].unsqueeze(1) | |
| bh = h[idx] | |
| bn = n[idx].unsqueeze(1) | |
| bt = target[idx].unsqueeze(1) | |
| y = bn | |
| loss = 0.0 | |
| for i in range(STUDENT_STEPS): | |
| ti = times[i] | |
| dt = times[i + 1] - ti | |
| tv_t = torch.tensor(float(ti), device=device) | |
| with torch.no_grad(), autocast_ctx(): | |
| pred_cfg = teacher.forward_with_cfg( | |
| x=y, t=tv_t, c=bz, latent_history=bh, patch_size=1 | |
| ) | |
| pred, null = torch.chunk(pred_cfg, 2, dim=0) | |
| tv = pred + (pred - null) * 2.0 | |
| with autocast_ctx(): | |
| 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.float(), tv.float()) * dt | |
| y = (y + sv.float() * dt).detach() | |
| loss = loss + 0.5 * F.mse_loss(y, bt) | |
| optimizer.zero_grad(set_to_none=True) | |
| if scaler is not None: | |
| scaler.scale(loss).backward() | |
| scaler.unscale_(optimizer) | |
| torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0) | |
| scaler.step(optimizer) | |
| scaler.update() | |
| else: | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0) | |
| optimizer.step() | |
| losses.append(float(loss.detach().cpu())) | |
| if step % 10 == 0 or step == TRAIN_STEPS - 1: | |
| log(f"train {step+1}/{TRAIN_STEPS} loss={losses[-1]:.5f}") | |
| return losses | |
| def export_student(student, path): | |
| student.eval() | |
| g = DiTGraph(student.float()).cpu() | |
| 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] | |
| a = ref.numpy().reshape(-1) | |
| b = got.reshape(-1) | |
| log(f"student onnx size={path.stat().st_size/1e6:.1f}MB max_abs={np.abs(a-b).max():.2e}") | |
| return g | |
| def main(): | |
| torch.set_grad_enabled(True) | |
| 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"torch={torch.__version__} cuda={torch.cuda.is_available()} device={device}") | |
| if torch.cuda.is_available(): | |
| log(f"gpu={torch.cuda.get_device_name(0)} capability={torch.cuda.get_device_capability(0)}") | |
| MingTTS, tts_tasks = build_models() | |
| t0 = time.time() | |
| tts = MingTTS(str(MODEL_DIR), device=str(device), text_normalization=False) | |
| log(f"loaded tts in {time.time()-t0:.1f}s") | |
| texts = load_texts(N_UTTERANCES) | |
| log(f"texts={len(texts)} example={texts[0]}") | |
| if not any(DATA.glob("*.pt")): | |
| teacher_trajectories(tts, tts_tasks, texts) | |
| else: | |
| log("trajectories already exist; skipping generation") | |
| data = load_dataset() | |
| torch.set_grad_enabled(True) | |
| teacher = copy.deepcopy(tts.model.flowloss.cfm.model).float().to(device).eval() | |
| student = copy.deepcopy(teacher).to(device).train() | |
| for p in teacher.parameters(): | |
| p.requires_grad_(False) | |
| losses = train(student, teacher, data, device) | |
| OUT.mkdir(exist_ok=True) | |
| torch.save({k: v.half().cpu() for k, v in student.state_dict().items()}, OUT / "student.pt") | |
| g = export_student(student, OUT / "dit4.onnx") | |
| report = { | |
| "teacher_steps": 10, | |
| "teacher_cfg": 2.0, | |
| "student_steps": STUDENT_STEPS, | |
| "student_cfg": 0.0, | |
| "schedule": [0.0, 0.25, 0.5, 0.75, 1.0], | |
| "utterances": N_UTTERANCES, | |
| "train_steps": TRAIN_STEPS, | |
| "batch": BATCH, | |
| "lr": LR, | |
| "frames": int(data[0].shape[0]), | |
| "first_loss": losses[0] if losses else None, | |
| "last_loss": losses[-1] if losses else None, | |
| "student_onnx": str(OUT / "dit4.onnx"), | |
| } | |
| (OUT / "report.json").write_text(json.dumps(report, indent=2)) | |
| log("DONE " + json.dumps(report, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| try: | |
| main() | |
| except Exception: | |
| log(traceback.format_exc()) | |
| raise | |