ACloudCenter commited on
Commit
fb314da
·
verified ·
1 Parent(s): 82157d4

v2: restore build_sample (was omitted — NameError), keep verified Part A/B/C structure

Browse files
Files changed (1) hide show
  1. diagnose_closedloop.py +81 -15
diagnose_closedloop.py CHANGED
@@ -1,9 +1,6 @@
1
- """diagnose_closedloop.py — three-part diagnosis of the SOAR closed-loop failure.
2
- User report: SOAR samples = "horror movie noise echoing forever and louder".
3
-
4
- Part A: per-5s RMS(dB) + spectral flatness for all 18 eval wavs (stock = control)
5
- + Whisper on first/last 10 s of each SOAR wav -> onset vs compounding.
6
- Part B: latent-scale check — std(x0hat)/std(x0_target), stock vs SOAR head, same draws.
7
  Part C: teacher-forced v-pred loss, stock vs SOAR head, 8 held-out shard-3 dialogues.
8
  Prints DIAGNOSIS DONE.
9
  """
@@ -66,6 +63,77 @@ def load_dialogues(shard_idx, min_turns=4, max_turns=10, min_sec=20.0, max_sec=6
66
  return out
67
 
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  def part_a():
70
  from transformers import pipeline
71
  transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3",
@@ -129,7 +197,7 @@ def build_conditions(model, proc, tok, refs, dialogues):
129
  return conds
130
 
131
 
132
- def eval_head(model, conds, tag, seed=7):
133
  torch.manual_seed(7)
134
  random.seed(7)
135
  mul = 4
@@ -148,17 +216,15 @@ def eval_head(model, conds, tag, seed=7):
148
  el = ((v.float() - tv.float()) ** 2).mean(-1)
149
  losses.append(float(el.mean()))
150
  a1 = sched.alpha_t[t].view(-1, 1).float()
151
- s1 = sched.sigma_t.view(-1, 1).float() if hasattr(sched, "sigma_t") else None
152
  s1 = sched.sigma_t[t].view(-1, 1).float()
153
  x0h = a1 * noisy.float() - s1 * v.float()
154
- ratio = float(x0h.std() / x0r.float().std())
155
- ratios.append(ratio)
156
  m = t < 200
157
  if int(m.sum()) > 0:
158
  ratios_low.append(float(x0h[m].std() / x0r[m].float().std()))
159
- print(f" dlg {ci}: per-elem {float(el.mean()):.4f} x0hat/target {ratio:.3f}", flush=True)
160
- print(f"HEAD {name}: mean tfl {np.mean(losses):.4f} | x0hat/target {np.mean(ratios):.3f} "
161
- f"| t<200 {np.mean(ratios_low) if ratios_low else float('nan'):.3f}", flush=True)
162
  return np.mean(losses)
163
 
164
 
@@ -190,13 +256,13 @@ conds = build_conditions(model, proc, tok, refs, dgs)
190
 
191
  print("=== PARTS B+C: stock head ===", flush=True)
192
  head0 = {k: v.clone() for k, v in model.model.prediction_head.state_dict().items()}
193
- stock_loss = eval_head(model, conds, "stock")
194
 
195
  print("=== PARTS B+C: SOAR head ===", flush=True)
196
  sd_path = hf_hub_download(SOAR_REPO, "soar_head_state.pt")
197
  sd = torch.load(sd_path, map_location="cpu", weights_only=True)
198
  model.model.prediction_head.load_state_dict(sd, strict=True)
199
- soar_loss = eval_head(model, conds, "soar")
200
  print(f"VERDICT teacher-forced: stock {stock_loss:.4f} vs soar {soar_loss:.4f}", flush=True)
201
  model.model.prediction_head.load_state_dict(head0)
202
  print("DIAGNOSIS DONE", flush=True)
 
1
+ """diagnose_closedloop.py v2 — three-part diagnosis of the SOAR closed-loop failure.
2
+ Part A: per-5s RMS(dB) + spectral flatness for all 18 eval wavs + Whisper first/last 10s.
3
+ Part B: latent-scale check — std(x0hat)/std(x0_target), stock vs SOAR head.
 
 
 
4
  Part C: teacher-forced v-pred loss, stock vs SOAR head, 8 held-out shard-3 dialogues.
5
  Prints DIAGNOSIS DONE.
6
  """
 
63
  return out
64
 
65
 
66
+ def build_sample(model, proc, tok, dialogue, refs, turn_sec_cap, gap_sec=0.45):
67
+ _TD = next(model.model.acoustic_tokenizer.parameters())
68
+ audio_norm = AudioNormalizer()
69
+ parts = []
70
+ for spk, text, wav in dialogue:
71
+ parts.append(audio_norm(wav[: int(turn_sec_cap * SR)]).astype(np.float32))
72
+ parts.append(np.zeros(int(gap_sec * SR), dtype=np.float32))
73
+ if len(parts):
74
+ parts.pop()
75
+ target = np.concatenate(parts).astype(np.float32)
76
+ script = "".join(f"Speaker {spk}: {text.strip()}\n" for spk, text, _ in dialogue)
77
+ with torch.no_grad():
78
+ out = proc(text=[script], voice_samples=[[refs[1], refs[2]]], padding=False,
79
+ return_tensors="pt", return_attention_mask=True)
80
+ ids = out["input_ids"][0].tolist()
81
+ sim = out["speech_input_mask"][0].tolist()
82
+ voice_np = out["speech_tensors"].cpu().numpy()
83
+ voice_masks = out["speech_masks"].cpu().numpy().astype(bool)
84
+ n_voice = voice_np.shape[0]
85
+ with torch.no_grad():
86
+ _enc = model.model.acoustic_tokenizer.encode(torch.from_numpy(target).to(_TD)[None, None, :])
87
+ t_lat, _ = _enc.sample("fix")
88
+ T_t = t_lat.shape[1]
89
+ lat_segs = []
90
+ for i in range(n_voice):
91
+ T_v = int(voice_masks[i].sum())
92
+ w = torch.from_numpy(np.ascontiguousarray(voice_np[i][: T_v * COMPRESS])).to(_TD)[None, None, :]
93
+ with torch.no_grad():
94
+ e = model.model.acoustic_tokenizer.encode(w)
95
+ v_lat, _ = e.sample("fix")
96
+ lat_segs.append(v_lat[0])
97
+ lat_segs.append(t_lat[0])
98
+ n_seg = len(lat_segs)
99
+ max_lat = max(s.shape[0] for s in lat_segs)
100
+ speech_tensors = np.zeros((n_seg, max_lat, LATENT_DIM), dtype=np.float32)
101
+ for i, s in enumerate(lat_segs):
102
+ speech_tensors[i, : s.shape[0]] = s.float().cpu().numpy()
103
+ speech_masks = np.zeros((n_seg, max_lat), dtype=bool)
104
+ loss_input = np.zeros((n_seg, max_lat), dtype=bool)
105
+ for i, s in enumerate(lat_segs):
106
+ speech_masks[i, : s.shape[0]] = True
107
+ loss_input[-1, : T_t] = True
108
+ sems = np.zeros((n_seg, max_lat, SEM_DIM), dtype=np.float32)
109
+ with torch.no_grad():
110
+ for i in range(n_voice):
111
+ T_v = int(voice_masks[i].sum())
112
+ w = torch.from_numpy(np.ascontiguousarray(voice_np[i][: T_v * COMPRESS])).to(_TD)[None, None, :]
113
+ m = model.model.semantic_tokenizer.encode(w).mean[0]
114
+ n = min(m.shape[0], max_lat)
115
+ sems[i, :n] = m[:n].float().cpu().numpy()
116
+ m = model.model.semantic_tokenizer.encode(torch.from_numpy(target).to(_TD)[None, None, :]).mean[0]
117
+ n = min(m.shape[0], max_lat)
118
+ sems[-1, :n] = m[:n].float().cpu().numpy()
119
+ diff_id, end_id = tok.speech_diffusion_id, tok.speech_end_id
120
+ eos = getattr(tok, "eos_token_id", None)
121
+ tail = [end_id] + ([eos] if eos is not None else [])
122
+ ids_ext = ids + [diff_id] * T_t + tail
123
+ in_mask = sim + [True] * T_t + [False] * len(tail)
124
+ lo_mask = [False] * len(ids) + [True] * T_t + [False] * len(tail)
125
+ return {
126
+ "input_ids": torch.tensor(ids_ext, dtype=torch.long),
127
+ "in_mask": torch.tensor(in_mask, dtype=torch.bool),
128
+ "prompt_len": len(ids),
129
+ "lo_mask": torch.tensor(lo_mask, dtype=torch.bool),
130
+ "speech_tensors": torch.from_numpy(speech_tensors),
131
+ "speech_masks": torch.from_numpy(speech_masks),
132
+ "loss_input": torch.from_numpy(loss_input),
133
+ "sems": torch.from_numpy(sems),
134
+ }
135
+
136
+
137
  def part_a():
138
  from transformers import pipeline
139
  transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3",
 
197
  return conds
198
 
199
 
200
+ def eval_head(model, sched, conds, tag, seed=7):
201
  torch.manual_seed(7)
202
  random.seed(7)
203
  mul = 4
 
216
  el = ((v.float() - tv.float()) ** 2).mean(-1)
217
  losses.append(float(el.mean()))
218
  a1 = sched.alpha_t[t].view(-1, 1).float()
 
219
  s1 = sched.sigma_t[t].view(-1, 1).float()
220
  x0h = a1 * noisy.float() - s1 * v.float()
221
+ ratios.append(float(x0h.std() / x0r.float().std()))
 
222
  m = t < 200
223
  if int(m.sum()) > 0:
224
  ratios_low.append(float(x0h[m].std() / x0r[m].float().std()))
225
+ print(f" dlg {ci}: per-elem {float(el.mean()):.4f} x0hat/target {ratios[-1]:.3f}", flush=True)
226
+ low = np.mean(ratios_low) if ratios_low else float("nan")
227
+ print(f"HEAD {tag}: mean tfl {np.mean(losses):.4f} | x0hat/target {np.mean(ratios):.3f} | t<200 {low:.3f}", flush=True)
228
  return np.mean(losses)
229
 
230
 
 
256
 
257
  print("=== PARTS B+C: stock head ===", flush=True)
258
  head0 = {k: v.clone() for k, v in model.model.prediction_head.state_dict().items()}
259
+ stock_loss = eval_head(model, sched, conds, "stock")
260
 
261
  print("=== PARTS B+C: SOAR head ===", flush=True)
262
  sd_path = hf_hub_download(SOAR_REPO, "soar_head_state.pt")
263
  sd = torch.load(sd_path, map_location="cpu", weights_only=True)
264
  model.model.prediction_head.load_state_dict(sd, strict=True)
265
+ soar_loss = eval_head(model, sched, conds, "soar")
266
  print(f"VERDICT teacher-forced: stock {stock_loss:.4f} vs soar {soar_loss:.4f}", flush=True)
267
  model.model.prediction_head.load_state_dict(head0)
268
  print("DIAGNOSIS DONE", flush=True)