v2: restore build_sample (was omitted — NameError), keep verified Part A/B/C structure
fb314da verified Download diagnose_closedloop.py from ACloudCenter/fast-vibevoice-notes: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/datasets/ACloudCenter/fast-vibevoice-notes/resolve/main/diagnose_closedloop.py
- Command line
-
hf download hf://datasets/ACloudCenter/fast-vibevoice-notes/diagnose_closedloop.py
-
curl -L -o diagnose_closedloop.py https://huggingface.co/datasets/ACloudCenter/fast-vibevoice-notes/resolve/main/diagnose_closedloop.py
12.3 kB
| """diagnose_closedloop.py v2 — three-part diagnosis of the SOAR closed-loop failure. | |
| Part A: per-5s RMS(dB) + spectral flatness for all 18 eval wavs + Whisper first/last 10s. | |
| Part B: latent-scale check — std(x0hat)/std(x0_target), stock vs SOAR head. | |
| Part C: teacher-forced v-pred loss, stock vs SOAR head, 8 held-out shard-3 dialogues. | |
| Prints DIAGNOSIS DONE. | |
| """ | |
| import io, os, random, sys | |
| sys.path.insert(0, "/VibeVoice-classic") | |
| import numpy as np | |
| import pyarrow.parquet as pq | |
| import soundfile as sf | |
| import torch | |
| import torch.nn.functional as F | |
| from huggingface_hub import hf_hub_download | |
| from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration | |
| from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor | |
| from vibevoice.processor.vibevoice_tokenizer_processor import AudioNormalizer | |
| MODEL = "microsoft/VibeVoice-1.5B" | |
| SOAR_REPO = "ACloudCenter/vibevoice-soar-head-1.5B" | |
| EVAL_REPO = "ACloudCenter/vibevoice-eval-2x2" | |
| SR, COMPRESS, LATENT_DIM, SEM_DIM = 24000, 3200, 64, 128 | |
| device = "cuda" | |
| TIERS = ["short", "short", "short", "medium", "medium", "medium", "long", "long", "long"] | |
| def load_dialogues(shard_idx, min_turns=4, max_turns=10, min_sec=20.0, max_sec=60.0, limit=None): | |
| fn = hf_hub_download("eustlb/dailytalk", f"data/train-{shard_idx:05d}-of-00009.parquet", repo_type="dataset") | |
| tbl = pq.read_table(fn, columns=["conversation_id", "turn_id", "speaker_id", "text", "audio"]) | |
| cids = tbl.column("conversation_id").to_pylist() | |
| tids = tbl.column("turn_id").to_pylist() | |
| spks = tbl.column("speaker_id").to_pylist() | |
| texts = tbl.column("text").to_pylist() | |
| auds = tbl.column("audio").to_pylist() | |
| convs = {} | |
| for i, cid in enumerate(cids): | |
| convs.setdefault(cid, []).append(i) | |
| out = [] | |
| for cid, idxs in convs.items(): | |
| idxs.sort(key=lambda i: tids[i]) | |
| turns, ok = [], True | |
| for i in idxs: | |
| try: | |
| wav, sr = sf.read(io.BytesIO(auds[i]["bytes"])) | |
| except Exception: | |
| ok = False | |
| break | |
| if sr != SR or wav.ndim > 1: | |
| ok = False | |
| break | |
| turns.append((1 + int(spks[i]), texts[i], wav.astype(np.float32))) | |
| if not ok: | |
| continue | |
| total = sum(len(w) for _, _, w in turns) / SR | |
| nspk = len(set(s for s, _, _ in turns)) | |
| if min_turns <= len(turns) <= max_turns and min_sec <= total <= max_sec and nspk == 2: | |
| out.append(turns) | |
| if limit and len(out) >= limit: | |
| break | |
| return out | |
| def build_sample(model, proc, tok, dialogue, refs, turn_sec_cap, gap_sec=0.45): | |
| _TD = next(model.model.acoustic_tokenizer.parameters()) | |
| audio_norm = AudioNormalizer() | |
| parts = [] | |
| for spk, text, wav in dialogue: | |
| parts.append(audio_norm(wav[: int(turn_sec_cap * SR)]).astype(np.float32)) | |
| parts.append(np.zeros(int(gap_sec * SR), dtype=np.float32)) | |
| if len(parts): | |
| parts.pop() | |
| target = np.concatenate(parts).astype(np.float32) | |
| script = "".join(f"Speaker {spk}: {text.strip()}\n" for spk, text, _ in dialogue) | |
| with torch.no_grad(): | |
| out = proc(text=[script], voice_samples=[[refs[1], refs[2]]], padding=False, | |
| return_tensors="pt", return_attention_mask=True) | |
| ids = out["input_ids"][0].tolist() | |
| sim = out["speech_input_mask"][0].tolist() | |
| voice_np = out["speech_tensors"].cpu().numpy() | |
| voice_masks = out["speech_masks"].cpu().numpy().astype(bool) | |
| n_voice = voice_np.shape[0] | |
| with torch.no_grad(): | |
| _enc = model.model.acoustic_tokenizer.encode(torch.from_numpy(target).to(_TD)[None, None, :]) | |
| t_lat, _ = _enc.sample("fix") | |
| T_t = t_lat.shape[1] | |
| lat_segs = [] | |
| for i in range(n_voice): | |
| T_v = int(voice_masks[i].sum()) | |
| w = torch.from_numpy(np.ascontiguousarray(voice_np[i][: T_v * COMPRESS])).to(_TD)[None, None, :] | |
| with torch.no_grad(): | |
| e = model.model.acoustic_tokenizer.encode(w) | |
| v_lat, _ = e.sample("fix") | |
| lat_segs.append(v_lat[0]) | |
| lat_segs.append(t_lat[0]) | |
| n_seg = len(lat_segs) | |
| max_lat = max(s.shape[0] for s in lat_segs) | |
| speech_tensors = np.zeros((n_seg, max_lat, LATENT_DIM), dtype=np.float32) | |
| for i, s in enumerate(lat_segs): | |
| speech_tensors[i, : s.shape[0]] = s.float().cpu().numpy() | |
| speech_masks = np.zeros((n_seg, max_lat), dtype=bool) | |
| loss_input = np.zeros((n_seg, max_lat), dtype=bool) | |
| for i, s in enumerate(lat_segs): | |
| speech_masks[i, : s.shape[0]] = True | |
| loss_input[-1, : T_t] = True | |
| sems = np.zeros((n_seg, max_lat, SEM_DIM), dtype=np.float32) | |
| with torch.no_grad(): | |
| for i in range(n_voice): | |
| T_v = int(voice_masks[i].sum()) | |
| w = torch.from_numpy(np.ascontiguousarray(voice_np[i][: T_v * COMPRESS])).to(_TD)[None, None, :] | |
| m = model.model.semantic_tokenizer.encode(w).mean[0] | |
| n = min(m.shape[0], max_lat) | |
| sems[i, :n] = m[:n].float().cpu().numpy() | |
| m = model.model.semantic_tokenizer.encode(torch.from_numpy(target).to(_TD)[None, None, :]).mean[0] | |
| n = min(m.shape[0], max_lat) | |
| sems[-1, :n] = m[:n].float().cpu().numpy() | |
| diff_id, end_id = tok.speech_diffusion_id, tok.speech_end_id | |
| eos = getattr(tok, "eos_token_id", None) | |
| tail = [end_id] + ([eos] if eos is not None else []) | |
| ids_ext = ids + [diff_id] * T_t + tail | |
| in_mask = sim + [True] * T_t + [False] * len(tail) | |
| lo_mask = [False] * len(ids) + [True] * T_t + [False] * len(tail) | |
| return { | |
| "input_ids": torch.tensor(ids_ext, dtype=torch.long), | |
| "in_mask": torch.tensor(in_mask, dtype=torch.bool), | |
| "prompt_len": len(ids), | |
| "lo_mask": torch.tensor(lo_mask, dtype=torch.bool), | |
| "speech_tensors": torch.from_numpy(speech_tensors), | |
| "speech_masks": torch.from_numpy(speech_masks), | |
| "loss_input": torch.from_numpy(loss_input), | |
| "sems": torch.from_numpy(sems), | |
| } | |
| def part_a(): | |
| from transformers import pipeline | |
| transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", | |
| device=device, torch_dtype=torch.float16, chunk_length_s=30) | |
| print("=== PART A: onset / energy-growth analysis ===", flush=True) | |
| for arm in ("stock", "soar"): | |
| for idx, tier in enumerate(TIERS): | |
| fn = f"{arm}_{tier}_{idx % 3}.wav" | |
| p = hf_hub_download(EVAL_REPO, f"{arm}/{fn}", repo_type="model") | |
| wav, sr = sf.read(p, dtype="float32") | |
| win = 5 * sr | |
| nwin = max(1, len(wav) // win) | |
| rms, flat = [], [] | |
| for k in range(nwin): | |
| w = wav[k * win:(k + 1) * win] | |
| rms.append(20 * np.log10(np.sqrt(np.mean(w ** 2)) + 1e-9)) | |
| spec = np.abs(np.fft.rfft(w)) ** 2 | |
| flat.append(float(np.exp(np.mean(np.log(spec + 1e-12))) / (np.mean(spec) + 1e-12))) | |
| def fmt(xs, f="{:5.1f}"): | |
| return " ".join(f.format(x) for x in xs) | |
| print(f"{fn}: dur {len(wav) / sr:6.1f}s", flush=True) | |
| print(f" rmsdB {fmt(rms[:20])}", flush=True) | |
| print(f" flatn {fmt(flat[:20], '{:5.2f}')}", flush=True) | |
| if arm == "soar": | |
| first = transcriber({"array": wav[: 10 * sr], "sampling_rate": sr}, | |
| generate_kwargs={"language": "english"})["text"].strip() | |
| last = transcriber({"array": wav[-10 * sr:], "sampling_rate": sr}, | |
| generate_kwargs={"language": "english"})["text"].strip() | |
| print(f" first10s: {first[:120]!r}", flush=True) | |
| print(f" last10s : {last[:120]!r}", flush=True) | |
| def build_conditions(model, proc, tok, refs, dialogues): | |
| conds = [] | |
| for di, dialogue in enumerate(dialogues): | |
| b = build_sample(model, proc, tok, dialogue, refs, 3.0) | |
| smask = b["speech_masks"].to(device) | |
| n_t = int(b["loss_input"].sum()) | |
| with torch.no_grad(): | |
| x = model.get_input_embeddings()(b["input_ids"].to(device)[None]) | |
| af, conn = model.forward_speech_features( | |
| speech_tensors=b["speech_tensors"].to(device).type_as(x), speech_masks=smask, | |
| speech_type="vae", return_unmask=True) | |
| sem_conn = model.model.semantic_connector(b["sems"].to(device).type_as(x)) | |
| feat_all = conn[smask] + sem_conn[smask] | |
| assert feat_all.shape[0] == int(smask.sum()) | |
| def cond_from(xe): | |
| h = model.model.language_model( | |
| inputs_embeds=xe, attention_mask=torch.ones(1, xe.shape[1], device=device), | |
| use_cache=False).last_hidden_state | |
| return h[b["lo_mask"].unsqueeze(0).to(device)] | |
| xe_c = x.clone() | |
| xe_c[b["in_mask"].unsqueeze(0).to(device)] = feat_all | |
| cond_c = cond_from(xe_c) | |
| x0 = af[b["loss_input"].to(device) & smask] | |
| assert x0.shape[0] == n_t | |
| conds.append({"cond": cond_c, "x0": x0}) | |
| print(f"cond {di}: frames {n_t}", flush=True) | |
| return conds | |
| def eval_head(model, sched, conds, tag, seed=7): | |
| torch.manual_seed(7) | |
| random.seed(7) | |
| mul = 4 | |
| losses, ratios, ratios_low = [], [], [] | |
| with torch.no_grad(): | |
| for ci, c in enumerate(conds): | |
| x0 = c["x0"].to(device) | |
| cond = c["cond"].to(device) | |
| N = x0.shape[0] | |
| t = torch.multinomial(torch.ones(1000), N * mul, replacement=True).to(device) | |
| noise = torch.randn(N * mul, LATENT_DIM, device=device) | |
| x0r = x0.repeat_interleave(mul, 0) | |
| noisy = sched.add_noise(x0r, noise, t) | |
| tv = sched.get_velocity(x0r, noise, t) | |
| v = model.model.prediction_head(noisy, t.type_as(noisy), cond.repeat_interleave(mul, 0)) | |
| el = ((v.float() - tv.float()) ** 2).mean(-1) | |
| losses.append(float(el.mean())) | |
| a1 = sched.alpha_t[t].view(-1, 1).float() | |
| s1 = sched.sigma_t[t].view(-1, 1).float() | |
| x0h = a1 * noisy.float() - s1 * v.float() | |
| ratios.append(float(x0h.std() / x0r.float().std())) | |
| m = t < 200 | |
| if int(m.sum()) > 0: | |
| ratios_low.append(float(x0h[m].std() / x0r[m].float().std())) | |
| print(f" dlg {ci}: per-elem {float(el.mean()):.4f} x0hat/target {ratios[-1]:.3f}", flush=True) | |
| low = np.mean(ratios_low) if ratios_low else float("nan") | |
| print(f"HEAD {tag}: mean tfl {np.mean(losses):.4f} | x0hat/target {np.mean(ratios):.3f} | t<200 {low:.3f}", flush=True) | |
| return np.mean(losses) | |
| random.seed(0) | |
| torch.manual_seed(0) | |
| np.random.seed(0) | |
| print("=== PART A ===", flush=True) | |
| part_a() | |
| print("=== loading model (fp32) ===", flush=True) | |
| model = VibeVoiceForConditionalGeneration.from_pretrained( | |
| MODEL, torch_dtype=torch.float32, low_cpu_mem_usage=True).to(device).eval() | |
| proc = VibeVoiceProcessor.from_pretrained(MODEL) | |
| tok = proc.tokenizer | |
| sched = model.model.noise_scheduler | |
| assert hasattr(sched, "alpha_t") and hasattr(sched, "sigma_t") | |
| alpha_t = sched.alpha_t.to(device).float() | |
| sigma_t = sched.sigma_t.to(device).float() | |
| refs = {} | |
| 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 | |
| refs[spk] = wav.astype(np.float32) | |
| dgs = load_dialogues(3, limit=8) | |
| print(f"held-out dialogues: {len(dgs)}", flush=True) | |
| conds = build_conditions(model, proc, tok, refs, dgs) | |
| print("=== PARTS B+C: stock head ===", flush=True) | |
| head0 = {k: v.clone() for k, v in model.model.prediction_head.state_dict().items()} | |
| stock_loss = eval_head(model, sched, conds, "stock") | |
| print("=== PARTS B+C: SOAR head ===", flush=True) | |
| 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) | |
| soar_loss = eval_head(model, sched, conds, "soar") | |
| print(f"VERDICT teacher-forced: stock {stock_loss:.4f} vs soar {soar_loss:.4f}", flush=True) | |
| model.model.prediction_head.load_state_dict(head0) | |
| print("DIAGNOSIS DONE", flush=True) |