Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / spike_nnfp_match.rs
spike_nnfp_match.rs293 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 | |
| 11 | use std::collections::BTreeMap; |
| 12 | use std::path::Path; |
| 13 | |
| 14 | use modelrunner::microfrontend::{Frontend, NOW_PLAYING}; |
| 15 | use modelrunner::nets::nnfp; |
| 16 | use modelrunner::preprocess::RESCALE_ONLY; |
| 17 | use modelrunner::vulkan::context; |
| 18 | use modelrunner::vulkan::run::Net; |
| 19 | use modelrunner::weights::{graph, Weights}; |
| 20 | |
| 21 | /// 10 ms frames per embedding window, and how far the window walks between embeddings. |
| 22 | const REF_HOP_FRAMES: usize = 100; |
| 23 | const 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. |
| 28 | const TARGET_RMS: f32 = 3000.0; |
| 29 | |
| 30 | fn 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 | |
| 78 | fn 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. |
| 92 | fn 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 | |
| 99 | fn 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 | |
| 108 | /// Slide the 478-frame window over `frames` and embed each position. |
| 109 | /// |
| 110 | /// Returns the L2-normalised embeddings for matching, and separately the raw pre-normalisation |
| 111 | /// output, which is what an AC/DC reading has to be taken on. |
| 112 | fn embed_all( |
| 113 | net: &mut Net, |
| 114 | frames: &[f32], |
| 115 | hop_frames: usize, |
| 116 | ) -> Result<(Vec<(f32, Vec<f32>)>, Vec<f32>), String> { |
| 117 | let bins = nnfp::MEL_BINS as usize; |
| 118 | let window = nnfp::WINDOW_FRAMES as usize; |
| 119 | let total = frames.len() / bins; |
| 120 | let mut out = Vec::new(); |
| 121 | let mut raw = Vec::new(); |
| 122 | let mut start = 0usize; |
| 123 | while start + window <= total { |
| 124 | let slice = &frames[start * bins..(start + window) * bins]; |
| 125 | let mut e = net.infer_raw(slice)?.remove(0); |
| 126 | raw.extend_from_slice(&e); |
| 127 | l2(&mut e); |
| 128 | out.push((start as f32 * 0.01, e)); |
| 129 | start += hop_frames; |
| 130 | } |
| 131 | Ok((out, raw)) |
| 132 | } |
| 133 | |
| 134 | fn cosine(a: &[f32], b: &[f32]) -> f32 { |
| 135 | a.iter().zip(b).map(|(x, y)| x * y).sum() |
| 136 | } |
| 137 | |
| 138 | /// The AC/DC ratio task 49 uses: how much of the representation varies with the audio versus |
| 139 | /// sits as a fixed offset. `rows` is time-major, `width` values per row. |
| 140 | /// |
| 141 | /// Per dimension, AC is the standard deviation across time and DC the mean across time; the |
| 142 | /// ratio is the mean AC over the mean |DC|. A discriminative embedder should *raise* this from |
| 143 | /// its input to its output — log-mel is all-positive with a large common mode, so a low value |
| 144 | /// going in is expected and correct. |
| 145 | fn ac_dc(rows: &[f32], width: usize) -> f32 { |
| 146 | let t = rows.len() / width; |
| 147 | if t < 2 { |
| 148 | return f32::NAN; |
| 149 | } |
| 150 | let (mut ac, mut dc) = (0.0f64, 0.0f64); |
| 151 | for d in 0..width { |
| 152 | let mean: f64 = (0..t).map(|i| rows[i * width + d] as f64).sum::<f64>() / t as f64; |
| 153 | let var: f64 = (0..t) |
| 154 | .map(|i| { |
| 155 | let x = rows[i * width + d] as f64 - mean; |
| 156 | x * x |
| 157 | }) |
| 158 | .sum::<f64>() |
| 159 | / t as f64; |
| 160 | ac += var.sqrt(); |
| 161 | dc += mean.abs(); |
| 162 | } |
| 163 | (ac / dc) as f32 |
| 164 | } |
| 165 | |
| 166 | fn main() -> Result<(), String> { |
| 167 | let args: Vec<String> = std::env::args().skip(1).collect(); |
| 168 | if args.len() < 3 { |
| 169 | return Err("usage: spike_nnfp_match <nnfp.maml> <query.wav> <ref.wav>...".into()); |
| 170 | } |
| 171 | |
| 172 | let blob = std::fs::read(&args[0]).map_err(|e| format!("{}: {e}", args[0]))?; |
| 173 | let weights = Weights::parse(&blob, graph::NNFP)?; |
| 174 | let plan = nnfp::build(&weights)?; |
| 175 | // `infer_raw` feeds the arena directly, so the image normalisation is never applied. |
| 176 | let context = context::shared()?; |
| 177 | let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?; |
| 178 | eprintln!("embedder ready: {} tensors, {} B", weights.len(), blob.len()); |
| 179 | |
| 180 | // Reference set. |
| 181 | let mut refs: Vec<(String, f32, Vec<f32>)> = Vec::new(); |
| 182 | let mut ref_raw: Vec<f32> = Vec::new(); |
| 183 | for path in &args[2..] { |
| 184 | let mut pcm = read_wav_mono16(Path::new(path))?; |
| 185 | let rms = rms_normalise(&mut pcm); |
| 186 | let frames = log_mel(&pcm)?; |
| 187 | let (embedded, raw) = embed_all(&mut net, &frames, REF_HOP_FRAMES)?; |
| 188 | ref_raw.extend_from_slice(&raw); |
| 189 | let name = Path::new(path) |
| 190 | .file_stem() |
| 191 | .map(|s| s.to_string_lossy().into_owned()) |
| 192 | .unwrap_or_else(|| path.clone()); |
| 193 | eprintln!( |
| 194 | " ref {name}: {:.1}s, rms {rms:.0}, {} segments", |
| 195 | pcm.len() as f32 / 16000.0, |
| 196 | embedded.len() |
| 197 | ); |
| 198 | for (at, e) in embedded { |
| 199 | refs.push((name.clone(), at, e)); |
| 200 | } |
| 201 | } |
| 202 | eprintln!("reference set: {} segments", refs.len()); |
| 203 | |
| 204 | // Query. |
| 205 | let mut pcm = read_wav_mono16(Path::new(&args[1]))?; |
| 206 | let rms = rms_normalise(&mut pcm); |
| 207 | let frames = log_mel(&pcm)?; |
| 208 | let (query, raw) = embed_all(&mut net, &frames, QUERY_HOP_FRAMES)?; |
| 209 | eprintln!( |
| 210 | "query {}: {:.1}s, rms {rms:.0}, {} windows", |
| 211 | args[1], |
| 212 | pcm.len() as f32 / 16000.0, |
| 213 | query.len() |
| 214 | ); |
| 215 | println!( |
| 216 | "\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)", |
| 217 | ac_dc(&frames, nnfp::MEL_BINS as usize), |
| 218 | ac_dc(&raw, nnfp::EMBEDDING as usize), |
| 219 | ac_dc(&ref_raw, nnfp::EMBEDDING as usize), |
| 220 | ref_raw.len() / nnfp::EMBEDDING as usize, |
| 221 | args.len() - 2 |
| 222 | ); |
| 223 | |
| 224 | // Raw pre-L2 reference embeddings, for the effective-rank check that needs numpy. |
| 225 | if let Ok(path) = std::env::var("SPIKE_DUMP_RAW") { |
| 226 | let bytes: Vec<u8> = ref_raw.iter().flat_map(|v| v.to_le_bytes()).collect(); |
| 227 | std::fs::write(&path, &bytes).map_err(|e| format!("{path}: {e}"))?; |
| 228 | eprintln!( |
| 229 | "wrote {} raw embeddings x {} dims to {path}", |
| 230 | ref_raw.len() / nnfp::EMBEDDING as usize, |
| 231 | nnfp::EMBEDDING |
| 232 | ); |
| 233 | } |
| 234 | |
| 235 | // The query's log-mel frames, to check whether a working front end is itself low-rank. |
| 236 | if let Ok(path) = std::env::var("SPIKE_DUMP_LOGMEL") { |
| 237 | let bytes: Vec<u8> = frames.iter().flat_map(|v| v.to_le_bytes()).collect(); |
| 238 | std::fs::write(&path, &bytes).map_err(|e| format!("{path}: {e}"))?; |
| 239 | eprintln!( |
| 240 | "wrote {} log-mel frames x {} bins to {path}", |
| 241 | frames.len() / nnfp::MEL_BINS as usize, |
| 242 | nnfp::MEL_BINS |
| 243 | ); |
| 244 | } |
| 245 | |
| 246 | // Best (query window, reference segment) pair per reference track. |
| 247 | let mut best: BTreeMap<String, (f32, f32, f32)> = BTreeMap::new(); |
| 248 | for (qt, q) in &query { |
| 249 | for (name, rt, r) in &refs { |
| 250 | let s = cosine(q, r); |
| 251 | let slot = best.entry(name.clone()).or_insert((f32::MIN, 0.0, 0.0)); |
| 252 | if s > slot.0 { |
| 253 | *slot = (s, *qt, *rt); |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | let mut ranked: Vec<(&String, &(f32, f32, f32))> = best.iter().collect(); |
| 259 | ranked.sort_by(|a, b| b.1 .0.partial_cmp(&a.1 .0).unwrap()); |
| 260 | |
| 261 | println!("\n=== per-track best cosine ==="); |
| 262 | for (name, (s, qt, rt)) in &ranked { |
| 263 | println!(" {name:<28} {s:.4} query t={qt:.2}s ref t={rt:.2}s"); |
| 264 | } |
| 265 | if ranked.len() >= 2 { |
| 266 | let margin = ranked[0].1 .0 - ranked[1].1 .0; |
| 267 | println!( |
| 268 | "\ntop-1: {} ({:.4})\nrunner-up: {} ({:.4})\nmargin: {:.4}", |
| 269 | ranked[0].0, ranked[0].1 .0, ranked[1].0, ranked[1].1 .0, margin |
| 270 | ); |
| 271 | } |
| 272 | |
| 273 | // The null distribution: how high a wrong pair gets, so the top-1 has a scale to be read |
| 274 | // against. Without it a cosine of 0.8 means nothing. |
| 275 | let mut all: Vec<f32> = Vec::new(); |
| 276 | for (_, q) in query.iter().take(40) { |
| 277 | for (_, _, r) in refs.iter() { |
| 278 | all.push(cosine(q, r)); |
| 279 | } |
| 280 | } |
| 281 | all.sort_by(|a, b| a.partial_cmp(b).unwrap()); |
| 282 | let pick = |f: f32| all[((all.len() - 1) as f32 * f) as usize]; |
| 283 | println!( |
| 284 | "\nall-pairs cosine over {} pairs: p50 {:.4} p95 {:.4} p99 {:.4} max {:.4}", |
| 285 | all.len(), |
| 286 | pick(0.50), |
| 287 | pick(0.95), |
| 288 | pick(0.99), |
| 289 | all[all.len() - 1] |
| 290 | ); |
| 291 | |
| 292 | Ok(()) |
| 293 | } |