File size: 10,725 Bytes
5a0fc48
8b488bb
5a0fc48
 
 
 
8b488bb
555d805
 
8b488bb
00ed9c6
8b488bb
 
 
 
 
555d805
 
8b488bb
555d805
8b488bb
00ed9c6
8b488bb
 
 
 
 
 
 
555d805
8b488bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555d805
8b488bb
00ed9c6
8b488bb
 
 
 
 
555d805
8b488bb
 
 
555d805
 
 
 
 
8b488bb
 
 
 
 
00ed9c6
5a0fc48
 
8b488bb
 
 
5a0fc48
 
 
8b488bb
 
 
 
555d805
 
8b488bb
5a0fc48
555d805
8b488bb
 
 
 
 
 
 
 
 
 
00ed9c6
 
8b488bb
00ed9c6
 
8b488bb
00ed9c6
8b488bb
 
 
5a0fc48
555d805
5a0fc48
 
555d805
8b488bb
 
 
555d805
 
 
 
8b488bb
 
555d805
 
8b488bb
 
555d805
8b488bb
555d805
 
 
8b488bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555d805
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""eval_2x2.py — canonical eval harness: stock vs SOAR head on identical 9-dialogue scripts.

All fixes baked in (v10):
- demo-exact generate pattern (return_tensors="pt", voice paths, tokenizer pass-through)
- sf.read tuple unpacks everywhere
- audio written via proc.save_audio (fork demo's own path), read back for metrics

Env: ARMS (comma list, default "stock,soar"). Pushes wavs + results to
ACloudCenter/vibevoice-eval-2x2 under {arm}/. Prints EVAL DONE at the end.
"""
import json, os, sys, time
sys.path.insert(0, "/VibeVoice-classic")

import numpy as np
import soundfile as sf
import torch
import jiwer
import statistics as st
from huggingface_hub import hf_hub_download, HfApi
from resemblyzer import VoiceEncoder, preprocess_wav

from vibevoice.modular.modeling_vibevoice_inference import VibeVoiceForConditionalGenerationInference
from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor

MODEL = "microsoft/VibeVoice-1.5B"
SOAR_REPO = "ACloudCenter/vibevoice-soar-head-1.5B"
OUT_REPO = "ACloudCenter/vibevoice-eval-2x2"
SR = 24000
device = "cuda"
ARMS = [a.strip() for a in os.environ.get("ARMS", "stock,soar").split(",")]

SHORTS = [
    "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.",
    "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.",
    "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.",
]
MEDIUMS = [
    "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.",
    "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.",
    "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.",
]
LONGS = [
    "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.",
    "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.",
    "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.",
]


def load_model_with_head(load_soar):
    model = VibeVoiceForConditionalGenerationInference.from_pretrained(
        MODEL, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True,
        attn_implementation="sdpa").to(device).eval()
    if load_soar:
        sd_path = hf_hub_download(SOAR_REPO, "soar_head_state.pt")
        sd = torch.load(sd_path, map_location="cpu", weights_only=True)
        model.model.prediction_head.load_state_dict(sd, strict=True)
        print(f"loaded SOAR head: {len(sd)} tensors", flush=True)
    return model


def gt_text(script):
    return " ".join(line.split(": ", 1)[1].strip() for line in script.strip().splitlines())


def main():
    api = HfApi()
    scripts = ([("short", i, t) for i, t in enumerate(SHORTS)]
               + [("medium", i, t) for i, t in enumerate(MEDIUMS)]
               + [("long", i, t) for i, t in enumerate(LONGS)])

    os.makedirs("/ref", exist_ok=True)
    ref_wavs = {}
    for spk, name in ((1, "en-Carter_man.wav"), (2, "en-Maya_woman.wav")):
        wav, sr = sf.read(f"/VibeVoice-classic/demo/voices/{name}")
        assert sr == SR
        ref_wavs[spk] = wav.astype(np.float32)
        sf.write(f"/ref/s{spk}.wav", ref_wavs[spk], SR)
    ref_paths = {spk: f"/ref/s{spk}.wav" for spk in (1, 2)}

    proc = VibeVoiceProcessor.from_pretrained(MODEL)
    from transformers import pipeline
    transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3",
                           device=device, torch_dtype=torch.float16)
    encoder = VoiceEncoder(device)

    ref_wav = np.concatenate([ref_wavs[1], np.zeros(SR // 4, dtype=np.float32), ref_wavs[2]])
    emb_ref = encoder.embed_utterance(preprocess_wav(ref_wav, SR))

    results = []
    os.makedirs("/out", exist_ok=True)
    for arm in ARMS:
        print(f"=== ARM {arm} ===", flush=True)
        model = load_model_with_head(load_soar=(arm == "soar"))
        model.set_ddpm_inference_steps(num_steps=10)
        for tier, idx, script in scripts:
            t0 = time.time()
            with torch.no_grad():
                inputs = proc(text=[script], voice_samples=[[ref_paths[1], ref_paths[2]]],
                              padding=True, return_tensors="pt", return_attention_mask=True)
                out = model.generate(
                    **inputs,
                    max_new_tokens=None,
                    cfg_scale=1.3,
                    tokenizer=proc.tokenizer,
                    generation_config={"do_sample": False},
                )
            gen_s = time.time() - t0
            fn = f"{arm}_{tier}_{idx}.wav"
            audio = out.speech_outputs[0]
            proc.save_audio(audio, output_path=f"/out/{fn}")
            wav = sf.read(f"/out/{fn}", dtype="float32")[0]
            wav = np.asarray(wav, dtype=np.float32)
            audio_s = len(wav) / SR
            rtf = gen_s / max(audio_s, 1e-6)
            hyp = transcriber(f"/out/{fn}", generate_kwargs={"language": "english"})["text"].strip()
            gt = gt_text(script)
            wer = float(jiwer.wer(gt, hyp))
            emb_gen = encoder.embed_utterance(preprocess_wav(f"/out/{fn}"))
            sim = float(np.dot(emb_gen, emb_ref) / (np.linalg.norm(emb_gen) * np.linalg.norm(emb_ref)))
            drift = None
            if tier == "long" and audio_s > 60:
                e1 = encoder.embed_utterance(preprocess_wav(wav[: 30 * SR], SR))
                e2 = encoder.embed_utterance(preprocess_wav(wav[-30 * SR:], SR))
                drift = float(np.dot(e1, e2) / (np.linalg.norm(e1) * np.linalg.norm(e2)))
            results.append({"arm": arm, "tier": tier, "idx": idx, "audio_s": audio_s,
                            "gen_s": gen_s, "rtf": rtf, "wer": wer, "sim_ref": sim,
                            "drift": drift, "hyp": hyp})
            d = "n/a" if drift is None else f"{drift:.3f}"
            print(f"{arm} {tier}{idx}: rtf {rtf:.3f} wer {wer:.3f} sim {sim:.3f} drift {d}", flush=True)
            trackio.log({"rtf": rtf, "wer": wer, "sim": sim}, step=len(results))
            api.upload_file(path_or_fileobj=f"/out/{fn}", path_in_repo=f"{arm}/{fn}",
                            repo_id=OUT_REPO, repo_type="model")
            torch.cuda.empty_cache()
        del model
        torch.cuda.empty_cache()

    with open("/out/results.json", "w") as f:
        json.dump(results, f, indent=2)
    summary = {}
    for arm in ARMS:
        rows = [r for r in results if r["arm"] == arm]
        summary[arm] = {"mean_wer": st.mean(r["wer"] for r in rows),
                        "mean_sim": st.mean(r["sim_ref"] for r in rows),
                        "mean_rtf": st.mean(r["rtf"] for r in rows),
                        "long_drift": st.mean(r["drift"] for r in rows if r["drift"] is not None)}
    with open("/out/summary.json", "w") as f:
        json.dump(summary, f, indent=2)
    print("SUMMARY " + json.dumps(summary), flush=True)
    api.upload_file(path_or_fileobj="/out/results.json", path_in_repo="results.json",
                    repo_id=OUT_REPO, repo_type="model")
    api.upload_file(path_or_fileobj="/out/summary.json", path_in_repo="summary.json",
                    repo_id=OUT_REPO, repo_type="model")
    print("EVAL DONE", flush=True)


import trackio
trackio.init(project="vibevoice-soar-head", space_id="ACloudCenter/vibevoice-soar-head-trackio")
main()
trackio.finish()