holdout run: exclude a07 from training, add int4 eval stage
Browse files- kaggle/train_voices.py +97 -6
kaggle/train_voices.py
CHANGED
|
@@ -42,6 +42,7 @@ 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 |
|
|
@@ -64,9 +65,11 @@ def patch_fp32() -> None:
|
|
| 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
|
|
@@ -281,7 +284,7 @@ def sample_latent(dit, z, hist, noise, n_steps):
|
|
| 281 |
return y
|
| 282 |
|
| 283 |
|
| 284 |
-
def ar_generate(mm,
|
| 285 |
import torch
|
| 286 |
|
| 287 |
device = next(mm.parameters()).device
|
|
@@ -313,7 +316,7 @@ def ar_generate(mm, dit, n_steps, text, task_prompt, prompt_latent, prompt_text,
|
|
| 313 |
# no_grad matters: the DiT params require grad, so an unguarded sample
|
| 314 |
# builds a graph per frame that stays alive through `hist`.
|
| 315 |
with torch.no_grad():
|
| 316 |
-
latent =
|
| 317 |
out.append(latent.detach())
|
| 318 |
inputs_embeds = mm.linear_proj_audio(latent)
|
| 319 |
position_ids = position_ids[:, -1:] + 1
|
|
@@ -357,7 +360,7 @@ def stage_eval() -> None:
|
|
| 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 |
-
sel = [x for x in voices() if x["slot"] in want]
|
| 361 |
wav_dir = OUT / "eval_wavs"
|
| 362 |
wav_dir.mkdir(parents=True, exist_ok=True)
|
| 363 |
rows = []
|
|
@@ -410,8 +413,8 @@ def stage_eval() -> None:
|
|
| 410 |
tw = torch.load(tp, map_location="cpu").numpy()
|
| 411 |
frames = max(16, int(round(tw.size / 3528)))
|
| 412 |
torch.manual_seed(SEED)
|
| 413 |
-
sw = ar_generate(mm, student,
|
| 414 |
-
v["prompt_text"], spk, frames)
|
| 415 |
hyp = asr(sw)
|
| 416 |
s = score_row({"text": text, "hyp_text": hyp}, table)
|
| 417 |
rows.append({"voice": v["slot"], "artist": v["artist"], "id": item["id"],
|
|
@@ -433,6 +436,89 @@ def stage_eval() -> None:
|
|
| 433 |
log(f" {v} n={len(vs)} cer={np.mean(vs):.4f}")
|
| 434 |
|
| 435 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
def main() -> None:
|
| 437 |
import torch
|
| 438 |
|
|
@@ -446,6 +532,11 @@ def main() -> None:
|
|
| 446 |
stage_traj()
|
| 447 |
return
|
| 448 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 449 |
sys.path.insert(0, str(REPO))
|
| 450 |
patch_fp32()
|
| 451 |
from ming_tts import MingTTS
|
|
|
|
| 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 |
+
HOLDOUT = {v for v in os.environ.get("HOLDOUT", "").split(",") if v}
|
| 46 |
N_TEXTS = int(os.environ.get("N_TEXTS", "120"))
|
| 47 |
SMOKE = os.environ.get("SMOKE", "0") == "1"
|
| 48 |
|
|
|
|
| 65 |
path.write_text(s)
|
| 66 |
|
| 67 |
|
| 68 |
+
def voices(include_holdout: bool = False) -> list[dict]:
|
| 69 |
vs = json.loads((BUNDLE / "mined/manifest.json").read_text())["voices"]
|
| 70 |
vs = [v for v in vs if v["artist"] not in DROP]
|
| 71 |
+
if not include_holdout:
|
| 72 |
+
vs = [v for v in vs if v["slot"] not in HOLDOUT]
|
| 73 |
if VOICE_FILTER:
|
| 74 |
vs = [v for v in vs if v["slot"] in VOICE_FILTER]
|
| 75 |
return vs
|
|
|
|
| 284 |
return y
|
| 285 |
|
| 286 |
|
| 287 |
+
def ar_generate(mm, sample_fn, text, task_prompt, prompt_latent, prompt_text, spk, frames):
|
| 288 |
import torch
|
| 289 |
|
| 290 |
device = next(mm.parameters()).device
|
|
|
|
| 316 |
# no_grad matters: the DiT params require grad, so an unguarded sample
|
| 317 |
# builds a graph per frame that stays alive through `hist`.
|
| 318 |
with torch.no_grad():
|
| 319 |
+
latent = sample_fn(z, hist, noise).to(device=device, dtype=dtype)
|
| 320 |
out.append(latent.detach())
|
| 321 |
inputs_embeds = mm.linear_proj_audio(latent)
|
| 322 |
position_ids = position_ids[:, -1:] + 1
|
|
|
|
| 360 |
|
| 361 |
sents = json.loads((BUNDLE / "eval/sentences.json").read_text())["items"]
|
| 362 |
want = EVAL_VOICES or [v["slot"] for v in voices()[:2]]
|
| 363 |
+
sel = [x for x in voices(include_holdout=True) if x["slot"] in want]
|
| 364 |
wav_dir = OUT / "eval_wavs"
|
| 365 |
wav_dir.mkdir(parents=True, exist_ok=True)
|
| 366 |
rows = []
|
|
|
|
| 413 |
tw = torch.load(tp, map_location="cpu").numpy()
|
| 414 |
frames = max(16, int(round(tw.size / 3528)))
|
| 415 |
torch.manual_seed(SEED)
|
| 416 |
+
sw = ar_generate(mm, lambda z, h, n: sample_latent(student, z, h, n, STEPS),
|
| 417 |
+
text, task_prompt, latent, v["prompt_text"], spk, frames)
|
| 418 |
hyp = asr(sw)
|
| 419 |
s = score_row({"text": text, "hyp_text": hyp}, table)
|
| 420 |
rows.append({"voice": v["slot"], "artist": v["artist"], "id": item["id"],
|
|
|
|
| 436 |
log(f" {v} n={len(vs)} cer={np.mean(vs):.4f}")
|
| 437 |
|
| 438 |
|
| 439 |
+
def stage_eval_int4() -> None:
|
| 440 |
+
"""Same cells as stage_eval, sampled through the int4 ONNX graph.
|
| 441 |
+
|
| 442 |
+
Runs as its own process so the PyTorch DiT is not resident: the ORT session
|
| 443 |
+
plus the backbone is already close to a 15 GB T4.
|
| 444 |
+
"""
|
| 445 |
+
import onnxruntime as ort
|
| 446 |
+
import torch
|
| 447 |
+
from transformers import pipeline
|
| 448 |
+
|
| 449 |
+
sys.path.insert(0, str(REPO))
|
| 450 |
+
from ming_tts import MingTTS
|
| 451 |
+
import tts_tasks
|
| 452 |
+
sys.path.insert(0, str(BUNDLE / "eval"))
|
| 453 |
+
from score import load_t2s, score_row
|
| 454 |
+
|
| 455 |
+
table = load_t2s()
|
| 456 |
+
model_path = OUT / f"dit{STEPS}_int4.onnx"
|
| 457 |
+
if not model_path.exists():
|
| 458 |
+
raise SystemExit(f"{model_path} missing")
|
| 459 |
+
sess = ort.InferenceSession(str(model_path), providers=["CUDAExecutionProvider"])
|
| 460 |
+
log(f"int4 session providers: {sess.get_providers()}")
|
| 461 |
+
|
| 462 |
+
def ort_sample(z, hist, noise):
|
| 463 |
+
times = [i / STEPS for i in range(STEPS + 1)]
|
| 464 |
+
y = noise.detach().cpu().numpy()
|
| 465 |
+
zc, hc = z.detach().cpu().numpy(), hist.detach().cpu().numpy()
|
| 466 |
+
for i in range(STEPS):
|
| 467 |
+
v = sess.run(None, {"x": y, "t": np.array([times[i]], np.float32),
|
| 468 |
+
"c": zc, "history": hc})[0]
|
| 469 |
+
y = y + v * (times[i + 1] - times[i])
|
| 470 |
+
return torch.from_numpy(y)
|
| 471 |
+
|
| 472 |
+
tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
|
| 473 |
+
mm = tts.model
|
| 474 |
+
device = next(mm.parameters()).device
|
| 475 |
+
dtype = next(mm.parameters()).dtype
|
| 476 |
+
task_prompt = tts_tasks.build_tts_prompt("Chinese")
|
| 477 |
+
asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small",
|
| 478 |
+
device=0, torch_dtype=torch.float16)
|
| 479 |
+
|
| 480 |
+
def asr(y):
|
| 481 |
+
out = asr_pipe({"array": y.astype(np.float32), "sampling_rate": 44100},
|
| 482 |
+
generate_kwargs={"language": "zh", "task": "transcribe"})
|
| 483 |
+
return (out.get("text", "") if isinstance(out, dict) else str(out)).strip()
|
| 484 |
+
|
| 485 |
+
sents = json.loads((BUNDLE / "eval/sentences.json").read_text())["items"]
|
| 486 |
+
want = EVAL_VOICES or [v["slot"] for v in voices(include_holdout=True)[:2]]
|
| 487 |
+
wav_dir = OUT / "eval_wavs"
|
| 488 |
+
rows = []
|
| 489 |
+
for v in [x for x in voices(include_holdout=True) if x["slot"] in want]:
|
| 490 |
+
latent, spk = tts.prepare_prompt(str(BUNDLE / v["wav"]), use_spk_emb=True)
|
| 491 |
+
latent = latent.to(device=device, dtype=dtype)
|
| 492 |
+
spk = [x.to(device=device, dtype=dtype) for x in spk]
|
| 493 |
+
for item in sents:
|
| 494 |
+
text = item["text"]
|
| 495 |
+
try:
|
| 496 |
+
tp = wav_dir / f"{v['slot']}_{item['id']}_teacher.pt"
|
| 497 |
+
tw = torch.load(tp, map_location="cpu").numpy()
|
| 498 |
+
frames = max(16, int(round(tw.size / 3528)))
|
| 499 |
+
torch.manual_seed(SEED)
|
| 500 |
+
sw = ar_generate(mm, ort_sample, text, task_prompt, latent,
|
| 501 |
+
v["prompt_text"], spk, frames)
|
| 502 |
+
hyp = asr(sw)
|
| 503 |
+
s = score_row({"text": text, "hyp_text": hyp}, table)
|
| 504 |
+
rows.append({"voice": v["slot"], "artist": v["artist"], "id": item["id"],
|
| 505 |
+
"model": "int4", "text": text, "cer": s["cer_norm"],
|
| 506 |
+
"cer_head": s["cer_prefix"], "hyp": hyp})
|
| 507 |
+
except Exception:
|
| 508 |
+
log(f"int4 {v['slot']} {item['id']} failed\n{traceback.format_exc()}")
|
| 509 |
+
torch.cuda.empty_cache()
|
| 510 |
+
log(f"int4 {v['slot']} done ({len(rows)} rows)")
|
| 511 |
+
|
| 512 |
+
(OUT / "eval_rows_int4.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
|
| 513 |
+
sel_rows = rows
|
| 514 |
+
if sel_rows:
|
| 515 |
+
log(f"int4 n={len(sel_rows)} cer={np.mean([r['cer'] for r in sel_rows]):.4f} "
|
| 516 |
+
f"head={np.mean([r['cer_head'] for r in sel_rows]):.4f}")
|
| 517 |
+
for v in sorted({r["voice"] for r in sel_rows}):
|
| 518 |
+
vs = [r["cer"] for r in sel_rows if r["voice"] == v]
|
| 519 |
+
log(f" {v} n={len(vs)} cer={np.mean(vs):.4f}")
|
| 520 |
+
|
| 521 |
+
|
| 522 |
def main() -> None:
|
| 523 |
import torch
|
| 524 |
|
|
|
|
| 532 |
stage_traj()
|
| 533 |
return
|
| 534 |
|
| 535 |
+
if STAGE == "eval_int4":
|
| 536 |
+
patch_fp32()
|
| 537 |
+
stage_eval_int4()
|
| 538 |
+
return
|
| 539 |
+
|
| 540 |
sys.path.insert(0, str(REPO))
|
| 541 |
patch_fp32()
|
| 542 |
from ming_tts import MingTTS
|