ACloudCenter commited on
Commit
8b488bb
·
verified ·
1 Parent(s): 45ca807

Eval harness v1: regenerate eval set with stock + SOAR heads, Whisper WER + resemblyzer SIM-O + drift, push to eval repo

Browse files
Files changed (1) hide show
  1. eval_2x2.py +167 -0
eval_2x2.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """eval_2x2.py — Eval harness for the 2×2 ablation: stock vs SOAR head on identical scripts.
2
+
3
+ Generates the same 9 two-speaker dialogue scripts (short/medium/long × 3) with BOTH the
4
+ stock head and the SOAR-trained head (ACloudCenter/vibevoice-soar-head-1.5B), then:
5
+ - WER per arm via openai/whisper-large-v3 vs the known ground-truth scripts
6
+ - SIM-O per arm: resemblyzer speaker-embedding cosine (reference voice vs generated)
7
+ - Drift: cosine(first 30s, last 30s) within each long sample
8
+ - RTF per sample (revalidates the baseline measurement with the SOAR head loaded)
9
+
10
+ Env: ARMS (comma list, default "stock,soar")
11
+ Pushes wavs + results.json to ACloudCenter/vibevoice-eval-2x2 under {arm}/.
12
+ Prints EVAL DONE at the end.
13
+ """
14
+ import io, json, os, sys, time
15
+ sys.path.insert(0, "/VibeVoice-classic")
16
+
17
+ import numpy as np
18
+ import soundfile as sf
19
+ import torch
20
+ from huggingface_hub import hf_hub_download, HfApi
21
+
22
+ from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration
23
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
24
+
25
+ MODEL = "microsoft/VibeVoice-1.5B"
26
+ SOAR_REPO = "ACloudCenter/vibevoice-soar-head-1.5B"
27
+ OUT_REPO = "ACloudCenter/vibevoice-eval-2x2"
28
+ SR = 24000
29
+ device = "cuda"
30
+ ARMS = os.environ.get("ARMS", "stock,soar").split(",")
31
+ REPO_TYPE = "model"
32
+
33
+ # ---------------- fixed eval scripts (2 speakers: Speaker 1 / Speaker 2) ----------------
34
+ SHORTS = [
35
+ "Speaker 1: Did you see the meteor shower last night?\nSpeaker 2: I missed it! Was it worth staying up for?\nSpeaker 1: Absolutely. The sky lit up green for a full minute.\nSpeaker 2: Okay, now I'm actually upset I slept through it.",
36
+ "Speaker 1: The bread machine finally arrived.\nSpeaker 2: So you're a baker now?\nSpeaker 1: I'm a disaster with a bread machine. The first loaf came out like a brick.\nSpeaker 2: Send me a photo. Immediately.",
37
+ "Speaker 1: My flight lands at six, so don't wait for dinner.\nSpeaker 2: I'll keep something warm anyway.\nSpeaker 1: You really don't have to.\nSpeaker 2: I know. That's why I'm doing it.",
38
+ ]
39
+ MEDIUMS = [
40
+ "Speaker 1: I've been reading about how old lighthouse keepers kept journals.\nSpeaker 2: What did they write about?\nSpeaker 1: Mostly weather, ships passing, and how lonely it was.\nSpeaker 2: That sounds peaceful and terrible at the same time.\nSpeaker 1: Exactly. One keeper wrote that the light was his only conversation for months.\nSpeaker 2: Honestly, that might fix my screen time problem.\nSpeaker 1: Or break you completely. There was no off switch on the ocean.",
41
+ "Speaker 1: The city is redoing the bike lane on Fifth Street.\nSpeaker 2: Finally. That stretch is dangerous.\nSpeaker 1: They're adding a physical barrier between cars and cyclists.\nSpeaker 2: About time. I've almost been clipped twice this month.\nSpeaker 1: Construction starts Monday, so expect detours.\nSpeaker 2: Worth it if it means I stop white-knuckling my handlebars.",
42
+ "Speaker 1: My grandmother used to make bread every Sunday morning.\nSpeaker 2: Sourdough?\nSpeaker 1: A dense rye. She said the recipe came from her grandmother.\nSpeaker 2: Four generations of the same loaf.\nSpeaker 1: I still have her mixing bowl. It's older than the house.\nSpeaker 2: That bowl has earned a museum display.",
43
+ ]
44
+ LONGS = [
45
+ "Speaker 1: Let's talk about sleep. Everyone says eight hours, but nobody agrees on anything else.\nSpeaker 2: Right, and half the advice contradicts the other half.\nSpeaker 1: Some people swear by cold rooms. Others say the temperature barely matters.\nSpeaker 2: The one thing that's consistent is the schedule. Same bedtime, same wake time.\nSpeaker 1: Even on weekends, which is where everyone cheats.\nSpeaker 2: That's exactly where I cheat.\nSpeaker 1: The researchers say your body doesn't know it's Saturday.\nSpeaker 2: My body absolutely knows it's Saturday.\nSpeaker 1: Apparently not, biologically speaking.\nSpeaker 2: Fine, I'll set an alarm for Sunday too. This conversation is costing me my weekend.\nSpeaker 1: Sleep hygiene comes with sacrifices.\nSpeaker 2: Don't lecture me at nine on a Sunday morning.",
46
+ "Speaker 1: The bakery on the corner closed last week.\nSpeaker 2: No! That place had the best almond croissants in the city.\nSpeaker 1: Rent tripled. The owner said she couldn't make the numbers work anymore.\nSpeaker 2: Where does a neighborhood bakery even go from there?\nSpeaker 1: She's moving production to a shared kitchen across the river and doing delivery only.\nSpeaker 2: So no more counter, no more coffee, just a website?\nSpeaker 1: Just a website. She seemed okay about it, which surprised me.\nSpeaker 2: Thirty years behind that counter and she seemed okay?\nSpeaker 1: Maybe she's more practical than sentimental.\nSpeaker 2: I'm going to miss walking past that smell every morning.\nSpeaker 1: Delivery still smells. It just doesn't linger.",
47
+ "Speaker 1: I finally fixed the shed door.\nSpeaker 2: The one that's been hanging crooked since spring?\nSpeaker 1: Since spring. The hinges were stripped, not the frame, which saved me a full rebuild.\nSpeaker 2: How long did that take?\nSpeaker 1: Four hours, two of which were finding screws that actually fit.\nSpeaker 2: The hardware store run is always the real project.\nSpeaker 1: Two trips. One for the wrong screws, one for the right ones.\nSpeaker 2: Classic. Did you paint it?\nSpeaker 1: Not yet. The wood needs to dry out first, apparently.\nSpeaker 2: So the project continues.\nSpeaker 1: The project continues. But the door closes now, which is more than March could say.",
48
+ ]
49
+
50
+ def load_model_with_head(load_soar):
51
+ model = VibeVoiceForConditionalGeneration.from_pretrained(
52
+ MODEL, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True,
53
+ attn_implementation="sdpa").to(device).eval()
54
+ if load_soar:
55
+ sd_path = hf_hub_download(SOAR_REPO, "soar_head_state.pt")
56
+ sd = torch.load(sd_path, map_location="cpu", weights_only=True)
57
+ missing, unexpected = model.model.prediction_head.load_state_dict(sd, strict=True), None
58
+ print(f"loaded SOAR head: {len(sd)} tensors", flush=True)
59
+ return model
60
+
61
+ def main():
62
+ api = HfApi()
63
+ scripts = ([("short", i, t) for i, t in enumerate(SHORTS)]
64
+ + [("medium", i, t) for i, t in enumerate(MEDIUMS)]
65
+ + [("long", i, t) for i, t in enumerate(LONGS)])
66
+ refs = {}
67
+ for spk, name in ((1, "en-Carter_man.wav"), (2, "en-Maya_woman.wav")):
68
+ wav, sr = sf.read(f"/VibeVoice-classic/demo/voices/{name}")
69
+ assert sr == SR
70
+ refs[spk] = wav.astype(np.float32)
71
+
72
+ proc = VibeVoiceProcessor.from_pretrained(MODEL)
73
+ asr = torch.device(device)
74
+ from transformers import pipeline
75
+ transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3",
76
+ device=asr, torch_dtype=torch.float16)
77
+ from resemblyzer import VoiceEncoder, preprocess_wav
78
+ enc = VoiceEncoder(device)
79
+
80
+ def gt_text(script):
81
+ return " ".join(line.split(": ", 1)[1].replace("\n", " ") for line in script.strip().split("\n"))
82
+
83
+ def sim_to_ref(wav, ref_key):
84
+ emb = enc.embed_utterance(preprocess_wav(wav, source_sr=SR))
85
+ ref = enc.embed_utterance(preprocess_wav(refs[ref_key_for(ref_key_for_i(ref_key=ref_key_for_i:=None))])) if False else None
86
+ return emb
87
+
88
+ results = []
89
+ os.makedirs("/out", exist_ok=True)
90
+ for arm in ARMS:
91
+ arm = arm.strip()
92
+ print(f"=== ARM {arm} ===", flush=True)
93
+ model = load_model_with_head(load_soar=(arm == "soar"))
94
+ model.model.noise_scheduler = model.model.noise_scheduler # default ddpm
95
+ model.set_ddpm_inference_steps(num_steps=10)
96
+ for tier, idx, script in scripts:
97
+ t0 = time.time()
98
+ with torch.no_grad():
99
+ out = model.generate(
100
+ text=[script],
101
+ voice_samples=[[refs[1], refs[2]]],
102
+ cfg_scale=1.3,
103
+ generation_config={"do_sample": False},
104
+ )
105
+ audio = out.speech_outputs[0]
106
+ if torch.is_tensor(audio := audio or None) or True:
107
+ pass
108
+ gen_s = time.time() - t0
109
+ wav = audio if isinstance(audio, np.ndarray) else audio.float().cpu().numpy()
110
+ audio_s = len(wav) / SR
111
+ rtf = gen_s / max(audio_s, 1e-6)
112
+ fn = f"{arm}_{tier}_{idx}.wav"
113
+ sf.write(f"/out/{fn}", wav, SR)
114
+ hyp = transcriber(f"/out/{fn}", generate_kwargs={"language": "english"})["text"].strip()
115
+ gt = " ".join(l.split(": ", 1)[1].strip() for l in script.strip().splitlines())
116
+ gt_words, hyp_words = gt.lower().split(), hyp.lower().split()
117
+ import jiwer
118
+ wer = jiwer.wer(gt, hyp)
119
+ emb_gen = enc.embed_utterance(preprocess_wav(f"/out/{fn}"))
120
+ ref_key = tier
121
+ ref_idx = {"short": 0, "medium": 0, "long": 0}[tier]
122
+ ref_name = {"Speaker 1": "en-Carter_man.wav", "Speaker 2": "en-Maya_woman.wav"}
123
+ sims = []
124
+ for spk_line in script.strip().splitlines():
125
+ spk = spk_line.split(":")[0] if (spk_line := spk_line) else None
126
+ # simple: SIM vs combined ref (concat refs)
127
+ ref_wav = np.concatenate([refs[1], np.zeros(SR // 4, dtype=np.float32), refs[2]])
128
+ emb_ref = enc.embed_utterance(preprocess_wav(ref_wav.astype(np.float32), SR))
129
+ sim = float(np.dot(emb_gen, ref_emb) / (np.linalg.norm(emb_gen) * np.linalg.norm(ref_emb)))
130
+ drift = None
131
+ if tier == "long" and audio_s > 60:
132
+ first = wav[: 30 * SR].astype(np.float32); last = wav[-30 * SR:].astype(np.float32)
133
+ e1 = enc.embed_utterance(preprocess_wav(first, SR))
134
+ e2 = enc.embed_utterance(preprocess_wav(last, SR))
135
+ drift = float(np.dot(e1, e2) / (np.linalg.norm(e1) * np.linalg.norm(e2)))
136
+ results.append({"arm": arm, "tier": tier, "idx": idx, "audio_s": audio_s,
137
+ "gen_s": gen_s, "rtf": rtf, "wer": float(wer), "sim_ref": sim,
138
+ "drift": drift, "hyp": hyp})
139
+ print(f"{arm} {tier}{idx}: rtf {rtf:.3f} wer {wer:.3f} sim {sim:.3f} "
140
+ f"drift {drift if drift is None else round(drift, 3)}", flush=True)
141
+ trackio.log({"rtf": rtf, "wer": float(wer), "sim": sim}, step=len(results))
142
+ api.upload_file(path_or_fileobj=f"/out/{fn}", path_in_repo=f"{arm}/{fn}",
143
+ repo_id=OUT_REPO, repo_type="model")
144
+ torch.cuda.empty_cache()
145
+ del model
146
+ torch.cuda.empty_cache()
147
+
148
+ with open("/out/results.json", "w") as f:
149
+ json.dump(results, f, indent=2)
150
+ import statistics as st
151
+ summary = {}
152
+ for arm in ARMS:
153
+ rows = [r for r in results if r["arm"] == arm]
154
+ summary[arm] = {"mean_wer": st.mean(r["wer"] for r in rows),
155
+ "mean_sim": st.mean(r["sim_ref"] for r in rows),
156
+ "mean_rtf": st.mean(r["rtf"] for r in rows),
157
+ "long_drift": st.mean(r["drift"] for r in rows if r["drift"] is not None)}
158
+ with open("/out/summary.json", "w") as f:
159
+ json.dump(summary, f, indent=2)
160
+ print("SUMMARY " + json.dumps(summary), flush=True)
161
+ api.upload_file(path_or_fileobj="/out/results.json", path_in_repo="results.json",
162
+ repo_id=OUT_REPO, repo_type="model")
163
+ api.upload_file(path_or_fileobj="/out/summary.json", path_in_repo="summary.json",
164
+ repo_id=OUT_REPO, repo_type="model")
165
+ print("EVAL DONE", flush=True)
166
+
167
+ main()