fast-vibevoice-notes / eval_joint2.py
ACloudCenter's picture
v2.1: download_adapter reads downloaded file and writes bytes explicitly (kills symlink/makedirs trap); isfile+size assert kept
adb17c4 verified
Raw History Blame Contribute Delete
12.4 kB
"""eval_joint2.py v2.1 — closed-loop eval of the POLISHED joint model (epoch2/checkpoint-900/lora).
Standalone: no runtime patching; adapter path baked to ground-truth layout (verified via repo ls).
Baked fixes: download via read-bytes + explicit write (immune to HF-cache symlink chains),
isfile+size asserts after write, Whisper return_timestamps, safe drift aggregation,
demo-exact generate. Env: ARMS (default "joint2"). Pushes to ACloudCenter/vibevoice-eval-jointv1.
Prints EVAL DONE.
"""
VERSION = "eval_joint2.py v2.1 (bytes-explicit download)"
import importlib.util, json, os, 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
_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 = "epoch2/checkpoint-900/lora"
OUT_REPO = "ACloudCenter/vibevoice-eval-jointv1"
SR = 24000
device = "cuda"
ARMS = [a.strip() for a in os.environ.get("ARMS", "joint2").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 under {ADAPTER_SUB}: {files}"
for f in files:
local = hf_hub_download(ADAPTER_REPO, f)
# read the REAL bytes from the resolved file (follows any symlink chain),
# then write them explicitly — immune to dangling links and makedirs traps
with open(local, "rb") as fh:
data = fh.read()
assert len(data) > 0, f"downloaded empty: {f}"
name = f[len(ADAPTER_SUB) + 1:]
op = os.path.join(dest, name)
os.makedirs(os.path.dirname(op), exist_ok=True)
with open(op, "wb") as fh:
fh.write(data)
assert os.path.isfile(op) and os.path.getsize(op) == len(data), f"write failed: {name}"
listing = sorted(os.listdir(dest))
print(f"ADAPTER OK: {listing}", flush=True)
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}"
assert os.path.getsize(os.path.join(dest, must)) > 0, f"empty: {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 == "joint2":
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"JOINT2 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()
print(VERSION, flush=True)
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.inference_mode():
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_joint2.json", "w") as f:
json.dump(blob, f, indent=1)
api.upload_file(path_or_fileobj="/out/results_joint2.json", path_in_repo="results_joint2.json", repo_id=OUT_REPO)
print("SUMMARY:", json.dumps(summary), flush=True)
print("EVAL DONE", flush=True)
if __name__ == "__main__":
main()