rikhoffbauer2 commited on
Commit
d34b37f
·
verified ·
1 Parent(s): 26de08e

Add optimizer.py

Browse files
Files changed (1) hide show
  1. optimizer.py +385 -0
optimizer.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Autonomous parameter optimizer for the drum extraction pipeline.
3
+
4
+ Runs a loop:
5
+ 1. Generate synthetic songs with known ground truth
6
+ 2. Run the extraction pipeline with current params
7
+ 3. Evaluate extraction quality against ground truth
8
+ 4. Use results to tune parameters for next iteration
9
+
10
+ Uses Bayesian-ish optimization: maintain a history of (params → score),
11
+ then perturb the best-so-far params toward improving weak metrics.
12
+ """
13
+
14
+ import json
15
+ import time
16
+ import traceback
17
+ import numpy as np
18
+ from copy import deepcopy
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ from synth_generator import generate_test_song, SyntheticSong
23
+ from evaluation import evaluate_extraction, report_to_dict, EvalReport
24
+ from quality_metrics import drum_sample_score
25
+
26
+
27
+ @dataclass
28
+ class PipelineParams:
29
+ """All tunable parameters of the extraction pipeline."""
30
+ # Onset detection
31
+ pre_pad: float = 0.005
32
+ min_hit_dur: float = 0.03
33
+ max_hit_dur: float = 0.8
34
+ min_gap: float = 0.02
35
+ energy_threshold_db: float = -40.0
36
+
37
+ # Overlap separation
38
+ separate_overlaps: bool = True
39
+ overlap_energy_threshold: float = 0.15 # band energy ratio to count as significant
40
+
41
+ # Clustering
42
+ use_clap: bool = False
43
+
44
+ # Selection weights (must sum to 1.0)
45
+ w_completeness: float = 0.30
46
+ w_cleanness: float = 0.40
47
+ w_onset: float = 0.20
48
+ w_representativeness: float = 0.10
49
+
50
+ # Synthesis
51
+ synthesize: bool = True
52
+ synth_best_weight: float = 2.0 # weight multiplier for best sample in cluster
53
+
54
+ def to_dict(self) -> dict:
55
+ return self.__dict__.copy()
56
+
57
+ @classmethod
58
+ def from_dict(cls, d: dict) -> 'PipelineParams':
59
+ valid_keys = cls.__dataclass_fields__.keys()
60
+ return cls(**{k: v for k, v in d.items() if k in valid_keys})
61
+
62
+
63
+ @dataclass
64
+ class IterationResult:
65
+ """Result of one optimization iteration."""
66
+ iteration: int
67
+ params: dict
68
+ eval_report: dict
69
+ overall_score: float
70
+ duration_seconds: float
71
+ test_config: dict # which synthetic song was used
72
+ timestamp: str
73
+
74
+
75
+ @dataclass
76
+ class OptimizerState:
77
+ """Persistent state of the optimizer."""
78
+ history: list = field(default_factory=list) # [IterationResult]
79
+ best_params: dict = field(default_factory=dict)
80
+ best_score: float = 0.0
81
+ iteration: int = 0
82
+
83
+
84
+ # ─────────────────────────────────────────────────────────────────────────────
85
+ # Parameter perturbation strategies
86
+ # ─────────────────────────────────────────────────────────────────────────────
87
+
88
+ def diagnose_and_perturb(params: PipelineParams, report: EvalReport,
89
+ rng: np.random.RandomState) -> PipelineParams:
90
+ """Analyze evaluation report and intelligently perturb parameters.
91
+
92
+ Instead of random search, we diagnose specific failure modes from the
93
+ evaluation metrics and adjust the relevant parameters.
94
+ """
95
+ new_params = deepcopy(params)
96
+ changes = []
97
+
98
+ # ── Diagnosis 1: Poor onset precision (>20ms mean error) ──
99
+ if report.mean_onset_error_ms > 20:
100
+ # Reduce pre_pad to tighten onset capture
101
+ new_params.pre_pad = max(0.001, params.pre_pad * rng.uniform(0.5, 0.9))
102
+ # Reduce min_gap to catch faster sequences
103
+ new_params.min_gap = max(0.01, params.min_gap * rng.uniform(0.6, 0.9))
104
+ changes.append(f"onset_error={report.mean_onset_error_ms:.1f}ms → tightened pre_pad/min_gap")
105
+
106
+ # ── Diagnosis 2: Missing hits (low hit count accuracy) ──
107
+ if report.hit_count_accuracy < 0.7:
108
+ # Lower energy threshold to catch quieter hits
109
+ new_params.energy_threshold_db = max(-60, params.energy_threshold_db - rng.uniform(2, 8))
110
+ # Reduce min_hit_dur to catch shorter sounds
111
+ new_params.min_hit_dur = max(0.01, params.min_hit_dur * rng.uniform(0.5, 0.8))
112
+ changes.append(f"hit_acc={report.hit_count_accuracy:.2f} → lowered threshold/min_dur")
113
+
114
+ # ── Diagnosis 3: Too many false hits (extracted >> GT) ──
115
+ total_ext = sum(m.n_hits_extracted for m in report.matches) if report.matches else 0
116
+ total_gt = sum(m.n_hits_gt for m in report.matches) if report.matches else 1
117
+ if total_ext > total_gt * 1.5:
118
+ # Raise energy threshold
119
+ new_params.energy_threshold_db = min(-20, params.energy_threshold_db + rng.uniform(2, 5))
120
+ new_params.min_hit_dur = min(0.08, params.min_hit_dur * rng.uniform(1.1, 1.5))
121
+ changes.append(f"over-extraction ({total_ext} vs {total_gt} GT) → raised threshold")
122
+
123
+ # ── Diagnosis 4: Low SI-SDR (poor sample quality) ──
124
+ if report.mean_si_sdr < 5:
125
+ # The extracted samples don't match GT well
126
+ # Try adjusting overlap separation threshold
127
+ new_params.overlap_energy_threshold = params.overlap_energy_threshold + rng.uniform(-0.05, 0.05)
128
+ new_params.overlap_energy_threshold = np.clip(new_params.overlap_energy_threshold, 0.05, 0.4)
129
+ changes.append(f"SI-SDR={report.mean_si_sdr:.1f}dB → adjusted overlap threshold")
130
+
131
+ # ── Diagnosis 5: Low sample scores (poor completeness/cleanness) ──
132
+ if report.mean_sample_score < 50:
133
+ # Adjust selection weights
134
+ # More weight on cleanness if we're getting bleed-heavy samples
135
+ new_params.w_cleanness = min(0.6, params.w_cleanness + rng.uniform(0, 0.1))
136
+ new_params.w_completeness = max(0.15, params.w_completeness + rng.uniform(-0.05, 0.05))
137
+ # Renormalize
138
+ total_w = new_params.w_cleanness + new_params.w_completeness + new_params.w_onset + new_params.w_representativeness
139
+ new_params.w_cleanness /= total_w
140
+ new_params.w_completeness /= total_w
141
+ new_params.w_onset /= total_w
142
+ new_params.w_representativeness /= total_w
143
+ changes.append(f"sample_score={report.mean_sample_score:.1f} → adjusted selection weights")
144
+
145
+ # ── Diagnosis 6: Low envelope correlation (transient mismatch) ──
146
+ if report.mean_env_corr < 0.7:
147
+ new_params.max_hit_dur = min(1.5, params.max_hit_dur * rng.uniform(1.1, 1.3))
148
+ changes.append(f"env_corr={report.mean_env_corr:.2f} → increased max_hit_dur")
149
+
150
+ # ── Diagnosis 7: Unmatched GT samples (some drums never found) ──
151
+ if len(report.unmatched_gt) > 0:
152
+ new_params.energy_threshold_db = max(-60, params.energy_threshold_db - rng.uniform(3, 6))
153
+ changes.append(f"missed {report.unmatched_gt} → lowered energy threshold")
154
+
155
+ # If no specific diagnosis triggered, apply small random perturbation
156
+ if not changes:
157
+ # Explore nearby parameter space
158
+ new_params.energy_threshold_db += rng.uniform(-3, 3)
159
+ new_params.pre_pad += rng.uniform(-0.002, 0.002)
160
+ new_params.pre_pad = max(0.001, new_params.pre_pad)
161
+ new_params.min_hit_dur += rng.uniform(-0.01, 0.01)
162
+ new_params.min_hit_dur = max(0.01, new_params.min_hit_dur)
163
+ changes.append("no specific issue → random exploration")
164
+
165
+ return new_params, changes
166
+
167
+
168
+ # ─────────────────────────────────────────────────────────────────────────────
169
+ # Main optimization loop
170
+ # ─────────────────────────────────────────────────────────────────────────────
171
+
172
+ def run_extraction_with_params(song: SyntheticSong, params: PipelineParams) -> tuple:
173
+ """Run the extraction pipeline with given params on a song.
174
+ Returns (clusters, all_hits) or raises on failure."""
175
+ from drum_extractor import (
176
+ detect_onsets, classify_and_separate_hits,
177
+ compute_librosa_embeddings, cluster_hits,
178
+ select_best_representatives, synthesize_from_cluster,
179
+ )
180
+
181
+ # Stage 2: Onset detection
182
+ hits = detect_onsets(
183
+ song.drums_only, song.sr,
184
+ pre_pad=params.pre_pad,
185
+ min_hit_dur=params.min_hit_dur,
186
+ max_hit_dur=params.max_hit_dur,
187
+ min_gap=params.min_gap,
188
+ energy_threshold_db=params.energy_threshold_db,
189
+ )
190
+
191
+ if len(hits) == 0:
192
+ return [], []
193
+
194
+ # Stage 3: Classify & separate
195
+ hits = classify_and_separate_hits(hits, separate_overlaps=params.separate_overlaps)
196
+
197
+ # Stage 4: Embed & cluster
198
+ embeddings = compute_librosa_embeddings(hits)
199
+ clusters = cluster_hits(hits, embeddings)
200
+
201
+ # Stage 5: Select best (using our improved scoring)
202
+ for cluster in clusters:
203
+ if cluster.count == 1:
204
+ cluster.best_hit_idx = 0
205
+ continue
206
+
207
+ scores = []
208
+ base_label = cluster.label.rsplit('_', 1)[0]
209
+
210
+ # Compute cluster radius for representativeness scoring
211
+ hit_features = []
212
+ for hit in cluster.hits:
213
+ import librosa
214
+ feat = np.concatenate([
215
+ librosa.feature.mfcc(y=hit.audio, sr=hit.sr, n_mfcc=13).mean(axis=1),
216
+ [hit.rms_energy, hit.spectral_centroid, hit.duration]
217
+ ])
218
+ hit_features.append(feat)
219
+ hit_features = np.array(hit_features)
220
+ mean_f = hit_features.mean(axis=0)
221
+ std_f = hit_features.std(axis=0) + 1e-8
222
+ hit_features_norm = (hit_features - mean_f) / std_f
223
+ centroid = hit_features_norm.mean(axis=0)
224
+ dists = np.linalg.norm(hit_features_norm - centroid, axis=1)
225
+ radius = dists.max() + 1e-8
226
+
227
+ for i, hit in enumerate(cluster.hits):
228
+ score = drum_sample_score(
229
+ hit.audio, hit.sr, base_label,
230
+ centroid_dist=dists[i],
231
+ cluster_radius=radius,
232
+ )
233
+ scores.append(score['total'])
234
+
235
+ cluster.best_hit_idx = int(np.argmax(scores))
236
+
237
+ # Stage 6: Synthesis
238
+ if params.synthesize:
239
+ for cluster in clusters:
240
+ if cluster.count >= 2:
241
+ cluster.synthesized = synthesize_from_cluster(cluster)
242
+
243
+ return clusters, hits
244
+
245
+
246
+ def run_optimization_loop(
247
+ n_iterations: int = 10,
248
+ patterns: list = None,
249
+ initial_params: PipelineParams = None,
250
+ seed: int = 42,
251
+ log_callback=None,
252
+ ) -> OptimizerState:
253
+ """Run the full autonomous optimization loop.
254
+
255
+ Args:
256
+ n_iterations: number of optimization iterations
257
+ patterns: list of pattern names to test with (cycles through them)
258
+ initial_params: starting pipeline parameters
259
+ seed: random seed
260
+ log_callback: function(str) called with log messages
261
+ """
262
+ if patterns is None:
263
+ patterns = ['rock', 'funk', 'halftime']
264
+ if initial_params is None:
265
+ initial_params = PipelineParams()
266
+
267
+ rng = np.random.RandomState(seed)
268
+ state = OptimizerState(best_params=initial_params.to_dict())
269
+ current_params = deepcopy(initial_params)
270
+
271
+ def log(msg):
272
+ if log_callback:
273
+ log_callback(msg)
274
+ print(msg)
275
+
276
+ log(f"Starting optimization loop: {n_iterations} iterations")
277
+ log(f"Patterns: {patterns}")
278
+
279
+ for i in range(n_iterations):
280
+ t0 = time.time()
281
+ pattern_name = patterns[i % len(patterns)]
282
+ song_seed = seed + i * 17 # different song each iteration
283
+
284
+ log(f"\n{'='*60}")
285
+ log(f"ITERATION {i+1}/{n_iterations} — pattern={pattern_name}, seed={song_seed}")
286
+ log(f"{'='*60}")
287
+
288
+ try:
289
+ # 1. Generate synthetic song
290
+ log(" Generating synthetic song...")
291
+ song = generate_test_song(
292
+ pattern_name=pattern_name,
293
+ bars=4,
294
+ bpm=100 + rng.randint(0, 40) * 2, # vary BPM
295
+ variation='medium',
296
+ seed=song_seed,
297
+ )
298
+ log(f" → {song.duration:.1f}s, {song.bpm}BPM, "
299
+ f"{len(song.hits)} hits, {len(song.samples)} sample types")
300
+
301
+ # 2. Run extraction
302
+ log(f" Running extraction with params: threshold={current_params.energy_threshold_db:.1f}dB, "
303
+ f"pre_pad={current_params.pre_pad:.3f}, min_dur={current_params.min_hit_dur:.3f}")
304
+ clusters, all_hits = run_extraction_with_params(song, current_params)
305
+ log(f" → {len(clusters)} clusters, {len(all_hits)} total hits")
306
+
307
+ # 3. Evaluate
308
+ log(" Evaluating against ground truth...")
309
+ gt_samples = {name: s.audio for name, s in song.samples.items()}
310
+ gt_hit_map = [
311
+ {'sample': h.sample_name, 'onset': h.onset_time, 'velocity': h.velocity}
312
+ for h in song.hits
313
+ ]
314
+
315
+ report = evaluate_extraction(
316
+ extracted_clusters=clusters,
317
+ gt_samples=gt_samples,
318
+ gt_hit_map=gt_hit_map,
319
+ sr=song.sr,
320
+ all_hits=all_hits,
321
+ pipeline_params=current_params.to_dict(),
322
+ )
323
+
324
+ duration = time.time() - t0
325
+
326
+ log(f" RESULTS:")
327
+ log(f" Overall Score: {report.overall_score:.1f}/100")
328
+ log(f" SI-SDR: {report.mean_si_sdr:.1f} dB")
329
+ log(f" Sample Score: {report.mean_sample_score:.1f}/100")
330
+ log(f" Env Corr: {report.mean_env_corr:.3f}")
331
+ log(f" Onset Error: {report.mean_onset_error_ms:.1f} ms")
332
+ log(f" Hit Count Acc: {report.hit_count_accuracy:.2f}")
333
+ log(f" Matched: {len(report.matches)}/{len(song.samples)}")
334
+ if report.unmatched_gt:
335
+ log(f" ⚠ Unmatched GT: {report.unmatched_gt}")
336
+
337
+ # Record iteration
338
+ result = IterationResult(
339
+ iteration=i,
340
+ params=current_params.to_dict(),
341
+ eval_report=report_to_dict(report),
342
+ overall_score=report.overall_score,
343
+ duration_seconds=duration,
344
+ test_config={'pattern': pattern_name, 'bpm': song.bpm, 'seed': song_seed},
345
+ timestamp=time.strftime('%Y-%m-%d %H:%M:%S'),
346
+ )
347
+ state.history.append(result)
348
+
349
+ # Update best
350
+ if report.overall_score > state.best_score:
351
+ state.best_score = report.overall_score
352
+ state.best_params = current_params.to_dict()
353
+ log(f" ★ NEW BEST SCORE: {report.overall_score:.1f}")
354
+
355
+ # 4. Tune parameters for next iteration
356
+ new_params, changes = diagnose_and_perturb(current_params, report, rng)
357
+ log(f" Parameter adjustments:")
358
+ for change in changes:
359
+ log(f" → {change}")
360
+ current_params = new_params
361
+
362
+ except Exception as e:
363
+ log(f" ✗ ERROR: {e}")
364
+ log(traceback.format_exc())
365
+ # On error, try random perturbation
366
+ current_params.energy_threshold_db += rng.uniform(-5, 5)
367
+ state.history.append(IterationResult(
368
+ iteration=i,
369
+ params=current_params.to_dict(),
370
+ eval_report={'error': str(e)},
371
+ overall_score=0.0,
372
+ duration_seconds=time.time() - t0,
373
+ test_config={'pattern': pattern_name},
374
+ timestamp=time.strftime('%Y-%m-%d %H:%M:%S'),
375
+ ))
376
+
377
+ state.iteration = i + 1
378
+
379
+ log(f"\n{'='*60}")
380
+ log(f"OPTIMIZATION COMPLETE")
381
+ log(f"{'='*60}")
382
+ log(f" Best score: {state.best_score:.1f}/100")
383
+ log(f" Best params: {json.dumps(state.best_params, indent=2)}")
384
+
385
+ return state