zziang commited on
Commit
b177b83
·
verified ·
1 Parent(s): 705fdf1

multi-voice distillation: train_texts, train_voices.py, notebook_train.py

Browse files
Files changed (3) hide show
  1. kaggle/notebook_train.py +71 -0
  2. kaggle/train_voices.py +451 -0
  3. train_texts.json +127 -0
kaggle/notebook_train.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kaggle notebook body: distil the flow head on the seven mined voices.
2
+
3
+ Order matters. A smoke pass (5 texts, 5 optimizer steps) validates the
4
+ trajectory and training code paths before spending an hour generating 840
5
+ trajectories; the earlier failures in this project each cost a full session.
6
+
7
+ smoke traj x5 on one GPU, train x5 steps ~4 min
8
+ traj 7 voices x 120 texts, sharded over 2 GPUs ~70 min
9
+ train 4-step student on all shards ~25 min
10
+ export ONNX fp32 + int4 ~5 min
11
+ eval 40 sentences x 2 voices x {teacher, stu} ~25 min
12
+ """
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ import time
17
+
18
+ from notebook_eval import BUNDLE, MODEL, ROOT, WEIGHTS, pull, stage_deps, stage_repo
19
+
20
+ BUNDLE_REPO = "idefinity/webfm-eval"
21
+ SHARDS = [["a01", "a03", "a04"], ["a05", "a06", "a07", "a08"]]
22
+ EVAL_VOICES = "a08,a01"
23
+
24
+
25
+ def run(tag: str, env_extra: dict, gpu: int = 0) -> int:
26
+ env = dict(os.environ, WORK_ROOT=str(ROOT), **env_extra)
27
+ if gpu is not None:
28
+ env["CUDA_VISIBLE_DEVICES"] = str(gpu)
29
+ log = open(ROOT / f"train_{tag}.log", "w")
30
+ p = subprocess.Popen([sys.executable, str(BUNDLE / "kaggle/train_voices.py")],
31
+ env=env, stdout=log, stderr=subprocess.STDOUT, cwd=str(ROOT))
32
+ return p.wait()
33
+
34
+
35
+ def main() -> None:
36
+ stage_repo()
37
+ stage_deps()
38
+ pull(WEIGHTS, MODEL)
39
+ pull(BUNDLE_REPO, BUNDLE, repo_type="dataset")
40
+
41
+ print("== smoke: traj x5, train x5 ==", flush=True)
42
+ rc = run("smoke_traj", {"STAGE": "traj", "VOICES": "a08", "SMOKE": "1", "N_TEXTS": "5"})
43
+ print("smoke traj rc", rc)
44
+ rc = run("smoke_train", {"STAGE": "train", "TRAIN_STEPS": "5", "BATCH": "4"})
45
+ print("smoke train rc", rc)
46
+ if rc != 0:
47
+ print((ROOT / "train_smoke_train.log").read_text()[-3000:])
48
+ raise SystemExit("training path failed in smoke")
49
+
50
+ print("== full trajectories ==", flush=True)
51
+ procs = []
52
+ for gpu, shard in enumerate(SHARDS):
53
+ env = dict(os.environ, WORK_ROOT=str(ROOT), STAGE="traj",
54
+ VOICES=",".join(shard), CUDA_VISIBLE_DEVICES=str(gpu))
55
+ log = open(ROOT / f"traj_gpu{gpu}.log", "w")
56
+ procs.append(subprocess.Popen([sys.executable, str(BUNDLE / "kaggle/train_voices.py")],
57
+ env=env, stdout=log, stderr=subprocess.STDOUT, cwd=str(ROOT)))
58
+ while any(p.poll() is None for p in procs):
59
+ time.sleep(60)
60
+ n = len(list((ROOT / "train/traj").glob("*/*.pt")))
61
+ print(f"[{time.strftime('%H:%M')}] trajectories={n}", flush=True)
62
+ print("traj exits:", [p.returncode for p in procs])
63
+
64
+ print("== train + export + eval ==", flush=True)
65
+ rc = run("final", {"STAGE": "all", "TRAIN_STEPS": "1500", "BATCH": "16",
66
+ "EVAL_VOICES": EVAL_VOICES}, gpu=0)
67
+ print("final rc", rc)
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
kaggle/train_voices.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distil the Ming flow head on the seven mined voices.
2
+
3
+ Why this run: the existing 3/4-step students were trained on 200 utterances of a
4
+ single voice (`lingguang`). On a clean prompt at eval time they cost +5.2 pp
5
+ (v08, 4step) to +11.8 pp (3step) CER against the teacher. The hypothesis is that
6
+ the gap is voice generalisation, not step count, and the fix is trajectory data
7
+ that spans the voices we actually ship.
8
+
9
+ One variable changes this round: the data. The training recipe is copied from
10
+ ming_multistep.py unchanged, including the CFG coefficient, so the new student
11
+ is comparable to the old one. If multi-voice data does not close the gap, that
12
+ coefficient is the next thing to look at.
13
+
14
+ Stages:
15
+ STAGE=traj shard by VOICES env, write traj/{voice}/{i}.pt, resumable
16
+ STAGE=train merge shards, train the 4-step CFG-free student
17
+ STAGE=export ONNX fp32 + int4, validate against PyTorch
18
+ STAGE=eval 40 sentences x EVAL_VOICES x {teacher, student}
19
+ STAGE=all train -> export -> eval (traj is run separately, per GPU)
20
+ """
21
+ import json
22
+ import os
23
+ import sys
24
+ import time
25
+ import traceback
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+
30
+ ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
31
+ REPO = ROOT / "Ming-3.0-tts"
32
+ MODEL = ROOT / "Ming-3.0-tts-0.5b"
33
+ BUNDLE = ROOT / "webfm-eval"
34
+ OUT = ROOT / "train"
35
+ TRAJ = OUT / "traj"
36
+
37
+ STAGE = os.environ.get("STAGE", "all")
38
+ SEED = 20261030
39
+ STEPS = int(os.environ.get("STEPS", "4"))
40
+ TRAIN_STEPS = int(os.environ.get("TRAIN_STEPS", "1500"))
41
+ BATCH = int(os.environ.get("BATCH", "16"))
42
+ LR = float(os.environ.get("LR", "1e-4"))
43
+ VOICE_FILTER = [v for v in os.environ.get("VOICES", "").split(",") if v]
44
+ EVAL_VOICES = [v for v in os.environ.get("EVAL_VOICES", "").split(",") if v]
45
+ N_TEXTS = int(os.environ.get("N_TEXTS", "120"))
46
+ SMOKE = os.environ.get("SMOKE", "0") == "1"
47
+
48
+ TEACHER_CFG = 2.0
49
+ CFG_MULT = 2.0 # unchanged from ming_multistep.py, for comparability
50
+ DROP = {"Miss哈尼"}
51
+
52
+
53
+ def log(msg: str) -> None:
54
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
55
+
56
+
57
+ def patch_fp32() -> None:
58
+ for name in ("ming_tts.py", "modeling_bailingmm.py"):
59
+ path = REPO / name
60
+ s = path.read_text()
61
+ s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
62
+ s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
63
+ s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
64
+ path.write_text(s)
65
+
66
+
67
+ def voices() -> list[dict]:
68
+ vs = json.loads((BUNDLE / "mined/manifest.json").read_text())["voices"]
69
+ vs = [v for v in vs if v["artist"] not in DROP]
70
+ if VOICE_FILTER:
71
+ vs = [v for v in vs if v["slot"] in VOICE_FILTER]
72
+ return vs
73
+
74
+
75
+ def texts() -> list[str]:
76
+ t = json.loads((BUNDLE / "train_texts.json").read_text())["texts"]
77
+ return t[:N_TEXTS]
78
+
79
+
80
+ def stage_traj() -> None:
81
+ import torch
82
+
83
+ sys.path.insert(0, str(REPO))
84
+ from ming_tts import MingTTS
85
+ import tts_tasks
86
+
87
+ TRAJ.mkdir(parents=True, exist_ok=True)
88
+ tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
89
+ mm = tts.model
90
+ device = next(mm.parameters()).device
91
+ dtype = next(mm.parameters()).dtype
92
+ task_prompt = tts_tasks.build_tts_prompt("Chinese")
93
+ torch.set_grad_enabled(False)
94
+
95
+ total = 0
96
+ for v in voices():
97
+ vdir = TRAJ / v["slot"]
98
+ vdir.mkdir(parents=True, exist_ok=True)
99
+ prompt_latent, spk = tts.prepare_prompt(str(BUNDLE / v["wav"]), use_spk_emb=True)
100
+ prompt_latent = prompt_latent.to(device=device, dtype=dtype)
101
+ spk = [x.to(device=device, dtype=dtype) for x in spk]
102
+
103
+ for i, text in enumerate(texts()):
104
+ dst = vdir / f"{i:04d}.pt"
105
+ if dst.exists():
106
+ continue
107
+ try:
108
+ torch.manual_seed(SEED + i)
109
+ input_ids, inputs_embeds = mm.prepare_input_embed(
110
+ prompt=task_prompt, text=text, spk_emb=spk,
111
+ prompt_latent=prompt_latent, prompt_text=v["prompt_text"],
112
+ )
113
+ attention_mask = torch.ones(input_ids.shape, device=device)
114
+ position_ids = (attention_mask.cumsum(-1) - 1).masked_fill_(attention_mask == 0, 1)
115
+ past = None
116
+ hist = torch.zeros(1, mm.history_patch_size, mm.latent_dim,
117
+ device=device, dtype=dtype)
118
+ start = mm.history_patch_size - prompt_latent.size(1)
119
+ if start < 0:
120
+ hist[:] = prompt_latent[:, -start:, :]
121
+ else:
122
+ hist[:, start:, :] = prompt_latent
123
+
124
+ budget = (512 - inputs_embeds.shape[1]) // mm.patch_size
125
+ n = max(1, min(200, max(16, int(len(text) * 2.6)), budget))
126
+ zs, hs, ns, ls = [], [], [], []
127
+ for _ in range(n):
128
+ with torch.no_grad():
129
+ out = mm.model(
130
+ attention_mask=attention_mask, position_ids=position_ids,
131
+ inputs_embeds=inputs_embeds, audio_mask=None, image_mask=None,
132
+ output_hidden_states=True, return_dict=True, use_cache=True,
133
+ past_key_values=past,
134
+ )
135
+ past = out.past_key_values
136
+ z = out.hidden_states[-1][:, -1:, :]
137
+ noise = torch.randn(1, 1, mm.latent_dim, device=device, dtype=dtype)
138
+ sde = torch.randn(10, 1, 1, mm.latent_dim, device=device, dtype=dtype)
139
+ with torch.no_grad():
140
+ latent = mm.flowloss.cfm.sample(
141
+ noise=noise, c=z, latent_history=hist, sde_noise=sde,
142
+ cfg_scale=TEACHER_CFG, sway_sampling_coef=-1.0, use_epss=True,
143
+ patch_size=1, sigma=0.25, temperature=0.0,
144
+ )
145
+ zs.append(z[0, 0].detach().float().cpu())
146
+ hs.append(hist[0].detach().float().cpu())
147
+ ns.append(noise[0, 0].detach().float().cpu())
148
+ ls.append(latent[0, 0].detach().float().cpu())
149
+ inputs_embeds = mm.linear_proj_audio(latent)
150
+ position_ids = position_ids[:, -1:] + 1
151
+ attention_mask = torch.ones(inputs_embeds.shape[0], 1, device=device)
152
+ hist[:, :-mm.patch_size, :] = hist[:, mm.patch_size:, :].clone()
153
+ hist[:, -mm.patch_size:, :] = latent
154
+
155
+ torch.save({"text": text, "voice": v["slot"],
156
+ "z": torch.stack(zs), "history": torch.stack(hs),
157
+ "noise": torch.stack(ns), "latent": torch.stack(ls)}, dst)
158
+ total += n
159
+ if i % 10 == 0:
160
+ log(f"{v['slot']} {i+1}/{len(texts())} frames={n} total={total}")
161
+ except Exception:
162
+ log(f"{v['slot']} {i} failed\n{traceback.format_exc()}")
163
+ if SMOKE and i >= 4:
164
+ break
165
+ log(f"traj done: {total} frames")
166
+
167
+
168
+ def load_dataset():
169
+ import torch
170
+
171
+ zs, hs, ns, ls = [], [], [], []
172
+ for path in sorted(TRAJ.glob("*/*.pt")):
173
+ row = torch.load(path, map_location="cpu", weights_only=False)
174
+ zs.append(row["z"]); hs.append(row["history"])
175
+ ns.append(row["noise"]); ls.append(row["latent"])
176
+ if not zs:
177
+ raise RuntimeError("no trajectories")
178
+ z, h, n, l = (torch.cat(x).float() for x in (zs, hs, ns, ls))
179
+ log(f"dataset: {z.shape[0]} frames from {len(zs)} files")
180
+ return z, h, n, l
181
+
182
+
183
+ def train_student(teacher, data, n_steps, device):
184
+ import copy
185
+ import torch
186
+ import torch.nn.functional as F
187
+
188
+ z, h, n, target = [x.to(device) for x in data]
189
+ count = z.shape[0]
190
+ student = copy.deepcopy(teacher).to(device).train()
191
+ for p in student.parameters():
192
+ p.requires_grad_(True)
193
+ opt = torch.optim.AdamW(student.parameters(), lr=LR, weight_decay=0.01)
194
+ times = torch.linspace(0, 1, n_steps + 1).tolist()
195
+ losses = []
196
+ for step in range(TRAIN_STEPS):
197
+ idx = torch.randint(0, count, (min(BATCH, count),), device=device)
198
+ bz, bh = z[idx].unsqueeze(1), h[idx]
199
+ bn, bt = n[idx].unsqueeze(1), target[idx].unsqueeze(1)
200
+ y = bn
201
+ loss = 0.0
202
+ for i in range(n_steps):
203
+ ti, dt = times[i], times[i + 1] - times[i]
204
+ with torch.no_grad():
205
+ pred_cfg = teacher.forward_with_cfg(
206
+ x=y, t=torch.tensor(float(ti), device=device), c=bz,
207
+ latent_history=bh, patch_size=1,
208
+ )
209
+ pred, null = torch.chunk(pred_cfg, 2, dim=0)
210
+ tv = pred + (pred - null) * CFG_MULT
211
+ sv = student(
212
+ x=y, t=torch.full((y.shape[0],), float(ti), device=device),
213
+ c=bz, latent_history=bh, mask=None,
214
+ )[:, -1:, :]
215
+ loss = loss + F.mse_loss(sv, tv) * dt
216
+ y = (y + sv * dt).detach()
217
+ loss = loss + 0.5 * F.mse_loss(y, bt)
218
+ opt.zero_grad(set_to_none=True)
219
+ loss.backward()
220
+ torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0)
221
+ opt.step()
222
+ losses.append(float(loss.detach().cpu()))
223
+ if step % 100 == 0 or step == TRAIN_STEPS - 1:
224
+ log(f"train {step+1}/{TRAIN_STEPS} loss={losses[-1]:.5f}")
225
+ student.eval()
226
+ return student, losses
227
+
228
+
229
+ class _unused:
230
+ pass
231
+
232
+
233
+ def export_onnx(student, path: Path):
234
+ import copy
235
+ import torch
236
+
237
+ class Graph(torch.nn.Module):
238
+ def __init__(self, dit):
239
+ super().__init__()
240
+ self.dit = dit
241
+
242
+ def forward(self, x, t, c, history):
243
+ return self.dit(x=x, t=t, c=c, latent_history=history, mask=None)[:, -1:, :]
244
+
245
+ g = Graph(copy.deepcopy(student).float()).cpu().eval()
246
+ x = torch.randn(1, 1, 64); t = torch.tensor([0.5])
247
+ c = torch.randn(1, 1, 896); h = torch.randn(1, 1, 64)
248
+ with torch.inference_mode():
249
+ ref = g(x, t, c, h)
250
+ torch.onnx.export(g, (x, t, c, h), str(path),
251
+ input_names=["x", "t", "c", "history"],
252
+ output_names=["velocity"], opset_version=20,
253
+ do_constant_folding=True, dynamo=False)
254
+ import onnxruntime as ort
255
+ sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
256
+ got = sess.run(None, {"x": x.numpy(), "t": t.numpy(), "c": c.numpy(), "history": h.numpy()})[0]
257
+ err = float(np.abs(ref.numpy().reshape(-1) - got.reshape(-1)).max())
258
+ log(f"{path.name} {path.stat().st_size/1e6:.1f}MB max_abs={err:.2e}")
259
+ return err
260
+
261
+
262
+ def quantize(src: Path, dst: Path) -> None:
263
+ from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer
264
+
265
+ q = MatMulNBitsQuantizer(str(src), bits=4, block_size=32, is_symmetric=True,
266
+ accuracy_level=4, op_types_to_quantize=("MatMul",))
267
+ q.process()
268
+ q.model.save_model_to_file(str(dst), use_external_data_format=False)
269
+ log(f"{dst.name} {dst.stat().st_size/1e6:.1f}MB")
270
+
271
+
272
+ def sample_latent(dit, z, hist, noise, n_steps):
273
+ import torch
274
+
275
+ y = noise
276
+ for i in range(n_steps):
277
+ dt = 1.0 / n_steps
278
+ v = dit(x=y, t=torch.full((y.shape[0],), i / n_steps, device=y.device),
279
+ c=z, latent_history=hist, mask=None)[:, -1:, :]
280
+ y = y + v * dt
281
+ return y
282
+
283
+
284
+ def ar_generate(mm, dit, n_steps, text, task_prompt, prompt_latent, prompt_text, spk, frames):
285
+ import torch
286
+
287
+ device = next(mm.parameters()).device
288
+ dtype = next(mm.parameters()).dtype
289
+ with torch.no_grad():
290
+ input_ids, inputs_embeds = mm.prepare_input_embed(
291
+ prompt=task_prompt, text=text, spk_emb=spk,
292
+ prompt_latent=prompt_latent, prompt_text=prompt_text,
293
+ )
294
+ attention_mask = torch.ones(input_ids.shape, device=device)
295
+ position_ids = (attention_mask.cumsum(-1) - 1).masked_fill_(attention_mask == 0, 1)
296
+ past = None
297
+ hist = torch.zeros(1, mm.history_patch_size, mm.latent_dim, device=device, dtype=dtype)
298
+ start = mm.history_patch_size - prompt_latent.size(1)
299
+ if start < 0:
300
+ hist[:] = prompt_latent[:, -start:, :]
301
+ else:
302
+ hist[:, start:, :] = prompt_latent
303
+ out = []
304
+ for _ in range(frames):
305
+ with torch.no_grad():
306
+ hidden = mm.model(attention_mask=attention_mask, position_ids=position_ids,
307
+ inputs_embeds=inputs_embeds, audio_mask=None, image_mask=None,
308
+ output_hidden_states=True, return_dict=True, use_cache=True,
309
+ past_key_values=past)
310
+ past = hidden.past_key_values
311
+ z = hidden.hidden_states[-1][:, -1:, :]
312
+ noise = torch.randn(1, 1, mm.latent_dim, device=device, dtype=dtype)
313
+ latent = sample_latent(dit, z, hist, noise, n_steps).to(device=device, dtype=dtype)
314
+ out.append(latent)
315
+ inputs_embeds = mm.linear_proj_audio(latent)
316
+ position_ids = position_ids[:, -1:] + 1
317
+ attention_mask = torch.ones(inputs_embeds.shape[0], 1, device=device)
318
+ hist[:, :-mm.patch_size, :] = hist[:, mm.patch_size:, :].clone()
319
+ hist[:, -mm.patch_size:, :] = latent
320
+ with torch.no_grad():
321
+ speech = mm.audio.decode(torch.cat(out, dim=1), past_key_values=None,
322
+ use_cache=False, last_chunk=True)[0]
323
+ return speech.cpu().float().reshape(-1).numpy()
324
+
325
+
326
+ def stage_eval() -> None:
327
+ import copy
328
+ import torch
329
+ from transformers import pipeline
330
+
331
+ sys.path.insert(0, str(REPO))
332
+ from ming_tts import MingTTS
333
+ import tts_tasks
334
+ sys.path.insert(0, str(BUNDLE / "eval"))
335
+ from score import load_t2s, score_row
336
+
337
+ table = load_t2s()
338
+ task_prompt = tts_tasks.build_tts_prompt("Chinese")
339
+ ckpt = OUT / f"student{STEPS}.pt"
340
+ state = {k: v.float() for k, v in torch.load(ckpt, map_location="cpu").items()}
341
+
342
+ tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
343
+ mm = tts.model
344
+ device = next(mm.parameters()).device
345
+ teacher = mm.flowloss.cfm.model.float().eval()
346
+ student = copy.deepcopy(teacher)
347
+ student.load_state_dict(state)
348
+ student = student.to(device).eval()
349
+
350
+ asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small",
351
+ device=0, torch_dtype=torch.float16)
352
+
353
+ def asr(y):
354
+ out = asr_pipe({"array": y.astype(np.float32), "sampling_rate": 44100},
355
+ generate_kwargs={"language": "zh", "task": "transcribe"})
356
+ return (out.get("text", "") if isinstance(out, dict) else str(out)).strip()
357
+
358
+ sents = json.loads((BUNDLE / "eval/sentences.json").read_text())["items"]
359
+ want = EVAL_VOICES or [v["slot"] for v in voices()[:2]]
360
+ rows = []
361
+ for v in [x for x in voices() if x["slot"] in want]:
362
+ latent, spk = tts.prepare_prompt(str(BUNDLE / v["wav"]), use_spk_emb=True)
363
+ latent = latent.to(device=device, dtype=next(mm.parameters()).dtype)
364
+ spk = [x.to(device=device, dtype=next(mm.parameters()).dtype) for x in spk]
365
+ for item in sents:
366
+ text = item["text"]
367
+ try:
368
+ tw = tts.synthesize(task="TTS", text=text, language_id="Chinese",
369
+ prompt_wav_path=str(BUNDLE / v["wav"]),
370
+ prompt_text=v["prompt_text"], use_spk_emb=True,
371
+ raw_text=True, max_decode_steps=max(32, min(400, int(len(text) * 3.5))))
372
+ tw = tw.cpu().numpy().reshape(-1)
373
+ frames = max(16, int(round(tw.size / 3528)))
374
+ torch.manual_seed(SEED)
375
+ sw = ar_generate(mm, student, STEPS, text, task_prompt, latent,
376
+ v["prompt_text"], spk, frames)
377
+ for name, arr in (("teacher", tw), ("student", sw)):
378
+ hyp = asr(arr)
379
+ s = score_row({"text": text, "hyp_text": hyp}, table)
380
+ rows.append({"voice": v["slot"], "artist": v["artist"], "id": item["id"],
381
+ "model": name, "text": text, "cer": s["cer_norm"],
382
+ "cer_head": s["cer_prefix"], "hyp": hyp})
383
+ except Exception:
384
+ log(f"eval {v['slot']} {item['id']} failed\n{traceback.format_exc()}")
385
+ log(f"eval {v['slot']} done ({len(rows)} rows)")
386
+
387
+ (OUT / "eval_rows.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
388
+ for name in ("teacher", "student"):
389
+ sel = [r for r in rows if r["model"] == name]
390
+ if sel:
391
+ log(f"{name:<8} n={len(sel)} cer={np.mean([r['cer'] for r in sel]):.4f} "
392
+ f"head={np.mean([r['cer_head'] for r in sel]):.4f}")
393
+ for v in sorted({r["voice"] for r in sel}):
394
+ vs = [r["cer"] for r in sel if r["voice"] == v]
395
+ log(f" {v} n={len(vs)} cer={np.mean(vs):.4f}")
396
+
397
+
398
+ def main() -> None:
399
+ import torch
400
+
401
+ torch.manual_seed(SEED)
402
+ if torch.cuda.is_available():
403
+ torch.cuda.manual_seed_all(SEED)
404
+ device = torch.device("cuda")
405
+
406
+ if STAGE == "traj":
407
+ patch_fp32()
408
+ stage_traj()
409
+ return
410
+
411
+ sys.path.insert(0, str(REPO))
412
+ patch_fp32()
413
+ from ming_tts import MingTTS
414
+ tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
415
+ mm = tts.model
416
+
417
+ if STAGE in ("train", "all"):
418
+ data = load_dataset()
419
+ teacher = mm.flowloss.cfm.model.float().to(device).eval()
420
+ for p in teacher.parameters():
421
+ p.requires_grad_(False)
422
+ student, losses = train_student(teacher, data, STEPS, device)
423
+ torch.save({k: v.half().cpu() for k, v in student.state_dict().items()},
424
+ OUT / f"student{STEPS}.pt")
425
+ (OUT / "train_loss.json").write_text(json.dumps({"first": losses[0], "last": losses[-1],
426
+ "steps": TRAIN_STEPS, "lr": LR}))
427
+ log(f"saved student{STEPS}.pt loss {losses[0]:.4f} -> {losses[-1]:.4f}")
428
+
429
+ if STAGE in ("export", "all"):
430
+ student = copy_state(mm, OUT / f"student{STEPS}.pt", device) if STAGE == "export" else student
431
+ fp32 = OUT / f"dit{STEPS}.onnx"
432
+ export_onnx(student, fp32)
433
+ quantize(fp32, OUT / f"dit{STEPS}_int4.onnx")
434
+
435
+ if STAGE in ("eval", "all"):
436
+ stage_eval()
437
+
438
+
439
+ def copy_state(mm, path, device):
440
+ import copy
441
+ import torch
442
+
443
+ state = {k: v.float() for k, v in torch.load(path, map_location="cpu").items()}
444
+ dit = copy.deepcopy(mm.flowloss.cfm.model.float())
445
+ dit.load_state_dict(state)
446
+ return dit.to(device).eval()
447
+
448
+
449
+ if __name__ == "__main__":
450
+ main()
451
+
train_texts.json ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "seed": 20261030,
3
+ "source": "books/story.txt",
4
+ "n": 120,
5
+ "texts": [
6
+ "‘大王是向来善于猜疑,又极残忍的。",
7
+ "巡士反背着手,看他渐跑渐远,没入尘头中,这才慢慢的回转身,向原来的路上踱去。",
8
+ "O.K美国式的英语:“对啦。",
9
+ "”老子再三称谢,收了口袋,和大家走下城楼,到得关口,还要牵着青牛走路;",
10
+ "“这模样了,还要来攻它!",
11
+ "特别的寂静倒使殿上殿下的人们警醒。",
12
+ "前面并没有仪仗,不过一大批乞丐似的随员。",
13
+ "谓其妻曰:‘吾藏剑在南山之阴,北山之阳;",
14
+ "”他说着,又看看网兜里的母鸡,倒并没有压坏,便跨上马,径自走了。",
15
+ ")阿金姐作者虚拟的人名。",
16
+ "现在谁都讲卫生,卫生是顶要紧的。",
17
+ "”他看见他的母亲坐在灰白色的月影中,仿佛身体都在颤动;",
18
+ "于是轰轰了一阵,屋里逐渐坐满了听讲的人们。",
19
+ "我庄周曾经做梦变了蝴蝶,是一只飘飘荡荡的蝴蝶,醒来成了庄周,是一个忙忙碌碌的庄周。",
20
+ "不过……”孔子很有些焦躁模样,这是他从来所没有的。",
21
+ "指物件,含有轻蔑、厌恶的意思。",
22
+ "口渴可不是玩意儿呀,真不如化为蝴蝶。",
23
+ "我是有正经事,探亲去的。",
24
+ "“三弟,有什么捞儿没有?",
25
+ "六樵夫偶然发见了伯夷和叔齐都缩做一团,死在山背后的石洞里,是大约这之后的二十天。",
26
+ "公孙高古书中无可查考,当是作者虚拟的人名。",
27
+ "’子墨子归,过宋,天雨,庇其闾中,守闾者不内(纳)也。",
28
+ "大家只得停住,等候她的到来。",
29
+ "然而这诧异使伊喜欢,以未曾有的勇往和愉快继续着伊的事业,呼吸吹嘘着,汗混和着……“Nga!",
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
+ "庄子(约前369—前286)名周,战国时宋国人,曾为漆园吏,我国古代思想家,道家思想的代表人物。",
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
+ }