Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / ml / src / main / rust / examples / spike_nnfp_match.rs

spike_nnfp_match.rs291 lines · 10.7 KiBRaw
1//! SCRATCH — task 42 acoustic spike. Delete after the run; not intended to land.
2//!
3//! Embeds 16 kHz mono 16-bit WAVs with the NNFP embedder and retrieves a query against a
4//! reference set by cosine similarity over the 64-d embeddings, searching all alignments.
5//!
6//! ```text
7//! cargo run --release -p modelrunner --example spike_nnfp_match -- \
8//! <nnfp.maml> <query.wav> <ref.wav>...
9//! ```
10
11use std::collections::BTreeMap;
12use std::path::Path;
13
14use modelrunner::microfrontend::{Frontend, NOW_PLAYING};
15use modelrunner::nets::nnfp;
16use modelrunner::preprocess::RESCALE_ONLY;
17use modelrunner::vulkan::context;
18use modelrunner::vulkan::run::Net;
19use modelrunner::weights::{graph, Weights};
20
21/// 10 ms frames per embedding window, and how far the window walks between embeddings.
22const REF_HOP_FRAMES: usize = 100;
23const QUERY_HOP_FRAMES: usize = 25;
24
25/// The log-mel front end has no per-utterance normalisation, so absolute level walks straight
26/// into the features. A mic capture and a decoded file are never at the same level, so both
27/// sides are brought to a common RMS first; otherwise the retrieval would be measuring gain.
28const TARGET_RMS: f32 = 3000.0;
29
30fn read_wav_mono16(path: &Path) -> Result<Vec<i16>, String> {
31 let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
32 if bytes.len() < 12 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {
33 return Err(format!("{}: not a RIFF/WAVE file", path.display()));
34 }
35 let u16at = |o: usize| u16::from_le_bytes([bytes[o], bytes[o + 1]]);
36 let u32at = |o: usize| u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]);
37
38 let (mut channels, mut rate, mut bits) = (0u16, 0u32, 0u16);
39 let mut at = 12;
40 let mut pcm: Option<(usize, usize)> = None;
41 while at + 8 <= bytes.len() {
42 let id = &bytes[at..at + 4];
43 let size = u32at(at + 4) as usize;
44 let body = at + 8;
45 if id == b"fmt " && body + 16 <= bytes.len() {
46 channels = u16at(body + 2);
47 rate = u32at(body + 4);
48 bits = u16at(body + 14);
49 } else if id == b"data" {
50 pcm = Some((body, size.min(bytes.len().saturating_sub(body))));
51 }
52 at = body + size + (size & 1);
53 }
54 let (start, len) = pcm.ok_or_else(|| format!("{}: no data chunk", path.display()))?;
55 if bits != 16 {
56 return Err(format!("{}: {bits}-bit, expected 16", path.display()));
57 }
58 if rate != 16000 {
59 return Err(format!("{}: {rate} Hz, expected 16000", path.display()));
60 }
61
62 let frames = len / 2;
63 let mut mono = Vec::with_capacity(frames / channels.max(1) as usize);
64 let chans = channels.max(1) as usize;
65 let mut i = 0;
66 while (i + chans) * 2 <= len {
67 let mut sum = 0i32;
68 for c in 0..chans {
69 let o = start + (i + c) * 2;
70 sum += i16::from_le_bytes([bytes[o], bytes[o + 1]]) as i32;
71 }
72 mono.push((sum / chans as i32) as i16);
73 i += chans;
74 }
75 Ok(mono)
76}
77
78fn rms_normalise(samples: &mut [i16]) -> f32 {
79 let sum: f64 = samples.iter().map(|&s| (s as f64) * (s as f64)).sum();
80 let rms = (sum / samples.len().max(1) as f64).sqrt() as f32;
81 if rms > 1.0 {
82 let gain = TARGET_RMS / rms;
83 for s in samples.iter_mut() {
84 *s = (*s as f32 * gain).clamp(-32768.0, 32767.0) as i16;
85 }
86 }
87 rms
88}
89
90/// Every 10 ms log-mel frame of `samples`, laid out frame-major exactly as the plan's input
91/// expects.
92fn log_mel(samples: &[i16]) -> Result<Vec<f32>, String> {
93 let mut frontend = Frontend::new(NOW_PLAYING)?;
94 let mut out = Vec::new();
95 frontend.process(samples, &mut out);
96 Ok(out)
97}
98
99fn l2(v: &mut [f32]) {
100 let n = v.iter().map(|x| x * x).sum::<f32>().sqrt();
101 if n > 0.0 {
102 for x in v.iter_mut() {
103 *x /= n;
104 }
105 }
106}
107
108type EmbedAll = (Vec<(f32, Vec<f32>)>, Vec<f32>);
109
110/// Slide the 478-frame window over `frames` and embed each position.
111///
112/// Returns the L2-normalised embeddings for matching, and separately the raw pre-normalisation
113/// output, which is what an AC/DC reading has to be taken on.
114fn embed_all(net: &mut Net, frames: &[f32], hop_frames: usize) -> Result<EmbedAll, String> {
115 let bins = nnfp::MEL_BINS as usize;
116 let window = nnfp::WINDOW_FRAMES as usize;
117 let total = frames.len() / bins;
118 let mut out = Vec::new();
119 let mut raw = Vec::new();
120 let mut start = 0usize;
121 while start + window <= total {
122 let slice = &frames[start * bins..(start + window) * bins];
123 let mut e = net.infer_raw(slice)?.remove(0);
124 raw.extend_from_slice(&e);
125 l2(&mut e);
126 out.push((start as f32 * 0.01, e));
127 start += hop_frames;
128 }
129 Ok((out, raw))
130}
131
132fn cosine(a: &[f32], b: &[f32]) -> f32 {
133 a.iter().zip(b).map(|(x, y)| x * y).sum()
134}
135
136/// The AC/DC ratio task 49 uses: how much of the representation varies with the audio versus
137/// sits as a fixed offset. `rows` is time-major, `width` values per row.
138///
139/// Per dimension, AC is the standard deviation across time and DC the mean across time; the
140/// ratio is the mean AC over the mean |DC|. A discriminative embedder should *raise* this from
141/// its input to its output — log-mel is all-positive with a large common mode, so a low value
142/// going in is expected and correct.
143fn ac_dc(rows: &[f32], width: usize) -> f32 {
144 let t = rows.len() / width;
145 if t < 2 {
146 return f32::NAN;
147 }
148 let (mut ac, mut dc) = (0.0f64, 0.0f64);
149 for d in 0..width {
150 let mean: f64 = (0..t).map(|i| rows[i * width + d] as f64).sum::<f64>() / t as f64;
151 let var: f64 = (0..t)
152 .map(|i| {
153 let x = rows[i * width + d] as f64 - mean;
154 x * x
155 })
156 .sum::<f64>()
157 / t as f64;
158 ac += var.sqrt();
159 dc += mean.abs();
160 }
161 (ac / dc) as f32
162}
163
164fn main() -> Result<(), String> {
165 let args: Vec<String> = std::env::args().skip(1).collect();
166 if args.len() < 3 {
167 return Err("usage: spike_nnfp_match <nnfp.maml> <query.wav> <ref.wav>...".into());
168 }
169
170 let blob = std::fs::read(&args[0]).map_err(|e| format!("{}: {e}", args[0]))?;
171 let weights = Weights::parse(&blob, graph::NNFP)?;
172 let plan = nnfp::build(&weights)?;
173 // `infer_raw` feeds the arena directly, so the image normalisation is never applied.
174 let context = context::shared()?;
175 let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;
176 eprintln!("embedder ready: {} tensors, {} B", weights.len(), blob.len());
177
178 // Reference set.
179 let mut refs: Vec<(String, f32, Vec<f32>)> = Vec::new();
180 let mut ref_raw: Vec<f32> = Vec::new();
181 for path in &args[2..] {
182 let mut pcm = read_wav_mono16(Path::new(path))?;
183 let rms = rms_normalise(&mut pcm);
184 let frames = log_mel(&pcm)?;
185 let (embedded, raw) = embed_all(&mut net, &frames, REF_HOP_FRAMES)?;
186 ref_raw.extend_from_slice(&raw);
187 let name = Path::new(path)
188 .file_stem()
189 .map(|s| s.to_string_lossy().into_owned())
190 .unwrap_or_else(|| path.clone());
191 eprintln!(
192 " ref {name}: {:.1}s, rms {rms:.0}, {} segments",
193 pcm.len() as f32 / 16000.0,
194 embedded.len()
195 );
196 for (at, e) in embedded {
197 refs.push((name.clone(), at, e));
198 }
199 }
200 eprintln!("reference set: {} segments", refs.len());
201
202 // Query.
203 let mut pcm = read_wav_mono16(Path::new(&args[1]))?;
204 let rms = rms_normalise(&mut pcm);
205 let frames = log_mel(&pcm)?;
206 let (query, raw) = embed_all(&mut net, &frames, QUERY_HOP_FRAMES)?;
207 eprintln!(
208 "query {}: {:.1}s, rms {rms:.0}, {} windows",
209 args[1],
210 pcm.len() as f32 / 16000.0,
211 query.len()
212 );
213 println!(
214 "\n=== AC/DC (task 49 diagnostic) ===\n input log-mel {:.3}\n after head, 1 track {:.3}\n after head, all refs {:.3} ({} segments, {} tracks)",
215 ac_dc(&frames, nnfp::MEL_BINS as usize),
216 ac_dc(&raw, nnfp::EMBEDDING as usize),
217 ac_dc(&ref_raw, nnfp::EMBEDDING as usize),
218 ref_raw.len() / nnfp::EMBEDDING as usize,
219 args.len() - 2
220 );
221
222 // Raw pre-L2 reference embeddings, for the effective-rank check that needs numpy.
223 if let Ok(path) = std::env::var("SPIKE_DUMP_RAW") {
224 let bytes: Vec<u8> = ref_raw.iter().flat_map(|v| v.to_le_bytes()).collect();
225 std::fs::write(&path, &bytes).map_err(|e| format!("{path}: {e}"))?;
226 eprintln!(
227 "wrote {} raw embeddings x {} dims to {path}",
228 ref_raw.len() / nnfp::EMBEDDING as usize,
229 nnfp::EMBEDDING
230 );
231 }
232
233 // The query's log-mel frames, to check whether a working front end is itself low-rank.
234 if let Ok(path) = std::env::var("SPIKE_DUMP_LOGMEL") {
235 let bytes: Vec<u8> = frames.iter().flat_map(|v| v.to_le_bytes()).collect();
236 std::fs::write(&path, &bytes).map_err(|e| format!("{path}: {e}"))?;
237 eprintln!(
238 "wrote {} log-mel frames x {} bins to {path}",
239 frames.len() / nnfp::MEL_BINS as usize,
240 nnfp::MEL_BINS
241 );
242 }
243
244 // Best (query window, reference segment) pair per reference track.
245 let mut best: BTreeMap<String, (f32, f32, f32)> = BTreeMap::new();
246 for (qt, q) in &query {
247 for (name, rt, r) in &refs {
248 let s = cosine(q, r);
249 let slot = best.entry(name.clone()).or_insert((f32::MIN, 0.0, 0.0));
250 if s > slot.0 {
251 *slot = (s, *qt, *rt);
252 }
253 }
254 }
255
256 let mut ranked: Vec<(&String, &(f32, f32, f32))> = best.iter().collect();
257 ranked.sort_by(|a, b| b.1 .0.partial_cmp(&a.1 .0).unwrap());
258
259 println!("\n=== per-track best cosine ===");
260 for (name, (s, qt, rt)) in &ranked {
261 println!(" {name:<28} {s:.4} query t={qt:.2}s ref t={rt:.2}s");
262 }
263 if ranked.len() >= 2 {
264 let margin = ranked[0].1 .0 - ranked[1].1 .0;
265 println!(
266 "\ntop-1: {} ({:.4})\nrunner-up: {} ({:.4})\nmargin: {:.4}",
267 ranked[0].0, ranked[0].1 .0, ranked[1].0, ranked[1].1 .0, margin
268 );
269 }
270
271 // The null distribution: how high a wrong pair gets, so the top-1 has a scale to be read
272 // against. Without it a cosine of 0.8 means nothing.
273 let mut all: Vec<f32> = Vec::new();
274 for (_, q) in query.iter().take(40) {
275 for (_, _, r) in refs.iter() {
276 all.push(cosine(q, r));
277 }
278 }
279 all.sort_by(|a, b| a.partial_cmp(b).unwrap());
280 let pick = |f: f32| all[((all.len() - 1) as f32 * f) as usize];
281 println!(
282 "\nall-pairs cosine over {} pairs: p50 {:.4} p95 {:.4} p99 {:.4} max {:.4}",
283 all.len(),
284 pick(0.50),
285 pick(0.95),
286 pick(0.99),
287 all[all.len() - 1]
288 );
289
290 Ok(())
291}