zziang commited on
Commit
d731422
·
verified ·
1 Parent(s): 8351d1d

add ming_distill for the real distillation run

Browse files
Files changed (1) hide show
  1. kaggle/ming_distill.py +370 -0
kaggle/ming_distill.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distill the Ming-3.0-tts flow head to 4-step CFG-free.
2
+
3
+ Teacher: 10-step CFG=2, fp16/fp32 Ming reference.
4
+ Student: same DiT architecture, initialized from the teacher, trained to match
5
+ teacher velocity on student states.
6
+
7
+ Environment:
8
+ N_UTTERANCES=20 number of teacher trajectories (smoke default 20)
9
+ TRAIN_STEPS=100 optimizer steps (smoke default 100)
10
+ BATCH=8
11
+ LR=1e-4
12
+ """
13
+ import contextlib
14
+ import copy
15
+ import json
16
+ import math
17
+ import os
18
+ import random
19
+ import re
20
+ import sys
21
+ import time
22
+ import traceback
23
+ import urllib.request
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+ import torch
28
+ import torch.nn.functional as F
29
+
30
+ ROOT = Path("/kaggle/working")
31
+ REPO = ROOT / "Ming-3.0-tts"
32
+ MODEL_DIR = ROOT / "Ming-3.0-tts-0.5b"
33
+ OUT = ROOT / "ming_distill"
34
+ DATA = OUT / "trajectories"
35
+ LOG = ROOT / "distill.log"
36
+ TEXT_URL = "https://paste.rs/m5OkO"
37
+
38
+ N_UTTERANCES = int(os.environ.get("N_UTTERANCES", "20"))
39
+ TRAIN_STEPS = int(os.environ.get("TRAIN_STEPS", "100"))
40
+ BATCH = int(os.environ.get("BATCH", "8"))
41
+ LR = float(os.environ.get("LR", "1e-4"))
42
+ STUDENT_STEPS = 4
43
+ SEED = 20261021
44
+ DTYPE = os.environ.get("DTYPE", "fp32").lower()
45
+ MODEL_DTYPE_NAME = "torch.float32" if DTYPE == "fp32" else "torch.float16"
46
+ MODEL_DTYPE = torch.float32 if DTYPE == "fp32" else torch.float16
47
+
48
+ DATA.mkdir(parents=True, exist_ok=True)
49
+
50
+
51
+ def log(msg):
52
+ line = f"[{time.strftime('%H:%M:%S')}] {msg}"
53
+ print(line, flush=True)
54
+ with open(LOG, "a") as f:
55
+ f.write(line + "\n")
56
+
57
+
58
+ def load_texts(n):
59
+ raw = urllib.request.urlopen(TEXT_URL, timeout=60).read().decode("utf-8", "ignore")
60
+ parts = re.split(r"(?<=[。!?!?;;])\s*", raw)
61
+ rows = []
62
+ for part in parts:
63
+ text = re.sub(r"\s+", "", part).strip()
64
+ if 12 <= len(text) <= 55 and not text.startswith(("一", "二", "三", "四", "五", "六", "七", "八", "九", "十")):
65
+ rows.append(text)
66
+ random.Random(SEED).shuffle(rows)
67
+ if len(rows) < n:
68
+ raise RuntimeError(f"only {len(rows)} usable texts")
69
+ return rows[:n]
70
+
71
+
72
+ class DiTGraph(torch.nn.Module):
73
+ def __init__(self, dit):
74
+ super().__init__()
75
+ self.dit = dit
76
+
77
+ def forward(self, x, t, c, history):
78
+ return self.dit(x=x, t=t, c=c, latent_history=history, mask=None)[:, -1:, :]
79
+
80
+
81
+ def build_models():
82
+ sys.path.insert(0, str(REPO))
83
+ subprocess_patch()
84
+ from ming_tts import MingTTS
85
+ import tts_tasks
86
+ return MingTTS, tts_tasks
87
+
88
+
89
+ def subprocess_patch():
90
+ for name in ("ming_tts.py", "modeling_bailingmm.py"):
91
+ path = REPO / name
92
+ s = path.read_text()
93
+ s = s.replace("torch_dtype=torch.bfloat16", f"torch_dtype={MODEL_DTYPE_NAME}")
94
+ s = s.replace(".eval().to(torch.bfloat16).to(device)", f".eval().to({MODEL_DTYPE_NAME}).to(device)")
95
+ s = s.replace("dtype=torch.bfloat16", f"dtype={MODEL_DTYPE_NAME}")
96
+ path.write_text(s)
97
+
98
+
99
+ def autocast_ctx():
100
+ if DTYPE == "fp16" and torch.cuda.is_available():
101
+ return torch.autocast(device_type="cuda", dtype=torch.float16)
102
+ return contextlib.nullcontext()
103
+
104
+
105
+ def teacher_trajectories(tts, tts_tasks, texts):
106
+ torch.set_grad_enabled(False)
107
+ mm = tts.model
108
+ device = next(mm.parameters()).device
109
+ dtype = next(mm.parameters()).dtype
110
+ prompts = json.loads((REPO / "data/voice_presets/voice_prompts.json").read_text())
111
+ prompt_text = prompts["lingguang"]["text"]
112
+ prompt_wav = REPO / "data/voice_presets/voice_audio/lingguang.wav"
113
+ torch.manual_seed(1234)
114
+ prompt_latent, spk_emb = tts.prepare_prompt(str(prompt_wav), use_spk_emb=True)
115
+ prompt_latent = prompt_latent.to(device=device, dtype=dtype)
116
+ spk_emb = [x.to(device=device, dtype=dtype) for x in spk_emb]
117
+ prompt = tts_tasks.build_tts_prompt("Chinese")
118
+ log(f"prompt latent {tuple(prompt_latent.shape)} spk {len(spk_emb)}")
119
+
120
+ total_frames = 0
121
+ for i, text in enumerate(texts):
122
+ torch.manual_seed(SEED + i)
123
+ try:
124
+ input_ids, inputs_embeds = mm.prepare_input_embed(
125
+ prompt=prompt,
126
+ text=text,
127
+ spk_emb=spk_emb,
128
+ prompt_latent=prompt_latent,
129
+ prompt_text=prompt_text,
130
+ )
131
+ attention_mask = torch.ones(input_ids.shape, device=device)
132
+ position_ids = (attention_mask.cumsum(-1) - 1).masked_fill_(attention_mask == 0, 1)
133
+ past = None
134
+ latent_history = torch.zeros(
135
+ 1, mm.history_patch_size, mm.latent_dim, device=device, dtype=dtype
136
+ )
137
+ if prompt_latent is not None:
138
+ start = mm.history_patch_size - prompt_latent.size(1)
139
+ if start < 0:
140
+ latent_history[:] = prompt_latent[:, -start:, :]
141
+ else:
142
+ latent_history[:, start:, :] = prompt_latent
143
+
144
+ budget = (512 - inputs_embeds.shape[1]) // mm.patch_size
145
+ cap = min(200, max(16, int(len(text) * 2.6)))
146
+ steps = max(1, min(cap, budget))
147
+ zs, hs, ns, ls = [], [], [], []
148
+ for step in range(steps):
149
+ with autocast_ctx():
150
+ out = mm.model(
151
+ attention_mask=attention_mask,
152
+ position_ids=position_ids,
153
+ inputs_embeds=inputs_embeds,
154
+ audio_mask=None,
155
+ image_mask=None,
156
+ output_hidden_states=True,
157
+ return_dict=True,
158
+ use_cache=True,
159
+ past_key_values=past,
160
+ )
161
+ past = out.past_key_values
162
+ z = out.hidden_states[-1][:, -1:, :]
163
+ noise = torch.randn(1, 1, mm.latent_dim, device=device, dtype=dtype)
164
+ sde = torch.randn(10, 1, 1, mm.latent_dim, device=device, dtype=dtype)
165
+ with autocast_ctx():
166
+ latent = mm.flowloss.cfm.sample(
167
+ noise=noise,
168
+ c=z,
169
+ latent_history=latent_history,
170
+ sde_noise=sde,
171
+ cfg_scale=2.0,
172
+ sway_sampling_coef=-1.0,
173
+ use_epss=True,
174
+ patch_size=1,
175
+ sigma=0.25,
176
+ temperature=0.0,
177
+ )
178
+ zs.append(z[0, 0].detach().float().cpu())
179
+ hs.append(latent_history[0].detach().float().cpu())
180
+ ns.append(noise[0, 0].detach().float().cpu())
181
+ ls.append(latent[0, 0].detach().float().cpu())
182
+
183
+ inputs_embeds = mm.linear_proj_audio(latent)
184
+ position_ids = position_ids[:, -1:] + 1
185
+ attention_mask = torch.ones(inputs_embeds.shape[0], 1, device=device)
186
+ latent_history[:, :-mm.patch_size, :] = latent_history[:, mm.patch_size:, :].clone()
187
+ latent_history[:, -mm.patch_size:, :] = latent
188
+
189
+ payload = {
190
+ "text": text,
191
+ "z": torch.stack(zs),
192
+ "history": torch.stack(hs),
193
+ "noise": torch.stack(ns),
194
+ "latent": torch.stack(ls),
195
+ }
196
+ torch.save(payload, DATA / f"{i:04d}.pt")
197
+ total_frames += steps
198
+ if i % 5 == 0 or i == len(texts) - 1:
199
+ log(f"trajectory {i+1}/{len(texts)} frames={steps} total={total_frames}")
200
+ except Exception:
201
+ log(f"trajectory {i} failed: {text}\n{traceback.format_exc()}")
202
+ log(f"trajectories done frames={total_frames}")
203
+ torch.set_grad_enabled(True)
204
+ return total_frames
205
+
206
+
207
+ def load_dataset():
208
+ zs, hs, ns, ls = [], [], [], []
209
+ for path in sorted(DATA.glob("*.pt")):
210
+ row = torch.load(path, map_location="cpu", weights_only=False)
211
+ zs.append(row["z"])
212
+ hs.append(row["history"])
213
+ ns.append(row["noise"])
214
+ ls.append(row["latent"])
215
+ if not zs:
216
+ raise RuntimeError("no trajectories")
217
+ z = torch.cat(zs).float()
218
+ h = torch.cat(hs).float()
219
+ n = torch.cat(ns).float()
220
+ l = torch.cat(ls).float()
221
+ log(f"dataset frames={z.shape[0]} z={tuple(z.shape)}")
222
+ return z, h, n, l
223
+
224
+
225
+ def train(student, teacher, data, device):
226
+ z, h, n, target = [x.to(device) for x in data]
227
+ n_frames = z.shape[0]
228
+ optimizer = torch.optim.AdamW(student.parameters(), lr=LR, weight_decay=0.01)
229
+ scaler = None
230
+ if DTYPE == "fp16":
231
+ try:
232
+ scaler = torch.cuda.amp.GradScaler()
233
+ except Exception:
234
+ scaler = torch.amp.GradScaler("cuda")
235
+ student.train()
236
+ teacher.eval()
237
+ losses = []
238
+ times = [0.0, 0.25, 0.5, 0.75, 1.0]
239
+ for step in range(TRAIN_STEPS):
240
+ idx = torch.randint(0, n_frames, (min(BATCH, n_frames),), device=device)
241
+ bz = z[idx].unsqueeze(1)
242
+ bh = h[idx]
243
+ bn = n[idx].unsqueeze(1)
244
+ bt = target[idx].unsqueeze(1)
245
+ y = bn
246
+ loss = 0.0
247
+ for i in range(STUDENT_STEPS):
248
+ ti = times[i]
249
+ dt = times[i + 1] - ti
250
+ tv_t = torch.tensor(float(ti), device=device)
251
+ with torch.no_grad(), autocast_ctx():
252
+ pred_cfg = teacher.forward_with_cfg(
253
+ x=y, t=tv_t, c=bz, latent_history=bh, patch_size=1
254
+ )
255
+ pred, null = torch.chunk(pred_cfg, 2, dim=0)
256
+ tv = pred + (pred - null) * 2.0
257
+ with autocast_ctx():
258
+ sv = student(
259
+ x=y,
260
+ t=torch.full((y.shape[0],), float(ti), device=device),
261
+ c=bz,
262
+ latent_history=bh,
263
+ mask=None,
264
+ )[:, -1:, :]
265
+ loss = loss + F.mse_loss(sv.float(), tv.float()) * dt
266
+ y = (y + sv.float() * dt).detach()
267
+ loss = loss + 0.5 * F.mse_loss(y, bt)
268
+ optimizer.zero_grad(set_to_none=True)
269
+ if scaler is not None:
270
+ scaler.scale(loss).backward()
271
+ scaler.unscale_(optimizer)
272
+ torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0)
273
+ scaler.step(optimizer)
274
+ scaler.update()
275
+ else:
276
+ loss.backward()
277
+ torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0)
278
+ optimizer.step()
279
+ losses.append(float(loss.detach().cpu()))
280
+ if step % 10 == 0 or step == TRAIN_STEPS - 1:
281
+ log(f"train {step+1}/{TRAIN_STEPS} loss={losses[-1]:.5f}")
282
+ return losses
283
+
284
+
285
+ def export_student(student, path):
286
+ student.eval()
287
+ g = DiTGraph(student.float()).cpu()
288
+ x = torch.randn(1, 1, 64)
289
+ t = torch.tensor([0.5])
290
+ c = torch.randn(1, 1, 896)
291
+ h = torch.randn(1, 1, 64)
292
+ with torch.inference_mode():
293
+ ref = g(x, t, c, h)
294
+ torch.onnx.export(
295
+ g, (x, t, c, h), str(path),
296
+ input_names=["x", "t", "c", "history"],
297
+ output_names=["velocity"],
298
+ opset_version=20,
299
+ do_constant_folding=True,
300
+ dynamo=False,
301
+ )
302
+ import onnxruntime as ort
303
+ sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
304
+ got = sess.run(None, {
305
+ "x": x.numpy(), "t": t.numpy(), "c": c.numpy(), "history": h.numpy()
306
+ })[0]
307
+ a = ref.numpy().reshape(-1)
308
+ b = got.reshape(-1)
309
+ log(f"student onnx size={path.stat().st_size/1e6:.1f}MB max_abs={np.abs(a-b).max():.2e}")
310
+ return g
311
+
312
+
313
+ def main():
314
+ torch.set_grad_enabled(True)
315
+ torch.manual_seed(SEED)
316
+ if torch.cuda.is_available():
317
+ torch.cuda.manual_seed_all(SEED)
318
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
319
+ log(f"torch={torch.__version__} cuda={torch.cuda.is_available()} device={device}")
320
+ if torch.cuda.is_available():
321
+ log(f"gpu={torch.cuda.get_device_name(0)} capability={torch.cuda.get_device_capability(0)}")
322
+
323
+ MingTTS, tts_tasks = build_models()
324
+ t0 = time.time()
325
+ tts = MingTTS(str(MODEL_DIR), device=str(device), text_normalization=False)
326
+ log(f"loaded tts in {time.time()-t0:.1f}s")
327
+
328
+ texts = load_texts(N_UTTERANCES)
329
+ log(f"texts={len(texts)} example={texts[0]}")
330
+ if not any(DATA.glob("*.pt")):
331
+ teacher_trajectories(tts, tts_tasks, texts)
332
+ else:
333
+ log("trajectories already exist; skipping generation")
334
+
335
+ data = load_dataset()
336
+ torch.set_grad_enabled(True)
337
+ teacher = copy.deepcopy(tts.model.flowloss.cfm.model).float().to(device).eval()
338
+ student = copy.deepcopy(teacher).to(device).train()
339
+ for p in teacher.parameters():
340
+ p.requires_grad_(False)
341
+ losses = train(student, teacher, data, device)
342
+
343
+ OUT.mkdir(exist_ok=True)
344
+ torch.save({k: v.half().cpu() for k, v in student.state_dict().items()}, OUT / "student.pt")
345
+ g = export_student(student, OUT / "dit4.onnx")
346
+ report = {
347
+ "teacher_steps": 10,
348
+ "teacher_cfg": 2.0,
349
+ "student_steps": STUDENT_STEPS,
350
+ "student_cfg": 0.0,
351
+ "schedule": [0.0, 0.25, 0.5, 0.75, 1.0],
352
+ "utterances": N_UTTERANCES,
353
+ "train_steps": TRAIN_STEPS,
354
+ "batch": BATCH,
355
+ "lr": LR,
356
+ "frames": int(data[0].shape[0]),
357
+ "first_loss": losses[0] if losses else None,
358
+ "last_loss": losses[-1] if losses else None,
359
+ "student_onnx": str(OUT / "dit4.onnx"),
360
+ }
361
+ (OUT / "report.json").write_text(json.dumps(report, indent=2))
362
+ log("DONE " + json.dumps(report, ensure_ascii=False))
363
+
364
+
365
+ if __name__ == "__main__":
366
+ try:
367
+ main()
368
+ except Exception:
369
+ log(traceback.format_exc())
370
+ raise