File size: 12,014 Bytes
655c248
 
c545bd5
98a73e8
 
 
655c248
 
98a73e8
c545bd5
655c248
 
 
 
 
 
 
 
 
 
 
c545bd5
a478e5b
c545bd5
 
a478e5b
c545bd5
 
 
655c248
 
 
 
 
 
 
 
 
 
 
 
 
 
a478e5b
655c248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a73e8
c545bd5
 
98a73e8
 
 
655c248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""eval_joint.py — stock vs JOINT (LLM-LoRA + full head, fullv3) on the identical 9-dialogue set.
Baked fixes: demo-exact generate, sf tuple unpacks, save_audio write path, safe drift
aggregation, Whisper return_timestamps=True, adapter download from model repo via
list_repo_files with shutil.copyfile (HF cache paths are RELATIVE symlinks — os.replace
leaves dangling links), load_lora_assets (imported standalone from vibevoice-community
main with sys.modules registration) with component asserts.
Env: ARMS (default "stock,joint"). Pushes to ACloudCenter/vibevoice-eval-jointv1. Prints EVAL DONE.
"""
import importlib.util, json, os, shutil, sys, time
sys.path.insert(0, "/VibeVoice-classic")

import numpy as np
import soundfile as sf
import torch
import jiwer
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

_spec = importlib.util.spec_from_file_location(
    "vibevoice.modular.lora_loading", "/vv-main/vibevoice/modular/lora_loading.py")
assert _spec is not None and _spec.loader is not None, "lora_loading.py not found at /vv-main"
lora_loading = importlib.util.module_from_spec(_spec)
sys.modules[_spec.name] = lora_loading  # dataclass machinery needs the module registered
_spec.loader.exec_module(lora_loading)
load_lora_assets = lora_loading.load_lora_assets

MODEL = "microsoft/VibeVoice-1.5B"
ADAPTER_REPO = "ACloudCenter/vibevoice-lora-joint"
ADAPTER_SUB = "fullv3/lora"
OUT_REPO = "ACloudCenter/vibevoice-eval-jointv1"
SR = 24000
device = "cuda"
ARMS = [a.strip() for a in os.environ.get("ARMS", "stock,joint").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: 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 download_adapter(dest="/adapter"):
    api = HfApi()
    files = [f for f in api.list_repo_files(ADAPTER_REPO) if f.startswith(ADAPTER_SUB + "/")]
    assert len(files) >= 4, f"adapter files not found: {files}"
    for f in files:
        local = hf_hub_download(ADAPTER_REPO, f)
        name = f[len(ADAPTER_SUB) + 1:]
        op = os.path.join(dest, name)
        os.makedirs(os.path.dirname(op), exist_ok=True)
        shutil.copyfile(local, op)  # NOT os.replace: cache paths are relative symlinks
    listing = sorted(os.listdir(dest))
    print(f"ADAPTER OK: {listing}", flush=True)
    # follow-the-link verification: os.listdir can show dangling symlinks
    for must in ("adapter_config.json", "adapter_model.safetensors", "diffusion_head_full.bin"):
        assert os.path.isfile(os.path.join(dest, must)), f"dangling or missing: {must}"
    return dest


def load_model(arm):
    model = VibeVoiceForConditionalGenerationInference.from_pretrained(
        MODEL, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True,
        attn_implementation="sdpa").to(device).eval()
    if arm == "joint":
        report = load_lora_assets(model, "/adapter")
        loaded = [n for n, ok in (("language_model", report.language_model),
                                  ("diffusion_head_lora", report.diffusion_head_lora),
                                  ("diffusion_head_full", report.diffusion_head_full),
                                  ("acoustic_connector", report.acoustic_connector),
                                  ("semantic_connector", report.semantic_connector)) if ok]
        print(f"JOINT LOADED: {loaded}", flush=True)
        assert "language_model" in loaded and "diffusion_head_full" in loaded, loaded
    return model


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


def main():
    api = HfApi()
    download_adapter()
    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(arm)
        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"
            proc.save_audio(out.speech_outputs[0], 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"},
                              return_timestamps=True)["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))
                n = np.linalg.norm(e1) * np.linalg.norm(e2)
                drift = float(np.dot(e1, e2) / n) if n > 0 else None
            results.append({"arm": arm, "tier": tier, "idx": idx, "audio_s": round(audio_s, 1),
                            "rtf": round(rtf, 3), "wer": round(wer, 3), "sim": round(sim, 3),
                            "drift": round(drift, 3) if drift is not None else None})
            api.upload_file(path_or_fileobj=f"/out/{fn}", path_in_repo=fn, repo_id=OUT_REPO)
            print(f"{arm} {tier}{idx}: rtf {rtf:.3f} wer {wer:.3f} sim {sim:.3f} "
                  f"dur {audio_s:.1f}s drift {drift}", flush=True)
        del model
        torch.cuda.empty_cache()

    import statistics as stat
    def agg(arm, key):
        vals = [r[key] for r in results if r["arm"] == arm and r[key] is not None]
        return round(stat.mean(vals), 3) if vals else None
    summary = {arm: {"wer": agg(arm, "wer"), "sim": agg(arm, "sim"),
                     "rtf": agg(arm, "rtf"), "drift": agg(arm, "drift")} for arm in ARMS}
    blob = {"summary": summary, "results": results}
    with open("/out/results.json", "w") as f:
        json.dump(blob, f, indent=1)
    api.upload_file(path_or_fileobj="/out/results.json", path_in_repo="results.json", repo_id=OUT_REPO)
    print("SUMMARY:", json.dumps(summary), flush=True)
    print("EVAL DONE", flush=True)


if __name__ == "__main__":
    main()