ACloudCenter commited on
Commit
d9000fb
·
verified ·
1 Parent(s): 8d54a92

diag3: 200-step overfits for C, E, and zero-condition; every-20 trajectory

Browse files
Files changed (1) hide show
  1. diag3.py +239 -0
diag3.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """diag3: extended overfit bisection following diag2 v3 results.
2
+
3
+ diag2 (10-step overfits) put C (teacher-forced leak) ahead of E everywhere except
4
+ the highest t bucket, but neither clearly crossed the ~0.8 chance floor. This run
5
+ extends the overfits to 200 steps (trajectory every 20) and adds a ZERO-condition
6
+ overfit: if even a null condition cannot fit below the floor on a single batch,
7
+ the problem is in the data/scheduler/loss path, not the condition format.
8
+
9
+ C: xe[in_mask] = connect+sem at voice AND target slots (teacher-forced leak)
10
+ E: xe[in_mask_voice] = connect+sem at voice slots ONLY; target diff slots keep the
11
+ raw embedding of speech_diffusion_id (AR-generation-faithful format)
12
+ Z: condition = zeros (null-condition capacity test)
13
+
14
+ All fp32 on cuda; tokenizer inputs cast via the tokenizer's own param.
15
+ """
16
+ import io, math, random, sys
17
+ sys.path.insert(0, "/VibeVoice-classic")
18
+
19
+ import numpy as np
20
+ import pyarrow.parquet as pq
21
+ import soundfile as sf
22
+ import torch
23
+ import torch.nn.functional as F
24
+ from huggingface_hub import hf_hub_download
25
+
26
+ from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration
27
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
28
+ from vibevoice.processor.vibevoice_tokenizer_processor import AudioNormalizer
29
+
30
+ MODEL = "microsoft/VibeVoice-1.5B"
31
+ SR, COMPRESS, LATENT_DIM, SEM_DIM = 24000, 3200, 64, 128
32
+ device = "cuda"
33
+
34
+ def load_dialogues(shard_idx, min_turns=4, max_turns=10, min_sec=20.0, max_sec=60.0, limit=None):
35
+ fn = hf_hub_download("eustlb/dailytalk", f"data/train-{shard_idx:05d}-of-00009.parquet", repo_type="dataset")
36
+ tbl = pq.read_table(fn, columns=["conversation_id", "turn_id", "speaker_id", "text", "audio"])
37
+ cids = tbl.column("conversation_id").to_pylist()
38
+ tids = tbl.column("turn_id").to_pylist()
39
+ spks = tbl.column("speaker_id").to_pylist()
40
+ texts = tbl.column("text").to_pylist()
41
+ auds = tbl.column("audio").to_pylist()
42
+ convs = {}
43
+ for i, cid in enumerate(cids):
44
+ convs.setdefault(cid, []).append(i)
45
+ out = []
46
+ for cid, idxs in convs.items():
47
+ idxs.sort(key=lambda i: tids[i])
48
+ turns, ok = [], True
49
+ for i in idxs:
50
+ try:
51
+ wav, sr = sf.read(io.BytesIO(auds[i]["bytes"]))
52
+ except Exception:
53
+ ok = False
54
+ break
55
+ if sr != SR or wav.ndim > 1:
56
+ ok = False
57
+ break
58
+ turns.append((1 + int(spks[i]), texts[i], wav.astype(np.float32)))
59
+ if not ok:
60
+ continue
61
+ total = sum(len(w) for _, _, w in turns) / SR
62
+ nspk = len(set(s for s, _, _ in turns))
63
+ if min_turns <= len(turns) <= max_turns and min_sec <= total <= max_sec and nspk == 2:
64
+ out.append(turns)
65
+ if limit and len(out) >= limit:
66
+ break
67
+ return out
68
+
69
+ def build_sample(model, proc, tok, dialogue, refs, turn_sec_cap, gap_sec=0.45):
70
+ _TD = next(model.model.acoustic_tokenizer.parameters())
71
+ audio_norm = AudioNormalizer()
72
+ parts = []
73
+ for spk, text, wav in dialogue:
74
+ parts.append(audio_norm(wav[: int(turn_sec_cap * SR)]).astype(np.float32))
75
+ parts.append(np.zeros(int(gap_sec * SR), dtype=np.float32))
76
+ if len(parts):
77
+ parts.pop()
78
+ target = np.concatenate(parts).astype(np.float32)
79
+ script = "".join(f"Speaker {spk}: {text.strip()}\n" for spk, text, _ in dialogue)
80
+ with torch.no_grad():
81
+ out = proc(text=[script], voice_samples=[[refs[1], refs[2]]], padding=False,
82
+ return_tensors="pt", return_attention_mask=True)
83
+ ids = out["input_ids"][0].tolist()
84
+ sim = out["speech_input_mask"][0].tolist()
85
+ voice_np = out["speech_tensors"].cpu().numpy()
86
+ voice_masks = out["speech_masks"].cpu().numpy().astype(bool)
87
+ n_voice = voice_np.shape[0]
88
+ with torch.no_grad():
89
+ _enc = model.model.acoustic_tokenizer.encode(torch.from_numpy(target).to(_TD)[None, None, :])
90
+ t_lat, _ = _enc.sample("fix")
91
+ T_t = t_lat.shape[1]
92
+ lat_segs = []
93
+ for i in range(n_voice):
94
+ T_v = int(voice_masks[i].sum())
95
+ w = torch.from_numpy(np.ascontiguousarray(voice_np[i][: T_v * COMPRESS])).to(_TD)[None, None, :]
96
+ with torch.no_grad():
97
+ e = model.model.acoustic_tokenizer.encode(w)
98
+ v_lat, _ = e.sample("fix")
99
+ lat_segs.append(v_lat[0])
100
+ lat_segs.append(t_lat[0])
101
+ n_seg = len(lat_segs)
102
+ max_lat = max(s.shape[0] for s in lat_segs)
103
+ speech_tensors = np.zeros((n_seg, max_lat, LATENT_DIM), dtype=np.float32)
104
+ for i, s in enumerate(lat_segs):
105
+ speech_tensors[i, : s.shape[0]] = s.float().cpu().numpy()
106
+ speech_masks = np.zeros((n_seg, max_lat), dtype=bool)
107
+ loss_input = np.zeros((n_seg, max_lat), dtype=bool)
108
+ for i, s in enumerate(lat_segs):
109
+ speech_masks[i, : s.shape[0]] = True
110
+ loss_input[-1, : T_t] = True
111
+ sems = np.zeros((n_seg, max_lat, SEM_DIM), dtype=np.float32)
112
+ with torch.no_grad():
113
+ for i in range(n_voice):
114
+ T_v = int(voice_masks[i].sum())
115
+ w = torch.from_numpy(np.ascontiguousarray(voice_np[i][: T_v * COMPRESS])).to(_TD)[None, None, :]
116
+ m = model.model.semantic_tokenizer.encode(w).mean[0]
117
+ n = min(m.shape[0], max_lat)
118
+ sems[i, :n] = m[:n].float().cpu().numpy()
119
+ m = model.model.semantic_tokenizer.encode(torch.from_numpy(target).to(_TD)[None, None, :]).mean[0]
120
+ n = min(m.shape[0], max_lat)
121
+ sems[-1, :n] = m[:n].float().cpu().numpy()
122
+ diff_id, end_id = tok.speech_diffusion_id, tok.speech_end_id
123
+ eos = getattr(tok, "eos_token_id", None)
124
+ tail = [end_id] + ([eos] if eos is not None else [])
125
+ ids_ext = ids + [diff_id] * T_t + tail
126
+ in_mask = sim + [True] * T_t + [False] * len(tail)
127
+ lo_mask = [False] * len(ids) + [True] * T_t + [False] * len(tail)
128
+ return {
129
+ "input_ids": torch.tensor(ids_ext, dtype=torch.long),
130
+ "in_mask": torch.tensor(in_mask, dtype=torch.bool),
131
+ "prompt_len": len(ids),
132
+ "lo_mask": torch.tensor(lo_mask, dtype=torch.bool),
133
+ "speech_tensors": torch.from_numpy(speech_tensors),
134
+ "speech_masks": torch.from_numpy(speech_masks),
135
+ "loss_input": torch.from_numpy(loss_input),
136
+ "sems": torch.from_numpy(sems),
137
+ }
138
+
139
+ random.seed(0)
140
+ torch.manual_seed(0)
141
+ model = VibeVoiceForConditionalGeneration.from_pretrained(
142
+ MODEL, torch_dtype=torch.float32, low_cpu_mem_usage=True).to(device).eval()
143
+ proc = VibeVoiceProcessor.from_pretrained(MODEL)
144
+ tok = proc.tokenizer
145
+ sched = model.model.noise_scheduler
146
+ refs = {}
147
+ for spk, name in ((1, "en-Carter_man.wav"), (2, "en-Maya_woman.wav")):
148
+ wav, sr = sf.read(f"/VibeVoice-classic/demo/voices/{name}")
149
+ assert sr == SR
150
+ refs[spk] = wav.astype(np.float32)
151
+ dialogues = load_dialogues(0, max_turns=10, limit=10)
152
+ print(f"dialogues: {len(dialogues)}", flush=True)
153
+ b = build_sample(model, proc, tok, dialogues[3], refs, 3.0)
154
+ L = b["input_ids"].numel()
155
+ smask = b["speech_masks"].to(device)
156
+ n_t = int(b["loss_input"].sum())
157
+
158
+ with torch.no_grad():
159
+ x = model.get_input_embeddings()(b["input_ids"].to(device)[None])
160
+ af, conn = model.forward_speech_features(
161
+ speech_tensors=b["speech_tensors"].to(device).type_as(x), speech_masks=smask,
162
+ speech_type="vae", return_unmask=True)
163
+ sem_conn = model.model.semantic_connector(b["sems"].to(device).type_as(x))
164
+ feat_all = conn[smask] + sem_conn[smask]
165
+ assert feat_all.shape[0] == int(smask.sum()), \
166
+ f"feat rows {feat_all.shape[0]} vs valid latent frames {int(smask.sum())}"
167
+
168
+ inm = b["in_mask"].to(device).clone()
169
+ inm[b["prompt_len"]: b["prompt_len"] + n_t] = False # E: target slots keep raw diff embedding
170
+ inm_e = inm.unsqueeze(0)
171
+ n_voice = int(inm.sum())
172
+ print(f"prompt_len={b['prompt_len']} voice slots={n_voice} target frames={n_t} total speech slots={int(b['in_mask'].sum())}", flush=True)
173
+ assert int(b["in_mask"].sum()) == n_voice + n_t, "target-slot zeroing misaligned"
174
+ assert n_voice == int(smask.sum()) - n_t, \
175
+ f"voice token slots {n_voice} vs latent frames {int(smask.sum()) - n_t}"
176
+
177
+ def cond_from(xe):
178
+ h = model.model.language_model(
179
+ inputs_embeds=xe, attention_mask=torch.ones(1, L, device=device), use_cache=False).last_hidden_state
180
+ return h[b["lo_mask"].unsqueeze(0).to(device)]
181
+
182
+ xe_c = x.clone()
183
+ xe_c[b["in_mask"].unsqueeze(0).to(device)] = feat_all
184
+ xe_e = x.clone()
185
+ feat_voice = feat_all[: n_voice]
186
+ xe_e[inm_e] = feat_voice
187
+
188
+ cond_c = cond_from(xe_c)
189
+ cond_e = cond_from(xe_e)
190
+ x0 = af[b["loss_input"].to(device) & smask]
191
+ assert x0.shape[0] == n_t, f"x0 rows {x0.shape[0]} vs target frames {n_t}"
192
+ N = x0.shape[0]
193
+ mul = 4
194
+ torch.manual_seed(7)
195
+ noise = torch.randn(N * mul, LATENT_DIM, device=device)
196
+ t = torch.multinomial(torch.ones(1000), N * mul, replacement=True).to(device)
197
+ x0r = x0.repeat_interleave(mul, 0)
198
+ noisy = sched.add_noise(x0r, noise, t)
199
+ tv = sched.get_velocity(x0r, noise, t)
200
+ print(f"N={N}", flush=True)
201
+
202
+ def bucket(name, cond):
203
+ v0 = model.model.prediction_head(noisy, t.type_as(noisy), cond.repeat_interleave(mul, 0))
204
+ el = (v0.float() - tv.float()) ** 2
205
+ print(name, flush=True)
206
+ for lo, hi in ((0, 200), (200, 500), (500, 800), (800, 1000)):
207
+ m = (t >= lo) & (t < hi)
208
+ print(f" t in [{lo:4d},{hi:4d}): per-elem {float(el[m].mean()):.4f} (n={int(m.sum())})", flush=True)
209
+ return float(el.mean())
210
+
211
+ bucket("C (teacher-forced leak at ALL speech slots):", cond_c)
212
+ bucket("E (inference-faithful, plain diff embeddings):", cond_e)
213
+
214
+ head0 = {k: v.clone() for k, v in model.model.prediction_head.state_dict().items()}
215
+
216
+ def overfit(name, cond, steps=200, lr=2e-4):
217
+ for p in model.parameters():
218
+ p.requires_grad_(False)
219
+ for p in model.model.prediction_head.parameters():
220
+ p.requires_grad_(True)
221
+ hp = [p for p in model.model.prediction_head.parameters()]
222
+ opt = torch.optim.AdamW(hp, lr=lr)
223
+ hist = []
224
+ for stp in range(steps):
225
+ v = model.model.prediction_head(noisy, t.type_as(noisy), cond)
226
+ loss = F.mse_loss(v.float(), tv.float(), reduction="sum") / LATENT_DIM / mul / N
227
+ opt.zero_grad(set_to_none=True)
228
+ loss.backward()
229
+ torch.nn.utils.clip_grad_norm_(hp, 5.0)
230
+ opt.step()
231
+ hist.append(float(loss))
232
+ traj = hist[::20] + ([hist[-1]] if (steps - 1) % 20 != 0 else [])
233
+ print(f"{name:44s}: " + " ".join(f"{h:.3f}" for h in traj) + f" (final {hist[-1]:.3f})", flush=True)
234
+ model.model.prediction_head.load_state_dict(head0)
235
+
236
+ overfit("C overfit (leak conditions)", cond_c.repeat_interleave(mul, 0))
237
+ overfit("E overfit (plain diff embeddings)", cond_e.repeat_interleave(mul, 0))
238
+ overfit("Z overfit (zero condition)", torch.zeros(N * mul, cond_c.shape[-1], device=device))
239
+ print("DIAG3 DONE", flush=True)